@keboola/design 11.5.0 → 11.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/AGENTS.md +7 -6
  2. package/CHANGELOG.md +31 -0
  3. package/COMPONENT-API.md +5 -5
  4. package/dist/{AIKit-CNX6aiKm.js → AIKit-CQxVwyAk.js} +212 -38
  5. package/dist/AIKit-CQxVwyAk.js.map +1 -0
  6. package/dist/{Alert-Ba5b2YPq.js → Alert-C4Y9IwMI.js} +2 -2
  7. package/dist/{Alert-Ba5b2YPq.js.map → Alert-C4Y9IwMI.js.map} +1 -1
  8. package/dist/{Badge-D0pXdekt.js → Badge-o5jURtpB.js} +2 -2
  9. package/dist/{Badge-D0pXdekt.js.map → Badge-o5jURtpB.js.map} +1 -1
  10. package/dist/{BrandEditor-CSANsxUz.js → BrandEditor-CS9P4r2p.js} +5 -5
  11. package/dist/{BrandEditor-CSANsxUz.js.map → BrandEditor-CS9P4r2p.js.map} +1 -1
  12. package/dist/{Breadcrumb-g_xn_-Nf.js → Breadcrumb-D1id7YXd.js} +2 -2
  13. package/dist/{Breadcrumb-g_xn_-Nf.js.map → Breadcrumb-D1id7YXd.js.map} +1 -1
  14. package/dist/{Checkbox-CUIn2jap.js → Checkbox-Bqr6zXcW.js} +2 -2
  15. package/dist/{Checkbox-CUIn2jap.js.map → Checkbox-Bqr6zXcW.js.map} +1 -1
  16. package/dist/{Clipboard-BTW6C-b_.js → Clipboard-C2YBRfD8.js} +2 -2
  17. package/dist/{Clipboard-BTW6C-b_.js.map → Clipboard-C2YBRfD8.js.map} +1 -1
  18. package/dist/{ClipboardButton-CwZJdRaz.js → ClipboardButton-CrljClL1.js} +2 -2
  19. package/dist/{ClipboardButton-CwZJdRaz.js.map → ClipboardButton-CrljClL1.js.map} +1 -1
  20. package/dist/{CodeEditor-C9zy7PxK.js → CodeEditor-C9AS8Ch0.js} +4 -4
  21. package/dist/{CodeEditor-C9zy7PxK.js.map → CodeEditor-C9AS8Ch0.js.map} +1 -1
  22. package/dist/{ColorInput-BZV-u_94.js → ColorInput-Dg87lKcR.js} +2 -2
  23. package/dist/{ColorInput-BZV-u_94.js.map → ColorInput-Dg87lKcR.js.map} +1 -1
  24. package/dist/{Combobox-BfIfaVMA.js → Combobox-BfanUAqY.js} +3 -3
  25. package/dist/{Combobox-BfIfaVMA.js.map → Combobox-BfanUAqY.js.map} +1 -1
  26. package/dist/{Command-Bfa1kpbt.js → Command-CqxoI_De.js} +2 -2
  27. package/dist/{Command-Bfa1kpbt.js.map → Command-CqxoI_De.js.map} +1 -1
  28. package/dist/{CopyField-DpT0Ngz1.js → CopyField-Rx9HPTbJ.js} +2 -2
  29. package/dist/{CopyField-DpT0Ngz1.js.map → CopyField-Rx9HPTbJ.js.map} +1 -1
  30. package/dist/{DateInput-DiEd5uCL.js → DateInput-DpifECUQ.js} +2 -2
  31. package/dist/{DateInput-DiEd5uCL.js.map → DateInput-DpifECUQ.js.map} +1 -1
  32. package/dist/{DateRangeInput-DPfVYchl.js → DateRangeInput-9MIw7P6L.js} +2 -2
  33. package/dist/{DateRangeInput-DPfVYchl.js.map → DateRangeInput-9MIw7P6L.js.map} +1 -1
  34. package/dist/DiagramSource-C5_d8Gdj.js +11 -0
  35. package/dist/DiagramSource-C5_d8Gdj.js.map +1 -0
  36. package/dist/{FieldItem-B7XMmZSz.js → FieldItem-DtPTzNef.js} +3 -3
  37. package/dist/{FieldItem-B7XMmZSz.js.map → FieldItem-DtPTzNef.js.map} +1 -1
  38. package/dist/{FileUpload-ABThVZyg.js → FileUpload-DYQCTGjU.js} +3 -3
  39. package/dist/{FileUpload-ABThVZyg.js.map → FileUpload-DYQCTGjU.js.map} +1 -1
  40. package/dist/{Form-CsttTHn4.js → Form-DAaatlBk.js} +5 -5
  41. package/dist/{Form-CsttTHn4.js.map → Form-DAaatlBk.js.map} +1 -1
  42. package/dist/{FormGroup-DHvTFdno.js → FormGroup-Bl8JmnzJ.js} +3 -3
  43. package/dist/{FormGroup-DHvTFdno.js.map → FormGroup-Bl8JmnzJ.js.map} +1 -1
  44. package/dist/{FullScreenModal-BvPuYibe.js → FullScreenModal-CN9nAs72.js} +50 -2
  45. package/dist/FullScreenModal-CN9nAs72.js.map +1 -0
  46. package/dist/{Kbd-Cvvt91Q8.js → Kbd-D1Azcc4g.js} +2 -2
  47. package/dist/{Kbd-Cvvt91Q8.js.map → Kbd-D1Azcc4g.js.map} +1 -1
  48. package/dist/{MermaidDiagram-CXG5tC6J.js → MermaidDiagram-CujFxVzk.js} +4 -3
  49. package/dist/{MermaidDiagram-CXG5tC6J.js.map → MermaidDiagram-CujFxVzk.js.map} +1 -1
  50. package/dist/{MultiActionButtonGroup-DokHbPgM.js → MultiActionButtonGroup-CNNoBQbv.js} +2 -2
  51. package/dist/{MultiActionButtonGroup-DokHbPgM.js.map → MultiActionButtonGroup-CNNoBQbv.js.map} +1 -1
  52. package/dist/{PageToolbar-DExqEYGl.js → PageToolbar-BKVJiDAL.js} +2 -2
  53. package/dist/{PageToolbar-DExqEYGl.js.map → PageToolbar-BKVJiDAL.js.map} +1 -1
  54. package/dist/{RadioGroup-DXPbSj8P.js → RadioGroup-CUBsuP7r.js} +2 -2
  55. package/dist/{RadioGroup-DXPbSj8P.js.map → RadioGroup-CUBsuP7r.js.map} +1 -1
  56. package/dist/{Search-5uQAiNIP.js → Search-DVpJuzr9.js} +2 -2
  57. package/dist/{Search-5uQAiNIP.js.map → Search-DVpJuzr9.js.map} +1 -1
  58. package/dist/{SearchInput-D4UgAXJK.js → SearchInput-Q85p8Ews.js} +2 -2
  59. package/dist/{SearchInput-D4UgAXJK.js.map → SearchInput-Q85p8Ews.js.map} +1 -1
  60. package/dist/{SectionNav-OkKCjSA-.js → SectionNav-mpmSM3OC.js} +3 -3
  61. package/dist/{SectionNav-OkKCjSA-.js.map → SectionNav-mpmSM3OC.js.map} +1 -1
  62. package/dist/{Sidebar-D3cY1kha.js → Sidebar-CTWsHZhF.js} +2 -2
  63. package/dist/{Sidebar-D3cY1kha.js.map → Sidebar-CTWsHZhF.js.map} +1 -1
  64. package/dist/{Slider-CRf-bB4y.js → Slider-Bv0B6lI0.js} +2 -2
  65. package/dist/{Slider-CRf-bB4y.js.map → Slider-Bv0B6lI0.js.map} +1 -1
  66. package/dist/{TextInput-DH5SkbsE.js → TextInput-DiEMxVF6.js} +2 -2
  67. package/dist/{TextInput-DH5SkbsE.js.map → TextInput-DiEMxVF6.js.map} +1 -1
  68. package/dist/{ThemeProvider-2RMdVGxO.js → ThemeProvider-BI6JWBdJ.js} +2 -2
  69. package/dist/{ThemeProvider-2RMdVGxO.js.map → ThemeProvider-BI6JWBdJ.js.map} +1 -1
  70. package/dist/{ZoomableSvg-pooPb1Cu.js → ZoomableSvg-U_VH3QRO.js} +3 -3
  71. package/dist/{ZoomableSvg-pooPb1Cu.js.map → ZoomableSvg-U_VH3QRO.js.map} +1 -1
  72. package/dist/editors.js +2 -2
  73. package/dist/flint.js +3 -2
  74. package/dist/flint.js.map +1 -1
  75. package/dist/index.d.ts +358 -283
  76. package/dist/index.js +32 -32
  77. package/dist/internal/blocks/AIKit.js +2 -2
  78. package/dist/internal/blocks/BrandEditor.js +1 -1
  79. package/dist/internal/blocks/ClipboardButton.js +1 -1
  80. package/dist/internal/blocks/ColorInput.js +1 -1
  81. package/dist/internal/blocks/Command.js +1 -1
  82. package/dist/internal/blocks/CopyField.js +1 -1
  83. package/dist/internal/blocks/DateInput.js +1 -1
  84. package/dist/internal/blocks/DateRangeInput.js +1 -1
  85. package/dist/internal/blocks/ExportMenu.js +1 -1
  86. package/dist/internal/blocks/Form/connectors/MultiComboboxField.js +1 -1
  87. package/dist/internal/blocks/Form.js +1 -1
  88. package/dist/internal/blocks/FormGroup.js +1 -1
  89. package/dist/internal/blocks/MultiActionButtonGroup.js +1 -1
  90. package/dist/internal/blocks/MultiCombobox.js +1 -1
  91. package/dist/internal/blocks/PageToolbar.js +1 -1
  92. package/dist/internal/blocks/PasswordInput.js +1 -1
  93. package/dist/internal/blocks/SearchInput.js +1 -1
  94. package/dist/internal/blocks/SearchInputWithNavigation.js +2 -2
  95. package/dist/internal/blocks/SectionNav.js +1 -1
  96. package/dist/internal/blocks/TextInput.js +1 -1
  97. package/dist/internal/blocks/TimeInput.js +1 -1
  98. package/dist/internal/components/Alert.js +1 -1
  99. package/dist/internal/components/Avatar.js +1 -1
  100. package/dist/internal/components/Badge.js +1 -1
  101. package/dist/internal/components/Breadcrumb.js +1 -1
  102. package/dist/internal/components/Checkbox.js +1 -1
  103. package/dist/internal/components/Clipboard.js +1 -1
  104. package/dist/internal/components/CollapsiblePanel.js +1 -1
  105. package/dist/internal/components/Combobox.js +1 -1
  106. package/dist/internal/components/FileUpload.js +1 -1
  107. package/dist/internal/components/FullScreenModal.js +1 -1
  108. package/dist/internal/components/Kbd.js +1 -1
  109. package/dist/internal/components/Progress.js +3 -1
  110. package/dist/internal/components/Progress.js.map +1 -1
  111. package/dist/internal/components/RadioGroup.js +1 -1
  112. package/dist/internal/components/Search.js +1 -1
  113. package/dist/internal/components/Sidebar.js +1 -1
  114. package/dist/internal/components/Slider.js +1 -1
  115. package/dist/internal/components/ThemeProvider.js +1 -1
  116. package/dist/internal/components/Tooltip.js +1 -1
  117. package/dist/internal/components/Truncated.js +1 -1
  118. package/dist/internal/components/ZoomableSvg.js +1 -1
  119. package/dist/internal/utils.js +1 -1
  120. package/dist/markdown-editor.js +4 -4
  121. package/dist/mermaid.js +1 -1
  122. package/dist/rjsf.js +9 -9
  123. package/dist/styles.css +1 -1
  124. package/dist/{svgTransforms-C9njt92h.js → svgTransforms-CJAYPk7o.js} +2 -10
  125. package/dist/svgTransforms-CJAYPk7o.js.map +1 -0
  126. package/dist/testing.js +1 -1
  127. package/dist/{utils-DSvrhU8E.js → utils-DnkrFYqY.js} +3 -5
  128. package/dist/utils-DnkrFYqY.js.map +1 -0
  129. package/package.json +16 -16
  130. package/dist/AIKit-CNX6aiKm.js.map +0 -1
  131. package/dist/FullScreenModal-BvPuYibe.js.map +0 -1
  132. package/dist/svgTransforms-C9njt92h.js.map +0 -1
  133. package/dist/utils-DSvrhU8E.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ThemeProvider-2RMdVGxO.js","names":[],"sources":["../src/components/ThemeProvider/AIGradientSvg.tsx","../src/components/ThemeProvider/useThemeTokens.ts","../src/components/ThemeProvider/ThemeProvider.tsx","../src/components/ThemeProvider/ThemeScope.tsx"],"sourcesContent":["export const AIGradientsSvg = () => (\n <svg width=\"0\" height=\"0\" style={{ position: 'absolute', visibility: 'hidden' }}>\n <defs>\n {/*aigradient-600*/}\n <linearGradient id=\"aigradient-600\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stopColor=\"#61E4FF\" />\n <stop offset=\"50%\" stopColor=\"#1F8FFF\" />\n <stop offset=\"100%\" stopColor=\"#7C5CFF\" />\n </linearGradient>\n\n {/*aigradient-700*/}\n <linearGradient id=\"aigradient-700\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stopColor=\"#075fb8\" />\n <stop offset=\"100%\" stopColor=\"#5b2cb8\" />\n </linearGradient>\n </defs>\n </svg>\n);\n","import { useInsertionEffect } from 'react';\n\nimport type {\n BrandTheme,\n Colors,\n Gradient,\n Motion,\n Radii,\n Shadows,\n Spacing,\n Typography,\n} from '@keboola/brand-registry';\n\nimport type { ResolvedColorScheme } from './types';\nimport { createCssVars } from './utils';\n\nexport type ThemeTokens = {\n colors?: Colors;\n typography?: Typography;\n radii?: Radii;\n shadows?: Shadows;\n spacing?: Spacing;\n motion?: Motion;\n gradient?: Gradient;\n};\n\nexport const brandThemeToTokens = (\n theme: BrandTheme,\n scheme: ResolvedColorScheme,\n): ThemeTokens => ({\n colors: scheme === 'dark' ? theme.colorsDark : theme.colors,\n typography: theme.typography,\n radii: theme.radii,\n // Scheme-independent — the same values apply in light and dark.\n shadows: theme.shadows,\n spacing: theme.spacing,\n motion: theme.motion,\n gradient: theme.gradient,\n});\n\nexport const tokensToCssVars = ({\n colors,\n typography,\n radii,\n shadows,\n spacing,\n motion,\n gradient,\n}: ThemeTokens): Record<string, string> => {\n const vars = createCssVars();\n\n vars.set('--background', colors?.background);\n vars.set('--foreground', colors?.foreground);\n vars.set('--muted', colors?.muted);\n vars.set('--muted-foreground', colors?.mutedForeground);\n vars.set('--border', colors?.border);\n vars.set('--input', colors?.input);\n vars.set('--input-background', colors?.inputBackground);\n vars.set('--ring', colors?.ring);\n vars.set('--ring-offset', colors?.ringOffset);\n vars.set('--primary', colors?.primary);\n vars.set('--primary-foreground', colors?.primaryForeground);\n vars.set('--secondary', colors?.secondary);\n vars.set('--secondary-foreground', colors?.secondaryForeground);\n vars.set('--accent', colors?.accent);\n vars.set('--accent-foreground', colors?.accentForeground);\n vars.set('--card', colors?.card);\n vars.set('--card-foreground', colors?.cardForeground);\n vars.set('--popover', colors?.popover);\n vars.set('--popover-foreground', colors?.popoverForeground);\n vars.set('--destructive', colors?.destructive);\n vars.set('--destructive-foreground', colors?.destructiveForeground);\n vars.set('--success', colors?.success);\n vars.set('--success-foreground', colors?.successForeground);\n vars.set('--warning', colors?.warning);\n vars.set('--warning-foreground', colors?.warningForeground);\n vars.set('--info', colors?.info);\n vars.set('--info-foreground', colors?.infoForeground);\n\n vars.set('--chart-1', colors?.chart?.chart1);\n vars.set('--chart-2', colors?.chart?.chart2);\n vars.set('--chart-3', colors?.chart?.chart3);\n vars.set('--chart-4', colors?.chart?.chart4);\n vars.set('--chart-5', colors?.chart?.chart5);\n\n vars.set('--sidebar', colors?.sidebar?.sidebar);\n vars.set('--sidebar-foreground', colors?.sidebar?.sidebarForeground);\n vars.set('--sidebar-primary', colors?.sidebar?.sidebarPrimary);\n vars.set('--sidebar-primary-foreground', colors?.sidebar?.sidebarPrimaryForeground);\n vars.set('--sidebar-accent', colors?.sidebar?.sidebarAccent);\n vars.set('--sidebar-accent-foreground', colors?.sidebar?.sidebarAccentForeground);\n vars.set('--sidebar-border', colors?.sidebar?.sidebarBorder);\n vars.set('--sidebar-ring', colors?.sidebar?.sidebarRing);\n\n /**\n * TYPOGRAPHY\n */\n vars.set('--font-sans', typography?.fontFamily?.trim() || undefined);\n vars.set('--font-display', typography?.fontDisplay?.trim() || undefined);\n vars.set('--font-mono', typography?.fontMono?.trim() || undefined);\n\n // Chrome font-weight slots — read by Tailwind's `fontWeight` scale.\n vars.set('--font-weight-normal', typography?.weight?.normal);\n vars.set('--font-weight-medium', typography?.weight?.medium);\n vars.set('--font-weight-semibold', typography?.weight?.semibold);\n vars.set('--font-weight-bold', typography?.weight?.bold);\n\n // Chrome tracking — behind Button/Badge `tracking-chrome`.\n vars.set('--letter-spacing-chrome', typography?.letterSpacing?.chrome);\n\n // Type scale — display/heading/body steps read by `text-display/heading/body`.\n vars.set('--type-display-size', typography?.typeScale?.display?.size);\n vars.set('--type-display-weight', typography?.typeScale?.display?.weight);\n vars.set('--type-display-leading', typography?.typeScale?.display?.leading);\n vars.set('--type-display-tracking', typography?.typeScale?.display?.tracking);\n vars.set('--type-heading-size', typography?.typeScale?.heading?.size);\n vars.set('--type-heading-weight', typography?.typeScale?.heading?.weight);\n vars.set('--type-heading-leading', typography?.typeScale?.heading?.leading);\n vars.set('--type-heading-tracking', typography?.typeScale?.heading?.tracking);\n vars.set('--type-body-size', typography?.typeScale?.body?.size);\n vars.set('--type-body-weight', typography?.typeScale?.body?.weight);\n vars.set('--type-body-leading', typography?.typeScale?.body?.leading);\n vars.set('--type-body-tracking', typography?.typeScale?.body?.tracking);\n\n vars.set('--radius-sm', radii?.sm);\n vars.set('--radius-md', radii?.md);\n vars.set('--radius-lg', radii?.lg);\n\n /**\n * ELEVATION / DENSITY / MOTION / GRADIENT\n */\n vars.set('--shadow-sm', shadows?.sm);\n vars.set('--shadow-md', shadows?.md);\n vars.set('--shadow-lg', shadows?.lg);\n vars.set('--shadow-lift', shadows?.lift);\n\n vars.set('--space-gutter', spacing?.gutter);\n vars.set('--space-inset', spacing?.inset);\n\n vars.set('--motion-duration', motion?.duration);\n vars.set('--motion-easing', motion?.easing);\n\n vars.set('--gradient-brand', gradient?.brand);\n\n return vars.expose();\n};\n\nconst setTokens = (node: HTMLElement, vars: Record<string, string>) => {\n for (const [name, value] of Object.entries(vars)) {\n node.style.setProperty(name, value);\n }\n};\n\nconst removeTokens = (node: HTMLElement, vars: Record<string, string>) => {\n for (const name of Object.keys(vars)) {\n node.style.removeProperty(name);\n }\n};\n\n/**\n * Writes a brand's token overrides as inline custom properties.\n *\n * `target` defaults to `<html>` (the app-wide provider). Pass an element to\n * scope the overrides to that subtree instead — `ThemeScope` uses this so a\n * panel can run its own colour scheme: the stylesheet's `[data-theme='dark']`\n * block only re-points the *raw* tokens, while a brand injects the resolved\n * `--color-*` aliases, so a nested scheme must re-inject the brand's values for\n * its own scheme or the brand's light colours leak into a dark subtree.\n */\nexport const useThemeTokens = (tokens: ThemeTokens, target?: HTMLElement | null) => {\n // Insertion effect: runs before the DOM mutates and before any (descendant)\n // layout effect measures token-dependent geometry. Write-only, so it fits the\n // hook's constraints. Only the brand's overrides are set; unset slots fall\n // through to the stylesheet's `:root` / `[data-theme='dark']` defaults.\n useInsertionEffect(() => {\n if (typeof document === 'undefined') return;\n // `undefined` means \"app-wide\"; `null` means \"a scope whose node has not\n // mounted yet\" — nothing to write until the ref lands.\n const node = target === undefined ? document.documentElement : target;\n if (!node) return;\n\n const vars = tokensToCssVars(tokens);\n\n setTokens(node, vars);\n\n return () => removeTokens(node, vars);\n }, [tokens, target]);\n};\n","import { type ReactNode, useMemo } from 'react';\n\nimport type { Brand } from '@keboola/brand-registry';\n\nimport { TooltipProvider } from '../Tooltip';\n\nimport { AIGradientsSvg } from './AIGradientSvg';\nimport { ThemeContext, type ThemeContextValue } from './context';\nimport { DEFAULT_BRANDS, defaultBrand } from './defaults';\nimport { type UseBrandOptions, useBrandState } from './useBrandState';\nimport { type UseColorSchemeOptions, useColorSchemeState } from './useColorSchemeState';\nimport { brandThemeToTokens, useThemeTokens } from './useThemeTokens';\nimport { createTheme } from './utils';\n\ntype Props = UseColorSchemeOptions &\n UseBrandOptions & {\n /** Brands this provider knows about; the active brand id resolves against these. */\n brands?: readonly Brand[];\n children: ReactNode;\n };\n\nexport const ThemeProvider = ({\n defaultScheme,\n scheme,\n onSchemeChange,\n defaultBrandId,\n brandId,\n onBrandIdChange,\n brands = DEFAULT_BRANDS,\n children,\n}: Props) => {\n const colorSchemeState = useColorSchemeState({\n defaultScheme,\n scheme,\n onSchemeChange,\n });\n\n const brandState = useBrandState({\n defaultBrandId,\n brandId,\n onBrandIdChange,\n });\n\n // Resolve the active brand; an unknown id (incl. the default sentinel) falls\n // back to `defaultBrand`, whose empty theme injects nothing so the stylesheet\n // defaults apply.\n const brand = useMemo(\n () => brands.find((item) => item.id === brandState.brandId) ?? defaultBrand,\n [brands, brandState.brandId],\n );\n const themes = useMemo(() => brands.map(createTheme), [brands]);\n const currentTheme = useMemo(() => createTheme(brand), [brand]);\n\n // Only the brand's overrides for the resolved scheme are injected; every slot\n // it omits (including a missing dark palette) falls through to the stylesheet's\n // `:root` / `[data-theme='dark']` defaults — so dark mode works for any brand.\n const themeTokens = useMemo(\n () => brandThemeToTokens(brand.theme, colorSchemeState.resolvedScheme),\n [brand, colorSchemeState.resolvedScheme],\n );\n\n useThemeTokens(themeTokens);\n\n const { scheme: activeScheme, resolvedScheme, setScheme } = colorSchemeState;\n const { brandId: activeBrandId, setBrand } = brandState;\n const context = useMemo<ThemeContextValue>(\n () => ({\n scheme: activeScheme,\n resolvedScheme,\n setScheme,\n brandId: activeBrandId,\n setBrand,\n themes,\n currentTheme,\n brandTheme: brand.theme,\n }),\n [activeScheme, resolvedScheme, setScheme, activeBrandId, setBrand, themes, currentTheme, brand],\n );\n\n return (\n <ThemeContext value={context}>\n <AIGradientsSvg />\n <TooltipProvider>{children}</TooltipProvider>\n </ThemeContext>\n );\n};\n","import { type ReactNode, use, useEffect, useMemo, useRef, useState } from 'react';\nimport { Slot } from '@radix-ui/react-slot';\n\nimport { useTheme } from './context';\nimport { ThemeScopeContainerContext, ThemeScopeSchemeContext } from './themeScopeContext';\nimport type { ColorScheme, ResolvedColorScheme } from './types';\nimport { brandThemeToTokens, tokensToCssVars, useThemeTokens } from './useThemeTokens';\n\nconst DARK_QUERY = '(prefers-color-scheme: dark)';\n\n// Portalled overlays (menus, popovers) mount at the end of <body>, outside the\n// scope, so they would render in the app's scheme. The scope keeps a body-level\n// container carrying the same tokens and hands it to consumers, which pass it to\n// a `container` prop — themed, and without the clipping that portalling back\n// into the panel would cause.\n/** The scope's themed portal container, or `null` outside a `ThemeScope`. */\nexport const useThemeScopeContainer = () => use(ThemeScopeContainerContext);\n\nconst useResolvedScheme = (scheme: ColorScheme): ResolvedColorScheme => {\n const [systemPrefersDark, setSystemPrefersDark] = useState(\n () => globalThis.matchMedia?.(DARK_QUERY).matches ?? false,\n );\n\n useEffect(() => {\n const query = globalThis.matchMedia?.(DARK_QUERY);\n if (!query) return;\n\n const onChange = (event: MediaQueryListEvent) => setSystemPrefersDark(event.matches);\n query.addEventListener('change', onChange);\n\n return () => query.removeEventListener('change', onChange);\n }, []);\n\n if (scheme === 'system') return systemPrefersDark ? 'dark' : 'light';\n\n return scheme;\n};\n\ntype Props = {\n /** Colour scheme for this subtree. `system` follows the OS preference. */\n scheme: ColorScheme;\n /** Merged onto the child element. */\n className?: string;\n /** A single element to theme. Its props are merged — no wrapper is rendered. */\n children: ReactNode;\n};\n\n/**\n * Runs one subtree in its own colour scheme while the rest of the app keeps the\n * provider's.\n *\n * Two things have to happen for that to look right, and doing only the first is\n * why a bare `data-theme` attribute produces a half-themed panel: the\n * stylesheet's `[data-theme='dark']` block re-points the *raw* tokens\n * (`--foreground`), but a brand injects the resolved aliases as inline vars on\n * `<html>`, which the subtree inherits. So the scope also re-injects the active\n * brand's tokens **for its own scheme**, where they beat the inherited ones.\n *\n * It renders **no element of its own** — the attribute, vars and className are\n * merged onto the child. An extra wrapper (even `display: contents`, which\n * layout ignores but selectors do not) silently breaks direct-child selectors\n * like `[data-fill=true] > &` in the element it wraps.\n */\nexport const ThemeScope = ({ scheme, className, children }: Props) => {\n const { brandTheme } = useTheme();\n const resolvedScheme = useResolvedScheme(scheme);\n const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(null);\n\n const tokens = useMemo(\n () => brandThemeToTokens(brandTheme, resolvedScheme),\n [brandTheme, resolvedScheme],\n );\n const style = useMemo(() => tokensToCssVars(tokens), [tokens]);\n\n useThemeTokens(tokens, portalContainer);\n\n // Read at creation without making the container depend on the scheme, which would rebuild it\n // on every flip.\n const schemeRef = useRef(resolvedScheme);\n schemeRef.current = resolvedScheme;\n\n useEffect(() => {\n const container = document.createElement('div');\n container.dataset.themeScopePortal = '';\n // Scoped before it is published: a consumer resolving tokens off this node in the very commit\n // it arrives would otherwise read the page's palette — and cache it under this scope's key.\n container.dataset.theme = schemeRef.current;\n document.body.append(container);\n setPortalContainer(container);\n\n return () => container.remove();\n }, []);\n\n // Keeps an existing container in step; the creation above covers the first commit.\n useEffect(() => {\n portalContainer?.setAttribute('data-theme', resolvedScheme);\n }, [portalContainer, resolvedScheme]);\n\n return (\n <ThemeScopeContainerContext value={portalContainer}>\n {/* The scheme is published as well as painted: a canvas (chart, diagram, editor) builds its\n own palette from the tokens and has to resolve this scope's, not the page's. */}\n <ThemeScopeSchemeContext value={resolvedScheme}>\n <Slot data-theme={resolvedScheme} className={className} style={style}>\n {children}\n </Slot>\n </ThemeScopeSchemeContext>\n </ThemeScopeContainerContext>\n );\n};\n"],"mappings":";;;;;;;;;AAAA,MAAa,uBACX,oBAAC,OAAD;CAAK,OAAM;CAAI,QAAO;CAAI,OAAO;EAAE,UAAU;EAAY,YAAY;CAAS;CAC5E,UAAA,qBAAC,QAAD,EAAA,UAAA,CAEE,qBAAC,kBAAD;EAAgB,IAAG;EAAiB,IAAG;EAAK,IAAG;EAAK,IAAG;EAAO,IAAG;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AC,MAAM,CAAC;CAE7D,eAAe,QAAQ,eAAe;CAItC,MAAM,YAAY,OAAO,cAAc;CACvC,UAAU,UAAU;CAEpB,gBAAgB;EACd,MAAM,YAAY,SAAS,cAAc,KAAK;EAC9C,UAAU,QAAQ,mBAAmB;EAGrC,UAAU,QAAQ,QAAQ,UAAU;EACpC,SAAS,KAAK,OAAO,SAAS;EAC9B,mBAAmB,SAAS;EAE5B,aAAa,UAAU,OAAO;CAChC,GAAG,CAAC,CAAC;CAGL,gBAAgB;EACd,iBAAiB,aAAa,cAAc,cAAc;CAC5D,GAAG,CAAC,iBAAiB,cAAc,CAAC;CAEpC,OACE,oBAAC,4BAAD;EAA4B,OAAO;EAGjC,UAAA,oBAAC,yBAAD;GAAyB,OAAO;GAC9B,UAAA,oBAAC,MAAD;IAAM,cAAY;IAA2B;IAAkB;IAC5D;GACG,CAAA;EACiB,CAAA;CACC,CAAA;AAEhC"}
