@kubohiroya/turbowarp-plus-editor-project-folder 0.2.0 → 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.
package/README.ja.md CHANGED
@@ -18,13 +18,13 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
18
18
 
19
19
  | Editor の状態 | 動作 |
20
20
  | --- | --- |
21
- | 未保存編集なし・実行停止中 | 既存ブロックの値と座標の変更は、2 回の確認でファイルが変わらなければその場で反映します。 |
21
+ | 未保存編集なし・実行停止中 | 2 回の確認でファイルが変わらなければ、既存のスプライトとステージのスクリプトの変更をその場で反映します。値と座標の変更はすべてのブロックを保ちます。ブロックの追加・削除・接続の変更は、ホストが `blockReload.deserializeBlocks` を渡す場合に、該当するスクリプトだけを置き換えます。 |
22
22
  | 作品の実行中 | 反映を保留します。値と座標の変更は停止後に反映します。 |
23
- | 未保存編集あり | 編集を保持します。**編集を破棄して再読み込み…** は確認してからフォルダの内容に置き換えます。 |
24
- | 作品 JSON のその他の変更、アセット・マニフェスト・拡張機能の変更 | **作品全体を再読み込み** で、開くときと同じ検証を経てフォルダを読み直します。自動では行いません。 |
23
+ | 未保存編集あり | 編集を保持します。ホストが `blockReload.compareChanges` を渡す場合は、**比較して選ぶ…** で未保存の編集とフォルダでの変更を並べて示し、**編集を破棄してフォルダから読み込む** を選んだときだけ置き換えます。渡さない場合は、**編集を破棄して再読み込み…** で確認してから置き換えます。 |
24
+ | その他の変更(ターゲット・変数・コメントの変更、作品に無い変数や拡張機能を使うブロック、アセット・マニフェスト・拡張機能の変更) | **作品全体を再読み込み** で、開くときと同じ検証を経てフォルダを読み直します。自動では行いません。 |
25
25
  | JSON の途中など書き込み途中 | 更新待ちを表示し、間を置かずに再確認します。 |
26
26
 
27
- `mountProjectFolder` に `autoReload: false` を渡すと、すべての反映をボタン操作にします。確認はファイルの内容を読む前にサイズと更新時刻を比べるため、両方が変わらない上書きは検出できません。保存時はディスクのバイト列を照合し、変更されたフォルダへの上書きを拒否します。
27
+ スクリプトの置き換えは VM を変更する前に検証し、途中で VM が失敗した場合はすべてのターゲットを元に戻して **作品全体を再読み込み** を待ちます。`mountProjectFolder` に `autoReload: false` を渡すと、すべての反映をボタン操作にします。確認はファイルの内容を読む前にサイズと更新時刻を比べるため、両方が変わらない上書きは検出できません。保存時はディスクのバイト列を照合し、変更されたフォルダへの上書きを拒否します。
28
28
 
29
29
  ## 開発
30
30
 
@@ -33,3 +33,11 @@ Node.js 26 で `npm ci` と `npm test` を実行します。Vite で JavaScript
33
33
  Editor のヘッドレス統合テストは実ディスク上のフォルダを使い、選択画面の操作を差し替えます。OS のフォルダ選択画面を確認するときは、使い捨ての sb3-toolchain v1 作品を **ファイル → プロジェクトフォルダを開く…** から選び、読み書きを許可します。標準ブロックを変更し、**ファイル → プロジェクトフォルダに保存** を選びます。選んだフォルダの `project.source.json` が更新されたことを確かめ、同じフォルダを開き直して編集が反映されることを確認します。
34
34
 
35
35
  初期実装は MPL-2.0 の [TurboWarp Plus Editor d14d065](https://github.com/kubohiroya/turbowarp-plus-editor/tree/d14d0659f77f37328c855ecfeeae0927d81ae81a/packages/editor-project-folder) から分離しました。
36
+
37
+ ## 公開
38
+
39
+ npm への公開は `.github/workflows/release.yml` が行う。`package.json` の版と同じ `v<版>` のタグを
40
+ `main` のコミットに push すると、テストを通したうえで npm に入れるアーカイブを作り、GitHub Release に
41
+ 添付してから npm に公開し、`latest` と `next` をその版に向ける。認証はトークンではなく npm の
42
+ Trusted Publisher(OIDC)で、provenance を付けて公開する。npm 側の設定にはこのワークフローの
43
+ ファイル名をそのまま登録するため、改名するときは npm の設定も合わせる。
package/README.md CHANGED
@@ -18,13 +18,13 @@ When the host passes `host.blockReload`, the package checks the open folder ever
18
18
 
19
19
  | Editor state | Behavior |
20
20
  | --- | --- |
21
- | No unsaved edits, project stopped | Changes to values and positions of existing blocks are applied in place once the file has stayed the same across two checks. |
21
+ | No unsaved edits, project stopped | Once the file has stayed the same across two checks, changes to the scripts of existing sprites and the stage are applied in place. Value and position changes keep every block. Added, removed or reconnected blocks replace only the scripts they belong to, when the host passes `blockReload.deserializeBlocks`. |
22
22
  | Project running | The change is held. Value and position changes apply when the project stops. |
23
- | Unsaved edits | The edits are kept. **Discard Edits and Reload…** asks before replacing them with the folder contents. |
24
- | Other changes to the project JSON, assets, the manifest or extensions | **Reload Whole Project** reads the folder again with the same checks as opening it. This is never automatic. |
23
+ | Unsaved edits | The edits are kept. When the host passes `blockReload.compareChanges`, **Compare and Choose…** shows your unsaved edits next to the folder's changes, and the edits are replaced only if you choose **Discard Edits and Load from Folder**. Without it, **Discard Edits and Reload…** asks before replacing them. |
24
+ | Other changes: targets, variables, comments, blocks that need a variable or an extension the project lacks, assets, the manifest or extensions | **Reload Whole Project** reads the folder again with the same checks as opening it. This is never automatic. |
25
25
  | Incomplete write, such as truncated JSON | The notice waits and the folder is checked again shortly. |
26
26
 
27
- Pass `autoReload: false` to `mountProjectFolder` to keep every reload behind the button. Checks compare file size and modification time before reading contents, so an overwrite that keeps both unchanged is not detected. Saving still compares the bytes on disk and refuses to overwrite a folder that changed.
27
+ Script replacements are checked against the VM before any change, and every target is restored if the VM fails part way; the change then waits for **Reload Whole Project**. Pass `autoReload: false` to `mountProjectFolder` to keep every reload behind the button. Checks compare file size and modification time before reading contents, so an overwrite that keeps both unchanged is not detected. Saving still compares the bytes on disk and refuses to overwrite a folder that changed.
28
28
 
29
29
  ## Development
30
30
 
@@ -33,3 +33,11 @@ Use Node.js 26, then run `npm ci` and `npm test`. Vite builds the JavaScript lib
33
33
  The Editor's headless integration test uses an actual disk directory and substitutes the picker interaction. To verify the native picker separately, open a disposable sb3-toolchain v1 project with **File → Open Project Folder…**, accept read/write access, edit a standard block, and select **File → Save to Project Folder**. Check that `project.source.json` changed in the chosen directory and reopen the same folder to confirm the edit.
34
34
 
35
35
  The initial source was extracted from [TurboWarp Plus Editor at d14d065](https://github.com/kubohiroya/turbowarp-plus-editor/tree/d14d0659f77f37328c855ecfeeae0927d81ae81a/packages/editor-project-folder) under MPL-2.0.
36
+
37
+ ## Release
38
+
39
+ `.github/workflows/release.yml` publishes to npm. Push a `v<version>` tag that names the
40
+ `package.json` version on a `main` commit: the workflow runs the tests, packs the archive, attaches it
41
+ to the GitHub Release, publishes it to npm and points `latest` and `next` at it. It authenticates with
42
+ npm Trusted Publishing (OIDC), not a token, and publishes with provenance. The npm settings name this
43
+ workflow file, so rename both together.
@@ -0,0 +1,3 @@
1
+ # Licenses
2
+
3
+ The app does not bundle any dependencies with licenses.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { FolderHost, FolderVM } from './session.js';
2
- export type { FolderHost, FolderVM, OpenResult } from './session.js';
2
+ export type { Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult } from './session.js';
3
3
  export type { ReloadTarget } from './block-reload.js';
4
+ export type { DeserializeBlocks } from './script-reload.js';
4
5
  type MenuElement = (component: any, props: any, ...children: any[]) => any;
5
6
  interface MenuProps {
6
7
  vm: FolderVM;
package/dist/index.js CHANGED
@@ -278,17 +278,17 @@ function I(e, t, n) {
278
278
  }) }) : null;
