@kubohiroya/turbowarp-plus-editor-code-views 0.10.0 → 0.11.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
@@ -60,14 +60,38 @@ MPL-2.0。turbowarp-plus-editor の `packages/editor-views` と `packages/editor
60
60
 
61
61
  | 関数 | 内容 |
62
62
  | --- | --- |
63
- | `createPaletteVisibilityStore()` | 1つの作品の設定を、実行時の対象の ID ごとに持つ。名前を変えたスプライトも設定を保つ。`visible`・`set`・`copy`(複製)・`sets`・`addSets`、画面状態のスライスへの `capture(targets)` と `apply(value, targets)`、`reset` |
63
+ | `createPaletteVisibilityStore({catalog})` | 1つの作品の設定を、実行時の対象の ID ごとに持つ。名前を変えたスプライトも設定を保つ。`visible`・`set`・`copy`(複製)・`sets`・`addSets`、画面状態のスライスへの `capture(targets)` と `apply(value, targets)`、`reset` |
64
64
  | `paletteScreenStateKey` | 画面状態のスライスの名前(`blockPalette`) |
65
- | `filterToolboxTree(tree, visible)` | パレットを描く前のツールボックスの木から、出さないカテゴリを外す |
66
- | `usedGroups(target)`・`groupOfOpcode(opcode)`・`defaultVisibleGroups(target, extensionIds)` | コードが使っているグループとその数、設定のない対象に出すグループ |
65
+ | `filterToolboxTree(tree, visible, catalog)` | パレットを描く前のツールボックスの木から、出さないカテゴリを外す。カタログを渡すと、グループを宣言した機能拡張を先にグループごとのカテゴリに分ける(`splitExtensionCategories`) |
66
+ | `installExtensionPaletteGroups(runtime)`・`extensionPaletteCatalog(runtime._blockInfo)` | 機能拡張が宣言したグループを VM のカテゴリ情報に残し、読み込み済みの機能拡張のグループと、各ブロックの属するグループを一覧にする |
67
+ | `usedGroups(target, catalog)`・`groupOfOpcode(opcode, catalog)`・`defaultVisibleGroups(target, extensionGroups, catalog)` | コードが使っているグループとその数、設定のない対象に出すグループ |
67
68
  | `paletteGroupSets(locale, projectSets)` | 「標準」「表現」「変数・リスト」「基本の制御」と、作品のセット |
68
69
  | `attachPaletteMenuButton(menu, getLocale, getItems)` | カテゴリの一覧の末尾(横配置では右端、縦配置では下端)に ▼ のボタンを置く。押すと、ホストが渡す項目のメニューを出す。項目は「ブロックグループの表示・非表示の設定」(`paletteVisibilityMenuLabel`)と、ホストの機能拡張に関する項目 |
69
70
 
70
71
  `./palette-visibility-dialog` の `openPaletteVisibilityDialog(document, props)` は「パレット内のブロックグループの表示・非表示の設定」の画面を開く。機能拡張の各行は `@kubohiroya/turbowarp-extension-security-dialog/react` の `ExtensionRow` で描くので、拡張の追加の画面と同じ見た目になる。画面は、「まとめて選ぶ」の欄に「設定のショートカット」(「標準」「表現」などのセット)と「設定のコピー元」を左右に並べ、その下に標準と機能拡張のブロックグループのチェックを並べる。ショートカットやコピー元にポインターを重ねるかフォーカスすると、それが選ぶグループのチェックが、そのチェックにポインターを重ねたときと同じ背景になる。「確定」を押すと、出すグループと、この画面で足したショートカットを `onApply` に渡して閉じる。`newSprite` を渡すと、追加したばかりのスプライトについて尋ねる画面になり、見出しの下に「新しいスプライト「名前」」と出す。あわせて `copySources`(作成済みのスプライトの名前と、それぞれが表示中のグループ)を渡すと、「設定のコピー元」に選ぶ一覧と「コピー」を出す。一覧は「スプライトを選ぶ」から始まり、スプライトを選んでいる間は、それが選ぶグループのチェックを強調したままにする。「コピー」を押すと、選んだスプライトのグループのうちこのスプライトに出せるものを、画面のチェックに写す。画面は閉じないので、利用者はチェックを足したり外したりしてから「確定」を押す。
71
72
 
72
- ホストは `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、その `styles.css` も読み込む。設定を画面状態のスライスとして登録するのはホストの役目である。1つの機能拡張の中を複数のグループに分けて選ぶ機能は、VM がグループごとのカテゴリを作れるようになってから足す。
73
+ ホストは `@kubohiroya/turbowarp-extension-security-dialog`(0.9.0 以上)を入れ、その `styles.css` も読み込む。設定を画面状態のスライスとして登録するのはホストの役目である。
74
+
75
+ ### 1つの機能拡張の中のグループ
76
+
77
+ 機能拡張は、ブロックをいくつかのグループに分け、グループごとに表示・非表示を選べるようにできる。`getInfo()` にグループを宣言し、各ブロックに `paletteGroup` を付ける。
78
+
79
+ ```js
80
+ getInfo() {
81
+ return {
82
+ id: 'shapes', name: 'Shapes', color1: '#0fbd8c',
83
+ groups: [{id: 'geometry', name: '図形', color1: '#ff8c1a', color2: '#db6e00', color3: '#c26200'}, {id: 'text', name: '文字'}],
84
+ blocks: [
85
+ {opcode: 'circle', blockType: 'command', text: 'circle', paletteGroup: 'geometry'},
86
+ {opcode: 'write', blockType: 'command', text: 'write [TEXT]', paletteGroup: 'text', arguments: {/* ... */}},
87
+ {opcode: 'reset', blockType: 'command', text: 'reset'}
88
+ ]
89
+ };
90
+ }
91
+ ```
92
+
93
+ - 各グループはパレットのカテゴリ `shapes/geometry` になり、名前はグループの名前になる。設定もこの ID で記録する。`paletteGroup` のないブロック(宣言していないグループを指すものを含む)は、カテゴリ `shapes` に残る。
94
+ - グループの `color1`・`color2`・`color3`・`menuIconURI` は省略でき、省略すると機能拡張のものを使う。ブロック自身の色はグループの色より優先する。
95
+ - 見出し・区切り・ボタンは、その次のブロックと同じグループに入る。オペコードは `shapes_circle` などのまま変わらないので、SB3 は変わらない。標準の TurboWarp と Scratch は `groups` と `paletteGroup` を無視し、1つのカテゴリとして表示する。
96
+ - ホストは、機能拡張を読み込む前に `installExtensionPaletteGroups(vm.runtime)` を呼び、`extensionPaletteCatalog(vm.runtime._blockInfo)` をストア、`filterToolboxTree`、`usedGroups` に渡す。設定の画面には、そのような機能拡張の項目の `groups` としてグループを渡す。画面は機能拡張の行の中に、グループごとのチェックを出す。
73
97
 
