@kubohiroya/turbowarp-plus-editor-workbench 0.11.1 → 0.13.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
@@ -131,8 +131,13 @@ Editor がファイルメニューの接続口を提供している場合は、
131
131
 
132
132
  Web 版の Plus 標準配置で `twPlusDockview=1` を付けて起動すると、スプライト編集ペインを左右・上下に分割できます。同じスプライトを複数のペインで開いた場合、表示セクション、コスチュームと音の選択、素材一覧のスクロール位置をペインごとに保持します。変数の値はプロジェクト内で共有され、編集中のペインで変更できます。URL から `twPlusDockview=1` を外して再読み込みすると、通常のスプライトタブに戻ります。
133
133
 
134
- スプライトと背景の編集タブには「コード」「コスチューム / 背景」「音」「変数など」に続いて「メッセージ」がある。
135
- 表示は `@kubohiroya/turbowarp-plus-editor-sprite-panes` の `SpriteMessagePane` が担う。
134
+ スプライトと背景の編集タブには「自由配置」(コード領域)、「コスチューム / 背景」「音」、「変数」「メッセージ」がある。
135
+ 「メッセージ」の表示は `@kubohiroya/turbowarp-plus-editor-sprite-panes` の `SpriteMessagePane` が担う。
136
136
  `broadcast_msg` はステージ所有なので、メッセージ名の変更は作品全体に及ぶ。
137
137
  送受信の判定は `@kubohiroya/turbowarp-plus-editor-project-model` の `messageReference` だけが持ち、Editor の作品内検索も同じ関数を使う。
138
138
  このパッケージの `./project-messages` は、既存の import のためにそれを再 export している。
