@tokenroll/llmdoc 3.5.1 → 3.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/viewer-app.js +243 -0
- package/assets/viewer-detail.js +223 -0
- package/assets/viewer-graph.js +471 -0
- package/assets/viewer-model.js +127 -0
- package/assets/viewer.css +343 -0
- package/assets/viewer.html +51 -547
- package/dist/commands/context.js +14 -1
- package/dist/commands/serve.js +0 -0
- package/dist/commands/status.js +3 -19
- package/dist/lib/repository-health.js +26 -0
- package/dist/lib/viewer-http.js +107 -0
- package/dist/lib/viewer-state.js +131 -0
- package/dist/lib/workspace.js +39 -0
- package/package.json +1 -1
- package/schemas/output.schema.json +8 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { createDetailRenderer } from "./viewer-detail.js";
|
|
2
|
+
import { createGraphController } from "./viewer-graph.js";
|
|
3
|
+
import { colorOf, createTopicColors, documentName, matchesSearch, STATUS_COLOR } from "./viewer-model.js";
|
|
4
|
+
|
|
5
|
+
const elements = {
|
|
6
|
+
repo: document.getElementById("repo"),
|
|
7
|
+
statDocs: document.getElementById("stat-docs"),
|
|
8
|
+
statBaseline: document.getElementById("stat-baseline"),
|
|
9
|
+
statValidate: document.getElementById("stat-validate"),
|
|
10
|
+
statDelta: document.getElementById("stat-delta"),
|
|
11
|
+
refresh: document.getElementById("refresh"),
|
|
12
|
+
modeTopics: document.getElementById("mode-topics"),
|
|
13
|
+
modeDocs: document.getElementById("mode-docs"),
|
|
14
|
+
search: document.getElementById("search"),
|
|
15
|
+
documentList: document.getElementById("doc-list"),
|
|
16
|
+
graphWrap: document.getElementById("graph-wrap"),
|
|
17
|
+
graph: document.getElementById("graph"),
|
|
18
|
+
graphHint: document.getElementById("graph-hint"),
|
|
19
|
+
legend: document.getElementById("legend"),
|
|
20
|
+
graphEmpty: document.getElementById("graph-empty"),
|
|
21
|
+
detail: document.getElementById("detail"),
|
|
22
|
+
detailContainer: document.querySelector("#detail .inner"),
|
|
23
|
+
detailClose: document.getElementById("detail-close"),
|
|
24
|
+
error: document.getElementById("load-error"),
|
|
25
|
+
zoomIn: document.getElementById("zoom-in"),
|
|
26
|
+
zoomOut: document.getElementById("zoom-out"),
|
|
27
|
+
zoomReset: document.getElementById("zoom-reset")
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
let state = null;
|
|
31
|
+
let selectedDocument = null;
|
|
32
|
+
let selectedTopic = null;
|
|
33
|
+
let mode = "topics";
|
|
34
|
+
let topicColors = new Map();
|
|
35
|
+
let resizeTimer = null;
|
|
36
|
+
|
|
37
|
+
const graph = createGraphController({
|
|
38
|
+
svg: elements.graph,
|
|
39
|
+
hint: elements.graphHint,
|
|
40
|
+
legend: elements.legend,
|
|
41
|
+
empty: elements.graphEmpty,
|
|
42
|
+
onSelectTopic: selectTopic,
|
|
43
|
+
onSelectDocument: selectDocument
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const detail = createDetailRenderer({
|
|
47
|
+
panel: elements.detail,
|
|
48
|
+
container: elements.detailContainer,
|
|
49
|
+
onSelectDocument: selectDocument,
|
|
50
|
+
getState: () => state
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
async function loadState() {
|
|
54
|
+
elements.refresh.disabled = true;
|
|
55
|
+
elements.refresh.setAttribute("aria-busy", "true");
|
|
56
|
+
hideError();
|
|
57
|
+
try {
|
|
58
|
+
const response = await fetch("/api/state", { headers: { accept: "application/json" } });
|
|
59
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
60
|
+
const nextState = await response.json();
|
|
61
|
+
if (!Array.isArray(nextState.nodes) || !Array.isArray(nextState.edges)) throw new Error("服务返回了无效状态");
|
|
62
|
+
state = nextState;
|
|
63
|
+
topicColors = createTopicColors(state.nodes);
|
|
64
|
+
if (selectedDocument && !state.nodes.some((node) => node.path === selectedDocument)) selectedDocument = null;
|
|
65
|
+
if (selectedTopic && !state.nodes.some((node) => node.topic === selectedTopic)) selectedTopic = null;
|
|
66
|
+
renderHeader();
|
|
67
|
+
renderSidebar();
|
|
68
|
+
renderGraph();
|
|
69
|
+
if (selectedDocument) await detail.showDocument(selectedDocument, state);
|
|
70
|
+
else if (selectedTopic) detail.showTopic(selectedTopic, state, topicColors);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
showError(error instanceof Error ? error.message : String(error));
|
|
73
|
+
} finally {
|
|
74
|
+
elements.refresh.disabled = false;
|
|
75
|
+
elements.refresh.removeAttribute("aria-busy");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function renderHeader() {
|
|
80
|
+
elements.repo.textContent = `/ ${state.repository}`;
|
|
81
|
+
elements.statDocs.textContent = `${state.nodes.length} docs · ~${state.growth.currentTotalEstimatedTokens} tokens`;
|
|
82
|
+
|
|
83
|
+
const baseline = state.baseline;
|
|
84
|
+
const shortRevision = baseline.revision?.slice(0, 7);
|
|
85
|
+
if (!baseline.revision) {
|
|
86
|
+
setChip(elements.statBaseline, "baseline 缺失", "bad");
|
|
87
|
+
} else if (baseline.degradedReason || baseline.relevantBehindHead === null) {
|
|
88
|
+
setChip(elements.statBaseline, `baseline ${shortRevision} · 状态未知`, "warn");
|
|
89
|
+
} else if (baseline.relevantBehindHead > 0) {
|
|
90
|
+
setChip(elements.statBaseline, `baseline ${shortRevision} · ${baseline.relevantBehindHead} 个源码提交待复核`, "warn");
|
|
91
|
+
} else if (baseline.metadataOnlyBehind) {
|
|
92
|
+
setChip(elements.statBaseline, `baseline ${shortRevision} · metadata-only,知识干净`, "ok");
|
|
93
|
+
} else {
|
|
94
|
+
setChip(elements.statBaseline, `baseline ${shortRevision} · 最新`, "ok");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const validation = state.validate;
|
|
98
|
+
setChip(
|
|
99
|
+
elements.statValidate,
|
|
100
|
+
validation.ok ? `validate ok${validation.warnings ? ` · ${validation.warnings} warn` : ""}` : `validate ${validation.errors} errors`,
|
|
101
|
+
validation.ok ? "ok" : "bad"
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const stale = state.nodes.filter((node) => node.status !== "fresh").length;
|
|
105
|
+
const unmapped = state.delta.unmappedCommittedPaths.length + state.delta.unmappedDirtyPaths.length;
|
|
106
|
+
if (stale) setChip(elements.statDelta, `${stale} 份待同步 · 建议 ${state.delta.suggestedMode}`, "warn");
|
|
107
|
+
else if (unmapped) setChip(elements.statDelta, `${unmapped} 个未映射变化 · 建议 ${state.delta.suggestedMode}`, "warn");
|
|
108
|
+
else setChip(elements.statDelta, "知识面新鲜", "ok");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function setChip(chip, text, stateClass) {
|
|
112
|
+
chip.textContent = text;
|
|
113
|
+
chip.className = `chip ${stateClass}`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function renderSidebar() {
|
|
117
|
+
if (!state) return;
|
|
118
|
+
const query = elements.search.value;
|
|
119
|
+
const matchingNodes = state.nodes.filter((node) => matchesSearch(node, query));
|
|
120
|
+
const groups = new Map([["", matchingNodes.filter((node) => !node.topic)]]);
|
|
121
|
+
for (const node of matchingNodes) {
|
|
122
|
+
if (!node.topic) continue;
|
|
123
|
+
const documents = groups.get(node.topic) ?? [];
|
|
124
|
+
documents.push(node);
|
|
125
|
+
groups.set(node.topic, documents);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const fragment = document.createDocumentFragment();
|
|
129
|
+
for (const [topic, nodes] of groups) {
|
|
130
|
+
if (!nodes.length) continue;
|
|
131
|
+
const label = document.createElement(topic ? "button" : "div");
|
|
132
|
+
label.className = "group-label";
|
|
133
|
+
if (topic) {
|
|
134
|
+
label.type = "button";
|
|
135
|
+
const swatch = element("span", "swatch");
|
|
136
|
+
swatch.style.backgroundColor = colorOf(topicColors, topic);
|
|
137
|
+
label.append(swatch, `${topic}/`);
|
|
138
|
+
label.addEventListener("click", () => selectTopic(topic));
|
|
139
|
+
} else {
|
|
140
|
+
label.textContent = "root";
|
|
141
|
+
}
|
|
142
|
+
fragment.append(label);
|
|
143
|
+
|
|
144
|
+
for (const node of nodes) {
|
|
145
|
+
const item = element("button", `doc-item${selectedDocument === node.path ? " active" : ""}`);
|
|
146
|
+
item.type = "button";
|
|
147
|
+
item.title = node.path;
|
|
148
|
+
item.setAttribute("aria-current", selectedDocument === node.path ? "true" : "false");
|
|
149
|
+
const dot = element("span", "dot");
|
|
150
|
+
dot.style.backgroundColor = STATUS_COLOR[node.status];
|
|
151
|
+
dot.style.color = STATUS_COLOR[node.status];
|
|
152
|
+
item.append(dot, element("span", "name", documentName(node.path)), element("span", "kind", node.kind));
|
|
153
|
+
item.addEventListener("click", () => selectDocument(node.path));
|
|
154
|
+
fragment.append(item);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (!fragment.childNodes.length) fragment.append(element("div", "empty-list", "没有匹配的文档"));
|
|
158
|
+
elements.documentList.replaceChildren(fragment);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function renderGraph() {
|
|
162
|
+
if (!state) return;
|
|
163
|
+
graph.render(graphInput());
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function graphInput() {
|
|
167
|
+
return { state, mode, selected: selectedDocument, topicColors };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function setMode(nextMode, { render = true } = {}) {
|
|
171
|
+
mode = nextMode;
|
|
172
|
+
elements.modeTopics.className = mode === "topics" ? "on" : "";
|
|
173
|
+
elements.modeDocs.className = mode === "docs" ? "on" : "";
|
|
174
|
+
elements.modeTopics.setAttribute("aria-pressed", String(mode === "topics"));
|
|
175
|
+
elements.modeDocs.setAttribute("aria-pressed", String(mode === "docs"));
|
|
176
|
+
if (render && state) renderGraph();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function selectTopic(topic) {
|
|
180
|
+
selectedTopic = topic;
|
|
181
|
+
selectedDocument = null;
|
|
182
|
+
renderSidebar();
|
|
183
|
+
if (mode !== "topics") setMode("topics");
|
|
184
|
+
graph.highlight(`topic:${topic}`);
|
|
185
|
+
detail.showTopic(topic, state, topicColors);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function selectDocument(path) {
|
|
189
|
+
selectedDocument = path;
|
|
190
|
+
selectedTopic = null;
|
|
191
|
+
renderSidebar();
|
|
192
|
+
if (mode !== "docs") setMode("docs");
|
|
193
|
+
else graph.highlight(path);
|
|
194
|
+
await detail.showDocument(path, state);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function showError(message) {
|
|
198
|
+
elements.error.textContent = `Viewer 加载失败:${message}`;
|
|
199
|
+
elements.error.hidden = false;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function hideError() {
|
|
203
|
+
elements.error.hidden = true;
|
|
204
|
+
elements.error.textContent = "";
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function element(tagName, className, text) {
|
|
208
|
+
const node = document.createElement(tagName);
|
|
209
|
+
if (className) node.className = className;
|
|
210
|
+
if (text !== undefined) node.textContent = text;
|
|
211
|
+
return node;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
elements.search.addEventListener("input", renderSidebar);
|
|
215
|
+
elements.refresh.addEventListener("click", loadState);
|
|
216
|
+
elements.modeTopics.addEventListener("click", () => setMode("topics"));
|
|
217
|
+
elements.modeDocs.addEventListener("click", () => setMode("docs"));
|
|
218
|
+
elements.zoomIn.addEventListener("click", () => graph.zoomBy(1.15));
|
|
219
|
+
elements.zoomOut.addEventListener("click", () => graph.zoomBy(.87));
|
|
220
|
+
elements.zoomReset.addEventListener("click", graph.resetView);
|
|
221
|
+
elements.detailClose.addEventListener("click", detail.closePanel);
|
|
222
|
+
|
|
223
|
+
window.addEventListener("keydown", (event) => {
|
|
224
|
+
const target = event.target;
|
|
225
|
+
const isEditing = target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target.isContentEditable;
|
|
226
|
+
if (event.key === "/" && !isEditing) {
|
|
227
|
+
event.preventDefault();
|
|
228
|
+
elements.search.focus();
|
|
229
|
+
} else if (event.key === "Escape") {
|
|
230
|
+
detail.closePanel();
|
|
231
|
+
if (document.activeElement === elements.search) elements.search.blur();
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
const resizeObserver = new ResizeObserver(() => {
|
|
236
|
+
if (!state) return;
|
|
237
|
+
window.clearTimeout(resizeTimer);
|
|
238
|
+
resizeTimer = window.setTimeout(() => graph.resize(graphInput()), 120);
|
|
239
|
+
});
|
|
240
|
+
resizeObserver.observe(elements.graphWrap);
|
|
241
|
+
|
|
242
|
+
setMode("topics", { render: false });
|
|
243
|
+
loadState();
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { colorOf, documentName, resolveRelativeDocumentPath, STATUS_COLOR, worstStatus } from "./viewer-model.js";
|
|
2
|
+
|
|
3
|
+
const ALLOWED_TAGS = new Set([
|
|
4
|
+
"A", "BLOCKQUOTE", "BR", "CODE", "DEL", "EM", "H1", "H2", "H3", "H4", "H5", "H6",
|
|
5
|
+
"HR", "IMG", "LI", "OL", "P", "PRE", "STRONG", "TABLE", "TBODY", "TD", "TH", "THEAD", "TR", "UL"
|
|
6
|
+
]);
|
|
7
|
+
const DROP_TAGS = new Set(["EMBED", "FORM", "IFRAME", "INPUT", "LINK", "META", "OBJECT", "SCRIPT", "STYLE"]);
|
|
8
|
+
|
|
9
|
+
export function createDetailRenderer({ panel, container, onSelectDocument, getState }) {
|
|
10
|
+
let activeRequest = null;
|
|
11
|
+
|
|
12
|
+
function showPlaceholder(message = "选择一个 topic 或文档查看详情") {
|
|
13
|
+
activeRequest?.abort();
|
|
14
|
+
const placeholder = element("div", "placeholder", message);
|
|
15
|
+
container.replaceChildren(placeholder);
|
|
16
|
+
panel.classList.remove("open");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function showTopic(topic, state, topicColors) {
|
|
20
|
+
activeRequest?.abort();
|
|
21
|
+
const documents = state.nodes.filter((node) => node.topic === topic);
|
|
22
|
+
const title = element("h2");
|
|
23
|
+
const swatch = element("span", "swatch");
|
|
24
|
+
swatch.style.backgroundColor = colorOf(topicColors, topic);
|
|
25
|
+
swatch.style.width = "12px";
|
|
26
|
+
swatch.style.height = "12px";
|
|
27
|
+
swatch.style.marginRight = "7px";
|
|
28
|
+
title.append(swatch, `${topic}/`);
|
|
29
|
+
|
|
30
|
+
const tokenCount = documents.reduce((sum, node) => sum + node.estimatedTokens, 0);
|
|
31
|
+
const description = element(
|
|
32
|
+
"div",
|
|
33
|
+
"desc",
|
|
34
|
+
`${documents.length} docs · ~${tokenCount} tokens · 状态最差 ${worstStatus(documents)}`
|
|
35
|
+
);
|
|
36
|
+
const cards = documents.map((node) => {
|
|
37
|
+
const card = element("button", "topic-doc-card");
|
|
38
|
+
card.type = "button";
|
|
39
|
+
card.addEventListener("click", () => onSelectDocument(node.path));
|
|
40
|
+
const cardTitle = element("span", "title");
|
|
41
|
+
const dot = element("span", "dot");
|
|
42
|
+
dot.style.backgroundColor = STATUS_COLOR[node.status];
|
|
43
|
+
cardTitle.append(dot, documentName(node.path), element("span", "kind", node.kind));
|
|
44
|
+
card.append(cardTitle, element("span", "description", node.description));
|
|
45
|
+
return card;
|
|
46
|
+
});
|
|
47
|
+
container.replaceChildren(title, description, ...cards);
|
|
48
|
+
openPanel();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function showDocument(path, state) {
|
|
52
|
+
activeRequest?.abort();
|
|
53
|
+
activeRequest = new AbortController();
|
|
54
|
+
const request = activeRequest;
|
|
55
|
+
container.replaceChildren(element("div", "placeholder", "正在加载文档…"));
|
|
56
|
+
openPanel();
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const response = await fetch(`/api/doc?path=${encodeURIComponent(path)}`, { signal: request.signal });
|
|
60
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
61
|
+
const documentData = await response.json();
|
|
62
|
+
if (request !== activeRequest) return;
|
|
63
|
+
renderDocument(path, documentData, state);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (error instanceof DOMException && error.name === "AbortError") return;
|
|
66
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
67
|
+
container.replaceChildren(element("div", "placeholder", `加载失败:${message}`));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function renderDocument(path, documentData, state) {
|
|
72
|
+
const node = state.nodes.find((item) => item.path === path);
|
|
73
|
+
const frontmatter = documentData.frontmatter ?? {};
|
|
74
|
+
const title = element("h2", null, path);
|
|
75
|
+
const description = element("div", "desc", frontmatter.description ?? "");
|
|
76
|
+
const meta = element("div", "meta-row");
|
|
77
|
+
meta.append(
|
|
78
|
+
element("span", "chip", frontmatter.kind ?? "?"),
|
|
79
|
+
statusChip(node?.status ?? "fresh"),
|
|
80
|
+
element("span", "chip", `~${documentData.estimatedTokens} tokens · ${documentData.lineCount} lines`)
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
const content = [title, description, meta];
|
|
84
|
+
const relations = frontmatter.relations ?? {};
|
|
85
|
+
const requires = relationBlock("requires", relations.requires);
|
|
86
|
+
const related = relationBlock("related", relations.related);
|
|
87
|
+
if (requires) content.push(requires);
|
|
88
|
+
if (related) content.push(related);
|
|
89
|
+
|
|
90
|
+
const codePaths = frontmatter.code?.paths ?? [];
|
|
91
|
+
if (codePaths.length) {
|
|
92
|
+
const paths = element("div", "meta-row");
|
|
93
|
+
paths.append(...codePaths.map((codePath) => element("span", "code-path", codePath)));
|
|
94
|
+
content.push(paths);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const body = element("div");
|
|
98
|
+
body.id = "doc-body";
|
|
99
|
+
renderMarkdown(body, documentData.body ?? "", path, getState(), onSelectDocument);
|
|
100
|
+
content.push(body);
|
|
101
|
+
container.replaceChildren(...content);
|
|
102
|
+
panel.scrollTop = 0;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function relationBlock(label, targets) {
|
|
106
|
+
if (!targets?.length) return null;
|
|
107
|
+
const block = element("div", "rel-block");
|
|
108
|
+
const heading = element("b", null, `${label}: `);
|
|
109
|
+
block.append(heading);
|
|
110
|
+
targets.forEach((target, index) => {
|
|
111
|
+
if (index > 0) block.append(" · ");
|
|
112
|
+
const link = element("button", "rel-link", target);
|
|
113
|
+
link.type = "button";
|
|
114
|
+
link.addEventListener("click", () => onSelectDocument(target));
|
|
115
|
+
block.append(link);
|
|
116
|
+
});
|
|
117
|
+
return block;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function openPanel() {
|
|
121
|
+
panel.classList.add("open");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function closePanel() {
|
|
125
|
+
panel.classList.remove("open");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { showPlaceholder, showTopic, showDocument, closePanel };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function statusChip(status) {
|
|
132
|
+
const chip = element("span", "chip", status);
|
|
133
|
+
chip.style.color = STATUS_COLOR[status] ?? STATUS_COLOR.fresh;
|
|
134
|
+
return chip;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function renderMarkdown(target, source, documentPath, state, onSelectDocument) {
|
|
138
|
+
const normalized = replaceCodeReferences(String(source));
|
|
139
|
+
let rendered;
|
|
140
|
+
try {
|
|
141
|
+
rendered = window.marked.parse(normalized);
|
|
142
|
+
} catch {
|
|
143
|
+
const fallback = element("pre", null, source);
|
|
144
|
+
target.replaceChildren(fallback);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const template = document.createElement("template");
|
|
149
|
+
template.innerHTML = rendered;
|
|
150
|
+
sanitizeFragment(template.content);
|
|
151
|
+
for (const code of template.content.querySelectorAll("code")) {
|
|
152
|
+
if (code.textContent.startsWith("⌁ ")) code.classList.add("coderef");
|
|
153
|
+
}
|
|
154
|
+
for (const link of template.content.querySelectorAll("a[href]")) {
|
|
155
|
+
const href = link.getAttribute("href") ?? "";
|
|
156
|
+
if (/^(https?:|mailto:)/i.test(href)) {
|
|
157
|
+
link.target = "_blank";
|
|
158
|
+
link.rel = "noopener noreferrer";
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (href.startsWith("#")) continue;
|
|
162
|
+
const targetPath = resolveRelativeDocumentPath(documentPath, href);
|
|
163
|
+
if (state.nodes.some((node) => node.path === targetPath)) {
|
|
164
|
+
link.addEventListener("click", (event) => {
|
|
165
|
+
event.preventDefault();
|
|
166
|
+
onSelectDocument(targetPath);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
target.replaceChildren(template.content);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function replaceCodeReferences(source) {
|
|
174
|
+
return source.replace(/<CodeRef\s+([^>]*?)\/>/g, (_match, attributes) => {
|
|
175
|
+
const path = /path="([^"]*)"/.exec(attributes)?.[1] ?? "";
|
|
176
|
+
const symbol = /symbol="([^"]*)"/.exec(attributes)?.[1] ?? "";
|
|
177
|
+
const label = `⌁ ${path}${symbol ? ` · ${symbol}` : ""}`.replace(/`/g, "ˋ");
|
|
178
|
+
return `\`${label}\``;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function sanitizeFragment(fragment) {
|
|
183
|
+
const elements = [...fragment.querySelectorAll("*")].reverse();
|
|
184
|
+
for (const node of elements) {
|
|
185
|
+
if (DROP_TAGS.has(node.tagName)) {
|
|
186
|
+
node.remove();
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (!ALLOWED_TAGS.has(node.tagName)) {
|
|
190
|
+
node.replaceWith(...node.childNodes);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
for (const attribute of [...node.attributes]) {
|
|
194
|
+
if (!isAllowedAttribute(node, attribute.name, attribute.value)) node.removeAttribute(attribute.name);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function isAllowedAttribute(node, name, value) {
|
|
200
|
+
const normalized = name.toLowerCase();
|
|
201
|
+
if (node.tagName === "A" && ["href", "title"].includes(normalized)) {
|
|
202
|
+
return normalized !== "href" || isSafeUrl(value);
|
|
203
|
+
}
|
|
204
|
+
if (node.tagName === "IMG" && ["src", "alt", "title"].includes(normalized)) {
|
|
205
|
+
return normalized !== "src" || isSafeUrl(value);
|
|
206
|
+
}
|
|
207
|
+
if (["TD", "TH"].includes(node.tagName) && ["colspan", "rowspan"].includes(normalized)) {
|
|
208
|
+
return /^\d{1,2}$/.test(value);
|
|
209
|
+
}
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function isSafeUrl(value) {
|
|
214
|
+
const trimmed = value.trim();
|
|
215
|
+
return /^(https?:|mailto:|#|\/|\.\.?\/)/i.test(trimmed) || !/^[a-z][a-z\d+.-]*:/i.test(trimmed);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function element(tagName, className, text) {
|
|
219
|
+
const node = document.createElement(tagName);
|
|
220
|
+
if (className) node.className = className;
|
|
221
|
+
if (text !== undefined) node.textContent = text;
|
|
222
|
+
return node;
|
|
223
|
+
}
|