@kubohiroya/turbowarp-plus-editor-code-views 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
@@ -17,7 +17,7 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
17
17
  | `./target-combobox` | コードの窓の対象の選択 |
18
18
  | `./detached-block-palette` | 別窓のブロックパレット |
19
19
  | `./palette-category-reorder`・`./palette-category-search`・`./palette-dropdown-resize` | パレットのカテゴリの並べ替えと検索、パレットのドロップダウンの大きさの変更 |
20
- | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はパレットのコメントに保存し、選ぶ画面を持つ |
20
+ | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ |
21
21
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する |
22
22
  | `./asset-edit-session`・`./dockview-unsaved` | 素材の編集のセッションと、Dockview のタブの未保存の印。ホストが GUI のエディターとレイアウトにつなぐ |
23
23
  | `./styles.css` | 上のすべてのスタイルシート |
@@ -46,7 +46,7 @@ MPL-2.0。turbowarp-plus-editor の `packages/editor-views` と `packages/editor
46
46
 
47
47
  スプライト・背景ごとに、パレットに出すブロックグループ(標準のグループと、機能拡張のグループ)を選べる。TypeScript で言えば、作品の `extensions` が package.json、スプライトごとの設定が各ファイルの import 文にあたる。
48
48
 
49
- - 設定は sb3-toolchain の展開ソース形式 2 と同じ、スプライト・背景ごとのパレットのコメントに入る(作品フォルダでは `block-palette.json`)。既定と同じスプライトにはコメントを置かない。背景のコメントは、作品の「適用可能なセット」も持つ。
49
+ - 設定は作品のコードではなくエディターのもので、タブの配置と同じ画面状態に入る。SB3 では `tw-plus/workspace.json`、作品フォルダでは `.tw-plus/workspace.json` の `blockPalette` のスライスになる。スプライトはタブの配置と同じく名前で、背景は `stage` で記録する。
50
50
  - 設定のないスプライト・背景は、標準のグループと、そのコードが使っている機能拡張のグループを出す。
51
51
  - 非表示にしても、コード領域のブロックはそのまま見えて編集できる。
52
52
 
@@ -54,14 +54,14 @@ MPL-2.0。turbowarp-plus-editor の `packages/editor-views` と `packages/editor
54
54
 
55
55
  | 関数 | 内容 |
56
56
  | --- | --- |
57
- | `visibleGroups(target, extensionIds)` | 対象に出すグループ |
57
+ | `createPaletteVisibilityStore()` | 1つの作品の設定を、実行時の対象の ID ごとに持つ。名前を変えたスプライトも設定を保つ。`visible`・`set`・`copy`(複製)・`sets`・`addSets`、画面状態のスライスへの `capture(targets)` と `apply(value, targets)`、`reset` |
58
+ | `paletteScreenStateKey` | 画面状態のスライスの名前(`blockPalette`) |
58
59
  | `filterToolboxTree(tree, visible)` | パレットを描く前のツールボックスの木から、出さないカテゴリを外す |
59
- | `readTargetPalette(target)`・`writeTargetPalette(target, groups, options)` | パレットのコメントを読み書きする。書く文は sb3-toolchain の `formatBlockPaletteComment` と同じ |
60
- | `usedGroups(target)`・`groupOfOpcode(opcode)` | コードが使っているグループと、その数 |
60
+ | `usedGroups(target)`・`groupOfOpcode(opcode)`・`defaultVisibleGroups(target, extensionIds)` | コードが使っているグループとその数、設定のない対象に出すグループ |
61
61
  | `paletteGroupSets(locale, projectSets)` | 「標準」「表現」「変数・リスト」「基本の制御」と、作品のセット |
62
62
  | `attachPaletteMenuButton(menu, getLocale, getItems)` | カテゴリの一覧の末尾(横配置では右端、縦配置では下端)に ▼ のボタンを置く。押すと、ホストが渡す項目のメニューを出す。項目は「ブロックグループの表示・非表示の設定」(`paletteVisibilityMenuLabel`)と、ホストの機能拡張に関する項目 |
63
63
 
64
64
  `./palette-visibility-dialog` の `openPaletteVisibilityDialog(document, props)` は「パレット内のブロックグループの表示・非表示の設定」の画面を開く。機能拡張の各行は `@kubohiroya/turbowarp-extension-security-dialog/react` の `ExtensionRow` で描くので、拡張の追加の画面と同じ見た目になる。適用すると、出すグループと、この画面で足したセットを `onApply` に渡す。
65
65
 
66
- ホストは `@kubohiroya/sb3-toolchain`(0.25.1 以上)と `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、security-dialog の `styles.css` も読み込む。1つの機能拡張の中を複数のグループに分けて選ぶ機能は、VM がグループごとのカテゴリを作れるようになってから足す。
66
+ ホストは `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、その `styles.css` も読み込む。設定を画面状態のスライスとして登録するのはホストの役目である。1つの機能拡張の中を複数のグループに分けて選ぶ機能は、VM がグループごとのカテゴリを作れるようになってから足す。
67
67
 