139
+
140
+ ホストが `getFunctions` を渡すと、「自由配置」の次に「ハット・関数一覧」と「呼び出し関係」がある(ボタンの並びは
141
+ `@kubohiroya/turbowarp-plus-editor-sprite-panes` のツールバーが決め、保存済みのレイアウトが持つセクションの番号は変わらない。「呼び出し関係」は次の番号を使う)。`SpriteFunctionPane` が、前者ではホストが `hats` で渡すハットのスクリプトとブロック定義を
142
+ 一覧し(並べ方は名前順・Z順・N順)、後者では LR・TD の呼び出し図を表示する。並べ方・流れはビューごとに保つ。どちらで選んだ関数もホストの `openFunction` で、ハットのスクリプトは `openScript` で開く(スプライトの横のタブなど)。`openFunction` が無ければ関数はダイアログで開く。`createFunction` を渡すと、一覧や図の下の分割ボタンで、標準のブロック定義か TurboWarp-Plus の名前付き関数を作れる。ダイアログはホストの
143
+ `mountFunctionEditor` を呼び、その定義のコード編集画面はホストが持つ。このパッケージは Scratch Blocks のコードを持たないためである。
package/README.md CHANGED
@@ -129,8 +129,18 @@ Sprite editing tabs are enabled by default in the Plus standard layout. Set `twP
129
129
 
130
130
  In the Plus web editor, add `twPlusDockview=1` to enable split sprite panes. Each pane remembers its section, costume and sound selections, and asset-list scroll position. Variable values are shared across panes and can be changed in the active pane. Remove the startup parameter and reload to return to the regular sprite tabs.
131
131
 
132
- The sprite and stage editor tabs carry a Messages section after Code, Costumes or Backdrops, Sounds and
133
- Variables, drawn by `SpriteMessagePane` from `@kubohiroya/turbowarp-plus-editor-sprite-panes`. The stage owns
132
+ The sprite and stage editor tabs carry Free layout (the code area), then Costumes or Backdrops and Sounds, then
133
+ Variables and Messages. Messages is drawn by `SpriteMessagePane` from `@kubohiroya/turbowarp-plus-editor-sprite-panes`. The stage owns
134
134
  `broadcast_msg` variables, so a rename applies project-wide. `messageReference` in `@kubohiroya/turbowarp-plus-editor-project-model` is the only place that decides what
135
135
  sends or receives a message, and the editor's project search calls the same function. This package's
136
136
  `./project-messages` re-exports it for existing imports.
137
+
138
+ When the host passes `getFunctions`, two sections follow Free layout: Hats and functions, and Calls (the
139
+ toolbar of `@kubohiroya/turbowarp-plus-editor-sprite-panes` sets the button order; the section numbers stored in
140
+ saved layouts do not change, and Calls takes the next one). `SpriteFunctionPane` shows the list in the first, with
141
+ the other hat scripts the host passes in `hats` above the definitions, ordered by name, in Z order or in N order, and the call
142
+ graph flowing LR or TD in the second; each view keeps the order and flow it chose. A function picked in either opens through
143
+ `openFunction`, and a hat script through `openScript`, such as in a tab beside the sprite; without `openFunction` a function opens
144
+ in a dialog. With `createFunction`, a split button below the list or graph makes a standard custom block or a TurboWarp-Plus named
145
+ function. The dialog calls the host's `mountFunctionEditor`, which owns the code workspace of that
146
+ definition, because this package carries no Scratch Blocks code.
@@ -11,6 +11,12 @@ interface SpriteLayoutCommands {
11
11
  /** Whether the tabs stand in a column at the left of each split panel instead of a row above it. */
12
12
  verticalTabs?(): boolean;
13
13
  setVerticalTabs?(vertical: boolean): void;
14
+ /** Whether the column of section buttons at the left of each sprite tab is hidden. */
15
+ sectionsHidden?(): boolean;
16
+ setSectionsHidden?(hidden: boolean): void;
17
+ /** Whether the costume thumbnail at the bottom right of each code area is hidden. */
18
+ thumbnailHidden?(): boolean;
19
+ setThumbnailHidden?(hidden: boolean): void;
14
20
  }
15
21
  export declare const panelLayoutIconPath = "M2.5 3.5h11v9h-11zM2.5 6.5h11m-7 0v6";
16
22
  export declare function createSpriteLayoutMenu(document: Document, locale: string, commands: SpriteLayoutCommands): {
@@ -1,9 +1,12 @@
1
1
  export const panelLayoutIconPath = 'M2.5 3.5h11v9h-11zM2.5 6.5h11m-7 0v6';
2
+ const checkIconPath = 'm3.5 8.5 3 3 6-7';
2
3
  const labels = {
3
4
  ja: ['編集パネルのレイアウト', 'パネルを横に分割', 'パネルを縦に分割', 'この分割パネルを閉じる',
4
- 'パネルを別画面で開く', 'ブロックパレットを別画面で開く', 'タブを垂直に並べて表示', 'タブを水平に並べて表示'],
5
+ 'パネルを別画面で開く', 'ブロックパレットを別画面で開く', 'タブを垂直に並べて表示', 'タブを水平に並べて表示',
6
+ 'パネル切り替えボタンを表示', 'サムネイルを表示'],
5
7
  en: ['Editor panel layout', 'Split right', 'Split below', 'Close this split',
6
- 'Open panel in another window', 'Open block palette in another window', 'Show tabs vertically', 'Show tabs horizontally']
8
+ 'Open panel in another window', 'Open block palette in another window', 'Show tabs vertically', 'Show tabs horizontally',
9
+ 'Show panel switch buttons', 'Show thumbnail']
7
10
  };
8
11
  function createIcon(document, path) {
9
12
  const ns = 'http://www.w3.org/2000/svg';
@@ -21,7 +24,7 @@ function createIcon(document, path) {
21
24
  return icon;
22
25
  }
23
26
  export function createSpriteLayoutMenu(document, locale, commands) {
24
- const [title, right, below, closeLabel, panelLabel, paletteLabel, verticalLabel, horizontalLabel] = /^ja(?:-|$)/i.test(locale) ? labels.ja : labels.en;
27
+ const [title, right, below, closeLabel, panelLabel, paletteLabel, verticalLabel, horizontalLabel, sectionsLabel, thumbnailLabel] = /^ja(?:-|$)/i.test(locale) ? labels.ja : labels.en;
25
28
  const element = document.createElement('div');
26
29
  element.className = 'tw-plus-sprite-layout-menu';
27
30
  const trigger = document.createElement('button');
@@ -42,36 +45,60 @@ export function createSpriteLayoutMenu(document, locale, commands) {
42
45
  { label: below, run: commands.splitBelow, enabled: commands.canSplit, path: 'M2.5 3.5h11v9h-11zM2.5 8h11' },
43
46
  { label: closeLabel, run: commands.close, enabled: commands.canClose, path: 'm4.5 4.5 7 7m0-7-7 7' },
44
47
  { label: panelLabel, run: commands.openPanel, enabled: commands.canOpenPanel, path: 'M7 3H3v10h10V9m-5-1 5-5m-4 0h4v4' },
45
- { label: paletteLabel, run: commands.openPalette, enabled: commands.canOpenPalette,
48
+ { label: paletteLabel, group: 'palette', run: commands.openPalette, enabled: commands.canOpenPalette,
46
49
  path: 'M7 4H3v3h2v2H3v3h7v-2h2V9m-3-2 4-4m-3 0h3v3' },
47
50
  ...(commands.verticalTabs && commands.setVerticalTabs ? [{
48
- label: verticalLabel, run: () => commands.setVerticalTabs(!commands.verticalTabs()),
51
+ label: verticalLabel, group: 'tabs', run: () => commands.setVerticalTabs(!commands.verticalTabs()),
49
52
  path: 'M2.5 3.5h11v9h-11zM6 3.5v9M2.5 6h3.5m-3.5 2.5h3.5',
50
53
  // The item names the arrangement it switches to.
51
54
  current: () => commands.verticalTabs() ?
52
55
  { label: horizontalLabel, path: 'M2.5 3.5h11v9h-11zM2.5 6.5h11M6 3.5v3m3.5-3v3' } : undefined
56
+ }] : []),
57
+ // These two say what is shown, with a check mark while it is.
58
+ ...(commands.sectionsHidden && commands.setSectionsHidden ? [{
59
+ label: sectionsLabel, group: 'shown', run: () => commands.setSectionsHidden(!commands.sectionsHidden()),
60
+ path: '', checked: () => !commands.sectionsHidden()
61
+ }] : []),
62
+ ...(commands.thumbnailHidden && commands.setThumbnailHidden ? [{
63
+ label: thumbnailLabel, group: 'shown', run: () => commands.setThumbnailHidden(!commands.thumbnailHidden()),
64
+ path: '', checked: () => !commands.thumbnailHidden()
53
65
  }] : [])
54
66
  ];
55
- const entries = items.flatMap(({ label, run, enabled, path, current }) => {
67
+ const entries = items.flatMap(({ label, group, run, enabled, path, current, checked }) => {
56
68
  if (!run)
57
69
  return [];
58
70
  const item = document.createElement('button');
59
71
  item.type = 'button';
60
72
  const render = () => {
73
+ if (checked) {
74
+ const on = checked();
75
+ item.setAttribute('aria-checked', String(on));
76
+ item.replaceChildren(createIcon(document, on ? checkIconPath : ''), label);
77
+ return;
78
+ }
61
79
  const shown = current?.() ?? { label, path };
62
80
  item.replaceChildren(createIcon(document, shown.path), shown.label);
63
81
  };
64
82
  render();
65
83
  item.tabIndex = -1;
66
- item.setAttribute('role', 'menuitem');
84
+ item.setAttribute('role', checked ? 'menuitemcheckbox' : 'menuitem');
67
85
  item.addEventListener('click', () => {
68
86
  close(true);
69
87
  run();
70
88
  });
71
- return [{ item, enabled, render: current && render }];
89
+ return [{ item, group, enabled, render: (current || checked) && render }];
72
90
  });
73
91
  const buttons = entries.map(({ item }) => item);
74
- popup.append(...buttons);
92
+ // A divider stands between groups of items, so it never leads the menu or doubles up when a group is missing.
93
+ entries.forEach(({ item, group }, index) => {
94
+ if (index > 0 && group !== entries[index - 1].group) {
95
+ const divider = document.createElement('div');
96
+ divider.className = 'tw-plus-sprite-layout-menu-divider';
97
+ divider.setAttribute('role', 'separator');
98
+ popup.append(divider);
99
+ }
100
+ popup.append(item);
101
+ });
75
102
  let openedIn;
76
103
  let topLayer = false;
77
104
  function close(restoreFocus = false) {
@@ -7,6 +7,7 @@ import type { DockviewStagePane } from './dockview-stage.ts';
7
7
  import type { WorkspaceLayoutStore, WorkspaceProjectIdentity } from './workspace-layout-store.ts';
8
8
  import type { SpriteVariableEdit, SpriteVariableEditError } from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
9
9
  import type { MessageRenameError } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
10
+ import type { FunctionKind, FunctionPaneData, MountFunctionEditor, OpenScriptOptions, SpriteFunction, SpriteHatScript } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
10
11
  import type { MessageUse, ProjectMessage, TargetMessages } from '@kubohiroya/turbowarp-plus-editor-project-model/project-messages';
11
12
  export { getDocumentWorkspace } from './document-workspace.ts';
12
13
  export { createWorkspaceLayoutStore, workspaceLayoutDatabase, workspaceLayoutLimit } from './workspace-layout-store.ts';
@@ -92,6 +93,7 @@ interface TabOptions<Snapshot = unknown> {
92
93
  stagePane?: DockviewStagePane;
93
94
  variables?: boolean;
94
95
  messages?: boolean;
96
+ functions?: boolean;
95
97
  locale?: string;
96
98
  viewAdapter?: SpriteTabAdapter<Snapshot>;
97
99
  popouts?: {
@@ -115,7 +117,7 @@ interface ToolbarSlot {
115
117
  interface AssetPreviewSlot {
116
118
  id: string;
117
119
  targetId: string;
118
- kind: AssetKind | 'variables' | 'messages';
120
+ kind: AssetKind | 'variables' | 'messages' | 'functions' | 'calls';
119
121
  editable: boolean;
120
122
  selected?: object;
121
123
  renderLayout?: SpriteAssetLayout;
@@ -187,6 +189,34 @@ type SpriteTabsProps<Snapshot> = Omit<TabOptions<Snapshot>, 'activateSection' |
187
189
  openMessageTarget?(targetId: string): void;
188
190
  /** Rename a message everywhere in the project. The stage owns broadcast_msg variables. */
189
191
  renameMessage?(message: ProjectMessage, name: string): MessageRenameError | void;
192
+ /**
193
+ * The custom block definitions of this target, with its other hat scripts in `hats` for the list.
194
+ * `readTargetFunctions` reads the definitions from the runtime.
195
+ */
196
+ getFunctions?(targetId: string): FunctionPaneData;
197
+ /** Mount an editor of one definition script in an open item of the functions pane. */
198
+ mountFunctionEditor?: MountFunctionEditor;
199
+ /**
200
+ * Open one function picked in the list or the call graph of the functions section, such as in a tab
201
+ * split beside the sprite. Without it the function opens in a dialog.
202
+ */
203
+ openFunction?(targetId: string, fn: SpriteFunction, options?: OpenScriptOptions): void;
204
+ /**
205
+ * Open a hat script picked in the list of hats and functions, as `openFunction` opens a function.
206
+ * `options.block` asks to show one block, such as a call picked in the list of a function's uses.
207
+ */
208
+ openScript?(targetId: string, hat: SpriteHatScript, options?: OpenScriptOptions): void;
209
+ /** The function or hat script shown beside the sprite, which the list of hats and functions highlights. */
210
+ selectedScript?: {
211
+ targetId: string;
212
+ id: string;
213
+ };
214
+ /**
215
+ * Make a new function in the target: a standard custom block or a TurboWarp-Plus named function.
216
+ * Resolves with the id of the new hat, or with nothing when cancelled. Without it, the functions
217
+ * section has no create button.
218
+ */
219
+ createFunction?(targetId: string, kind: FunctionKind): Promise<string | void>;
190
220
  getCodeSearchItems?(targetId: string): readonly SpriteSearchResult[];
191
221
  openCodeSearchResult?(targetId: string, id: string): void;
192
222
  };
@@ -9,6 +9,7 @@ import { projectFolderIconPath } from "./drawer-views.js";
9
9
  import { dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels } from "./workspace-layout.js";
10
10
  import { createWorkspaceLayoutStore } from "./workspace-layout-store.js";
11
11
  import { SpriteMessagePane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
12
+ import { functionLabel, SpriteFunctionPane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
12
13
  import { createTargetTabMenuItem, spriteRenameLabel } from "./target-tab-menu.js";
13
14
  export { getDocumentWorkspace } from "./document-workspace.js";
14
15
  export { createWorkspaceLayoutStore, workspaceLayoutDatabase, workspaceLayoutLimit } from "./workspace-layout-store.js";
@@ -17,6 +18,8 @@ export { useDockviewStage } from "./dockview-stage.js";
17
18
  export { SpriteTargetTabsContext, useTargetTabMenu } from "./target-tab-menu.js";
18
19
  const variableSection = spriteEditorSections.indexOf('variables');
19
20
  const messageSection = spriteEditorSections.indexOf('messages');
21
+ const functionSection = spriteEditorSections.indexOf('functions');
22
+ const callSection = spriteEditorSections.indexOf('calls');
20
23
  // The first three sections are the GUI's own panels; the rest are rendered by this package.
21
24
  const lastNativeSection = 2;
22
25
  function createAssetSelections(target, locale, source) {
@@ -115,7 +118,8 @@ export function mountSpriteTabs(root, content, options) {
115
118
  const viewAdapter = multiView ? options.viewAdapter : undefined;
116
119
  const stagePane = multiView ? options.stagePane : undefined;
117
120
  const ownSection = (section) => (section === variableSection && Boolean(options.variables)) ||
118
- (section === messageSection && Boolean(options.messages));
121
+ (section === messageSection && Boolean(options.messages)) ||
122
+ ((section === functionSection || section === callSection) && Boolean(options.functions));
119
123
  const usesNativeSection = (section) => !ownSection(section);
120
124
  const sectionAvailable = (section) => section <= lastNativeSection || ownSection(section);
121
125
  const document = root.ownerDocument;
@@ -172,6 +176,12 @@ export function mountSpriteTabs(root, content, options) {
172
176
  // Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
173
177
  let verticalTabs = false;
174
178
  let tabsChosen = false;
179
+ // Whether the section buttons at the left of each sprite tab are hidden. It is also one preference for every project.
180
+ let sectionsHidden = false;
181
+ let sectionsChosen = false;
182
+ // Whether the costume thumbnail at the bottom right of each code area is hidden, for every project.
183
+ let thumbnailHidden = false;
184
+ let thumbnailChosen = false;
175
185
  const dockview = createDockview(root, {
176
186
  theme: themeLight,
177
187
  disableFloatingGroups: true,
@@ -243,9 +253,11 @@ export function mountSpriteTabs(root, content, options) {
243
253
  if (multiView) {
244
254
  element.classList.add('tw-plus-sprite-tab-slot--split');
245
255
  body.className = 'tw-plus-sprite-tab-body';
256
+ body.toggleAttribute('data-thumbnail-hidden', thumbnailHidden);
246
257
  if (toolbar) {
247
258
  body.setAttribute('role', 'tabpanel');
248
259
  toolbar.className = 'tw-plus-sprite-tab-toolbar';
260
+ toolbar.toggleAttribute('data-sections-hidden', sectionsHidden);
249
261
  element.append(toolbar);
250
262
  }
251
263
  if (assetPreview) {
@@ -346,6 +358,9 @@ export function mountSpriteTabs(root, content, options) {
346
358
  canSplit: () => views.has(group.activePanel?.id),
347
359
  verticalTabs: () => verticalTabs,
348
360
  setVerticalTabs,
361
+ ...(options.onToolbarSlots && { sectionsHidden: () => sectionsHidden, setSectionsHidden }),
362
+ thumbnailHidden: () => thumbnailHidden,
363
+ setThumbnailHidden,
349
364
  ...(popouts && {
350
365
  canOpenPanel,
351
366
  openPanel() {
@@ -394,6 +409,27 @@ export function mountSpriteTabs(root, content, options) {
394
409
  }
395
410
  refreshSurfaces();
396
411
  }
412
+ function setSectionsHidden(hidden, chosen = true) {
413
+ sectionsHidden = hidden;
414
+ for (const { toolbar } of slots.values())
415
+ toolbar?.toggleAttribute('data-sections-hidden', hidden);
416
+ if (chosen) {
417
+ sectionsChosen = true;
418
+ layoutStore?.writeSectionsHidden?.(hidden).catch(() => undefined);
419
+ }
420
+ // The code area is wider or narrower now, though the panel itself kept its size.
421
+ if (active)
422
+ options.resize();
423
+ }
424
+ function setThumbnailHidden(hidden, chosen = true) {
425
+ thumbnailHidden = hidden;
426
+ for (const { body } of slots.values())
427
+ body.toggleAttribute('data-thumbnail-hidden', hidden);
428
+ if (chosen) {
429
+ thumbnailChosen = true;
430
+ layoutStore?.writeThumbnailHidden?.(hidden).catch(() => undefined);
431
+ }
432
+ }
397
433
  const canRename = (target) => target.isOriginal && !target.isStage && Boolean(vm.renameSprite) && vm.runtime.targets.includes(target);
398
434
  function openRenameDialog(target) {
399
435
  if (renameDialog || !canRename(target))
@@ -479,7 +515,9 @@ export function mountSpriteTabs(root, content, options) {
479
515
  if (ownSection(view.section) && slot.assetPreview) {
480
516
  slot.assetPreview.hidden = false;
481
517
  assetPreviews.push({ id, targetId: descriptor.targetId,
482
- kind: view.section === messageSection ? 'messages' : 'variables', editable: active === view,
518
+ kind: view.section === messageSection ? 'messages' : view.section === functionSection ? 'functions' :
519
+ view.section === callSection ? 'calls' : 'variables',
520
+ editable: active === view,
483
521
  element: slot.assetPreview });
484
522
  continue;
485
523
  }
@@ -1250,6 +1288,14 @@ export function mountSpriteTabs(root, content, options) {
1250
1288
  readingTabs = false;
1251
1289
  updateLayoutState();
1252
1290
  });
1291
+ layoutStore?.readSectionsHidden?.().then(hidden => {
1292
+ if (!disposed && !sectionsChosen && hidden)
1293
+ setSectionsHidden(true, false);
1294
+ }, () => undefined);
1295
+ layoutStore?.readThumbnailHidden?.().then(hidden => {
1296
+ if (!disposed && !thumbnailChosen && hidden)
1297
+ setThumbnailHidden(true, false);
1298
+ }, () => undefined);
1253
1299
  if (persistence)
1254
1300
  window.addEventListener('pagehide', flushLayout);
1255
1301
  updateLayoutState();
@@ -1357,11 +1403,14 @@ function SpriteTabs(props) {
1357
1403
  });
1358
1404
  const [toolbarSlots, setToolbarSlots] = React.useState([]);
1359
1405
  const [assetPreviewSlots, setAssetPreviewSlots] = React.useState([]);
1406
+ // The functions pane remounts when its view switches sections; keep the view, order and flow each view chose.
1407
+ const [functionSettings] = React.useState(() => new Map());
1360
1408
  const controller = React.useRef(null);
1361
1409
  const hasVariables = Boolean(props.getVariables);
1362
1410
  const hasMessages = Boolean(props.getMessages);
1411
+ const hasFunctions = Boolean(props.getFunctions);
1363
1412
  const hasToolbar = Boolean(props.renderToolbar) || hasVariables;
1364
- const hasAssetPreview = Boolean(props.getAssetPreview) || hasVariables || hasMessages;
1413
+ const hasAssetPreview = Boolean(props.getAssetPreview) || hasVariables || hasMessages || hasFunctions;
1365
1414
  React.useLayoutEffect(() => {
1366
1415
  sections.current.append(...props.slots);
1367
1416
  parking.current.appendChild(content);
@@ -1409,6 +1458,7 @@ function SpriteTabs(props) {
1409
1458
  stagePane: props.stagePane,
1410
1459
  variables: hasVariables,
1411
1460
  messages: hasMessages,
1461
+ functions: hasFunctions,
1412
1462
  locale: props.locale,
1413
1463
  viewAdapter: props.viewAdapter,
1414
1464
  popouts: props.popouts && { ...props.popouts, className: props.className },
@@ -1428,7 +1478,7 @@ function SpriteTabs(props) {
1428
1478
  };
1429
1479
  }, [content, props.enabled, props.vm, props.reopenLabel, props.multiView, props.locale,
1430
1480
  props.viewAdapter, props.stagePane, props.workspaceLayout, props.renameLabels, props.popouts, props.className,
1431
- hasVariables, hasMessages, hasToolbar, hasAssetPreview]);
1481
+ hasVariables, hasMessages, hasFunctions, hasToolbar, hasAssetPreview]);
1432
1482
  React.useLayoutEffect(() => {
1433
1483
  controller.current?.syncActiveSection(props.activeSection);
1434
1484
  }, [props.activeSection]);
@@ -1453,7 +1503,8 @@ function SpriteTabs(props) {
1453
1503
  viewId: view.id, locale: props.locale, section: currentSection, isStage: view.isStage,
1454
1504
  activeGroup: view.groupActive, propertiesInVariables: Boolean(props.getProperties),
1455
1505
  // A section with no port behind it would open an empty panel.
1456
- availableSections: spriteEditorSections.filter(section => section !== 'messages' || Boolean(props.getMessages)),
1506
+ availableSections: spriteEditorSections.filter(section => (section !== 'messages' || Boolean(props.getMessages)) &&
1507
+ (section !== 'functions' && section !== 'calls' || Boolean(props.getFunctions))),
1457
1508
  actions: view.active && currentSection !== 'variables' ? props.activeTools : undefined,
1458
1509
  onSectionChange: section => actions.setSection(spriteEditorSections.indexOf(section)),
1459
1510
  search: {
@@ -1469,6 +1520,11 @@ function SpriteTabs(props) {
1469
1520
  items = (props.getMessages?.(view.targetId).messages ?? [])
1470
1521
  .map(message => ({ id: message.key, label: message.name }));
1471
1522
  }
1523
+ else if (section === 'functions' || section === 'calls') {
1524
+ const data = props.getFunctions?.(view.targetId);
1525
+ items = [...(section === 'functions' ? data?.hats ?? [] : []).map(hat => ({ id: hat.id, label: hat.label })),
1526
+ ...(data?.functions ?? []).map(fn => ({ id: fn.id, label: functionLabel(fn) }))];
1527
+ }
1472
1528
  else {
1473
1529
  items = props.getAssetPreview?.(view.targetId, section).items.map((item, index) => ({ id: String(index), label: item.name })) ?? [];
1474
1530
  }
@@ -1489,6 +1545,11 @@ function SpriteTabs(props) {
1489
1545
  [...(pane?.querySelectorAll('[data-message-key]') ?? [])]
1490
1546
  .find(node => node.dataset.messageKey === result.id)?.focus();
1491
1547
  }
1548
+ else if (section === 'functions' || section === 'calls') {
1549
+ const pane = assetPreviewSlots.find(slot => slot.id === view.id)?.element;
1550
+ [...(pane?.querySelectorAll('[data-function-key], [data-hat-key]') ?? [])]
1551
+ .find(node => (node.dataset.functionKey ?? node.dataset.hatKey) === result.id)?.focus();
1552
+ }
1492
1553
  else
1493
1554
  workspace?.selectAsset(view.id, section, Number(result.id));
1494
1555
  }
@@ -1505,6 +1566,25 @@ function SpriteTabs(props) {
1505
1566
  workspace?.refreshSurfaces();
1506
1567
  return result;
1507
1568
  })
1569
+ }) : kind === 'functions' || kind === 'calls' ? React.createElement(SpriteFunctionPane, {
1570
+ // The list and the call graph are sections of their own.
1571
+ kind: 'functions', view: kind === 'calls' ? 'graph' : 'list',
1572
+ locale: props.locale, editable, data: props.getFunctions(targetId),
1573
+ defaultSettings: functionSettings.get(id),
1574
+ onSettingsChange: (settings) => functionSettings.set(id, settings),
1575
+ mountEditor: props.mountFunctionEditor,
1576
+ onOpenFunction: props.openFunction &&
1577
+ ((fn, options) => props.openFunction(targetId, fn, options)),
1578
+ onOpenScript: props.openScript &&
1579
+ ((hat, options) => props.openScript(targetId, hat, options)),
1580
+ selectedId: props.selectedScript?.targetId === targetId ? props.selectedScript.id : undefined,
1581
+ onCreate: props.createFunction && (async (functionKind) => {
1582
+ const created = await props.createFunction(targetId, functionKind);
1583
+ // Show the new function now rather than at the next project change.
1584
+ if (created)
1585
+ workspace?.refreshSurfaces();
1586
+ return created;
1587
+ })
1508
1588
  }) : kind === 'variables' ? renderVariablePane(id, targetId, editable) :
1509
1589
  props.getAssetPreview && React.createElement(AssetPreview, {
1510
1590
  locale: props.locale, kind, selected, renderLayout, scrollTop, data: props.getAssetPreview(targetId, kind)
@@ -33,6 +33,12 @@ export interface WorkspaceLayoutStore {
33
33
  open(identity: WorkspaceProjectIdentity, signature: string): Promise<WorkspaceLayoutSession>;
34
34
  readTabsPosition(): Promise<TabsPosition | undefined>;
35
35
  writeTabsPosition(position: TabsPosition): Promise<void>;
36
+ /** Whether the section buttons of the sprite tabs are hidden, one preference for every project. */
37
+ readSectionsHidden?(): Promise<boolean | undefined>;
38
+ writeSectionsHidden?(hidden: boolean): Promise<void>;
39
+ /** Whether the costume thumbnail of the code areas is hidden, one preference for every project. */
40
+ readThumbnailHidden?(): Promise<boolean | undefined>;
41
+ writeThumbnailHidden?(hidden: boolean): Promise<void>;
36
42
  }
37
43
  export interface WorkspaceLayoutStoreOptions {
38
44
  indexedDB?: IDBFactory;
@@ -12,6 +12,8 @@ export const workspaceLayoutMaxBytes = 256 * 1024;
12
12
  const layoutsStore = 'layouts';
13
13
  const preferencesStore = 'preferences';
14
14
  const tabsPositionKey = 'tabsPosition';
15
+ const sectionsHiddenKey = 'sectionsHidden';
16
+ const thumbnailHiddenKey = 'thumbnailHidden';
15
17
  const legacyKeys = ['twPlusDockviewLayout', 'twPlusDockviewLayout.tabs'];
16
18
  const result = (request) => new Promise((resolve, reject) => {
17
19
  request.onsuccess = () => resolve(request.result);
@@ -165,13 +167,26 @@ export function createWorkspaceLayoutStore({ indexedDB: factory = globalThis.ind
165
167
  return value === 'left' || value === 'top' ? value : undefined;
166
168
  },
167
169
  writeTabsPosition(position) {
168
- return enqueue(async () => {
169
- const opened = await connect();
170
- const transaction = opened.transaction(preferencesStore, 'readwrite');
171
- const finished = completion(transaction);
172
- transaction.objectStore(preferencesStore).put(position, tabsPositionKey);
173
- await finished;
174
- });
175
- }
170
+ return writePreference(tabsPositionKey, position);
171
+ },
172
+ readSectionsHidden: () => readFlag(sectionsHiddenKey),
173
+ writeSectionsHidden: hidden => writePreference(sectionsHiddenKey, hidden),
174
+ readThumbnailHidden: () => readFlag(thumbnailHiddenKey),
175
+ writeThumbnailHidden: hidden => writePreference(thumbnailHiddenKey, hidden)
176
176
  };
177
+ async function readFlag(key) {
178
+ const opened = await connect();
179
+ const transaction = opened.transaction(preferencesStore, 'readonly');
180
+ const value = await result(transaction.objectStore(preferencesStore).get(key));
181
+ return typeof value === 'boolean' ? value : undefined;
182
+ }
183
+ function writePreference(key, value) {
184
+ return enqueue(async () => {
185
+ const opened = await connect();
186
+ const transaction = opened.transaction(preferencesStore, 'readwrite');
187
+ const finished = completion(transaction);
188
+ transaction.objectStore(preferencesStore).put(value, key);
189
+ await finished;
190
+ });
191
+ }
177
192
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -72,8 +72,8 @@
72
72
  "url": "git+https://github.com/kubohiroya/turbowarp-plus-editor-workbench.git"
73
73
  },
74
74
  "dependencies": {
75
- "@kubohiroya/turbowarp-plus-editor-project-model": "0.1.0",
76
- "@kubohiroya/turbowarp-plus-editor-sprite-panes": "0.1.1",
75
+ "@kubohiroya/turbowarp-plus-editor-project-model": "0.1.2",
76
+ "@kubohiroya/turbowarp-plus-editor-sprite-panes": "0.4.0",
77
77
  "dockview": "8.8.3"
78
78
  },
79
79
  "peerDependencies": {
@@ -52,6 +52,12 @@
52
52
 
53
53
  .tw-plus-sprite-layout-menu-popup svg { width: 16px; height: 16px; flex: none; }
54
54
 
55
+ .tw-plus-sprite-layout-menu-divider {
56
+ height: 1px;
57
+ margin: 4px 0;
58
+ background: var(--ui-black-transparent, #c6cfda);
59
+ }
60
+
55
61
  .tw-plus-sprite-layout-menu-popup button:disabled { opacity: 0.55; cursor: default; }
56
62
  .tw-plus-sprite-layout-menu-popup button:enabled:is(:hover, :focus-visible) {
57
63
  background: var(--looks-light-transparent, #e6dff3);
@@ -127,3 +133,14 @@
127
133
  opacity: 1;
128
134
  pointer-events: auto;
129
135
  }
136
+
137
+ /* The layout menu can hide the section buttons at the left of every sprite tab. */
138
+ .tw-plus-sprite-tab-toolbar[data-sections-hidden] .tw-plus-sprite-toolbar-sections {
139
+ display: none;
140
+ }
141
+
142
+ /* It can also hide the costume thumbnail at the bottom right of each code area: the GUI's own
143
+ watermark in the active tab and the copy the editor shows in the other tabs. */
144
+ .tw-plus-sprite-tab-body[data-thumbnail-hidden] :is([data-dockview-costume-thumbnail], [class*="gui_watermark_"]) {
145
+ display: none;
146
+ }
@@ -11,15 +11,24 @@ interface SpriteLayoutCommands {
11
11
  /** Whether the tabs stand in a column at the left of each split panel instead of a row above it. */
12
12
  verticalTabs?(): boolean;
13
13
  setVerticalTabs?(vertical: boolean): void;
14
+ /** Whether the column of section buttons at the left of each sprite tab is hidden. */
15
+ sectionsHidden?(): boolean;
16
+ setSectionsHidden?(hidden: boolean): void;
17
+ /** Whether the costume thumbnail at the bottom right of each code area is hidden. */
18
+ thumbnailHidden?(): boolean;
19
+ setThumbnailHidden?(hidden: boolean): void;
14
20
  }
15
21
 
16
22
  export const panelLayoutIconPath = 'M2.5 3.5h11v9h-11zM2.5 6.5h11m-7 0v6';
23
+ const checkIconPath = 'm3.5 8.5 3 3 6-7';
17
24
 
18
25
  const labels = {
19
26
  ja: ['編集パネルのレイアウト', 'パネルを横に分割', 'パネルを縦に分割', 'この分割パネルを閉じる',
20
- 'パネルを別画面で開く', 'ブロックパレットを別画面で開く', 'タブを垂直に並べて表示', 'タブを水平に並べて表示'],
27
+ 'パネルを別画面で開く', 'ブロックパレットを別画面で開く', 'タブを垂直に並べて表示', 'タブを水平に並べて表示',
28
+ 'パネル切り替えボタンを表示', 'サムネイルを表示'],
21
29
  en: ['Editor panel layout', 'Split right', 'Split below', 'Close this split',
22
- 'Open panel in another window', 'Open block palette in another window', 'Show tabs vertically', 'Show tabs horizontally']
30
+ 'Open panel in another window', 'Open block palette in another window', 'Show tabs vertically', 'Show tabs horizontally',
31
+ 'Show panel switch buttons', 'Show thumbnail']
23
32
  };
24
33
 
25
34
  function createIcon(document: Document, path: string) {
@@ -39,7 +48,8 @@ function createIcon(document: Document, path: string) {
39
48
  }
40
49
 
41
50
  export function createSpriteLayoutMenu(document: Document, locale: string, commands: SpriteLayoutCommands) {
42
- const [title, right, below, closeLabel, panelLabel, paletteLabel, verticalLabel, horizontalLabel] = /^ja(?:-|$)/i.test(locale) ? labels.ja : labels.en;
51
+ const [title, right, below, closeLabel, panelLabel, paletteLabel, verticalLabel, horizontalLabel,
52
+ sectionsLabel, thumbnailLabel] = /^ja(?:-|$)/i.test(locale) ? labels.ja : labels.en;
43
53
  const element = document.createElement('div');
44
54
  element.className = 'tw-plus-sprite-layout-menu';
45
55
  const trigger = document.createElement('button');
@@ -61,37 +71,63 @@ export function createSpriteLayoutMenu(document: Document, locale: string, comma
61
71
  {label: below, run: commands.splitBelow, enabled: commands.canSplit, path: 'M2.5 3.5h11v9h-11zM2.5 8h11'},
62
72
  {label: closeLabel, run: commands.close, enabled: commands.canClose, path: 'm4.5 4.5 7 7m0-7-7 7'},
63
73
  {label: panelLabel, run: commands.openPanel, enabled: commands.canOpenPanel, path: 'M7 3H3v10h10V9m-5-1 5-5m-4 0h4v4'},
64
- {label: paletteLabel, run: commands.openPalette, enabled: commands.canOpenPalette,
74
+ {label: paletteLabel, group: 'palette', run: commands.openPalette, enabled: commands.canOpenPalette,
65
75
  path: 'M7 4H3v3h2v2H3v3h7v-2h2V9m-3-2 4-4m-3 0h3v3'},
66
76
  ...(commands.verticalTabs && commands.setVerticalTabs ? [{
67
- label: verticalLabel, run: () => commands.setVerticalTabs!(!commands.verticalTabs!()),
77
+ label: verticalLabel, group: 'tabs', run: () => commands.setVerticalTabs!(!commands.verticalTabs!()),
68
78
  path: 'M2.5 3.5h11v9h-11zM6 3.5v9M2.5 6h3.5m-3.5 2.5h3.5',
69
79
  // The item names the arrangement it switches to.
70
80
  current: () => commands.verticalTabs!() ?
71
81
  {label: horizontalLabel, path: 'M2.5 3.5h11v9h-11zM2.5 6.5h11M6 3.5v3m3.5-3v3'} : undefined
82
+ }] : []),
83
+ // These two say what is shown, with a check mark while it is.
84
+ ...(commands.sectionsHidden && commands.setSectionsHidden ? [{
85
+ label: sectionsLabel, group: 'shown', run: () => commands.setSectionsHidden!(!commands.sectionsHidden!()),
86
+ path: '', checked: () => !commands.sectionsHidden!()
87
+ }] : []),
88
+ ...(commands.thumbnailHidden && commands.setThumbnailHidden ? [{
89
+ label: thumbnailLabel, group: 'shown', run: () => commands.setThumbnailHidden!(!commands.thumbnailHidden!()),
90
+ path: '', checked: () => !commands.thumbnailHidden!()
72
91
  }] : [])
73
92
  ];
74
- const entries = items.flatMap(({label, run, enabled, path, current}: typeof items[number] & {
93
+ const entries = items.flatMap(({label, group, run, enabled, path, current, checked}: typeof items[number] & {
94
+ group?: string;
75
95
  current?(): {label: string; path: string} | undefined;
96
+ checked?(): boolean;
76
97
  }) => {
77
98
  if (!run) return [];
78
99
  const item = document.createElement('button');
79
100
  item.type = 'button';
80
101
  const render = () => {
102
+ if (checked) {
103
+ const on = checked();
104
+ item.setAttribute('aria-checked', String(on));
105
+ item.replaceChildren(createIcon(document, on ? checkIconPath : ''), label);
106
+ return;
107
+ }
81
108
  const shown = current?.() ?? {label, path};
82
109
  item.replaceChildren(createIcon(document, shown.path), shown.label);
83
110
  };
84
111
  render();
85
112
  item.tabIndex = -1;
86
- item.setAttribute('role', 'menuitem');
113
+ item.setAttribute('role', checked ? 'menuitemcheckbox' : 'menuitem');
87
114
  item.addEventListener('click', () => {
88
115
  close(true);
89
116
  run();
90
117
  });
91
- return [{item, enabled, render: current && render}];
118
+ return [{item, group, enabled, render: (current || checked) && render}];
92
119
  });
93
120
  const buttons = entries.map(({item}) => item);
94
- popup.append(...buttons);
121
+ // A divider stands between groups of items, so it never leads the menu or doubles up when a group is missing.
122
+ entries.forEach(({item, group}, index) => {
123
+ if (index > 0 && group !== entries[index - 1].group) {
124
+ const divider = document.createElement('div');
125
+ divider.className = 'tw-plus-sprite-layout-menu-divider';
126
+ divider.setAttribute('role', 'separator');
127
+ popup.append(divider);
128
+ }
129
+ popup.append(item);
130
+ });
95
131
  let openedIn: Document | undefined;
96
132
  let topLayer = false;
97
133
 
@@ -21,6 +21,8 @@ import type {WorkspaceLayoutSession, WorkspaceLayoutStore, WorkspaceProjectIdent
21
21
  import type {SpriteVariableEdit, SpriteVariableEditError} from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
22
22
  import {SpriteMessagePane} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
23
23
  import type {MessageRenameError} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
24
+ import {functionLabel, SpriteFunctionPane} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
25
+ import type {FunctionKind, FunctionPaneData, FunctionPaneSettings, MountFunctionEditor, OpenScriptOptions, SpriteFunction, SpriteHatScript} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
24
26
  import type {MessageUse, ProjectMessage, TargetMessages} from '@kubohiroya/turbowarp-plus-editor-project-model/project-messages';
25
27
  import {createTargetTabMenuItem, spriteRenameLabel} from './target-tab-menu.ts';
26
28
 
@@ -88,6 +90,8 @@ type AssetKind = SpriteAssetKind;
88
90
 
89
91
  const variableSection = spriteEditorSections.indexOf('variables');
90
92
  const messageSection = spriteEditorSections.indexOf('messages');
93
+ const functionSection = spriteEditorSections.indexOf('functions');
94
+ const callSection = spriteEditorSections.indexOf('calls');
91
95
  // The first three sections are the GUI's own panels; the rest are rendered by this package.
92
96
  const lastNativeSection = 2;
93
97
 
@@ -162,6 +166,7 @@ interface TabOptions<Snapshot = unknown> {
162
166
  stagePane?: DockviewStagePane;
163
167
  variables?: boolean;
164
168
  messages?: boolean;
169
+ functions?: boolean;
165
170
  locale?: string;
166
171
  viewAdapter?: SpriteTabAdapter<Snapshot>;
167
172
  popouts?: {url: string; className?: string; openPalette?(view: SpriteTabView): void};
@@ -184,7 +189,7 @@ interface ToolbarSlot {
184
189
  interface AssetPreviewSlot {
185
190
  id: string;
186
191
  targetId: string;
187
- kind: AssetKind | 'variables' | 'messages';
192
+ kind: AssetKind | 'variables' | 'messages' | 'functions' | 'calls';
188
193
  editable: boolean;
189
194
  selected?: object;
190
195
  renderLayout?: SpriteAssetLayout;
@@ -266,7 +271,8 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
266
271
  const viewAdapter = multiView ? options.viewAdapter : undefined;
267
272
  const stagePane = multiView ? options.stagePane : undefined;
268
273
  const ownSection = (section: number) => (section === variableSection && Boolean(options.variables)) ||
269
- (section === messageSection && Boolean(options.messages));
274
+ (section === messageSection && Boolean(options.messages)) ||
275
+ ((section === functionSection || section === callSection) && Boolean(options.functions));
270
276
  const usesNativeSection = (section: number) => !ownSection(section);
271
277
  const sectionAvailable = (section: number) => section <= lastNativeSection || ownSection(section);
272
278
  const document = root.ownerDocument;
@@ -323,6 +329,12 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
323
329
  // Whether tabs stand in a column at the left of each split. It is the user's preference for every project.
324
330
  let verticalTabs = false;
325
331
  let tabsChosen = false;
332
+ // Whether the section buttons at the left of each sprite tab are hidden. It is also one preference for every project.
333
+ let sectionsHidden = false;
334
+ let sectionsChosen = false;
335
+ // Whether the costume thumbnail at the bottom right of each code area is hidden, for every project.
336
+ let thumbnailHidden = false;
337
+ let thumbnailChosen = false;
326
338
 
327
339
  const dockview = createDockview(root, {
328
340
  theme: themeLight,
@@ -388,9 +400,11 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
388
400
  if (multiView) {
389
401
  element.classList.add('tw-plus-sprite-tab-slot--split');
390
402
  body.className = 'tw-plus-sprite-tab-body';
403
+ body.toggleAttribute('data-thumbnail-hidden', thumbnailHidden);
391
404
  if (toolbar) {
392
405
  body.setAttribute('role', 'tabpanel');
393
406
  toolbar.className = 'tw-plus-sprite-tab-toolbar';
407
+ toolbar.toggleAttribute('data-sections-hidden', sectionsHidden);
394
408
  element.append(toolbar);
395
409
  }
396
410
  if (assetPreview) {
@@ -480,6 +494,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
480
494
  canSplit: () => views.has(group.activePanel?.id),
481
495
  verticalTabs: () => verticalTabs,
482
496
  setVerticalTabs,
497
+ ...(options.onToolbarSlots && {sectionsHidden: () => sectionsHidden, setSectionsHidden}),
498
+ thumbnailHidden: () => thumbnailHidden,
499
+ setThumbnailHidden,
483
500
  ...(popouts && {
484
501
  canOpenPanel,
485
502
  openPanel() {
@@ -526,6 +543,26 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
526
543
  refreshSurfaces();
527
544
  }
528
545
 
546
+ function setSectionsHidden(hidden: boolean, chosen = true) {
547
+ sectionsHidden = hidden;
548
+ for (const {toolbar} of slots.values()) toolbar?.toggleAttribute('data-sections-hidden', hidden);
549
+ if (chosen) {
550
+ sectionsChosen = true;
551
+ layoutStore?.writeSectionsHidden?.(hidden).catch(() => undefined);
552
+ }
553
+ // The code area is wider or narrower now, though the panel itself kept its size.
554
+ if (active) options.resize();
555
+ }
556
+
557
+ function setThumbnailHidden(hidden: boolean, chosen = true) {
558
+ thumbnailHidden = hidden;
559
+ for (const {body} of slots.values()) body.toggleAttribute('data-thumbnail-hidden', hidden);
560
+ if (chosen) {
561
+ thumbnailChosen = true;
562
+ layoutStore?.writeThumbnailHidden?.(hidden).catch(() => undefined);
563
+ }
564
+ }
565
+
529
566
  const canRename = (target: Target) =>
530
567
  target.isOriginal && !target.isStage && Boolean(vm.renameSprite) && vm.runtime.targets.includes(target);
531
568
 
@@ -609,7 +646,9 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
609
646
  if (ownSection(view.section) && slot.assetPreview) {
610
647
  slot.assetPreview.hidden = false;
611
648
  assetPreviews.push({id, targetId: descriptor.targetId,
612
- kind: view.section === messageSection ? 'messages' : 'variables', editable: active === view,
649
+ kind: view.section === messageSection ? 'messages' : view.section === functionSection ? 'functions' :
650
+ view.section === callSection ? 'calls' : 'variables',
651
+ editable: active === view,
613
652
  element: slot.assetPreview});
614
653
  continue;
615
654
  }
@@ -1318,6 +1357,12 @@ export function mountSpriteTabs<Snapshot>(root: HTMLElement, content: HTMLElemen
1318
1357
  readingTabs = false;
1319
1358
  updateLayoutState();
1320
1359
  });
1360
+ layoutStore?.readSectionsHidden?.().then(hidden => {
1361
+ if (!disposed && !sectionsChosen && hidden) setSectionsHidden(true, false);
1362
+ }, () => undefined);
1363
+ layoutStore?.readThumbnailHidden?.().then(hidden => {
1364
+ if (!disposed && !thumbnailChosen && hidden) setThumbnailHidden(true, false);
1365
+ }, () => undefined);
1321
1366
  if (persistence) window.addEventListener('pagehide', flushLayout);
1322
1367
  updateLayoutState();
1323
1368
  root.addEventListener('click', guardDocumentClose, true);
@@ -1401,6 +1446,31 @@ type SpriteTabsProps<Snapshot> = Omit<TabOptions<Snapshot>, 'activateSection' |
1401
1446
  openMessageTarget?(targetId: string): void;
1402
1447
  /** Rename a message everywhere in the project. The stage owns broadcast_msg variables. */
1403
1448
  renameMessage?(message: ProjectMessage, name: string): MessageRenameError | void;
1449
+ /**
1450
+ * The custom block definitions of this target, with its other hat scripts in `hats` for the list.
1451
+ * `readTargetFunctions` reads the definitions from the runtime.
1452
+ */
1453
+ getFunctions?(targetId: string): FunctionPaneData;
1454
+ /** Mount an editor of one definition script in an open item of the functions pane. */
1455
+ mountFunctionEditor?: MountFunctionEditor;
1456
+ /**
1457
+ * Open one function picked in the list or the call graph of the functions section, such as in a tab
1458
+ * split beside the sprite. Without it the function opens in a dialog.
1459
+ */
1460
+ openFunction?(targetId: string, fn: SpriteFunction, options?: OpenScriptOptions): void;
1461
+ /**
1462
+ * Open a hat script picked in the list of hats and functions, as `openFunction` opens a function.
1463
+ * `options.block` asks to show one block, such as a call picked in the list of a function's uses.
1464
+ */
1465
+ openScript?(targetId: string, hat: SpriteHatScript, options?: OpenScriptOptions): void;
1466
+ /** The function or hat script shown beside the sprite, which the list of hats and functions highlights. */
1467
+ selectedScript?: {targetId: string; id: string};
1468
+ /**
1469
+ * Make a new function in the target: a standard custom block or a TurboWarp-Plus named function.
1470
+ * Resolves with the id of the new hat, or with nothing when cancelled. Without it, the functions
1471
+ * section has no create button.
1472
+ */
1473
+ createFunction?(targetId: string, kind: FunctionKind): Promise<string | void>;
1404
1474
  getCodeSearchItems?(targetId: string): readonly SpriteSearchResult[];
1405
1475
  openCodeSearchResult?(targetId: string, id: string): void;
1406
1476
  };
@@ -1455,11 +1525,14 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1455
1525
  });
1456
1526
  const [toolbarSlots, setToolbarSlots] = React.useState<readonly ToolbarSlot[]>([]);
1457
1527
  const [assetPreviewSlots, setAssetPreviewSlots] = React.useState<readonly AssetPreviewSlot[]>([]);
1528
+ // The functions pane remounts when its view switches sections; keep the view, order and flow each view chose.
1529
+ const [functionSettings] = React.useState(() => new Map<string, FunctionPaneSettings>());
1458
1530
  const controller = React.useRef<SpriteTabsController<Snapshot>>(null);
1459
1531
  const hasVariables = Boolean(props.getVariables);
1460
1532
  const hasMessages = Boolean(props.getMessages);
1533
+ const hasFunctions = Boolean(props.getFunctions);
1461
1534
  const hasToolbar = Boolean(props.renderToolbar) || hasVariables;
1462
- const hasAssetPreview = Boolean(props.getAssetPreview) || hasVariables || hasMessages;
1535
+ const hasAssetPreview = Boolean(props.getAssetPreview) || hasVariables || hasMessages || hasFunctions;
1463
1536
  React.useLayoutEffect(() => {
1464
1537
  sections.current.append(...props.slots);
1465
1538
  parking.current.appendChild(content);
@@ -1507,6 +1580,7 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1507
1580
  stagePane: props.stagePane,
1508
1581
  variables: hasVariables,
1509
1582
  messages: hasMessages,
1583
+ functions: hasFunctions,
1510
1584
  locale: props.locale,
1511
1585
  viewAdapter: props.viewAdapter,
1512
1586
  popouts: props.popouts && {...props.popouts, className: props.className},
@@ -1525,7 +1599,7 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1525
1599
  };
1526
1600
  }, [content, props.enabled, props.vm, props.reopenLabel, props.multiView, props.locale,
1527
1601
  props.viewAdapter, props.stagePane, props.workspaceLayout, props.renameLabels, props.popouts, props.className,
1528
- hasVariables, hasMessages, hasToolbar, hasAssetPreview]);
1602
+ hasVariables, hasMessages, hasFunctions, hasToolbar, hasAssetPreview]);
1529
1603
  React.useLayoutEffect(() => {
1530
1604
  controller.current?.syncActiveSection(props.activeSection);
1531
1605
  }, [props.activeSection]);
@@ -1555,7 +1629,8 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1555
1629
  activeGroup: view.groupActive, propertiesInVariables: Boolean(props.getProperties),
1556
1630
  // A section with no port behind it would open an empty panel.
1557
1631
  availableSections: spriteEditorSections.filter(section =>
1558
- section !== 'messages' || Boolean(props.getMessages)),
1632
+ (section !== 'messages' || Boolean(props.getMessages)) &&
1633
+ (section !== 'functions' && section !== 'calls' || Boolean(props.getFunctions))),
1559
1634
  actions: view.active && currentSection !== 'variables' ? props.activeTools : undefined,
1560
1635
  onSectionChange: section => actions.setSection(spriteEditorSections.indexOf(section)),
1561
1636
  search: {
@@ -1568,6 +1643,10 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1568
1643
  } else if (section === 'messages') {
1569
1644
  items = (props.getMessages?.(view.targetId).messages ?? [])
1570
1645
  .map(message => ({id: message.key, label: message.name}));
1646
+ } else if (section === 'functions' || section === 'calls') {
1647
+ const data = props.getFunctions?.(view.targetId);
1648
+ items = [...(section === 'functions' ? data?.hats ?? [] : []).map(hat => ({id: hat.id, label: hat.label})),
1649
+ ...(data?.functions ?? []).map(fn => ({id: fn.id, label: functionLabel(fn)}))];
1571
1650
  } else {
1572
1651
  items = props.getAssetPreview?.(view.targetId, section).items.map((item, index) =>
1573
1652
  ({id: String(index), label: item.name})) ?? [];
@@ -1586,6 +1665,10 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1586
1665
  const pane = assetPreviewSlots.find(slot => slot.id === view.id)?.element;
1587
1666
  [...(pane?.querySelectorAll<HTMLElement>('[data-message-key]') ?? [])]
1588
1667
  .find(node => node.dataset.messageKey === result.id)?.focus();
1668
+ } else if (section === 'functions' || section === 'calls') {
1669
+ const pane = assetPreviewSlots.find(slot => slot.id === view.id)?.element;
1670
+ [...(pane?.querySelectorAll<HTMLElement>('[data-function-key], [data-hat-key]') ?? [])]
1671
+ .find(node => (node.dataset.functionKey ?? node.dataset.hatKey) === result.id)?.focus();
1589
1672
  } else workspace?.selectAsset(view.id, section, Number(result.id));
1590
1673
  }
1591
1674
  }
@@ -1601,6 +1684,24 @@ function SpriteTabs<Snapshot>(props: SpriteTabsProps<Snapshot>) {
1601
1684
  if (!result) workspace?.refreshSurfaces();
1602
1685
  return result;
1603
1686
  })
1687
+ }) : kind === 'functions' || kind === 'calls' ? React.createElement(SpriteFunctionPane, {
1688
+ // The list and the call graph are sections of their own.
1689
+ kind: 'functions', view: kind === 'calls' ? 'graph' : 'list',
1690
+ locale: props.locale, editable, data: props.getFunctions!(targetId),
1691
+ defaultSettings: functionSettings.get(id),
1692
+ onSettingsChange: (settings: FunctionPaneSettings) => functionSettings.set(id, settings),
1693
+ mountEditor: props.mountFunctionEditor,
1694
+ onOpenFunction: props.openFunction &&
1695
+ ((fn: SpriteFunction, options?: OpenScriptOptions) => props.openFunction!(targetId, fn, options)),
1696
+ onOpenScript: props.openScript &&
1697
+ ((hat: SpriteHatScript, options?: OpenScriptOptions) => props.openScript!(targetId, hat, options)),
1698
+ selectedId: props.selectedScript?.targetId === targetId ? props.selectedScript.id : undefined,
1699
+ onCreate: props.createFunction && (async (functionKind: FunctionKind) => {
1700
+ const created = await props.createFunction!(targetId, functionKind);
1701
+ // Show the new function now rather than at the next project change.
1702
+ if (created) workspace?.refreshSurfaces();
1703
+ return created;
1704
+ })
1604
1705
  }) : kind === 'variables' ? renderVariablePane(id, targetId, editable) :
1605
1706
  props.getAssetPreview && React.createElement(AssetPreview, {
1606
1707
  locale: props.locale, kind, selected, renderLayout, scrollTop, data: props.getAssetPreview(targetId, kind)
@@ -29,6 +29,12 @@ export interface WorkspaceLayoutStore {
29
29
  open(identity: WorkspaceProjectIdentity, signature: string): Promise<WorkspaceLayoutSession>;
30
30
  readTabsPosition(): Promise<TabsPosition | undefined>;
31
31
  writeTabsPosition(position: TabsPosition): Promise<void>;
32
+ /** Whether the section buttons of the sprite tabs are hidden, one preference for every project. */
33
+ readSectionsHidden?(): Promise<boolean | undefined>;
34
+ writeSectionsHidden?(hidden: boolean): Promise<void>;
35
+ /** Whether the costume thumbnail of the code areas is hidden, one preference for every project. */
36
+ readThumbnailHidden?(): Promise<boolean | undefined>;
37
+ writeThumbnailHidden?(hidden: boolean): Promise<void>;
32
38
  }
33
39
 
34
40
  export interface WorkspaceLayoutStoreOptions {
@@ -50,6 +56,8 @@ export const workspaceLayoutMaxBytes = 256 * 1024;
50
56
  const layoutsStore = 'layouts';
51
57
  const preferencesStore = 'preferences';
52
58
  const tabsPositionKey = 'tabsPosition';
59
+ const sectionsHiddenKey = 'sectionsHidden';
60
+ const thumbnailHiddenKey = 'thumbnailHidden';
53
61
  const legacyKeys = ['twPlusDockviewLayout', 'twPlusDockviewLayout.tabs'];
54
62
 
55
63
  interface LayoutRecord {
@@ -209,13 +217,28 @@ export function createWorkspaceLayoutStore({indexedDB: factory = globalThis.inde
209
217
  return value === 'left' || value === 'top' ? value : undefined;
210
218
  },
211
219
  writeTabsPosition(position) {
212
- return enqueue(async () => {
213
- const opened = await connect();
214
- const transaction = opened.transaction(preferencesStore, 'readwrite');
215
- const finished = completion(transaction);
216
- transaction.objectStore(preferencesStore).put(position, tabsPositionKey);
217
- await finished;
218
- });
219
- }
220
+ return writePreference(tabsPositionKey, position);
221
+ },
222
+ readSectionsHidden: () => readFlag(sectionsHiddenKey),
223
+ writeSectionsHidden: hidden => writePreference(sectionsHiddenKey, hidden),
224
+ readThumbnailHidden: () => readFlag(thumbnailHiddenKey),
225
+ writeThumbnailHidden: hidden => writePreference(thumbnailHiddenKey, hidden)
220
226
  };
227
+
228
+ async function readFlag(key: string) {
229
+ const opened = await connect();
230
+ const transaction = opened.transaction(preferencesStore, 'readonly');
231
+ const value = await result(transaction.objectStore(preferencesStore).get(key));
232
+ return typeof value === 'boolean' ? value : undefined;
233
+ }
234
+
235
+ function writePreference(key: string, value: unknown) {
236
+ return enqueue(async () => {
237
+ const opened = await connect();
238
+ const transaction = opened.transaction(preferencesStore, 'readwrite');
239
+ const finished = completion(transaction);
240
+ transaction.objectStore(preferencesStore).put(value, key);
241
+ await finished;
242
+ });
243
+ }
221
244
  }