File size: 4,110 Bytes
b7b13c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
<script lang="ts">
	import { browser } from '$app/environment';
	import { SYNTAX_CODE_SCROLL_AT_BOTTOM_THRESHOLD_PX, UI_DATA_ATTRS } from '$lib/constants';
	import { BooleanString, ColorMode } from '$lib/enums';
	import { highlightCode } from '$lib/utils';
	import githubLightCss from 'highlight.js/styles/github.css?inline';
	import githubDarkCss from 'highlight.js/styles/github-dark.css?inline';
	import { mode } from 'mode-watcher';

	interface Props {
		code: string;
		language?: string;
		class?: string;
		maxHeight?: string;
		maxWidth?: string;
		/** Auto-scrolls to the bottom of new chunks; pauses on user scroll-up
		 *  until the user returns to the bottom. */
		streaming?: boolean;
	}

	let {
		class: className = '',
		code,
		language = 'text',
		maxHeight = '60vh',
		maxWidth = '',
		streaming = false
	}: Props = $props();

	const highlightedHtml = $derived(highlightCode(code, language));

	let scrollEl = $state<HTMLDivElement>();
	let userScrolledUp = $state(false);
	let lastScrollTop = 0;
	const SCROLL_BOTTOM_THRESHOLD_PX = SYNTAX_CODE_SCROLL_AT_BOTTOM_THRESHOLD_PX;
	let pendingFrame: number | null = null;

	function loadHighlightTheme(isDark: boolean) {
		if (!browser) return;

		const existingThemes = document.querySelectorAll(
			`style[${UI_DATA_ATTRS.HIGHLIGHT_THEME_PREVIEW}]`
		);

		existingThemes.forEach((style) => style.remove());

		const style = document.createElement('style');

		style.setAttribute(UI_DATA_ATTRS.HIGHLIGHT_THEME_PREVIEW, BooleanString.TRUE);
		style.textContent = isDark ? githubDarkCss : githubLightCss;

		document.head.appendChild(style);
	}

	function isAtBottom(): boolean {
		if (!scrollEl) return false;

		return (
			scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop <=
			SCROLL_BOTTOM_THRESHOLD_PX
		);
	}

	function scrollToBottomOnFrame() {
		if (pendingFrame !== null || !scrollEl || userScrolledUp) return;

		pendingFrame = requestAnimationFrame(() => {
			pendingFrame = null;

			// User may scroll between scheduling and paint.
			if (scrollEl && !userScrolledUp) {
				scrollEl.scrollTop = scrollEl.scrollHeight;
			}
		});
	}

	function handleScrollEvent() {
		if (!scrollEl) return;

		const isScrollingUp = scrollEl.scrollTop < lastScrollTop;

		if (isScrollingUp && !isAtBottom()) {
			userScrolledUp = true;
		} else if (isAtBottom()) {
			userScrolledUp = false;
		}

		lastScrollTop = scrollEl.scrollTop;
	}

	$effect(() => {
		const currentMode = mode.current;
		const isDark = currentMode === ColorMode.DARK;

		loadHighlightTheme(isDark);
	});

	// Pin to bottom at the start of each streaming episode.
	$effect(() => {
		if (streaming) {
			userScrolledUp = false;
			lastScrollTop = 0;
		}
	});

	$effect(() => {
		void code;

		if (!streaming || userScrolledUp) return;

		scrollToBottomOnFrame();
	});

	// Layout shifts that don't change `code` (highlight.js re-tokenize, line-wrap reflow).
	$effect(() => {
		if (!streaming || !scrollEl) return;

		const observer = new MutationObserver(() => scrollToBottomOnFrame());

		observer.observe(scrollEl, {
			characterData: true,
			childList: true,
			subtree: true
		});

		return () => observer.disconnect();
	});
</script>

<div
	bind:this={scrollEl}
	class="code-preview-wrapper min-w-0 max-w-full overflow-auto rounded-xl border shadow-[0_1px_2px_0_rgb(0_0_0_/_0.05)] {className}"
	onscroll={handleScrollEvent}
	style="border-color: color-mix(in oklch, var(--border) 30%, transparent); background: var(--code-background); max-height: {maxHeight}; {maxWidth
		? `max-width: ${maxWidth};`
		: ''}"
>
	<!-- Single line: hljs injection depends on a contiguous source string. -->
	<pre class="m-0"><code class="hljs text-sm leading-relaxed">{@html highlightedHtml}</code></pre>
</div>

<style>
	.code-preview-wrapper {
		overscroll-behavior: contain;
	}

	.code-preview-wrapper pre {
		background: transparent;
		padding: 0;
	}

	.code-preview-wrapper code {
		background: transparent;
		display: block;
		padding: 0.5rem;
	}

	:global(.dark) .code-preview-wrapper {
		border-color: color-mix(in oklch, var(--border) 20%, transparent);
	}
</style>