package/README.md CHANGED
@@ -16,7 +16,7 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
16
16
  | `./variable-references` | Variable references scoped to the edited target |
17
17
  | `./target-combobox` | The target picker of a code window |
18
18
  | `./detached-block-palette` | The block palette in its own window |
19
- | `./palette-category-visibility`, `./palette-visibility-dialog` | Choose which block groups the palette shows for each sprite and the stage. The setting is kept in a palette comment, with a screen to choose |
19
+ | `./palette-category-visibility`, `./palette-visibility-dialog` | Choose which block groups the palette shows for each sprite and the stage. The setting is saved with the editor's screen state, with a screen to choose |
20
20
  | `./palette-category-reorder`, `./palette-category-search`, `./palette-dropdown-resize` | Reordering and searching palette categories, and resizing palette dropdowns |
21
21
  | `./block-argument-text` | Shortens long text arguments and edits them in a dialog |
22
22
  | `./asset-edit-session`, `./dockview-unsaved` | The asset edit session and the unsaved marks on Dockview tabs, which the host connects to the GUI's editors and layout |
@@ -46,7 +46,7 @@ MPL-2.0. This code moved here from `packages/editor-views` and `packages/editor-
46
46
 
47
47
  Each sprite and the stage can choose which block groups the palette shows: the standard groups and the groups of extensions. In TypeScript terms, the project's `extensions` are package.json and each sprite's setting is a file's import statements.
48
48
 
49
- - The setting is kept where sb3-toolchain source format 2 keeps it: one palette comment per sprite or stage (`block-palette.json` in a project folder). A sprite whose setting equals its default gets no comment. The stage's comment also holds the project's applicable sets.
49
+ - The setting belongs to the editor, not to the project's code, and is saved with the same screen state as the tab layout: the `blockPalette` slice of `tw-plus/workspace.json` in an SB3, or `.tw-plus/workspace.json` in a project folder. Sprites are recorded by name, as the tab layout records them, and the stage as `stage`.
50
50
  - A sprite or stage without a setting shows the standard groups and the groups of the extensions its code uses.
51
51
  - Hiding a group never hides blocks already in the code; they stay visible and editable.
52
52
 
@@ -54,14 +54,14 @@ Each sprite and the stage can choose which block groups the palette shows: the s
54
54
 
55
55
  | Function | What it does |
56
56
  | --- | --- |
57
- | `visibleGroups(target, extensionIds)` | The groups shown for a target |
57
+ | `createPaletteVisibilityStore()` | One project's settings, by runtime target ID, so a renamed sprite keeps its setting: `visible`, `set`, `copy` (for a duplicate), `sets`, `addSets`, `capture(targets)` and `apply(value, targets)` for the screen-state slice, and `reset` |
58
+ | `paletteScreenStateKey` | The name of the screen-state slice (`blockPalette`) |
58
59
  | `filterToolboxTree(tree, visible)` | Removes the categories a target does not show from the parsed toolbox before the palette is drawn |
59
- | `readTargetPalette(target)`, `writeTargetPalette(target, groups, options)` | Read and write the palette comment, in the text sb3-toolchain's `formatBlockPaletteComment` writes |
60
- | `usedGroups(target)`, `groupOfOpcode(opcode)` | The groups the code uses, and how many blocks of each |
60
+ | `usedGroups(target)`, `groupOfOpcode(opcode)`, `defaultVisibleGroups(target, extensionIds)` | The groups the code uses and how many blocks of each, and the groups shown for a target without a setting |
61
61
  | `paletteGroupSets(locale, projectSets)` | Standard, Expression, Variables and lists, Basic control, and the project's own sets |
62
62
  | `attachPaletteMenuButton(menu, getLocale, getItems)` | Puts a ▼ button at the end of the category menu (the right end of a horizontal palette, the bottom of a vertical one). Pressing it lists the items the host gives: the group settings (`paletteVisibilityMenuLabel`) and the host's extension items |
63
63
 
64
64
  `openPaletteVisibilityDialog(document, props)` from `./palette-visibility-dialog` opens the screen that chooses the groups. Each extension is drawn with `ExtensionRow` from `@kubohiroya/turbowarp-extension-security-dialog/react`, so it looks the same as in the screen that adds extensions. Applying passes the groups to show, and the sets added in the screen, to `onApply`.
65
65
 
66
- The host installs `@kubohiroya/sb3-toolchain` (0.25.1 or later) and `@kubohiroya/turbowarp-extension-security-dialog` (0.9.0 or later), and loads security-dialog's `styles.css`. Choosing groups inside one extension comes once the VM can make a category per group.
66
+ The host installs `@kubohiroya/turbowarp-extension-security-dialog` (0.9.0 or later) and loads its `styles.css`, and registers the store as a screen-state slice. Choosing groups inside one extension comes once the VM can make a category per group.
67
67
 
@@ -1,72 +1,80 @@
1
- import type { BlockPaletteSet } from '@kubohiroya/sb3-toolchain/browser';
2
1
  /**
3
2
  * Which block groups the palette shows for each sprite and the stage.
4
3
  *
5
- * The setting lives where sb3-toolchain source format 2 keeps it: one palette comment per sprite or
6
- * stage (`block-palette.json` in a project folder). It changes only what the palette offers; blocks
4
+ * The settings belong to the editor, not to the project's code: they are kept in memory per target and saved with
5
+ * the editor's own screen state (a slice of `tw-plus/workspace.json` in an SB3, `.tw-plus/workspace.json` in a
6
+ * project folder), the same way the tab layout is. Hiding a group changes only what the palette offers; blocks
7
7
  * already in the code stay visible and editable.
8
8
  */
9
9
  /** The standard groups, by the palette's category IDs. `lists` is Plus's own split of `variables`. */
10
10
  export declare const standardGroups: readonly ["motion", "looks", "sound", "events", "control", "sensing", "operators", "variables", "lists", "myBlocks"];
11
+ /** A named set of groups the project keeps. */
12
+ export interface SavedGroupSet {
13
+ name: string;
14
+ groups: string[];
15
+ }
11
16
  export interface PaletteGroupSet {
12
17
  id: string;
13
18
  name: string;
14
19
  groups: readonly string[];
15
20
  }
16
- /** The sets every project has, then the project's own sets from its stage palette comment. */
17
- export declare function paletteGroupSets(locale?: string, projectSets?: Record<string, BlockPaletteSet>): PaletteGroupSet[];
21
+ /** The sets every project has, then the project's own sets. */
22
+ export declare function paletteGroupSets(locale?: string, projectSets?: Record<string, SavedGroupSet>): PaletteGroupSet[];
18
23
  /** The group a block belongs to, or null for a block no palette group offers. */
19
24
  export declare function groupOfOpcode(opcode: string): string | null;
20
25
  type BlockLike = {
21
26
  opcode?: string;
22
27
  shadow?: boolean;
23
28
  };
24
- type CommentLike = {
25
- text?: string;
26
- id?: string;
27
- };
28
- /** The parts of a VM target this module reads and writes. */
29
+ /** The parts of a VM target this module reads. */
29
30
  export interface PaletteTarget {
31
+ id: string;
30
32
  isStage: boolean;
31
33
  getName(): string;
32
34
  blocks?: {
33
35
  _blocks?: Record<string, BlockLike>;
34
36
  };
35
- comments: Record<string, CommentLike>;
36
- createComment?(id: string, blockId: string | null, text: string, x: number, y: number, width: number, height: number, minimized: boolean): void;
37
- deleteComment?(id: string): void;
38
37
  }
39
38
  /** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
40
39
  export declare function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, number>;
41
- export interface TargetPalette {
42
- /** The comment that holds the setting. */
43
- commentId: string;
44
- groups?: string[];
45
- /** Present on the stage's comment only. */
46
- order?: string[];
47
- sets?: Record<string, BlockPaletteSet>;
48
- }
49
- /** The palette setting a target carries in its palette comment, or null when it has none or it cannot be read. */
50
- export declare function readTargetPalette(target: Pick<PaletteTarget, 'comments'>): TargetPalette | null;
51
40
  /**
52
41
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
53
- * the extensions its code already uses, so an existing project opens with nothing missing.
42
+ * the extensions its code already uses, so a project opens with nothing missing.
54
43
  */
55
44
  export declare function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[];
56
- /** The groups the palette shows for the target. */
57
- export declare function visibleGroups(target: Pick<PaletteTarget, 'blocks' | 'comments'>, extensionIds: readonly string[]): Set<string>;
58
45
  /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
59
46
  export declare function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void;
60
- /**
61
- * Stores the target's palette setting in its palette comment, as sb3-toolchain source format 2 reads it.
62
- * A sprite whose groups equal its default gets no comment; the stage keeps one while it carries the
63
- * project's group order or sets.
64
- */
65
- export declare function writeTargetPalette(target: PaletteTarget, groups: readonly string[], { extensionIds, order, sets }?: {
66
- extensionIds?: readonly string[];
67
- order?: readonly string[];
68
- sets?: Record<string, BlockPaletteSet>;
69
- }): void;
47
+ /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
48
+ export declare const paletteScreenStateKey = "blockPalette";
49
+ export interface SavedPaletteVisibility {
50
+ version: 1;
51
+ stage?: {
52
+ groups: string[];
53
+ };
54
+ sprites?: Record<string, {
55
+ groups: string[];
56
+ }>;
57
+ sets?: Record<string, SavedGroupSet>;
58
+ }
59
+ export interface PaletteVisibilityStore {
60
+ /** The groups the palette shows for the target. */
61
+ visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
62
+ /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
63
+ set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
64
+ /** A new sprite made from another, such as a duplicate, starts with its setting. */
65
+ copy(from: Pick<PaletteTarget, 'id'>, to: Pick<PaletteTarget, 'id'>): void;
66
+ /** The project's own sets. */
67
+ sets(): Record<string, SavedGroupSet>;
68
+ addSets(sets: readonly PaletteGroupSet[]): void;
69
+ /** The slice to save, or nothing when no target has a setting and the project has no sets. */
70
+ capture(targets: readonly PaletteTarget[]): SavedPaletteVisibility | undefined;
71
+ /** Takes the settings of a loaded project. A value that is not a saved slice leaves every target at its default. */
72
+ apply(value: unknown, targets: readonly PaletteTarget[]): void;
73
+ /** Forgets every setting, for a project without any. */
74
+ reset(): void;
75
+ }
76
+ /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
77
+ export declare function createPaletteVisibilityStore(): PaletteVisibilityStore;
70
78
  /** The menu item that opens the group settings. */
71
79
  export declare const paletteVisibilityMenuLabel: (locale: string) => "ブロックグループの表示・非表示の設定" | "Show or hide block groups";
72
80
  export interface PaletteMenuItem {
@@ -1,9 +1,9 @@
1
- import { blockPaletteCommentMarker, formatBlockPaletteComment } from '@kubohiroya/sb3-toolchain/browser';
2
1
  /**
3
2
  * Which block groups the palette shows for each sprite and the stage.
4
3
  *
5
- * The setting lives where sb3-toolchain source format 2 keeps it: one palette comment per sprite or
6
- * stage (`block-palette.json` in a project folder). It changes only what the palette offers; blocks
4
+ * The settings belong to the editor, not to the project's code: they are kept in memory per target and saved with
5
+ * the editor's own screen state (a slice of `tw-plus/workspace.json` in an SB3, `.tw-plus/workspace.json` in a
6
+ * project folder), the same way the tab layout is. Hiding a group changes only what the palette offers; blocks
7
7
  * already in the code stay visible and editable.
8
8
  */
9
9
  /** The standard groups, by the palette's category IDs. `lists` is Plus's own split of `variables`. */
@@ -22,7 +22,7 @@ const builtinSetGroups = {
22
22
  basics: ['events', 'control', 'operators']
23
23
  };
24
24
  const japanese = (locale) => /^ja(?:-|$)/i.test(locale ?? '');
25
- /** The sets every project has, then the project's own sets from its stage palette comment. */
25
+ /** The sets every project has, then the project's own sets. */
26
26
  export function paletteGroupSets(locale, projectSets = {}) {
27
27
  const builtin = Object.keys(builtinSetGroups).map(id => ({
28
28
  id, name: builtinSetNames[id][japanese(locale) ? 'ja' : 'en'], groups: builtinSetGroups[id]
@@ -55,45 +55,14 @@ export function usedGroups(target) {
55
55
  }
56
56
  return counts;
57
57
  }
58
- const markedLine = (text) => text.split('\n').find(line => line.endsWith(blockPaletteCommentMarker));
59
- /** The palette setting a target carries in its palette comment, or null when it has none or it cannot be read. */
60
- export function readTargetPalette(target) {
61
- for (const [commentId, comment] of Object.entries(target.comments ?? {})) {
62
- const line = typeof comment?.text === 'string' ? markedLine(comment.text) : undefined;
63
- if (!line)
64
- continue;
65
- try {
66
- const value = JSON.parse(line.slice(0, -blockPaletteCommentMarker.length));
67
- if (!value || typeof value !== 'object')
68
- return null;
69
- const strings = (list) => Array.isArray(list) && list.every(item => typeof item === 'string') ?
70
- list : undefined;
71
- return {
72
- commentId,
73
- groups: strings(value.groups),
74
- order: strings(value.order),
75
- sets: value.sets && typeof value.sets === 'object' ? value.sets : undefined
76
- };
77
- }
78
- catch {
79
- return null;
80
- }
81
- }
82
- return null;
83
- }
84
58
  /**
85
59
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
86
- * the extensions its code already uses, so an existing project opens with nothing missing.
60
+ * the extensions its code already uses, so a project opens with nothing missing.
87
61
  */
88
62
  export function defaultVisibleGroups(target, extensionIds) {
89
63
  const used = usedGroups(target);
90
64
  return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
91
65
  }
92
- /** The groups the palette shows for the target. */
93
- export function visibleGroups(target, extensionIds) {
94
- const groups = readTargetPalette(target)?.groups;
95
- return new Set(groups ?? defaultVisibleGroups(target, extensionIds));
96
- }
97
66
  /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
98
67
  export function filterToolboxTree(tree, visible) {
99
68
  if (!tree)
@@ -104,45 +73,82 @@ export function filterToolboxTree(tree, visible) {
104
73
  category.remove();
105
74
  }
106
75
  }
107
- const newCommentId = () => `twplus-palette-${Math.random().toString(36).slice(2, 10)}`;
108
- /**
109
- * Stores the target's palette setting in its palette comment, as sb3-toolchain source format 2 reads it.
110
- * A sprite whose groups equal its default gets no comment; the stage keeps one while it carries the
111
- * project's group order or sets.
112
- */
113
- export function writeTargetPalette(target, groups, { extensionIds = [], order, sets } = {}) {
114
- const current = readTargetPalette(target);
115
- const name = target.getName();
116
- const isDefault = sameGroups(groups, defaultVisibleGroups(target, extensionIds));
117
- const projectOrder = target.isStage ? order ?? current?.order : undefined;
118
- const projectSets = target.isStage ? sets ?? current?.sets : undefined;
119
- const keepsProjectSettings = (projectOrder && projectOrder.length > 0) ||
120
- (projectSets && Object.keys(projectSets).length > 0);
121
- if (isDefault && !keepsProjectSettings) {
122
- if (current)
123
- target.deleteComment?.(current.commentId);
124
- return;
125
- }
126
- const document = { formatVersion: 1 };
127
- if (projectOrder?.length)
128
- document.order = [...projectOrder];
129
- if (projectSets && Object.keys(projectSets).length)
130
- document.sets = projectSets;
131
- if (target.isStage) {
132
- if (!isDefault)
133
- document.stage = { groups: [...groups] };
134
- }
135
- else {
136
- document.sprites = { [name]: { groups: [...groups] } };
137
- }
138
- const text = formatBlockPaletteComment(document, { isStage: target.isStage, name });
139
- if (current) {
140
- target.comments[current.commentId].text = text;
141
- return;
142
- }
143
- target.createComment?.(newCommentId(), null, text, 0, 0, 200, 200, true);
144
- }
76
+ /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
77
+ export const paletteScreenStateKey = 'blockPalette';
78
+ const strings = (value) => Array.isArray(value) && value.every(item => typeof item === 'string') ? [...value] : undefined;
145
79
  const sameGroups = (left, right) => left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
80
+ /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
81
+ export function createPaletteVisibilityStore() {
82
+ let groups = new Map();
83
+ let projectSets = {};
84
+ return {
85
+ visible(target, extensionIds) {
86
+ return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
87
+ },
88
+ set(target, chosen, extensionIds) {
89
+ if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds)))
90
+ groups.delete(target.id);
91
+ else
92
+ groups.set(target.id, [...chosen]);
93
+ },
94
+ copy(from, to) {
95
+ const chosen = groups.get(from.id);
96
+ if (chosen)
97
+ groups.set(to.id, [...chosen]);
98
+ },
99
+ sets: () => ({ ...projectSets }),
100
+ addSets(sets) {
101
+ for (const set of sets)
102
+ projectSets[set.id] = { name: set.name, groups: [...set.groups] };
103
+ },
104
+ capture(targets) {
105
+ const saved = { version: 1 };
106
+ const sprites = {};
107
+ for (const target of targets) {
108
+ const chosen = groups.get(target.id);
109
+ if (!chosen)
110
+ continue;
111
+ if (target.isStage)
112
+ saved.stage = { groups: [...chosen] };
113
+ else
114
+ sprites[target.getName()] = { groups: [...chosen] };
115
+ }
116
+ if (Object.keys(sprites).length)
117
+ saved.sprites = sprites;
118
+ if (Object.keys(projectSets).length)
119
+ saved.sets = structuredClone(projectSets);
120
+ return saved.stage || saved.sprites || saved.sets ? saved : undefined;
121
+ },
122
+ apply(value, targets) {
123
+ groups = new Map();
124
+ projectSets = {};
125
+ if (!value || typeof value !== 'object' || value.version !== 1)
126
+ return;
127
+ const saved = value;
128
+ const setting = (entry) => entry && typeof entry === 'object' ?
129
+ strings(entry.groups) : undefined;
130
+ const sprites = saved.sprites && typeof saved.sprites === 'object' ? saved.sprites : {};
131
+ for (const target of targets) {
132
+ const chosen = target.isStage ? setting(saved.stage) :
133
+ Object.hasOwn(sprites, target.getName()) ? setting(sprites[target.getName()]) : undefined;
134
+ if (chosen)
135
+ groups.set(target.id, chosen);
136
+ }
137
+ if (saved.sets && typeof saved.sets === 'object') {
138
+ for (const [id, set] of Object.entries(saved.sets)) {
139
+ const name = set && typeof set === 'object' ? set.name : undefined;
140
+ const members = setting(set);
141
+ if (typeof name === 'string' && members)
142
+ projectSets[id] = { name, groups: members };
143
+ }
144
+ }
145
+ },
146
+ reset() {
147
+ groups = new Map();
148
+ projectSets = {};
149
+ }
150
+ };
151
+ }
146
152
  /** The menu item that opens the group settings. */
147
153
  export const paletteVisibilityMenuLabel = (locale) => japanese(locale) ? 'ブロックグループの表示・非表示の設定' :
148
154
  'Show or hide block groups';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -94,14 +94,12 @@
94
94
  "@kubohiroya/turbowarp-script-transfer": "0.1.5"
95
95
  },
96
96
  "peerDependencies": {
97
- "@kubohiroya/sb3-toolchain": ">=0.25.1 <0.26.0",
98
97
  "@kubohiroya/turbowarp-extension-security-dialog": ">=0.9.0 <0.10.0",
99
98
  "@kubohiroya/turbowarp-plus-editor-windows": ">=0.2.0 <0.3.0",
100
99
  "react": ">=16.14",
101
100
  "react-dom": ">=16.14"
102
101
  },
103
102
  "devDependencies": {
104
- "@kubohiroya/sb3-toolchain": "0.25.1",
105
103
  "@kubohiroya/turbowarp-extension-security-dialog": "0.9.0",
106
104
  "@kubohiroya/turbowarp-plus-editor-windows": "0.2.0",
107
105
  "@types/react": "18.3.31",
@@ -1,11 +1,9 @@
1
- import {blockPaletteCommentMarker, formatBlockPaletteComment} from '@kubohiroya/sb3-toolchain/browser';
2
- import type {BlockPaletteDocument, BlockPaletteSet} from '@kubohiroya/sb3-toolchain/browser';
3
-
4
1
  /**
5
2
  * Which block groups the palette shows for each sprite and the stage.
6
3
  *
7
- * The setting lives where sb3-toolchain source format 2 keeps it: one palette comment per sprite or
8
- * stage (`block-palette.json` in a project folder). It changes only what the palette offers; blocks
4
+ * The settings belong to the editor, not to the project's code: they are kept in memory per target and saved with
5
+ * the editor's own screen state (a slice of `tw-plus/workspace.json` in an SB3, `.tw-plus/workspace.json` in a
6
+ * project folder), the same way the tab layout is. Hiding a group changes only what the palette offers; blocks
9
7
  * already in the code stay visible and editable.
10
8
  */
11
9
 
@@ -13,6 +11,12 @@ import type {BlockPaletteDocument, BlockPaletteSet} from '@kubohiroya/sb3-toolch
13
11
  export const standardGroups = ['motion', 'looks', 'sound', 'events', 'control', 'sensing', 'operators', 'variables', 'lists',
14
12
  'myBlocks'] as const;
15
13
 
14
+ /** A named set of groups the project keeps. */
15
+ export interface SavedGroupSet {
16
+ name: string;
17
+ groups: string[];
18
+ }
19
+
16
20
  export interface PaletteGroupSet {
17
21
  id: string;
18
22
  name: string;
@@ -33,8 +37,8 @@ const builtinSetGroups: Record<string, readonly string[]> = {
33
37
  };
34
38
  const japanese = (locale?: string) => /^ja(?:-|$)/i.test(locale ?? '');
35
39
 
36
- /** The sets every project has, then the project's own sets from its stage palette comment. */
37
- export function paletteGroupSets(locale?: string, projectSets: Record<string, BlockPaletteSet> = {}): PaletteGroupSet[] {
40
+ /** The sets every project has, then the project's own sets. */
41
+ export function paletteGroupSets(locale?: string, projectSets: Record<string, SavedGroupSet> = {}): PaletteGroupSet[] {
38
42
  const builtin = Object.keys(builtinSetGroups).map(id => ({
39
43
  id, name: builtinSetNames[id][japanese(locale) ? 'ja' : 'en'], groups: builtinSetGroups[id]
40
44
  }));
@@ -56,16 +60,12 @@ export function groupOfOpcode(opcode: string): string | null {
56
60
  }
57
61
 
58
62
  type BlockLike = {opcode?: string; shadow?: boolean};
59
- type CommentLike = {text?: string; id?: string};
60
- /** The parts of a VM target this module reads and writes. */
63
+ /** The parts of a VM target this module reads. */
61
64
  export interface PaletteTarget {
65
+ id: string;
62
66
  isStage: boolean;
63
67
  getName(): string;
64
68
  blocks?: {_blocks?: Record<string, BlockLike>};
65
- comments: Record<string, CommentLike>;
66
- createComment?(id: string, blockId: string | null, text: string, x: number, y: number, width: number, height: number,
67
- minimized: boolean): void;
68
- deleteComment?(id: string): void;
69
69
  }
70
70
 
71
71
  /** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
@@ -79,55 +79,15 @@ export function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, n
79
79
  return counts;
80
80
  }
81
81
 
82
- export interface TargetPalette {
83
- /** The comment that holds the setting. */
84
- commentId: string;
85
- groups?: string[];
86
- /** Present on the stage's comment only. */
87
- order?: string[];
88
- sets?: Record<string, BlockPaletteSet>;
89
- }
90
-
91
- const markedLine = (text: string) => text.split('\n').find(line => line.endsWith(blockPaletteCommentMarker));
92
-
93
- /** The palette setting a target carries in its palette comment, or null when it has none or it cannot be read. */
94
- export function readTargetPalette(target: Pick<PaletteTarget, 'comments'>): TargetPalette | null {
95
- for (const [commentId, comment] of Object.entries(target.comments ?? {})) {
96
- const line = typeof comment?.text === 'string' ? markedLine(comment.text) : undefined;
97
- if (!line) continue;
98
- try {
99
- const value = JSON.parse(line.slice(0, -blockPaletteCommentMarker.length));
100
- if (!value || typeof value !== 'object') return null;
101
- const strings = (list: unknown) => Array.isArray(list) && list.every(item => typeof item === 'string') ?
102
- list as string[] : undefined;
103
- return {
104
- commentId,
105
- groups: strings(value.groups),
106
- order: strings(value.order),
107
- sets: value.sets && typeof value.sets === 'object' ? value.sets : undefined
108
- };
109
- } catch {
110
- return null;
111
- }
112
- }
113
- return null;
114
- }
115
-
116
82
  /**
117
83
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
118
- * the extensions its code already uses, so an existing project opens with nothing missing.
84
+ * the extensions its code already uses, so a project opens with nothing missing.
119
85
  */
120
86
  export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[] {
121
87
  const used = usedGroups(target);
122
88
  return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
123
89
  }
124
90
 
125
- /** The groups the palette shows for the target. */
126
- export function visibleGroups(target: Pick<PaletteTarget, 'blocks' | 'comments'>, extensionIds: readonly string[]): Set<string> {
127
- const groups = readTargetPalette(target)?.groups;
128
- return new Set(groups ?? defaultVisibleGroups(target, extensionIds));
129
- }
130
-
131
91
  /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
132
92
  export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void {
133
93
  if (!tree) return;
@@ -137,48 +97,99 @@ export function filterToolboxTree(tree: Element | null | undefined, visible: Rea
137
97
  }
138
98
  }
139
99
 
140
- const newCommentId = () => `twplus-palette-${Math.random().toString(36).slice(2, 10)}`;
141
-
142
- /**
143
- * Stores the target's palette setting in its palette comment, as sb3-toolchain source format 2 reads it.
144
- * A sprite whose groups equal its default gets no comment; the stage keeps one while it carries the
145
- * project's group order or sets.
146
- */
147
- export function writeTargetPalette(target: PaletteTarget, groups: readonly string[], {extensionIds = [], order, sets}: {
148
- extensionIds?: readonly string[];
149
- order?: readonly string[];
150
- sets?: Record<string, BlockPaletteSet>;
151
- } = {}): void {
152
- const current = readTargetPalette(target);
153
- const name = target.getName();
154
- const isDefault = sameGroups(groups, defaultVisibleGroups(target, extensionIds));
155
- const projectOrder = target.isStage ? order ?? current?.order : undefined;
156
- const projectSets = target.isStage ? sets ?? current?.sets : undefined;
157
- const keepsProjectSettings = (projectOrder && projectOrder.length > 0) ||
158
- (projectSets && Object.keys(projectSets).length > 0);
159
- if (isDefault && !keepsProjectSettings) {
160
- if (current) target.deleteComment?.(current.commentId);
161
- return;
162
- }
163
- const document: BlockPaletteDocument = {formatVersion: 1};
164
- if (projectOrder?.length) document.order = [...projectOrder];
165
- if (projectSets && Object.keys(projectSets).length) document.sets = projectSets;
166
- if (target.isStage) {
167
- if (!isDefault) document.stage = {groups: [...groups]};
168
- } else {
169
- document.sprites = {[name]: {groups: [...groups]}};
170
- }
171
- const text = formatBlockPaletteComment(document, {isStage: target.isStage, name});
172
- if (current) {
173
- target.comments[current.commentId].text = text;
174
- return;
175
- }
176
- target.createComment?.(newCommentId(), null, text, 0, 0, 200, 200, true);
100
+ /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
101
+ export const paletteScreenStateKey = 'blockPalette';
102
+ export interface SavedPaletteVisibility {
103
+ version: 1;
104
+ stage?: {groups: string[]};
105
+ sprites?: Record<string, {groups: string[]}>;
106
+ sets?: Record<string, SavedGroupSet>;
177
107
  }
178
108
 
109
+ const strings = (value: unknown): string[] | undefined =>
110
+ Array.isArray(value) && value.every(item => typeof item === 'string') ? [...value] : undefined;
179
111
  const sameGroups = (left: readonly string[], right: readonly string[]) =>
180
112
  left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
181
113
 
114
+ export interface PaletteVisibilityStore {
115
+ /** The groups the palette shows for the target. */
116
+ visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
117
+ /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
118
+ set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
119
+ /** A new sprite made from another, such as a duplicate, starts with its setting. */
120
+ copy(from: Pick<PaletteTarget, 'id'>, to: Pick<PaletteTarget, 'id'>): void;
121
+ /** The project's own sets. */
122
+ sets(): Record<string, SavedGroupSet>;
123
+ addSets(sets: readonly PaletteGroupSet[]): void;
124
+ /** The slice to save, or nothing when no target has a setting and the project has no sets. */
125
+ capture(targets: readonly PaletteTarget[]): SavedPaletteVisibility | undefined;
126
+ /** Takes the settings of a loaded project. A value that is not a saved slice leaves every target at its default. */
127
+ apply(value: unknown, targets: readonly PaletteTarget[]): void;
128
+ /** Forgets every setting, for a project without any. */
129
+ reset(): void;
130
+ }
131
+
132
+ /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
133
+ export function createPaletteVisibilityStore(): PaletteVisibilityStore {
134
+ let groups = new Map<string, string[]>();
135
+ let projectSets: Record<string, SavedGroupSet> = {};
136
+ return {
137
+ visible(target, extensionIds) {
138
+ return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
139
+ },
140
+ set(target, chosen, extensionIds) {
141
+ if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds))) groups.delete(target.id);
142
+ else groups.set(target.id, [...chosen]);
143
+ },
144
+ copy(from, to) {
145
+ const chosen = groups.get(from.id);
146
+ if (chosen) groups.set(to.id, [...chosen]);
147
+ },
148
+ sets: () => ({...projectSets}),
149
+ addSets(sets) {
150
+ for (const set of sets) projectSets[set.id] = {name: set.name, groups: [...set.groups]};
151
+ },
152
+ capture(targets) {
153
+ const saved: SavedPaletteVisibility = {version: 1};
154
+ const sprites: Record<string, {groups: string[]}> = {};
155
+ for (const target of targets) {
156
+ const chosen = groups.get(target.id);
157
+ if (!chosen) continue;
158
+ if (target.isStage) saved.stage = {groups: [...chosen]};
159
+ else sprites[target.getName()] = {groups: [...chosen]};
160
+ }
161
+ if (Object.keys(sprites).length) saved.sprites = sprites;
162
+ if (Object.keys(projectSets).length) saved.sets = structuredClone(projectSets);
163
+ return saved.stage || saved.sprites || saved.sets ? saved : undefined;
164
+ },
165
+ apply(value, targets) {
166
+ groups = new Map();
167
+ projectSets = {};
168
+ if (!value || typeof value !== 'object' || (value as {version?: unknown}).version !== 1) return;
169
+ const saved = value as Record<string, unknown>;
170
+ const setting = (entry: unknown) => entry && typeof entry === 'object' ?
171
+ strings((entry as {groups?: unknown}).groups) : undefined;
172
+ const sprites = saved.sprites && typeof saved.sprites === 'object' ? saved.sprites as Record<string, unknown> : {};
173
+ for (const target of targets) {
174
+ const chosen = target.isStage ? setting(saved.stage) :
175
+ Object.hasOwn(sprites, target.getName()) ? setting(sprites[target.getName()]) : undefined;
176
+ if (chosen) groups.set(target.id, chosen);
177
+ }
178
+ if (saved.sets && typeof saved.sets === 'object') {
179
+ for (const [id, set] of Object.entries(saved.sets as Record<string, unknown>)) {
180
+ const name = set && typeof set === 'object' ? (set as {name?: unknown}).name : undefined;
181
+ const members = setting(set);
182
+ if (typeof name === 'string' && members) projectSets[id] = {name, groups: members};
183
+ }
184
+ }
185
+ },
186
+ reset() {
187
+ groups = new Map();
188
+ projectSets = {};
189
+ }
190
+ };
191
+ }
192
+
182
193
  /** The menu item that opens the group settings. */
183
194
  export const paletteVisibilityMenuLabel = (locale: string) => japanese(locale) ? 'ブロックグループの表示・非表示の設定' :
184
195
  'Show or hide block groups';