@kubohiroya/turbowarp-plus-editor-code-views 0.15.0 → 0.16.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,8 +18,8 @@ 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)` で木を整え、`prepareGroupedToolboxTree(tree, {catalog, visible})` は、機能拡張が宣言したグループの入れ子化と表示するグループの絞り込みを含めて、これを一度に行う。`hasCategoryGroups(tree)` は木が category を入れ子にしているかを返す。`attachPaletteCategoryGroups(menu, options)` で子ブロックパレットを開く。その `selectionTarget(id)` は、自分のブロックを持たないグループの代わりに選ぶ category を返し、`syncButtons(openId)` はグループのアイコンの状態を付け直す。`reorder: true` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
22
- | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ |
21
+ | `./palette-category-groups` | ツールボックスで別の category を含む category をグループとして表示する。アイコンをクリックすると、要素を並べた子ブロックパレットを影つきで重ねて開く(横配置のパレットではアイコンの右に横並び、縦配置では下に縦並び)。外側をクリックすると閉じる。Scratch Blocks は入れ子の category を捨てるので、`flattenCategoryGroups(tree)` と `filterGroupedToolboxTree(tree, groups, filter)` で木を整え、`prepareGroupedToolboxTree(tree, {catalog, visible})` は、機能拡張が宣言したグループの入れ子化と表示するグループの絞り込みを含めて、これを一度に行う。`hasCategoryGroups(tree)` は木が category を入れ子にしているかを返す。`attachPaletteCategoryGroups(menu, options)` で子ブロックパレットを開く。その `selectionTarget(id)` は、自分のブロックを持たないグループの代わりに選ぶ category を返し、`syncButtons(openId)` はグループのアイコンの状態を付け直す。`reorder: true` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち(`order` を渡せば、プロジェクトと一緒に保存するパレットの設定に保つ)、`prepare(tree, options)` はツールボックスをその順番で描かせ、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
22
+ | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ。ストアの `order`(`createPaletteOrder`)は、パレットのカテゴリーと各グループの要素を並べ替えた順番を保ち、同じ設定と一緒に保存する |
23
23
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
24
24
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
25
25
  | `./clean-up-comments` | 「きれいにする」でコメントをスクリプトについて動かす。ブロックのコメントはブロックとの相対位置を保ち、コメントを含めたスクリプト同士が重ならないようにし、スクリプトに重なるワークスペースのコメントはスクリプトの横へ移す(`installCleanUpComments(ScratchBlocks)`) |
package/README.md CHANGED
@@ -17,9 +17,9 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
17
17
  | `./variable-merge` | Merges a variable or list into another one on rename, and moves one between this sprite and all sprites from the palette |
18
18
  | `./target-combobox` | The target picker of a code window |
19
19
  | `./detached-block-palette` | The block palette in its own window |
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 |
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. The store's `order` (`createPaletteOrder`) keeps the order the palette's categories and each group's members were dragged into, saved with the same settings |
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; `prepareGroupedToolboxTree(tree, {catalog, visible})` does both in one step, also nesting the groups extensions declare and keeping only the groups to show, and `hasCategoryGroups(tree)` tells whether a tree nests categories. `attachPaletteCategoryGroups(menu, options)` opens the child palettes; its `selectionTarget(id)` gives the category to select for a group without blocks of its own, and `syncButtons(openId)` marks the groups' icons. With `reorder: true`, a long press on a member of a child palette drags it among the members of the same group (not to another group or level); the order is kept while the palette is drawn again, and `arrange(categories, rank)` orders the toolbox's categories to match, each group followed by its members. `splitExtensionCategories(tree, catalog, {nested: true})` makes an extension that declares groups such a group |
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; `prepareGroupedToolboxTree(tree, {catalog, visible})` does both in one step, also nesting the groups extensions declare and keeping only the groups to show, and `hasCategoryGroups(tree)` tells whether a tree nests categories. `attachPaletteCategoryGroups(menu, options)` opens the child palettes; its `selectionTarget(id)` gives the category to select for a group without blocks of its own, and `syncButtons(openId)` marks the groups' icons. With `reorder: true`, a long press on a member of a child palette drags it among the members of the same group (not to another group or level); the order is kept while the palette is drawn again (in the `order` given, such as the palette settings saved with the project), `prepare(tree, options)` draws the toolbox in it, and `arrange(categories, rank)` orders the toolbox's categories to match, each group followed by its members. `splitExtensionCategories(tree, catalog, {nested: true})` makes an extension that declares groups such a group |
23
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 |
24
24
  | `./block-number-input` | Converts full-width digits and signs typed into number arguments to half-width |
25
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)`) |
@@ -1,4 +1,4 @@
1
- import type { PaletteGroupCatalog } from './palette-category-visibility.ts';
1
+ import type { PaletteGroupCatalog, PaletteOrder } from './palette-category-visibility.ts';
2
2
  /**
3
3
  * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
4
4
  * reads only the top-level categories and drops nested ones, so the tree is flattened before it is drawn:
@@ -62,8 +62,21 @@ export interface PaletteCategoryGroupsOptions {
62
62
  reorder?: boolean;
63
63
  /** Called after the members of a group were reordered, so the host can lay out its categories with `arrange`. */
