@kubohiroya/turbowarp-plus-editor-project-folder 0.3.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
@@ -20,7 +20,7 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
20
20
  | --- | --- |
21
21
  | 未保存編集なし・実行停止中 | 2 回の確認でファイルが変わらなければ、既存のスプライトとステージのスクリプトの変更をその場で反映します。値と座標の変更はすべてのブロックを保ちます。ブロックの追加・削除・接続の変更は、ホストが `blockReload.deserializeBlocks` を渡す場合に、該当するスクリプトだけを置き換えます。 |
22
22
  | 作品の実行中 | 反映を保留します。値と座標の変更は停止後に反映します。 |
23
- | 未保存編集あり | 編集を保持します。**編集を破棄して再読み込み…** は確認してからフォルダの内容に置き換えます。 |
23
+ | 未保存編集あり | 編集を保持します。ホストが `blockReload.compareChanges` を渡す場合は、**比較して選ぶ…** で未保存の編集とフォルダでの変更を並べて示し、**編集を破棄してフォルダから読み込む** を選んだときだけ置き換えます。渡さない場合は、**編集を破棄して再読み込み…** で確認してから置き換えます。 |
24
24
  | その他の変更(ターゲット・変数・コメントの変更、作品に無い変数や拡張機能を使うブロック、アセット・マニフェスト・拡張機能の変更) | **作品全体を再読み込み** で、開くときと同じ検証を経てフォルダを読み直します。自動では行いません。 |
25
25
  | JSON の途中など書き込み途中 | 更新待ちを表示し、間を置かずに再確認します。 |
26
26
 
package/README.md CHANGED
@@ -20,7 +20,7 @@ When the host passes `host.blockReload`, the package checks the open folder ever
20
20
  | --- | --- |
21
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. |
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
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
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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
4
  export type { DeserializeBlocks } from './script-reload.js';
5
5
  type MenuElement = (component: any, props: any, ...children: any[]) => any;
package/dist/index.js CHANGED
@@ -212,7 +212,7 @@ async function A(e, t) {
212
212
  };
213
213
  }
214
214
  var j = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
