import type { FdsTreeNode } from './types' const getTitleFromProperties = (node: FdsTreeNode, titleTemplate?: string) => { if (!titleTemplate) { return node.title } const template = titleTemplate ?? '' // Extract all occurrences of content inside [[]] in the template string const templateVariables = extractTemplateVariables(template) // Replace template variables with actual values let result = template templateVariables.forEach((variable) => { const value = getNodePropertyValue(node, variable) const regex = new RegExp(`\\[\\[${variable.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\]\\]`, 'g') result = result.replace(regex, value) }) return result } /** * Extract all occurrences of content inside [[]] in a string * @param template - The template string containing [[]] placeholders * @returns Array of variable names found in the template */ const extractTemplateVariables = (template: string): string[] => { const regex = /\[\[([^\]]+)\]\]/g const matches: string[] = [] let match while ((match = regex.exec(template)) !== null) { if (match[1]) { matches.push(match[1]) } } return matches } /** * Get property value from node object * @param node - The tree node * @param property - The property name to extract * @returns The property value as string */ const getNodePropertyValue = (node: FdsTreeNode, property: string): string => { // Handle direct properties if (property in node) { const value = node[property as keyof FdsTreeNode] return value ? String(value) : '' } // Handle nested data properties if (node.data && typeof node.data === 'object') { const dataRecord = node.data as Record const dataValue = dataRecord[property] if (dataValue !== undefined && dataValue !== null) { return String(dataValue) } } // Return empty string if property not found return '' } export { getTitleFromProperties }