279
279
  }
280
280
  // src/block-reload.ts
281
- var L = ["targets"], R = ["targets"], z = ["blocks"], B = ["blocks"], V = [
281
+ var ee = ["targets"], te = ["targets"], ne = ["blocks"], L = ["blocks"], R = [
282
282
  "inputs",
283
283
  "fields",
284
284
  "x",
285
285
  "y"
286
- ], H = [
286
+ ], z = [
287
287
  "inputs",
288
288
  "fields",
289
289
  "x",
290
290
  "y"
291
- ], U = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), W = {
291
+ ], B = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), V = {
292
292
  4: ["math_number", "NUM"],
293
293
  5: ["math_positive_number", "NUM"],
294
294
  6: ["math_whole_number", "NUM"],
@@ -296,28 +296,28 @@ var L = ["targets"], R = ["targets"], z = ["blocks"], B = ["blocks"], V = [
296
296
  8: ["math_angle", "NUM"],
297
297
  9: ["colour_picker", "COLOUR"],
298
298
  10: ["text", "TEXT"]
299
- }, G = () => v("Only values and coordinates of existing blocks can be reloaded"), K = (e, t) => P(Object.keys(e), Object.keys(t)), q = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? G() : {
299
+ }, H = () => v("Only values and coordinates of existing blocks can be reloaded"), U = (e, t) => P(Object.keys(e), Object.keys(t)), W = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? H() : {
300
300
  x: e,
301
301
  y: t
302
302
  };
303
- function J(e, t) {
304
- let { targets: n } = e, i = r(e, L), { targets: a } = t, o = r(t, R);
305
- if (n.length !== a.length || !P(i, o)) return G();
303
+ function G(e, t) {
304
+ let { targets: n } = e, i = r(e, ee), { targets: a } = t, o = r(t, te);
305
+ if (n.length !== a.length || !P(i, o)) return H();
306
306
  let s = [];
307
307
  for (let [e, t] of n.entries()) {
308
- let { blocks: n } = t, i = r(t, z), o = a[e], { blocks: c } = o;
309
- if (!P(i, r(o, B))) return G();
308
+ let { blocks: n } = t, i = r(t, ne), o = a[e], { blocks: c } = o;
309
+ if (!P(i, r(o, L))) return H();
310
310
  if (!y(n) || !y(c)) {
311
311
  if (P(n, c)) continue;
312
- return G();
312
+ return H();
313
313
  }
314
- if (!K(n, c)) return G();
314
+ if (!U(n, c)) return H();
315
315
  for (let [e, i] of Object.entries(n)) {
316
316
  let n = c[e];
317
317
  if (P(i, n)) continue;
318
- if (!y(i) || !y(n)) return G();
319
- let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, V), { inputs: p, fields: m, x: h, y: g } = n;
320
- if (!P(f, r(n, H)) || typeof f.opcode != "string") return G();
318
+ if (!y(i) || !y(n)) return H();
319
+ let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, R), { inputs: p, fields: m, x: h, y: g } = n;
320
+ if (!P(f, r(n, z)) || typeof f.opcode != "string") return H();
321
321
  let _ = {
322
322
  id: e,
323
323
  target: t.name,
@@ -325,15 +325,15 @@ function J(e, t) {
325
325
  opcode: f.opcode
326
326
  };
327
327
  if (u !== h || d !== g) {
328
- if (f.topLevel !== !0) return G();
328
+ if (f.topLevel !== !0) return H();
329
329
  s.push(l(l({}, _), {}, {
330
330
  kind: "position",
331
- before: q(u, d),
332
- after: q(h, g)
331
+ before: W(u, d),
332
+ after: W(h, g)
333
333
  }));
334
334
  }
335
335
  if (!P(o, m)) {
336
- if (!y(o) || !y(m) || !K(o, m)) return G();
336
+ if (!y(o) || !y(m) || !U(o, m)) return H();
337
337
  for (let [e, t] of Object.entries(o)) {
338
338
  let n = m[e];
339
339
  if (!P(t, n)) {
@@ -341,7 +341,7 @@ function J(e, t) {
341
341
  "VARIABLE",
342
342
  "LIST",
343
343
  "BROADCAST_OPTION"
344
- ].includes(e) || f.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !U(t[0]) || !U(n[0])) return G();
344
+ ].includes(e) || f.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !B(t[0]) || !B(n[0])) return H();
345
345
  s.push(l(l({}, _), {}, {
346
346
  kind: "field",
347
347
  name: e,
@@ -352,15 +352,15 @@ function J(e, t) {
352
352
  }
353
353
  }
354
354
  if (!P(a, p)) {
355
- if (!y(a) || !y(p) || !K(a, p)) return G();
355
+ if (!y(a) || !y(p) || !U(a, p)) return H();
356
356
  for (let [e, t] of Object.entries(a)) {
357
357
  let n = p[e];
358
358
  if (P(t, n)) continue;
359
- if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return G();
359
+ if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return H();
360
360
  let r = t[0] === 1 ? 1 : t[0] === 3 && typeof t[1] == "string" && t[1] === n[1] ? 2 : null;
361
- if (r === null || t.length !== r + 1 || n.length !== r + 1) return G();
361
+ if (r === null || t.length !== r + 1 || n.length !== r + 1) return H();
362
362
  let i = t[r], a = n[r];
363
- if (!Array.isArray(i) || !Array.isArray(a) || i.length !== 2 || a.length !== 2 || typeof i[0] != "number" || !Object.hasOwn(W, i[0]) || i[0] !== a[0] || !U(i[1]) || !U(a[1])) return G();
363
+ if (!Array.isArray(i) || !Array.isArray(a) || i.length !== 2 || a.length !== 2 || typeof i[0] != "number" || !Object.hasOwn(V, i[0]) || i[0] !== a[0] || !B(i[1]) || !B(a[1])) return H();
364
364
  let o = r === 2 ? t[1] : null;
365
365
  s.push(l(l({}, _), {}, {
366
366
  kind: "input",
@@ -376,15 +376,15 @@ function J(e, t) {
376
376
  }
377
377
  return s;
378
378
  }
379
- function Y(e, t) {
379
+ function K(e, t) {
380
380
  let n = /* @__PURE__ */ new Set(), r = t.map((t) => {
381
381
  let r = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
382
- if (r.length !== 1) return G();
382
+ if (r.length !== 1) return H();
383
383
  let i = r[0], a = i.blocks, o = a.getBlock(t.id);
384
- if (!o || o.opcode !== t.opcode) return G();
384
+ if (!o || o.opcode !== t.opcode) return H();
385
385
  if (n.add(i), t.kind === "position") {
386
386
  var s, c;
387
- return !o.topLevel || Math.round((s = o.x) == null ? 0 : s) !== t.before.x || Math.round((c = o.y) == null ? 0 : c) !== t.before.y ? G() : (e) => a.moveBlock({
387
+ return !o.topLevel || Math.round((s = o.x) == null ? 0 : s) !== t.before.x || Math.round((c = o.y) == null ? 0 : c) !== t.before.y ? H() : (e) => a.moveBlock({
388
388
  id: t.id,
389
389
  newCoordinate: t[e]
390
390
  });
@@ -393,13 +393,13 @@ function Y(e, t) {
393
393
  if (t.kind === "input") {
394
394
  var d;
395
395
  let e = o.inputs[t.name], n = e == null ? void 0 : e.shadow;
396
- if (!n || e.block !== ((d = t.connected) == null ? n : d)) return G();
397
- let r = a.getBlock(n), [i, s] = W[t.tag];
398
- if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return G();
396
+ if (!n || e.block !== ((d = t.connected) == null ? n : d)) return H();
397
+ let r = a.getBlock(n), [i, s] = V[t.tag];
398
+ if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return H();
399
399
  l = r, u = s;
400
400
  }
401
401
  let f = l.fields[u];
402
- return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? G() : (e) => a.changeBlock({
402
+ return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? H() : (e) => a.changeBlock({
403
403
  id: l.id,
404
404
  element: "field",
405
405
  name: u,
@@ -414,18 +414,141 @@ function Y(e, t) {
414
414
  }
415
415
  return [...n];
416
416
  }
417
+ // src/script-reload.ts
418
+ var q = ["targets"], re = ["targets"], ie = ["blocks"], ae = ["blocks"], J = (e = "Only changes to the scripts of existing targets can be reloaded in place") => v(e), oe = /* @__PURE__ */ new Set([
419
+ "motion",
420
+ "looks",
421
+ "sound",
422
+ "event",
423
+ "control",
424
+ "sensing",
425
+ "operator",
426
+ "data",
427
+ "procedures",
428
+ "argument",
429
+ "math",
430
+ "text",
431
+ "colour"
432
+ ]), Y = (e) => e.split("_", 1)[0], se = /* @__PURE__ */ new Set([
433
+ "VARIABLE",
434
+ "LIST",
435
+ "BROADCAST_OPTION"
436
+ ]), ce = (e) => y(e) && typeof e.parent == "string" ? e.parent : null;
437
+ function X(e) {
438
+ let t = /* @__PURE__ */ new Map();
439
+ for (let n of Object.keys(e)) {
440
+ let r = n, i = /* @__PURE__ */ new Set();
441
+ for (;;) {
442
+ if (i.has(r)) return J("Blocks form a cycle");
443
+ i.add(r);
444
+ let t = ce(e[r]);
445
+ if (t === null) break;
446
+ if (!Object.hasOwn(e, t)) return J("A block refers to a missing parent");
447
+ r = t;
448
+ }
449
+ t.set(n, r);
450
+ }
451
+ return t;
452
+ }
453
+ function le(e, t) {
454
+ for (let n of Object.values(e)) y(n) && typeof n.opcode == "string" && t.add(Y(n.opcode));
455
+ }
456
+ function ue(e, t) {
457
+ let { targets: n } = e, i = r(e, q), { targets: a } = t, o = r(t, re);
458
+ if (n.length !== a.length || !P(i, o)) return J();
459
+ let s = new Set(oe);
460
+ for (let e of n) y(e.blocks) && le(e.blocks, s);
461
+ let c = [];
462
+ for (let [e, t] of n.entries()) {
463
+ let { blocks: n } = t, i = r(t, ie), o = a[e], { blocks: l } = o;
464
+ if (!P(i, r(o, ae))) return J();
465
+ if (P(n, l)) continue;
466
+ let u = y(n) ? n : {}, d = y(l) ? l : {}, f = X(u), p = X(d), m = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Set(), g = (e) => {
467
+ let t = f.get(e), n = p.get(e), r = !1;
468
+ return t !== void 0 && !m.has(t) && (m.add(t), r = !0), n !== void 0 && !h.has(n) && (h.add(n), r = !0), r;
469
+ };
470
+ for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) P(u[e], d[e]) || g(e);
471
+ for (let e = !0; e;) {
472
+ e = !1;
473
+ for (let [t, n] of f) m.has(n) && g(t) && (e = !0);
474
+ for (let [t, n] of p) h.has(n) && g(t) && (e = !0);
475
+ }
476
+ let _ = {};
477
+ for (let [e, t] of p) h.has(t) && (_[e] = d[e]);
478
+ for (let e of Object.values(_)) if (y(e)) {
479
+ if (typeof e.opcode != "string") return J("A block has no opcode");
480
+ if (!s.has(Y(e.opcode))) return J(`Blocks need an extension the project does not use: ${e.opcode}`);
481
+ }
482
+ c.push({
483
+ target: t.name,
484
+ stage: t.isStage,
485
+ remove: [...m],
486
+ blocks: _
487
+ });
488
+ }
489
+ return c;
490
+ }
491
+ var de = (e, t) => {
492
+ let n = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
493
+ return n.length === 1 ? n[0] : J();
494
+ };
495
+ function fe(e, t, n) {
496
+ let r = t.map((t) => {
497
+ let r = de(e, t), i = r.blocks;
498
+ for (let e of t.remove) {
499
+ let t = i.getBlock(e);
500
+ if (!t || !t.topLevel || !i._scripts.includes(e)) return J("The editor and the folder differ");
501
+ }
502
+ let a = Object.values(n(JSON.parse(JSON.stringify(t.blocks))));
503
+ for (let e of a) {
504
+ var o;
505
+ if (typeof e.id != "string" || typeof e.opcode != "string") return J("A block could not be read");
506
+ if (e.comment && !(r.comments && Object.hasOwn(r.comments, e.comment))) return J("A block refers to a missing comment");
507
+ for (let [t, n] of Object.entries((o = e.fields) == null ? {} : o)) {
508
+ var s;
509
+ if ((se.has(t) || n.variableType) && (typeof n.id != "string" || !((s = r.lookupVariableById) != null && s.call(r, n.id)))) return J("A block refers to a variable, list or message the project does not have");
510
+ }
511
+ }
512
+ return {
513
+ target: r,
514
+ container: i,
515
+ edit: t,
516
+ created: a
517
+ };
518
+ }), i = r.map(({ container: e }) => ({
519
+ container: e,
520
+ blocks: l({}, e._blocks),
521
+ scripts: [...e._scripts],
522
+ tops: new Map(Object.entries(e._blocks).map(([e, t]) => [e, t.topLevel]))
523
+ }));
524
+ try {
525
+ for (let { container: e, edit: t, created: n } of r) {
526
+ for (let n of t.remove) e.deleteBlock(n);
527
+ for (let t of n) e.createBlock(t, !0), e._blocks[t.id] !== t && J("A block id is already in use");
528
+ e.resetCache();
529
+ }
530
+ } catch (e) {
531
+ for (let { container: e, blocks: t, scripts: n, tops: r } of i) {
532
+ e._blocks = t, e._scripts = n;
533
+ for (let [e, n] of r) t[e].topLevel = n;
534
+ e.resetCache();
535
+ }
536
+ throw e;
537
+ }
538
+ return r.map(({ target: e }) => e);
539
+ }
417
540
  // src/session.ts
418
- var X = /* @__PURE__ */ new WeakMap(), Z = (e) => {
419
- let t = X.get(e);
541
+ var Z = /* @__PURE__ */ new WeakMap(), pe = (e) => {
542
+ let t = Z.get(e);
420
543
  if (t) return t;
421
544
  let n = { assets: null };
422
545
  return e.addHelper({ load(e, t, r) {
423
546
  var i;
424
547
  let a = (i = n.assets) == null ? void 0 : i.get(k(e, t, r));
425
548
  return a ? Promise.resolve(a) : null;
426
- } }, 101), X.set(e, n), n;
549
+ } }, 101), Z.set(e, n), n;
427
550
  };
428
- function ee(e, t) {
551
+ function me(e, t) {
429
552
  let n = null, r = !1, i = !1, a = 0, o = null, s = () => S(e.toJSON(void 0, { allowOptimization: !1 })), c = () => {
430
553
  a++;
431
554
  }, u = () => {
@@ -447,7 +570,7 @@ function ee(e, t) {
447
570
  let u = e.runtime.storage, d = await A(r, u);
448
571
  if (i || e.runtime.getTargetForStage() !== c || t.isProjectDirty() && !o()) return "cancelled";
449
572
  t.beforeLoad(), n = null;
450
- let f = Z(u), p = d.storageAssets;
573
+ let f = pe(u), p = d.storageAssets;
451
574
  f.assets = p;
452
575
  let m;
453
576
  try {
@@ -464,33 +587,42 @@ function ee(e, t) {
464
587
  } finally {
465
588
  r = !1;
466
589
  }
467
- }, h = async (e) => {
468
- var t;
469
- let n = typeof e.pending == "object" ? e.pending : null, r = await M(e.source, (t = n == null ? void 0 : n.update) == null ? null : t);
470
- if (!r || typeof r == "string") return r;
471
- if ((n == null ? void 0 : n.update) === r) return l(l({}, n), {}, { stable: !0 });
590
+ }, h = (e, n) => {
591
+ var r;
472
592
  try {
473
593
  return {
474
- update: r,
475
- edits: J(e.source.project, r.project),
476
- stable: !1
594
+ kind: "values",
595
+ changes: G(e, n)
477
596
  };
478
597
  } catch (e) {
479
598
  if (!(e instanceof _)) throw e;
599
+ }
600
+ if (!((r = t.blockReload) != null && r.deserializeBlocks)) return null;
601
+ try {
480
602
  return {
481
- update: r,
482
- edits: null,
483
- stable: !1
603
+ kind: "scripts",
604
+ changes: ue(e, n)
484
605
  };
606
+ } catch (e) {
607
+ if (!(e instanceof _)) throw e;
608
+ return null;
485
609
  }
486
- }, g = () => {
610
+ }, g = async (e) => {
611
+ var t;
612
+ let n = typeof e.pending == "object" ? e.pending : null, r = await M(e.source, (t = n == null ? void 0 : n.update) == null ? null : t);
613
+ return !r || typeof r == "string" ? r : (n == null ? void 0 : n.update) === r ? l(l({}, n), {}, { stable: !0 }) : {
614
+ update: r,
615
+ edits: h(e.source.project, r.project),
616
+ stable: !1
617
+ };
618
+ }, v = () => {
487
619
  let e = n == null ? void 0 : n.pending;
488
620
  return !e || e === "waiting" ? null : e === "structure" || e.edits === null ? "full" : "partial";
489
- }, v = () => {
621
+ }, y = () => {
490
622
  var e;
491
623
  let i = n == null ? void 0 : n.pending;
492
- return i ? r ? "busy" : i === "waiting" ? "waiting" : t.isProjectDirty() ? "dirty" : (e = t.blockReload) != null && e.isRunning() ? "running" : g() === "full" ? "full" : "ready" : null;
493
- }, y = () => {
624
+ return i ? r ? "busy" : i === "waiting" ? "waiting" : t.isProjectDirty() ? "dirty" : (e = t.blockReload) != null && e.isRunning() ? "running" : v() === "full" ? "full" : "ready" : null;
625
+ }, b = () => {
494
626
  var e;
495
627
  return !t.isProjectDirty() && !((e = t.blockReload) != null && e.isRunning());
496
628
  };
@@ -505,14 +637,14 @@ function ee(e, t) {
505
637
  return r;
506
638
  },
507
639
  get reloadState() {
508
- return v();
640
+ return y();
509
641
  },
510
642
  get reloadKind() {
511
- return g();
643
+ return v();
512
644
  },
513
645
  get canAutoReload() {
514
646
  let e = n == null ? void 0 : n.pending;
515
- return v() === "ready" && typeof e == "object" && !!e && e.stable;
647
+ return y() === "ready" && typeof e == "object" && !!e && e.stable;
516
648
  },
517
649
  get settling() {
518
650
  let e = n == null ? void 0 : n.pending;
@@ -526,31 +658,56 @@ function ee(e, t) {
526
658
  var e;
527
659
  return (e = n == null ? void 0 : n.source.directory) == null ? null : e;
528
660
  },
661
+ async comparison() {
662
+ let e = n;
663
+ if (!e) return null;
664
+ let t = new TextDecoder(), r = t.decode(e.source.files.get(m)), i;
665
+ try {
666
+ let t = I(e.source.project, e.baseline, s());
667
+ i = t ? `${JSON.stringify(t, null, 2)}\n` : r;
668
+ } catch (e) {
669
+ if (!(e instanceof _)) throw e;
670
+ i = null;
671
+ }
672
+ let a;
673
+ try {
674
+ let n = await (await e.source.directory.getFileHandle(m)).getFile();
675
+ a = t.decode(new Uint8Array(await n.arrayBuffer()));
676
+ } catch (e) {
677
+ a = null;
678
+ }
679
+ return n === e ? {
680
+ base: r,
681
+ editor: i,
682
+ disk: a
683
+ } : null;
684
+ },
529
685
  refresh() {
530
686
  if (i || r || !n || !t.blockReload) return Promise.resolve();
531
687
  if (o) return o;
532
688
  let e = n, a = e.baseline;
533
- return o = h(e).then((t) => {
689
+ return o = g(e).then((t) => {
534
690
  n === e && e.baseline === a && !r && (e.pending = t);
535
691
  }).finally(() => {
536
692
  o = null;
537
693
  }), o;
538
694
  },
539
695
  async reload() {
540
- if (!n || v() !== "ready" || !t.blockReload) return !1;
696
+ if (!n || y() !== "ready" || !t.blockReload) return !1;
541
697
  let o = n;
542
698
  d(o), r = !0;
543
699
  try {
544
- let r = a, u = await h(o);
545
- if (n !== o || i || e.runtime.getTargetForStage() !== o.stage || (o.pending = u, !u || typeof u == "string" || u.edits === null || r !== a || !y())) return !1;
546
- let d;
700
+ let r = a, d = await g(o);
701
+ if (n !== o || i || e.runtime.getTargetForStage() !== o.stage || (o.pending = d, !d || typeof d == "string" || d.edits === null || r !== a || !b())) return !1;
702
+ let f;
547
703
  try {
548
- var c;
549
- d = Y((c = e.runtime.targets) == null ? [] : c, u.edits);
704
+ var c, u;
705
+ let { edits: n } = d;
706
+ f = n.kind === "values" ? K((c = e.runtime.targets) == null ? [] : c, n.changes) : fe((u = e.runtime.targets) == null ? [] : u, n.changes, t.blockReload.deserializeBlocks);
550
707
  } catch (e) {
551
- throw e instanceof _ && (o.pending = l(l({}, u), {}, { edits: null })), e;
708
+ throw o.pending = l(l({}, d), {}, { edits: null }), e;
552
709
  }
553
- return o.baseline = s(), o.source.project = u.update.project, o.source.files.set(m, u.update.bytes), o.source.versions.set(m, u.update.version), o.pending = null, t.blockReload.onApplied(d), !0;
710
+ return o.baseline = s(), o.source.project = d.update.project, o.source.files.set(m, d.update.bytes), o.source.versions.set(m, d.update.version), o.pending = null, t.blockReload.onApplied(f), !0;
554
711
  } finally {
555
712
  r = !1;
556
713
  }
@@ -615,6 +772,15 @@ var Q = {
615
772
  reloadAll: "Reload Whole Project",
616
773
  discard: "Discard Edits and Reload…",
617
774
  discardConfirm: "Discard your unsaved edits and load the project from the folder?",
775
+ compare: "Compare and Choose…",
776
+ compareTitle: "External changes and your unsaved edits",
777
+ compareDescription: "The project folder changed while the Editor has unsaved edits. Loading from the folder discards your edits.",
778
+ compareUnsaved: "Some of your edits are outside what the project folder can save, so they are not shown here.",
779
+ yourEdits: "Your unsaved edits",
780
+ diskChanges: "Changes in the folder",
781
+ keep: "Keep My Edits",
782
+ discardLoad: "Discard Edits and Load from Folder",
783
+ close: "Close",
618
784
  dirty: "You have unsaved edits.",
619
785
  running: "Stop the project before reloading.",
620
786
  runningAuto: "The changes load when the project stops.",
@@ -638,6 +804,15 @@ var Q = {
638
804
  reloadAll: "作品全体を再読み込み",
639
805
  discard: "編集を破棄して再読み込み…",
640
806
  discardConfirm: "未保存の編集を破棄して、フォルダの作品を読み込みますか?",
807
+ compare: "比較して選ぶ…",
808
+ compareTitle: "外部の変更と未保存の編集",
809
+ compareDescription: "Editor に未保存の編集がある間に、プロジェクトフォルダが変更されました。フォルダから読み込むと、未保存の編集は失われます。",
810
+ compareUnsaved: "未保存の編集の一部はプロジェクトフォルダに保存できない種類のため、ここには表示していません。",
811
+ yourEdits: "あなたの未保存の編集",
812
+ diskChanges: "フォルダでの変更",
813
+ keep: "編集を残す",
814
+ discardLoad: "編集を破棄してフォルダから読み込む",
815
+ close: "閉じる",
641
816
  dirty: "未保存の編集があります。",
642
817
  running: "作品を停止してから再読み込みできます。",
643
818
  runningAuto: "作品の停止後に反映します。",
@@ -646,11 +821,11 @@ var Q = {
646
821
  full: "この変更は作品全体の再読み込みが必要です。"
647
822
  }
648
823
  }, $ = /* @__PURE__ */ new WeakMap();
649
- function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
824
+ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
650
825
  var a;
651
826
  let o = t.defaultView, s = o == null ? void 0 : o.showDirectoryPicker;
652
827
  if (!s || !((a = e.runtime) != null && a.storage)) return null;
653
- let c = ee(e, n), l = t.createElement("output");
828
+ let c = me(e, n), l = t.createElement("output");
654
829
  l.dataset.projectFolderStatus = "", l.setAttribute("role", "status"), l.hidden = !0, Object.assign(l.style, {
655
830
  position: "fixed",
656
831
  insetInlineEnd: "1rem",
@@ -672,6 +847,7 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
672
847
  d((t instanceof _ ? n[t.code] : n.failed) + r);
673
848
  }, m, h = () => {};
674
849
  if (n.blockReload) {
850
+ var g;
675
851
  let e = f(r), a = t.createElement("aside");
676
852
  a.dataset.projectFolderExternal = "", a.hidden = !0, Object.assign(a.style, {
677
853
  position: "fixed",
@@ -689,7 +865,42 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
689
865
  s.setAttribute("role", "status");
690
866
  let l = t.createElement("button");
691
867
  l.type = "button", l.textContent = e.reload, a.append(s, l), t.body.append(a);
692
- let u, g = null, _ = null, v = null, y = (t) => {
868
+ let u = (g = n.blockReload.compareChanges) == null ? void 0 : g.bind(n.blockReload), _ = !1, v = async (t) => {
869
+ if (!_) {
870
+ _ = !0;
871
+ try {
872
+ let n = await c.comparison();
873
+ if (!n) return;
874
+ let r = [{
875
+ title: e.diskChanges,
876
+ before: n.base,
877
+ after: n.disk
878
+ }];
879
+ n.editor !== null && r.unshift({
880
+ title: e.yourEdits,
881
+ before: n.base,
882
+ after: n.editor
883
+ }), await t({
884
+ title: e.compareTitle,
885
+ description: e.compareDescription,
886
+ notes: n.editor === null ? [e.compareUnsaved] : [],
887
+ sections: r,
888
+ actions: [{
889
+ id: "keep",
890
+ label: e.keep
891
+ }, {
892
+ id: "discard",
893
+ label: e.discardLoad
894
+ }],
895
+ closeLabel: e.close
896
+ }) === "discard" && c.reloadState === "dirty" && C(() => c.reloadAll(() => !0));
897
+ } catch (e) {
898
+ p(r, e);
899
+ } finally {
900
+ _ = !1, h();
901
+ }
902
+ }
903
+ }, y, b = null, x = null, S = null, C = (t) => {
693
904
  let n = t();
694
905
  h(), n.then((t) => {
695
906
  (t === !0 || t === "opened") && d(e.reloaded);
@@ -697,8 +908,8 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
697
908
  };
698
909
  h = () => {
699
910
  let t = c.reloadState, n = c.reloadKind;
700
- if (i && c.canAutoReload && c.pendingVersion !== g) {
701
- g = c.pendingVersion, y(() => c.reload());
911
+ if (i && c.canAutoReload && c.pendingVersion !== b) {
912
+ b = c.pendingVersion, C(() => c.reload());
702
913
  return;
703
914
  }
704
915
  a.hidden = !t, l.hidden = !n, l.disabled = ![
@@ -706,32 +917,32 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
706
917
  "full",
707
918
  "dirty"
708
919
  ].includes(t == null ? "" : t);
709
- let r = t === "dirty" ? e.discard : n === "full" ? e.reloadAll : e.reload;
920
+ let r = t === "dirty" ? u ? e.compare : e.discard : n === "full" ? e.reloadAll : e.reload;
710
921
  l.textContent !== r && (l.textContent = r);
711
- let o = !t || t === "ready" ? "" : t === "running" && n === "partial" && i ? e.runningAuto : e[t], u = o ? `${e.external} ${o}` : e.external;
712
- s.textContent !== u && (s.textContent = u);
713
- let d = c.directory;
714
- v && _ !== d && (v.disconnect(), _ = d, d && v.observe(d, { recursive: !0 }).catch(() => {}));
922
+ let o = !t || t === "ready" ? "" : t === "running" && n === "partial" && i ? e.runningAuto : e[t], d = o ? `${e.external} ${o}` : e.external;
923
+ s.textContent !== d && (s.textContent = d);
924
+ let f = c.directory;
925
+ S && x !== f && (S.disconnect(), x = f, f && S.observe(f, { recursive: !0 }).catch(() => {}));
715
926
  };
716
- let b = () => {
927
+ let w = () => {
717
928
  t.visibilityState === "visible" && c.refresh().then(() => {
718
- h(), c.settling && x(500);
929
+ h(), c.settling && T(500);
719
930
  }, (e) => p(r, e));
720
- }, x = (e) => {
721
- o.clearTimeout(u), u = o.setTimeout(b, e);
931
+ }, T = (e) => {
932
+ o.clearTimeout(y), y = o.setTimeout(w, e);
722
933
  };
723
934
  if (o.FileSystemObserver) try {
724
- v = new o.FileSystemObserver(() => x(300));
935
+ S = new o.FileSystemObserver(() => T(300));
725
936
  } catch (e) {
726
- v = null;
937
+ S = null;
727
938
  }
728
939
  l.addEventListener("click", () => {
729
940
  let t = c.reloadState;
730
- t === "ready" ? y(() => c.reload()) : t === "full" ? y(() => c.reloadAll(() => !0)) : t === "dirty" && y(() => c.reloadAll(() => o.confirm(e.discardConfirm)));
941
+ t === "ready" ? C(() => c.reload()) : t === "full" ? C(() => c.reloadAll(() => !0)) : t === "dirty" && u ? v(u) : t === "dirty" && C(() => c.reloadAll(() => o.confirm(e.discardConfirm)));
731
942
  });
732
- let S = n.blockReload.subscribe(h), C = o.setInterval(b, 2e3);
733
- o.addEventListener("focus", b), t.addEventListener("visibilitychange", b), m = () => {
734
- S(), o.clearInterval(C), o.clearTimeout(u), v == null || v.disconnect(), o.removeEventListener("focus", b), t.removeEventListener("visibilitychange", b), a.remove();
943
+ let E = n.blockReload.subscribe(h), D = o.setInterval(w, 2e3);
944
+ o.addEventListener("focus", w), t.addEventListener("visibilitychange", w), m = () => {
945
+ E(), o.clearInterval(D), o.clearTimeout(y), S == null || S.disconnect(), o.removeEventListener("focus", w), t.removeEventListener("visibilitychange", w), a.remove();
735
946
  };
736
947
  }
737
948
  return $.set(e, {
@@ -752,7 +963,7 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
752
963
  }
753
964
  };
754
965
  }
755
- function ne(e, t = "en") {
966
+ function ge(e, t = "en") {
756
967
  let n = $.get(e);
757
968
  if (n) return {
758
969
  open: () => n.open(t),
@@ -760,7 +971,7 @@ function ne(e, t = "en") {
760
971
  detach: () => n.session.detach()
761
972
  };
762
973
  }
763
- function re(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
974
+ function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
764
975
  let o = $.get(t);
765
976
  if (!o) return null;
766
977
  let s = n.startsWith("ja") ? Q.ja : Q.en, c = (t) => {
@@ -780,4 +991,4 @@ function re(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequest
780
991
  };
781
992
  return e(i, null, c("open"), o.session.canSave ? c("save") : null);
782
993
  }
783
- export { te as mountProjectFolder, ne as projectFolderActions, re as renderProjectFolderMenu };
994
+ export { he as mountProjectFolder, ge as projectFolderActions, _e as renderProjectFolderMenu };
@@ -0,0 +1,50 @@
1
+ import type { JsonObject, Project } from './source.js';
2
+ import type { ReloadTarget } from './block-reload.js';
3
+ /** A block as the VM stores it after `deserializeBlocks`. */
4
+ export type VmBlock = {
5
+ id: string;
6
+ opcode: string;
7
+ topLevel: boolean;
8
+ parent?: string | null;
9
+ comment?: string;
10
+ fields: Record<string, {
11
+ name?: string;
12
+ value: unknown;
13
+ id?: string | null;
14
+ variableType?: string;
15
+ }>;
16
+ };
17
+ /** The VM's sb3 `deserializeBlocks`: turns serialized blocks into VM blocks, in place. Results are checked before use. */
18
+ export type DeserializeBlocks = (blocks: Record<string, unknown>) => Record<string, {
19
+ id: string;
20
+ }>;
21
+ type Container = ReloadTarget['blocks'] & {
22
+ _blocks: Record<string, VmBlock>;
23
+ _scripts: string[];
24
+ createBlock(block: VmBlock, deferProjectChanged?: boolean): void;
25
+ deleteBlock(id: string): void;
26
+ resetCache(): void;
27
+ };
28
+ export type ScriptReloadTarget = ReloadTarget & {
29
+ blocks: Container;
30
+ comments?: Record<string, unknown>;
31
+ lookupVariableById?(id: string): unknown;
32
+ };
33
+ /** Replace whole scripts of one target: delete the old top blocks, then create the new scripts' blocks. */
34
+ export type ScriptEdit = {
35
+ target: string;
36
+ stage: boolean;
37
+ remove: string[];
38
+ blocks: JsonObject;
39
+ };
40
+ /**
41
+ * Plans script replacements for changes that add, remove or reconnect blocks. Every other property of the
42
+ * project and its targets, including comments, must stay the same; otherwise the whole project is reloaded.
43
+ */
44
+ export declare function planScriptReload(before: Project, after: Project): ScriptEdit[];
45
+ /**
46
+ * Applies planned script replacements. Every edit is checked against the VM before any change. If a change
47
+ * fails part way, every target is restored to its previous blocks.
48
+ */
49
+ export declare function applyScriptReload(targets: readonly ScriptReloadTarget[], edits: ScriptEdit[], deserialize: DeserializeBlocks): ScriptReloadTarget[];
50
+ export {};
package/dist/session.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Storage } from './source.js';
2
2
  import type { ReloadTarget } from './block-reload.js';
3
+ import type { DeserializeBlocks } from './script-reload.js';
3
4
  export interface FolderVM {
4
5
  runtime: {
5
6
  storage: Storage;
@@ -35,10 +36,43 @@ export interface FolderHost {
35
36
  isRunning(): boolean;
36
37
  subscribe(listener: () => void): () => void;
37
38
  onApplied(targets: readonly ReloadTarget[]): void;
39
+ /**
40
+ * The VM's sb3 `deserializeBlocks`. With it, changes that add, remove or reconnect blocks replace the
41
+ * changed scripts in place; without it they need the whole project reloaded.
42
+ */
43
+ deserializeBlocks?: DeserializeBlocks;
44
+ /**
45
+ * Shows the comparisons in `request` and resolves with the chosen action's id, or `null` when closed.
46
+ * With it, unsaved edits are compared with the folder before the user chooses to replace them.
47
+ */
48
+ compareChanges?(request: ComparisonRequest): Promise<string | null>;
38
49
  };
39
50
  }
51
+ /** A titled comparison of two project.source.json texts; `null` stands for a version that cannot be shown. */
52
+ export type ComparisonSection = {
53
+ title: string;
54
+ before: string | null;
55
+ after: string | null;
56
+ };
57
+ export type ComparisonRequest = {
58
+ title: string;
59
+ description: string;
60
+ notes: string[];
61
+ sections: ComparisonSection[];
62
+ actions: {
63
+ id: string;
64
+ label: string;
65
+ }[];
66
+ closeLabel: string;
67
+ };
68
+ /** The last version loaded or saved, the Editor's edits as Save would write them, and the folder now. */
69
+ export type Comparison = {
70
+ base: string;
71
+ editor: string | null;
72
+ disk: string | null;
73
+ };
40
74
  /**
41
- * `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
75
+ * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
42
76
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
43
77
  */
44
78
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
@@ -59,6 +93,11 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
59
93
  /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
60
94
  readonly pendingVersion: string | null;
61
95
  readonly directory: FileSystemDirectoryHandle | null;
96
+ /**
97
+ * Reads what to compare before unsaved edits are replaced. `editor` is `null` when the edits cannot be
98
+ * written to the folder, and `disk` when the folder's project file cannot be read.
99
+ */
100
+ comparison(): Promise<Comparison | null>;
62
101
  refresh(): Promise<void>;
63
102
  reload(): Promise<boolean>;
64
103
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -21,8 +21,13 @@
21
21
  "src",
22
22
  "vite.config.ts",
23
23
  "tsconfig.json",
24
- "README.ja.md"
24
+ "README.ja.md",
25
+ "README.md",
26
+ "LICENSE"
25
27
  ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
26
31
  "scripts": {
27
32
  "build": "vite build && tsc -p tsconfig.json",
28
33
  "test": "npm run build && node --test",
package/src/index.ts CHANGED
@@ -2,8 +2,9 @@ import {FolderError} from './source.js';
2
2
  import {createFolderSession} from './session.js';
3
3
  import type {FolderHost, FolderVM, PickerWindow} from './session.js';
4
4
 
5
- export type {FolderHost, FolderVM, OpenResult} from './session.js';
5
+ export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult} from './session.js';
6
6
  export type {ReloadTarget} from './block-reload.js';
7
+ export type {DeserializeBlocks} from './script-reload.js';
7
8
 
8
9
  const messages = {
9
10
  en: {
@@ -16,6 +17,11 @@ const messages = {
16
17
  external: 'External changes detected.', reload: 'Reload from Disk', reloaded: 'Changes loaded from disk.',
17
18
  reloadAll: 'Reload Whole Project', discard: 'Discard Edits and Reload…',
18
19
  discardConfirm: 'Discard your unsaved edits and load the project from the folder?',
20
+ compare: 'Compare and Choose…', compareTitle: 'External changes and your unsaved edits',
21
+ compareDescription: 'The project folder changed while the Editor has unsaved edits. Loading from the folder discards your edits.',
22
+ compareUnsaved: 'Some of your edits are outside what the project folder can save, so they are not shown here.',
23
+ yourEdits: 'Your unsaved edits', diskChanges: 'Changes in the folder',
24
+ keep: 'Keep My Edits', discardLoad: 'Discard Edits and Load from Folder', close: 'Close',
19
25
  dirty: 'You have unsaved edits.', running: 'Stop the project before reloading.',
20
26
  runningAuto: 'The changes load when the project stops.', busy: 'Please wait for the current operation.',
21
27
  waiting: 'Waiting for the external write to finish.',
@@ -31,6 +37,11 @@ const messages = {
31
37
  external: '外部変更あり', reload: 'ディスクから再読み込み', reloaded: 'ディスクの変更を読み込みました。',
32
38
  reloadAll: '作品全体を再読み込み', discard: '編集を破棄して再読み込み…',
33
39
  discardConfirm: '未保存の編集を破棄して、フォルダの作品を読み込みますか?',
40
+ compare: '比較して選ぶ…', compareTitle: '外部の変更と未保存の編集',
41
+ compareDescription: 'Editor に未保存の編集がある間に、プロジェクトフォルダが変更されました。フォルダから読み込むと、未保存の編集は失われます。',
42
+ compareUnsaved: '未保存の編集の一部はプロジェクトフォルダに保存できない種類のため、ここには表示していません。',
43
+ yourEdits: 'あなたの未保存の編集', diskChanges: 'フォルダでの変更',
44
+ keep: '編集を残す', discardLoad: '編集を破棄してフォルダから読み込む', close: '閉じる',
34
45
  dirty: '未保存の編集があります。', running: '作品を停止してから再読み込みできます。',
35
46
  runningAuto: '作品の停止後に反映します。', busy: '処理が終わるまでお待ちください。',
36
47
  waiting: '外部の書き込みが終わるのを待っています。',
@@ -108,6 +119,31 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
108
119
  button.textContent = message.reload;
109
120
  notice.append(text, button);
110
121
  document.body.append(notice);
122
+ const compareChanges = host.blockReload.compareChanges?.bind(host.blockReload);
123
+ let comparing = false;
124
+ // Lets the user see their unsaved edits next to the folder's changes before choosing to replace them.
125
+ const compare = async (show: NonNullable<typeof compareChanges>) => {
126
+ if (comparing) return;
127
+ comparing = true;
128
+ try {
129
+ const texts = await session.comparison();
130
+ if (!texts) return;
131
+ const sections = [{title: message.diskChanges, before: texts.base, after: texts.disk}];
132
+ if (texts.editor !== null) sections.unshift({title: message.yourEdits, before: texts.base, after: texts.editor});
133
+ const choice = await show({
134
+ title: message.compareTitle, description: message.compareDescription,
135
+ notes: texts.editor === null ? [message.compareUnsaved] : [], sections,
136
+ actions: [{id: 'keep', label: message.keep}, {id: 'discard', label: message.discardLoad}],
137
+ closeLabel: message.close
138
+ });
139
+ if (choice === 'discard' && session.reloadState === 'dirty') apply(() => session.reloadAll(() => true));
140
+ } catch (error) {
141
+ fail(locale, error);
142
+ } finally {
143
+ comparing = false;
144
+ renderReload();
145
+ }
146
+ };
111
147
  let settle: number | undefined;
112
148
  let autoTried: string | null = null;
113
149
  let observed: FileSystemDirectoryHandle | null = null;
@@ -129,7 +165,8 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
129
165
  notice.hidden = !state;
130
166
  button.hidden = !kind;
131
167
  button.disabled = !['ready', 'full', 'dirty'].includes(state ?? '');
132
- const action = state === 'dirty' ? message.discard : kind === 'full' ? message.reloadAll : message.reload;
168
+ const action = state === 'dirty' ? (compareChanges ? message.compare : message.discard) :
169
+ kind === 'full' ? message.reloadAll : message.reload;
133
170
  if (button.textContent !== action) button.textContent = action;
134
171
  const detail = !state || state === 'ready' ? '' :
135
172
  state === 'running' && kind === 'partial' && autoReload ? message.runningAuto : message[state];
@@ -165,6 +202,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
165
202
  const state = session.reloadState;
166
203
  if (state === 'ready') apply(() => session.reload());
167
204
  else if (state === 'full') apply(() => session.reloadAll(() => true));
205
+ else if (state === 'dirty' && compareChanges) void compare(compareChanges);
168
206
  else if (state === 'dirty') apply(() => session.reloadAll(() => view.confirm(message.discardConfirm)));
169
207
  });
170
208
  const unsubscribe = host.blockReload.subscribe(renderReload);
@@ -0,0 +1,171 @@
1
+ import {equal, isObject, unsupported} from './source.js';
2
+ import type {Json, JsonObject, Project} from './source.js';
3
+ import type {ReloadTarget} from './block-reload.js';
4
+
5
+ /** A block as the VM stores it after `deserializeBlocks`. */
6
+ export type VmBlock = {
7
+ id: string; opcode: string; topLevel: boolean; parent?: string | null; comment?: string;
8
+ fields: Record<string, {name?: string; value: unknown; id?: string | null; variableType?: string}>;
9
+ };
10
+ /** The VM's sb3 `deserializeBlocks`: turns serialized blocks into VM blocks, in place. Results are checked before use. */
11
+ export type DeserializeBlocks = (blocks: Record<string, unknown>) => Record<string, {id: string}>;
12
+
13
+ type Container = ReloadTarget['blocks'] & {
14
+ _blocks: Record<string, VmBlock>;
15
+ _scripts: string[];
16
+ createBlock(block: VmBlock, deferProjectChanged?: boolean): void;
17
+ deleteBlock(id: string): void;
18
+ resetCache(): void;
19
+ };
20
+ export type ScriptReloadTarget = ReloadTarget & {
21
+ blocks: Container;
22
+ comments?: Record<string, unknown>;
23
+ lookupVariableById?(id: string): unknown;
24
+ };
25
+
26
+ /** Replace whole scripts of one target: delete the old top blocks, then create the new scripts' blocks. */
27
+ export type ScriptEdit = {target: string; stage: boolean; remove: string[]; blocks: JsonObject};
28
+
29
+ const reject = (detail = 'Only changes to the scripts of existing targets can be reloaded in place'): never =>
30
+ unsupported(detail);
31
+ // Shadow and menu blocks use these prefixes too. Other prefixes must already appear in the project,
32
+ // so that a reload never needs an extension the VM has not loaded.
33
+ const corePrefixes = new Set(['motion', 'looks', 'sound', 'event', 'control', 'sensing', 'operator', 'data',
34
+ 'procedures', 'argument', 'math', 'text', 'colour']);
35
+ const prefix = (opcode: string) => opcode.split('_', 1)[0];
36
+ const variableFields = new Set(['VARIABLE', 'LIST', 'BROADCAST_OPTION']);
37
+
38
+ // A top-level primitive is stored as an array and is its own script.
39
+ const parentOf = (block: Json): string | null => isObject(block) && typeof block.parent === 'string' ? block.parent : null;
40
+
41
+ function rootsOf(blocks: JsonObject) {
42
+ const roots = new Map<string, string>();
43
+ for (const id of Object.keys(blocks)) {
44
+ let current = id;
45
+ const seen = new Set<string>();
46
+ for (;;) {
47
+ if (seen.has(current)) return reject('Blocks form a cycle');
48
+ seen.add(current);
49
+ const parent = parentOf(blocks[current]);
50
+ if (parent === null) break;
51
+ if (!Object.hasOwn(blocks, parent)) return reject('A block refers to a missing parent');
52
+ current = parent;
53
+ }
54
+ roots.set(id, current);
55
+ }
56
+ return roots;
57
+ }
58
+
59
+ function opcodesOf(blocks: JsonObject, into: Set<string>) {
60
+ for (const block of Object.values(blocks)) {
61
+ if (isObject(block) && typeof block.opcode === 'string') into.add(prefix(block.opcode));
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Plans script replacements for changes that add, remove or reconnect blocks. Every other property of the
67
+ * project and its targets, including comments, must stay the same; otherwise the whole project is reloaded.
68
+ */
69
+ export function planScriptReload(before: Project, after: Project): ScriptEdit[] {
70
+ const {targets: oldTargets, ...oldProject} = before;
71
+ const {targets: newTargets, ...newProject} = after;
72
+ if (oldTargets.length !== newTargets.length || !equal(oldProject, newProject)) return reject();
73
+ const known = new Set(corePrefixes);
74
+ for (const target of oldTargets) if (isObject(target.blocks)) opcodesOf(target.blocks, known);
75
+ const edits: ScriptEdit[] = [];
76
+ for (const [index, oldTarget] of oldTargets.entries()) {
77
+ const {blocks: oldValue, ...oldRest} = oldTarget;
78
+ const {blocks: newValue, ...newRest} = newTargets[index];
79
+ if (!equal(oldRest, newRest)) return reject();
80
+ if (equal(oldValue, newValue)) continue;
81
+ const oldBlocks = isObject(oldValue) ? oldValue : {};
82
+ const newBlocks = isObject(newValue) ? newValue : {};
83
+ const oldRoots = rootsOf(oldBlocks);
84
+ const newRoots = rootsOf(newBlocks);
85
+ const removed = new Set<string>();
86
+ const added = new Set<string>();
87
+ const mark = (id: string) => {
88
+ const oldRoot = oldRoots.get(id);
89
+ const newRoot = newRoots.get(id);
90
+ let grew = false;
91
+ if (oldRoot !== undefined && !removed.has(oldRoot)) {removed.add(oldRoot); grew = true;}
92
+ if (newRoot !== undefined && !added.has(newRoot)) {added.add(newRoot); grew = true;}
93
+ return grew;
94
+ };
95
+ for (const id of new Set([...Object.keys(oldBlocks), ...Object.keys(newBlocks)])) {
96
+ if (!equal(oldBlocks[id], newBlocks[id])) mark(id);
97
+ }
98
+ // A block in a replaced script is replaced with it on both sides, so no script is left half-moved.
99
+ for (let grew = true; grew;) {
100
+ grew = false;
101
+ for (const [id, root] of oldRoots) if (removed.has(root) && mark(id)) grew = true;
102
+ for (const [id, root] of newRoots) if (added.has(root) && mark(id)) grew = true;
103
+ }
104
+ const blocks: JsonObject = {};
105
+ for (const [id, root] of newRoots) if (added.has(root)) blocks[id] = newBlocks[id];
106
+ for (const block of Object.values(blocks)) {
107
+ if (!isObject(block)) continue;
108
+ if (typeof block.opcode !== 'string') return reject('A block has no opcode');
109
+ if (!known.has(prefix(block.opcode))) return reject(`Blocks need an extension the project does not use: ${block.opcode}`);
110
+ }
111
+ edits.push({target: oldTarget.name, stage: oldTarget.isStage, remove: [...removed], blocks});
112
+ }
113
+ return edits;
114
+ }
115
+
116
+ const resolveTarget = (targets: readonly ScriptReloadTarget[], edit: ScriptEdit) => {
117
+ const matching = targets.filter(target => target.isStage === edit.stage &&
118
+ (edit.stage || target.isOriginal && target.getName() === edit.target));
119
+ return matching.length === 1 ? matching[0] : reject();
120
+ };
121
+
122
+ /**
123
+ * Applies planned script replacements. Every edit is checked against the VM before any change. If a change
124
+ * fails part way, every target is restored to its previous blocks.
125
+ */
126
+ export function applyScriptReload(targets: readonly ScriptReloadTarget[], edits: ScriptEdit[], deserialize: DeserializeBlocks) {
127
+ const prepared = edits.map(edit => {
128
+ const target = resolveTarget(targets, edit);
129
+ const container = target.blocks;
130
+ for (const id of edit.remove) {
131
+ const block = container.getBlock(id);
132
+ if (!block || !block.topLevel || !container._scripts.includes(id)) return reject('The editor and the folder differ');
133
+ }
134
+ const created = Object.values(deserialize(JSON.parse(JSON.stringify(edit.blocks)))) as VmBlock[];
135
+ for (const block of created) {
136
+ if (typeof block.id !== 'string' || typeof block.opcode !== 'string') return reject('A block could not be read');
137
+ if (block.comment && !(target.comments && Object.hasOwn(target.comments, block.comment))) {
138
+ return reject('A block refers to a missing comment');
139
+ }
140
+ for (const [name, field] of Object.entries(block.fields ?? {})) {
141
+ if (!variableFields.has(name) && !field.variableType) continue;
142
+ if (typeof field.id !== 'string' || !target.lookupVariableById?.(field.id)) {
143
+ return reject('A block refers to a variable, list or message the project does not have');
144
+ }
145
+ }
146
+ }
147
+ return {target, container, edit, created};
148
+ });
149
+ const saved = prepared.map(({container}) => ({container, blocks: {...container._blocks}, scripts: [...container._scripts],
150
+ tops: new Map(Object.entries(container._blocks).map(([id, block]) => [id, block.topLevel]))}));
151
+ try {
152
+ for (const {container, edit, created} of prepared) {
153
+ for (const id of edit.remove) container.deleteBlock(id);
154
+ for (const block of created) {
155
+ container.createBlock(block, true);
156
+ // createBlock ignores an id that is already present, which would leave the script incomplete.
157
+ if (container._blocks[block.id] !== block) reject('A block id is already in use');
158
+ }
159
+ container.resetCache();
160
+ }
161
+ } catch (error) {
162
+ for (const {container, blocks, scripts, tops} of saved) {
163
+ container._blocks = blocks;
164
+ container._scripts = scripts;
165
+ for (const [id, top] of tops) blocks[id].topLevel = top;
166
+ container.resetCache();
167
+ }
168
+ throw error;
169
+ }
170
+ return prepared.map(({target}) => target);
171
+ }
package/src/session.ts CHANGED
@@ -2,6 +2,8 @@ import {assetKey, assertFolderUnchanged, FolderError, parseProject, projectChang
2
2
  import type {Asset, FolderSource, FolderUpdate, Project, Storage} from './source.js';
3
3
  import {applyBlockReload, planBlockReload} from './block-reload.js';
4
4
  import type {ReloadTarget} from './block-reload.js';
5
+ import {applyScriptReload, planScriptReload} from './script-reload.js';
6
+ import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
5
7
 
6
8
  export interface FolderVM {
7
9
  runtime: {
@@ -44,15 +46,36 @@ export interface FolderHost {
44
46
  isRunning(): boolean;
45
47
  subscribe(listener: () => void): () => void;
46
48
  onApplied(targets: readonly ReloadTarget[]): void;
49
+ /**
50
+ * The VM's sb3 `deserializeBlocks`. With it, changes that add, remove or reconnect blocks replace the
51
+ * changed scripts in place; without it they need the whole project reloaded.
52
+ */
53
+ deserializeBlocks?: DeserializeBlocks;
54
+ /**
55
+ * Shows the comparisons in `request` and resolves with the chosen action's id, or `null` when closed.
56
+ * With it, unsaved edits are compared with the folder before the user chooses to replace them.
57
+ */
58
+ compareChanges?(request: ComparisonRequest): Promise<string | null>;
47
59
  };
48
60
  }
49
61
 
62
+ /** A titled comparison of two project.source.json texts; `null` stands for a version that cannot be shown. */
63
+ export type ComparisonSection = {title: string; before: string | null; after: string | null};
64
+ export type ComparisonRequest = {
65
+ title: string; description: string; notes: string[]; sections: ComparisonSection[];
66
+ actions: {id: string; label: string}[]; closeLabel: string;
67
+ };
68
+ /** The last version loaded or saved, the Editor's edits as Save would write them, and the folder now. */
69
+ export type Comparison = {base: string; editor: string | null; disk: string | null};
70
+
50
71
  // `stable` turns true once two scans see the same file version, so consecutive writes settle before auto-apply.
51
- type PendingUpdate = {update: FolderUpdate; edits: ReturnType<typeof planBlockReload> | null; stable: boolean};
72
+ type Edits = {kind: 'values'; changes: ReturnType<typeof planBlockReload>} |
73
+ {kind: 'scripts'; changes: ReturnType<typeof planScriptReload>};
74
+ type PendingUpdate = {update: FolderUpdate; edits: Edits | null; stable: boolean};
52
75
  type Pending = PendingUpdate | 'structure' | 'waiting';
53
76
  type Session = {source: FolderSource; baseline: Project; stage: object; pending: Pending | null};
54
77
  /**
55
- * `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
78
+ * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
56
79
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
57
80
  */
58
81
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
@@ -119,17 +142,27 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
119
142
  busy = false;
120
143
  }
121
144
  };
145
+ // Value and position edits keep every VM block. Other script changes replace only the changed scripts.
146
+ const planEdits = (before: Project, after: Project): Edits | null => {
147
+ try {
148
+ return {kind: 'values', changes: planBlockReload(before, after)};
149
+ } catch (error) {
150
+ if (!(error instanceof FolderError)) throw error;
151
+ }
152
+ if (!host.blockReload?.deserializeBlocks) return null;
153
+ try {
154
+ return {kind: 'scripts', changes: planScriptReload(before, after)};
155
+ } catch (error) {
156
+ if (!(error instanceof FolderError)) throw error;
157
+ return null;
158
+ }
159
+ };
122
160
  const readUpdate = async (session: Session): Promise<Session['pending']> => {
123
161
  const previous = typeof session.pending === 'object' ? session.pending : null;
124
162
  const update = await readFolderUpdate(session.source, previous?.update ?? null);
125
163
  if (!update || typeof update === 'string') return update;
126
164
  if (previous?.update === update) return {...previous, stable: true};
127
- try {
128
- return {update, edits: planBlockReload(session.source.project, update.project), stable: false};
129
- } catch (error) {
130
- if (!(error instanceof FolderError)) throw error;
131
- return {update, edits: null, stable: false};
132
- }
165
+ return {update, edits: planEdits(session.source.project, update.project), stable: false};
133
166
  };
134
167
  const reloadKind = (): ReloadKind => {
135
168
  const pending = current?.pending;
@@ -168,6 +201,32 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
168
201
  return typeof pending === 'object' && pending !== null ? pending.update.version : null;
169
202
  },
170
203
  get directory() {return current?.source.directory ?? null;},
204
+ /**
205
+ * Reads what to compare before unsaved edits are replaced. `editor` is `null` when the edits cannot be
206
+ * written to the folder, and `disk` when the folder's project file cannot be read.
207
+ */
208
+ async comparison(): Promise<Comparison | null> {
209
+ const session = current;
210
+ if (!session) return null;
211
+ const decoder = new TextDecoder();
212
+ const base = decoder.decode(session.source.files.get(projectFile));
213
+ let editor: string | null;
214
+ try {
215
+ const result = projectChanges(session.source.project, session.baseline, snapshot());
216
+ editor = result ? `${JSON.stringify(result, null, 2)}\n` : base;
217
+ } catch (error) {
218
+ if (!(error instanceof FolderError)) throw error;
219
+ editor = null;
220
+ }
221
+ let disk: string | null;
222
+ try {
223
+ const file = await (await session.source.directory.getFileHandle(projectFile)).getFile();
224
+ disk = decoder.decode(new Uint8Array(await file.arrayBuffer()));
225
+ } catch {
226
+ disk = null;
227
+ }
228
+ return current === session ? {base, editor, disk} : null;
229
+ },
171
230
  refresh(): Promise<void> {
172
231
  if (disposed || busy || !current || !host.blockReload) return Promise.resolve();
173
232
  if (scanning) return scanning;
@@ -193,9 +252,13 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
193
252
  }
194
253
  let targets: readonly ReloadTarget[];
195
254
  try {
196
- targets = applyBlockReload(vm.runtime.targets ?? [], pending.edits);
255
+ const {edits} = pending;
256
+ targets = edits.kind === 'values' ? applyBlockReload(vm.runtime.targets ?? [], edits.changes) :
257
+ applyScriptReload((vm.runtime.targets ?? []) as readonly ScriptReloadTarget[], edits.changes,
258
+ host.blockReload.deserializeBlocks!);
197
259
  } catch (error) {
198
- if (error instanceof FolderError) session.pending = {...pending, edits: null};
260
+ // After a refused or failed in-place change, offer the whole reload instead of retrying it.
261
+ session.pending = {...pending, edits: null};
199
262
  throw error;
200
263
  }
201
264
  session.baseline = snapshot();
package/vite.config.ts CHANGED
@@ -4,6 +4,7 @@ export default defineConfig({
4
4
  build: {
5
5
  // The pinned Scratch GUI still parses the library with Webpack 4.
6
6
  target: 'es2017',
7
+ license: {fileName: 'THIRD_PARTY_NOTICES.md'},
7
8
  lib: {entry: 'src/index.ts', formats: ['es'], fileName: () => 'index.js'}
8
9
  }
9
10
  });