@kubohiroya/turbowarp-plus-editor-code-views 0.10.0 → 0.12.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,6 +18,7 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
18
18
  | `./target-combobox` | コードの窓の対象の選択 |
19
19
  | `./detached-block-palette` | 別窓のブロックパレット |
20
20
  | `./palette-category-reorder`・`./palette-category-search`・`./palette-dropdown-resize` | パレットのカテゴリの並べ替えと検索、パレットのドロップダウンの大きさの変更 |
21
+ | `./palette-category-groups` | ツールボックスで別の category を含む category をグループとして表示する。アイコンをクリックすると、要素を並べた子ブロックパレットを影つきで重ねて開く(横配置のパレットではアイコンの右に横並び、縦配置では下に縦並び)。外側をクリックすると閉じる。Scratch Blocks は入れ子の category を捨てるので、`flattenCategoryGroups(tree)` と `filterGroupedToolboxTree(tree, groups, filter)` で木を整え、`attachPaletteCategoryGroups(menu, options)` で子ブロックパレットを開く。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
21
22
  | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ |
22
23
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
23
24
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
@@ -60,14 +61,38 @@ MPL-2.0。turbowarp-plus-editor の `packages/editor-views` と `packages/editor
60
61
 
61
62
  | 関数 | 内容 |
62
63
  | --- | --- |
63
- | `createPaletteVisibilityStore()` | 1つの作品の設定を、実行時の対象の ID ごとに持つ。名前を変えたスプライトも設定を保つ。`visible`・`set`・`copy`(複製)・`sets`・`addSets`、画面状態のスライスへの `capture(targets)` と `apply(value, targets)`、`reset` |
64
+ | `createPaletteVisibilityStore({catalog})` | 1つの作品の設定を、実行時の対象の ID ごとに持つ。名前を変えたスプライトも設定を保つ。`visible`・`set`・`copy`(複製)・`sets`・`addSets`、画面状態のスライスへの `capture(targets)` と `apply(value, targets)`、`reset` |
64
65
  | `paletteScreenStateKey` | 画面状態のスライスの名前(`blockPalette`) |
65
- | `filterToolboxTree(tree, visible)` | パレットを描く前のツールボックスの木から、出さないカテゴリを外す |
66
- | `usedGroups(target)`・`groupOfOpcode(opcode)`・`defaultVisibleGroups(target, extensionIds)` | コードが使っているグループとその数、設定のない対象に出すグループ |
66
+ | `filterToolboxTree(tree, visible, catalog)` | パレットを描く前のツールボックスの木から、出さないカテゴリを外す。カタログを渡すと、グループを宣言した機能拡張を先にグループごとのカテゴリに分ける(`splitExtensionCategories`) |
67
+ | `installExtensionPaletteGroups(runtime)`・`extensionPaletteCatalog(runtime._blockInfo)` | 機能拡張が宣言したグループを VM のカテゴリ情報に残し、読み込み済みの機能拡張のグループと、各ブロックの属するグループを一覧にする |
68
+ | `usedGroups(target, catalog)`・`groupOfOpcode(opcode, catalog)`・`defaultVisibleGroups(target, extensionGroups, catalog)` | コードが使っているグループとその数、設定のない対象に出すグループ |
67
69
  | `paletteGroupSets(locale, projectSets)` | 「標準」「表現」「変数・リスト」「基本の制御」と、作品のセット |
68
70
  | `attachPaletteMenuButton(menu, getLocale, getItems)` | カテゴリの一覧の末尾(横配置では右端、縦配置では下端)に ▼ のボタンを置く。押すと、ホストが渡す項目のメニューを出す。項目は「ブロックグループの表示・非表示の設定」(`paletteVisibilityMenuLabel`)と、ホストの機能拡張に関する項目 |
69
71
 
70
72
  `./palette-visibility-dialog` の `openPaletteVisibilityDialog(document, props)` は「パレット内のブロックグループの表示・非表示の設定」の画面を開く。機能拡張の各行は `@kubohiroya/turbowarp-extension-security-dialog/react` の `ExtensionRow` で描くので、拡張の追加の画面と同じ見た目になる。画面は、「まとめて選ぶ」の欄に「設定のショートカット」(「標準」「表現」などのセット)と「設定のコピー元」を左右に並べ、その下に標準と機能拡張のブロックグループのチェックを並べる。ショートカットやコピー元にポインターを重ねるかフォーカスすると、それが選ぶグループのチェックが、そのチェックにポインターを重ねたときと同じ背景になる。「確定」を押すと、出すグループと、この画面で足したショートカットを `onApply` に渡して閉じる。`newSprite` を渡すと、追加したばかりのスプライトについて尋ねる画面になり、見出しの下に「新しいスプライト「名前」」と出す。あわせて `copySources`(作成済みのスプライトの名前と、それぞれが表示中のグループ)を渡すと、「設定のコピー元」に選ぶ一覧と「コピー」を出す。一覧は「スプライトを選ぶ」から始まり、スプライトを選んでいる間は、それが選ぶグループのチェックを強調したままにする。「コピー」を押すと、選んだスプライトのグループのうちこのスプライトに出せるものを、画面のチェックに写す。画面は閉じないので、利用者はチェックを足したり外したりしてから「確定」を押す。
71
73
 
72
- ホストは `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、その `styles.css` も読み込む。設定を画面状態のスライスとして登録するのはホストの役目である。1つの機能拡張の中を複数のグループに分けて選ぶ機能は、VM がグループごとのカテゴリを作れるようになってから足す。
74
+ ホストは `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、その `styles.css` も読み込む。設定を画面状態のスライスとして登録するのはホストの役目である。
75
+
76
+ ### 1つの機能拡張の中のグループ
77
+
78
+ 機能拡張は、ブロックをいくつかのグループに分け、グループごとに表示・非表示を選べるようにできる。`getInfo()` にグループを宣言し、各ブロックに `paletteGroup` を付ける。
79
+
80
+ ```js
81
+ getInfo() {
82
+ return {
83
+ id: 'shapes', name: 'Shapes', color1: '#0fbd8c',
84
+ groups: [{id: 'geometry', name: '図形', color1: '#ff8c1a', color2: '#db6e00', color3: '#c26200'}, {id: 'text', name: '文字'}],
85
+ blocks: [
86
+ {opcode: 'circle', blockType: 'command', text: 'circle', paletteGroup: 'geometry'},
87
+ {opcode: 'write', blockType: 'command', text: 'write [TEXT]', paletteGroup: 'text', arguments: {/* ... */}},
88
+ {opcode: 'reset', blockType: 'command', text: 'reset'}
89
+ ]
90
+ };
91
+ }
92
+ ```
93
+
94
+ - 各グループはパレットのカテゴリ `shapes/geometry` になり、名前はグループの名前になる。設定もこの ID で記録する。`paletteGroup` のないブロック(宣言していないグループを指すものを含む)は、カテゴリ `shapes` に残る。
95
+ - グループの `color1`・`color2`・`color3`・`menuIconURI` は省略でき、省略すると機能拡張のものを使う。ブロック自身の色はグループの色より優先する。
96
+ - 見出し・区切り・ボタンは、その次のブロックと同じグループに入る。オペコードは `shapes_circle` などのまま変わらないので、SB3 は変わらない。標準の TurboWarp と Scratch は `groups` と `paletteGroup` を無視し、1つのカテゴリとして表示する。
97
+ - ホストは、機能拡張を読み込む前に `installExtensionPaletteGroups(vm.runtime)` を呼び、`extensionPaletteCatalog(vm.runtime._blockInfo)` をストア、`filterToolboxTree`、`usedGroups` に渡す。設定の画面には、そのような機能拡張の項目の `groups` としてグループを渡す。画面は機能拡張の行の中に、グループごとのチェックを出す。
73
98
 
package/README.md CHANGED
@@ -19,6 +19,7 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
19
19
  | `./detached-block-palette` | The block palette in its own window |
20
20
  | `./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 |
