@@ -25,6 +25,48 @@ class CSVTextarea extends HTMLElement {
2525 this . isComponentInitialized = true ;
2626 this . initializeTable ( ) ;
2727 this . setupEventListeners ( ) ;
28+ this . setupMutationObserver ( ) ;
29+ }
30+
31+ setupMutationObserver ( ) {
32+ // Select the node that will be observed for mutations
33+ const targetNode = this . shadowRoot . querySelector ( 'tbody' ) ;
34+
35+ // Options for the observer (which mutations to observe)
36+ const config = {
37+ attributes : true ,
38+ childList : true ,
39+ subtree : true ,
40+ attributeFilter : [ 'value' ] // This ensures we only observe changes to the 'value' attribute
41+ } ;
42+
43+ // Callback function to execute when mutations are observed
44+ const callback = ( mutationsList , observer ) => {
45+ for ( const mutation of mutationsList ) {
46+ if ( mutation . type === 'attributes' && mutation . attributeName === 'value' ) {
47+ // If an input value changes, update the textarea
48+ this . toTextarea ( ) ;
49+ } else if ( mutation . type === 'childList' ) {
50+ // If there are changes in the child list (like adding or removing rows), update the textarea
51+ this . toTextarea ( ) ;
52+ }
53+ }
54+ } ;
55+
56+ // Create an observer instance linked to the callback function
57+ this . observer = new MutationObserver ( callback ) ;
58+
59+ // Start observing the target node for configured mutations
60+ if ( targetNode ) {
61+ this . observer . observe ( targetNode , config ) ;
62+ }
63+ }
64+
65+ disconnectedCallback ( ) {
66+ // Disconnect the observer when the element is removed from the DOM
67+ if ( this . observer ) {
68+ this . observer . disconnect ( ) ;
69+ }
2870 }
2971
3072 async initializeComponent ( ) {
@@ -202,6 +244,7 @@ class CSVTextarea extends HTMLElement {
202244 toCSV ( ) {
203245 const rows = [ ] ;
204246 const tbody = this . shadowRoot . querySelector ( 'tbody' ) . rows ;
247+ console . log ( this . innertHTML ) ; //DEBUG
205248 for ( let i = 0 ; i < tbody . length ; i ++ ) {
206249 const cells = tbody [ i ] . cells ;
207250 const row = [ ] ;
@@ -267,6 +310,7 @@ class CSVTextarea extends HTMLElement {
267310 } ) ;
268311 }
269312
313+
270314 fromTextarea ( ) {
271315 const textarea = this . querySelector ( 'textarea' ) ;
272316 if ( textarea ) {
@@ -277,7 +321,17 @@ class CSVTextarea extends HTMLElement {
277321 toTextarea ( ) {
278322 const textarea = this . querySelector ( 'textarea' ) ;
279323 if ( textarea ) {
280- textarea . value = this . toCSV ( ) ;
324+ textarea . value = this . toCSV ( ) ; // Convert the current state of the component to CSV and update the textarea
325+ console . log ( 'Textarea updated with CSV data:' , textarea . value ) ;
326+ }
327+ }
328+
329+ setupFormListener ( ) {
330+ const form = this . closest ( 'form' ) ;
331+ if ( form ) {
332+ form . addEventListener ( 'submit' , ( event ) => {
333+ this . toTextarea ( ) ; // Update the textarea with the latest CSV data
334+ } ) ;
281335 }
282336 }
283337
0 commit comments