import { Render } from '../../'; export async function renderData(this : Render) { if (this.hideEmptyParent && !this.data.length) { if (this.parent) { this.parent.style.display = 'none'; } if (this.emptyState) { this.emptyState.style.display = ''; } return; } else { if (this.parent) { this.parent.style.display = ''; } if (this.emptyState) { this.emptyState.style.display = 'none'; } } this.clear(); // Clear previous content // Treat data as an array even if it's a single object const items = Array.isArray(this.data) ? this.data : [this.data]; // Clone the initial element as the template const template = this.htmlObject.cloneNode(true) as HTMLElement; // Iterate over each item in the data for (const itemData of items) { let newItem // length of the items array if (items.length === 1 && this.clearOnUpdate === false) { newItem = this.htmlObject; } else { this.template = this.htmlObject; this.htmlObject.remove(); if (items.indexOf(itemData) !== 0) { newItem = template.cloneNode(true) as HTMLElement; this.parent.appendChild(newItem); } else { // If it's the first item, use the original element newItem = this.template.cloneNode(true) as HTMLElement; this.parent.appendChild(newItem); } } // Perform the initial config action if it exists if (this.configAction) { this.configAction(itemData, newItem); } // Perform actions based on the config for each key if (this.config) { Object.keys(this.config).forEach(key => { const index = items.indexOf(itemData); const action = this.config[key]; const elements = newItem.querySelectorAll(`[${this.prop}="${key}"]`); const dataKey = action.dataKey || key; let data ; try { data = itemData[dataKey] } catch (error) { console.log('Awaitiing data for:', dataKey); } elements.forEach(element => { action.action(data, element, itemData, index); }); // Handle nested configurations if (action.config !== undefined && elements[0] !== null) { const nestedRender = new Render({ element: elements[0] as HTMLElement, prop: this.prop, hideEmptyParent: false, config: action.config, dataStore: this.dataStore, key: this.key }); this.childRenders.push(nestedRender); } }); } // Perform the final config action if it exists if (this.configAfter) { this.configAfter(itemData, newItem); } } requestAnimationFrame(() => { this.clear(false); }); } export function updateData(this: Render, data: Record < string, any > []) { this.data = data; this.render().catch(error => { console.error('Failed to update and render:', error); }); } export function clearData(this: Render, clearParent: boolean = true) { // Recursively clear nested renders first if (this.childRenders && this.childRenders.length) { this.childRenders.forEach(render => render.clear()); } // After all nested renders are cleared, reset the array this.childRenders = []; // Clear the parent element if specified if (clearParent) { this.parent.innerHTML = ''; } }