import { Plugin, Schema } from '@pdfme/common'; import { convertForPdfLayoutProps, isEditable, addAlphaToHex, createErrorElm, createSvgStr, } from '../utils.js'; import { Route } from 'lucide'; const isValidSVG = (svgString: string): boolean => { try { // Basic validation checks that work in both Node.js and browser if (!svgString || typeof svgString !== 'string') { return false; } // Check for basic SVG structure if (!svgString.includes('')) { return false; } // Additional browser-specific validation if DOMParser is available if (typeof DOMParser !== 'undefined') { const parser = new DOMParser(); const doc = parser.parseFromString(svgString, 'image/svg+xml'); const parserError = doc.querySelector('parsererror'); if (parserError !== null) { return false; } } return true; } catch { return false; } }; const defaultValue = ` `; export type SVGSchema = Schema; const svgSchema: Plugin = { ui: (arg) => { const { rootElement, value, mode, onChange, theme, schema } = arg; const container = document.createElement(isEditable(mode, schema) ? 'textarea' : 'div'); container.style.width = '100%'; container.style.height = '100%'; container.style.boxSizing = 'border-box'; if (isEditable(mode, schema)) { const textarea = container as HTMLTextAreaElement; textarea.value = value; textarea.style.position = 'absolute'; textarea.style.backgroundColor = addAlphaToHex(theme.colorPrimaryBg, 30); if (isValidSVG(value)) { const svgElement = new DOMParser().parseFromString(value, 'text/xml').childNodes[0]; if (svgElement instanceof SVGElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); svgElement.style.position = 'absolute'; } rootElement.appendChild(svgElement); } else if (value) { const errorElm = createErrorElm(); errorElm.style.position = 'absolute'; rootElement.appendChild(errorElm); } textarea.addEventListener('change', (e: Event) => { const newValue = (e.target as HTMLTextAreaElement).value; if (onChange) onChange({ key: 'content', value: newValue }); }); rootElement.appendChild(container); textarea.setSelectionRange(value.length, value.length); textarea.focus(); } else { if (!value) return; if (!isValidSVG(value)) { rootElement.appendChild(createErrorElm()); return; } container.innerHTML = value; const svgElement = container.childNodes[0]; if (svgElement instanceof SVGElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); rootElement.appendChild(container); } } }, pdf: async (arg) => { const { page, schema, value } = arg; if (!value || !isValidSVG(value)) return; const pageHeight = page.getHeight(); const { width, height, position } = convertForPdfLayoutProps({ schema, pageHeight }); const { x, y } = position; await page.drawSvg(value, { x, y: y + height, width, height }); }, propPanel: { schema: {}, defaultSchema: { name: '', type: 'svg', content: defaultValue, position: { x: 0, y: 0 }, width: 40, height: 50, }, }, icon: createSvgStr(Route), }; export default svgSchema;