@sparkelf/dsh-genui 0.11.4-patch.1 → 0.13.0-sparkelf.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/ICON-NAMES.md +30 -0
  3. package/README.md +26 -28
  4. package/README.zh-CN.md +26 -28
  5. package/SKILL.md +128 -19
  6. package/THIRD_PARTY_NOTICES.md +42 -0
  7. package/assets/genui-icon.svg +20 -0
  8. package/assets/genui-logo.svg +18 -0
  9. package/cordis.patch.yml +1 -1
  10. package/lib/assets/icons.js +1 -0
  11. package/lib/assets/mermaid.js +325 -325
  12. package/lib/assets/standalone-runtime.js +10 -9
  13. package/lib/client.js +32 -31
  14. package/lib/index.js +489 -80
  15. package/lib/types/client/action-context.d.ts +1 -1
  16. package/lib/types/client/artifact/types.d.ts +1 -1
  17. package/lib/types/client/asset-loader.d.ts +2 -2
  18. package/lib/types/client/blocks/blocks.d.ts +12 -0
  19. package/lib/types/client/blocks/icon.d.ts +4 -0
  20. package/lib/types/client/dom-fence.d.ts +2 -1
  21. package/lib/types/client/fence-render.d.ts +5 -21
  22. package/lib/types/client/file-address.d.ts +4 -0
  23. package/lib/types/client/file-link-context.d.ts +49 -0
  24. package/lib/types/client/file-link.d.ts +17 -0
  25. package/lib/types/client/gallery.d.ts +8 -2
  26. package/lib/types/client/genui-runtime/diagnostics.d.ts +1 -1
  27. package/lib/types/client/genui-runtime/limits.d.ts +4 -0
  28. package/lib/types/client/genui-runtime/schema.d.ts +14 -1
  29. package/lib/types/client/guard.d.ts +4 -1
  30. package/lib/types/client/i18n/en.d.ts +5 -1
  31. package/lib/types/client/i18n/index.d.ts +1 -1
  32. package/lib/types/client/icons/asset-icons.d.ts +1 -0
  33. package/lib/types/client/icons/icon-data-full.d.ts +23 -0
  34. package/lib/types/client/icons/icon-data.d.ts +24 -0
  35. package/lib/types/client/icons/icon-lazy.d.ts +18 -0
  36. package/lib/types/client/icons/icon-names-full.d.ts +12 -0
  37. package/lib/types/client/index.d.ts +5 -15
  38. package/lib/types/client/inline.d.ts +1 -1
  39. package/lib/types/client/mermaid-colors.d.ts +2 -0
  40. package/lib/types/client/mermaid-core.d.ts +2 -1
  41. package/lib/types/client/mermaid-lazy.d.ts +5 -1
  42. package/lib/types/client/panel-command.d.ts +21 -1
  43. package/lib/types/client/panel.d.ts +6 -1
  44. package/lib/types/client/primitive-adapter.d.ts +0 -2
  45. package/lib/types/client/session-resolver.d.ts +13 -2
  46. package/lib/types/client/source-fence.d.ts +1 -1
  47. package/lib/types/client/spec.d.ts +107 -3
  48. package/lib/types/client/standalone/asset-loader.d.ts +1 -1
  49. package/lib/types/client/standalone/primitive-adapter.d.ts +0 -4
  50. package/lib/types/plugin/fence-feedback.d.ts +11 -7
  51. package/lib/types/plugin/index.d.ts +6 -2
  52. package/lib/types/shared/fence-language.d.ts +14 -0
  53. package/lib/types/shared/fence-repair.d.ts +2 -1
  54. package/lib/types/shared/fence-resolve.d.ts +1 -1
  55. package/package.json +92 -83
  56. package/src/client/EChartNode.tsx +17 -3
  57. package/src/client/GenuiBlock.module.css +411 -76
  58. package/src/client/action-context.ts +5 -15
  59. package/src/client/artifact/ArtifactExport.module.css +34 -3
  60. package/src/client/artifact/ExportableGenuiBlock.tsx +23 -2
  61. package/src/client/artifact/portability.ts +6 -1
  62. package/src/client/artifact/types.ts +1 -1
  63. package/src/client/asset-loader.ts +3 -3
  64. package/src/client/blocks/advanced.tsx +101 -14
  65. package/src/client/blocks/blocks.tsx +143 -0
  66. package/src/client/blocks/charts.tsx +22 -6
  67. package/src/client/blocks/icon.tsx +93 -0
  68. package/src/client/blocks/image.tsx +1 -0
  69. package/src/client/blocks/render-node.tsx +84 -52
  70. package/src/client/dom-fence.tsx +546 -72
  71. package/src/client/fence-render.tsx +5 -21
  72. package/src/client/file-address.ts +37 -0
  73. package/src/client/file-link-context.tsx +116 -0
  74. package/src/client/file-link.ts +46 -0
  75. package/src/client/gallery.ts +161 -133
  76. package/src/client/genui-runtime/diagnostics.ts +1 -1
  77. package/src/client/genui-runtime/limits.ts +4 -0
  78. package/src/client/genui-runtime/normalize.ts +42 -6
  79. package/src/client/genui-runtime/schema.ts +39 -7
  80. package/src/client/guard.ts +170 -15
  81. package/src/client/i18n/en.ts +5 -1
  82. package/src/client/i18n/index.ts +1 -1
  83. package/src/client/i18n/zh.ts +5 -1
  84. package/src/client/icons/asset-icons.ts +16 -0
  85. package/src/client/icons/icon-data-full.ts +5715 -0
  86. package/src/client/icons/icon-data.ts +507 -0
  87. package/src/client/icons/icon-lazy.ts +80 -0
  88. package/src/client/icons/icon-names-full.ts +12 -0
  89. package/src/client/index.tsx +27 -51
  90. package/src/client/inline.ts +17 -6
  91. package/src/client/mermaid-colors.ts +40 -0
  92. package/src/client/mermaid-core.ts +69 -61
  93. package/src/client/mermaid-lazy.ts +99 -4
  94. package/src/client/panel-command.ts +16 -2
  95. package/src/client/panel.tsx +18 -5
  96. package/src/client/primitive-adapter.ts +0 -11
  97. package/src/client/session-resolver.ts +12 -21
  98. package/src/client/source-fence.ts +4 -2
  99. package/src/client/spec.ts +116 -2
  100. package/src/client/standalone/asset-loader.ts +1 -1
  101. package/src/client/standalone/primitive-adapter.tsx +1 -9
  102. package/src/client/table-details.ts +4 -3
  103. package/src/plugin/fence-feedback.ts +60 -14
  104. package/src/plugin/index.ts +45 -20
  105. package/src/plugin/tool.ts +11 -2
  106. package/src/shared/fence-language.ts +30 -0
  107. package/src/shared/fence-repair.ts +37 -1
  108. package/src/shared/fence-resolve.ts +1 -1
  109. package/tsdown.config.ts +7 -8
  110. package/lib/invariant.js +0 -19
  111. package/lib/types/plugin/invariant.d.ts +0 -15
  112. package/src/plugin/invariant.ts +0 -30
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Two-tier icon lookup.
3
+ *
4
+ * Tier 1 (`ICONS`, inlined 64 glyphs) answers synchronously for the names a
5
+ * conversation reaches for most: states, arrows, and the compute primitives
6
+ * figures are built from. Tier 2 is the FULL 749-glyph catalogue, shipped as
7
+ * `lib/assets/icons.js` (~1 MB of path data) and fetched once, on demand,
8
+ * the first time a spec names something outside tier 1.
9
+ *
10
+ * Why a tier at all: one unknown glyph must not cost every reader 1 MB, and
11
+ * one mis-typed glyph must not cost anything — `ICON_NAMES_FULL` is inlined as
12
+ * names only, so "typo" degrades to the fallback dot without a network round
13
+ * trip, while "not downloaded yet" triggers exactly one load and then
14
+ * re-renders the mounted glyphs through the subscription below.
15
+ * @module @changfenhuang/dsh-genui/client/icons/icon-lazy
16
+ */
17
+ import { loadGenuiAsset } from '../asset-loader.ts'
18
+ import { ICONS, type BundledIcon } from './icon-data.ts'
19
+ import { ICON_NAMES_FULL } from './icon-names-full.ts'
20
+
21
+ const known = new Set(ICON_NAMES_FULL)
22
+
23
+ let full: Readonly<Record<string, BundledIcon>> | undefined
24
+ let load: Promise<void> | undefined
25
+ const listeners = new Set<() => void>()
26
+
27
+ /**
28
+ * 原型链安全的存在性判断。
29
+ *
30
+ * `icon.name` 是模型能任意填的字符串:若直接用 `ICONS[name]`,`constructor` /
31
+ * `toString` / `__proto__` 会命中原型链拿到 truthy 对象,随后渲染器读 `shapes`
32
+ * 抛 TypeError,整块围栏变成错误卡——与「未知名字降级为圆点」的承诺相反。
33
+ * `Object.hasOwn` 只认自身属性。
34
+ */
35
+ function hasIcon(source: Record<string, unknown> | undefined, name: string): boolean {
36
+ return source !== undefined && Object.hasOwn(source, name)
37
+ }
38
+
39
+ /** Is `name` a real catalogue entry (even if its shapes are not downloaded)? */
40
+ export function isKnownIcon(name: string): boolean {
41
+ return hasIcon(ICONS as unknown as Record<string, unknown>, name) || known.has(name)
42
+ }
43
+
44
+ /** Resolve a glyph if its shapes are already available, synchronously. */
45
+ export function resolveIcon(name: string): BundledIcon | undefined {
46
+ const inline = hasIcon(ICONS as unknown as Record<string, unknown>, name) ? ICONS[name] : undefined
47
+ if (inline !== undefined && Array.isArray(inline.shapes)) return inline
48
+ const lazy = hasIcon(full as unknown as Record<string, unknown> | undefined, name) ? full?.[name] : undefined
49
+ return lazy !== undefined && Array.isArray(lazy.shapes) ? lazy : undefined
50
+ }
51
+
52
+ /**
53
+ * Subscribe to the one-shot full-catalogue load. Used by mounted `icon` nodes
54
+ * to swap their fallback dot for the real glyph.
55
+ * @returns unsubscribe.
56
+ */
57
+ export function onIconsLoaded(listener: () => void): () => void {
58
+ listeners.add(listener)
59
+ return () => { listeners.delete(listener) }
60
+ }
61
+
62
+ /**
63
+ * Fetch the full catalogue once. A failed load stays failed for the page (the
64
+ * glyphs keep their fallback), matching the asset loader's memoized-rejection
65
+ * contract — retrying on every render would turn a missing route into a
66
+ * request storm.
67
+ */
68
+ export function ensureIcons(): Promise<void> {
69
+ if (full !== undefined) return Promise.resolve()
70
+ if (load !== undefined) return load
71
+ load = loadGenuiAsset<Readonly<Record<string, BundledIcon>>>('icons')
72
+ .then((catalogue) => {
73
+ full = catalogue
74
+ for (const listener of [...listeners]) listener()
75
+ })
76
+ .catch((error: unknown) => {
77
+ if (typeof console !== 'undefined') console.warn('[genui] icon catalogue unavailable', error)
78
+ })
79
+ return load
80
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * OpenAI Apps SDK UI icons — https://github.com/openai/apps-sdk-ui
3
+ * Pinned commit 0f00143c7a639906f1621fe58e1b6be7b5bea46d · MIT · Copyright 2025 OpenAI.
4
+ * See THIRD_PARTY_NOTICES.md.
5
+ *
6
+ * Generated by scripts/generate-icon-data.mjs — do not hand-edit.
7
+ */
8
+ /**
9
+ * 全部规范名(749)。只内联名字,好让渲染器区分「拼错」和「还没下载」:
10
+ * 不在这里的名字立刻走中性圆点兜底,不会触发全量字形包下载。
11
+ */
12
+ export const ICON_NAMES_FULL: readonly string[] = ["AddMember","AddSources","Agent","AgentMode","AllGizmos","AllProductsExplore","Analytics","AnalyzeData","ApiKey","ApiKeyAdmin","ApiKeyServiceAccount","ApiKeys","Archive","Array","ArrowBottomLeftSm","ArrowBottomRightSm","ArrowCurved","ArrowCurvedLeft","ArrowCurvedRight","ArrowCurvedRightXs","ArrowCurvedRightXs24px","ArrowDown","ArrowDownLg","ArrowDownSm","ArrowLeft","ArrowLeftLg","ArrowLeftSm","ArrowRight","ArrowRightLg","ArrowRightSm","ArrowRotateCcw","ArrowRotateCw","ArrowTopLeftSm","ArrowTopRightSm","ArrowUp","ArrowUpLg","ArrowUpRight","ArrowUpSm","AspectRatio11","AspectRatio169","AspectRatio34","AspectRatio43","AspectRatio916","Assistant","Astronout","AtSign","Atom","AutoPairApps","AutoSuggestedEdits","Autocomplete","AvatarFilledProfile","AvatarProfile","Back10s","Back15s","BackLarge","BackSmall","BackToApp","BackgroundConversation","BalancingScale","BarChart","BarChartFilled","Batch","Batches","Bell","BellFilled","Beta","Bills","Blend","BlendingCurveSharp","BlendingCurveSmooth","BlendingCurveSubtle","Bolt","Book","BookBookmark","BookClock","BookClosed","BookOpen","BookWrench","Boolean","Brain","Branch","BranchAlt","Bug","BuilderProfileCard","BuildingWorkspace","Business","BusinessFilled","Cabinet","Calendar","CalendarAlt","CalendarToday","Camera","CameraFilledPhoto","CameraPhoto","CaptionCcOff","CaptionCcOn","CaptionOff","CaptionOn","Card","CaretDown","CaretLeft","CaretRight","CaretUp","Category","Certificate","Chart","ChartXAxis","ChartYAxis","Chat","ChatCompose","ChatDashedCheckedTemp","ChatDashedTemp","ChatTemporary","ChatTripleDots","Chats","Check","CheckCircle","CheckCircleDashed","CheckCircleFilled","CheckLg","CheckMd","ChevronDown","ChevronDownLg","ChevronDownMd","ChevronDownUp","ChevronDownVector","ChevronLeft","ChevronLeftLg","ChevronLeftMd","ChevronRight","ChevronRightAlt","ChevronRightLg","ChevronRightMd","ChevronSmallDown","ChevronSmallLeft","ChevronSmallRight","ChevronSmallUp","ChevronUp","ChevronUpDown","ChevronUpLg","ChevronUpMd","Circle","CircleDashed","CircleQuestion","ClappingBoardClosed","ClappingBoardOpen","Cleanup","Clear","Click","Clip","Clipboard","ClipboardCopy","Clock","Clock10s","Clock15s","Clock20s","Clock5s","ClockOff","CloseBold","Code","CodeSquareSlash","Collapse","CollapseLarge","CollapseLeft","CollapseLg","CollapseRight","CollapseSm","CollapseSmall","ColorTheme","Comment","Commit","Compare","CompareArrows","Compass","Complete","ComposeCanvasEditStar","ComposeDashedTemporary","ComposeEditSquare","Confetti","ConfettiParty","Connect","ConnectApps","ConnectedDynamicGpt","ConnectorsConnectedApps","Copy","CreditCard","Credits","Cube","Cursor","Customize","DarkMode","DataControls","DeepSearchTelescope","Delete","DeleteAccount","Desktop","DiningEvents","DisabledCursor","Dock","Documentation","DollarCircle","Dot","DotsHorizontal","DotsHorizontalCircle","DotsHorizontalMoreMenu","DotsVertical","DotsVerticalCircle","DotsVerticalMoreMenu","DoubleChevronLeft","DoubleChevronRight","Download","DownloadCircle","DownloadSimple","DownloadVideo","DownloadVideoWatermark","Dropdown","DropdownVector","Dumbbell","EarthTravelWorld","Edit","EditAlt","EditDalleImage","EditPencil","EditStar","EditXs","Education","Email","EmojiAdd","EmojiLists","EmojiRemove","EmojiSections","EmojiWords","EmptyCircle","EmptyCircleFilled","EnterLogin","Enum","Equal","Error","ExclamationMarkCircle","ExitLogout","Expand","ExpandLarge","ExpandLg","ExpandMd","ExpandSm","ExpandSmall","Explore","ExploreSora","ExternalLink","Eye","EyeClosed","EyeOff","FeaturedWreath","File","File3d","FileAudio","FileBlank","FileCode","FileDocument","FileImage","FilePresentation","FileSpreadsheet","FileSpreedsheet","FileUpload","FileVideo","FileZip","Filter","FineTuning","FistBump","Flag","Flash","Flask","FlaskFilled","Folder","FolderDocumentsFinder","FolderOpen","FolderPlus","FolderPlusAdd","FolderShared","FolderSharedOpen","FolderStuffed","FolderUnshare","Folders","Followup","Forum","Forward","Forward10s","Forward15s","Frozen","Function","Functions","GenerateSuggestedEdits","Glasses","Globe","GlobeAltRealTimeSearch","GlobeFilled","GlobeOffRealTimeSearch","GlobeRealTimeSearch","GlobeSpin","Go","GoFilled","Graduate","GraduationCap","Grid","GridAlt","Group","GroupFilled","Groups","Hamburger","HandBack","HandFront","HandPeace","HandRaised","HandRaisedHey","HandWavingBye","HapticFeedback","Headphones","Health","Heart","HeartFilled","HeartFilledXs","HeartXs","Help","History","HistoryOff","HistoryOn","Home","HomeAlt","Identity","IdentityMeSecure","ImageCaption","ImageSquare","ImageSquarePictureLibrary","ImageToText","ImageWide","ImageWideFilled","ImageWidePictureLibrary","Images","Info","InfoCircle","Inkedin","Inpaint","InpaintRespond","Inspiration","InspirationFilled","Instagram","Interactiv","InternalKnowledge","InternalKnowledgeOptimizedForCircle","Invoice","Io","Jira","JumpToCaption","Kettlebell","Key","Keyboard","KeyboardShortcut","Lab","Language","Latency","Lifesaver","LightMode","Lightbulb","Lightbulb20","Lightbulb22","Lightbulb22Filled","LightbulbGlow","Link","LinkDisabledBold","LinkExternalWebsite","LocalServices","Lock","LockKeyHole","Logout","Loop","LoopLong","LoopNormal","LoopShort","LoopXs","Lotus","Love","MagnifyingGlassSearch","MagnifyingGlassSmSearch","Mail","ManageHistory","MapPin","Maps","MapsAddress","MapsDirections","MarkerCode","MarkerData","MarkerMultiple","MarkerQuote","Mcp","Members","MembersFilled","MemoryFilledSm","MemoryOffRemember","MemoryOnRemember","MemoryWriteSm","Menu","MenuInverted","MenuSidebar","Menubar","Messaging","Mic","MicFilled","MicFilledOff","MicLgDictate","MicOff","MinimizeDown","MinimizeLeft","MinimizeRight","MinimizeTop","Minus","MinusCircle","MinusCircleFilled","Mobile","Moon","MoonSunSystem","MoreCircleMenuDots","Music","MyGptProfileMe","Name","NewsPaper","NoTraining","Nodes","Notebook","NotebookCheck","NotebookNarrow","NotebookPencil","Notepad","NotificationBell","NotificationOffBell","Number","ObjectIcon","On","OpenLeft","OpenRight","OpenaiLogoBoldBoundingBox","OpenaiLogoRegularBoundingBox","OpenaiLogoWebappVariable480","Operator","Order","PageBlank","Paid","Paperclip","PaperclipAttach","ParentControl","PastedText","Pause","PauseCircle","PauseCircleFilled","PauseOutline","PauseSm","Paw","Pencil","PencilSparkle","PencilSquare","Pens","Phone","PhoneMissed","PhoneRing","PhoneWaves","PictureInPicture","Pin","PinFilled","PinWindow","Plane","PlantDesk","Play","PlayCircle","PlayCircleFilled","PlayOutline","PlaySm","PlayTriangle","Playground","Plugin","PluginPuzzle","Plus","Plus14px","PlusCircle","PlusCircleAdd","PlusCircleFilled","PlusComposer","PlusFilled","PlusLg","PlusLg18pxAdd","PlusSm12px","PlusSquareAdd","PopOutWindow","PresetDefault","PresetSelected","PrivacyIntern","ProDiamond","ProFilledDiamond","ProductTag","PullRequestClosed","PullRequestDraft","PullRequestMerged","PullRequestOpen","Pulse","Question","QuestionMark","QuestionMarkCircle","QuickStart","Quote","QuoteReplyFilledQuoteXs","RadioSelected","ReadingLevel","Record","Regenerate","RegenerateOff","RegenerateStar","Reload","RemixMild","RemixMildXs","RemixStrong","RemixSubtle","RemoveForeverPermanently","RemoveRedEye","Reply","Report","Resend","ResetChat","Resolution1080p","Resolution360p","Resolution480p","Resolution720p","RestoreUntrash","Rewind","Robot","RobotHead","RobotHeadSad","SavedFilledXs","SavedXs","Scales","Scissor","ScissorXs","ScreenPosition","Search","SearchConnector","SearchFeed","SearchXs","SelectText","Settings","SettingsCircle","SettingsCog","SettingsSlider","SettingsWrench","Share","ShareChat","ShareScreen","ShareScreenFilled","ShareScreenOff","ShareScreenOffFilled","ShieldCheck","ShieldKey","ShieldLock","ShieldPerson","ShoppingBag","Shortcuts","Shuffle","Sidebar","SidebarCollapseLeft","SidebarCollapseRight","SidebarFloatingLeft","SidebarFloatingOpenLeft","SidebarFloatingOpenRight","SidebarFloatingRight","SidebarLeft","SidebarMenuMobile","SidebarMenuMobileBadgeCutout","SidebarOpenLeft","SidebarOpenLeftAlt","SidebarOpenRight","SidebarOpenRightAlt","SidebarRight","SimpleRelax","SimpleSad","SimpleSmile","Skip","Sleep","Snapchat","Snorkle","Snowflake","SoraBasicPopcorn","SoraProDirector","SoundOffSimpleMute","SoundOffSpeaker","SoundOnReadOutLoudSpeaker","Sparkle","SparkleDouble","SparkleFilledPlus","SparklePlus","Sparkles","SparklesFilled","Speak","SpeechToText","Speed","SpeedometerLatencySpeed","Spelling","Spin","SquareCheckCheckboxChecked","SquareCheckFilledCheckboxCheckedFilled","SquareCheckboxUnchecked","SquareCode","SquareFilledTableLegend","SquareImage","SquarePlus","SquarePlusAlt","SquareTableLegend","SquareText","Stack","Star","StarFilled","StartStrokeMd","Status","Stethoscope","StickyNote","Stop","StopCircle","StopCircleFilled","StopOutline","StopSm","StopStrokeMd","Stopwatch","Storage","Storyboard","String","Studio","Stuff","StuffTools","SubscriptionPlan","SuggestEdit","Suitcase","SuitcaseFilledWorkBusiness","SuitcaseWorkBusiness","Sun","SystemMode","TBoneRaw","TableCellFilled","TableCellsFilled","TableColumnFilled","TableFilled","TableRowFilled","Tag","Tap","Tasks","Telescope","Terminal","TerminalLg","Terms","Text","TextLonger","TextPrompt","TextShorter","TextShorterConcise","TextToSpeech","ThumbDown","ThumbDownFilled","ThumbMixed","ThumbUp","ThumbUpFilled","ThumbnailLarge","ThumbnailMedium","ThumbnailSmall","Thumbs","Tiktok","Timer","Tools","ToolsSkills","Translate","Trash","TrashRemove","Trending","TriangleExclamationErrorWarning","TriangleExclamationFilledErrorWarning","TrophyTop","TuningFork","Unarchive","Undo","Unlink","Unpin","Upgrade","UpgradePlan","UploadDocuments","Upscale","UpscaleXs","Usage","User","UserAdd","UserGpts","UserHeart","UserLock","UserVoice","Users","Variation2v2","VariationV21","VariationV31","VariationV32","VariationV33","VariationV41","VariationV42","VariationV43","VariationV44","VersionsV1","Video","VideoCaption","VideoFilled","VideoFilledOff","VideoGrid","VideoList","VideoToText","Videos","Voice","Voice4Bars","Voice5BarsSoundwave","VoiceBold","VoiceInputAreaMobileFilledVoiceXs","VoiceLight","Warning","WarningFilledWrapCenteredForCircle","WarningWrapCenteredForCircle","Wave","WebsiteNetwork","Wechat","Whatsapp","Whisk","WhisperAutoSubmit","Widget","WidgetAdd","WorkWithApps","Workspace","Wreath","WriteAlt","WriteAlt2","Writing","X","XCircle","XCircleCrossedClose","XCircleFilled","XCircleFilledCrossedClose","XCrossed","XSquareCrossed","XSquareFilledCrossed","XXs","XXsCrossed","Youtube"]
@@ -2,17 +2,10 @@
2
2
  * dsh-genui browser half: the ```dsh-ui fence renderer, the keyed toolview
3
3
  * for the `render_ui` tool, and the session panel dock.
4
4
  *
5
- * Fence rendering is dual-mode, chosen at boot:
6
- * - **Registry channel** (contract hosts): the host's MarkdownText resolves
7
- * ```dsh-ui fences through the fence-registry extension point; this package
8
- * registers `renderGenuiFence`. Action callbacks ride the host-installed
9
- * GenuiActionContext.
10
- * - **DOM channel** (pristine hosts): no extension point exists, so
11
- * `dom-fence.ts` observes the conversation DOM, finds settled stock code
12
- * blocks labelled `dsh-ui`, and mounts the same render pipeline in its own
13
- * React roots — wrapped in the plugin-owned GenuiActionContext that relays
14
- * `[genui-action]` through the scoped conversation send. Either way the
15
- * deployment is the STOCK DSH snapshot plus this plugin.
5
+ * Fence rendering uses the stock DSH DOM. `dom-fence.ts` observes the
6
+ * conversation DOM, identifies `dsh-ui` blocks and mounts the renderer in
7
+ * plugin-owned React roots. The plugin-owned GenuiActionContext relays
8
+ * `[genui-action]` through the scoped conversation send.
16
9
  *
17
10
  * The renderer parses the fence body with the partial parser: while the reply
18
11
  * streams, every FINISHED component appears the moment its JSON object
@@ -26,11 +19,10 @@ import type {} from '@deepseek-ai/dsh-api-session-controller/client'
26
19
  import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
27
20
  import type { SessionId } from '@deepseek-ai/dsh-session/types'
28
21
  import type { IConversation } from '@deepseek-ai/dsh-client-ui-conversation/client'
29
- import type { Key, ReactNode } from 'react'
30
- import * as primitives from '@deepseek-ai/dsh-client-ui-primitives'
22
+ import { createElement } from 'react'
23
+ import type { ToolCallViewProps } from '@deepseek-ai/dsh-client-ui-tool/client'
31
24
  import { installDomFenceRenderer } from './dom-fence.tsx'
32
- import { renderGenuiFence, type GenuiFenceContext } from './fence-render.tsx'
33
- import { renderSvgFence } from './svg-fence.tsx'
25
+ import { createFileLinkAvailability, withFileLinkContext, type FileLinkCordisContext } from './file-link-context.tsx'
34
26
  import { createPanelSlashSource } from './panel-command.ts'
35
27
  import { GenuiPanel, type GenuiPanelInjected } from './panel.tsx'
36
28
  import { GenuiToolView } from './toolview.tsx'
@@ -39,11 +31,6 @@ import { bridgeHostLocale } from './i18n/index.ts'
39
31
  import type { InputTriggerServiceContract } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
40
32
  import { assetUrl } from './asset-loader.ts'
41
33
 
42
- /** Host extension surface the registry channel needs (absent on pristine). */
43
- type HostFenceExt = {
44
- registerFenceRenderer?: (lang: string, renderer: (raw: string, key: Key, context?: GenuiFenceContext) => ReactNode) => () => void
45
- }
46
-
47
34
  /** Add low-priority prefetch links for the lazy engine assets (mermaid/three).
48
35
  * Browser-dependent: some engines ignore `<link rel=prefetch>`; harmless
49
36
  * either way — the on-demand loader still covers a cache miss. Exported for
@@ -110,8 +97,7 @@ function sendPanelInstruction(ctx: Context, sessionId: SessionId, instruction: s
110
97
 
111
98
  /**
112
99
  * Inline-fence action relay (DOM channel): the same message template the
113
- * contract host's sendGenuiAction uses, so the model sees one identical
114
- * [genui-action] contract on both channels.
100
+ * host action message template, so inline actions reach the model consistently.
115
101
  */
116
102
  function sendInlineGenuiAction(ctx: Context, sessionId: SessionId, action: string, payload: Record<string, unknown>): void {
117
103
  const scoped = ctx.sessions.scope(sessionId)
@@ -126,36 +112,22 @@ function sendInlineGenuiAction(ctx: Context, sessionId: SessionId, action: strin
126
112
  })
127
113
  }
