@k2b/ui 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/browser/content/MarkdownView.js +13 -5
- package/dist/browser/content/MarkdownView.js.map +1 -1
- package/dist/browser/content/PdfPreview.js +5 -2
- package/dist/browser/content/PdfPreview.js.map +1 -1
- package/dist/browser/content/index.js +1 -0
- package/dist/browser/content/index.js.map +1 -1
- package/dist/browser/content/markdown-info-blocks.js +363 -0
- package/dist/browser/content/markdown-info-blocks.js.map +1 -0
- package/dist/browser/feedback/InstallGuide.js +267 -0
- package/dist/browser/feedback/InstallGuide.js.map +1 -0
- package/dist/browser/feedback/announce.js +50 -0
- package/dist/browser/feedback/announce.js.map +1 -0
- package/dist/browser/feedback/dialog-core.js +88 -2
- package/dist/browser/feedback/dialog-core.js.map +1 -1
- package/dist/browser/feedback/index.js +4 -0
- package/dist/browser/feedback/index.js.map +1 -1
- package/dist/browser/feedback/install.js +99 -0
- package/dist/browser/feedback/install.js.map +1 -0
- package/dist/browser/feedback/prompts.js +11 -1
- package/dist/browser/feedback/prompts.js.map +1 -1
- package/dist/browser/feedback/theme-color.js +15 -0
- package/dist/browser/feedback/theme-color.js.map +1 -0
- package/dist/browser/feedback/toast.js +10 -44
- package/dist/browser/feedback/toast.js.map +1 -1
- package/dist/browser/inputs/QrScanner.js +164 -0
- package/dist/browser/inputs/QrScanner.js.map +1 -0
- package/dist/browser/inputs/index.js +1 -0
- package/dist/browser/inputs/index.js.map +1 -1
- package/dist/browser/intl/messages.js +96 -2
- package/dist/browser/intl/messages.js.map +1 -1
- package/dist/browser/layout/Discussion.js +2 -1
- package/dist/browser/layout/Discussion.js.map +1 -1
- package/dist/browser/layout/MobileShell.js +284 -0
- package/dist/browser/layout/MobileShell.js.map +1 -0
- package/dist/browser/layout/TabBar.js +69 -0
- package/dist/browser/layout/TabBar.js.map +1 -0
- package/dist/browser/layout/index.js +2 -0
- package/dist/browser/layout/index.js.map +1 -1
- package/dist/browser/surfaces/NoticeCard.js +55 -60
- package/dist/browser/surfaces/NoticeCard.js.map +1 -1
- package/dist/browser/surfaces/index.js +1 -1
- package/dist/browser/surfaces/index.js.map +1 -1
- package/dist/ssr/content/MarkdownView.js +13 -5
- package/dist/ssr/content/MarkdownView.js.map +1 -1
- package/dist/ssr/content/PdfPreview.js +4 -2
- package/dist/ssr/content/PdfPreview.js.map +1 -1
- package/dist/ssr/content/index.js +1 -0
- package/dist/ssr/content/index.js.map +1 -1
- package/dist/ssr/content/markdown-info-blocks.js +363 -0
- package/dist/ssr/content/markdown-info-blocks.js.map +1 -0
- package/dist/ssr/feedback/InstallGuide.js +201 -0
- package/dist/ssr/feedback/InstallGuide.js.map +1 -0
- package/dist/ssr/feedback/announce.js +50 -0
- package/dist/ssr/feedback/announce.js.map +1 -0
- package/dist/ssr/feedback/dialog-core.js +88 -2
- package/dist/ssr/feedback/dialog-core.js.map +1 -1
- package/dist/ssr/feedback/index.js +4 -0
- package/dist/ssr/feedback/index.js.map +1 -1
- package/dist/ssr/feedback/install.js +99 -0
- package/dist/ssr/feedback/install.js.map +1 -0
- package/dist/ssr/feedback/prompts.js +11 -1
- package/dist/ssr/feedback/prompts.js.map +1 -1
- package/dist/ssr/feedback/theme-color.js +15 -0
- package/dist/ssr/feedback/theme-color.js.map +1 -0
- package/dist/ssr/feedback/toast.js +10 -44
- package/dist/ssr/feedback/toast.js.map +1 -1
- package/dist/ssr/inputs/QrScanner.js +128 -0
- package/dist/ssr/inputs/QrScanner.js.map +1 -0
- package/dist/ssr/inputs/index.js +1 -0
- package/dist/ssr/inputs/index.js.map +1 -1
- package/dist/ssr/intl/messages.js +96 -2
- package/dist/ssr/intl/messages.js.map +1 -1
- package/dist/ssr/layout/Discussion.js +2 -1
- package/dist/ssr/layout/Discussion.js.map +1 -1
- package/dist/ssr/layout/MobileShell.js +253 -0
- package/dist/ssr/layout/MobileShell.js.map +1 -0
- package/dist/ssr/layout/TabBar.js +25 -0
- package/dist/ssr/layout/TabBar.js.map +1 -0
- package/dist/ssr/layout/index.js +2 -0
- package/dist/ssr/layout/index.js.map +1 -1
- package/dist/ssr/surfaces/NoticeCard.js +21 -30
- package/dist/ssr/surfaces/NoticeCard.js.map +1 -1
- package/dist/ssr/surfaces/index.js +1 -1
- package/dist/ssr/surfaces/index.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/tabler.css +1 -1
- package/dist/types/content/MarkdownView.d.ts +6 -2
- package/dist/types/content/index.d.ts +1 -0
- package/dist/types/content/markdown-info-blocks.d.ts +67 -0
- package/dist/types/feedback/InstallGuide.d.ts +26 -0
- package/dist/types/feedback/announce.d.ts +19 -0
- package/dist/types/feedback/dialog-core.d.ts +5 -0
- package/dist/types/feedback/index.d.ts +7 -0
- package/dist/types/feedback/install.d.ts +32 -0
- package/dist/types/feedback/prompts.d.ts +2 -0
- package/dist/types/feedback/theme-color.d.ts +6 -0
- package/dist/types/inputs/QrScanner.d.ts +20 -0
- package/dist/types/inputs/index.d.ts +2 -0
- package/dist/types/intl/messages.d.ts +47 -0
- package/dist/types/layout/MobileShell.d.ts +40 -0
- package/dist/types/layout/TabBar.d.ts +26 -0
- package/dist/types/layout/index.d.ts +4 -0
- package/dist/types/surfaces/NoticeCard.d.ts +4 -4
- package/dist/types/surfaces/index.d.ts +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -61,7 +61,7 @@ See the [TextInput guide](https://cloud.k2b.dev/en/ui/input/text) for details.
|
|
|
61
61
|
| Inputs | Text fields, selectors, date pickers, file inputs |
|
|
62
62
|
| Layout | Panels, settings, split panes, floating windows |
|
|
63
63
|
| Surfaces | Cards, avatars, badges, empty states |
|
|
64
|
-
| Feedback | Dialogs, prompts, tooltips, toasts |
|
|
64
|
+
| Feedback | Dialogs, prompts, tooltips, toasts, screen-reader announcements |
|
|
65
65
|
| Content | Tables, charts, calendars, Markdown, file previews |
|
|
66
66
|
| Chat | Timeline, messages, composer, context usage |
|
|
67
67
|
| Widgets | Dashboard summaries, lists, statistics |
|
|
@@ -5,7 +5,9 @@ import { className as _$className } from "solid-js/web";
|
|
|
5
5
|
import { effect as _$effect } from "solid-js/web";
|
|
6
6
|
import { getNextElement as _$getNextElement } from "solid-js/web";
|
|
7
7
|
var _tmpl$ = /*#__PURE__*/_$template(`<div>`);
|
|
8
|
-
import {
|
|
8
|
+
import { Marked, Renderer } from "marked";
|
|
9
|
+
import { useLocale } from "../intl/locale";
|
|
10
|
+
import { markdownInfoBlocks } from "./markdown-info-blocks";
|
|
9
11
|
const escapeHtml = value => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
10
12
|
const safeUrl = value => {
|
|
11
13
|
const normalized = value.trim().replace(/[\u0000-\u001f\u007f-\u009f\s]+/g, "");
|
|
@@ -110,7 +112,9 @@ const createSafeRenderer = (options = {}) => {
|
|
|
110
112
|
};
|
|
111
113
|
return renderer;
|
|
112
114
|
};
|
|
113
|
-
export const renderSafeMarkdown = (markdown, options = {}) =>
|
|
115
|
+
export const renderSafeMarkdown = (markdown, options = {}) => new Marked(markdownInfoBlocks({
|
|
116
|
+
locale: options.locale
|
|
117
|
+
})).parse(markdown, {
|
|
114
118
|
async: false,
|
|
115
119
|
renderer: createSafeRenderer(options)
|
|
116
120
|
});
|
|
@@ -119,8 +123,10 @@ export const renderSafeMarkdown = (markdown, options = {}) => marked.parse(markd
|
|
|
119
123
|
* Markdown View Component (SSR)
|
|
120
124
|
*
|
|
121
125
|
* Renders untrusted Markdown safely by default. Raw HTML and unsafe link
|
|
122
|
-
* protocols are escaped.
|
|
123
|
-
* `
|
|
126
|
+
* protocols are escaped. Info blocks (`:::note`, `:::info`, `:::success`,
|
|
127
|
+
* `:::warning`, `:::danger`) render as the calm `NoticeCard`. Already-rendered
|
|
128
|
+
* HTML requires the deliberately named `trustedHtml` boundary; the caller owns
|
|
129
|
+
* sanitization in that mode.
|
|
124
130
|
*
|
|
125
131
|
* @example
|
|
126
132
|
* ```tsx
|
|
@@ -135,11 +141,13 @@ export const renderSafeMarkdown = (markdown, options = {}) => marked.parse(markd
|
|
|
135
141
|
* ```
|
|
136
142
|
*/
|
|
137
143
|
export default function MarkdownView(props) {
|
|
144
|
+
const locale = useLocale();
|
|
138
145
|
const html = () => props.markdown !== undefined ? renderSafeMarkdown(props.markdown, {
|
|
139
146
|
inlineTokens: props.inlineTokens,
|
|
140
147
|
allowImages: props.allowImages,
|
|
141
148
|
linkProtocols: props.linkProtocols,
|
|
142
|
-
linkTarget: props.linkTarget
|
|
149
|
+
linkTarget: props.linkTarget,
|
|
150
|
+
locale: locale()
|
|
143
151
|
}) : props.trustedHtml;
|
|
144
152
|
return (() => {
|
|
145
153
|
var _el$ = _$getNextElement(_tmpl$);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["content/MarkdownView.tsx"],"sourcesContent":["import { marked, Renderer, type Tokens } from \"marked\";\n\ntype CommonProps = MarkdownRenderOptions & {\n /** Optional additional CSS classes */\n class?: string;\n /**\n * Visual heading scale. Markdown heading levels and document structure stay\n * unchanged.\n */\n headingScale?: \"compact\" | \"normal\" | \"large\";\n};\n\nexport type MarkdownViewProps = CommonProps &\n (\n | {\n /** Untrusted Markdown. Raw HTML and unsafe link protocols are escaped. */\n markdown: string;\n /** Exact standalone text tokens to emphasize without changing Markdown parsing or trusted-HTML boundaries. */\n inlineTokens?: readonly string[];\n trustedHtml?: never;\n }\n | {\n /** Explicitly trusted, already-rendered HTML. The caller owns sanitization. */\n trustedHtml: string;\n markdown?: never;\n inlineTokens?: never;\n }\n );\n\nexport type MarkdownRenderOptions = {\n inlineTokens?: readonly string[];\n /** Whether to render images. False renders alt text without resource requests. Defaults to true. */\n allowImages?: boolean;\n /** Optional protocol allowlist, including trailing colons. Relative URLs resolve as HTTPS. */\n linkProtocols?: readonly string[];\n linkTarget?: \"_blank\";\n};\n\nconst escapeHtml = (value: string): string =>\n value.replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll('\"', \""\").replaceAll(\"'\", \"'\");\n\nconst safeUrl = (value: string): string | null => {\n const normalized = value.trim().replace(/[\\u0000-\\u001f\\u007f-\\u009f\\s]+/g, \"\");\n if (/^(?:javascript|vbscript|data):/i.test(normalized)) return null;\n return value;\n};\n\nconst normalizeInlineTokens = (tokens: readonly string[] | undefined): string[] =>\n [...new Set(tokens?.filter(Boolean) ?? [])].sort((left, right) => right.length - left.length);\n\nconst isStandaloneInlineToken = (text: string, start: number, value: string): boolean => {\n const before = text[start - 1];\n if (before && /[a-zA-Z0-9_.%+\\-]/.test(before)) return false;\n const end = start + value.length;\n const after = text[end];\n if (after && /[a-zA-Z0-9_@]/.test(after)) return false;\n return !(after === \".\" && /[a-zA-Z0-9_]/.test(text[end + 1] ?? \"\"));\n};\n\nconst createSafeRenderer = (options: MarkdownRenderOptions = {}): Renderer => {\n const renderer = new Renderer();\n const inlineTokens = normalizeInlineTokens(options.inlineTokens);\n const baseText = renderer.text.bind(renderer);\n // marked flags text that follows an inline <pre>, <code>, <kbd> or <script>\n // tag as already escaped, because it expects that tag to reach the output as\n // HTML. The tag is escaped here, so the text after it is escaped as well.\n const renderText: Renderer[\"text\"] = (token) => baseText(token.type === \"text\" && token.escaped ? { ...token, escaped: false } : token);\n const renderTable = renderer.table.bind(renderer);\n renderer.table = (token: Tokens.Table) => {\n const table = renderTable(token);\n const content = token.header.every((cell) => !cell.text.trim()) ? table.replace(/<thead>[\\s\\S]*?<\\/thead>\\n?/, \"\") : table;\n return `<div class=\"k2b-content-markdown__table\" tabindex=\"0\">${content}</div>`;\n };\n renderer.html = ({ text }: Tokens.HTML | Tokens.Tag) => escapeHtml(text);\n renderer.link = function ({ href, title, tokens }: Tokens.Link) {\n const body = this.parser.parseInline(tokens);\n const url = safeUrl(href);\n if (!url) return body;\n if (options.linkProtocols) {\n try {\n if (!options.linkProtocols.includes(new URL(url, \"https://markdown.invalid/\").protocol)) return body;\n } catch {\n return body;\n }\n }\n const titleAttribute = title ? ` title=\"${escapeHtml(title)}\"` : \"\";\n const target = options.linkTarget === \"_blank\" ? ' target=\"_blank\" rel=\"noopener noreferrer\"' : \"\";\n return `<a href=\"${escapeHtml(url)}\"${titleAttribute}${target}>${body}</a>`;\n };\n renderer.image = ({ href, title, text }: Tokens.Image) => {\n const url = safeUrl(href);\n if (!url || options.allowImages === false) return escapeHtml(text);\n const titleAttribute = title ? ` title=\"${escapeHtml(title)}\"` : \"\";\n return `<img src=\"${escapeHtml(url)}\" alt=\"${escapeHtml(text)}\"${titleAttribute}>`;\n };\n renderer.text = (token) => {\n if (inlineTokens.length === 0 || token.type === \"escape\" || (\"tokens\" in token && token.tokens)) return renderText(token);\n const parts: string[] = [];\n let plainStart = 0;\n let cursor = 0;\n while (cursor < token.text.length) {\n const inlineToken = inlineTokens.find(\n (candidate) => token.text.startsWith(candidate, cursor) && isStandaloneInlineToken(token.text, cursor, candidate),\n );\n if (!inlineToken) {\n cursor += 1;\n continue;\n }\n if (plainStart < cursor) {\n const text = token.text.slice(plainStart, cursor);\n parts.push(renderText({ ...token, raw: text, text }));\n }\n parts.push(\n `<span class=\"k2b-content-markdown__inline-token\">${renderText({ ...token, raw: inlineToken, text: inlineToken })}</span>`,\n );\n cursor += inlineToken.length;\n plainStart = cursor;\n }\n if (plainStart === 0) return renderText(token);\n if (plainStart < token.text.length) {\n const text = token.text.slice(plainStart);\n parts.push(renderText({ ...token, raw: text, text }));\n }\n return parts.join(\"\");\n };\n return renderer;\n};\n\nexport const renderSafeMarkdown = (markdown: string, options: MarkdownRenderOptions = {}): string =>\n marked.parse(markdown, {\n async: false,\n renderer: createSafeRenderer(options),\n }) as string;\n\n/**\n * Markdown View Component (SSR)\n *\n * Renders untrusted Markdown safely by default. Raw HTML and unsafe link\n * protocols are escaped. Already-rendered HTML requires the deliberately named\n * `trustedHtml` boundary; the caller owns sanitization in that mode.\n *\n * @example\n * ```tsx\n * import { MarkdownView } from \"@k2b/ui\";\n *\n * <MarkdownView markdown={source} />;\n * ```\n *\n * @example Compact headings, e.g. inside comments or file previews:\n * ```tsx\n * <MarkdownView markdown={source} headingScale=\"compact\" />;\n * ```\n */\nexport default function MarkdownView(props: MarkdownViewProps) {\n const html = () =>\n props.markdown !== undefined\n ? renderSafeMarkdown(props.markdown, {\n inlineTokens: props.inlineTokens,\n allowImages: props.allowImages,\n linkProtocols: props.linkProtocols,\n linkTarget: props.linkTarget,\n })\n : props.trustedHtml;\n return (\n <div\n class={`k2b-content-markdown ${props.class ?? \"\"}`}\n data-heading-scale={props.headingScale && props.headingScale !== \"normal\" ? props.headingScale : undefined}\n innerHTML={html()}\n />\n );\n}\n"],"mappings":";;;;;;;AAAA,SAAS,MAAM,EAAE,QAAQ,QAAqB,QAAQ;AAsCtD,MAAM,UAAU,GAAI,KAAa,IAC/B,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;AAEnI,MAAM,OAAO,GAAI,KAAa,IAAoB;EAChD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,kCAAkC,EAAE,EAAE,CAAC;EAC/E,IAAI,iCAAiC,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI;EACnE,OAAO,KAAK;AACd,CAAC;AAED,MAAM,qBAAqB,GAAI,MAAqC,IAClE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC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CAAC,CAAC;MAAA;MAAA;MAAA;MAAA;IAAA;MAAA;MAAA;MAAA;IAAA;IAAA;EAAA;AAGvB","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":[],"sources":["content/MarkdownView.tsx"],"sourcesContent":["import { Marked, Renderer, type Tokens } from \"marked\";\nimport { useLocale } from \"../intl/locale\";\nimport { markdownInfoBlocks } from \"./markdown-info-blocks\";\n\ntype CommonProps = MarkdownRenderOptions & {\n /** Optional additional CSS classes */\n class?: string;\n /**\n * Visual heading scale. Markdown heading levels and document structure stay\n * unchanged.\n */\n headingScale?: \"compact\" | \"normal\" | \"large\";\n};\n\nexport type MarkdownViewProps = CommonProps &\n (\n | {\n /** Untrusted Markdown. Raw HTML and unsafe link protocols are escaped. */\n markdown: string;\n /** Exact standalone text tokens to emphasize without changing Markdown parsing or trusted-HTML boundaries. */\n inlineTokens?: readonly string[];\n trustedHtml?: never;\n }\n | {\n /** Explicitly trusted, already-rendered HTML. The caller owns sanitization. */\n trustedHtml: string;\n markdown?: never;\n inlineTokens?: never;\n }\n );\n\nexport type MarkdownRenderOptions = {\n inlineTokens?: readonly string[];\n /** Whether to render images. False renders alt text without resource requests. Defaults to true. */\n allowImages?: boolean;\n /** Optional protocol allowlist, including trailing colons. Relative URLs resolve as HTTPS. */\n linkProtocols?: readonly string[];\n linkTarget?: \"_blank\";\n /** Locale for the screen-reader names of untitled info blocks. `MarkdownView` passes the inherited render locale. */\n locale?: string;\n};\n\nconst escapeHtml = (value: string): string =>\n value.replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\").replaceAll('\"', \""\").replaceAll(\"'\", \"'\");\n\nconst safeUrl = (value: string): string | null => {\n const normalized = value.trim().replace(/[\\u0000-\\u001f\\u007f-\\u009f\\s]+/g, \"\");\n if (/^(?:javascript|vbscript|data):/i.test(normalized)) return null;\n return value;\n};\n\nconst normalizeInlineTokens = (tokens: readonly string[] | undefined): string[] =>\n [...new Set(tokens?.filter(Boolean) ?? [])].sort((left, right) => right.length - left.length);\n\nconst isStandaloneInlineToken = (text: string, start: number, value: string): boolean => {\n const before = text[start - 1];\n if (before && /[a-zA-Z0-9_.%+\\-]/.test(before)) return false;\n const end = start + value.length;\n const after = text[end];\n if (after && /[a-zA-Z0-9_@]/.test(after)) return false;\n return !(after === \".\" && /[a-zA-Z0-9_]/.test(text[end + 1] ?? \"\"));\n};\n\nconst createSafeRenderer = (options: MarkdownRenderOptions = {}): Renderer => {\n const renderer = new Renderer();\n const inlineTokens = normalizeInlineTokens(options.inlineTokens);\n const baseText = renderer.text.bind(renderer);\n // marked flags text that follows an inline <pre>, <code>, <kbd> or <script>\n // tag as already escaped, because it expects that tag to reach the output as\n // HTML. The tag is escaped here, so the text after it is escaped as well.\n const renderText: Renderer[\"text\"] = (token) => baseText(token.type === \"text\" && token.escaped ? { ...token, escaped: false } : token);\n const renderTable = renderer.table.bind(renderer);\n renderer.table = (token: Tokens.Table) => {\n const table = renderTable(token);\n const content = token.header.every((cell) => !cell.text.trim()) ? table.replace(/<thead>[\\s\\S]*?<\\/thead>\\n?/, \"\") : table;\n return `<div class=\"k2b-content-markdown__table\" tabindex=\"0\">${content}</div>`;\n };\n renderer.html = ({ text }: Tokens.HTML | Tokens.Tag) => escapeHtml(text);\n renderer.link = function ({ href, title, tokens }: Tokens.Link) {\n const body = this.parser.parseInline(tokens);\n const url = safeUrl(href);\n if (!url) return body;\n if (options.linkProtocols) {\n try {\n if (!options.linkProtocols.includes(new URL(url, \"https://markdown.invalid/\").protocol)) return body;\n } catch {\n return body;\n }\n }\n const titleAttribute = title ? ` title=\"${escapeHtml(title)}\"` : \"\";\n const target = options.linkTarget === \"_blank\" ? ' target=\"_blank\" rel=\"noopener noreferrer\"' : \"\";\n return `<a href=\"${escapeHtml(url)}\"${titleAttribute}${target}>${body}</a>`;\n };\n renderer.image = ({ href, title, text }: Tokens.Image) => {\n const url = safeUrl(href);\n if (!url || options.allowImages === false) return escapeHtml(text);\n const titleAttribute = title ? ` title=\"${escapeHtml(title)}\"` : \"\";\n return `<img src=\"${escapeHtml(url)}\" alt=\"${escapeHtml(text)}\"${titleAttribute}>`;\n };\n renderer.text = (token) => {\n if (inlineTokens.length === 0 || token.type === \"escape\" || (\"tokens\" in token && token.tokens)) return renderText(token);\n const parts: string[] = [];\n let plainStart = 0;\n let cursor = 0;\n while (cursor < token.text.length) {\n const inlineToken = inlineTokens.find(\n (candidate) => token.text.startsWith(candidate, cursor) && isStandaloneInlineToken(token.text, cursor, candidate),\n );\n if (!inlineToken) {\n cursor += 1;\n continue;\n }\n if (plainStart < cursor) {\n const text = token.text.slice(plainStart, cursor);\n parts.push(renderText({ ...token, raw: text, text }));\n }\n parts.push(\n `<span class=\"k2b-content-markdown__inline-token\">${renderText({ ...token, raw: inlineToken, text: inlineToken })}</span>`,\n );\n cursor += inlineToken.length;\n plainStart = cursor;\n }\n if (plainStart === 0) return renderText(token);\n if (plainStart < token.text.length) {\n const text = token.text.slice(plainStart);\n parts.push(renderText({ ...token, raw: text, text }));\n }\n return parts.join(\"\");\n };\n return renderer;\n};\n\nexport const renderSafeMarkdown = (markdown: string, options: MarkdownRenderOptions = {}): string =>\n new Marked(markdownInfoBlocks({ locale: options.locale })).parse(markdown, {\n async: false,\n renderer: createSafeRenderer(options),\n }) as string;\n\n/**\n * Markdown View Component (SSR)\n *\n * Renders untrusted Markdown safely by default. Raw HTML and unsafe link\n * protocols are escaped. Info blocks (`:::note`, `:::info`, `:::success`,\n * `:::warning`, `:::danger`) render as the calm `NoticeCard`. Already-rendered\n * HTML requires the deliberately named `trustedHtml` boundary; the caller owns\n * sanitization in that mode.\n *\n * @example\n * ```tsx\n * import { MarkdownView } from \"@k2b/ui\";\n *\n * <MarkdownView markdown={source} />;\n * ```\n *\n * @example Compact headings, e.g. inside comments or file previews:\n * ```tsx\n * <MarkdownView markdown={source} headingScale=\"compact\" />;\n * ```\n */\nexport default function MarkdownView(props: MarkdownViewProps) {\n const locale = useLocale();\n const html = () =>\n props.markdown !== undefined\n ? renderSafeMarkdown(props.markdown, {\n inlineTokens: props.inlineTokens,\n allowImages: props.allowImages,\n linkProtocols: props.linkProtocols,\n linkTarget: props.linkTarget,\n locale: locale(),\n })\n : props.trustedHtml;\n return (\n <div\n class={`k2b-content-markdown ${props.class ?? \"\"}`}\n data-heading-scale={props.headingScale && props.headingScale !== \"normal\" ? props.headingScale : undefined}\n innerHTML={html()}\n />\n );\n}\n"],"mappings":";;;;;;;AAAA,SAAS,MAAM,EAAE,QAAQ,QAAqB,QAAQ;AACtD,SAAS,SAAS,QAAQ,gBAAgB;AAC1C,SAAS,kBAAkB,QAAQ,wBAAwB;AAwC3D,MAAM,UAAU,GAAI,KAAa,IAC/B,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC;AAEnI,MAAM,OAAO,GAAI,KAAa,IAAoB;EAChD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,kCAAkC,EAAE,EAAE,CAAC;EAC/E,IAAI,iCAAiC,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI;EACnE,OAAO,KAAK;AACd,CAAC;AAED,MAAM,qBAAqB,GAAI,MAAqC,IAClE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAE/F,MAAM,uBAAuB,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,KAAa,KAAc;EACvF,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,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,GAAG,KAAK,CAAC,YAAY,GAAG,SAAS;QAAA,OAC/F,IAAI,CAAC,CAAC;MAAA;MAAA;MAAA;MAAA;IAAA;MAAA;MAAA;MAAA;IAAA;IAAA;EAAA;AAGvB","ignoreList":[]}
|
|
@@ -47,6 +47,7 @@ export default function PdfPreview(props) {
|
|
|
47
47
|
// An automatic preview shows one fixed document; the open action reuses it instead of requesting it again.
|
|
48
48
|
let shownBlob = null;
|
|
49
49
|
let openButton;
|
|
50
|
+
let frame;
|
|
50
51
|
let renderButton;
|
|
51
52
|
let errorRetryButton;
|
|
52
53
|
let disposed = false;
|
|
@@ -90,8 +91,9 @@ export default function PdfPreview(props) {
|
|
|
90
91
|
setUrl(nextUrl);
|
|
91
92
|
setLoading(false);
|
|
92
93
|
if (previousUrl) URL.revokeObjectURL(previousUrl);
|
|
93
|
-
// The shown document removes the retry action; keep keyboard focus in the actions instead of the page
|
|
94
|
-
|
|
94
|
+
// The shown document removes the retry action; keep keyboard focus in the actions instead of the page, or on the
|
|
95
|
+
// document itself when the host shows only the content.
|
|
96
|
+
if (retryFocused && document.activeElement === document.body) (openButton?.isConnected ? openButton : frame)?.focus();
|
|
95
97
|
} catch (e) {
|
|
96
98
|
if (disposed || generation !== loadGeneration) return;
|
|
97
99
|
shownBlob = null;
|
|
@@ -272,6 +274,7 @@ export default function PdfPreview(props) {
|
|
|
272
274
|
},
|
|
273
275
|
children: currentUrl => (() => {
|
|
274
276
|
var _el$25 = _$getNextElement(_tmpl$6);
|
|
277
|
+
_$use(element => frame = element, _el$25);
|
|
275
278
|
_$effect(_p$ => {
|
|
276
279
|
var _v$5 = currentUrl(),
|
|
277
280
|
_v$6 = props.title ?? messages().pdfPreview;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["content/PdfPreview.tsx"],"sourcesContent":["import { createSignal, type JSX, onCleanup, onMount, Show } from \"solid-js\";\nimport { resolveUiMessages, useUiMessages } from \"../intl/messages\";\nimport Placeholder from \"../surfaces/Placeholder\";\n\nexport type PdfPreviewRequest = () => Promise<Response | Blob>;\n\nexport type PdfPreviewProps = {\n request: PdfPreviewRequest;\n autoLoad?: boolean;\n disabled?: () => boolean;\n title?: string;\n buttonLabel?: string;\n openButtonLabel?: string;\n /**\n * Opens the document at this address in a new tab instead of a local copy. Pass a stable same-origin URL that\n * serves the PDF inline, so reloading and the viewer's file name keep working. Without it, the open action shows\n * a temporary copy of the requested document.\n */\n openHref?: string;\n /** Adds a Download action. The host owns the download, for example a fresh attachment URL. */\n onDownload?: () => void;\n emptyText?: string;\n class?: string;\n children?: (parts: { actions: JSX.Element; content: JSX.Element }) => JSX.Element;\n renderError?: (message: string) => JSX.Element;\n};\n\nconst readErrorMessage = async (response: Response): Promise<string> => {\n try {\n const data = (await response.json()) as unknown;\n if (data && typeof data === \"object\" && \"message\" in data && typeof data.message === \"string\") return data.message;\n } catch {\n // Fall through to the HTTP status fallback.\n }\n return resolveUiMessages().pdfPreviewHttpError({ status: response.status });\n};\n\nexport default function PdfPreview(props: PdfPreviewProps) {\n const messages = useUiMessages();\n const [url, setUrl] = createSignal<string | null>(null);\n // An automatic preview starts loading once mounted. The server and the page before hydration already show that\n // state, so they offer neither a retry nor an invitation to render while nothing has failed.\n const [loading, setLoading] = createSignal(Boolean(props.autoLoad) && !props.disabled?.());\n const [opening, setOpening] = createSignal(false);\n const [error, setError] = createSignal<string | null>(null);\n const [failed, setFailed] = createSignal(false);\n const [tabBlocked, setTabBlocked] = createSignal(false);\n // An automatic preview shows one fixed document; the open action reuses it instead of requesting it again.\n let shownBlob: Blob | null = null;\n let openButton: HTMLElement | undefined;\n let renderButton: HTMLButtonElement | undefined;\n let errorRetryButton: HTMLButtonElement | undefined;\n let disposed = false;\n let loadGeneration = 0;\n let openGeneration = 0;\n\n const revokeCurrent = () => {\n const current = url();\n if (current) URL.revokeObjectURL(current);\n setUrl(null);\n };\n\n onCleanup(() => {\n disposed = true;\n loadGeneration += 1;\n openGeneration += 1;\n revokeCurrent();\n });\n\n const readPdfBlob = async () => {\n const response = await props.request();\n const blob = response instanceof Response ? (response.ok ? await response.blob() : null) : response;\n if (!blob) throw new Error(await readErrorMessage(response as Response));\n if (blob.type && blob.type !== \"application/pdf\") throw new Error(`PDF preview returned ${blob.type} instead of application/pdf`);\n return blob;\n };\n\n const load = async () => {\n if (loading() || opening() || props.disabled?.()) return;\n const generation = ++loadGeneration;\n // A retry the shown document or the loading state removes hands keyboard focus on instead of dropping it.\n const retryFocused =\n (props.autoLoad && document.activeElement === renderButton) ||\n (errorRetryButton?.isConnected && document.activeElement === errorRetryButton);\n setLoading(true);\n setError(null);\n try {\n const blob = await readPdfBlob();\n const nextUrl = URL.createObjectURL(blob);\n if (disposed || generation !== loadGeneration) {\n URL.revokeObjectURL(nextUrl);\n return;\n }\n const previousUrl = url();\n shownBlob = blob;\n setFailed(false);\n setUrl(nextUrl);\n setLoading(false);\n if (previousUrl) URL.revokeObjectURL(previousUrl);\n // The shown document removes the retry action; keep keyboard focus in the actions instead of the page.\n if (retryFocused && document.activeElement === document.body) openButton?.focus();\n } catch (e) {\n if (disposed || generation !== loadGeneration) return;\n shownBlob = null;\n setFailed(true);\n setError(e instanceof Error ? e.message : \"PDF preview failed\");\n if (retryFocused && document.activeElement === document.body) errorRetryButton?.focus();\n } finally {\n if (!disposed && generation === loadGeneration) setLoading(false);\n }\n };\n\n onMount(() => {\n // Hand the initial loading state to the request itself, which also covers a preview disabled by now.\n setLoading(false);\n if (props.autoLoad) void load();\n });\n\n const openInNewTab = async () => {\n if (loading() || opening() || props.disabled?.()) return;\n const generation = ++openGeneration;\n const tab = window.open(\"\", \"_blank\");\n // A blocked tab is not a document error: keep the shown document and report it beside the actions.\n setTabBlocked(!tab);\n if (!tab) return;\n tab.opener = null;\n tab.document.title = props.title ?? messages().pdfPreview;\n tab.document.body.textContent = messages().pdfPreviewRendering;\n setOpening(true);\n setError(null);\n try {\n const blob = (props.autoLoad ? shownBlob : null) ?? (await readPdfBlob());\n if (disposed || generation !== openGeneration) {\n tab.close();\n return;\n }\n const objectUrl = URL.createObjectURL(blob);\n tab.location.href = objectUrl;\n window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);\n } catch (e) {\n tab.close();\n if (!disposed && generation === openGeneration) setError(e instanceof Error ? e.message : \"PDF preview failed\");\n } finally {\n if (!disposed && generation === openGeneration) setOpening(false);\n }\n };\n\n // With autoLoad, rendering again would show the same document: offer it only until one is shown. After a failure the\n // default error state carries it as the retry; beside a caller's error content it stays in place while a retry loads.\n const renderable = () => !props.autoLoad || (failed() ? Boolean(props.renderError) : !url() && !loading());\n const actions = () => (\n <div class=\"k2b-content-pdf-preview__actions\">\n <Show\n when={!props.disabled?.() && props.openHref}\n fallback={\n <button\n ref={(element) => (openButton = element)}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void openInNewTab()}\n disabled={loading() || opening() || props.disabled?.()}\n >\n <i class={opening() ? \"ti ti-loader-2 k2b-spin\" : \"ti ti-external-link\"} aria-hidden=\"true\" />\n {props.openButtonLabel ?? messages().openPreview}\n </button>\n }\n >\n {(href) => (\n // A plain link to a real address: the browser opens it on the user's own click, and the tab can reload it.\n <a\n ref={(element) => (openButton = element)}\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n href={href()}\n target=\"_blank\"\n rel=\"noopener\"\n >\n <i class=\"ti ti-external-link\" aria-hidden=\"true\" />\n {props.openButtonLabel ?? messages().openPreview}\n </a>\n )}\n </Show>\n <Show when={props.onDownload}>\n <button\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => props.onDownload?.()}\n disabled={props.disabled?.()}\n >\n <i class=\"ti ti-download\" aria-hidden=\"true\" />\n {messages().download}\n </button>\n </Show>\n <Show when={renderable()}>\n <button\n ref={renderButton}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void load()}\n disabled={loading() || opening() || props.disabled?.()}\n >\n <i class={loading() ? \"ti ti-loader-2 k2b-spin\" : \"ti ti-file-type-pdf\"} aria-hidden=\"true\" />\n {props.buttonLabel ?? messages().previewPdf}\n </button>\n </Show>\n <Show when={tabBlocked()}>\n <span role=\"alert\" class=\"k2b-content-pdf-preview__notice\">\n {messages().pdfPreviewTabBlocked}\n </span>\n </Show>\n </div>\n );\n // Every state before a document is shown uses one placeholder in the viewer's box, so loading changes no layout.\n const content = () => (\n <Show\n when={error()}\n fallback={\n <Show\n when={url()}\n fallback={\n <Placeholder\n class=\"k2b-content-pdf-preview__placeholder\"\n state={loading() ? \"loading\" : \"empty\"}\n icon={loading() ? undefined : \"ti ti-file-type-pdf\"}\n title={loading() ? messages().loading : undefined}\n description={loading() ? undefined : (props.emptyText ?? messages().renderPdfPreview)}\n />\n }\n >\n {(currentUrl) => (\n <iframe class=\"k2b-content-pdf-preview__frame\" src={currentUrl()} title={props.title ?? messages().pdfPreview} />\n )}\n </Show>\n }\n >\n {(message) =>\n props.renderError?.(message()) ?? (\n <Placeholder\n class=\"k2b-content-pdf-preview__placeholder\"\n state=\"error\"\n description={message()}\n action={\n // One retry at a time: the render action moves here only where the toolbar no longer offers it.\n renderable() ? undefined : (\n <button\n ref={(element) => (errorRetryButton = element)}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void load()}\n disabled={opening() || props.disabled?.()}\n >\n {props.buttonLabel ?? messages().retry}\n </button>\n )\n }\n />\n )\n }\n </Show>\n );\n\n if (props.children)\n return props.children({\n get actions() {\n return actions();\n },\n get content() {\n return content();\n },\n });\n return (\n <section class={`k2b-content-pdf-preview ${props.class ?? \"\"}`}>\n <div class=\"k2b-content-pdf-preview__toolbar\">\n <div class=\"k2b-content-pdf-preview__heading\">\n <Show when={props.title}>\n <h2 class=\"k2b-content-pdf-preview__title\">{props.title}</h2>\n </Show>\n </div>\n {actions()}\n </div>\n {content()}\n </section>\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AAC,IAAI;QAAA,OAAE,KAAK,CAAC,KAAK;MAAA;MAAA;QAAA;QAAA,uBACuB,KAAK,CAAC,KAAK;QAAA;MAAA;IAAA;IAAA,iBAG1D,OAAO;IAAA,iBAET,OAAO;IAAA,mCATM,2BAA2B,KAAK,CAAC,KAAK,IAAI,EAAE,EAAE;IAAA;EAAA;AAYlE;AAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":[],"sources":["content/PdfPreview.tsx"],"sourcesContent":["import { createSignal, type JSX, onCleanup, onMount, Show } from \"solid-js\";\nimport { resolveUiMessages, useUiMessages } from \"../intl/messages\";\nimport Placeholder from \"../surfaces/Placeholder\";\n\nexport type PdfPreviewRequest = () => Promise<Response | Blob>;\n\nexport type PdfPreviewProps = {\n request: PdfPreviewRequest;\n autoLoad?: boolean;\n disabled?: () => boolean;\n title?: string;\n buttonLabel?: string;\n openButtonLabel?: string;\n /**\n * Opens the document at this address in a new tab instead of a local copy. Pass a stable same-origin URL that\n * serves the PDF inline, so reloading and the viewer's file name keep working. Without it, the open action shows\n * a temporary copy of the requested document.\n */\n openHref?: string;\n /** Adds a Download action. The host owns the download, for example a fresh attachment URL. */\n onDownload?: () => void;\n emptyText?: string;\n class?: string;\n children?: (parts: { actions: JSX.Element; content: JSX.Element }) => JSX.Element;\n renderError?: (message: string) => JSX.Element;\n};\n\nconst readErrorMessage = async (response: Response): Promise<string> => {\n try {\n const data = (await response.json()) as unknown;\n if (data && typeof data === \"object\" && \"message\" in data && typeof data.message === \"string\") return data.message;\n } catch {\n // Fall through to the HTTP status fallback.\n }\n return resolveUiMessages().pdfPreviewHttpError({ status: response.status });\n};\n\nexport default function PdfPreview(props: PdfPreviewProps) {\n const messages = useUiMessages();\n const [url, setUrl] = createSignal<string | null>(null);\n // An automatic preview starts loading once mounted. The server and the page before hydration already show that\n // state, so they offer neither a retry nor an invitation to render while nothing has failed.\n const [loading, setLoading] = createSignal(Boolean(props.autoLoad) && !props.disabled?.());\n const [opening, setOpening] = createSignal(false);\n const [error, setError] = createSignal<string | null>(null);\n const [failed, setFailed] = createSignal(false);\n const [tabBlocked, setTabBlocked] = createSignal(false);\n // An automatic preview shows one fixed document; the open action reuses it instead of requesting it again.\n let shownBlob: Blob | null = null;\n let openButton: HTMLElement | undefined;\n let frame: HTMLIFrameElement | undefined;\n let renderButton: HTMLButtonElement | undefined;\n let errorRetryButton: HTMLButtonElement | undefined;\n let disposed = false;\n let loadGeneration = 0;\n let openGeneration = 0;\n\n const revokeCurrent = () => {\n const current = url();\n if (current) URL.revokeObjectURL(current);\n setUrl(null);\n };\n\n onCleanup(() => {\n disposed = true;\n loadGeneration += 1;\n openGeneration += 1;\n revokeCurrent();\n });\n\n const readPdfBlob = async () => {\n const response = await props.request();\n const blob = response instanceof Response ? (response.ok ? await response.blob() : null) : response;\n if (!blob) throw new Error(await readErrorMessage(response as Response));\n if (blob.type && blob.type !== \"application/pdf\") throw new Error(`PDF preview returned ${blob.type} instead of application/pdf`);\n return blob;\n };\n\n const load = async () => {\n if (loading() || opening() || props.disabled?.()) return;\n const generation = ++loadGeneration;\n // A retry the shown document or the loading state removes hands keyboard focus on instead of dropping it.\n const retryFocused =\n (props.autoLoad && document.activeElement === renderButton) ||\n (errorRetryButton?.isConnected && document.activeElement === errorRetryButton);\n setLoading(true);\n setError(null);\n try {\n const blob = await readPdfBlob();\n const nextUrl = URL.createObjectURL(blob);\n if (disposed || generation !== loadGeneration) {\n URL.revokeObjectURL(nextUrl);\n return;\n }\n const previousUrl = url();\n shownBlob = blob;\n setFailed(false);\n setUrl(nextUrl);\n setLoading(false);\n if (previousUrl) URL.revokeObjectURL(previousUrl);\n // The shown document removes the retry action; keep keyboard focus in the actions instead of the page, or on the\n // document itself when the host shows only the content.\n if (retryFocused && document.activeElement === document.body) (openButton?.isConnected ? openButton : frame)?.focus();\n } catch (e) {\n if (disposed || generation !== loadGeneration) return;\n shownBlob = null;\n setFailed(true);\n setError(e instanceof Error ? e.message : \"PDF preview failed\");\n if (retryFocused && document.activeElement === document.body) errorRetryButton?.focus();\n } finally {\n if (!disposed && generation === loadGeneration) setLoading(false);\n }\n };\n\n onMount(() => {\n // Hand the initial loading state to the request itself, which also covers a preview disabled by now.\n setLoading(false);\n if (props.autoLoad) void load();\n });\n\n const openInNewTab = async () => {\n if (loading() || opening() || props.disabled?.()) return;\n const generation = ++openGeneration;\n const tab = window.open(\"\", \"_blank\");\n // A blocked tab is not a document error: keep the shown document and report it beside the actions.\n setTabBlocked(!tab);\n if (!tab) return;\n tab.opener = null;\n tab.document.title = props.title ?? messages().pdfPreview;\n tab.document.body.textContent = messages().pdfPreviewRendering;\n setOpening(true);\n setError(null);\n try {\n const blob = (props.autoLoad ? shownBlob : null) ?? (await readPdfBlob());\n if (disposed || generation !== openGeneration) {\n tab.close();\n return;\n }\n const objectUrl = URL.createObjectURL(blob);\n tab.location.href = objectUrl;\n window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60_000);\n } catch (e) {\n tab.close();\n if (!disposed && generation === openGeneration) setError(e instanceof Error ? e.message : \"PDF preview failed\");\n } finally {\n if (!disposed && generation === openGeneration) setOpening(false);\n }\n };\n\n // With autoLoad, rendering again would show the same document: offer it only until one is shown. After a failure the\n // default error state carries it as the retry; beside a caller's error content it stays in place while a retry loads.\n const renderable = () => !props.autoLoad || (failed() ? Boolean(props.renderError) : !url() && !loading());\n const actions = () => (\n <div class=\"k2b-content-pdf-preview__actions\">\n <Show\n when={!props.disabled?.() && props.openHref}\n fallback={\n <button\n ref={(element) => (openButton = element)}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void openInNewTab()}\n disabled={loading() || opening() || props.disabled?.()}\n >\n <i class={opening() ? \"ti ti-loader-2 k2b-spin\" : \"ti ti-external-link\"} aria-hidden=\"true\" />\n {props.openButtonLabel ?? messages().openPreview}\n </button>\n }\n >\n {(href) => (\n // A plain link to a real address: the browser opens it on the user's own click, and the tab can reload it.\n <a\n ref={(element) => (openButton = element)}\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n href={href()}\n target=\"_blank\"\n rel=\"noopener\"\n >\n <i class=\"ti ti-external-link\" aria-hidden=\"true\" />\n {props.openButtonLabel ?? messages().openPreview}\n </a>\n )}\n </Show>\n <Show when={props.onDownload}>\n <button\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => props.onDownload?.()}\n disabled={props.disabled?.()}\n >\n <i class=\"ti ti-download\" aria-hidden=\"true\" />\n {messages().download}\n </button>\n </Show>\n <Show when={renderable()}>\n <button\n ref={renderButton}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void load()}\n disabled={loading() || opening() || props.disabled?.()}\n >\n <i class={loading() ? \"ti ti-loader-2 k2b-spin\" : \"ti ti-file-type-pdf\"} aria-hidden=\"true\" />\n {props.buttonLabel ?? messages().previewPdf}\n </button>\n </Show>\n <Show when={tabBlocked()}>\n <span role=\"alert\" class=\"k2b-content-pdf-preview__notice\">\n {messages().pdfPreviewTabBlocked}\n </span>\n </Show>\n </div>\n );\n // Every state before a document is shown uses one placeholder in the viewer's box, so loading changes no layout.\n const content = () => (\n <Show\n when={error()}\n fallback={\n <Show\n when={url()}\n fallback={\n <Placeholder\n class=\"k2b-content-pdf-preview__placeholder\"\n state={loading() ? \"loading\" : \"empty\"}\n icon={loading() ? undefined : \"ti ti-file-type-pdf\"}\n title={loading() ? messages().loading : undefined}\n description={loading() ? undefined : (props.emptyText ?? messages().renderPdfPreview)}\n />\n }\n >\n {(currentUrl) => (\n <iframe\n ref={(element) => (frame = element)}\n class=\"k2b-content-pdf-preview__frame\"\n src={currentUrl()}\n title={props.title ?? messages().pdfPreview}\n />\n )}\n </Show>\n }\n >\n {(message) =>\n props.renderError?.(message()) ?? (\n <Placeholder\n class=\"k2b-content-pdf-preview__placeholder\"\n state=\"error\"\n description={message()}\n action={\n // One retry at a time: the render action moves here only where the toolbar no longer offers it.\n renderable() ? undefined : (\n <button\n ref={(element) => (errorRetryButton = element)}\n type=\"button\"\n class=\"k2b-button\"\n data-variant=\"secondary\"\n data-size=\"sm\"\n onClick={() => void load()}\n disabled={opening() || props.disabled?.()}\n >\n {props.buttonLabel ?? messages().retry}\n </button>\n )\n }\n />\n )\n }\n </Show>\n );\n\n if (props.children)\n return props.children({\n get actions() {\n return actions();\n },\n get content() {\n return content();\n },\n });\n return (\n <section class={`k2b-content-pdf-preview ${props.class ?? \"\"}`}>\n <div class=\"k2b-content-pdf-preview__toolbar\">\n <div class=\"k2b-content-pdf-preview__heading\">\n <Show when={props.title}>\n <h2 class=\"k2b-content-pdf-preview__title\">{props.title}</h2>\n </Show>\n </div>\n {actions()}\n </div>\n {content()}\n </section>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,EAAY,SAAS,EAAE,OAAO,EAAE,IAAI,QAAQ,UAAU;AAC3E,SAAS,iBAAiB,EAAE,aAAa,QAAQ,kBAAkB;AACnE,OAAO,WAAW,MAAM,yBAAyB;AAyBjD,MAAM,gBAAgB,GAAG,MAAO,QAAkB,IAAsB;EACtE,IAAI;IACF,MAAM,IAAI,GAAI,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAa;IAC/C,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,OAAO,IAAI,CAAC,OAAO;EACpH,CAAC,CAAC,MAAM;IACN;EAAA;EAEF,OAAO,iBAAiB,CAAC,CAAC,CAAC,mBAAmB,CAAC;IAAE,MAAM,EAAE,QAAQ,CAAC;EAAO,CAAC,CAAC;AAC7E,CAAC;AAED,eAAe,SAAS,UAAU,CAAC,KAAsB,EAAE;EACzD,MAAM,QAAQ,GAAG,aAAa,CAAC,CAAC;EAChC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,G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BAAU,CAAC,CAAC,MAAG,SAAS;YAAA;YAAA,iBAOX,MAAM,KAAK,IAAI,CAAC,CAAC;YAAA,MALpB,OAAO,IAAM,gBAAgB,GAAG,OAAQ;YAAA,uBAQ7C,KAAK,CAAC,WAAW,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;YAAA,iDAF5B,OAAO,CAAC,CAAC,IAAI,KAAK,CAAC,QAAQ,GAAG,CAAC;YAAA;YAAA;UAAA;QAI5C;MAAA;IAAA;EAGN,EAGN;EAED,IAAI,KAAK,CAAC,QAAQ,EAChB,OAAO,KAAK,CAAC,QAAQ,CAAC;IACpB,IAAI,OAAO,GAAG;MACZ,OAAO,OAAO,CAAC,CAAC;IAClB,CAAC;IACD,IAAI,OAAO,GAAG;MACZ,OAAO,OAAO,CAAC,CAAC;IAClB;EACF,CAAC,CAAC;EACJ;IAAA;MAAA;MAAA;MAAA;MAAA;MAAA;MAAA;IAAA,mCAIS,IAAI;MAAA,IAAC,IAAI;QAAA,OAAE,KAAK,CAAC,KAAK;MAAA;MAAA;QAAA;QAAA,uBACuB,KAAK,CAAC,KAAK;QAAA;MAAA;IAAA;IAAA,iBAG1D,OAAO;IAAA,iBAET,OAAO;IAAA,mCATM,2BAA2B,KAAK,CAAC,KAAK,IAAI,EAAE,EAAE;IAAA;EAAA;AAYlE;AAAC","ignoreList":[]}
|
|
@@ -18,6 +18,7 @@ export { canPreviewFile, default as FileView, formatFileViewSize, getFileViewPre
|
|
|
18
18
|
export { default as Lightbox } from "./Lightbox";
|
|
19
19
|
export { default as LogEntriesTable } from "./LogEntriesTable";
|
|
20
20
|
export { default as MarkdownView, renderSafeMarkdown } from "./MarkdownView";
|
|
21
|
+
export { markdownInfoBlocks, renderMarkdownInfoBlock, scanMarkdownInfoBlock } from "./markdown-info-blocks";
|
|
21
22
|
export { Pagination } from "./Pagination";
|
|
22
23
|
export { default as PdfPreview } from "./PdfPreview";
|
|
23
24
|
export { default as RangePicker } from "./RangePicker";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["content/index.ts"],"sourcesContent":["export type {\n CalendarAttendee,\n CalendarDayBadge,\n CalendarEvent,\n CalendarEventColor,\n CalendarEventRenderContext,\n CalendarEventTimeChange,\n CalendarLabels,\n CalendarProps,\n CalendarRecurrence,\n CalendarResource,\n CalendarView,\n} from \"./Calendar\";\nexport { default as Calendar } from \"./Calendar\";\n\nexport type { ChartKind, ChartLabels, ChartProps, ChartRenderOptions } from \"./Chart\";\nexport { default as Chart } from \"./Chart\";\nexport type { ChartExplorerColumn, ChartExplorerProps } from \"./ChartExplorer\";\nexport { ChartExplorer } from \"./ChartExplorer\";\nexport type { ChartExplorerControlsProps } from \"./ChartExplorerControls\";\nexport { ChartExplorerControls } from \"./ChartExplorerControls\";\nexport { ChartFilterControls, type ChartFilterControlsProps } from \"./ChartFilterControls\";\nexport { ChartSnapshotView } from \"./ChartSnapshotView\";\nexport type { CodeDisplayLanguage, CodeDisplayProps } from \"./CodeDisplay\";\nexport { default as CodeDisplay } from \"./CodeDisplay\";\nexport { type ChartCursor, createChartCursor } from \"./chart-cursor\";\nexport type {\n ChartExplorerCharts,\n ChartExplorerController,\n ChartExplorerData,\n ChartExplorerOptions,\n ChartExplorerRequest,\n ChartExplorerRow,\n ChartExplorerSnapshot,\n} from \"./chart-explorer\";\nexport { createChartExplorer } from \"./chart-explorer\";\nexport type { ChartDatumRef, ChartSelection, ChartTooltip, ChartTooltipFormatter } from \"./chart-inspection\";\nexport type { ChartSnapshot } from \"./chart-snapshot\";\nexport { prepareChartSnapshot } from \"./chart-snapshot\";\nexport type {\n StateTimelineChartOptions,\n StateTimelineDomain,\n StateTimelineInterval,\n StateTimelineRow,\n StateTimelineState,\n} from \"./chart-state-timeline\";\nexport { type CollectionSelection, createCollectionSelection, type SelectionModifiers } from \"./collection-selection\";\nexport type {\n DataTableColumn,\n DataTableControlsProps,\n DataTableFooter,\n DataTableHeaderProps,\n DataTablePanelFooterProps,\n DataTablePanelProps,\n DataTableProps,\n DataTableRenderCell,\n DataTableRenderHeader,\n DataTableSort,\n} from \"./DataTable\";\nexport { default as DataTable } from \"./DataTable\";\nexport type { DocCodeHighlighter, DocCodeProps, DocConcept, DocNoteVariant, DocRow } from \"./Docs\";\nexport { DocCode, DocConceptGrid, DocInlineCode, DocLead, DocNote, DocPage, DocRows, DocSection } from \"./Docs\";\nexport { FileBrowserPanel, type FileBrowserPanelProps, type FileSource, openFileBrowser } from \"./FileBrowser\";\nexport { FileGrid, type FileGridProps } from \"./FileGrid\";\nexport { default as FileTree, type FileTreeActions, type FileTreeEntry, type FileTreeProps } from \"./FileTree\";\nexport {\n canPreviewFile,\n default as FileView,\n type FileViewContent,\n type FileViewFile,\n type FileViewPreviewKind,\n type FileViewProps,\n type FileViewRenderer,\n type FileViewRendererProps,\n formatFileViewSize,\n getFileViewPreviewKind,\n} from \"./FileView\";\nexport type { LightboxImage } from \"./Lightbox\";\nexport { default as Lightbox } from \"./Lightbox\";\nexport type { LogTableEntry } from \"./LogEntriesTable\";\nexport { default as LogEntriesTable } from \"./LogEntriesTable\";\nexport { default as MarkdownView, type MarkdownRenderOptions, type MarkdownViewProps, renderSafeMarkdown } from \"./MarkdownView\";\nexport { Pagination, type PaginationProps } from \"./Pagination\";\nexport type { PdfPreviewProps, PdfPreviewRequest } from \"./PdfPreview\";\nexport { default as PdfPreview } from \"./PdfPreview\";\nexport type { RangeOption, RangePickerProps } from \"./RangePicker\";\nexport { default as RangePicker } from \"./RangePicker\";\nexport type { StructuredDataPreviewMode, StructuredDataPreviewProps, StructuredDataValue } from \"./StructuredDataPreview\";\nexport { default as StructuredDataPreview, isStructuredDataValue } from \"./StructuredDataPreview\";\nexport type { ZoomPanAction, ZoomPanFullscreen, ZoomPanViewportProps } from \"./ZoomPanViewport\";\nexport { ZoomPanViewport } from \"./ZoomPanViewport\";\n"],"mappings":"AAaA,SAAS,OAAO,IAAI,QAAQ,QAAQ,YAAY;AAGhD,SAAS,OAAO,IAAI,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arEventRenderContext,\n CalendarEventTimeChange,\n CalendarLabels,\n CalendarProps,\n CalendarRecurrence,\n CalendarResource,\n CalendarView,\n} from \"./Calendar\";\nexport { default as Calendar } from \"./Calendar\";\n\nexport type { ChartKind, ChartLabels, ChartProps, ChartRenderOptions } from \"./Chart\";\nexport { default as Chart } from \"./Chart\";\nexport type { ChartExplorerColumn, ChartExplorerProps } from \"./ChartExplorer\";\nexport { ChartExplorer } from \"./ChartExplorer\";\nexport type { ChartExplorerControlsProps } from \"./ChartExplorerControls\";\nexport { ChartExplorerControls } from \"./ChartExplorerControls\";\nexport { ChartFilterControls, type ChartFilterControlsProps } from \"./ChartFilterControls\";\nexport { ChartSnapshotView } from \"./ChartSnapshotView\";\nexport type { CodeDisplayLanguage, CodeDisplayProps } from \"./CodeDisplay\";\nexport { default as CodeDisplay } from \"./CodeDisplay\";\nexport { type ChartCursor, createChartCursor } from \"./chart-cursor\";\nexport type {\n ChartExplorerCharts,\n ChartExplorerController,\n ChartExplorerData,\n ChartExplorerOptions,\n ChartExplorerRequest,\n ChartExplorerRow,\n ChartExplorerSnapshot,\n} from \"./chart-explorer\";\nexport { createChartExplorer } from \"./chart-explorer\";\nexport type { ChartDatumRef, ChartSelection, ChartTooltip, ChartTooltipFormatter } from \"./chart-inspection\";\nexport type { ChartSnapshot } from \"./chart-snapshot\";\nexport { prepareChartSnapshot } from \"./chart-snapshot\";\nexport type {\n StateTimelineChartOptions,\n StateTimelineDomain,\n StateTimelineInterval,\n StateTimelineRow,\n StateTimelineState,\n} from \"./chart-state-timeline\";\nexport { type CollectionSelection, createCollectionSelection, type SelectionModifiers } from \"./collection-selection\";\nexport type {\n DataTableColumn,\n DataTableControlsProps,\n DataTableFooter,\n DataTableHeaderProps,\n DataTablePanelFooterProps,\n DataTablePanelProps,\n DataTableProps,\n DataTableRenderCell,\n DataTableRenderHeader,\n DataTableSort,\n} from \"./DataTable\";\nexport { default as DataTable } from \"./DataTable\";\nexport type { DocCodeHighlighter, DocCodeProps, DocConcept, DocNoteVariant, DocRow } from \"./Docs\";\nexport { DocCode, DocConceptGrid, DocInlineCode, DocLead, DocNote, DocPage, DocRows, DocSection } from \"./Docs\";\nexport { FileBrowserPanel, type FileBrowserPanelProps, type FileSource, openFileBrowser } from \"./FileBrowser\";\nexport { FileGrid, type FileGridProps } from \"./FileGrid\";\nexport { default as FileTree, type FileTreeActions, type FileTreeEntry, type FileTreeProps } from \"./FileTree\";\nexport {\n canPreviewFile,\n default as FileView,\n type FileViewContent,\n type FileViewFile,\n type FileViewPreviewKind,\n type FileViewProps,\n type FileViewRenderer,\n type FileViewRendererProps,\n formatFileViewSize,\n getFileViewPreviewKind,\n} from \"./FileView\";\nexport type { LightboxImage } from \"./Lightbox\";\nexport { default as Lightbox } from \"./Lightbox\";\nexport type { LogTableEntry } from \"./LogEntriesTable\";\nexport { default as LogEntriesTable } from \"./LogEntriesTable\";\nexport { default as MarkdownView, type MarkdownRenderOptions, type MarkdownViewProps, renderSafeMarkdown } from \"./MarkdownView\";\nexport {\n type MarkdownInfoBlock,\n type MarkdownInfoBlockRenderInput,\n type MarkdownInfoBlockType,\n markdownInfoBlocks,\n renderMarkdownInfoBlock,\n scanMarkdownInfoBlock,\n} from \"./markdown-info-blocks\";\nexport { Pagination, type PaginationProps } from \"./Pagination\";\nexport type { PdfPreviewProps, PdfPreviewRequest } from \"./PdfPreview\";\nexport { default as PdfPreview } from \"./PdfPreview\";\nexport type { RangeOption, RangePickerProps } from \"./RangePicker\";\nexport { default as RangePicker } from \"./RangePicker\";\nexport type { StructuredDataPreviewMode, StructuredDataPreviewProps, StructuredDataValue } from \"./StructuredDataPreview\";\nexport { default as StructuredDataPreview, isStructuredDataValue } from \"./StructuredDataPreview\";\nexport type { ZoomPanAction, ZoomPanFullscreen, ZoomPanViewportProps } from \"./ZoomPanViewport\";\nexport { ZoomPanViewport } from \"./ZoomPanViewport\";\n"],"mappings":"AAaA,SAAS,OAAO,IAAI,QAAQ,QAAQ,YAAY;AAGhD,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1
|
+
import { Lexer, Tokenizer } from "marked";
|
|
2
|
+
import { resolveUiMessages } from "../intl/messages";
|
|
3
|
+
import { NOTICE_CARD_CLASSES } from "../surfaces/NoticeCard";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Markdown info blocks: one grammar and one look for every Markdown surface.
|
|
7
|
+
*
|
|
8
|
+
* ```markdown
|
|
9
|
+
* :::warning Before deleting
|
|
10
|
+
* Deleting an item cannot be undone.
|
|
11
|
+
* :::
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* The opening line holds `:::`, a type in any letter case, and an optional
|
|
15
|
+
* plain-text title. The block ends at a line holding only `:::`, indented no
|
|
16
|
+
* deeper than the opener; code, lists, quotes, and HTML inside the body cannot
|
|
17
|
+
* end it. The body is ordinary Markdown. A block that is never closed stays
|
|
18
|
+
* ordinary text.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const TONES = {
|
|
22
|
+
note: "neutral",
|
|
23
|
+
info: "info",
|
|
24
|
+
success: "success",
|
|
25
|
+
warning: "warning",
|
|
26
|
+
danger: "danger"
|
|
27
|
+
};
|
|
28
|
+
const OPENER = /^( {0,3}):::(note|info|success|warning|danger)(?:[ \t]+(.*?))?[ \t]*$/i;
|
|
29
|
+
const START = /^ {0,3}:::(?:note|info|success|warning|danger)(?=[ \t\n]|$)/i;
|
|
30
|
+
const OPENERS = /(?<=^|\n) {0,3}:::(?:note|info|success|warning|danger)(?=[ \t\n]|$)/gi;
|
|
31
|
+
const CLOSING = /^( {0,3}):::[ \t]*$/;
|
|
32
|
+
const FENCE = /^( *)(`{3,}|~{3,})(.*)$/;
|
|
33
|
+
const LABELS = {
|
|
34
|
+
note: t => t.infoBlockNote,
|
|
35
|
+
info: t => t.infoBlockInfo,
|
|
36
|
+
success: t => t.infoBlockSuccess,
|
|
37
|
+
warning: t => t.infoBlockWarning,
|
|
38
|
+
danger: t => t.infoBlockDanger
|
|
39
|
+
};
|
|
40
|
+
const escapeHtml = value => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
41
|
+
const lineEnd = (source, from) => {
|
|
42
|
+
const end = source.indexOf("\n", from);
|
|
43
|
+
return end < 0 ? source.length : end;
|
|
44
|
+
};
|
|
45
|
+
const closes = (line, indent) => {
|
|
46
|
+
const closing = CLOSING.exec(line);
|
|
47
|
+
return !!closing && closing[1].length <= indent;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Column where a list item's text starts, as CommonMark counts it. */
|
|
51
|
+
const itemTextIndent = raw => {
|
|
52
|
+
const [, bullet = "", gap = ""] = /^( {0,3}(?:[-+*]|\d{1,9}[.)]))( *)/.exec(raw) ?? [];
|
|
53
|
+
return bullet.length + (gap.length >= 1 && gap.length <= 4 && raw[bullet.length + gap.length] !== "\n" ? gap.length : 1);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Offset of the block's closing line inside a list or quote, or -1. Lazy
|
|
58
|
+
* paragraph lines may hold it; a list item's own fenced code cannot.
|
|
59
|
+
*/
|
|
60
|
+
const closingLineIn = (token, indent) => {
|
|
61
|
+
if (token.type !== "list" && token.type !== "blockquote") return -1;
|
|
62
|
+
const items = token.type === "list" ? token.items : [];
|
|
63
|
+
let item = -1;
|
|
64
|
+
let itemStart = 0;
|
|
65
|
+
let itemEnd = 0;
|
|
66
|
+
let text = 0;
|
|
67
|
+
let fence = "";
|
|
68
|
+
for (let from = 0; from < token.raw.length;) {
|
|
69
|
+
while (item + 1 < items.length && from >= itemEnd) {
|
|
70
|
+
item++;
|
|
71
|
+
itemStart = itemEnd;
|
|
72
|
+
itemEnd += items[item].raw.length;
|
|
73
|
+
text = itemTextIndent(items[item].raw);
|
|
74
|
+
fence = "";
|
|
75
|
+
}
|
|
76
|
+
const end = lineEnd(token.raw, from);
|
|
77
|
+
const line = token.raw.slice(from, end);
|
|
78
|
+
// A line indented less than the item's text has left the item and its fence.
|
|
79
|
+
if (fence && line.trim() && line.length - line.trimStart().length < text) fence = "";
|
|
80
|
+
// The first line of an item carries its bullet where the text would be indented.
|
|
81
|
+
const marker = items.length ? FENCE.exec(from === itemStart ? " ".repeat(text) + line.slice(text) : line) : null;
|
|
82
|
+
if (fence) {
|
|
83
|
+
if (marker && marker[2][0] === fence[0] && marker[2].length >= fence.length && !marker[3].trim()) fence = "";
|
|
84
|
+
} else if (marker && marker[1].length >= text && marker[1].length <= text + 3 && !(marker[2][0] === "`" && marker[3].includes("`"))) {
|
|
85
|
+
fence = marker[2];
|
|
86
|
+
} else if (closes(line, indent)) {
|
|
87
|
+
return from;
|
|
88
|
+
}
|
|
89
|
+
from = end + 1;
|
|
90
|
+
}
|
|
91
|
+
return -1;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Whether `line` starts a block of its own after a paragraph line instead of continuing the paragraph, as marked decides. */
|
|
95
|
+
const interruptsParagraph = line => Lexer.rules.block.gfm.paragraph.exec(`x\n${line}\n`)?.[0] === "x";
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Reads info blocks in one `\n`-separated source. The opening line reads like
|
|
99
|
+
* a paragraph line, so the body continues it: only a block that may interrupt
|
|
100
|
+
* a paragraph, such as a fence, a list, a quote, or block HTML, hides its
|
|
101
|
+
* lines from the closing line. A scan's only state is its line and whether a
|
|
102
|
+
* paragraph is open there, so a later scan that reaches a line an earlier one
|
|
103
|
+
* passed ends the same way; `outcomes` remembers that, which keeps reading
|
|
104
|
+
* many openers of one document linear.
|
|
105
|
+
*/
|
|
106
|
+
const infoBlockReader = source => {
|
|
107
|
+
const outcomes = new Map();
|
|
108
|
+
let tokenizer;
|
|
109
|
+
|
|
110
|
+
/** Code, lists, quotes, and HTML whose lines belong to the body even when one of them reads `:::`. */
|
|
111
|
+
const container = (offset, line, paragraph) => {
|
|
112
|
+
const kind = /^(?: {4}| {0,3}\t)/.test(line) ? "code" : /^ {0,3}(?:`{3,}|~{3,})/.test(line) ? "fences" : /^ {0,3}(?:[-+*][ \t]|\d{1,9}[.)][ \t])/.test(line) ? "list" : /^ {0,3}>/.test(line) ? "blockquote" : /^ {0,3}</.test(line) ? "html" : undefined;
|
|
113
|
+
if (!kind || paragraph && !interruptsParagraph(line)) return undefined;
|
|
114
|
+
if (!tokenizer) {
|
|
115
|
+
// One tokenizer per document: its lexer queues inline work that nothing drains.
|
|
116
|
+
tokenizer = new Tokenizer({
|
|
117
|
+
gfm: true
|
|
118
|
+
});
|
|
119
|
+
new Lexer({
|
|
120
|
+
gfm: true,
|
|
121
|
+
tokenizer
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return tokenizer[kind](source.slice(offset));
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/** Offset of the closing line for a body that starts at `start`, or -1 when the block never closes. */
|
|
128
|
+
const closingLine = (start, indent) => {
|
|
129
|
+
const passed = [];
|
|
130
|
+
let offset = start;
|
|
131
|
+
let paragraph = true;
|
|
132
|
+
let result = -1;
|
|
133
|
+
while (offset < source.length) {
|
|
134
|
+
const key = offset * 8 + indent * 2 + (paragraph ? 1 : 0);
|
|
135
|
+
const known = outcomes.get(key);
|
|
136
|
+
if (known !== undefined) {
|
|
137
|
+
result = known;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
passed.push(key);
|
|
141
|
+
const end = lineEnd(source, offset);
|
|
142
|
+
const line = source.slice(offset, end);
|
|
143
|
+
if (closes(line, indent)) {
|
|
144
|
+
result = offset;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
const token = container(offset, line, paragraph);
|
|
148
|
+
if (token) {
|
|
149
|
+
const closing = closingLineIn(token, indent);
|
|
150
|
+
const length = closing < 0 ? token.raw.length : closing;
|
|
151
|
+
if (length > 0) {
|
|
152
|
+
offset += length;
|
|
153
|
+
paragraph = false;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
// A blank line ends a paragraph; any other line continues or starts one.
|
|
158
|
+
paragraph = line.trim() !== "";
|
|
159
|
+
offset = Math.min(end + 1, source.length);
|
|
160
|
+
}
|
|
161
|
+
for (const key of passed) outcomes.set(key, result);
|
|
162
|
+
return result;
|
|
163
|
+
};
|
|
164
|
+
return offset => {
|
|
165
|
+
const firstEnd = lineEnd(source, offset);
|
|
166
|
+
const opener = OPENER.exec(source.slice(offset, firstEnd));
|
|
167
|
+
if (!opener) return null;
|
|
168
|
+
const indent = opener[1].length;
|
|
169
|
+
const type = opener[2].toLowerCase();
|
|
170
|
+
const title = opener[3]?.trim() || undefined;
|
|
171
|
+
const bodyStart = Math.min(firstEnd + 1, source.length);
|
|
172
|
+
const closing = closingLine(bodyStart, indent);
|
|
173
|
+
if (closing < 0) return {
|
|
174
|
+
type,
|
|
175
|
+
title,
|
|
176
|
+
body: source.slice(bodyStart),
|
|
177
|
+
length: source.length - offset,
|
|
178
|
+
closed: false
|
|
179
|
+
};
|
|
180
|
+
const body = source.slice(bodyStart, closing).replace(/\n$/, "");
|
|
181
|
+
return {
|
|
182
|
+
type,
|
|
183
|
+
title,
|
|
184
|
+
body,
|
|
185
|
+
length: Math.min(lineEnd(source, closing) + 1, source.length) - offset,
|
|
186
|
+
closed: true
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Reads the info block that starts `source`. Returns `null` when the first
|
|
193
|
+
* line is not an info-block opener. Applications with their own Markdown
|
|
194
|
+
* pipeline use this to recognize exactly the blocks `MarkdownView` renders.
|
|
195
|
+
* Any line endings are accepted; `length` counts `source` as given.
|
|
196
|
+
*/
|
|
197
|
+
export const scanMarkdownInfoBlock = source => {
|
|
198
|
+
const normalized = source.replace(/\r\n?/g, "\n");
|
|
199
|
+
const block = infoBlockReader(normalized)(0);
|
|
200
|
+
if (!block || normalized.length === source.length) return block;
|
|
201
|
+
// Only `\r\n` shortens the source; count each one twice up to the block's end.
|
|
202
|
+
let length = 0;
|
|
203
|
+
for (let index = 0; index < block.length; index++) length += source[length] === "\r" && source[length + 1] === "\n" ? 2 : 1;
|
|
204
|
+
return {
|
|
205
|
+
...block,
|
|
206
|
+
length
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
const renderBlock = (input, messages) => {
|
|
210
|
+
const name = input.title ? `<p class="${NOTICE_CARD_CLASSES.title}">${escapeHtml(input.title)}</p>` : `<span class="k2b-sr-only">${escapeHtml(LABELS[input.type](messages))}: </span>`;
|
|
211
|
+
return `<aside class="${NOTICE_CARD_CLASSES.root}" data-tone="${TONES[input.type]}" role="note">${name}<div class="${NOTICE_CARD_CLASSES.body}">${input.bodyHtml}</div></aside>`;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Renders an info block as the calm `NoticeCard`: the tone tints the surface,
|
|
216
|
+
* the text stays neutral, and there is no icon. A title is the visible heading
|
|
217
|
+
* and names the block; without one, the localized type name is announced to
|
|
218
|
+
* screen readers only.
|
|
219
|
+
*/
|
|
220
|
+
export const renderMarkdownInfoBlock = input => renderBlock(input, resolveUiMessages(input.locale));
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* What one `marked` lexer run knows about its document: the opening lines, the
|
|
224
|
+
* blocks read so far, the length of the last top-level source, and the extent
|
|
225
|
+
* of the last top-level paragraph `start` measured.
|
|
226
|
+
*/
|
|
227
|
+
|
|
228
|
+
const documents = new WeakMap();
|
|
229
|
+
|
|
230
|
+
/** The closed block that starts at `offset`, read once per document. */
|
|
231
|
+
const closedBlockAt = (document, offset) => {
|
|
232
|
+
let block = document.blocks.get(offset);
|
|
233
|
+
if (block === undefined) {
|
|
234
|
+
const read = document.read(offset);
|
|
235
|
+
block = read?.closed ? read : null;
|
|
236
|
+
document.blocks.set(offset, block);
|
|
237
|
+
}
|
|
238
|
+
return block;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/** Index of the first of the ascending `offsets` at or after `from`. */
|
|
242
|
+
const firstAtOrAfter = (offsets, from) => {
|
|
243
|
+
let low = 0;
|
|
244
|
+
let high = offsets.length;
|
|
245
|
+
while (low < high) {
|
|
246
|
+
const middle = low + high >> 1;
|
|
247
|
+
if (offsets[middle] < from) low = middle + 1;else high = middle;
|
|
248
|
+
}
|
|
249
|
+
return low;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The first closed block after the top-level `position` inside the paragraph
|
|
254
|
+
* that would start there. Openers further away cannot end that paragraph, and
|
|
255
|
+
* a paragraph that starts inside the last measured one ends where it ends.
|
|
256
|
+
*/
|
|
257
|
+
const nextBlockStart = (document, position, rules) => {
|
|
258
|
+
if (position < document.paragraph.start || position >= document.paragraph.end) {
|
|
259
|
+
const extent = rules.exec(document.source.slice(position))?.[0].length ?? 0;
|
|
260
|
+
document.paragraph = {
|
|
261
|
+
start: position,
|
|
262
|
+
end: position + extent
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
for (let index = firstAtOrAfter(document.openers, position + 1); index < document.openers.length; index++) {
|
|
266
|
+
const offset = document.openers[index];
|
|
267
|
+
if (offset >= document.paragraph.end) return undefined;
|
|
268
|
+
if (closedBlockAt(document, offset)) return offset;
|
|
269
|
+
}
|
|
270
|
+
return undefined;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
/** The paragraph rule of the lexer's own flavour. */
|
|
274
|
+
const paragraphRule = lexer => Lexer.rules.block[lexer.options.pedantic ? "pedantic" : lexer.options.gfm ? "gfm" : "normal"].paragraph;
|
|
275
|
+
const createExtension = messages => {
|
|
276
|
+
const extension = {
|
|
277
|
+
name: "markdownInfoBlock",
|
|
278
|
+
level: "block",
|
|
279
|
+
// marked ends a top-level paragraph where `start` points. Only a block
|
|
280
|
+
// that closes renders, so `start` points at the first one inside the
|
|
281
|
+
// paragraph; a split anywhere else would only make marked lex the rest of
|
|
282
|
+
// the document again.
|
|
283
|
+
start(source) {
|
|
284
|
+
const document = documents.get(this.lexer);
|
|
285
|
+
// marked asks right after the tokenizer below ran at the same top-level position.
|
|
286
|
+
if (!document || source.length + 1 !== document.top) return undefined;
|
|
287
|
+
const position = document.source.length - source.length - 1;
|
|
288
|
+
const next = nextBlockStart(document, position, paragraphRule(this.lexer));
|
|
289
|
+
return next === undefined ? undefined : next - position - 1;
|
|
290
|
+
},
|
|
291
|
+
tokenizer(source, tokens) {
|
|
292
|
+
let document = documents.get(this.lexer);
|
|
293
|
+
if (tokens !== this.lexer.tokens) {
|
|
294
|
+
// Nested sources are rewritten text, not the rest of the document.
|
|
295
|
+
if (document) document.top = -1;
|
|
296
|
+
return undefined;
|
|
297
|
+
}
|
|
298
|
+
// The first top-level call sees the whole document; later ones see what is left of it.
|
|
299
|
+
if (!document) {
|
|
300
|
+
document = {
|
|
301
|
+
source,
|
|
302
|
+
read: infoBlockReader(source),
|
|
303
|
+
openers: Array.from(source.matchAll(OPENERS), opener => opener.index),
|
|
304
|
+
blocks: new Map(),
|
|
305
|
+
top: source.length,
|
|
306
|
+
paragraph: {
|
|
307
|
+
start: -1,
|
|
308
|
+
end: -1
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
documents.set(this.lexer, document);
|
|
312
|
+
}
|
|
313
|
+
document.top = source.length;
|
|
314
|
+
if (!START.test(source)) return undefined;
|
|
315
|
+
const block = closedBlockAt(document, document.source.length - source.length);
|
|
316
|
+
if (!block) return undefined;
|
|
317
|
+
return {
|
|
318
|
+
type: "markdownInfoBlock",
|
|
319
|
+
raw: source.slice(0, block.length),
|
|
320
|
+
blockType: block.type,
|
|
321
|
+
title: block.title,
|
|
322
|
+
tokens: this.lexer.blockTokens(block.body, [])
|
|
323
|
+
};
|
|
324
|
+
},
|
|
325
|
+
renderer(token) {
|
|
326
|
+
return renderBlock({
|
|
327
|
+
type: token.blockType,
|
|
328
|
+
title: token.title,
|
|
329
|
+
bodyHtml: this.parser.parse(token.tokens ?? [])
|
|
330
|
+
}, messages);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
return {
|
|
334
|
+
extensions: [extension],
|
|
335
|
+
tokenizer: {
|
|
336
|
+
// A setext heading's text is a paragraph, so it ends before a block as
|
|
337
|
+
// well; marked does not clip it at `start` itself.
|
|
338
|
+
lheading(source) {
|
|
339
|
+
const document = documents.get(this.lexer);
|
|
340
|
+
if (!document || source.length !== document.top) return false;
|
|
341
|
+
const position = document.source.length - source.length;
|
|
342
|
+
const next = nextBlockStart(document, position, paragraphRule(this.lexer));
|
|
343
|
+
return next === undefined ? false : Tokenizer.prototype.lheading.call(this, source.slice(0, next - position));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
const extensions = new WeakMap();
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* `marked` extension for info blocks at the top level of a document. Blocks
|
|
352
|
+
* inside lists, quotes, or another block stay ordinary text. The body goes
|
|
353
|
+
* through the host's own Markdown renderer, so its escaping and link rules
|
|
354
|
+
* apply unchanged. Locales that share a UI message catalog get the same
|
|
355
|
+
* extension, so a host may cache one `marked` instance per extension.
|
|
356
|
+
*/
|
|
357
|
+
export const markdownInfoBlocks = (options = {}) => {
|
|
358
|
+
const messages = resolveUiMessages(options.locale);
|
|
359
|
+
const extension = extensions.get(messages) ?? createExtension(messages);
|
|
360
|
+
extensions.set(messages, extension);
|
|
361
|
+
return extension;
|
|
362
|
+
};
|
|
363
|
+
//# sourceMappingURL=markdown-info-blocks.js.map
|