21
21
  | `./palette-category-reorder`, `./palette-category-search`, `./palette-dropdown-resize` | Reordering and searching palette categories, and resizing palette dropdowns |
22
+ | `./palette-category-groups` | Shows a category of the toolbox that holds other categories as a group: clicking its icon opens a child palette of its members, floating with a shadow — a row to the right of the icon in a horizontal palette, a column below it in a vertical one — and a click outside closes it. `flattenCategoryGroups(tree)` and `filterGroupedToolboxTree(tree, groups, filter)` prepare the tree, which Scratch Blocks would otherwise drop nested categories from; `attachPaletteCategoryGroups(menu, options)` opens the child palettes. `splitExtensionCategories(tree, catalog, {nested: true})` makes an extension that declares groups such a group |
22
23
  | `./block-argument-text` | Shortens long text arguments and edits them in a dialog. Shift+Enter in a text argument continues in the dialog with a line break |
23
24
  | `./block-number-input` | Converts full-width digits and signs typed into number arguments to half-width |
24
25
  | `./clean-up-comments` | Keeps comments with their scripts in "Clean up blocks": block comments keep their offset from the block, scripts with their comments do not cover one another, and workspace comments that cover a script move beside the scripts (`installCleanUpComments(ScratchBlocks)`) |
@@ -60,14 +61,38 @@ Each sprite and the stage can choose which block groups the palette shows: the s
60
61
 
61
62
  | Function | What it does |
62
63
  | --- | --- |
