Files
RuneStone/src/lib/layout/MarkdownView.svelte
T
Knotty Wyvern 9cf82503d0 Show one view control and name the file once
Phase 5-3.

- One radio group shows Write, Source, and Read at all times, with an
  icon and a name. Narrow panes show only the icons. The arrow keys
  move the choice, and the group has one Tab stop. The current choice
  gets the selection fill and an accent bar. Hover gets only a fill.
- A Split toggle shows Read beside Write or Source. Each document pane
  keeps a split flag beside its reading flag. Read ends Split.
- Ctrl+Shift+E switches between Read and the editor. Ctrl+E still
  switches between Write and Source.
- "IDE" becomes "Source" in the Chrome type, the tab menu (a View
  submenu), the status bar, the catalog, the tests, and the docs.
- Settings, General, File name title hides the title in Write and
  Read. It is on by default.
- The breadcrumb shows only the folder of the file. The status bar
  shows the view, not the path.
- ModeSwitcher.svelte and its hover test are gone. The new test
  layout/viewModes covers the control.
- The command palette from 5-2 gets its row in docs/menu-surfaces.json.
- The user guide Format table is whole again. The 5-2 edit had put
  the Paragraph and Insert rows under the shortcut table.
- 8 new catalog rows and 10 removed rows, in French, Japanese, and
  Simplified Chinese.
- Docs: UI-049, the user guide, ui-design.md, document-tools.md,
  development.md, and the README feature list.

Tests: the new layout/viewModes, new cases in documentPanes.spec.ts
and settings.spec.ts, and the chooseView harness helper. 21 smoke
tests use the new control. Tests that read the full path from the
breadcrumb now read its tooltip.
2026-10-28 19:45:08 -07:00

212 lines
8.3 KiB
Svelte

<script lang="ts">
import { t } from "$lib/i18n";
import { tableFormulasEnabled } from "$lib/formulas";
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import { fileTitleVisible } from "$lib/editor/fileTitle";
import { documentHeadings } from "$lib/workspace/headingLinks";
import "$lib/editor/headingFolding.css";
import { readingMenu } from "$lib/editor/readingMenu";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
noteRel: string;
contents: string;
focusLine?: number | null;
linkActions?: DocumentLinkActions;
onSearch?: (text: string) => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onEditBlock?: (start: number, end: number) => void;
editing?: { start: number; end: number } | null;
blockEditor?: Snippet;
};
let { noteRel, contents, focusLine = null, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let menuError = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
const collapsedHeadings = new Set<string>();
let foldingNote = "";
let headingControls: ReturnType<typeof readerHeadingFolding> | undefined;
$effect(() => {
if (!root) return;
return readingMenu(root, { ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }, onSearch, message => { menuError = message; });
});
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
await Promise.all(markdownImages(contents).map(async source => {
if (isRemoteImage(source)) {
urls.set(source, source.trim());
return;
}
let path = source;
try { path = decodeURIComponent(source); } catch { /* Keep literal malformed escapes. */ }
const primary = resolveImageRel(noteRel, path);
const normalized = path.replaceAll("\\", "/").replace(/^\/+/, "");
const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) {
try {
urls.set(source, await workspaceReadDataUrl(candidate));
return;
} catch { /* Try the workspace-relative attachment next. */ }
}
urls.set(source, "");
}));
return urls;
}
$effect(() => {
void $tableFormulasEnabled;
const path = noteRel;
if (foldingNote !== path) { collapsedHeadings.clear(); foldingNote = path; }
const text = contents;
let cancelled = false;
html = renderMarkdownHtml(text, new Map());
sections = renderMarkdownSections(text, new Map());
void loadUrls(path, text).then(urls => {
if (!cancelled) {
html = renderMarkdownHtml(text, urls);
sections = renderMarkdownSections(text, urls);
}
});
return () => { cancelled = true; };
});
$effect(() => {
void html;
void sections;
void editing;
const line = focusLine;
const headings = documentHeadings(contents);
const el = root;
let cancelled = false;
let releaseImages: (() => void) | undefined;
let currentHeadings: ReturnType<typeof readerHeadingFolding> | undefined;
if (el) void tick().then(() => {
if (cancelled) return;
releaseImages = imageControls(el);
headingControls = currentHeadings = readerHeadingFolding(el, collapsedHeadings);
if (line !== null) requestAnimationFrame(() => {
if (cancelled) return;
const index = headings.findIndex(heading => heading.line === line);
const target = line === 1 && index < 0 ? el.querySelector<HTMLElement>(".document-title") :
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return;
currentHeadings?.reveal(target);
target.scrollIntoView({ block: "center" });
el.focus({ preventScroll: true });
});
return renderDiagrams(el, () => cancelled);
});
return () => { cancelled = true; releaseImages?.(); currentHeadings?.destroy(); };
});
async function copyFence(button: HTMLButtonElement, body: string) {
try {
await navigator.clipboard.writeText(body);
} catch {
const ta = document.createElement("textarea");
ta.value = body;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
} finally {
ta.remove();
}
}
button.dataset.copied = "true";
button.setAttribute("aria-label", $t("Copied"));
button.title = $t("Copied");
window.setTimeout(() => {
if (button.isConnected) {
delete button.dataset.copied;
button.setAttribute("aria-label", $t("Copy code"));
button.title = $t("Copy code");
}
}, 1200);
}
</script>
<!-- Events are delegated from generated native links and buttons, which support keyboard activation. -->
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="reading"
tabindex="-1"
bind:this={root}
onkeydown={(event) => {
if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) {
event.preventDefault();
onEditBlock?.(Number(event.target.dataset.start), Number(event.target.dataset.end));
}
}}
onclick={(event) => {
const copy = event.target instanceof Element ? event.target.closest("button.rs-fence-copy") : null;
if (copy instanceof HTMLButtonElement) {
event.preventDefault();
const pre = copy.closest("pre.md-code") ?? copy.closest("pre");
const body = pre?.querySelector("code")?.textContent ?? "";
void copyFence(copy, body);
return;
}
const node = event.target instanceof Element ? event.target.closest("a") : null;
if (!node) {
const target = event.target instanceof Element ? event.target : null;
if (target?.closest("textarea, button, summary")) return;
const block = target?.closest<HTMLElement>(".md-edit-block");
if (block) onEditBlock?.(Number(block.dataset.start), Number(block.dataset.end));
return;
}
const href = node.getAttribute("href") ?? "";
if (node.hasAttribute("data-footnote-link")) {
event.preventDefault();
const target = root?.querySelector<HTMLElement>(`[id="${href.slice(1)}"]`);
if (target) {
// A footnote can sit in a folded section. Reveal it before navigation.
headingControls?.reveal(target);
target.scrollIntoView({ block: "center" });
target.focus({ preventScroll: true });
}
return;
}
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
onOpenLink?.("wiki", href);
return;
}
if (kind === "md") {
event.preventDefault();
onOpenLink?.("md", href);
}
}}
>
{#if menuError}<p role="alert">{menuError}</p>{/if}
{#if $fileTitleVisible}<h1 class="document-title">{markdownTitle(noteRel)}</h1>{/if}
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{#if editing && blockEditor}
{@render blockEditor()}
{#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{/if}
{:else}
{@html html}
{/if}
</div>