-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.ts
More file actions
246 lines (214 loc) · 7.97 KB
/
Copy pathrender.ts
File metadata and controls
246 lines (214 loc) · 7.97 KB
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
/**
* DOM rendering for the inspector UI. This is the ONE renderer, shared by the
* DevTools panel (`panel.ts`) and the standalone demo (`demo/index.html`). It
* depends on `document` but on nothing chrome- or framework-specific, so the
* demo can prove the whole UI in an ordinary browser tab.
*/
import type { CacheEvent, DerivedStatus, QuerySnapshot } from "./types.js";
import { statusMeta } from "./status.js";
import {
formatClock,
formatQueryKey,
formatRelativeTime,
truncate,
} from "./format.js";
import {
InspectorStore,
selectQueries,
selectStatusCounts,
type InspectorState,
} from "./store.js";
const STATUS_ORDER: DerivedStatus[] = ["fetching", "stale", "fresh", "inactive"];
export interface MountOptions {
/** Documentation URL for the discrete header link. */
docsUrl?: string;
/** Called when the user clicks "Refresh" (panel wires this to a page ping). */
onRefresh?: () => void;
/** Called when the user clears the event log. */
onClearEvents?: () => void;
}
function el<K extends keyof HTMLElementTagNameMap>(
tag: K,
className?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function badge(status: DerivedStatus): HTMLElement {
const meta = statusMeta(status);
const span = el("span", `qci-badge qci-badge--${meta.token}`, meta.label);
span.style.setProperty("--qci-badge-color", meta.color);
return span;
}
/**
* Mount the inspector UI into `root` and keep it in sync with `store`. Returns a
* disposer that unsubscribes. Selection state lives locally in the closure.
*/
export function mountInspector(
root: HTMLElement,
store: InspectorStore,
options: MountOptions = {},
): () => void {
root.classList.add("qci");
root.replaceChildren();
let selectedHash: string | null = null;
// ---- Header -------------------------------------------------------------
const header = el("header", "qci-header");
const title = el("div", "qci-title");
title.append(el("span", "qci-logo", "◆"), el("span", "qci-title-text", "Query Cache"));
const summary = el("div", "qci-summary");
const actions = el("div", "qci-actions");
const refreshBtn = el("button", "qci-btn", "Refresh");
refreshBtn.type = "button";
refreshBtn.addEventListener("click", () => options.onRefresh?.());
const clearBtn = el("button", "qci-btn qci-btn--ghost", "Clear log");
clearBtn.type = "button";
clearBtn.addEventListener("click", () => options.onClearEvents?.());
actions.append(refreshBtn, clearBtn);
if (options.docsUrl) {
const docs = el("a", "qci-docs", "Docs");
docs.href = options.docsUrl;
docs.target = "_blank";
docs.rel = "noreferrer noopener";
actions.append(docs);
}
header.append(title, summary, actions);
// ---- Body: query table + detail ----------------------------------------
const body = el("div", "qci-body");
const tableWrap = el("div", "qci-table-wrap");
const detail = el("aside", "qci-detail");
body.append(tableWrap, detail);
// ---- Event log ----------------------------------------------------------
const logSection = el("section", "qci-log");
const logHeader = el("div", "qci-log-header", "Cache events");
const logList = el("ol", "qci-log-list");
logSection.append(logHeader, logList);
root.append(header, body, logSection);
function renderSummary(state: InspectorState): void {
summary.replaceChildren();
const counts = selectStatusCounts(state);
const total = state.queries.size;
const totalPill = el("span", "qci-pill qci-pill--total", `${total} queries`);
summary.append(totalPill);
for (const status of STATUS_ORDER) {
const meta = statusMeta(status);
const pill = el("span", `qci-pill qci-pill--${meta.token}`, `${counts[status]} ${meta.label.toLowerCase()}`);
pill.style.setProperty("--qci-badge-color", meta.color);
summary.append(pill);
}
if (!state.connected) {
summary.append(el("span", "qci-pill qci-pill--warn", "no cache detected"));
}
}
function renderTable(state: InspectorState): void {
const queries = selectQueries(state);
tableWrap.replaceChildren();
if (queries.length === 0) {
const empty = el(
"div",
"qci-empty",
state.connected
? "The cache is empty. Trigger a query in the page."
: "Waiting for a QueryClient on the page…",
);
tableWrap.append(empty);
return;
}
const table = el("table", "qci-table");
const thead = el("thead");
const hrow = el("tr");
for (const label of ["Status", "Query key", "Obs", "Updated"]) {
hrow.append(el("th", undefined, label));
}
thead.append(hrow);
const tbody = el("tbody");
for (const q of queries) {
const row = el("tr", "qci-row");
if (q.queryHash === selectedHash) row.classList.add("qci-row--selected");
row.addEventListener("click", () => {
selectedHash = q.queryHash;
render(store.getState());
});
const statusCell = el("td");
statusCell.append(badge(q.derived));
if (q.fetchStatus === "fetching") statusCell.append(el("span", "qci-spinner"));
const keyCell = el("td", "qci-key", truncate(formatQueryKey(q.queryKey), 64));
keyCell.title = formatQueryKey(q.queryKey);
const obsCell = el("td", "qci-num", String(q.observers));
const updatedCell = el(
"td",
"qci-time",
formatRelativeTime(Math.max(q.dataUpdatedAt, q.errorUpdatedAt)),
);
row.append(statusCell, keyCell, obsCell, updatedCell);
tbody.append(row);
}
table.append(thead, tbody);
tableWrap.append(table);
}
function renderDetail(state: InspectorState): void {
detail.replaceChildren();
const q: QuerySnapshot | undefined = selectedHash
? state.queries.get(selectedHash)
: undefined;
if (!q) {
detail.append(el("div", "qci-detail-empty", "Select a query to inspect it."));
return;
}
detail.append(el("div", "qci-detail-head", "Query detail"));
const dl = el("dl", "qci-dl");
const addRow = (label: string, value: Node | string): void => {
dl.append(el("dt", undefined, label));
const dd = el("dd");
if (typeof value === "string") dd.textContent = value;
else dd.append(value);
dl.append(dd);
};
addRow("Status", badge(q.derived));
addRow("Raw status", `${q.status} / ${q.fetchStatus}`);
addRow("Query key", formatQueryKey(q.queryKey));
addRow("Query hash", q.queryHash);
addRow("Observers", String(q.observers));
addRow("Active", q.isActive ? "yes" : "no");
addRow("Stale", q.isStale ? "yes" : "no");
addRow("Data updated", `${formatRelativeTime(q.dataUpdatedAt)}`);
if (q.error) addRow("Error", q.error);
detail.append(dl);
detail.append(el("div", "qci-detail-head", "Data preview"));
const pre = el("pre", "qci-pre", q.dataPreview ?? "— no data —");
detail.append(pre);
}
function renderLog(state: InspectorState): void {
logList.replaceChildren();
if (state.events.length === 0) {
logList.append(el("li", "qci-log-empty", "No events yet."));
return;
}
// Newest first.
for (let i = state.events.length - 1; i >= 0; i--) {
logList.append(logRow(state.events[i]!));
}
}
function logRow(event: CacheEvent): HTMLElement {
const li = el("li", `qci-log-row qci-log-row--${event.type}`);
li.append(el("span", "qci-log-time", formatClock(event.at)));
li.append(el("span", "qci-log-type", event.type));
li.append(el("span", "qci-log-key", truncate(formatQueryKey(event.queryKey), 48)));
if (event.fetchStatus) {
li.append(el("span", "qci-log-fetch", event.fetchStatus));
}
return li;
}
function render(state: InspectorState): void {
renderSummary(state);
renderTable(state);
renderDetail(state);
renderLog(state);
}
const unsubscribe = store.subscribe(render);
render(store.getState());
return unsubscribe;
}