64
64
  onReorder?(): void;
65
+ /**
66
+ * Where the members' order is kept, such as the palette settings saved with the project. By default the order
67
+ * lasts while the palette does.
68
+ */
69
+ order?(): Pick<PaletteOrder, 'members' | 'setMembers'> | undefined;
65
70
  }
66
71
  export interface PaletteCategoryGroupsController {
72
+ /**
73
+ * Prepares a toolbox tree as {@link prepareGroupedToolboxTree} does, and puts each group's members in the order
74
+ * they were dragged into, so the palette is drawn in that order. Pass the groups returned to `update`.
75
+ */
76
+ prepare(tree: Element, options?: {
77
+ catalog?: PaletteGroupCatalog;
78
+ visible?: ReadonlySet<string> | null;
79
+ }): PaletteGroups;
67
80
  /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
68
81
  update(groups: PaletteGroups): void;
69
82
  isGroup(id: string): boolean;
@@ -1,4 +1,5 @@
1
1
  import { filterToolboxTree, splitExtensionCategories } from "./palette-category-visibility.js";
2
+ import { createPaletteOrder } from "./palette-category-visibility.js";
2
3
  import { attachPaletteCategoryReorder } from "./palette-category-reorder.js";
3
4
  /**
4
5
  * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
@@ -133,19 +134,28 @@ export const attachPaletteCategoryGroups = (menu, options) => {
133
134
  // The open child palettes, outermost first, with the icon each opened from.
134
135
  const stack = [];
135
136
  // The order members were dragged into, by group, kept while the toolbox is drawn again.
136
- const memberOrder = new Map();
137
- const applyMemberOrder = () => {
138
- for (const [id, members] of groups.members) {
139
- const saved = memberOrder.get(id);
137
+ const ownOrder = createPaletteOrder();
138
+ const memberOrder = () => options.order?.() ?? ownOrder;
139
+ const applyMemberOrder = (target) => {
140
+ for (const [id, members] of target.members) {
141
+ const saved = memberOrder().members(id);
140
142
  if (!saved)
141
143
  continue;
142
144
  const rank = (member) => {
143
145
  const index = saved.indexOf(member);
144
146
  return index < 0 ? saved.length : index;
145
147
  };
146
- groups.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
148
+ target.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
147
149
  }
148
150
  };
151
+ const useGroups = (next) => {
152
+ groups = next;
153
+ applyMemberOrder(groups);
154
+ parentOf.clear();
155
+ for (const [id, members] of groups.members)
156
+ for (const member of members)
157
+ parentOf.set(member, id);
158
+ };
149
159
  let selected = null;
150
160
  const categoryById = (id) => options.categories().find(category => category.id_ === id);
151
161
  const topLevelOf = (id) => {
@@ -288,7 +298,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
288
298
  const reorder = options.reorder ? attachPaletteCategoryReorder(popup, () => entries, (from, to) => {
289
299
  const order = members.map(member => member.id_);
290
300
  order.splice(to, 0, order.splice(from, 1)[0]);
291
- memberOrder.set(group.id_, order);
301
+ memberOrder().setMembers(group.id_, order);
292
302
  groups.members.set(group.id_, order);
293
303
  open(group, anchor, depth, false);
294
304
  options.onReorder?.();
@@ -348,14 +358,41 @@ export const attachPaletteCategoryGroups = (menu, options) => {
348
358
  menu.addEventListener('scroll', close, { signal: events.signal });
349
359
  doc.defaultView.addEventListener('resize', close, { signal: events.signal });
350
360
  return {
361
+ prepare(tree, prepareOptions) {
362
+ const prepared = prepareGroupedToolboxTree(tree, prepareOptions);
363
+ close();
364
+ useGroups(prepared);
365
+ // Each group is followed by its members, each with its own members, in their order.
366
+ const elements = Array.from(tree.children).filter(isCategory);
367
+ const byId = new Map(elements.map(element => [element.getAttribute('id'), element]));
368
+ const ordered = [];
369
+ const visit = (element) => {
370
+ ordered.push(element);
371
+ for (const member of groups.members.get(element.getAttribute('id')) ?? []) {
372
+ const child = byId.get(member);
373
+ if (child)
374
+ visit(child);
375
+ }
376
+ };
377
+ for (const element of elements)
378
+ if (!element.hasAttribute(groupParentAttribute))
379
+ visit(element);
380
+ const slots = elements.map(element => {
381
+ const slot = tree.ownerDocument.createComment('palette-category');
382
+ element.replaceWith(slot);
383
+ return slot;
384
+ });
385
+ slots.forEach((slot, index) => {
386
+ if (ordered[index])
387
+ slot.replaceWith(ordered[index]);
388
+ else
389
+ slot.remove();
390
+ });
391
+ return prepared;
392
+ },
351
393
  update(next) {
352
394
  close();
353
- groups = next;
354
- applyMemberOrder();
355
- parentOf.clear();
356
- for (const [id, members] of groups.members)
357
- for (const member of members)
358
- parentOf.set(member, id);
395
+ useGroups(next);
359
396
  for (const category of options.categories()) {
360
397
  const member = parentOf.has(category.id_);
361
398
  const row = category.item_.parentElement;
@@ -128,7 +128,31 @@ export interface SavedPaletteVisibility {
128
128
  groups: string[];
129
129
  }>;
130
130
  sets?: Record<string, SavedGroupSet>;
131
+ order?: SavedPaletteOrder;
131
132
  }
133
+ /** The order the palette's categories were dragged into: the top level, and the members of each group, by ID. */
134
+ export interface SavedPaletteOrder {
135
+ categories?: string[];
136
+ groups?: Record<string, string[]>;
137
+ }
138
+ /** The order the palette's categories were dragged into, for the whole project. */
139
+ export interface PaletteOrder {
140
+ /** The top-level categories, by ID, in order. Categories not listed follow them. */
141
+ categories(): string[];
142
+ setCategories(ids: readonly string[]): void;
143
+ /** A group's members, by ID, in order, or nothing when they were never reordered. */
144
+ members(groupId: string): string[] | undefined;
145
+ setMembers(groupId: string, ids: readonly string[]): void;
146
+ /** The order to save, or nothing when nothing was reordered. */
147
+ capture(): SavedPaletteOrder | undefined;
148
+ /** Takes a saved order. A value that is not one leaves the palette in its own order. */
149
+ apply(value: unknown): void;
150
+ reset(): void;
151
+ }
152
+ /** Keeps the order of the palette's categories. `onChange` is called when the user reorders them. */
153
+ export declare function createPaletteOrder({ onChange }?: {
154
+ onChange?(): void;
155
+ }): PaletteOrder;
132
156
  export interface PaletteVisibilityStore {
133
157
  /**
134
158
  * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
@@ -148,11 +172,15 @@ export interface PaletteVisibilityStore {
148
172
  apply(value: unknown, targets: readonly PaletteTarget[]): void;
149
173
  /** Forgets every setting, for a project without any. */
150
174
  reset(): void;
175
+ /** The order of the palette's categories, saved and loaded with the other settings. */
176
+ order: PaletteOrder;
151
177
  }
152
178
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
153
- export declare function createPaletteVisibilityStore({ catalog }?: {
179
+ export declare function createPaletteVisibilityStore({ catalog, onOrderChange }?: {
154
180
  /** The extension groups on offer now, so the default counts the blocks of declared groups. */
155
181
  catalog?: () => PaletteGroupCatalog | undefined;
182
+ /** Called when the user reorders the palette's categories, so the project can be marked as changed. */
183
+ onOrderChange?(): void;
156
184
  }): PaletteVisibilityStore;
157
185
  /** The menu item that opens the group settings. */
158
186
  export declare const paletteVisibilityMenuLabel: (locale: string) => "ブロックグループの表示・非表示の設定" | "Show or hide block groups";
@@ -261,10 +261,55 @@ export function filterToolboxTree(tree, visible, catalog) {
261
261
  }
262
262
  /** The screen-state slice the settings are saved as. Sprites are named as the tab layout names them. */
263
263
  export const paletteScreenStateKey = 'blockPalette';
264
+ /** Keeps the order of the palette's categories. `onChange` is called when the user reorders them. */
265
+ export function createPaletteOrder({ onChange } = {}) {
266
+ let categories = [];
267
+ let groups = new Map();
268
+ return {
269
+ categories: () => [...categories],
270
+ setCategories(ids) {
271
+ categories = [...ids];
272
+ onChange?.();
273
+ },
274
+ members: groupId => groups.has(groupId) ? [...groups.get(groupId)] : undefined,
275
+ setMembers(groupId, ids) {
276
+ groups.set(groupId, [...ids]);
277
+ onChange?.();
278
+ },
279
+ capture() {
280
+ const saved = {};
281
+ if (categories.length)
282
+ saved.categories = [...categories];
283
+ if (groups.size)
284
+ saved.groups = Object.fromEntries([...groups].map(([id, ids]) => [id, [...ids]]));
285
+ return saved.categories || saved.groups ? saved : undefined;
286
+ },
287
+ apply(value) {
288
+ categories = [];
289
+ groups = new Map();
290
+ if (!value || typeof value !== 'object')
291
+ return;
292
+ const saved = value;
293
+ categories = strings(saved.categories) ?? [];
294
+ if (saved.groups && typeof saved.groups === 'object' && !Array.isArray(saved.groups)) {
295
+ for (const [id, ids] of Object.entries(saved.groups)) {
296
+ const members = strings(ids);
297
+ if (members)
298
+ groups.set(id, members);
299
+ }
300
+ }
301
+ },
302
+ reset() {
303
+ categories = [];
304
+ groups = new Map();
305
+ }
306
+ };
307
+ }
264
308
  const strings = (value) => Array.isArray(value) && value.every(item => typeof item === 'string') ? [...value] : undefined;
265
309
  const sameGroups = (left, right) => left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
266
310
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
267
- export function createPaletteVisibilityStore({ catalog } = {}) {
311
+ export function createPaletteVisibilityStore({ catalog, onOrderChange } = {}) {
312
+ const order = createPaletteOrder({ onChange: onOrderChange });
268
313
  const defaults = (target, extensionIds) => defaultVisibleGroups(target, extensionIds, catalog?.());
269
314
  let groups = new Map();
270
315
  let projectSets = {};
@@ -304,14 +349,19 @@ export function createPaletteVisibilityStore({ catalog } = {}) {
304
349
  saved.sprites = sprites;
305
350
  if (Object.keys(projectSets).length)
306
351
  saved.sets = structuredClone(projectSets);
307
- return saved.stage || saved.sprites || saved.sets ? saved : undefined;
352
+ const arranged = order.capture();
353
+ if (arranged)
354
+ saved.order = arranged;
355
+ return saved.stage || saved.sprites || saved.sets || saved.order ? saved : undefined;
308
356
  },
309
357
  apply(value, targets) {
310
358
  groups = new Map();
311
359
  projectSets = {};
360
+ order.reset();
312
361
  if (!value || typeof value !== 'object' || value.version !== 1)
313
362
  return;
314
363
  const saved = value;
364
+ order.apply(saved.order);
315
365
  const setting = (entry) => entry && typeof entry === 'object' ?
316
366
  strings(entry.groups) : undefined;
317
367
  const sprites = saved.sprites && typeof saved.sprites === 'object' ? saved.sprites : {};
@@ -333,7 +383,9 @@ export function createPaletteVisibilityStore({ catalog } = {}) {
333
383
  reset() {
334
384
  groups = new Map();
335
385
  projectSets = {};
336
- }
386
+ order.reset();
387
+ },
388
+ order
337
389
  };
338
390
  }
339
391
  /** The menu item that opens the group settings. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.15.0",
3
+ "version": "0.16.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",
@@ -1,5 +1,6 @@
1
1
  import {filterToolboxTree, splitExtensionCategories} from './palette-category-visibility.ts';
2
- import type {PaletteGroupCatalog} from './palette-category-visibility.ts';
2
+ import {createPaletteOrder} from './palette-category-visibility.ts';
3
+ import type {PaletteGroupCatalog, PaletteOrder} from './palette-category-visibility.ts';
3
4
  import {attachPaletteCategoryReorder} from './palette-category-reorder.ts';
4
5
 
5
6
  /**
@@ -152,9 +153,19 @@ export interface PaletteCategoryGroupsOptions {
152
153
  reorder?: boolean;
153
154
  /** Called after the members of a group were reordered, so the host can lay out its categories with `arrange`. */
154
155
  onReorder?(): void;
156
+ /**
157
+ * Where the members' order is kept, such as the palette settings saved with the project. By default the order
158
+ * lasts while the palette does.
159
+ */
160
+ order?(): Pick<PaletteOrder, 'members' | 'setMembers'> | undefined;
155
161
  }
156
162
 
157
163
  export interface PaletteCategoryGroupsController {
164
+ /**
165
+ * Prepares a toolbox tree as {@link prepareGroupedToolboxTree} does, and puts each group's members in the order
166
+ * they were dragged into, so the palette is drawn in that order. Pass the groups returned to `update`.
167
+ */
168
+ prepare(tree: Element, options?: {catalog?: PaletteGroupCatalog; visible?: ReadonlySet<string> | null}): PaletteGroups;
158
169
  /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
159
170
  update(groups: PaletteGroups): void;
160
171
  isGroup(id: string): boolean;
@@ -199,18 +210,25 @@ export const attachPaletteCategoryGroups = (menu: HTMLElement, options: PaletteC
199
210
  // The open child palettes, outermost first, with the icon each opened from.
200
211
  const stack: {id: string; anchor: HTMLElement; popup: HTMLElement; reorder?: {dispose(): void}}[] = [];
201
212
  // The order members were dragged into, by group, kept while the toolbox is drawn again.
202
- const memberOrder = new Map<string, string[]>();
203
- const applyMemberOrder = () => {
204
- for (const [id, members] of groups.members) {
205
- const saved = memberOrder.get(id);
213
+ const ownOrder = createPaletteOrder();
214
+ const memberOrder = () => options.order?.() ?? ownOrder;
215
+ const applyMemberOrder = (target: PaletteGroups) => {
216
+ for (const [id, members] of target.members) {
217
+ const saved = memberOrder().members(id);
206
218
  if (!saved) continue;
207
219
  const rank = (member: string) => {
208
220
  const index = saved.indexOf(member);
209
221
  return index < 0 ? saved.length : index;
210
222
  };
211
- groups.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
223
+ target.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
212
224
  }
213
225
  };
226
+ const useGroups = (next: PaletteGroups) => {
227
+ groups = next;
228
+ applyMemberOrder(groups);
229
+ parentOf.clear();
230
+ for (const [id, members] of groups.members) for (const member of members) parentOf.set(member, id);
231
+ };
214
232
  let selected: string | null = null;
215
233
 
216
234
  const categoryById = (id: string) => options.categories().find(category => category.id_ === id);
@@ -348,7 +366,7 @@ export const attachPaletteCategoryGroups = (menu: HTMLElement, options: PaletteC
348
366
  (from, to) => {
349
367
  const order = members.map(member => member.id_);
350
368
  order.splice(to, 0, order.splice(from, 1)[0]);
351
- memberOrder.set(group.id_, order);
369
+ memberOrder().setMembers(group.id_, order);
352
370
  groups.members.set(group.id_, order);
353
371
  open(group, anchor, depth, false);
354
372
  options.onReorder?.();
@@ -403,12 +421,36 @@ export const attachPaletteCategoryGroups = (menu: HTMLElement, options: PaletteC
403
421
  doc.defaultView!.addEventListener('resize', close, {signal: events.signal});
404
422
 
405
423
  return {
424
+ prepare(tree, prepareOptions) {
425
+ const prepared = prepareGroupedToolboxTree(tree, prepareOptions);
426
+ close();
427
+ useGroups(prepared);
428
+ // Each group is followed by its members, each with its own members, in their order.
429
+ const elements = Array.from(tree.children).filter(isCategory);
430
+ const byId = new Map(elements.map(element => [element.getAttribute('id')!, element]));
431
+ const ordered: Element[] = [];
432
+ const visit = (element: Element) => {
433
+ ordered.push(element);
434
+ for (const member of groups.members.get(element.getAttribute('id')!) ?? []) {
435
+ const child = byId.get(member);
436
+ if (child) visit(child);
437
+ }
438
+ };
439
+ for (const element of elements) if (!element.hasAttribute(groupParentAttribute)) visit(element);
440
+ const slots = elements.map(element => {
441
+ const slot = tree.ownerDocument.createComment('palette-category');
442
+ element.replaceWith(slot);
443
+ return slot;
444
+ });
445
+ slots.forEach((slot, index) => {
446
+ if (ordered[index]) slot.replaceWith(ordered[index]);
447
+ else slot.remove();
448
+ });
449
+ return prepared;
450
+ },
406
451
  update(next) {
407
452
  close();
408
- groups = next;
409
- applyMemberOrder();
410
- parentOf.clear();
411
- for (const [id, members] of groups.members) for (const member of members) parentOf.set(member, id);
453
+ useGroups(next);
412
454
  for (const category of options.categories()) {
413
455
  const member = parentOf.has(category.id_);
414
456
  const row = category.item_.parentElement;
@@ -331,6 +331,69 @@ export interface SavedPaletteVisibility {
331
331
  stage?: {groups: string[]};
332
332
  sprites?: Record<string, {groups: string[]}>;
333
333
  sets?: Record<string, SavedGroupSet>;
334
+ order?: SavedPaletteOrder;
335
+ }
336
+
337
+ /** The order the palette's categories were dragged into: the top level, and the members of each group, by ID. */
338
+ export interface SavedPaletteOrder {
339
+ categories?: string[];
340
+ groups?: Record<string, string[]>;
341
+ }
342
+
343
+ /** The order the palette's categories were dragged into, for the whole project. */
344
+ export interface PaletteOrder {
345
+ /** The top-level categories, by ID, in order. Categories not listed follow them. */
346
+ categories(): string[];
347
+ setCategories(ids: readonly string[]): void;
348
+ /** A group's members, by ID, in order, or nothing when they were never reordered. */
349
+ members(groupId: string): string[] | undefined;
350
+ setMembers(groupId: string, ids: readonly string[]): void;
351
+ /** The order to save, or nothing when nothing was reordered. */
352
+ capture(): SavedPaletteOrder | undefined;
353
+ /** Takes a saved order. A value that is not one leaves the palette in its own order. */
354
+ apply(value: unknown): void;
355
+ reset(): void;
356
+ }
357
+
358
+ /** Keeps the order of the palette's categories. `onChange` is called when the user reorders them. */
359
+ export function createPaletteOrder({onChange}: {onChange?(): void} = {}): PaletteOrder {
360
+ let categories: string[] = [];
361
+ let groups = new Map<string, string[]>();
362
+ return {
363
+ categories: () => [...categories],
364
+ setCategories(ids) {
365
+ categories = [...ids];
366
+ onChange?.();
367
+ },
368
+ members: groupId => groups.has(groupId) ? [...groups.get(groupId)!] : undefined,
369
+ setMembers(groupId, ids) {
370
+ groups.set(groupId, [...ids]);
371
+ onChange?.();
372
+ },
373
+ capture() {
374
+ const saved: SavedPaletteOrder = {};
375
+ if (categories.length) saved.categories = [...categories];
376
+ if (groups.size) saved.groups = Object.fromEntries([...groups].map(([id, ids]) => [id, [...ids]]));
377
+ return saved.categories || saved.groups ? saved : undefined;
378
+ },
379
+ apply(value) {
380
+ categories = [];
381
+ groups = new Map();
382
+ if (!value || typeof value !== 'object') return;
383
+ const saved = value as Record<string, unknown>;
384
+ categories = strings(saved.categories) ?? [];
385
+ if (saved.groups && typeof saved.groups === 'object' && !Array.isArray(saved.groups)) {
386
+ for (const [id, ids] of Object.entries(saved.groups as Record<string, unknown>)) {
387
+ const members = strings(ids);
388
+ if (members) groups.set(id, members);
389
+ }
390
+ }
391
+ },
392
+ reset() {
393
+ categories = [];
394
+ groups = new Map();
395
+ }
396
+ };
334
397
  }
335
398
 
336
399
  const strings = (value: unknown): string[] | undefined =>
@@ -357,13 +420,18 @@ export interface PaletteVisibilityStore {
357
420
  apply(value: unknown, targets: readonly PaletteTarget[]): void;
358
421
  /** Forgets every setting, for a project without any. */
359
422
  reset(): void;
423
+ /** The order of the palette's categories, saved and loaded with the other settings. */
424
+ order: PaletteOrder;
360
425
  }
361
426
 
362
427
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
363
- export function createPaletteVisibilityStore({catalog}: {
428
+ export function createPaletteVisibilityStore({catalog, onOrderChange}: {
364
429
  /** The extension groups on offer now, so the default counts the blocks of declared groups. */
365
430
  catalog?: () => PaletteGroupCatalog | undefined;
431
+ /** Called when the user reorders the palette's categories, so the project can be marked as changed. */
432
+ onOrderChange?(): void;
366
433
  } = {}): PaletteVisibilityStore {
434
+ const order = createPaletteOrder({onChange: onOrderChange});
367
435
  const defaults = (target: PaletteTarget, extensionIds: readonly string[]) =>
368
436
  defaultVisibleGroups(target, extensionIds, catalog?.());
369
437
  let groups = new Map<string, string[]>();
@@ -395,13 +463,17 @@ export function createPaletteVisibilityStore({catalog}: {
395
463
  }
396
464
  if (Object.keys(sprites).length) saved.sprites = sprites;
397
465
  if (Object.keys(projectSets).length) saved.sets = structuredClone(projectSets);
398
- return saved.stage || saved.sprites || saved.sets ? saved : undefined;
466
+ const arranged = order.capture();
467
+ if (arranged) saved.order = arranged;
468
+ return saved.stage || saved.sprites || saved.sets || saved.order ? saved : undefined;
399
469
  },
400
470
  apply(value, targets) {
401
471
  groups = new Map();
402
472
  projectSets = {};
473
+ order.reset();
403
474
  if (!value || typeof value !== 'object' || (value as {version?: unknown}).version !== 1) return;
404
475
  const saved = value as Record<string, unknown>;
476
+ order.apply(saved.order);
405
477
  const setting = (entry: unknown) => entry && typeof entry === 'object' ?
406
478
  strings((entry as {groups?: unknown}).groups) : undefined;
407
479
  const sprites = saved.sprites && typeof saved.sprites === 'object' ? saved.sprites as Record<string, unknown> : {};
@@ -421,7 +493,9 @@ export function createPaletteVisibilityStore({catalog}: {
421
493
  reset() {
422
494
  groups = new Map();
423
495
  projectSets = {};
424
- }
496
+ order.reset();
497
+ },
498
+ order
425
499
  };
426
500
  }
427
501