@zyro-sec/session-ui 0.0.0-stage → 1.0.3
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/AGENTS.md +25 -0
- package/bunfig.toml +2 -0
- package/component-tests/basic-tool.fixture.tsx +46 -0
- package/component-tests/basic-tool.spec.ts +63 -0
- package/component-tests/file-media.fixture.tsx +39 -0
- package/component-tests/file-media.spec.ts +13 -0
- package/component-tests/file-tool.spec.ts +62 -0
- package/component-tests/file-viewer.fixture.tsx +109 -0
- package/component-tests/file-viewer.spec.ts +134 -0
- package/component-tests/file.spec.ts +33 -0
- package/component-tests/line-comment-v2.spec.ts +15 -0
- package/component-tests/markdown-code-wrap.spec.ts +94 -0
- package/component-tests/markdown-readiness.spec.ts +95 -0
- package/component-tests/markdown.fixture.tsx +104 -0
- package/component-tests/markdown.spec.ts +1564 -0
- package/component-tests/mermaid-preview.spec.ts +43 -0
- package/component-tests/patch-group.spec.ts +79 -0
- package/component-tests/read-group.spec.ts +72 -0
- package/component-tests/read-image.fixture.tsx +66 -0
- package/component-tests/read-image.spec.ts +154 -0
- package/component-tests/session-compaction.spec.ts +254 -0
- package/component-tests/session-lifecycle.spec.ts +190 -0
- package/component-tests/session-message-projection.spec.ts +639 -0
- package/component-tests/session-notice-projection.spec.ts +20 -0
- package/component-tests/session-review-comments.spec.ts +179 -0
- package/component-tests/session-shell.spec.ts +93 -0
- package/component-tests/session-timeline-mobile.spec.ts +201 -0
- package/component-tests/session-timeline-notices.spec.ts +38 -0
- package/component-tests/session-timeline-reasoning.spec.ts +107 -0
- package/component-tests/session-timeline.spec.ts +157 -0
- package/component-tests/session-tool-projection.spec.ts +323 -0
- package/component-tests/text-lifecycle.fixture.tsx +26 -0
- package/component-tests/text-lifecycle.spec.ts +42 -0
- package/component-tests/timeline-subagent-rows.spec.ts +33 -0
- package/component-tests/tool-disclosure.spec.ts +48 -0
- package/component-tests/tool-group-sticky.spec.ts +37 -0
- package/component-tests/tool-group.spec.ts +290 -0
- package/component-tests/tool-status-title.fixture.tsx +22 -0
- package/component-tests/tool-status-title.spec.ts +30 -0
- package/component-tests/user-message-quotes.spec.ts +111 -0
- package/package.json +91 -4
- package/playwright.components.config.ts +4 -0
- package/playwright.local.config.ts +2 -0
- package/src/actions.ts +54 -0
- package/src/components/apply-patch-file.ts +122 -0
- package/src/components/basic-tool.css +487 -0
- package/src/components/basic-tool.tsx +258 -0
- package/src/components/copy-machine.ts +78 -0
- package/src/components/copy.ts +85 -0
- package/src/components/diagram-preview.tsx +28 -0
- package/src/components/disclosure-machine.ts +188 -0
- package/src/components/disclosure.ts +129 -0
- package/src/components/dock-prompt.stories.tsx +73 -0
- package/src/components/dock-prompt.tsx +29 -0
- package/src/components/file-comment-selection.tsx +146 -0
- package/src/components/file-media-machine.ts +165 -0
- package/src/components/file-media.stories.tsx +112 -0
- package/src/components/file-media.tsx +323 -0
- package/src/components/file-search.tsx +73 -0
- package/src/components/file.css +59 -0
- package/src/components/file.tsx +1300 -0
- package/src/components/image-preview.tsx +35 -0
- package/src/components/line-comment-annotations.tsx +580 -0
- package/src/components/line-comment-machine.ts +262 -0
- package/src/components/line-comment-styles.ts +293 -0
- package/src/components/line-comment.stories.tsx +152 -0
- package/src/components/line-comment.tsx +448 -0
- package/src/components/link-segments.ts +20 -0
- package/src/components/linked-text.tsx +21 -0
- package/src/components/markdown-cache-machine.ts +257 -0
- package/src/components/markdown-cache.tsx +556 -0
- package/src/components/markdown-clipboard.ts +101 -0
- package/src/components/markdown-code-machine.ts +200 -0
- package/src/components/markdown-code-state.ts +22 -0
- package/src/components/markdown-fragment-links.ts +74 -0
- package/src/components/markdown-github.svg +3 -0
- package/src/components/markdown-globe.svg +5 -0
- package/src/components/markdown-image-machine.ts +170 -0
- package/src/components/markdown-image.ts +156 -0
- package/src/components/markdown-inline-code-kind.ts +39 -0
- package/src/components/markdown-mermaid.ts +18 -0
- package/src/components/markdown-phase-machine.ts +102 -0
- package/src/components/markdown-projection.ts +13 -0
- package/src/components/markdown-session-links.ts +183 -0
- package/src/components/markdown-solid.test.tsx +92 -0
- package/src/components/markdown-solid.tsx +113 -0
- package/src/components/markdown-stream.ts +95 -0
- package/src/components/markdown-worker-machine.ts +516 -0
- package/src/components/markdown-worker-protocol.ts +73 -0
- package/src/components/markdown-worker.ts +250 -0
- package/src/components/markdown.css +672 -0
- package/src/components/markdown.stories.tsx +199 -0
- package/src/components/markdown.tsx +1612 -0
- package/src/components/markdown.worker.ts +188 -0
- package/src/components/message-file.ts +102 -0
- package/src/components/message-nav.css +134 -0
- package/src/components/message-nav.tsx +159 -0
- package/src/components/message-part.css +2109 -0
- package/src/components/message-part.tsx +3 -0
- package/src/components/question-prompt-experimental.css +576 -0
- package/src/components/question-prompt.css +527 -0
- package/src/components/quote-highlight.css +59 -0
- package/src/components/review-focus-driver.ts +142 -0
- package/src/components/review-focus-machine.ts +95 -0
- package/src/components/session-compaction.css +270 -0
- package/src/components/session-diff.ts +358 -0
- package/src/components/session-error.tsx +41 -0
- package/src/components/session-retry.tsx +92 -0
- package/src/components/session-review-machine.ts +241 -0
- package/src/components/session-review.css +264 -0
- package/src/components/session-review.stories.tsx +232 -0
- package/src/components/session-review.tsx +733 -0
- package/src/components/session-turn.css +282 -0
- package/src/components/shell-submessage.css +24 -0
- package/src/components/timeline-separator.tsx +69 -0
- package/src/components/tool-count-label.css +57 -0
- package/src/components/tool-count-label.tsx +76 -0
- package/src/components/tool-count-summary.css +102 -0
- package/src/components/tool-count-summary.stories.tsx +99 -0
- package/src/components/tool-count-summary.tsx +44 -0
- package/src/components/tool-error-card.css +178 -0
- package/src/components/tool-error-card.stories.tsx +113 -0
- package/src/components/tool-error-card.tsx +202 -0
- package/src/components/tool-status-title-machine.ts +128 -0
- package/src/components/tool-status-title.css +89 -0
- package/src/components/tool-status-title.tsx +163 -0
- package/src/context/data.tsx +107 -0
- package/src/context/index.ts +1 -0
- package/src/context/markdown.tsx +129 -0
- package/src/context/sources.tsx +34 -0
- package/src/document.ts +8 -0
- package/src/file-presentation.ts +34 -0
- package/src/message/action-machine.ts +72 -0
- package/src/message/agent-label.ts +3 -0
- package/src/message/attachment-card.css +119 -0
- package/src/message/attachment-card.tsx +40 -0
- package/src/message/attachment-media-machine.ts +213 -0
- package/src/message/comment-card.tsx +155 -0
- package/src/message/compaction-entrance-machine.ts +93 -0
- package/src/message/current-message.tsx +157 -0
- package/src/message/current-tool-state.ts +161 -0
- package/src/message/message-content.tsx +1391 -0
- package/src/message/paced-text-machine.ts +73 -0
- package/src/message/prompt-message.stories.tsx +149 -0
- package/src/message/relative-time.ts +45 -0
- package/src/message/user-message-quote-parts.ts +16 -0
- package/src/message/user-message-quotes.stories.tsx +797 -0
- package/src/message/user-message-quotes.tsx +135 -0
- package/src/pierre/comment-hover-machine.ts +53 -0
- package/src/pierre/comment-hover.ts +131 -0
- package/src/pierre/comment-selection-machine.ts +257 -0
- package/src/pierre/commented-lines.ts +106 -0
- package/src/pierre/diff-selection.ts +91 -0
- package/src/pierre/file-find-machine.ts +323 -0
- package/src/pierre/file-find.ts +537 -0
- package/src/pierre/file-runtime.ts +42 -0
- package/src/pierre/file-selection.ts +140 -0
- package/src/pierre/index.ts +344 -0
- package/src/pierre/media.ts +140 -0
- package/src/pierre/render-machine.ts +381 -0
- package/src/pierre/selection-bridge.ts +82 -0
- package/src/pierre/selection-machine.ts +198 -0
- package/src/pierre/virtualizer.ts +114 -0
- package/src/pierre/worker.ts +46 -0
- package/src/sources/experiment.ts +59 -0
- package/src/sources/site-icon.tsx +53 -0
- package/src/sources/sources-chip.tsx +57 -0
- package/src/sources/sources-expand-machine.ts +101 -0
- package/src/sources/sources-panel.tsx +249 -0
- package/src/sources/sources-title.tsx +21 -0
- package/src/sources/sources.css +266 -0
- package/src/sources/sources.ts +141 -0
- package/src/storybook/current-session-fixtures.ts +1492 -0
- package/src/storybook/current-session-scenarios.ts +76 -0
- package/src/storybook/current-session-story.tsx +154 -0
- package/src/storybook/index.ts +43 -0
- package/src/styles/index.css +19 -0
- package/src/timeline/__snapshots__/group-labels.test.ts.snap +110 -0
- package/src/timeline/__snapshots__/placement.test.ts.snap +1041 -0
- package/src/timeline/code-blocks.stories.tsx +105 -0
- package/src/timeline/commentary.stories.tsx +70 -0
- package/src/timeline/commentary.ts +38 -0
- package/src/timeline/detail.ts +111 -0
- package/src/timeline/error-card.stories.tsx +134 -0
- package/src/timeline/error-spacing.stories.tsx +71 -0
- package/src/timeline/facts.ts +493 -0
- package/src/timeline/file-changes.stories.tsx +436 -0
- package/src/timeline/group-label-fixtures.ts +97 -0
- package/src/timeline/mermaid.stories.tsx +131 -0
- package/src/timeline/place.ts +280 -0
- package/src/timeline/placement-fixtures.ts +365 -0
- package/src/timeline/placement-reactivity.ts +133 -0
- package/src/timeline/projection.ts +1261 -0
- package/src/timeline/research-and-agents.stories.tsx +461 -0
- package/src/timeline/session-timeline-row.tsx +1675 -0
- package/src/timeline/session-timeline.tsx +68 -0
- package/src/timeline/steer-arrival-machine.ts +134 -0
- package/src/timeline/terminal-work.stories.tsx +464 -0
- package/src/timeline/timeline-row.stories.tsx +1069 -0
- package/src/timeline/timeline-row.ts +238 -0
- package/src/timeline/turn-phase-machine.ts +112 -0
- package/src/timeline/user-message-fold.stories.tsx +194 -0
- package/src/timeline/user-runs.ts +87 -0
- package/src/timeline-next/__snapshots__/placement.test.ts.snap +990 -0
- package/src/timeline-next/compaction.tsx +236 -0
- package/src/timeline-next/errors.ts +101 -0
- package/src/timeline-next/event-row.tsx +168 -0
- package/src/timeline-next/events.ts +103 -0
- package/src/timeline-next/index.ts +10 -0
- package/src/timeline-next/nested-rail.ts +125 -0
- package/src/timeline-next/projection.ts +1028 -0
- package/src/timeline-next/row.tsx +1728 -0
- package/src/timeline-next/rules.ts +89 -0
- package/src/timeline-next/separator.tsx +73 -0
- package/src/timeline-next/spacing.ts +127 -0
- package/src/timeline-next/status-line.tsx +41 -0
- package/src/timeline-next/status.ts +33 -0
- package/src/timeline-next/stories/compare-renderer.stories.tsx +190 -0
- package/src/timeline-next/stories/compare-sessions/.gitignore +3 -0
- package/src/timeline-next/stories/compare.stories.tsx +486 -0
- package/src/timeline-next/stories/playground.stories.tsx +297 -0
- package/src/timeline-next/stories/session-replay.ts +1156 -0
- package/src/timeline-next/stories/session-timeline.tsx +50 -0
- package/src/timeline-next/stories/subagent-status.stories.tsx +132 -0
- package/src/timeline-next/timeline-next.css +649 -0
- package/src/timeline-next/tools/__snapshots__/activity-label.test.ts.snap +39 -0
- package/src/timeline-next/tools/activity-label.ts +166 -0
- package/src/timeline-next/tools/assistant-content.tsx +84 -0
- package/src/timeline-next/tools/context-group.tsx +619 -0
- package/src/timeline-next/tools/error-card.tsx +147 -0
- package/src/timeline-next/tools/explore.tsx +119 -0
- package/src/timeline-next/tools/file-group.tsx +128 -0
- package/src/timeline-next/tools/patch.tsx +174 -0
- package/src/timeline-next/tools/shell.tsx +186 -0
- package/src/timeline-next/tools/thought.tsx +87 -0
- package/src/timeline-next/tools/tool-display.tsx +119 -0
- package/src/tools/ansi.ts +8 -0
- package/src/tools/context-group-label.ts +123 -0
- package/src/tools/file-runs.ts +35 -0
- package/src/tools/project-path.ts +18 -0
- package/src/tools/read-group.stories.tsx +159 -0
- package/src/tools/run-machine.ts +185 -0
- package/src/tools/shell-output-machine.ts +233 -0
- package/src/tools/shell-output.ts +91 -0
- package/src/tools/subagent-row-variants.stories.tsx +129 -0
- package/src/tools/tool-group.stories.tsx +345 -0
- package/src/tools/tool-renderer.tsx +2876 -0
- package/src/v2/components/line-comment-annotations-v2.tsx +215 -0
- package/src/v2/components/session-file-panel-v2.tsx +149 -0
- package/src/v2/components/session-progress-indicator-v2.css +5 -0
- package/src/v2/components/session-progress-indicator-v2.stories.tsx +86 -0
- package/src/v2/components/session-progress-indicator-v2.tsx +16 -0
- package/src/v2/components/session-review-empty-changes-v2.tsx +17 -0
- package/src/v2/components/session-review-empty-no-git-v2.tsx +28 -0
- package/src/v2/components/session-review-file-preview-v2-virtualize.ts +5 -0
- package/src/v2/components/session-review-file-preview-v2.tsx +266 -0
- package/src/v2/components/session-review-v2.css +653 -0
- package/src/v2/components/session-review-v2.tsx +422 -0
- package/src/v2/components/sidebar-presence-machine.ts +69 -0
- package/tsconfig.json +20 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1612 @@
|
|
|
1
|
+
import { useI18n } from "@zyro-sec/ui/context/i18n"
|
|
2
|
+
import { abort } from "@zyro-sec/util/abort"
|
|
3
|
+
import { checksum } from "@zyro-sec/util/encode"
|
|
4
|
+
import {
|
|
5
|
+
type ComponentProps,
|
|
6
|
+
createComputed,
|
|
7
|
+
createEffect,
|
|
8
|
+
createMemo,
|
|
9
|
+
createResource,
|
|
10
|
+
createSignal,
|
|
11
|
+
createUniqueId,
|
|
12
|
+
For,
|
|
13
|
+
onCleanup,
|
|
14
|
+
type Setter,
|
|
15
|
+
splitProps,
|
|
16
|
+
untrack,
|
|
17
|
+
} from "solid-js"
|
|
18
|
+
import { isServer, render } from "solid-js/web"
|
|
19
|
+
import { Icon } from "@zyro-sec/ui/icon"
|
|
20
|
+
import { IconButton } from "@zyro-sec/ui/icon-button"
|
|
21
|
+
import { Tooltip } from "@zyro-sec/ui/tooltip"
|
|
22
|
+
import { canReusePendingBlock, completedProjection } from "./markdown-projection"
|
|
23
|
+
import type { Block, Projection } from "./markdown-stream"
|
|
24
|
+
import {
|
|
25
|
+
disposeMarkdownProjection,
|
|
26
|
+
disposeStreamingCode,
|
|
27
|
+
highlightStreamingCode,
|
|
28
|
+
MarkdownWorkerDisposedError,
|
|
29
|
+
MarkdownWorkerSupersededError,
|
|
30
|
+
MarkdownWorkerUnavailableError,
|
|
31
|
+
projectMarkdown,
|
|
32
|
+
} from "./markdown-worker"
|
|
33
|
+
import { markdownBlockKey, type MarkdownToken } from "./markdown-worker-protocol"
|
|
34
|
+
import { shouldResetCodeTokens, type RenderedCodeState } from "./markdown-code-state"
|
|
35
|
+
import {
|
|
36
|
+
getCachedMarkdown,
|
|
37
|
+
enableMarkdownAppLinks,
|
|
38
|
+
getReadyMarkdown,
|
|
39
|
+
renderCachedMarkdown,
|
|
40
|
+
touchCachedMarkdown,
|
|
41
|
+
type MarkdownCacheEntry,
|
|
42
|
+
} from "./markdown-cache"
|
|
43
|
+
import { inlineCodeKind } from "./markdown-inline-code-kind"
|
|
44
|
+
import {
|
|
45
|
+
INITIAL_CODE_DECORATION_STATE,
|
|
46
|
+
transitionCodeDecoration,
|
|
47
|
+
viewCodeDecoration,
|
|
48
|
+
type CodeDecorationEffect,
|
|
49
|
+
type CodeDecorationEvent,
|
|
50
|
+
} from "./markdown-code-machine"
|
|
51
|
+
import {
|
|
52
|
+
createMarkdownPhaseState,
|
|
53
|
+
DISPOSED_MARKDOWN_PHASE_EVENT,
|
|
54
|
+
INLINE_PATH_CHECK_TIMEOUT_MS,
|
|
55
|
+
markdownMode,
|
|
56
|
+
markdownReady,
|
|
57
|
+
transitionMarkdownPhase,
|
|
58
|
+
type MarkdownPhaseEvent,
|
|
59
|
+
} from "./markdown-phase-machine"
|
|
60
|
+
import { renderMermaidSvg } from "./markdown-mermaid"
|
|
61
|
+
import { createMarkdownRenderer } from "./markdown-solid"
|
|
62
|
+
import {
|
|
63
|
+
useMarkdown,
|
|
64
|
+
type MarkdownCodeBlock,
|
|
65
|
+
type MarkdownCodeBlockMatch,
|
|
66
|
+
type MarkdownCodeBlocks,
|
|
67
|
+
type OpenMarkdownLocalFile,
|
|
68
|
+
type ReadMarkdownImage,
|
|
69
|
+
type MarkdownLocalFileExists,
|
|
70
|
+
} from "../context/markdown"
|
|
71
|
+
import { createMarkdownImages } from "./markdown-image"
|
|
72
|
+
import { createImagePreview } from "./image-preview"
|
|
73
|
+
import { createDiagramPreview } from "./diagram-preview"
|
|
74
|
+
import { setupFragmentLinks } from "./markdown-fragment-links"
|
|
75
|
+
import { markSessionLinks, sessionReferenceClipboardText, setupSessionLinks } from "./markdown-session-links"
|
|
76
|
+
import { markdownClipboardHtml } from "./markdown-clipboard"
|
|
77
|
+
import { createCopyFeedback } from "./copy"
|
|
78
|
+
|
|
79
|
+
type RenderedBlock =
|
|
80
|
+
| (MarkdownCacheEntry & { key: string; mode: Exclude<Block["mode"], "code"> })
|
|
81
|
+
| {
|
|
82
|
+
key: string
|
|
83
|
+
mode: "code"
|
|
84
|
+
raw: string
|
|
85
|
+
hash: string
|
|
86
|
+
language: string
|
|
87
|
+
complete: boolean
|
|
88
|
+
generation: number
|
|
89
|
+
stable: MarkdownToken[]
|
|
90
|
+
unstable: MarkdownToken[]
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
type RenderResult = {
|
|
94
|
+
text: string
|
|
95
|
+
blocks: RenderedBlock[]
|
|
96
|
+
ready: boolean
|
|
97
|
+
/** Rendered from a live projection, so a stream that ends still waits for its settled render. */
|
|
98
|
+
live?: boolean
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const renderedCodeTokens = new WeakMap<HTMLDivElement, RenderedCodeState>()
|
|
102
|
+
|
|
103
|
+
const renderedMarkdown = new WeakMap<
|
|
104
|
+
HTMLDivElement,
|
|
105
|
+
{ renderer: ReturnType<typeof createMarkdownRenderer>; raw: string }
|
|
106
|
+
>()
|
|
107
|
+
|
|
108
|
+
type InlineCodeCheck = { pending?: Promise<void> }
|
|
109
|
+
|
|
110
|
+
const inlineCodeChecks = new WeakMap<HTMLDivElement, InlineCodeCheck>()
|
|
111
|
+
|
|
112
|
+
function escape(text: string) {
|
|
113
|
+
return text
|
|
114
|
+
.replace(/&/g, "&")
|
|
115
|
+
.replace(/</g, "<")
|
|
116
|
+
.replace(/>/g, ">")
|
|
117
|
+
.replace(/"/g, """)
|
|
118
|
+
.replace(/'/g, "'")
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function fallback(markdown: string) {
|
|
122
|
+
return escape(markdown).replace(/\r\n?/g, "\n").replace(/\n/g, "<br>")
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function code(text: string, language: string | undefined, key: string, complete = false) {
|
|
126
|
+
try {
|
|
127
|
+
const result = await highlightStreamingCode(key, text, language ?? "text", complete)
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
language: result.language,
|
|
131
|
+
generation: result.generation,
|
|
132
|
+
stable: result.stable,
|
|
133
|
+
unstable: result.unstable,
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (
|
|
137
|
+
!(error instanceof MarkdownWorkerDisposedError) &&
|
|
138
|
+
!(error instanceof MarkdownWorkerSupersededError) &&
|
|
139
|
+
!(error instanceof MarkdownWorkerUnavailableError)
|
|
140
|
+
)
|
|
141
|
+
console.error("Markdown highlighting worker failed", error)
|
|
142
|
+
|
|
143
|
+
const fallbackToken: MarkdownToken = [text, ""]
|
|
144
|
+
|
|
145
|
+
return { language: language ?? "text", generation: 0, stable: [], unstable: [fallbackToken] }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
type CodeLabels = {
|
|
150
|
+
copy: string
|
|
151
|
+
copied: string
|
|
152
|
+
maximize: string
|
|
153
|
+
wrap: string
|
|
154
|
+
unwrap: string
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type CodeButtonState = {
|
|
158
|
+
setLabels: Setter<CodeLabels>
|
|
159
|
+
/** Only a copy button copies. */
|
|
160
|
+
copy?: (text: string) => void
|
|
161
|
+
dispose: () => void
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const codeButtonState = new WeakMap<HTMLElement, CodeButtonState>()
|
|
165
|
+
|
|
166
|
+
const urlPattern = /^https?:\/\/[^\s<>()`"']+$/
|
|
167
|
+
|
|
168
|
+
function codeUrl(text: string) {
|
|
169
|
+
const href = text.trim().replace(/[),.;!?]+$/, "")
|
|
170
|
+
|
|
171
|
+
if (!urlPattern.test(href)) return
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
const url = new URL(href)
|
|
175
|
+
|
|
176
|
+
return url.toString()
|
|
177
|
+
} catch {
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function createCopyButton(labels: CodeLabels) {
|
|
183
|
+
const host = document.createElement("div")
|
|
184
|
+
host.setAttribute("data-slot", "markdown-copy-button")
|
|
185
|
+
|
|
186
|
+
const state: Partial<CodeButtonState> = {}
|
|
187
|
+
|
|
188
|
+
const dispose = render(() => {
|
|
189
|
+
const [labelState, setLabels] = createSignal(labels, { equals: false })
|
|
190
|
+
const copy = createCopyFeedback()
|
|
191
|
+
state.setLabels = setLabels
|
|
192
|
+
state.copy = copy.copy
|
|
193
|
+
createEffect(() => {
|
|
194
|
+
if (copy.copied()) return host.setAttribute("data-copied", "true")
|
|
195
|
+
host.removeAttribute("data-copied")
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
return <MarkdownCopyButton labels={labelState()} copied={copy.copied()} />
|
|
199
|
+
}, host)
|
|
200
|
+
|
|
201
|
+
state.dispose = dispose
|
|
202
|
+
// SAFETY: `render` runs its function synchronously, so `setLabels` and `copy` are assigned before this line.
|
|
203
|
+
codeButtonState.set(host, state as CodeButtonState)
|
|
204
|
+
|
|
205
|
+
return host
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function MarkdownCopyButton(props: { labels: CodeLabels; copied: boolean }) {
|
|
209
|
+
const label = () => (props.copied ? props.labels.copied : props.labels.copy)
|
|
210
|
+
|
|
211
|
+
return (
|
|
212
|
+
<Tooltip placement="top" value={label()} forceOpen={props.copied || undefined}>
|
|
213
|
+
<IconButton
|
|
214
|
+
type="button"
|
|
215
|
+
size="normal"
|
|
216
|
+
variant="ghost-muted"
|
|
217
|
+
aria-label={label()}
|
|
218
|
+
icon={
|
|
219
|
+
<>
|
|
220
|
+
<Icon name="copy" data-copy-icon />
|
|
221
|
+
<Icon name="check" data-check-icon />
|
|
222
|
+
</>
|
|
223
|
+
}
|
|
224
|
+
/>
|
|
225
|
+
</Tooltip>
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// A block's own wrap choice lives in its `data-wrap`; without one it follows the provider's default.
|
|
230
|
+
function createWrapButton(wrapper: HTMLElement, labels: CodeLabels, wrapDefault: () => boolean) {
|
|
231
|
+
const host = document.createElement("div")
|
|
232
|
+
host.setAttribute("data-slot", "markdown-wrap-button")
|
|
233
|
+
|
|
234
|
+
const state: Partial<CodeButtonState> = {}
|
|
235
|
+
|
|
236
|
+
const dispose = render(() => {
|
|
237
|
+
const [labelState, setLabels] = createSignal(labels, { equals: false })
|
|
238
|
+
const [override, setOverride] = createSignal<boolean>()
|
|
239
|
+
const wrapped = () => override() ?? wrapDefault()
|
|
240
|
+
const label = () => (wrapped() ? labelState().unwrap : labelState().wrap)
|
|
241
|
+
state.setLabels = setLabels
|
|
242
|
+
|
|
243
|
+
const toggle = () => {
|
|
244
|
+
const next = !wrapped()
|
|
245
|
+
// Choosing the default again follows the setting from then on.
|
|
246
|
+
const value = next === wrapDefault() ? undefined : next
|
|
247
|
+
setOverride(value)
|
|
248
|
+
|
|
249
|
+
if (value === undefined) return delete wrapper.dataset.wrap
|
|
250
|
+
wrapper.dataset.wrap = String(value)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return (
|
|
254
|
+
<Tooltip placement="top" value={label()}>
|
|
255
|
+
<IconButton
|
|
256
|
+
type="button"
|
|
257
|
+
size="normal"
|
|
258
|
+
variant="ghost-muted"
|
|
259
|
+
aria-label={label()}
|
|
260
|
+
icon={<Icon name="text-wrap" />}
|
|
261
|
+
onClick={toggle}
|
|
262
|
+
/>
|
|
263
|
+
</Tooltip>
|
|
264
|
+
)
|
|
265
|
+
}, host)
|
|
266
|
+
|
|
267
|
+
state.dispose = dispose
|
|
268
|
+
// SAFETY: `render` runs its function synchronously, so the setter is assigned before this line.
|
|
269
|
+
codeButtonState.set(host, state as CodeButtonState)
|
|
270
|
+
|
|
271
|
+
return host
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function appendCodeButtons(wrapper: HTMLElement, labels: CodeLabels, wrapDefault: () => boolean) {
|
|
275
|
+
const toolbar = document.createElement("div")
|
|
276
|
+
toolbar.setAttribute("data-slot", "markdown-code-toolbar")
|
|
277
|
+
toolbar.append(createWrapButton(wrapper, labels, wrapDefault), createCopyButton(labels))
|
|
278
|
+
wrapper.append(toolbar)
|
|
279
|
+
codeOverflow()?.observe(wrapper)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// The wrap button shows only on a block whose lines are wider than the block. Each check measures the blocks unwrapped
|
|
283
|
+
// in one synchronous layout and restores them before the observer compares sizes again, so it reports no resize.
|
|
284
|
+
let overflowObserver: ResizeObserver | undefined
|
|
285
|
+
|
|
286
|
+
function codeOverflow() {
|
|
287
|
+
if (typeof ResizeObserver === "undefined") return
|
|
288
|
+
overflowObserver ??= new ResizeObserver((entries) =>
|
|
289
|
+
measureCodeOverflow(entries.map((entry) => entry.target).filter((el) => el instanceof HTMLElement)),
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
return overflowObserver
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function isCodeWrapped(wrapper: HTMLElement) {
|
|
296
|
+
if (wrapper.dataset.wrap === "true") return true
|
|
297
|
+
|
|
298
|
+
if (wrapper.dataset.wrap === "false") return false
|
|
299
|
+
|
|
300
|
+
return !!wrapper.closest('[data-component="markdown"][data-code-wrap]')
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function measureCodeOverflow(wrappers: HTMLElement[]) {
|
|
304
|
+
// Unwrapped blocks already lay out at their unwrapped width, so reading them directly in the observer
|
|
305
|
+
// avoids forcing a style recalculation and layout.
|
|
306
|
+
const wrapped = wrappers.filter(isCodeWrapped)
|
|
307
|
+
wrapped.forEach((wrapper) => wrapper.toggleAttribute("data-code-measure", true))
|
|
308
|
+
|
|
309
|
+
const overflow = wrappers.map((wrapper) => {
|
|
310
|
+
const pre = wrapper.querySelector(":scope > pre")
|
|
311
|
+
|
|
312
|
+
return !!pre && pre.scrollWidth > pre.clientWidth
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
wrapped.forEach((wrapper) => wrapper.removeAttribute("data-code-measure"))
|
|
316
|
+
wrappers.forEach((wrapper, index) => {
|
|
317
|
+
if (wrapper.hasAttribute("data-code-overflow") !== overflow[index])
|
|
318
|
+
wrapper.toggleAttribute("data-code-overflow", overflow[index])
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// A line can grow wider without the block resizing, so a hovered block checks again before its buttons show.
|
|
323
|
+
function setupCodeOverflow(root: HTMLDivElement) {
|
|
324
|
+
const handleOver = (event: PointerEvent) => {
|
|
325
|
+
if (!(event.target instanceof Element)) return
|
|
326
|
+
const wrapper = event.target.closest('[data-component="markdown-code"]')
|
|
327
|
+
|
|
328
|
+
if (!(wrapper instanceof HTMLElement)) return
|
|
329
|
+
|
|
330
|
+
if (event.relatedTarget instanceof Node && wrapper.contains(event.relatedTarget)) return
|
|
331
|
+
measureCodeOverflow([wrapper])
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
root.addEventListener("pointerover", handleOver)
|
|
335
|
+
|
|
336
|
+
return () => root.removeEventListener("pointerover", handleOver)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const codeButtons =
|
|
340
|
+
'[data-slot="markdown-copy-button"], [data-slot="markdown-mermaid-maximize"], [data-slot="markdown-wrap-button"]'
|
|
341
|
+
|
|
342
|
+
const codeHostSelector = `${codeButtons}, [data-component="markdown-code"]`
|
|
343
|
+
|
|
344
|
+
function disposeCodeHosts(root: Element) {
|
|
345
|
+
const hosts = [
|
|
346
|
+
...(root instanceof HTMLElement && root.matches(codeHostSelector) ? [root] : []),
|
|
347
|
+
...Array.from(root.querySelectorAll(codeHostSelector)).filter((el): el is HTMLElement => el instanceof HTMLElement),
|
|
348
|
+
]
|
|
349
|
+
|
|
350
|
+
hosts.forEach((host) => {
|
|
351
|
+
disposeCodeButton(host)
|
|
352
|
+
overflowObserver?.unobserve(host)
|
|
353
|
+
codeDrivers.get(host)?.dispatch({ type: "disposed" })
|
|
354
|
+
codeDrivers.delete(host)
|
|
355
|
+
})
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function disposeCodeButton(host: HTMLElement) {
|
|
359
|
+
codeButtonState.get(host)?.dispose()
|
|
360
|
+
codeButtonState.delete(host)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Opens the diagram in a maximized view, where it zooms and pans. The click is handled by the Markdown root.
|
|
364
|
+
function createDiagramButton(labels: CodeLabels) {
|
|
365
|
+
const host = document.createElement("div")
|
|
366
|
+
host.setAttribute("data-slot", "markdown-mermaid-maximize")
|
|
367
|
+
|
|
368
|
+
const state: Partial<CodeButtonState> = {}
|
|
369
|
+
|
|
370
|
+
const dispose = render(() => {
|
|
371
|
+
const [labelState, setLabels] = createSignal(labels, { equals: false })
|
|
372
|
+
state.setLabels = setLabels
|
|
373
|
+
|
|
374
|
+
return (
|
|
375
|
+
<Tooltip placement="top" value={labelState().maximize}>
|
|
376
|
+
<IconButton
|
|
377
|
+
type="button"
|
|
378
|
+
size="normal"
|
|
379
|
+
variant="ghost-muted"
|
|
380
|
+
aria-label={labelState().maximize}
|
|
381
|
+
aria-haspopup="dialog"
|
|
382
|
+
icon={<Icon name="outline-maximize" />}
|
|
383
|
+
/>
|
|
384
|
+
</Tooltip>
|
|
385
|
+
)
|
|
386
|
+
}, host)
|
|
387
|
+
|
|
388
|
+
state.dispose = dispose
|
|
389
|
+
// SAFETY: `render` runs its function synchronously, so the setter is assigned before this line.
|
|
390
|
+
codeButtonState.set(host, state as CodeButtonState)
|
|
391
|
+
|
|
392
|
+
return host
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function disposeRenderedMarkdown(root: Element) {
|
|
396
|
+
const blocks = [
|
|
397
|
+
...(root instanceof HTMLDivElement && root.hasAttribute("data-markdown-block") ? [root] : []),
|
|
398
|
+
...Array.from(root.querySelectorAll<HTMLDivElement>("[data-markdown-block]")),
|
|
399
|
+
]
|
|
400
|
+
|
|
401
|
+
blocks.forEach((block) => {
|
|
402
|
+
renderedMarkdown.get(block)?.renderer.dispose()
|
|
403
|
+
renderedMarkdown.delete(block)
|
|
404
|
+
inlineCodeChecks.delete(block)
|
|
405
|
+
})
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const shellLanguages = new Set(["bash", "sh", "shell", "zsh", "fish", "console", "terminal"])
|
|
409
|
+
|
|
410
|
+
function codeKind(language: string | undefined) {
|
|
411
|
+
const value = language?.toLowerCase()
|
|
412
|
+
|
|
413
|
+
if (!value) return
|
|
414
|
+
|
|
415
|
+
if (shellLanguages.has(value)) return "shell"
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function applyCodeMetadata(wrapper: HTMLElement, language: string | undefined) {
|
|
419
|
+
if (language) wrapper.dataset.language = language
|
|
420
|
+
else delete wrapper.dataset.language
|
|
421
|
+
|
|
422
|
+
const kind = codeKind(language)
|
|
423
|
+
|
|
424
|
+
if (kind) wrapper.dataset.codeKind = kind
|
|
425
|
+
else delete wrapper.dataset.codeKind
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
type CodePlugins = { blocks: MarkdownCodeBlocks; match: MarkdownCodeBlockMatch }
|
|
429
|
+
|
|
430
|
+
// The plugins and labels are the driver's input for mounting; the block's phase lives only in the machine's state.
|
|
431
|
+
type CodeDriver = {
|
|
432
|
+
plugins: CodePlugins | undefined
|
|
433
|
+
labels: CodeLabels
|
|
434
|
+
dispatch: (event: CodeDecorationEvent) => void
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const codeDrivers = new WeakMap<HTMLElement, CodeDriver>()
|
|
438
|
+
|
|
439
|
+
// Plugin content mounted into a block; `dispose` arrives once the plugin's render returns.
|
|
440
|
+
type CodeContent = { host: HTMLElement; dispose?: () => void }
|
|
441
|
+
|
|
442
|
+
// Content for a block's language replaces its code only once the closing fence arrived, so it never receives half a
|
|
443
|
+
// block; until then, and when the content declines or fails, the block shows its code (or the built-in diagram).
|
|
444
|
+
// Blocks of other languages take the plain path and never get a driver.
|
|
445
|
+
function decorateCode(
|
|
446
|
+
wrapper: HTMLElement,
|
|
447
|
+
code: HTMLElement,
|
|
448
|
+
complete: boolean,
|
|
449
|
+
plugins: CodePlugins | undefined,
|
|
450
|
+
labels: CodeLabels,
|
|
451
|
+
) {
|
|
452
|
+
const language = codeLanguage(wrapper.dataset.language)
|
|
453
|
+
const existing = codeDrivers.get(wrapper)
|
|
454
|
+
|
|
455
|
+
if (!existing && !plugins && language !== "mermaid") return
|
|
456
|
+
const driver = existing ?? createCodeDriver(wrapper, labels)
|
|
457
|
+
|
|
458
|
+
if (!existing) codeDrivers.set(wrapper, driver)
|
|
459
|
+
driver.plugins = plugins
|
|
460
|
+
driver.labels = labels
|
|
461
|
+
driver.dispatch({ type: "sync", language, source: code.textContent ?? "", complete, match: plugins?.match })
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Matches the language the worker's parser puts in a block's class, so streamed and completed blocks agree.
|
|
465
|
+
function codeLanguage(language: string | undefined) {
|
|
466
|
+
return (language ?? "").toLowerCase().replace(/[^\w#+.-]/g, "")
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function createCodeDriver(wrapper: HTMLElement, labels: CodeLabels): CodeDriver {
|
|
470
|
+
let state = INITIAL_CODE_DECORATION_STATE
|
|
471
|
+
let actions: { host: HTMLElement; dispose: () => void } | undefined
|
|
472
|
+
let content: CodeContent | undefined
|
|
473
|
+
|
|
474
|
+
const dispatch = (event: CodeDecorationEvent) => {
|
|
475
|
+
const previous = state
|
|
476
|
+
const next = transitionCodeDecoration(state, event)
|
|
477
|
+
|
|
478
|
+
if (next.state === previous) return
|
|
479
|
+
state = next.state
|
|
480
|
+
showCodeDecoration(wrapper, viewCodeDecoration(previous), viewCodeDecoration(state), driver.labels)
|
|
481
|
+
next.effects.forEach(run)
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const run = (effect: CodeDecorationEffect) => {
|
|
485
|
+
if (effect.type === "clear-actions") {
|
|
486
|
+
actions?.dispose()
|
|
487
|
+
actions?.host.remove()
|
|
488
|
+
actions = undefined
|
|
489
|
+
|
|
490
|
+
return
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (effect.type === "clear-plugin") {
|
|
494
|
+
content?.dispose?.()
|
|
495
|
+
content?.host.remove()
|
|
496
|
+
content = undefined
|
|
497
|
+
|
|
498
|
+
return
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (effect.type === "render-mermaid") {
|
|
502
|
+
void renderMermaidSvg(effect.input).then(
|
|
503
|
+
(svg) => dispatch({ type: "mermaid.resolved", attempt: effect.attempt, svg }),
|
|
504
|
+
() => dispatch({ type: "mermaid.failed", attempt: effect.attempt }),
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
return
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const blocks = driver.plugins?.blocks
|
|
511
|
+
|
|
512
|
+
if (effect.type === "mount-actions") {
|
|
513
|
+
if (!blocks) return
|
|
514
|
+
actions = createCodeActions(blocks, effect.block)
|
|
515
|
+
wrapper.querySelector(':scope > [data-slot="markdown-code-toolbar"]')?.prepend(actions.host)
|
|
516
|
+
|
|
517
|
+
return
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const host = document.createElement("div")
|
|
521
|
+
host.dataset.slot = "markdown-code-content"
|
|
522
|
+
wrapper.appendChild(host)
|
|
523
|
+
const mounted: CodeContent = { host }
|
|
524
|
+
content = mounted
|
|
525
|
+
const fallback = () => dispatch({ type: "plugin.failed", attempt: effect.attempt })
|
|
526
|
+
const dispose = blocks?.render(host, effect.block, fallback)
|
|
527
|
+
|
|
528
|
+
// The content already failed while it rendered.
|
|
529
|
+
if (content !== mounted) return dispose?.()
|
|
530
|
+
|
|
531
|
+
if (!dispose) return fallback()
|
|
532
|
+
mounted.dispose = dispose
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const driver: CodeDriver = { plugins: undefined, labels, dispatch }
|
|
536
|
+
|
|
537
|
+
return driver
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function showCodeDecoration(
|
|
541
|
+
wrapper: HTMLElement,
|
|
542
|
+
previous: ReturnType<typeof viewCodeDecoration>,
|
|
543
|
+
view: ReturnType<typeof viewCodeDecoration>,
|
|
544
|
+
labels: CodeLabels,
|
|
545
|
+
) {
|
|
546
|
+
if (view.pending) wrapper.dataset.mermaidPending = "true"
|
|
547
|
+
else delete wrapper.dataset.mermaidPending
|
|
548
|
+
|
|
549
|
+
if (view.svg !== undefined) wrapper.dataset.mermaidReady = "true"
|
|
550
|
+
else delete wrapper.dataset.mermaidReady
|
|
551
|
+
wrapper.toggleAttribute("data-code-content", view.content)
|
|
552
|
+
const existing = wrapper.querySelector(':scope > [data-component="markdown-mermaid"]')
|
|
553
|
+
|
|
554
|
+
if (!view.diagram) {
|
|
555
|
+
existing?.remove()
|
|
556
|
+
const button = wrapper.querySelector<HTMLElement>(':scope > [data-slot="markdown-mermaid-maximize"]')
|
|
557
|
+
|
|
558
|
+
if (!button) return
|
|
559
|
+
disposeCodeButton(button)
|
|
560
|
+
|
|
561
|
+
return button.remove()
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const diagram = existing ?? document.createElement("div")
|
|
565
|
+
|
|
566
|
+
// The maximize button comes and goes with the diagram, and shows once it is drawn.
|
|
567
|
+
if (!existing) {
|
|
568
|
+
diagram.setAttribute("data-component", "markdown-mermaid")
|
|
569
|
+
wrapper.append(diagram, createDiagramButton(labels))
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (!existing || view.svg !== previous.svg) diagram.innerHTML = view.svg ?? ""
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function createCodeActions(blocks: MarkdownCodeBlocks, block: MarkdownCodeBlock) {
|
|
576
|
+
const host = document.createElement("div")
|
|
577
|
+
host.setAttribute("data-slot", "markdown-code-actions")
|
|
578
|
+
|
|
579
|
+
const dispose = render(
|
|
580
|
+
() => (
|
|
581
|
+
<For each={blocks.actions(block.language)}>
|
|
582
|
+
{(action) => (
|
|
583
|
+
<Tooltip placement="top" value={action.title}>
|
|
584
|
+
<IconButton
|
|
585
|
+
type="button"
|
|
586
|
+
size="normal"
|
|
587
|
+
variant="ghost-muted"
|
|
588
|
+
aria-label={action.title}
|
|
589
|
+
icon={<Icon name={action.icon} />}
|
|
590
|
+
onClick={() => action.run(block)}
|
|
591
|
+
/>
|
|
592
|
+
</Tooltip>
|
|
593
|
+
)}
|
|
594
|
+
</For>
|
|
595
|
+
),
|
|
596
|
+
host,
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
return { host, dispose }
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function markCodeLinks(root: HTMLDivElement) {
|
|
603
|
+
const codeNodes = Array.from(root.querySelectorAll(":not(pre) > code"))
|
|
604
|
+
|
|
605
|
+
for (const code of codeNodes) {
|
|
606
|
+
// Code inside a link already goes where the link does.
|
|
607
|
+
if (code.closest("a")) continue
|
|
608
|
+
const href = codeUrl(code.textContent ?? "")
|
|
609
|
+
|
|
610
|
+
if (!href) continue
|
|
611
|
+
|
|
612
|
+
const link = document.createElement("a")
|
|
613
|
+
link.href = href
|
|
614
|
+
link.className = "external-link"
|
|
615
|
+
link.target = "_blank"
|
|
616
|
+
link.rel = "noopener noreferrer"
|
|
617
|
+
code.parentNode?.replaceChild(link, code)
|
|
618
|
+
link.appendChild(code)
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// Tables scroll inside a rounded frame.
|
|
623
|
+
function wrapTables(root: HTMLDivElement) {
|
|
624
|
+
root.querySelectorAll("table").forEach((table) => {
|
|
625
|
+
const wrapper = document.createElement("div")
|
|
626
|
+
wrapper.dataset.component = "markdown-table"
|
|
627
|
+
table.replaceWith(wrapper)
|
|
628
|
+
wrapper.appendChild(table)
|
|
629
|
+
})
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const publicFaviconHost = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
|
|
633
|
+
|
|
634
|
+
const privateFaviconSuffix = /\.(?:alt|example|internal|invalid|local|localhost|onion|test|ts\.net)$/
|
|
635
|
+
|
|
636
|
+
function markExternalLinkFavicons(root: HTMLDivElement) {
|
|
637
|
+
root.querySelectorAll<HTMLAnchorElement>("a.external-link[href]").forEach((link) => {
|
|
638
|
+
if (!link.textContent?.trim() || link.querySelector("img")) return
|
|
639
|
+
|
|
640
|
+
if (!URL.canParse(link.href)) return
|
|
641
|
+
const url = new URL(link.href)
|
|
642
|
+
|
|
643
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return
|
|
644
|
+
|
|
645
|
+
const favicon = document.createElement("span")
|
|
646
|
+
favicon.className = "markdown-link-favicon"
|
|
647
|
+
favicon.setAttribute("aria-hidden", "true")
|
|
648
|
+
const host = url.hostname.toLowerCase()
|
|
649
|
+
|
|
650
|
+
if (host === "github.com") favicon.dataset.github = ""
|
|
651
|
+
else if (
|
|
652
|
+
publicFaviconHost.test(host) &&
|
|
653
|
+
!privateFaviconSuffix.test(host) &&
|
|
654
|
+
host !== "home.arpa" &&
|
|
655
|
+
!host.endsWith(".home.arpa")
|
|
656
|
+
) {
|
|
657
|
+
const image = document.createElement("img")
|
|
658
|
+
image.src = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(url.host)}&sz=32`
|
|
659
|
+
favicon.style.setProperty("--markdown-link-favicon", `url("${image.src}")`)
|
|
660
|
+
image.alt = ""
|
|
661
|
+
image.setAttribute("data-markdown-favicon", "")
|
|
662
|
+
image.width = 14
|
|
663
|
+
image.height = 14
|
|
664
|
+
image.decoding = "async"
|
|
665
|
+
favicon.appendChild(image)
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
link.insertBefore(favicon, link.firstChild)
|
|
669
|
+
})
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// The globe stands in only until the favicon loads, then the favicon replaces it so a transparent one hides it.
|
|
673
|
+
function showFavicon(image: HTMLImageElement) {
|
|
674
|
+
image.dataset.loaded = ""
|
|
675
|
+
image.parentElement?.setAttribute("data-loaded", "")
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function setupExternalLinkFavicons(root: HTMLDivElement) {
|
|
679
|
+
const loaded = (event: Event) => {
|
|
680
|
+
const image = event.target
|
|
681
|
+
|
|
682
|
+
if (!(image instanceof HTMLImageElement) || !image.hasAttribute("data-markdown-favicon")) return
|
|
683
|
+
|
|
684
|
+
if (image.naturalWidth > 0) showFavicon(image)
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
root.addEventListener("load", loaded, true)
|
|
688
|
+
|
|
689
|
+
return () => root.removeEventListener("load", loaded, true)
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// A path becomes a link once `localFileExists` says the file exists. A streaming block skips the check: its last code
|
|
693
|
+
// span may still be half written, and the block renders again once it completes.
|
|
694
|
+
function markInlineCode(
|
|
695
|
+
source: HTMLDivElement,
|
|
696
|
+
target: HTMLDivElement,
|
|
697
|
+
live: boolean,
|
|
698
|
+
signal: AbortSignal,
|
|
699
|
+
localFileExists?: MarkdownLocalFileExists,
|
|
700
|
+
) {
|
|
701
|
+
const check: InlineCodeCheck = {}
|
|
702
|
+
inlineCodeChecks.set(target, check)
|
|
703
|
+
const checked = new Map<string, boolean | Promise<boolean>>()
|
|
704
|
+
const pending: Promise<void>[] = []
|
|
705
|
+
|
|
706
|
+
for (const code of source.querySelectorAll<HTMLElement>(":not(pre) > code")) {
|
|
707
|
+
delete code.dataset.inlineCodeKind
|
|
708
|
+
const text = (code.textContent ?? "").trim()
|
|
709
|
+
const kind = inlineCodeKind(text)
|
|
710
|
+
|
|
711
|
+
if (kind === "url") code.dataset.inlineCodeKind = kind
|
|
712
|
+
|
|
713
|
+
// Code inside a link already goes where the link does.
|
|
714
|
+
if (kind !== "path" || live || !localFileExists || code.closest("a")) continue
|
|
715
|
+
|
|
716
|
+
const previous = checked.get(text)
|
|
717
|
+
|
|
718
|
+
if (previous !== undefined) {
|
|
719
|
+
if (previous === true) code.dataset.inlineCodeKind = "path"
|
|
720
|
+
|
|
721
|
+
continue
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const exists = localFileExists(text)
|
|
725
|
+
checked.set(text, exists)
|
|
726
|
+
|
|
727
|
+
// Decorate the source before it is inserted or copied into a live Markdown renderer.
|
|
728
|
+
if (exists === true || exists === false) {
|
|
729
|
+
if (exists) code.dataset.inlineCodeKind = "path"
|
|
730
|
+
|
|
731
|
+
continue
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
pending.push(
|
|
735
|
+
exists
|
|
736
|
+
.then((exists) => {
|
|
737
|
+
if (!exists || signal.aborted || inlineCodeChecks.get(target) !== check) return
|
|
738
|
+
target.querySelectorAll<HTMLElement>(":not(pre) > code").forEach((node) => {
|
|
739
|
+
if (!node.closest("a") && (node.textContent ?? "").trim() === text) node.dataset.inlineCodeKind = "path"
|
|
740
|
+
})
|
|
741
|
+
})
|
|
742
|
+
.catch(() => undefined),
|
|
743
|
+
)
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
if (pending.length === 0) return
|
|
747
|
+
|
|
748
|
+
check.pending = Promise.all(pending).then(() => {
|
|
749
|
+
if (inlineCodeChecks.get(target) === check) inlineCodeChecks.delete(target)
|
|
750
|
+
})
|
|
751
|
+
|
|
752
|
+
return check.pending
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function localLinkTarget(target: EventTarget | null) {
|
|
756
|
+
if (!(target instanceof Element)) return
|
|
757
|
+
const link = target.closest("a[data-local-link]")
|
|
758
|
+
|
|
759
|
+
if (link instanceof HTMLElement) return link.dataset.localLink
|
|
760
|
+
// Bare inline paths such as `src/app.ts` open like links when the host can resolve them.
|
|
761
|
+
const code = target.closest(':not(pre) > code[data-inline-code-kind="path"]')
|
|
762
|
+
|
|
763
|
+
if (code instanceof HTMLElement && !code.closest("a")) return code.textContent?.trim() || undefined
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function setupLocalLinks(root: HTMLDivElement, open: () => OpenMarkdownLocalFile | undefined) {
|
|
767
|
+
const handleClick = (event: MouseEvent) => {
|
|
768
|
+
if (event.defaultPrevented || event.button !== 0) return
|
|
769
|
+
const path = localLinkTarget(event.target)
|
|
770
|
+
|
|
771
|
+
if (!path) return
|
|
772
|
+
const handler = open()
|
|
773
|
+
|
|
774
|
+
if (!handler) return
|
|
775
|
+
event.preventDefault()
|
|
776
|
+
handler(path)
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const handleKeyDown = (event: KeyboardEvent) => {
|
|
780
|
+
if (event.key !== "Enter" || event.defaultPrevented) return
|
|
781
|
+
|
|
782
|
+
if (!(event.target instanceof HTMLElement) || !event.target.matches("a[data-local-link]")) return
|
|
783
|
+
const path = event.target.dataset.localLink
|
|
784
|
+
const handler = open()
|
|
785
|
+
|
|
786
|
+
if (!path || !handler) return
|
|
787
|
+
event.preventDefault()
|
|
788
|
+
handler(path)
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
root.addEventListener("click", handleClick)
|
|
792
|
+
root.addEventListener("keydown", handleKeyDown)
|
|
793
|
+
|
|
794
|
+
return () => {
|
|
795
|
+
root.removeEventListener("click", handleClick)
|
|
796
|
+
root.removeEventListener("keydown", handleKeyDown)
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// Each button owns its feedback, so a block replaced mid-feedback drops its reset timer with its host.
|
|
801
|
+
function setupCodeCopy(root: HTMLDivElement) {
|
|
802
|
+
const handleClick = (event: MouseEvent) => {
|
|
803
|
+
const target = event.target
|
|
804
|
+
|
|
805
|
+
if (!(target instanceof Element)) return
|
|
806
|
+
|
|
807
|
+
const button = target.closest('[data-slot="markdown-copy-button"]')
|
|
808
|
+
|
|
809
|
+
if (!(button instanceof HTMLElement)) return
|
|
810
|
+
const code = button.closest('[data-component="markdown-code"]')?.querySelector("code")
|
|
811
|
+
codeButtonState.get(button)?.copy?.(code?.textContent ?? "")
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
root.addEventListener("click", handleClick)
|
|
815
|
+
|
|
816
|
+
return () => {
|
|
817
|
+
root.removeEventListener("click", handleClick)
|
|
818
|
+
disposeCodeHosts(root)
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// Selections that leave this message keep the browser's copy, since surrounding UI may hold hidden content.
|
|
823
|
+
function copySelection(event: ClipboardEvent & { currentTarget: HTMLDivElement }) {
|
|
824
|
+
const selection = window.getSelection()
|
|
825
|
+
|
|
826
|
+
if (event.defaultPrevented || !event.clipboardData || !selection || selection.isCollapsed) return
|
|
827
|
+
const ranges = Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index))
|
|
828
|
+
|
|
829
|
+
if (!ranges.every((range) => event.currentTarget.contains(range.commonAncestorContainer))) return
|
|
830
|
+
event.preventDefault()
|
|
831
|
+
event.clipboardData.setData(
|
|
832
|
+
"text/plain",
|
|
833
|
+
sessionReferenceClipboardText(event.currentTarget, ranges) ?? selection.toString(),
|
|
834
|
+
)
|
|
835
|
+
event.clipboardData.setData(
|
|
836
|
+
"text/html",
|
|
837
|
+
`<meta charset="utf-8">${ranges.map((range) => markdownClipboardHtml(event.currentTarget, range)).join("")}`,
|
|
838
|
+
)
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function initialResult(
|
|
842
|
+
text: string,
|
|
843
|
+
key: string | undefined,
|
|
844
|
+
projection: Projection,
|
|
845
|
+
owner: string,
|
|
846
|
+
deferUntilReady: boolean | undefined,
|
|
847
|
+
): RenderResult {
|
|
848
|
+
if (!text) return { text, blocks: [], ready: true }
|
|
849
|
+
const base = key ?? checksum(text)
|
|
850
|
+
|
|
851
|
+
if (base) {
|
|
852
|
+
const blocks = projection.blocks.flatMap((block, index) => {
|
|
853
|
+
if (block.mode === "code") return []
|
|
854
|
+
const cacheKey = `${base}:${index}:${block.mode}`
|
|
855
|
+
const cached = block.mode === "full" ? getReadyMarkdown(block, cacheKey) : getCachedMarkdown(cacheKey)
|
|
856
|
+
|
|
857
|
+
if (cached?.raw !== block.raw) return []
|
|
858
|
+
|
|
859
|
+
if (block.mode !== "full") touchCachedMarkdown(cacheKey, cached)
|
|
860
|
+
|
|
861
|
+
return [{ key: `${owner}:${cacheKey}`, mode: block.mode, ...cached }]
|
|
862
|
+
})
|
|
863
|
+
|
|
864
|
+
if (blocks.length === projection.blocks.length) return { text, blocks, ready: true }
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
if (deferUntilReady) return { text, blocks: [], ready: false }
|
|
868
|
+
|
|
869
|
+
return {
|
|
870
|
+
text,
|
|
871
|
+
ready: false,
|
|
872
|
+
blocks: [
|
|
873
|
+
{
|
|
874
|
+
key: "initial",
|
|
875
|
+
mode: "full",
|
|
876
|
+
raw: text,
|
|
877
|
+
hash: checksum(text) ?? "",
|
|
878
|
+
html: fallback(text),
|
|
879
|
+
},
|
|
880
|
+
],
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function pendingProjection(text: string): Projection {
|
|
885
|
+
return { text, blocks: text ? [{ raw: text, src: text, mode: "live" }] : [] }
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export function Markdown(
|
|
889
|
+
props: ComponentProps<"div"> & {
|
|
890
|
+
text: string
|
|
891
|
+
cacheKey?: string
|
|
892
|
+
streaming?: boolean
|
|
893
|
+
deferUntilReady?: boolean
|
|
894
|
+
class?: string
|
|
895
|
+
classList?: Record<string, boolean>
|
|
896
|
+
},
|
|
897
|
+
) {
|
|
898
|
+
const [local, others] = splitProps(props, ["text", "cacheKey", "streaming", "deferUntilReady", "class", "classList"])
|
|
899
|
+
const i18n = useI18n()
|
|
900
|
+
const markdown = useMarkdown()
|
|
901
|
+
const previewImages = createImagePreview()
|
|
902
|
+
const previewDiagrams = createDiagramPreview()
|
|
903
|
+
const wrapDefault = () => !!markdown?.codeWrap
|
|
904
|
+
const [root, setRoot] = createSignal<HTMLDivElement>()
|
|
905
|
+
const owner = createUniqueId()
|
|
906
|
+
const lifetime = new AbortController()
|
|
907
|
+
const activeCodeKeys = new Set<string>()
|
|
908
|
+
const completedCode = new Map<string, Extract<RenderedBlock, { mode: "code" }>>()
|
|
909
|
+
const settledMarkdown = new Map<string, Exclude<RenderedBlock, { mode: "code" }>>()
|
|
910
|
+
let renderedBlocks: RenderedBlock[] = []
|
|
911
|
+
let lastRender: { base: string | undefined; blocks: Block[]; rendered: RenderedBlock[] } | undefined
|
|
912
|
+
let appliedLabels: CodeLabels | undefined
|
|
913
|
+
// The code block languages the blocks were decorated for; false before the first run.
|
|
914
|
+
let decoratedMatch: MarkdownCodeBlockMatch | undefined | false = false
|
|
915
|
+
// Every streamed delta dispatches a rendered event, so the driver reuses its events and the machine returns the same
|
|
916
|
+
// state when nothing changed.
|
|
917
|
+
const [phase, setPhase] = createSignal(createMarkdownPhaseState(!!local.streaming))
|
|
918
|
+
const mode = createMemo(() => markdownMode(phase()))
|
|
919
|
+
const syncEvent = { type: "props.sync" as const, streaming: false }
|
|
920
|
+
const renderedEvent = { type: "dom.rendered" as const, rendered: false, pendingChecks: 0, reused: false }
|
|
921
|
+
let checkTimer: ReturnType<typeof setTimeout> | undefined
|
|
922
|
+
|
|
923
|
+
const dispatchPhase = (event: MarkdownPhaseEvent, checks?: Promise<void>[]) => {
|
|
924
|
+
const previous = untrack(phase)
|
|
925
|
+
const next = transitionMarkdownPhase(previous, event)
|
|
926
|
+
|
|
927
|
+
if (next === previous) return
|
|
928
|
+
const started = next.status === "checking" && (previous.status !== "checking" || previous.attempt !== next.attempt)
|
|
929
|
+
|
|
930
|
+
if (previous.status === "checking" && (next.status !== "checking" || started)) {
|
|
931
|
+
clearTimeout(checkTimer)
|
|
932
|
+
checkTimer = undefined
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
if (next.status === "disposed") {
|
|
936
|
+
if (markdownMode(previous) !== "static") disposeMarkdownProjection(owner)
|
|
937
|
+
|
|
938
|
+
return
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
setPhase(next)
|
|
942
|
+
// The timeline observes this attribute, and toggling it to its current value records no mutation.
|
|
943
|
+
untrack(root)?.toggleAttribute("data-markdown-ready", markdownReady(next))
|
|
944
|
+
|
|
945
|
+
if (!started) return
|
|
946
|
+
const attempt = next.attempt
|
|
947
|
+
checkTimer = setTimeout(() => dispatchPhase({ type: "checks.timed-out", attempt }), INLINE_PATH_CHECK_TIMEOUT_MS)
|
|
948
|
+
// Each check catches its own failure, so this always settles.
|
|
949
|
+
void Promise.all(checks ?? []).then(() => dispatchPhase({ type: "checks.settled", attempt }))
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// Runs before the resources below read the mode, so a stream that ends never projects with the old mode.
|
|
953
|
+
createComputed(() => {
|
|
954
|
+
syncEvent.streaming = !!local.streaming
|
|
955
|
+
dispatchPhase(syncEvent)
|
|
956
|
+
})
|
|
957
|
+
|
|
958
|
+
const [projection] = createResource(
|
|
959
|
+
() => {
|
|
960
|
+
if (isServer || mode() === "static") return
|
|
961
|
+
|
|
962
|
+
return { key: owner, text: local.text, live: mode() === "streaming" }
|
|
963
|
+
},
|
|
964
|
+
// A failed projection renders the text unprojected, so the block still settles and the next delta projects again.
|
|
965
|
+
// The result names the mode it was projected for, so a settled render never uses the last live projection.
|
|
966
|
+
(src) =>
|
|
967
|
+
projectMarkdown(src.key, src.text, src.live)
|
|
968
|
+
.catch((error) => {
|
|
969
|
+
if (
|
|
970
|
+
!(error instanceof MarkdownWorkerDisposedError) &&
|
|
971
|
+
!(error instanceof MarkdownWorkerSupersededError) &&
|
|
972
|
+
!(error instanceof MarkdownWorkerUnavailableError)
|
|
973
|
+
)
|
|
974
|
+
console.error("Markdown projection worker failed", error)
|
|
975
|
+
|
|
976
|
+
return src.live ? pendingProjection(src.text) : completedProjection(src.text)
|
|
977
|
+
})
|
|
978
|
+
.then((value) => ({ text: value.text, blocks: value.blocks, live: src.live })),
|
|
979
|
+
{ initialValue: { text: "", blocks: [], live: true } },
|
|
980
|
+
)
|
|
981
|
+
|
|
982
|
+
const currentProjection = () => {
|
|
983
|
+
if (mode() === "static") return completedProjection(local.text)
|
|
984
|
+
const value = projection.latest
|
|
985
|
+
|
|
986
|
+
if (value?.text === local.text) return value
|
|
987
|
+
|
|
988
|
+
if (value?.text) return value
|
|
989
|
+
|
|
990
|
+
return pendingProjection(local.text)
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
const initial = {
|
|
994
|
+
...initialResult(
|
|
995
|
+
local.text,
|
|
996
|
+
local.cacheKey,
|
|
997
|
+
local.streaming ? pendingProjection(local.text) : completedProjection(local.text),
|
|
998
|
+
owner,
|
|
999
|
+
local.deferUntilReady,
|
|
1000
|
+
),
|
|
1001
|
+
live: !!local.streaming,
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const [html] = createResource(
|
|
1005
|
+
() => {
|
|
1006
|
+
if (isServer)
|
|
1007
|
+
return {
|
|
1008
|
+
text: local.text,
|
|
1009
|
+
key: local.cacheKey,
|
|
1010
|
+
mode: "static" as const,
|
|
1011
|
+
projection: pendingProjection(local.text),
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (mode() === "static")
|
|
1015
|
+
return { text: local.text, key: local.cacheKey, mode: mode(), projection: completedProjection(local.text) }
|
|
1016
|
+
const value = projection.latest
|
|
1017
|
+
|
|
1018
|
+
if (value.text !== local.text || value.live !== (mode() === "streaming")) return
|
|
1019
|
+
|
|
1020
|
+
return {
|
|
1021
|
+
text: local.text,
|
|
1022
|
+
key: local.cacheKey,
|
|
1023
|
+
mode: mode(),
|
|
1024
|
+
projection: value,
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
(src): RenderResult | Promise<RenderResult> => {
|
|
1028
|
+
const live = src.mode === "streaming"
|
|
1029
|
+
|
|
1030
|
+
if (isServer)
|
|
1031
|
+
return {
|
|
1032
|
+
text: src.text,
|
|
1033
|
+
ready: true,
|
|
1034
|
+
live,
|
|
1035
|
+
blocks: [
|
|
1036
|
+
{
|
|
1037
|
+
key: "server",
|
|
1038
|
+
mode: "full" as const,
|
|
1039
|
+
raw: src.text,
|
|
1040
|
+
hash: checksum(src.text) ?? "",
|
|
1041
|
+
html: fallback(src.text),
|
|
1042
|
+
},
|
|
1043
|
+
],
|
|
1044
|
+
} satisfies RenderResult
|
|
1045
|
+
|
|
1046
|
+
if (!src.text) return { text: src.text, blocks: [], ready: true, live } satisfies RenderResult
|
|
1047
|
+
|
|
1048
|
+
if (src.mode === "static" && initial.ready && initial.text === src.text) return initial
|
|
1049
|
+
|
|
1050
|
+
const base = src.key ?? (src.mode === "static" ? checksum(src.text) : undefined)
|
|
1051
|
+
|
|
1052
|
+
const render = async (block: Block, index: number): Promise<RenderedBlock> => {
|
|
1053
|
+
const key = base ? `${base}:${index}:${block.mode}` : undefined
|
|
1054
|
+
const blockKey = markdownBlockKey(owner, src.key, index, block.mode)
|
|
1055
|
+
|
|
1056
|
+
if (block.mode === "code") {
|
|
1057
|
+
const cached = completedCode.get(blockKey)
|
|
1058
|
+
|
|
1059
|
+
if (block.complete && cached?.raw === block.raw) return cached
|
|
1060
|
+
const result = await code(block.src, block.language, blockKey, block.complete)
|
|
1061
|
+
|
|
1062
|
+
const rendered = {
|
|
1063
|
+
key: blockKey,
|
|
1064
|
+
mode: block.mode,
|
|
1065
|
+
raw: block.raw,
|
|
1066
|
+
hash: String(block.raw.length),
|
|
1067
|
+
complete: !!block.complete,
|
|
1068
|
+
...result,
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
if (block.complete) completedCode.set(blockKey, rendered)
|
|
1072
|
+
|
|
1073
|
+
return rendered
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
if (block.mode === "full") {
|
|
1077
|
+
const settled = settledMarkdown.get(blockKey)
|
|
1078
|
+
|
|
1079
|
+
if (settled && (settled.src ?? settled.raw) === block.src) {
|
|
1080
|
+
if (key) {
|
|
1081
|
+
const cached = getCachedMarkdown(key)
|
|
1082
|
+
|
|
1083
|
+
if (cached) touchCachedMarkdown(key, cached)
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
return settled
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
const ready = block.mode === "full" ? getReadyMarkdown(block, key) : undefined
|
|
1091
|
+
const entry = ready ?? (await renderCachedMarkdown(block, key, lifetime.signal))
|
|
1092
|
+
|
|
1093
|
+
if (block.mode === "full") {
|
|
1094
|
+
const settled = {
|
|
1095
|
+
key: blockKey,
|
|
1096
|
+
mode: block.mode,
|
|
1097
|
+
...entry,
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
settledMarkdown.set(blockKey, settled)
|
|
1101
|
+
|
|
1102
|
+
return settled
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
return {
|
|
1106
|
+
key: blockKey,
|
|
1107
|
+
mode: block.mode,
|
|
1108
|
+
...entry,
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// The worker keeps an unchanged block as the same object, so the block the last render made from it is reused.
|
|
1113
|
+
// Rendering every block of the answer again on each delta cost a promise and two key strings per block.
|
|
1114
|
+
const previous = lastRender?.base === base ? lastRender : undefined
|
|
1115
|
+
|
|
1116
|
+
const queued = src.projection.blocks.map((block, index) =>
|
|
1117
|
+
previous?.blocks[index] === block ? previous.rendered[index]! : render(block, index),
|
|
1118
|
+
)
|
|
1119
|
+
|
|
1120
|
+
return Promise.all(
|
|
1121
|
+
queued.flatMap((item, index) =>
|
|
1122
|
+
item instanceof Promise ? [item.then((block) => [index, block] as const)] : [],
|
|
1123
|
+
),
|
|
1124
|
+
)
|
|
1125
|
+
.then((done) => {
|
|
1126
|
+
const resolved = new Map(done)
|
|
1127
|
+
const blocks = queued.map((item, index) => (item instanceof Promise ? resolved.get(index)! : item))
|
|
1128
|
+
lastRender = { base, blocks: src.projection.blocks, rendered: blocks }
|
|
1129
|
+
|
|
1130
|
+
return { text: src.text, blocks, ready: true, live } satisfies RenderResult
|
|
1131
|
+
})
|
|
1132
|
+
.catch(
|
|
1133
|
+
() =>
|
|
1134
|
+
(lifetime.signal.aborted
|
|
1135
|
+
? { text: src.text, blocks: [], ready: false, live }
|
|
1136
|
+
: {
|
|
1137
|
+
text: src.text,
|
|
1138
|
+
ready: true,
|
|
1139
|
+
live,
|
|
1140
|
+
blocks: [
|
|
1141
|
+
{
|
|
1142
|
+
key: base ?? "fallback",
|
|
1143
|
+
mode: "full" as const,
|
|
1144
|
+
raw: src.text,
|
|
1145
|
+
hash: checksum(src.text) ?? "",
|
|
1146
|
+
html: fallback(src.text),
|
|
1147
|
+
},
|
|
1148
|
+
],
|
|
1149
|
+
}) satisfies RenderResult,
|
|
1150
|
+
)
|
|
1151
|
+
},
|
|
1152
|
+
{ initialValue: initial },
|
|
1153
|
+
)
|
|
1154
|
+
|
|
1155
|
+
let copyCleanup: (() => void) | undefined
|
|
1156
|
+
let overflowCleanup: (() => void) | undefined
|
|
1157
|
+
let linkCleanup: (() => void) | undefined
|
|
1158
|
+
let diagramCleanup: (() => void) | undefined
|
|
1159
|
+
let faviconCleanup: (() => void) | undefined
|
|
1160
|
+
let sessionLinkCleanup: (() => void) | undefined
|
|
1161
|
+
let fragmentLinkCleanup: (() => void) | undefined
|
|
1162
|
+
let readImage: ReadMarkdownImage | undefined
|
|
1163
|
+
let images: ReturnType<typeof createMarkdownImages> | undefined
|
|
1164
|
+
|
|
1165
|
+
createEffect(() => {
|
|
1166
|
+
const container = root()
|
|
1167
|
+
const result = html.latest ?? html()
|
|
1168
|
+
const projected = currentProjection()
|
|
1169
|
+
const content = local.text ? pendingBlocks(result, projected, local.cacheKey, owner, local.deferUntilReady) : []
|
|
1170
|
+
|
|
1171
|
+
if (!container) return
|
|
1172
|
+
|
|
1173
|
+
if (isServer) return
|
|
1174
|
+
|
|
1175
|
+
if (readImage !== markdown?.readImage) {
|
|
1176
|
+
images?.dispose()
|
|
1177
|
+
readImage = markdown?.readImage
|
|
1178
|
+
images = readImage ? createMarkdownImages(readImage) : undefined
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
const codeBlocks = markdown?.codeBlocks
|
|
1182
|
+
const match = codeBlocks?.current()
|
|
1183
|
+
|
|
1184
|
+
const plugins =
|
|
1185
|
+
codeBlocks && match && (match.render.size > 0 || match.actions.size > 0)
|
|
1186
|
+
? { blocks: codeBlocks, match }
|
|
1187
|
+
: undefined
|
|
1188
|
+
|
|
1189
|
+
const redecorate = decoratedMatch !== false && decoratedMatch !== match
|
|
1190
|
+
decoratedMatch = match
|
|
1191
|
+
renderedEvent.rendered = !!result?.ready && result.text === local.text && !!result.live === (mode() === "streaming")
|
|
1192
|
+
|
|
1193
|
+
if (content.length === 0) {
|
|
1194
|
+
renderedEvent.reused = renderedBlocks.length === 0
|
|
1195
|
+
renderedBlocks = []
|
|
1196
|
+
disposeCodeHosts(container)
|
|
1197
|
+
disposeRenderedMarkdown(container)
|
|
1198
|
+
container.innerHTML = ""
|
|
1199
|
+
images?.update(container)
|
|
1200
|
+
renderedEvent.pendingChecks = 0
|
|
1201
|
+
dispatchPhase(renderedEvent)
|
|
1202
|
+
|
|
1203
|
+
return
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
const labels = {
|
|
1207
|
+
copy: i18n.t("ui.message.copy"),
|
|
1208
|
+
copied: i18n.t("ui.message.copied"),
|
|
1209
|
+
maximize: i18n.t("ui.diagramPreview.open"),
|
|
1210
|
+
wrap: i18n.t("ui.message.wrapLines"),
|
|
1211
|
+
unwrap: i18n.t("ui.message.unwrapLines"),
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const nextCodeKeys = new Set(content.filter((block) => block.mode === "code").map((block) => block.key))
|
|
1215
|
+
activeCodeKeys.forEach((key) => {
|
|
1216
|
+
if (!nextCodeKeys.has(key)) disposeCode(key)
|
|
1217
|
+
})
|
|
1218
|
+
activeCodeKeys.clear()
|
|
1219
|
+
nextCodeKeys.forEach((key) => activeCodeKeys.add(key))
|
|
1220
|
+
const sessionLinks = markdown?.sessionTitle
|
|
1221
|
+
const localFileExists = markdown?.localFileExists
|
|
1222
|
+
|
|
1223
|
+
renderedEvent.reused = content.length === renderedBlocks.length
|
|
1224
|
+
|
|
1225
|
+
const pending = content.flatMap((block, index) => {
|
|
1226
|
+
const current = container.children[index]
|
|
1227
|
+
const kept = renderedBlocks[index] === block && current instanceof HTMLDivElement
|
|
1228
|
+
|
|
1229
|
+
if (!kept) renderedEvent.reused = false
|
|
1230
|
+
|
|
1231
|
+
const check = kept
|
|
1232
|
+
? inlineCodeChecks.get(current)?.pending
|
|
1233
|
+
: updateBlock(
|
|
1234
|
+
container,
|
|
1235
|
+
index,
|
|
1236
|
+
block,
|
|
1237
|
+
labels,
|
|
1238
|
+
wrapDefault,
|
|
1239
|
+
plugins,
|
|
1240
|
+
sessionLinks,
|
|
1241
|
+
lifetime.signal,
|
|
1242
|
+
markdown?.appLinks,
|
|
1243
|
+
localFileExists,
|
|
1244
|
+
)
|
|
1245
|
+
|
|
1246
|
+
return check ? [check] : []
|
|
1247
|
+
})
|
|
1248
|
+
|
|
1249
|
+
renderedBlocks = content
|
|
1250
|
+
|
|
1251
|
+
// Blocks kept from earlier runs follow a plugin that starts or stops handling their language.
|
|
1252
|
+
if (redecorate)
|
|
1253
|
+
container.querySelectorAll<HTMLElement>('[data-component="markdown-code"]').forEach((wrapper) => {
|
|
1254
|
+
const code = wrapper.querySelector<HTMLElement>(":scope > pre > code")
|
|
1255
|
+
|
|
1256
|
+
if (code)
|
|
1257
|
+
decorateCode(wrapper, code, wrapper.parentElement?.dataset.markdownComplete !== "false", plugins, labels)
|
|
1258
|
+
})
|
|
1259
|
+
|
|
1260
|
+
if (sessionLinks) markSessionLinks(container, sessionLinks)
|
|
1261
|
+
|
|
1262
|
+
while (container.children.length > content.length) {
|
|
1263
|
+
const child = container.lastElementChild
|
|
1264
|
+
|
|
1265
|
+
if (!child) break
|
|
1266
|
+
disposeCodeHosts(child)
|
|
1267
|
+
disposeRenderedMarkdown(child)
|
|
1268
|
+
child.remove()
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
images?.update(container)
|
|
1272
|
+
previewImages(container)
|
|
1273
|
+
container.querySelectorAll<HTMLImageElement>("img[data-markdown-favicon]").forEach((image) => {
|
|
1274
|
+
if (image.complete && image.naturalWidth > 0) showFavicon(image)
|
|
1275
|
+
})
|
|
1276
|
+
|
|
1277
|
+
// A button gets the labels of the run that creates it, so the others only need new ones when the language changes.
|
|
1278
|
+
// Relabelling every button on each streamed delta re-rendered each one's tooltip and icon button.
|
|
1279
|
+
if (
|
|
1280
|
+
appliedLabels?.copy !== labels.copy ||
|
|
1281
|
+
appliedLabels?.copied !== labels.copied ||
|
|
1282
|
+
appliedLabels?.maximize !== labels.maximize ||
|
|
1283
|
+
appliedLabels?.wrap !== labels.wrap ||
|
|
1284
|
+
appliedLabels?.unwrap !== labels.unwrap
|
|
1285
|
+
)
|
|
1286
|
+
container
|
|
1287
|
+
.querySelectorAll<HTMLElement>(codeButtons)
|
|
1288
|
+
.forEach((button) => codeButtonState.get(button)?.setLabels(labels))
|
|
1289
|
+
|
|
1290
|
+
appliedLabels = labels
|
|
1291
|
+
|
|
1292
|
+
if (!copyCleanup) copyCleanup = setupCodeCopy(container)
|
|
1293
|
+
|
|
1294
|
+
if (!overflowCleanup) overflowCleanup = setupCodeOverflow(container)
|
|
1295
|
+
|
|
1296
|
+
if (!linkCleanup) linkCleanup = setupLocalLinks(container, () => markdown?.openLocalFile)
|
|
1297
|
+
|
|
1298
|
+
if (!diagramCleanup) diagramCleanup = previewDiagrams(container)
|
|
1299
|
+
|
|
1300
|
+
if (!sessionLinkCleanup)
|
|
1301
|
+
sessionLinkCleanup = setupSessionLinks(
|
|
1302
|
+
container,
|
|
1303
|
+
() => markdown?.openSession,
|
|
1304
|
+
() => markdown?.sessionMenu,
|
|
1305
|
+
)
|
|
1306
|
+
|
|
1307
|
+
if (!fragmentLinkCleanup) fragmentLinkCleanup = setupFragmentLinks(container)
|
|
1308
|
+
|
|
1309
|
+
if (!faviconCleanup) faviconCleanup = setupExternalLinkFavicons(container)
|
|
1310
|
+
container.toggleAttribute("data-local-links", !!markdown?.openLocalFile)
|
|
1311
|
+
// Cold timelines already wait for Markdown readiness before measuring and revealing their content. Include
|
|
1312
|
+
// path classification so the first visible frame uses the final blue-link styling and padding.
|
|
1313
|
+
renderedEvent.pendingChecks = pending.length
|
|
1314
|
+
dispatchPhase(renderedEvent, pending)
|
|
1315
|
+
})
|
|
1316
|
+
|
|
1317
|
+
onCleanup(() => {
|
|
1318
|
+
abort(lifetime)
|
|
1319
|
+
images?.dispose()
|
|
1320
|
+
|
|
1321
|
+
if (copyCleanup) copyCleanup()
|
|
1322
|
+
|
|
1323
|
+
if (overflowCleanup) overflowCleanup()
|
|
1324
|
+
|
|
1325
|
+
if (linkCleanup) linkCleanup()
|
|
1326
|
+
|
|
1327
|
+
if (diagramCleanup) diagramCleanup()
|
|
1328
|
+
|
|
1329
|
+
if (sessionLinkCleanup) sessionLinkCleanup()
|
|
1330
|
+
|
|
1331
|
+
if (fragmentLinkCleanup) fragmentLinkCleanup()
|
|
1332
|
+
|
|
1333
|
+
if (faviconCleanup) faviconCleanup()
|
|
1334
|
+
const container = root()
|
|
1335
|
+
|
|
1336
|
+
if (container) disposeRenderedMarkdown(container)
|
|
1337
|
+
|
|
1338
|
+
dispatchPhase(DISPOSED_MARKDOWN_PHASE_EVENT)
|
|
1339
|
+
activeCodeKeys.forEach(disposeCode)
|
|
1340
|
+
completedCode.clear()
|
|
1341
|
+
settledMarkdown.clear()
|
|
1342
|
+
renderedBlocks = []
|
|
1343
|
+
})
|
|
1344
|
+
|
|
1345
|
+
return (
|
|
1346
|
+
<div
|
|
1347
|
+
data-component="markdown"
|
|
1348
|
+
data-streaming={local.streaming ? "" : undefined}
|
|
1349
|
+
data-code-wrap={wrapDefault() ? "" : undefined}
|
|
1350
|
+
dir="auto"
|
|
1351
|
+
classList={{
|
|
1352
|
+
...local.classList,
|
|
1353
|
+
[local.class ?? ""]: !!local.class,
|
|
1354
|
+
}}
|
|
1355
|
+
ref={setRoot}
|
|
1356
|
+
onCopy={copySelection}
|
|
1357
|
+
{...others}
|
|
1358
|
+
/>
|
|
1359
|
+
)
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
function pendingBlocks(
|
|
1363
|
+
result: RenderResult | undefined,
|
|
1364
|
+
projection: Projection | undefined,
|
|
1365
|
+
cacheKey: string | undefined,
|
|
1366
|
+
owner: string,
|
|
1367
|
+
deferUntilReady: boolean | undefined,
|
|
1368
|
+
) {
|
|
1369
|
+
if (!result) return []
|
|
1370
|
+
|
|
1371
|
+
if (!projection || result.text === projection.text) return result.blocks
|
|
1372
|
+
|
|
1373
|
+
if (deferUntilReady) return result.blocks
|
|
1374
|
+
const initial = result.blocks.length === 1 && result.blocks[0]?.key === "initial"
|
|
1375
|
+
|
|
1376
|
+
return projection.blocks.map((block, index) => {
|
|
1377
|
+
const current = initial ? undefined : result.blocks[index]
|
|
1378
|
+
|
|
1379
|
+
if (current && canReusePendingBlock(current, block)) return current
|
|
1380
|
+
const key = markdownBlockKey(owner, cacheKey, index, block.mode)
|
|
1381
|
+
|
|
1382
|
+
if (block.mode !== "code")
|
|
1383
|
+
return { key, mode: block.mode, raw: block.raw, hash: String(block.raw.length), html: fallback(block.src) }
|
|
1384
|
+
|
|
1385
|
+
const fallbackToken: MarkdownToken = [block.src, ""]
|
|
1386
|
+
|
|
1387
|
+
return {
|
|
1388
|
+
key,
|
|
1389
|
+
mode: block.mode,
|
|
1390
|
+
raw: block.raw,
|
|
1391
|
+
hash: String(block.raw.length),
|
|
1392
|
+
language: block.language ?? "text",
|
|
1393
|
+
complete: !!block.complete,
|
|
1394
|
+
stable: [],
|
|
1395
|
+
generation: 0,
|
|
1396
|
+
unstable: [fallbackToken],
|
|
1397
|
+
}
|
|
1398
|
+
})
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
function disposeCode(key: string) {
|
|
1402
|
+
disposeStreamingCode(key)
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
function updateBlock(
|
|
1406
|
+
container: HTMLDivElement,
|
|
1407
|
+
index: number,
|
|
1408
|
+
block: RenderedBlock,
|
|
1409
|
+
labels: CodeLabels,
|
|
1410
|
+
wrapDefault: () => boolean,
|
|
1411
|
+
plugins: CodePlugins | undefined,
|
|
1412
|
+
sessionLinks: ((id: string) => string | undefined) | undefined,
|
|
1413
|
+
signal: AbortSignal,
|
|
1414
|
+
appLinks: boolean | undefined,
|
|
1415
|
+
localFileExists?: MarkdownLocalFileExists,
|
|
1416
|
+
) {
|
|
1417
|
+
const current = container.children[index]
|
|
1418
|
+
|
|
1419
|
+
if (block.mode === "code") {
|
|
1420
|
+
updateCodeBlock(container, current, block, labels, wrapDefault, plugins)
|
|
1421
|
+
|
|
1422
|
+
return
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
const existing =
|
|
1426
|
+
current instanceof HTMLDivElement && current.dataset.markdownKey === block.key && !renderedCodeTokens.has(current)
|
|
1427
|
+
? current
|
|
1428
|
+
: undefined
|
|
1429
|
+
|
|
1430
|
+
if (existing?.dataset.markdownHash === block.hash) {
|
|
1431
|
+
// A block that finishes streaming keeps its DOM and the user's selection; only its file paths get checked now.
|
|
1432
|
+
if (existing.dataset.markdownMode === "live" && block.mode !== "live") {
|
|
1433
|
+
existing.dataset.markdownMode = block.mode
|
|
1434
|
+
|
|
1435
|
+
return markInlineCode(existing, existing, false, signal, localFileExists)
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
return inlineCodeChecks.get(existing)?.pending
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
const next = existing ?? document.createElement("div")
|
|
1442
|
+
next.dataset.markdownBlock = ""
|
|
1443
|
+
next.dataset.markdownKey = block.key
|
|
1444
|
+
next.dataset.markdownHash = block.hash
|
|
1445
|
+
next.dataset.markdownMode = block.mode
|
|
1446
|
+
next.style.display = "contents"
|
|
1447
|
+
const rendered = renderedMarkdown.get(next)
|
|
1448
|
+
// Keep live renderers in control of their DOM, including after completion.
|
|
1449
|
+
const source = rendered || block.mode === "live" ? document.createElement("div") : next
|
|
1450
|
+
|
|
1451
|
+
if (source === next) disposeCodeHosts(next)
|
|
1452
|
+
source.innerHTML = block.html
|
|
1453
|
+
|
|
1454
|
+
if (appLinks) enableMarkdownAppLinks(source)
|
|
1455
|
+
const pending = markInlineCode(source, next, block.mode === "live", signal, localFileExists)
|
|
1456
|
+
markCodeLinks(source)
|
|
1457
|
+
wrapTables(source)
|
|
1458
|
+
|
|
1459
|
+
if (sessionLinks) markSessionLinks(source, sessionLinks)
|
|
1460
|
+
markExternalLinkFavicons(source)
|
|
1461
|
+
|
|
1462
|
+
if (rendered) {
|
|
1463
|
+
rendered.renderer.update(source, block.mode === "live", rendered.raw !== block.raw)
|
|
1464
|
+
rendered.raw = block.raw
|
|
1465
|
+
|
|
1466
|
+
return pending
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
if (block.mode === "live") {
|
|
1470
|
+
next.replaceChildren()
|
|
1471
|
+
renderedMarkdown.set(next, {
|
|
1472
|
+
renderer: createMarkdownRenderer(next, source, true),
|
|
1473
|
+
raw: block.raw,
|
|
1474
|
+
})
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
if (block.mode !== "live") {
|
|
1478
|
+
next.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
|
|
1479
|
+
const pre = code.parentElement!
|
|
1480
|
+
const wrapper = document.createElement("div")
|
|
1481
|
+
wrapper.dataset.component = "markdown-code"
|
|
1482
|
+
applyCodeMetadata(
|
|
1483
|
+
wrapper,
|
|
1484
|
+
Array.from(code.classList)
|
|
1485
|
+
.find((name) => name.startsWith("language-"))
|
|
1486
|
+
?.slice(9),
|
|
1487
|
+
)
|
|
1488
|
+
pre.replaceWith(wrapper)
|
|
1489
|
+
wrapper.appendChild(pre)
|
|
1490
|
+
appendCodeButtons(wrapper, labels, wrapDefault)
|
|
1491
|
+
decorateCode(wrapper, code, true, plugins, labels)
|
|
1492
|
+
})
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
if (existing) return pending
|
|
1496
|
+
|
|
1497
|
+
if (!current) {
|
|
1498
|
+
container.appendChild(next)
|
|
1499
|
+
|
|
1500
|
+
return pending
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
disposeCodeHosts(current)
|
|
1504
|
+
disposeRenderedMarkdown(current)
|
|
1505
|
+
current.replaceWith(next)
|
|
1506
|
+
|
|
1507
|
+
return pending
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function updateCodeBlock(
|
|
1511
|
+
container: HTMLDivElement,
|
|
1512
|
+
current: Element | undefined,
|
|
1513
|
+
block: Extract<RenderedBlock, { mode: "code" }>,
|
|
1514
|
+
labels: CodeLabels,
|
|
1515
|
+
wrapDefault: () => boolean,
|
|
1516
|
+
plugins: CodePlugins | undefined,
|
|
1517
|
+
) {
|
|
1518
|
+
const existing =
|
|
1519
|
+
current instanceof HTMLDivElement && current.dataset.markdownKey === block.key && renderedCodeTokens.has(current)
|
|
1520
|
+
? current
|
|
1521
|
+
: undefined
|
|
1522
|
+
|
|
1523
|
+
const next = existing ?? document.createElement("div")
|
|
1524
|
+
next.dataset.markdownBlock = ""
|
|
1525
|
+
next.dataset.markdownKey = block.key
|
|
1526
|
+
next.dataset.markdownHash = block.hash
|
|
1527
|
+
next.dataset.markdownComplete = block.complete ? "true" : "false"
|
|
1528
|
+
next.style.display = "contents"
|
|
1529
|
+
|
|
1530
|
+
const code = existing?.querySelector("code")
|
|
1531
|
+
|
|
1532
|
+
if (code instanceof HTMLElement) {
|
|
1533
|
+
const wrapper = code.closest('[data-component="markdown-code"]')
|
|
1534
|
+
|
|
1535
|
+
if (wrapper instanceof HTMLElement) applyCodeMetadata(wrapper, block.language)
|
|
1536
|
+
code.className = `language-${block.language}`
|
|
1537
|
+
const previous = renderedCodeTokens.get(next)
|
|
1538
|
+
|
|
1539
|
+
const reset = shouldResetCodeTokens(previous, {
|
|
1540
|
+
language: block.language,
|
|
1541
|
+
generation: block.generation,
|
|
1542
|
+
stableCount: block.stable.length,
|
|
1543
|
+
raw: block.raw,
|
|
1544
|
+
})
|
|
1545
|
+
|
|
1546
|
+
const stableCount = reset ? 0 : previous!.stableCount
|
|
1547
|
+
const tail = [...block.stable.slice(stableCount), ...block.unstable]
|
|
1548
|
+
const prior = reset ? [] : previous!.unstable
|
|
1549
|
+
const prefix = prior.findIndex((token, index) => !sameToken(token, tail[index]))
|
|
1550
|
+
const keep = stableCount + (prefix < 0 ? Math.min(prior.length, tail.length) : prefix)
|
|
1551
|
+
|
|
1552
|
+
while (code.children.length > keep) code.lastElementChild?.remove()
|
|
1553
|
+
tail
|
|
1554
|
+
.slice(keep - stableCount)
|
|
1555
|
+
.map(createTokenSpan)
|
|
1556
|
+
.forEach((span) => code.appendChild(span))
|
|
1557
|
+
renderedCodeTokens.set(next, {
|
|
1558
|
+
language: block.language,
|
|
1559
|
+
generation: block.generation,
|
|
1560
|
+
stableCount: block.stable.length,
|
|
1561
|
+
unstable: block.unstable,
|
|
1562
|
+
raw: block.raw,
|
|
1563
|
+
})
|
|
1564
|
+
|
|
1565
|
+
if (wrapper instanceof HTMLElement) decorateCode(wrapper, code, block.complete, plugins, labels)
|
|
1566
|
+
|
|
1567
|
+
return
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
const wrapper = document.createElement("div")
|
|
1571
|
+
wrapper.setAttribute("data-component", "markdown-code")
|
|
1572
|
+
applyCodeMetadata(wrapper, block.language)
|
|
1573
|
+
const pre = document.createElement("pre")
|
|
1574
|
+
pre.className = "highlights"
|
|
1575
|
+
const codeElement = document.createElement("code")
|
|
1576
|
+
codeElement.className = `language-${block.language}`
|
|
1577
|
+
;[...block.stable, ...block.unstable].map(createTokenSpan).forEach((span) => codeElement.appendChild(span))
|
|
1578
|
+
pre.appendChild(codeElement)
|
|
1579
|
+
wrapper.appendChild(pre)
|
|
1580
|
+
appendCodeButtons(wrapper, labels, wrapDefault)
|
|
1581
|
+
decorateCode(wrapper, codeElement, block.complete, plugins, labels)
|
|
1582
|
+
next.appendChild(wrapper)
|
|
1583
|
+
renderedCodeTokens.set(next, {
|
|
1584
|
+
language: block.language,
|
|
1585
|
+
generation: block.generation,
|
|
1586
|
+
stableCount: block.stable.length,
|
|
1587
|
+
unstable: block.unstable,
|
|
1588
|
+
raw: block.raw,
|
|
1589
|
+
})
|
|
1590
|
+
|
|
1591
|
+
if (current) {
|
|
1592
|
+
disposeCodeHosts(current)
|
|
1593
|
+
disposeRenderedMarkdown(current)
|
|
1594
|
+
current.replaceWith(next)
|
|
1595
|
+
|
|
1596
|
+
return
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
container.appendChild(next)
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function sameToken(left: MarkdownToken, right: MarkdownToken | undefined) {
|
|
1603
|
+
return !!right && left[0] === right[0] && left[1] === right[1]
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
function createTokenSpan(token: MarkdownToken) {
|
|
1607
|
+
const span = document.createElement("span")
|
|
1608
|
+
span.setAttribute("style", token[1])
|
|
1609
|
+
span.textContent = token[0]
|
|
1610
|
+
|
|
1611
|
+
return span
|
|
1612
|
+
}
|