63
- | `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` |
64
+ | `createPaletteVisibilityStore({catalog})` | 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` |
64
65
  | `paletteScreenStateKey` | The name of the screen-state slice (`blockPalette`) |
65
- | `filterToolboxTree(tree, visible)` | Removes the categories a target does not show from the parsed toolbox before the palette is drawn |
66
- | `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 |
66
+ | `filterToolboxTree(tree, visible, catalog)` | Removes the categories a target does not show from the parsed toolbox before the palette is drawn. With a catalog, an extension that declares groups is first split into one category per group (`splitExtensionCategories`) |
67
+ | `installExtensionPaletteGroups(runtime)`, `extensionPaletteCatalog(runtime._blockInfo)` | Keep the groups each extension declares on the VM's category info, and list the groups of the loaded extensions with the group of each block |
68
+ | `usedGroups(target, catalog)`, `groupOfOpcode(opcode, catalog)`, `defaultVisibleGroups(target, extensionGroups, catalog)` | The groups the code uses and how many blocks of each, and the groups shown for a target without a setting |
67
69
  | `paletteGroupSets(locale, projectSets)` | Standard, Expression, Variables and lists, Basic control, and the project's own sets |
68
70
  | `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 |
69
71
 
70
72
  `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. The screen puts “Setting shortcuts” (sets such as Standard and Expression) and “Copy settings from” side by side under “Choose several at once”, above the checkboxes of the standard and extension block groups. Pointing at or focusing a shortcut or the copy source gives the checkboxes it would choose the same background as pointing at them. Confirm passes the groups to show, and the shortcuts added in the screen, to `onApply` and closes. With `newSprite`, the screen asks about a sprite just added and names it as a new sprite. Given `copySources` too (the sprites already in the project, each with the groups it shows), “Copy settings from” offers a list to choose one, starting at “Choose a sprite”, and “Copy”. While a sprite is chosen, the checkboxes it would choose stay marked. “Copy” checks that sprite's groups, as far as this sprite is offered them. The screen stays open; the person adds or removes checks and presses Confirm.
71
73
 
