~james/core

core/web/src/lib/components/ui/codeblockToolbars.ts -rw-r--r-- 996 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { mount, unmount } from "svelte";
import type { Action } from "svelte/action";
import CodeBlockToolbar from "#lib/components/ui/CodeBlockToolbar.svelte";

export const codeblockToolbars: Action<HTMLElement, unknown> = (node) => {
	let toolbars: ReturnType<typeof mount>[] = [];

	const clear = () => {
		for (const toolbar of toolbars) void unmount(toolbar);
		toolbars = [];
	};

	const run = () => {
		clear();
		for (const block of node.querySelectorAll<HTMLElement>("[data-codeblock]")) {
			const target = block.querySelector<HTMLElement>(":scope > [data-codeblock-toolbar]");
			const pre = block.querySelector(":scope > pre");
			if (!target || !pre) continue;
			block.removeAttribute("data-expanded");
			target.replaceChildren();
			toolbars.push(
				mount(CodeBlockToolbar, {
					target,
					props: {
						block,
						code: pre.textContent ?? "",
						lines: Number(block.dataset.codeblock)
					}
				})
			);
		}
	};

	run();
	return { update: run, destroy: clear };
};