@dooc-dev/dooc 0.0.29 → 0.0.30

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.
@@ -20,10 +20,11 @@ export interface RenderCtx {
20
20
  lang?: string;
21
21
  /** Localized in-page table of contents title. Default: Contents. */
22
22
  tocTitle?: string;
23
- /** Download URL of the page's own source, shown beside its title. */
23
+ /** Download URLs for the page's source and standalone HTML. */
24
24
  pageDownload?: {
25
25
  file: string;
26
26
  href: string;
27
+ htmlHref: string;
27
28
  };
28
29
  /** Document URL for the reader's section-copy buttons. */
29
30
  sectionUrl?: string;
@@ -37,6 +38,7 @@ export declare const emptyCtx: RenderCtx;
37
38
  /** Shared dictionary entries for definitions and the Resources list. */
38
39
  export declare const termsHtml: (terms: readonly TermEntry[], language?: LanguageAdapter, sortable?: boolean) => string;
39
40
  export declare const resourceDownloadHtml: (file: string, href: string) => string;
41
+ export declare const pageHtmlFilename: (file: string) => string;
40
42
  export declare const subformatTableHtml: (collection: SubformatCollection, label: string) => string;
41
43
  export declare const blocksHtml: (blocks: Block[], ctx?: RenderCtx) => string;
42
44
  export declare const docHtml: (_fm: Frontmatter, blocks: Block[], errors: string[], ctx?: RenderCtx, toc?: TocEntry[]) => string;
@@ -344,7 +344,10 @@ export const termsHtml = (terms, language, sortable = false) => {
344
344
  .map((e, i) => `<fieldset class="dict-card" data-source-order="${e.sourceOrder}" data-sort-order="${i}" data-term="${escapeHtml(e.id)}"><legend id="${termAnchor(e.id)}">${TERM_ICON}<a class="term-name" href="/_files/terms#${encodeURIComponent(termAnchor(e.id))}"${e.description ? ` aria-describedby="term-description-${encodeURIComponent(e.id)}"` : ""}>${escapeHtml(e.name)}${e.description ? `<span class="term-description" role="tooltip" id="term-description-${encodeURIComponent(e.id)}">${escapeHtml(e.description)}</span>` : ""}</a></legend><p class="term-definition">${escapeHtml(e.definition)}</p></fieldset>`)
345
345
  .join("")}</div></section>`;
346
346
  };
347
- export const resourceDownloadHtml = (file, href) => `<a class="resource-download" href="${escapeHtml(href)}" download="${escapeHtml(textfileName(file))}" data-resource-download title="${escapeHtml(`Download ${textfileName(file)}`)}" aria-label="${escapeHtml(`Download ${textfileName(file)}`)}"><svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 2v10m-4-4 4 4 4-4M3 13v4h14v-4"/></svg></a>`;
347
+ const DOWNLOAD_ICON = '<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 2v10m-4-4 4 4 4-4M3 13v4h14v-4"/></svg>';
348
+ export const resourceDownloadHtml = (file, href) => `<a class="resource-download" href="${escapeHtml(href)}" download="${escapeHtml(textfileName(file))}" data-resource-download title="${escapeHtml(`Download ${textfileName(file)}`)}" aria-label="${escapeHtml(`Download ${textfileName(file)}`)}">${DOWNLOAD_ICON}</a>`;
349
+ export const pageHtmlFilename = (file) => `${textfileName(file).replace(/\.(?:md|markdown)$/i, "")}.html`;
350
+ const pageDownloadPicker = ({ file, href, htmlHref, }) => `<div class="page-download"><button class="pbtn" type="button" title="Download page" aria-label="Download page" data-i18n-title="Download page" data-i18n-aria-label="Download page">${DOWNLOAD_ICON}</button><div class="page-download-options theme-picker" popover><a href="${escapeHtml(htmlHref)}" download="${escapeHtml(pageHtmlFilename(file))}" data-resource-download>HTML (.html)</a><a href="${escapeHtml(href)}" download="${escapeHtml(textfileName(file))}" data-resource-download>Markdown (.md)</a></div></div>`;
348
351
  export const subformatTableHtml = (collection, label) => `<div class="subformat-table" tabindex="0" role="region" aria-label="${escapeHtml(label)}"><table><thead><tr><th scope="col" data-i18n="File name">File name</th>${collection.fields.map((field) => `<th scope="col">${escapeHtml(field.title)}</th>`).join("")}</tr></thead><tbody>${collection.records.map((record, index) => `<tr data-record-file="${escapeHtml(record.file)}"><th scope="row"><button type="button" data-subformat-record="${index}" aria-haspopup="dialog" title="${escapeHtml(record.file)}">${escapeHtml(textfileName(record.file))}</button></th>${collection.fields.map((field) => `<td><span>${Object.hasOwn(record.data, field.name) ? escapeHtml(typeof record.data[field.name] === "object" ? JSON.stringify(record.data[field.name]) : String(record.data[field.name])) : ""}</span></td>`).join("")}</tr>`).join("")}</tbody></table></div>${collection.records.length ? "" : '<p data-i18n="No results">No results</p>'}`;
349
352
  const RESOURCE_EXPAND = '<button class="resource-download resource-expand" type="button" data-resource-expand title="Expand" aria-label="Expand"><svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 8V3h5M17 8V3h-5M3 12v5h5M17 12v5h-5"/></svg></button>';
350
353
  const blockHtml = (b, ctx, seg) => {
@@ -499,6 +502,6 @@ export const docHtml = (_fm, blocks, errors, ctx = emptyCtx, toc = []) => {
499
502
  ? `<div class="errors">${errors.map((e) => `<div>${escapeHtml(e)}</div>`).join("")}</div>`
500
503
  : "";
501
504
  const lang = ctx.lang ? ` lang="${escapeHtml(ctx.lang)}"` : "";
502
- const controls = `${inPageTocHtml(toc, ctx.tocTitle)}${ctx.pageDownload ? resourceDownloadHtml(ctx.pageDownload.file, ctx.pageDownload.href) : ""}`;
505
+ const controls = `${inPageTocHtml(toc, ctx.tocTitle)}${ctx.pageDownload ? pageDownloadPicker(ctx.pageDownload) : ""}`;
503
506
  return `<article${lang}>${errBox}${controls ? `<header class="doc-title">${controls}</header>` : ""}${blocksHtml(blocks, ctx)}</article>`;
504
507
  };
@@ -24,7 +24,7 @@ import { figureFrameHtml, mountFigureFrames } from "../engine/core/figure-frame.
24
24
  import { defaultFilePath, docIconFile, isSkillFile, manifestDirectory, parseFileLayout, docFile as sourceDocFile, suggestDocFileName, } from "../engine/core/files.js";
25
25
  import { FORMAT_TRAITS, formatSelector, matchesFormat, parseFormatQuery, } from "../engine/core/format-collections.js";
26
26
  import { fenceFormat, fileFormat, isReferenceLibrary, REFERENCE_LIBRARIES, } from "../engine/core/formats.js";
27
- import { blocksHtml, docHtml, escapeHtml, resourceDownloadHtml, termsHtml, } from "../engine/core/html.js";
27
+ import { blocksHtml, docHtml, escapeHtml, pageHtmlFilename, resourceDownloadHtml, termsHtml, } from "../engine/core/html.js";
28
28
  import { FOLDER_ICON_PATH, LIBRARY_ICONS, LLM_ICON, libraryIcon, PLUGINS_ICON, SUBFORMATS_ICON, } from "../engine/core/icons.js";
29
29
  import { DEFAULT_LANG, isLangTag, resolveLanguage, } from "../engine/core/language.js";
30
30
  import { ja } from "../engine/core/languages/ja.js";
@@ -371,21 +371,76 @@ export const createDocumentApplication = (root, host) => {
371
371
  const jump = docHref(site.entries, id);
372
372
  return `${isLinkedEntry(entry) ? "data-document-link " : ""}${/^https?:\/\//i.test(jump) ? `data-jump-url="${escapeHtml(jump)}" ` : ""}href="${escapeHtml(docHref(site.entries, id, true))}`;
373
373
  });
374
- /** Easy download offers the page's own Markdown above its content. */
374
+ const pageContext = (site, entry) => ({
375
+ ...site.ctx,
376
+ pageContents: (file, recursive, title) => contentsLibrary(site, file, recursive, title),
377
+ terms: entry.terms ?? site.ctx.terms,
378
+ lang: webLanguage(entry.lang),
379
+ language: resolveLanguage(entry.lang, site.languages),
380
+ });
381
+ const offlinePolicy = (split = false) => {
382
+ const self = split ? "'self' " : "";
383
+ return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${self}'unsafe-inline'; style-src ${self}'unsafe-inline' data:; img-src ${self}data: blob:; media-src ${self}data: blob:; object-src ${self}data:; font-src ${self}data: blob:; frame-src ${self}data: blob:; connect-src ${split ? "'self'" : "'none'"}; base-uri 'none'; form-action 'none'">`;
384
+ };
385
+ const standalonePageHtml = (site, entry) => {
386
+ const ctx = pageContext(site, entry);
387
+ const body = blocksHtml(entry.blocks, { ...ctx, downloads: undefined, figurePreview: undefined }) ||
388
+ (!entry.root && childrenOf(site.entries, entry.id).length
389
+ ? contentsTree(site, entry, true)
390
+ : "");
391
+ const pages = new Map(Array.from(site.ctx.docLinks ?? [], ([file, route]) => [route, file]));
392
+ const source = entry.sourceFile ?? CONTENT_PREFIX + entry.file;
393
+ const content = docLinks(site, body).replace(/href="(\/[^"#?]*)(#[^"]*)?"/g, (original, path, hash = "") => {
394
+ const target = pages.get(path);
395
+ if (target === source)
396
+ return `href="${hash || "#"}"`;
397
+ if (target)
398
+ return `href="./${encodeURIComponent(pageHtmlFilename(target))}${hash}"`;
399
+ if (path.startsWith("/_files/file/"))
400
+ return `href="./${path.slice("/_files/file/".length).split(/%2F/i).at(-1)}${hash}"`;
401
+ return original;
402
+ });
403
+ const frames = content.includes("data-doc-figure-frame=")
404
+ ? `<script>var __name = (f) => f; (${inlineScript(mountFigureFrames.toString())})(document);</script>`
405
+ : "";
406
+ return `<!doctype html><html lang="${escapeHtml(ctx.lang ?? "en")}"><head><meta charset="utf-8">${offlinePolicy()}<meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><title>${escapeHtml(docDisplayName(entry.frontmatter, entry.id))}</title>
407
+ <style>
408
+ :root { ${LIGHT_C} ${DOC_FROM_C} }
409
+ @media (prefers-color-scheme: dark) { :root { ${DARK_C} } }
410
+ body { max-width: 75ch; margin: auto; padding: 1.5rem; color: var(--doc-fg); background: var(--doc-bg);
411
+ font: 1rem/1.6 system-ui, sans-serif; overflow-wrap: anywhere; }
412
+ a { color: var(--doc-accent-2); }
413
+ img, video, iframe, object, svg { max-width: 100%; }
414
+ iframe { border: 0; }
415
+ pre, .data-table-scroll { overflow: auto; }
416
+ table { border-collapse: collapse; }
417
+ th, td { padding: .3em .6em; border: 1px solid var(--doc-border); }
418
+ figure { margin: 1em 0; }
419
+ .cap { white-space: pre-line; }
420
+ .codecopy, .codefold, .figpop, .dictpop, .dict-toolbar, .data-table-resize, .subformat-embed-toolbar { display: none; }
421
+ .codeblk-head { display: flex; gap: .5em; }
422
+ .doc-icon { width: 1em; height: 1em; margin-right: .4em; }
423
+ </style>${frames}</head><body><article>${content}</article></body></html>`;
424
+ };
375
425
  const pageDownload = (site, entry) => {
376
426
  const file = entry.sourceFile ?? CONTENT_PREFIX + entry.file;
377
- const href = site.ctx.downloads?.get(file);
378
- return href ? { pageDownload: { file, href } } : {};
427
+ const source = site.ctx.downloads?.get(file);
428
+ if (!source)
429
+ return {};
430
+ const language = contentLanguageCode(site.defaultLang);
431
+ const locale = site.contentLanguage ?? language;
432
+ const url = `/api/download?page=${encodeURIComponent(docPath(site.entries, entry.id))}&lang=${encodeURIComponent(locale)}`;
433
+ const href = site.download !== "easy" && locale !== language ? `${url}&format=md` : source;
434
+ const htmlHref = site.download === "easy"
435
+ ? `data:application/octet-stream;base64,${Buffer.from(standalonePageHtml(site, entry)).toString("base64")}`
436
+ : `${url}&format=html`;
437
+ return { pageDownload: { file, href, htmlHref } };
379
438
  };