72
- 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.
74
+ 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.
75
+
76
+ ### Groups inside one extension
77
+
78
+ An extension can split its blocks into groups that are shown and hidden on their own. It declares them in `getInfo()` and marks each block with `paletteGroup`:
79
+
80
+ ```js
81
+ getInfo() {
82
+ return {
83
+ id: 'shapes', name: 'Shapes', color1: '#0fbd8c',
84
+ groups: [{id: 'geometry', name: 'Geometry', color1: '#ff8c1a', color2: '#db6e00', color3: '#c26200'}, {id: 'text', name: 'Text'}],
85
+ blocks: [
86
+ {opcode: 'circle', blockType: 'command', text: 'circle', paletteGroup: 'geometry'},
87
+ {opcode: 'write', blockType: 'command', text: 'write [TEXT]', paletteGroup: 'text', arguments: {/* ... */}},
88
+ {opcode: 'reset', blockType: 'command', text: 'reset'}
89
+ ]
90
+ };
91
+ }
92
+ ```
93
+
94
+ - Each group is the palette category `shapes/geometry`, named after the group, and the settings name it by that ID. Blocks without `paletteGroup` (or naming a group not declared) stay in the category `shapes`.
95
+ - `color1`, `color2`, `color3` and `menuIconURI` of a group are optional, and default to the extension's. A block's own colour wins over its group's.
96
+ - A label, separator or button goes with the block after it. The opcodes stay `shapes_circle` and so on, so the SB3 does not change: standard TurboWarp and Scratch ignore `groups` and `paletteGroup` and show one category.
97
+ - The host calls `installExtensionPaletteGroups(vm.runtime)` before extensions load, and passes `extensionPaletteCatalog(vm.runtime._blockInfo)` to the store, `filterToolboxTree` and `usedGroups`. The dialog takes the groups of such an extension as `groups` of its entry and shows a checkbox for each inside the extension's row.
73
98
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
3
+ * reads only the top-level categories and drops nested ones, so the tree is flattened before it is drawn:
4
+ * each nested category becomes a top-level one right after its group, and the menu hides it. Clicking the
5
+ * group's icon then shows its members in a child palette laid out like the palette it opens from — a row to the
6
+ * right of the icon for a horizontal palette, a column below it for a vertical one — and a member that is itself
7
+ * a group opens the next level the same way. A click outside the child palettes closes them.
8
+ */
9
+ /** The attribute a flattened category keeps with the id of the group it was nested in. */
10
+ export declare const groupParentAttribute = "palette-group-parent";
11
+ export interface PaletteGroups {
12
+ /** Each group's members, in order, by category id. A member may itself be a group. */
13
+ members: Map<string, string[]>;
14
+ /** The groups that also hold blocks of their own, which their child palette offers first. */
15
+ withOwnContents: Set<string>;
16
+ }
17
+ /**
18
+ * Moves every nested category of the toolbox tree to the top level, right after the group that held it, depth
19
+ * first, so Scratch Blocks makes a category of each. Returns the groups found. A nested category without an id
20
+ * gets one from its group's id and its position.
21
+ */
22
+ export declare const flattenCategoryGroups: (tree: Element | null | undefined) => PaletteGroups;
23
+ /**
24
+ * Runs a filter that removes top-level categories by id, such as the palette's group settings, on a flattened tree.
25
+ * A group the filter removes still stays, without blocks of its own, while one of its members stays; a group left
26
+ * with neither members nor blocks of its own is removed with its members. Returns the groups that remain.
27
+ */
28
+ export declare const filterGroupedToolboxTree: (tree: Element, groups: PaletteGroups, filter: (tree: Element) => void) => PaletteGroups;
29
+ /** The part of a Scratch Blocks toolbox category the child palettes use. */
30
+ export interface PaletteCategory {
31
+ id_: string;
32
+ name_: string;
33
+ item_: HTMLElement;
34
+ setSelected(selected: boolean): void;
35
+ }
36
+ export interface PaletteCategoryGroupsOptions {
37
+ /** The toolbox's categories, top level and flattened members alike. */
38
+ categories(): PaletteCategory[];
39
+ /** Whether the palette is laid out in a row. */
40
+ horizontal(): boolean;
41
+ rtl?: boolean;
42
+ /** Opens a category that is not a group, as clicking its icon in the palette would. */
43
+ choose(category: PaletteCategory): void;
44
+ /** Called when a child palette opens or the last one closes. */
45
+ onChange?(): void;
46
+ }
47
+ export interface PaletteCategoryGroupsController {
48
+ /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
49
+ update(groups: PaletteGroups): void;
50
+ isGroup(id: string): boolean;
51
+ /** The id of the outermost group the category is in, or its own id when it is in none. */
52
+ topLevelId(id: string): string;
53
+ /** Opens the group's child palette from its icon, or closes it if it is open. */
54
+ toggle(category: PaletteCategory, focus?: boolean): void;
55
+ isOpen(): boolean;
56
+ /** The icon the palette shows for the category: its own, or that of the group it is in. */
57
+ anchorOf(category: PaletteCategory): HTMLElement;
58
+ /** Whether the node is in a child palette. */
59
+ contains(node: Node | null): boolean;
60
+ close(): void;
61
+ dispose(): void;
62
+ }
63
+ /** Makes clicking a group's icon in the palette menu open its child palette. */
64
+ export declare const attachPaletteCategoryGroups: (menu: HTMLElement, options: PaletteCategoryGroupsOptions) => PaletteCategoryGroupsController;
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
3
+ * reads only the top-level categories and drops nested ones, so the tree is flattened before it is drawn:
4
+ * each nested category becomes a top-level one right after its group, and the menu hides it. Clicking the
5
+ * group's icon then shows its members in a child palette laid out like the palette it opens from — a row to the
6
+ * right of the icon for a horizontal palette, a column below it for a vertical one — and a member that is itself
7
+ * a group opens the next level the same way. A click outside the child palettes closes them.
8
+ */
9
+ /** The attribute a flattened category keeps with the id of the group it was nested in. */
10
+ export const groupParentAttribute = 'palette-group-parent';
11
+ const isCategory = (node) => node.nodeType === 1 && node.tagName.toLowerCase() === 'category';
12
+ const ownsContents = (category) => Array.from(category.children).some(child => !isCategory(child));
13
+ /**
14
+ * Moves every nested category of the toolbox tree to the top level, right after the group that held it, depth
15
+ * first, so Scratch Blocks makes a category of each. Returns the groups found. A nested category without an id
16
+ * gets one from its group's id and its position.
17
+ */
18
+ export const flattenCategoryGroups = (tree) => {
19
+ const groups = { members: new Map(), withOwnContents: new Set() };
20
+ if (!tree)
21
+ return groups;
22
+ const used = new Set(Array.from(tree.querySelectorAll('category[id]'), category => category.getAttribute('id')));
23
+ const flatten = (category, after) => {
24
+ const nested = Array.from(category.children).filter(isCategory);
25
+ if (!nested.length)
26
+ return after;
27
+ const id = category.getAttribute('id');
28
+ groups.members.set(id, []);
29
+ if (ownsContents(category))
30
+ groups.withOwnContents.add(id);
31
+ let last = after;
32
+ nested.forEach((child, index) => {
33
+ if (!child.getAttribute('id')) {
34
+ let generated = `${id}/${index}`;
35
+ while (used.has(generated))
36
+ generated += '_';
37
+ used.add(generated);
38
+ child.setAttribute('id', generated);
39
+ }
40
+ child.setAttribute(groupParentAttribute, id);
41
+ groups.members.get(id).push(child.getAttribute('id'));
42
+ last.after(child);
43
+ last = flatten(child, child);
44
+ });
45
+ return last;
46
+ };
47
+ for (const category of Array.from(tree.children).filter(isCategory)) {
48
+ if (!category.getAttribute('id'))
49
+ continue;
50
+ flatten(category, category);
51
+ }
52
+ return groups;
53
+ };
54
+ /**
55
+ * Runs a filter that removes top-level categories by id, such as the palette's group settings, on a flattened tree.
56
+ * A group the filter removes still stays, without blocks of its own, while one of its members stays; a group left
57
+ * with neither members nor blocks of its own is removed with its members. Returns the groups that remain.
58
+ */
59
+ export const filterGroupedToolboxTree = (tree, groups, filter) => {
60
+ const elements = new Map();
61
+ const markers = new Map();
62
+ for (const category of Array.from(tree.children).filter(isCategory)) {
63
+ const id = category.getAttribute('id');
64
+ if (!groups.members.has(id))
65
+ continue;
66
+ const marker = tree.ownerDocument.createComment('palette-group');
67
+ category.before(marker);
68
+ elements.set(id, category);
69
+ markers.set(id, marker);
70
+ }
71
+ filter(tree);
72
+ const present = (element) => !!element && element.parentNode === tree;
73
+ const remaining = { members: new Map(), withOwnContents: new Set() };
74
+ const keep = (id) => {
75
+ const members = groups.members.get(id);
76
+ if (!members)
77
+ return present(Array.from(tree.children).find(child => isCategory(child) && child.getAttribute('id') === id));
78
+ const kept = members.filter(keep);
79
+ const ownShown = groups.withOwnContents.has(id) && present(elements.get(id));
80
+ if (!kept.length && !ownShown)
81
+ return false;
82
+ remaining.members.set(id, kept);
83
+ if (ownShown)
84
+ remaining.withOwnContents.add(id);
85
+ return true;
86
+ };
87
+ for (const [id, element] of elements) {
88
+ if (!element.hasAttribute(groupParentAttribute))
89
+ keep(id);
90
+ }
91
+ for (const [id, element] of elements) {
92
+ if (!remaining.members.has(id))
93
+ element.remove();
94
+ else if (!present(element)) {
95
+ // Shown only as the way to its members.
96
+ element.replaceChildren();
97
+ markers.get(id).after(element);
98
+ }
99
+ }
100
+ for (const marker of markers.values())
101
+ marker.remove();
102
+ // A member whose group is gone goes with it.
103
+ for (const category of Array.from(tree.children).filter(isCategory)) {
104
+ const parent = category.getAttribute(groupParentAttribute);
105
+ if (parent && !remaining.members.has(parent))
106
+ category.remove();
107
+ }
108
+ return remaining;
109
+ };
110
+ const selectedClass = 'categorySelected';
111
+ /** Makes clicking a group's icon in the palette menu open its child palette. */
112
+ export const attachPaletteCategoryGroups = (menu, options) => {
113
+ const doc = menu.ownerDocument;
114
+ const events = new doc.defaultView.AbortController();
115
+ const capture = { capture: true, signal: events.signal };
116
+ let groups = { members: new Map(), withOwnContents: new Set() };
117
+ const parentOf = new Map();
118
+ // The open child palettes, outermost first, with the icon each opened from.
119
+ const stack = [];
120
+ let selected = null;
121
+ const categoryById = (id) => options.categories().find(category => category.id_ === id);
122
+ const topLevelOf = (id) => {
123
+ let current = id;
124
+ while (parentOf.has(current))
125
+ current = parentOf.get(current);
126
+ return current;
127
+ };
128
+ const markSelection = () => {
129
+ for (const [id] of groups.members) {
130
+ if (parentOf.has(id))
131
+ continue;
132
+ const item = categoryById(id)?.item_;
133
+ if (!item)
134
+ continue;
135
+ const current = selected !== null && selected !== id && topLevelOf(selected) === id;
136
+ item.toggleAttribute('data-palette-group-current', current);
137
+ if (current)
138
+ item.classList.add(selectedClass);
139
+ else if (selected !== id)
140
+ item.classList.remove(selectedClass);
141
+ }
142
+ };
143
+ const closeFrom = (depth) => {
144
+ let changed = false;
145
+ while (stack.length > depth) {
146
+ const { anchor, popup } = stack.pop();
147
+ anchor.setAttribute('aria-expanded', 'false');
148
+ popup.remove();
149
+ changed = true;
150
+ }
151
+ if (changed)
152
+ options.onChange?.();
153
+ };
154
+ const close = () => closeFrom(0);
155
+ const place = (popup, anchor) => {
156
+ const container = popup.offsetParent ?? popup.parentElement;
157
+ const bounds = container.getBoundingClientRect();
158
+ const rect = anchor.getBoundingClientRect();
159
+ const width = popup.offsetWidth;
160
+ const height = popup.offsetHeight;
161
+ const maxLeft = Math.max(0, container.clientWidth - width);
162
+ const maxTop = Math.max(0, container.clientHeight - height);
163
+ let left;
164
+ let top;
165
+ if (options.horizontal()) {
166
+ left = (options.rtl ? rect.left - width : rect.right) - bounds.left;
167
+ top = rect.top - bounds.top;
168
+ }
169
+ else {
170
+ left = (options.rtl ? rect.right - width : rect.left) - bounds.left;
171
+ top = rect.bottom - bounds.top;
172
+ }
173
+ popup.style.left = `${Math.min(Math.max(0, left), maxLeft)}px`;
174
+ popup.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
175
+ };
176
+ const activate = (category, entry, depth, focus, self) => {
177
+ if (!self && groups.members.has(category.id_)) {
178
+ if (stack[depth]?.id === category.id_)
179
+ closeFrom(depth);
180
+ else
181
+ open(category, entry, depth, focus);
182
+ return;
183
+ }
184
+ close();
185
+ options.choose(category);
186
+ };
187
+ const createEntry = (category, depth, self = false) => {
188
+ const entry = doc.createElement('div');
189
+ entry.className = `scratchCategoryMenuItem scratchCategoryId-${category.id_}`;
190
+ entry.classList.add('tw-palette-group-item');
191
+ entry.setAttribute('data-palette-group-item', category.id_);
192
+ entry.setAttribute('role', 'menuitem');
193
+ entry.tabIndex = -1;
194
+ for (const child of Array.from(category.item_.children))
195
+ entry.append(child.cloneNode(true));
196
+ const isGroup = !self && groups.members.has(category.id_);
197
+ if (isGroup) {
198
+ entry.setAttribute('aria-haspopup', 'true');
199
+ entry.setAttribute('aria-expanded', 'false');
200
+ }
201
+ if (selected === category.id_ || (isGroup && selected !== null && isInside(selected, category.id_))) {
202
+ entry.classList.add(selectedClass);
203
+ }
204
+ entry.addEventListener('click', event => {
205
+ event.stopPropagation();
206
+ activate(category, entry, depth, false, self);
207
+ }, { signal: events.signal });
208
+ entry.addEventListener('keydown', event => {
209
+ if (event.key === 'Enter' || event.key === ' ') {
210
+ event.preventDefault();
211
+ event.stopPropagation();
212
+ activate(category, entry, depth, true, self);
213
+ return;
214
+ }
215
+ const forward = options.horizontal() ? (options.rtl ? 'ArrowLeft' : 'ArrowRight') : 'ArrowDown';
216
+ const backward = options.horizontal() ? (options.rtl ? 'ArrowRight' : 'ArrowLeft') : 'ArrowUp';
217
+ if (event.key !== forward && event.key !== backward)
218
+ return;
219
+ event.preventDefault();
220
+ const entries = Array.from(entry.parentElement.children);
221
+ const index = entries.indexOf(entry) + (event.key === forward ? 1 : -1);
222
+ entries[(index + entries.length) % entries.length].focus();
223
+ }, { signal: events.signal });
224
+ return entry;
225
+ };
226
+ const isInside = (id, groupId) => {
227
+ for (let current = id; current !== undefined; current = parentOf.get(current)) {
228
+ if (current === groupId)
229
+ return true;
230
+ }
231
+ return false;
232
+ };
233
+ const open = (group, anchor, depth, focus) => {
234
+ closeFrom(depth);
235
+ const members = (groups.members.get(group.id_) ?? []).map(categoryById).filter(Boolean);
236
+ const popup = doc.createElement('div');
237
+ popup.className = 'tw-palette-group-popup';
238
+ popup.setAttribute('data-palette-group-popup', group.id_);
239
+ popup.setAttribute('role', 'menu');
240
+ popup.setAttribute('aria-label', anchor.textContent?.trim() || group.id_);
241
+ popup.toggleAttribute('data-horizontal', options.horizontal());
242
+ // The child palette is drawn in the palette's own colours and type.
243
+ const look = doc.defaultView.getComputedStyle(menu.querySelector('.scratchCategoryMenu, .scratchCategoryMenuHorizontal') ?? menu);
244
+ popup.style.setProperty('--palette-group-background', look.backgroundColor);
245
+ popup.style.color = look.color;
246
+ popup.style.fontSize = look.fontSize;
247
+ popup.style.fontFamily = look.fontFamily;
248
+ if (groups.withOwnContents.has(group.id_))
249
+ popup.append(createEntry(group, depth, true));
250
+ for (const member of members)
251
+ popup.append(createEntry(member, depth + 1));
252
+ (menu.parentElement ?? doc.body).append(popup);
253
+ place(popup, anchor);
254
+ anchor.setAttribute('aria-expanded', 'true');
255
+ stack.push({ id: group.id_, anchor, popup });
256
+ options.onChange?.();
257
+ if (focus)
258
+ popup.firstElementChild?.focus();
259
+ };
260
+ const toggle = (category, focus = false) => {
261
+ if (stack[0]?.id === category.id_)
262
+ close();
263
+ else
264
+ open(category, category.item_, 0, focus);
265
+ };
266
+ const groupItem = (target) => {
267
+ if (!(target instanceof doc.defaultView.Node))
268
+ return null;
269
+ return options.categories().find(category => groups.members.has(category.id_) &&
270
+ !parentOf.has(category.id_) && category.item_.contains(target)) ?? null;
271
+ };
272
+ // Scratch Blocks opens a category on mouseup (touchend on touch screens); a group opens its child palette on click.
273
+ for (const type of ['mouseup', 'touchend']) {
274
+ menu.addEventListener(type, event => {
275
+ if (groupItem(event.target))
276
+ event.stopPropagation();
277
+ }, capture);
278
+ }
279
+ menu.addEventListener('click', event => {
280
+ const category = groupItem(event.target);
281
+ if (!category)
282
+ return;
283
+ event.stopPropagation();
284
+ toggle(category);
285
+ }, capture);
286
+ const contains = (node) => !!node && stack.some(({ popup }) => popup.contains(node));
287
+ const onPointerDown = (event) => {
288
+ if (!stack.length)
289
+ return;
290
+ const target = event.target;
291
+ if (contains(target) || stack[0].anchor.contains(target))
292
+ return;
293
+ close();
294
+ };
295
+ const onKeyDown = (event) => {
296
+ if (event.key !== 'Escape' || event.isComposing || !stack.length)
297
+ return;
298
+ event.preventDefault();
299
+ // The palette's own Escape would close the block list as well.
300
+ event.stopImmediatePropagation();
301
+ const { anchor } = stack[stack.length - 1];
302
+ closeFrom(stack.length - 1);
303
+ anchor.focus();
304
+ };
305
+ doc.addEventListener('pointerdown', onPointerDown, capture);
306
+ doc.addEventListener('keydown', onKeyDown, capture);
307
+ menu.addEventListener('scroll', close, { signal: events.signal });
308
+ doc.defaultView.addEventListener('resize', close, { signal: events.signal });
309
+ return {
310
+ update(next) {
311
+ close();
312
+ groups = next;
313
+ parentOf.clear();
314
+ for (const [id, members] of groups.members)
315
+ for (const member of members)
316
+ parentOf.set(member, id);
317
+ for (const category of options.categories()) {
318
+ const member = parentOf.has(category.id_);
319
+ const row = category.item_.parentElement;
320
+ if (row && row !== menu)
321
+ row.hidden = member;
322
+ const group = groups.members.has(category.id_) && !member;
323
+ if (group) {
324
+ category.item_.setAttribute('aria-haspopup', 'true');
325
+ category.item_.setAttribute('aria-expanded', 'false');
326
+ category.item_.setAttribute('data-palette-group', '');
327
+ category.item_.classList.add('tw-palette-group');
328
+ }
329
+ const { setSelected } = category;
330
+ category.setSelected = function (value) {
331
+ setSelected.call(this, value);
332
+ if (value)
333
+ selected = category.id_;
334
+ else if (selected === category.id_)
335
+ selected = null;
336
+ markSelection();
337
+ };
338
+ if (category.item_.classList.contains(selectedClass))
339
+ selected = category.id_;
340
+ }
341
+ markSelection();
342
+ },
343
+ isGroup: id => groups.members.has(id) && !parentOf.has(id),
344
+ topLevelId: topLevelOf,
345
+ toggle,
346
+ isOpen: () => stack.length > 0,
347
+ anchorOf: category => categoryById(topLevelOf(category.id_))?.item_ ?? category.item_,
348
+ contains,
349
+ close,
350
+ dispose() {
351
+ close();
352
+ events.abort();
353
+ }
354
+ };
355
+ };
@@ -20,8 +20,61 @@ export interface PaletteGroupSet {
20
20
  }
