Files
beaver-gateway/ui/src/lib/panel/markdown.svelte
T

113 lines
2.9 KiB
Svelte

<script lang="ts">
import { cn } from "$lib/utils";
import { usePanelHost } from "./host";
import { linkOf, renderMarkdown } from "./markdown";
let {
text,
class: className = "",
eager = true,
inert = false,
}: {
text: string;
class?: string;
eager?: boolean;
inert?: boolean;
} = $props();
const NEAR = "1200px";
const host = usePanelHost();
const html = $derived(host.markdown ? "" : renderMarkdown(text));
// Links inside rendered markdown are the only interactive things here:
// real anchors, reached by pointer or by Enter on the focused link. The
// handlers ride on the container so re-rendered HTML keeps them.
function follow(event: MouseEvent | KeyboardEvent) {
if (event instanceof KeyboardEvent && event.key !== "Enter") {
return;
}
const link = linkOf(event);
if (!link) {
return;
}
event.preventDefault();
event.stopPropagation();
host.openLink(link.target, link.kind);
}
function links(node: HTMLElement) {
node.addEventListener("click", follow);
node.addEventListener("keydown", follow);
return {
destroy() {
node.removeEventListener("click", follow);
node.removeEventListener("keydown", follow);
},
};
}
// The host renders when asked; far up the thread that is when the
// node comes near the viewport, with the plain text holding its place.
function render(node: HTMLElement, value: string) {
let dispose: (() => void) | undefined;
let watcher: IntersectionObserver | null = null;
let pending = value;
const now = (next: string) => {
dispose?.();
node.classList.remove("whitespace-pre-wrap");
dispose = host.markdown?.(node, next, { inert });
};
const later = (next: string) => {
pending = next;
node.textContent = next;
node.classList.add("whitespace-pre-wrap");
if (watcher) {
return;
}
watcher = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
watcher?.disconnect();
watcher = null;
now(pending);
}
},
{ rootMargin: NEAR }
);
watcher.observe(node);
};
if (eager || typeof IntersectionObserver === "undefined") {
now(value);
} else {
later(value);
}
return {
destroy() {
watcher?.disconnect();
dispose?.();
},
update(next: string) {
if (watcher) {
later(next);
} else {
now(next);
}
},
};
}
</script>
{#if host.markdown}
<div
class={cn("beaver-md markdown-rendered", className)}
use:links
use:render={text}
></div>
{:else}
<div class={cn("prose prose-sm max-w-none", className)} use:links>
<!-- eslint-disable-next-line svelte/no-at-html-tags -- sanitized in renderMarkdown -->
{@html html}
</div>
{/if}