@kubohiroya/turbowarp-title-menu 0.4.0 → 0.6.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.
package/README.ja.md CHANGED
@@ -6,6 +6,14 @@
6
6
 
7
7
  TurboWarp拡張やPackager実行環境で使える、汎用のタイトル表示、アプリケーションメニュー、DSLファイル保管機構です。
8
8
 
9
+ ## 最小デモ
10
+
11
+ [Open in TurboWarp Editor](https://turbowarp.org/editor?project_url=https%3A%2F%2Fkubohiroya.github.io%2Fturbowarp-title-menu%2Fsamples%2Fchoose-menu-action.sb3) · [Download SB3](https://kubohiroya.github.io/turbowarp-title-menu/samples/choose-menu-action.sb3)
12
+
13
+ 緑の旗を押し、メニューの **Hello** を選択すると `Selected action` が `Hello` になります。**Close** を選ぶとメニューを閉じます。
14
+
15
+ 公式TurboWarp Editorでカスタム拡張の確認画面の **Run extension without sandbox** をチェックし、**Allow** を選択してください。SB3はこのリポジトリの配布JSを内包します。 app-shellは配布JSに含まれ、追加のホストは不要です。
16
+
9
17
  ## 利用者ガイド
10
18
 
11
19
  英語ドキュメント: [https://kubohiroya.github.io/turbowarp-title-menu/](https://kubohiroya.github.io/turbowarp-title-menu/)
@@ -15,6 +23,7 @@ TurboWarp拡張やPackager実行環境で使える、汎用のタイトル表示
15
23
  - 起動直後のタイトル表示として、タイトル、作者名、ライセンス、公式Webサイト、閉じるボタンを表示します。
16
24
  - ステージ上にアプリケーションメニューを表示します。共有primitiveの`@kubohiroya/turbowarp-app-shell`の上に作っており、項目はblockから定義してhatで受けられるため、固定の項目に縛られません。
17
25
  - DSLファイル管理ダイアログで、追加、開く、名前の変更、個別削除ができ、名前・更新日時・サイズで並べ替えできます。
26
+ - 機能拡張キャッシュ管理ダイアログで、Loaderがキャッシュした機能拡張のバイト列を、作品ごと・カタログ共有ごとに一覧して手放せます。
18
27
  - 複数のDSLファイルをIndexedDBに保管します。TM Kamishibai専用ではありません。
19
28
  - ホスト側ランタイムから直接組み込める Composition API を提供します。
20
29
 
@@ -35,7 +44,7 @@ IndexedDBはoriginごとに分かれます。TurboWarp Web、TurboWarp Desktop
35
44
  ## インストール
36
45
 
37
46
  ```bash
38
- pnpm add --save-exact @kubohiroya/turbowarp-title-menu@0.4.0
47
+ pnpm add --save-exact @kubohiroya/turbowarp-title-menu@0.6.0
39
48
  ```
40
49
 
41
50
  TurboWarpでは `dist/turbowarp-title-menu.js` をCustom Extensionとして読み込み、sandboxなしの実行を許可します。
@@ -199,11 +208,31 @@ IndexedDBに保管しているDSLファイルの件数を返します。
199
208
  | Type | Reporter |
200
209
  | Opcode | `lastDslError` |
201
210
 
211
+ ### `show extension cache manager`
212
+
213
+ キャッシュされた機能拡張のバイト列を作品ごとに一覧し、手放すためのダイアログを表示します。
214
+
215
+ | Property | Value |
216
+ |---|---|
217
+ | Type | Command |
218
+ | Opcode | `showExtensionCache` |
219
+
220
+ ### `label cached project [URI] as [TITLE]`
221
+
222
+ 機能拡張キャッシュ管理ダイアログで、作品のURIの横に出す読める名前を登録します。作品のURIは意図的に不透明なので、タイトルがないと行を見分けられません。タイトルは作品自身の申告で、URIとの対応は検証しません。
223
+
224
+ | Property | Value |
225
+ |---|---|
226
+ | Type | Command |
227
+ | Opcode | `setCachedProjectTitle` |
228
+ | `URI` | String, default: `https://example.com/turbowarp-plus-projects/ab/cd/project` |
229
+ | `TITLE` | String, default: `My project` |
230
+
202
231
  ## 動作の要点
203
232
 
204
233
  | 場面 | 動作 |
205
234
  |---|---|
206
- | 組み込みのメニュー項目 | `files`/`reload`/`about`/`close` は最初から登録されており、それぞれの動作を保ちます。同時にhatも発火します。`clear app menu actions` で外せます。 |
235
+ | 組み込みのメニュー項目 | `files`/`cache`/`reload`/`about`/`close` は最初から登録されており、それぞれの動作を保ちます。同時にhatも発火します。`clear app menu actions` で外せます。 |
207
236
  | メニューの変更 | 項目の追加や消去でメニューを作り直します。表示中だった場合は消えずに再表示します。 |
208
237
  | 項目が0件のとき | 1件も登録されていない状態では `show application menu` は何もせず、すべて消すと表示中のメニューは閉じます。土台のprimitiveが0件のメニューを作れないため、自分の項目を入れる前に全消しするプロジェクトが途中で止まらないようにしています。 |
209
238
  | ファイルの追加 | 「ファイルを追加」はファイル選択ダイアログを開き、選ばれた内容を保管します。開きはしません。使うときは「開く」を押します。 |
@@ -211,6 +240,12 @@ IndexedDBに保管しているDSLファイルの件数を返します。
211
240
  | 削除 | 削除には確認のためもう一度クリックが必要です。開いているファイルを削除すると、開いている内容も解除されます。 |
212
241
  | 保管の上限 | 1 MiBを超えるファイル、および65件目は、理由を表示して拒否します。古いファイルを自動で消すことはしません。 |
213
242
  | 失敗時 | 失敗はダイアログに表示し、`last DSL storage error` からも読めます。保管の失敗でスクリプトが止まることはありません。 |
243
+ | キャッシュを手放すとき | キャッシュは内容で参照されており、作品はエントリを所有しているのではなく名指しているだけです。作品を手放すと、その作品が名指すdigestを落とします。別の作品が使い回したはずのバイト列まで落ちることがあります。失われたままにはなりません。必要なものは、次にその作品を開いたときに取り直します。 |
244
+ | 一覧に出る作品のURI | 作品のURIはその作品自身の申告で、検証していません。別の作品のURIの下にバイト列を置くこともできます。狂うのはこの一覧の見え方だけです。Loaderは使うたびにdigestを照合するので、誤ったバイト列を渡すことはできません。ダイアログはこの両方を画面上で述べます。 |
245
+ | 解決しないURI | 作品のURIは作者が公開するまで何も返しません。未公開の作品は404を返します。ダイアログはURIを取得しにいかず、到達性を削除の根拠にもしません。それをすると、まだ書いている途中の作品のキャッシュを全部消すことになります。 |
246
+ | 作品のタイトル | キャッシュはタイトルを持ちません。作品のURIは、作品名を変えてもアドレスが変わらないよう意図的に不透明にしてあります。`label cached project [URI] as [TITLE]` でURIの横に出す読める名前を登録します。登録がない行は、ないと明示します。 |
247
+ | 共有のキャッシュ | カタログが指定したバイト列はどの作品のものでもないため、最初に取得した作品の責任にせず、独立した行として一覧します。この行も他と同じように手放せます。 |
248
+ | キャッシュの読み取り失敗 | 一覧の取得に失敗したときは、空の一覧ではなく失敗を表示します。「キャッシュは空」と「キャッシュを読めなかった」は別の主張です。失敗は `last DSL storage error` からも読めます。 |
214
249
 
215
250
  ## Composition API
216
251
 
@@ -223,10 +258,16 @@ import {
223
258
  createApplicationMenu,
224
259
  createDslFilesDialog,
225
260
  createDslStore,
261
+ createExtensionCache,
262
+ createExtensionCacheDialog,
226
263
  createTitleDialog
227
264
  } from '@kubohiroya/turbowarp-title-menu';
228
265
  ```
229
266
 
267
+ 機能拡張キャッシュも同じように組み込めます。キャッシュのデータベースをこのパッケージが名前で開くことはありません。
268
+ すべての操作は`@kubohiroya/turbowarp-extension-loader/indexeddb-cache`を通します。
269
+ どこに何の形で置かれているかを知っているのはLoaderだけ、という状態を保つためです。
270
+
230
271
  詳しい例は[英語版README](README.md#composition-api)を参照してください。
231
272
 
232
273
  ## 開発
package/README.md CHANGED
@@ -8,11 +8,20 @@ Reusable title, application menu, and DSL source storage controls for TurboWarp
8
8
 
9
9
  **User guide:** [English](https://kubohiroya.github.io/turbowarp-title-menu/)
10
10
 
11
+ ## Minimal demo
12
+
13
+ [Open in TurboWarp Editor](https://turbowarp.org/editor?project_url=https%3A%2F%2Fkubohiroya.github.io%2Fturbowarp-title-menu%2Fsamples%2Fchoose-menu-action.sb3) · [Download SB3](https://kubohiroya.github.io/turbowarp-title-menu/samples/choose-menu-action.sb3)
14
+
15
+ Click the green flag, then choose **Hello**; `Selected action` becomes `Hello`. Choose **Close** to close the menu.
16
+
17
+ In the official TurboWarp Editor, enable **Run extension without sandbox** and choose **Allow**. The SB3 embeds this repository’s distributed JavaScript. App Shell is bundled; no additional host is required.
18
+
11
19
  ## What it does
12
20
 
13
21
  - Shows a reusable title dialog with title, author, license, official website, language, and close controls.
14
22
  - Shows a stage-mounted application menu built on the shared `@kubohiroya/turbowarp-app-shell` primitive. A project defines its own actions from blocks and reacts to them with a hat, so the menu is not limited to a fixed set.
15
23
  - Shows a DSL file manager that adds, opens, renames, and deletes stored files, and sorts them by name, update time, or size.
24
+ - Shows an extension cache manager that lists the extension bytes the loader cached, per project and for the shared catalog, and releases them.
16
25
  - Stores many DSL files in IndexedDB without tying the mechanism to TM Kamishibai.
17
26
  - Exposes a small Composition API for projects that want to wire the controls into their own runtime.
18
27
 
@@ -50,7 +59,7 @@ The reviewed JavaScript build is committed to this repository, so users do not n
50
59
  Install an exact version that you have reviewed:
51
60
 
52
61
  ```bash
53
- pnpm add --save-exact @kubohiroya/turbowarp-title-menu@0.4.0
62
+ pnpm add --save-exact @kubohiroya/turbowarp-title-menu@0.6.0
54
63
  ```
55
64
 
56
65
  Load the standalone bundle from:
@@ -62,7 +71,7 @@ node_modules/@kubohiroya/turbowarp-title-menu/dist/turbowarp-title-menu.js
62
71
  A version-pinned CDN URL is:
63
72
 
64
73
  ```text
65
- https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-title-menu@0.4.0/dist/turbowarp-title-menu.js
74
+ https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-title-menu@0.6.0/dist/turbowarp-title-menu.js
66
75
  ```
67
76
 
68
77
  ## Quick start
@@ -227,6 +236,26 @@ Returns the most recent DSL storage failure in the interface language, or an emp
227
236
  | Type | Reporter |
228
237
  | Opcode | `lastDslError` |
229
238
 
239
+ ### `show extension cache manager`
240
+
241
+ Shows the dialog that lists the cached extension bytes per project and releases them.
242
+
243
+ | Property | Value |
244
+ |---|---|
245
+ | Type | Command |
246
+ | Opcode | `showExtensionCache` |
247
+
248
+ ### `label cached project [URI] as [TITLE]`
249
+
250
+ Records a readable title to show beside a project URI in the extension cache manager. A project URI is deliberately opaque, so without a title the rows cannot be told apart; the title is self-declared and is never checked against the URI.
251
+
252
+ | Property | Value |
253
+ |---|---|
254
+ | Type | Command |
255
+ | Opcode | `setCachedProjectTitle` |
256
+ | `URI` | String, default: `https://example.com/turbowarp-plus-projects/ab/cd/project` |
257
+ | `TITLE` | String, default: `My project` |
258
+
230
259
  <!-- END GENERATED BLOCKS -->
231
260
 
232
261
  ## Important behavior
@@ -235,7 +264,7 @@ Returns the most recent DSL storage failure in the interface language, or an emp
235
264
  |---|---|
236
265
  | Startup title | `show title dialog` mounts a dialog over the stage and keeps Scratch sprites untouched. |
237
266
  | Official website | The title dialog opens the configured website URL in a new browser tab. |
238
- | Built-in menu actions | `files`, `reload`, `about`, and `close` are pre-registered and keep their own behavior. They also start the hat, and `clear app menu actions` removes them. |
267
+ | Built-in menu actions | `files`, `cache`, `reload`, `about`, and `close` are pre-registered and keep their own behavior. They also start the hat, and `clear app menu actions` removes them. |
239
268
  | Changing the menu | Adding or clearing an action rebuilds the menu. A menu that was on screen is shown again rather than disappearing. |
240
269
  | An empty menu | `show application menu` does nothing while no action is registered, and clearing every action closes an open menu. The underlying primitive refuses to build a menu with no actions, so a project that clears the set before installing its own is not interrupted. |
241
270
  | Adding a DSL file | `Add file` opens a browser file picker and stores the chosen source. It does not open the file; the operator presses `Open` when the project should use it. |
@@ -243,6 +272,12 @@ Returns the most recent DSL storage failure in the interface language, or an emp
243
272
  | Deleting | Deleting asks for a second confirming click, and deleting the open file clears the opened source. |
244
273
  | Storage limits | A file over 1 MiB, or a 65th file, is refused with a message. The store never evicts a file on its own. |
245
274
  | Storage failures | Every failure is shown in the dialog and reported by `last DSL storage error`; a script is never interrupted by a thrown storage error. |
275
+ | Releasing a cached project | Cached entries are addressed by their contents, so a project claims entries rather than owning them. Releasing a project drops the digests that project names, which can take bytes another project would have reused. Nothing is lost for good: whatever is still needed is downloaded again the next time a project is opened. |
276
+ | Project URIs in the cache | A project URI is what that project called itself and is not verified, so a project can file its bytes under another project's URI. Only this list is misled by that; the loader re-checks every digest when it uses it, so the wrong bytes can never be handed over. The dialog states both facts on screen. |
277
+ | Unreachable project URIs | A project URI serves nothing until its author publishes, so an unpublished project answers 404. The dialog never fetches a URI and never treats reachability as a reason to release anything, because that would clear the cache of every project still being written. |
278
+ | Project titles | The cache has no titles, and a project URI is deliberately opaque so that renaming a project does not rename its address. `label cached project [URI] as [TITLE]` records a readable name to show beside the URI; a row with no recorded title says so. |
279
+ | The shared cache bucket | Bytes the catalog pinned belong to no one project, so they are listed under their own row rather than charged to whichever project fetched them first. That row can be released like any other. |
280
+ | Cache failures | A listing that fails shows the failure instead of an empty list, because "nothing is cached" and "the cache could not be read" are different claims. Failures are also reported by `last DSL storage error`. |
246
281
  | Project stop | The controls remain explicit UI overlays; consumers can dispose Composition API instances when their runtime ends. |
247
282
 
248
283
  ## Composition API
@@ -303,6 +338,34 @@ const menu = createApplicationMenu({
303
338
  menu.show('en');
304
339
  ```
305
340
 
341
+ The extension cache manager is composed the same way. The cache itself is never opened by name
342
+ here: every operation goes through `@kubohiroya/turbowarp-extension-loader/indexeddb-cache`, so the
343
+ loader stays the only package that knows where those bytes live and what shape they are in.
344
+
345
+ ```ts
346
+ import {
347
+ createExtensionCache,
348
+ createExtensionCacheDialog
349
+ } from '@kubohiroya/turbowarp-title-menu';
350
+
351
+ // The host knows its projects' titles; the cache only knows their URIs.
352
+ const titles = new Map<string, string>();
353
+
354
+ const cache = createExtensionCache({titleFor: (uri) => titles.get(uri)});
355
+
356
+ const cacheManager = createExtensionCacheDialog({
357
+ mount: stageContainer,
358
+ locales: {en: myCacheLabels},
359
+ listProjects: () => cache.listProjects(),
360
+ listDigests: (bucket) => cache.listDigests(bucket),
361
+ totals: () => cache.totals(),
362
+ onReleaseProject: (bucket) => cache.releaseProject(bucket),
363
+ onReleaseDigest: (bucket, key) => cache.releaseDigests(bucket, [key])
364
+ });
365
+
366
+ await cacheManager.show('en');
367
+ ```
368
+
306
369
  ## Compatibility
307
370
 
308
371
  | Identifier | Value | Stability |
@@ -66,11 +66,30 @@
66
66
  }
67
67
  ]
68
68
  },
69
+ {
70
+ "opcode": "setCachedProjectTitle",
71
+ "blockType": "COMMAND",
72
+ "arguments": [
73
+ {
74
+ "id": "TITLE",
75
+ "type": "STRING"
76
+ },
77
+ {
78
+ "id": "URI",
79
+ "type": "STRING"
80
+ }
81
+ ]
82
+ },
69
83
  {
70
84
  "opcode": "showDslFiles",
71
85
  "blockType": "COMMAND",
72
86
  "arguments": []
73
87
  },
88
+ {
89
+ "opcode": "showExtensionCache",
90
+ "blockType": "COMMAND",
91
+ "arguments": []
92
+ },
74
93
  {
75
94
  "opcode": "showMenu",
76
95
  "blockType": "COMMAND",
@@ -2,4 +2,6 @@ export { createAppShellApplicationMenu as createApplicationMenu } from '@kubohir
2
2
  export { createDslFilesDialog } from './dsl-files-dialog.js';
3
3
  export { createDslStore, defaultDslSort, DslStoreError, readDslFile } from './dsl-store.js';
4
4
  export { dslOpenEventName, dslReloadEventName } from './events.js';
5
+ export { createExtensionCache, ExtensionCacheError, SHARED_BUCKET } from './extension-cache.js';
6
+ export { createExtensionCacheDialog } from './extension-cache-dialog.js';
5
7
  export { createTitleDialog } from './title-dialog.js';
@@ -0,0 +1,389 @@
1
+ import { isRecord, requireDocument, requireElement } from './dom';
2
+ /** How much of a digest is shown. Enough to tell two rows apart; the full value is the title. */
3
+ const digestPreviewLength = 12;
4
+ function requireLocales(value) {
5
+ if (!isRecord(value) || Object.keys(value).length === 0) {
6
+ throw new TypeError('locales must contain at least one locale');
7
+ }
8
+ return value;
9
+ }
10
+ function textFor(locales, locale) {
11
+ const text = locales[locale] ?? locales['en'] ?? Object.values(locales)[0];
12
+ if (text === undefined)
13
+ throw new TypeError('locales must contain at least one locale');
14
+ return text;
15
+ }
16
+ /** Fills `{name}` placeholders, so a locale decides where a count or a size sits in a sentence. */
17
+ function fill(template, values) {
18
+ return template.replace(/\{(\w+)\}/g, (match, name) => values[name] ?? match);
19
+ }
20
+ function defaultFormatSize(byteLength) {
21
+ if (byteLength < 1024)
22
+ return `${byteLength} B`;
23
+ if (byteLength < 1024 * 1024)
24
+ return `${(byteLength / 1024).toFixed(1)} KB`;
25
+ return `${(byteLength / (1024 * 1024)).toFixed(1)} MB`;
26
+ }
27
+ function defaultFormatDate(epochMilliseconds) {
28
+ const parsed = new Date(epochMilliseconds);
29
+ if (Number.isNaN(parsed.getTime()))
30
+ return String(epochMilliseconds);
31
+ const pad = (value) => String(value).padStart(2, '0');
32
+ return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
33
+ }
34
+ function defaultDescribeError(error) {
35
+ if (error instanceof Error && error.message.length > 0)
36
+ return error.message;
37
+ return String(error);
38
+ }
39
+ export function createExtensionCacheDialog(options) {
40
+ if (!isRecord(options))
41
+ throw new TypeError('extension cache dialog options must be an object');
42
+ const document = requireDocument(options.document ?? globalThis.document);
43
+ const mount = requireElement(options.mount ?? document.body, 'mount');
44
+ const locales = requireLocales(options.locales);
45
+ const describeError = options.describeError ?? defaultDescribeError;
46
+ const formatSize = options.formatSize ?? defaultFormatSize;
47
+ const formatDate = options.formatDate ?? defaultFormatDate;
48
+ let locale = options.initialLocale ?? 'en';
49
+ let projects = [];
50
+ let totals = { entries: 0, bytes: 0 };
51
+ let expandedBucket = null;
52
+ let digests = [];
53
+ let confirmingBucket = null;
54
+ let confirmingDigest = null;
55
+ let status = '';
56
+ let result = '';
57
+ /** Whether the list on screen came from a listing that finished. See `render`. */
58
+ let listed = false;
59
+ let disposed = false;
60
+ const root = document.createElement('section');
61
+ const panel = document.createElement('div');
62
+ const heading = document.createElement('h1');
63
+ const closeButton = document.createElement('button');
64
+ const toolbar = document.createElement('div');
65
+ const refreshButton = document.createElement('button');
66
+ const totalElement = document.createElement('p');
67
+ const noticeElement = document.createElement('p');
68
+ const listElement = document.createElement('div');
69
+ const resultElement = document.createElement('p');
70
+ const statusElement = document.createElement('p');
71
+ root.setAttribute('data-turbowarp-title-menu-extension-cache', 'true');
72
+ root.style.cssText =
73
+ '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;';
74
+ // Visibility is the one property the dialog toggles, so it is set apart from the style sheet.
75
+ root.style.display = 'none';
76
+ panel.style.cssText =
77
+ 'width:min(760px,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;';
78
+ heading.style.cssText = 'margin:0;font-size:20px;line-height:1.3;';
79
+ toolbar.style.cssText = 'display:flex;gap:8px;align-items:center;flex-wrap:wrap;';
80
+ totalElement.style.cssText = 'margin:0;font-size:13px;color:#1b1f27;';
81
+ noticeElement.style.cssText =
82
+ 'margin:0;padding:8px 10px;font-size:12px;line-height:1.5;color:#45506a;background:#f2f4f8;border:1px solid #ccd2de;border-radius:8px;';
83
+ listElement.style.cssText =
84
+ 'flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:6px;';
85
+ resultElement.style.cssText = 'margin:0;min-height:18px;font-size:13px;color:#1f6feb;';
86
+ statusElement.style.cssText = 'margin:0;min-height:18px;font-size:13px;color:#8a1c1c;';
87
+ const headerRow = document.createElement('div');
88
+ headerRow.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px;';
89
+ headerRow.appendChild(heading);
90
+ headerRow.appendChild(closeButton);
91
+ panel.appendChild(headerRow);
92
+ toolbar.appendChild(refreshButton);
93
+ toolbar.appendChild(totalElement);
94
+ panel.appendChild(toolbar);
95
+ panel.appendChild(noticeElement);
96
+ panel.appendChild(listElement);
97
+ panel.appendChild(resultElement);
98
+ panel.appendChild(statusElement);
99
+ root.appendChild(panel);
100
+ const previousMountPosition = mount.style.position;
101
+ if (previousMountPosition === '' || previousMountPosition === 'static') {
102
+ mount.style.position = 'relative';
103
+ }
104
+ mount.appendChild(root);
105
+ function styleButton(button, tone) {
106
+ const palette = {
107
+ primary: 'background:#1f6feb;color:#ffffff;border:1px solid #1f6feb;',
108
+ plain: 'background:#f2f4f8;color:#1b1f27;border:1px solid #ccd2de;',
109
+ danger: 'background:#b42318;color:#ffffff;border:1px solid #b42318;',
110
+ active: 'background:#d7e6ff;color:#0b3a82;border:1px solid #1f6feb;'
111
+ }[tone];
112
+ button.style.cssText = `${palette}padding:5px 10px;border-radius:6px;font-size:13px;cursor:pointer;`;
113
+ }
114
+ function createButton(label, tone, onClick) {
115
+ const button = document.createElement('button');
116
+ button.type = 'button';
117
+ button.textContent = label;
118
+ styleButton(button, tone);
119
+ button.addEventListener('click', onClick);
120
+ return button;
121
+ }
122
+ function run(operation) {
123
+ try {
124
+ Promise.resolve(operation()).catch(handleFailure);
125
+ }
126
+ catch (error) {
127
+ handleFailure(error);
128
+ }
129
+ }
130
+ function handleFailure(error) {
131
+ status = describeError(error);
132
+ options.onError?.(error);
133
+ render();
134
+ }
135
+ /** Every release goes through here, so the list, the total, and the status stay in step. */
136
+ function release(operation) {
137
+ run(async () => {
138
+ status = '';
139
+ try {
140
+ const released = await operation();
141
+ result = fill(textFor(locales, locale).releaseResult, {
142
+ released: String(released.released),
143
+ freed: formatSize(released.freed)
144
+ });
145
+ }
146
+ catch (error) {
147
+ handleFailure(error);
148
+ return;
149
+ }
150
+ await reload();
151
+ });
152
+ }
153
+ /**
154
+ * Reloads the whole screen.
155
+ *
156
+ * The expanded bucket is re-listed rather than filtered out of a stale list, because releasing
157
+ * a digest from one bucket can remove bytes a second bucket claimed, which changes totals the
158
+ * dialog never asked about. Asking again is cheap; guessing would be wrong.
159
+ */
160
+ async function reload() {
161
+ if (disposed)
162
+ return;
163
+ // Cleared first so that a failure below cannot leave the panel claiming the cache is empty.
164
+ listed = false;
165
+ projects = await options.listProjects();
166
+ totals = await options.totals();
167
+ if (expandedBucket !== null && !projects.some((entry) => entry.bucket === expandedBucket)) {
168
+ // The bucket was released entirely, so there is nothing left to expand.
169
+ expandedBucket = null;
170
+ }
171
+ digests = expandedBucket === null ? [] : await options.listDigests(expandedBucket);
172
+ listed = true;
173
+ render();
174
+ }
175
+ /**
176
+ * Reloads without letting the failure escape.
177
+ *
178
+ * A listing that failed must not leave the panel showing an empty list: "nothing is cached" and
179
+ * "the cache could not be read" are different claims, and only one of them is true. So the
180
+ * status line carries the failure while the panel stays open, instead of the promise rejecting
181
+ * into a caller that has no way to say so on screen.
182
+ */
183
+ async function reloadSafely() {
184
+ try {
185
+ await reload();
186
+ }
187
+ catch (error) {
188
+ handleFailure(error);
189
+ }
190
+ }
191
+ function toggleExpanded(bucket) {
192
+ expandedBucket = expandedBucket === bucket ? null : bucket;
193
+ confirmingBucket = null;
194
+ confirmingDigest = null;
195
+ run(() => reload());
196
+ }
197
+ function renderDigestRow(digest, bucket, text) {
198
+ const row = document.createElement('div');
199
+ row.setAttribute('data-cache-digest', digest.key);
200
+ row.style.cssText =
201
+ 'display:flex;align-items:center;gap:8px;padding:6px 8px;margin-left:18px;border:1px solid #eef1f6;border-radius:6px;';
202
+ const key = document.createElement('span');
203
+ key.textContent = `${digest.key.slice(0, digestPreviewLength)}…`;
204
+ // The digest is the whole name of the bytes, so the full value stays available on hover.
205
+ key.setAttribute('title', digest.key);
206
+ key.style.cssText =
207
+ 'flex:1;min-width:0;font-family:monospace;font-size:12px;color:#1b1f27;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
208
+ const used = document.createElement('span');
209
+ used.textContent = fill(text.lastUsed, { date: formatDate(digest.lastAccess) });
210
+ used.style.cssText = 'font-size:12px;color:#5a6172;white-space:nowrap;';
211
+ const size = document.createElement('span');
212
+ size.textContent = formatSize(digest.bytes);
213
+ size.setAttribute('title', fill(text.originalSize, { bytes: formatSize(digest.originalBytes) }));
214
+ size.style.cssText =
215
+ 'font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;';
216
+ row.appendChild(key);
217
+ row.appendChild(used);
218
+ row.appendChild(size);
219
+ if (confirmingDigest === digest.key) {
220
+ row.appendChild(createButton(text.confirmRelease, 'danger', () => {
221
+ confirmingDigest = null;
222
+ release(() => options.onReleaseDigest(bucket, digest.key));
223
+ }));
224
+ row.appendChild(createButton(text.cancel, 'plain', () => {
225
+ confirmingDigest = null;
226
+ render();
227
+ }));
228
+ return row;
229
+ }
230
+ row.appendChild(createButton(text.release, 'plain', () => {
231
+ confirmingDigest = digest.key;
232
+ confirmingBucket = null;
233
+ render();
234
+ }));
235
+ return row;
236
+ }
237
+ function renderProjectRow(project, text) {
238
+ const row = document.createElement('div');
239
+ row.setAttribute('data-cache-bucket', project.bucket);
240
+ row.style.cssText =
241
+ 'display:flex;align-items:center;gap:8px;padding:8px;border:1px solid #e2e6ee;border-radius:8px;';
242
+ const names = document.createElement('div');
243
+ names.style.cssText = 'flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;';
244
+ const title = document.createElement('span');
245
+ // The shared bucket is not a project and carries no URI, so it is named by the locale alone.
246
+ title.textContent = project.shared ? text.shared : (project.title ?? text.untitled);
247
+ title.style.cssText =
248
+ 'font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
249
+ names.appendChild(title);
250
+ if (!project.shared) {
251
+ const uri = document.createElement('span');
252
+ uri.textContent = project.bucket;
253
+ uri.setAttribute('title', project.bucket);
254
+ uri.style.cssText =
255
+ 'font-size:11px;font-family:monospace;color:#5a6172;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
256
+ names.appendChild(uri);
257
+ }
258
+ row.appendChild(names);
259
+ const count = document.createElement('span');
260
+ count.textContent = fill(text.entryCount, { entries: String(project.entries) });
261
+ count.style.cssText = 'font-size:12px;color:#5a6172;white-space:nowrap;';
262
+ const size = document.createElement('span');
263
+ size.textContent = formatSize(project.bytes);
264
+ size.style.cssText =
265
+ 'font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;';
266
+ row.appendChild(count);
267
+ row.appendChild(size);
268
+ const expanded = expandedBucket === project.bucket;
269
+ const expandButton = createButton(expanded ? text.collapse : text.expand, expanded ? 'active' : 'primary', () => toggleExpanded(project.bucket));
270
+ expandButton.setAttribute('data-cache-expand', project.bucket);
271
+ expandButton.setAttribute('aria-expanded', expanded ? 'true' : 'false');
272
+ row.appendChild(expandButton);
273
+ if (confirmingBucket === project.bucket) {
274
+ row.appendChild(createButton(text.confirmRelease, 'danger', () => {
275
+ confirmingBucket = null;
276
+ release(() => options.onReleaseProject(project.bucket));
277
+ }));
278
+ row.appendChild(createButton(text.cancel, 'plain', () => {
279
+ confirmingBucket = null;
280
+ render();
281
+ }));
282
+ return row;
283
+ }
284
+ row.appendChild(createButton(text.release, 'plain', () => {
285
+ confirmingBucket = project.bucket;
286
+ confirmingDigest = null;
287
+ render();
288
+ }));
289
+ return row;
290
+ }
291
+ function render() {
292
+ if (disposed)
293
+ return;
294
+ const text = textFor(locales, locale);
295
+ heading.textContent = text.title;
296
+ closeButton.textContent = text.close;
297
+ closeButton.setAttribute('aria-label', text.close);
298
+ refreshButton.textContent = text.refresh;
299
+ noticeElement.textContent = text.notice;
300
+ totalElement.textContent = fill(text.total, {
301
+ entries: String(totals.entries),
302
+ bytes: formatSize(totals.bytes)
303
+ });
304
+ resultElement.textContent = result;
305
+ statusElement.textContent = status;
306
+ listElement.replaceChildren();
307
+ if (projects.length === 0) {
308
+ // "Nothing is cached" and "the cache could not be read" are different claims, and only one
309
+ // of them is ever true. A failed listing shows the status line alone rather than the second
310
+ // dressed as the first, because the first invites an operator to stop looking.
311
+ if (!listed)
312
+ return;
313
+ const empty = document.createElement('p');
314
+ empty.textContent = text.empty;
315
+ empty.style.cssText = 'margin:8px 0;font-size:14px;color:#5a6172;';
316
+ listElement.appendChild(empty);
317
+ return;
318
+ }
319
+ for (const project of projects) {
320
+ listElement.appendChild(renderProjectRow(project, text));
321
+ if (expandedBucket !== project.bucket)
322
+ continue;
323
+ for (const digest of digests) {
324
+ listElement.appendChild(renderDigestRow(digest, project.bucket, text));
325
+ }
326
+ }
327
+ }
328
+ styleButton(closeButton, 'plain');
329
+ styleButton(refreshButton, 'primary');
330
+ closeButton.type = 'button';
331
+ refreshButton.type = 'button';
332
+ closeButton.addEventListener('click', () => hide());
333
+ refreshButton.addEventListener('click', () => {
334
+ result = '';
335
+ status = '';
336
+ run(() => reload());
337
+ });
338
+ function hide() {
339
+ if (disposed)
340
+ return;
341
+ confirmingBucket = null;
342
+ confirmingDigest = null;
343
+ root.style.display = 'none';
344
+ }
345
+ function ensureActive() {
346
+ if (disposed)
347
+ throw new TypeError('extension cache dialog is disposed');
348
+ }
349
+ render();
350
+ return Object.freeze({
351
+ element: root,
352
+ get locale() {
353
+ return locale;
354
+ },
355
+ get expanded() {
356
+ return expandedBucket;
357
+ },
358
+ async show(nextLocale) {
359
+ ensureActive();
360
+ if (nextLocale !== undefined)
361
+ locale = nextLocale;
362
+ status = '';
363
+ result = '';
364
+ root.style.display = 'flex';
365
+ await reloadSafely();
366
+ return locale;
367
+ },
368
+ hide,
369
+ async refresh() {
370
+ ensureActive();
371
+ await reload();
372
+ },
373
+ setLocale(nextLocale) {
374
+ ensureActive();
375
+ locale = nextLocale;
376
+ render();
377
+ return locale;
378
+ },
379
+ dispose() {
380
+ if (disposed)
381
+ return;
382
+ disposed = true;
383
+ root.remove();
384
+ if (previousMountPosition === '' || previousMountPosition === 'static') {
385
+ mount.style.position = previousMountPosition;
386
+ }
387
+ }
388
+ });
389
+ }