aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/frontend/html/pages/docs.js
blob: 8caf36d0c9c9e2befde1e863646c295eb3e2b328 (plain) (blame)
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright Epic Games, Inc. All Rights Reserved.

"use strict";

import { ZenPage } from "./page.js"
import { marked, Renderer } from "../thirdparty/marked.esm.js"
import { Fetcher } from "../util/fetcher.js"

function slugify(text)
{
	return text.toLowerCase().replace(/[^\w]+/g, "-").replace(/^-|-$/g, "");
}

const renderer = new Renderer();
renderer.heading = function({ text, depth })
{
	const id = slugify(text);
	if (depth === 1)
	{
		return `<h1 id="${id}">${text}<a class="docs-source-link" title="View source"></a><a class="docs-github-link" title="View on GitHub" target="_blank"></a></h1>`;
	}
	if (depth === 2)
	{
		// Close previous <details> section (if any) and open a new one
		return `</details><details class="docs-section" open><summary class="docs-section-title" id="${id}">${text}</summary>`;
	}
	return `<h${depth} id="${id}">${text}</h${depth}>`;
};

////////////////////////////////////////////////////////////////////////////////
export class Page extends ZenPage
{
	generate_crumbs() {}

	async main()
	{
		this.set_title("docs");
		this._parent.inner().classList.add("docs-page");

		const index = await new Fetcher().resource("/dashboard/data/_index.json").json();
		if (!index || index.length === 0)
		{
			this._parent.tag().text("No documentation available.");
			return;
		}

		// Filter input
		const filter_box = document.createElement("input");
		filter_box.type = "text";
		filter_box.className = "docs-filter";
		filter_box.placeholder = "Filter\u2026";
		filter_box.addEventListener("input", () => this._apply_filter(filter_box.value));
		this._parent.inner().appendChild(filter_box);

		// Layout: sidebar + content
		const layout = document.createElement("div");
		layout.className = "docs-layout";
		this._parent.inner().appendChild(layout);

		// Sidebar
		const sidebar = document.createElement("nav");
		sidebar.className = "docs-sidebar";
		layout.appendChild(sidebar);

		this._docs_index = index;
		this._sidebar = sidebar;
		this._selected_link = null;
		this._filter = "";
		this._docs_cache = {};

		for (const entry of index)
		{
			const link = document.createElement("a");
			link.className = "docs-sidebar-link";
			link.textContent = entry.title;
			link.href = "#";
			link.addEventListener("click", (e) => {
				e.preventDefault();
				this._select_doc(entry, link);
			});
			sidebar.appendChild(link);
		}

		// Prefetch all docs in the background for filtering
		Promise.all(index.map(entry =>
			new Fetcher().resource("/dashboard/data/" + entry.path).text()
				.then(md => { this._docs_cache[entry.path] = md.toLowerCase(); })
				.catch(() => {})
		));

		// Content area
		const content = document.createElement("article");
		content.className = "docs-content";
		layout.appendChild(content);
		this._content = content;

		// Intercept clicks on links within rendered doc content
		content.addEventListener("click", (e) => {
			const anchor = e.target.closest("a");
			if (!anchor || anchor.classList.contains("docs-source-link") || anchor.classList.contains("docs-github-link"))
			{
				return;
			}

			const href = anchor.getAttribute("href") || "";

			// Fragment-only link (e.g. #workers) — scroll within current doc
			if (href.startsWith("#"))
			{
				e.preventDefault();
				this._scroll_to_fragment(href.slice(1));
				return;
			}

			// Relative link to another doc (e.g. API.md or specs/CompactBinary.md)
			if (!href.startsWith("http") && href.endsWith(".md"))
			{
				const parts = href.split("#");
				const target_path = parts[0];
				const target_fragment = parts[1] || null;
				const target_entry = this._docs_index.find(d => d.path.toLowerCase() === target_path.toLowerCase());
				if (target_entry)
				{
					e.preventDefault();
					const target_link = this._sidebar.children[this._docs_index.indexOf(target_entry)];
					this._select_doc(target_entry, target_link, target_fragment);
				}
			}
		});

		// Select initial doc from URL param or first entry
		const requested = this.get_param("doc", "");
		const initial = index.find(e => e.path === requested) || index[0];
		const initial_link = sidebar.children[index.indexOf(initial)];
		this._select_doc(initial, initial_link);
	}

	async _select_doc(entry, link, fragment)
	{
		if (this._selected_link)
		{
			this._selected_link.classList.remove("active");
		}
		this._selected_link = link;
		link.classList.add("active");

		this.set_param("doc", entry.path);

		this._content.innerHTML = "<p class=\"docs-loading\">Loading\u2026</p>";

		try
		{
			const md = await new Fetcher().resource("/dashboard/data/" + entry.path).text();
			this._content.innerHTML = marked.parse(md, { renderer });

			const source_link = this._content.querySelector(".docs-source-link");
			if (source_link)
			{
				source_link.href = "/dashboard/data/" + entry.path;
			}

			const github_link = this._content.querySelector(".docs-github-link");
			if (github_link)
			{
				github_link.href = "https://github.com/EpicGames/zen/blob/main/docs/" + entry.path;
			}

			// Render mermaid diagrams
			await this._render_mermaid();

			// Re-apply filter to the newly rendered content
			if (this._filter)
			{
				this._apply_filter_to_content();
			}

			// Scroll to fragment if specified
			const target_fragment = fragment || window.location.hash.slice(1);
			if (target_fragment)
			{
				this._scroll_to_fragment(target_fragment);
			}
			else
			{
				window.scrollTo(0, 0);
			}
		}
		catch (e)
		{
			this._content.innerHTML = "<p class=\"docs-error\">Failed to load document.</p>";
		}
	}