21
21
  /** The sets every project has, then the project's own sets. */
22
22
  export declare function paletteGroupSets(locale?: string, projectSets?: Record<string, SavedGroupSet>): PaletteGroupSet[];
23
+ /**
24
+ * One block group an extension offers. An extension that declares no groups offers one, named and identified like
25
+ * the extension. One that declares `groups: [{id, name, color1?, color2?, color3?, menuIconURI?}]` in `getInfo()` and
26
+ * marks blocks with `paletteGroup` offers each group as `extensionId/groupId`, and its unmarked blocks as one more
27
+ * group with the extension's ID. Standard TurboWarp ignores both fields and shows the extension as one category.
28
+ */
29
+ export interface ExtensionPaletteGroup {
30
+ id: string;
31
+ extensionId: string;
32
+ /** The group's own name; for the unmarked blocks, the extension's name. */
33
+ name: string;
34
+ extensionName: string;
35
+ /** Whether this is a group the extension declares, rather than its unmarked blocks. */
36
+ declared: boolean;
37
+ color1?: string;
38
+ color2?: string;
39
+ menuIconURI?: string;
40
+ }
41
+ /** The extension groups the project's extensions offer, and which group each of their blocks belongs to. */
42
+ export interface PaletteGroupCatalog {
43
+ groups: readonly ExtensionPaletteGroup[];
44
+ /** Block opcode to group ID, for the blocks of declared groups. */
45
+ groupOf: ReadonlyMap<string, string>;
46
+ }
47
+ /** The parts of the VM's category info (`runtime._blockInfo`) this module reads. */
48
+ export interface PaletteCategoryInfo {
49
+ id: string;
50
+ name?: string;
51
+ color1?: string;
52
+ color2?: string;
53
+ menuIconURI?: string;
54
+ blockIconURI?: string;
55
+ /** The groups the extension declares, kept by {@link installExtensionPaletteGroups}. */
56
+ paletteGroups?: unknown;
57
+ blocks?: readonly {
58
+ info?: {
59
+ paletteGroup?: unknown;
60
+ };
61
+ json?: {
62
+ type?: unknown;
63
+ } | null;
64
+ }[];
65
+ }
66
+ /**
67
+ * Keeps the groups each extension declares on its category info, where {@link extensionPaletteCatalog} reads them,
68
+ * and draws the blocks of a group with a colour of its own in the group's colours. Install it before extensions load.
69
+ * Returns the function that removes it.
70
+ */
71
+ export declare function installExtensionPaletteGroups(runtime: {
72
+ _fillExtensionCategory?: (...args: any[]) => unknown;
73
+ }): () => void;
74
+ /** The groups of the loaded extensions, in palette order, from the VM's category info. */
75
+ export declare function extensionPaletteCatalog(categories?: readonly PaletteCategoryInfo[]): PaletteGroupCatalog;
23
76
  /** The group a block belongs to, or null for a block no palette group offers. */
