@kubohiroya/turbowarp-plus-editor-code-views 0.16.0 → 0.18.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
@@ -16,9 +16,9 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
16
16
  | `./variable-references` | 編集中の対象に絞った変数の参照 |
17
17
  | `./variable-merge` | 名前の変更で変数・リストを既存のものに統合し、パレットから「このスプライトのみ」と「すべてのスプライト用」を切り替える |
18
18
  | `./target-combobox` | コードの窓の対象の選択 |
19
- | `./detached-block-palette` | 別窓のブロックパレット |
19
+ | `./detached-block-palette` | 別窓のブロックパレット。パレットの `grouping` を渡すと、パレットと同じくグループを子ブロックパレットで開き、固定できる |
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` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち(`order` を渡せば、プロジェクトと一緒に保存するパレットの設定に保つ)、`prepare(tree, options)` はツールボックスをその順番で描かせ、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
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 をそれに合わせて、グループの後にその要素が続くように並べる。子ブロックパレットの右上にはピンがあり、押すとグループの要素を、そのグループを表示していたパレットのそのグループの直後に広げて固定する。固定したグループのアイコンにはピンが付き、押すと元のようにたたむ。固定は同じ `order` に保つので、それを渡したパレット同士は揃う。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
22
22
  | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ。ストアの `order`(`createPaletteOrder`)は、パレットのカテゴリーと各グループの要素を並べ替えた順番を保ち、同じ設定と一緒に保存する |
23
23
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
24
24
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
@@ -45,6 +45,8 @@ Editor は GUI の React 16 にこれらを描画するので、React 16.14 以
45
45
 
46
46
  `npm test` でビルドし、単体テストを実行し、React 16.14 より新しい API を使っていないことを確かめる。
47
47
 
48
+ `npm run test:browser` は、最小のエディター実行環境(`@kubohiroya/turbowarp-plus-editor-test-runtime`)で、Editor と同じ VM と Scratch Blocks を使い、パレットのグループを Chromium で操作して確かめる(子ブロックパレット、ピン、並べ替え、別窓のパレット)。`TWPE_CHROME_EXECUTABLE` を指定すると、Playwright のものの代わりにその Chromium を使う。
49
+
48
50
  ## ライセンス
49
51
 
50
52
  MPL-2.0。turbowarp-plus-editor の `packages/editor-views` と `packages/editor-ui` から移したコードで、同じ作者が書いたもの。移すときに GPL-3.0 から MPL-2.0 にした。由来の監査は [turbowarp-plus-packages の移行計画](https://github.com/kubohiroya/turbowarp-plus-packages/blob/main/docs/editor-migration-plan.ja.md)の「由来の監査(7b)」にある。
package/README.md CHANGED
@@ -16,10 +16,10 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
16
16
  | `./variable-references` | Variable references scoped to the edited target |
17
17
  | `./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
- | `./detached-block-palette` | The block palette in its own window |
19
+ | `./detached-block-palette` | The block palette in its own window. Given the palette's `grouping`, it opens groups in child palettes and pins them as the palette does |
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. 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 (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 |
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 group drags it among the members of the same group, in the group's child palette or where a pinned group shows its members (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. A child palette has a pin at its top right: pinning the group shows its members in the palette that showed the group, right after it, and the pinned group's icon shows a pin that folds them back. The pins are kept in the same `order`, so palettes given it follow each other. `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)`) |
@@ -45,6 +45,8 @@ React 16.14 or later is supported, because the Editor mounts these views in the
45
45
 
46
46
  Run `npm test` to build the package, run the unit tests, and check that the sources use no React API newer than 16.14.
47
47
 
48
+ Run `npm run test:browser` to drive the palette's groups in Chromium with the Editor's own VM and Scratch Blocks, through the minimal editor runtime (`@kubohiroya/turbowarp-plus-editor-test-runtime`): child palettes, pins, reordering and the detached palette. `TWPE_CHROME_EXECUTABLE` names a Chromium to use instead of Playwright's own.
49
+
48
50
  ## License
49
51
 