	_scroll_to_fragment(id)
	{
		if (!id)
		{
			return;
		}
		const target = this._content.querySelector("#" + CSS.escape(id));
		if (target)
		{
			target.scrollIntoView({ behavior: "smooth" });
		}
	}

	_apply_filter(query)
	{
		this._filter = query.toLowerCase().trim();

		// Filter sidebar entries based on cached doc content
		const sidebar_links = this._sidebar.children;
		for (let i = 0; i < this._docs_index.length; i++)
		{
			const entry = this._docs_index[i];
			const link = sidebar_links[i];
			if (!this._filter)
			{
				link.style.display = "";
				continue;
			}

			const cached = this._docs_cache[entry.path];
			const matches = !cached || cached.includes(this._filter) || entry.title.toLowerCase().includes(this._filter);
			link.style.display = matches ? "" : "none";
		}

		this._apply_filter_to_content();
	}

	_apply_filter_to_content()
	{
		// Remove existing highlights
		for (const mark of this._content.querySelectorAll("mark.docs-highlight"))
		{
			const parent = mark.parentNode;
			parent.replaceChild(document.createTextNode(mark.textContent), mark);
			parent.normalize();
		}

		const sections = this._content.querySelectorAll("details.docs-section");

		for (const section of sections)
		{
			if (!this._filter)
			{
				section.style.display = "";
				section.open = true;
				continue;
			}

			const matches = section.textContent.toLowerCase().includes(this._filter);
			section.style.display = matches ? "" : "none";

			if (matches)
			{
				section.open = true;
				this._highlight_element(section);
			}
		}
	}

	_get_mermaid_theme()
	{
		const attr = document.documentElement.getAttribute("data-theme");
		const is_dark = attr
			? attr === "dark"
			: window.matchMedia("(prefers-color-scheme: dark)").matches;
		return is_dark ? "dark" : "default";
	}

	async _load_mermaid()
	{
		if (window.mermaid)
		{
			return window.mermaid;
		}

		return new Promise((resolve, reject) => {
			const script = document.createElement("script");
			script.src = "/dashboard/thirdparty/mermaid.min.js";
			script.onload = () => {
				window.mermaid.initialize({
					startOnLoad: false,
					theme: this._get_mermaid_theme(),
					themeVariables: {
						background: "transparent",
					},
				});
				resolve(window.mermaid);
			};
			script.onerror = reject;
			document.head.appendChild(script);
		});
	}

	async _render_mermaid()
	{
		// marked renders ```mermaid blocks as <code class="language-mermaid"> inside <pre>
		const code_blocks = this._content.querySelectorAll("pre > code.language-mermaid");
		if (code_blocks.length === 0)
		{
			return;
		}

		try
		{
			const mermaid = await this._load_mermaid();

			for (let i = 0; i < code_blocks.length; i++)
			{
				const code = code_blocks[i];
				const pre = code.parentElement;
				const definition = code.textContent;

				const { svg } = await mermaid.render(`mermaid-${Date.now()}-${i}`, definition);

				const container = document.createElement("div");
				container.className = "docs-mermaid";
				container.dataset.definition = definition;
				container.innerHTML = svg;
				pre.replaceWith(container);
			}

			this._watch_theme();
		}
		catch (e)
		{
			// Mermaid failed to load or render — leave code blocks as-is
		}
	}

	_watch_theme()
	{
		if (this._theme_observer)
		{
			return;
		}

		this._theme_observer = new MutationObserver(() => this._rerender_mermaid());
		this._theme_observer.observe(document.documentElement, {
			attributes: true,
			attributeFilter: ["data-theme"],
		});
	}

	async _rerender_mermaid()
	{
		const containers = this._content.querySelectorAll(".docs-mermaid[data-definition]");
		if (containers.length === 0)
		{
			return;
		}

		try
		{
			const mermaid = await this._load_mermaid();
			mermaid.initialize({
				startOnLoad: false,
				theme: this._get_mermaid_theme(),
				themeVariables: {
					background: "transparent",
				},
			});

			for (let i = 0; i < containers.length; i++)
			{
				const container = containers[i];
				const definition = container.dataset.definition;
				const { svg } = await mermaid.render(`mermaid-${Date.now()}-${i}`, definition);
				container.innerHTML = svg;
			}
		}
		catch (e)
		{
			// Mermaid failed to re-render — leave existing SVGs as-is
		}
	}

	_highlight_element(root)
	{
		const filter = this._filter;
		const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
		const matches = [];

		let node;
		while ((node = walker.nextNode()))
		{
			if (node.parentElement && node.parentElement.closest("pre"))
			{
				continue;
			}

			const text = node.textContent.toLowerCase();
			let pos = 0;
			while ((pos = text.indexOf(filter, pos)) !== -1)
			{
				matches.push({ node, pos, len: filter.length });
				pos += filter.length;
			}
		}

		for (let i = matches.length - 1; i >= 0; i--)
		{
			const { node: text_node, pos, len } = matches[i];
			const after = text_node.splitText(pos);
			after.splitText(len);

			const mark = document.createElement("mark");
			mark.className = "docs-highlight";
			mark.textContent = after.textContent;
			after.parentNode.replaceChild(mark, after);
		}
	}
}