380
439
  const renderEntry = (site, entry, fallbackTitle) => docLinks(site, docHtml(entry.frontmatter ?? { title: fallbackTitle }, entry.blocks, [...site.errors, ...entry.errors], {
381
- ...site.ctx,
382
- pageContents: (file, recursive, title) => contentsLibrary(site, file, recursive, title),
440
+ ...pageContext(site, entry),
383
441
  ...pageDownload(site, entry),
384
- terms: entry.terms ?? site.ctx.terms,
385
- lang: webLanguage(entry.lang),
386
442
  tocTitle: translate(entry.lang, "Contents"),
387
443
  sectionUrl: `${docPath(site.entries, entry.id)}?lang=${encodeURIComponent(site.contentLanguage ?? entry.lang)}`,
388
- language: resolveLanguage(entry.lang, site.languages),
389
444
  }, entry.toc));
390
445
  /** Compiles one source (unsaved or on disk; file = `<id>.md`) in the site context into an Entry. */
391
446
  const draftEntry = (site, file, raw, textfiles) => {
@@ -655,9 +710,9 @@ body.edit :is(#sidebar, #panel, .resources-pane, .subformat-toast, .app-dialog,
655
710
  .preview-pane { background: var(--c-bg0); color: var(--c-fg); }
656
711
  .theme-picker { position: fixed; margin: 0; padding: 5px; width: 148px; border: 1px solid var(--c-line);
657
712
  border-radius: 6px; background: var(--c-bg1); color: var(--c-fg); box-shadow: 0 8px 24px var(--c-shadow); }
658
- .theme-picker button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 8px;
659
- border: 0; border-radius: 4px; background: transparent; color: inherit; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
660
- .theme-picker button:hover, .theme-picker button:focus-visible { background: var(--c-raised); }
713
+ .theme-picker :is(button, a[download]) { display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 8px;
714
+ border: 0; border-radius: 4px; background: transparent; color: inherit; font: inherit; font-size: 12px; text-align: left; text-decoration: none; cursor: pointer; }
715
+ .theme-picker :is(button, a[download]):is(:hover, :focus-visible) { background: var(--c-raised); }
661
716
  .theme-picker [aria-checked="true"]::after { content: "✓"; margin-left: auto; color: var(--c-accent); }
662
717
  .font-control:focus:not(:focus-visible), .font-picker button:focus:not(:focus-visible) { outline: none; }
663
718
  .font-control:focus-visible, .font-picker button:focus-visible { outline: 1px solid var(--c-accent); outline-offset: 1px; }
@@ -3081,7 +3136,6 @@ body.edit .nav-row { cursor: grab; }
3081
3136
  const stylesheet = output
3082
3137
  ? `<link rel="stylesheet" href="${escapeHtml(output.asset(css, "css"))}">`
3083
3138
  : `<style>${css}</style>`;
3084
- const self = output ? "'self' " : "";
3085
3139
  const bootScripts = opts.boot != null
3086
3140
  ? `<script id="boot" type="application/json">${JSON.stringify(opts.boot).replace(/</g, "\\u003c")}</script>
3087
3141
  <script src="/assets/edit.js"></script>
@@ -3109,7 +3163,7 @@ body.edit .nav-row { cursor: grab; }
3109
3163
  ? script(opts.publish.graphJs)
3110
3164
  : `<script>(${loadPreviewScript.toString()})("/assets/graph.js", "svg[data-sg-layout], [data-mermaid]", "module");</script>`;
3111
3165
  const frame = `<!doctype html><html lang="en"${site.accentColor ? ` style="--project-accent:${escapeHtml(site.accentColor)}"` : ""}><head><meta charset="utf-8">
3112
- ${opts.publish ? `<meta name="referrer" content="no-referrer"><meta http-equiv="x-dns-prefetch-control" content="off">${opts.publish.network ? "" : `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${self}'unsafe-inline'; style-src ${self}'unsafe-inline' data:; img-src ${self}data: blob:; media-src ${self}data: blob:; object-src ${self}data:; font-src ${self}data: blob:; frame-src ${self}data: blob:; connect-src ${output ? "'self'" : "'none'"}; base-uri 'none'; form-action 'none'">`}` : ""}
3166
+ ${opts.publish ? `<meta name="referrer" content="no-referrer"><meta http-equiv="x-dns-prefetch-control" content="off">${opts.publish.network ? "" : offlinePolicy(Boolean(output))}` : ""}
3113
3167
  <meta name="viewport" content="width=device-width, initial-scale=1">
3114
3168
  <title>${escapeHtml(pageTitle(mode, opts.title, site))}</title>
3115
3169
  ${favicons}
@@ -4595,11 +4649,39 @@ ${languageFieldHtml(site.defaultLang, site.contentLanguage, entry.translatedLang
4595
4649
  }
4596
4650
  if (mode === "edit" && req.method === "GET" && path === "/api/download") {
4597
4651
  try {
4598
- const file = requestUrl.searchParams.get("file") ?? "";
4599
- const data = readDownloadFile(root, file);
4652
+ const route = requestUrl.searchParams.get("page");
4653
+ let filename;
4654
+ let data;
4655
+ let contentType = "application/octet-stream";
4656
+ if (route !== null) {
4657
+ const format = requestUrl.searchParams.get("format");
4658
+ if (format !== "html" && format !== "md") {
4659
+ sendJson(res, 400, { error: "Expected HTML or Markdown download format" });
4660
+ return;
4661
+ }
4662
+ const site = loadSite(locale, route);
4663
+ const id = resolveDocPath(site.entries, route);
4664
+ const entry = site.entries.find((page) => page.id === id && isContentPage(page));
4665
+ const file = entry && (entry.sourceFile ?? CONTENT_PREFIX + entry.file);
4666
+ if (!entry || !file || !site.ctx.downloads?.has(file)) {
4667
+ notFound(res, route);
4668
+ return;
4669
+ }
4670
+ filename = format === "html" ? pageHtmlFilename(file) : textfileName(file);
4671
+ data = format === "html" ? standalonePageHtml(site, entry) : entry.raw;
4672
+ contentType =
4673
+ format === "html"
4674
+ ? "text/html; charset=utf-8"
4675
+ : "text/markdown; charset=utf-8";
4676
+ }
4677
+ else {
4678
+ const file = requestUrl.searchParams.get("file") ?? "";
4679
+ filename = textfileName(file);
4680
+ data = readDownloadFile(root, file);
4681
+ }
4600
4682
  res.writeHead(200, {
4601
- "content-type": "application/octet-stream",
4602
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(textfileName(file))}`,
4683
+ "content-type": contentType,
4684
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
4603
4685
  "cache-control": "no-store",
4604
4686
  "x-content-type-options": "nosniff",
4605
4687
  });
@@ -623,6 +623,7 @@
623
623
  "Remove format": "Remove format",
624
624
  "Enter a new file extension": "Enter a new file extension",
625
625
  "Could not load formats": "Could not load formats",
626
+ "Download page": "Download page",
626
627
  "Downloading…": "Downloading…",
627
628
  "Access denied.": "Access denied.",
628
629
  "File unavailable.": "File unavailable.",
@@ -623,6 +623,7 @@
623
623
  "Remove format": "フォーマットを削除",
624
624
  "Enter a new file extension": "未登録の拡張子を入力してください",
625
625
  "Could not load formats": "フォーマットを読み込めませんでした",
626
+ "Download page": "ページをダウンロード",
626
627
  "Downloading…": "ダウンロード中…",
627
628
  "Access denied.": "アクセス権がありません。",
628
629
  "File unavailable.": "ファイルが見つかりません。",
@@ -623,6 +623,7 @@
623
623
  "Remove format": "移除格式",
624
624
  "Enter a new file extension": "请输入尚未配置的扩展名",
625
625
  "Could not load formats": "无法加载格式",
626
+ "Download page": "下载页面",
626
627
  "Downloading…": "正在下载…",
627
628
  "Access denied.": "没有访问权限。",
628
629
  "File unavailable.": "文件不可用。",
@@ -65,8 +65,13 @@ export const mountResourceDownloads = (request = fetch) => {
65
65
  const link = event.target instanceof Element
66
66
  ? event.target.closest("a[data-resource-download]")
67
67
  : null;
68
- if (!link || !/^https?:/.test(link.href))
68
+ if (!link)
69
69
  return;
70
+ const formats = link.closest(".page-download-options");
71
+ if (!/^https?:/.test(link.href)) {
72
+ formats?.hidePopover();
73
+ return;
74
+ }
70
75
  event.preventDefault();
71
76
  if (link.getAttribute("aria-busy") === "true")
72
77
  return;
@@ -101,6 +106,7 @@ export const mountResourceDownloads = (request = fetch) => {
101
106
  download.remove();
102
107
  setTimeout(() => URL.revokeObjectURL(url), 60000);
103
108
  status.textContent = "";
109
+ formats?.hidePopover();
104
110
  }
105
111
  catch {
106
112
  status.textContent = translate("Download failed. Retry.");
@@ -53,6 +53,19 @@ export function mountToc(doc) {
53
53
  },
54
54
  };
55
55
  mounted.set(toolbar, state);
56
+ const download = controls.querySelector(".page-download");
57
+ const trigger = download?.querySelector("button");
58
+ const formats = download?.querySelector("[popover]");
59
+ if (trigger && formats) {
60
+ trigger.popoverTargetElement = formats;
61
+ formats.addEventListener("beforetoggle", (event) => {
62
+ if (event.newState !== "open")
63
+ return;
64
+ const rect = trigger.getBoundingClientRect();
65
+ formats.style.left = `${Math.max(8, Math.min(rect.left, innerWidth - 156))}px`;
66
+ formats.style.top = `${rect.bottom + 4}px`;
67
+ }, options);
68
+ }
56
69
  const nav = controls.querySelector(".in-toc");
57
70
  const button = nav?.querySelector(".toc-current");
58
71
  const list = nav?.querySelector("ul");