package/README.md CHANGED
@@ -60,14 +60,38 @@ Each sprite and the stage can choose which block groups the palette shows: the s
60
60
 
61
61
  | Function | What it does |
62
62
  | --- | --- |
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` |
63
+ | `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
64
  | `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 |
65
+ | `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`) |
66
+ | `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 |
67
+ | `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
68
  | `paletteGroupSets(locale, projectSets)` | Standard, Expression, Variables and lists, Basic control, and the project's own sets |
68
69
  | `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
70
 
70
71
  `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
72
 
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.
73
+ 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.
74
+
75
+ ### Groups inside one extension
76
+
77
+ 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`:
78
+
79
+ ```js
80
+ getInfo() {
81
+ return {
82
+ id: 'shapes', name: 'Shapes', color1: '#0fbd8c',
83
+ groups: [{id: 'geometry', name: 'Geometry', color1: '#ff8c1a', color2: '#db6e00', color3: '#c26200'}, {id: 'text', name: 'Text'}],
84
+ blocks: [
85
+ {opcode: 'circle', blockType: 'command', text: 'circle', paletteGroup: 'geometry'},
86
+ {opcode: 'write', blockType: 'command', text: 'write [TEXT]', paletteGroup: 'text', arguments: {/* ... */}},
87
+ {opcode: 'reset', blockType: 'command', text: 'reset'}
88
+ ]
89
+ };
90
+ }
91
+ ```
92
+
93
+ - 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`.
94
+ - `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.
95
+ - 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.
96
+ - 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
97
 
@@ -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,23 @@ 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
+ */
103
+ export declare function splitExtensionCategories(tree: Element, catalog: PaletteGroupCatalog): void;
104
+ /**
105
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
106
+ * With a catalog, an extension that declares groups is first split into a category per group.
43
107
  */
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;
108
+ export declare function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>, catalog?: PaletteGroupCatalog): void;
47
109
  /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
48
110
  export declare const paletteScreenStateKey = "blockPalette";
