~james/core

core/web/src/lib/components/ui/CodeBlockToolbar.svelte -rw-r--r-- 1.9 KiB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script lang="ts">
	import ExternalLink from "$icon/external-link";
	import FoldVertical from "$icon/fold-vertical";
	import UnfoldVertical from "$icon/unfold-vertical";
	import { MediaQuery } from "svelte/reactivity";
	import Button from "#lib/components/ui/Button.svelte";
	import CopyButton from "#lib/components/ui/CopyButton.svelte";
	import { plural } from "#lib/format.ts";

	interface Props {
		block: HTMLElement;
		code: string;
		lines: number;
	}

	let { block, code, lines }: Props = $props();

	const narrow = new MediaQuery("width < 40rem");
	let expanded = $state(false);
	let raw: string | undefined;

	$effect(() => () => {
		if (raw) URL.revokeObjectURL(raw);
	});

	const toggle = () => {
		expanded = !expanded;
		block.toggleAttribute("data-expanded", expanded);
		if (!expanded && block.getBoundingClientRect().top < 0) block.scrollIntoView();
	};

	const openRaw = () => {
		raw ??= URL.createObjectURL(new Blob([code], { type: "text/plain;charset=utf-8" }));
		window.open(raw, "_blank");
	};

	const toggleLabel = $derived(expanded ? "Collapse code" : "Expand code");
</script>

{#snippet toggleText()}{toggleLabel}{/snippet}

<div class="flex flex-wrap items-center justify-between gap-xs">
	<div class="flex items-center gap-sm">
		<Button
			icon={expanded ? FoldVertical : UnfoldVertical}
			aria-label={toggleLabel}
			onclick={toggle}
			children={narrow.current ? undefined : toggleText}
			variant="ghost"
		/>
		<span class="typography-monospace-small text-foreground-muted">
			{lines}
			{plural(lines, "line", "lines")}
		</span>
	</div>
	<div class="flex flex-row items-center gap-xs *:hit-area-x-1.5 *:overflow-visible">
		<CopyButton
			value={code}
			variant="ghost"
			label="Copy to clipboard"
			showLabel={false}
			size="regular"
		/>
		<Button
			icon={ExternalLink}
			iconSide="right"
			aria-label="Open raw in new tab"
			onclick={openRaw}
			variant="ghost"
		/>
	</div>
</div>