markdown-flow-ui 0.2.32 → 0.2.34
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.
- package/README.md +9 -0
- package/dist/_virtual/index.es10.js +3 -2
- package/dist/_virtual/index.es10.js.map +1 -1
- package/dist/_virtual/index.es11.js +2 -3
- package/dist/_virtual/index.es11.js.map +1 -1
- package/dist/_virtual/index.es3.js +4 -5
- package/dist/_virtual/index.es3.js.map +1 -1
- package/dist/_virtual/index.es4.js +5 -4
- package/dist/_virtual/index.es4.js.map +1 -1
- package/dist/_virtual/index.es7.js +2 -5
- package/dist/_virtual/index.es7.js.map +1 -1
- package/dist/_virtual/index.es8.js +5 -2
- package/dist/_virtual/index.es8.js.map +1 -1
- package/dist/_virtual/index.es9.js +2 -2
- package/dist/_virtual/index10.cjs +1 -1
- package/dist/_virtual/index11.cjs +1 -1
- package/dist/_virtual/index3.cjs +1 -1
- package/dist/_virtual/index4.cjs +1 -1
- package/dist/_virtual/index7.cjs +1 -1
- package/dist/_virtual/index8.cjs +1 -1
- package/dist/_virtual/index9.cjs +1 -1
- package/dist/components/ContentRender/IframeSandbox.cjs +4 -4
- package/dist/components/ContentRender/IframeSandbox.cjs.map +1 -1
- package/dist/components/ContentRender/IframeSandbox.es.js +299 -282
- package/dist/components/ContentRender/IframeSandbox.es.js.map +1 -1
- package/dist/components/ui/inputGroup/textarea.cjs +1 -1
- package/dist/components/ui/inputGroup/textarea.es.js +1 -1
- package/dist/lib/interaction-defaults.cjs +1 -1
- package/dist/lib/interaction-defaults.cjs.map +1 -1
- package/dist/lib/interaction-defaults.es.js +1 -1
- package/dist/lib/interaction-defaults.es.js.map +1 -1
- package/dist/node_modules/@braintree/sanitize-url/dist/index.cjs +1 -1
- package/dist/node_modules/@braintree/sanitize-url/dist/index.es.js +1 -1
- package/dist/node_modules/classnames/index.cjs +1 -1
- package/dist/node_modules/classnames/index.es.js +1 -1
- package/dist/node_modules/hast-util-to-jsx-runtime/lib/index.cjs +1 -1
- package/dist/node_modules/hast-util-to-jsx-runtime/lib/index.es.js +1 -1
- package/dist/node_modules/rc-input/es/BaseInput.cjs +1 -1
- package/dist/node_modules/rc-input/es/BaseInput.es.js +1 -1
- package/dist/node_modules/rc-textarea/es/ResizableTextArea.cjs +1 -1
- package/dist/node_modules/rc-textarea/es/ResizableTextArea.es.js +1 -1
- package/dist/node_modules/rc-textarea/es/TextArea.cjs +1 -1
- package/dist/node_modules/rc-textarea/es/TextArea.es.js +1 -1
- package/dist/node_modules/rc-textarea/es/index.cjs +1 -1
- package/dist/node_modules/rc-textarea/es/index.es.js +1 -1
- package/dist/node_modules/rc-util/es/ref.cjs +1 -1
- package/dist/node_modules/rc-util/es/ref.es.js +1 -1
- package/dist/node_modules/remark-flow/dist/interaction-plugin-core.cjs +1 -1
- package/dist/node_modules/remark-flow/dist/interaction-plugin-core.es.js +1 -1
- package/dist/node_modules/style-to-object/cjs/index.cjs +1 -1
- package/dist/node_modules/style-to-object/cjs/index.es.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IframeSandbox.es.js","sources":["../../../src/components/ContentRender/IframeSandbox.tsx"],"sourcesContent":["import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport SandboxApp from \"./SandboxApp\";\nimport ContentRender from \"./ContentRender\";\nimport {\n EMPTY_ROOT_HEIGHT_META,\n inspectViewportHeightFromHtmlRootString,\n inspectViewportHeightFromNodeChain,\n parseExplicitHeight,\n resolveExplicitHeightFromNodeChain,\n} from \"./utils/iframe-viewport-height\";\nimport {\n SANDBOX_INTERACTION_MESSAGE_SOURCE,\n SANDBOX_INTERACTION_MESSAGE_TYPE,\n} from \"../../lib/sandboxInteraction\";\nimport {\n injectScalingSystem,\n type ScalingWindow,\n} from \"./utils/iframe-scaling\";\nimport {\n getMarkdownFlowDirection,\n getMarkdownFlowLanguage,\n type MarkdownFlowLocale,\n} from \"../../lib/locale\";\nimport { useDetachedLanguage } from \"../../lib/useDetachedLanguage\";\nimport { useResolvedDirection } from \"../../lib/useResolvedDirection\";\nimport { getContentRenderLocaleTexts } from \"./contentRenderI18n\";\nimport { CJK_SAFE_SANS_FONT_FAMILY } from \"./cjkFontFamily\";\n\ntype BlackboardVendorModule = typeof import(\"./blackboard-vendor\");\n\n// Cache the sandbox vendor loader so every iframe reuses the same preload request.\nlet blackboardVendorPromise: Promise<BlackboardVendorModule> | null = null;\n\nconst loadBlackboardVendor = () => {\n if (!blackboardVendorPromise) {\n blackboardVendorPromise = import(\"./blackboard-vendor\");\n }\n\n return blackboardVendorPromise;\n};\n\nconst COMPLETE_IMAGE_TAG_PATTERN = /<img\\b[^>]*>/i;\nconst POST_IMAGE_STREAM_DEBOUNCE_MS = 180;\nconst SANDBOX_INTERACTION_THROTTLE_MS = 240;\n\nexport interface IframeSandboxProps {\n content: string;\n className?: string;\n locale?: MarkdownFlowLocale;\n /** Overrides the locale-derived language without changing authored HTML language. */\n lang?: string;\n /** Overrides locale-derived direction without replacing authored HTML direction. */\n dir?: React.HTMLAttributes<HTMLDivElement>[\"dir\"];\n loadingText?: string;\n styleLoadingText?: string;\n scriptLoadingText?: string;\n fullScreenButtonText?: string;\n exitFullScreenButtonText?: string;\n hideFullScreen?: boolean;\n mode?: \"content\" | \"blackboard\";\n type: \"sandbox\" | \"markdown\";\n replaceRootScreenHeightWithFull?: boolean;\n enableScaling?: boolean;\n disableLoadingOverlay?: boolean;\n}\n\nconst replaceRootScreenHeightToken = (className: string) =>\n className\n .split(/\\s+/)\n .filter(Boolean)\n .map((token) => {\n const segments = token.split(\":\");\n if (\n segments[segments.length - 1] !== \"h-screen\" &&\n segments[segments.length - 1] !== \"min-h-screen\"\n ) {\n return token;\n }\n segments[segments.length - 1] = \"h-full\";\n return segments.join(\":\");\n })\n .join(\" \");\n\nconst replaceRootScreenHeightWithFullClass = (\n html: string,\n enabled: boolean\n) => {\n if (!enabled || !html.trim()) {\n return html;\n }\n\n return html.replace(\n /^(\\s*<[a-zA-Z][\\w:-]*)(\\s[^>]*?)?>/,\n (match, tagStart: string, attrs = \"\") => {\n const classMatch = attrs.match(/\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/i);\n\n if (!classMatch) {\n return match;\n }\n\n const nextClassName = replaceRootScreenHeightToken(classMatch[2]);\n\n if (nextClassName === classMatch[2]) {\n return match;\n }\n\n return `${tagStart}${attrs.replace(\n classMatch[0],\n `class=${classMatch[1]}${nextClassName}${classMatch[1]}`\n )}>`;\n }\n );\n};\n\nconst IframeSandboxInstance: React.FC<IframeSandboxProps> = ({\n content,\n type,\n className,\n locale,\n lang,\n dir,\n loadingText,\n styleLoadingText,\n scriptLoadingText,\n fullScreenButtonText,\n exitFullScreenButtonText,\n hideFullScreen = false,\n mode = \"content\",\n replaceRootScreenHeightWithFull = false,\n enableScaling = false,\n disableLoadingOverlay = false,\n}) => {\n const localeTexts = getContentRenderLocaleTexts(locale);\n const direction = dir ?? getMarkdownFlowDirection(locale);\n const language = lang ?? getMarkdownFlowLanguage(locale);\n const resolvedFullScreenButtonText =\n fullScreenButtonText || localeTexts.sandboxFullscreenButtonText;\n const resolvedExitFullScreenButtonText =\n exitFullScreenButtonText || localeTexts.sandboxExitFullscreenButtonText;\n const containerRef = useRef<HTMLDivElement>(null);\n const sandboxLanguage = useDetachedLanguage(containerRef, language);\n const { resolvedDirection } = useResolvedDirection(containerRef, direction);\n const markdownContainerRef = useRef<HTMLDivElement>(null);\n const markdownContentRef = useRef<HTMLElement>(null);\n const setMarkdownContentContainerRef = useCallback(\n (node: HTMLDivElement | null) => {\n markdownContainerRef.current = node;\n markdownContentRef.current =\n node?.querySelector<HTMLElement>(\".content-render\") ?? null;\n },\n []\n );\n const { resolvedDirection: markdownContentDirection } = useResolvedDirection(\n markdownContentRef,\n direction\n );\n const sandboxDirection = direction ?? resolvedDirection;\n const requestedDirectionRef = useRef(direction);\n requestedDirectionRef.current = direction;\n // Auto direction cannot inspect text across the iframe document boundary.\n // Mirror the rendered sandbox direction to host controls instead.\n const [sandboxContentDirection, setSandboxContentDirection] = useState<\n \"ltr\" | \"rtl\"\n >();\n let fullscreenControlDirection: \"ltr\" | \"rtl\" | undefined;\n if (direction === \"auto\") {\n fullscreenControlDirection = resolvedDirection;\n if (type === \"sandbox\") {\n fullscreenControlDirection = sandboxContentDirection ?? resolvedDirection;\n } else if (mode === \"blackboard\") {\n fullscreenControlDirection = markdownContentDirection;\n }\n }\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const rootRef = useRef<Root | null>(null);\n const updateHeightRef = useRef<() => void>(() => {});\n const [height, setHeight] = useState(480);\n const [contentHeight, setContentHeight] = useState(0);\n const [containerWidth, setContainerWidth] = useState(0);\n const isMeasuringContentRef = useRef(false);\n const pendingHeightUpdateRef = useRef(false);\n const lastSandboxInteractionTimeRef = useRef(0);\n const [resetToken, setResetToken] = useState(0);\n const [isFullscreen, setIsFullscreen] = useState(false);\n const shouldInjectSandboxVendor = type === \"sandbox\";\n\n const isBlackboardMode = mode === \"blackboard\";\n const shouldEnableScaling =\n enableScaling && isBlackboardMode && type === \"sandbox\";\n const shouldMeasureDynamicHeight = isBlackboardMode && type === \"sandbox\";\n const shouldProcessRootScreenHeight =\n shouldMeasureDynamicHeight && replaceRootScreenHeightWithFull;\n const prevHtmlRef = useRef<string>(\"\");\n const htmlContent = React.useMemo(\n () => (type === \"sandbox\" ? content : \"\"),\n [content, type]\n );\n const normalizedHtmlContent = React.useMemo(\n () =>\n replaceRootScreenHeightWithFullClass(\n htmlContent,\n shouldProcessRootScreenHeight\n ),\n [htmlContent, shouldProcessRootScreenHeight]\n );\n const originalRootHeightMeta = React.useMemo(\n () =>\n shouldProcessRootScreenHeight\n ? inspectViewportHeightFromHtmlRootString(htmlContent)\n : EMPTY_ROOT_HEIGHT_META,\n [htmlContent, shouldProcessRootScreenHeight]\n );\n const shouldStretchRootHeight = React.useMemo(\n () =>\n shouldProcessRootScreenHeight &&\n originalRootHeightMeta.hasFullViewportHeight,\n [\n originalRootHeightMeta.hasFullViewportHeight,\n shouldProcessRootScreenHeight,\n ]\n );\n const [renderHtmlContent, setRenderHtmlContent] = useState(\n normalizedHtmlContent\n );\n const prevIncomingHtmlRef = useRef(normalizedHtmlContent);\n const pendingHtmlRef = useRef(normalizedHtmlContent);\n const deferRenderTimerRef = useRef<number | null>(null);\n const initialPaintFrameRef = useRef<number | null>(null);\n const renderViewportHeightCssRef = useRef<string | null>(null);\n\n const emitSandboxInteraction = useCallback((eventType: string) => {\n if (typeof window === \"undefined\") {\n return;\n }\n const now = Date.now();\n if (\n now - lastSandboxInteractionTimeRef.current <\n SANDBOX_INTERACTION_THROTTLE_MS\n ) {\n return;\n }\n lastSandboxInteractionTimeRef.current = now;\n window.postMessage(\n {\n source: SANDBOX_INTERACTION_MESSAGE_SOURCE,\n type: SANDBOX_INTERACTION_MESSAGE_TYPE,\n eventType,\n },\n window.location.origin\n );\n }, []);\n\n useEffect(() => {\n if (type !== \"markdown\" || mode !== \"blackboard\") return;\n const container = markdownContainerRef.current;\n if (!container) return;\n const handleClick = () => emitSandboxInteraction(\"click\");\n container.addEventListener(\"click\", handleClick);\n return () => container.removeEventListener(\"click\", handleClick);\n }, [emitSandboxInteraction, mode, type]);\n\n const clearDeferredRenderTimer = () => {\n if (deferRenderTimerRef.current === null) return;\n window.clearTimeout(deferRenderTimerRef.current);\n deferRenderTimerRef.current = null;\n };\n\n const clearInitialPaintFrames = () => {\n if (initialPaintFrameRef.current !== null) {\n window.cancelAnimationFrame(initialPaintFrameRef.current);\n initialPaintFrameRef.current = null;\n }\n };\n\n useEffect(\n () => () => {\n clearDeferredRenderTimer();\n clearInitialPaintFrames();\n },\n []\n );\n\n useEffect(() => {\n const prevIncomingHtml = prevIncomingHtmlRef.current;\n prevIncomingHtmlRef.current = normalizedHtmlContent;\n\n const isAppendOnlyStream =\n !!prevIncomingHtml &&\n normalizedHtmlContent.length > prevIncomingHtml.length &&\n normalizedHtmlContent.startsWith(prevIncomingHtml);\n const containsCompleteImage = COMPLETE_IMAGE_TAG_PATTERN.test(\n normalizedHtmlContent\n );\n const shouldDeferRender = isAppendOnlyStream && containsCompleteImage;\n\n if (!shouldDeferRender) {\n clearDeferredRenderTimer();\n pendingHtmlRef.current = normalizedHtmlContent;\n setRenderHtmlContent(normalizedHtmlContent);\n return;\n }\n\n pendingHtmlRef.current = normalizedHtmlContent;\n clearDeferredRenderTimer();\n deferRenderTimerRef.current = window.setTimeout(() => {\n setRenderHtmlContent(pendingHtmlRef.current);\n deferRenderTimerRef.current = null;\n }, POST_IMAGE_STREAM_DEBOUNCE_MS);\n }, [normalizedHtmlContent]);\n\n const rootViewportHeightCss = React.useMemo(() => {\n if (!shouldMeasureDynamicHeight) {\n return null;\n }\n\n return inspectViewportHeightFromHtmlRootString(renderHtmlContent)\n .viewportHeightCss;\n }, [renderHtmlContent, shouldMeasureDynamicHeight]);\n\n useEffect(() => {\n renderViewportHeightCssRef.current = rootViewportHeightCss;\n }, [rootViewportHeightCss]);\n\n const hasRootVhHeight = Boolean(rootViewportHeightCss);\n const sandboxViewportHeight =\n isBlackboardMode && type === \"sandbox\"\n ? shouldEnableScaling\n ? \"100%\"\n : shouldStretchRootHeight\n ? \"100%\"\n : (rootViewportHeightCss ?? `${height}px`)\n : undefined;\n useEffect(() => {\n if (mode !== \"blackboard\") {\n prevHtmlRef.current = normalizedHtmlContent;\n return;\n }\n const prev = prevHtmlRef.current;\n const isContinuation = prev && normalizedHtmlContent.startsWith(prev);\n if (!isContinuation && prev) {\n setResetToken((token) => token + 1);\n }\n prevHtmlRef.current = normalizedHtmlContent;\n }, [mode, normalizedHtmlContent]);\n\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe) return undefined;\n\n const doc = iframe.contentDocument;\n if (!doc) return undefined;\n\n doc.open();\n doc.write(`<!DOCTYPE html>\n<html${mode === \"blackboard\" ? ' style=\"height: 100%;\"' : \"\"}>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <style>\n :root { color-scheme: light; }\n html, body, #root { width: 100%; font-family: ${CJK_SAFE_SANS_FONT_FAMILY}; }\n ${mode === \"blackboard\" ? \"html, body, #root { height: 100%; }\" : \"\"}\n html, body { margin: 0; padding: 0; overflow: ${shouldEnableScaling ? \"hidden auto\" : mode === \"blackboard\" ? \"auto\" : \"hidden\"}; }\n *, *::before, *::after { box-sizing: border-box; }\n ${\n mode !== \"blackboard\"\n ? `\n .h-screen { height: auto !important; }\n .min-h-screen { min-height: auto !important; }\n .h-dvh, .h-svh, .h-lvh { height: auto !important; }\n .min-h-dvh, .min-h-svh, .min-h-lvh { min-height: auto !important; }\n `\n : \"\"\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n </body>\n</html>`);\n doc.close();\n\n // Force iframe theme to stay in light mode regardless of host OS preference.\n doc.documentElement.setAttribute(\"data-theme\", \"light\");\n doc.documentElement.style.colorScheme = \"light\";\n doc.body?.style.setProperty(\"color-scheme\", \"light\");\n\n const shouldBridgeSandboxInteraction =\n isBlackboardMode && type === \"sandbox\";\n const handleSandboxClick = () => emitSandboxInteraction(\"click\");\n\n if (shouldBridgeSandboxInteraction) {\n doc.addEventListener(\"click\", handleSandboxClick, true);\n }\n\n const rootEl = doc.getElementById(\"root\");\n if (!rootEl) return undefined;\n\n const root = createRoot(rootEl);\n rootRef.current = root;\n let isDestroyed = false;\n const getHeightInspectionNode = (node: HTMLElement) => ({\n heightAttrValue: node.getAttribute(\"height\"),\n styleAttrValue: node.getAttribute(\"style\"),\n classAttrValue: node.getAttribute(\"class\"),\n });\n const getSingleChildElement = (node: HTMLElement) => {\n const childElements = Array.from(node.children) as HTMLElement[];\n\n return childElements.length === 1 ? childElements[0] : null;\n };\n\n const resolveExplicitHeight = () => {\n if (!shouldMeasureDynamicHeight) return null;\n if (!iframeRef.current || !doc.body) return null;\n const parentViewportHeight =\n iframeRef.current.ownerDocument?.documentElement?.clientHeight ||\n window.innerHeight;\n // Reuse parsed height metadata from the current html snapshot first to\n // avoid re-inspecting the same DOM chain on every height tick.\n const precomputedViewportHeightCss = renderViewportHeightCssRef.current;\n const parsed = precomputedViewportHeightCss\n ? parseExplicitHeight(\n precomputedViewportHeightCss,\n parentViewportHeight\n )\n : null;\n\n if (parsed !== null) {\n return Math.ceil(parsed);\n }\n\n const wrapper = doc.body.querySelector(\n \".sandbox-wrapper\"\n ) as HTMLElement | null;\n const container = wrapper?.firstElementChild as HTMLElement | null;\n if (!container) return null;\n const containerChildren = Array.from(container.children) as HTMLElement[];\n const rootContentElement =\n containerChildren.length === 1 ? containerChildren[0] : null;\n const runtimeHeightMeta = inspectViewportHeightFromNodeChain(\n rootContentElement,\n {\n getNode: getHeightInspectionNode,\n getSingleChild: getSingleChildElement,\n }\n );\n const runtimeViewportHeightCss = runtimeHeightMeta.viewportHeightCss;\n\n if (runtimeViewportHeightCss) {\n const runtimeViewportHeight = parseExplicitHeight(\n runtimeViewportHeightCss,\n parentViewportHeight\n );\n\n if (runtimeViewportHeight !== null) {\n return Math.ceil(runtimeViewportHeight);\n }\n }\n\n const explicitPixelHeight = resolveExplicitHeightFromNodeChain(\n rootContentElement,\n parentViewportHeight,\n {\n getNode: getHeightInspectionNode,\n getSingleChild: getSingleChildElement,\n }\n );\n\n return explicitPixelHeight !== null\n ? Math.ceil(explicitPixelHeight)\n : null;\n };\n\n const updateHeight = () => {\n if (!iframeRef.current || !doc.body) return;\n\n if (!isBlackboardMode) {\n // Guard: prevent re-entrant measurement from ResizeObserver /\n // MutationObserver callbacks triggered by our own height changes.\n if (isMeasuringContentRef.current) {\n // Mark that an update was requested while the guard was active.\n // We will retry once the guard releases (see setTimeout below).\n pendingHeightUpdateRef.current = true;\n return;\n }\n isMeasuringContentRef.current = true;\n\n // Content mode height measurement strategy:\n // Temporarily set iframe height to the 16:9 minimum so that:\n // 1. vmin units are stable: vmin = min(cw, minH)/100 = minH/100,\n // consistent with the final rendered 16:9 iframe.\n // 2. Viewport-filling content (e.g. inline style=\"height:100vh\")\n // fills the 16:9 space → scrollHeight = minH, which is then\n // correctly bounded by the 16:9 minimum in contentModeStyle.\n // (Previously using cw caused such content to report 1:1 height,\n // overriding the 16:9 minimum.)\n const iframe = iframeRef.current;\n const cw = containerRef.current?.clientWidth || 0;\n const prevH = iframe.style.height;\n\n if (cw > 0) {\n const minH = Math.round((cw * 9) / 16);\n // Absolute height cap. Diverging vh-feedback (multiple `height:100vh`\n // siblings, or compound vh-relative children whose sum exceeds the\n // viewport) can otherwise grow the iframe geometrically across\n // repeated ResizeObserver/MutationObserver passes. 1:20 aspect is\n // a generous upper bound for any single sandbox slide.\n const maxH = Math.max(8192, cw * 20);\n iframe.style.height = minH + \"px\";\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n doc.body.offsetHeight; // force layout\n\n let measuredH = doc.body.scrollHeight;\n\n // Detect inner elements that clip overflowing content behind a\n // scrollbar (e.g. <div style=\"height:100vh; overflow-y:auto\"> whose\n // content is taller than the iframe). body.scrollHeight won't see\n // that overflow, so we walk the tree and factor in each scrollable\n // element's full scroll height based on its position in the iframe.\n const iframeWin = doc.defaultView;\n if (iframeWin) {\n // Returns the max natural bottom of inner elements that clip\n // content via overflow:auto/scroll (i.e. internal scrollbars).\n const getInnerScrollableHeight = (root: Element): number => {\n let maxH = 0;\n const walk = (el: Element) => {\n if (el !== root && el.scrollHeight > el.clientHeight + 1) {\n const oy = iframeWin.getComputedStyle(el).overflowY;\n if (oy === \"auto\" || oy === \"scroll\") {\n const rect = el.getBoundingClientRect();\n if (rect.top >= 0) {\n maxH = Math.max(\n maxH,\n Math.ceil(rect.top + el.scrollHeight)\n );\n }\n }\n }\n for (const child of el.children) walk(child);\n };\n walk(root);\n return maxH;\n };\n\n measuredH = Math.max(measuredH, getInnerScrollableHeight(doc.body));\n\n // Content that uses vh-relative sizing grows as the viewport\n // expands. Measure up to 8 more times at the expanded height so\n // we capture the full content height in a single updateHeight()\n // call rather than waiting for external re-triggers.\n for (let i = 0; i < 8 && measuredH > minH; i++) {\n iframe.style.height = measuredH + \"px\";\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n doc.body.offsetHeight; // force layout at expanded size\n const nextH = Math.max(\n doc.body.scrollHeight,\n getInnerScrollableHeight(doc.body)\n );\n if (nextH <= measuredH + 1) break; // stable — stop iterating\n // Geometric vh-feedback detection: vh-relative children scale\n // with the iframe viewport, so growing the iframe makes them\n // larger which grows scrollHeight — runaway divergence. Two\n // `height:100vh` siblings produce a 2× per-iteration multiplier.\n // Stop iterating; keep the prior (stable) measuredH.\n if (nextH >= measuredH * 1.5) break;\n measuredH = nextH;\n }\n }\n\n // Restore iframe to let React control it via contentModeStyle\n iframe.style.height = prevH;\n\n setContentHeight((prev) => {\n const next = Math.min(maxH, Math.max(200, Math.ceil(measuredH)));\n return prev === next ? prev : next;\n });\n }\n\n setTimeout(() => {\n isMeasuringContentRef.current = false;\n // Retry any update that was blocked while the guard was active\n // (e.g. dynamic content injected by scripts or images loading).\n if (pendingHeightUpdateRef.current) {\n pendingHeightUpdateRef.current = false;\n scheduleHeightUpdate();\n }\n }, 50);\n return;\n }\n\n // Scaling mode: viewport is fixed, content scales via font-size.\n if (shouldEnableScaling) return;\n\n // Blackboard mode: use existing measurement logic\n const bodyScrollH = doc.body.scrollHeight;\n const htmlScrollH = doc.documentElement?.scrollHeight || 0;\n const rootScrollH = rootEl?.scrollHeight || 0;\n const measuredHeight = Math.max(bodyScrollH, htmlScrollH, rootScrollH);\n\n if (shouldMeasureDynamicHeight) {\n const explicitHeight = resolveExplicitHeight();\n const nextHeight = Math.max(\n 200,\n explicitHeight ?? Math.ceil(measuredHeight)\n );\n setHeight((prevHeight) =>\n prevHeight === nextHeight ? prevHeight : nextHeight\n );\n }\n };\n const scheduleHeightUpdate = () => {\n requestAnimationFrame(() => {\n if (isDestroyed) return;\n updateHeight();\n });\n };\n updateHeightRef.current = scheduleHeightUpdate;\n\n updateHeight();\n scheduleHeightUpdate();\n\n if (shouldInjectSandboxVendor) {\n // Inject Tailwind/DaisyUI/GSAP before rendering sandbox content to avoid FOUC.\n loadBlackboardVendor()\n .then(({ injectBlackboardLibraries }) => {\n if (isDestroyed) return;\n injectBlackboardLibraries(doc);\n if (shouldEnableScaling) {\n injectScalingSystem(doc);\n }\n requestAnimationFrame(() => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n });\n })\n .catch(() => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n });\n }\n\n const hostElement = containerRef.current;\n let needsTailwindRefreshAfterHidden = Boolean(\n hostElement &&\n (hostElement.clientWidth <= 0 || hostElement.clientHeight <= 0)\n );\n let isTailwindRefreshQueued = false;\n let tailwindRefreshFrame: number | null = null;\n let tailwindRefreshTimer: number | null = null;\n const runPostTailwindRefreshLayout = () => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n const iframeWin = iframe.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_triggerFitContent?.();\n };\n const isHostVisible = () =>\n Boolean(\n hostElement &&\n hostElement.clientWidth > 0 &&\n hostElement.clientHeight > 0\n );\n const queueTailwindRefreshAfterHidden = () => {\n if (\n !shouldInjectSandboxVendor ||\n !hostElement ||\n !needsTailwindRefreshAfterHidden ||\n isTailwindRefreshQueued ||\n !isHostVisible()\n ) {\n return;\n }\n\n isTailwindRefreshQueued = true;\n loadBlackboardVendor()\n .then(({ refreshTailwindRuntime }) => {\n if (isDestroyed) return;\n\n tailwindRefreshFrame = window.requestAnimationFrame(() => {\n tailwindRefreshFrame = null;\n isTailwindRefreshQueued = false;\n\n const sandboxContainer = doc.querySelector(\".sandbox-container\");\n if (\n isDestroyed ||\n !isHostVisible() ||\n !sandboxContainer?.childNodes.length ||\n !refreshTailwindRuntime(doc)\n ) {\n return;\n }\n\n needsTailwindRefreshAfterHidden = false;\n runPostTailwindRefreshLayout();\n tailwindRefreshTimer = window.setTimeout(() => {\n tailwindRefreshTimer = null;\n runPostTailwindRefreshLayout();\n }, 100);\n });\n })\n .catch(() => {\n isTailwindRefreshQueued = false;\n });\n };\n const canObserveResize = typeof ResizeObserver !== \"undefined\";\n const hostResizeObserver =\n shouldInjectSandboxVendor && hostElement && canObserveResize\n ? new ResizeObserver((entries) => {\n const contentRect = entries[0]?.contentRect;\n const hostWidth = contentRect?.width ?? hostElement.clientWidth;\n const hostHeight = contentRect?.height ?? hostElement.clientHeight;\n const isHostSizeVisible = hostWidth > 0 && hostHeight > 0;\n\n if (!isHostSizeVisible) {\n return;\n }\n\n queueTailwindRefreshAfterHidden();\n })\n : null;\n if (hostResizeObserver && hostElement) {\n hostResizeObserver.observe(hostElement);\n }\n\n const resizeObserver = canObserveResize\n ? new ResizeObserver(() => updateHeight())\n : null;\n resizeObserver?.observe(doc.body);\n if (rootEl) {\n resizeObserver?.observe(rootEl);\n }\n\n const syncSandboxContentDirection = () => {\n if (type !== \"sandbox\" || requestedDirectionRef.current !== \"auto\") {\n return;\n }\n const wrapper = doc.querySelector<HTMLElement>(\".sandbox-wrapper\");\n const view = doc.defaultView;\n if (!wrapper || !view) return;\n const nextDirection =\n view.getComputedStyle(wrapper).direction === \"rtl\" ? \"rtl\" : \"ltr\";\n setSandboxContentDirection((currentDirection) =>\n currentDirection === nextDirection ? currentDirection : nextDirection\n );\n };\n\n // MutationObserver: detect DOM changes that ResizeObserver might miss\n // (e.g. content injected by scripts, images loading, dynamic rendering)\n const mutationObserver = new MutationObserver(() => {\n syncSandboxContentDirection();\n scheduleHeightUpdate();\n if (!isHostVisible()) {\n needsTailwindRefreshAfterHidden = true;\n return;\n }\n queueTailwindRefreshAfterHidden();\n });\n mutationObserver.observe(doc.body, {\n childList: true,\n characterData: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"style\", \"class\", \"dir\"],\n });\n\n return () => {\n isDestroyed = true;\n hostResizeObserver?.disconnect();\n resizeObserver?.disconnect();\n mutationObserver.disconnect();\n if (tailwindRefreshFrame !== null) {\n window.cancelAnimationFrame(tailwindRefreshFrame);\n }\n if (tailwindRefreshTimer !== null) {\n window.clearTimeout(tailwindRefreshTimer);\n }\n if (shouldEnableScaling) {\n const iframeWin = iframe.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_cleanupScaling?.();\n }\n if (shouldBridgeSandboxInteraction) {\n doc.removeEventListener(\"click\", handleSandboxClick, true);\n }\n if (rootRef.current === root) {\n rootRef.current = null;\n updateHeightRef.current = () => {};\n }\n // Defer unmount to avoid React warning when parent is mid-render\n setTimeout(() => {\n root.unmount();\n }, 0);\n };\n }, []);\n\n useEffect(() => {\n const onFullscreenChange = () => {\n setIsFullscreen(Boolean(document.fullscreenElement));\n };\n document.addEventListener(\"fullscreenchange\", onFullscreenChange);\n return () =>\n document.removeEventListener(\"fullscreenchange\", onFullscreenChange);\n }, []);\n\n // Track container width for computing min-height in content mode\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n if (typeof ResizeObserver === \"undefined\") {\n setContainerWidth(el.clientWidth);\n return;\n }\n const ro = new ResizeObserver((entries) => {\n setContainerWidth(entries[0]?.contentRect.width ?? el.clientWidth);\n });\n ro.observe(el);\n setContainerWidth(el.clientWidth);\n return () => ro.disconnect();\n }, []);\n\n // Content mode: min 16:9 aspect ratio, grow to fit content (no scrollbar)\n const contentModeStyle = useMemo<React.CSSProperties | undefined>(() => {\n if (isBlackboardMode || containerWidth === 0 || isFullscreen)\n return undefined;\n const minH = Math.round((containerWidth * 9) / 16);\n const h = Math.max(minH, contentHeight);\n return { height: h };\n }, [isBlackboardMode, containerWidth, contentHeight, isFullscreen]);\n\n const toggleFullscreen = () => {\n const target = containerRef.current || iframeRef.current;\n if (!target) return;\n if (document.fullscreenElement) {\n document.exitFullscreen().catch(() => {});\n return;\n }\n if (target.requestFullscreen) {\n target.requestFullscreen().catch(() => {});\n }\n };\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n\n root.render(\n <SandboxApp\n html={renderHtmlContent}\n locale={locale}\n dir={sandboxDirection}\n lang={sandboxLanguage}\n loadingText={loadingText}\n styleLoadingText={styleLoadingText}\n scriptLoadingText={scriptLoadingText}\n disableLoadingOverlay={disableLoadingOverlay}\n resetToken={resetToken}\n hasRootVhHeight={hasRootVhHeight}\n mode={mode}\n stretchRootHeight={shouldStretchRootHeight}\n enableScaling={shouldEnableScaling}\n />\n );\n\n // Schedule multiple measurements to catch async content (scripts, images, styles).\n initialPaintFrameRef.current = window.requestAnimationFrame(() => {\n updateHeightRef.current?.();\n if (shouldEnableScaling) {\n const iframeWin = iframeRef.current\n ?.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_triggerFitContent?.();\n }\n initialPaintFrameRef.current = null;\n });\n const t1 = setTimeout(() => updateHeightRef.current?.(), 100);\n const t2 = setTimeout(() => updateHeightRef.current?.(), 500);\n return () => {\n if (initialPaintFrameRef.current !== null) {\n window.cancelAnimationFrame(initialPaintFrameRef.current);\n initialPaintFrameRef.current = null;\n }\n clearTimeout(t1);\n clearTimeout(t2);\n };\n }, [\n renderHtmlContent,\n locale,\n sandboxDirection,\n sandboxLanguage,\n loadingText,\n styleLoadingText,\n scriptLoadingText,\n resetToken,\n disableLoadingOverlay,\n hasRootVhHeight,\n mode,\n shouldStretchRootHeight,\n shouldEnableScaling,\n ]);\n const containerClassName = [\n `w-full relative content-render-iframe-sandbox content-render-iframe-sandbox--${type}`,\n isBlackboardMode\n ? \"h-full overflow-auto flex flex-col\"\n : contentModeStyle\n ? \"overflow-hidden flex items-center justify-center\"\n : \"aspect-[16/9] overflow-hidden flex items-center justify-center\",\n ]\n .filter(Boolean)\n .join(\" \");\n\n return (\n <div\n ref={containerRef}\n dir={direction}\n lang={language}\n data-root-vh={hasRootVhHeight ? \"true\" : \"false\"}\n className={containerClassName}\n style={\n sandboxViewportHeight\n ? {\n height: sandboxViewportHeight,\n minHeight: sandboxViewportHeight,\n }\n : contentModeStyle\n }\n >\n {!hideFullScreen && (\n <button\n type=\"button\"\n dir={fullscreenControlDirection}\n onClick={toggleFullscreen}\n className={\n \"absolute top-2 end-2 z-50 p-1.5 bg-black/75 text-white rounded-md cursor-pointer\"\n }\n >\n {isFullscreen\n ? resolvedExitFullScreenButtonText\n : resolvedFullScreenButtonText}\n </button>\n )}\n {mode === \"blackboard\" && type === \"markdown\" ? (\n <div ref={setMarkdownContentContainerRef}>\n <ContentRender\n content={content}\n locale={locale}\n dir={direction}\n lang={language}\n disableSandboxLoadingOverlay={disableLoadingOverlay}\n />\n </div>\n ) : (\n <iframe\n ref={iframeRef}\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox\"\n allow=\"fullscreen\"\n allowFullScreen\n className={[className, \"w-full h-full mx-auto my-auto block\"]\n .filter(Boolean)\n .join(\" \")}\n style={{\n height: sandboxViewportHeight ?? \"100%\",\n minHeight: sandboxViewportHeight,\n margin: \"auto\",\n }}\n />\n )}\n </div>\n );\n};\n\nconst IframeSandbox: React.FC<IframeSandboxProps> = (props) => {\n const mode = props.mode ?? \"content\";\n const shouldEnableScaling = Boolean(\n props.enableScaling && mode === \"blackboard\" && props.type === \"sandbox\"\n );\n // The iframe shell captures these initialization-only values. Remounting the\n // inner instance keeps old and new React roots from sharing cleanup refs.\n const lifecycleKey = `${props.type}:${mode}:${shouldEnableScaling ? \"scaled\" : \"unscaled\"}`;\n\n return <IframeSandboxInstance key={lifecycleKey} {...props} />;\n};\n\nexport default IframeSandbox;\n"],"names":["blackboardVendorPromise","loadBlackboardVendor","COMPLETE_IMAGE_TAG_PATTERN","POST_IMAGE_STREAM_DEBOUNCE_MS","SANDBOX_INTERACTION_THROTTLE_MS","replaceRootScreenHeightToken","className","token","segments","replaceRootScreenHeightWithFullClass","html","enabled","match","tagStart","attrs","classMatch","nextClassName","IframeSandboxInstance","content","type","locale","lang","dir","loadingText","styleLoadingText","scriptLoadingText","fullScreenButtonText","exitFullScreenButtonText","hideFullScreen","mode","replaceRootScreenHeightWithFull","enableScaling","disableLoadingOverlay","localeTexts","getContentRenderLocaleTexts","direction","getMarkdownFlowDirection","language","getMarkdownFlowLanguage","resolvedFullScreenButtonText","resolvedExitFullScreenButtonText","containerRef","useRef","sandboxLanguage","useDetachedLanguage","resolvedDirection","useResolvedDirection","markdownContainerRef","markdownContentRef","setMarkdownContentContainerRef","useCallback","node","markdownContentDirection","sandboxDirection","requestedDirectionRef","sandboxContentDirection","setSandboxContentDirection","useState","fullscreenControlDirection","iframeRef","rootRef","updateHeightRef","height","setHeight","contentHeight","setContentHeight","containerWidth","setContainerWidth","isMeasuringContentRef","pendingHeightUpdateRef","lastSandboxInteractionTimeRef","resetToken","setResetToken","isFullscreen","setIsFullscreen","shouldInjectSandboxVendor","isBlackboardMode","shouldEnableScaling","shouldMeasureDynamicHeight","shouldProcessRootScreenHeight","prevHtmlRef","htmlContent","React","normalizedHtmlContent","originalRootHeightMeta","inspectViewportHeightFromHtmlRootString","EMPTY_ROOT_HEIGHT_META","shouldStretchRootHeight","renderHtmlContent","setRenderHtmlContent","prevIncomingHtmlRef","pendingHtmlRef","deferRenderTimerRef","initialPaintFrameRef","renderViewportHeightCssRef","emitSandboxInteraction","eventType","now","SANDBOX_INTERACTION_MESSAGE_SOURCE","SANDBOX_INTERACTION_MESSAGE_TYPE","useEffect","container","handleClick","clearDeferredRenderTimer","clearInitialPaintFrames","prevIncomingHtml","isAppendOnlyStream","containsCompleteImage","rootViewportHeightCss","hasRootVhHeight","sandboxViewportHeight","prev","iframe","doc","CJK_SAFE_SANS_FONT_FAMILY","shouldBridgeSandboxInteraction","handleSandboxClick","rootEl","root","createRoot","isDestroyed","getHeightInspectionNode","getSingleChildElement","childElements","resolveExplicitHeight","parentViewportHeight","precomputedViewportHeightCss","parsed","parseExplicitHeight","containerChildren","rootContentElement","runtimeViewportHeightCss","inspectViewportHeightFromNodeChain","runtimeViewportHeight","explicitPixelHeight","resolveExplicitHeightFromNodeChain","updateHeight","cw","prevH","minH","maxH","measuredH","iframeWin","getInnerScrollableHeight","walk","el","oy","rect","child","i","nextH","next","scheduleHeightUpdate","bodyScrollH","htmlScrollH","rootScrollH","measuredHeight","explicitHeight","nextHeight","prevHeight","injectBlackboardLibraries","injectScalingSystem","hostElement","needsTailwindRefreshAfterHidden","isTailwindRefreshQueued","tailwindRefreshFrame","tailwindRefreshTimer","runPostTailwindRefreshLayout","isHostVisible","queueTailwindRefreshAfterHidden","refreshTailwindRuntime","sandboxContainer","canObserveResize","hostResizeObserver","entries","contentRect","hostWidth","hostHeight","resizeObserver","syncSandboxContentDirection","wrapper","view","nextDirection","currentDirection","mutationObserver","onFullscreenChange","ro","contentModeStyle","useMemo","toggleFullscreen","target","jsx","SandboxApp","t1","t2","containerClassName","jsxs","ContentRender","IframeSandbox","props","lifecycleKey"],"mappings":";;;;;;;;;;;;;AAsCA,IAAIA,KAAkE;AAEtE,MAAMC,KAAuB,OACtBD,OACHA,KAA0B,OAAO,2BAAqB,IAGjDA,KAGHE,KAA6B,iBAC7BC,KAAgC,KAChCC,KAAkC,KAuBlCC,KAA+B,CAACC,MACpCA,EACG,MAAM,KAAK,EACX,OAAO,OAAO,EACd,IAAI,CAACC,MAAU;AACd,QAAMC,IAAWD,EAAM,MAAM,GAAG;AAChC,SACEC,EAASA,EAAS,SAAS,CAAC,MAAM,cAClCA,EAASA,EAAS,SAAS,CAAC,MAAM,iBAE3BD,KAETC,EAASA,EAAS,SAAS,CAAC,IAAI,UACzBA,EAAS,KAAK,GAAG;AAC1B,CAAC,EACA,KAAK,GAAG,GAEPC,KAAuC,CAC3CC,GACAC,MAEI,CAACA,KAAW,CAACD,EAAK,SACbA,IAGFA,EAAK;AAAA,EACV;AAAA,EACA,CAACE,GAAOC,GAAkBC,IAAQ,OAAO;AACvC,UAAMC,IAAaD,EAAM,MAAM,iCAAiC;AAEhE,QAAI,CAACC;AACH,aAAOH;AAGT,UAAMI,IAAgBX,GAA6BU,EAAW,CAAC,CAAC;AAEhE,WAAIC,MAAkBD,EAAW,CAAC,IACzBH,IAGF,GAAGC,CAAQ,GAAGC,EAAM;AAA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AAAA,YACL,SAASmI;AAAA,YACT,WACE;AAAA,YAGD,eACGrJ,KACAD;AAAA,UAAA;AAAA,QAAA;AAAA,QAGPV,MAAS,gBAAgBV,MAAS,aACjC,gBAAA4K,EAAC,OAAA,EAAI,KAAK9I,IACR,UAAA,gBAAA8I;AAAA,UAACM;AAAA,UAAA;AAAA,YACC,SAAAnL;AAAA,YACA,QAAAE;AAAA,YACA,KAAKe;AAAA,YACL,MAAME;AAAA,YACN,8BAA8BL;AAAA,UAAA;AAAA,QAAA,GAElC,IAEA,gBAAA+J;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,KAAKpI;AAAA,YACL,SAAQ;AAAA,YACR,OAAM;AAAA,YACN,iBAAe;AAAA,YACf,WAAW,CAACrD,GAAW,qCAAqC,EACzD,OAAO,OAAO,EACd,KAAK,GAAG;AAAA,YACX,OAAO;AAAA,cACL,QAAQwG,KAAyB;AAAA,cACjC,WAAWA;AAAA,cACX,QAAQ;AAAA,YAAA;AAAA,UACV;AAAA,QAAA;AAAA,MACF;AAAA,IAAA;AAAA,EAAA;AAIR,GAEMwF,KAA8C,CAACC,MAAU;AAC7D,QAAM1K,IAAO0K,EAAM,QAAQ,WACrB1H,IAAsB,GAC1B0H,EAAM,iBAAiB1K,MAAS,gBAAgB0K,EAAM,SAAS,YAI3DC,IAAe,GAAGD,EAAM,IAAI,IAAI1K,CAAI,IAAIgD,IAAsB,WAAW,UAAU;AAEzF,SAAO,gBAAAkH,EAAC9K,IAAA,EAA0C,GAAGsL,EAAA,GAAlBC,CAAyB;AAC9D;"}
|
|
1
|
+
{"version":3,"file":"IframeSandbox.es.js","sources":["../../../src/components/ContentRender/IframeSandbox.tsx"],"sourcesContent":["import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport SandboxApp from \"./SandboxApp\";\nimport ContentRender from \"./ContentRender\";\nimport {\n EMPTY_ROOT_HEIGHT_META,\n inspectViewportHeightFromHtmlRootString,\n inspectViewportHeightFromNodeChain,\n parseExplicitHeight,\n resolveExplicitHeightFromNodeChain,\n} from \"./utils/iframe-viewport-height\";\nimport {\n SANDBOX_INTERACTION_MESSAGE_SOURCE,\n SANDBOX_INTERACTION_MESSAGE_TYPE,\n} from \"../../lib/sandboxInteraction\";\nimport {\n injectScalingSystem,\n type ScalingWindow,\n} from \"./utils/iframe-scaling\";\nimport {\n getMarkdownFlowDirection,\n getMarkdownFlowLanguage,\n type MarkdownFlowLocale,\n} from \"../../lib/locale\";\nimport { useDetachedLanguage } from \"../../lib/useDetachedLanguage\";\nimport { useResolvedDirection } from \"../../lib/useResolvedDirection\";\nimport { getContentRenderLocaleTexts } from \"./contentRenderI18n\";\nimport { CJK_SAFE_SANS_FONT_FAMILY } from \"./cjkFontFamily\";\n\ntype BlackboardVendorModule = typeof import(\"./blackboard-vendor\");\n\n// Cache the sandbox vendor loader so every iframe reuses the same preload request.\nlet blackboardVendorPromise: Promise<BlackboardVendorModule> | null = null;\n\nconst loadBlackboardVendor = () => {\n if (!blackboardVendorPromise) {\n blackboardVendorPromise = import(\"./blackboard-vendor\");\n }\n\n return blackboardVendorPromise;\n};\n\nconst COMPLETE_IMAGE_TAG_PATTERN = /<img\\b[^>]*>/i;\nconst POST_IMAGE_STREAM_DEBOUNCE_MS = 180;\nconst SANDBOX_INTERACTION_THROTTLE_MS = 240;\n\nexport interface IframeSandboxProps {\n content: string;\n className?: string;\n locale?: MarkdownFlowLocale;\n /** Overrides the locale-derived language without changing authored HTML language. */\n lang?: string;\n /** Overrides locale-derived direction without replacing authored HTML direction. */\n dir?: React.HTMLAttributes<HTMLDivElement>[\"dir\"];\n loadingText?: string;\n styleLoadingText?: string;\n scriptLoadingText?: string;\n fullScreenButtonText?: string;\n exitFullScreenButtonText?: string;\n hideFullScreen?: boolean;\n mode?: \"content\" | \"blackboard\";\n type: \"sandbox\" | \"markdown\";\n replaceRootScreenHeightWithFull?: boolean;\n enableScaling?: boolean;\n disableLoadingOverlay?: boolean;\n}\n\nconst replaceRootScreenHeightToken = (className: string) =>\n className\n .split(/\\s+/)\n .filter(Boolean)\n .map((token) => {\n const segments = token.split(\":\");\n if (\n segments[segments.length - 1] !== \"h-screen\" &&\n segments[segments.length - 1] !== \"min-h-screen\"\n ) {\n return token;\n }\n segments[segments.length - 1] = \"h-full\";\n return segments.join(\":\");\n })\n .join(\" \");\n\nconst replaceRootScreenHeightWithFullClass = (\n html: string,\n enabled: boolean\n) => {\n if (!enabled || !html.trim()) {\n return html;\n }\n\n return html.replace(\n /^(\\s*<[a-zA-Z][\\w:-]*)(\\s[^>]*?)?>/,\n (match, tagStart: string, attrs = \"\") => {\n const classMatch = attrs.match(/\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/i);\n\n if (!classMatch) {\n return match;\n }\n\n const nextClassName = replaceRootScreenHeightToken(classMatch[2]);\n\n if (nextClassName === classMatch[2]) {\n return match;\n }\n\n return `${tagStart}${attrs.replace(\n classMatch[0],\n `class=${classMatch[1]}${nextClassName}${classMatch[1]}`\n )}>`;\n }\n );\n};\n\nconst IframeSandboxInstance: React.FC<IframeSandboxProps> = ({\n content,\n type,\n className,\n locale,\n lang,\n dir,\n loadingText,\n styleLoadingText,\n scriptLoadingText,\n fullScreenButtonText,\n exitFullScreenButtonText,\n hideFullScreen = false,\n mode = \"content\",\n replaceRootScreenHeightWithFull = false,\n enableScaling = false,\n disableLoadingOverlay = false,\n}) => {\n const localeTexts = getContentRenderLocaleTexts(locale);\n const direction = dir ?? getMarkdownFlowDirection(locale);\n const language = lang ?? getMarkdownFlowLanguage(locale);\n const resolvedFullScreenButtonText =\n fullScreenButtonText || localeTexts.sandboxFullscreenButtonText;\n const resolvedExitFullScreenButtonText =\n exitFullScreenButtonText || localeTexts.sandboxExitFullscreenButtonText;\n const containerRef = useRef<HTMLDivElement>(null);\n const fullscreenButtonRef = useRef<HTMLButtonElement>(null);\n const sandboxLanguage = useDetachedLanguage(containerRef, language);\n const { resolvedDirection } = useResolvedDirection(containerRef, direction);\n const markdownContainerRef = useRef<HTMLDivElement>(null);\n const markdownContentRef = useRef<HTMLElement>(null);\n const setMarkdownContentContainerRef = useCallback(\n (node: HTMLDivElement | null) => {\n markdownContainerRef.current = node;\n markdownContentRef.current =\n node?.querySelector<HTMLElement>(\".content-render\") ?? null;\n },\n []\n );\n const { resolvedDirection: markdownContentDirection } = useResolvedDirection(\n markdownContentRef,\n direction\n );\n const sandboxDirection = direction ?? resolvedDirection;\n const requestedDirectionRef = useRef(direction);\n requestedDirectionRef.current = direction;\n // Auto direction cannot inspect text across the iframe document boundary.\n // Mirror the rendered sandbox direction to host controls instead.\n const [sandboxContentDirection, setSandboxContentDirection] = useState<\n \"ltr\" | \"rtl\"\n >();\n let fullscreenControlDirection: \"ltr\" | \"rtl\" | undefined;\n if (direction === \"auto\") {\n fullscreenControlDirection = resolvedDirection;\n if (type === \"sandbox\") {\n fullscreenControlDirection = sandboxContentDirection ?? resolvedDirection;\n } else if (mode === \"blackboard\") {\n fullscreenControlDirection = markdownContentDirection;\n }\n }\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const rootRef = useRef<Root | null>(null);\n const updateHeightRef = useRef<() => void>(() => {});\n const [height, setHeight] = useState(480);\n const [contentHeight, setContentHeight] = useState<number | null>(null);\n const [containerWidth, setContainerWidth] = useState(0);\n const [fullscreenControlHeight, setFullscreenControlHeight] = useState(0);\n const isMeasuringContentRef = useRef(false);\n const pendingHeightUpdateRef = useRef(false);\n const lastSandboxInteractionTimeRef = useRef(0);\n const [resetToken, setResetToken] = useState(0);\n const [isFullscreen, setIsFullscreen] = useState(false);\n const shouldInjectSandboxVendor = type === \"sandbox\";\n\n const isBlackboardMode = mode === \"blackboard\";\n const shouldEnableScaling =\n enableScaling && isBlackboardMode && type === \"sandbox\";\n const shouldMeasureDynamicHeight = isBlackboardMode && type === \"sandbox\";\n const shouldProcessRootScreenHeight =\n shouldMeasureDynamicHeight && replaceRootScreenHeightWithFull;\n const prevHtmlRef = useRef<string>(\"\");\n const htmlContent = React.useMemo(\n () => (type === \"sandbox\" ? content : \"\"),\n [content, type]\n );\n const normalizedHtmlContent = React.useMemo(\n () =>\n replaceRootScreenHeightWithFullClass(\n htmlContent,\n shouldProcessRootScreenHeight\n ),\n [htmlContent, shouldProcessRootScreenHeight]\n );\n const originalRootHeightMeta = React.useMemo(\n () =>\n shouldProcessRootScreenHeight\n ? inspectViewportHeightFromHtmlRootString(htmlContent)\n : EMPTY_ROOT_HEIGHT_META,\n [htmlContent, shouldProcessRootScreenHeight]\n );\n const shouldStretchRootHeight = React.useMemo(\n () =>\n shouldProcessRootScreenHeight &&\n originalRootHeightMeta.hasFullViewportHeight,\n [\n originalRootHeightMeta.hasFullViewportHeight,\n shouldProcessRootScreenHeight,\n ]\n );\n const [renderHtmlContent, setRenderHtmlContent] = useState(\n normalizedHtmlContent\n );\n const prevIncomingHtmlRef = useRef(normalizedHtmlContent);\n const pendingHtmlRef = useRef(normalizedHtmlContent);\n const deferRenderTimerRef = useRef<number | null>(null);\n const initialPaintFrameRef = useRef<number | null>(null);\n const renderViewportHeightCssRef = useRef<string | null>(null);\n\n const emitSandboxInteraction = useCallback((eventType: string) => {\n if (typeof window === \"undefined\") {\n return;\n }\n const now = Date.now();\n if (\n now - lastSandboxInteractionTimeRef.current <\n SANDBOX_INTERACTION_THROTTLE_MS\n ) {\n return;\n }\n lastSandboxInteractionTimeRef.current = now;\n window.postMessage(\n {\n source: SANDBOX_INTERACTION_MESSAGE_SOURCE,\n type: SANDBOX_INTERACTION_MESSAGE_TYPE,\n eventType,\n },\n window.location.origin\n );\n }, []);\n\n useEffect(() => {\n if (type !== \"markdown\" || mode !== \"blackboard\") return;\n const container = markdownContainerRef.current;\n if (!container) return;\n const handleClick = () => emitSandboxInteraction(\"click\");\n container.addEventListener(\"click\", handleClick);\n return () => container.removeEventListener(\"click\", handleClick);\n }, [emitSandboxInteraction, mode, type]);\n\n const clearDeferredRenderTimer = () => {\n if (deferRenderTimerRef.current === null) return;\n window.clearTimeout(deferRenderTimerRef.current);\n deferRenderTimerRef.current = null;\n };\n\n const clearInitialPaintFrames = () => {\n if (initialPaintFrameRef.current !== null) {\n window.cancelAnimationFrame(initialPaintFrameRef.current);\n initialPaintFrameRef.current = null;\n }\n };\n\n useEffect(\n () => () => {\n clearDeferredRenderTimer();\n clearInitialPaintFrames();\n },\n []\n );\n\n useEffect(() => {\n const prevIncomingHtml = prevIncomingHtmlRef.current;\n prevIncomingHtmlRef.current = normalizedHtmlContent;\n\n const isAppendOnlyStream =\n !!prevIncomingHtml &&\n normalizedHtmlContent.length > prevIncomingHtml.length &&\n normalizedHtmlContent.startsWith(prevIncomingHtml);\n const containsCompleteImage = COMPLETE_IMAGE_TAG_PATTERN.test(\n normalizedHtmlContent\n );\n const shouldDeferRender = isAppendOnlyStream && containsCompleteImage;\n\n if (!shouldDeferRender) {\n clearDeferredRenderTimer();\n pendingHtmlRef.current = normalizedHtmlContent;\n setRenderHtmlContent(normalizedHtmlContent);\n return;\n }\n\n pendingHtmlRef.current = normalizedHtmlContent;\n clearDeferredRenderTimer();\n deferRenderTimerRef.current = window.setTimeout(() => {\n setRenderHtmlContent(pendingHtmlRef.current);\n deferRenderTimerRef.current = null;\n }, POST_IMAGE_STREAM_DEBOUNCE_MS);\n }, [normalizedHtmlContent]);\n\n const rootViewportHeightCss = React.useMemo(() => {\n if (!shouldMeasureDynamicHeight) {\n return null;\n }\n\n return inspectViewportHeightFromHtmlRootString(renderHtmlContent)\n .viewportHeightCss;\n }, [renderHtmlContent, shouldMeasureDynamicHeight]);\n\n useEffect(() => {\n renderViewportHeightCssRef.current = rootViewportHeightCss;\n }, [rootViewportHeightCss]);\n\n const hasRootVhHeight = Boolean(rootViewportHeightCss);\n const sandboxViewportHeight =\n isBlackboardMode && type === \"sandbox\"\n ? shouldEnableScaling\n ? \"100%\"\n : shouldStretchRootHeight\n ? \"100%\"\n : (rootViewportHeightCss ?? `${height}px`)\n : undefined;\n useEffect(() => {\n if (mode !== \"blackboard\") {\n prevHtmlRef.current = normalizedHtmlContent;\n return;\n }\n const prev = prevHtmlRef.current;\n const isContinuation = prev && normalizedHtmlContent.startsWith(prev);\n if (!isContinuation && prev) {\n setResetToken((token) => token + 1);\n }\n prevHtmlRef.current = normalizedHtmlContent;\n }, [mode, normalizedHtmlContent]);\n\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe) return undefined;\n\n const doc = iframe.contentDocument;\n if (!doc) return undefined;\n\n doc.open();\n doc.write(`<!DOCTYPE html>\n<html${mode === \"blackboard\" ? ' style=\"height: 100%;\"' : \"\"}>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <style>\n :root { color-scheme: light; }\n html, body, #root { width: 100%; font-family: ${CJK_SAFE_SANS_FONT_FAMILY}; }\n ${mode === \"blackboard\" ? \"html, body, #root { height: 100%; }\" : \"\"}\n html, body { margin: 0; padding: 0; overflow: ${shouldEnableScaling ? \"hidden auto\" : mode === \"blackboard\" ? \"auto\" : \"hidden\"}; }\n *, *::before, *::after { box-sizing: border-box; }\n ${\n mode !== \"blackboard\"\n ? `\n .h-screen { height: auto !important; }\n .min-h-screen { min-height: auto !important; }\n .h-dvh, .h-svh, .h-lvh { height: auto !important; }\n .min-h-dvh, .min-h-svh, .min-h-lvh { min-height: auto !important; }\n `\n : \"\"\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n </body>\n</html>`);\n doc.close();\n\n // Force iframe theme to stay in light mode regardless of host OS preference.\n doc.documentElement.setAttribute(\"data-theme\", \"light\");\n doc.documentElement.style.colorScheme = \"light\";\n doc.body?.style.setProperty(\"color-scheme\", \"light\");\n\n const shouldBridgeSandboxInteraction =\n isBlackboardMode && type === \"sandbox\";\n const handleSandboxClick = () => emitSandboxInteraction(\"click\");\n\n if (shouldBridgeSandboxInteraction) {\n doc.addEventListener(\"click\", handleSandboxClick, true);\n }\n\n const rootEl = doc.getElementById(\"root\");\n if (!rootEl) return undefined;\n\n const root = createRoot(rootEl);\n rootRef.current = root;\n let isDestroyed = false;\n const getHeightInspectionNode = (node: HTMLElement) => ({\n heightAttrValue: node.getAttribute(\"height\"),\n styleAttrValue: node.getAttribute(\"style\"),\n classAttrValue: node.getAttribute(\"class\"),\n });\n const getSingleChildElement = (node: HTMLElement) => {\n const childElements = Array.from(node.children) as HTMLElement[];\n\n return childElements.length === 1 ? childElements[0] : null;\n };\n\n const resolveExplicitHeight = () => {\n if (!shouldMeasureDynamicHeight) return null;\n if (!iframeRef.current || !doc.body) return null;\n const parentViewportHeight =\n iframeRef.current.ownerDocument?.documentElement?.clientHeight ||\n window.innerHeight;\n // Reuse parsed height metadata from the current html snapshot first to\n // avoid re-inspecting the same DOM chain on every height tick.\n const precomputedViewportHeightCss = renderViewportHeightCssRef.current;\n const parsed = precomputedViewportHeightCss\n ? parseExplicitHeight(\n precomputedViewportHeightCss,\n parentViewportHeight\n )\n : null;\n\n if (parsed !== null) {\n return Math.ceil(parsed);\n }\n\n const wrapper = doc.body.querySelector(\n \".sandbox-wrapper\"\n ) as HTMLElement | null;\n const container = wrapper?.firstElementChild as HTMLElement | null;\n if (!container) return null;\n const containerChildren = Array.from(container.children) as HTMLElement[];\n const rootContentElement =\n containerChildren.length === 1 ? containerChildren[0] : null;\n const runtimeHeightMeta = inspectViewportHeightFromNodeChain(\n rootContentElement,\n {\n getNode: getHeightInspectionNode,\n getSingleChild: getSingleChildElement,\n }\n );\n const runtimeViewportHeightCss = runtimeHeightMeta.viewportHeightCss;\n\n if (runtimeViewportHeightCss) {\n const runtimeViewportHeight = parseExplicitHeight(\n runtimeViewportHeightCss,\n parentViewportHeight\n );\n\n if (runtimeViewportHeight !== null) {\n return Math.ceil(runtimeViewportHeight);\n }\n }\n\n const explicitPixelHeight = resolveExplicitHeightFromNodeChain(\n rootContentElement,\n parentViewportHeight,\n {\n getNode: getHeightInspectionNode,\n getSingleChild: getSingleChildElement,\n }\n );\n\n return explicitPixelHeight !== null\n ? Math.ceil(explicitPixelHeight)\n : null;\n };\n\n const updateHeight = () => {\n if (!iframeRef.current || !doc.body) return;\n\n if (!isBlackboardMode) {\n // Guard: prevent re-entrant measurement from ResizeObserver /\n // MutationObserver callbacks triggered by our own height changes.\n if (isMeasuringContentRef.current) {\n // Mark that an update was requested while the guard was active.\n // We will retry once the guard releases (see setTimeout below).\n pendingHeightUpdateRef.current = true;\n return;\n }\n isMeasuringContentRef.current = true;\n\n // Content mode height measurement strategy:\n // Temporarily set iframe height to the 16:9 layout viewport so that:\n // 1. vmin units are stable: vmin = min(cw, minH)/100 = minH/100,\n // consistent with the final rendered 16:9 iframe.\n // 2. Viewport-filling content (e.g. inline style=\"height:100vh\")\n // retains its 16:9 viewport. Naturally sized content reserves only\n // its measured body height in the host page.\n // (Previously using cw caused such content to report 1:1 height,\n // overriding the 16:9 minimum.)\n const iframe = iframeRef.current;\n const cw = containerRef.current?.clientWidth || 0;\n const prevH = iframe.style.height;\n\n if (cw > 0) {\n const minH = Math.round((cw * 9) / 16);\n // Absolute height cap. Diverging vh-feedback (multiple `height:100vh`\n // siblings, or compound vh-relative children whose sum exceeds the\n // viewport) can otherwise grow the iframe geometrically across\n // repeated ResizeObserver/MutationObserver passes. 1:20 aspect is\n // a generous upper bound for any single sandbox slide.\n const maxH = Math.max(8192, cw * 20);\n iframe.style.height = minH + \"px\";\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n doc.body.offsetHeight; // force layout\n\n let measuredH = doc.body.scrollHeight;\n\n // Detect inner elements that clip overflowing content behind a\n // scrollbar (e.g. <div style=\"height:100vh; overflow-y:auto\"> whose\n // content is taller than the iframe). body.scrollHeight won't see\n // that overflow, so we walk the tree and factor in each scrollable\n // element's full scroll height based on its position in the iframe.\n const iframeWin = doc.defaultView;\n if (iframeWin) {\n // Include fixed-position widgets, which do not contribute to body\n // scrollHeight, as well as content behind internal scrollbars.\n const getInnerScrollableHeight = (root: Element): number => {\n let maxH = 0;\n const walk = (el: Element) => {\n const style = iframeWin.getComputedStyle(el);\n if (style.position === \"fixed\") {\n maxH = Math.max(\n maxH,\n Math.ceil(el.getBoundingClientRect().bottom)\n );\n }\n if (el !== root && el.scrollHeight > el.clientHeight + 1) {\n const oy = style.overflowY;\n if (oy === \"auto\" || oy === \"scroll\") {\n const rect = el.getBoundingClientRect();\n if (rect.top >= 0) {\n maxH = Math.max(\n maxH,\n Math.ceil(rect.top + el.scrollHeight)\n );\n }\n }\n }\n for (const child of el.children) walk(child);\n };\n walk(root);\n return maxH;\n };\n\n measuredH = Math.max(measuredH, getInnerScrollableHeight(doc.body));\n\n // Content that uses vh-relative sizing grows as the viewport\n // expands. Measure up to 8 more times at the expanded height so\n // we capture the full content height in a single updateHeight()\n // call rather than waiting for external re-triggers.\n for (let i = 0; i < 8 && measuredH > minH; i++) {\n iframe.style.height = measuredH + \"px\";\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n doc.body.offsetHeight; // force layout at expanded size\n const nextH = Math.max(\n doc.body.scrollHeight,\n getInnerScrollableHeight(doc.body)\n );\n if (nextH <= measuredH + 1) break; // stable — stop iterating\n // Geometric vh-feedback detection: vh-relative children scale\n // with the iframe viewport, so growing the iframe makes them\n // larger which grows scrollHeight — runaway divergence. Two\n // `height:100vh` siblings produce a 2× per-iteration multiplier.\n // Stop iterating; keep the prior (stable) measuredH.\n if (nextH >= measuredH * 1.5) break;\n measuredH = nextH;\n }\n }\n\n // Restore iframe to let React control it via contentModeStyle\n iframe.style.height = prevH;\n\n setContentHeight((prev) => {\n const next = Math.min(maxH, Math.max(1, Math.ceil(measuredH)));\n return prev === next ? prev : next;\n });\n }\n\n setTimeout(() => {\n isMeasuringContentRef.current = false;\n // Retry any update that was blocked while the guard was active\n // (e.g. dynamic content injected by scripts or images loading).\n if (pendingHeightUpdateRef.current) {\n pendingHeightUpdateRef.current = false;\n scheduleHeightUpdate();\n }\n }, 50);\n return;\n }\n\n // Scaling mode: viewport is fixed, content scales via font-size.\n if (shouldEnableScaling) return;\n\n // Blackboard mode: use existing measurement logic\n const bodyScrollH = doc.body.scrollHeight;\n const htmlScrollH = doc.documentElement?.scrollHeight || 0;\n const rootScrollH = rootEl?.scrollHeight || 0;\n const measuredHeight = Math.max(bodyScrollH, htmlScrollH, rootScrollH);\n\n if (shouldMeasureDynamicHeight) {\n const explicitHeight = resolveExplicitHeight();\n const nextHeight = Math.max(\n 200,\n explicitHeight ?? Math.ceil(measuredHeight)\n );\n setHeight((prevHeight) =>\n prevHeight === nextHeight ? prevHeight : nextHeight\n );\n }\n };\n const scheduleHeightUpdate = () => {\n requestAnimationFrame(() => {\n if (isDestroyed) return;\n updateHeight();\n });\n };\n updateHeightRef.current = scheduleHeightUpdate;\n\n updateHeight();\n scheduleHeightUpdate();\n\n if (shouldInjectSandboxVendor) {\n // Inject Tailwind/DaisyUI/GSAP before rendering sandbox content to avoid FOUC.\n loadBlackboardVendor()\n .then(({ injectBlackboardLibraries }) => {\n if (isDestroyed) return;\n injectBlackboardLibraries(doc);\n if (shouldEnableScaling) {\n injectScalingSystem(doc);\n }\n requestAnimationFrame(() => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n });\n })\n .catch(() => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n });\n }\n\n const hostElement = containerRef.current;\n let needsTailwindRefreshAfterHidden = Boolean(\n hostElement &&\n (hostElement.clientWidth <= 0 || hostElement.clientHeight <= 0)\n );\n let isTailwindRefreshQueued = false;\n let tailwindRefreshFrame: number | null = null;\n let tailwindRefreshTimer: number | null = null;\n const runPostTailwindRefreshLayout = () => {\n if (isDestroyed) return;\n scheduleHeightUpdate();\n const iframeWin = iframe.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_triggerFitContent?.();\n };\n const isHostVisible = () =>\n Boolean(\n hostElement &&\n hostElement.clientWidth > 0 &&\n hostElement.clientHeight > 0\n );\n const queueTailwindRefreshAfterHidden = () => {\n if (\n !shouldInjectSandboxVendor ||\n !hostElement ||\n !needsTailwindRefreshAfterHidden ||\n isTailwindRefreshQueued ||\n !isHostVisible()\n ) {\n return;\n }\n\n isTailwindRefreshQueued = true;\n loadBlackboardVendor()\n .then(({ refreshTailwindRuntime }) => {\n if (isDestroyed) return;\n\n tailwindRefreshFrame = window.requestAnimationFrame(() => {\n tailwindRefreshFrame = null;\n isTailwindRefreshQueued = false;\n\n const sandboxContainer = doc.querySelector(\".sandbox-container\");\n if (\n isDestroyed ||\n !isHostVisible() ||\n !sandboxContainer?.childNodes.length ||\n !refreshTailwindRuntime(doc)\n ) {\n return;\n }\n\n needsTailwindRefreshAfterHidden = false;\n runPostTailwindRefreshLayout();\n tailwindRefreshTimer = window.setTimeout(() => {\n tailwindRefreshTimer = null;\n runPostTailwindRefreshLayout();\n }, 100);\n });\n })\n .catch(() => {\n isTailwindRefreshQueued = false;\n });\n };\n const canObserveResize = typeof ResizeObserver !== \"undefined\";\n const hostResizeObserver =\n shouldInjectSandboxVendor && hostElement && canObserveResize\n ? new ResizeObserver((entries) => {\n const contentRect = entries[0]?.contentRect;\n const hostWidth = contentRect?.width ?? hostElement.clientWidth;\n const hostHeight = contentRect?.height ?? hostElement.clientHeight;\n const isHostSizeVisible = hostWidth > 0 && hostHeight > 0;\n\n if (!isHostSizeVisible) {\n return;\n }\n\n queueTailwindRefreshAfterHidden();\n })\n : null;\n if (hostResizeObserver && hostElement) {\n hostResizeObserver.observe(hostElement);\n }\n\n const resizeObserver = canObserveResize\n ? new ResizeObserver(() => updateHeight())\n : null;\n resizeObserver?.observe(doc.body);\n if (rootEl) {\n resizeObserver?.observe(rootEl);\n }\n\n const syncSandboxContentDirection = () => {\n if (type !== \"sandbox\" || requestedDirectionRef.current !== \"auto\") {\n return;\n }\n const wrapper = doc.querySelector<HTMLElement>(\".sandbox-wrapper\");\n const view = doc.defaultView;\n if (!wrapper || !view) return;\n const nextDirection =\n view.getComputedStyle(wrapper).direction === \"rtl\" ? \"rtl\" : \"ltr\";\n setSandboxContentDirection((currentDirection) =>\n currentDirection === nextDirection ? currentDirection : nextDirection\n );\n };\n\n // MutationObserver: detect DOM changes that ResizeObserver might miss\n // (e.g. content injected by scripts, images loading, dynamic rendering)\n const mutationObserver = new MutationObserver(() => {\n syncSandboxContentDirection();\n scheduleHeightUpdate();\n if (!isHostVisible()) {\n needsTailwindRefreshAfterHidden = true;\n return;\n }\n queueTailwindRefreshAfterHidden();\n });\n mutationObserver.observe(doc.body, {\n childList: true,\n characterData: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"style\", \"class\", \"dir\"],\n });\n\n return () => {\n isDestroyed = true;\n hostResizeObserver?.disconnect();\n resizeObserver?.disconnect();\n mutationObserver.disconnect();\n if (tailwindRefreshFrame !== null) {\n window.cancelAnimationFrame(tailwindRefreshFrame);\n }\n if (tailwindRefreshTimer !== null) {\n window.clearTimeout(tailwindRefreshTimer);\n }\n if (shouldEnableScaling) {\n const iframeWin = iframe.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_cleanupScaling?.();\n }\n if (shouldBridgeSandboxInteraction) {\n doc.removeEventListener(\"click\", handleSandboxClick, true);\n }\n if (rootRef.current === root) {\n rootRef.current = null;\n updateHeightRef.current = () => {};\n }\n // Defer unmount to avoid React warning when parent is mid-render\n setTimeout(() => {\n root.unmount();\n }, 0);\n };\n }, []);\n\n useEffect(() => {\n const onFullscreenChange = () => {\n setIsFullscreen(Boolean(document.fullscreenElement));\n };\n document.addEventListener(\"fullscreenchange\", onFullscreenChange);\n return () =>\n document.removeEventListener(\"fullscreenchange\", onFullscreenChange);\n }, []);\n\n // Track the layout viewport width and enough host space for its own control.\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n const button = fullscreenButtonRef.current;\n const updateControlHeight = () => {\n setFullscreenControlHeight(\n button ? Math.ceil(button.offsetTop + button.offsetHeight) : 0\n );\n };\n if (typeof ResizeObserver === \"undefined\") {\n setContainerWidth(el.clientWidth);\n updateControlHeight();\n return;\n }\n const ro = new ResizeObserver((entries) => {\n const hostEntry = entries.find((entry) => entry.target === el);\n if (hostEntry) setContainerWidth(hostEntry.contentRect.width);\n updateControlHeight();\n });\n ro.observe(el);\n if (button) ro.observe(button);\n setContainerWidth(el.clientWidth);\n updateControlHeight();\n return () => ro.disconnect();\n }, [hideFullScreen]);\n\n // Keep a stable layout viewport for authored vh/vmin sizing, while the host\n // reserves only the measured content height. The iframe is top-aligned inside\n // the clipped host so a short card does not leave a slide-sized blank area.\n const contentModeStyle = useMemo<React.CSSProperties | undefined>(() => {\n if (isBlackboardMode || containerWidth === 0 || isFullscreen)\n return undefined;\n const minH = Math.round((containerWidth * 9) / 16);\n return { height: Math.max(contentHeight ?? minH, fullscreenControlHeight) };\n }, [\n isBlackboardMode,\n containerWidth,\n contentHeight,\n isFullscreen,\n fullscreenControlHeight,\n ]);\n\n const contentIframeHeight = contentModeStyle\n ? Math.max(Math.round((containerWidth * 9) / 16), contentHeight ?? 0)\n : undefined;\n\n const toggleFullscreen = () => {\n const target = containerRef.current || iframeRef.current;\n if (!target) return;\n if (document.fullscreenElement) {\n document.exitFullscreen().catch(() => {});\n return;\n }\n if (target.requestFullscreen) {\n target.requestFullscreen().catch(() => {});\n }\n };\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n\n root.render(\n <SandboxApp\n html={renderHtmlContent}\n locale={locale}\n dir={sandboxDirection}\n lang={sandboxLanguage}\n loadingText={loadingText}\n styleLoadingText={styleLoadingText}\n scriptLoadingText={scriptLoadingText}\n disableLoadingOverlay={disableLoadingOverlay}\n resetToken={resetToken}\n hasRootVhHeight={hasRootVhHeight}\n mode={mode}\n stretchRootHeight={shouldStretchRootHeight}\n enableScaling={shouldEnableScaling}\n />\n );\n\n // Schedule multiple measurements to catch async content (scripts, images, styles).\n initialPaintFrameRef.current = window.requestAnimationFrame(() => {\n updateHeightRef.current?.();\n if (shouldEnableScaling) {\n const iframeWin = iframeRef.current\n ?.contentWindow as ScalingWindow | null;\n iframeWin?.__mdf_triggerFitContent?.();\n }\n initialPaintFrameRef.current = null;\n });\n const t1 = setTimeout(() => updateHeightRef.current?.(), 100);\n const t2 = setTimeout(() => updateHeightRef.current?.(), 500);\n return () => {\n if (initialPaintFrameRef.current !== null) {\n window.cancelAnimationFrame(initialPaintFrameRef.current);\n initialPaintFrameRef.current = null;\n }\n clearTimeout(t1);\n clearTimeout(t2);\n };\n }, [\n renderHtmlContent,\n locale,\n sandboxDirection,\n sandboxLanguage,\n loadingText,\n styleLoadingText,\n scriptLoadingText,\n resetToken,\n disableLoadingOverlay,\n hasRootVhHeight,\n mode,\n shouldStretchRootHeight,\n shouldEnableScaling,\n ]);\n const containerClassName = [\n `w-full relative content-render-iframe-sandbox content-render-iframe-sandbox--${type}`,\n isBlackboardMode\n ? \"h-full overflow-auto flex flex-col\"\n : contentModeStyle\n ? \"overflow-hidden\"\n : \"aspect-[16/9] overflow-hidden flex items-center justify-center\",\n ]\n .filter(Boolean)\n .join(\" \");\n\n return (\n <div\n ref={containerRef}\n dir={direction}\n lang={language}\n data-root-vh={hasRootVhHeight ? \"true\" : \"false\"}\n className={containerClassName}\n style={\n sandboxViewportHeight\n ? {\n height: sandboxViewportHeight,\n minHeight: sandboxViewportHeight,\n }\n : contentModeStyle\n }\n >\n {!hideFullScreen && (\n <button\n ref={fullscreenButtonRef}\n type=\"button\"\n dir={fullscreenControlDirection}\n onClick={toggleFullscreen}\n className={\n \"absolute top-2 end-2 z-50 p-1.5 bg-black/75 text-white rounded-md cursor-pointer\"\n }\n >\n {isFullscreen\n ? resolvedExitFullScreenButtonText\n : resolvedFullScreenButtonText}\n </button>\n )}\n {mode === \"blackboard\" && type === \"markdown\" ? (\n <div ref={setMarkdownContentContainerRef}>\n <ContentRender\n content={content}\n locale={locale}\n dir={direction}\n lang={language}\n disableSandboxLoadingOverlay={disableLoadingOverlay}\n />\n </div>\n ) : (\n <iframe\n ref={iframeRef}\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox\"\n allow=\"fullscreen\"\n allowFullScreen\n className={[className, \"w-full h-full mx-auto my-auto block\"]\n .filter(Boolean)\n .join(\" \")}\n style={{\n height: sandboxViewportHeight ?? contentIframeHeight ?? \"100%\",\n minHeight: sandboxViewportHeight,\n margin: \"auto\",\n }}\n />\n )}\n </div>\n );\n};\n\nconst IframeSandbox: React.FC<IframeSandboxProps> = (props) => {\n const mode = props.mode ?? \"content\";\n const shouldEnableScaling = Boolean(\n props.enableScaling && mode === \"blackboard\" && props.type === \"sandbox\"\n );\n // The iframe shell captures these initialization-only values. Remounting the\n // inner instance keeps old and new React roots from sharing cleanup refs.\n const lifecycleKey = `${props.type}:${mode}:${shouldEnableScaling ? \"scaled\" : \"unscaled\"}`;\n\n return <IframeSandboxInstance key={lifecycleKey} {...props} />;\n};\n\nexport default IframeSandbox;\n"],"names":["blackboardVendorPromise","loadBlackboardVendor","COMPLETE_IMAGE_TAG_PATTERN","POST_IMAGE_STREAM_DEBOUNCE_MS","SANDBOX_INTERACTION_THROTTLE_MS","replaceRootScreenHeightToken","className","token","segments","replaceRootScreenHeightWithFullClass","html","enabled","match","tagStart","attrs","classMatch","nextClassName","IframeSandboxInstance","content","type","locale","lang","dir","loadingText","styleLoadingText","scriptLoadingText","fullScreenButtonText","exitFullScreenButtonText","hideFullScreen","mode","replaceRootScreenHeightWithFull","enableScaling","disableLoadingOverlay","localeTexts","getContentRenderLocaleTexts","direction","getMarkdownFlowDirection","language","getMarkdownFlowLanguage","resolvedFullScreenButtonText","resolvedExitFullScreenButtonText","containerRef","useRef","fullscreenButtonRef","sandboxLanguage","useDetachedLanguage","resolvedDirection","useResolvedDirection","markdownContainerRef","markdownContentRef","setMarkdownContentContainerRef","useCallback","node","markdownContentDirection","sandboxDirection","requestedDirectionRef","sandboxContentDirection","setSandboxContentDirection","useState","fullscreenControlDirection","iframeRef","rootRef","updateHeightRef","height","setHeight","contentHeight","setContentHeight","containerWidth","setContainerWidth","fullscreenControlHeight","setFullscreenControlHeight","isMeasuringContentRef","pendingHeightUpdateRef","lastSandboxInteractionTimeRef","resetToken","setResetToken","isFullscreen","setIsFullscreen","shouldInjectSandboxVendor","isBlackboardMode","shouldEnableScaling","shouldMeasureDynamicHeight","shouldProcessRootScreenHeight","prevHtmlRef","htmlContent","React","normalizedHtmlContent","originalRootHeightMeta","inspectViewportHeightFromHtmlRootString","EMPTY_ROOT_HEIGHT_META","shouldStretchRootHeight","renderHtmlContent","setRenderHtmlContent","prevIncomingHtmlRef","pendingHtmlRef","deferRenderTimerRef","initialPaintFrameRef","renderViewportHeightCssRef","emitSandboxInteraction","eventType","now","SANDBOX_INTERACTION_MESSAGE_SOURCE","SANDBOX_INTERACTION_MESSAGE_TYPE","useEffect","container","handleClick","clearDeferredRenderTimer","clearInitialPaintFrames","prevIncomingHtml","isAppendOnlyStream","containsCompleteImage","rootViewportHeightCss","hasRootVhHeight","sandboxViewportHeight","prev","iframe","doc","CJK_SAFE_SANS_FONT_FAMILY","shouldBridgeSandboxInteraction","handleSandboxClick","rootEl","root","createRoot","isDestroyed","getHeightInspectionNode","getSingleChildElement","childElements","resolveExplicitHeight","parentViewportHeight","precomputedViewportHeightCss","parsed","parseExplicitHeight","containerChildren","rootContentElement","runtimeViewportHeightCss","inspectViewportHeightFromNodeChain","runtimeViewportHeight","explicitPixelHeight","resolveExplicitHeightFromNodeChain","updateHeight","cw","prevH","minH","maxH","measuredH","iframeWin","getInnerScrollableHeight","walk","el","style","oy","rect","child","i","nextH","next","scheduleHeightUpdate","bodyScrollH","htmlScrollH","rootScrollH","measuredHeight","explicitHeight","nextHeight","prevHeight","injectBlackboardLibraries","injectScalingSystem","hostElement","needsTailwindRefreshAfterHidden","isTailwindRefreshQueued","tailwindRefreshFrame","tailwindRefreshTimer","runPostTailwindRefreshLayout","isHostVisible","queueTailwindRefreshAfterHidden","refreshTailwindRuntime","sandboxContainer","canObserveResize","hostResizeObserver","entries","contentRect","hostWidth","hostHeight","resizeObserver","syncSandboxContentDirection","wrapper","view","nextDirection","currentDirection","mutationObserver","onFullscreenChange","button","updateControlHeight","ro","hostEntry","entry","contentModeStyle","useMemo","contentIframeHeight","toggleFullscreen","target","jsx","SandboxApp","t1","t2","containerClassName","jsxs","ContentRender","IframeSandbox","props","lifecycleKey"],"mappings":";;;;;;;;;;;;;AAsCA,IAAIA,KAAkE;AAEtE,MAAMC,KAAuB,OACtBD,OACHA,KAA0B,OAAO,2BAAqB,IAGjDA,KAGHE,KAA6B,iBAC7BC,KAAgC,KAChCC,KAAkC,KAuBlCC,KAA+B,CAACC,MACpCA,EACG,MAAM,KAAK,EACX,OAAO,OAAO,EACd,IAAI,CAACC,MAAU;AACd,QAAMC,IAAWD,EAAM,MAAM,GAAG;AAChC,SACEC,EAASA,EAAS,SAAS,CAAC,MAAM,cAClCA,EAASA,EAAS,SAAS,CAAC,MAAM,iBAE3BD,KAETC,EAASA,EAAS,SAAS,CAAC,IAAI,UACzBA,EAAS,KAAK,GAAG;AAC1B,CAAC,EACA,KAAK,GAAG,GAEPC,KAAuC,CAC3CC,GACAC,MAEI,CAACA,KAAW,CAACD,EAAK,SACbA,IAGFA,EAAK;AAAA,EACV;AAAA,EACA,CAACE,GAAOC,GAAkBC,IAAQ,OAAO;AACvC,UAAMC,IAAaD,EAAM,MAAM,iCAAiC;AAEhE,QAAI,CAACC;AACH,aAAOH;AAGT,UAAMI,IAAgBX,GAA6BU,EAAW,CAAC,CAAC;AAEhE,WAAIC,MAAkBD,EAAW,CAAC,IACzBH,IAGF,GAAGC,CAAQ,GAAGC,EAAM;AAAA,MACzBC,EAAW,CAAC;AAAA,MACZ,SAASA,EAAW,CAAC,CAAC,GAAGC,CAAa,GAAGD,EAAW,CAAC,CAAC;AAAA,IAAA,CACvD;AAAA,EACH;AAAA,GAIEE,KAAsD,CAAC;AAAA,EAC3D,SAAAC;AAAA,EACA,MAAAC;AAAA,EACA,WAAAb;AAAA,EACA,QAAAc;AAAA,EACA,MAAAC;AAAA,EACA,KAAAC;AAAA,EACA,aAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,mBAAAC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B,WAAW,UAAU;AAEzF,SAAO,gBAAAwH,EAACvL,IAAA,EAA0C,GAAG+L,EAAA,GAAlBC,CAAyB;AAC9D;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),d=require("react"),u=require("../../../node_modules/rc-textarea/es/TextArea.cjs");require("../../../_virtual/
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),d=require("react"),u=require("../../../node_modules/rc-textarea/es/TextArea.cjs");require("../../../_virtual/index4.cjs");require("../../../node_modules/rc-resize-observer/es/index.cjs");require("../../../node_modules/rc-util/es/hooks/useLayoutEffect.cjs");require("../../../node_modules/rc-util/es/raf.cjs");const s=require("../../../lib/utils.cjs");function c(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const l=c(d),i=l.forwardRef(({className:e,autoSize:t={minRows:1},style:r,...a},n)=>o.jsx(u.default,{ref:n,autoSize:t,className:s.cn("border-input placeholder:text-muted-foreground aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 w-full rounded-md border bg-transparent pl-3 py-1.5 text-base shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50","resize-none",e),style:{whiteSpace:"pre-wrap",wordBreak:"break-word",...r},...a}));i.displayName="Textarea";exports.Textarea=i;
|
|
2
2
|
//# sourceMappingURL=textarea.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsx as i } from "react/jsx-runtime";
|
|
2
2
|
import * as d from "react";
|
|
3
3
|
import n from "../../../node_modules/rc-textarea/es/TextArea.es.js";
|
|
4
|
-
import "../../../_virtual/index.
|
|
4
|
+
import "../../../_virtual/index.es4.js";
|
|
5
5
|
import "../../../node_modules/rc-resize-observer/es/index.es.js";
|
|
6
6
|
import "../../../node_modules/rc-util/es/hooks/useLayoutEffect.es.js";
|
|
7
7
|
import "../../../node_modules/rc-util/es/raf.es.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("../_virtual/index.cjs"),b=p.distExports.createInteractionParser(),I=/<custom-variable\b/i,T=new RegExp(`\\?\\[
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("../_virtual/index.cjs"),b=p.distExports.createInteractionParser(),I=/<custom-variable\b/i,T=new RegExp(`\\?\\[(?:%\\{\\{([^}]+)\\}\\})?(${p.distExports.INTERACTION_CONTENT_SOURCE})\\]`),g=/^[\[{]/,v=/^[\s,,\n]+/,E=t=>{if(!t)return null;const n=t.match(T),s=n?.[1]?.trim(),e=n?.[2]?.trim();if(!e)return null;const r=e.includes("||"),l=r?"||":"|",u=e.split(l).map(a=>a.trim()).filter(Boolean);if(!u.length)return null;const i=[],o=[];let c;return u.forEach(a=>{if(a.startsWith("...")){const f=a.replace(/^\.\.\./,"").trim();f&&(c=f);return}i.push(a),o.push(a)}),{variableName:s,buttonTexts:i.length?i:void 0,buttonValues:o.length?o:void 0,placeholder:c,isMultiSelect:r}},V=t=>{if(!t)return null;try{return b.parseToRemarkFormat(t)}catch(n){console.warn("Failed to parse interaction block",n)}return E(t)},h=(t,n)=>{if(!t)return null;const s=t.trim(),e=n.buttonValues||[],r=n.buttonTexts||[],l=e.indexOf(s);if(l>-1)return{value:e[l],display:r[l]};const u=r.indexOf(s);return u>-1?{value:e[u]||r[u],display:r[u]}:null},S=t=>t.split(/[,,\n]/).map(n=>n.trim()).filter(Boolean),d=t=>t.replace(v,""),R=t=>{const n=t.buttonValues||[],s=t.buttonTexts||[],e=[],r=new Set;return n.forEach((l,u)=>{const i=`${l??""}`.trim(),o=`${s[u]??""}`.trim();[i,o].forEach(c=>{if(!c)return;const a=`${c}::${i||c}`;r.has(a)||(r.add(a),e.push({token:c,value:i||c}))})}),e.sort((l,u)=>u.token.length-l.token.length)},A=(t,n)=>{const s=d(t),e=R(n);for(const r of e){if(!s.startsWith(r.token))continue;const l=s[r.token.length];if(!(l&&!/[\s,,\n]/.test(l)))return r}return null},N=(t,n)=>{const s=S(t);if(!s.length)return{};const e=[],r=[];return s.forEach(l=>{const u=h(l,n);if(u){e.push(u.value);return}if(n.placeholder){r.push(l);return}e.push(l)}),{selectedValues:e.length?e:void 0,inputText:r.length?r.join(", "):void 0}},O=(t,n)=>{const s=[];let e=t.trim();for(;e;){const l=A(e,n);if(!l)break;s.push(l.value);const u=d(e);e=d(u.slice(l.token.length))}if(s.length>0)return{selectedValues:s,inputText:n.placeholder&&e.trim()?e.trim():void 0};const r=N(t,n);return r.selectedValues?.length?r:n.placeholder?{inputText:t.trim()}:r},D=t=>{if(!t||Array.isArray(t))return null;const n=Array.isArray(t.selectedValues)?t.selectedValues.map(r=>`${r??""}`.trim()).filter(Boolean):void 0,s=`${t.buttonText??""}`.trim(),e=typeof t.inputText=="string"?t.inputText:void 0;return!n?.length&&!s&&!e?null:{buttonText:s||void 0,inputText:e,selectedValues:n?.length?n:void 0}},C=t=>{if(!t||!g.test(t.trim()))return null;try{const n=JSON.parse(t);return D(n)}catch{return null}},P=t=>!!(t&&(I.test(t)||T.test(t))),m=(t,n,s,e)=>e?.resolveDefaultValues?.({content:t,rawValue:n,interactionInfo:s})??null,x=(t,n,s)=>{const e=n?.toString().trim();if(!e)return{};const r=C(e);if(r)return r;const l=m(t,e,null,s);if(l)return l;if(!P(t))return{buttonText:e,inputText:e};const u=V(t),i=m(t,e,u,s);if(i)return i;if(!u)return{buttonText:e,inputText:e};if(u.isMultiSelect)return O(e,u);const o=h(e,u);return o?{buttonText:o.value||o.display||e}:u.placeholder?{inputText:e}:{buttonText:e,inputText:e}},_=(t,n,s)=>{const e=x(t,n,s);return e.selectedValues?e.selectedValues:n?n.split(",").map(r=>r.trim()).filter(Boolean):void 0};exports.getInteractionDefaultSelectedValues=_;exports.getInteractionDefaultValues=x;
|
|
2
2
|
//# sourceMappingURL=interaction-defaults.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interaction-defaults.cjs","sources":["../../src/lib/interaction-defaults.ts"],"sourcesContent":["import {\n createInteractionParser,\n INTERACTION_CONTENT_SOURCE,\n} from \"remark-flow\";\n\nexport interface InteractionParseResult {\n buttonTexts?: string[];\n buttonValues?: string[];\n placeholder?: string;\n variableName?: string;\n isMultiSelect?: boolean;\n}\n\nexport interface InteractionDefaultValues {\n buttonText?: string;\n inputText?: string;\n selectedValues?: string[];\n}\n\nexport interface InteractionDefaultResolverParams {\n content?: string | null;\n rawValue?: string | null;\n interactionInfo?: InteractionParseResult | null;\n}\n\nexport type InteractionDefaultResolver = (\n params: InteractionDefaultResolverParams\n) => InteractionDefaultValues | null | undefined;\n\nexport interface InteractionDefaultValueOptions {\n resolveDefaultValues?: InteractionDefaultResolver;\n}\n\ninterface StructuredInteractionPayload {\n buttonText?: unknown;\n inputText?: unknown;\n selectedValues?: unknown;\n}\n\nconst interactionParser = createInteractionParser();\nconst INTERACTION_TAG_PATTERN = /<custom-variable\\b/i;\n// Same definition of where an interaction ends as the parser uses, so an option carrying a\n// `\\]` is read whole instead of being cut at its first bracket.\nconst INTERACTION_SHORTCODE_PATTERN = new RegExp(\n `\\\\?\\\\[%\\\\{\\\\{([^}]+)\\\\}\\\\}(${INTERACTION_CONTENT_SOURCE})\\\\]`\n);\nconst JSON_LIKE_VALUE_PATTERN = /^[\\[{]/;\nconst INTERACTION_VALUE_SEPARATOR_PATTERN = /^[\\s,,\\n]+/;\n\ninterface InteractionOptionCandidate {\n token: string;\n value: string;\n}\n\nconst parseInteractionShortcode = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n const matched = content.match(INTERACTION_SHORTCODE_PATTERN);\n const variableName = matched?.[1]?.trim();\n const interactionBody = matched?.[2]?.trim();\n\n if (!interactionBody) {\n return null;\n }\n\n const isMultiSelect = interactionBody.includes(\"||\");\n const separator = isMultiSelect ? \"||\" : \"|\";\n const rawOptions = interactionBody\n .split(separator)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (!rawOptions.length) {\n return null;\n }\n\n const buttonTexts: string[] = [];\n const buttonValues: string[] = [];\n let placeholder: string | undefined;\n\n rawOptions.forEach((option) => {\n if (option.startsWith(\"...\")) {\n const normalizedPlaceholder = option.replace(/^\\.\\.\\./, \"\").trim();\n if (normalizedPlaceholder) {\n placeholder = normalizedPlaceholder;\n }\n return;\n }\n\n buttonTexts.push(option);\n buttonValues.push(option);\n });\n\n return {\n variableName,\n buttonTexts: buttonTexts.length ? buttonTexts : undefined,\n buttonValues: buttonValues.length ? buttonValues : undefined,\n placeholder,\n isMultiSelect,\n };\n};\n\nconst parseInteractionBlock = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n try {\n return interactionParser.parseToRemarkFormat(\n content\n ) as InteractionParseResult;\n } catch (error) {\n console.warn(\"Failed to parse interaction block\", error);\n }\n\n return parseInteractionShortcode(content);\n};\n\nconst normalizeButtonValue = (\n token: string,\n info: InteractionParseResult\n): { value: string; display?: string } | null => {\n if (!token) {\n return null;\n }\n\n const cleaned = token.trim();\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const valueIndex = buttonValues.indexOf(cleaned);\n\n if (valueIndex > -1) {\n return {\n value: buttonValues[valueIndex],\n display: buttonTexts[valueIndex],\n };\n }\n\n const textIndex = buttonTexts.indexOf(cleaned);\n\n if (textIndex > -1) {\n return {\n value: buttonValues[textIndex] || buttonTexts[textIndex],\n display: buttonTexts[textIndex],\n };\n }\n\n return null;\n};\n\nconst splitPresetValues = (raw: string) => {\n return raw\n .split(/[,,\\n]/)\n .map((item) => item.trim())\n .filter(Boolean);\n};\n\nconst trimLeadingInteractionSeparators = (raw: string) =>\n raw.replace(INTERACTION_VALUE_SEPARATOR_PATTERN, \"\");\n\nconst buildInteractionOptionCandidates = (\n info: InteractionParseResult\n): InteractionOptionCandidate[] => {\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const candidates: InteractionOptionCandidate[] = [];\n const seenCandidates = new Set<string>();\n\n buttonValues.forEach((buttonValue, index) => {\n const normalizedValue = `${buttonValue ?? \"\"}`.trim();\n const normalizedText = `${buttonTexts[index] ?? \"\"}`.trim();\n\n [normalizedValue, normalizedText].forEach((token) => {\n if (!token) {\n return;\n }\n\n const candidateKey = `${token}::${normalizedValue || token}`;\n if (seenCandidates.has(candidateKey)) {\n return;\n }\n\n seenCandidates.add(candidateKey);\n candidates.push({\n token,\n value: normalizedValue || token,\n });\n });\n });\n\n return candidates.sort(\n (left, right) => right.token.length - left.token.length\n );\n};\n\nconst matchInteractionOptionPrefix = (\n raw: string,\n info: InteractionParseResult\n): InteractionOptionCandidate | null => {\n const normalizedRaw = trimLeadingInteractionSeparators(raw);\n const candidates = buildInteractionOptionCandidates(info);\n\n for (const candidate of candidates) {\n if (!normalizedRaw.startsWith(candidate.token)) {\n continue;\n }\n\n const trailingChar = normalizedRaw[candidate.token.length];\n if (trailingChar && !/[\\s,,\\n]/.test(trailingChar)) {\n continue;\n }\n\n return candidate;\n }\n\n return null;\n};\n\nconst resolveMultiSelectFallbackDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const tokens = splitPresetValues(raw);\n\n if (!tokens.length) {\n return {};\n }\n\n const selectedValues: string[] = [];\n const customInputs: string[] = [];\n\n tokens.forEach((token) => {\n const mapped = normalizeButtonValue(token, info);\n\n if (mapped) {\n selectedValues.push(mapped.value);\n return;\n }\n\n if (info.placeholder) {\n customInputs.push(token);\n return;\n }\n\n selectedValues.push(token);\n });\n\n return {\n selectedValues: selectedValues.length ? selectedValues : undefined,\n inputText: customInputs.length ? customInputs.join(\", \") : undefined,\n };\n};\n\nconst resolveMultiSelectInteractionDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const selectedValues: string[] = [];\n let remainingRaw = raw.trim();\n\n // Prefer option-aware prefix matching before delimiter splitting so\n // option labels that contain commas can still round-trip correctly.\n while (remainingRaw) {\n const matchedCandidate = matchInteractionOptionPrefix(remainingRaw, info);\n\n if (!matchedCandidate) {\n break;\n }\n\n selectedValues.push(matchedCandidate.value);\n const normalizedRemainingRaw =\n trimLeadingInteractionSeparators(remainingRaw);\n remainingRaw = trimLeadingInteractionSeparators(\n normalizedRemainingRaw.slice(matchedCandidate.token.length)\n );\n }\n\n if (selectedValues.length > 0) {\n return {\n selectedValues,\n inputText:\n info.placeholder && remainingRaw.trim()\n ? remainingRaw.trim()\n : undefined,\n };\n }\n\n const fallbackDefaults = resolveMultiSelectFallbackDefaults(raw, info);\n\n if (fallbackDefaults.selectedValues?.length) {\n return fallbackDefaults;\n }\n\n if (info.placeholder) {\n return {\n inputText: raw.trim(),\n };\n }\n\n return fallbackDefaults;\n};\n\nconst normalizeStructuredInteractionDefaults = (\n payload?: StructuredInteractionPayload | null\n): InteractionDefaultValues | null => {\n if (!payload || Array.isArray(payload)) {\n return null;\n }\n\n const selectedValues = Array.isArray(payload.selectedValues)\n ? payload.selectedValues\n .map((item) => `${item ?? \"\"}`.trim())\n .filter(Boolean)\n : undefined;\n const buttonText = `${payload.buttonText ?? \"\"}`.trim();\n const inputText =\n typeof payload.inputText === \"string\" ? payload.inputText : undefined;\n\n if (!selectedValues?.length && !buttonText && !inputText) {\n return null;\n }\n\n return {\n buttonText: buttonText || undefined,\n inputText,\n selectedValues: selectedValues?.length ? selectedValues : undefined,\n };\n};\n\nconst parseStructuredInteractionDefaults = (rawValue?: string | null) => {\n if (!rawValue) {\n return null;\n }\n\n if (!JSON_LIKE_VALUE_PATTERN.test(rawValue.trim())) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(rawValue) as StructuredInteractionPayload;\n return normalizeStructuredInteractionDefaults(parsed);\n } catch {\n return null;\n }\n};\n\nconst hasPotentialInteractionBlock = (content?: string | null) =>\n Boolean(\n content &&\n (INTERACTION_TAG_PATTERN.test(content) ||\n INTERACTION_SHORTCODE_PATTERN.test(content))\n );\n\nconst resolveCustomInteractionDefaults = (\n content?: string | null,\n rawValue?: string | null,\n interactionInfo?: InteractionParseResult | null,\n options?: InteractionDefaultValueOptions\n) => {\n return (\n options?.resolveDefaultValues?.({\n content,\n rawValue,\n interactionInfo,\n }) ?? null\n );\n};\n\nexport const getInteractionDefaultValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n): InteractionDefaultValues => {\n const normalized = rawValue?.toString().trim();\n\n if (!normalized) {\n return {};\n }\n\n const structuredDefaults = parseStructuredInteractionDefaults(normalized);\n\n if (structuredDefaults) {\n return structuredDefaults;\n }\n\n const customDefaults = resolveCustomInteractionDefaults(\n content,\n normalized,\n null,\n options\n );\n\n if (customDefaults) {\n return customDefaults;\n }\n\n if (!hasPotentialInteractionBlock(content)) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n const interactionInfo = parseInteractionBlock(content);\n const customDefaultsWithInteraction = resolveCustomInteractionDefaults(\n content,\n normalized,\n interactionInfo,\n options\n );\n\n if (customDefaultsWithInteraction) {\n return customDefaultsWithInteraction;\n }\n\n if (!interactionInfo) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n if (interactionInfo.isMultiSelect) {\n return resolveMultiSelectInteractionDefaults(normalized, interactionInfo);\n }\n\n const mapped = normalizeButtonValue(normalized, interactionInfo);\n\n if (mapped) {\n return {\n buttonText: mapped.value || mapped.display || normalized,\n };\n }\n\n if (interactionInfo.placeholder) {\n return {\n inputText: normalized,\n };\n }\n\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n};\n\nexport const getInteractionDefaultSelectedValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n) => {\n const defaults = getInteractionDefaultValues(content, rawValue, options);\n\n if (defaults.selectedValues) {\n return defaults.selectedValues;\n }\n\n return rawValue\n ? rawValue\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n : undefined;\n};\n"],"names":["interactionParser","createInteractionParser","INTERACTION_TAG_PATTERN","INTERACTION_SHORTCODE_PATTERN","INTERACTION_CONTENT_SOURCE","JSON_LIKE_VALUE_PATTERN","INTERACTION_VALUE_SEPARATOR_PATTERN","parseInteractionShortcode","content","matched","variableName","interactionBody","isMultiSelect","separator","rawOptions","item","buttonTexts","buttonValues","placeholder","option","normalizedPlaceholder","parseInteractionBlock","error","normalizeButtonValue","token","info","cleaned","valueIndex","textIndex","splitPresetValues","raw","trimLeadingInteractionSeparators","buildInteractionOptionCandidates","candidates","seenCandidates","buttonValue","index","normalizedValue","normalizedText","candidateKey","left","right","matchInteractionOptionPrefix","normalizedRaw","candidate","trailingChar","resolveMultiSelectFallbackDefaults","tokens","selectedValues","customInputs","mapped","resolveMultiSelectInteractionDefaults","remainingRaw","matchedCandidate","normalizedRemainingRaw","fallbackDefaults","normalizeStructuredInteractionDefaults","payload","buttonText","inputText","parseStructuredInteractionDefaults","rawValue","parsed","hasPotentialInteractionBlock","resolveCustomInteractionDefaults","interactionInfo","options","getInteractionDefaultValues","normalized","structuredDefaults","customDefaults","customDefaultsWithInteraction","getInteractionDefaultSelectedValues","defaults","value"],"mappings":"yHAuCMA,EAAoBC,EAAAA,YAAAA,wBAAA,EACpBC,EAA0B,sBAG1BC,EAAgC,IAAI,OACxC,8BAA8BC,EAAAA,YAAAA,0BAA0B,MAC1D,EACMC,EAA0B,SAC1BC,EAAsC,aAOtCC,EACJC,GACkC,CAClC,GAAI,CAACA,EACH,OAAO,KAGT,MAAMC,EAAUD,EAAQ,MAAML,CAA6B,EACrDO,EAAeD,IAAU,CAAC,GAAG,KAAA,EAC7BE,EAAkBF,IAAU,CAAC,GAAG,KAAA,EAEtC,GAAI,CAACE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B,EAAqB6C,EAAYH,CAAe,EAE/D,OAAIf,EACK,CACL,WAAYA,EAAO,OAASA,EAAO,SAAWkB,CAAA,EAI9CH,EAAgB,YACX,CACL,UAAWG,CAAA,EAIR,CACL,WAAYA,EACZ,UAAWA,CAAA,CAEf,EAEaI,EAAsC,CACjDhE,EACAqD,EACAK,IACG,CACH,MAAMO,EAAWN,EAA4B3D,EAASqD,EAAUK,CAAO,EAEvE,OAAIO,EAAS,eACJA,EAAS,eAGXZ,EACHA,EACG,MAAM,GAAG,EACT,IAAKa,GAAUA,EAAM,KAAA,CAAM,EAC3B,OAAO,OAAO,EACjB,MACN"}
|
|
1
|
+
{"version":3,"file":"interaction-defaults.cjs","sources":["../../src/lib/interaction-defaults.ts"],"sourcesContent":["import {\n createInteractionParser,\n INTERACTION_CONTENT_SOURCE,\n} from \"remark-flow\";\n\nexport interface InteractionParseResult {\n buttonTexts?: string[];\n buttonValues?: string[];\n placeholder?: string;\n variableName?: string;\n isMultiSelect?: boolean;\n}\n\nexport interface InteractionDefaultValues {\n buttonText?: string;\n inputText?: string;\n selectedValues?: string[];\n}\n\nexport interface InteractionDefaultResolverParams {\n content?: string | null;\n rawValue?: string | null;\n interactionInfo?: InteractionParseResult | null;\n}\n\nexport type InteractionDefaultResolver = (\n params: InteractionDefaultResolverParams\n) => InteractionDefaultValues | null | undefined;\n\nexport interface InteractionDefaultValueOptions {\n resolveDefaultValues?: InteractionDefaultResolver;\n}\n\ninterface StructuredInteractionPayload {\n buttonText?: unknown;\n inputText?: unknown;\n selectedValues?: unknown;\n}\n\nconst interactionParser = createInteractionParser();\nconst INTERACTION_TAG_PATTERN = /<custom-variable\\b/i;\n// Same definition of where an interaction ends as the parser uses, so an option carrying a\n// `\\]` is read whole instead of being cut at its first bracket. A variable assignment is optional.\nconst INTERACTION_SHORTCODE_PATTERN = new RegExp(\n `\\\\?\\\\[(?:%\\\\{\\\\{([^}]+)\\\\}\\\\})?(${INTERACTION_CONTENT_SOURCE})\\\\]`\n);\nconst JSON_LIKE_VALUE_PATTERN = /^[\\[{]/;\nconst INTERACTION_VALUE_SEPARATOR_PATTERN = /^[\\s,,\\n]+/;\n\ninterface InteractionOptionCandidate {\n token: string;\n value: string;\n}\n\nconst parseInteractionShortcode = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n const matched = content.match(INTERACTION_SHORTCODE_PATTERN);\n const variableName = matched?.[1]?.trim();\n const interactionBody = matched?.[2]?.trim();\n\n if (!interactionBody) {\n return null;\n }\n\n const isMultiSelect = interactionBody.includes(\"||\");\n const separator = isMultiSelect ? \"||\" : \"|\";\n const rawOptions = interactionBody\n .split(separator)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (!rawOptions.length) {\n return null;\n }\n\n const buttonTexts: string[] = [];\n const buttonValues: string[] = [];\n let placeholder: string | undefined;\n\n rawOptions.forEach((option) => {\n if (option.startsWith(\"...\")) {\n const normalizedPlaceholder = option.replace(/^\\.\\.\\./, \"\").trim();\n if (normalizedPlaceholder) {\n placeholder = normalizedPlaceholder;\n }\n return;\n }\n\n buttonTexts.push(option);\n buttonValues.push(option);\n });\n\n return {\n variableName,\n buttonTexts: buttonTexts.length ? buttonTexts : undefined,\n buttonValues: buttonValues.length ? buttonValues : undefined,\n placeholder,\n isMultiSelect,\n };\n};\n\nconst parseInteractionBlock = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n try {\n return interactionParser.parseToRemarkFormat(\n content\n ) as InteractionParseResult;\n } catch (error) {\n console.warn(\"Failed to parse interaction block\", error);\n }\n\n return parseInteractionShortcode(content);\n};\n\nconst normalizeButtonValue = (\n token: string,\n info: InteractionParseResult\n): { value: string; display?: string } | null => {\n if (!token) {\n return null;\n }\n\n const cleaned = token.trim();\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const valueIndex = buttonValues.indexOf(cleaned);\n\n if (valueIndex > -1) {\n return {\n value: buttonValues[valueIndex],\n display: buttonTexts[valueIndex],\n };\n }\n\n const textIndex = buttonTexts.indexOf(cleaned);\n\n if (textIndex > -1) {\n return {\n value: buttonValues[textIndex] || buttonTexts[textIndex],\n display: buttonTexts[textIndex],\n };\n }\n\n return null;\n};\n\nconst splitPresetValues = (raw: string) => {\n return raw\n .split(/[,,\\n]/)\n .map((item) => item.trim())\n .filter(Boolean);\n};\n\nconst trimLeadingInteractionSeparators = (raw: string) =>\n raw.replace(INTERACTION_VALUE_SEPARATOR_PATTERN, \"\");\n\nconst buildInteractionOptionCandidates = (\n info: InteractionParseResult\n): InteractionOptionCandidate[] => {\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const candidates: InteractionOptionCandidate[] = [];\n const seenCandidates = new Set<string>();\n\n buttonValues.forEach((buttonValue, index) => {\n const normalizedValue = `${buttonValue ?? \"\"}`.trim();\n const normalizedText = `${buttonTexts[index] ?? \"\"}`.trim();\n\n [normalizedValue, normalizedText].forEach((token) => {\n if (!token) {\n return;\n }\n\n const candidateKey = `${token}::${normalizedValue || token}`;\n if (seenCandidates.has(candidateKey)) {\n return;\n }\n\n seenCandidates.add(candidateKey);\n candidates.push({\n token,\n value: normalizedValue || token,\n });\n });\n });\n\n return candidates.sort(\n (left, right) => right.token.length - left.token.length\n );\n};\n\nconst matchInteractionOptionPrefix = (\n raw: string,\n info: InteractionParseResult\n): InteractionOptionCandidate | null => {\n const normalizedRaw = trimLeadingInteractionSeparators(raw);\n const candidates = buildInteractionOptionCandidates(info);\n\n for (const candidate of candidates) {\n if (!normalizedRaw.startsWith(candidate.token)) {\n continue;\n }\n\n const trailingChar = normalizedRaw[candidate.token.length];\n if (trailingChar && !/[\\s,,\\n]/.test(trailingChar)) {\n continue;\n }\n\n return candidate;\n }\n\n return null;\n};\n\nconst resolveMultiSelectFallbackDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const tokens = splitPresetValues(raw);\n\n if (!tokens.length) {\n return {};\n }\n\n const selectedValues: string[] = [];\n const customInputs: string[] = [];\n\n tokens.forEach((token) => {\n const mapped = normalizeButtonValue(token, info);\n\n if (mapped) {\n selectedValues.push(mapped.value);\n return;\n }\n\n if (info.placeholder) {\n customInputs.push(token);\n return;\n }\n\n selectedValues.push(token);\n });\n\n return {\n selectedValues: selectedValues.length ? selectedValues : undefined,\n inputText: customInputs.length ? customInputs.join(\", \") : undefined,\n };\n};\n\nconst resolveMultiSelectInteractionDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const selectedValues: string[] = [];\n let remainingRaw = raw.trim();\n\n // Prefer option-aware prefix matching before delimiter splitting so\n // option labels that contain commas can still round-trip correctly.\n while (remainingRaw) {\n const matchedCandidate = matchInteractionOptionPrefix(remainingRaw, info);\n\n if (!matchedCandidate) {\n break;\n }\n\n selectedValues.push(matchedCandidate.value);\n const normalizedRemainingRaw =\n trimLeadingInteractionSeparators(remainingRaw);\n remainingRaw = trimLeadingInteractionSeparators(\n normalizedRemainingRaw.slice(matchedCandidate.token.length)\n );\n }\n\n if (selectedValues.length > 0) {\n return {\n selectedValues,\n inputText:\n info.placeholder && remainingRaw.trim()\n ? remainingRaw.trim()\n : undefined,\n };\n }\n\n const fallbackDefaults = resolveMultiSelectFallbackDefaults(raw, info);\n\n if (fallbackDefaults.selectedValues?.length) {\n return fallbackDefaults;\n }\n\n if (info.placeholder) {\n return {\n inputText: raw.trim(),\n };\n }\n\n return fallbackDefaults;\n};\n\nconst normalizeStructuredInteractionDefaults = (\n payload?: StructuredInteractionPayload | null\n): InteractionDefaultValues | null => {\n if (!payload || Array.isArray(payload)) {\n return null;\n }\n\n const selectedValues = Array.isArray(payload.selectedValues)\n ? payload.selectedValues\n .map((item) => `${item ?? \"\"}`.trim())\n .filter(Boolean)\n : undefined;\n const buttonText = `${payload.buttonText ?? \"\"}`.trim();\n const inputText =\n typeof payload.inputText === \"string\" ? payload.inputText : undefined;\n\n if (!selectedValues?.length && !buttonText && !inputText) {\n return null;\n }\n\n return {\n buttonText: buttonText || undefined,\n inputText,\n selectedValues: selectedValues?.length ? selectedValues : undefined,\n };\n};\n\nconst parseStructuredInteractionDefaults = (rawValue?: string | null) => {\n if (!rawValue) {\n return null;\n }\n\n if (!JSON_LIKE_VALUE_PATTERN.test(rawValue.trim())) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(rawValue) as StructuredInteractionPayload;\n return normalizeStructuredInteractionDefaults(parsed);\n } catch {\n return null;\n }\n};\n\nconst hasPotentialInteractionBlock = (content?: string | null) =>\n Boolean(\n content &&\n (INTERACTION_TAG_PATTERN.test(content) ||\n INTERACTION_SHORTCODE_PATTERN.test(content))\n );\n\nconst resolveCustomInteractionDefaults = (\n content?: string | null,\n rawValue?: string | null,\n interactionInfo?: InteractionParseResult | null,\n options?: InteractionDefaultValueOptions\n) => {\n return (\n options?.resolveDefaultValues?.({\n content,\n rawValue,\n interactionInfo,\n }) ?? null\n );\n};\n\nexport const getInteractionDefaultValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n): InteractionDefaultValues => {\n const normalized = rawValue?.toString().trim();\n\n if (!normalized) {\n return {};\n }\n\n const structuredDefaults = parseStructuredInteractionDefaults(normalized);\n\n if (structuredDefaults) {\n return structuredDefaults;\n }\n\n const customDefaults = resolveCustomInteractionDefaults(\n content,\n normalized,\n null,\n options\n );\n\n if (customDefaults) {\n return customDefaults;\n }\n\n if (!hasPotentialInteractionBlock(content)) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n const interactionInfo = parseInteractionBlock(content);\n const customDefaultsWithInteraction = resolveCustomInteractionDefaults(\n content,\n normalized,\n interactionInfo,\n options\n );\n\n if (customDefaultsWithInteraction) {\n return customDefaultsWithInteraction;\n }\n\n if (!interactionInfo) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n if (interactionInfo.isMultiSelect) {\n return resolveMultiSelectInteractionDefaults(normalized, interactionInfo);\n }\n\n const mapped = normalizeButtonValue(normalized, interactionInfo);\n\n if (mapped) {\n return {\n buttonText: mapped.value || mapped.display || normalized,\n };\n }\n\n if (interactionInfo.placeholder) {\n return {\n inputText: normalized,\n };\n }\n\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n};\n\nexport const getInteractionDefaultSelectedValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n) => {\n const defaults = getInteractionDefaultValues(content, rawValue, options);\n\n if (defaults.selectedValues) {\n return defaults.selectedValues;\n }\n\n return rawValue\n ? rawValue\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n : undefined;\n};\n"],"names":["interactionParser","createInteractionParser","INTERACTION_TAG_PATTERN","INTERACTION_SHORTCODE_PATTERN","INTERACTION_CONTENT_SOURCE","JSON_LIKE_VALUE_PATTERN","INTERACTION_VALUE_SEPARATOR_PATTERN","parseInteractionShortcode","content","matched","variableName","interactionBody","isMultiSelect","separator","rawOptions","item","buttonTexts","buttonValues","placeholder","option","normalizedPlaceholder","parseInteractionBlock","error","normalizeButtonValue","token","info","cleaned","valueIndex","textIndex","splitPresetValues","raw","trimLeadingInteractionSeparators","buildInteractionOptionCandidates","candidates","seenCandidates","buttonValue","index","normalizedValue","normalizedText","candidateKey","left","right","matchInteractionOptionPrefix","normalizedRaw","candidate","trailingChar","resolveMultiSelectFallbackDefaults","tokens","selectedValues","customInputs","mapped","resolveMultiSelectInteractionDefaults","remainingRaw","matchedCandidate","normalizedRemainingRaw","fallbackDefaults","normalizeStructuredInteractionDefaults","payload","buttonText","inputText","parseStructuredInteractionDefaults","rawValue","parsed","hasPotentialInteractionBlock","resolveCustomInteractionDefaults","interactionInfo","options","getInteractionDefaultValues","normalized","structuredDefaults","customDefaults","customDefaultsWithInteraction","getInteractionDefaultSelectedValues","defaults","value"],"mappings":"yHAuCMA,EAAoBC,EAAAA,YAAAA,wBAAA,EACpBC,EAA0B,sBAG1BC,EAAgC,IAAI,OACxC,mCAAmCC,EAAAA,YAAAA,0BAA0B,MAC/D,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O,EAC/C+D,EAAgCP,EACpCxD,EACA4D,EACAH,EACAC,CAAA,EAGF,GAAIK,EACF,OAAOA,EAGT,GAAI,CAACN,EACH,MAAO,CACL,WAAYG,EACZ,UAAWA,CAAA,EAIf,GAAIH,EAAgB,cAClB,OAAOd,EAAsCiB,EAAYH,CAAe,EAG1E,MAAMf,EAAS3B,EAAqB6C,EAAYH,CAAe,EAE/D,OAAIf,EACK,CACL,WAAYA,EAAO,OAASA,EAAO,SAAWkB,CAAA,EAI9CH,EAAgB,YACX,CACL,UAAWG,CAAA,EAIR,CACL,WAAYA,EACZ,UAAWA,CAAA,CAEf,EAEaI,EAAsC,CACjDhE,EACAqD,EACAK,IACG,CACH,MAAMO,EAAWN,EAA4B3D,EAASqD,EAAUK,CAAO,EAEvE,OAAIO,EAAS,eACJA,EAAS,eAGXZ,EACHA,EACG,MAAM,GAAG,EACT,IAAKa,GAAUA,EAAM,KAAA,CAAM,EAC3B,OAAO,OAAO,EACjB,MACN"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { d as p } from "../_virtual/index.es.js";
|
|
2
2
|
const x = p.createInteractionParser(), b = /<custom-variable\b/i, T = new RegExp(
|
|
3
|
-
`\\?\\[
|
|
3
|
+
`\\?\\[(?:%\\{\\{([^}]+)\\}\\})?(${p.INTERACTION_CONTENT_SOURCE})\\]`
|
|
4
4
|
), I = /^[\[{]/, g = /^[\s,,\n]+/, v = (t) => {
|
|
5
5
|
if (!t)
|
|
6
6
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interaction-defaults.es.js","sources":["../../src/lib/interaction-defaults.ts"],"sourcesContent":["import {\n createInteractionParser,\n INTERACTION_CONTENT_SOURCE,\n} from \"remark-flow\";\n\nexport interface InteractionParseResult {\n buttonTexts?: string[];\n buttonValues?: string[];\n placeholder?: string;\n variableName?: string;\n isMultiSelect?: boolean;\n}\n\nexport interface InteractionDefaultValues {\n buttonText?: string;\n inputText?: string;\n selectedValues?: string[];\n}\n\nexport interface InteractionDefaultResolverParams {\n content?: string | null;\n rawValue?: string | null;\n interactionInfo?: InteractionParseResult | null;\n}\n\nexport type InteractionDefaultResolver = (\n params: InteractionDefaultResolverParams\n) => InteractionDefaultValues | null | undefined;\n\nexport interface InteractionDefaultValueOptions {\n resolveDefaultValues?: InteractionDefaultResolver;\n}\n\ninterface StructuredInteractionPayload {\n buttonText?: unknown;\n inputText?: unknown;\n selectedValues?: unknown;\n}\n\nconst interactionParser = createInteractionParser();\nconst INTERACTION_TAG_PATTERN = /<custom-variable\\b/i;\n// Same definition of where an interaction ends as the parser uses, so an option carrying a\n// `\\]` is read whole instead of being cut at its first bracket.\nconst INTERACTION_SHORTCODE_PATTERN = new RegExp(\n `\\\\?\\\\[%\\\\{\\\\{([^}]+)\\\\}\\\\}(${INTERACTION_CONTENT_SOURCE})\\\\]`\n);\nconst JSON_LIKE_VALUE_PATTERN = /^[\\[{]/;\nconst INTERACTION_VALUE_SEPARATOR_PATTERN = /^[\\s,,\\n]+/;\n\ninterface InteractionOptionCandidate {\n token: string;\n value: string;\n}\n\nconst parseInteractionShortcode = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n const matched = content.match(INTERACTION_SHORTCODE_PATTERN);\n const variableName = matched?.[1]?.trim();\n const interactionBody = matched?.[2]?.trim();\n\n if (!interactionBody) {\n return null;\n }\n\n const isMultiSelect = interactionBody.includes(\"||\");\n const separator = isMultiSelect ? \"||\" : \"|\";\n const rawOptions = interactionBody\n .split(separator)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (!rawOptions.length) {\n return null;\n }\n\n const buttonTexts: string[] = [];\n const buttonValues: string[] = [];\n let placeholder: string | undefined;\n\n rawOptions.forEach((option) => {\n if (option.startsWith(\"...\")) {\n const normalizedPlaceholder = option.replace(/^\\.\\.\\./, \"\").trim();\n if (normalizedPlaceholder) {\n placeholder = normalizedPlaceholder;\n }\n return;\n }\n\n buttonTexts.push(option);\n buttonValues.push(option);\n });\n\n return {\n variableName,\n buttonTexts: buttonTexts.length ? buttonTexts : undefined,\n buttonValues: buttonValues.length ? buttonValues : undefined,\n placeholder,\n isMultiSelect,\n };\n};\n\nconst parseInteractionBlock = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n try {\n return interactionParser.parseToRemarkFormat(\n content\n ) as InteractionParseResult;\n } catch (error) {\n console.warn(\"Failed to parse interaction block\", error);\n }\n\n return parseInteractionShortcode(content);\n};\n\nconst normalizeButtonValue = (\n token: string,\n info: InteractionParseResult\n): { value: string; display?: string } | null => {\n if (!token) {\n return null;\n }\n\n const cleaned = token.trim();\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const valueIndex = buttonValues.indexOf(cleaned);\n\n if (valueIndex > -1) {\n return {\n value: buttonValues[valueIndex],\n display: buttonTexts[valueIndex],\n };\n }\n\n const textIndex = buttonTexts.indexOf(cleaned);\n\n if (textIndex > -1) {\n return {\n value: buttonValues[textIndex] || buttonTexts[textIndex],\n display: buttonTexts[textIndex],\n };\n }\n\n return null;\n};\n\nconst splitPresetValues = (raw: string) => {\n return raw\n .split(/[,,\\n]/)\n .map((item) => item.trim())\n .filter(Boolean);\n};\n\nconst trimLeadingInteractionSeparators = (raw: string) =>\n raw.replace(INTERACTION_VALUE_SEPARATOR_PATTERN, \"\");\n\nconst buildInteractionOptionCandidates = (\n info: InteractionParseResult\n): InteractionOptionCandidate[] => {\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const candidates: InteractionOptionCandidate[] = [];\n const seenCandidates = new Set<string>();\n\n buttonValues.forEach((buttonValue, index) => {\n const normalizedValue = `${buttonValue ?? \"\"}`.trim();\n const normalizedText = `${buttonTexts[index] ?? \"\"}`.trim();\n\n [normalizedValue, normalizedText].forEach((token) => {\n if (!token) {\n return;\n }\n\n const candidateKey = `${token}::${normalizedValue || token}`;\n if (seenCandidates.has(candidateKey)) {\n return;\n }\n\n seenCandidates.add(candidateKey);\n candidates.push({\n token,\n value: normalizedValue || token,\n });\n });\n });\n\n return candidates.sort(\n (left, right) => right.token.length - left.token.length\n );\n};\n\nconst matchInteractionOptionPrefix = (\n raw: string,\n info: InteractionParseResult\n): InteractionOptionCandidate | null => {\n const normalizedRaw = trimLeadingInteractionSeparators(raw);\n const candidates = buildInteractionOptionCandidates(info);\n\n for (const candidate of candidates) {\n if (!normalizedRaw.startsWith(candidate.token)) {\n continue;\n }\n\n const trailingChar = normalizedRaw[candidate.token.length];\n if (trailingChar && !/[\\s,,\\n]/.test(trailingChar)) {\n continue;\n }\n\n return candidate;\n }\n\n return null;\n};\n\nconst resolveMultiSelectFallbackDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const tokens = splitPresetValues(raw);\n\n if (!tokens.length) {\n return {};\n }\n\n const selectedValues: string[] = [];\n const customInputs: string[] = [];\n\n tokens.forEach((token) => {\n const mapped = normalizeButtonValue(token, info);\n\n if (mapped) {\n selectedValues.push(mapped.value);\n return;\n }\n\n if (info.placeholder) {\n customInputs.push(token);\n return;\n }\n\n selectedValues.push(token);\n });\n\n return {\n selectedValues: selectedValues.length ? selectedValues : undefined,\n inputText: customInputs.length ? customInputs.join(\", \") : undefined,\n };\n};\n\nconst resolveMultiSelectInteractionDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const selectedValues: string[] = [];\n let remainingRaw = raw.trim();\n\n // Prefer option-aware prefix matching before delimiter splitting so\n // option labels that contain commas can still round-trip correctly.\n while (remainingRaw) {\n const matchedCandidate = matchInteractionOptionPrefix(remainingRaw, info);\n\n if (!matchedCandidate) {\n break;\n }\n\n selectedValues.push(matchedCandidate.value);\n const normalizedRemainingRaw =\n trimLeadingInteractionSeparators(remainingRaw);\n remainingRaw = trimLeadingInteractionSeparators(\n normalizedRemainingRaw.slice(matchedCandidate.token.length)\n );\n }\n\n if (selectedValues.length > 0) {\n return {\n selectedValues,\n inputText:\n info.placeholder && remainingRaw.trim()\n ? remainingRaw.trim()\n : undefined,\n };\n }\n\n const fallbackDefaults = resolveMultiSelectFallbackDefaults(raw, info);\n\n if (fallbackDefaults.selectedValues?.length) {\n return fallbackDefaults;\n }\n\n if (info.placeholder) {\n return {\n inputText: raw.trim(),\n };\n }\n\n return fallbackDefaults;\n};\n\nconst normalizeStructuredInteractionDefaults = (\n payload?: StructuredInteractionPayload | null\n): InteractionDefaultValues | null => {\n if (!payload || Array.isArray(payload)) {\n return null;\n }\n\n const selectedValues = Array.isArray(payload.selectedValues)\n ? payload.selectedValues\n .map((item) => `${item ?? \"\"}`.trim())\n .filter(Boolean)\n : undefined;\n const buttonText = `${payload.buttonText ?? \"\"}`.trim();\n const inputText =\n typeof payload.inputText === \"string\" ? payload.inputText : undefined;\n\n if (!selectedValues?.length && !buttonText && !inputText) {\n return null;\n }\n\n return {\n buttonText: buttonText || undefined,\n inputText,\n selectedValues: selectedValues?.length ? selectedValues : undefined,\n };\n};\n\nconst parseStructuredInteractionDefaults = (rawValue?: string | null) => {\n if (!rawValue) {\n return null;\n }\n\n if (!JSON_LIKE_VALUE_PATTERN.test(rawValue.trim())) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(rawValue) as StructuredInteractionPayload;\n return normalizeStructuredInteractionDefaults(parsed);\n } catch {\n return null;\n }\n};\n\nconst hasPotentialInteractionBlock = (content?: string | null) =>\n Boolean(\n content &&\n (INTERACTION_TAG_PATTERN.test(content) ||\n INTERACTION_SHORTCODE_PATTERN.test(content))\n );\n\nconst resolveCustomInteractionDefaults = (\n content?: string | null,\n rawValue?: string | null,\n interactionInfo?: InteractionParseResult | null,\n options?: InteractionDefaultValueOptions\n) => {\n return (\n options?.resolveDefaultValues?.({\n content,\n rawValue,\n interactionInfo,\n }) ?? null\n );\n};\n\nexport const getInteractionDefaultValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n): InteractionDefaultValues => {\n const normalized = rawValue?.toString().trim();\n\n if (!normalized) {\n return {};\n }\n\n const structuredDefaults = parseStructuredInteractionDefaults(normalized);\n\n if (structuredDefaults) {\n return structuredDefaults;\n }\n\n const customDefaults = resolveCustomInteractionDefaults(\n content,\n normalized,\n null,\n options\n );\n\n if (customDefaults) {\n return customDefaults;\n }\n\n if (!hasPotentialInteractionBlock(content)) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n const interactionInfo = parseInteractionBlock(content);\n const customDefaultsWithInteraction = resolveCustomInteractionDefaults(\n content,\n normalized,\n interactionInfo,\n options\n );\n\n if (customDefaultsWithInteraction) {\n return customDefaultsWithInteraction;\n }\n\n if (!interactionInfo) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n if (interactionInfo.isMultiSelect) {\n return resolveMultiSelectInteractionDefaults(normalized, interactionInfo);\n }\n\n const mapped = normalizeButtonValue(normalized, interactionInfo);\n\n if (mapped) {\n return {\n buttonText: mapped.value || mapped.display || normalized,\n };\n }\n\n if (interactionInfo.placeholder) {\n return {\n inputText: normalized,\n };\n }\n\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n};\n\nexport const getInteractionDefaultSelectedValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n) => {\n const defaults = getInteractionDefaultValues(content, rawValue, options);\n\n if (defaults.selectedValues) {\n return defaults.selectedValues;\n }\n\n return rawValue\n ? rawValue\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n : undefined;\n};\n"],"names":["interactionParser","createInteractionParser","INTERACTION_TAG_PATTERN","INTERACTION_SHORTCODE_PATTERN","INTERACTION_CONTENT_SOURCE","JSON_LIKE_VALUE_PATTERN","INTERACTION_VALUE_SEPARATOR_PATTERN","parseInteractionShortcode","content","matched","variableName","interactionBody","isMultiSelect","separator","rawOptions","item","buttonTexts","buttonValues","placeholder","option","normalizedPlaceholder","parseInteractionBlock","error","normalizeButtonValue","token","info","cleaned","valueIndex","textIndex","splitPresetValues","raw","trimLeadingInteractionSeparators","buildInteractionOptionCandidates","candidates","seenCandidates","buttonValue","index","normalizedValue","normalizedText","candidateKey","left","right","matchInteractionOptionPrefix","normalizedRaw","candidate","trailingChar","resolveMultiSelectFallbackDefaults","tokens","selectedValues","customInputs","mapped","resolveMultiSelectInteractionDefaults","remainingRaw","matchedCandidate","normalizedRemainingRaw","fallbackDefaults","normalizeStructuredInteractionDefaults","payload","buttonText","inputText","parseStructuredInteractionDefaults","rawValue","parsed","hasPotentialInteractionBlock","resolveCustomInteractionDefaults","interactionInfo","options","getInteractionDefaultValues","normalized","structuredDefaults","customDefaults","customDefaultsWithInteraction","getInteractionDefaultSelectedValues","defaults","value"],"mappings":";AAuCA,MAAMA,IAAoBC,EAAAA,wBAAA,GACpBC,IAA0B,uBAG1BC,IAAgC,IAAI;AAAA,EACxC,8BAA8BC,EAAAA,0BAA0B;AAC1D,GACMC,IAA0B,UAC1BC,IAAsC,cAOtCC,IAA4B,CAChCC,MACkC;AAClC,MAAI,CAACA;AACH,WAAO;AAGT,QAAMC,IAAUD,EAAQ,MAAML,CAA6B,GACrDO,IAAeD,IAAU,CAAC,GAAG,KAAA,GAC7BE,IAAkBF,IAAU,CAAC,GAAG,KAAA;AAEtC,MAAI,CAACE;AACH,WAAO;AAGT,QAAMC,IAAgBD,EAAgB,SAAS,IAAI,GAC7CE,IAAYD,IAAgB,OAAO,KACnCE,IAAaH,EAChB,MAAME,CAAS,EACf,IAAI,CAACE,MAASA,EAAK,KAAA,CAAM,EACzB,OAAO,OAAO;AAEjB,MAAI,CAACD,EAAW;AACd,WAAO;AAGT,QAAME,IAAwB,CAAA,GACxBC,IAAyB,CAAA;AAC/B,MAAIC;AAEJ,SAAAJ,EAAW,QAAQ,CAACK,MAAW;AAC7B,QAAIA,EAAO,WAAW,KAAK,GAAG;AAC5B,YAAMC,IAAwBD,EAAO,QAAQ,WAAW,EAAE,EAAE,KAAA;AAC5D,MAAIC,MACFF,IAAcE;AAEhB;AAAA,IACF;AAEA,IAAAJ,EAAY,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EAAgB;AAClB,WAAOd,EAAsCiB,GAAYH,CAAe;AAG1E,QAAMf,IAAS3B,EAAqB6C,GAAYH,CAAe;AAE/D,SAAIf,IACK;AAAA,IACL,YAAYA,EAAO,SAASA,EAAO,WAAWkB;AAAA,EAAA,IAI9CH,EAAgB,cACX;AAAA,IACL,WAAWG;AAAA,EAAA,IAIR;AAAA,IACL,YAAYA;AAAA,IACZ,WAAWA;AAAA,EAAA;AAEf,GAEaI,IAAsC,CACjDhE,GACAqD,GACAK,MACG;AACH,QAAMO,IAAWN,EAA4B3D,GAASqD,GAAUK,CAAO;AAEvE,SAAIO,EAAS,iBACJA,EAAS,iBAGXZ,IACHA,EACG,MAAM,GAAG,EACT,IAAI,CAACa,MAAUA,EAAM,KAAA,CAAM,EAC3B,OAAO,OAAO,IACjB;AACN;"}
|
|
1
|
+
{"version":3,"file":"interaction-defaults.es.js","sources":["../../src/lib/interaction-defaults.ts"],"sourcesContent":["import {\n createInteractionParser,\n INTERACTION_CONTENT_SOURCE,\n} from \"remark-flow\";\n\nexport interface InteractionParseResult {\n buttonTexts?: string[];\n buttonValues?: string[];\n placeholder?: string;\n variableName?: string;\n isMultiSelect?: boolean;\n}\n\nexport interface InteractionDefaultValues {\n buttonText?: string;\n inputText?: string;\n selectedValues?: string[];\n}\n\nexport interface InteractionDefaultResolverParams {\n content?: string | null;\n rawValue?: string | null;\n interactionInfo?: InteractionParseResult | null;\n}\n\nexport type InteractionDefaultResolver = (\n params: InteractionDefaultResolverParams\n) => InteractionDefaultValues | null | undefined;\n\nexport interface InteractionDefaultValueOptions {\n resolveDefaultValues?: InteractionDefaultResolver;\n}\n\ninterface StructuredInteractionPayload {\n buttonText?: unknown;\n inputText?: unknown;\n selectedValues?: unknown;\n}\n\nconst interactionParser = createInteractionParser();\nconst INTERACTION_TAG_PATTERN = /<custom-variable\\b/i;\n// Same definition of where an interaction ends as the parser uses, so an option carrying a\n// `\\]` is read whole instead of being cut at its first bracket. A variable assignment is optional.\nconst INTERACTION_SHORTCODE_PATTERN = new RegExp(\n `\\\\?\\\\[(?:%\\\\{\\\\{([^}]+)\\\\}\\\\})?(${INTERACTION_CONTENT_SOURCE})\\\\]`\n);\nconst JSON_LIKE_VALUE_PATTERN = /^[\\[{]/;\nconst INTERACTION_VALUE_SEPARATOR_PATTERN = /^[\\s,,\\n]+/;\n\ninterface InteractionOptionCandidate {\n token: string;\n value: string;\n}\n\nconst parseInteractionShortcode = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n const matched = content.match(INTERACTION_SHORTCODE_PATTERN);\n const variableName = matched?.[1]?.trim();\n const interactionBody = matched?.[2]?.trim();\n\n if (!interactionBody) {\n return null;\n }\n\n const isMultiSelect = interactionBody.includes(\"||\");\n const separator = isMultiSelect ? \"||\" : \"|\";\n const rawOptions = interactionBody\n .split(separator)\n .map((item) => item.trim())\n .filter(Boolean);\n\n if (!rawOptions.length) {\n return null;\n }\n\n const buttonTexts: string[] = [];\n const buttonValues: string[] = [];\n let placeholder: string | undefined;\n\n rawOptions.forEach((option) => {\n if (option.startsWith(\"...\")) {\n const normalizedPlaceholder = option.replace(/^\\.\\.\\./, \"\").trim();\n if (normalizedPlaceholder) {\n placeholder = normalizedPlaceholder;\n }\n return;\n }\n\n buttonTexts.push(option);\n buttonValues.push(option);\n });\n\n return {\n variableName,\n buttonTexts: buttonTexts.length ? buttonTexts : undefined,\n buttonValues: buttonValues.length ? buttonValues : undefined,\n placeholder,\n isMultiSelect,\n };\n};\n\nconst parseInteractionBlock = (\n content?: string | null\n): InteractionParseResult | null => {\n if (!content) {\n return null;\n }\n\n try {\n return interactionParser.parseToRemarkFormat(\n content\n ) as InteractionParseResult;\n } catch (error) {\n console.warn(\"Failed to parse interaction block\", error);\n }\n\n return parseInteractionShortcode(content);\n};\n\nconst normalizeButtonValue = (\n token: string,\n info: InteractionParseResult\n): { value: string; display?: string } | null => {\n if (!token) {\n return null;\n }\n\n const cleaned = token.trim();\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const valueIndex = buttonValues.indexOf(cleaned);\n\n if (valueIndex > -1) {\n return {\n value: buttonValues[valueIndex],\n display: buttonTexts[valueIndex],\n };\n }\n\n const textIndex = buttonTexts.indexOf(cleaned);\n\n if (textIndex > -1) {\n return {\n value: buttonValues[textIndex] || buttonTexts[textIndex],\n display: buttonTexts[textIndex],\n };\n }\n\n return null;\n};\n\nconst splitPresetValues = (raw: string) => {\n return raw\n .split(/[,,\\n]/)\n .map((item) => item.trim())\n .filter(Boolean);\n};\n\nconst trimLeadingInteractionSeparators = (raw: string) =>\n raw.replace(INTERACTION_VALUE_SEPARATOR_PATTERN, \"\");\n\nconst buildInteractionOptionCandidates = (\n info: InteractionParseResult\n): InteractionOptionCandidate[] => {\n const buttonValues = info.buttonValues || [];\n const buttonTexts = info.buttonTexts || [];\n const candidates: InteractionOptionCandidate[] = [];\n const seenCandidates = new Set<string>();\n\n buttonValues.forEach((buttonValue, index) => {\n const normalizedValue = `${buttonValue ?? \"\"}`.trim();\n const normalizedText = `${buttonTexts[index] ?? \"\"}`.trim();\n\n [normalizedValue, normalizedText].forEach((token) => {\n if (!token) {\n return;\n }\n\n const candidateKey = `${token}::${normalizedValue || token}`;\n if (seenCandidates.has(candidateKey)) {\n return;\n }\n\n seenCandidates.add(candidateKey);\n candidates.push({\n token,\n value: normalizedValue || token,\n });\n });\n });\n\n return candidates.sort(\n (left, right) => right.token.length - left.token.length\n );\n};\n\nconst matchInteractionOptionPrefix = (\n raw: string,\n info: InteractionParseResult\n): InteractionOptionCandidate | null => {\n const normalizedRaw = trimLeadingInteractionSeparators(raw);\n const candidates = buildInteractionOptionCandidates(info);\n\n for (const candidate of candidates) {\n if (!normalizedRaw.startsWith(candidate.token)) {\n continue;\n }\n\n const trailingChar = normalizedRaw[candidate.token.length];\n if (trailingChar && !/[\\s,,\\n]/.test(trailingChar)) {\n continue;\n }\n\n return candidate;\n }\n\n return null;\n};\n\nconst resolveMultiSelectFallbackDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const tokens = splitPresetValues(raw);\n\n if (!tokens.length) {\n return {};\n }\n\n const selectedValues: string[] = [];\n const customInputs: string[] = [];\n\n tokens.forEach((token) => {\n const mapped = normalizeButtonValue(token, info);\n\n if (mapped) {\n selectedValues.push(mapped.value);\n return;\n }\n\n if (info.placeholder) {\n customInputs.push(token);\n return;\n }\n\n selectedValues.push(token);\n });\n\n return {\n selectedValues: selectedValues.length ? selectedValues : undefined,\n inputText: customInputs.length ? customInputs.join(\", \") : undefined,\n };\n};\n\nconst resolveMultiSelectInteractionDefaults = (\n raw: string,\n info: InteractionParseResult\n): InteractionDefaultValues => {\n const selectedValues: string[] = [];\n let remainingRaw = raw.trim();\n\n // Prefer option-aware prefix matching before delimiter splitting so\n // option labels that contain commas can still round-trip correctly.\n while (remainingRaw) {\n const matchedCandidate = matchInteractionOptionPrefix(remainingRaw, info);\n\n if (!matchedCandidate) {\n break;\n }\n\n selectedValues.push(matchedCandidate.value);\n const normalizedRemainingRaw =\n trimLeadingInteractionSeparators(remainingRaw);\n remainingRaw = trimLeadingInteractionSeparators(\n normalizedRemainingRaw.slice(matchedCandidate.token.length)\n );\n }\n\n if (selectedValues.length > 0) {\n return {\n selectedValues,\n inputText:\n info.placeholder && remainingRaw.trim()\n ? remainingRaw.trim()\n : undefined,\n };\n }\n\n const fallbackDefaults = resolveMultiSelectFallbackDefaults(raw, info);\n\n if (fallbackDefaults.selectedValues?.length) {\n return fallbackDefaults;\n }\n\n if (info.placeholder) {\n return {\n inputText: raw.trim(),\n };\n }\n\n return fallbackDefaults;\n};\n\nconst normalizeStructuredInteractionDefaults = (\n payload?: StructuredInteractionPayload | null\n): InteractionDefaultValues | null => {\n if (!payload || Array.isArray(payload)) {\n return null;\n }\n\n const selectedValues = Array.isArray(payload.selectedValues)\n ? payload.selectedValues\n .map((item) => `${item ?? \"\"}`.trim())\n .filter(Boolean)\n : undefined;\n const buttonText = `${payload.buttonText ?? \"\"}`.trim();\n const inputText =\n typeof payload.inputText === \"string\" ? payload.inputText : undefined;\n\n if (!selectedValues?.length && !buttonText && !inputText) {\n return null;\n }\n\n return {\n buttonText: buttonText || undefined,\n inputText,\n selectedValues: selectedValues?.length ? selectedValues : undefined,\n };\n};\n\nconst parseStructuredInteractionDefaults = (rawValue?: string | null) => {\n if (!rawValue) {\n return null;\n }\n\n if (!JSON_LIKE_VALUE_PATTERN.test(rawValue.trim())) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(rawValue) as StructuredInteractionPayload;\n return normalizeStructuredInteractionDefaults(parsed);\n } catch {\n return null;\n }\n};\n\nconst hasPotentialInteractionBlock = (content?: string | null) =>\n Boolean(\n content &&\n (INTERACTION_TAG_PATTERN.test(content) ||\n INTERACTION_SHORTCODE_PATTERN.test(content))\n );\n\nconst resolveCustomInteractionDefaults = (\n content?: string | null,\n rawValue?: string | null,\n interactionInfo?: InteractionParseResult | null,\n options?: InteractionDefaultValueOptions\n) => {\n return (\n options?.resolveDefaultValues?.({\n content,\n rawValue,\n interactionInfo,\n }) ?? null\n );\n};\n\nexport const getInteractionDefaultValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n): InteractionDefaultValues => {\n const normalized = rawValue?.toString().trim();\n\n if (!normalized) {\n return {};\n }\n\n const structuredDefaults = parseStructuredInteractionDefaults(normalized);\n\n if (structuredDefaults) {\n return structuredDefaults;\n }\n\n const customDefaults = resolveCustomInteractionDefaults(\n content,\n normalized,\n null,\n options\n );\n\n if (customDefaults) {\n return customDefaults;\n }\n\n if (!hasPotentialInteractionBlock(content)) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n const interactionInfo = parseInteractionBlock(content);\n const customDefaultsWithInteraction = resolveCustomInteractionDefaults(\n content,\n normalized,\n interactionInfo,\n options\n );\n\n if (customDefaultsWithInteraction) {\n return customDefaultsWithInteraction;\n }\n\n if (!interactionInfo) {\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n }\n\n if (interactionInfo.isMultiSelect) {\n return resolveMultiSelectInteractionDefaults(normalized, interactionInfo);\n }\n\n const mapped = normalizeButtonValue(normalized, interactionInfo);\n\n if (mapped) {\n return {\n buttonText: mapped.value || mapped.display || normalized,\n };\n }\n\n if (interactionInfo.placeholder) {\n return {\n inputText: normalized,\n };\n }\n\n return {\n buttonText: normalized,\n inputText: normalized,\n };\n};\n\nexport const getInteractionDefaultSelectedValues = (\n content?: string | null,\n rawValue?: string | null,\n options?: InteractionDefaultValueOptions\n) => {\n const defaults = getInteractionDefaultValues(content, rawValue, options);\n\n if (defaults.selectedValues) {\n return defaults.selectedValues;\n }\n\n return rawValue\n ? rawValue\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n : undefined;\n};\n"],"names":["interactionParser","createInteractionParser","INTERACTION_TAG_PATTERN","INTERACTION_SHORTCODE_PATTERN","INTERACTION_CONTENT_SOURCE","JSON_LIKE_VALUE_PATTERN","INTERACTION_VALUE_SEPARATOR_PATTERN","parseInteractionShortcode","content","matched","variableName","interactionBody","isMultiSelect","separator","rawOptions","item","buttonTexts","buttonValues","placeholder","option","normalizedPlaceholder","parseInteractionBlock","error","normalizeButtonValue","token","info","cleaned","valueIndex","textIndex","splitPresetValues","raw","trimLeadingInteractionSeparators","buildInteractionOptionCandidates","candidates","seenCandidates","buttonValue","index","normalizedValue","normalizedText","candidateKey","left","right","matchInteractionOptionPrefix","normalizedRaw","candidate","trailingChar","resolveMultiSelectFallbackDefaults","tokens","selectedValues","customInputs","mapped","resolveMultiSelectInteractionDefaults","remainingRaw","matchedCandidate","normalizedRemainingRaw","fallbackDefaults","normalizeStructuredInteractionDefaults","payload","buttonText","inputText","parseStructuredInteractionDefaults","rawValue","parsed","hasPotentialInteractionBlock","resolveCustomInteractionDefaults","interactionInfo","options","getInteractionDefaultValues","normalized","structuredDefaults","customDefaults","customDefaultsWithInteraction","getInteractionDefaultSelectedValues","defaults","value"],"mappings":";AAuCA,M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MAAM,GAAG,EACT,IAAI,CAACa,MAAUA,EAAM,KAAA,CAAM,EAC3B,OAAO,OAAO,IACjB;AACN;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../../../../_virtual/
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("../../../../_virtual/index9.cjs"),v=require("./constants.cjs");var d;function x(){if(d)return c.__exports;d=1,Object.defineProperty(c.__exports,"__esModule",{value:!0}),c.__exports.sanitizeUrl=void 0;var e=v.__require();function m(r){return e.relativeFirstCharacters.indexOf(r[0])>-1}function p(r){var i=r.replace(e.ctrlCharactersRegex,"");return i.replace(e.htmlEntitiesRegex,function(t,a){return String.fromCharCode(a)})}function R(r){return URL.canParse(r)}function l(r){try{return decodeURIComponent(r)}catch{return r}}function f(r){if(!r)return e.BLANK_URL;var i,t=l(r.trim());do t=p(t).replace(e.htmlCtrlEntityRegex,"").replace(e.ctrlCharactersRegex,"").replace(e.whitespaceEscapeCharsRegex,"").trim(),t=l(t),i=t.match(e.ctrlCharactersRegex)||t.match(e.htmlEntitiesRegex)||t.match(e.htmlCtrlEntityRegex)||t.match(e.whitespaceEscapeCharsRegex);while(i&&i.length>0);var a=t;if(!a)return e.BLANK_URL;if(m(a))return a;var u=a.trimStart(),h=u.match(e.urlSchemeRegex);if(!h)return a;var n=h[0].toLowerCase().trim();if(e.invalidProtocolRegex.test(n))return e.BLANK_URL;var s=u.replace(/\\/g,"/");if(n==="mailto:"||n.includes("://"))return s;if(n==="http:"||n==="https:"){if(!R(s))return e.BLANK_URL;var o=new URL(s);return o.protocol=o.protocol.toLowerCase(),o.hostname=o.hostname.toLowerCase(),o.toString()}return s}return c.__exports.sanitizeUrl=f,c.__exports}exports.__require=x;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../../_virtual/
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../../_virtual/index7.cjs");/*!
|
|
2
2
|
Copyright (c) 2018 Jed Watson.
|
|
3
3
|
Licensed under the MIT License (MIT), see
|
|
4
4
|
http://jedwatson.github.io/classnames
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../../comma-separated-tokens/index.cjs"),u=require("../../devlop/lib/default.cjs"),f=require("../../property-information/index.cjs"),C=require("../../space-separated-tokens/index.cjs"),S=require("../../../_virtual/
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("../../comma-separated-tokens/index.cjs"),u=require("../../devlop/lib/default.cjs"),f=require("../../property-information/index.cjs"),C=require("../../space-separated-tokens/index.cjs"),S=require("../../../_virtual/index8.cjs"),N=require("../../hast-util-whitespace/lib/index.cjs"),x=require("../../estree-util-is-identifier-name/lib/index.cjs"),h=require("../../vfile-message/lib/index.cjs"),j=require("../../property-information/lib/find.cjs"),A=require("../../property-information/lib/hast-to-react.cjs"),T=require("../../unist-util-position/lib/index.cjs"),m={}.hasOwnProperty,F=new Map,P=/[A-Z]/g,q=new Set(["table","tbody","thead","tfoot","tr"]),J=new Set(["td","th"]),g="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function M(t,e){if(!e||e.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=e.filePath||void 0;let n;if(e.development){if(typeof e.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=K(r,e.jsxDEV)}else{if(typeof e.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof e.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=k(r,e.jsx,e.jsxs)}const s={Fragment:e.Fragment,ancestors:[],components:e.components||{},create:n,elementAttributeNameCase:e.elementAttributeNameCase||"react",evaluater:e.createEvaluater?e.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:e.ignoreInvalidStyle||!1,passKeys:e.passKeys!==!1,passNode:e.passNode||!1,schema:e.space==="svg"?f.svg:f.html,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},i=E(s,t,void 0);return i&&typeof i!="string"?i:s.create(t,s.Fragment,{children:i||void 0},void 0)}function E(t,e,r){if(e.type==="element")return I(t,e,r);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return L(t,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return V(t,e,r);if(e.type==="mdxjsEsm")return $(t,e);if(e.type==="root")return D(t,e,r);if(e.type==="text")return O(t,e)}function I(t,e,r){const n=t.schema;let s=n;e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(s=f.svg,t.schema=s),t.ancestors.push(e);const i=b(t,e.tagName,!1),a=R(t,e);let o=d(t,e);return q.has(e.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!N.whitespace(l):!0})),v(t,a,i,e),y(a,o),t.ancestors.pop(),t.schema=n,t.create(e,i,a,r)}function L(t,e){if(e.data&&e.data.estree&&t.evaluater){const n=e.data.estree.body[0];return u.ok(n.type==="ExpressionStatement"),t.evaluater.evaluateExpression(n.expression)}p(t,e.position)}function $(t,e){if(e.data&&e.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(e.data.estree);p(t,e.position)}function V(t,e,r){const n=t.schema;let s=n;e.name==="svg"&&n.space==="html"&&(s=f.svg,t.schema=s),t.ancestors.push(e);const i=e.name===null?t.Fragment:b(t,e.name,!0),a=_(t,e),o=d(t,e);return v(t,a,i,e),y(a,o),t.ancestors.pop(),t.schema=n,t.create(e,i,a,r)}function D(t,e,r){const n={};return y(n,d(t,e)),t.create(e,t.Fragment,n,r)}function O(t,e){return e.value}function v(t,e,r,n){typeof r!="string"&&r!==t.Fragment&&t.passNode&&(e.node=n)}function y(t,e){if(e.length>0){const r=e.length>1?e:e[0];r&&(t.children=r)}}function k(t,e,r){return n;function n(s,i,a,o){const c=Array.isArray(a.children)?r:e;return o?c(i,a,o):c(i,a)}}function K(t,e){return r;function r(n,s,i,a){const o=Array.isArray(i.children),l=T.pointStart(n);return e(s,i,a,o,{columnNumber:l?l.column-1:void 0,fileName:t,lineNumber:l?l.line:void 0},void 0)}}function R(t,e){const r={};let n,s;for(s in e.properties)if(s!=="children"&&m.call(e.properties,s)){const i=B(t,s,e.properties[s]);if(i){const[a,o]=i;t.tableCellAlignToStyle&&a==="align"&&typeof o=="string"&&J.has(e.tagName)?n=o:r[a]=o}}if(n){const i=r.style||(r.style={});i[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function _(t,e){const r={};for(const n of e.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&t.evaluater){const i=n.data.estree.body[0];u.ok(i.type==="ExpressionStatement");const a=i.expression;u.ok(a.type==="ObjectExpression");const o=a.properties[0];u.ok(o.type==="SpreadElement"),Object.assign(r,t.evaluater.evaluateExpression(o.argument))}else p(t,e.position);else{const s=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&t.evaluater){const o=n.value.data.estree.body[0];u.ok(o.type==="ExpressionStatement"),i=t.evaluater.evaluateExpression(o.expression)}else p(t,e.position);else i=n.value===null?!0:n.value;r[s]=i}return r}function d(t,e){const r=[];let n=-1;const s=t.passKeys?new Map:F;for(;++n<e.children.length;){const i=e.children[n];let a;if(t.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const c=s.get(l)||0;a=l+"-"+c,s.set(l,c+1)}}const o=E(t,i,a);o!==void 0&&r.push(o)}return r}function B(t,e,r){const n=j.find(t.schema,e);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?w.stringify(r):C.stringify(r)),n.property==="style"){let s=typeof r=="object"?r:z(t,String(r));return t.stylePropertyNameCase==="css"&&(s=X(s)),["style",s]}return[t.elementAttributeNameCase==="react"&&n.space?A.hastToReact[n.property]||n.property:n.attribute,r]}}function z(t,e){try{return S.default(e,{reactCompat:!0})}catch(r){if(t.ignoreInvalidStyle)return{};const n=r,s=new h.VFileMessage("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw s.file=t.filePath||void 0,s.url=g+"#cannot-parse-style-attribute",s}}function b(t,e,r){let n;if(!r)n={type:"Literal",value:e};else if(e.includes(".")){const s=e.split(".");let i=-1,a;for(;++i<s.length;){const o=x.name(s[i])?{type:"Identifier",name:s[i]}:{type:"Literal",value:s[i]};a=a?{type:"MemberExpression",object:a,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=a}else n=x.name(e)&&!/^[a-z]/.test(e)?{type:"Identifier",name:e}:{type:"Literal",value:e};if(n.type==="Literal"){const s=n.value;return m.call(t.components,s)?t.components[s]:s}if(t.evaluater)return t.evaluater.evaluateExpression(n);p(t)}function p(t,e){const r=new h.VFileMessage("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:e,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=t.filePath||void 0,r.url=g+"#cannot-handle-mdx-estrees-without-createevaluater",r}function X(t){const e={};let r;for(r in t)m.call(t,r)&&(e[Z(r)]=t[r]);return e}function Z(t){let e=t.replace(P,G);return e.slice(0,3)==="ms-"&&(e="-"+e),e}function G(t){return"-"+t.toLowerCase()}exports.toJsxRuntime=M;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|