24
- export declare function groupOfOpcode(opcode: string): string | null;
77
+ export declare function groupOfOpcode(opcode: string, catalog?: PaletteGroupCatalog): string | null;
25
78
  type BlockLike = {
26
79
  opcode?: string;
27
80
  shadow?: boolean;
@@ -36,14 +89,27 @@ export interface PaletteTarget {
36
89
  };
37
90
  }
38
91
  /** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
39
- export declare function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, number>;
92
+ export declare function usedGroups(target: Pick<PaletteTarget, 'blocks'>, catalog?: PaletteGroupCatalog): Map<string, number>;
40
93
  /**
41
94
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
42
- * the extensions its code already uses, so a project opens with nothing missing.
95
+ * the extension groups its code already uses, so a project opens with nothing missing. `extensionGroups` are the
96
+ * IDs of the extension groups on offer: the extension IDs, or with a catalog, its group IDs.
97
+ */
98
+ export declare function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionGroups: readonly string[], catalog?: PaletteGroupCatalog): string[];
99
+ /**
100
+ * Splits each extension category whose extension declares groups into one category per group, in the catalog's
101
+ * order. A label, separator or button goes with the block after it, or with the last block when none follows.
102
+ * With `nested`, the extension's category stays, with its unmarked blocks, and holds the categories of its declared
103
+ * groups, so the palette can show it as a group that opens them (see `./palette-category-groups`).
104
+ */
105
+ export declare function splitExtensionCategories(tree: Element, catalog: PaletteGroupCatalog, { nested }?: {
106
+ nested?: boolean;
107
+ }): void;
108
+ /**
109
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
110
+ * With a catalog, an extension that declares groups is first split into a category per group.
43
111
  */