1
+ {"version":3,"file":"ThemeProvider-BI6JWBdJ.js","names":[],"sources":["../src/components/ThemeProvider/AIGradientSvg.tsx","../src/components/ThemeProvider/useThemeTokens.ts","../src/components/ThemeProvider/ThemeProvider.tsx","../src/components/ThemeProvider/ThemeScope.tsx"],"sourcesContent":["export const AIGradientsSvg = () => (\n <svg width=\"0\" height=\"0\" style={{ position: 'absolute', visibility: 'hidden' }}>\n <defs>\n {/*aigradient-600*/}\n <linearGradient id=\"aigradient-600\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stopColor=\"#61E4FF\" />\n <stop offset=\"50%\" stopColor=\"#1F8FFF\" />\n <stop offset=\"100%\" stopColor=\"#7C5CFF\" />\n </linearGradient>\n\n {/*aigradient-700*/}\n <linearGradient id=\"aigradient-700\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stopColor=\"#075fb8\" />\n <stop offset=\"100%\" stopColor=\"#5b2cb8\" />\n </linearGradient>\n </defs>\n </svg>\n);\n","import { useInsertionEffect } from 'react';\n\nimport type {\n BrandTheme,\n Colors,\n Gradient,\n Motion,\n Radii,\n Shadows,\n Spacing,\n Typography,\n} from '@keboola/brand-registry';\n\nimport type { ResolvedColorScheme } from './types';\nimport { createCssVars } from './utils';\n\nexport type ThemeTokens = {\n colors?: Colors;\n typography?: Typography;\n radii?: Radii;\n shadows?: Shadows;\n spacing?: Spacing;\n motion?: Motion;\n gradient?: Gradient;\n};\n\nexport const brandThemeToTokens = (\n theme: BrandTheme,\n scheme: ResolvedColorScheme,\n): ThemeTokens => ({\n colors: scheme === 'dark' ? theme.colorsDark : theme.colors,\n typography: theme.typography,\n radii: theme.radii,\n // Scheme-independent — the same values apply in light and dark.\n shadows: theme.shadows,\n spacing: theme.spacing,\n motion: theme.motion,\n gradient: theme.gradient,\n});\n\nexport const tokensToCssVars = ({\n colors,\n typography,\n radii,\n shadows,\n spacing,\n motion,\n gradient,\n}: ThemeTokens): Record<string, string> => {\n const vars = createCssVars();\n\n vars.set('--background', colors?.background);\n vars.set('--foreground', colors?.foreground);\n vars.set('--muted', colors?.muted);\n vars.set('--muted-foreground', colors?.mutedForeground);\n vars.set('--border', colors?.border);\n vars.set('--input', colors?.input);\n vars.set('--input-background', colors?.inputBackground);\n vars.set('--ring', colors?.ring);\n vars.set('--ring-offset', colors?.ringOffset);\n vars.set('--primary', colors?.primary);\n vars.set('--primary-foreground', colors?.primaryForeground);\n vars.set('--secondary', colors?.secondary);\n vars.set('--secondary-foreground', colors?.secondaryForeground);\n vars.set('--accent', colors?.accent);\n vars.set('--accent-foreground', colors?.accentForeground);\n vars.set('--card', colors?.card);\n vars.set('--card-foreground', colors?.cardForeground);\n vars.set('--popover', colors?.popover);\n vars.set('--popover-foreground', colors?.popoverForeground);\n vars.set('--destructive', colors?.destructive);\n vars.set('--destructive-foreground', colors?.destructiveForeground);\n vars.set('--success', colors?.success);\n vars.set('--success-foreground', colors?.successForeground);\n vars.set('--warning', colors?.warning);\n vars.set('--warning-foreground', colors?.warningForeground);\n vars.set('--info', colors?.info);\n vars.set('--info-foreground', colors?.infoForeground);\n\n vars.set('--chart-1', colors?.chart?.chart1);\n vars.set('--chart-2', colors?.chart?.chart2);\n vars.set('--chart-3', colors?.chart?.chart3);\n vars.set('--chart-4', colors?.chart?.chart4);\n vars.set('--chart-5', colors?.chart?.chart5);\n\n vars.set('--sidebar', colors?.sidebar?.sidebar);\n vars.set('--sidebar-foreground', colors?.sidebar?.sidebarForeground);\n vars.set('--sidebar-primary', colors?.sidebar?.sidebarPrimary);\n vars.set('--sidebar-primary-foreground', colors?.sidebar?.sidebarPrimaryForeground);\n vars.set('--sidebar-accent', colors?.sidebar?.sidebarAccent);\n vars.set('--sidebar-accent-foreground', colors?.sidebar?.sidebarAccentForeground);\n vars.set('--sidebar-border', colors?.sidebar?.sidebarBorder);\n vars.set('--sidebar-ring', colors?.sidebar?.sidebarRing);\n\n /**\n * TYPOGRAPHY\n */\n vars.set('--font-sans', typography?.fontFamily?.trim() || undefined);\n vars.set('--font-display', typography?.fontDisplay?.trim() || undefined);\n vars.set('--font-mono', typography?.fontMono?.trim() || undefined);\n\n // Chrome font-weight slots — read by Tailwind's `fontWeight` scale.\n vars.set('--font-weight-normal', typography?.weight?.normal);\n vars.set('--font-weight-medium', typography?.weight?.medium);\n vars.set('--font-weight-semibold', typography?.weight?.semibold);\n vars.set('--font-weight-bold', typography?.weight?.bold);\n\n // Chrome tracking — behind Button/Badge `tracking-chrome`.\n vars.set('--letter-spacing-chrome', typography?.letterSpacing?.chrome);\n\n // Type scale — display/heading/body steps read by `text-display/heading/body`.\n vars.set('--type-display-size', typography?.typeScale?.display?.size);\n vars.set('--type-display-weight', typography?.typeScale?.display?.weight);\n vars.set('--type-display-leading', typography?.typeScale?.display?.leading);\n vars.set('--type-display-tracking', typography?.typeScale?.display?.tracking);\n vars.set('--type-heading-size', typography?.typeScale?.heading?.size);\n vars.set('--type-heading-weight', typography?.typeScale?.heading?.weight);\n vars.set('--type-heading-leading', typography?.typeScale?.heading?.leading);\n vars.set('--type-heading-tracking', typography?.typeScale?.heading?.tracking);\n vars.set('--type-body-size', typography?.typeScale?.body?.size);\n vars.set('--type-body-weight', typography?.typeScale?.body?.weight);\n vars.set('--type-body-leading', typography?.typeScale?.body?.leading);\n vars.set('--type-body-tracking', typography?.typeScale?.body?.tracking);\n\n vars.set('--radius-sm', radii?.sm);\n vars.set('--radius-md', radii?.md);\n vars.set('--radius-lg', radii?.lg);\n\n /**\n * ELEVATION / DENSITY / MOTION / GRADIENT\n */\n vars.set('--shadow-sm', shadows?.sm);\n vars.set('--shadow-md', shadows?.md);\n vars.set('--shadow-lg', shadows?.lg);\n vars.set('--shadow-lift', shadows?.lift);\n\n vars.set('--space-gutter', spacing?.gutter);\n vars.set('--space-inset', spacing?.inset);\n\n vars.set('--motion-duration', motion?.duration);\n vars.set('--motion-easing', motion?.easing);\n\n vars.set('--gradient-brand', gradient?.brand);\n\n return vars.expose();\n};\n\nconst setTokens = (node: HTMLElement, vars: Record<string, string>) => {\n for (const [name, value] of Object.entries(vars)) {\n node.style.setProperty(name, value);\n }\n};\n\nconst removeTokens = (node: HTMLElement, vars: Record<string, string>) => {\n for (const name of Object.keys(vars)) {\n node.style.removeProperty(name);\n }\n};\n\n/**\n * Writes a brand's token overrides as inline custom properties.\n *\n * `target` defaults to `<html>` (the app-wide provider). Pass an element to\n * scope the overrides to that subtree instead — `ThemeScope` uses this so a\n * panel can run its own colour scheme: the stylesheet's `[data-theme='dark']`\n * block only re-points the *raw* tokens, while a brand injects the resolved\n * `--color-*` aliases, so a nested scheme must re-inject the brand's values for\n * its own scheme or the brand's light colours leak into a dark subtree.\n */\nexport const useThemeTokens = (tokens: ThemeTokens, target?: HTMLElement | null) => {\n // Insertion effect: runs before the DOM mutates and before any (descendant)\n // layout effect measures token-dependent geometry. Write-only, so it fits the\n // hook's constraints. Only the brand's overrides are set; unset slots fall\n // through to the stylesheet's `:root` / `[data-theme='dark']` defaults.\n useInsertionEffect(() => {\n if (typeof document === 'undefined') return;\n // `undefined` means \"app-wide\"; `null` means \"a scope whose node has not\n // mounted yet\" — nothing to write until the ref lands.\n const node = target === undefined ? document.documentElement : target;\n if (!node) return;\n\n const vars = tokensToCssVars(tokens);\n\n setTokens(node, vars);\n\n return () => removeTokens(node, vars);\n }, [tokens, target]);\n};\n","import { type ReactNode, useMemo } from 'react';\n\nimport type { Brand } from '@keboola/brand-registry';\n\nimport { TooltipProvider } from '../Tooltip';\n\nimport { AIGradientsSvg } from './AIGradientSvg';\nimport { ThemeContext, type ThemeContextValue } from './context';\nimport { DEFAULT_BRANDS, defaultBrand } from './defaults';\nimport { type UseBrandOptions, useBrandState } from './useBrandState';\nimport { type UseColorSchemeOptions, useColorSchemeState } from './useColorSchemeState';\nimport { brandThemeToTokens, useThemeTokens } from './useThemeTokens';\nimport { createTheme } from './utils';\n\ntype Props = UseColorSchemeOptions &\n UseBrandOptions & {\n /** Brands this provider knows about; the active brand id resolves against these. */\n brands?: readonly Brand[];\n children: ReactNode;\n };\n\nexport const ThemeProvider = ({\n defaultScheme,\n scheme,\n onSchemeChange,\n defaultBrandId,\n brandId,\n onBrandIdChange,\n brands = DEFAULT_BRANDS,\n children,\n}: Props) => {\n const colorSchemeState = useColorSchemeState({\n defaultScheme,\n scheme,\n onSchemeChange,\n });\n\n const brandState = useBrandState({\n defaultBrandId,\n brandId,\n onBrandIdChange,\n });\n\n // Resolve the active brand; an unknown id (incl. the default sentinel) falls\n // back to `defaultBrand`, whose empty theme injects nothing so the stylesheet\n // defaults apply.\n const brand = useMemo(\n () => brands.find((item) => item.id === brandState.brandId) ?? defaultBrand,\n [brands, brandState.brandId],\n );\n const themes = useMemo(() => brands.map(createTheme), [brands]);\n const currentTheme = useMemo(() => createTheme(brand), [brand]);\n\n // Only the brand's overrides for the resolved scheme are injected; every slot\n // it omits (including a missing dark palette) falls through to the stylesheet's\n // `:root` / `[data-theme='dark']` defaults — so dark mode works for any brand.\n const themeTokens = useMemo(\n () => brandThemeToTokens(brand.theme, colorSchemeState.resolvedScheme),\n [brand, colorSchemeState.resolvedScheme],\n );\n\n useThemeTokens(themeTokens);\n\n const { scheme: activeScheme, resolvedScheme, setScheme } = colorSchemeState;\n const { brandId: activeBrandId, setBrand } = brandState;\n const context = useMemo<ThemeContextValue>(\n () => ({\n scheme: activeScheme,\n resolvedScheme,\n setScheme,\n brandId: activeBrandId,\n setBrand,\n themes,\n currentTheme,\n brandTheme: brand.theme,\n }),\n [activeScheme, resolvedScheme, setScheme, activeBrandId, setBrand, themes, currentTheme, brand],\n );\n\n return (\n <ThemeContext value={context}>\n <AIGradientsSvg />\n <TooltipProvider>{children}</TooltipProvider>\n </ThemeContext>\n );\n};\n","import { type ReactNode, use, useEffect, useMemo, useRef, useState } from 'react';\nimport { Slot } from '@radix-ui/react-slot';\n\nimport { useTheme } from './context';\nimport { ThemeScopeContainerContext, ThemeScopeSchemeContext } from './themeScopeContext';\nimport type { ColorScheme, ResolvedColorScheme } from './types';\nimport { brandThemeToTokens, tokensToCssVars, useThemeTokens } from './useThemeTokens';\n\nconst DARK_QUERY = '(prefers-color-scheme: dark)';\n\n// Portalled overlays (menus, popovers) mount at the end of <body>, outside the\n// scope, so they would render in the app's scheme. The scope keeps a body-level\n// container carrying the same tokens and hands it to consumers, which pass it to\n// a `container` prop — themed, and without the clipping that portalling back\n// into the panel would cause.\n/** The scope's themed portal container, or `null` outside a `ThemeScope`. */\nexport const useThemeScopeContainer = () => use(ThemeScopeContainerContext);\n\nconst useResolvedScheme = (scheme: ColorScheme): ResolvedColorScheme => {\n const [systemPrefersDark, setSystemPrefersDark] = useState(\n () => globalThis.matchMedia?.(DARK_QUERY).matches ?? false,\n );\n\n useEffect(() => {\n const query = globalThis.matchMedia?.(DARK_QUERY);\n if (!query) return;\n\n const onChange = (event: MediaQueryListEvent) => setSystemPrefersDark(event.matches);\n query.addEventListener('change', onChange);\n\n return () => query.removeEventListener('change', onChange);\n }, []);\n\n if (scheme === 'system') return systemPrefersDark ? 'dark' : 'light';\n\n return scheme;\n};\n\ntype Props = {\n /** Colour scheme for this subtree. `system` follows the OS preference. */\n scheme: ColorScheme;\n /** Merged onto the child element. */\n className?: string;\n /** A single element to theme. Its props are merged — no wrapper is rendered. */\n children: ReactNode;\n};\n\n/**\n * Runs one subtree in its own colour scheme while the rest of the app keeps the\n * provider's.\n *\n * Two things have to happen for that to look right, and doing only the first is\n * why a bare `data-theme` attribute produces a half-themed panel: the\n * stylesheet's `[data-theme='dark']` block re-points the *raw* tokens\n * (`--foreground`), but a brand injects the resolved aliases as inline vars on\n * `<html>`, which the subtree inherits. So the scope also re-injects the active\n * brand's tokens **for its own scheme**, where they beat the inherited ones.\n *\n * It renders **no element of its own** — the attribute, vars and className are\n * merged onto the child. An extra wrapper (even `display: contents`, which\n * layout ignores but selectors do not) silently breaks direct-child selectors\n * like `[data-fill=true] > &` in the element it wraps.\n */\nexport const ThemeScope = ({ scheme, className, children }: Props) => {\n const { brandTheme } = useTheme();\n const resolvedScheme = useResolvedScheme(scheme);\n const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(null);\n\n const tokens = useMemo(\n () => brandThemeToTokens(brandTheme, resolvedScheme),\n [brandTheme, resolvedScheme],\n );\n const style = useMemo(() => tokensToCssVars(tokens), [tokens]);\n\n useThemeTokens(tokens, portalContainer);\n\n // Read at creation without making the container depend on the scheme, which would rebuild it\n // on every flip.\n const schemeRef = useRef(resolvedScheme);\n schemeRef.current = resolvedScheme;\n\n useEffect(() => {\n const container = document.createElement('div');\n container.dataset.themeScopePortal = '';\n // Scoped before it is published: a consumer resolving tokens off this node in the very commit\n // it arrives would otherwise read the page's palette — and cache it under this scope's key.\n container.dataset.theme = schemeRef.current;\n document.body.append(container);\n setPortalContainer(container);\n\n return () => container.remove();\n }, []);\n\n // Keeps an existing container in step; the creation above covers the first commit.\n useEffect(() => {\n portalContainer?.setAttribute('data-theme', resolvedScheme);\n }, [portalContainer, resolvedScheme]);\n\n return (\n <ThemeScopeContainerContext value={portalContainer}>\n {/* The scheme is published as well as painted: a canvas (chart, diagram, editor) builds its\n own palette from the tokens and has to resolve this scope's, not the page's. */}\n <ThemeScopeSchemeContext value={resolvedScheme}>\n <Slot data-theme={resolvedScheme} className={className} style={style}>\n {children}\n </Slot>\n </ThemeScopeSchemeContext>\n </ThemeScopeContainerContext>\n );\n};\n"],"mappings":";;;;;;;;;AAAA,MAAa,uBACX,oBAAC,OAAD;CAAK,OAAM;CAAI,QAAO;CAAI,OAAO;EAAE,UAAU;EAAY,YAAY;CAAS;CAC5E,UAAA,qBAAC,QAAD,EAAA,UAAA,CAEE,qBAAC,kBAAD;EAAgB,IAAG;EAAiB,IAAG;EAAK,IAAG;EAAK,IAAG;EAAO,IAAG;EAAjE,UAAA;GACE,oBAAC,QAAD;IAAM,QAAO;IAAK,WAAU;GAAW,CAAA;GACvC,oBAAC,QAAD;IAAM,QAAO;IAAM,WAAU;GAAW,CAAA;GACxC,oBAAC,QAAD;IAAM,QAAO;IAAO,WAAU;GAAW,CAAA;EAC3B;CAGhB,CAAA,GAAA,qBAAC,kBAAD;EAAgB,IAAG;EAAiB,IAAG;EAAK,IAAG;EAAK,IAAG;EAAO,IAAG;EAAjE,UAAA,CACE,oBAAC,QAAD;GAAM,QAAO;GAAK,WAAU;EAAW,CAAA,GACvC,oBAAC,QAAD;GAAM,QAAO;GAAO,WAAU;EAAW,CAAA,CAC3B;CACZ,CAAA,CAAA,EAAA,CAAA;AACH,CAAA;;;ACUP,MAAa,sBACX,OACA,YACiB;CACjB,QAAQ,WAAW,SAAS,MAAM,aAAa,MAAM;CACrD,YAAY,MAAM;CAClB,OAAO,MAAM;CAEb,SAAS,MAAM;CACf,SAAS,MAAM;CACf,QAAQ,MAAM;CACd,UAAU,MAAM;AAClB;AAEA,MAAa,mBAAmB,EAC9B,QACA,YACA,OACA,SACA,SACA,QACA,eACyC;CACzC,MAAM,OAAO,cAAc;CAE3B,KAAK,IAAI,gBAAgB,QAAQ,UAAU;CAC3C,KAAK,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,iBAAiB,UAAU,QAAQ;EAEzC,aAAa,MAAM,oBAAoB,UAAU,QAAQ;CAC3D,GAAG,CAAC,CAAC;CAEL,IAAI,WAAW,UAAU,OAAO,oBAAoB,SAAS;CAE7D,OAAO;AACT;;;;;;;;;;;;;;;;;AA2BA,MAAa,cAAc,EAAE,QAAQ,WAAW,eAAsB;CACpE,MAAM,EAAE,eAAe,SAAS;CAChC,MAAM,iBAAiB,kBAAkB,MAAM;CAC/C,MAAM,CAAC,iBAAiB,sBAAsB,SAAgC,IAAI;CAElF,MAAM,SAAS,cACP,mBAAmB,YAAY,cAAc,GACnD,CAAC,YAAY,cAAc,CAC7B;CACA,MAAM,QAAQ,cAAc,gBAAgB,MAAM,GAAG,CAAC,MAAM,CAAC;CAE7D,eAAe,QAAQ,eAAe;CAItC,MAAM,YAAY,OAAO,cAAc;CACvC,UAAU,UAAU;CAEpB,gBAAgB;EACd,MAAM,YAAY,SAAS,cAAc,KAAK;EAC9C,UAAU,QAAQ,mBAAmB;EAGrC,UAAU,QAAQ,QAAQ,UAAU;EACpC,SAAS,KAAK,OAAO,SAAS;EAC9B,mBAAmB,SAAS;EAE5B,aAAa,UAAU,OAAO;CAChC,GAAG,CAAC,CAAC;CAGL,gBAAgB;EACd,iBAAiB,aAAa,cAAc,cAAc;CAC5D,GAAG,CAAC,iBAAiB,cAAc,CAAC;CAEpC,OACE,oBAAC,4BAAD;EAA4B,OAAO;EAGjC,UAAA,oBAAC,yBAAD;GAAyB,OAAO;GAC9B,UAAA,oBAAC,MAAD;IAAM,cAAY;IAA2B;IAAkB;IAC5D;GACG,CAAA;EACiB,CAAA;CACC,CAAA;AAEhC"}
@@ -1,8 +1,8 @@
1
1
  import { cn } from "./classNames-BzrkDnOD.js";
