@kubohiroya/turbowarp-title-menu 0.2.6 → 0.4.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.
@@ -7,1625 +7,1625 @@
7
7
  (function (Scratch) {
8
8
  'use strict';
9
9
 
10
- //#region node_modules/.pnpm/@kubohiroya+turbowarp-app-shell@0.3.1/node_modules/@kubohiroya/turbowarp-app-shell/dist/index.js
11
- function isRecord$1(value) {
12
- return typeof value === "object" && value !== null && !Array.isArray(value);
13
- }
14
- function requireElement$1(value, name) {
15
- if (!isRecord$1(value) || typeof value["appendChild"] !== "function") throw new TypeError(`${name} must be a DOM element.`);
16
- return value;
17
- }
18
- function requireDocument$1(value) {
19
- if (!isRecord$1(value) || typeof value["createElement"] !== "function") throw new TypeError("document must provide the DOM document contract.");
20
- return value;
21
- }
22
- function requireString(value, name) {
23
- if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
24
- return value;
25
- }
26
- function optionalBoolean(value, name, fallback) {
27
- if (value === void 0) return fallback;
28
- if (typeof value !== "boolean") throw new TypeError(`${name} must be a boolean.`);
29
- return value;
30
- }
31
- function optionalString(value, name) {
32
- if (value === void 0) return void 0;
33
- if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
34
- return value;
35
- }
36
- function requireLocalizedLabels(value, name) {
37
- if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
38
- const entries = Object.entries(value);
39
- if (entries.length === 0) throw new TypeError(`${name} must include at least one locale.`);
40
- for (const [locale, label] of entries) if (typeof label !== "string" || label.length === 0) throw new TypeError(`${name}.${locale} must be a non-empty string.`);
41
- return value;
42
- }
43
- function firstLocale(locales, name) {
44
- const [locale] = Object.keys(locales);
45
- if (locale === void 0) throw new TypeError(`${name} must include at least one locale.`);
46
- return locale;
47
- }
48
- function resolveInjectedLocale(locales, requested, fallback, name) {
49
- if (requested !== void 0 && Object.hasOwn(locales, requested)) return requested;
50
- if (fallback !== void 0 && Object.hasOwn(locales, fallback)) return fallback;
51
- if (Object.hasOwn(locales, "en")) return "en";
52
- return firstLocale(locales, name);
53
- }
54
- function localized(locales, locale, fallback, name) {
55
- return locales[resolveInjectedLocale(locales, locale, fallback, name)];
56
- }
57
- function requireIcon(value, name) {
58
- if (value === void 0) return void 0;
59
- if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
60
- const url = optionalString(value["url"], `${name}.url`);
61
- const text = optionalString(value["text"], `${name}.text`);
62
- const filter = optionalString(value["filter"], `${name}.filter`);
63
- const size = optionalString(value["size"], `${name}.size`);
64
- const fontSize = optionalString(value["fontSize"], `${name}.fontSize`);
65
- if ((url === void 0 || url.length === 0) && (text === void 0 || text.length === 0)) throw new TypeError(`${name} must include a non-empty url or text.`);
66
- return {
67
- ...url === void 0 ? {} : { url },
68
- ...text === void 0 ? {} : { text },
69
- ...filter === void 0 ? {} : { filter },
70
- ...size === void 0 ? {} : { size },
71
- ...fontSize === void 0 ? {} : { fontSize }
72
- };
73
- }
74
- function requireAttributes(value, name) {
75
- if (value === void 0) return void 0;
76
- if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
77
- for (const [attribute, attributeValue] of Object.entries(value)) {
78
- if (attribute.length === 0) throw new TypeError(`${name} names must be non-empty.`);
79
- if (typeof attributeValue !== "string") throw new TypeError(`${name}.${attribute} must be a string.`);
80
- }
81
- return value;
82
- }
83
- function applyAttributes(element, attributes) {
84
- if (attributes === void 0) return;
85
- for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
86
- }
87
- function requireRect(value, name) {
88
- if (value === void 0) return void 0;
89
- if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
90
- const left = optionalString(value["left"], `${name}.left`);
91
- const top = optionalString(value["top"], `${name}.top`);
92
- const width = optionalString(value["width"], `${name}.width`);
93
- const height = optionalString(value["height"], `${name}.height`);
94
- return {
95
- ...left === void 0 ? {} : { left },
96
- ...top === void 0 ? {} : { top },
97
- ...width === void 0 ? {} : { width },
98
- ...height === void 0 ? {} : { height }
99
- };
100
- }
101
- function applyRect(element, rect) {
102
- if (rect === void 0) return;
103
- if (rect.left !== void 0) element.style.left = rect.left;
104
- if (rect.top !== void 0) element.style.top = rect.top;
105
- if (rect.width !== void 0) element.style.width = rect.width;
106
- if (rect.height !== void 0) element.style.height = rect.height;
107
- }
108
- function requireTestId(value, name) {
109
- if (value === void 0) return void 0;
110
- if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
111
- return value;
112
- }
113
- function applyTestId(element, testId) {
114
- if (testId !== void 0) element.setAttribute("data-testid", testId);
115
- }
116
- function restoreableMountPosition(document, mount) {
117
- if (mount === document.body) return null;
118
- const previous = mount.style.position;
119
- if (previous === void 0 || previous === "" || previous === "static") {
120
- mount.style.position = "relative";
121
- return () => {
122
- mount.style.position = previous ?? "";
123
- };
124
- }
125
- return null;
126
- }
127
- function setButtonEnabled(button, enabled) {
128
- button.disabled = !enabled;
129
- button.setAttribute("aria-disabled", String(!enabled));
130
- button.style.cursor = enabled ? "pointer" : "not-allowed";
131
- button.style.opacity = enabled ? "1" : "0.42";
132
- }
133
- function setElementVisible(element, visible, display) {
134
- element.hidden = !visible;
135
- element.style.display = visible ? display : "none";
136
- }
137
- function reportActionError(onError, error) {
138
- try {
139
- onError?.(error);
140
- } catch {}
141
- }
142
- function invokeAction(action, onError, event) {
143
- event?.preventDefault();
144
- event?.stopPropagation();
145
- try {
146
- Promise.resolve(action()).catch((error) => {
147
- reportActionError(onError, error);
148
- });
149
- } catch (error) {
150
- reportActionError(onError, error);
151
- }
152
- }
153
- function iconCssUrl(url) {
154
- return `url("${url.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}")`;
155
- }
156
- function renderIcon(element, icon) {
157
- element.textContent = "";
158
- element.style.backgroundImage = "";
159
- element.style.display = icon === void 0 ? "none" : "inline-flex";
160
- if (icon === void 0) return;
161
- element.style.filter = icon.filter ?? "";
162
- if (icon.size !== void 0) {
163
- element.style.width = icon.size;
164
- element.style.height = icon.size;
165
- }
166
- if (icon.fontSize !== void 0) element.style.fontSize = icon.fontSize;
167
- if (icon.url !== void 0) {
168
- element.style.backgroundImage = iconCssUrl(icon.url);
169
- element.style.backgroundPosition = "center";
170
- element.style.backgroundRepeat = "no-repeat";
171
- element.style.backgroundSize = "contain";
172
- return;
173
- }
174
- element.textContent = icon.text ?? "";
175
- }
176
- function loadingTone(tone) {
177
- if (tone === "warning") return "#805300";
178
- if (tone === "error") return "#a00020";
179
- if (tone === "info") return "#176e9f";
180
- return "#35524c";
181
- }
182
- function resolveAppShellLocale(input) {
183
- const preferred = input?.language ?? input?.languages?.[0] ?? globalThis.navigator?.language ?? "";
184
- return /^ja(?:-|$)/iu.test(preferred) ? "ja" : "en";
185
- }
186
- function boundedText(value, limit = 2e3) {
187
- const text = String(value ?? "");
188
- const scalars = [...text];
189
- return scalars.length <= limit ? text : `${scalars.slice(0, limit - 1).join("")}...`;
190
- }
191
- /**
192
- * Where the application menu places its actions: two columns of up to two rows, as it always has,
193
- * and more columns and rows when there are more actions, so that every action stays on the stage.
194
- * The band starts under the title area and ends above the status row; labels and icons shrink with
195
- * the cells. An action's own `position` still overrides its cell.
196
- */
197
- function applicationMenuGrid(count) {
198
- const columns = count <= 4 ? 2 : count <= 12 ? 3 : 4;
199
- const rows = Math.ceil(count / columns);
200
- const top = 25.5556;
201
- const bottom = rows <= 2 ? 80 : 90;
202
- const gapX = columns === 2 ? 6.6667 : 3.3333;
203
- const gapY = rows <= 2 ? 5.5556 : 2.7778;
204
- const width = (80 - (columns - 1) * gapX) / columns;
205
- const height = (bottom - top - (rows - 1) * gapY) / rows;
206
- const scale = Math.min(1, width / 36.6667, height / 24.4444);
207
- const percent = (value) => `${Number(value.toFixed(4))}%`;
208
- return {
209
- cell(index) {
210
- const row = Math.floor(index / columns);
211
- const column = index % columns;
212
- if (count <= 4) return {
213
- left: column === 0 ? "10%" : "53.3333%",
214
- top: `${25.5556 + row * 30}%`,
215
- width: "36.6667%",
216
- height: "24.4444%"
217
- };
218
- return {
219
- left: percent(10 + column * (width + gapX)),
220
- top: percent(top + row * (height + gapY)),
221
- width: percent(width),
222
- height: percent(height)
223
- };
224
- },
225
- cqw(size) {
226
- return `${count <= 4 ? size : Number((size * scale).toFixed(4))}cqw`;
227
- }
228
- };
229
- }
230
- function createAppShellApplicationMenu(options) {
231
- if (!isRecord$1(options)) throw new TypeError("application menu options must be an object.");
232
- const document = requireDocument$1(options.document);
233
- const mount = requireElement$1(options.mount, "mount");
234
- if (!Array.isArray(options.actions) || options.actions.length === 0) throw new TypeError("actions must include at least one menu action.");
235
- const fallbackLocale = optionalString(options.fallbackLocale, "fallbackLocale");
236
- const rootTestId = requireTestId(options.rootTestId, "rootTestId");
237
- const statusTestId = requireTestId(options.statusTestId, "statusTestId");
238
- const menuAttributes = options.attributes ?? {};
239
- if (!isRecord$1(menuAttributes)) throw new TypeError("attributes must be an object.");
240
- const rootAttributes = requireAttributes(menuAttributes.root, "attributes.root");
241
- const statusAttributes = requireAttributes(menuAttributes.status, "attributes.status");
242
- const root = document.createElement("section");
243
- const status = document.createElement("p");
244
- const restoreMountPosition = restoreableMountPosition(document, mount);
245
- root.setAttribute("data-turbowarp-app-shell-application-menu", "true");
246
- root.setAttribute("aria-label", options.ariaLabel ?? "Application menu");
247
- root.style.cssText = "position:absolute;inset:0;z-index:2147483600;display:none;box-sizing:border-box;overflow:hidden;pointer-events:auto;font-family:sans-serif;container-type:inline-size;";
248
- root.style.position = "absolute";
249
- root.style.display = "none";
250
- root.style.cursor = "pointer";
251
- applyTestId(root, rootTestId);
252
- applyAttributes(root, rootAttributes);
253
- status.setAttribute("data-turbowarp-app-shell-menu-status", "true");
254
- status.setAttribute("role", "status");
255
- status.setAttribute("aria-live", "polite");
256
- status.style.cssText = "position:absolute;left:10%;top:93%;width:80%;margin:0;color:#35524c;font-size:2.7cqw;line-height:1.1;text-align:center;";
257
- applyTestId(status, statusTestId);
258
- applyAttributes(status, statusAttributes);
259
- const buttons = /* @__PURE__ */ new Map();
260
- const seen = /* @__PURE__ */ new Set();
261
- let locale = optionalString(options.initialLocale, "initialLocale") ?? resolveAppShellLocale();
262
- const grid = applicationMenuGrid(options.actions.length);
263
- for (const [index, definition] of options.actions.entries()) {
264
- if (!isRecord$1(definition)) throw new TypeError(`actions.${index} must be an object.`);
265
- const id = requireString(definition.id, `actions.${index}.id`);
266
- if (seen.has(id)) throw new TypeError(`Duplicate application menu action id: ${id}.`);
267
- seen.add(id);
268
- const labels = requireLocalizedLabels(definition.labels, `actions.${index}.labels`);
269
- const icon = requireIcon(definition.icon, `actions.${index}.icon`);
270
- const enabled = optionalBoolean(definition.enabled, `actions.${index}.enabled`, true);
271
- const visible = optionalBoolean(definition.visible, `actions.${index}.visible`, true);
272
- const testId = requireTestId(definition.testId, `actions.${index}.testId`);
273
- const position = requireRect(definition.position, `actions.${index}.position`);
274
- const actionAttributes = requireAttributes(definition.attributes, `actions.${index}.attributes`);
275
- if (typeof definition.onSelect !== "function") throw new TypeError(`actions.${index}.onSelect must be a function.`);
276
- const onSelect = definition.onSelect;
277
- const button = document.createElement("button");
278
- const iconElement = document.createElement("span");
279
- const label = document.createElement("span");
280
- const cell = grid.cell(index);
281
- button.type = "button";
282
- button.setAttribute("data-turbowarp-app-shell-menu-action", id);
283
- button.style.cssText = `position:absolute;left:${cell.left};top:${cell.top};width:${cell.width};height:${cell.height};display:flex;min-width:0;min-height:0;align-items:center;justify-content:center;flex-direction:column;gap:.4167cqw;border:.4167cqw solid #005f50;border-radius:2.9167cqw;background:#007d66;color:#fff;box-shadow:0 .625cqw 1.6667cqw rgba(0,0,0,.2);cursor:pointer;font:inherit;`;
284
- button.style.cursor = "pointer";
285
- applyTestId(button, testId);
286
- applyAttributes(button, actionAttributes);
287
- iconElement.setAttribute("aria-hidden", "true");
288
- iconElement.style.cssText = `display:inline-flex;width:${grid.cqw(10)};height:${grid.cqw(10)};align-items:center;justify-content:center;line-height:1;font-size:${grid.cqw(6)};`;
289
- label.style.cssText = `font-size:${grid.cqw(3.8)};line-height:1.15;text-align:center;`;
290
- button.appendChild(iconElement);
291
- button.appendChild(label);
292
- const onClick = (event) => {
293
- const current = buttons.get(id);
294
- if (current === void 0 || !current.enabled || !current.visible) return;
295
- invokeAction(current.onSelect, options.onError, event);
296
- };
297
- button.addEventListener("click", onClick);
298
- buttons.set(id, {
299
- button,
300
- icon: iconElement,
301
- label,
302
- labels,
303
- iconDefinition: icon,
304
- enabled,
305
- visible,
306
- position,
307
- onSelect,
308
- onClick
309
- });
310
- root.appendChild(button);
311
- }
312
- root.appendChild(status);
313
- mount.appendChild(root);
314
- let statusState = {
315
- text: options.status?.text ?? "",
316
- visible: options.status?.visible ?? false,
317
- tone: options.status?.tone ?? "neutral",
318
- color: optionalString(options.status?.color, "status.color")
319
- };
320
- if (typeof statusState.text !== "string") throw new TypeError("status.text must be a string.");
321
- if (typeof statusState.visible !== "boolean") throw new TypeError("status.visible must be a boolean.");
322
- if (![
323
- "neutral",
324
- "info",
325
- "warning",
326
- "error"
327
- ].includes(statusState.tone)) throw new TypeError("status.tone must be neutral, info, warning, or error.");
328
- let disposed = false;
329
- function renderMenu() {
330
- for (const [id, value] of buttons) {
331
- const label = localized(value.labels, locale, fallbackLocale, `menu action ${id} labels`);
332
- value.label.textContent = label;
333
- value.button.setAttribute("aria-label", label);
334
- renderIcon(value.icon, value.iconDefinition);
335
- setButtonEnabled(value.button, value.enabled);
336
- setElementVisible(value.button, value.visible, "flex");
337
- value.button.style.boxShadow = value.enabled ? "0 .625cqw 1.6667cqw rgba(0,0,0,.2)" : "none";
338
- applyRect(value.button, value.position);
339
- }
340
- status.textContent = boundedText(statusState.text, 500);
341
- status.style.color = statusState.color ?? loadingTone(statusState.tone);
342
- setElementVisible(status, statusState.visible && statusState.text.length > 0, "block");
343
- }
344
- function ensureActive() {
345
- if (disposed) throw new TypeError("application menu is disposed.");
346
- }
347
- renderMenu();
348
- return Object.freeze({
349
- show(nextLocale) {
350
- ensureActive();
351
- locale = optionalString(nextLocale, "nextLocale") ?? locale;
352
- renderMenu();
353
- root.style.display = "block";
354
- return locale;
355
- },
356
- hide() {
357
- if (!disposed) root.style.display = "none";
358
- },
359
- setLocale(nextLocale) {
360
- ensureActive();
361
- locale = requireString(nextLocale, "nextLocale");
362
- renderMenu();
363
- return locale;
364
- },
365
- setActionState(id, state) {
366
- ensureActive();
367
- const action = buttons.get(requireString(id, "action id"));
368
- if (action === void 0) throw new TypeError(`Unknown application menu action: ${id}.`);
369
- if (!isRecord$1(state)) throw new TypeError("application menu action state must be an object.");
370
- if (state.enabled !== void 0) {
371
- if (typeof state.enabled !== "boolean") throw new TypeError("action enabled must be a boolean.");
372
- action.enabled = state.enabled;
373
- }
374
- if (state.visible !== void 0) {
375
- if (typeof state.visible !== "boolean") throw new TypeError("action visible must be a boolean.");
376
- action.visible = state.visible;
377
- }
378
- if (state.labels !== void 0) action.labels = requireLocalizedLabels(state.labels, "action state labels");
379
- if (state.icon !== void 0) action.iconDefinition = requireIcon(state.icon, "action state icon");
380
- if (state.position !== void 0) action.position = requireRect(state.position, "action state position");
381
- renderMenu();
382
- },
383
- setStatus(nextStatus) {
384
- ensureActive();
385
- if (!isRecord$1(nextStatus)) throw new TypeError("application menu status must be an object.");
386
- const nextToneValue = nextStatus["tone"] ?? statusState.tone;
387
- if (![
388
- "neutral",
389
- "info",
390
- "warning",
391
- "error"
392
- ].includes(String(nextToneValue))) throw new TypeError("status.tone must be neutral, info, warning, or error.");
393
- const nextTone = nextToneValue;
394
- statusState = {
395
- text: optionalString(nextStatus["text"], "status.text") ?? statusState.text,
396
- visible: optionalBoolean(nextStatus["visible"], "status.visible", statusState.visible),
397
- tone: nextTone,
398
- color: optionalString(nextStatus["color"], "status.color") ?? statusState.color
399
- };
400
- renderMenu();
401
- },
402
- dispose() {
403
- if (disposed) return;
404
- disposed = true;
405
- for (const { button, onClick } of buttons.values()) button.removeEventListener("click", onClick);
406
- buttons.clear();
407
- root.remove();
408
- restoreMountPosition?.();
409
- },
410
- get element() {
411
- return root;
412
- }
413
- });
414
- }
415
- //#endregion
416
- //#region src/config.ts
417
- var extensionConfig = {
418
- id: "kubohiroyaturbowarptitlemenu",
419
- slug: "turbowarp-title-menu",
420
- name: "TurboWarp Title Menu",
421
- description: "Reusable title, application menu, and DSL source storage controls for TurboWarp.",
422
- author: "Hiroya Kubo",
423
- license: "MPL-2.0",
424
- unsandboxed: true,
425
- homepage: "https://github.com/kubohiroya/turbowarp-title-menu",
426
- docsURI: "https://kubohiroya.github.io/turbowarp-title-menu/",
427
- blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNSIgeT0iOCIgd2lkdGg9IjM4IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzAwN2Q2NiIvPjxyZWN0IHg9IjkiIHk9IjEyIiB3aWR0aD0iMzAiIGhlaWdodD0iMjQiIHJ4PSIyIiBmaWxsPSIjZjRmZmZiIi8+PHBhdGggZD0iTTE1IDE5aDE4TTE1IDI0aDE4TTE1IDI5aDEyIiBzdHJva2U9IiMwMDdkNjYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PC9zdmc+"
428
- };
429
- //#endregion
430
- //#region src/dom.ts
431
- function isRecord(value) {
432
- return typeof value === "object" && value !== null && !Array.isArray(value);
433
- }
434
- function requireDocument(value) {
435
- if (!isRecord(value) || typeof value.createElement !== "function") throw new TypeError("document must provide createElement");
436
- return value;
437
- }
438
- function requireElement(value, name) {
439
- if (!isRecord(value) || typeof value.appendChild !== "function") throw new TypeError(`${name} must be a DOM element`);
440
- return value;
441
- }
442
- function ensureRelativeMount(mount) {
443
- const previous = mount.style.position;
444
- if (previous === "" || previous === "static") {
445
- mount.style.position = "relative";
446
- return () => {
447
- mount.style.position = previous;
448
- };
449
- }
450
- return () => {};
451
- }
452
- function invokeSafely(operation, onError) {
453
- try {
454
- Promise.resolve(operation()).catch((error) => onError?.(error));
455
- } catch (error) {
456
- onError?.(error);
457
- }
458
- }
459
- //#endregion
460
- //#region src/dsl-store.ts
461
- var DslStoreError = class extends Error {
462
- constructor(code, message, cause) {
463
- super(message, cause === void 0 ? void 0 : { cause });
464
- this.name = "DslStoreError";
465
- this.code = code;
466
- }
467
- };
468
- var defaultDslSort = Object.freeze({
469
- field: "updatedAt",
470
- direction: "desc"
471
- });
472
- var fileStoreName = "files";
473
- var metaStoreName = "meta";
474
- var lastOpenedKey = "last-opened";
475
- var nameIndexName = "by-name";
476
- var encoder = new TextEncoder();
477
- var maximumNameLength = 200;
478
- /** Rejects control characters so a name cannot break the dialog's text rendering. */
479
- function hasControlCharacter(value) {
480
- for (const character of value) {
481
- const code = character.codePointAt(0) ?? 0;
482
- if (code < 32 || code === 127) return true;
483
- }
484
- return false;
485
- }
486
- function normalizeName(value) {
487
- if (typeof value !== "string") throw new DslStoreError("invalid-name", "DSL name must be a string.");
488
- const name = value.trim();
489
- if (name.length === 0) throw new DslStoreError("invalid-name", "DSL name must not be empty.");
490
- if (name.length > maximumNameLength) throw new DslStoreError("invalid-name", `DSL name must be at most ${maximumNameLength} characters.`);
491
- if (hasControlCharacter(name)) throw new DslStoreError("invalid-name", "DSL name must not contain control characters.");
492
- return name;
493
- }
494
- function request(input) {
495
- return new Promise((resolve, reject) => {
496
- input.onsuccess = () => resolve(input.result);
497
- input.onerror = () => reject(toStoreError(input.error));
498
- });
499
- }
500
- function transactionDone(transaction) {
501
- return new Promise((resolve, reject) => {
502
- transaction.oncomplete = () => resolve();
503
- transaction.onabort = () => reject(toStoreError(transaction.error));
504
- transaction.onerror = () => reject(toStoreError(transaction.error));
505
- });
506
- }
507
- function toStoreError(cause) {
508
- const name = cause?.name;
509
- if (name === "QuotaExceededError") return new DslStoreError("quota", "Browser storage is full. Delete a saved DSL file first.", cause);
510
- if (name === "ConstraintError") return new DslStoreError("name-taken", "A DSL file with that name already exists.", cause);
511
- return new DslStoreError("failed", "The DSL storage operation failed.", cause);
512
- }
513
- function compareSummaries(sort) {
514
- const direction = sort.direction === "asc" ? 1 : -1;
515
- return (left, right) => {
516
- if (sort.field === "name") return direction * left.name.localeCompare(right.name, void 0, { numeric: true });
517
- if (sort.field === "byteLength") return direction * (left.byteLength - right.byteLength) || left.name.localeCompare(right.name);
518
- return direction * left.updatedAt.localeCompare(right.updatedAt) || left.name.localeCompare(right.name);
519
- };
520
- }
521
- function toSummary(record) {
522
- return {
523
- id: record.id,
524
- name: record.name,
525
- byteLength: record.byteLength,
526
- savedAt: record.savedAt,
527
- updatedAt: record.updatedAt
528
- };
529
- }
530
- function createDslStore(options = {}) {
531
- const factory = options.indexedDB ?? globalThis.indexedDB;
532
- if (factory === void 0 || typeof factory.open !== "function") throw new DslStoreError("unavailable", "IndexedDB is not available in this environment.");
533
- const databaseName = options.databaseName ?? "turbowarp-title-menu";
534
- const maxSourceBytes = options.maxSourceBytes ?? 1048576;
535
- const maxFileCount = options.maxFileCount ?? 64;
536
- const now = options.now ?? (() => /* @__PURE__ */ new Date());
537
- const createId = options.createId ?? defaultCreateId;
538
- let connection = null;
539
- function open() {
540
- connection ?? (connection = new Promise((resolve, reject) => {
541
- const opening = factory.open(databaseName, 1);
542
- opening.onupgradeneeded = () => {
543
- const database = opening.result;
544
- if (!database.objectStoreNames.contains(fileStoreName)) database.createObjectStore(fileStoreName, { keyPath: "id" }).createIndex(nameIndexName, "name", { unique: true });
545
- if (!database.objectStoreNames.contains(metaStoreName)) database.createObjectStore(metaStoreName, { keyPath: "key" });
546
- };
547
- opening.onsuccess = () => resolve(opening.result);
548
- opening.onerror = () => reject(toStoreError(opening.error));
549
- opening.onblocked = () => reject(new DslStoreError("failed", "Another tab is upgrading the DSL database."));
550
- }));
551
- return connection;
552
- }
553
- async function readAll() {
554
- const transaction = (await open()).transaction(fileStoreName, "readonly");
555
- const records = await request(transaction.objectStore(fileStoreName).getAll());
556
- await transactionDone(transaction);
557
- return records;
558
- }
559
- async function readOne(id) {
560
- const transaction = (await open()).transaction(fileStoreName, "readonly");
561
- const record = await request(transaction.objectStore(fileStoreName).get(id));
562
- await transactionDone(transaction);
563
- return record ?? null;
564
- }
565
- return Object.freeze({
566
- databaseName,
567
- async list(sort = defaultDslSort) {
568
- return (await readAll()).map(toSummary).sort(compareSummaries(sort));
569
- },
570
- async count() {
571
- const transaction = (await open()).transaction(fileStoreName, "readonly");
572
- const total = await request(transaction.objectStore(fileStoreName).count());
573
- await transactionDone(transaction);
574
- return total;
575
- },
576
- get(id) {
577
- return readOne(id);
578
- },
579
- async save(file) {
580
- const name = normalizeName(file.name);
581
- if (typeof file.source !== "string") throw new DslStoreError("invalid-source", "DSL source must be a string.");
582
- const byteLength = encoder.encode(file.source).byteLength;
583
- if (byteLength > maxSourceBytes) throw new DslStoreError("too-large", `DSL source exceeds ${maxSourceBytes} bytes.`);
584
- const transaction = (await open()).transaction(fileStoreName, "readwrite");
585
- const files = transaction.objectStore(fileStoreName);
586
- const existing = await request(files.index(nameIndexName).get(name));
587
- if (existing === void 0) {
588
- if (await request(files.count()) >= maxFileCount) {
589
- transaction.abort();
590
- throw new DslStoreError("too-many", `The DSL store already holds ${maxFileCount} files.`);
591
- }
592
- }
593
- const timestamp = now().toISOString();
594
- const record = {
595
- id: existing?.id ?? createId(),
596
- name,
597
- source: file.source,
598
- byteLength,
599
- savedAt: existing?.savedAt ?? timestamp,
600
- updatedAt: timestamp
601
- };
602
- await request(files.put(record));
603
- await transactionDone(transaction);
604
- return record;
605
- },
606
- async rename(id, nextName) {
607
- const name = normalizeName(nextName);
608
- const transaction = (await open()).transaction(fileStoreName, "readwrite");
609
- const files = transaction.objectStore(fileStoreName);
610
- const existing = await request(files.get(id));
611
- if (existing === void 0) {
612
- transaction.abort();
613
- throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
614
- }
615
- if (existing.name !== name) {
616
- if (await request(files.index(nameIndexName).get(name)) !== void 0) {
617
- transaction.abort();
618
- throw new DslStoreError("name-taken", `A DSL file named ${name} already exists.`);
619
- }
620
- }
621
- const record = {
622
- ...existing,
623
- name,
624
- updatedAt: now().toISOString()
625
- };
626
- await request(files.put(record));
627
- await transactionDone(transaction);
628
- return record;
629
- },
630
- async remove(id) {
631
- const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
632
- await request(transaction.objectStore(fileStoreName).delete(id));
633
- const meta = transaction.objectStore(metaStoreName);
634
- if ((await request(meta.get(lastOpenedKey)))?.id === id) await request(meta.delete(lastOpenedKey));
635
- await transactionDone(transaction);
636
- },
637
- async clear() {
638
- const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
639
- await request(transaction.objectStore(fileStoreName).clear());
640
- await request(transaction.objectStore(metaStoreName).clear());
641
- await transactionDone(transaction);
642
- },
643
- async lastOpened() {
644
- const transaction = (await open()).transaction(metaStoreName, "readonly");
645
- const pointer = await request(transaction.objectStore(metaStoreName).get(lastOpenedKey));
646
- await transactionDone(transaction);
647
- if (pointer === void 0) return null;
648
- return readOne(pointer.id);
649
- },
650
- async markOpened(id) {
651
- if (await readOne(id) === null) throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
652
- const transaction = (await open()).transaction(metaStoreName, "readwrite");
653
- await request(transaction.objectStore(metaStoreName).put({
654
- key: lastOpenedKey,
655
- id
656
- }));
657
- await transactionDone(transaction);
658
- },
659
- close() {
660
- const pending = connection;
661
- connection = null;
662
- pending?.then((database) => database.close()).catch(() => void 0);
663
- }
664
- });
665
- }
666
- function defaultCreateId() {
667
- const crypto = globalThis.crypto;
668
- if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
669
- return `dsl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
670
- }
671
- /** Reads a picked browser file into a record shape the store accepts. */
672
- async function readDslFile(file, maxSourceBytes = 1048576) {
673
- if (typeof file?.text !== "function") throw new DslStoreError("invalid-source", "file must be a browser File.");
674
- if (file.size > maxSourceBytes) throw new DslStoreError("too-large", `DSL file exceeds ${maxSourceBytes} bytes.`);
675
- return {
676
- name: file.name,
677
- source: await file.text()
678
- };
679
- }
680
- //#endregion
681
- //#region src/dsl-files-dialog.ts
682
- var defaultSortDirections = Object.freeze({
683
- name: "asc",
684
- updatedAt: "desc",
685
- byteLength: "desc"
686
- });
687
- function requireLocales(value) {
688
- if (!isRecord(value) || Object.keys(value).length === 0) throw new TypeError("locales must contain at least one locale");
689
- return value;
690
- }
691
- function textFor(locales, locale) {
692
- const text = locales[locale] ?? locales["en"] ?? Object.values(locales)[0];
693
- if (text === void 0) throw new TypeError("locales must contain at least one locale");
694
- return text;
695
- }
696
- function defaultFormatSize(byteLength) {
697
- if (byteLength < 1024) return `${byteLength} B`;
698
- if (byteLength < 1048576) return `${(byteLength / 1024).toFixed(1)} KB`;
699
- return `${(byteLength / 1048576).toFixed(1)} MB`;
700
- }
701
- function defaultFormatDate(isoDate) {
702
- const parsed = new Date(isoDate);
703
- if (Number.isNaN(parsed.getTime())) return isoDate;
704
- const pad = (value) => String(value).padStart(2, "0");
705
- return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
706
- }
707
- function defaultDescribeError(error) {
708
- if (error instanceof Error && error.message.length > 0) return error.message;
709
- return String(error);
710
- }
711
- function createDslFilesDialog(options) {
712
- if (!isRecord(options)) throw new TypeError("DSL files dialog options must be an object");
713
- const document = requireDocument(options.document ?? globalThis.document);
714
- const mount = requireElement(options.mount ?? document.body, "mount");
715
- const locales = requireLocales(options.locales);
716
- const describeError = options.describeError ?? defaultDescribeError;
717
- const formatSize = options.formatSize ?? defaultFormatSize;
718
- const formatDate = options.formatDate ?? defaultFormatDate;
719
- let locale = options.initialLocale ?? "en";
720
- let sort = options.initialSort ?? defaultDslSort;
721
- let summaries = [];
722
- let renamingId = null;
723
- let confirmingRemovalId = null;
724
- let status = "";
725
- let disposed = false;
726
- const root = document.createElement("section");
727
- const panel = document.createElement("div");
728
- const heading = document.createElement("h1");
729
- const closeButton = document.createElement("button");
730
- const toolbar = document.createElement("div");
731
- const addButton = document.createElement("button");
732
- const sortBar = document.createElement("div");
733
- const listElement = document.createElement("div");
734
- const statusElement = document.createElement("p");
735
- root.setAttribute("data-turbowarp-title-menu-dsl-files", "true");
736
- root.style.cssText = "position:absolute;inset:0;z-index:2147483646;align-items:center;justify-content:center;padding:16px;box-sizing:border-box;background:rgba(0,0,0,.6);font-family:sans-serif;";
737
- root.style.display = "none";
738
- panel.style.cssText = "width:min(720px,96%);max-height:90%;display:flex;flex-direction:column;gap:10px;padding:18px;box-sizing:border-box;background:#ffffff;color:#1b1f27;border-radius:10px;box-shadow:0 10px 36px rgba(0,0,0,.45);overflow:hidden;";
739
- heading.style.cssText = "margin:0;font-size:20px;line-height:1.3;";
740
- toolbar.style.cssText = "display:flex;gap:8px;align-items:center;flex-wrap:wrap;";
741
- sortBar.style.cssText = "display:flex;gap:6px;align-items:center;flex-wrap:wrap;";
742
- listElement.style.cssText = "flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:6px;";
743
- statusElement.style.cssText = "margin:0;min-height:18px;font-size:13px;color:#8a1c1c;";
744
- const headerRow = document.createElement("div");
745
- headerRow.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:8px;";
746
- headerRow.appendChild(heading);
747
- headerRow.appendChild(closeButton);
748
- panel.appendChild(headerRow);
749
- toolbar.appendChild(addButton);
750
- toolbar.appendChild(sortBar);
751
- panel.appendChild(toolbar);
752
- panel.appendChild(listElement);
753
- panel.appendChild(statusElement);
754
- root.appendChild(panel);
755
- const previousMountPosition = mount.style.position;
756
- if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = "relative";
757
- mount.appendChild(root);
758
- function styleButton(button, tone) {
759
- const palette = {
760
- primary: "background:#1f6feb;color:#ffffff;border:1px solid #1f6feb;",
761
- plain: "background:#f2f4f8;color:#1b1f27;border:1px solid #ccd2de;",
762
- danger: "background:#b42318;color:#ffffff;border:1px solid #b42318;",
763
- active: "background:#d7e6ff;color:#0b3a82;border:1px solid #1f6feb;"
764
- }[tone];
765
- button.style.cssText = `${palette}padding:5px 10px;border-radius:6px;font-size:13px;cursor:pointer;`;
766
- }
767
- function run(operation) {
768
- try {
769
- Promise.resolve(operation()).catch(handleFailure);
770
- } catch (error) {
771
- handleFailure(error);
772
- }
773
- }
774
- function handleFailure(error) {
775
- status = describeError(error);
776
- options.onError?.(error);
777
- render();
778
- }
779
- /** Every mutation goes through here so the list and the status line stay in step. */
780
- function mutate(operation) {
781
- run(async () => {
782
- status = "";
783
- try {
784
- await operation();
785
- } catch (error) {
786
- status = describeError(error);
787
- options.onError?.(error);
788
- render();
789
- return;
790
- }
791
- await reload();
792
- });
793
- }
794
- async function reload() {
795
- if (disposed) return;
796
- summaries = await options.list(sort);
797
- render();
798
- }
799
- function selectSort(field) {
800
- if (sort.field === field) sort = {
801
- field,
802
- direction: sort.direction === "asc" ? "desc" : "asc"
803
- };
804
- else sort = {
805
- field,
806
- direction: defaultSortDirections[field]
807
- };
808
- renamingId = null;
809
- confirmingRemovalId = null;
810
- mutate(() => void 0);
811
- }
812
- function createButton(label, tone, onClick) {
813
- const button = document.createElement("button");
814
- button.type = "button";
815
- button.textContent = label;
816
- styleButton(button, tone);
817
- button.addEventListener("click", onClick);
818
- return button;
819
- }
820
- function renderSortBar(text) {
821
- const arrow = sort.direction === "asc" ? " ▲" : " ▼";
822
- const fields = [
823
- ["name", text.sortByName],
824
- ["updatedAt", text.sortByDate],
825
- ["byteLength", text.sortBySize]
826
- ];
827
- for (const [field, label] of fields) {
828
- const active = sort.field === field;
829
- const button = createButton(active ? `${label}${arrow}` : label, active ? "active" : "plain", () => selectSort(field));
830
- button.setAttribute("data-sort-field", field);
831
- if (active) button.setAttribute("aria-pressed", "true");
832
- sortBar.appendChild(button);
833
- }
834
- }
835
- function renderRow(summary, text) {
836
- const row = document.createElement("div");
837
- row.setAttribute("data-dsl-file-id", summary.id);
838
- row.style.cssText = "display:flex;align-items:center;gap:8px;padding:8px;border:1px solid #e2e6ee;border-radius:8px;";
839
- if (renamingId === summary.id) {
840
- const input = document.createElement("input");
841
- input.type = "text";
842
- input.value = summary.name;
843
- input.setAttribute("data-rename-input", summary.id);
844
- input.style.cssText = "flex:1;min-width:0;padding:5px 8px;border:1px solid #1f6feb;border-radius:6px;font-size:14px;";
845
- const commit = () => {
846
- const nextName = input.value;
847
- renamingId = null;
848
- mutate(() => options.onRename(summary.id, nextName));
849
- };
850
- input.addEventListener("keydown", (event) => {
851
- const key = event.key;
852
- if (key === "Enter") commit();
853
- if (key === "Escape") {
854
- renamingId = null;
855
- render();
856
- }
857
- });
858
- row.appendChild(input);
859
- row.appendChild(createButton(text.confirm, "primary", commit));
860
- row.appendChild(createButton(text.cancel, "plain", () => {
861
- renamingId = null;
862
- render();
863
- }));
864
- return row;
865
- }
866
- const name = document.createElement("span");
867
- name.textContent = summary.name;
868
- name.style.cssText = "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;";
869
- const date = document.createElement("span");
870
- date.textContent = formatDate(summary.updatedAt);
871
- date.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;";
872
- const size = document.createElement("span");
873
- size.textContent = formatSize(summary.byteLength);
874
- size.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;";
875
- row.appendChild(name);
876
- row.appendChild(date);
877
- row.appendChild(size);
878
- if (confirmingRemovalId === summary.id) {
879
- row.appendChild(createButton(text.confirmRemove, "danger", () => {
880
- confirmingRemovalId = null;
881
- mutate(() => options.onRemove(summary.id));
882
- }));
883
- row.appendChild(createButton(text.cancel, "plain", () => {
884
- confirmingRemovalId = null;
885
- render();
886
- }));
887
- return row;
888
- }
889
- row.appendChild(createButton(text.open, "primary", () => {
890
- mutate(() => options.onOpen(summary.id));
891
- }));
892
- row.appendChild(createButton(text.rename, "plain", () => {
893
- renamingId = summary.id;
894
- confirmingRemovalId = null;
895
- render();
896
- }));
897
- row.appendChild(createButton(text.remove, "plain", () => {
898
- confirmingRemovalId = summary.id;
899
- renamingId = null;
900
- render();
901
- }));
902
- return row;
903
- }
904
- function render() {
905
- if (disposed) return;
906
- const text = textFor(locales, locale);
907
- heading.textContent = text.title;
908
- closeButton.textContent = text.close;
909
- closeButton.setAttribute("aria-label", text.close);
910
- addButton.textContent = text.add;
911
- statusElement.textContent = status;
912
- sortBar.replaceChildren();
913
- renderSortBar(text);
914
- listElement.replaceChildren();
915
- if (summaries.length === 0) {
916
- const empty = document.createElement("p");
917
- empty.textContent = text.empty;
918
- empty.style.cssText = "margin:8px 0;font-size:14px;color:#5a6172;";
919
- listElement.appendChild(empty);
920
- } else for (const summary of summaries) listElement.appendChild(renderRow(summary, text));
921
- }
922
- styleButton(closeButton, "plain");
923
- styleButton(addButton, "primary");
924
- closeButton.type = "button";
925
- addButton.type = "button";
926
- closeButton.addEventListener("click", () => hide());
927
- addButton.addEventListener("click", () => {
928
- mutate(() => options.onAdd());
929
- });
930
- function hide() {
931
- if (disposed) return;
932
- renamingId = null;
933
- confirmingRemovalId = null;
934
- root.style.display = "none";
935
- }
936
- function ensureActive() {
937
- if (disposed) throw new TypeError("DSL files dialog is disposed");
938
- }
939
- render();
940
- return Object.freeze({
941
- element: root,
942
- get locale() {
943
- return locale;
944
- },
945
- get sort() {
946
- return sort;
947
- },
948
- async show(nextLocale) {
949
- ensureActive();
950
- if (nextLocale !== void 0) locale = nextLocale;
951
- status = "";
952
- root.style.display = "flex";
953
- await reload();
954
- return locale;
955
- },
956
- hide,
957
- async refresh() {
958
- ensureActive();
959
- await reload();
960
- },
961
- setLocale(nextLocale) {
962
- ensureActive();
963
- locale = nextLocale;
964
- render();
965
- return locale;
966
- },
967
- dispose() {
968
- if (disposed) return;
969
- disposed = true;
970
- root.remove();
971
- if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = previousMountPosition;
972
- }
973
- });
974
- }
975
- //#endregion
976
- //#region src/events.ts
977
- var dslOpenEventName = "turbowarp-title-menu:dsl-open";
978
- var dslReloadEventName = "turbowarp-title-menu:dsl-reload";
979
- /**
980
- * Announces an opened DSL source on the window.
981
- *
982
- * The extension also starts a Scratch hat, but a packaged host that embeds this extension may run
983
- * its own runtime outside the VM, so the DOM event stays the transport that assumes no Scratch.
984
- */
985
- function dispatchDslSourceEvent(type, record) {
986
- const target = globalThis;
987
- if (typeof target.dispatchEvent !== "function") return;
988
- const event = typeof CustomEvent === "function" ? new CustomEvent(type, { detail: { record } }) : new Event(type);
989
- if (!("detail" in event)) Object.defineProperty(event, "detail", { value: { record } });
990
- target.dispatchEvent(event);
991
- }
992
- //#endregion
993
- //#region src/title-dialog.ts
994
- function requireLocaleText(locales, locale) {
995
- const text = locales[locale] ?? locales.en ?? Object.values(locales)[0];
996
- if (!text) throw new TypeError("locales must contain at least one locale");
997
- for (const key of [
998
- "title",
999
- "website",
1000
- "close"
1001
- ]) if (typeof text[key] !== "string" || text[key].length === 0) throw new TypeError(`locales.${locale}.${key} must be a non-empty string`);
1002
- return text;
1003
- }
1004
- function openWebsite(url) {
1005
- const opener = globalThis.open;
1006
- if (typeof opener === "function") opener(url, "_blank", "noopener,noreferrer");
1007
- else if (globalThis.location) globalThis.location.href = url;
1008
- }
1009
- function createTitleDialog(options) {
1010
- const document = requireDocument(options.document ?? globalThis.document);
1011
- const mount = requireElement(options.mount ?? document.body, "mount");
1012
- const locales = options.locales;
1013
- if (!locales || typeof locales !== "object") throw new TypeError("locales must be an object");
1014
- const root = document.createElement("section");
1015
- const panel = document.createElement("div");
1016
- const language = document.createElement("button");
1017
- const close = document.createElement("button");
1018
- const heading = document.createElement("h1");
1019
- const meta = document.createElement("p");
1020
- const website = document.createElement("button");
1021
- root.setAttribute("data-turbowarp-title-dialog", "true");
1022
- root.setAttribute("role", "dialog");
1023
- root.setAttribute("aria-modal", "true");
1024
- root.style.cssText = "position:absolute;inset:0;z-index:2147483647;display:none;align-items:center;justify-content:center;box-sizing:border-box;background:rgba(0,0,0,.35);font-family:sans-serif;";
1025
- panel.style.cssText = "position:relative;box-sizing:border-box;width:min(88%,420px);padding:36px 28px 28px;text-align:center;background:#f4fffb;border:1px solid #007d66;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.3);color:#006b58;";
1026
- language.style.cssText = "position:absolute;top:14px;left:16px;border:0;background:transparent;color:#007d66;font-size:14px;cursor:pointer;";
1027
- close.style.cssText = "position:absolute;top:12px;right:12px;width:32px;height:32px;border:0;border-radius:50%;background:#007d66;color:#fff;font-size:22px;line-height:28px;cursor:pointer;";
1028
- heading.style.cssText = "margin:0 24px 8px;font-size:30px;font-weight:600;line-height:1.15;";
1029
- meta.style.cssText = "margin:0 0 22px;font-size:14px;line-height:1.4;";
1030
- website.style.cssText = "display:inline-flex;align-items:center;justify-content:center;min-height:48px;padding:8px 18px;border:0;border-radius:10px;background:#007d66;color:#fff;font-size:16px;cursor:pointer;";
1031
- language.type = "button";
1032
- close.type = "button";
1033
- website.type = "button";
1034
- close.textContent = "x";
1035
- panel.append(language, close, heading, meta, website);
1036
- root.appendChild(panel);
1037
- const restoreMount = ensureRelativeMount(mount);
1038
- mount.appendChild(root);
1039
- let locale = options.initialLocale ?? (locales.ja ? "ja" : Object.keys(locales)[0] ?? "en");
1040
- let disposed = false;
1041
- const render = () => {
1042
- const text = requireLocaleText(locales, locale);
1043
- heading.textContent = text.title;
1044
- meta.textContent = [text.author, text.license].filter(Boolean).join(" / ");
1045
- meta.hidden = meta.textContent.length === 0;
1046
- website.textContent = text.website;
1047
- website.setAttribute("aria-label", text.website);
1048
- close.setAttribute("aria-label", text.close);
1049
- close.setAttribute("title", text.close);
1050
- language.textContent = text.language ?? locale;
1051
- language.setAttribute("aria-label", text.language ?? locale);
1052
- };
1053
- const handleWebsite = () => {
1054
- if (options.onWebsite) invokeSafely(options.onWebsite, options.onError);
1055
- else if (options.websiteUrl) openWebsite(options.websiteUrl);
1056
- };
1057
- const handleClose = () => {
1058
- hide();
1059
- if (options.onClose) invokeSafely(options.onClose, options.onError);
1060
- };
1061
- const handleLanguage = () => {
1062
- const keys = Object.keys(locales);
1063
- locale = keys[(Math.max(keys.indexOf(locale), 0) + 1) % keys.length] ?? locale;
1064
- render();
1065
- if (options.onLocaleChange) invokeSafely(() => options.onLocaleChange?.(locale), options.onError);
1066
- };
1067
- website.addEventListener("click", handleWebsite);
1068
- close.addEventListener("click", handleClose);
1069
- language.addEventListener("click", handleLanguage);
1070
- function show(nextLocale = locale) {
1071
- if (disposed) throw new TypeError("title dialog is disposed");
1072
- locale = nextLocale;
1073
- render();
1074
- root.style.display = "flex";
1075
- return locale;
1076
- }
1077
- function hide() {
1078
- if (!disposed) root.style.display = "none";
1079
- }
1080
- function setLocale(nextLocale) {
1081
- if (disposed) throw new TypeError("title dialog is disposed");
1082
- locale = nextLocale;
1083
- render();
1084
- return locale;
1085
- }
1086
- function dispose() {
1087
- if (disposed) return;
1088
- disposed = true;
1089
- website.removeEventListener("click", handleWebsite);
1090
- close.removeEventListener("click", handleClose);
1091
- language.removeEventListener("click", handleLanguage);
1092
- root.remove();
1093
- restoreMount();
1094
- }
1095
- render();
1096
- return Object.freeze({
1097
- element: root,
1098
- get locale() {
1099
- return locale;
1100
- },
1101
- show,
1102
- hide,
1103
- setLocale,
1104
- dispose
1105
- });
1106
- }
1107
- var block_definitions_default = {
1108
- extensionName: "TurboWarp Title Menu",
1109
- menus: { "menuActions": {
1110
- "acceptReporters": false,
1111
- "items": "menuActionItems"
1112
- } },
1113
- blocks: [
1114
- {
1115
- "opcode": "showTitle",
1116
- "blockType": "COMMAND",
1117
- "text": "show title dialog",
1118
- "description": "Shows the configured title dialog above the TurboWarp stage."
1119
- },
1120
- {
1121
- "opcode": "showMenu",
1122
- "blockType": "COMMAND",
1123
- "text": "show application menu",
1124
- "description": "Shows the application menu above the TurboWarp stage."
1125
- },
1126
- {
1127
- "opcode": "addAppMenuAction",
1128
- "blockType": "COMMAND",
1129
- "text": "add app menu action [ACTION] labelled [LABEL]",
1130
- "description": "Adds an application menu action this project owns, or relabels one it already added.",
1131
- "arguments": {
1132
- "ACTION": {
1133
- "type": "STRING",
1134
- "defaultValue": "start"
1135
- },
1136
- "LABEL": {
1137
- "type": "STRING",
1138
- "defaultValue": "Start"
1139
- }
1140
- }
1141
- },
1142
- {
1143
- "opcode": "clearAppMenuActions",
1144
- "blockType": "COMMAND",
1145
- "text": "clear app menu actions",
1146
- "description": "Removes every application menu action, including the built-in ones, so a project can define its own set."
1147
- },
1148
- {
1149
- "opcode": "setAppMenuActionEnabled",
1150
- "blockType": "COMMAND",
1151
- "text": "set app menu action [ACTION] enabled [ENABLED]",
1152
- "description": "Enables or disables one application menu action.",
1153
- "arguments": {
1154
- "ACTION": {
1155
- "type": "STRING",
1156
- "menu": "menuActions"
1157
- },
1158
- "ENABLED": {
1159
- "type": "BOOLEAN",
1160
- "defaultValue": true
1161
- }
1162
- }
1163
- },
1164
- {
1165
- "opcode": "whenAppMenuActionSelected",
1166
- "blockType": "HAT",
1167
- "text": "when app menu action [ACTION] selected",
1168
- "description": "Runs when the operator selects the named application menu action.",
1169
- "arguments": { "ACTION": {
1170
- "type": "STRING",
1171
- "menu": "menuActions"
1172
- } }
1173
- },
1174
- {
1175
- "opcode": "showDslFiles",
1176
- "blockType": "COMMAND",
1177
- "text": "show DSL file manager",
1178
- "description": "Shows the dialog that adds, opens, renames, deletes, and sorts stored DSL files."
1179
- },
1180
- {
1181
- "opcode": "whenDslSourceOpened",
1182
- "blockType": "HAT",
1183
- "text": "when a DSL source is opened",
1184
- "description": "Runs after the operator opens a stored DSL file, or after the opened source is announced again."
1185
- },
1186
- {
1187
- "opcode": "reloadOpenedDsl",
1188
- "blockType": "COMMAND",
1189
- "text": "reload the opened DSL source",
1190
- "description": "Announces the currently opened DSL source again without showing a dialog."
1191
- },
1192
- {
1193
- "opcode": "openedDslName",
1194
- "blockType": "REPORTER",
1195
- "text": "opened DSL file name",
1196
- "description": "Returns the name of the DSL file that is currently open, or an empty string."
1197
- },
1198
- {
1199
- "opcode": "openedDslSource",
1200
- "blockType": "REPORTER",
1201
- "text": "opened DSL source",
1202
- "description": "Returns the text of the DSL file that is currently open, or an empty string."
1203
- },
1204
- {
1205
- "opcode": "hasSavedDsl",
1206
- "blockType": "BOOLEAN",
1207
- "text": "has a saved DSL file?",
1208
- "description": "Reports whether at least one DSL file is stored in IndexedDB."
1209
- },
1210
- {
1211
- "opcode": "savedDslCount",
1212
- "blockType": "REPORTER",
1213
- "text": "saved DSL file count",
1214
- "description": "Returns how many DSL files are stored in IndexedDB."
1215
- },
1216
- {
1217
- "opcode": "lastDslError",
1218
- "blockType": "REPORTER",
1219
- "text": "last DSL storage error",
1220
- "description": "Returns the most recent DSL storage failure in the interface language, or an empty string."
1221
- }
1222
- ]
1223
- };
1224
- //#endregion
1225
- //#region src/locales.ts
1226
- var titleLocales = Object.freeze({
1227
- en: {
1228
- title: "TurboWarp Title Menu",
1229
- author: "Author: Hiroya Kubo",
1230
- license: "License: MPL-2.0",
1231
- website: "Official Website",
1232
- close: "Close"
1233
- },
1234
- ja: {
1235
- title: "TurboWarp Title Menu",
1236
- author: "作者: Hiroya Kubo",
1237
- license: "ライセンス: MPL-2.0",
1238
- website: "公式Webサイト",
1239
- close: "閉じる"
1240
- }
1241
- });
1242
- var menuLocales = Object.freeze({
1243
- en: {
1244
- files: "DSL files",
1245
- reload: "Reload DSL",
1246
- about: "About",
1247
- close: "Close"
1248
- },
1249
- ja: {
1250
- files: "DSLファイル",
1251
- reload: "DSLを再読み込み",
1252
- about: "情報",
1253
- close: "閉じる"
1254
- }
1255
- });
1256
- var dslFilesLocales = Object.freeze({
1257
- en: {
1258
- title: "DSL files",
1259
- add: "Add file",
1260
- open: "Open",
1261
- rename: "Rename",
1262
- remove: "Delete",
1263
- confirmRemove: "Delete for good?",
1264
- confirm: "OK",
1265
- cancel: "Cancel",
1266
- close: "Close",
1267
- sortByName: "Name",
1268
- sortByDate: "Updated",
1269
- sortBySize: "Size",
1270
- empty: "No DSL file is saved yet. Use Add file to store one."
1271
- },
1272
- ja: {
1273
- title: "DSLファイル",
1274
- add: "ファイルを追加",
1275
- open: "開く",
1276
- rename: "名前を変える",
1277
- remove: "削除",
1278
- confirmRemove: "本当に削除?",
1279
- confirm: "OK",
1280
- cancel: "やめる",
1281
- close: "閉じる",
1282
- sortByName: "名前",
1283
- sortByDate: "更新日時",
1284
- sortBySize: "サイズ",
1285
- empty: "保存されたDSLファイルはありません。「ファイルを追加」から保存してください。"
1286
- }
1287
- });
1288
- var storeErrorMessages = Object.freeze({
1289
- en: {
1290
- unavailable: "Browser storage is unavailable, so DSL files cannot be saved.",
1291
- "invalid-name": "That file name cannot be used.",
1292
- "invalid-source": "That file could not be read as text.",
1293
- "name-taken": "Another DSL file already uses that name.",
1294
- "too-large": "That DSL file is too large to store.",
1295
- "too-many": "The DSL store is full. Delete a file before adding another.",
1296
- "not-found": "That DSL file is no longer stored.",
1297
- quota: "Browser storage is full. Delete a DSL file and try again.",
1298
- failed: "The DSL storage operation failed."
1299
- },
1300
- ja: {
1301
- unavailable: "ブラウザの保存領域が使えないため、DSLファイルを保存できません。",
1302
- "invalid-name": "そのファイル名は使えません。",
1303
- "invalid-source": "そのファイルをテキストとして読み込めませんでした。",
1304
- "name-taken": "同じ名前のDSLファイルがすでにあります。",
1305
- "too-large": "そのDSLファイルは大きすぎて保存できません。",
1306
- "too-many": "保存できる数に達しています。どれかを削除してから追加してください。",
1307
- "not-found": "そのDSLファイルは保存されていません。",
1308
- quota: "ブラウザの保存領域がいっぱいです。DSLファイルを削除してからやり直してください。",
1309
- failed: "DSLファイルの操作に失敗しました。"
1310
- }
1311
- });
1312
- /** Turns a store error code into operator-facing text, falling back to the raw message. */
1313
- function describeStoreError(locale, error) {
1314
- const code = error?.code;
1315
- const messages = storeErrorMessages[locale] ?? storeErrorMessages.en;
1316
- if (code !== void 0 && code in messages) return messages[code];
1317
- if (error instanceof Error && error.message.length > 0) return error.message;
1318
- return String(error);
1319
- }
1320
- //#endregion
1321
- //#region src/extension.ts
1322
- var blockDefinitions = block_definitions_default.blocks;
1323
- var dslFileAccept = ".txt,.yaml,.yml,.json,.k4,.kamishibai";
1324
- /** Reserved action IDs the extension handles itself. A project may still remove or relabel them. */
1325
- var builtinActionIds = [
1326
- "files",
1327
- "reload",
1328
- "about",
1329
- "close"
1330
- ];
1331
- function stageMount() {
1332
- return Scratch.vm?.renderer?.canvas?.parentElement ?? globalThis.document?.body;
1333
- }
1334
- var TurboWarpTitleMenuExtension = class {
1335
- constructor() {
1336
- this.titleDialog = null;
1337
- this.applicationMenu = null;
1338
- this.filesDialog = null;
1339
- this.store = null;
1340
- this.openedRecord = null;
1341
- this.lastError = "";
1342
- this.menuActions = builtinActionIds.map((id) => ({
1343
- id,
1344
- labels: {
1345
- en: menuLocales.en[id],
1346
- ja: menuLocales.ja[id]
1347
- },
1348
- enabled: true
1349
- }));
1350
- this.menuVisible = false;
1351
- }
1352
- getInfo() {
1353
- return {
1354
- id: extensionConfig.id,
1355
- name: Scratch.translate(block_definitions_default.extensionName),
1356
- docsURI: extensionConfig.docsURI,
1357
- blockIconURI: extensionConfig.blockIconURI,
1358
- blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
1359
- menus: block_definitions_default.menus
1360
- };
1361
- }
1362
- showTitle() {
1363
- this.ensureTitleDialog().show(this.locale());
1364
- }
1365
- /**
1366
- * Shows the application menu.
1367
- *
1368
- * An empty registry does nothing: the underlying primitive requires at least one action, and a
1369
- * project that cleared the actions to install its own should not be interrupted by an error
1370
- * between the two steps.
1371
- */
1372
- showMenu() {
1373
- if (this.menuActions.length === 0) return;
1374
- this.ensureApplicationMenu().show(this.locale());
1375
- this.menuVisible = true;
1376
- }
1377
- /**
1378
- * Backs the dynamic `menuActions` dropdown, so it always lists what the project registered.
1379
- *
1380
- * The menu must refuse reporters. Scratch turns a reporter-accepting menu argument into an input
1381
- * holding a shadow block, and `startHats` matches a hat against its *fields*, so the action hat
1382
- * would never fire for a specific action. Refusing reporters keeps the argument an inline
1383
- * dropdown, which is what the match reads.
1384
- */
1385
- menuActionItems() {
1386
- if (this.menuActions.length === 0) return [{
1387
- text: "—",
1388
- value: ""
1389
- }];
1390
- const locale = this.locale();
1391
- return this.menuActions.map((action) => ({
1392
- text: action.labels[locale],
1393
- value: action.id
1394
- }));
1395
- }
1396
- addAppMenuAction(args) {
1397
- const id = Scratch.Cast.toString(args.ACTION).trim();
1398
- if (id.length === 0) return;
1399
- const label = Scratch.Cast.toString(args.LABEL);
1400
- const existing = this.menuActions.find((action) => action.id === id);
1401
- if (existing === void 0) this.menuActions.push({
1402
- id,
1403
- labels: {
1404
- en: label,
1405
- ja: label
1406
- },
1407
- enabled: true
1408
- });
1409
- else existing.labels = {
1410
- en: label,
1411
- ja: label
1412
- };
1413
- this.rebuildMenu();
1414
- }
1415
- clearAppMenuActions() {
1416
- this.menuActions = [];
1417
- this.rebuildMenu();
1418
- }
1419
- setAppMenuActionEnabled(args) {
1420
- const id = Scratch.Cast.toString(args.ACTION);
1421
- const action = this.menuActions.find((entry) => entry.id === id);
1422
- if (action === void 0) return;
1423
- action.enabled = Scratch.Cast.toBoolean(args.ENABLED);
1424
- this.applicationMenu?.setActionState(id, { enabled: action.enabled });
1425
- }
1426
- /** Started by the menu callback, so the handler only has to accept the match. */
1427
- whenAppMenuActionSelected() {
1428
- return true;
1429
- }
1430
- showDslFiles() {
1431
- return this.ensureFilesDialog().show(this.locale());
1432
- }
1433
- /** The hat is started by the open path, so its own handler only has to accept the match. */
1434
- whenDslSourceOpened() {
1435
- return true;
1436
- }
1437
- reloadOpenedDsl() {
1438
- if (this.openedRecord === null) return;
1439
- this.announce(dslReloadEventName, this.openedRecord);
1440
- }
1441
- openedDslName() {
1442
- return this.openedRecord?.name ?? "";
1443
- }
1444
- openedDslSource() {
1445
- return this.openedRecord?.source ?? "";
1446
- }
1447
- async hasSavedDsl() {
1448
- return await this.savedDslCount() > 0;
1449
- }
1450
- async savedDslCount() {
1451
- try {
1452
- return await this.requireStore().count();
1453
- } catch (error) {
1454
- this.recordFailure(error);
1455
- return 0;
1456
- }
1457
- }
1458
- lastDslError() {
1459
- return this.lastError;
1460
- }
1461
- locale() {
1462
- return resolveAppShellLocale() === "ja" ? "ja" : "en";
1463
- }
1464
- /**
1465
- * Opens the store on first use.
1466
- *
1467
- * A browser without IndexedDB, or one with storage blocked, fails here rather than at extension
1468
- * load: the title and menu blocks stay usable even when nothing can be stored.
1469
- */
1470
- requireStore() {
1471
- this.store ?? (this.store = createDslStore({ databaseName: extensionConfig.id }));
1472
- return this.store;
1473
- }
1474
- recordFailure(error) {
1475
- this.lastError = describeStoreError(this.locale(), error);
1476
- }
1477
- /**
1478
- * Rebuilds the menu after its action list changed.
1479
- *
1480
- * The app-shell primitive fixes its actions at construction, so a changed list means a new menu.
1481
- * A menu that was on screen is shown again, because a project that adds an action while the menu
1482
- * is open should not have it silently disappear. Clearing every action closes the menu instead,
1483
- * because the primitive refuses to build one with no actions.
1484
- */
1485
- rebuildMenu() {
1486
- this.applicationMenu?.dispose();
1487
- this.applicationMenu = null;
1488
- if (!this.menuVisible) return;
1489
- if (this.menuActions.length === 0) {
1490
- this.menuVisible = false;
1491
- return;
1492
- }
1493
- this.showMenu();
1494
- }
1495
- selectMenuAction(id) {
1496
- Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenAppMenuActionSelected`, { ACTION: id });
1497
- if (!builtinActionIds.includes(id)) return;
1498
- if (id === "files") this.showDslFiles();
1499
- if (id === "reload") this.reloadOpenedDsl();
1500
- if (id === "about") this.showTitle();
1501
- if (id === "close") this.hideMenu();
1502
- }
1503
- hideMenu() {
1504
- this.applicationMenu?.hide();
1505
- this.menuVisible = false;
1506
- }
1507
- announce(eventName, record) {
1508
- dispatchDslSourceEvent(eventName, record);
1509
- Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenDslSourceOpened`);
1510
- }
1511
- ensureTitleDialog() {
1512
- if (this.titleDialog) return this.titleDialog;
1513
- const mount = stageMount();
1514
- this.titleDialog = createTitleDialog({
1515
- document: globalThis.document,
1516
- ...mount ? { mount } : {},
1517
- locales: titleLocales,
1518
- initialLocale: this.locale(),
1519
- websiteUrl: extensionConfig.homepage
1520
- });
1521
- return this.titleDialog;
1522
- }
1523
- /**
1524
- * Builds the menu from the shared app-shell primitive.
1525
- *
1526
- * The actions below are this extension's own vocabulary, not the primitive's: a host application
1527
- * that needs different actions composes `createAppShellApplicationMenu` itself through the
1528
- * composition API instead of being limited to these four.
1529
- */
1530
- ensureApplicationMenu() {
1531
- if (this.applicationMenu) return this.applicationMenu;
1532
- const mount = stageMount();
1533
- if (mount === void 0) throw new TypeError("a stage container is required to show the menu");
1534
- this.applicationMenu = createAppShellApplicationMenu({
1535
- document: globalThis.document,
1536
- mount,
1537
- initialLocale: this.locale(),
1538
- actions: this.menuActions.map((action) => ({
1539
- id: action.id,
1540
- labels: action.labels,
1541
- enabled: action.enabled,
1542
- onSelect: () => this.selectMenuAction(action.id)
1543
- }))
1544
- });
1545
- return this.applicationMenu;
1546
- }
1547
- ensureFilesDialog() {
1548
- if (this.filesDialog) return this.filesDialog;
1549
- const mount = stageMount();
1550
- this.filesDialog = createDslFilesDialog({
1551
- document: globalThis.document,
1552
- ...mount ? { mount } : {},
1553
- locales: dslFilesLocales,
1554
- initialLocale: this.locale(),
1555
- list: (sort) => this.requireStore().list(sort),
1556
- onAdd: () => this.addDslFile(),
1557
- onOpen: (id) => this.openDslFile(id),
1558
- onRename: (id, name) => this.requireStore().rename(id, name),
1559
- onRemove: (id) => this.removeDslFile(id),
1560
- describeError: (error) => describeStoreError(this.locale(), error),
1561
- onError: (error) => this.recordFailure(error)
1562
- });
1563
- return this.filesDialog;
1564
- }
1565
- async addDslFile() {
1566
- const chosen = await this.pickDslFile();
1567
- if (chosen === null) return;
1568
- await this.requireStore().save(await readDslFile(chosen));
1569
- this.lastError = "";
1570
- }
1571
- async openDslFile(id) {
1572
- const store = this.requireStore();
1573
- const record = await store.get(id);
1574
- if (record === null) return;
1575
- await store.markOpened(id);
1576
- this.openedRecord = record;
1577
- this.lastError = "";
1578
- this.announce(dslOpenEventName, record);
1579
- }
1580
- async removeDslFile(id) {
1581
- await this.requireStore().remove(id);
1582
- if (this.openedRecord?.id === id) this.openedRecord = null;
1583
- this.lastError = "";
1584
- }
1585
- pickDslFile() {
1586
- const document = globalThis.document;
1587
- if (!document) throw new TypeError("document is required to open a DSL file");
1588
- const input = document.createElement("input");
1589
- input.type = "file";
1590
- input.accept = dslFileAccept;
1591
- return new Promise((resolve) => {
1592
- input.addEventListener("change", () => {
1593
- resolve(input.files?.[0] ?? null);
1594
- }, { once: true });
1595
- input.click();
1596
- });
1597
- }
1598
- toScratchBlock(block) {
1599
- const scratchBlock = {
1600
- opcode: block.opcode,
1601
- blockType: Scratch.BlockType[block.blockType],
1602
- text: Scratch.translate(block.text),
1603
- arguments: Object.fromEntries(Object.entries(block.arguments ?? {}).map(([name, argument]) => [name, {
1604
- type: Scratch.ArgumentType[argument.type],
1605
- ...argument.defaultValue === void 0 ? {} : { defaultValue: argument.defaultValue },
1606
- ...argument.menu === void 0 ? {} : { menu: argument.menu }
1607
- }]))
1608
- };
1609
- if (block.blockType === "HAT") scratchBlock["isEdgeActivated"] = false;
1610
- return scratchBlock;
1611
- }
1612
- };
1613
- //#endregion
1614
- //#region src/index.ts
1615
- var publicApi = Object.freeze({
1616
- createApplicationMenu: createAppShellApplicationMenu,
1617
- createDslFilesDialog,
1618
- createDslStore,
1619
- createTitleDialog,
1620
- dslOpenEventName,
1621
- dslReloadEventName
1622
- });
1623
- Object.defineProperty(globalThis, "TurboWarpTitleMenu", {
1624
- value: publicApi,
1625
- configurable: true
1626
- });
1627
- if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1628
- Scratch.extensions.register(new TurboWarpTitleMenuExtension());
1629
- //#endregion
10
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-app-shell@0.5.0/node_modules/@kubohiroya/turbowarp-app-shell/dist/index.js
11
+ function isRecord$1(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ function requireElement$1(value, name) {
15
+ if (!isRecord$1(value) || typeof value["appendChild"] !== "function") throw new TypeError(`${name} must be a DOM element.`);
16
+ return value;
17
+ }
18
+ function requireDocument$1(value) {
19
+ if (!isRecord$1(value) || typeof value["createElement"] !== "function") throw new TypeError("document must provide the DOM document contract.");
20
+ return value;
21
+ }
22
+ function requireString(value, name) {
23
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
24
+ return value;
25
+ }
26
+ function optionalBoolean(value, name, fallback) {
27
+ if (value === void 0) return fallback;
28
+ if (typeof value !== "boolean") throw new TypeError(`${name} must be a boolean.`);
29
+ return value;
30
+ }
31
+ function optionalString(value, name) {
32
+ if (value === void 0) return void 0;
33
+ if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
34
+ return value;
35
+ }
36
+ function requireLocalizedLabels(value, name) {
37
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
38
+ const entries = Object.entries(value);
39
+ if (entries.length === 0) throw new TypeError(`${name} must include at least one locale.`);
40
+ for (const [locale, label] of entries) if (typeof label !== "string" || label.length === 0) throw new TypeError(`${name}.${locale} must be a non-empty string.`);
41
+ return value;
42
+ }
43
+ function firstLocale(locales, name) {
44
+ const [locale] = Object.keys(locales);
45
+ if (locale === void 0) throw new TypeError(`${name} must include at least one locale.`);
46
+ return locale;
47
+ }
48
+ function resolveInjectedLocale(locales, requested, fallback, name) {
49
+ if (requested !== void 0 && Object.hasOwn(locales, requested)) return requested;
50
+ if (fallback !== void 0 && Object.hasOwn(locales, fallback)) return fallback;
51
+ if (Object.hasOwn(locales, "en")) return "en";
52
+ return firstLocale(locales, name);
53
+ }
54
+ function localized(locales, locale, fallback, name) {
55
+ return locales[resolveInjectedLocale(locales, locale, fallback, name)];
56
+ }
57
+ function requireIcon(value, name) {
58
+ if (value === void 0) return void 0;
59
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
60
+ const url = optionalString(value["url"], `${name}.url`);
61
+ const text = optionalString(value["text"], `${name}.text`);
62
+ const filter = optionalString(value["filter"], `${name}.filter`);
63
+ const size = optionalString(value["size"], `${name}.size`);
64
+ const fontSize = optionalString(value["fontSize"], `${name}.fontSize`);
65
+ if ((url === void 0 || url.length === 0) && (text === void 0 || text.length === 0)) throw new TypeError(`${name} must include a non-empty url or text.`);
66
+ return {
67
+ ...url === void 0 ? {} : { url },
68
+ ...text === void 0 ? {} : { text },
69
+ ...filter === void 0 ? {} : { filter },
70
+ ...size === void 0 ? {} : { size },
71
+ ...fontSize === void 0 ? {} : { fontSize }
72
+ };
73
+ }
74
+ function requireAttributes(value, name) {
75
+ if (value === void 0) return void 0;
76
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
77
+ for (const [attribute, attributeValue] of Object.entries(value)) {
78
+ if (attribute.length === 0) throw new TypeError(`${name} names must be non-empty.`);
79
+ if (typeof attributeValue !== "string") throw new TypeError(`${name}.${attribute} must be a string.`);
80
+ }
81
+ return value;
82
+ }
83
+ function applyAttributes(element, attributes) {
84
+ if (attributes === void 0) return;
85
+ for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
86
+ }
87
+ function requireRect(value, name) {
88
+ if (value === void 0) return void 0;
89
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
90
+ const left = optionalString(value["left"], `${name}.left`);
91
+ const top = optionalString(value["top"], `${name}.top`);
92
+ const width = optionalString(value["width"], `${name}.width`);
93
+ const height = optionalString(value["height"], `${name}.height`);
94
+ return {
95
+ ...left === void 0 ? {} : { left },
96
+ ...top === void 0 ? {} : { top },
97
+ ...width === void 0 ? {} : { width },
98
+ ...height === void 0 ? {} : { height }
99
+ };
100
+ }
101
+ function applyRect(element, rect) {
102
+ if (rect === void 0) return;
103
+ if (rect.left !== void 0) element.style.left = rect.left;
104
+ if (rect.top !== void 0) element.style.top = rect.top;
105
+ if (rect.width !== void 0) element.style.width = rect.width;
106
+ if (rect.height !== void 0) element.style.height = rect.height;
107
+ }
108
+ function requireTestId(value, name) {
109
+ if (value === void 0) return void 0;
110
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
111
+ return value;
112
+ }
113
+ function applyTestId(element, testId) {
114
+ if (testId !== void 0) element.setAttribute("data-testid", testId);
115
+ }
116
+ function restoreableMountPosition(document, mount) {
117
+ if (mount === document.body) return null;
118
+ const previous = mount.style.position;
119
+ if (previous === void 0 || previous === "" || previous === "static") {
120
+ mount.style.position = "relative";
121
+ return () => {
122
+ mount.style.position = previous ?? "";
123
+ };
124
+ }
125
+ return null;
126
+ }
127
+ function setButtonEnabled(button, enabled) {
128
+ button.disabled = !enabled;
129
+ button.setAttribute("aria-disabled", String(!enabled));
130
+ button.style.cursor = enabled ? "pointer" : "not-allowed";
131
+ button.style.opacity = enabled ? "1" : "0.42";
132
+ }
133
+ function setElementVisible(element, visible, display) {
134
+ element.hidden = !visible;
135
+ element.style.display = visible ? display : "none";
136
+ }
137
+ function reportActionError(onError, error) {
138
+ try {
139
+ onError?.(error);
140
+ } catch {}
141
+ }
142
+ function invokeAction(action, onError, event) {
143
+ event?.preventDefault();
144
+ event?.stopPropagation();
145
+ try {
146
+ Promise.resolve(action()).catch((error) => {
147
+ reportActionError(onError, error);
148
+ });
149
+ } catch (error) {
150
+ reportActionError(onError, error);
151
+ }
152
+ }
153
+ function iconCssUrl(url) {
154
+ return `url("${url.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}")`;
155
+ }
156
+ function renderIcon(element, icon) {
157
+ element.textContent = "";
158
+ element.style.backgroundImage = "";
159
+ element.style.display = icon === void 0 ? "none" : "inline-flex";
160
+ if (icon === void 0) return;
161
+ element.style.filter = icon.filter ?? "";
162
+ if (icon.size !== void 0) {
163
+ element.style.width = icon.size;
164
+ element.style.height = icon.size;
165
+ }
166
+ if (icon.fontSize !== void 0) element.style.fontSize = icon.fontSize;
167
+ if (icon.url !== void 0) {
168
+ element.style.backgroundImage = iconCssUrl(icon.url);
169
+ element.style.backgroundPosition = "center";
170
+ element.style.backgroundRepeat = "no-repeat";
171
+ element.style.backgroundSize = "contain";
172
+ return;
173
+ }
174
+ element.textContent = icon.text ?? "";
175
+ }
176
+ function loadingTone(tone) {
177
+ if (tone === "warning") return "#805300";
178
+ if (tone === "error") return "#a00020";
179
+ if (tone === "info") return "#176e9f";
180
+ return "#35524c";
181
+ }
182
+ function resolveAppShellLocale(input) {
183
+ const preferred = input?.language ?? input?.languages?.[0] ?? globalThis.navigator?.language ?? "";
184
+ return /^ja(?:-|$)/iu.test(preferred) ? "ja" : "en";
185
+ }
186
+ function boundedText(value, limit = 2e3) {
187
+ const text = String(value ?? "");
188
+ const scalars = [...text];
189
+ return scalars.length <= limit ? text : `${scalars.slice(0, limit - 1).join("")}...`;
190
+ }
191
+ /**
192
+ * Where the application menu places its actions: two columns of up to two rows, as it always has,
193
+ * and more columns and rows when there are more actions, so that every action stays on the stage.
194
+ * The band starts under the title area and ends above the status row; labels and icons shrink with
195
+ * the cells. An action's own `position` still overrides its cell.
196
+ */
197
+ function applicationMenuGrid(count) {
198
+ const columns = count <= 4 ? 2 : count <= 12 ? 3 : 4;
199
+ const rows = Math.ceil(count / columns);
200
+ const top = 25.5556;
201
+ const bottom = rows <= 2 ? 80 : 90;
202
+ const gapX = columns === 2 ? 6.6667 : 3.3333;
203
+ const gapY = rows <= 2 ? 5.5556 : 2.7778;
204
+ const width = (80 - (columns - 1) * gapX) / columns;
205
+ const height = (bottom - top - (rows - 1) * gapY) / rows;
206
+ const scale = Math.min(1, width / 36.6667, height / 24.4444);
207
+ const percent = (value) => `${Number(value.toFixed(4))}%`;
208
+ return {
209
+ cell(index) {
210
+ const row = Math.floor(index / columns);
211
+ const column = index % columns;
212
+ if (count <= 4) return {
213
+ left: column === 0 ? "10%" : "53.3333%",
214
+ top: `${25.5556 + row * 30}%`,
215
+ width: "36.6667%",
216
+ height: "24.4444%"
217
+ };
218
+ return {
219
+ left: percent(10 + column * (width + gapX)),
220
+ top: percent(top + row * (height + gapY)),
221
+ width: percent(width),
222
+ height: percent(height)
223
+ };
224
+ },
225
+ cqw(size) {
226
+ return `${count <= 4 ? size : Number((size * scale).toFixed(4))}cqw`;
227
+ }
228
+ };
229
+ }
230
+ function createAppShellApplicationMenu(options) {
231
+ if (!isRecord$1(options)) throw new TypeError("application menu options must be an object.");
232
+ const document = requireDocument$1(options.document);
233
+ const mount = requireElement$1(options.mount, "mount");
234
+ if (!Array.isArray(options.actions) || options.actions.length === 0) throw new TypeError("actions must include at least one menu action.");
235
+ const fallbackLocale = optionalString(options.fallbackLocale, "fallbackLocale");
236
+ const rootTestId = requireTestId(options.rootTestId, "rootTestId");
237
+ const statusTestId = requireTestId(options.statusTestId, "statusTestId");
238
+ const menuAttributes = options.attributes ?? {};
239
+ if (!isRecord$1(menuAttributes)) throw new TypeError("attributes must be an object.");
240
+ const rootAttributes = requireAttributes(menuAttributes.root, "attributes.root");
241
+ const statusAttributes = requireAttributes(menuAttributes.status, "attributes.status");
242
+ const root = document.createElement("section");
243
+ const status = document.createElement("p");
244
+ const restoreMountPosition = restoreableMountPosition(document, mount);
245
+ root.setAttribute("data-turbowarp-app-shell-application-menu", "true");
246
+ root.setAttribute("aria-label", options.ariaLabel ?? "Application menu");
247
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483600;display:none;box-sizing:border-box;overflow:hidden;pointer-events:auto;font-family:sans-serif;container-type:inline-size;";
248
+ root.style.position = "absolute";
249
+ root.style.display = "none";
250
+ root.style.cursor = "pointer";
251
+ applyTestId(root, rootTestId);
252
+ applyAttributes(root, rootAttributes);
253
+ status.setAttribute("data-turbowarp-app-shell-menu-status", "true");
254
+ status.setAttribute("role", "status");
255
+ status.setAttribute("aria-live", "polite");
256
+ status.style.cssText = "position:absolute;left:10%;top:93%;width:80%;margin:0;color:#35524c;font-size:2.7cqw;line-height:1.1;text-align:center;";
257
+ applyTestId(status, statusTestId);
258
+ applyAttributes(status, statusAttributes);
259
+ const buttons = /* @__PURE__ */ new Map();
260
+ const seen = /* @__PURE__ */ new Set();
261
+ let locale = optionalString(options.initialLocale, "initialLocale") ?? resolveAppShellLocale();
262
+ const grid = applicationMenuGrid(options.actions.length);
263
+ for (const [index, definition] of options.actions.entries()) {
264
+ if (!isRecord$1(definition)) throw new TypeError(`actions.${index} must be an object.`);
265
+ const id = requireString(definition.id, `actions.${index}.id`);
266
+ if (seen.has(id)) throw new TypeError(`Duplicate application menu action id: ${id}.`);
267
+ seen.add(id);
268
+ const labels = requireLocalizedLabels(definition.labels, `actions.${index}.labels`);
269
+ const icon = requireIcon(definition.icon, `actions.${index}.icon`);
270
+ const enabled = optionalBoolean(definition.enabled, `actions.${index}.enabled`, true);
271
+ const visible = optionalBoolean(definition.visible, `actions.${index}.visible`, true);
272
+ const testId = requireTestId(definition.testId, `actions.${index}.testId`);
273
+ const position = requireRect(definition.position, `actions.${index}.position`);
274
+ const actionAttributes = requireAttributes(definition.attributes, `actions.${index}.attributes`);
275
+ if (typeof definition.onSelect !== "function") throw new TypeError(`actions.${index}.onSelect must be a function.`);
276
+ const onSelect = definition.onSelect;
277
+ const button = document.createElement("button");
278
+ const iconElement = document.createElement("span");
279
+ const label = document.createElement("span");
280
+ const cell = grid.cell(index);
281
+ button.type = "button";
282
+ button.setAttribute("data-turbowarp-app-shell-menu-action", id);
283
+ button.style.cssText = `position:absolute;left:${cell.left};top:${cell.top};width:${cell.width};height:${cell.height};display:flex;min-width:0;min-height:0;align-items:center;justify-content:center;flex-direction:column;gap:.4167cqw;border:.4167cqw solid #005f50;border-radius:2.9167cqw;background:#007d66;color:#fff;box-shadow:0 .625cqw 1.6667cqw rgba(0,0,0,.2);cursor:pointer;font:inherit;`;
284
+ button.style.cursor = "pointer";
285
+ applyTestId(button, testId);
286
+ applyAttributes(button, actionAttributes);
287
+ iconElement.setAttribute("aria-hidden", "true");
288
+ iconElement.style.cssText = `display:inline-flex;width:${grid.cqw(10)};height:${grid.cqw(10)};align-items:center;justify-content:center;line-height:1;font-size:${grid.cqw(6)};`;
289
+ label.style.cssText = `font-size:${grid.cqw(3.8)};line-height:1.15;text-align:center;`;
290
+ button.appendChild(iconElement);
291
+ button.appendChild(label);
292
+ const onClick = (event) => {
293
+ const current = buttons.get(id);
294
+ if (current === void 0 || !current.enabled || !current.visible) return;
295
+ invokeAction(current.onSelect, options.onError, event);
296
+ };
297
+ button.addEventListener("click", onClick);
298
+ buttons.set(id, {
299
+ button,
300
+ icon: iconElement,
301
+ label,
302
+ labels,
303
+ iconDefinition: icon,
304
+ enabled,
305
+ visible,
306
+ position,
307
+ onSelect,
308
+ onClick
309
+ });
310
+ root.appendChild(button);
311
+ }
312
+ root.appendChild(status);
313
+ mount.appendChild(root);
314
+ let statusState = {
315
+ text: options.status?.text ?? "",
316
+ visible: options.status?.visible ?? false,
317
+ tone: options.status?.tone ?? "neutral",
318
+ color: optionalString(options.status?.color, "status.color")
319
+ };
320
+ if (typeof statusState.text !== "string") throw new TypeError("status.text must be a string.");
321
+ if (typeof statusState.visible !== "boolean") throw new TypeError("status.visible must be a boolean.");
322
+ if (![
323
+ "neutral",
324
+ "info",
325
+ "warning",
326
+ "error"
327
+ ].includes(statusState.tone)) throw new TypeError("status.tone must be neutral, info, warning, or error.");
328
+ let disposed = false;
329
+ function renderMenu() {
330
+ for (const [id, value] of buttons) {
331
+ const label = localized(value.labels, locale, fallbackLocale, `menu action ${id} labels`);
332
+ value.label.textContent = label;
333
+ value.button.setAttribute("aria-label", label);
334
+ renderIcon(value.icon, value.iconDefinition);
335
+ setButtonEnabled(value.button, value.enabled);
336
+ setElementVisible(value.button, value.visible, "flex");
337
+ value.button.style.boxShadow = value.enabled ? "0 .625cqw 1.6667cqw rgba(0,0,0,.2)" : "none";
338
+ applyRect(value.button, value.position);
339
+ }
340
+ status.textContent = boundedText(statusState.text, 500);
341
+ status.style.color = statusState.color ?? loadingTone(statusState.tone);
342
+ setElementVisible(status, statusState.visible && statusState.text.length > 0, "block");
343
+ }
344
+ function ensureActive() {
345
+ if (disposed) throw new TypeError("application menu is disposed.");
346
+ }
347
+ renderMenu();
348
+ return Object.freeze({
349
+ show(nextLocale) {
350
+ ensureActive();
351
+ locale = optionalString(nextLocale, "nextLocale") ?? locale;
352
+ renderMenu();
353
+ root.style.display = "block";
354
+ return locale;
355
+ },
356
+ hide() {
357
+ if (!disposed) root.style.display = "none";
358
+ },
359
+ setLocale(nextLocale) {
360
+ ensureActive();
361
+ locale = requireString(nextLocale, "nextLocale");
362
+ renderMenu();
363
+ return locale;
364
+ },
365
+ setActionState(id, state) {
366
+ ensureActive();
367
+ const action = buttons.get(requireString(id, "action id"));
368
+ if (action === void 0) throw new TypeError(`Unknown application menu action: ${id}.`);
369
+ if (!isRecord$1(state)) throw new TypeError("application menu action state must be an object.");
370
+ if (state.enabled !== void 0) {
371
+ if (typeof state.enabled !== "boolean") throw new TypeError("action enabled must be a boolean.");
372
+ action.enabled = state.enabled;
373
+ }
374
+ if (state.visible !== void 0) {
375
+ if (typeof state.visible !== "boolean") throw new TypeError("action visible must be a boolean.");
376
+ action.visible = state.visible;
377
+ }
378
+ if (state.labels !== void 0) action.labels = requireLocalizedLabels(state.labels, "action state labels");
379
+ if (state.icon !== void 0) action.iconDefinition = requireIcon(state.icon, "action state icon");
380
+ if (state.position !== void 0) action.position = requireRect(state.position, "action state position");
381
+ renderMenu();
382
+ },
383
+ setStatus(nextStatus) {
384
+ ensureActive();
385
+ if (!isRecord$1(nextStatus)) throw new TypeError("application menu status must be an object.");
386
+ const nextToneValue = nextStatus["tone"] ?? statusState.tone;
387
+ if (![
388
+ "neutral",
389
+ "info",
390
+ "warning",
391
+ "error"
392
+ ].includes(String(nextToneValue))) throw new TypeError("status.tone must be neutral, info, warning, or error.");
393
+ const nextTone = nextToneValue;
394
+ statusState = {
395
+ text: optionalString(nextStatus["text"], "status.text") ?? statusState.text,
396
+ visible: optionalBoolean(nextStatus["visible"], "status.visible", statusState.visible),
397
+ tone: nextTone,
398
+ color: optionalString(nextStatus["color"], "status.color") ?? statusState.color
399
+ };
400
+ renderMenu();
401
+ },
402
+ dispose() {
403
+ if (disposed) return;
404
+ disposed = true;
405
+ for (const { button, onClick } of buttons.values()) button.removeEventListener("click", onClick);
406
+ buttons.clear();
407
+ root.remove();
408
+ restoreMountPosition?.();
409
+ },
410
+ get element() {
411
+ return root;
412
+ }
413
+ });
414
+ }
415
+ //#endregion
416
+ //#region src/config.ts
417
+ var extensionConfig = {
418
+ id: "kubohiroyaturbowarptitlemenu",
419
+ slug: "turbowarp-title-menu",
420
+ name: "TurboWarp Title Menu",
421
+ description: "Reusable title, application menu, and DSL source storage controls for TurboWarp.",
422
+ author: "Hiroya Kubo",
423
+ license: "MPL-2.0",
424
+ unsandboxed: true,
425
+ homepage: "https://github.com/kubohiroya/turbowarp-title-menu",
426
+ docsURI: "https://kubohiroya.github.io/turbowarp-title-menu/",
427
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNSIgeT0iOCIgd2lkdGg9IjM4IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzAwN2Q2NiIvPjxyZWN0IHg9IjkiIHk9IjEyIiB3aWR0aD0iMzAiIGhlaWdodD0iMjQiIHJ4PSIyIiBmaWxsPSIjZjRmZmZiIi8+PHBhdGggZD0iTTE1IDE5aDE4TTE1IDI0aDE4TTE1IDI5aDEyIiBzdHJva2U9IiMwMDdkNjYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PC9zdmc+"
428
+ };
429
+ //#endregion
430
+ //#region src/dom.ts
431
+ function isRecord(value) {
432
+ return typeof value === "object" && value !== null && !Array.isArray(value);
433
+ }
434
+ function requireDocument(value) {
435
+ if (!isRecord(value) || typeof value.createElement !== "function") throw new TypeError("document must provide createElement");
436
+ return value;
437
+ }
438
+ function requireElement(value, name) {
439
+ if (!isRecord(value) || typeof value.appendChild !== "function") throw new TypeError(`${name} must be a DOM element`);
440
+ return value;
441
+ }
442
+ function ensureRelativeMount(mount) {
443
+ const previous = mount.style.position;
444
+ if (previous === "" || previous === "static") {
445
+ mount.style.position = "relative";
446
+ return () => {
447
+ mount.style.position = previous;
448
+ };
449
+ }
450
+ return () => {};
451
+ }
452
+ function invokeSafely(operation, onError) {
453
+ try {
454
+ Promise.resolve(operation()).catch((error) => onError?.(error));
455
+ } catch (error) {
456
+ onError?.(error);
457
+ }
458
+ }
459
+ //#endregion
460
+ //#region src/dsl-store.ts
461
+ var DslStoreError = class extends Error {
462
+ constructor(code, message, cause) {
463
+ super(message, cause === void 0 ? void 0 : { cause });
464
+ this.name = "DslStoreError";
465
+ this.code = code;
466
+ }
467
+ };
468
+ var defaultDslSort = Object.freeze({
469
+ field: "updatedAt",
470
+ direction: "desc"
471
+ });
472
+ var fileStoreName = "files";
473
+ var metaStoreName = "meta";
474
+ var lastOpenedKey = "last-opened";
475
+ var nameIndexName = "by-name";
476
+ var encoder = new TextEncoder();
477
+ var maximumNameLength = 200;
478
+ /** Rejects control characters so a name cannot break the dialog's text rendering. */
479
+ function hasControlCharacter(value) {
480
+ for (const character of value) {
481
+ const code = character.codePointAt(0) ?? 0;
482
+ if (code < 32 || code === 127) return true;
483
+ }
484
+ return false;
485
+ }
486
+ function normalizeName(value) {
487
+ if (typeof value !== "string") throw new DslStoreError("invalid-name", "DSL name must be a string.");
488
+ const name = value.trim();
489
+ if (name.length === 0) throw new DslStoreError("invalid-name", "DSL name must not be empty.");
490
+ if (name.length > maximumNameLength) throw new DslStoreError("invalid-name", `DSL name must be at most ${maximumNameLength} characters.`);
491
+ if (hasControlCharacter(name)) throw new DslStoreError("invalid-name", "DSL name must not contain control characters.");
492
+ return name;
493
+ }
494
+ function request(input) {
495
+ return new Promise((resolve, reject) => {
496
+ input.onsuccess = () => resolve(input.result);
497
+ input.onerror = () => reject(toStoreError(input.error));
498
+ });
499
+ }
500
+ function transactionDone(transaction) {
501
+ return new Promise((resolve, reject) => {
502
+ transaction.oncomplete = () => resolve();
503
+ transaction.onabort = () => reject(toStoreError(transaction.error));
504
+ transaction.onerror = () => reject(toStoreError(transaction.error));
505
+ });
506
+ }
507
+ function toStoreError(cause) {
508
+ const name = cause?.name;
509
+ if (name === "QuotaExceededError") return new DslStoreError("quota", "Browser storage is full. Delete a saved DSL file first.", cause);
510
+ if (name === "ConstraintError") return new DslStoreError("name-taken", "A DSL file with that name already exists.", cause);
511
+ return new DslStoreError("failed", "The DSL storage operation failed.", cause);
512
+ }
513
+ function compareSummaries(sort) {
514
+ const direction = sort.direction === "asc" ? 1 : -1;
515
+ return (left, right) => {
516
+ if (sort.field === "name") return direction * left.name.localeCompare(right.name, void 0, { numeric: true });
517
+ if (sort.field === "byteLength") return direction * (left.byteLength - right.byteLength) || left.name.localeCompare(right.name);
518
+ return direction * left.updatedAt.localeCompare(right.updatedAt) || left.name.localeCompare(right.name);
519
+ };
520
+ }
521
+ function toSummary(record) {
522
+ return {
523
+ id: record.id,
524
+ name: record.name,
525
+ byteLength: record.byteLength,
526
+ savedAt: record.savedAt,
527
+ updatedAt: record.updatedAt
528
+ };
529
+ }
530
+ function createDslStore(options = {}) {
531
+ const factory = options.indexedDB ?? globalThis.indexedDB;
532
+ if (factory === void 0 || typeof factory.open !== "function") throw new DslStoreError("unavailable", "IndexedDB is not available in this environment.");
533
+ const databaseName = options.databaseName ?? "turbowarp-title-menu";
534
+ const maxSourceBytes = options.maxSourceBytes ?? 1048576;
535
+ const maxFileCount = options.maxFileCount ?? 64;
536
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
537
+ const createId = options.createId ?? defaultCreateId;
538
+ let connection = null;
539
+ function open() {
540
+ connection ?? (connection = new Promise((resolve, reject) => {
541
+ const opening = factory.open(databaseName, 1);
542
+ opening.onupgradeneeded = () => {
543
+ const database = opening.result;
544
+ if (!database.objectStoreNames.contains(fileStoreName)) database.createObjectStore(fileStoreName, { keyPath: "id" }).createIndex(nameIndexName, "name", { unique: true });
545
+ if (!database.objectStoreNames.contains(metaStoreName)) database.createObjectStore(metaStoreName, { keyPath: "key" });
546
+ };
547
+ opening.onsuccess = () => resolve(opening.result);
548
+ opening.onerror = () => reject(toStoreError(opening.error));
549
+ opening.onblocked = () => reject(new DslStoreError("failed", "Another tab is upgrading the DSL database."));
550
+ }));
551
+ return connection;
552
+ }
553
+ async function readAll() {
554
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
555
+ const records = await request(transaction.objectStore(fileStoreName).getAll());
556
+ await transactionDone(transaction);
557
+ return records;
558
+ }
559
+ async function readOne(id) {
560
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
561
+ const record = await request(transaction.objectStore(fileStoreName).get(id));
562
+ await transactionDone(transaction);
563
+ return record ?? null;
564
+ }
565
+ return Object.freeze({
566
+ databaseName,
567
+ async list(sort = defaultDslSort) {
568
+ return (await readAll()).map(toSummary).sort(compareSummaries(sort));
569
+ },
570
+ async count() {
571
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
572
+ const total = await request(transaction.objectStore(fileStoreName).count());
573
+ await transactionDone(transaction);
574
+ return total;
575
+ },
576
+ get(id) {
577
+ return readOne(id);
578
+ },
579
+ async save(file) {
580
+ const name = normalizeName(file.name);
581
+ if (typeof file.source !== "string") throw new DslStoreError("invalid-source", "DSL source must be a string.");
582
+ const byteLength = encoder.encode(file.source).byteLength;
583
+ if (byteLength > maxSourceBytes) throw new DslStoreError("too-large", `DSL source exceeds ${maxSourceBytes} bytes.`);
584
+ const transaction = (await open()).transaction(fileStoreName, "readwrite");
585
+ const files = transaction.objectStore(fileStoreName);
586
+ const existing = await request(files.index(nameIndexName).get(name));
587
+ if (existing === void 0) {
588
+ if (await request(files.count()) >= maxFileCount) {
589
+ transaction.abort();
590
+ throw new DslStoreError("too-many", `The DSL store already holds ${maxFileCount} files.`);
591
+ }
592
+ }
593
+ const timestamp = now().toISOString();
594
+ const record = {
595
+ id: existing?.id ?? createId(),
596
+ name,
597
+ source: file.source,
598
+ byteLength,
599
+ savedAt: existing?.savedAt ?? timestamp,
600
+ updatedAt: timestamp
601
+ };
602
+ await request(files.put(record));
603
+ await transactionDone(transaction);
604
+ return record;
605
+ },
606
+ async rename(id, nextName) {
607
+ const name = normalizeName(nextName);
608
+ const transaction = (await open()).transaction(fileStoreName, "readwrite");
609
+ const files = transaction.objectStore(fileStoreName);
610
+ const existing = await request(files.get(id));
611
+ if (existing === void 0) {
612
+ transaction.abort();
613
+ throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
614
+ }
615
+ if (existing.name !== name) {
616
+ if (await request(files.index(nameIndexName).get(name)) !== void 0) {
617
+ transaction.abort();
618
+ throw new DslStoreError("name-taken", `A DSL file named ${name} already exists.`);
619
+ }
620
+ }
621
+ const record = {
622
+ ...existing,
623
+ name,
624
+ updatedAt: now().toISOString()
625
+ };
626
+ await request(files.put(record));
627
+ await transactionDone(transaction);
628
+ return record;
629
+ },
630
+ async remove(id) {
631
+ const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
632
+ await request(transaction.objectStore(fileStoreName).delete(id));
633
+ const meta = transaction.objectStore(metaStoreName);
634
+ if ((await request(meta.get(lastOpenedKey)))?.id === id) await request(meta.delete(lastOpenedKey));
635
+ await transactionDone(transaction);
636
+ },
637
+ async clear() {
638
+ const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
639
+ await request(transaction.objectStore(fileStoreName).clear());
640
+ await request(transaction.objectStore(metaStoreName).clear());
641
+ await transactionDone(transaction);
642
+ },
643
+ async lastOpened() {
644
+ const transaction = (await open()).transaction(metaStoreName, "readonly");
645
+ const pointer = await request(transaction.objectStore(metaStoreName).get(lastOpenedKey));
646
+ await transactionDone(transaction);
647
+ if (pointer === void 0) return null;
648
+ return readOne(pointer.id);
649
+ },
650
+ async markOpened(id) {
651
+ if (await readOne(id) === null) throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
652
+ const transaction = (await open()).transaction(metaStoreName, "readwrite");
653
+ await request(transaction.objectStore(metaStoreName).put({
654
+ key: lastOpenedKey,
655
+ id
656
+ }));
657
+ await transactionDone(transaction);
658
+ },
659
+ close() {
660
+ const pending = connection;
661
+ connection = null;
662
+ pending?.then((database) => database.close()).catch(() => void 0);
663
+ }
664
+ });
665
+ }
666
+ function defaultCreateId() {
667
+ const crypto = globalThis.crypto;
668
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
669
+ return `dsl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
670
+ }
671
+ /** Reads a picked browser file into a record shape the store accepts. */
672
+ async function readDslFile(file, maxSourceBytes = 1048576) {
673
+ if (typeof file?.text !== "function") throw new DslStoreError("invalid-source", "file must be a browser File.");
674
+ if (file.size > maxSourceBytes) throw new DslStoreError("too-large", `DSL file exceeds ${maxSourceBytes} bytes.`);
675
+ return {
676
+ name: file.name,
677
+ source: await file.text()
678
+ };
679
+ }
680
+ //#endregion
681
+ //#region src/dsl-files-dialog.ts
682
+ var defaultSortDirections = Object.freeze({
683
+ name: "asc",
684
+ updatedAt: "desc",
685
+ byteLength: "desc"
686
+ });
687
+ function requireLocales(value) {
688
+ if (!isRecord(value) || Object.keys(value).length === 0) throw new TypeError("locales must contain at least one locale");
689
+ return value;
690
+ }
691
+ function textFor(locales, locale) {
692
+ const text = locales[locale] ?? locales["en"] ?? Object.values(locales)[0];
693
+ if (text === void 0) throw new TypeError("locales must contain at least one locale");
694
+ return text;
695
+ }
696
+ function defaultFormatSize(byteLength) {
697
+ if (byteLength < 1024) return `${byteLength} B`;
698
+ if (byteLength < 1048576) return `${(byteLength / 1024).toFixed(1)} KB`;
699
+ return `${(byteLength / 1048576).toFixed(1)} MB`;
700
+ }
701
+ function defaultFormatDate(isoDate) {
702
+ const parsed = new Date(isoDate);
703
+ if (Number.isNaN(parsed.getTime())) return isoDate;
704
+ const pad = (value) => String(value).padStart(2, "0");
705
+ return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
706
+ }
707
+ function defaultDescribeError(error) {
708
+ if (error instanceof Error && error.message.length > 0) return error.message;
709
+ return String(error);
710
+ }
711
+ function createDslFilesDialog(options) {
712
+ if (!isRecord(options)) throw new TypeError("DSL files dialog options must be an object");
713
+ const document = requireDocument(options.document ?? globalThis.document);
714
+ const mount = requireElement(options.mount ?? document.body, "mount");
715
+ const locales = requireLocales(options.locales);
716
+ const describeError = options.describeError ?? defaultDescribeError;
717
+ const formatSize = options.formatSize ?? defaultFormatSize;
718
+ const formatDate = options.formatDate ?? defaultFormatDate;
719
+ let locale = options.initialLocale ?? "en";
720
+ let sort = options.initialSort ?? defaultDslSort;
721
+ let summaries = [];
722
+ let renamingId = null;
723
+ let confirmingRemovalId = null;
724
+ let status = "";
725
+ let disposed = false;
726
+ const root = document.createElement("section");
727
+ const panel = document.createElement("div");
728
+ const heading = document.createElement("h1");
729
+ const closeButton = document.createElement("button");
730
+ const toolbar = document.createElement("div");
731
+ const addButton = document.createElement("button");
732
+ const sortBar = document.createElement("div");
733
+ const listElement = document.createElement("div");
734
+ const statusElement = document.createElement("p");
735
+ root.setAttribute("data-turbowarp-title-menu-dsl-files", "true");
736
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483646;align-items:center;justify-content:center;padding:16px;box-sizing:border-box;background:rgba(0,0,0,.6);font-family:sans-serif;";
737
+ root.style.display = "none";
738
+ panel.style.cssText = "width:min(720px,96%);max-height:90%;display:flex;flex-direction:column;gap:10px;padding:18px;box-sizing:border-box;background:#ffffff;color:#1b1f27;border-radius:10px;box-shadow:0 10px 36px rgba(0,0,0,.45);overflow:hidden;";
739
+ heading.style.cssText = "margin:0;font-size:20px;line-height:1.3;";
740
+ toolbar.style.cssText = "display:flex;gap:8px;align-items:center;flex-wrap:wrap;";
741
+ sortBar.style.cssText = "display:flex;gap:6px;align-items:center;flex-wrap:wrap;";
742
+ listElement.style.cssText = "flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:6px;";
743
+ statusElement.style.cssText = "margin:0;min-height:18px;font-size:13px;color:#8a1c1c;";
744
+ const headerRow = document.createElement("div");
745
+ headerRow.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:8px;";
746
+ headerRow.appendChild(heading);
747
+ headerRow.appendChild(closeButton);
748
+ panel.appendChild(headerRow);
749
+ toolbar.appendChild(addButton);
750
+ toolbar.appendChild(sortBar);
751
+ panel.appendChild(toolbar);
752
+ panel.appendChild(listElement);
753
+ panel.appendChild(statusElement);
754
+ root.appendChild(panel);
755
+ const previousMountPosition = mount.style.position;
756
+ if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = "relative";
757
+ mount.appendChild(root);
758
+ function styleButton(button, tone) {
759
+ const palette = {
760
+ primary: "background:#1f6feb;color:#ffffff;border:1px solid #1f6feb;",
761
+ plain: "background:#f2f4f8;color:#1b1f27;border:1px solid #ccd2de;",
762
+ danger: "background:#b42318;color:#ffffff;border:1px solid #b42318;",
763
+ active: "background:#d7e6ff;color:#0b3a82;border:1px solid #1f6feb;"
764
+ }[tone];
765
+ button.style.cssText = `${palette}padding:5px 10px;border-radius:6px;font-size:13px;cursor:pointer;`;
766
+ }
767
+ function run(operation) {
768
+ try {
769
+ Promise.resolve(operation()).catch(handleFailure);
770
+ } catch (error) {
771
+ handleFailure(error);
772
+ }
773
+ }
774
+ function handleFailure(error) {
775
+ status = describeError(error);
776
+ options.onError?.(error);
777
+ render();
778
+ }
779
+ /** Every mutation goes through here so the list and the status line stay in step. */
780
+ function mutate(operation) {
781
+ run(async () => {
782
+ status = "";
783
+ try {
784
+ await operation();
785
+ } catch (error) {
786
+ status = describeError(error);
787
+ options.onError?.(error);
788
+ render();
789
+ return;
790
+ }
791
+ await reload();
792
+ });
793
+ }
794
+ async function reload() {
795
+ if (disposed) return;
796
+ summaries = await options.list(sort);
797
+ render();
798
+ }
799
+ function selectSort(field) {
800
+ if (sort.field === field) sort = {
801
+ field,
802
+ direction: sort.direction === "asc" ? "desc" : "asc"
803
+ };
804
+ else sort = {
805
+ field,
806
+ direction: defaultSortDirections[field]
807
+ };
808
+ renamingId = null;
809
+ confirmingRemovalId = null;
810
+ mutate(() => void 0);
811
+ }
812
+ function createButton(label, tone, onClick) {
813
+ const button = document.createElement("button");
814
+ button.type = "button";
815
+ button.textContent = label;
816
+ styleButton(button, tone);
817
+ button.addEventListener("click", onClick);
818
+ return button;
819
+ }
820
+ function renderSortBar(text) {
821
+ const arrow = sort.direction === "asc" ? " ▲" : " ▼";
822
+ const fields = [
823
+ ["name", text.sortByName],
824
+ ["updatedAt", text.sortByDate],
825
+ ["byteLength", text.sortBySize]
826
+ ];
827
+ for (const [field, label] of fields) {
828
+ const active = sort.field === field;
829
+ const button = createButton(active ? `${label}${arrow}` : label, active ? "active" : "plain", () => selectSort(field));
830
+ button.setAttribute("data-sort-field", field);
831
+ if (active) button.setAttribute("aria-pressed", "true");
832
+ sortBar.appendChild(button);
833
+ }
834
+ }
835
+ function renderRow(summary, text) {
836
+ const row = document.createElement("div");
837
+ row.setAttribute("data-dsl-file-id", summary.id);
838
+ row.style.cssText = "display:flex;align-items:center;gap:8px;padding:8px;border:1px solid #e2e6ee;border-radius:8px;";
839
+ if (renamingId === summary.id) {
840
+ const input = document.createElement("input");
841
+ input.type = "text";
842
+ input.value = summary.name;
843
+ input.setAttribute("data-rename-input", summary.id);
844
+ input.style.cssText = "flex:1;min-width:0;padding:5px 8px;border:1px solid #1f6feb;border-radius:6px;font-size:14px;";
845
+ const commit = () => {
846
+ const nextName = input.value;
847
+ renamingId = null;
848
+ mutate(() => options.onRename(summary.id, nextName));
849
+ };
850
+ input.addEventListener("keydown", (event) => {
851
+ const key = event.key;
852
+ if (key === "Enter") commit();
853
+ if (key === "Escape") {
854
+ renamingId = null;
855
+ render();
856
+ }
857
+ });
858
+ row.appendChild(input);
859
+ row.appendChild(createButton(text.confirm, "primary", commit));
860
+ row.appendChild(createButton(text.cancel, "plain", () => {
861
+ renamingId = null;
862
+ render();
863
+ }));
864
+ return row;
865
+ }
866
+ const name = document.createElement("span");
867
+ name.textContent = summary.name;
868
+ name.style.cssText = "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;";
869
+ const date = document.createElement("span");
870
+ date.textContent = formatDate(summary.updatedAt);
871
+ date.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;";
872
+ const size = document.createElement("span");
873
+ size.textContent = formatSize(summary.byteLength);
874
+ size.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;";
875
+ row.appendChild(name);
876
+ row.appendChild(date);
877
+ row.appendChild(size);
878
+ if (confirmingRemovalId === summary.id) {
879
+ row.appendChild(createButton(text.confirmRemove, "danger", () => {
880
+ confirmingRemovalId = null;
881
+ mutate(() => options.onRemove(summary.id));
882
+ }));
883
+ row.appendChild(createButton(text.cancel, "plain", () => {
884
+ confirmingRemovalId = null;
885
+ render();
886
+ }));
887
+ return row;
888
+ }
889
+ row.appendChild(createButton(text.open, "primary", () => {
890
+ mutate(() => options.onOpen(summary.id));
891
+ }));
892
+ row.appendChild(createButton(text.rename, "plain", () => {
893
+ renamingId = summary.id;
894
+ confirmingRemovalId = null;
895
+ render();
896
+ }));
897
+ row.appendChild(createButton(text.remove, "plain", () => {
898
+ confirmingRemovalId = summary.id;
899
+ renamingId = null;
900
+ render();
901
+ }));
902
+ return row;
903
+ }
904
+ function render() {
905
+ if (disposed) return;
906
+ const text = textFor(locales, locale);
907
+ heading.textContent = text.title;
908
+ closeButton.textContent = text.close;
909
+ closeButton.setAttribute("aria-label", text.close);
910
+ addButton.textContent = text.add;
911
+ statusElement.textContent = status;
912
+ sortBar.replaceChildren();
913
+ renderSortBar(text);
914
+ listElement.replaceChildren();
915
+ if (summaries.length === 0) {
916
+ const empty = document.createElement("p");
917
+ empty.textContent = text.empty;
918
+ empty.style.cssText = "margin:8px 0;font-size:14px;color:#5a6172;";
919
+ listElement.appendChild(empty);
920
+ } else for (const summary of summaries) listElement.appendChild(renderRow(summary, text));
921
+ }
922
+ styleButton(closeButton, "plain");
923
+ styleButton(addButton, "primary");
924
+ closeButton.type = "button";
925
+ addButton.type = "button";
926
+ closeButton.addEventListener("click", () => hide());
927
+ addButton.addEventListener("click", () => {
928
+ mutate(() => options.onAdd());
929
+ });
930
+ function hide() {
931
+ if (disposed) return;
932
+ renamingId = null;
933
+ confirmingRemovalId = null;
934
+ root.style.display = "none";
935
+ }
936
+ function ensureActive() {
937
+ if (disposed) throw new TypeError("DSL files dialog is disposed");
938
+ }
939
+ render();
940
+ return Object.freeze({
941
+ element: root,
942
+ get locale() {
943
+ return locale;
944
+ },
945
+ get sort() {
946
+ return sort;
947
+ },
948
+ async show(nextLocale) {
949
+ ensureActive();
950
+ if (nextLocale !== void 0) locale = nextLocale;
951
+ status = "";
952
+ root.style.display = "flex";
953
+ await reload();
954
+ return locale;
955
+ },
956
+ hide,
957
+ async refresh() {
958
+ ensureActive();
959
+ await reload();
960
+ },
961
+ setLocale(nextLocale) {
962
+ ensureActive();
963
+ locale = nextLocale;
964
+ render();
965
+ return locale;
966
+ },
967
+ dispose() {
968
+ if (disposed) return;
969
+ disposed = true;
970
+ root.remove();
971
+ if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = previousMountPosition;
972
+ }
973
+ });
974
+ }
975
+ //#endregion
976
+ //#region src/events.ts
977
+ var dslOpenEventName = "turbowarp-title-menu:dsl-open";
978
+ var dslReloadEventName = "turbowarp-title-menu:dsl-reload";
979
+ /**
980
+ * Announces an opened DSL source on the window.
981
+ *
982
+ * The extension also starts a Scratch hat, but a packaged host that embeds this extension may run
983
+ * its own runtime outside the VM, so the DOM event stays the transport that assumes no Scratch.
984
+ */
985
+ function dispatchDslSourceEvent(type, record) {
986
+ const target = globalThis;
987
+ if (typeof target.dispatchEvent !== "function") return;
988
+ const event = typeof CustomEvent === "function" ? new CustomEvent(type, { detail: { record } }) : new Event(type);
989
+ if (!("detail" in event)) Object.defineProperty(event, "detail", { value: { record } });
990
+ target.dispatchEvent(event);
991
+ }
992
+ //#endregion
993
+ //#region src/title-dialog.ts
994
+ function requireLocaleText(locales, locale) {
995
+ const text = locales[locale] ?? locales.en ?? Object.values(locales)[0];
996
+ if (!text) throw new TypeError("locales must contain at least one locale");
997
+ for (const key of [
998
+ "title",
999
+ "website",
1000
+ "close"
1001
+ ]) if (typeof text[key] !== "string" || text[key].length === 0) throw new TypeError(`locales.${locale}.${key} must be a non-empty string`);
1002
+ return text;
1003
+ }
1004
+ function openWebsite(url) {
1005
+ const opener = globalThis.open;
1006
+ if (typeof opener === "function") opener(url, "_blank", "noopener,noreferrer");
1007
+ else if (globalThis.location) globalThis.location.href = url;
1008
+ }
1009
+ function createTitleDialog(options) {
1010
+ const document = requireDocument(options.document ?? globalThis.document);
1011
+ const mount = requireElement(options.mount ?? document.body, "mount");
1012
+ const locales = options.locales;
1013
+ if (!locales || typeof locales !== "object") throw new TypeError("locales must be an object");
1014
+ const root = document.createElement("section");
1015
+ const panel = document.createElement("div");
1016
+ const language = document.createElement("button");
1017
+ const close = document.createElement("button");
1018
+ const heading = document.createElement("h1");
1019
+ const meta = document.createElement("p");
1020
+ const website = document.createElement("button");
1021
+ root.setAttribute("data-turbowarp-title-dialog", "true");
1022
+ root.setAttribute("role", "dialog");
1023
+ root.setAttribute("aria-modal", "true");
1024
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483647;display:none;align-items:center;justify-content:center;box-sizing:border-box;background:rgba(0,0,0,.35);font-family:sans-serif;";
1025
+ panel.style.cssText = "position:relative;box-sizing:border-box;width:min(88%,420px);padding:36px 28px 28px;text-align:center;background:#f4fffb;border:1px solid #007d66;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.3);color:#006b58;";
1026
+ language.style.cssText = "position:absolute;top:14px;left:16px;border:0;background:transparent;color:#007d66;font-size:14px;cursor:pointer;";
1027
+ close.style.cssText = "position:absolute;top:12px;right:12px;width:32px;height:32px;border:0;border-radius:50%;background:#007d66;color:#fff;font-size:22px;line-height:28px;cursor:pointer;";
1028
+ heading.style.cssText = "margin:0 24px 8px;font-size:30px;font-weight:600;line-height:1.15;";
1029
+ meta.style.cssText = "margin:0 0 22px;font-size:14px;line-height:1.4;";
1030
+ website.style.cssText = "display:inline-flex;align-items:center;justify-content:center;min-height:48px;padding:8px 18px;border:0;border-radius:10px;background:#007d66;color:#fff;font-size:16px;cursor:pointer;";
1031
+ language.type = "button";
1032
+ close.type = "button";
1033
+ website.type = "button";
1034
+ close.textContent = "x";
1035
+ panel.append(language, close, heading, meta, website);
1036
+ root.appendChild(panel);
1037
+ const restoreMount = ensureRelativeMount(mount);
1038
+ mount.appendChild(root);
1039
+ let locale = options.initialLocale ?? (locales.ja ? "ja" : Object.keys(locales)[0] ?? "en");
1040
+ let disposed = false;
1041
+ const render = () => {
1042
+ const text = requireLocaleText(locales, locale);
1043
+ heading.textContent = text.title;
1044
+ meta.textContent = [text.author, text.license].filter(Boolean).join(" / ");
1045
+ meta.hidden = meta.textContent.length === 0;
1046
+ website.textContent = text.website;
1047
+ website.setAttribute("aria-label", text.website);
1048
+ close.setAttribute("aria-label", text.close);
1049
+ close.setAttribute("title", text.close);
1050
+ language.textContent = text.language ?? locale;
1051
+ language.setAttribute("aria-label", text.language ?? locale);
1052
+ };
1053
+ const handleWebsite = () => {
1054
+ if (options.onWebsite) invokeSafely(options.onWebsite, options.onError);
1055
+ else if (options.websiteUrl) openWebsite(options.websiteUrl);
1056
+ };
1057
+ const handleClose = () => {
1058
+ hide();
1059
+ if (options.onClose) invokeSafely(options.onClose, options.onError);
1060
+ };
1061
+ const handleLanguage = () => {
1062
+ const keys = Object.keys(locales);
1063
+ locale = keys[(Math.max(keys.indexOf(locale), 0) + 1) % keys.length] ?? locale;
1064
+ render();
1065
+ if (options.onLocaleChange) invokeSafely(() => options.onLocaleChange?.(locale), options.onError);
1066
+ };
1067
+ website.addEventListener("click", handleWebsite);
1068
+ close.addEventListener("click", handleClose);
1069
+ language.addEventListener("click", handleLanguage);
1070
+ function show(nextLocale = locale) {
1071
+ if (disposed) throw new TypeError("title dialog is disposed");
1072
+ locale = nextLocale;
1073
+ render();
1074
+ root.style.display = "flex";
1075
+ return locale;
1076
+ }
1077
+ function hide() {
1078
+ if (!disposed) root.style.display = "none";
1079
+ }
1080
+ function setLocale(nextLocale) {
1081
+ if (disposed) throw new TypeError("title dialog is disposed");
1082
+ locale = nextLocale;
1083
+ render();
1084
+ return locale;
1085
+ }
1086
+ function dispose() {
1087
+ if (disposed) return;
1088
+ disposed = true;
1089
+ website.removeEventListener("click", handleWebsite);
1090
+ close.removeEventListener("click", handleClose);
1091
+ language.removeEventListener("click", handleLanguage);
1092
+ root.remove();
1093
+ restoreMount();
1094
+ }
1095
+ render();
1096
+ return Object.freeze({
1097
+ element: root,
1098
+ get locale() {
1099
+ return locale;
1100
+ },
1101
+ show,
1102
+ hide,
1103
+ setLocale,
1104
+ dispose
1105
+ });
1106
+ }
1107
+ var block_definitions_default = {
1108
+ extensionName: "TurboWarp Title Menu",
1109
+ menus: { "menuActions": {
1110
+ "acceptReporters": false,
1111
+ "items": "menuActionItems"
1112
+ } },
1113
+ blocks: [
1114
+ {
1115
+ "opcode": "showTitle",
1116
+ "blockType": "COMMAND",
1117
+ "text": "show title dialog",
1118
+ "description": "Shows the configured title dialog above the TurboWarp stage."
1119
+ },
1120
+ {
1121
+ "opcode": "showMenu",
1122
+ "blockType": "COMMAND",
1123
+ "text": "show application menu",
1124
+ "description": "Shows the application menu above the TurboWarp stage."
1125
+ },
1126
+ {
1127
+ "opcode": "addAppMenuAction",
1128
+ "blockType": "COMMAND",
1129
+ "text": "add app menu action [ACTION] labelled [LABEL]",
1130
+ "description": "Adds an application menu action this project owns, or relabels one it already added.",
1131
+ "arguments": {
1132
+ "ACTION": {
1133
+ "type": "STRING",
1134
+ "defaultValue": "start"
1135
+ },
1136
+ "LABEL": {
1137
+ "type": "STRING",
1138
+ "defaultValue": "Start"
1139
+ }
1140
+ }
1141
+ },
1142
+ {
1143
+ "opcode": "clearAppMenuActions",
1144
+ "blockType": "COMMAND",
1145
+ "text": "clear app menu actions",
1146
+ "description": "Removes every application menu action, including the built-in ones, so a project can define its own set."
1147
+ },
1148
+ {
1149
+ "opcode": "setAppMenuActionEnabled",
1150
+ "blockType": "COMMAND",
1151
+ "text": "set app menu action [ACTION] enabled [ENABLED]",
1152
+ "description": "Enables or disables one application menu action.",
1153
+ "arguments": {
1154
+ "ACTION": {
1155
+ "type": "STRING",
1156
+ "menu": "menuActions"
1157
+ },
1158
+ "ENABLED": {
1159
+ "type": "BOOLEAN",
1160
+ "defaultValue": true
1161
+ }
1162
+ }
1163
+ },
1164
+ {
1165
+ "opcode": "whenAppMenuActionSelected",
1166
+ "blockType": "HAT",
1167
+ "text": "when app menu action [ACTION] selected",
1168
+ "description": "Runs when the operator selects the named application menu action.",
1169
+ "arguments": { "ACTION": {
1170
+ "type": "STRING",
1171
+ "menu": "menuActions"
1172
+ } }
1173
+ },
1174
+ {
1175
+ "opcode": "showDslFiles",
1176
+ "blockType": "COMMAND",
1177
+ "text": "show DSL file manager",
1178
+ "description": "Shows the dialog that adds, opens, renames, deletes, and sorts stored DSL files."
1179
+ },
1180
+ {
1181
+ "opcode": "whenDslSourceOpened",
1182
+ "blockType": "HAT",
1183
+ "text": "when a DSL source is opened",
1184
+ "description": "Runs after the operator opens a stored DSL file, or after the opened source is announced again."
1185
+ },
1186
+ {
1187
+ "opcode": "reloadOpenedDsl",
1188
+ "blockType": "COMMAND",
1189
+ "text": "reload the opened DSL source",
1190
+ "description": "Announces the currently opened DSL source again without showing a dialog."
1191
+ },
1192
+ {
1193
+ "opcode": "openedDslName",
1194
+ "blockType": "REPORTER",
1195
+ "text": "opened DSL file name",
1196
+ "description": "Returns the name of the DSL file that is currently open, or an empty string."
1197
+ },
1198
+ {
1199
+ "opcode": "openedDslSource",
1200
+ "blockType": "REPORTER",
1201
+ "text": "opened DSL source",
1202
+ "description": "Returns the text of the DSL file that is currently open, or an empty string."
1203
+ },
1204
+ {
1205
+ "opcode": "hasSavedDsl",
1206
+ "blockType": "BOOLEAN",
1207
+ "text": "has a saved DSL file?",
1208
+ "description": "Reports whether at least one DSL file is stored in IndexedDB."
1209
+ },
1210
+ {
1211
+ "opcode": "savedDslCount",
1212
+ "blockType": "REPORTER",
1213
+ "text": "saved DSL file count",
1214
+ "description": "Returns how many DSL files are stored in IndexedDB."
1215
+ },
1216
+ {
1217
+ "opcode": "lastDslError",
1218
+ "blockType": "REPORTER",
1219
+ "text": "last DSL storage error",
1220
+ "description": "Returns the most recent DSL storage failure in the interface language, or an empty string."
1221
+ }
1222
+ ]
1223
+ };
1224
+ //#endregion
1225
+ //#region src/locales.ts
1226
+ var titleLocales = Object.freeze({
1227
+ en: {
1228
+ title: "TurboWarp Title Menu",
1229
+ author: "Author: Hiroya Kubo",
1230
+ license: "License: MPL-2.0",
1231
+ website: "Official Website",
1232
+ close: "Close"
1233
+ },
1234
+ ja: {
1235
+ title: "TurboWarp Title Menu",
1236
+ author: "作者: Hiroya Kubo",
1237
+ license: "ライセンス: MPL-2.0",
1238
+ website: "公式Webサイト",
1239
+ close: "閉じる"
1240
+ }
1241
+ });
1242
+ var menuLocales = Object.freeze({
1243
+ en: {
1244
+ files: "DSL files",
1245
+ reload: "Reload DSL",
1246
+ about: "About",
1247
+ close: "Close"
1248
+ },
1249
+ ja: {
1250
+ files: "DSLファイル",
1251
+ reload: "DSLを再読み込み",
1252
+ about: "情報",
1253
+ close: "閉じる"
1254
+ }
1255
+ });
1256
+ var dslFilesLocales = Object.freeze({
1257
+ en: {
1258
+ title: "DSL files",
1259
+ add: "Add file",
1260
+ open: "Open",
1261
+ rename: "Rename",
1262
+ remove: "Delete",
1263
+ confirmRemove: "Delete for good?",
1264
+ confirm: "OK",
1265
+ cancel: "Cancel",
1266
+ close: "Close",
1267
+ sortByName: "Name",
1268
+ sortByDate: "Updated",
1269
+ sortBySize: "Size",
1270
+ empty: "No DSL file is saved yet. Use Add file to store one."
1271
+ },
1272
+ ja: {
1273
+ title: "DSLファイル",
1274
+ add: "ファイルを追加",
1275
+ open: "開く",
1276
+ rename: "名前を変える",
1277
+ remove: "削除",
1278
+ confirmRemove: "本当に削除?",
1279
+ confirm: "OK",
1280
+ cancel: "やめる",
1281
+ close: "閉じる",
1282
+ sortByName: "名前",
1283
+ sortByDate: "更新日時",
1284
+ sortBySize: "サイズ",
1285
+ empty: "保存されたDSLファイルはありません。「ファイルを追加」から保存してください。"
1286
+ }
1287
+ });
1288
+ var storeErrorMessages = Object.freeze({
1289
+ en: {
1290
+ unavailable: "Browser storage is unavailable, so DSL files cannot be saved.",
1291
+ "invalid-name": "That file name cannot be used.",
1292
+ "invalid-source": "That file could not be read as text.",
1293
+ "name-taken": "Another DSL file already uses that name.",
1294
+ "too-large": "That DSL file is too large to store.",
1295
+ "too-many": "The DSL store is full. Delete a file before adding another.",
1296
+ "not-found": "That DSL file is no longer stored.",
1297
+ quota: "Browser storage is full. Delete a DSL file and try again.",
1298
+ failed: "The DSL storage operation failed."
1299
+ },
1300
+ ja: {
1301
+ unavailable: "ブラウザの保存領域が使えないため、DSLファイルを保存できません。",
1302
+ "invalid-name": "そのファイル名は使えません。",
1303
+ "invalid-source": "そのファイルをテキストとして読み込めませんでした。",
1304
+ "name-taken": "同じ名前のDSLファイルがすでにあります。",
1305
+ "too-large": "そのDSLファイルは大きすぎて保存できません。",
1306
+ "too-many": "保存できる数に達しています。どれかを削除してから追加してください。",
1307
+ "not-found": "そのDSLファイルは保存されていません。",
1308
+ quota: "ブラウザの保存領域がいっぱいです。DSLファイルを削除してからやり直してください。",
1309
+ failed: "DSLファイルの操作に失敗しました。"
1310
+ }
1311
+ });
1312
+ /** Turns a store error code into operator-facing text, falling back to the raw message. */
1313
+ function describeStoreError(locale, error) {
1314
+ const code = error?.code;
1315
+ const messages = storeErrorMessages[locale] ?? storeErrorMessages.en;
1316
+ if (code !== void 0 && code in messages) return messages[code];
1317
+ if (error instanceof Error && error.message.length > 0) return error.message;
1318
+ return String(error);
1319
+ }
1320
+ //#endregion
1321
+ //#region src/extension.ts
1322
+ var blockDefinitions = block_definitions_default.blocks;
1323
+ var dslFileAccept = ".txt,.yaml,.yml,.json,.k4,.kamishibai";
1324
+ /** Reserved action IDs the extension handles itself. A project may still remove or relabel them. */
1325
+ var builtinActionIds = [
1326
+ "files",
1327
+ "reload",
1328
+ "about",
1329
+ "close"
1330
+ ];
1331
+ function stageMount() {
1332
+ return Scratch.vm?.renderer?.canvas?.parentElement ?? globalThis.document?.body;
1333
+ }
1334
+ var TurboWarpTitleMenuExtension = class {
1335
+ constructor() {
1336
+ this.titleDialog = null;
1337
+ this.applicationMenu = null;
1338
+ this.filesDialog = null;
1339
+ this.store = null;
1340
+ this.openedRecord = null;
1341
+ this.lastError = "";
1342
+ this.menuActions = builtinActionIds.map((id) => ({
1343
+ id,
1344
+ labels: {
1345
+ en: menuLocales.en[id],
1346
+ ja: menuLocales.ja[id]
1347
+ },
1348
+ enabled: true
1349
+ }));
1350
+ this.menuVisible = false;
1351
+ }
1352
+ getInfo() {
1353
+ return {
1354
+ id: extensionConfig.id,
1355
+ name: Scratch.translate(block_definitions_default.extensionName),
1356
+ docsURI: extensionConfig.docsURI,
1357
+ blockIconURI: extensionConfig.blockIconURI,
1358
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
1359
+ menus: block_definitions_default.menus
1360
+ };
1361
+ }
1362
+ showTitle() {
1363
+ this.ensureTitleDialog().show(this.locale());
1364
+ }
1365
+ /**
1366
+ * Shows the application menu.
1367
+ *
1368
+ * An empty registry does nothing: the underlying primitive requires at least one action, and a
1369
+ * project that cleared the actions to install its own should not be interrupted by an error
1370
+ * between the two steps.
1371
+ */
1372
+ showMenu() {
1373
+ if (this.menuActions.length === 0) return;
1374
+ this.ensureApplicationMenu().show(this.locale());
1375
+ this.menuVisible = true;
1376
+ }
1377
+ /**
1378
+ * Backs the dynamic `menuActions` dropdown, so it always lists what the project registered.
1379
+ *
1380
+ * The menu must refuse reporters. Scratch turns a reporter-accepting menu argument into an input
1381
+ * holding a shadow block, and `startHats` matches a hat against its *fields*, so the action hat
1382
+ * would never fire for a specific action. Refusing reporters keeps the argument an inline
1383
+ * dropdown, which is what the match reads.
1384
+ */
1385
+ menuActionItems() {
1386
+ if (this.menuActions.length === 0) return [{
1387
+ text: "—",
1388
+ value: ""
1389
+ }];
1390
+ const locale = this.locale();
1391
+ return this.menuActions.map((action) => ({
1392
+ text: action.labels[locale],
1393
+ value: action.id
1394
+ }));
1395
+ }
1396
+ addAppMenuAction(args) {
1397
+ const id = Scratch.Cast.toString(args.ACTION).trim();
1398
+ if (id.length === 0) return;
1399
+ const label = Scratch.Cast.toString(args.LABEL);
1400
+ const existing = this.menuActions.find((action) => action.id === id);
1401
+ if (existing === void 0) this.menuActions.push({
1402
+ id,
1403
+ labels: {
1404
+ en: label,
1405
+ ja: label
1406
+ },
1407
+ enabled: true
1408
+ });
1409
+ else existing.labels = {
1410
+ en: label,
1411
+ ja: label
1412
+ };
1413
+ this.rebuildMenu();
1414
+ }
1415
+ clearAppMenuActions() {
1416
+ this.menuActions = [];
1417
+ this.rebuildMenu();
1418
+ }
1419
+ setAppMenuActionEnabled(args) {
1420
+ const id = Scratch.Cast.toString(args.ACTION);
1421
+ const action = this.menuActions.find((entry) => entry.id === id);
1422
+ if (action === void 0) return;
1423
+ action.enabled = Scratch.Cast.toBoolean(args.ENABLED);
1424
+ this.applicationMenu?.setActionState(id, { enabled: action.enabled });
1425
+ }
1426
+ /** Started by the menu callback, so the handler only has to accept the match. */
1427
+ whenAppMenuActionSelected() {
1428
+ return true;
1429
+ }
1430
+ showDslFiles() {
1431
+ return this.ensureFilesDialog().show(this.locale());
1432
+ }
1433
+ /** The hat is started by the open path, so its own handler only has to accept the match. */
1434
+ whenDslSourceOpened() {
1435
+ return true;
1436
+ }
1437
+ reloadOpenedDsl() {
1438
+ if (this.openedRecord === null) return;
1439
+ this.announce(dslReloadEventName, this.openedRecord);
1440
+ }
1441
+ openedDslName() {
1442
+ return this.openedRecord?.name ?? "";
1443
+ }
1444
+ openedDslSource() {
1445
+ return this.openedRecord?.source ?? "";
1446
+ }
1447
+ async hasSavedDsl() {
1448
+ return await this.savedDslCount() > 0;
1449
+ }
1450
+ async savedDslCount() {
1451
+ try {
1452
+ return await this.requireStore().count();
1453
+ } catch (error) {
1454
+ this.recordFailure(error);
1455
+ return 0;
1456
+ }
1457
+ }
1458
+ lastDslError() {
1459
+ return this.lastError;
1460
+ }
1461
+ locale() {
1462
+ return resolveAppShellLocale() === "ja" ? "ja" : "en";
1463
+ }
1464
+ /**
1465
+ * Opens the store on first use.
1466
+ *
1467
+ * A browser without IndexedDB, or one with storage blocked, fails here rather than at extension
1468
+ * load: the title and menu blocks stay usable even when nothing can be stored.
1469
+ */
1470
+ requireStore() {
1471
+ this.store ?? (this.store = createDslStore({ databaseName: extensionConfig.id }));
1472
+ return this.store;
1473
+ }
1474
+ recordFailure(error) {
1475
+ this.lastError = describeStoreError(this.locale(), error);
1476
+ }
1477
+ /**
1478
+ * Rebuilds the menu after its action list changed.
1479
+ *
1480
+ * The app-shell primitive fixes its actions at construction, so a changed list means a new menu.
1481
+ * A menu that was on screen is shown again, because a project that adds an action while the menu
1482
+ * is open should not have it silently disappear. Clearing every action closes the menu instead,
1483
+ * because the primitive refuses to build one with no actions.
1484
+ */
1485
+ rebuildMenu() {
1486
+ this.applicationMenu?.dispose();
1487
+ this.applicationMenu = null;
1488
+ if (!this.menuVisible) return;
1489
+ if (this.menuActions.length === 0) {
1490
+ this.menuVisible = false;
1491
+ return;
1492
+ }
1493
+ this.showMenu();
1494
+ }
1495
+ selectMenuAction(id) {
1496
+ Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenAppMenuActionSelected`, { ACTION: id });
1497
+ if (!builtinActionIds.includes(id)) return;
1498
+ if (id === "files") this.showDslFiles();
1499
+ if (id === "reload") this.reloadOpenedDsl();
1500
+ if (id === "about") this.showTitle();
1501
+ if (id === "close") this.hideMenu();
1502
+ }
1503
+ hideMenu() {
1504
+ this.applicationMenu?.hide();
1505
+ this.menuVisible = false;
1506
+ }
1507
+ announce(eventName, record) {
1508
+ dispatchDslSourceEvent(eventName, record);
1509
+ Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenDslSourceOpened`);
1510
+ }
1511
+ ensureTitleDialog() {
1512
+ if (this.titleDialog) return this.titleDialog;
1513
+ const mount = stageMount();
1514
+ this.titleDialog = createTitleDialog({
1515
+ document: globalThis.document,
1516
+ ...mount ? { mount } : {},
1517
+ locales: titleLocales,
1518
+ initialLocale: this.locale(),
1519
+ websiteUrl: extensionConfig.homepage
1520
+ });
1521
+ return this.titleDialog;
1522
+ }
1523
+ /**
1524
+ * Builds the menu from the shared app-shell primitive.
1525
+ *
1526
+ * The actions below are this extension's own vocabulary, not the primitive's: a host application
1527
+ * that needs different actions composes `createAppShellApplicationMenu` itself through the
1528
+ * composition API instead of being limited to these four.
1529
+ */
1530
+ ensureApplicationMenu() {
1531
+ if (this.applicationMenu) return this.applicationMenu;
1532
+ const mount = stageMount();
1533
+ if (mount === void 0) throw new TypeError("a stage container is required to show the menu");
1534
+ this.applicationMenu = createAppShellApplicationMenu({
1535
+ document: globalThis.document,
1536
+ mount,
1537
+ initialLocale: this.locale(),
1538
+ actions: this.menuActions.map((action) => ({
1539
+ id: action.id,
1540
+ labels: action.labels,
1541
+ enabled: action.enabled,
1542
+ onSelect: () => this.selectMenuAction(action.id)
1543
+ }))
1544
+ });
1545
+ return this.applicationMenu;
1546
+ }
1547
+ ensureFilesDialog() {
1548
+ if (this.filesDialog) return this.filesDialog;
1549
+ const mount = stageMount();
1550
+ this.filesDialog = createDslFilesDialog({
1551
+ document: globalThis.document,
1552
+ ...mount ? { mount } : {},
1553
+ locales: dslFilesLocales,
1554
+ initialLocale: this.locale(),
1555
+ list: (sort) => this.requireStore().list(sort),
1556
+ onAdd: () => this.addDslFile(),
1557
+ onOpen: (id) => this.openDslFile(id),
1558
+ onRename: (id, name) => this.requireStore().rename(id, name),
1559
+ onRemove: (id) => this.removeDslFile(id),
1560
+ describeError: (error) => describeStoreError(this.locale(), error),
1561
+ onError: (error) => this.recordFailure(error)
1562
+ });
1563
+ return this.filesDialog;
1564
+ }
1565
+ async addDslFile() {
1566
+ const chosen = await this.pickDslFile();
1567
+ if (chosen === null) return;
1568
+ await this.requireStore().save(await readDslFile(chosen));
1569
+ this.lastError = "";
1570
+ }
1571
+ async openDslFile(id) {
1572
+ const store = this.requireStore();
1573
+ const record = await store.get(id);
1574
+ if (record === null) return;
1575
+ await store.markOpened(id);
1576
+ this.openedRecord = record;
1577
+ this.lastError = "";
1578
+ this.announce(dslOpenEventName, record);
1579
+ }
1580
+ async removeDslFile(id) {
1581
+ await this.requireStore().remove(id);
1582
+ if (this.openedRecord?.id === id) this.openedRecord = null;
1583
+ this.lastError = "";
1584
+ }
1585
+ pickDslFile() {
1586
+ const document = globalThis.document;
1587
+ if (!document) throw new TypeError("document is required to open a DSL file");
1588
+ const input = document.createElement("input");
1589
+ input.type = "file";
1590
+ input.accept = dslFileAccept;
1591
+ return new Promise((resolve) => {
1592
+ input.addEventListener("change", () => {
1593
+ resolve(input.files?.[0] ?? null);
1594
+ }, { once: true });
1595
+ input.click();
1596
+ });
1597
+ }
1598
+ toScratchBlock(block) {
1599
+ const scratchBlock = {
1600
+ opcode: block.opcode,
1601
+ blockType: Scratch.BlockType[block.blockType],
1602
+ text: Scratch.translate(block.text),
1603
+ arguments: Object.fromEntries(Object.entries(block.arguments ?? {}).map(([name, argument]) => [name, {
1604
+ type: Scratch.ArgumentType[argument.type],
1605
+ ...argument.defaultValue === void 0 ? {} : { defaultValue: argument.defaultValue },
1606
+ ...argument.menu === void 0 ? {} : { menu: argument.menu }
1607
+ }]))
1608
+ };
1609
+ if (block.blockType === "HAT") scratchBlock["isEdgeActivated"] = false;
1610
+ return scratchBlock;
1611
+ }
1612
+ };
1613
+ //#endregion
1614
+ //#region src/index.ts
1615
+ var publicApi = Object.freeze({
1616
+ createApplicationMenu: createAppShellApplicationMenu,
1617
+ createDslFilesDialog,
1618
+ createDslStore,
1619
+ createTitleDialog,
1620
+ dslOpenEventName,
1621
+ dslReloadEventName
1622
+ });
1623
+ Object.defineProperty(globalThis, "TurboWarpTitleMenu", {
1624
+ value: publicApi,
1625
+ configurable: true
1626
+ });
1627
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1628
+ Scratch.extensions.register(new TurboWarpTitleMenuExtension());
1629
+ //#endregion
1630
1630
 
1631
1631
  })(Scratch);