128
114
 
129
- /** Visual-regression flag: `scripts/e2e-visual.mts` sets
130
- * `window.__DSH_GENUI_E2E__ = true` via an init script BEFORE this bundle
131
- * boots, which pins the DOM channel even on hosts that ship the registry
132
- * extension point. The DOM channel is what lets the harness inject a gallery
133
- * fence into an empty scratch profile and screenshot the real React tree
134
- * without a model round trip; production pages never set the flag. */
135
- function forcedDomChannel(): boolean {
136
- return (globalThis as { __DSH_GENUI_E2E__?: boolean }).__DSH_GENUI_E2E__ === true
137
- }
138
-
139
- /** Cordis client entry: register the fence renderer on boot, the keyed
115
+ /** Cordis client entry: install the fence renderer on boot, the keyed
140
116
  * toolview for the render_ui tool, and the session panel dock; returning the
141
117
  * disposers lets cordis tear all registrations down on plugin unload. */
142
118
  export function apply(ctx: Context): () => void {
143
- // Fence channel selection: the registry extension point when the host
144
- // ships it (contract line), the DOM observer otherwise (pristine line).
145
- // One plugin build serves both deployments.
146
119
  // Language: follow the host's DSH language preference when the deployment
147
120
  // ships the locale service, otherwise fall back to browser detection. Read
148
- // OPTIONALLY (never declared in `inject`) so a pristine host without the
121
+ // OPTIONALLY (never declared in `inject`) so a host without the
149
122
  // service still renders — a declared-but-absent service would park the
150
123
  // fiber forever and kill all GenUI rendering.
151
124
  const localeDispose = bridgeHostLocale(ctx)
152
- const registerFn = (primitives as unknown as HostFenceExt).registerFenceRenderer
153
- const useRegistry = typeof registerFn === 'function' && !forcedDomChannel()
154
- const channel = useRegistry ? 'registry' : 'dom'
155
- console.info(`[genui] client active; fence-channel=${channel}`)
156
- const disposers: Array<() => void> = useRegistry
157
- ? [localeDispose, registerFn!('dsh-ui', renderGenuiFence), registerFn!('svg', renderSvgFence)]
158
- : [localeDispose, installDomFenceRenderer(ctx, (sessionId, action, payload) => sendInlineGenuiAction(ctx, sessionId, action, payload))]
125
+ const fileLinkAvailability = createFileLinkAvailability(ctx as unknown as FileLinkCordisContext)
126
+ console.info('[genui] client active; fence-channel=dom')
127
+ const disposers: Array<() => void> = [
128
+ localeDispose,
129
+ installDomFenceRenderer(ctx, (sessionId, action, payload) => sendInlineGenuiAction(ctx, sessionId, action, payload), fileLinkAvailability),
130
+ ]
159
131
  // Idle prefetch of the lazy engine assets: the browser downloads them at
160
132
  // LOW priority whenever the page is idle, so the first mermaid/3D node in
161
133
  // a session usually hits a warm cache instead of paying the fetch on first
@@ -170,7 +142,13 @@ export function apply(ctx: Context): () => void {
170
142
  disposers.push(ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
171
143
  name: 'tool.call.toolview',
172
144
  key: 'render_ui',
173
- }, GenuiToolView)))
145
+ }, (props: ToolCallViewProps) => withFileLinkContext(
146
+ ctx as unknown as FileLinkCordisContext,
147
+ fileLinkAvailability,
148
+ props.sessionId,
149
+ false,
150
+ createElement(GenuiToolView, props),
151
+ ))))
174
152
  // Session panel dock: a session-scoped, always-present seat above the
