t3mode 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,2198 @@
1
+ (function() {
2
+ // src/PluginStorage.ts
3
+ const pluginStorage = (data, unreadable, pathOf, write, warn) => {
4
+ const unreadableIds = new Set(unreadable);
5
+ const refused = /* @__PURE__ */ new Set();
6
+ const pending = /* @__PURE__ */ new Map();
7
+ const persist = async (id, record) => {
8
+ const active = pending.get(id);
9
+ if (active) {
10
+ active.latest = record;
11
+ return;
12
+ }
13
+ const state = {
14
+ latest: void 0,
15
+ done: Promise.withResolvers()
16
+ };
17
+ pending.set(id, state);
18
+ let next = record;
19
+ while (next) {
20
+ state.latest = void 0;
21
+ try {
22
+ await write(id, next);
23
+ } catch (error) {
24
+ warn(`Plugin ${id} could not store data: ${String(error)}`);
25
+ }
26
+ next = state.latest;
27
+ }
28
+ pending.delete(id);
29
+ state.done.resolve();
30
+ };
31
+ const storage = (id) => ({
32
+ readable: !unreadableIds.has(id),
33
+ path: pathOf(id),
34
+ get: (key, fallback) => {
35
+ const record = data.get(id);
36
+ return record && Object.hasOwn(record, key) ? JSON.parse(JSON.stringify(record[key])) : fallback;
37
+ },
38
+ set: (key, value) => {
39
+ if (unreadableIds.has(id)) {
40
+ if (!refused.has(id)) {
41
+ refused.add(id);
42
+ warn(`Plugin ${id} data file is unreadable, so nothing is stored until it is fixed`);
43
+ }
44
+ return;
45
+ }
46
+ try {
47
+ const normalized = JSON.parse(JSON.stringify(value));
48
+ const record = {
49
+ ...data.get(id),
50
+ [key]: normalized
51
+ };
52
+ data.set(id, record);
53
+ persist(id, record);
54
+ } catch (error) {
55
+ warn(`Plugin ${id} could not store ${key}: ${String(error)}`);
56
+ }
57
+ }
58
+ });
59
+ return {
60
+ storage,
61
+ flush: (id) => pending.get(id)?.done.promise ?? Promise.resolve(),
62
+ /** After the plugin's file is deleted, a new install starts with readable, empty storage. */
63
+ forget: (id) => {
64
+ unreadableIds.delete(id);
65
+ refused.delete(id);
66
+ }
67
+ };
68
+ };
69
+ // src/dom.ts
70
+ const h = (tag, init = {}, ...children) => {
71
+ const element = document.createElement(tag);
72
+ if (init.className) element.className = init.className;
73
+ if (init.text !== void 0) element.textContent = init.text;
74
+ if (init.title !== void 0) element.title = init.title;
75
+ for (const [name, value] of Object.entries(init.attrs ?? {})) element.setAttribute(name, value);
76
+ if (init.style) Object.assign(element.style, init.style);
77
+ for (const [name, value] of Object.entries(init.props ?? {})) element[name] = value;
78
+ for (const [type, handler] of Object.entries(init.on ?? {})) element.addEventListener(type, handler);
79
+ for (const child of children) if (child) element.append(child);
80
+ return element;
81
+ };
82
+ /** The first element matching any of the selectors, tried in order: newest markup first. */
83
+ const queryFirst = (candidates) => {
84
+ for (const selector of candidates) {
85
+ const found = document.querySelector(selector);
86
+ if (found) return found;
87
+ }
88
+ return null;
89
+ };
90
+ // src/lib/react.ts
91
+ const isObject$1 = (value) => typeof value === "object" && value !== null;
92
+ /** The fiber React attached to a DOM node. */
93
+ const fiberOf = (node) => {
94
+ const key = Object.keys(node).find((name) => name.startsWith("__reactFiber$"));
95
+ return key ? node[key] ?? void 0 : void 0;
96
+ };
97
+ /** Props of the closest ancestor component (inclusive) whose props match `test`. */
98
+ const findPropsUp = (node, test, maxDepth = 80) => {
99
+ let fiber = fiberOf(node);
100
+ for (let depth = 0; fiber && depth < maxDepth; depth++, fiber = fiber.return) if (isObject$1(fiber.memoizedProps) && test(fiber.memoizedProps)) return fiber.memoizedProps;
101
+ };
102
+ const hooksOf = function* (fiber) {
103
+ let hook = fiber.memoizedState;
104
+ for (let index = 0; isObject$1(hook) && "next" in hook && index < 300; index++) {
105
+ yield hook.memoizedState;
106
+ hook = hook.next;
107
+ }
108
+ };
109
+ /**
110
+ * The first hook state anywhere in the tree under the root of `node` that matches `test`.
111
+ * Walks at most `budget` fibers.
112
+ */
113
+ const findHookState = (node, test, budget = 5e4) => {
114
+ let root = fiberOf(node);
115
+ while (root?.return) root = root.return;
116
+ const stack = root ? [root] : [];
117
+ for (let visited = 0; stack.length > 0 && visited < budget; visited++) {
118
+ const fiber = stack.pop();
119
+ if (!fiber) break;
120
+ for (const state of hooksOf(fiber)) if (test(state)) return state;
121
+ if (fiber.sibling) stack.push(fiber.sibling);
122
+ if (fiber.child) stack.push(fiber.child);
123
+ }
124
+ };
125
+ // src/lib/thread.ts
126
+ const NON_THREAD_ROUTES = /* @__PURE__ */ new Set([
127
+ "settings",
128
+ "welcome",
129
+ "usage",
130
+ "pull-requests",
131
+ "archive"
132
+ ]);
133
+ const currentThreadKey = (hash = location.hash) => {
134
+ const [first, second] = hash.replace(/^#\/?/, "").split(/[/?]/);
135
+ if (!first || !second || NON_THREAD_ROUTES.has(first)) return null;
136
+ try {
137
+ return first === "draft" ? `draft:${decodeURIComponent(second)}` : `${decodeURIComponent(first)}:${decodeURIComponent(second)}`;
138
+ } catch {
139
+ return null;
140
+ }
141
+ };
142
+ // src/ui/icons.ts
143
+ const SVG_NS = "http://www.w3.org/2000/svg";
144
+ const path = (d) => ["path", { d }];
145
+ const ICONS = {
146
+ puzzle: [path("M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z")],
147
+ gear: [path("M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"), ["circle", {
148
+ cx: "12",
149
+ cy: "12",
150
+ r: "3"
151
+ }]],
152
+ settings: [
153
+ path("M14 17H5"),
154
+ path("M19 7h-9"),
155
+ ["circle", {
156
+ cx: "17",
157
+ cy: "17",
158
+ r: "3"
159
+ }],
160
+ ["circle", {
161
+ cx: "7",
162
+ cy: "7",
163
+ r: "3"
164
+ }]
165
+ ],
166
+ info: [
167
+ ["circle", {
168
+ cx: "12",
169
+ cy: "12",
170
+ r: "10"
171
+ }],
172
+ path("M12 16v-4"),
173
+ path("M12 8h.01")
174
+ ],
175
+ chevronDown: [path("m6 9 6 6 6-6")],
176
+ check: [path("M20 6 9 17l-5-5")],
177
+ search: [path("m21 21-4.34-4.34"), ["circle", {
178
+ cx: "11",
179
+ cy: "11",
180
+ r: "8"
181
+ }]],
182
+ x: [path("M18 6 6 18"), path("m6 6 12 12")],
183
+ retry: [path("M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"), path("M3 3v5h5")],
184
+ download: [
185
+ path("M12 15V3"),
186
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"),
187
+ path("m7 10 5 5 5-5")
188
+ ],
189
+ trash: [
190
+ path("M3 6h18"),
191
+ path("M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"),
192
+ path("M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2")
193
+ ],
194
+ warning: [
195
+ path("m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"),
196
+ path("M12 9v4"),
197
+ path("M12 17h.01")
198
+ ],
199
+ folder: [path("M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z")]
200
+ };
201
+ const icon = (name, className = "") => {
202
+ const svg = document.createElementNS(SVG_NS, "svg");
203
+ for (const [key, value] of Object.entries({
204
+ xmlns: SVG_NS,
205
+ width: "24",
206
+ height: "24",
207
+ viewBox: "0 0 24 24",
208
+ fill: "none",
209
+ stroke: "currentColor",
210
+ "stroke-width": "2",
211
+ "stroke-linecap": "round",
212
+ "stroke-linejoin": "round",
213
+ "aria-hidden": "true",
214
+ class: `lucide lucide-${name} ${className}`.trim()
215
+ })) svg.setAttribute(key, value);
216
+ for (const [tag, attrs] of ICONS[name]) {
217
+ const shape = document.createElementNS(SVG_NS, tag);
218
+ for (const [key, value] of Object.entries(attrs)) shape.setAttribute(key, value);
219
+ svg.append(shape);
220
+ }
221
+ return svg;
222
+ };
223
+ // src/ui/native.ts
224
+ const native = {
225
+ header: "flex h-12 shrink-0 items-center gap-3 border-b ps-5 pe-2",
226
+ breadcrumb: "m-0 flex min-w-0 list-none items-center gap-2 p-0 text-sm sm:gap-3",
227
+ crumb: "flex min-w-0 items-center font-medium shrink-0 text-muted-foreground",
228
+ crumbSeparator: "flex shrink-0 items-center text-icon-muted",
229
+ crumbCurrent: "flex min-w-0 items-center font-medium text-foreground truncate",
230
+ headerActions: "ms-auto flex shrink-0 items-center gap-1",
231
+ pageScroll: "topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto",
232
+ pageBody: "mx-auto flex w-full flex-col px-5 pt-6 pb-12 sm:px-6 max-w-4xl gap-8",
233
+ section: "space-y-2.5",
234
+ sectionHeader: "flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4",
235
+ sectionTitleWrap: "flex min-w-0 items-center gap-1",
236
+ sectionTitle: "flex min-h-7 items-center gap-2 text-base font-semibold text-foreground",
237
+ sectionActions: "flex min-h-7 min-w-7 items-center justify-end",
238
+ group: "relative overflow-visible text-foreground rounded-xl border border-border/60 bg-card/40 shadow-xs/5 [&>*+*]:border-t [&>*+*]:border-border/50 [&>[data-slot=settings-row]]:rounded-none",
239
+ /** A settings group's surface without the dividers between its rows. */
240
+ card: "relative overflow-visible text-foreground rounded-xl border border-border/60 bg-card/40 shadow-xs/5",
241
+ row: "group/settings-row @container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground py-3",
242
+ rowLayout: "flex flex-col gap-3 @min-[32rem]/settings-row:grid @min-[32rem]/settings-row:grid-cols-[minmax(0,1fr)_auto] @min-[32rem]/settings-row:items-center @min-[32rem]/settings-row:gap-8",
243
+ rowText: "min-w-0 flex-1 space-y-1",
244
+ rowTitleLine: "flex min-h-5 items-center gap-1.5",
245
+ rowTitle: "text-sm font-medium text-foreground",
246
+ rowDescription: "max-w-2xl text-pretty text-xs leading-normal text-muted-foreground",
247
+ rowControl: "flex w-full min-w-0 shrink-0 items-center gap-2 @min-[32rem]/settings-row:w-auto @min-[32rem]/settings-row:justify-end @min-[32rem]/settings-row:[&_[data-slot=select-trigger]]:min-w-40",
248
+ switch: "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 cursor-pointer items-center rounded-full p-[2px] outline-none transition-[background-color,box-shadow] duration-200 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:cursor-not-allowed data-disabled:opacity-64 data-[mixed]:bg-input [--thumb-size:--spacing(5)] sm:[--thumb-size:--spacing(4)]",
249
+ switchThumb: "pointer-events-none block size-[calc(var(--thumb-size)-2px)] shrink-0 origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 dark:data-unchecked:bg-muted-foreground [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-right data-checked:translate-x-[calc(var(--thumb-size)-4px)]",
250
+ selectTrigger: "relative inline-flex cursor-pointer select-none items-center justify-between border rounded-lg text-left text-base outline-none transition-[color,box-shadow,background-color] data-disabled:pointer-events-none data-disabled:opacity-64 sm:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-inset aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-icon-muted [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:min-h-7 w-full sm:w-56",
251
+ selectValue: "flex-1 truncate data-placeholder:text-placeholder",
252
+ selectPopup: "origin-(--transform-origin) rounded-lg text-foreground outline-none",
253
+ selectSurface: "dropdown-glass relative h-full rounded-lg shadow-[0_16px_40px_-18px_rgb(0_0_0/55%)] dark:shadow-[0_18px_44px_-18px_rgb(0_0_0/80%)] min-w-(--anchor-width)",
254
+ selectList: "max-h-(--available-height) overflow-y-auto p-1 base-ui-disable-scrollbar",
255
+ selectItem: "flex min-h-8 cursor-pointer items-center rounded-sm px-2 py-1 text-base outline-none data-selected:bg-foreground/[0.08] data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
256
+ selectItemText: "min-w-0 flex-1 [&_svg:not([class*='text-'])]:text-muted-foreground",
257
+ /** The header's "Restore device defaults" button. */
258
+ ghostButton: "[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer items-center justify-center whitespace-nowrap rounded-[var(--control-radius)] border font-medium outline-none transition-[box-shadow,scale] [&:not([aria-haspopup]):not(:disabled):not([aria-disabled=true])]:will-change-[scale] [&:active:not([aria-haspopup])]:scale-[0.97] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--control-radius)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 aria-disabled:cursor-not-allowed aria-disabled:opacity-64 [&_svg:not([class*='text-'])]:text-[var(--control-icon-color)] [&_svg]:pointer-events-none [&_svg]:shrink-0 h-7 gap-1 px-[calc(--spacing(2)-1px)] text-sm sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5 [--control-icon-color:var(--contrast-muted-foreground)] border-transparent text-foreground data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent",
259
+ /** The header's close button. */
260
+ iconButton: "[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-[var(--control-radius)] border font-medium text-base outline-none transition-[box-shadow,scale] [&:not([aria-haspopup]):not(:disabled):not([aria-disabled=true])]:will-change-[scale] [&:active:not([aria-haspopup])]:scale-[0.97] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--control-radius)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 aria-disabled:cursor-not-allowed aria-disabled:opacity-64 sm:text-sm [&_svg:not([class*='text-'])]:text-[var(--control-icon-color)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0 size-8 sm:size-7 [--control-icon-color:var(--contrast-muted-foreground)] border-transparent text-foreground data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent"
261
+ };
262
+ /** The outlined variant: the ghost button with the select trigger's border and fill. */
263
+ const outlineButton = native.ghostButton.replace("border-transparent", "border-input bg-background dark:bg-input/32 shadow-xs/5");
264
+ let nextId = 0;
265
+ const uniqueId = (prefix) => `t3mode-${prefix}-${++nextId}`;
266
+ const section = (title, actions, ...content) => h("section", { className: native.section }, h("div", { className: native.sectionHeader }, h("div", { className: native.sectionTitleWrap }, h("h2", {
267
+ className: native.sectionTitle,
268
+ text: title
269
+ })), h("div", { className: native.sectionActions }, actions)), ...content);
270
+ const group = (...rows) => h("div", {
271
+ className: native.group,
272
+ attrs: { "data-slot": "settings-group" }
273
+ }, ...rows);
274
+ const row = (options) => h("div", {
275
+ className: native.row,
276
+ attrs: {
277
+ "data-slot": "settings-row",
278
+ ...options.disabled ? { "aria-disabled": "true" } : {}
279
+ }
280
+ }, h("div", { className: native.rowLayout }, h("div", { className: native.rowText }, options.title === void 0 ? null : h("div", { className: native.rowTitleLine }, h("h3", {
281
+ className: native.rowTitle,
282
+ text: options.title
283
+ })), options.description === void 0 ? null : typeof options.description === "string" ? h("p", {
284
+ className: native.rowDescription,
285
+ text: options.description
286
+ }) : h("div", { className: native.rowDescription }, options.description)), h("div", { className: native.rowControl }, options.control ?? null)));
287
+ const setChecked = (element, checked) => {
288
+ element.toggleAttribute("data-checked", checked);
289
+ element.toggleAttribute("data-unchecked", !checked);
290
+ };
291
+ /** T3 Code's switch: a `role="switch"` span with a thumb, toggled by click, Space or Enter. */
292
+ const switchControl = (options) => {
293
+ const thumb = h("span", {
294
+ className: native.switchThumb,
295
+ attrs: { "data-slot": "switch-thumb" }
296
+ });
297
+ const control = h("span", {
298
+ className: native.switch,
299
+ attrs: {
300
+ role: "switch",
301
+ tabindex: "0",
302
+ "aria-label": options.label,
303
+ "data-size": "default",
304
+ "data-slot": "switch"
305
+ }
306
+ }, thumb);
307
+ let checked = options.checked;
308
+ const apply = () => {
309
+ control.setAttribute("aria-checked", String(checked));
310
+ setChecked(control, checked);
311
+ setChecked(thumb, checked);
312
+ };
313
+ const toggle = (event) => {
314
+ event.preventDefault();
315
+ event.stopPropagation();
316
+ checked = !checked;
317
+ apply();
318
+ options.onChange(checked);
319
+ };
320
+ control.addEventListener("click", toggle);
321
+ control.addEventListener("keydown", (event) => {
322
+ if (event.key === " " || event.key === "Enter") toggle(event);
323
+ });
324
+ apply();
325
+ return control;
326
+ };
327
+ const button = (options) => h("button", {
328
+ className: options.variant === "outline" ? outlineButton : native.ghostButton,
329
+ attrs: {
330
+ type: "button",
331
+ "data-slot": "button"
332
+ },
333
+ on: { click: options.onClick }
334
+ }, options.icon ? icon(options.icon) : null, h("span", { text: options.text }));
335
+ const iconButton = (options) => h("button", {
336
+ className: native.iconButton,
337
+ title: options.label,
338
+ attrs: {
339
+ type: "button",
340
+ "aria-label": options.label
341
+ },
342
+ on: { click: (event) => {
343
+ event.stopPropagation();
344
+ options.onClick();
345
+ } }
346
+ }, icon(options.icon));
347
+ /**
348
+ * T3 Code's select: the trigger and popup markup of its base-ui select. The popup opens inside
349
+ * `host` instead of document.body, because T3 Code's settings dialog closes on any press
350
+ * outside itself.
351
+ */
352
+ const selectControl = (options) => {
353
+ let value = options.value;
354
+ const labelOf = (v) => options.choices.find((choice) => choice.value === v)?.label ?? v;
355
+ const valueText = h("span", {
356
+ className: native.selectValue,
357
+ attrs: { "data-slot": "select-value" },
358
+ text: labelOf(value)
359
+ });
360
+ const trigger = h("button", {
361
+ className: native.selectTrigger,
362
+ attrs: {
363
+ type: "button",
364
+ role: "combobox",
365
+ "aria-haspopup": "listbox",
366
+ "aria-expanded": "false",
367
+ "aria-label": options.label,
368
+ "data-slot": "select-trigger"
369
+ },
370
+ ...options.width ? { style: { width: options.width } } : {}
371
+ }, valueText, h("span", { attrs: {
372
+ "aria-hidden": "true",
373
+ "data-slot": "select-icon"
374
+ } }, icon("chevronDown", "-me-1 size-3.5 opacity-70")));
375
+ let close = null;
376
+ const open = () => {
377
+ const listId = uniqueId("list");
378
+ const items = options.choices.map((choice) => h("div", {
379
+ className: native.selectItem,
380
+ attrs: {
381
+ role: "option",
382
+ "data-slot": "select-item",
383
+ "data-value": choice.value,
384
+ "aria-selected": String(choice.value === value),
385
+ ...choice.value === value ? { "data-selected": "" } : {}
386
+ }
387
+ }, h("div", {
388
+ className: native.selectItemText,
389
+ text: choice.label
390
+ })));
391
+ const list = h("div", {
392
+ className: native.selectList,
393
+ attrs: {
394
+ id: listId,
395
+ role: "listbox",
396
+ tabindex: "-1",
397
+ "data-slot": "select-list"
398
+ }
399
+ }, ...items);
400
+ const popup = h("div", {
401
+ className: "t3mode-select-positioner",
402
+ attrs: { "data-slot": "select-positioner" }
403
+ }, h("div", {
404
+ className: native.selectPopup,
405
+ attrs: {
406
+ "data-slot": "select-popup",
407
+ "data-open": ""
408
+ }
409
+ }, h("div", { className: native.selectSurface }, list)));
410
+ let highlighted = Math.max(0, options.choices.findIndex((choice) => choice.value === value));
411
+ const highlight = (index) => {
412
+ highlighted = (index + items.length) % items.length;
413
+ items.forEach((item, i) => item.toggleAttribute("data-highlighted", i === highlighted));
414
+ items[highlighted]?.scrollIntoView({ block: "nearest" });
415
+ };
416
+ const choose = (index) => {
417
+ const choice = options.choices[index];
418
+ close?.();
419
+ trigger.focus();
420
+ if (!choice || choice.value === value) return;
421
+ value = choice.value;
422
+ valueText.textContent = choice.label;
423
+ options.onChange(choice.value);
424
+ };
425
+ items.forEach((item, index) => {
426
+ item.addEventListener("mouseenter", () => highlight(index));
427
+ item.addEventListener("click", () => choose(index));
428
+ });
429
+ const host = options.host.getBoundingClientRect();
430
+ const anchor = trigger.getBoundingClientRect();
431
+ popup.style.setProperty("--anchor-width", `${anchor.width}px`);
432
+ options.host.append(popup);
433
+ const below = host.bottom - anchor.bottom - 12;
434
+ const above = anchor.top - host.top - 12;
435
+ const up = popup.offsetHeight > below && above > below;
436
+ popup.style.setProperty("--available-height", `${Math.max(120, up ? above : below)}px`);
437
+ popup.style.right = `${host.right - anchor.right}px`;
438
+ if (up) popup.style.bottom = `${host.bottom - anchor.top + 4}px`;
439
+ else popup.style.top = `${anchor.bottom - host.top + 4}px`;
440
+ trigger.setAttribute("aria-expanded", "true");
441
+ trigger.setAttribute("aria-controls", listId);
442
+ trigger.toggleAttribute("data-popup-open", true);
443
+ highlight(highlighted);
444
+ list.focus();
445
+ const onKey = (event) => {
446
+ if (![
447
+ "ArrowDown",
448
+ "ArrowUp",
449
+ "Home",
450
+ "End",
451
+ "Enter",
452
+ " ",
453
+ "Escape",
454
+ "Tab"
455
+ ].includes(event.key)) return;
456
+ event.stopImmediatePropagation();
457
+ if (event.key !== "Tab") event.preventDefault();
458
+ if (event.key === "ArrowDown") highlight(highlighted + 1);
459
+ else if (event.key === "ArrowUp") highlight(highlighted - 1);
460
+ else if (event.key === "Home") highlight(0);
461
+ else if (event.key === "End") highlight(items.length - 1);
462
+ else if (event.key === "Enter" || event.key === " ") choose(highlighted);
463
+ else {
464
+ close?.();
465
+ if (event.key === "Escape") trigger.focus();
466
+ }
467
+ };
468
+ const onPointer = (event) => {
469
+ const target = event.target;
470
+ if (!popup.contains(target) && !trigger.contains(target)) close?.();
471
+ };
472
+ window.addEventListener("keydown", onKey, true);
473
+ document.addEventListener("pointerdown", onPointer, true);
474
+ close = () => {
475
+ close = null;
476
+ window.removeEventListener("keydown", onKey, true);
477
+ document.removeEventListener("pointerdown", onPointer, true);
478
+ popup.remove();
479
+ trigger.setAttribute("aria-expanded", "false");
480
+ trigger.removeAttribute("data-popup-open");
481
+ };
482
+ };
483
+ trigger.addEventListener("click", (event) => {
484
+ event.stopPropagation();
485
+ if (close) close();
486
+ else open();
487
+ });
488
+ trigger.addEventListener("keydown", (event) => {
489
+ if (!close && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
490
+ event.preventDefault();
491
+ open();
492
+ }
493
+ });
494
+ new MutationObserver((_, observer) => {
495
+ if (!trigger.isConnected) {
496
+ close?.();
497
+ observer.disconnect();
498
+ }
499
+ }).observe(options.host, {
500
+ childList: true,
501
+ subtree: true
502
+ });
503
+ return trigger;
504
+ };
505
+ // ../shared/src/Shortcut.ts
506
+ const SHORTCUT_COMMAND = "script.t3-mode-plugins.run";
507
+ // ../shared/src/T3Hooks.ts
508
+ const T3_HOOKS = {
509
+ pane: {
510
+ attribute: "data-workspace-area",
511
+ value: "settings"
512
+ },
513
+ nav: {
514
+ attribute: "data-workspace-area",
515
+ value: "settings-nav"
516
+ },
517
+ section: { attribute: "data-settings-section" },
518
+ capture: { attribute: "data-keybinding-capture" },
519
+ keybinding: {
520
+ attribute: "id",
521
+ value: "keybinding-"
522
+ },
523
+ badge: {
524
+ attribute: "data-slot",
525
+ value: "badge"
526
+ }
527
+ };
528
+ const hookSelector = (hook) => hook.value === void 0 ? `[${hook.attribute}]` : `[${hook.attribute}="${hook.value}"]`;
529
+ // src/ui/styles.ts
530
+ const STYLE_ATTRIBUTE = "data-t3mode-ui";
531
+ const SHORTCUT_BADGE = `${hookSelector({
532
+ ...T3_HOOKS.keybinding,
533
+ value: `${T3_HOOKS.keybinding.value}${SHORTCUT_COMMAND}`
534
+ })} ${hookSelector(T3_HOOKS.badge)}`;
535
+ const CSS = `
536
+ [data-t3mode-toasts] {
537
+ position: fixed; right: 16px; bottom: 16px; z-index: 2147483646;
538
+ display: flex; flex-direction: column; gap: 8px; max-width: 360px; pointer-events: none;
539
+ }
540
+ .t3mode-toast {
541
+ padding: 10px 12px; border-radius: 12px; font: 13px/1.4 var(--font-sans, system-ui, sans-serif);
542
+ color: var(--popover-foreground, #f5f5f5); background: var(--popover, #1c1c1c);
543
+ border: 1px solid var(--border, rgba(255,255,255,.1)); box-shadow: 0 8px 24px rgba(0,0,0,.35);
544
+ }
545
+ .t3mode-toast-error { border-color: var(--destructive, #e5484d); }
546
+
547
+ /* While t3mode's page is open, React's own page stays mounted but hidden. */
548
+ [data-t3mode-page-open] > :not([data-t3mode-page]) { display: none !important; }
549
+
550
+ [data-t3mode-page] .t3mode-toolbar { display: flex; gap: 8px; align-items: center; }
551
+ [data-t3mode-page] .t3mode-search { flex: 1; width: auto; cursor: text; }
552
+ [data-t3mode-page] .t3mode-search:focus-within {
553
+ border-color: var(--ring); box-shadow: inset 0 0 0 3px color-mix(in oklab, var(--ring) 24%, transparent);
554
+ }
555
+ [data-t3mode-page] .t3mode-search-input {
556
+ flex: 1; min-width: 0; height: 100%; padding: 0; border: 0; outline: 0;
557
+ background: transparent; color: inherit; font: inherit;
558
+ }
559
+ [data-t3mode-page] .t3mode-search-input::placeholder { color: var(--muted-foreground); opacity: .8; }
560
+ [data-t3mode-page] .t3mode-search-input::-webkit-search-cancel-button { display: none; }
561
+ [data-t3mode-page] .t3mode-count { font-size: var(--text-xs, 12px); color: var(--muted-foreground); }
562
+ [data-t3mode-page] .t3mode-path { font-family: var(--font-mono, ui-monospace, monospace); word-break: break-all; }
563
+
564
+ [data-t3mode-page] .t3mode-grid {
565
+ display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr));
566
+ }
567
+ [data-t3mode-page] .t3mode-card {
568
+ display: flex; flex-direction: column; gap: 6px; padding: 12px 12px 12px 16px; min-height: 124px;
569
+ cursor: pointer; transition: border-color .15s, background-color .15s;
570
+ }
571
+ [data-t3mode-page] .t3mode-card:hover {
572
+ border-color: color-mix(in oklab, var(--border) 100%, var(--foreground) 6%);
573
+ background-color: color-mix(in oklab, var(--card) 70%, var(--accent));
574
+ }
575
+ [data-t3mode-page] .t3mode-card-head { display: flex; align-items: center; gap: 6px; min-height: 28px; }
576
+ [data-t3mode-page] .t3mode-card-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
577
+ [data-t3mode-page] .t3mode-card-head [role="switch"] { margin-left: 4px; }
578
+ [data-t3mode-page] .t3mode-card-description { flex: 1; padding-right: 4px; }
579
+ [data-t3mode-page] .t3mode-card-foot { display: flex; align-items: center; gap: 8px; min-height: 24px; }
580
+ [data-t3mode-page] .t3mode-empty { padding: 4px 16px; }
581
+ [data-t3mode-page] .t3mode-actions { display: flex; align-items: center; gap: 8px; }
582
+ [data-t3mode-page] .t3mode-card-meta {
583
+ margin-top: -6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
584
+ font-size: var(--text-xs, 12px); color: var(--muted-foreground);
585
+ }
586
+ [data-t3mode-page] .t3mode-install { display: flex; flex-direction: column; gap: 10px; }
587
+ [data-t3mode-page] .t3mode-install-error { padding: 0 16px; font-size: var(--text-xs, 12px); color: var(--destructive-foreground, #ff8a8a); }
588
+ [data-t3mode-page] .t3mode-confirm { display: flex; flex-direction: column; gap: 6px; padding: 12px 16px; }
589
+ [data-t3mode-page] .t3mode-confirm .t3mode-actions { margin-top: 4px; }
590
+ [data-t3mode-page] .t3mode-warning { display: flex; align-items: flex-start; gap: 6px; font-size: var(--text-xs, 12px); color: var(--foreground); }
591
+ [data-t3mode-page] .t3mode-warning svg { flex: none; width: 14px; height: 14px; margin-top: 1px; color: var(--warning, #f5a524); }
592
+
593
+ [data-t3mode-page] .t3mode-status {
594
+ display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1;
595
+ font-size: var(--text-xs, 12px); color: var(--muted-foreground);
596
+ }
597
+ [data-t3mode-page] .t3mode-status-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
598
+ [data-t3mode-page] .t3mode-dot { flex: none; width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: .6; }
599
+ [data-t3mode-page] .t3mode-status[data-tone="active"] .t3mode-dot { color: var(--success, #3fb950); opacity: 1; }
600
+ [data-t3mode-page] .t3mode-status[data-tone="waiting"] .t3mode-dot { color: var(--warning, #f5a524); opacity: 1; }
601
+ [data-t3mode-page] .t3mode-status[data-tone="failed"] { color: var(--destructive-foreground, #ff8a8a); }
602
+ [data-t3mode-page] .t3mode-status[data-tone="failed"] .t3mode-dot { opacity: 1; }
603
+
604
+ [data-t3mode-page] .t3mode-crumb-link {
605
+ padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer;
606
+ }
607
+ [data-t3mode-page] .t3mode-crumb-link:hover { color: var(--foreground); }
608
+ [data-t3mode-page] .t3mode-select-positioner { position: absolute; z-index: 130; user-select: none; }
609
+ [data-t3mode-page] [data-slot="select-list"]:focus { outline: none; }
610
+
611
+ /* Settings → Keybindings lists T3 Mode's shortcut as a project script; badge it "T3 Mode" instead. */
612
+ ${SHORTCUT_BADGE} { font-size: 0; }
613
+ ${SHORTCUT_BADGE}::after {
614
+ content: "T3 Mode"; font-size: .75rem;
615
+ }
616
+ @media (min-width: 640px) {
617
+ ${SHORTCUT_BADGE}::after { font-size: .625rem; }
618
+ }
619
+ `;
620
+ const ensureStyles = () => {
621
+ if (document.head.querySelector(`[${STYLE_ATTRIBUTE}]`)) return;
622
+ const style = document.createElement("style");
623
+ style.setAttribute(STYLE_ATTRIBUTE, "");
624
+ style.textContent = CSS;
625
+ document.head.append(style);
626
+ };
627
+ // src/ui/toast.ts
628
+ const STACK_ATTRIBUTE = "data-t3mode-toasts";
629
+ /** A small message in the bottom-right corner, gone after a few seconds. */
630
+ const toast = (message, kind = "info") => {
631
+ ensureStyles();
632
+ let stack = document.querySelector(`[${STACK_ATTRIBUTE}]`);
633
+ if (!stack) {
634
+ stack = h("div", { attrs: {
635
+ [STACK_ATTRIBUTE]: "",
636
+ role: "status",
637
+ "aria-live": "polite"
638
+ } });
639
+ document.body.append(stack);
640
+ }
641
+ const item = h("div", {
642
+ className: `t3mode-toast t3mode-toast-${kind}`,
643
+ text: message
644
+ });
645
+ stack.append(item);
646
+ window.setTimeout(() => item.remove(), kind === "error" ? 8e3 : 4e3);
647
+ };
648
+ // src/Runtime.ts
649
+ const describe$1 = (error) => error instanceof Error ? error.stack ?? error.message : String(error);
650
+ const firstLine = (text) => text.split("\n")[0] ?? text;
651
+ const isObject = (value) => typeof value === "object" && value !== null;
652
+ const isDefinition = (value) => isObject(value) && typeof value["start"] === "function" && isObject(value["options"]);
653
+ const pluginDefinition = (exported) => {
654
+ const candidate = isObject(exported) && !isDefinition(exported) ? exported["default"] : exported;
655
+ return isDefinition(candidate) ? candidate : void 0;
656
+ };
657
+ const optionValues = (spec, stored) => {
658
+ const values = {};
659
+ for (const [key, option] of Object.entries(spec)) {
660
+ const value = stored?.[key];
661
+ values[key] = (option.type === "boolean" ? typeof value === "boolean" : option.choices.some((choice) => choice.value === value)) ? value : option.default;
662
+ }
663
+ return values;
664
+ };
665
+ var Runtime = class {
666
+ #native;
667
+ #data = /* @__PURE__ */ new Map();
668
+ #storage;
669
+ #entries = /* @__PURE__ */ new Map();
670
+ #registrations = /* @__PURE__ */ new Map();
671
+ #cleanups = /* @__PURE__ */ new Map();
672
+ #states = /* @__PURE__ */ new Map();
673
+ #listeners = /* @__PURE__ */ new Set();
674
+ #updateListeners = /* @__PURE__ */ new Set();
675
+ #panels = /* @__PURE__ */ new Map();
676
+ #backends = /* @__PURE__ */ new Map();
677
+ #backendListeners = /* @__PURE__ */ new Map();
678
+ #settings;
679
+ #update;
680
+ info;
681
+ constructor(native, installed, settings, info, pluginData) {
682
+ this.#native = native;
683
+ for (const [id, data] of Object.entries(pluginData.data)) this.#data.set(id, { ...data });
684
+ const separator = info.home.includes("\\") ? "\\" : "/";
685
+ this.#storage = pluginStorage(this.#data, pluginData.unreadable, (id) => [
686
+ info.home,
687
+ "plugin-data",
688
+ `${id}.json`
689
+ ].join(separator), native.writePluginData, (message) => this.log("warn", message));
690
+ this.#settings = settings;
691
+ this.info = info;
692
+ const pending = window.__t3modePlugins;
693
+ if (Array.isArray(pending)) for (const item of pending) this.#register(item);
694
+ window.__t3modePlugins = { push: (...registrations) => {
695
+ for (const item of registrations) this.#register(item);
696
+ return registrations.length;
697
+ } };
698
+ for (const plugin of installed) this.#entries.set(plugin.id, this.#entryFor(plugin));
699
+ }
700
+ /**
701
+ * Follows the plugins' backends. Main sends the current statuses before it answers, so plugins
702
+ * started after this see their backend's status from the first call.
703
+ */
704
+ async followBackends() {
705
+ try {
706
+ this.#native.onBackendEvent((event) => this.#onBackendEvent(event));
707
+ await this.#native.backend({ _tag: "subscribe" });
708
+ } catch (error) {
709
+ this.log("warn", `Could not follow plugin backends: ${describe$1(error)}`);
710
+ }
711
+ }
712
+ /** The plugin's backend, as main last reported it. Null: none runs. */
713
+ backendStatus(id) {
714
+ return this.#backends.get(id) ?? null;
715
+ }
716
+ #onBackendEvent(event) {
717
+ if (event._tag === "status") {
718
+ if (event.status) this.#backends.set(event.plugin, event.status);
719
+ else this.#backends.delete(event.plugin);
720
+ this.#emit();
721
+ }
722
+ for (const listener of this.#backendListeners.get(event.plugin) ?? []) if (event._tag === "message") listener.message?.(event.data);
723
+ else listener.status?.(event.status);
724
+ }
725
+ #listenBackend(id, listener, add) {
726
+ let listeners = this.#backendListeners.get(id);
727
+ if (!listeners) {
728
+ listeners = /* @__PURE__ */ new Set();
729
+ this.#backendListeners.set(id, listeners);
730
+ }
731
+ listeners.add(listener);
732
+ add(() => listeners.delete(listener));
733
+ }
734
+ get plugins() {
735
+ return [...this.#entries.values()].map((entry) => entry.info).toSorted((a, b) => a.name.localeCompare(b.name));
736
+ }
737
+ plugin(id) {
738
+ return this.#entries.get(id)?.info;
739
+ }
740
+ optionSpec(id) {
741
+ const entry = this.#entries.get(id);
742
+ return entry?.kind === "loaded" ? entry.definition.options : {};
743
+ }
744
+ /** False until the plugin is first turned on, because its options are in its code. */
745
+ optionsKnown(id) {
746
+ return this.#entries.get(id)?.kind === "loaded";
747
+ }
748
+ state(id) {
749
+ const entry = this.#entries.get(id);
750
+ if (entry?.kind === "broken") return {
751
+ kind: "unavailable",
752
+ reason: entry.reason
753
+ };
754
+ return this.#states.get(id) ?? { kind: "off" };
755
+ }
756
+ /** The section a running plugin added to its settings page. */
757
+ panel(id) {
758
+ return this.#panels.get(id);
759
+ }
760
+ isEnabled(id) {
761
+ return this.#settings.plugins[id]?.enabled ?? true;
762
+ }
763
+ options(id) {
764
+ return optionValues(this.optionSpec(id), this.#settings.plugins[id]?.options);
765
+ }
766
+ /** Called whenever a plugin's state or settings change, for the settings page. */
767
+ subscribe(listener) {
768
+ this.#listeners.add(listener);
769
+ return () => this.#listeners.delete(listener);
770
+ }
771
+ startAll() {
772
+ for (const entry of this.#entries.values()) {
773
+ if (!this.isEnabled(entry.info.id)) continue;
774
+ if (entry.kind === "broken") {
775
+ this.log("error", `Plugin ${entry.info.id} can't start: ${entry.reason}`);
776
+ toast(`${entry.info.name} can't start. Open T3 Mode's plugins in Settings to see why.`, "error");
777
+ } else this.#start(entry.info.id);
778
+ }
779
+ }
780
+ async setEnabled(id, enabled) {
781
+ this.#stop(id);
782
+ if (enabled) this.#start(id);
783
+ await this.#save(id, { enabled });
784
+ }
785
+ async setOption(id, key, value) {
786
+ const options = {
787
+ ...this.#settings.plugins[id]?.options,
788
+ [key]: value
789
+ };
790
+ if (this.isEnabled(id)) {
791
+ this.#stop(id);
792
+ this.#start(id, options);
793
+ }
794
+ await this.#save(id, { options });
795
+ }
796
+ async retry(id) {
797
+ if (this.backendStatus(id)?.state === "failed") await this.#native.backend({
798
+ _tag: "retry",
799
+ plugin: id
800
+ }).catch((error) => {
801
+ this.log("warn", `Could not restart the backend of ${id}: ${describe$1(error)}`);
802
+ });
803
+ const kind = this.state(id).kind;
804
+ if (kind !== "failed" && kind !== "unavailable") return;
805
+ const entry = this.#entries.get(id);
806
+ if (!entry) return;
807
+ this.#stop(id);
808
+ this.#states.delete(id);
809
+ if (entry.kind === "broken") await this.#rereadFromDisk(entry.info);
810
+ if (this.isEnabled(id)) this.#start(id);
811
+ this.#emit();
812
+ }
813
+ async #rereadFromDisk(previous) {
814
+ const info = (await this.#native.plugins.list().catch(() => void 0))?.find((plugin) => plugin.id === previous.id) ?? previous;
815
+ if (info.error === void 0) {
816
+ this.#registrations.delete(info.id);
817
+ await this.#native.loadPlugin(info.id).catch((error) => {
818
+ this.log("error", `Plugin ${info.id} could not be loaded: ${describe$1(error)}`);
819
+ });
820
+ }
821
+ this.#entries.set(info.id, this.#entryFor(info));
822
+ }
823
+ preview(input) {
824
+ return this.#ask("Preview", () => this.#native.plugins.preview(input));
825
+ }
826
+ async install(source, id, approved) {
827
+ const result = await this.#ask("Install", () => this.#native.plugins.install(source, id, approved));
828
+ return this.#loadAndStart(result);
829
+ }
830
+ async updatePlugin(id, approved) {
831
+ const result = await this.#ask("Update", () => this.#native.plugins.update(id, approved));
832
+ return this.#loadAndStart(result);
833
+ }
834
+ async remove(id) {
835
+ const running = this.state(id).kind === "running";
836
+ this.#stop(id);
837
+ await this.#storage.flush(id);
838
+ const result = await this.#ask("Remove", () => this.#native.plugins.remove(id));
839
+ if (result.ok) {
840
+ this.#data.delete(id);
841
+ this.#storage.forget(id);
842
+ this.#entries.delete(id);
843
+ this.#registrations.delete(id);
844
+ this.#states.delete(id);
845
+ this.#emit();
846
+ } else if (running) this.#start(id);
847
+ return result;
848
+ }
849
+ async checkUpdates() {
850
+ const result = await this.#ask("Check", () => this.#native.plugins.checkUpdates());
851
+ const listed = result.ok ? result.value : await this.#native.plugins.list().catch(() => this.plugins);
852
+ for (const info of listed) {
853
+ const entry = this.#entries.get(info.id);
854
+ if (entry) this.#entries.set(info.id, {
855
+ ...entry,
856
+ info
857
+ });
858
+ }
859
+ this.#emit();
860
+ return result;
861
+ }
862
+ /** T3 Mode's shortcut in T3 Code's keybindings.json; "unavailable" when that fails. */
863
+ async shortcut(action) {
864
+ try {
865
+ return await this.#native.shortcut(action);
866
+ } catch (error) {
867
+ this.log("warn", `Shortcut ${action} failed: ${describe$1(error)}`);
868
+ return "unavailable";
869
+ }
870
+ }
871
+ /** The last T3 Code update status from main, once `watchUpdates` has run. */
872
+ get updateStatus() {
873
+ return this.#update;
874
+ }
875
+ /** Follows T3 Code updates: main pushes every change once the page asked for the status. */
876
+ watchUpdates() {
877
+ this.#native.onUpdate((status) => this.#setUpdate(status));
878
+ this.update("status");
879
+ }
880
+ async update(action) {
881
+ try {
882
+ const status = await this.#native.update(action);
883
+ this.#setUpdate(status);
884
+ return status;
885
+ } catch (error) {
886
+ this.log("warn", `Update ${action} failed: ${describe$1(error)}`);
887
+ return;
888
+ }
889
+ }
890
+ onUpdate(listener) {
891
+ this.#updateListeners.add(listener);
892
+ return () => this.#updateListeners.delete(listener);
893
+ }
894
+ /** Whether T3 Mode installs T3 Code's updates. Applies at the next launch. */
895
+ async setManageUpdates(manage) {
896
+ await this.#write({
897
+ ...this.#settings,
898
+ updates: {
899
+ ...this.#settings.updates,
900
+ manage
901
+ }
902
+ });
903
+ await this.update("status");
904
+ }
905
+ async openLogs() {
906
+ try {
907
+ await this.#native.openLogs();
908
+ } catch (error) {
909
+ this.log("warn", `Could not open the logs folder: ${describe$1(error)}`);
910
+ toast(`Could not open ${this.info.logs}.`, "error");
911
+ }
912
+ }
913
+ log(level, message) {
914
+ this.#native.log(level, message).catch(() => void 0);
915
+ }
916
+ #register(item) {
917
+ if (isObject(item) && typeof item["id"] === "string" && typeof item["load"] === "function") this.#registrations.set(item["id"], item["load"]);
918
+ else this.log("warn", "Ignored a plugin registration that has no id or load function");
919
+ }
920
+ #entryFor(info) {
921
+ if (info.error !== void 0) return {
922
+ info,
923
+ kind: "broken",
924
+ reason: info.error
925
+ };
926
+ const load = this.#registrations.get(info.id);
927
+ if (!load) return {
928
+ info,
929
+ kind: "broken",
930
+ reason: "Its code didn't run. See T3 Mode's log."
931
+ };
932
+ return this.isEnabled(info.id) ? this.#run(info, load) : {
933
+ info,
934
+ kind: "unloaded",
935
+ load
936
+ };
937
+ }
938
+ #run(info, load) {
939
+ try {
940
+ const definition = pluginDefinition(load());
941
+ return definition ? {
942
+ info,
943
+ kind: "loaded",
944
+ definition
945
+ } : {
946
+ info,
947
+ kind: "broken",
948
+ reason: "plugin.js doesn't export definePlugin(...)."
949
+ };
950
+ } catch (error) {
951
+ this.log("error", `Plugin ${info.id} failed to load: ${describe$1(error)}`);
952
+ return {
953
+ info,
954
+ kind: "broken",
955
+ reason: `Its code threw: ${firstLine(describe$1(error))}`
956
+ };
957
+ }
958
+ }
959
+ async #loadAndStart(result) {
960
+ if (!result.ok) return result;
961
+ const info = result.value;
962
+ this.#stop(info.id);
963
+ this.#states.delete(info.id);
964
+ this.#registrations.delete(info.id);
965
+ if (info.error === void 0) try {
966
+ await this.#native.loadPlugin(info.id);
967
+ } catch (error) {
968
+ this.log("error", `Plugin ${info.id} could not be loaded: ${describe$1(error)}`);
969
+ }
970
+ this.#entries.set(info.id, this.#entryFor(info));
971
+ if (this.isEnabled(info.id)) this.#start(info.id);
972
+ this.#emit();
973
+ return result;
974
+ }
975
+ async #ask(action, call) {
976
+ try {
977
+ return await call();
978
+ } catch (error) {
979
+ this.log("error", `${action} failed: ${describe$1(error)}`);
980
+ return {
981
+ ok: false,
982
+ error: `${action} failed. See T3 Mode's log.`
983
+ };
984
+ }
985
+ }
986
+ #emit() {
987
+ for (const listener of this.#listeners) try {
988
+ listener();
989
+ } catch (error) {
990
+ this.log("error", `Settings page listener failed: ${describe$1(error)}`);
991
+ }
992
+ }
993
+ #setState(id, state) {
994
+ this.#states.set(id, state);
995
+ this.#emit();
996
+ }
997
+ #setUpdate(status) {
998
+ const previous = this.#update;
999
+ this.#update = status;
1000
+ const { phase } = status;
1001
+ if (phase.kind === "ready" && previous !== void 0 && !(previous.phase.kind === "ready" && previous.phase.version === phase.version) && status.installable) toast(`T3 Code ${phase.version} is ready. It installs when you quit T3 Code.`, "info");
1002
+ for (const listener of this.#updateListeners) try {
1003
+ listener(status);
1004
+ } catch (error) {
1005
+ this.log("error", `Update listener failed: ${describe$1(error)}`);
1006
+ }
1007
+ }
1008
+ async #save(id, patch) {
1009
+ const current = this.#settings.plugins[id] ?? {};
1010
+ await this.#write({
1011
+ ...this.#settings,
1012
+ plugins: {
1013
+ ...this.#settings.plugins,
1014
+ [id]: {
1015
+ ...current,
1016
+ ...patch
1017
+ }
1018
+ }
1019
+ });
1020
+ }
1021
+ async #write(next) {
1022
+ this.#settings = next;
1023
+ this.#emit();
1024
+ try {
1025
+ await this.#native.writeSettings(this.#settings);
1026
+ } catch (error) {
1027
+ this.log("error", `Could not save settings: ${describe$1(error)}`);
1028
+ toast("T3 Mode could not save its settings. See its log.", "error");
1029
+ }
1030
+ }
1031
+ #fail(id, error) {
1032
+ if (this.state(id).kind !== "running") return;
1033
+ this.#stop(id);
1034
+ const detail = describe$1(error);
1035
+ this.#setState(id, {
1036
+ kind: "failed",
1037
+ error: firstLine(detail)
1038
+ });
1039
+ this.log("error", `Plugin ${id} failed and was stopped: ${detail}`);
1040
+ toast(`${this.plugin(id)?.name ?? id} stopped after an error. Open T3 Mode's plugins in Settings to retry.`, "error");
1041
+ }
1042
+ #stop(id) {
1043
+ const cleanups = this.#cleanups.get(id) ?? [];
1044
+ this.#cleanups.delete(id);
1045
+ for (const cleanup of cleanups.toReversed()) try {
1046
+ cleanup();
1047
+ } catch (error) {
1048
+ this.log("warn", `Cleanup of ${id} failed: ${describe$1(error)}`);
1049
+ }
1050
+ if (this.#states.get(id)?.kind === "running") this.#setState(id, { kind: "off" });
1051
+ }
1052
+ #start(id, storedOptions) {
1053
+ let entry = this.#entries.get(id);
1054
+ if (entry?.kind === "unloaded") {
1055
+ entry = this.#run(entry.info, entry.load);
1056
+ this.#entries.set(id, entry);
1057
+ this.#emit();
1058
+ }
1059
+ if (entry?.kind !== "loaded") return;
1060
+ const { definition } = entry;
1061
+ const cleanups = [];
1062
+ this.#cleanups.set(id, cleanups);
1063
+ this.#setState(id, {
1064
+ kind: "running",
1065
+ report: null
1066
+ });
1067
+ const alive = () => this.#cleanups.get(id) === cleanups;
1068
+ /** Wraps every callback a plugin hands to the API, so its errors stop only that plugin. */
1069
+ const guard = (callback) => (...args) => {
1070
+ if (!alive()) return;
1071
+ try {
1072
+ callback(...args);
1073
+ } catch (error) {
1074
+ this.#fail(id, error);
1075
+ }
1076
+ };
1077
+ const add = (cleanup) => cleanups.push(cleanup);
1078
+ const api = {
1079
+ id,
1080
+ options: optionValues(definition.options, storedOptions ?? this.#settings.plugins[id]?.options),
1081
+ css: (text) => {
1082
+ const style = document.createElement("style");
1083
+ style.dataset["t3modePlugin"] = id;
1084
+ style.textContent = text;
1085
+ document.head.append(style);
1086
+ add(() => style.remove());
1087
+ },
1088
+ observe: (callback) => {
1089
+ const run = guard(callback);
1090
+ let frame = 0;
1091
+ const schedule = () => {
1092
+ if (frame === 0) frame = requestAnimationFrame(() => {
1093
+ frame = 0;
1094
+ run();
1095
+ });
1096
+ };
1097
+ const observer = new MutationObserver(schedule);
1098
+ observer.observe(document.body, {
1099
+ childList: true,
1100
+ subtree: true,
1101
+ attributes: true
1102
+ });
1103
+ window.addEventListener("hashchange", schedule);
1104
+ add(() => {
1105
+ observer.disconnect();
1106
+ window.removeEventListener("hashchange", schedule);
1107
+ cancelAnimationFrame(frame);
1108
+ });
1109
+ run();
1110
+ },
1111
+ listen: (target, type, handler, options) => {
1112
+ const wrapped = guard(handler);
1113
+ target.addEventListener(type, wrapped, options);
1114
+ add(() => target.removeEventListener(type, wrapped, options));
1115
+ },
1116
+ interval: (callback, ms) => {
1117
+ const handle = window.setInterval(guard(callback), ms);
1118
+ add(() => window.clearInterval(handle));
1119
+ },
1120
+ element: (tag) => {
1121
+ const element = document.createElement(tag);
1122
+ element.dataset["t3modePlugin"] = id;
1123
+ add(() => element.remove());
1124
+ return element;
1125
+ },
1126
+ onCleanup: add,
1127
+ storage: this.#storage.storage(id),
1128
+ settingsPanel: (title, render) => {
1129
+ this.#panels.set(id, {
1130
+ title,
1131
+ render: guard(render)
1132
+ });
1133
+ add(() => this.#panels.delete(id));
1134
+ this.#emit();
1135
+ },
1136
+ toast: (message, kind) => {
1137
+ if (alive()) toast(message, kind);
1138
+ },
1139
+ ui: {
1140
+ group,
1141
+ row,
1142
+ button: (options) => button({
1143
+ ...options,
1144
+ onClick: guard(options.onClick)
1145
+ })
1146
+ },
1147
+ log: (level, message) => this.log(level, `[${id}] ${message}`),
1148
+ report: (report) => {
1149
+ const state = this.state(id);
1150
+ if (!alive() || state.kind !== "running") return;
1151
+ if (state.report?.state === report.state && state.report.detail === report.detail) return;
1152
+ this.#setState(id, {
1153
+ kind: "running",
1154
+ report
1155
+ });
1156
+ },
1157
+ queryFirst,
1158
+ currentThreadKey,
1159
+ react: {
1160
+ findPropsUp,
1161
+ findHookState
1162
+ },
1163
+ disks: () => this.#native.disks(),
1164
+ backend: {
1165
+ send: (data) => alive() ? this.#native.backend({
1166
+ _tag: "send",
1167
+ plugin: id,
1168
+ data
1169
+ }) : Promise.resolve(false),
1170
+ onMessage: (callback) => this.#listenBackend(id, { message: guard(callback) }, add),
1171
+ onStatus: (callback) => {
1172
+ const run = guard(callback);
1173
+ this.#listenBackend(id, { status: run }, add);
1174
+ run(this.backendStatus(id));
1175
+ }
1176
+ }
1177
+ };
1178
+ try {
1179
+ definition.start(api);
1180
+ } catch (error) {
1181
+ this.#fail(id, error);
1182
+ }
1183
+ }
1184
+ };
1185
+ // ../shared/src/Plugins.ts
1186
+ const declaredAccess = (manifest) => ({
1187
+ backend: manifest.backend !== void 0,
1188
+ mcp: manifest.mcp !== void 0
1189
+ });
1190
+ const accessLines = (access) => [...access.backend ? ["Runs a program outside T3 Code's window"] : [], ...access.mcp ? ["Adds tools to your agents"] : []];
1191
+ const sourceLabel = (source) => source.kind === "github" ? `${source.owner}/${source.repo}${source.tag === void 0 ? "" : `@${source.tag}`}` : `linked from ${source.path}`;
1192
+ // src/ui/updatesSection.ts
1193
+ const MB = 1048576;
1194
+ const ago = (at) => {
1195
+ if (at === null) return "";
1196
+ const minutes = Math.floor((Date.now() - at) / 6e4);
1197
+ if (minutes < 1) return " Checked just now.";
1198
+ if (minutes < 60) return ` Checked ${minutes} minute${minutes === 1 ? "" : "s"} ago.`;
1199
+ const hours = Math.floor(minutes / 60);
1200
+ return ` Checked ${hours} hour${hours === 1 ? "" : "s"} ago.`;
1201
+ };
1202
+ const describeStatus = (status) => {
1203
+ if (!status.managed) return status.manageSetting ? "T3 Mode installs updates from the next launch. Until then T3 Code's own updater runs, and an update it installs removes T3 Mode." : "T3 Code's own updater installs updates, and each one removes T3 Mode. Run \"t3mode repair\" after an update.";
1204
+ if (!status.manageSetting) return "Turned off. From the next launch, T3 Code's own updater installs updates, and each one removes T3 Mode.";
1205
+ const { phase } = status;
1206
+ switch (phase.kind) {
1207
+ case "idle": return "The first check runs shortly after T3 Code starts.";
1208
+ case "checking": return "Checking for updates…";
1209
+ case "up-to-date": return `Up to date on the ${status.channel} channel.${ago(status.checkedAt)}`;
1210
+ case "downloading": {
1211
+ const percent = phase.total > 0 ? Math.floor(phase.received / phase.total * 100) : 0;
1212
+ return `Downloading ${phase.version}: ${percent}% of ${Math.round(phase.total / MB)} MB.`;
1213
+ }
1214
+ case "verifying": return `Checking the download of ${phase.version}.`;
1215
+ case "ready": return status.installable ? `${phase.version} is ready. It installs when T3 Code quits, and T3 Mode puts itself back.` : `${phase.version} is downloaded and verified. The sandbox never installs T3 Code's real installer.`;
1216
+ case "failed": return `${phase.message}${ago(status.checkedAt)}`;
1217
+ }
1218
+ };
1219
+ const rows = (runtime, status) => {
1220
+ if (!status) return [row({
1221
+ title: "T3 Code",
1222
+ description: "Reading the update status…"
1223
+ })];
1224
+ const { phase } = status;
1225
+ const check = () => button({
1226
+ text: "Check now",
1227
+ icon: "retry",
1228
+ variant: "outline",
1229
+ onClick: () => void runtime.update("check")
1230
+ });
1231
+ const control = !status.managed || !status.manageSetting ? null : phase.kind === "ready" ? status.installable ? button({
1232
+ text: "Restart now",
1233
+ icon: "retry",
1234
+ variant: "outline",
1235
+ onClick: () => void runtime.update("restart")
1236
+ }) : null : phase.kind === "idle" || phase.kind === "up-to-date" || phase.kind === "failed" ? check() : null;
1237
+ return [row({
1238
+ title: `T3 Code ${status.current}`,
1239
+ description: describeStatus(status),
1240
+ control
1241
+ }), row({
1242
+ title: "Install updates through T3 Mode",
1243
+ description: "T3 Code's own updater removes T3 Mode with every update. T3 Mode installs the same updates, checks they are signed by T3 Code's publisher, and puts itself back. A change applies when T3 Code restarts.",
1244
+ control: switchControl({
1245
+ label: "Install updates through T3 Mode",
1246
+ checked: status.manageSetting,
1247
+ onChange: (checked) => void runtime.setManageUpdates(checked)
1248
+ })
1249
+ })];
1250
+ };
1251
+ const updatesSection = (runtime) => {
1252
+ const body = group(...rows(runtime, runtime.updateStatus));
1253
+ const stop = runtime.onUpdate((status) => {
1254
+ if (!body.isConnected) {
1255
+ stop();
1256
+ return;
1257
+ }
1258
+ body.replaceChildren(...rows(runtime, status));
1259
+ });
1260
+ return section("Updates", null, body);
1261
+ };
1262
+ // src/ui/settingsPage.ts
1263
+ const NAV_ATTRIBUTE = "data-t3mode-nav";
1264
+ const NAV_GROUP_ATTRIBUTE = "data-t3mode-nav-group";
1265
+ const NAME = "T3 Mode";
1266
+ const PAGE_ATTRIBUTE = "data-t3mode-page";
1267
+ const OPEN_ATTRIBUTE = "data-t3mode-page-open";
1268
+ const SETTINGS_ROUTE = "#/settings/general";
1269
+ const sel = {
1270
+ pane: hookSelector(T3_HOOKS.pane),
1271
+ nav: hookSelector(T3_HOOKS.nav),
1272
+ section: `button${hookSelector(T3_HOOKS.section)}`,
1273
+ close: "header button[aria-label=\"Close\"]"
1274
+ };
1275
+ const navKeyOf = (view) => view.kind === "home" ? "home" : "plugins";
1276
+ const FILTERS = [
1277
+ {
1278
+ value: "all",
1279
+ label: "All plugins"
1280
+ },
1281
+ {
1282
+ value: "enabled",
1283
+ label: "Enabled"
1284
+ },
1285
+ {
1286
+ value: "disabled",
1287
+ label: "Disabled"
1288
+ }
1289
+ ];
1290
+ const canRetry = (runtime, plugin) => {
1291
+ const kind = runtime.state(plugin.id).kind;
1292
+ return kind === "failed" || kind === "unavailable" && (plugin.error === void 0 || plugin.source.kind === "local") || runtime.backendStatus(plugin.id)?.state === "failed";
1293
+ };
1294
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1295
+ const busy = async (control, action) => {
1296
+ control.disabled = true;
1297
+ try {
1298
+ await action();
1299
+ } finally {
1300
+ control.disabled = false;
1301
+ }
1302
+ };
1303
+ const fragment = (...nodes) => {
1304
+ const result = document.createDocumentFragment();
1305
+ for (const node of nodes) if (node) result.append(node);
1306
+ return result;
1307
+ };
1308
+ const status = (runtime, plugin) => {
1309
+ const state = runtime.state(plugin.id);
1310
+ const backend = runtime.backendStatus(plugin.id);
1311
+ if (state.kind !== "failed" && state.kind !== "unavailable") {
1312
+ if (backend?.state === "failed") return {
1313
+ tone: "failed",
1314
+ text: `Backend stopped after ${backend.crashes} crashes: ${backend.error}`
1315
+ };
1316
+ if (backend?.state === "restarting") return {
1317
+ tone: "waiting",
1318
+ text: `Backend restarting after a crash: ${backend.error}`
1319
+ };
1320
+ }
1321
+ switch (state.kind) {
1322
+ case "off": return {
1323
+ tone: "off",
1324
+ text: runtime.isEnabled(plugin.id) ? "Starting" : "Off"
1325
+ };
1326
+ case "failed": return {
1327
+ tone: "failed",
1328
+ text: `Stopped after an error: ${state.error.split("\n")[0]}`
1329
+ };
1330
+ case "unavailable": return {
1331
+ tone: "failed",
1332
+ text: `Can't load: ${state.reason}`
1333
+ };
1334
+ case "running":
1335
+ if (!state.report) return {
1336
+ tone: "active",
1337
+ text: "Running"
1338
+ };
1339
+ return {
1340
+ tone: state.report.state,
1341
+ text: `${state.report.state === "active" ? "Active" : "Waiting"}: ${state.report.detail}`
1342
+ };
1343
+ }
1344
+ };
1345
+ const statusLine = (runtime, plugin) => {
1346
+ const { tone, text } = status(runtime, plugin);
1347
+ return h("div", {
1348
+ className: "t3mode-status",
1349
+ attrs: { "data-tone": tone },
1350
+ title: text
1351
+ }, h("span", { className: "t3mode-dot" }), h("span", {
1352
+ className: "t3mode-status-text",
1353
+ text
1354
+ }));
1355
+ };
1356
+ const crumbSeparator = () => h("li", {
1357
+ className: native.crumbSeparator,
1358
+ attrs: { "aria-hidden": "true" },
1359
+ text: "/"
1360
+ });
1361
+ const crumbCurrent = (text) => h("li", {
1362
+ className: native.crumbCurrent,
1363
+ attrs: { "aria-current": "page" },
1364
+ text
1365
+ });
1366
+ /** Section paths look like `/settings/general`, routes like `#/settings/general?x`. */
1367
+ const currentSection = () => location.hash.replace(/^#/, "").split("?")[0];
1368
+ var SettingsPage = class {
1369
+ #runtime;
1370
+ #view = { kind: "plugins" };
1371
+ #query = "";
1372
+ #filter = "all";
1373
+ #link = "";
1374
+ #step = { kind: "idle" };
1375
+ #installBox = null;
1376
+ #root = null;
1377
+ #body = null;
1378
+ #grid = null;
1379
+ #teardown = [];
1380
+ #openRequestedAt = 0;
1381
+ constructor(runtime) {
1382
+ this.#runtime = runtime;
1383
+ }
1384
+ /** Opens a page, opening T3 Code's settings first when they are closed. */
1385
+ open(view = { kind: "plugins" }) {
1386
+ this.#view = view;
1387
+ const pane = document.querySelector(sel.pane);
1388
+ if (pane) {
1389
+ this.#mount(pane);
1390
+ return;
1391
+ }
1392
+ this.#openRequestedAt = performance.now();
1393
+ location.hash = SETTINGS_ROUTE;
1394
+ }
1395
+ /** Run on DOM changes: keeps the nav entry in place and notices when settings close. */
1396
+ sync() {
1397
+ if (this.#root && !this.#root.isConnected) {
1398
+ this.#unmount();
1399
+ const pane = document.querySelector(sel.pane);
1400
+ if (pane) this.#mount(pane);
1401
+ }
1402
+ if (this.#openRequestedAt > 0) {
1403
+ const pane = document.querySelector(sel.pane);
1404
+ if (pane) {
1405
+ this.#openRequestedAt = 0;
1406
+ this.#mount(pane);
1407
+ } else if (performance.now() - this.#openRequestedAt > 3e3) this.#openRequestedAt = 0;
1408
+ }
1409
+ this.#syncNav();
1410
+ }
1411
+ #mount(pane) {
1412
+ ensureStyles();
1413
+ if (this.#root?.isConnected) {
1414
+ this.#render();
1415
+ return;
1416
+ }
1417
+ this.#unmount();
1418
+ const root = h("div", {
1419
+ className: "relative flex min-h-0 min-w-0 flex-1 flex-col",
1420
+ attrs: { [PAGE_ATTRIBUTE]: "" }
1421
+ });
1422
+ this.#root = root;
1423
+ pane.setAttribute(OPEN_ATTRIBUTE, "");
1424
+ pane.append(root);
1425
+ const reactActive = [...document.querySelectorAll(`${sel.section}[data-active="true"]`)];
1426
+ for (const item of reactActive) item.setAttribute("data-active", "false");
1427
+ this.#teardown.push(() => {
1428
+ for (const item of reactActive) if (item.isConnected && item.dataset["settingsSection"] === currentSection()) item.setAttribute("data-active", "true");
1429
+ pane.removeAttribute(OPEN_ATTRIBUTE);
1430
+ });
1431
+ const nav = document.querySelector(sel.nav);
1432
+ if (nav) {
1433
+ const onNav = (event) => {
1434
+ const target = event.target;
1435
+ if (target.closest(`[${NAV_GROUP_ATTRIBUTE}]`)) return;
1436
+ if (event.type === "input" || target.closest("button, a")) this.close();
1437
+ };
1438
+ nav.addEventListener("click", onNav, true);
1439
+ nav.addEventListener("input", onNav, true);
1440
+ this.#teardown.push(() => {
1441
+ nav.removeEventListener("click", onNav, true);
1442
+ nav.removeEventListener("input", onNav, true);
1443
+ });
1444
+ }
1445
+ const mountedAt = location.hash;
1446
+ const onRoute = () => {
1447
+ if (location.hash !== mountedAt) this.close();
1448
+ };
1449
+ window.addEventListener("hashchange", onRoute);
1450
+ this.#teardown.push(() => window.removeEventListener("hashchange", onRoute));
1451
+ this.#teardown.push(this.#runtime.subscribe(() => this.#refresh()));
1452
+ this.#render();
1453
+ this.#syncNav();
1454
+ root.querySelector("[data-t3mode-focus]")?.focus();
1455
+ }
1456
+ close() {
1457
+ this.#unmount();
1458
+ this.#syncNav();
1459
+ }
1460
+ #unmount() {
1461
+ for (const cleanup of this.#teardown.splice(0).toReversed()) cleanup();
1462
+ this.#root?.remove();
1463
+ this.#root = null;
1464
+ this.#body = null;
1465
+ this.#grid = null;
1466
+ this.#installBox = null;
1467
+ }
1468
+ #syncNav() {
1469
+ const nav = document.querySelector(sel.nav);
1470
+ if (!nav) return;
1471
+ let navGroup = nav.querySelector(`[${NAV_GROUP_ATTRIBUTE}]`);
1472
+ if (!navGroup) {
1473
+ navGroup = this.#buildNavGroup(nav);
1474
+ if (!navGroup) return;
1475
+ }
1476
+ const open = this.#root?.isConnected === true;
1477
+ for (const item of navGroup.querySelectorAll(`[${NAV_ATTRIBUTE}]`)) {
1478
+ const entry = item.querySelector("button");
1479
+ const active = open && item.getAttribute(NAV_ATTRIBUTE) === navKeyOf(this.#view);
1480
+ if (!entry || entry.getAttribute("data-active") === String(active)) continue;
1481
+ entry.setAttribute("data-active", String(active));
1482
+ if (active) entry.setAttribute("aria-current", "page");
1483
+ else entry.removeAttribute("aria-current");
1484
+ }
1485
+ }
1486
+ /**
1487
+ * A copy of T3 Code's "Connections" group (its label and list), renamed and given t3mode's
1488
+ * entries, placed right after it. Without labelled groups, the entries go after the last
1489
+ * section instead.
1490
+ */
1491
+ #buildNavGroup(nav) {
1492
+ const labels = [...nav.querySelectorAll("h3")];
1493
+ const template = (labels.find((item) => item.textContent.trim() === "Connections") ?? labels.at(-1))?.parentElement;
1494
+ const itemTemplate = template?.querySelector("li") ?? nav.querySelector(sel.section)?.closest("li");
1495
+ if (!itemTemplate) return null;
1496
+ const items = [this.#navItem(itemTemplate, "home", NAME, "gear"), this.#navItem(itemTemplate, "plugins", "Plugins", "puzzle")];
1497
+ if (template && template.querySelector("ul")) {
1498
+ const navGroup = template.cloneNode(true);
1499
+ navGroup.setAttribute(NAV_GROUP_ATTRIBUTE, "");
1500
+ const title = navGroup.querySelector("h3");
1501
+ if (title) {
1502
+ title.textContent = NAME;
1503
+ title.id = "t3mode-settings-nav-group";
1504
+ navGroup.querySelector("[role=group]")?.setAttribute("aria-labelledby", title.id);
1505
+ }
1506
+ navGroup.querySelector("ul")?.replaceChildren(...items);
1507
+ template.after(navGroup);
1508
+ return navGroup;
1509
+ }
1510
+ const last = [...nav.querySelectorAll(sel.section)].at(-1)?.closest("li");
1511
+ if (!last?.parentElement) return null;
1512
+ const list = last.parentElement;
1513
+ for (const item of items.toReversed()) last.after(item);
1514
+ list.setAttribute(NAV_GROUP_ATTRIBUTE, "");
1515
+ return list;
1516
+ }
1517
+ #navItem(template, key, text, iconName) {
1518
+ const item = template.cloneNode(true);
1519
+ item.setAttribute(NAV_ATTRIBUTE, key);
1520
+ const entry = item.querySelector("button");
1521
+ if (!entry) return item;
1522
+ entry.removeAttribute(T3_HOOKS.section.attribute);
1523
+ entry.removeAttribute("aria-current");
1524
+ entry.setAttribute("data-active", "false");
1525
+ const label = [...entry.querySelectorAll("span, div")].findLast((node) => node.children.length === 0 && node.textContent.trim().length > 0);
1526
+ if (label) label.textContent = text;
1527
+ else entry.textContent = text;
1528
+ entry.querySelector("svg")?.replaceWith(icon(iconName));
1529
+ entry.addEventListener("click", (event) => {
1530
+ event.preventDefault();
1531
+ event.stopPropagation();
1532
+ if (this.#root?.isConnected) this.#go({ kind: key });
1533
+ else this.open({ kind: key });
1534
+ });
1535
+ return item;
1536
+ }
1537
+ #go(view) {
1538
+ this.#view = view;
1539
+ this.#render();
1540
+ this.#syncNav();
1541
+ this.#root?.querySelector("[data-t3mode-focus]")?.focus();
1542
+ }
1543
+ /** Plugin state changed: redraw what shows it, keeping the search box and focus. */
1544
+ #refresh() {
1545
+ if (!this.#root) return;
1546
+ if (this.#view.kind === "plugins") this.#renderGrid();
1547
+ else if (this.#view.kind === "plugin") this.#render();
1548
+ }
1549
+ #render() {
1550
+ const root = this.#root;
1551
+ if (!root) return;
1552
+ const focusedId = document.activeElement?.id;
1553
+ const plugin = this.#view.kind === "plugin" ? this.#runtime.plugin(this.#view.id) : void 0;
1554
+ if (this.#view.kind === "plugin" && !plugin) this.#view = { kind: "plugins" };
1555
+ const body = h("div", { className: native.pageBody });
1556
+ this.#body = body;
1557
+ root.replaceChildren(this.#header(plugin), h("div", { className: "min-h-0 flex flex-1 flex-col" }, h("div", { className: native.pageScroll }, body)));
1558
+ if (plugin) this.#renderPlugin(body, plugin);
1559
+ else if (this.#view.kind === "home") this.#renderHome(body);
1560
+ else this.#renderPlugins(body);
1561
+ if (focusedId) document.getElementById(focusedId)?.focus();
1562
+ }
1563
+ #header(plugin) {
1564
+ const crumbs = [h("li", {
1565
+ className: native.crumb,
1566
+ text: "Settings"
1567
+ }), crumbSeparator()];
1568
+ if (plugin) crumbs.push(h("li", { className: native.crumb }, h("button", {
1569
+ className: "t3mode-crumb-link",
1570
+ text: "Plugins",
1571
+ attrs: { type: "button" },
1572
+ on: { click: () => this.#go({ kind: "plugins" }) }
1573
+ })), crumbSeparator(), crumbCurrent(plugin.name));
1574
+ else crumbs.push(crumbCurrent(this.#view.kind === "home" ? NAME : "Plugins"));
1575
+ const nativeClose = document.querySelector(`${sel.pane} > ${sel.close}`);
1576
+ return h("header", { className: native.header }, h("nav", {
1577
+ className: "min-w-0",
1578
+ attrs: { "aria-label": "Settings breadcrumb" }
1579
+ }, h("ol", { className: native.breadcrumb }, ...crumbs)), h("div", { className: native.headerActions }, nativeClose ? iconButton({
1580
+ label: "Close",
1581
+ icon: "x",
1582
+ onClick: () => nativeClose.click()
1583
+ }) : null));
1584
+ }
1585
+ #renderHome(body) {
1586
+ const runtime = this.#runtime;
1587
+ const info = runtime.info;
1588
+ const about = group(row({
1589
+ title: `${NAME} ${info.t3modeVersion}`,
1590
+ description: `Plugins for T3 Code, without changing T3 Code itself. Running on T3 Code ${info.t3codeVersion}.`
1591
+ }));
1592
+ runtime.shortcut("status").then((shortcutStatus) => {
1593
+ if (shortcutStatus !== "missing" || !about.isConnected) return;
1594
+ const restore = button({
1595
+ text: "Restore",
1596
+ icon: "retry",
1597
+ variant: "outline",
1598
+ onClick: () => {
1599
+ runtime.shortcut("restore").then((next) => {
1600
+ if (next === "added" || next === "present") {
1601
+ toast("Shortcut restored as Ctrl+Alt+M. Change it in Settings → Keybindings, under T3 Mode Plugins.", "info");
1602
+ shortcutRow.remove();
1603
+ } else toast("T3 Mode could not update T3 Code's keybindings. See its log.", "error");
1604
+ });
1605
+ }
1606
+ });
1607
+ const shortcutRow = row({
1608
+ title: "Keyboard shortcut",
1609
+ description: "The shortcut that opens Plugins was removed from Settings → Keybindings. Restore it, then change it there under \"T3 Mode Plugins\".",
1610
+ control: restore
1611
+ });
1612
+ about.append(shortcutRow);
1613
+ });
1614
+ body.append(section(NAME, null, about), updatesSection(runtime), section("Troubleshooting", null, group(row({
1615
+ title: "Logs",
1616
+ description: h("span", {
1617
+ className: "t3mode-path",
1618
+ text: info.logs
1619
+ }),
1620
+ control: button({
1621
+ text: "Open folder",
1622
+ icon: "folder",
1623
+ variant: "outline",
1624
+ onClick: () => {
1625
+ runtime.openLogs();
1626
+ }
1627
+ })
1628
+ }), row({
1629
+ title: "Safe mode",
1630
+ description: `To start T3 Code once without ${NAME}, close it and run "t3mode safe". ${NAME} also skips a launch on its own after failed starts or repeated crashes.`
1631
+ }), row({
1632
+ title: "Uninstall",
1633
+ description: `Close T3 Code and run "t3mode uninstall" to restore its original files.`
1634
+ }))));
1635
+ }
1636
+ #renderPlugins(body) {
1637
+ const runtime = this.#runtime;
1638
+ const enabled = runtime.plugins.filter((plugin) => runtime.isEnabled(plugin.id)).length;
1639
+ const search = h("input", {
1640
+ className: "t3mode-search-input",
1641
+ attrs: {
1642
+ id: "t3mode-plugin-search",
1643
+ type: "search",
1644
+ placeholder: "Search plugins",
1645
+ "aria-label": "Search plugins",
1646
+ autocomplete: "off",
1647
+ spellcheck: "false"
1648
+ },
1649
+ props: { value: this.#query },
1650
+ on: {
1651
+ input: (event) => {
1652
+ this.#query = event.target.value;
1653
+ this.#renderGrid();
1654
+ },
1655
+ keydown: (event) => {
1656
+ if (event.key === "Escape" && this.#query !== "") {
1657
+ event.stopPropagation();
1658
+ event.preventDefault();
1659
+ this.#query = "";
1660
+ event.target.value = "";
1661
+ this.#renderGrid();
1662
+ }
1663
+ }
1664
+ }
1665
+ });
1666
+ const grid = h("div", { className: "t3mode-grid" });
1667
+ this.#grid = grid;
1668
+ const check = button({
1669
+ text: "Check for updates",
1670
+ icon: "retry",
1671
+ variant: "outline",
1672
+ onClick: () => void busy(check, () => this.#checkUpdates())
1673
+ });
1674
+ check.id = "t3mode-plugins-check";
1675
+ body.append(this.#installSection(), section("Plugins", h("div", { className: "t3mode-actions" }, h("span", {
1676
+ className: "t3mode-count",
1677
+ text: `${enabled} of ${runtime.plugins.length} enabled`
1678
+ }), check), h("div", { className: "t3mode-toolbar" }, h("label", { className: `${native.selectTrigger} t3mode-search` }, icon("search", "size-3.5"), search), selectControl({
1679
+ host: this.#root ?? body,
1680
+ label: "Filter plugins",
1681
+ value: this.#filter,
1682
+ choices: FILTERS,
1683
+ width: "10rem",
1684
+ onChange: (value) => {
1685
+ this.#filter = value;
1686
+ this.#renderGrid();
1687
+ }
1688
+ })), grid));
1689
+ this.#renderGrid();
1690
+ }
1691
+ #installSection() {
1692
+ const link = h("input", {
1693
+ className: "t3mode-search-input",
1694
+ attrs: {
1695
+ id: "t3mode-plugin-link",
1696
+ type: "text",
1697
+ placeholder: "owner/repo, or the plugin's GitHub link",
1698
+ "aria-label": "Plugin's GitHub link",
1699
+ autocomplete: "off",
1700
+ spellcheck: "false"
1701
+ },
1702
+ props: { value: this.#link },
1703
+ on: {
1704
+ input: (event) => {
1705
+ this.#link = event.target.value;
1706
+ if (this.#step.kind === "failed") this.#setStep({ kind: "idle" });
1707
+ },
1708
+ keydown: (event) => {
1709
+ if (event.key === "Enter") this.#preview();
1710
+ }
1711
+ }
1712
+ });
1713
+ const box = h("div", { className: "t3mode-install" });
1714
+ this.#installBox = box;
1715
+ const install = button({
1716
+ text: "Install",
1717
+ icon: "download",
1718
+ variant: "outline",
1719
+ onClick: () => void this.#preview()
1720
+ });
1721
+ install.id = "t3mode-plugin-install";
1722
+ const result = section("Install from GitHub", null, h("div", { className: "t3mode-toolbar" }, h("label", { className: `${native.selectTrigger} t3mode-search` }, link), install), box);
1723
+ this.#renderInstallStep();
1724
+ return result;
1725
+ }
1726
+ #setStep(step) {
1727
+ this.#step = step;
1728
+ this.#renderInstallStep();
1729
+ }
1730
+ #renderInstallStep() {
1731
+ const box = this.#installBox;
1732
+ if (!box) return;
1733
+ const step = this.#step;
1734
+ switch (step.kind) {
1735
+ case "idle":
1736
+ box.replaceChildren();
1737
+ return;
1738
+ case "reading":
1739
+ box.replaceChildren(h("p", {
1740
+ className: `${native.rowDescription} t3mode-empty`,
1741
+ text: "Reading the release…"
1742
+ }));
1743
+ return;
1744
+ case "failed":
1745
+ box.replaceChildren(h("p", {
1746
+ className: "t3mode-install-error",
1747
+ attrs: { role: "alert" },
1748
+ text: step.error
1749
+ }));
1750
+ return;
1751
+ case "confirm":
1752
+ case "installing": box.replaceChildren(this.#confirmPanel(step));
1753
+ }
1754
+ }
1755
+ #confirmPanel(step) {
1756
+ const { preview, installed } = step;
1757
+ const installing = step.kind === "installing";
1758
+ let firstReady = true;
1759
+ let singleConfirm = null;
1760
+ const offers = preview.offers.map((offer) => {
1761
+ if (offer.kind === "unavailable") return h("div", {}, h("h3", {
1762
+ className: native.rowTitle,
1763
+ text: offer.id
1764
+ }), h("p", {
1765
+ className: "t3mode-install-error",
1766
+ text: offer.reason
1767
+ }));
1768
+ const { manifest, source } = offer;
1769
+ const done = installed.includes(manifest.id);
1770
+ const confirm = button({
1771
+ text: done ? "Installed" : installing && step.id === manifest.id ? "Installing…" : "Install",
1772
+ icon: "download",
1773
+ variant: "outline",
1774
+ onClick: () => void this.#install(preview, offer, installed)
1775
+ });
1776
+ if (firstReady) confirm.id = "t3mode-plugin-confirm";
1777
+ firstReady = false;
1778
+ confirm.disabled = installing || done;
1779
+ if (preview.offers.length === 1) singleConfirm = confirm;
1780
+ const by = manifest.author ? `by ${manifest.author} · ` : "";
1781
+ return h("div", { attrs: { "aria-label": `Install ${manifest.name}` } }, h("h3", {
1782
+ className: native.rowTitle,
1783
+ text: `${manifest.name} ${manifest.version}`
1784
+ }), h("p", {
1785
+ className: native.rowDescription,
1786
+ text: `${by}github.com/${sourceLabel(source)}`
1787
+ }), ...accessLines(declaredAccess(manifest)).map((text) => h("p", {
1788
+ className: native.rowDescription,
1789
+ text
1790
+ })), manifest.description ? h("p", {
1791
+ className: native.rowDescription,
1792
+ text: manifest.description
1793
+ }) : null, preview.offers.length > 1 ? confirm : null);
1794
+ });
1795
+ const allInstalled = preview.offers.every((offer) => offer.kind === "unavailable" || installed.includes(offer.manifest.id));
1796
+ const cancel = button({
1797
+ text: allInstalled ? "Done" : "Cancel",
1798
+ onClick: () => this.#setStep({ kind: "idle" })
1799
+ });
1800
+ cancel.disabled = installing;
1801
+ return h("div", { className: `${native.card} t3mode-confirm` }, ...offers, h("p", { className: "t3mode-warning" }, icon("warning"), h("span", { text: "A plugin gets full access to T3 Code, including your threads. Install it only if you trust its author." })), h("div", { className: "t3mode-actions" }, singleConfirm, cancel));
1802
+ }
1803
+ async #preview() {
1804
+ const input = this.#link.trim();
1805
+ if (input === "" || this.#step.kind === "reading" || this.#step.kind === "installing") return;
1806
+ this.#setStep({ kind: "reading" });
1807
+ const result = await this.#runtime.preview(input);
1808
+ this.#setStep(result.ok ? {
1809
+ kind: "confirm",
1810
+ preview: result.value,
1811
+ installed: []
1812
+ } : {
1813
+ kind: "failed",
1814
+ error: result.error
1815
+ });
1816
+ if (result.ok) document.getElementById("t3mode-plugin-confirm")?.focus();
1817
+ }
1818
+ async #install(preview, offer, installed) {
1819
+ this.#setStep({
1820
+ kind: "installing",
1821
+ preview,
1822
+ installed,
1823
+ id: offer.manifest.id
1824
+ });
1825
+ const result = await this.#runtime.install(offer.source, offer.manifest.id, declaredAccess(offer.manifest));
1826
+ if (!result.ok) {
1827
+ if (preview.offers.length === 1) {
1828
+ this.#setStep({
1829
+ kind: "failed",
1830
+ error: result.error
1831
+ });
1832
+ return;
1833
+ }
1834
+ this.#setStep({
1835
+ kind: "confirm",
1836
+ preview,
1837
+ installed
1838
+ });
1839
+ toast(result.error, "error");
1840
+ return;
1841
+ }
1842
+ if (preview.offers.length > 1) {
1843
+ this.#setStep({
1844
+ kind: "confirm",
1845
+ preview,
1846
+ installed: [...installed, offer.manifest.id]
1847
+ });
1848
+ toast(`${result.value.name} ${result.value.version} is installed.`, "info");
1849
+ return;
1850
+ }
1851
+ this.#link = "";
1852
+ const link = document.getElementById("t3mode-plugin-link");
1853
+ if (link) link.value = "";
1854
+ this.#setStep({ kind: "idle" });
1855
+ toast(`${result.value.name} ${result.value.version} is installed.`, "info");
1856
+ }
1857
+ async #checkUpdates() {
1858
+ const result = await this.#runtime.checkUpdates();
1859
+ if (!result.ok) {
1860
+ toast(`Some plugins could not be checked. ${result.error}`, "error");
1861
+ return;
1862
+ }
1863
+ const updates = result.value.filter((plugin) => plugin.update !== void 0).length;
1864
+ toast(updates > 0 ? `${plural(updates, "update")} available.` : "All plugins are up to date.", "info");
1865
+ }
1866
+ async #update(plugin) {
1867
+ const result = await this.#runtime.updatePlugin(plugin.id);
1868
+ if (!result.ok && result.approval) {
1869
+ const approval = result.approval;
1870
+ const panel = h("div", { className: `${native.card} t3mode-confirm` }, h("h3", {
1871
+ className: native.rowTitle,
1872
+ text: `Approve update for ${plugin.name}`
1873
+ }), ...accessLines(result.approval).map((text) => h("p", {
1874
+ className: native.rowDescription,
1875
+ text
1876
+ })), h("div", { className: "t3mode-actions" }, button({
1877
+ text: "Approve and update",
1878
+ onClick: () => void busy(approve, async () => {
1879
+ const updated = await this.#runtime.updatePlugin(plugin.id, approval);
1880
+ toast(updated.ok ? `${updated.value.name} is updated to ${updated.value.version}.` : updated.error, updated.ok ? "info" : "error");
1881
+ panel.remove();
1882
+ })
1883
+ }), button({
1884
+ text: "Cancel",
1885
+ onClick: () => panel.remove()
1886
+ })));
1887
+ const approve = panel.querySelector("button");
1888
+ this.#body?.querySelector("[data-t3mode-approval]")?.remove();
1889
+ panel.setAttribute("data-t3mode-approval", plugin.id);
1890
+ this.#body?.prepend(panel);
1891
+ panel.scrollIntoView({ block: "nearest" });
1892
+ return;
1893
+ }
1894
+ toast(result.ok ? `${result.value.name} is updated to ${result.value.version}.` : result.error, result.ok ? "info" : "error");
1895
+ }
1896
+ async #remove(plugin) {
1897
+ const result = await this.#runtime.remove(plugin.id);
1898
+ if (!result.ok) {
1899
+ toast(result.error, "error");
1900
+ return;
1901
+ }
1902
+ toast(`${plugin.name} is removed.`, "info");
1903
+ if (this.#view.kind === "plugin") this.#go({ kind: "plugins" });
1904
+ }
1905
+ #updateButton(plugin) {
1906
+ if (plugin.update === void 0) return null;
1907
+ const control = button({
1908
+ text: `Update to ${plugin.update}`,
1909
+ icon: "download",
1910
+ variant: "outline",
1911
+ onClick: () => void busy(control, () => this.#update(plugin))
1912
+ });
1913
+ control.id = `t3mode-${plugin.id}-update`;
1914
+ return control;
1915
+ }
1916
+ #removeButton(plugin) {
1917
+ const control = button({
1918
+ text: "Remove",
1919
+ icon: "trash",
1920
+ variant: "outline",
1921
+ onClick: () => void busy(control, () => this.#remove(plugin))
1922
+ });
1923
+ control.id = `t3mode-${plugin.id}-remove`;
1924
+ return control;
1925
+ }
1926
+ #retryButton(plugin, variant) {
1927
+ if (!canRetry(this.#runtime, plugin)) return null;
1928
+ return button({
1929
+ text: "Retry",
1930
+ icon: "retry",
1931
+ variant,
1932
+ onClick: () => void this.#runtime.retry(plugin.id)
1933
+ });
1934
+ }
1935
+ #renderGrid() {
1936
+ const grid = this.#grid;
1937
+ if (!grid?.isConnected) return;
1938
+ const runtime = this.#runtime;
1939
+ const query = this.#query.trim().toLowerCase();
1940
+ const shown = runtime.plugins.filter((plugin) => {
1941
+ const on = runtime.isEnabled(plugin.id);
1942
+ if (this.#filter === "enabled" && !on) return false;
1943
+ if (this.#filter === "disabled" && on) return false;
1944
+ return query === "" || plugin.name.toLowerCase().includes(query) || plugin.description.toLowerCase().includes(query) || plugin.id.includes(query);
1945
+ });
1946
+ const count = this.#body?.querySelector(".t3mode-count");
1947
+ if (count) count.textContent = `${runtime.plugins.filter((plugin) => runtime.isEnabled(plugin.id)).length} of ${runtime.plugins.length} enabled`;
1948
+ const focusedId = document.activeElement?.id;
1949
+ grid.replaceChildren(...shown.length > 0 ? shown.map((plugin) => this.#card(plugin)) : [h("p", {
1950
+ className: `${native.rowDescription} t3mode-empty`,
1951
+ text: query ? `No plugin matches "${this.#query.trim()}".` : runtime.plugins.length === 0 ? "No plugins installed yet. Paste a plugin's GitHub link above to install it." : "No plugins here."
1952
+ })]);
1953
+ if (focusedId) document.getElementById(focusedId)?.focus();
1954
+ }
1955
+ #card(plugin) {
1956
+ const runtime = this.#runtime;
1957
+ const details = () => this.#go({
1958
+ kind: "plugin",
1959
+ id: plugin.id
1960
+ });
1961
+ const toggle = switchControl({
1962
+ label: `Enable ${plugin.name}`,
1963
+ checked: runtime.isEnabled(plugin.id),
1964
+ onChange: (checked) => void runtime.setEnabled(plugin.id, checked)
1965
+ });
1966
+ toggle.id = `t3mode-${plugin.id}-switch`;
1967
+ const settings = iconButton({
1968
+ label: `${plugin.name} settings`,
1969
+ icon: "settings",
1970
+ onClick: details
1971
+ });
1972
+ settings.id = `t3mode-${plugin.id}-details`;
1973
+ return h("article", {
1974
+ className: `${native.card} t3mode-card`,
1975
+ attrs: {
1976
+ "data-plugin": plugin.id,
1977
+ "aria-label": plugin.name
1978
+ },
1979
+ on: { click: (event) => {
1980
+ if (!event.target.closest("button, [role=switch]")) details();
1981
+ } }
1982
+ }, h("div", { className: "t3mode-card-head" }, h("h3", {
1983
+ className: `${native.rowTitle} t3mode-card-title`,
1984
+ text: plugin.name
1985
+ }), settings, toggle), h("p", {
1986
+ className: "t3mode-card-meta",
1987
+ text: `${plugin.version} · ${sourceLabel(plugin.source)}`
1988
+ }), h("p", {
1989
+ className: `${native.rowDescription} t3mode-card-description`,
1990
+ text: plugin.description
1991
+ }), h("div", { className: "t3mode-card-foot" }, statusLine(runtime, plugin), this.#updateButton(plugin), this.#retryButton(plugin, "ghost"), plugin.error === void 0 ? null : this.#removeButton(plugin)));
1992
+ }
1993
+ #renderPlugin(body, plugin) {
1994
+ const runtime = this.#runtime;
1995
+ const enabled = runtime.isEnabled(plugin.id);
1996
+ const values = runtime.options(plugin.id);
1997
+ const toggle = switchControl({
1998
+ label: `Enable ${plugin.name}`,
1999
+ checked: enabled,
2000
+ onChange: (checked) => void runtime.setEnabled(plugin.id, checked)
2001
+ });
2002
+ toggle.id = `t3mode-${plugin.id}-enabled`;
2003
+ toggle.setAttribute("data-t3mode-focus", "");
2004
+ const optionRows = Object.entries(runtime.optionSpec(plugin.id)).map(([key, option]) => {
2005
+ const label = option.label;
2006
+ const control = option.type === "boolean" ? switchControl({
2007
+ label,
2008
+ checked: values[key] === true,
2009
+ onChange: (checked) => void runtime.setOption(plugin.id, key, checked)
2010
+ }) : selectControl({
2011
+ host: this.#root ?? body,
2012
+ label,
2013
+ value: String(values[key]),
2014
+ choices: option.choices,
2015
+ onChange: (value) => void runtime.setOption(plugin.id, key, value)
2016
+ });
2017
+ control.id = `t3mode-${plugin.id}-option-${key}`;
2018
+ return row({
2019
+ title: label,
2020
+ ...option.description ? { description: option.description } : {},
2021
+ control
2022
+ });
2023
+ });
2024
+ body.append(section(plugin.name, null, group(row({
2025
+ title: "Enabled",
2026
+ description: plugin.description,
2027
+ control: toggle
2028
+ }), row({
2029
+ title: "Status",
2030
+ description: statusLine(runtime, plugin),
2031
+ control: this.#retryButton(plugin, "outline")
2032
+ }), row({
2033
+ title: "Source",
2034
+ description: this.#sourceText(plugin),
2035
+ control: fragment(this.#updateButton(plugin), this.#removeButton(plugin))
2036
+ }))), optionRows.length > 0 ? section("Options", enabled ? null : h("span", {
2037
+ className: "t3mode-count",
2038
+ text: "Applied when the plugin is on"
2039
+ }), group(...optionRows)) : section("Options", null, h("p", {
2040
+ className: `${native.rowDescription} t3mode-empty`,
2041
+ text: runtime.optionsKnown(plugin.id) ? "This plugin has no options." : "Its options show once the plugin is on. T3 Mode runs none of a plugin's code while it is off."
2042
+ })));
2043
+ const panel = runtime.panel(plugin.id);
2044
+ if (panel) {
2045
+ const host = h("div");
2046
+ body.append(section(panel.title, null, host));
2047
+ panel.render(host);
2048
+ }
2049
+ }
2050
+ #sourceText(plugin) {
2051
+ const where = plugin.source.kind === "github" ? `github.com/${sourceLabel(plugin.source)}` : `Linked from ${plugin.source.path}, read again on every reload`;
2052
+ const by = plugin.author ? ` by ${plugin.author}` : "";
2053
+ const hash = plugin.sha256 ? ` · SHA-256 ${plugin.sha256.slice(0, 12)}` : "";
2054
+ return `${where} · version ${plugin.version}${by}${hash}`;
2055
+ }
2056
+ };
2057
+ // src/lib/keybindings.ts
2058
+ /** The resolved keybindings T3 Code keeps in React state. */
2059
+ const isResolvedRules = (value) => Array.isArray(value) && value.length > 0 && value.every((rule) => typeof rule === "object" && rule !== null && typeof rule.command === "string" && typeof rule.shortcut === "object" && typeof rule.shortcut?.key === "string");
2060
+ const KEY_NAMES = {
2061
+ " ": "space",
2062
+ esc: "escape"
2063
+ };
2064
+ /** Every name the event's key goes by: its character, and its physical key for letters and digits. */
2065
+ const eventKeys = (event) => {
2066
+ const key = event.key.toLowerCase();
2067
+ const keys = /* @__PURE__ */ new Set([KEY_NAMES[key] ?? key]);
2068
+ const physical = /^Key([A-Z])$/.exec(event.code) ?? /^Digit(\d)$/.exec(event.code);
2069
+ if (physical?.[1]) keys.add(physical[1].toLowerCase());
2070
+ return keys;
2071
+ };
2072
+ const matchesShortcut = (event, shortcut, isMac) => {
2073
+ const meta = shortcut.metaKey || shortcut.modKey && isMac;
2074
+ const ctrl = shortcut.ctrlKey || shortcut.modKey && !isMac;
2075
+ return event.metaKey === meta && event.ctrlKey === ctrl && event.altKey === shortcut.altKey && event.shiftKey === shortcut.shiftKey && eventKeys(event).has(shortcut.key.toLowerCase());
2076
+ };
2077
+ const evaluateWhen = (node, context) => {
2078
+ if (!node) return true;
2079
+ switch (node.type) {
2080
+ case "identifier":
2081
+ if (node.name === "true") return true;
2082
+ if (node.name === "false") return false;
2083
+ return context[node.name] === true;
2084
+ case "not": return !evaluateWhen(node.node, context);
2085
+ case "and": return evaluateWhen(node.left, context) && evaluateWhen(node.right, context);
2086
+ case "or": return evaluateWhen(node.left, context) || evaluateWhen(node.right, context);
2087
+ }
2088
+ };
2089
+ /** The command the event triggers, as T3 Code resolves it: the last matching rule wins. */
2090
+ const resolveCommand = (event, rules, context, isMac) => {
2091
+ for (let index = rules.length - 1; index >= 0; index--) {
2092
+ const rule = rules[index];
2093
+ if (rule && evaluateWhen(rule.whenAst, context) && matchesShortcut(event, rule.shortcut, isMac)) return rule.command;
2094
+ }
2095
+ return null;
2096
+ };
2097
+ /** T3 Code's keybindings, or undefined when their shape changed. */
2098
+ const readKeybindings = () => {
2099
+ const anchor = document.querySelector("#root > *") ?? document.body.firstElementChild;
2100
+ return anchor ? findHookState(anchor, isResolvedRules) : void 0;
2101
+ };
2102
+ const isEditable = (target) => target instanceof HTMLElement && (target.isContentEditable || target.matches("input, textarea, select, [role=textbox]"));
2103
+ /** The "When" identifiers T3 Code sets from focus. Others read as false. */
2104
+ const focusContext = (event) => {
2105
+ const active = document.activeElement;
2106
+ return {
2107
+ isDesktop: true,
2108
+ isWeb: false,
2109
+ terminalFocus: active instanceof Element && active.closest(".xterm") !== null,
2110
+ terminalOpen: document.querySelector(".xterm") !== null,
2111
+ editableFocus: isEditable(event.target)
2112
+ };
2113
+ };
2114
+ const isMacPlatform = () => /mac|iphone|ipad/i.test(navigator.platform);
2115
+ // src/ui/shortcut.ts
2116
+ const MODIFIER_KEYS = /* @__PURE__ */ new Set([
2117
+ "Control",
2118
+ "Alt",
2119
+ "Shift",
2120
+ "Meta",
2121
+ "AltGraph"
2122
+ ]);
2123
+ /** Used only while T3 Code's bindings can't be read: Ctrl+Alt+M (Cmd+Alt+M on macOS). */
2124
+ const FALLBACK = {
2125
+ key: "m",
2126
+ metaKey: false,
2127
+ ctrlKey: false,
2128
+ shiftKey: false,
2129
+ altKey: true,
2130
+ modKey: true
2131
+ };
2132
+ const installShortcut = (runtime, page) => {
2133
+ ensureStyles();
2134
+ const isMac = isMacPlatform();
2135
+ let warned = false;
2136
+ window.addEventListener("keydown", (event) => {
2137
+ if (event.repeat || MODIFIER_KEYS.has(event.key)) return;
2138
+ if (!(event.ctrlKey || event.metaKey || event.altKey || /^F\d+$/.test(event.key))) return;
2139
+ if (event.target instanceof Element && event.target.closest(hookSelector(T3_HOOKS.capture))) return;
2140
+ const rules = readKeybindings();
2141
+ if (!rules && !warned) {
2142
+ warned = true;
2143
+ runtime.log("warn", "T3 Code's keybindings were not found; using Ctrl+Alt+M");
2144
+ }
2145
+ if (!(rules ? resolveCommand(event, rules, focusContext(event), isMac) === "script.t3-mode-plugins.run" : matchesShortcut(event, FALLBACK, isMac))) return;
2146
+ event.preventDefault();
2147
+ event.stopImmediatePropagation();
2148
+ page.open({ kind: "plugins" });
2149
+ }, true);
2150
+ runtime.shortcut("seed").then((status) => {
2151
+ if (status === "added") runtime.log("info", "Shortcut added to T3 Code's keybindings");
2152
+ });
2153
+ };
2154
+ // src/renderer.ts
2155
+ const describe = (error) => error instanceof Error ? error.stack ?? error.message : String(error);
2156
+ const main = async () => {
2157
+ const native = window.t3modeNative;
2158
+ if (!native || window.__t3modeRuntime) return;
2159
+ try {
2160
+ const [info, settings, installed, pluginData] = await Promise.all([
2161
+ native.info(),
2162
+ native.readSettings(),
2163
+ native.plugins.list(),
2164
+ native.readPluginData()
2165
+ ]);
2166
+ const runtime = new Runtime(native, installed, settings, info, pluginData);
2167
+ window.__t3modeRuntime = runtime;
2168
+ await runtime.followBackends();
2169
+ runtime.startAll();
2170
+ runtime.watchUpdates();
2171
+ const page = new SettingsPage(runtime);
2172
+ installShortcut(runtime, page);
2173
+ let frame = 0;
2174
+ const sync = () => {
2175
+ frame = 0;
2176
+ try {
2177
+ page.sync();
2178
+ } catch (error) {
2179
+ runtime.log("warn", `Settings page failed: ${describe(error)}`);
2180
+ }
2181
+ };
2182
+ new MutationObserver(() => {
2183
+ if (frame === 0) frame = requestAnimationFrame(sync);
2184
+ }).observe(document.body, {
2185
+ childList: true,
2186
+ subtree: true
2187
+ });
2188
+ sync();
2189
+ await native.ready();
2190
+ await native.log("info", `Runtime started on T3 Code ${info.t3codeVersion} with ${installed.length} plugin${installed.length === 1 ? "" : "s"}`);
2191
+ } catch (error) {
2192
+ await native.log("error", `Runtime failed to start: ${describe(error)}`).catch(() => void 0);
2193
+ toast("T3 Mode failed to start. See its log in the logs folder.", "error");
2194
+ }
2195
+ };
2196
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", () => void main(), { once: true });
2197
+ else main();
2198
+ })();