49
111
  export interface SavedPaletteVisibility {
@@ -57,7 +119,10 @@ export interface SavedPaletteVisibility {
57
119
  sets?: Record<string, SavedGroupSet>;
58
120
  }
59
121
  export interface PaletteVisibilityStore {
60
- /** The groups the palette shows for the target. */
122
+ /**
123
+ * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
124
+ * IDs, or the group IDs of a catalog when the store was given one.
125
+ */
61
126
  visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
62
127
  /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
63
128
  set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
@@ -74,7 +139,10 @@ export interface PaletteVisibilityStore {
74
139
  reset(): void;
75
140
  }
76
141
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
77
- export declare function createPaletteVisibilityStore(): PaletteVisibilityStore;
142
+ export declare function createPaletteVisibilityStore({ catalog }?: {
143
+ /** The extension groups on offer now, so the default counts the blocks of declared groups. */
144
+ catalog?: () => PaletteGroupCatalog | undefined;
145
+ }): PaletteVisibilityStore;
78
146
  /** The menu item that opens the group settings. */
79
147
  export declare const paletteVisibilityMenuLabel: (locale: string) => "ブロックグループの表示・非表示の設定" | "Show or hide block groups";
80
148
  export interface PaletteMenuItem {
@@ -33,8 +33,100 @@ const standardPrefixes = {
33
33
  motion: 'motion', looks: 'looks', sound: 'sound', event: 'events', control: 'control', sensing: 'sensing',
34
34
  operator: 'operators', procedures: 'myBlocks', argument: 'myBlocks'
35
35
  };
36
+ const groupIdPattern = /^[A-Za-z0-9_-]+$/;
37
+ const optionalString = (value) => typeof value === 'string' && value ? value : undefined;
38
+ /** The groups `getInfo()` declares, leaving out any that are not well formed or repeat an ID. */
39
+ function declaredGroups(value) {
40
+ if (!Array.isArray(value))
41
+ return [];
42
+ const groups = [];
43
+ for (const item of value) {
44
+ if (!item || typeof item !== 'object')
45
+ continue;
46
+ const { id, name } = item;
47
+ if (typeof id !== 'string' || !groupIdPattern.test(id) || groups.some(group => group.id === id))
48
+ continue;
49
+ const entry = item;
50
+ groups.push({ id, name: typeof name === 'string' && name ? name : id, color1: optionalString(entry.color1),
51
+ color2: optionalString(entry.color2), color3: optionalString(entry.color3),
52
+ menuIconURI: optionalString(entry.menuIconURI) });
53
+ }
54
+ return groups;
55
+ }
56
+ /**
57
+ * Keeps the groups each extension declares on its category info, where {@link extensionPaletteCatalog} reads them,
58
+ * and draws the blocks of a group with a colour of its own in the group's colours. Install it before extensions load.
59
+ * Returns the function that removes it.
60
+ */
61
+ export function installExtensionPaletteGroups(runtime) {
62
+ const original = runtime._fillExtensionCategory;
63
+ if (typeof original !== 'function')
64
+ return () => { };
65
+ const wrapped = function (categoryInfo, extensionInfo, ...rest) {
66
+ const result = original.call(this, categoryInfo, extensionInfo, ...rest);
67
+ const groups = declaredGroups(extensionInfo?.groups);
68
+ if (categoryInfo && typeof categoryInfo === 'object') {
69
+ categoryInfo.paletteGroups = groups;
70
+ for (const block of Array.isArray(categoryInfo.blocks) ? categoryInfo.blocks : []) {
71
+ const group = groups.find(item => item.id === block?.info?.paletteGroup);
72
+ if (!group?.color1 || !block.json || block.info.color1 !== undefined)
73
+ continue;
74
+ block.json.colour = group.color1;
75
+ if (group.color2)
76
+ block.json.colourSecondary = group.color2;
77
+ if (group.color3)
78
+ block.json.colourTertiary = group.color3;
79
+ }
80
+ }
81
+ return result;
82
+ };
83
+ runtime._fillExtensionCategory = wrapped;
84
+ return () => {
85
+ if (runtime._fillExtensionCategory === wrapped)
86
+ runtime._fillExtensionCategory = original;
87
+ };
88
+ }
89
+ /** The groups of the loaded extensions, in palette order, from the VM's category info. */
90
+ export function extensionPaletteCatalog(categories = []) {
91
+ const groups = [];
92
+ const groupOf = new Map();
93
+ for (const category of categories) {
94
+ const extensionName = category.name || category.id;
95
+ const declared = declaredGroups(category.paletteGroups);
96
+ const used = new Set();
97
+ let unmarked = declared.length === 0;
98
+ for (const block of category.blocks ?? []) {
99
+ const opcode = block?.json?.type;
100
+ if (typeof opcode !== 'string')
101
+ continue;
102
+ const group = declared.find(item => item.id === block.info?.paletteGroup);
103
+ if (!group) {
104
+ unmarked = true;
105
+ continue;
106
+ }
107
+ groupOf.set(opcode, `${category.id}/${group.id}`);
108
+ used.add(group.id);
109
+ }
110
+ const menuIconURI = category.menuIconURI || category.blockIconURI || undefined;
111
+ if (unmarked) {
112
+ groups.push({ id: category.id, extensionId: category.id, name: extensionName, extensionName, declared: false,
113
+ color1: category.color1, color2: category.color2, menuIconURI });
114
+ }
115
+ for (const group of declared) {
116
+ if (!used.has(group.id))
117
+ continue;
118
+ groups.push({ id: `${category.id}/${group.id}`, extensionId: category.id, name: group.name, extensionName,
119
+ declared: true, color1: group.color1 ?? category.color1, color2: group.color2 ?? category.color2,
120
+ menuIconURI: group.menuIconURI ?? menuIconURI });
121
+ }
122
+ }
123
+ return { groups, groupOf };
124
+ }
36
125
  /** The group a block belongs to, or null for a block no palette group offers. */
37
- export function groupOfOpcode(opcode) {
126
+ export function groupOfOpcode(opcode, catalog) {
127
+ const declared = catalog?.groupOf.get(opcode);
128
+ if (declared)
129
+ return declared;
38
130
  const separator = opcode.indexOf('_');
39
131
  if (separator <= 0)
40
132
  return null;
@@ -44,12 +136,12 @@ export function groupOfOpcode(opcode) {
44
136
  return standardPrefixes[prefix] ?? prefix;
45
137
  }
46
138
  /** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
47
- export function usedGroups(target) {
139
+ export function usedGroups(target, catalog) {
48
140
  const counts = new Map();
49
141
  for (const block of Object.values(target.blocks?._blocks ?? {})) {
50
142
  if (!block || block.shadow || typeof block.opcode !== 'string')
51
143
  continue;
52
- const group = groupOfOpcode(block.opcode);
144
+ const group = groupOfOpcode(block.opcode, catalog);
53
145
  if (group)
54
146
  counts.set(group, (counts.get(group) ?? 0) + 1);
55
147
  }
@@ -57,16 +149,69 @@ export function usedGroups(target) {
57
149
  }
58
150
  /**
59
151
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
60
- * the extensions its code already uses, so a project opens with nothing missing.
152
+ * the extension groups its code already uses, so a project opens with nothing missing. `extensionGroups` are the
153
+ * IDs of the extension groups on offer: the extension IDs, or with a catalog, its group IDs.
61
154
  */
62
- export function defaultVisibleGroups(target, extensionIds) {
63
- const used = usedGroups(target);
64
- return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
155
+ export function defaultVisibleGroups(target, extensionGroups, catalog) {
156
+ const used = usedGroups(target, catalog);
157
+ return [...standardGroups, ...extensionGroups.filter(id => used.has(id))];
158
+ }
159
+ /**
160
+ * Splits each extension category whose extension declares groups into one category per group, in the catalog's
161
+ * order. A label, separator or button goes with the block after it, or with the last block when none follows.
162
+ */
163
+ export function splitExtensionCategories(tree, catalog) {
164
+ for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
165
+ const extensionId = category.getAttribute('id');
166
+ const groups = catalog.groups.filter(group => group.extensionId === extensionId);
167
+ if (!extensionId || !groups.some(group => group.declared))
168
+ continue;
169
+ const items = new Map();
170
+ let pending = [];
171
+ let last = extensionId;
172
+ for (const child of Array.from(category.children)) {
173
+ if (child.tagName.toLowerCase() !== 'block') {
174
+ pending.push(child);
175
+ continue;
176
+ }
177
+ last = catalog.groupOf.get(child.getAttribute('type') ?? '') ?? extensionId;
178
+ items.set(last, [...items.get(last) ?? [], ...pending, child]);
179
+ pending = [];
180
+ }
181
+ if (pending.length)
182
+ items.set(last, [...items.get(last) ?? [], ...pending]);
183
+ let first = true;
184
+ for (const group of groups) {
185
+ const children = items.get(group.id);
186
+ if (!children)
187
+ continue;
188
+ const part = category.cloneNode(false);
189
+ part.setAttribute('id', group.id);
190
+ part.setAttribute('name', group.name);
191
+ if (group.color1)
192
+ part.setAttribute('colour', group.color1);
193
+ if (group.color2)
194
+ part.setAttribute('secondaryColour', group.color2);
195
+ if (group.menuIconURI)
196
+ part.setAttribute('iconURI', group.menuIconURI);
197
+ if (!first)
198
+ part.removeAttribute('showStatusButton');
199
+ first = false;
200
+ part.append(...children);
201
+ category.before(part);
202
+ }
203
+ category.remove();
204
+ }
65
205
  }
66
- /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
67
- export function filterToolboxTree(tree, visible) {
206
+ /**
207
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
208
+ * With a catalog, an extension that declares groups is first split into a category per group.
209
+ */
210
+ export function filterToolboxTree(tree, visible, catalog) {
68
211
  if (!tree)
69
212
  return;
213
+ if (catalog)
214
+ splitExtensionCategories(tree, catalog);
70
215
  for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
71
216
  const id = category.getAttribute('id');
72
217
  if (id && !visible.has(id))
@@ -78,15 +223,16 @@ export const paletteScreenStateKey = 'blockPalette';
78
223
  const strings = (value) => Array.isArray(value) && value.every(item => typeof item === 'string') ? [...value] : undefined;
79
224
  const sameGroups = (left, right) => left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
80
225
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
81
- export function createPaletteVisibilityStore() {
226
+ export function createPaletteVisibilityStore({ catalog } = {}) {
227
+ const defaults = (target, extensionIds) => defaultVisibleGroups(target, extensionIds, catalog?.());
82
228
  let groups = new Map();
83
229
  let projectSets = {};
84
230
  return {
85
231
  visible(target, extensionIds) {
86
- return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
232
+ return new Set(groups.get(target.id) ?? defaults(target, extensionIds));
87
233
  },
88
234
  set(target, chosen, extensionIds) {
89
- if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds)))
235
+ if (sameGroups(chosen, defaults(target, extensionIds)))
90
236
  groups.delete(target.id);
91
237
  else
92
238
  groups.set(target.id, [...chosen]);
@@ -6,6 +6,15 @@ export interface PaletteExtension {
6
6
  id: string;
7
7
  /** What the host knows about the extension; at least its name. */
8
8
  metadata: ExtensionMetadata;
9
+ /**
10
+ * The groups the extension declares, each chosen on its own, in place of the extension. A group whose ID is the
11
+ * extension's holds the blocks no declared group takes.
12
+ */
13
+ groups?: readonly {
14
+ id: string;
15
+ name: string;
16
+ color?: string;
17
+ }[];
9
18
  }
10
19
  export interface PaletteVisibilityChoice {
11
20
  /** The groups to show for the target. */
@@ -70,11 +79,14 @@ export declare class PaletteVisibilityDialog extends React.PureComponent<Palette
70
79
  extensions: string;
71
80
  used: (count: number) => string;
72
81
  hiddenInUse: (count: number) => string;
82
+ otherBlocks: string;
73
83
  cancel: string;
74
84
  confirm: string;
75
85
  close: string;
76
86
  };
77
87
  standard(): ("sound" | "variables" | "events" | "motion" | "looks" | "control" | "sensing" | "operators" | "lists" | "myBlocks")[];
88
+ /** Every group on offer, in the order the screen lists them. */
89
+ offered(): string[];
78
90
  available(groups: readonly string[]): string[];
79
91
  toggle(group: string): void;
80
92
  toggleSet(set: PaletteGroupSet): void;
@@ -19,7 +19,7 @@ const messages = {
19
19
  quick: 'Choose several at once', copyFrom: 'Copy settings from', copy: 'Copy', chooseSprite: 'Choose a sprite',
20
20
  sets: 'Setting shortcuts', addSet: 'Add setting shortcut', setName: 'Shortcut name', add: 'Add',
21
21
  standard: 'Standard block groups', extensions: 'Extension block groups', used: (count) => `In use ${count}`,
22
- hiddenInUse: (count) => `Hidden and in use: ${count}`, cancel: 'Cancel', confirm: 'Confirm', close: 'Close'
22
+ hiddenInUse: (count) => `Hidden and in use: ${count}`, otherBlocks: 'Other blocks', cancel: 'Cancel', confirm: 'Confirm', close: 'Close'
23
23
  },
24
24
  ja: {
25
25
  title: 'パレット内のブロックグループの表示・非表示の設定', sprite: (name) => `スプライト「${name}」`, stage: '背景',
@@ -27,7 +27,7 @@ const messages = {
27
27
  quick: 'まとめて選ぶ', copyFrom: '設定のコピー元', copy: 'コピー', chooseSprite: 'スプライトを選ぶ',
28
28
  sets: '設定のショートカット', addSet: '設定のショートカットを追加', setName: 'ショートカットの名前', add: '追加',
29
29
  standard: '標準のブロックグループ', extensions: '機能拡張のブロックグループ', used: (count) => `使用中 ${count}`,
30
- hiddenInUse: (count) => `非表示中・使用中 ${count} 件`, cancel: 'キャンセル', confirm: '確定', close: '閉じる'
30
+ hiddenInUse: (count) => `非表示中・使用中 ${count} 件`, otherBlocks: 'そのほかのブロック', cancel: 'キャンセル', confirm: '確定', close: '閉じる'
31
31
  }
32
32
  };
33
33
  const isJapanese = (locale) => /^ja(?:-|$)/i.test(locale ?? '');
@@ -48,8 +48,12 @@ export class PaletteVisibilityDialog extends React.PureComponent {
48
48
  // The stage has no motion blocks.
49
49
  return standardGroups.filter(group => !(this.props.isStage && group === 'motion'));
50
50
  }
51
+ /** Every group on offer, in the order the screen lists them. */
52
+ offered() {
53
+ return [...this.standard(), ...this.props.extensions.flatMap(extension => extension.groups ? extension.groups.map(group => group.id) : [extension.id])];
54
+ }
51
55
  available(groups) {
52
- const offered = new Set([...this.standard(), ...this.props.extensions.map(extension => extension.id)]);
56
+ const offered = new Set(this.offered());
53
57
  return groups.filter(group => offered.has(group));
54
58
  }
55
59
  toggle(group) {
@@ -84,8 +88,7 @@ export class PaletteVisibilityDialog extends React.PureComponent {
84
88
  let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'set';
85
89
  for (let index = 2; taken.has(id); index++)
86
90
  id = `${id.replace(/-\d+$/, '')}-${index}`;
87
- const groups = [...this.standard(), ...this.props.extensions.map(extension => extension.id)]
88
- .filter(group => this.state.shown.has(group));
91
+ const groups = this.offered().filter(group => this.state.shown.has(group));
89
92
  this.setState(({ addedSets }) => ({ addedSets: [...addedSets, { id, name, groups }], naming: false, setName: '' }));
90
93
  }
91
94
  /**
@@ -103,8 +106,7 @@ export class PaletteVisibilityDialog extends React.PureComponent {
103
106
  return source ? this.available(source.groups) : [];
104
107
  }
105
108
  apply() {
106
- const order = [...this.standard(), ...this.props.extensions.map(extension => extension.id)];
107
- this.props.onApply({ groups: order.filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets });
109
+ this.props.onApply({ groups: this.offered().filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets });
108
110
  }
109
111
  render() {
110
112
  const { locale, targetName, isStage, used, extensions, onCancel } = this.props;
@@ -170,7 +172,12 @@ export class PaletteVisibilityDialog extends React.PureComponent {
170
172
  extensions.length > 0 && (React.createElement("section", { "aria-label": text.extensions },
171
173
  React.createElement("h3", null, text.extensions),
172
174
  React.createElement("div", { className: "twextsec-review" },
173
- React.createElement("ul", { className: "twextsec-rows" }, extensions.map(extension => (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-group': extension.id, 'data-highlighted': highlighted(extension.id) }, pick: { checked: shown.has(extension.id), onToggle: () => this.toggle(extension.id) } }, usedBadge(extension.id)))))))),
175
+ React.createElement("ul", { className: "twextsec-rows" }, extensions.map(extension => extension.groups ? (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-extension': extension.id } },
176
+ React.createElement("div", { className: "tw-palette-visibility-extension-groups" }, extension.groups.map(group => (React.createElement("label", { key: group.id, "data-group": group.id, "data-highlighted": highlighted(group.id) },
177
+ React.createElement("input", { type: "checkbox", checked: shown.has(group.id), onChange: () => this.toggle(group.id) }),
178
+ React.createElement("span", { className: "tw-palette-visibility-swatch", "aria-hidden": "true", style: { color: group.color } }, "\u25CF"),
179
+ group.id === extension.id ? text.otherBlocks : group.name,
180
+ usedBadge(group.id))))))) : (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-group': extension.id, 'data-highlighted': highlighted(extension.id) }, pick: { checked: shown.has(extension.id), onToggle: () => this.toggle(extension.id) } }, usedBadge(extension.id)))))))),
174
181
  React.createElement("footer", { className: "tw-palette-visibility-footer" },
175
182
  React.createElement("span", { role: "status" }, hiddenInUse > 0 ? text.hiddenInUse(hiddenInUse) : ''),
176
183
  React.createElement("span", null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.10.0",
3
+ "version": "0.11.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",
@@ -50,8 +50,140 @@ const standardPrefixes: Record<string, string> = {
50
50
  operator: 'operators', procedures: 'myBlocks', argument: 'myBlocks'
51
51
  };
52
52
 
53
+ /**
54
+ * One block group an extension offers. An extension that declares no groups offers one, named and identified like
55
+ * the extension. One that declares `groups: [{id, name, color1?, color2?, color3?, menuIconURI?}]` in `getInfo()` and
56
+ * marks blocks with `paletteGroup` offers each group as `extensionId/groupId`, and its unmarked blocks as one more
57
+ * group with the extension's ID. Standard TurboWarp ignores both fields and shows the extension as one category.
58
+ */
59
+ export interface ExtensionPaletteGroup {
60
+ id: string;
61
+ extensionId: string;
62
+ /** The group's own name; for the unmarked blocks, the extension's name. */
63
+ name: string;
64
+ extensionName: string;
65
+ /** Whether this is a group the extension declares, rather than its unmarked blocks. */
66
+ declared: boolean;
67
+ color1?: string;
68
+ color2?: string;
69
+ menuIconURI?: string;
70
+ }
71
+
72
+ /** The extension groups the project's extensions offer, and which group each of their blocks belongs to. */
73
+ export interface PaletteGroupCatalog {
74
+ groups: readonly ExtensionPaletteGroup[];
75
+ /** Block opcode to group ID, for the blocks of declared groups. */
76
+ groupOf: ReadonlyMap<string, string>;
77
+ }
78
+
79
+ /** A declared group as kept on the VM's category info. */
80
+ interface DeclaredGroup {
81
+ id: string;
82
+ name: string;
83
+ color1?: string;
84
+ color2?: string;
85
+ color3?: string;
86
+ menuIconURI?: string;
87
+ }
88
+ /** The parts of the VM's category info (`runtime._blockInfo`) this module reads. */
89
+ export interface PaletteCategoryInfo {
90
+ id: string;
91
+ name?: string;
92
+ color1?: string;
93
+ color2?: string;
94
+ menuIconURI?: string;
95
+ blockIconURI?: string;
96
+ /** The groups the extension declares, kept by {@link installExtensionPaletteGroups}. */
97
+ paletteGroups?: unknown;
98
+ blocks?: readonly {info?: {paletteGroup?: unknown}; json?: {type?: unknown} | null}[];
99
+ }
100
+
101
+ const groupIdPattern = /^[A-Za-z0-9_-]+$/;
102
+ const optionalString = (value: unknown) => typeof value === 'string' && value ? value : undefined;
103
+ /** The groups `getInfo()` declares, leaving out any that are not well formed or repeat an ID. */
104
+ function declaredGroups(value: unknown): DeclaredGroup[] {
105
+ if (!Array.isArray(value)) return [];
106
+ const groups: DeclaredGroup[] = [];
107
+ for (const item of value) {
108
+ if (!item || typeof item !== 'object') continue;
109
+ const {id, name} = item as Record<string, unknown>;
110
+ if (typeof id !== 'string' || !groupIdPattern.test(id) || groups.some(group => group.id === id)) continue;
111
+ const entry = item as Record<string, unknown>;
112
+ groups.push({id, name: typeof name === 'string' && name ? name : id, color1: optionalString(entry.color1),
113
+ color2: optionalString(entry.color2), color3: optionalString(entry.color3),
114
+ menuIconURI: optionalString(entry.menuIconURI)});
115
+ }
116
+ return groups;
117
+ }
118
+
119
+ /**
120
+ * Keeps the groups each extension declares on its category info, where {@link extensionPaletteCatalog} reads them,
121
+ * and draws the blocks of a group with a colour of its own in the group's colours. Install it before extensions load.
122
+ * Returns the function that removes it.
123
+ */
124
+ export function installExtensionPaletteGroups(runtime: {_fillExtensionCategory?: (...args: any[]) => unknown}): () => void {
125
+ const original = runtime._fillExtensionCategory;
126
+ if (typeof original !== 'function') return () => {};
127
+ const wrapped = function (this: unknown, categoryInfo: any, extensionInfo: any, ...rest: unknown[]) {
128
+ const result = original.call(this, categoryInfo, extensionInfo, ...rest);
129
+ const groups = declaredGroups(extensionInfo?.groups);
130
+ if (categoryInfo && typeof categoryInfo === 'object') {
131
+ categoryInfo.paletteGroups = groups;
132
+ for (const block of Array.isArray(categoryInfo.blocks) ? categoryInfo.blocks : []) {
133
+ const group = groups.find(item => item.id === block?.info?.paletteGroup);
134
+ if (!group?.color1 || !block.json || block.info.color1 !== undefined) continue;
135
+ block.json.colour = group.color1;
136
+ if (group.color2) block.json.colourSecondary = group.color2;
137
+ if (group.color3) block.json.colourTertiary = group.color3;
138
+ }
139
+ }
140
+ return result;
141
+ };
142
+ runtime._fillExtensionCategory = wrapped;
143
+ return () => {
144
+ if (runtime._fillExtensionCategory === wrapped) runtime._fillExtensionCategory = original;
145
+ };
146
+ }
147
+
148
+ /** The groups of the loaded extensions, in palette order, from the VM's category info. */
149
+ export function extensionPaletteCatalog(categories: readonly PaletteCategoryInfo[] = []): PaletteGroupCatalog {
150
+ const groups: ExtensionPaletteGroup[] = [];
151
+ const groupOf = new Map<string, string>();
152
+ for (const category of categories) {
153
+ const extensionName = category.name || category.id;
154
+ const declared = declaredGroups(category.paletteGroups);
155
+ const used = new Set<string>();
156
+ let unmarked = declared.length === 0;
157
+ for (const block of category.blocks ?? []) {
158
+ const opcode = block?.json?.type;
159
+ if (typeof opcode !== 'string') continue;
160
+ const group = declared.find(item => item.id === block.info?.paletteGroup);
161
+ if (!group) {
162
+ unmarked = true;
163
+ continue;
164
+ }
165
+ groupOf.set(opcode, `${category.id}/${group.id}`);
166
+ used.add(group.id);
167
+ }
168
+ const menuIconURI = category.menuIconURI || category.blockIconURI || undefined;
169
+ if (unmarked) {
170
+ groups.push({id: category.id, extensionId: category.id, name: extensionName, extensionName, declared: false,
171
+ color1: category.color1, color2: category.color2, menuIconURI});
172
+ }
173
+ for (const group of declared) {
174
+ if (!used.has(group.id)) continue;
175
+ groups.push({id: `${category.id}/${group.id}`, extensionId: category.id, name: group.name, extensionName,
176
+ declared: true, color1: group.color1 ?? category.color1, color2: group.color2 ?? category.color2,
177
+ menuIconURI: group.menuIconURI ?? menuIconURI});
178
+ }
179
+ }
180
+ return {groups, groupOf};
181
+ }
182
+
53
183
  /** The group a block belongs to, or null for a block no palette group offers. */
54
- export function groupOfOpcode(opcode: string): string | null {
184
+ export function groupOfOpcode(opcode: string, catalog?: PaletteGroupCatalog): string | null {
185
+ const declared = catalog?.groupOf.get(opcode);
186
+ if (declared) return declared;
55
187
  const separator = opcode.indexOf('_');
56
188
  if (separator <= 0) return null;
57
189
  const prefix = opcode.slice(0, separator);
@@ -69,11 +201,11 @@ export interface PaletteTarget {
69
201
  }
70
202
 
71
203
  /** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
72
- export function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, number> {
204
+ export function usedGroups(target: Pick<PaletteTarget, 'blocks'>, catalog?: PaletteGroupCatalog): Map<string, number> {
73
205
  const counts = new Map<string, number>();
74
206
  for (const block of Object.values(target.blocks?._blocks ?? {})) {
75
207
  if (!block || block.shadow || typeof block.opcode !== 'string') continue;
76
- const group = groupOfOpcode(block.opcode);
208
+ const group = groupOfOpcode(block.opcode, catalog);
77
209
  if (group) counts.set(group, (counts.get(group) ?? 0) + 1);
78
210
  }
79
211
  return counts;
@@ -81,16 +213,64 @@ export function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, n
81
213
 
82
214
  /**
83
215
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
84
- * the extensions its code already uses, so a project opens with nothing missing.
216
+ * the extension groups its code already uses, so a project opens with nothing missing. `extensionGroups` are the
217
+ * IDs of the extension groups on offer: the extension IDs, or with a catalog, its group IDs.
85
218
  */
86
- export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[] {
87
- const used = usedGroups(target);
88
- return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
219
+ export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionGroups: readonly string[],
220
+ catalog?: PaletteGroupCatalog): string[] {
221
+ const used = usedGroups(target, catalog);
222
+ return [...standardGroups, ...extensionGroups.filter(id => used.has(id))];
89
223
  }
90
224
 
91
- /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
92
- export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void {
225
+ /**
226
+ * Splits each extension category whose extension declares groups into one category per group, in the catalog's
227
+ * order. A label, separator or button goes with the block after it, or with the last block when none follows.
228
+ */
229
+ export function splitExtensionCategories(tree: Element, catalog: PaletteGroupCatalog): void {
230
+ for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
231
+ const extensionId = category.getAttribute('id');
232
+ const groups = catalog.groups.filter(group => group.extensionId === extensionId);
233
+ if (!extensionId || !groups.some(group => group.declared)) continue;
234
+ const items = new Map<string, Element[]>();
235
+ let pending: Element[] = [];
236
+ let last = extensionId;
237
+ for (const child of Array.from(category.children)) {
238
+ if (child.tagName.toLowerCase() !== 'block') {
239
+ pending.push(child);
240
+ continue;
241
+ }
242
+ last = catalog.groupOf.get(child.getAttribute('type') ?? '') ?? extensionId;
243
+ items.set(last, [...items.get(last) ?? [], ...pending, child]);
244
+ pending = [];
245
+ }
246
+ if (pending.length) items.set(last, [...items.get(last) ?? [], ...pending]);
247
+ let first = true;
248
+ for (const group of groups) {
249
+ const children = items.get(group.id);
250
+ if (!children) continue;
251
+ const part = category.cloneNode(false) as Element;
252
+ part.setAttribute('id', group.id);
253
+ part.setAttribute('name', group.name);
254
+ if (group.color1) part.setAttribute('colour', group.color1);
255
+ if (group.color2) part.setAttribute('secondaryColour', group.color2);
256
+ if (group.menuIconURI) part.setAttribute('iconURI', group.menuIconURI);
257
+ if (!first) part.removeAttribute('showStatusButton');
258
+ first = false;
259
+ part.append(...children);
260
+ category.before(part);
261
+ }
262
+ category.remove();
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
268
+ * With a catalog, an extension that declares groups is first split into a category per group.
269
+ */
270
+ export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>,
271
+ catalog?: PaletteGroupCatalog): void {
93
272
  if (!tree) return;
273
+ if (catalog) splitExtensionCategories(tree, catalog);
94
274
  for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
95
275
  const id = category.getAttribute('id');
96
276
  if (id && !visible.has(id)) category.remove();
@@ -112,7 +292,10 @@ const sameGroups = (left: readonly string[], right: readonly string[]) =>
112
292
  left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
113
293
 
114
294
  export interface PaletteVisibilityStore {
115
- /** The groups the palette shows for the target. */
295
+ /**
296
+ * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
297
+ * IDs, or the group IDs of a catalog when the store was given one.
298
+ */
116
299
  visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
117
300
  /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
118
301
  set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
@@ -130,15 +313,20 @@ export interface PaletteVisibilityStore {
130
313
  }
131
314
 
132
315
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
133
- export function createPaletteVisibilityStore(): PaletteVisibilityStore {
316
+ export function createPaletteVisibilityStore({catalog}: {
317
+ /** The extension groups on offer now, so the default counts the blocks of declared groups. */
318
+ catalog?: () => PaletteGroupCatalog | undefined;
319
+ } = {}): PaletteVisibilityStore {
320
+ const defaults = (target: PaletteTarget, extensionIds: readonly string[]) =>
321
+ defaultVisibleGroups(target, extensionIds, catalog?.());
134
322
  let groups = new Map<string, string[]>();
135
323
  let projectSets: Record<string, SavedGroupSet> = {};
136
324
  return {
137
325
  visible(target, extensionIds) {
138
- return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
326
+ return new Set(groups.get(target.id) ?? defaults(target, extensionIds));
139
327
  },
140
328
  set(target, chosen, extensionIds) {
141
- if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds))) groups.delete(target.id);
329
+ if (sameGroups(chosen, defaults(target, extensionIds))) groups.delete(target.id);
142
330
  else groups.set(target.id, [...chosen]);
143
331
  },
144
332
  copy(from, to) {
@@ -9,6 +9,11 @@ export interface PaletteExtension {
9
9
  id: string;
10
10
  /** What the host knows about the extension; at least its name. */
11
11
  metadata: ExtensionMetadata;
12
+ /**
13
+ * The groups the extension declares, each chosen on its own, in place of the extension. A group whose ID is the
14
+ * extension's holds the blocks no declared group takes.
15
+ */
16
+ groups?: readonly {id: string; name: string; color?: string}[];
12
17
  }
13
18
 
14
19
  export interface PaletteVisibilityChoice {
@@ -56,7 +61,7 @@ const messages = {
56
61
  quick: 'Choose several at once', copyFrom: 'Copy settings from', copy: 'Copy', chooseSprite: 'Choose a sprite',
57
62
  sets: 'Setting shortcuts', addSet: 'Add setting shortcut', setName: 'Shortcut name', add: 'Add',
58
63
  standard: 'Standard block groups', extensions: 'Extension block groups', used: (count: number) => `In use ${count}`,
59
- hiddenInUse: (count: number) => `Hidden and in use: ${count}`, cancel: 'Cancel', confirm: 'Confirm', close: 'Close'
64
+ hiddenInUse: (count: number) => `Hidden and in use: ${count}`, otherBlocks: 'Other blocks', cancel: 'Cancel', confirm: 'Confirm', close: 'Close'
60
65
  },
61
66
  ja: {
62
67
  title: 'パレット内のブロックグループの表示・非表示の設定', sprite: (name: string) => `スプライト「${name}」`, stage: '背景',
@@ -64,7 +69,7 @@ const messages = {
64
69
  quick: 'まとめて選ぶ', copyFrom: '設定のコピー元', copy: 'コピー', chooseSprite: 'スプライトを選ぶ',
65
70
  sets: '設定のショートカット', addSet: '設定のショートカットを追加', setName: 'ショートカットの名前', add: '追加',
66
71
  standard: '標準のブロックグループ', extensions: '機能拡張のブロックグループ', used: (count: number) => `使用中 ${count}`,
67
- hiddenInUse: (count: number) => `非表示中・使用中 ${count} 件`, cancel: 'キャンセル', confirm: '確定', close: '閉じる'
72
+ hiddenInUse: (count: number) => `非表示中・使用中 ${count} 件`, otherBlocks: 'そのほかのブロック', cancel: 'キャンセル', confirm: '確定', close: '閉じる'
68
73
  }
69
74
  };
70
75
  const isJapanese = (locale?: string) => /^ja(?:-|$)/i.test(locale ?? '');
@@ -97,8 +102,13 @@ export class PaletteVisibilityDialog extends React.PureComponent<PaletteVisibili
97
102
  // The stage has no motion blocks.
98
103
  return standardGroups.filter(group => !(this.props.isStage && group === 'motion'));
99
104
  }
105
+ /** Every group on offer, in the order the screen lists them. */
106
+ offered() {
107
+ return [...this.standard(), ...this.props.extensions.flatMap(extension =>
108
+ extension.groups ? extension.groups.map(group => group.id) : [extension.id])];
109
+ }
100
110
  available(groups: readonly string[]) {
101
- const offered = new Set<string>([...this.standard(), ...this.props.extensions.map(extension => extension.id)]);
111
+ const offered = new Set<string>(this.offered());
102
112
  return groups.filter(group => offered.has(group));
103
113
  }
104
114
  toggle(group: string) {
@@ -127,8 +137,7 @@ export class PaletteVisibilityDialog extends React.PureComponent<PaletteVisibili
127
137
  const taken = new Set([...this.props.sets, ...this.state.addedSets].map(set => set.id));
128
138
  let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'set';
129
139
  for (let index = 2; taken.has(id); index++) id = `${id.replace(/-\d+$/, '')}-${index}`;
130
- const groups = [...this.standard(), ...this.props.extensions.map(extension => extension.id)]
131
- .filter(group => this.state.shown.has(group));
140
+ const groups = this.offered().filter(group => this.state.shown.has(group));
132
141
  this.setState(({addedSets}) => ({addedSets: [...addedSets, {id, name, groups}], naming: false, setName: ''}));
133
142
  }
134
143
  /**
@@ -145,8 +154,7 @@ export class PaletteVisibilityDialog extends React.PureComponent<PaletteVisibili
145
154
  return source ? this.available(source.groups) : [];
146
155
  }
147
156
  apply() {
148
- const order = [...this.standard(), ...this.props.extensions.map(extension => extension.id)];
149
- this.props.onApply({groups: order.filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets});
157
+ this.props.onApply({groups: this.offered().filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets});
150
158
  }
151
159
  render() {
152
160
  const {locale, targetName, isStage, used, extensions, onCancel} = this.props;
@@ -250,7 +258,29 @@ export class PaletteVisibilityDialog extends React.PureComponent<PaletteVisibili
250
258
  <h3>{text.extensions}</h3>
251
259
  <div className="twextsec-review">
252
260
  <ul className="twextsec-rows">
253
- {extensions.map(extension => (
261
+ {extensions.map(extension => extension.groups ? (
262
+ <ExtensionRow
263
+ key={extension.id}
264
+ metadata={extension.metadata}
265
+ ids={[extension.id]}
266
+ locale={locale}
267
+ itemProps={{'data-extension': extension.id}}
268
+ >
269
+ <div className="tw-palette-visibility-extension-groups">
270
+ {extension.groups.map(group => (
271
+ <label key={group.id} data-group={group.id}
272
+ data-highlighted={highlighted(group.id)}>
273
+ <input type="checkbox" checked={shown.has(group.id)}
274
+ onChange={() => this.toggle(group.id)} />
275
+ <span className="tw-palette-visibility-swatch" aria-hidden="true"
276
+ style={{color: group.color}}>●</span>
277
+ {group.id === extension.id ? text.otherBlocks : group.name}
278
+ {usedBadge(group.id)}
279
+ </label>
280
+ ))}
281
+ </div>
282
+ </ExtensionRow>
283
+ ) : (
254
284
  <ExtensionRow
255
285
  key={extension.id}
256
286
  metadata={extension.metadata}
package/src/styles.css CHANGED
@@ -759,12 +759,21 @@
759
759
  gap: 0.35rem 0.75rem;
760
760
  }
761
761
 
762
- .tw-palette-visibility-standard label {
762
+ .tw-palette-visibility-standard label,
763
+ .tw-palette-visibility-extension-groups label {
763
764
  display: flex;
764
765
  align-items: center;
765
766
  gap: 0.35rem;
766
767
  }
767
768
 
769
+ /* The groups one extension declares, chosen one by one inside its row. */
770
+ .tw-palette-visibility-extension-groups {
771
+ display: grid;
772
+ grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
773
+ gap: 0.25rem 0.75rem;
774
+ margin-top: 0.4rem;
775
+ }
776
+
768
777
  .tw-palette-visibility-used {
769
778
  font-size: 0.75rem;
770
779
  color: var(--ui-warning, #b45309);
@@ -957,14 +966,17 @@
957
966
  }
958
967
 
959
968
  /* A group under the pointer, and the groups a shortcut or copy source under the pointer would choose. */
960
- .tw-palette-visibility-standard label {
969
+ .tw-palette-visibility-standard label,
970
+ .tw-palette-visibility-extension-groups label {
961
971
  padding: 0.15rem 0.3rem;
962
972
  border-radius: 0.3rem;
963
973
  }
964
974
 
965
975
  .tw-palette-visibility-standard label:hover,
966
976
  .tw-palette-visibility-standard label[data-highlighted],
967
- .tw-palette-visibility .twextsec-row:hover,
977
+ .tw-palette-visibility-extension-groups label:hover,
978
+ .tw-palette-visibility-extension-groups label[data-highlighted],
979
+ .tw-palette-visibility .twextsec-row:not([data-extension]):hover,
968
980
  .tw-palette-visibility .twextsec-row[data-highlighted] {
969
981
  background: color-mix(in srgb, var(--looks-secondary, #7951d1) 16%, transparent);
970
982
  }