44
- export declare function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[];
45
- /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
46
- export declare function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void;
112
+ export declare function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>, catalog?: PaletteGroupCatalog): void;
47
113
  /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
48
114
  export declare const paletteScreenStateKey = "blockPalette";
49
115
  export interface SavedPaletteVisibility {
@@ -57,7 +123,10 @@ export interface SavedPaletteVisibility {
57
123
  sets?: Record<string, SavedGroupSet>;
58
124
  }
59
125
  export interface PaletteVisibilityStore {
60
- /** The groups the palette shows for the target. */
126
+ /**
127
+ * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
128
+ * IDs, or the group IDs of a catalog when the store was given one.
129
+ */
61
130
  visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
62
131
  /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
63
132
  set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
@@ -74,7 +143,10 @@ export interface PaletteVisibilityStore {
74
143
  reset(): void;
75
144
  }
76
145
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
77
- export declare function createPaletteVisibilityStore(): PaletteVisibilityStore;
146
+ export declare function createPaletteVisibilityStore({ catalog }?: {
147
+ /** The extension groups on offer now, so the default counts the blocks of declared groups. */
148
+ catalog?: () => PaletteGroupCatalog | undefined;
149
+ }): PaletteVisibilityStore;
78
150
  /** The menu item that opens the group settings. */
79
151
  export declare const paletteVisibilityMenuLabel: (locale: string) => "ブロックグループの表示・非表示の設定" | "Show or hide block groups";
80
152
  export interface PaletteMenuItem {