2
- import { Tooltip } from "./utils-DSvrhU8E.js";
2
+ import { Tooltip } from "./utils-DnkrFYqY.js";
3
3
  import { Maximize2, Minimize2 } from "./icons-Cek151jC.js";
4
4
  import { Button } from "./Button-DsRrU5F1.js";
5
- import { ClipboardButton } from "./ClipboardButton-CwZJdRaz.js";
5
+ import { ClipboardButton } from "./ClipboardButton-CrljClL1.js";
6
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
7
  import { jsx, jsxs } from "react/jsx-runtime";
8
8
  import { createPortal } from "react-dom";
@@ -245,4 +245,4 @@ const svgToPngBlob = async (svg, background) => {
245
245
  //#endregion
246
246
  export { ZoomableSvg, svgToPngBlob, toSvgFileContent };
247
247
 
248
- //# sourceMappingURL=ZoomableSvg-pooPb1Cu.js.map
248
+ //# sourceMappingURL=ZoomableSvg-U_VH3QRO.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ZoomableSvg-pooPb1Cu.js","names":[],"sources":["../src/components/ZoomableSvg/ZoomableSvg.tsx","../src/components/ZoomableSvg/exportSvg.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport DOMPurify from 'dompurify';\n\nimport { ClipboardButton } from '../../blocks/ClipboardButton';\nimport { Maximize2, Minimize2 } from '../../icons';\nimport { cn } from '../../utils';\nimport { Button } from '../Button';\nimport { Tooltip } from '../Tooltip';\n\nconst MIN_SCALE = 0.5;\nconst MAX_SCALE = 3;\nconst ZOOM_STEP = 0.1;\n\ntype Props = {\n /** Raw SVG markup. Sanitized internally with DOMPurify (SVG profile) before rendering, so it is\n * safe even when it originates from user/LLM-controlled content. Non-SVG HTML is stripped. */\n html: string;\n copyText?: string;\n className?: string;\n /**\n * Opt in to keeping `<foreignObject>` elements through sanitization. Off by\n * default — the SVG profile drops `<foreignObject>` so no HTML subtree can\n * survive. Only enable when the caller pre-flattens each `<foreignObject>` to\n * bare text (the SVG profile still strips any HTML children even when the\n * element itself is allowed). `MermaidDiagram` sets this for node/icon labels.\n */\n allowForeignObject?: boolean;\n /**\n * Extra toolbar controls, rendered between the copy and fullscreen buttons.\n *\n * Injected rather than built in, so export behaviour — filenames,\n * rasterization, error reporting — stays with the consumer and this component\n * keeps shipping in the lazy `@keboola/design/mermaid` chunk with no download\n * dependencies of its own. Pass `ExportMenu` here. Receives the sanitized\n * SVG so an exporter writes exactly what is on screen.\n */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const ZoomableSvg = ({\n html,\n copyText,\n className,\n allowForeignObject,\n renderActions,\n}: Props) => {\n const safeHtml = useMemo(\n () =>\n DOMPurify.sanitize(html, {\n USE_PROFILES: { svg: true, svgFilters: true },\n ...(allowForeignObject ? { ADD_TAGS: ['foreignObject'] } : {}),\n }),\n [html, allowForeignObject],\n );\n\n const containerRef = useRef<HTMLDivElement>(null);\n const [scale, setScale] = useState(1);\n const [translate, setTranslate] = useState({ x: 0, y: 0 });\n const [isFullscreen, setIsFullscreen] = useState(false);\n\n useEffect(() => {\n if (!isFullscreen) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n e.stopPropagation();\n setIsFullscreen(false);\n }\n };\n document.addEventListener('keydown', onKeyDown, { capture: true });\n return () => document.removeEventListener('keydown', onKeyDown, { capture: true });\n }, [isFullscreen]);\n\n const dragRef = useRef<{\n startX: number;\n startY: number;\n startTx: number;\n startTy: number;\n } | null>(null);\n\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;\n setScale((s) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, s + delta)));\n };\n\n el.addEventListener('wheel', onWheel, { passive: false });\n return () => el.removeEventListener('wheel', onWheel);\n // Re-bind when toggling fullscreen: the portal/inline switch remounts the\n // container element, so the listener must attach to the new node.\n }, [isFullscreen]);\n\n const didDragRef = useRef(false);\n\n const handleMouseDown = useCallback(\n (e: React.MouseEvent) => {\n if (e.button !== 0) return;\n e.preventDefault();\n didDragRef.current = false;\n dragRef.current = {\n startX: e.clientX,\n startY: e.clientY,\n startTx: translate.x,\n startTy: translate.y,\n };\n },\n [translate],\n );\n\n const handleMouseMove = useCallback((e: React.MouseEvent) => {\n if (!dragRef.current) return;\n didDragRef.current = true;\n setTranslate({\n x: dragRef.current.startTx + e.clientX - dragRef.current.startX,\n y: dragRef.current.startTy + e.clientY - dragRef.current.startY,\n });\n }, []);\n\n const handleMouseUp = useCallback(() => {\n dragRef.current = null;\n }, []);\n\n const handleReset = useCallback(() => {\n setScale(1);\n setTranslate({ x: 0, y: 0 });\n }, []);\n\n const isZoomed = Math.abs(scale - 1) > 0.001 || translate.x !== 0 || translate.y !== 0;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (didDragRef.current) {\n e.stopPropagation();\n }\n }, []);\n\n const stopPropagation = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n }, []);\n\n const diagramContent = (\n <div\n role=\"presentation\"\n className={cn('tw:group/zoom tw:relative', isFullscreen && 'tw:h-full')}\n onClick={handleClick}\n >\n <div\n role=\"presentation\"\n ref={containerRef}\n className={cn(\n 'tw:overflow-hidden tw:cursor-grab tw:active:cursor-grabbing tw:p-3',\n isFullscreen && 'tw:h-full',\n )}\n onMouseDown={handleMouseDown}\n onMouseMove={handleMouseMove}\n onMouseUp={handleMouseUp}\n onMouseLeave={handleMouseUp}\n >\n <div\n className={cn(\n 'tw:flex tw:justify-center tw:origin-center',\n isFullscreen && 'tw:h-full tw:[&>svg]:h-full',\n )}\n style={{ transform: `translate(${translate.x}px, ${translate.y}px) scale(${scale})` }}\n dangerouslySetInnerHTML={{ __html: safeHtml }}\n />\n </div>\n <div\n role=\"presentation\"\n // `focus-within` as well as hover: the toolbar is opacity-0 but still in\n // the tab order, so without this a keyboard user tabs through invisible\n // controls with no visible focus ring.\n className=\"tw:absolute tw:right-1 tw:top-1 tw:flex tw:gap-1 tw:opacity-0 tw:transition-opacity tw:focus-within:opacity-100 tw:group-hover/zoom:opacity-100\"\n onClick={stopPropagation}\n >\n {isZoomed && (\n <Tooltip tooltip=\"Reset zoom\" placement=\"top\" triggerAsChild>\n <Button size=\"small\" variant=\"outline\" onClick={handleReset}>\n Reset\n </Button>\n </Tooltip>\n )}\n {copyText && (\n <ClipboardButton text={copyText} tooltip=\"Copy code\" size=\"icon-sm\" variant=\"outline\" />\n )}\n {renderActions?.(safeHtml)}\n <Tooltip\n tooltip={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}\n placement=\"top\"\n triggerAsChild\n >\n <Button\n size=\"icon-sm\"\n variant=\"outline\"\n aria-label={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}\n onClick={() => setIsFullscreen((f) => !f)}\n >\n {isFullscreen ? (\n <Minimize2 className=\"tw:size-4\" />\n ) : (\n <Maximize2 className=\"tw:size-4\" />\n )}\n </Button>\n </Tooltip>\n </div>\n </div>\n );\n\n if (isFullscreen) {\n return createPortal(\n <div\n role=\"presentation\"\n data-testid=\"zoomable-svg-fullscreen\"\n /**\n * Stacking contract for this overlay, which portals to `document.body`.\n *\n * - Sits at z-1051, the Modal/Sheet band: above page chrome.\n * - Stays *below* the floating-panel layer (z-1055: DropdownMenu,\n * Popover, Select, Combobox), which portals to `document.body` too —\n * an overlay above it hides any menu opened from the toolbar.\n * - `Tooltip` (z-1060) renders above, as it does over a Modal.\n * - `SpotlightBackdrop` (z-1056) dims this overlay rather than sitting\n * under it — by design, since it deliberately covers the portalled\n * surface tier so a tour's dim can't be punched through.\n * - An app may clamp poppers into this same band, making it a tie that\n * DOM order settles; Radix mounts its portal after this one.\n */\n className=\"tw:fixed tw:inset-0 tw:z-[1051] tw:bg-muted tw:p-4 tailwindcss-preflight\"\n onClick={stopPropagation}\n >\n {diagramContent}\n </div>,\n document.body,\n );\n }\n\n return (\n <div\n className={cn(\n 'tw:overflow-hidden tw:rounded-md tw:border tw:border-border tw:bg-muted',\n className,\n )}\n >\n {diagramContent}\n </div>\n );\n};\n","const PNG_SCALE = 2;\n\n// The root `<svg …>` tag, so the namespace check looks only at its attributes.\n// A plain `includes('xmlns=')` would also match a nested element or body text,\n// and would miss `xmlns = \"…\"` — adding a second declaration, which parsers\n// reject outright with \"Attribute xmlns redefined\".\nconst ROOT_SVG_TAG = /^<svg\\b[^>]*>/i;\nconst HAS_DEFAULT_NAMESPACE = /\\bxmlns\\s*=/i;\n\n// A standalone SVG file needs the namespace declaration; mermaid's inline output\n// omits it because an inline <svg> inherits it from the host document.\n// Trim before matching: the anchored `^<svg` misses markup that arrives with a\n// leading newline or indentation, which would emit a standalone file with no\n// namespace — unopenable in an image viewer.\nconst withSvgNamespace = (svg: string) => {\n const trimmed = svg.trim();\n const rootTag = trimmed.match(ROOT_SVG_TAG)?.[0];\n\n if (!rootTag || HAS_DEFAULT_NAMESPACE.test(rootTag)) return trimmed;\n\n return trimmed.replace(/^<svg\\b/i, '<svg xmlns=\"http://www.w3.org/2000/svg\"');\n};\n\nexport const toSvgFileContent = (svg: string) =>\n `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${withSvgNamespace(svg).trim()}\\n`;\n\n// A single decimal number: `12`, `12.5`, `.5`. Deliberately stricter than\n// `[\\d.]+`, which also matches `1.2.3` — and `parseFloat` truncates that to\n// `1.2` rather than rejecting it, so a malformed value would pass as a plausible\n// one.\nconst NUMBER = String.raw`\\d+(?:\\.\\d+)?|\\.\\d+`;\n\n// `parseFloat` happily reads a relative length as a number — `\"100%\"` becomes\n// `100`, `\"2em\"` becomes `2` — and `makeResponsive` sets `width=\"100%\"` on every\n// mermaid root, so an SVG with no usable viewBox would rasterize 100px wide with\n// no error. Accept only a unitless number or an explicit `px`.\nconst PIXEL_LENGTH = new RegExp(String.raw`^\\s*(?:${NUMBER})(?:px)?\\s*$`, 'i');\n\nconst parsePixelLength = (value: string | null): number | null => {\n if (!PIXEL_LENGTH.test(value ?? '')) return null;\n\n const parsed = Number.parseFloat(value ?? '');\n\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n};\n\nexport const parseSvgSize = (svg: string) => {\n const doc = new DOMParser().parseFromString(withSvgNamespace(svg), 'image/svg+xml');\n const element = doc.documentElement;\n\n const viewBox = element\n .getAttribute('viewBox')\n ?.split(/[\\s,]+/)\n .map(Number);\n // `> 0`, not truthiness: a negative extent is accepted by a truthy check, and\n // negative canvas dimensions silently fall back to the 300x150 default — an\n // export at the wrong size with no error. Falling through to width/height is\n // the better answer, since those are usually still valid.\n if (viewBox?.length === 4 && viewBox.every((value) => Number.isFinite(value))) {\n const [, , width, height] = viewBox;\n if (width !== undefined && height !== undefined && width > 0 && height > 0) {\n return { width, height };\n }\n }\n\n const width = parsePixelLength(element.getAttribute('width'));\n const height = parsePixelLength(element.getAttribute('height'));\n\n return width !== null && height !== null ? { width, height } : null;\n};\n\n// Resolve the themed page background so the exported PNG follows the active\n// brand and color scheme instead of a frozen literal. Falls back to `white`\n// (a CSS keyword, not a brand-locked hex) when the token is unset.\n//\n// The token holds Tailwind's bare channel triplet (\"249 250 251\") so utilities\n// can add an alpha. Canvas `fillStyle` rejects that form *silently* and keeps\n// its previous value (black), so wrap it back into rgb() before use.\nconst CHANNEL_TRIPLET = new RegExp(String.raw`^(?:${NUMBER})\\s+(?:${NUMBER})\\s+(?:${NUMBER})$`);\n\nexport const toCanvasColor = (token: string) => {\n const trimmed = token.trim();\n if (!trimmed) return 'white';\n\n // Only wrap a well-formed triplet. A malformed one (`1.2.3 4 5`) would produce\n // an invalid `rgb()` that `fillStyle` rejects silently, painting the PNG on\n // whatever colour was set before — passing it through unwrapped at least lets\n // a genuine CSS color value work.\n return CHANNEL_TRIPLET.test(trimmed) ? `rgb(${trimmed})` : trimmed;\n};\n\nconst resolveBackground = () =>\n toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue('--color-background'));\n\n/**\n * Rasterize SVG markup to a PNG blob at 2x for legible text.\n *\n * The SVG is loaded as a data URL rather than a blob URL: an <img> loading SVG\n * is treated as a foreign resource, so a blob URL would taint the canvas and\n * make toBlob throw a SecurityError. A background is painted first because a\n * transparent PNG reads as unusable when pasted into a slide deck.\n */\nexport const svgToPngBlob = async (svg: string, background?: string): Promise<Blob> => {\n const size = parseSvgSize(svg);\n if (!size) throw new Error('Cannot determine diagram dimensions.');\n\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(toSvgFileContent(svg))}`;\n\n const image = new Image();\n image.decoding = 'sync';\n await new Promise<void>((resolve, reject) => {\n image.onload = () => resolve();\n image.onerror = () => reject(new Error('Failed to load the diagram for export.'));\n image.src = encoded;\n });\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(size.width * PNG_SCALE);\n canvas.height = Math.round(size.height * PNG_SCALE);\n\n const context = canvas.getContext('2d');\n if (!context) throw new Error('Canvas is unavailable in this browser.');\n\n context.fillStyle = background ?? resolveBackground();\n context.fillRect(0, 0, canvas.width, canvas.height);\n context.drawImage(image, 0, 0, canvas.width, canvas.height);\n\n return new Promise<Blob>((resolve, reject) => {\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('Failed to encode the PNG.'))),\n 'image/png',\n );\n });\n};\n"],"mappings":";;;;;;;;;;AAWA,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,YAAY;AA4BlB,MAAa,eAAe,EAC1B,MACA,UACA,WACA,oBACA,oBACW;CACX,MAAM,WAAW,cAEb,UAAU,SAAS,MAAM;EACvB,cAAc;GAAE,KAAK;GAAM,YAAY;EAAK;EAC5C,GAAI,qBAAqB,EAAE,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;CAC9D,CAAC,GACH,CAAC,MAAM,kBAAkB,CAC3B;CAEA,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,CAAC,OAAO,YAAY,SAAS,CAAC;CACpC,MAAM,CAAC,WAAW,gBAAgB,SAAS;EAAE,GAAG;EAAG,GAAG;CAAE,CAAC;CACzD,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CAEtD,gBAAgB;EACd,IAAI,CAAC,cAAc;EACnB,MAAM,aAAa,MAAqB;GACtC,IAAI,EAAE,QAA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AAQ,SAAS;CAChD,OAAO,SAAS,KAAK,MAAM,KAAK,SAAS,SAAS;CAElD,MAAM,UAAU,OAAO,WAAW,IAAI;CACtC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,wCAAwC;CAEtE,QAAQ,YAAY,cAAc,kBAAkB;CACpD,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;CAClD,QAAQ,UAAU,OAAO,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;CAE1D,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,QACJ,SAAU,OAAO,QAAQ,IAAI,IAAI,uBAAO,IAAI,MAAM,2BAA2B,CAAC,GAC/E,WACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"ZoomableSvg-U_VH3QRO.js","names":[],"sources":["../src/components/ZoomableSvg/ZoomableSvg.tsx","../src/components/ZoomableSvg/exportSvg.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport DOMPurify from 'dompurify';\n\nimport { ClipboardButton } from '../../blocks/ClipboardButton';\nimport { Maximize2, Minimize2 } from '../../icons';\nimport { cn } from '../../utils';\nimport { Button } from '../Button';\nimport { Tooltip } from '../Tooltip';\n\nconst MIN_SCALE = 0.5;\nconst MAX_SCALE = 3;\nconst ZOOM_STEP = 0.1;\n\ntype Props = {\n /** Raw SVG markup. Sanitized internally with DOMPurify (SVG profile) before rendering, so it is\n * safe even when it originates from user/LLM-controlled content. Non-SVG HTML is stripped. */\n html: string;\n copyText?: string;\n className?: string;\n /**\n * Opt in to keeping `<foreignObject>` elements through sanitization. Off by\n * default — the SVG profile drops `<foreignObject>` so no HTML subtree can\n * survive. Only enable when the caller pre-flattens each `<foreignObject>` to\n * bare text (the SVG profile still strips any HTML children even when the\n * element itself is allowed). `MermaidDiagram` sets this for node/icon labels.\n */\n allowForeignObject?: boolean;\n /**\n * Extra toolbar controls, rendered between the copy and fullscreen buttons.\n *\n * Injected rather than built in, so export behaviour — filenames,\n * rasterization, error reporting — stays with the consumer and this component\n * keeps shipping in the lazy `@keboola/design/mermaid` chunk with no download\n * dependencies of its own. Pass `ExportMenu` here. Receives the sanitized\n * SVG so an exporter writes exactly what is on screen.\n */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const ZoomableSvg = ({\n html,\n copyText,\n className,\n allowForeignObject,\n renderActions,\n}: Props) => {\n const safeHtml = useMemo(\n () =>\n DOMPurify.sanitize(html, {\n USE_PROFILES: { svg: true, svgFilters: true },\n ...(allowForeignObject ? { ADD_TAGS: ['foreignObject'] } : {}),\n }),\n [html, allowForeignObject],\n );\n\n const containerRef = useRef<HTMLDivElement>(null);\n const [scale, setScale] = useState(1);\n const [translate, setTranslate] = useState({ x: 0, y: 0 });\n const [isFullscreen, setIsFullscreen] = useState(false);\n\n useEffect(() => {\n if (!isFullscreen) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n e.stopPropagation();\n setIsFullscreen(false);\n }\n };\n document.addEventListener('keydown', onKeyDown, { capture: true });\n return () => document.removeEventListener('keydown', onKeyDown, { capture: true });\n }, [isFullscreen]);\n\n const dragRef = useRef<{\n startX: number;\n startY: number;\n startTx: number;\n startTy: number;\n } | null>(null);\n\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;\n setScale((s) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, s + delta)));\n };\n\n el.addEventListener('wheel', onWheel, { passive: false });\n return () => el.removeEventListener('wheel', onWheel);\n // Re-bind when toggling fullscreen: the portal/inline switch remounts the\n // container element, so the listener must attach to the new node.\n }, [isFullscreen]);\n\n const didDragRef = useRef(false);\n\n const handleMouseDown = useCallback(\n (e: React.MouseEvent) => {\n if (e.button !== 0) return;\n e.preventDefault();\n didDragRef.current = false;\n dragRef.current = {\n startX: e.clientX,\n startY: e.clientY,\n startTx: translate.x,\n startTy: translate.y,\n };\n },\n [translate],\n );\n\n const handleMouseMove = useCallback((e: React.MouseEvent) => {\n if (!dragRef.current) return;\n didDragRef.current = true;\n setTranslate({\n x: dragRef.current.startTx + e.clientX - dragRef.current.startX,\n y: dragRef.current.startTy + e.clientY - dragRef.current.startY,\n });\n }, []);\n\n const handleMouseUp = useCallback(() => {\n dragRef.current = null;\n }, []);\n\n const handleReset = useCallback(() => {\n setScale(1);\n setTranslate({ x: 0, y: 0 });\n }, []);\n\n const isZoomed = Math.abs(scale - 1) > 0.001 || translate.x !== 0 || translate.y !== 0;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (didDragRef.current) {\n e.stopPropagation();\n }\n }, []);\n\n const stopPropagation = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n }, []);\n\n const diagramContent = (\n <div\n role=\"presentation\"\n className={cn('tw:group/zoom tw:relative', isFullscreen && 'tw:h-full')}\n onClick={handleClick}\n >\n <div\n role=\"presentation\"\n ref={containerRef}\n className={cn(\n 'tw:overflow-hidden tw:cursor-grab tw:active:cursor-grabbing tw:p-3',\n isFullscreen && 'tw:h-full',\n )}\n onMouseDown={handleMouseDown}\n onMouseMove={handleMouseMove}\n onMouseUp={handleMouseUp}\n onMouseLeave={handleMouseUp}\n >\n <div\n className={cn(\n 'tw:flex tw:justify-center tw:origin-center',\n isFullscreen && 'tw:h-full tw:[&>svg]:h-full',\n )}\n style={{ transform: `translate(${translate.x}px, ${translate.y}px) scale(${scale})` }}\n dangerouslySetInnerHTML={{ __html: safeHtml }}\n />\n </div>\n <div\n role=\"presentation\"\n // `focus-within` as well as hover: the toolbar is opacity-0 but still in\n // the tab order, so without this a keyboard user tabs through invisible\n // controls with no visible focus ring.\n className=\"tw:absolute tw:right-1 tw:top-1 tw:flex tw:gap-1 tw:opacity-0 tw:transition-opacity tw:focus-within:opacity-100 tw:group-hover/zoom:opacity-100\"\n onClick={stopPropagation}\n >\n {isZoomed && (\n <Tooltip tooltip=\"Reset zoom\" placement=\"top\" triggerAsChild>\n <Button size=\"small\" variant=\"outline\" onClick={handleReset}>\n Reset\n </Button>\n </Tooltip>\n )}\n {copyText && (\n <ClipboardButton text={copyText} tooltip=\"Copy code\" size=\"icon-sm\" variant=\"outline\" />\n )}\n {renderActions?.(safeHtml)}\n <Tooltip\n tooltip={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}\n placement=\"top\"\n triggerAsChild\n >\n <Button\n size=\"icon-sm\"\n variant=\"outline\"\n aria-label={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}\n onClick={() => setIsFullscreen((f) => !f)}\n >\n {isFullscreen ? (\n <Minimize2 className=\"tw:size-4\" />\n ) : (\n <Maximize2 className=\"tw:size-4\" />\n )}\n </Button>\n </Tooltip>\n </div>\n </div>\n );\n\n if (isFullscreen) {\n return createPortal(\n <div\n role=\"presentation\"\n data-testid=\"zoomable-svg-fullscreen\"\n /**\n * Stacking contract for this overlay, which portals to `document.body`.\n *\n * - Sits at z-1051, the Modal/Sheet band: above page chrome.\n * - Stays *below* the floating-panel layer (z-1055: DropdownMenu,\n * Popover, Select, Combobox), which portals to `document.body` too —\n * an overlay above it hides any menu opened from the toolbar.\n * - `Tooltip` (z-1060) renders above, as it does over a Modal.\n * - `SpotlightBackdrop` (z-1056) dims this overlay rather than sitting\n * under it — by design, since it deliberately covers the portalled\n * surface tier so a tour's dim can't be punched through.\n * - An app may clamp poppers into this same band, making it a tie that\n * DOM order settles; Radix mounts its portal after this one.\n */\n className=\"tw:fixed tw:inset-0 tw:z-[1051] tw:bg-muted tw:p-4 tailwindcss-preflight\"\n onClick={stopPropagation}\n >\n {diagramContent}\n </div>,\n document.body,\n );\n }\n\n return (\n <div\n className={cn(\n 'tw:overflow-hidden tw:rounded-md tw:border tw:border-border tw:bg-muted',\n className,\n )}\n >\n {diagramContent}\n </div>\n );\n};\n","const PNG_SCALE = 2;\n\n// The root `<svg …>` tag, so the namespace check looks only at its attributes.\n// A plain `includes('xmlns=')` would also match a nested element or body text,\n// and would miss `xmlns = \"…\"` — adding a second declaration, which parsers\n// reject outright with \"Attribute xmlns redefined\".\nconst ROOT_SVG_TAG = /^<svg\\b[^>]*>/i;\nconst HAS_DEFAULT_NAMESPACE = /\\bxmlns\\s*=/i;\n\n// A standalone SVG file needs the namespace declaration; mermaid's inline output\n// omits it because an inline <svg> inherits it from the host document.\n// Trim before matching: the anchored `^<svg` misses markup that arrives with a\n// leading newline or indentation, which would emit a standalone file with no\n// namespace — unopenable in an image viewer.\nconst withSvgNamespace = (svg: string) => {\n const trimmed = svg.trim();\n const rootTag = trimmed.match(ROOT_SVG_TAG)?.[0];\n\n if (!rootTag || HAS_DEFAULT_NAMESPACE.test(rootTag)) return trimmed;\n\n return trimmed.replace(/^<svg\\b/i, '<svg xmlns=\"http://www.w3.org/2000/svg\"');\n};\n\nexport const toSvgFileContent = (svg: string) =>\n `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${withSvgNamespace(svg).trim()}\\n`;\n\n// A single decimal number: `12`, `12.5`, `.5`. Deliberately stricter than\n// `[\\d.]+`, which also matches `1.2.3` — and `parseFloat` truncates that to\n// `1.2` rather than rejecting it, so a malformed value would pass as a plausible\n// one.\nconst NUMBER = String.raw`\\d+(?:\\.\\d+)?|\\.\\d+`;\n\n// `parseFloat` happily reads a relative length as a number — `\"100%\"` becomes\n// `100`, `\"2em\"` becomes `2` — and `makeResponsive` sets `width=\"100%\"` on every\n// mermaid root, so an SVG with no usable viewBox would rasterize 100px wide with\n// no error. Accept only a unitless number or an explicit `px`.\nconst PIXEL_LENGTH = new RegExp(String.raw`^\\s*(?:${NUMBER})(?:px)?\\s*$`, 'i');\n\nconst parsePixelLength = (value: string | null): number | null => {\n if (!PIXEL_LENGTH.test(value ?? '')) return null;\n\n const parsed = Number.parseFloat(value ?? '');\n\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n};\n\nexport const parseSvgSize = (svg: string) => {\n const doc = new DOMParser().parseFromString(withSvgNamespace(svg), 'image/svg+xml');\n const element = doc.documentElement;\n\n const viewBox = element\n .getAttribute('viewBox')\n ?.split(/[\\s,]+/)\n .map(Number);\n // `> 0`, not truthiness: a negative extent is accepted by a truthy check, and\n // negative canvas dimensions silently fall back to the 300x150 default — an\n // export at the wrong size with no error. Falling through to width/height is\n // the better answer, since those are usually still valid.\n if (viewBox?.length === 4 && viewBox.every((value) => Number.isFinite(value))) {\n const [, , width, height] = viewBox;\n if (width !== undefined && height !== undefined && width > 0 && height > 0) {\n return { width, height };\n }\n }\n\n const width = parsePixelLength(element.getAttribute('width'));\n const height = parsePixelLength(element.getAttribute('height'));\n\n return width !== null && height !== null ? { width, height } : null;\n};\n\n// Resolve the themed page background so the exported PNG follows the active\n// brand and color scheme instead of a frozen literal. Falls back to `white`\n// (a CSS keyword, not a brand-locked hex) when the token is unset.\n//\n// The token holds Tailwind's bare channel triplet (\"249 250 251\") so utilities\n// can add an alpha. Canvas `fillStyle` rejects that form *silently* and keeps\n// its previous value (black), so wrap it back into rgb() before use.\nconst CHANNEL_TRIPLET = new RegExp(String.raw`^(?:${NUMBER})\\s+(?:${NUMBER})\\s+(?:${NUMBER})$`);\n\nexport const toCanvasColor = (token: string) => {\n const trimmed = token.trim();\n if (!trimmed) return 'white';\n\n // Only wrap a well-formed triplet. A malformed one (`1.2.3 4 5`) would produce\n // an invalid `rgb()` that `fillStyle` rejects silently, painting the PNG on\n // whatever colour was set before — passing it through unwrapped at least lets\n // a genuine CSS color value work.\n return CHANNEL_TRIPLET.test(trimmed) ? `rgb(${trimmed})` : trimmed;\n};\n\nconst resolveBackground = () =>\n toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue('--color-background'));\n\n/**\n * Rasterize SVG markup to a PNG blob at 2x for legible text.\n *\n * The SVG is loaded as a data URL rather than a blob URL: an <img> loading SVG\n * is treated as a foreign resource, so a blob URL would taint the canvas and\n * make toBlob throw a SecurityError. A background is painted first because a\n * transparent PNG reads as unusable when pasted into a slide deck.\n */\nexport const svgToPngBlob = async (svg: string, background?: string): Promise<Blob> => {\n const size = parseSvgSize(svg);\n if (!size) throw new Error('Cannot determine diagram dimensions.');\n\n const encoded = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(toSvgFileContent(svg))}`;\n\n const image = new Image();\n image.decoding = 'sync';\n await new Promise<void>((resolve, reject) => {\n image.onload = () => resolve();\n image.onerror = () => reject(new Error('Failed to load the diagram for export.'));\n image.src = encoded;\n });\n\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(size.width * PNG_SCALE);\n canvas.height = Math.round(size.height * PNG_SCALE);\n\n const context = canvas.getContext('2d');\n if (!context) throw new Error('Canvas is unavailable in this browser.');\n\n context.fillStyle = background ?? resolveBackground();\n context.fillRect(0, 0, canvas.width, canvas.height);\n context.drawImage(image, 0, 0, canvas.width, canvas.height);\n\n return new Promise<Blob>((resolve, reject) => {\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('Failed to encode the PNG.'))),\n 'image/png',\n );\n });\n};\n"],"mappings":";;;;;;;;;;AAWA,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,YAAY;AA4BlB,MAAa,eAAe,EAC1B,MACA,UACA,WACA,oBACA,oBACW;CACX,MAAM,WAAW,cAEb,UAAU,SAAS,MAAM;EACvB,cAAc;GAAE,KAAK;GAAM,YAAY;EAAK;EAC5C,GAAI,qBAAqB,EAAE,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;CAC9D,CAAC,GACH,CAAC,MAAM,kBAAkB,CAC3B;CAEA,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,CAAC,OAAO,YAAY,SAAS,CAAC;CACpC,MAAM,CAAC,WAAW,gBAAgB,SAAS;EAAE,GAAG;EAAG,GAAG;CAAE,CAAC;CACzD,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CAEtD,gBAAgB;EACd,IAA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S,SAAS,cAAc,QAAQ;CAC9C,OAAO,QAAQ,KAAK,MAAM,KAAK,QAAQ,SAAS;CAChD,OAAO,SAAS,KAAK,MAAM,KAAK,SAAS,SAAS;CAElD,MAAM,UAAU,OAAO,WAAW,IAAI;CACtC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,wCAAwC;CAEtE,QAAQ,YAAY,cAAc,kBAAkB;CACpD,QAAQ,SAAS,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;CAClD,QAAQ,UAAU,OAAO,GAAG,GAAG,OAAO,OAAO,OAAO,MAAM;CAE1D,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,OAAO,QACJ,SAAU,OAAO,QAAQ,IAAI,IAAI,uBAAO,IAAI,MAAM,2BAA2B,CAAC,GAC/E,WACF;CACF,CAAC;AACH"}
package/dist/editors.js CHANGED
@@ -2,10 +2,10 @@ import { cn } from "./classNames-BzrkDnOD.js";
2
2
  import { ChevronsLeft, ChevronsRight, X } from "./icons-Cek151jC.js";
3
3
  import { Button } from "./Button-DsRrU5F1.js";
4
4
  import { useStableCallback } from "./internal/hooks/useStableCallback.js";
5
- import { FieldItem, useFieldContext } from "./FieldItem-B7XMmZSz.js";
5
+ import { FieldItem, useFieldContext } from "./FieldItem-DtPTzNef.js";
6
6
  import { CHANGE_CLASS } from "./internal/components/MergeEditor/constants.js";
7
7
  import { resolveToken } from "./themeTokens-qP1-55O7.js";
8
- import { CodeEditor, LANGUAGE_MODES, buildBaseThemeStyles, buildBasicSetup, buildCanvasChrome, buildChromeStyles, buildCustomTheme, buildDiffWash, isLanguageMode, searchExtension, updateSearch, useThemedExtension, useTooltipsExtension, useVariableCompletion } from "./CodeEditor-C9zy7PxK.js";
8
+ import { CodeEditor, LANGUAGE_MODES, buildBaseThemeStyles, buildBasicSetup, buildCanvasChrome, buildChromeStyles, buildCustomTheme, buildDiffWash, isLanguageMode, searchExtension, updateSearch, useThemedExtension, useTooltipsExtension, useVariableCompletion } from "./CodeEditor-C9AS8Ch0.js";
9
9
  import { useCallback, useEffect, useMemo, useRef } from "react";
10
10
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
11
11
  import { Decoration, EditorView, GutterMarker, ViewPlugin, gutter, gutterLineClass } from "@codemirror/view";
package/dist/flint.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { DiagramSkeleton } from "./internal/blocks/DiagramShared/DiagramSkeleton.js";
2
- import { ZoomableSvg } from "./ZoomableSvg-pooPb1Cu.js";
2
+ import { DiagramSource } from "./DiagramSource-C5_d8Gdj.js";
3
+ import { ZoomableSvg } from "./ZoomableSvg-U_VH3QRO.js";
3
4
  import { useThemeAttributes } from "./themeTokens-qP1-55O7.js";
4
5
  import { SERIES_TOKENS, createVegaColorResolver, vegaRgb, vegaTheme } from "./vegaTheme-CSvFEMBl.js";
5
- import { DiagramSource, makeResponsive } from "./svgTransforms-C9njt92h.js";
6
+ import { makeResponsive } from "./svgTransforms-CJAYPk7o.js";
6
7
  import { useEffect, useState } from "react";
7
8
  import { jsx } from "react/jsx-runtime";
8
9
  //#region src/blocks/FlintChart/flintTheme.ts
package/dist/flint.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"flint.js","names":[],"sources":["../src/blocks/FlintChart/flintTheme.ts","../src/blocks/FlintChart/refuseUnsafeSpec.ts","../src/blocks/FlintChart/renderFlintSvg.ts","../src/blocks/FlintChart/FlintChart.tsx"],"sourcesContent":["import type { ChartAssemblyInput } from 'flint-chart';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createVegaColorResolver, SERIES_TOKENS, vegaRgb } from '../../vega/vegaTokens';\n\n/**\n * How the second palette tier (series 6-10) is derived from the core hues.\n *\n * - Each core hue is pushed *away* from its own surface, so the tier stays\n * in-family but reads as a distinct series: darkened on light, lightened on\n * dark. A single \"multiply the channels\" rule would darken in both, which on\n * a dark surface moves toward the backdrop — measured, that drops contrast\n * from ~6.7:1 to ~3.7:1, while lightening raises it to ~9:1.\n * - `amount` is the fraction of the distance travelled toward black (light) or\n * white (dark).\n */\nconst TIER_TWO_SHIFT = {\n light: { towards: 0, amount: 0.38 },\n dark: { towards: 255, amount: 0.35 },\n} as const;\n\n/**\n * Move an `rgb()` string's channels a fraction of the way toward `towards`\n * (0 = black, 255 = white). Returns the input unchanged if it is not that shape.\n */\nconst shiftChannels = (colour: string, towards: number, amount: number): string => {\n const channels = colour.match(/\\d+/g);\n if (!channels || channels.length < 3) return colour;\n const shifted = channels\n .slice(0, 3)\n .map((c) => Math.round(Number(c) + (towards - Number(c)) * amount));\n return vegaRgb(shifted.join(' '));\n};\n\n/**\n * Put the design system's categorical chart palette on a Flint input.\n *\n * Series colours are resolved by flint itself during assembly (they land in the\n * Vega-Lite `color` scale's `range`), so unlike the chrome in `vegaTheme` they\n * cannot be set through the compile `config` — they ride `theme_spec.ink.series`\n * on the input instead.\n *\n * `--chart-1..5` is the decorative palette the recharts wrappers in\n * `@keboola/design/charts` already use, so a Flint chart now matches the rest of\n * the platform's data-viz, follows the colour scheme, and re-skins with a brand\n * that overrides `colors.chart` / `colorsDark.chart`.\n *\n * An author-supplied `theme_spec` wins: a fence that names a Flint house (or its\n * own spec) asked for that look deliberately, so it is passed through untouched.\n *\n * `null` is not such a spec. The input is `JSON.parse`d model output, where\n * `\"theme_spec\": null` is valid JSON, and flint dereferences the value while\n * assembling (`reading 'extends'`) — so leaving it in place throws and the chart\n * falls back to raw source. It is replaced, exactly like a missing one.\n */\nexport const withFlintSeriesPalette = (\n input: ChartAssemblyInput,\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): ChartAssemblyInput => {\n if (input.theme_spec !== undefined && input.theme_spec !== null) return input;\n\n const token = createVegaColorResolver(scheme, from);\n const categorical = SERIES_TOKENS.map((name) => token(name));\n\n return {\n ...input,\n theme_spec: {\n ink: {\n // `endpointsAgainstSurface` below needs to know what the chart sits on.\n surface: { canvas: token('card') },\n // Flint's own defaults for these assume a light canvas — a title in near-black, axis\n // labels and gridlines just under it. On a dark surface that is a chart with no\n // readable numbers, so both groups come from the tokens like everything else.\n text: {\n primary: token('foreground'),\n secondary: token('muted-foreground'),\n muted: token('muted-foreground'),\n // Ink *on* a filled mark, which is the series colour — the canvas reads against it.\n inverse: token('card'),\n },\n structure: {\n axis: token('border'),\n grid: token('border'),\n frame: token('border'),\n rule: token('border'),\n },\n series: {\n categorical,\n // Past five series flint drops `categorical` wholesale for its own\n // `tableau10` — brand-blind and scheme-blind — so a six-region or\n // seven-month split would silently stop following the theme. The\n // extended set keeps those on our hues: a second tier shifted away\n // from the surface (darker on light, lighter on dark, per\n // `TIER_TWO_SHIFT`), distinct from the core five but the same family.\n categoricalExtended: [\n ...categorical,\n ...categorical.map((colour) =>\n shiftChannels(colour, TIER_TWO_SHIFT[scheme].towards, TIER_TWO_SHIFT[scheme].amount),\n ),\n ],\n // The tail past even the extended set.\n overflow: token('muted-foreground'),\n // A quantitative `color` field takes this ramp instead of the\n // categorical set. Without it flint synthesises `[black, series[0]]`,\n // which puts pure black at the low end in *both* schemes — invisible\n // cells on a dark surface.\n sequential: {\n stops: [token('accent'), token('chart-1')],\n space: 'lab',\n endpointsAgainstSurface: true,\n },\n },\n },\n },\n };\n};\n","/**\n * The boundary in front of the flint renderer: a spec is data, and nothing in it may fetch or run.\n *\n * - Checked on the **input**, before `assembleVegaLite` compiles it. The compiled Vega spec\n * carries `signals` and `expr` of vega's own making, so after compilation the model's keys and\n * the compiler's are no longer tellable apart.\n * - Refused on the **presence of a key**, never on a value looking remote: a relative `data.url`\n * is still a fetch nobody authorised, made by the reader's browser to a host the model chose.\n */\n\n/** Keys whose presence anywhere in a spec is refused: each fetches, evaluates or binds a signal. */\nconst REFUSED_KEYS = new Set(['url', 'expr', 'signal', 'signals', 'params']);\n\n/**\n * Suffix of Vega-Lite's other expression properties — `labelExpr`, `tickCountExpr`, …\n *\n * Matched by shape rather than enumerated, so a property added upstream is refused by default.\n */\nconst EXPRESSION_KEY_SUFFIX = /Expr$/;\n\n/**\n * An own property's value, or `undefined`.\n *\n * - A descriptor, so a prototype's key is not read: an inherited key is not one the model wrote.\n * - And so a getter is not *called* — the payload is model-written, and reading it must not run it.\n */\nconst ownValue = (node: unknown, key: string): unknown => {\n if (typeof node !== 'object' || node === null) return undefined;\n\n return Object.getOwnPropertyDescriptor(node, key)?.value;\n};\n\n/**\n * The chart's own rows, which the walk does not descend into — `spec.data.values`, and nowhere else.\n *\n * - Rows are data, never spec: vega reads a row's fields as datum values and evaluates none of\n * them, so a column named `url` is a column. Without this the guard refuses a chart of URLs.\n * - Flint takes exactly one dataset, at the top level (`ChartAssemblyInput['data']`), and an\n * array is what a dataset is (`data: { values: any[] }`). So this is the whole of a payload\n * that is data, and every other node is spec.\n * - The walk then skips it by **identity**. Skipping on the key name would leave `values` the\n * one word in the payload that hides a refused key, at any depth and under any parent —\n * including a nested object merely named `data`.\n */\nconst inlineRows = (spec: unknown): unknown[] | null => {\n const values = ownValue(ownValue(spec, 'data'), 'values');\n\n return Array.isArray(values) ? values : null;\n};\n\n/**\n * The top-level maps flint keys by **column name**, whose keys are therefore the model's data.\n *\n * - `semantic_types` and `field_display_names` are `Record<columnName, …>`\n * (`ChartAssemblyInput`), so a column named `url` puts `url` in a key position. Checking those\n * keys refuses \"Top landing pages by sessions\" — a chart with nothing remote in it.\n * - Only the keys are the column's. Each value is spec, and is walked like any other node.\n * - Matched by identity, for the reason `inlineRows` is: a nested object merely *named*\n * `semantic_types` is one flint never reads, so it buys no exemption.\n */\nconst COLUMN_KEYED_MAPS = ['semantic_types', 'field_display_names'];\n\nconst columnKeyedMaps = (spec: unknown): unknown[] =>\n COLUMN_KEYED_MAPS.map((key) => ownValue(spec, key)).filter(\n (map) => typeof map === 'object' && map !== null,\n );\n\n/**\n * Ceiling on the nodes the walk will visit.\n *\n * The payload is model-written, so its shape is not ours to assume. Exceeding this refuses rather\n * than passes: a spec the guard could not finish checking has not been checked.\n */\nconst MAX_SPEC_NODES = 10_000;\n\nconst TOO_LARGE = 'is too large to check';\n\n/**\n * Why this spec may not be rendered, or `null` if it may.\n *\n * - The reason reaches a console line, not a reader — the refusal itself surfaces as the source\n * fence `DiagramSource` already draws for a chart that would not render.\n * - Iterative, not recursive: a deeply nested payload must not land as a stack overflow.\n * - Nodes are charged on entering the stack, so the ceiling bounds the work, not the result.\n * - An accessor property is refused, not skipped: JSON carries none, so it is not a spec the\n * model wrote, and its value cannot be read without running it — leaving that subtree unchecked.\n */\nexport const findUnsafeSpecKey = (spec: unknown): string | null => {\n const rows = inlineRows(spec);\n const columnKeyed = columnKeyedMaps(spec);\n const stack: unknown[] = [spec];\n let visited = 1;\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n visited += node.length;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(...node);\n continue;\n }\n\n if (typeof node !== 'object' || node === null) continue;\n\n const keysAreColumnNames = columnKeyed.includes(node);\n\n // Descriptors, not `Object.entries` or `for…in`: an inherited key is not one the model wrote,\n // and reading an own one must not *call* anything.\n for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(node))) {\n if (!keysAreColumnNames && (REFUSED_KEYS.has(key) || EXPRESSION_KEY_SUFFIX.test(key))) {\n return `carries \\`${key}\\``;\n }\n if (!('value' in descriptor)) return `carries an accessor at \\`${key}\\``;\n\n const { value } = descriptor;\n if (rows !== null && value === rows) continue;\n\n visited += 1;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(value);\n }\n }\n\n return null;\n};\n","import type { ChartAssemblyInput } from 'flint-chart';\nimport type { assembleVegaLite } from 'flint-chart/vegalite';\nimport type * as vega from 'vega';\nimport type * as vegaLite from 'vega-lite';\nimport type { Config, TopLevelSpec } from 'vega-lite';\n\nimport { findUnsafeSpecKey } from './refuseUnsafeSpec';\n\n// The subset of the lazily imported modules the render pipeline needs. Kept as\n// a parameter (not module state) so the pipeline is unit-testable with a fake\n// runtime, without mocking dynamic imports.\nexport type FlintRuntime = {\n assembleVegaLite: typeof assembleVegaLite;\n vega: Pick<typeof vega, 'View' | 'parse'>;\n vegaLite: Pick<typeof vegaLite, 'compile'>;\n};\n\n/**\n * Compile a Flint `ChartAssemblyInput` to a static SVG string.\n *\n * - The input is refused before anything compiles it if it carries a key that would fetch or\n * evaluate — see `refuseUnsafeSpec.ts`. Every path to the renderer goes through here, so this\n * is the one place that check has to be.\n * - `assembleVegaLite` returns a Vega-Lite spec carrying `_`-prefixed internal\n * hint keys (`_width`, `_options`, `_transform`, …) that are not part of the\n * Vega-Lite schema — they are stripped before compiling.\n * - `config` (the scheme-following theme) rides the compile options; flint's\n * spec-side config sets no colours, so the two cannot conflict on merge.\n * - The Vega view renders headless (`renderer: 'none'`); nothing mounts to the\n * DOM, `toSVG()` is the only output.\n */\nexport const renderFlintSvg = async (\n runtime: FlintRuntime,\n input: ChartAssemblyInput,\n config: Config,\n): Promise<string> => {\n const unsafe = findUnsafeSpecKey(input);\n if (unsafe !== null) {\n throw new Error(`Refusing to render a flint spec that ${unsafe}`);\n }\n\n const assembled: Record<string, unknown> = runtime.assembleVegaLite(input);\n // `assembleVegaLite` is typed loosely upstream; once the hint keys are gone\n // the remainder is the Vega-Lite spec `compile` expects, which TypeScript\n // cannot see through the untyped boundary — hence the assertion.\n const vlSpec = Object.fromEntries(\n Object.entries(assembled).filter(([key]) => !key.startsWith('_')),\n ) as unknown as TopLevelSpec;\n const { spec } = runtime.vegaLite.compile(vlSpec, { config });\n const view = new runtime.vega.View(runtime.vega.parse(spec), { renderer: 'none' });\n try {\n await view.runAsync();\n return await view.toSVG();\n } finally {\n view.finalize();\n }\n};\n","import { useEffect, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChartAssemblyInput } from 'flint-chart';\n\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { vegaTheme } from '../../vega/vegaTheme';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport { makeResponsive } from '../DiagramShared/svgTransforms';\n\nimport { withFlintSeriesPalette } from './flintTheme';\nimport type { FlintRuntime } from './renderFlintSvg';\nimport { renderFlintSvg } from './renderFlintSvg';\n\nlet runtimePromise: Promise<FlintRuntime> | null = null;\n\n// One memoized promise for the heavy chart stack (flint-chart + vega +\n// vega-lite), reset on failure so a transient chunk-load error can retry on the\n// next render — mirrors `getMermaid()` in `MermaidDiagram`.\nconst getFlintRuntime = (): Promise<FlintRuntime> => {\n if (!runtimePromise) {\n runtimePromise = Promise.all([\n import('flint-chart/vegalite'),\n import('vega'),\n import('vega-lite'),\n ])\n .then(([flint, vega, vegaLite]) => ({\n assembleVegaLite: flint.assembleVegaLite,\n vega,\n vegaLite,\n }))\n .catch((err) => {\n runtimePromise = null;\n throw err;\n });\n }\n return runtimePromise;\n};\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// No prefix of a JSON document parses, so while a ```flint fence streams in the\n// source is unparseable in exactly the same way a broken one is. Unparseable\n// source is treated as still-streaming (skeleton stays up) until it has been\n// unchanged this long — only then is it shown as raw source.\nconst PARSE_GRACE_MS = 1500;\n\n// Ceiling on the fence source, in characters. `JSON.parse` plus vega's compile\n// and layout are synchronous, so an oversized payload — a model dumping a raw\n// table into the block — would block the main thread and freeze the chat. The\n// prompt caps inline data at ~50 rows; this sits far above a legitimate spec of\n// that size while still refusing anything pathological.\nconst MAX_SOURCE_CHARS = 200_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The chart chrome colours are baked into\n// the markup, so the key is the code *plus* the theme key (scheme + brand): the\n// same spec is a different SVG under a different colour scheme or brand.\n// Values are stored already `makeResponsive`d, so the string identity is stable\n// and ZoomableSvg's sanitize memo never re-runs for an unchanged chart.\n//\n// Bounded, and evicted oldest-first: a vega SVG is mark-per-datum, so entries run\n// to hundreds of KB, and a long chat visits many distinct charts. `Map` iterates\n// in insertion order, so the first key is the oldest.\nconst MAX_CACHED_CHARTS = 24;\nconst svgCache = new Map<string, string>();\n\nconst cacheSvg = (key: string, svg: string): void => {\n // Overwriting an existing key adds no entry, so it must not evict one — two\n // instances of the same chart both missing the cache and both writing would\n // otherwise cost an unrelated chart its slot.\n if (!svgCache.has(key) && svgCache.size >= MAX_CACHED_CHARTS) {\n const oldest = svgCache.keys().next();\n if (!oldest.done) svgCache.delete(oldest.value);\n }\n svgCache.set(key, svg);\n};\n\nconst chartCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// The theme half of a cache key — used to tell \"same theme, more source\" (a spec\n// still streaming) from a theme/brand switch, which must not keep a stale chart.\nconst prevThemeKeyOf = (key: string): string => key.slice(0, key.indexOf('\\n'));\n\ntype Props = {\n /** Raw source of a ```flint fence — a flint-chart `ChartAssemblyInput` as pure JSON\n * (`data.values` rows, optional `semantic_types`, and a `chart_spec` naming the\n * chartType and encodings). Rendered through the Vega-Lite backend. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const FlintChart = ({ code, renderActions }: Props) => {\n // Re-renders whenever the active colour scheme or brand changes, so the chart\n // chrome is re-rendered in the new palette instead of staying a light island\n // on a dark page — same contract as MermaidDiagram.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = chartCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() => svgCache.get(cacheKey) ?? null);\n const [renderFailed, setRenderFailed] = useState(false);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash.\n //\n // A cache hit is applied immediately. On a miss the previous SVG is dropped\n // unless *only* the tail of the source grew — i.e. the same spec still\n // streaming in, where holding the last good chart avoids a skeleton flicker\n // between chunks. Anything else (a different spec, or a new theme/brand) must\n // clear: the colours are baked into the markup, so keeping it would show a\n // light chart on a dark page, and keeping a chart for a spec that is no longer\n // on screen is simply wrong.\n const [prevKey, setPrevKey] = useState(cacheKey);\n const [prevCode, setPrevCode] = useState(code);\n if (cacheKey !== prevKey) {\n const cached = svgCache.get(cacheKey);\n const sameThemeStillStreaming =\n themeKey === prevThemeKeyOf(prevKey) && code.startsWith(prevCode);\n setPrevKey(cacheKey);\n setPrevCode(code);\n if (cached) setSvg(cached);\n else if (!sameThemeStillStreaming) setSvg(null);\n setRenderFailed(false);\n }\n\n useEffect(() => {\n if (svgCache.has(cacheKey)) return;\n\n let cancelled = false;\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n\n const debounceTimer = setTimeout(() => {\n if (code.length > MAX_SOURCE_CHARS) {\n // Not a streaming artifact — a fence this size never becomes renderable,\n // so fail straight to the source instead of waiting out the grace period.\n console.error(\n `[FlintChart] source exceeds ${MAX_SOURCE_CHARS} characters (${code.length}); not rendering`,\n );\n setSvg(null);\n setRenderFailed(true);\n return;\n }\n\n let input: ChartAssemblyInput;\n try {\n input = JSON.parse(code);\n } catch (err) {\n // Likely a fence still streaming — declare failure (and log the parse\n // error) only if the code is still unchanged when the grace period ends.\n graceTimer = setTimeout(() => {\n console.debug('[FlintChart] source never became parseable JSON:', err);\n setSvg(null);\n setRenderFailed(true);\n }, PARSE_GRACE_MS - RENDER_DEBOUNCE_MS);\n return;\n }\n\n getFlintRuntime()\n .then(async (runtime) => {\n if (cancelled) return;\n // Theme resolved at render time, off the live CSS variables — the\n // scheme comes out of the same read as the cache key, so the palette\n // can never be resolved under one scheme and cached under the other.\n const svgOutput = makeResponsive(\n await renderFlintSvg(\n runtime,\n withFlintSeriesPalette(input, scheme, scope),\n vegaTheme(scheme, scope),\n ),\n );\n if (cancelled) return;\n cacheSvg(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n })\n .catch((err) => {\n if (cancelled) return;\n console.error('[FlintChart] render failed:', err);\n setSvg(null);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n return () => {\n cancelled = true;\n clearTimeout(debounceTimer);\n if (graceTimer) clearTimeout(graceTimer);\n };\n }, [cacheKey, code, scheme, scope]);\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (svg) {\n return (\n <ZoomableSvg\n // Keyed by the rendered SVG, not the source: while the same fence is\n // still streaming the chart is deliberately held (see above), and keying\n // on `code` would remount it on every chunk — dropping the reader's\n // zoom/pan and re-running the DOMPurify pass over an identical chart.\n key={svg}\n html={svg}\n copyText={`\\`\\`\\`flint\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n renderActions={renderActions}\n />\n );\n }\n\n return <DiagramSkeleton />;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;CACrB,OAAO;EAAE,SAAS;EAAG,QAAQ;CAAK;CAClC,MAAM;EAAE,SAAS;EAAK,QAAQ;CAAK;AACrC;;;;;AAMA,MAAM,iBAAiB,QAAgB,SAAiB,WAA2B;CACjF,MAAM,WAAW,OAAO,MAAM,MAAM;CACpC,IAAI,CAAC,YAAY,SAAS,SAAS,GAAG,OAAO;CAC7C,MAAM,UAAU,SACb,MAAM,GAAG,CAAC,CAAC,CACX,KAAK,MAAM,KAAK,MAAM,OAAO,CAAC,KAAK,UAAU,OAAO,CAAC,KAAK,MAAM,CAAC;CACpE,OAAO,QAAQ,QAAQ,KAAK,GAAG,CAAC;AAClC;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,0BACX,OACA,QACA,SACuB;CACvB,IAAI,MAAM,eAAe,KAAA,KAAa,MAAM,eAAe,MAAM,OAAO;CAExE,MAAM,QAAQ,wBAAwB,QAAQ,IAAI;CAClD,MAAM,cAAc,cAAc,KAAK,SAAS,MAAM,IAAI,CAAC;CAE3D,OAAO;EACL,GAAG;EACH,YAAY,EACV,KA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;EAAU;EAAM;EAAQ;CAAK,CAAC;CAElC,IAAI,cACF,OAAO,oBAAC,eAAD,EAAqB,KAAO,CAAA;CAGrC,IAAI,KACF,OACE,oBAAC,aAAD;EAME,MAAM;EACN,UAAU,gBAAgB,KAAK;EAC/B,WAAU;EACK;CAChB,GALM,GAKN;CAIL,OAAO,oBAAC,iBAAD,CAAkB,CAAA;AAC3B"}
1
+ {"version":3,"file":"flint.js","names":[],"sources":["../src/blocks/FlintChart/flintTheme.ts","../src/blocks/FlintChart/refuseUnsafeSpec.ts","../src/blocks/FlintChart/renderFlintSvg.ts","../src/blocks/FlintChart/FlintChart.tsx"],"sourcesContent":["import type { ChartAssemblyInput } from 'flint-chart';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createVegaColorResolver, SERIES_TOKENS, vegaRgb } from '../../vega/vegaTokens';\n\n/**\n * How the second palette tier (series 6-10) is derived from the core hues.\n *\n * - Each core hue is pushed *away* from its own surface, so the tier stays\n * in-family but reads as a distinct series: darkened on light, lightened on\n * dark. A single \"multiply the channels\" rule would darken in both, which on\n * a dark surface moves toward the backdrop — measured, that drops contrast\n * from ~6.7:1 to ~3.7:1, while lightening raises it to ~9:1.\n * - `amount` is the fraction of the distance travelled toward black (light) or\n * white (dark).\n */\nconst TIER_TWO_SHIFT = {\n light: { towards: 0, amount: 0.38 },\n dark: { towards: 255, amount: 0.35 },\n} as const;\n\n/**\n * Move an `rgb()` string's channels a fraction of the way toward `towards`\n * (0 = black, 255 = white). Returns the input unchanged if it is not that shape.\n */\nconst shiftChannels = (colour: string, towards: number, amount: number): string => {\n const channels = colour.match(/\\d+/g);\n if (!channels || channels.length < 3) return colour;\n const shifted = channels\n .slice(0, 3)\n .map((c) => Math.round(Number(c) + (towards - Number(c)) * amount));\n return vegaRgb(shifted.join(' '));\n};\n\n/**\n * Put the design system's categorical chart palette on a Flint input.\n *\n * Series colours are resolved by flint itself during assembly (they land in the\n * Vega-Lite `color` scale's `range`), so unlike the chrome in `vegaTheme` they\n * cannot be set through the compile `config` — they ride `theme_spec.ink.series`\n * on the input instead.\n *\n * `--chart-1..5` is the decorative palette the recharts wrappers in\n * `@keboola/design/charts` already use, so a Flint chart now matches the rest of\n * the platform's data-viz, follows the colour scheme, and re-skins with a brand\n * that overrides `colors.chart` / `colorsDark.chart`.\n *\n * An author-supplied `theme_spec` wins: a fence that names a Flint house (or its\n * own spec) asked for that look deliberately, so it is passed through untouched.\n *\n * `null` is not such a spec. The input is `JSON.parse`d model output, where\n * `\"theme_spec\": null` is valid JSON, and flint dereferences the value while\n * assembling (`reading 'extends'`) — so leaving it in place throws and the chart\n * falls back to raw source. It is replaced, exactly like a missing one.\n */\nexport const withFlintSeriesPalette = (\n input: ChartAssemblyInput,\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): ChartAssemblyInput => {\n if (input.theme_spec !== undefined && input.theme_spec !== null) return input;\n\n const token = createVegaColorResolver(scheme, from);\n const categorical = SERIES_TOKENS.map((name) => token(name));\n\n return {\n ...input,\n theme_spec: {\n ink: {\n // `endpointsAgainstSurface` below needs to know what the chart sits on.\n surface: { canvas: token('card') },\n // Flint's own defaults for these assume a light canvas — a title in near-black, axis\n // labels and gridlines just under it. On a dark surface that is a chart with no\n // readable numbers, so both groups come from the tokens like everything else.\n text: {\n primary: token('foreground'),\n secondary: token('muted-foreground'),\n muted: token('muted-foreground'),\n // Ink *on* a filled mark, which is the series colour — the canvas reads against it.\n inverse: token('card'),\n },\n structure: {\n axis: token('border'),\n grid: token('border'),\n frame: token('border'),\n rule: token('border'),\n },\n series: {\n categorical,\n // Past five series flint drops `categorical` wholesale for its own\n // `tableau10` — brand-blind and scheme-blind — so a six-region or\n // seven-month split would silently stop following the theme. The\n // extended set keeps those on our hues: a second tier shifted away\n // from the surface (darker on light, lighter on dark, per\n // `TIER_TWO_SHIFT`), distinct from the core five but the same family.\n categoricalExtended: [\n ...categorical,\n ...categorical.map((colour) =>\n shiftChannels(colour, TIER_TWO_SHIFT[scheme].towards, TIER_TWO_SHIFT[scheme].amount),\n ),\n ],\n // The tail past even the extended set.\n overflow: token('muted-foreground'),\n // A quantitative `color` field takes this ramp instead of the\n // categorical set. Without it flint synthesises `[black, series[0]]`,\n // which puts pure black at the low end in *both* schemes — invisible\n // cells on a dark surface.\n sequential: {\n stops: [token('accent'), token('chart-1')],\n space: 'lab',\n endpointsAgainstSurface: true,\n },\n },\n },\n },\n };\n};\n","/**\n * The boundary in front of the flint renderer: a spec is data, and nothing in it may fetch or run.\n *\n * - Checked on the **input**, before `assembleVegaLite` compiles it. The compiled Vega spec\n * carries `signals` and `expr` of vega's own making, so after compilation the model's keys and\n * the compiler's are no longer tellable apart.\n * - Refused on the **presence of a key**, never on a value looking remote: a relative `data.url`\n * is still a fetch nobody authorised, made by the reader's browser to a host the model chose.\n */\n\n/** Keys whose presence anywhere in a spec is refused: each fetches, evaluates or binds a signal. */\nconst REFUSED_KEYS = new Set(['url', 'expr', 'signal', 'signals', 'params']);\n\n/**\n * Suffix of Vega-Lite's other expression properties — `labelExpr`, `tickCountExpr`, …\n *\n * Matched by shape rather than enumerated, so a property added upstream is refused by default.\n */\nconst EXPRESSION_KEY_SUFFIX = /Expr$/;\n\n/**\n * An own property's value, or `undefined`.\n *\n * - A descriptor, so a prototype's key is not read: an inherited key is not one the model wrote.\n * - And so a getter is not *called* — the payload is model-written, and reading it must not run it.\n */\nconst ownValue = (node: unknown, key: string): unknown => {\n if (typeof node !== 'object' || node === null) return undefined;\n\n return Object.getOwnPropertyDescriptor(node, key)?.value;\n};\n\n/**\n * The chart's own rows, which the walk does not descend into — `spec.data.values`, and nowhere else.\n *\n * - Rows are data, never spec: vega reads a row's fields as datum values and evaluates none of\n * them, so a column named `url` is a column. Without this the guard refuses a chart of URLs.\n * - Flint takes exactly one dataset, at the top level (`ChartAssemblyInput['data']`), and an\n * array is what a dataset is (`data: { values: any[] }`). So this is the whole of a payload\n * that is data, and every other node is spec.\n * - The walk then skips it by **identity**. Skipping on the key name would leave `values` the\n * one word in the payload that hides a refused key, at any depth and under any parent —\n * including a nested object merely named `data`.\n */\nconst inlineRows = (spec: unknown): unknown[] | null => {\n const values = ownValue(ownValue(spec, 'data'), 'values');\n\n return Array.isArray(values) ? values : null;\n};\n\n/**\n * The top-level maps flint keys by **column name**, whose keys are therefore the model's data.\n *\n * - `semantic_types` and `field_display_names` are `Record<columnName, …>`\n * (`ChartAssemblyInput`), so a column named `url` puts `url` in a key position. Checking those\n * keys refuses \"Top landing pages by sessions\" — a chart with nothing remote in it.\n * - Only the keys are the column's. Each value is spec, and is walked like any other node.\n * - Matched by identity, for the reason `inlineRows` is: a nested object merely *named*\n * `semantic_types` is one flint never reads, so it buys no exemption.\n */\nconst COLUMN_KEYED_MAPS = ['semantic_types', 'field_display_names'];\n\nconst columnKeyedMaps = (spec: unknown): unknown[] =>\n COLUMN_KEYED_MAPS.map((key) => ownValue(spec, key)).filter(\n (map) => typeof map === 'object' && map !== null,\n );\n\n/**\n * Ceiling on the nodes the walk will visit.\n *\n * The payload is model-written, so its shape is not ours to assume. Exceeding this refuses rather\n * than passes: a spec the guard could not finish checking has not been checked.\n */\nconst MAX_SPEC_NODES = 10_000;\n\nconst TOO_LARGE = 'is too large to check';\n\n/**\n * Why this spec may not be rendered, or `null` if it may.\n *\n * - The reason reaches a console line, not a reader — the refusal itself surfaces as the source\n * fence `DiagramSource` already draws for a chart that would not render.\n * - Iterative, not recursive: a deeply nested payload must not land as a stack overflow.\n * - Nodes are charged on entering the stack, so the ceiling bounds the work, not the result.\n * - An accessor property is refused, not skipped: JSON carries none, so it is not a spec the\n * model wrote, and its value cannot be read without running it — leaving that subtree unchecked.\n */\nexport const findUnsafeSpecKey = (spec: unknown): string | null => {\n const rows = inlineRows(spec);\n const columnKeyed = columnKeyedMaps(spec);\n const stack: unknown[] = [spec];\n let visited = 1;\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n visited += node.length;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(...node);\n continue;\n }\n\n if (typeof node !== 'object' || node === null) continue;\n\n const keysAreColumnNames = columnKeyed.includes(node);\n\n // Descriptors, not `Object.entries` or `for…in`: an inherited key is not one the model wrote,\n // and reading an own one must not *call* anything.\n for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(node))) {\n if (!keysAreColumnNames && (REFUSED_KEYS.has(key) || EXPRESSION_KEY_SUFFIX.test(key))) {\n return `carries \\`${key}\\``;\n }\n if (!('value' in descriptor)) return `carries an accessor at \\`${key}\\``;\n\n const { value } = descriptor;\n if (rows !== null && value === rows) continue;\n\n visited += 1;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(value);\n }\n }\n\n return null;\n};\n","import type { ChartAssemblyInput } from 'flint-chart';\nimport type { assembleVegaLite } from 'flint-chart/vegalite';\nimport type * as vega from 'vega';\nimport type * as vegaLite from 'vega-lite';\nimport type { Config, TopLevelSpec } from 'vega-lite';\n\nimport { findUnsafeSpecKey } from './refuseUnsafeSpec';\n\n// The subset of the lazily imported modules the render pipeline needs. Kept as\n// a parameter (not module state) so the pipeline is unit-testable with a fake\n// runtime, without mocking dynamic imports.\nexport type FlintRuntime = {\n assembleVegaLite: typeof assembleVegaLite;\n vega: Pick<typeof vega, 'View' | 'parse'>;\n vegaLite: Pick<typeof vegaLite, 'compile'>;\n};\n\n/**\n * Compile a Flint `ChartAssemblyInput` to a static SVG string.\n *\n * - The input is refused before anything compiles it if it carries a key that would fetch or\n * evaluate — see `refuseUnsafeSpec.ts`. Every path to the renderer goes through here, so this\n * is the one place that check has to be.\n * - `assembleVegaLite` returns a Vega-Lite spec carrying `_`-prefixed internal\n * hint keys (`_width`, `_options`, `_transform`, …) that are not part of the\n * Vega-Lite schema — they are stripped before compiling.\n * - `config` (the scheme-following theme) rides the compile options; flint's\n * spec-side config sets no colours, so the two cannot conflict on merge.\n * - The Vega view renders headless (`renderer: 'none'`); nothing mounts to the\n * DOM, `toSVG()` is the only output.\n */\nexport const renderFlintSvg = async (\n runtime: FlintRuntime,\n input: ChartAssemblyInput,\n config: Config,\n): Promise<string> => {\n const unsafe = findUnsafeSpecKey(input);\n if (unsafe !== null) {\n throw new Error(`Refusing to render a flint spec that ${unsafe}`);\n }\n\n const assembled: Record<string, unknown> = runtime.assembleVegaLite(input);\n // `assembleVegaLite` is typed loosely upstream; once the hint keys are gone\n // the remainder is the Vega-Lite spec `compile` expects, which TypeScript\n // cannot see through the untyped boundary — hence the assertion.\n const vlSpec = Object.fromEntries(\n Object.entries(assembled).filter(([key]) => !key.startsWith('_')),\n ) as unknown as TopLevelSpec;\n const { spec } = runtime.vegaLite.compile(vlSpec, { config });\n const view = new runtime.vega.View(runtime.vega.parse(spec), { renderer: 'none' });\n try {\n await view.runAsync();\n return await view.toSVG();\n } finally {\n view.finalize();\n }\n};\n","import { useEffect, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChartAssemblyInput } from 'flint-chart';\n\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { vegaTheme } from '../../vega/vegaTheme';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport { makeResponsive } from '../DiagramShared/svgTransforms';\n\nimport { withFlintSeriesPalette } from './flintTheme';\nimport type { FlintRuntime } from './renderFlintSvg';\nimport { renderFlintSvg } from './renderFlintSvg';\n\nlet runtimePromise: Promise<FlintRuntime> | null = null;\n\n// One memoized promise for the heavy chart stack (flint-chart + vega +\n// vega-lite), reset on failure so a transient chunk-load error can retry on the\n// next render — mirrors `getMermaid()` in `MermaidDiagram`.\nconst getFlintRuntime = (): Promise<FlintRuntime> => {\n if (!runtimePromise) {\n runtimePromise = Promise.all([\n import('flint-chart/vegalite'),\n import('vega'),\n import('vega-lite'),\n ])\n .then(([flint, vega, vegaLite]) => ({\n assembleVegaLite: flint.assembleVegaLite,\n vega,\n vegaLite,\n }))\n .catch((err) => {\n runtimePromise = null;\n throw err;\n });\n }\n return runtimePromise;\n};\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// No prefix of a JSON document parses, so while a ```flint fence streams in the\n// source is unparseable in exactly the same way a broken one is. Unparseable\n// source is treated as still-streaming (skeleton stays up) until it has been\n// unchanged this long — only then is it shown as raw source.\nconst PARSE_GRACE_MS = 1500;\n\n// Ceiling on the fence source, in characters. `JSON.parse` plus vega's compile\n// and layout are synchronous, so an oversized payload — a model dumping a raw\n// table into the block — would block the main thread and freeze the chat. The\n// prompt caps inline data at ~50 rows; this sits far above a legitimate spec of\n// that size while still refusing anything pathological.\nconst MAX_SOURCE_CHARS = 200_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The chart chrome colours are baked into\n// the markup, so the key is the code *plus* the theme key (scheme + brand): the\n// same spec is a different SVG under a different colour scheme or brand.\n// Values are stored already `makeResponsive`d, so the string identity is stable\n// and ZoomableSvg's sanitize memo never re-runs for an unchanged chart.\n//\n// Bounded, and evicted oldest-first: a vega SVG is mark-per-datum, so entries run\n// to hundreds of KB, and a long chat visits many distinct charts. `Map` iterates\n// in insertion order, so the first key is the oldest.\nconst MAX_CACHED_CHARTS = 24;\nconst svgCache = new Map<string, string>();\n\nconst cacheSvg = (key: string, svg: string): void => {\n // Overwriting an existing key adds no entry, so it must not evict one — two\n // instances of the same chart both missing the cache and both writing would\n // otherwise cost an unrelated chart its slot.\n if (!svgCache.has(key) && svgCache.size >= MAX_CACHED_CHARTS) {\n const oldest = svgCache.keys().next();\n if (!oldest.done) svgCache.delete(oldest.value);\n }\n svgCache.set(key, svg);\n};\n\nconst chartCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// The theme half of a cache key — used to tell \"same theme, more source\" (a spec\n// still streaming) from a theme/brand switch, which must not keep a stale chart.\nconst prevThemeKeyOf = (key: string): string => key.slice(0, key.indexOf('\\n'));\n\ntype Props = {\n /** Raw source of a ```flint fence — a flint-chart `ChartAssemblyInput` as pure JSON\n * (`data.values` rows, optional `semantic_types`, and a `chart_spec` naming the\n * chartType and encodings). Rendered through the Vega-Lite backend. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const FlintChart = ({ code, renderActions }: Props) => {\n // Re-renders whenever the active colour scheme or brand changes, so the chart\n // chrome is re-rendered in the new palette instead of staying a light island\n // on a dark page — same contract as MermaidDiagram.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = chartCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() => svgCache.get(cacheKey) ?? null);\n const [renderFailed, setRenderFailed] = useState(false);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash.\n //\n // A cache hit is applied immediately. On a miss the previous SVG is dropped\n // unless *only* the tail of the source grew — i.e. the same spec still\n // streaming in, where holding the last good chart avoids a skeleton flicker\n // between chunks. Anything else (a different spec, or a new theme/brand) must\n // clear: the colours are baked into the markup, so keeping it would show a\n // light chart on a dark page, and keeping a chart for a spec that is no longer\n // on screen is simply wrong.\n const [prevKey, setPrevKey] = useState(cacheKey);\n const [prevCode, setPrevCode] = useState(code);\n if (cacheKey !== prevKey) {\n const cached = svgCache.get(cacheKey);\n const sameThemeStillStreaming =\n themeKey === prevThemeKeyOf(prevKey) && code.startsWith(prevCode);\n setPrevKey(cacheKey);\n setPrevCode(code);\n if (cached) setSvg(cached);\n else if (!sameThemeStillStreaming) setSvg(null);\n setRenderFailed(false);\n }\n\n useEffect(() => {\n if (svgCache.has(cacheKey)) return;\n\n let cancelled = false;\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n\n const debounceTimer = setTimeout(() => {\n if (code.length > MAX_SOURCE_CHARS) {\n // Not a streaming artifact — a fence this size never becomes renderable,\n // so fail straight to the source instead of waiting out the grace period.\n console.error(\n `[FlintChart] source exceeds ${MAX_SOURCE_CHARS} characters (${code.length}); not rendering`,\n );\n setSvg(null);\n setRenderFailed(true);\n return;\n }\n\n let input: ChartAssemblyInput;\n try {\n input = JSON.parse(code);\n } catch (err) {\n // Likely a fence still streaming — declare failure (and log the parse\n // error) only if the code is still unchanged when the grace period ends.\n graceTimer = setTimeout(() => {\n console.debug('[FlintChart] source never became parseable JSON:', err);\n setSvg(null);\n setRenderFailed(true);\n }, PARSE_GRACE_MS - RENDER_DEBOUNCE_MS);\n return;\n }\n\n getFlintRuntime()\n .then(async (runtime) => {\n if (cancelled) return;\n // Theme resolved at render time, off the live CSS variables — the\n // scheme comes out of the same read as the cache key, so the palette\n // can never be resolved under one scheme and cached under the other.\n const svgOutput = makeResponsive(\n await renderFlintSvg(\n runtime,\n withFlintSeriesPalette(input, scheme, scope),\n vegaTheme(scheme, scope),\n ),\n );\n if (cancelled) return;\n cacheSvg(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n })\n .catch((err) => {\n if (cancelled) return;\n console.error('[FlintChart] render failed:', err);\n setSvg(null);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n return () => {\n cancelled = true;\n clearTimeout(debounceTimer);\n if (graceTimer) clearTimeout(graceTimer);\n };\n }, [cacheKey, code, scheme, scope]);\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (svg) {\n return (\n <ZoomableSvg\n // Keyed by the rendered SVG, not the source: while the same fence is\n // still streaming the chart is deliberately held (see above), and keying\n // on `code` would remount it on every chunk — dropping the reader's\n // zoom/pan and re-running the DOMPurify pass over an identical chart.\n key={svg}\n html={svg}\n copyText={`\\`\\`\\`flint\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n renderActions={renderActions}\n />\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