50
52
  MPL-2.0. This code moved here from `packages/editor-views` and `packages/editor-ui` in turbowarp-plus-editor. The same author wrote it, and it changed from GPL-3.0 to MPL-2.0 in the move. The provenance audit is in the "由来の監査(7b)" section of the [migration plan in turbowarp-plus-packages](https://github.com/kubohiroya/turbowarp-plus-packages/blob/main/docs/editor-migration-plan.ja.md).
@@ -1,5 +1,7 @@
1
1
  import React from 'react';
2
2
  import { IconMenuButton } from '@kubohiroya/turbowarp-plus-editor-windows';
3
+ import { attachPaletteCategoryGroups } from "./palette-category-groups.js";
4
+ const noGroups = { members: new Map(), withOwnContents: new Set() };
3
5
  const horizontalLayoutIconPath = 'M2 5h5v6H2zm7 0h5v6H9z';
4
6
  const verticalLayoutIconPath = 'M5 2h6v5H5zm0 7h6v5H5z';
5
7
  function BlockPreview({ svg }) {
@@ -25,6 +27,45 @@ export default function Palette({ source, locale, categoryIcons, close, startDra
25
27
  const selected = categories.find(category => category.id === categoryId) ?? categories[0];
26
28
  const selectedId = selected?.id;
27
29
  React.useLayoutEffect(() => source.subscribe(refresh), [source]);
30
+ // The editor's groups open in child palettes here too, and pinning one shows its members in this list.
31
+ const list = React.useRef(null);
32
+ const groupsControl = React.useRef(null);
33
+ const layout = React.useRef(vertical);
34
+ layout.current = vertical;
35
+ const grouping = source.grouping?.();
36
+ // Opening a child palette or pinning a group only draws the list again; the blocks shown stay as they are.
37
+ const [, redraw] = React.useReducer(value => value + 1, 0);
38
+ React.useLayoutEffect(() => {
39
+ const menu = list.current;
40
+ const controller = attachPaletteCategoryGroups(menu, {
41
+ categories: () => source.categories().map(({ id, label }) => ({
42
+ id_: id, name_: label, setSelected() { },
43
+ item_: menu.querySelector(`button[data-category-id="${CSS.escape(id)}"]`)
44
+ })).filter(category => category.item_),
45
+ // A row of categories, when the blocks are laid out below them.
46
+ horizontal: () => layout.current,
47
+ choose: category => {
48
+ setCategory(category.id_);
49
+ setTooltip(null);
50
+ },
51
+ order: () => source.grouping?.()?.order,
52
+ locale: () => locale,
53
+ onChange: redraw
54
+ });
55
+ groupsControl.current = controller;
56
+ return () => {
57
+ groupsControl.current = null;
58
+ controller.dispose();
59
+ };
60
+ }, [source, locale]);
61
+ const categoryKey = categories.map(category => category.id).join('\n');
62
+ React.useLayoutEffect(() => {
63
+ groupsControl.current?.update(grouping?.groups ?? noGroups);
64
+ }, [categoryKey, grouping?.groups, vertical]);
65
+ React.useLayoutEffect(() => grouping?.order.subscribe(redraw), [grouping?.order]);
66
+ // A group stands for the selected category while its child palette holds it.
67
+ const pressed = (id) => id === selectedId ||
68
+ (!!selectedId && groupsControl.current?.isGroup(id) && groupsControl.current.shownAs(selectedId) === id);
28
69
  React.useLayoutEffect(() => {
29
70
  setItems(selectedId ? source.read(selectedId) : []);
30
71
  }, [source, selectedId, revision]);
@@ -39,15 +80,17 @@ export default function Palette({ source, locale, categoryIcons, close, startDra
39
80
  }
40
81
  return React.createElement("main", { className: "tw-detached-palette", "data-palette-orientation": vertical ? 'vertical' : 'horizontal' },
41
82
  React.createElement("div", { className: "tw-detached-palette__content" },
42
- React.createElement("div", { className: "tw-detached-palette__categories", role: "group", "aria-label": ja ? 'ブロックのカテゴリ' : 'Block categories', onScroll: () => setTooltip(null) }, categories.map(({ id, label, color, image }) => {
83
+ React.createElement("div", { ref: list, className: "tw-detached-palette__categories", role: "group", "aria-label": ja ? 'ブロックのカテゴリ' : 'Block categories', onScroll: () => setTooltip(null) }, categories.map(({ id, label, color, image }) => {
43
84
  const artwork = categoryIcons[id];
44
85
  const backgroundImage = image || (artwork ? `url("${artwork}")` : undefined);
45
- return React.createElement("button", { key: id, type: "button", "aria-label": label, "aria-pressed": id === selectedId, onMouseEnter: event => showLabel(event.currentTarget, label), onMouseLeave: () => setTooltip(null), onFocus: event => showLabel(event.currentTarget, label), onBlur: () => setTooltip(null), onKeyDown: event => { if (event.key === 'Escape')
46
- setTooltip(null); }, onClick: () => {
47
- setCategory(id);
48
- setTooltip(null);
49
- } },
50
- React.createElement("span", { "aria-hidden": "true", className: "tw-detached-palette__category-icon", style: { backgroundColor: color, backgroundImage } }, !backgroundImage && React.createElement(LayoutIcon, { path: "M2 4h5V2h3v2h4v8H2z" })));
86
+ // Each category sits in a row of its own, which a group hides while it holds the category.
87
+ return React.createElement("span", { key: id, className: "tw-detached-palette__category" },
88
+ React.createElement("button", { type: "button", "data-category-id": id, "aria-label": label, "aria-pressed": Boolean(pressed(id)), onMouseEnter: event => showLabel(event.currentTarget, label), onMouseLeave: () => setTooltip(null), onFocus: event => showLabel(event.currentTarget, label), onBlur: () => setTooltip(null), onKeyDown: event => { if (event.key === 'Escape')
89
+ setTooltip(null); }, onClick: () => {
90
+ setCategory(id);
91
+ setTooltip(null);
92
+ } },
93
+ React.createElement("span", { "aria-hidden": "true", className: "tw-detached-palette__category-icon", style: { backgroundColor: color, backgroundImage } }, !backgroundImage && React.createElement(LayoutIcon, { path: "M2 4h5V2h3v2h4v8H2z" }))));
51
94
  })),
52
95
  React.createElement("div", { className: "tw-detached-palette__blocks", role: "group", "aria-label": selected?.label }, items.map((item, index) => item.insert ? React.createElement("button", { key: index, type: "button", "aria-label": item.label, title: item.label, disabled: item.disabled, draggable: Boolean(item.preview && !item.disabled), onDragStart: event => startDrag(item, event.dataTransfer), onDragEnd: endDrag, onClick: () => item.insert() }, item.preview ? React.createElement(BlockPreview, { svg: item.preview }) : item.label) : React.createElement("span", { key: index }, item.label)))),
53
96
  tooltip && React.createElement("div", { className: "tw-detached-palette__tooltip", role: "tooltip", style: tooltip.position }, tooltip.label),
@@ -1,3 +1,4 @@
1
+ import type { PaletteGroups, PaletteGroupsOrder } from './palette-category-groups.ts';
1
2
  type Point = {
2
3
  x: number;
3
4
  y: number;
@@ -14,9 +15,15 @@ export type PaletteItem = {
14
15
  disabled?: boolean;
15
16
  insert?(point?: Point): void;
16
17
  };
18
+ /** The groups of the editor's palette, which the detached one shows the same way, and the order and pins they share. */
19
+ export type PaletteGrouping = {
20
+ groups: PaletteGroups;
21
+ order: PaletteGroupsOrder;
22
+ };
17
23
  export type PaletteSource = {
18
24
  surface: SVGSVGElement;
19
25
  categories(): PaletteCategory[];
26
+ grouping?(): PaletteGrouping | undefined;
20
27
  read(id: string): PaletteItem[];
21
28
  subscribe(refresh: () => void): () => void;
22
29
  setDetached(detached: boolean): void;
@@ -27,12 +34,15 @@ type PaletteWindowOptions = {
27
34
  decorate(document: Document): () => void;
28
35
  };
29
36
  export declare function openDetachedBlockPalette(workspace: object, { locale, categoryIcons, decorate }: PaletteWindowOptions): void;
30
- export declare function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, show, setDetached }: {
37
+ export declare function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, grouping, show, setDetached }: {
31
38
  blocks: any;
32
39
  workspace: any;
33
40
  flyout: any;
34
41
  menu: HTMLElement;
42
+ /** Every category, members of groups included, in the palette's order. */
35
43
  categories(): PaletteCategory[];
44
+ /** The palette's groups, so the detached palette opens them in child palettes too. */
45
+ grouping?(): PaletteGrouping | undefined;
36
46
  show(id: string): void;
37
47
  setDetached(detached: boolean): void;
38
48
  }): () => void;
@@ -76,7 +76,7 @@ function registerDetachedBlockPalette(workspace, source) {
76
76
  sources.delete(workspace);
77
77
  };
78
78
  }
79
- export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, show, setDetached }) {
79
+ export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, grouping, show, setDetached }) {
80
80
  const surface = workspace.getParentSvg();
81
81
  const ns = 'http://www.w3.org/2000/svg';
82
82
  const win = surface.ownerDocument.defaultView;
@@ -91,7 +91,7 @@ export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, c
91
91
  return position.matrixTransform(matrix.inverse());
92
92
  };
93
93
  return registerDetachedBlockPalette(workspace, {
94
- surface, categories, setDetached,
94
+ surface, categories, grouping, setDetached,
95
95
  read(id) {
96
96
  show(id);
97
97
  const items = [];
@@ -56,18 +56,24 @@ export interface PaletteCategoryGroupsOptions {
56
56
  /** Called when a child palette opens or the last one closes. */
57
57
  onChange?(): void;
58
58
  /**
59
- * Lets a long press on a member of a child palette drag it to another place among the members of the same group,
60
- * as the palette's own categories can be reordered. Members do not move to another group or level.
59
+ * Lets a long press on a member of a group drag it to another place among the members of the same group, as the
60
+ * palette's own categories can be reordered: in the group's child palette, or where a pinned group shows its
61
+ * members. Members do not move to another group or level.
61
62
  */
62
63
  reorder?: boolean;
63
64
  /** Called after the members of a group were reordered, so the host can lay out its categories with `arrange`. */
64
65
  onReorder?(): void;
65
66
  /**
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.
67
+ * Where the members' order and the pinned groups are kept, such as the palette settings saved with the project.
68
+ * Palettes given the same one, such as the editor's and the detached one, follow each other. By default they last
69
+ * while the palette does.
68
70
  */
69
- order?(): Pick<PaletteOrder, 'members' | 'setMembers'> | undefined;
71
+ order?(): PaletteGroupsOrder | undefined;
72
+ /** The locale the pin buttons are labelled in. By default, the document's language. */
73
+ locale?(): string;
70
74
  }
75
+ /** The part of a {@link PaletteOrder} the child palettes use. */
76
+ export type PaletteGroupsOrder = Pick<PaletteOrder, 'members' | 'setMembers' | 'isPinned' | 'setPinned' | 'subscribe'>;
71
77
  export interface PaletteCategoryGroupsController {
72
78
  /**
73
79
  * Prepares a toolbox tree as {@link prepareGroupedToolboxTree} does, and puts each group's members in the order
@@ -79,10 +85,21 @@ export interface PaletteCategoryGroupsController {
79
85
  }): PaletteGroups;
80
86
  /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
81
87
  update(groups: PaletteGroups): void;
88
+ /** The groups the palette was last drawn with, members in their order, to show another palette the same way. */
89
+ current(): PaletteGroups;
90
+ /** Whether the category is a group the palette shows, whose icon opens a child palette. */
82
91
  isGroup(id: string): boolean;
92
+ /**
93
+ * The category whose icon stands for the id in the palette: its own, when the palette shows it, or that of the
94
+ * nearest group the palette shows. A pinned group's members are shown in the palette that shows the group.
95
+ */
96
+ shownAs(id: string): string;
83
97
  /** The id of the outermost group the category is in, or its own id when it is in none. */
84
98
  topLevelId(id: string): string;
85
- /** Opens the group's child palette from its icon, or closes it if it is open. */
99
+ /**
100
+ * Opens the group's child palette from its icon, or closes it if it is open. A pinned group shows its members in
101
+ * place, so its icon only opens its own blocks, if it has any.
102
+ */
86
103
  toggle(category: PaletteCategory, focus?: boolean): void;
87
104
  isOpen(): boolean;
88
105
  /** The icon the palette shows for the category: its own, or that of the group it is in. */
@@ -164,14 +164,68 @@ export const attachPaletteCategoryGroups = (menu, options) => {
164
164
  current = parentOf.get(current);
165
165
  return current;
166
166
  };
167
+ const isPinned = (id) => groups.members.has(id) && memberOrder().isPinned(id);
168
+ // A category is in the palette when every group it is in is pinned open.
169
+ const inPalette = (id) => {
170
+ for (let parent = parentOf.get(id); parent !== undefined; parent = parentOf.get(parent)) {
171
+ if (!isPinned(parent))
172
+ return false;
173
+ }
174
+ return true;
175
+ };
176
+ const shownAs = (id) => {
177
+ let current = id;
178
+ while (!inPalette(current))
179
+ current = parentOf.get(current);
180
+ return current;
181
+ };
182
+ // Changes this palette makes itself, which it does not need to hear back about.
183
+ let writing = false;
184
+ const quietly = (write) => {
185
+ writing = true;
186
+ try {
187
+ write();
188
+ }
189
+ finally {
190
+ writing = false;
191
+ }
192
+ };
193
+ const japanese = () => /^ja(?:-|$)/i.test(options.locale?.() ?? doc.documentElement.lang);
194
+ /** A pin button: pinned, it folds the group back; unpinned, it pins the group open. */
195
+ const pinButton = (pinned, press) => {
196
+ const button = doc.createElement('span');
197
+ button.className = 'tw-palette-group-pin';
198
+ button.setAttribute('data-palette-group-pin', pinned ? 'pinned' : 'unpinned');
199
+ button.setAttribute('role', 'button');
200
+ button.tabIndex = 0;
201
+ const label = pinned ? (japanese() ? 'グループの固定を外して、たたむ' : 'Unpin and fold the group') :
202
+ (japanese() ? 'グループをパレットに広げて固定する' : 'Pin the group open in the palette');
203
+ button.setAttribute('aria-label', label);
204
+ button.title = label;
205
+ const pressed = (event) => {
206
+ event.preventDefault();
207
+ event.stopPropagation();
208
+ press();
209
+ };
210
+ button.addEventListener('click', pressed, { signal: events.signal });
211
+ button.addEventListener('keydown', event => {
212
+ if (event.key === 'Enter' || event.key === ' ')
213
+ pressed(event);
214
+ }, { signal: events.signal });
215
+ // Scratch Blocks would open the category the button sits on.
216
+ for (const type of ['mouseup', 'touchend']) {
217
+ button.addEventListener(type, event => event.stopPropagation(), { signal: events.signal });
218
+ }
219
+ return button;
220
+ };
167
221
  const markSelection = () => {
168
222
  for (const [id] of groups.members) {
169
- if (parentOf.has(id))
223
+ if (!inPalette(id))
170
224
  continue;
171
225
  const item = categoryById(id)?.item_;
172
226
  if (!item)
173
227
  continue;
174
- const current = selected !== null && selected !== id && topLevelOf(selected) === id;
228
+ const current = selected !== null && selected !== id && shownAs(selected) === id;
175
229
  item.toggleAttribute('data-palette-group-current', current);
176
230
  if (current)
177
231
  item.classList.add(selectedClass);
@@ -182,8 +236,9 @@ export const attachPaletteCategoryGroups = (menu, options) => {
182
236
  const closeFrom = (depth) => {
183
237
  let changed = false;
184
238
  while (stack.length > depth) {
185
- const { anchor, popup, reorder } = stack.pop();
186
- reorder?.dispose();
239
+ const { anchor, popup, reorders } = stack.pop();
240
+ for (const reorder of reorders)
241
+ reorder.dispose();
187
242
  anchor.setAttribute('aria-expanded', 'false');
188
243
  popup.remove();
189
244
  changed = true;
@@ -214,13 +269,16 @@ export const attachPaletteCategoryGroups = (menu, options) => {
214
269
  popup.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
215
270
  };
216
271
  const activate = (category, entry, depth, focus, self) => {
217
- if (!self && groups.members.has(category.id_)) {
272
+ if (!self && groups.members.has(category.id_) && !isPinned(category.id_)) {
218
273
  if (stack[depth]?.id === category.id_)
219
274
  closeFrom(depth);
220
275
  else
221
276
  open(category, entry, depth, focus);
222
277
  return;
223
278
  }
279
+ // A pinned group without blocks of its own shows its members where it is, so there is nothing to open.
280
+ if (!self && groups.members.has(category.id_) && !groups.withOwnContents.has(category.id_))
281
+ return;
224
282
  close();
225
283
  options.choose(category);
226
284
  };
@@ -231,10 +289,21 @@ export const attachPaletteCategoryGroups = (menu, options) => {
231
289
  entry.setAttribute('data-palette-group-item', category.id_);
232
290
  entry.setAttribute('role', 'menuitem');
233
291
  entry.tabIndex = -1;
234
- for (const child of Array.from(category.item_.children))
235
- entry.append(child.cloneNode(true));
292
+ entry.title = category.item_.textContent?.trim() || category.item_.getAttribute('aria-label') || '';
293
+ for (const child of Array.from(category.item_.children)) {
294
+ if (!child.hasAttribute('data-palette-group-pin'))
295
+ entry.append(child.cloneNode(true));
296
+ }
236
297
  const isGroup = !self && groups.members.has(category.id_);
237
- if (isGroup) {
298
+ if (isGroup && isPinned(category.id_)) {
299
+ entry.setAttribute('data-palette-group-pinned', '');
300
+ // Folding the group back draws this child palette again.
301
+ entry.append(pinButton(true, () => {
302
+ quietly(() => memberOrder().setPinned(category.id_, false));
303
+ reopen(depth - 1);
304
+ }));
305
+ }
306
+ else if (isGroup) {
238
307
  entry.setAttribute('aria-haspopup', 'true');
239
308
  entry.setAttribute('aria-expanded', 'false');
240
309
  }
@@ -257,7 +326,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
257
326
  if (event.key !== forward && event.key !== backward)
258
327
  return;
259
328
  event.preventDefault();
260
- const entries = Array.from(entry.parentElement.children);
329
+ const entries = Array.from(entry.parentElement.querySelectorAll(':scope > [data-palette-group-item]'));
261
330
  const index = entries.indexOf(entry) + (event.key === forward ? 1 : -1);
262
331
  entries[(index + entries.length) % entries.length].focus();
263
332
  }, { signal: events.signal });
@@ -287,38 +356,162 @@ export const attachPaletteCategoryGroups = (menu, options) => {
287
356
  popup.style.fontFamily = look.fontFamily;
288
357
  if (options.rtl)
289
358
  popup.dir = 'rtl';
359
+ // Pinning the group shows its members in the palette that shows the group.
360
+ popup.append(pinButton(false, () => pinFrom(depth)));
290
361
  if (groups.withOwnContents.has(group.id_))
291
362
  popup.append(createEntry(group, depth, true));
292
- const entries = members.map(member => createEntry(member, depth + 1));
293
- popup.append(...entries);
363
+ // The entries of each group's members shown here: the group's own, and those of pinned member groups.
364
+ const shown = new Map([[group.id_, []]]);
365
+ // A pinned member group is followed by its own members, here rather than in a child palette of its own.
366
+ const add = (member, groupId) => {
367
+ const entry = createEntry(member, depth + 1);
368
+ shown.get(groupId).push(entry);
369
+ popup.append(entry);
370
+ if (!isPinned(member.id_))
371
+ return;
372
+ shown.set(member.id_, []);
373
+ for (const id of groups.members.get(member.id_) ?? []) {
374
+ const inner = categoryById(id);
375
+ if (inner)
376
+ add(inner, member.id_);
377
+ }
378
+ };
379
+ for (const member of members)
380
+ add(member, group.id_);
294
381
  (menu.parentElement ?? doc.body).append(popup);
295
382
  place(popup, anchor);
296
383
  anchor.setAttribute('aria-expanded', 'true');
297
- // The group's own blocks stay first; its members can be dragged among themselves.
298
- const reorder = options.reorder ? attachPaletteCategoryReorder(popup, () => entries, (from, to) => {
299
- const order = members.map(member => member.id_);
300
- order.splice(to, 0, order.splice(from, 1)[0]);
301
- memberOrder().setMembers(group.id_, order);
302
- groups.members.set(group.id_, order);
384
+ // The group's own blocks stay first; the members of each group shown here can be dragged among themselves.
385
+ const reorders = options.reorder ? [...shown].filter(([, entries]) => entries.length > 1).map(([groupId, entries]) => attachPaletteCategoryReorder(popup, () => entries, (from, to) => {
386
+ moveMember(groupId, from, to);
303
387
  open(group, anchor, depth, false);
304
388
  options.onReorder?.();
305
- }, { horizontal: options.horizontal, area: entry => entry }) : undefined;
306
- stack.push({ id: group.id_, anchor, popup, reorder });
389
+ }, { horizontal: options.horizontal, area: entry => entry })) : [];
390
+ stack.push({ id: group.id_, anchor, popup, reorders });
307
391
  options.onChange?.();
308
392
  if (focus)
309
393
  popup.firstElementChild?.focus();
310
394
  };
311
395
  const toggle = (category, focus = false) => {
312
- if (stack[0]?.id === category.id_)
396
+ if (isPinned(category.id_)) {
397
+ close();
398
+ if (groups.withOwnContents.has(category.id_))
399
+ options.choose(category);
400
+ }
401
+ else if (stack[0]?.id === category.id_)
313
402
  close();
314
403
  else
315
404
  open(category, category.item_, 0, focus);
316
405
  };
406
+ // Draws the child palette at the depth again, or the palette itself.
407
+ function reopen(depth) {
408
+ if (depth < 0 || !stack[depth]) {
409
+ close();
410
+ applyVisibility();
411
+ return;
412
+ }
413
+ const { id, anchor } = stack[depth];
414
+ const group = categoryById(id);
415
+ if (group)
416
+ open(group, anchor, depth, false);
417
+ else
418
+ closeFrom(depth);
419
+ }
420
+ // Pins open the group of the child palette at the depth: its members join the palette it opened from.
421
+ function pinFrom(depth) {
422
+ const { id } = stack[depth];
423
+ quietly(() => memberOrder().setPinned(id, true));
424
+ closeFrom(depth);
425
+ if (depth > 0)
426
+ reopen(depth - 1);
427
+ else
428
+ applyVisibility();
429
+ }
430
+ /** Moves a member of the group, as dragged, and keeps the order. */
431
+ function moveMember(groupId, from, to) {
432
+ const order = [...(groups.members.get(groupId) ?? [])];
433
+ order.splice(to, 0, order.splice(from, 1)[0]);
434
+ quietly(() => memberOrder().setMembers(groupId, order));
435
+ groups.members.set(groupId, order);
436
+ }
437
+ // Where the palette shows a pinned group's members, they can be dragged among themselves.
438
+ let inlineReorders = [];
439
+ function attachInlineReorders() {
440
+ for (const reorder of inlineReorders)
441
+ reorder.dispose();
442
+ inlineReorders = [];
443
+ if (!options.reorder)
444
+ return;
445
+ for (const [id, members] of groups.members) {
446
+ if (members.length < 2 || !isPinned(id) || !inPalette(id))
447
+ continue;
448
+ const items = () => (groups.members.get(id) ?? []).map(member => categoryById(member)?.item_)
449
+ .filter((item) => Boolean(item));
450
+ inlineReorders.push(attachPaletteCategoryReorder(menu, items, (from, to) => {
451
+ moveMember(id, from, to);
452
+ close();
453
+ applyVisibility();
454
+ options.onReorder?.();
455
+ }, { horizontal: options.horizontal, ends: false }));
456
+ }
457
+ }
458
+ // Shows the categories every group of which is pinned open, hides the others, and marks the groups shown.
459
+ function applyVisibility() {
460
+ for (const category of options.categories()) {
461
+ const id = category.id_;
462
+ const item = category.item_;
463
+ const row = item.parentElement;
464
+ if (row && row !== menu)
465
+ row.hidden = !inPalette(id);
466
+ const group = groups.members.has(id) && inPalette(id);
467
+ if (group) {
468
+ item.setAttribute('aria-haspopup', 'true');
469
+ if (!item.hasAttribute('aria-expanded'))
470
+ item.setAttribute('aria-expanded', 'false');
471
+ item.setAttribute('data-palette-group', '');
472
+ item.classList.add('tw-palette-group');
473
+ }
474
+ const pinned = group && isPinned(id);
475
+ item.toggleAttribute('data-palette-group-pinned', pinned);
476
+ const button = item.querySelector(':scope > [data-palette-group-pin]');
477
+ if (pinned && !button) {
478
+ item.append(pinButton(true, () => {
479
+ quietly(() => memberOrder().setPinned(id, false));
480
+ close();
481
+ applyVisibility();
482
+ }));
483
+ }
484
+ else if (!pinned)
485
+ button?.remove();
486
+ }
487
+ attachInlineReorders();
488
+ markSelection();
489
+ options.onChange?.();
490
+ }
491
+ // Another palette given the same order, or a project loaded, may pin or fold groups.
492
+ let watched;
493
+ let unwatch;
494
+ const watchOrder = () => {
495
+ const order = memberOrder();
496
+ if (order === watched)
497
+ return;
498
+ unwatch?.();
499
+ watched = order;
500
+ unwatch = order.subscribe(() => {
501
+ if (writing)
502
+ return;
503
+ close();
504
+ applyVisibility();
505
+ });
506
+ };
317
507
  const groupItem = (target) => {
318
508
  if (!(target instanceof doc.defaultView.Node))
319
509
  return null;
510
+ // A pin button handles its own press.
511
+ if (target.closest?.('[data-palette-group-pin]'))
512
+ return null;
320
513
  return options.categories().find(category => groups.members.has(category.id_) &&
321
- !parentOf.has(category.id_) && category.item_.contains(target)) ?? null;
514
+ inPalette(category.id_) && category.item_.contains(target)) ?? null;
322
515
  };
323
516
  // Scratch Blocks opens a category on mouseup (touchend on touch screens); a group opens its child palette on click.
324
517
  for (const type of ['mouseup', 'touchend']) {
@@ -393,18 +586,8 @@ export const attachPaletteCategoryGroups = (menu, options) => {
393
586
  update(next) {
394
587
  close();
395
588
  useGroups(next);
589
+ watchOrder();
396
590
  for (const category of options.categories()) {
397
- const member = parentOf.has(category.id_);
398
- const row = category.item_.parentElement;
399
- if (row && row !== menu)
400
- row.hidden = member;
401
- const group = groups.members.has(category.id_) && !member;
402
- if (group) {
403
- category.item_.setAttribute('aria-haspopup', 'true');
404
- category.item_.setAttribute('aria-expanded', 'false');
405
- category.item_.setAttribute('data-palette-group', '');
406
- category.item_.classList.add('tw-palette-group');
407
- }
408
591
  const { setSelected } = category;
409
592
  category.setSelected = function (value) {
410
593
  setSelected.call(this, value);
@@ -417,13 +600,15 @@ export const attachPaletteCategoryGroups = (menu, options) => {
417
600
  if (category.item_.classList.contains(selectedClass))
418
601
  selected = category.id_;
419
602
  }
420
- markSelection();
603
+ applyVisibility();
421
604
  },
422
- isGroup: id => groups.members.has(id) && !parentOf.has(id),
605
+ current: () => groups,
606
+ isGroup: id => groups.members.has(id) && inPalette(id),
607
+ shownAs,
423
608
  topLevelId: topLevelOf,
424
609
  toggle,
425
610
  isOpen: () => stack.length > 0,
426
- anchorOf: category => categoryById(topLevelOf(category.id_))?.item_ ?? category.item_,
611
+ anchorOf: category => categoryById(shownAs(category.id_))?.item_ ?? category.item_,
427
612
  arrange(categories, rank) {
428
613
  const position = new Map();
429
614
  const visit = (id) => {
@@ -461,7 +646,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
461
646
  syncButtons(openId) {
462
647
  const horizontal = options.horizontal();
463
648
  for (const category of options.categories()) {
464
- if (!groups.members.has(category.id_) || parentOf.has(category.id_))
649
+ if (!groups.members.has(category.id_) || !inPalette(category.id_))
465
650
  continue;
466
651
  const item = category.item_;
467
652
  if (horizontal)
@@ -470,13 +655,16 @@ export const attachPaletteCategoryGroups = (menu, options) => {
470
655
  item.removeAttribute('tabindex');
471
656
  item.setAttribute('role', 'button');
472
657
  item.toggleAttribute('data-palette-group-shown', horizontal && openId !== null && openId !== category.id_ &&
473
- topLevelOf(openId) === category.id_);
658
+ shownAs(openId) === category.id_);
474
659
  }
475
660
  },
476
661
  contains,
477
662
  close,
478
663
  dispose() {
479
664
  close();
665
+ for (const reorder of inlineReorders)
666
+ reorder.dispose();
667
+ unwatch?.();
480
668
  events.abort();
481
669
  }
482
670
  };
@@ -3,6 +3,11 @@ export interface PaletteCategoryReorderOptions {
3
3
  horizontal?(): boolean;
4
4
  /** The element an item takes up, which a drop over it lands on. By default, the row that holds the item. */
5
5
  area?(item: HTMLElement): Element;
6
+ /**
7
+ * Whether a drop before the first item or after the last one lands at that end. On by default; off, a drop
8
+ * anywhere but over an item moves nothing, as when the items share the menu with others.
9
+ */
10
+ ends?: boolean;
6
11
  }
7
12
  /**
8
13
  * Lets a long press on an item of the menu drag it to another place among the items. Used for the palette's
@@ -40,7 +40,7 @@ export function attachPaletteCategoryReorder(menu, getItems, onDrop, options = {
40
40
  if (!items.length || !menu.contains(hit))
41
41
  return;
42
42
  const item = items.find(candidate => area(candidate).contains(hit));
43
- if (item)
43
+ if (item || options.ends === false)
44
44
  return item;
45
45
  const first = items[0];
46
46
  const last = items[items.length - 1];