175
153
  // composer (TodoDock posture). Renders the session's latest render_ui
176
154
  // spec in place; absent spec = no panel.
@@ -178,7 +156,10 @@ export function apply(ctx: Context): () => void {
178
156
  name: 'conversation.input.dock',
179
157
  id: 'genui-panel',
180
158
  order: 50,
181
- inject: (sessionId: SessionId): GenuiPanelInjected => panelActionSend(ctx, sessionId),
159
+ inject: (sessionId: SessionId): GenuiPanelInjected => ({
160
+ ...panelActionSend(ctx, sessionId),
161
+ fileLinkContext: { ctx: ctx as unknown as FileLinkCordisContext, availability: fileLinkAvailability },
162
+ }),
182
163
  }, GenuiPanel)))
183
164
  // /panel slash command: a deterministic, client-side entry point that
184
165
  // opens the panel dock (publishes the default spec + expand request),
@@ -221,8 +202,3 @@ export function apply(ctx: Context): () => void {
221
202
  // arrival order, hosts without it never register /panel — and the renderer
222
203
  // itself never depends on the service either way.
223
204
  export const inject = ['slots', 'sessions']
224
-
225
- // Re-export the registry renderer for the test suite (setup.ts registers it
226
- // exactly like apply() does on contract hosts).
227
- export { renderGenuiFence }
228
- export type { GenuiFenceContext } from './fence-render.tsx'
@@ -2,7 +2,8 @@
2
2
  import { createElement, useLayoutEffect, useRef, type ReactNode } from 'react'
3
3
  import katex from 'katex'
4
4
  import css from './GenuiBlock.module.css'
5
- import { safeHref } from './genui-runtime/value-utils.ts'
5
+ import { classifyLinkTarget } from './file-link.ts'
6
+ import { FileLink } from './file-link-context.tsx'
6
7
 
7
8
  /** KaTeX owns this span's children; React owns the span and its lifecycle.
8
9
  * The host's ui-primitives already supplies KaTeX CSS/fonts, including embeds. */
@@ -35,7 +36,7 @@ export function hasInlineMarkup(text: string): boolean {
35
36
  }
36
37
 
37
38
  /** Render safe phrasing content, usable in headings, buttons and labels too. */
38
- export function renderInline(text: string, allowLinks = true, depth = 0): ReactNode {
39
+ export function renderInline(text: string, allowLinks: boolean | 'file' = true, depth = 0): ReactNode {
39
40
  if (typeof text !== 'string' || text === '' || !hasInlineMarkup(text) || depth >= 8) return text
40
41
  const segments: ReactNode[] = []
41
42
  let fenceEnd = 0
@@ -93,10 +94,20 @@ export function renderInline(text: string, allowLinks = true, depth = 0): ReactN
93
94
  if (parts === null) {
94
95
  out.push(token)
95
96
  } else {
96
- const href = safeHref(parts[2])
97
- out.push(href === undefined || !allowLinks ? renderInline(parts[1]!, false, depth + 1) : createElement('a', {
98
- key: key++, className: css.inlineLink, href, target: '_blank', rel: 'noreferrer noopener',
99
- }, renderInline(parts[1]!, false, depth + 1)))
97
+ const target = classifyLinkTarget(parts[2])
98
+ const label = renderInline(parts[1]!, false, depth + 1)
99
+ if (target.type === 'external' && allowLinks === true) {
100
+ out.push(createElement('a', {
101
+ key: key++, className: css.inlineLink, href: target.href, target: '_blank', rel: 'noreferrer noopener',
102
+ }, label))
103
+ } else if (target.type === 'file' && allowLinks !== false) {
104
+ out.push(createElement(FileLink, {
105
+ key: key++, path: target.file.path, label: parts[1]!,
106
+ ...(target.file.line === undefined ? {} : { line: target.file.line }),
107
+ }, label))
108
+ } else {
109
+ out.push(label)
110
+ }
100
111
  }
101
112
  }
102
113
  last = index + token.length
@@ -0,0 +1,40 @@
1
+ /** Resolve host CSS colors before passing them to Mermaid's limited parser. */
2
+ export function readMermaidThemeColor(name: string, fallback: string, target?: HTMLElement): string {
3
+ if (typeof document === 'undefined' || document.body === null) return fallback
4
+ const source = target ?? document.body
5
+ const value = getComputedStyle(source).getPropertyValue(name).trim()
6
+ if (value === '') return fallback
7
+
8
+ // Computed custom properties still contain calc(), unlike computed color.
9
+ // A real color property also resolves currentColor and inherited variables.
10
+ const probe = document.createElement('span')
11
+ probe.style.setProperty('color', value, 'important')
12
+ if (probe.style.color === '') return fallback
13
+ probe.style.setProperty('display', 'none', 'important')
14
+ source.appendChild(probe)
15
+ let color: string
16
+ try {
17
+ color = getComputedStyle(probe).color
18
+ } finally {
19
+ probe.remove()
20
+ }
21
+ if (/^rgba?\([\d.,\s]+\)$/i.test(color)) return color
22
+
23
+ // Modern colors such as oklch() and color-mix() may remain in those formats
24
+ // after style resolution. Canvas converts them to the sRGB Mermaid accepts.
25
+ const canvas = document.createElement('canvas')
26
+ canvas.width = canvas.height = 1
27
+ const context = canvas.getContext('2d')
28
+ if (context === null) return fallback
29
+ context.fillStyle = '#010203'
30
+ const initialFillStyle = context.fillStyle
31
+ context.fillStyle = color
32
+ if (context.fillStyle === initialFillStyle) return fallback
33
+ try {
34
+ context.fillRect(0, 0, 1, 1)
35
+ const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data
36
+ return `rgba(${r}, ${g}, ${b}, ${a! / 255})`
37
+ } catch {
38
+ return fallback
39
+ }
40
+ }
@@ -16,72 +16,79 @@
16
16
  * @module @changfenhuang/dsh-genui/client/mermaid-core
17
17
  */
18
18
  import { assertSafeSvg, ensureFlowchartKind, repairMermaidSource } from './mermaid-safe.ts'
19
+ import { readMermaidThemeColor } from './mermaid-colors.ts'
19
20
 
20
21
  let mermaidPromise: Promise<typeof import('mermaid')> | null = null
21
22
 
22
23
  /** Monotonic render id (replaces Math.random): no collisions, no entropy. */
23
24
  let renderSeq = 0
24
25
 
25
- function loadMermaid(): Promise<typeof import('mermaid')> {
26
- mermaidPromise ??= import('mermaid').then(async m => {
27
- const api = m.default
28
- // Theme the diagram from the HOST tokens instead of a built-in mermaid
29
- // palette: the stock themes render grey boxes with sharp corners, dark
30
- // strokes and their own font, which sat next to our components as a
31
- // visibly foreign object. `base` + themeVariables is the supported way to
32
- // drive every colour (the dark/light branch is gone with it).
33
- const token = (name: string, fallback: string): string => {
34
- if (typeof document === 'undefined') return fallback
35
- const value = getComputedStyle(document.body).getPropertyValue(name).trim()
36
- return value === '' ? fallback : value
37
- }
38
- api.initialize({
39
- startOnLoad: false,
40
- // Strict default: mermaid escapes/sanitizes; we never enable htmlLabels.
41
- securityLevel: 'strict',
42
- theme: 'base',
43
- themeVariables: {
44
- background: 'transparent',
45
- fontFamily: 'inherit',
46
- fontSize: '13px',
47
- primaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
48
- primaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
49
- primaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
50
- secondaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
51
- secondaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
52
- secondaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
53
- tertiaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
54
- tertiaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
55
- tertiaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
56
- mainBkg: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
57
- nodeBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
58
- nodeTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
59
- lineColor: token('--dsw-alias-label-tertiary', '#8a8a92'),
60
- textColor: token('--dsw-alias-label-primary', '#e6e6e6'),
61
- edgeLabelBackground: 'transparent',
62
- clusterBkg: 'transparent',
63
- clusterBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
64
- titleColor: token('--dsw-alias-label-primary', '#e6e6e6'),
65
- },
66
- // Sharp corners and heavy strokes were the loudest mismatch; the radius
67
- // is set here because mermaid emits plain <rect> geometry.
68
- themeCSS: [
69
- '.node rect, .node polygon, .node circle, .node ellipse { rx: 8px; ry: 8px; stroke-width: 1px; }',
70
- '.cluster rect { rx: 10px; ry: 10px; }',
71
- '.edgePath .path { stroke-width: 1.4px; }',
72
- '.label { color: inherit; }',
73
- ].join(' '),
74
- // Fail loudly: with suppressErrorRendering false (the default) mermaid
75
- // renders an "error" diagram on parse/draw failure — the caller then
76
- // receives a normal-looking SVG whose text is the raw engine error
77
- // ("Syntax error in text / mermaid version …"), which lands on the page
78
- // with no exception ever thrown. Suppressing the error diagram makes
79
- // every failure throw so the caller shows its own fallback instead.
80
- suppressErrorRendering: true,
81
- })
82
- return m
26
+ async function loadMermaid(target?: HTMLElement): Promise<typeof import('mermaid')> {
27
+ mermaidPromise ??= import('mermaid')
28
+ const m = await mermaidPromise
29
+ // Called inside the client queue: initialize for each job so host theme
30
+ // tokens cannot remain frozen at the first diagram's palette.
31
+ const api = m.default
32
+ // Theme the diagram from the HOST tokens instead of a built-in mermaid
33
+ // palette: the stock themes render grey boxes with sharp corners, dark
34
+ // strokes and their own font, which sat next to our components as a
35
+ // visibly foreign object. `base` + themeVariables is the supported way to
36
+ // drive every colour (the dark/light branch is gone with it).
37
+ const colors = new Map<string, string>()
38
+ const token = (name: string, fallback: string): string => {
39
+ const cached = colors.get(name)
40
+ if (cached !== undefined) return cached
41
+ const color = readMermaidThemeColor(name, fallback, target)
42
+ colors.set(name, color)
43
+ return color
44
+ }
45
+ api.initialize({
46
+ startOnLoad: false,
47
+ // Strict default: mermaid escapes/sanitizes; we never enable htmlLabels.
48
+ securityLevel: 'strict',
49
+ theme: 'base',
50
+ themeVariables: {
51
+ background: 'transparent',
52
+ // Freeze the same font into measurement and the returned SVG: inheriting
53
+ // from body while measuring and from a card while displaying clips labels.
54
+ fontFamily: getComputedStyle(target ?? document.body).fontFamily,
55
+ fontSize: '13px',
56
+ primaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
57
+ primaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
58
+ primaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
59
+ secondaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
60
+ secondaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
61
+ secondaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
62
+ tertiaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
63
+ tertiaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
64
+ tertiaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
65
+ mainBkg: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
66
+ nodeBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
67
+ nodeTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
68
+ lineColor: token('--dsw-alias-label-tertiary', '#8a8a92'),
69
+ textColor: token('--dsw-alias-label-primary', '#e6e6e6'),
70
+ edgeLabelBackground: 'transparent',
71
+ clusterBkg: 'transparent',
72
+ clusterBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
73
+ titleColor: token('--dsw-alias-label-primary', '#e6e6e6'),
74
+ },
75
+ // Sharp corners and heavy strokes were the loudest mismatch; the radius
76
+ // is set here because mermaid emits plain <rect> geometry.
77
+ themeCSS: [
78
+ '.node rect, .node polygon, .node circle, .node ellipse { rx: 8px; ry: 8px; stroke-width: 1px; }',
79
+ '.cluster rect { rx: 10px; ry: 10px; }',
80
+ '.edgePath .path { stroke-width: 1.4px; }',
81
+ '.label { color: inherit; }',
82
+ ].join(' '),
83
+ // Fail loudly: with suppressErrorRendering false (the default) mermaid
84
+ // renders an "error" diagram on parse/draw failure — the caller then
85
+ // receives a normal-looking SVG whose text is the raw engine error
86
+ // ("Syntax error in text / mermaid version …"), which lands on the page
87
+ // with no exception ever thrown. Suppressing the error diagram makes
88
+ // every failure throw so the caller shows its own fallback instead.
89
+ suppressErrorRendering: true,
83
90
  })
84
- return mermaidPromise
91
+ return m
85
92
  }
86
93
 
87
94
  /** Diagram kinds allowed through to the renderer. */
@@ -115,11 +122,12 @@ async function renderInto(m: typeof import('mermaid'), id: string, code: string,
115
122
  /**
116
123
  * Render mermaid source to an SVG string.
117
124
  * @param code - the mermaid diagram source.
125
+ * @param target - final diagram element whose inherited font is used for layout.
118
126
  * @returns the rendered SVG markup (verified free of script/event handlers).
119
127
  * @throws when the kind is not whitelisted, rendering fails, or the output
120
128
  * fails the sanitization check.
121
129
  */
122
- export async function renderMermaid(code: string): Promise<string> {
130
+ export async function renderMermaid(code: string, target?: HTMLElement): Promise<string> {
123
131
  let trimmed = code.trim()
124
132
  const firstLine = trimmed.split('\n', 1)[0] ?? ''
125
133
  let kind = /^([A-Za-z]+)/.exec(firstLine)?.[1] ?? ''
@@ -138,7 +146,7 @@ export async function renderMermaid(code: string): Promise<string> {
138
146
  if (!ALLOWED_KINDS.includes(kind)) {
139
147
  throw new Error(`mermaid kind '${kind}' is not allowed`)
140
148
  }
141
- const m = await loadMermaid()
149
+ const m = await loadMermaid(target)
142
150
  const container = document.createElement('div')
143
151
  try {
144
152
  try {
@@ -15,17 +15,112 @@ export { assertSafeSvg, ensureFlowchartKind, repairMermaidSource } from './merma
15
15
 
16
16
  /** The engine surface registered by the mermaid asset bundle. */
17
17
  interface MermaidAssetApi {
18
- renderMermaid: (code: string) => Promise<string>
18
+ renderMermaid: (code: string, target?: HTMLElement) => Promise<string>
19
+ }
20
+
21
+ interface RenderJob {
22
+ code: string
23
+ signal: AbortSignal | undefined
24
+ target: HTMLElement | undefined
25
+ resolve: (svg: string) => void
26
+ reject: (error: unknown) => void
27
+ abort: () => void
28
+ }
29
+
30
+ const jobs: RenderJob[] = []
31
+ let active = false
32
+ let listening = false
33
+ let timer: ReturnType<typeof setTimeout> | undefined
34
+ let scrollUntil = 0
35
+
36
+ // Keep graph layout out of an ongoing scroll gesture. Matches #303's tested
37
+ // quiet period; this is scheduling, not a change to DOM-fence discovery.
38
+ const SCROLL_QUIET_MS = 250
39
+ const onScroll = (): void => {
40
+ scrollUntil = performance.now() + SCROLL_QUIET_MS
41
+ if (timer !== undefined) clearTimeout(timer)
42
+ timer = undefined
43
+ pump()
44
+ }
45
+ const onVisibility = (): void => { pump() }
46
+
47
+ /** 持续监听滚动与页面可见状态,供空闲调度器记录活动时间。 */
48
+ function listenForActivity(): void {
49
+ if (listening || typeof document === 'undefined') return
50
+ document.addEventListener('scroll', onScroll, { capture: true, passive: true })
51
+ document.addEventListener('visibilitychange', onVisibility)
52
+ listening = true
53
+ }
54
+
55
+ // 调度器随客户端渲染器加载,确保队列空闲时也能记录滚动事件。
56
+ listenForActivity()
57
+
58
+ function pump(): void {
59
+ if (active) return
60
+ if (jobs.length === 0) {
61
+ if (timer !== undefined) clearTimeout(timer)
62
+ timer = undefined
63
+ return
64
+ }
65
+ if (timer !== undefined || document.hidden) return
66
+ // A fresh task (rather than a promise/microtask chain) gives input, paint
67
+ // and the host watchdog a chance between diagrams, including after errors.
68
+ timer = setTimeout(() => {
69
+ timer = undefined
70
+ if (document.hidden) return
71
+ if (performance.now() < scrollUntil) { pump(); return }
72
+ const job = jobs.shift()
73
+ if (job === undefined) { pump(); return }
74
+ active = true
75
+ void (async () => {
76
+ let deferred = false
77
+ try {
78
+ job.signal?.throwIfAborted()
79
+ const api = await loadGenuiAsset<MermaidAssetApi>('mermaid')
80
+ job.signal?.throwIfAborted()
81
+ // Loading the engine may outlive a scroll or visibility change.
82
+ if (document.hidden || performance.now() < scrollUntil) {
83
+ deferred = true
84
+ jobs.unshift(job)
85
+ return
86
+ }
87
+ const svg = await api.renderMermaid(job.code, job.target)
88
+ job.signal?.throwIfAborted()
89
+ job.resolve(svg)
90
+ } catch (error) {
91
+ job.reject(error)
92
+ } finally {
93
+ if (!deferred) job.signal?.removeEventListener('abort', job.abort)
94
+ active = false
95
+ pump()
96
+ }
97
+ })()
98
+ }, Math.max(0, scrollUntil - performance.now()))
19
99
  }
20
100
 
21
101
  /**
22
102
  * Render mermaid source to an SVG string (engine loaded on demand).
23
103
  * @param code - the mermaid diagram source.
104
+ * @param options - abort signal for queued or superseded work.
24
105
  * @returns the rendered SVG markup (verified free of script/event handlers).
25
106
  * @throws when the asset cannot load, the kind is not whitelisted, rendering
26
107
  * fails, or the output fails the sanitization check.
27
108
  */
28
- export async function renderMermaid(code: string): Promise<string> {
29
- const api = await loadGenuiAsset<MermaidAssetApi>('mermaid')
30
- return api.renderMermaid(code)
109
+ // Queue one diagram; cancellation discards stale source before engine work.
110
+ export function renderMermaid(code: string, options: { signal?: AbortSignal; target?: HTMLElement } = {}): Promise<string> {
111
+ return new Promise((resolve, reject) => {
112
+ const signal = options.signal
113
+ if (signal?.aborted) { reject(signal.reason); return }
114
+ const job: RenderJob = { code, signal, target: options.target, resolve, reject, abort: () => {
115
+ const index = jobs.indexOf(job)
116
+ if (index !== -1) jobs.splice(index, 1)
117
+ reject(signal?.reason)
118
+ signal?.removeEventListener('abort', job.abort)
119
+ pump()
120
+ } }
121
+ signal?.addEventListener('abort', job.abort, { once: true })
122
+ jobs.push(job)
123
+ listenForActivity()
124
+ pump()
125
+ })
31
126
  }