215
- async function ee(e, t) {
215
+ async function M(e, t) {
216
216
  let { directory: n, versions: r } = e;
217
217
  try {
218
218
  let [i, a, o] = await Promise.all([
@@ -234,7 +234,7 @@ async function ee(e, t) {
234
234
  return e instanceof _ ? "structure" : "waiting";
235
235
  }
236
236
  }
237
- async function M(e) {
237
+ async function N(e) {
238
238
  try {
239
239
  let t = await e.directory.getDirectoryHandle("assets"), n = await e.directory.getDirectoryHandle("extensions");
240
240
  if (!O(await D(t), e.bytes.keys()) || (await D(n)).size) throw new _("conflict");
@@ -244,32 +244,32 @@ async function M(e) {
244
244
  throw e instanceof _ || e instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(e.name) ? new _("conflict") : e;
245
245
  }
246
246
  }
247
- var N = (e, t) => {
247
+ var P = (e, t) => {
248
248
  if (e === t) return !0;
249
- if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => N(e, t[n]));
249
+ if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => P(e, t[n]));
250
250
  if (!y(e) || !y(t)) return !1;
251
251
  let n = Object.keys(e);
252
- return n.length === Object.keys(t).length && n.every((n) => Object.hasOwn(t, n) && N(e[n], t[n]));
253
- }, P = (e, t, n) => {
254
- if (N(t, n)) return e === void 0 ? n : e;
252
+ return n.length === Object.keys(t).length && n.every((n) => Object.hasOwn(t, n) && P(e[n], t[n]));
253
+ }, F = (e, t, n) => {
254
+ if (P(t, n)) return e === void 0 ? n : e;
255
255
  if (!y(t) || !y(n)) return n;
256
256
  let r = Object.assign(Object.create(null), y(e) ? e : {});
257
- for (let e of Object.keys(t)) Object.hasOwn(n, e) ? N(t[e], n[e]) || (r[e] = P(Object.hasOwn(r, e) ? r[e] : void 0, t[e], n[e])) : delete r[e];
257
+ for (let e of Object.keys(t)) Object.hasOwn(n, e) ? P(t[e], n[e]) || (r[e] = F(Object.hasOwn(r, e) ? r[e] : void 0, t[e], n[e])) : delete r[e];
258
258
  for (let e of Object.keys(n)) Object.hasOwn(t, e) || (r[e] = n[e]);
259
259
  return r;
260
260
  };
261
- function te(e, t, n) {
261
+ function I(e, t, n) {
262
262
  let { targets: i } = t, a = r(t, u), { targets: o } = n;
263
- if (!N(a, r(n, d)) || !N(i.map(x), o.map(x))) return v("This prototype saves block edits on existing targets only");
263
+ if (!P(a, r(n, d)) || !P(i.map(x), o.map(x))) return v("This prototype saves block edits on existing targets only");
264
264
  let s = /* @__PURE__ */ new Map(), c = new Map(e.targets.map((e) => [x(e), e]));
265
265
  for (let [e, t] of o.entries()) {
266
266
  let { blocks: n, comments: a } = t, o = r(t, f), l = i[e], { blocks: u, comments: d } = l;
267
- if (!N(o, r(l, p))) return v("This prototype saves block edits on existing targets only");
267
+ if (!P(o, r(l, p))) return v("This prototype saves block edits on existing targets only");
268
268
  let m = x(t), h = c.get(m);
269
269
  if (!h) return v("The original target could not be identified");
270
- if (!N(u, n) || !N(d, a)) {
270
+ if (!P(u, n) || !P(d, a)) {
271
271
  let e = {};
272
- N(u, n) || (e.blocks = P(h.blocks, u, n)), N(d, a) || (e.comments = P(h.comments, d, a)), s.set(m, e);
272
+ P(u, n) || (e.blocks = F(h.blocks, u, n)), P(d, a) || (e.comments = F(h.comments, d, a)), s.set(m, e);
273
273
  }
274
274
  }
275
275
  return s.size ? l(l({}, e), {}, { targets: e.targets.map((e) => {
@@ -278,17 +278,17 @@ function te(e, t, n) {
278
278
  }) }) : null;
279
279
  }
280
280
  // src/block-reload.ts
281
- var ne = ["targets"], re = ["targets"], F = ["blocks"], ie = ["blocks"], ae = [
281
+ var ee = ["targets"], te = ["targets"], ne = ["blocks"], L = ["blocks"], R = [
282
282
  "inputs",
283
283
  "fields",
284
284
  "x",
285
285
  "y"
286
- ], oe = [
286
+ ], z = [
287
287
  "inputs",
288
288
  "fields",
289
289
  "x",
290
290
  "y"
291
- ], I = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), L = {
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 ne = ["targets"], re = ["targets"], F = ["blocks"], ie = ["blocks"], ae = [
296
296
  8: ["math_angle", "NUM"],
297
297
  9: ["colour_picker", "COLOUR"],
298
298
  10: ["text", "TEXT"]
299
- }, R = () => v("Only values and coordinates of existing blocks can be reloaded"), z = (e, t) => N(Object.keys(e), Object.keys(t)), B = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? R() : {
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 V(e, t) {
304
- let { targets: n } = e, i = r(e, ne), { targets: a } = t, o = r(t, re);
305
- if (n.length !== a.length || !N(i, o)) return R();
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, F), o = a[e], { blocks: c } = o;
309
- if (!N(i, r(o, ie))) return R();
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
- if (N(n, c)) continue;
312
- return R();
311
+ if (P(n, c)) continue;
312
+ return H();
313
313
  }
314
- if (!z(n, c)) return R();
314
+ if (!U(n, c)) return H();
315
315
  for (let [e, i] of Object.entries(n)) {
316
316
  let n = c[e];
317
- if (N(i, n)) continue;
318
- if (!y(i) || !y(n)) return R();
319
- let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, ae), { inputs: p, fields: m, x: h, y: g } = n;
320
- if (!N(f, r(n, oe)) || typeof f.opcode != "string") return R();
317
+ if (P(i, n)) continue;
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,23 +325,23 @@ function V(e, t) {
325
325
  opcode: f.opcode
326
326
  };
327
327
  if (u !== h || d !== g) {
328
- if (f.topLevel !== !0) return R();
328
+ if (f.topLevel !== !0) return H();
329
329
  s.push(l(l({}, _), {}, {
330
330
  kind: "position",
331
- before: B(u, d),
332
- after: B(h, g)
331
+ before: W(u, d),
332
+ after: W(h, g)
333
333
  }));
334
334
  }
335
- if (!N(o, m)) {
336
- if (!y(o) || !y(m) || !z(o, m)) return R();
335
+ if (!P(o, m)) {
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
- if (!N(t, n)) {
339
+ if (!P(t, n)) {
340
340
  if ([
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 || !I(t[0]) || !I(n[0])) return R();
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,
@@ -351,16 +351,16 @@ function V(e, t) {
351
351
  }
352
352
  }
353
353
  }
354
- if (!N(a, p)) {
355
- if (!y(a) || !y(p) || !z(a, p)) return R();
354
+ if (!P(a, p)) {
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
- if (N(t, n)) continue;
359
- if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return R();
358
+ if (P(t, n)) continue;
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 R();
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(L, i[0]) || i[0] !== a[0] || !I(i[1]) || !I(a[1])) return R();
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 V(e, t) {
376
376
  }
377
377
  return s;
378
378
  }
379
- function H(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 R();
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 R();
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 ? R() : (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 H(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 R();
397
- let r = a.getBlock(n), [i, s] = L[t.tag];
398
- if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return R();
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 ? R() : (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,
@@ -415,7 +415,7 @@ function H(e, t) {
415
415
  return [...n];
416
416
  }
417
417
  // src/script-reload.ts
418
- var U = ["targets"], W = ["targets"], G = ["blocks"], K = ["blocks"], q = (e = "Only changes to the scripts of existing targets can be reloaded in place") => v(e), se = /* @__PURE__ */ new Set([
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
419
  "motion",
420
420
  "looks",
421
421
  "sound",
@@ -429,45 +429,45 @@ var U = ["targets"], W = ["targets"], G = ["blocks"], K = ["blocks"], q = (e = "
429
429
  "math",
430
430
  "text",
431
431
  "colour"
432
- ]), J = (e) => e.split("_", 1)[0], ce = /* @__PURE__ */ new Set([
432
+ ]), Y = (e) => e.split("_", 1)[0], se = /* @__PURE__ */ new Set([
433
433
  "VARIABLE",
434
434
  "LIST",
435
435
  "BROADCAST_OPTION"
436
- ]), le = (e) => y(e) && typeof e.parent == "string" ? e.parent : null;
437
- function Y(e) {
436
+ ]), ce = (e) => y(e) && typeof e.parent == "string" ? e.parent : null;
437
+ function X(e) {
438
438
  let t = /* @__PURE__ */ new Map();
439
439
  for (let n of Object.keys(e)) {
440
440
  let r = n, i = /* @__PURE__ */ new Set();
441
441
  for (;;) {
442
- if (i.has(r)) return q("Blocks form a cycle");
442
+ if (i.has(r)) return J("Blocks form a cycle");
443
443
  i.add(r);
444
- let t = le(e[r]);
444
+ let t = ce(e[r]);
445
445
  if (t === null) break;
446
- if (!Object.hasOwn(e, t)) return q("A block refers to a missing parent");
446
+ if (!Object.hasOwn(e, t)) return J("A block refers to a missing parent");
447
447
  r = t;
448
448
  }
449
449
  t.set(n, r);
450
450
  }
451
451
  return t;
452
452
  }
453
- function ue(e, t) {
454
- for (let n of Object.values(e)) y(n) && typeof n.opcode == "string" && t.add(J(n.opcode));
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
455
  }
456
- function de(e, t) {
457
- let { targets: n } = e, i = r(e, U), { targets: a } = t, o = r(t, W);
458
- if (n.length !== a.length || !N(i, o)) return q();
459
- let s = new Set(se);
460
- for (let e of n) y(e.blocks) && ue(e.blocks, s);
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
461
  let c = [];
462
462
  for (let [e, t] of n.entries()) {
463
- let { blocks: n } = t, i = r(t, G), o = a[e], { blocks: l } = o;
464
- if (!N(i, r(o, K))) return q();
465
- if (N(n, l)) continue;
466
- let u = y(n) ? n : {}, d = y(l) ? l : {}, f = Y(u), p = Y(d), m = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Set(), g = (e) => {
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
467
  let t = f.get(e), n = p.get(e), r = !1;
468
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
469
  };
470
- for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) N(u[e], d[e]) || g(e);
470
+ for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) P(u[e], d[e]) || g(e);
471
471
  for (let e = !0; e;) {
472
472
  e = !1;
473
473
  for (let [t, n] of f) m.has(n) && g(t) && (e = !0);
@@ -476,8 +476,8 @@ function de(e, t) {
476
476
  let _ = {};
477
477
  for (let [e, t] of p) h.has(t) && (_[e] = d[e]);
478
478
  for (let e of Object.values(_)) if (y(e)) {
479
- if (typeof e.opcode != "string") return q("A block has no opcode");
480
- if (!s.has(J(e.opcode))) return q(`Blocks need an extension the project does not use: ${e.opcode}`);
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
481
  }
482
482
  c.push({
483
483
  target: t.name,
@@ -488,25 +488,25 @@ function de(e, t) {
488
488
  }
489
489
  return c;
490
490
  }
491
- var fe = (e, t) => {
491
+ var de = (e, t) => {
492
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] : q();
493
+ return n.length === 1 ? n[0] : J();
494
494
  };
495
- function pe(e, t, n) {
495
+ function fe(e, t, n) {
496
496
  let r = t.map((t) => {
497
- let r = fe(e, t), i = r.blocks;
497
+ let r = de(e, t), i = r.blocks;
498
498
  for (let e of t.remove) {
499
499
  let t = i.getBlock(e);
500
- if (!t || !t.topLevel || !i._scripts.includes(e)) return q("The editor and the folder differ");
500
+ if (!t || !t.topLevel || !i._scripts.includes(e)) return J("The editor and the folder differ");
501
501
  }
502
502
  let a = Object.values(n(JSON.parse(JSON.stringify(t.blocks))));
503
503
  for (let e of a) {
504
504
  var o;
505
- if (typeof e.id != "string" || typeof e.opcode != "string") return q("A block could not be read");
506
- if (e.comment && !(r.comments && Object.hasOwn(r.comments, e.comment))) return q("A block refers to a missing comment");
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
507
  for (let [t, n] of Object.entries((o = e.fields) == null ? {} : o)) {
508
508
  var s;
509
- if ((ce.has(t) || n.variableType) && (typeof n.id != "string" || !((s = r.lookupVariableById) != null && s.call(r, n.id)))) return q("A block refers to a variable, list or message the project does not have");
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
510
  }
511
511
  }
512
512
  return {
@@ -524,7 +524,7 @@ function pe(e, t, n) {
524
524
  try {
525
525
  for (let { container: e, edit: t, created: n } of r) {
526
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 && q("A block id is already in use");
527
+ for (let t of n) e.createBlock(t, !0), e._blocks[t.id] !== t && J("A block id is already in use");
528
528
  e.resetCache();
529
529
  }
530
530
  } catch (e) {
@@ -538,17 +538,17 @@ function pe(e, t, n) {
538
538
  return r.map(({ target: e }) => e);
539
539
  }
540
540
  // src/session.ts
541
- var X = /* @__PURE__ */ new WeakMap(), me = (e) => {
542
- let t = X.get(e);
541
+ var Z = /* @__PURE__ */ new WeakMap(), pe = (e) => {
542
+ let t = Z.get(e);
543
543
  if (t) return t;
544
544
  let n = { assets: null };
545
545
  return e.addHelper({ load(e, t, r) {
546
546
  var i;
547
547
  let a = (i = n.assets) == null ? void 0 : i.get(k(e, t, r));
548
548
  return a ? Promise.resolve(a) : null;
549
- } }, 101), X.set(e, n), n;
549
+ } }, 101), Z.set(e, n), n;
550
550
  };
551
- function he(e, t) {
551
+ function me(e, t) {
552
552
  let n = null, r = !1, i = !1, a = 0, o = null, s = () => S(e.toJSON(void 0, { allowOptimization: !1 })), c = () => {
553
553
  a++;
554
554
  }, u = () => {
@@ -570,7 +570,7 @@ function he(e, t) {
570
570
  let u = e.runtime.storage, d = await A(r, u);
571
571
  if (i || e.runtime.getTargetForStage() !== c || t.isProjectDirty() && !o()) return "cancelled";
572
572
  t.beforeLoad(), n = null;
573
- let f = me(u), p = d.storageAssets;
573
+ let f = pe(u), p = d.storageAssets;
574
574
  f.assets = p;
575
575
  let m;
576
576
  try {
@@ -592,7 +592,7 @@ function he(e, t) {
592
592
  try {
593
593
  return {
594
594
  kind: "values",
595
- changes: V(e, n)
595
+ changes: G(e, n)
596
596
  };
597
597
  } catch (e) {
598
598
  if (!(e instanceof _)) throw e;
@@ -601,7 +601,7 @@ function he(e, t) {
601
601
  try {
602
602
  return {
603
603
  kind: "scripts",
604
- changes: de(e, n)
604
+ changes: ue(e, n)
605
605
  };
606
606
  } catch (e) {
607
607
  if (!(e instanceof _)) throw e;
@@ -609,7 +609,7 @@ function he(e, t) {
609
609
  }
610
610
  }, g = async (e) => {
611
611
  var t;
612
- let n = typeof e.pending == "object" ? e.pending : null, r = await ee(e.source, (t = n == null ? void 0 : n.update) == null ? null : 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
613
  return !r || typeof r == "string" ? r : (n == null ? void 0 : n.update) === r ? l(l({}, n), {}, { stable: !0 }) : {
614
614
  update: r,
615
615
  edits: h(e.source.project, r.project),
@@ -658,6 +658,30 @@ function he(e, t) {
658
658
  var e;
659
659
  return (e = n == null ? void 0 : n.source.directory) == null ? null : e;
660
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
+ },
661
685
  refresh() {
662
686
  if (i || r || !n || !t.blockReload) return Promise.resolve();
663
687
  if (o) return o;
@@ -679,7 +703,7 @@ function he(e, t) {
679
703
  try {
680
704
  var c, u;
681
705
  let { edits: n } = d;
682
- f = n.kind === "values" ? H((c = e.runtime.targets) == null ? [] : c, n.changes) : pe((u = e.runtime.targets) == null ? [] : u, n.changes, t.blockReload.deserializeBlocks);
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);
683
707
  } catch (e) {
684
708
  throw o.pending = l(l({}, d), {}, { edits: null }), e;
685
709
  }
@@ -714,11 +738,11 @@ function he(e, t) {
714
738
  let e = n;
715
739
  d(e), r = !0;
716
740
  try {
717
- let r = a, i = s(), o = te(e.source.project, e.baseline, i);
718
- if (await M(e.source), d(e), !o) return a === r && t.onSaved(), "unchanged";
741
+ let r = a, i = s(), o = I(e.source.project, e.baseline, i);
742
+ if (await N(e.source), d(e), !o) return a === r && t.onSaved(), "unchanged";
719
743
  let c = `${JSON.stringify(o, null, 2)}\n`, l = await (await e.source.directory.getFileHandle(m)).createWritable({ mode: "exclusive" });
720
744
  try {
721
- await l.write(c), await M(e.source), d(e), await l.close();
745
+ await l.write(c), await N(e.source), d(e), await l.close();
722
746
  } catch (e) {
723
747
  throw await l.abort().catch(() => {}), e;
724
748
  }
@@ -731,7 +755,7 @@ function he(e, t) {
731
755
  };
732
756
  }
733
757
  // src/index.ts
734
- var Z = {
758
+ var Q = {
735
759
  en: {
736
760
  open: "Open Project Folder…",
737
761
  save: "Save to Project Folder",
@@ -748,6 +772,15 @@ var Z = {
748
772
  reloadAll: "Reload Whole Project",
749
773
  discard: "Discard Edits and Reload…",
750
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",
751
784
  dirty: "You have unsaved edits.",
752
785
  running: "Stop the project before reloading.",
753
786
  runningAuto: "The changes load when the project stops.",
@@ -771,6 +804,15 @@ var Z = {
771
804
  reloadAll: "作品全体を再読み込み",
772
805
  discard: "編集を破棄して再読み込み…",
773
806
  discardConfirm: "未保存の編集を破棄して、フォルダの作品を読み込みますか?",
807
+ compare: "比較して選ぶ…",
808
+ compareTitle: "外部の変更と未保存の編集",
809
+ compareDescription: "Editor に未保存の編集がある間に、プロジェクトフォルダが変更されました。フォルダから読み込むと、未保存の編集は失われます。",
810
+ compareUnsaved: "未保存の編集の一部はプロジェクトフォルダに保存できない種類のため、ここには表示していません。",
811
+ yourEdits: "あなたの未保存の編集",
812
+ diskChanges: "フォルダでの変更",
813
+ keep: "編集を残す",
814
+ discardLoad: "編集を破棄してフォルダから読み込む",
815
+ close: "閉じる",
774
816
  dirty: "未保存の編集があります。",
775
817
  running: "作品を停止してから再読み込みできます。",
776
818
  runningAuto: "作品の停止後に反映します。",
@@ -778,12 +820,12 @@ var Z = {
778
820
  waiting: "外部の書き込みが終わるのを待っています。",
779
821
  full: "この変更は作品全体の再読み込みが必要です。"
780
822
  }
781
- }, Q = /* @__PURE__ */ new WeakMap();
782
- function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
823
+ }, $ = /* @__PURE__ */ new WeakMap();
824
+ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
783
825
  var a;
784
826
  let o = t.defaultView, s = o == null ? void 0 : o.showDirectoryPicker;
785
827
  if (!s || !((a = e.runtime) != null && a.storage)) return null;
786
- let c = he(e, n), l = t.createElement("output");
828
+ let c = me(e, n), l = t.createElement("output");
787
829
  l.dataset.projectFolderStatus = "", l.setAttribute("role", "status"), l.hidden = !0, Object.assign(l.style, {
788
830
  position: "fixed",
789
831
  insetInlineEnd: "1rem",
@@ -800,11 +842,12 @@ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
800
842
  l.isConnected && (l.hidden = !1, l.textContent = e, o.clearTimeout(u), u = o.setTimeout(() => {
801
843
  l.hidden = !0;
802
844
  }, 7500));
803
- }, f = (e) => e.startsWith("ja") ? Z.ja : Z.en, p = (e, t) => {
845
+ }, f = (e) => e.startsWith("ja") ? Q.ja : Q.en, p = (e, t) => {
804
846
  let n = f(e), r = t instanceof _ && t.message !== t.code ? ` (${t.message})` : "";
805
847
  d((t instanceof _ ? n[t.code] : n.failed) + r);
806
848
  }, m, h = () => {};
807
849
  if (n.blockReload) {
850
+ var g;
808
851
  let e = f(r), a = t.createElement("aside");
809
852
  a.dataset.projectFolderExternal = "", a.hidden = !0, Object.assign(a.style, {
810
853
  position: "fixed",
@@ -822,7 +865,42 @@ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
822
865
  s.setAttribute("role", "status");
823
866
  let l = t.createElement("button");
824
867
  l.type = "button", l.textContent = e.reload, a.append(s, l), t.body.append(a);
825
- 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) => {
826
904
  let n = t();
827
905
  h(), n.then((t) => {
828
906
  (t === !0 || t === "opened") && d(e.reloaded);
@@ -830,8 +908,8 @@ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
830
908
  };
831
909
  h = () => {
832
910
  let t = c.reloadState, n = c.reloadKind;
833
- if (i && c.canAutoReload && c.pendingVersion !== g) {
834
- g = c.pendingVersion, y(() => c.reload());
911
+ if (i && c.canAutoReload && c.pendingVersion !== b) {
912
+ b = c.pendingVersion, C(() => c.reload());
835
913
  return;
836
914
  }
837
915
  a.hidden = !t, l.hidden = !n, l.disabled = ![
@@ -839,35 +917,35 @@ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
839
917
  "full",
840
918
  "dirty"
841
919
  ].includes(t == null ? "" : t);
842
- 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;
843
921
  l.textContent !== r && (l.textContent = r);
844
- let o = !t || t === "ready" ? "" : t === "running" && n === "partial" && i ? e.runningAuto : e[t], u = o ? `${e.external} ${o}` : e.external;
845
- s.textContent !== u && (s.textContent = u);
846
- let d = c.directory;
847
- 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(() => {}));
848
926
  };
849
- let b = () => {
927
+ let w = () => {
850
928
  t.visibilityState === "visible" && c.refresh().then(() => {
851
- h(), c.settling && x(500);
929
+ h(), c.settling && T(500);
852
930
  }, (e) => p(r, e));
853
- }, x = (e) => {
854
- o.clearTimeout(u), u = o.setTimeout(b, e);
931
+ }, T = (e) => {
932
+ o.clearTimeout(y), y = o.setTimeout(w, e);
855
933
  };
856
934
  if (o.FileSystemObserver) try {
857
- v = new o.FileSystemObserver(() => x(300));
935
+ S = new o.FileSystemObserver(() => T(300));
858
936
  } catch (e) {
859
- v = null;
937
+ S = null;
860
938
  }
861
939
  l.addEventListener("click", () => {
862
940
  let t = c.reloadState;
863
- 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)));
864
942
  });
865
- let S = n.blockReload.subscribe(h), C = o.setInterval(b, 2e3);
866
- o.addEventListener("focus", b), t.addEventListener("visibilitychange", b), m = () => {
867
- 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();
868
946
  };
869
947
  }
870
- return Q.set(e, {
948
+ return $.set(e, {
871
949
  session: c,
872
950
  open(e) {
873
951
  let t = f(e);
@@ -881,12 +959,12 @@ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
881
959
  }), {
882
960
  openDirectory: (...e) => c.openDirectory(...e).finally(h),
883
961
  dispose() {
884
- Q.delete(e), c.dispose(), m == null || m(), o.clearTimeout(u), l.remove();
962
+ $.delete(e), c.dispose(), m == null || m(), o.clearTimeout(u), l.remove();
885
963
  }
886
964
  };
887
965
  }
888
- function $(e, t = "en") {
889
- let n = Q.get(e);
966
+ function ge(e, t = "en") {
967
+ let n = $.get(e);
890
968
  if (n) return {
891
969
  open: () => n.open(t),
892
970
  save: n.session.canSave ? () => n.save(t) : void 0,
@@ -894,9 +972,9 @@ function $(e, t = "en") {
894
972
  };
895
973
  }
896
974
  function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
897
- let o = Q.get(t);
975
+ let o = $.get(t);
898
976
  if (!o) return null;
899
- let s = n.startsWith("ja") ? Z.ja : Z.en, c = (t) => {
977
+ let s = n.startsWith("ja") ? Q.ja : Q.en, c = (t) => {
900
978
  let i = () => {
901
979
  a(), o[t](n);
902
980
  };
@@ -913,4 +991,4 @@ function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequest
913
991
  };
914
992
  return e(i, null, c("open"), o.session.canSave ? c("save") : null);
915
993
  }
916
- export { ge as mountProjectFolder, $ as projectFolderActions, _e as renderProjectFolderMenu };
994
+ export { he as mountProjectFolder, ge as projectFolderActions, _e as renderProjectFolderMenu };
package/dist/session.d.ts CHANGED
@@ -41,8 +41,36 @@ export interface FolderHost {
41
41
  * changed scripts in place; without it they need the whole project reloaded.
42
42
  */
43
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>;
44
49
  };
45
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
+ };
46
74
  /**
47
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.
48
76
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
@@ -65,6 +93,11 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
65
93
  /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
66
94
  readonly pendingVersion: string | null;
67
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>;
68
101
  refresh(): Promise<void>;
69
102
  reload(): Promise<boolean>;
70
103
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.3.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",
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@ 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
7
  export type {DeserializeBlocks} from './script-reload.js';
8
8
 
@@ -17,6 +17,11 @@ const messages = {
17
17
  external: 'External changes detected.', reload: 'Reload from Disk', reloaded: 'Changes loaded from disk.',
18
18
  reloadAll: 'Reload Whole Project', discard: 'Discard Edits and Reload…',
19
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',
20
25
  dirty: 'You have unsaved edits.', running: 'Stop the project before reloading.',
21
26
  runningAuto: 'The changes load when the project stops.', busy: 'Please wait for the current operation.',
22
27
  waiting: 'Waiting for the external write to finish.',
@@ -32,6 +37,11 @@ const messages = {
32
37
  external: '外部変更あり', reload: 'ディスクから再読み込み', reloaded: 'ディスクの変更を読み込みました。',
33
38
  reloadAll: '作品全体を再読み込み', discard: '編集を破棄して再読み込み…',
34
39
  discardConfirm: '未保存の編集を破棄して、フォルダの作品を読み込みますか?',
40
+ compare: '比較して選ぶ…', compareTitle: '外部の変更と未保存の編集',
41
+ compareDescription: 'Editor に未保存の編集がある間に、プロジェクトフォルダが変更されました。フォルダから読み込むと、未保存の編集は失われます。',
42
+ compareUnsaved: '未保存の編集の一部はプロジェクトフォルダに保存できない種類のため、ここには表示していません。',
43
+ yourEdits: 'あなたの未保存の編集', diskChanges: 'フォルダでの変更',
44
+ keep: '編集を残す', discardLoad: '編集を破棄してフォルダから読み込む', close: '閉じる',
35
45
  dirty: '未保存の編集があります。', running: '作品を停止してから再読み込みできます。',
36
46
  runningAuto: '作品の停止後に反映します。', busy: '処理が終わるまでお待ちください。',
37
47
  waiting: '外部の書き込みが終わるのを待っています。',
@@ -109,6 +119,31 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
109
119
  button.textContent = message.reload;
110
120
  notice.append(text, button);
111
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
+ };
112
147
  let settle: number | undefined;
113
148
  let autoTried: string | null = null;
114
149
  let observed: FileSystemDirectoryHandle | null = null;
@@ -130,7 +165,8 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
130
165
  notice.hidden = !state;
131
166
  button.hidden = !kind;
132
167
  button.disabled = !['ready', 'full', 'dirty'].includes(state ?? '');
133
- 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;
134
170
  if (button.textContent !== action) button.textContent = action;
135
171
  const detail = !state || state === 'ready' ? '' :
136
172
  state === 'running' && kind === 'partial' && autoReload ? message.runningAuto : message[state];
@@ -166,6 +202,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
166
202
  const state = session.reloadState;
167
203
  if (state === 'ready') apply(() => session.reload());
168
204
  else if (state === 'full') apply(() => session.reloadAll(() => true));
205
+ else if (state === 'dirty' && compareChanges) void compare(compareChanges);
169
206
  else if (state === 'dirty') apply(() => session.reloadAll(() => view.confirm(message.discardConfirm)));
170
207
  });
171
208
  const unsubscribe = host.blockReload.subscribe(renderReload);
package/src/session.ts CHANGED
@@ -51,9 +51,23 @@ export interface FolderHost {
51
51
  * changed scripts in place; without it they need the whole project reloaded.
52
52
  */
53
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>;
54
59
  };
55
60
  }
56
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
+
57
71
  // `stable` turns true once two scans see the same file version, so consecutive writes settle before auto-apply.
58
72
  type Edits = {kind: 'values'; changes: ReturnType<typeof planBlockReload>} |
59
73
  {kind: 'scripts'; changes: ReturnType<typeof planScriptReload>};
@@ -187,6 +201,32 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
187
201
  return typeof pending === 'object' && pending !== null ? pending.update.version : null;
188
202
  },
189
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
+ },
190
230
  refresh(): Promise<void> {
191
231
  if (disposed || busy || !current || !host.blockReload) return Promise.resolve();
192
232
  if (scanning) return scanning;