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 };
};