@kubohiroya/turbowarp-plus-editor-workbench 0.6.0 → 0.8.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.
@@ -1,30 +1,51 @@
1
1
  import React, {createElement as element, type ComponentType} from 'react';
2
- import {createPortal} from 'react-dom';
3
2
 
4
3
  const labels = {
5
4
  ja: {
6
5
  open: 'ステージを開く',
7
6
  menu: 'ステージの開き方',
8
- window: '別ウィンドウで開く',
9
- fullscreen: '別ウィンドウで全画面で開く',
10
- tab: 'ステージをタブで開く',
11
- drawer: 'ステージを引き出しで開く',
12
- enterFullscreen: '全画面にする'
7
+ window: '別ウィンドウで表示',
8
+ tab: 'タブで表示',
9
+ drawer: '引出しで表示'
13
10
  },
14
11
  en: {
15
12
  open: 'Open stage',
16
13
  menu: 'Stage opening options',
17
- window: 'Open in a separate window',
18
- fullscreen: 'Open fullscreen in a separate window',
19
- tab: 'Open stage in a tab',
20
- drawer: 'Open stage in the drawer',
21
- enterFullscreen: 'Enter fullscreen'
14
+ window: 'Show in a separate window',
15
+ tab: 'Show in a tab',
16
+ drawer: 'Show in the drawer'
22
17
  }
23
18
  };
24
19
 
25
- const modes = ['window', 'fullscreen', 'tab', 'drawer'] as const;
20
+ const modes = ['window', 'tab', 'drawer'] as const;
26
21
  type StageMode = typeof modes[number];
27
22
  const textFor = (locale: string) => /^ja(?:-|$)/i.test(locale) ? labels.ja : labels.en;
23
+ const icons: Record<StageMode, string> = {
24
+ window: 'M7 3H3v10h10V9m-5-1 5-5m-4 0h4v4',
25
+ tab: 'M2.5 6V3.5H7L8.5 6h5v6.5h-11zM2.5 6H9',
26
+ drawer: 'M2.5 3.5h11v9h-11zM10.5 3.5v9M8.5 8h-4m1.5-1.5L4.5 8 6 9.5'
27
+ };
28
+
29
+ export function stagePresentationItems(locale: string, current: StageMode | null,
30
+ actions: Partial<Record<StageMode, () => void>>): MenuItem[] {
31
+ const text = textFor(locale);
32
+ return modes.map(id => ({
33
+ id, label: text[id], current: current === id, disabled: !actions[id], onSelect: actions[id],
34
+ icon: element('svg', {viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4,
35
+ strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true}, element('path', {d: icons[id]}))
36
+ }));
37
+ }
38
+
39
+ export function useStageDocumentFullscreen(doc?: Document) {
40
+ const [fullscreenDocument, setFullscreenDocument] = React.useState<Document>();
41
+ React.useLayoutEffect(() => {
42
+ const update = () => setFullscreenDocument(doc?.fullscreenElement ? doc : undefined);
43
+ update();
44
+ doc?.addEventListener('fullscreenchange', update);
45
+ return () => doc?.removeEventListener('fullscreenchange', update);
46
+ }, [doc]);
47
+ return Boolean(doc && fullscreenDocument === doc);
48
+ }
28
49
 
29
50
  export interface StageDockAction {
30
51
  kind: 'docked' | 'opening' | 'external';
@@ -38,13 +59,14 @@ interface MenuItem {
38
59
  label: string;
39
60
  current: boolean;
40
61
  disabled: boolean;
41
- onSelect(): void;
62
+ icon: React.ReactNode;
63
+ onSelect?(): void;
42
64
  }
43
65
 
44
66
  export interface StageLauncherOptions {
45
67
  mount: HTMLElement;
46
68
  styles: Record<string, string>;
47
- MenuButton: ComponentType<{label: string; icon: React.ReactNode; items: MenuItem[]; className: string}>;
69
+ MenuButton: ComponentType<{label: string; icon: React.ReactNode; items: MenuItem[]; className: string; disabled?: boolean}>;
48
70
  }
49
71
 
50
72
  interface StageLauncherProps {
@@ -53,94 +75,52 @@ interface StageLauncherProps {
53
75
  dockAction?: StageDockAction;
54
76
  tab?: {docked: boolean; commands: {open(): void} | null};
55
77
  drawerOpen: boolean;
78
+ savedDrawerSelected?: boolean;
79
+ editorFullscreen?: boolean;
56
80
  focusDrawer(): void;
57
81
  revealStage(): void;
58
82
  }
59
83
 
60
- export function StageLauncher({locale, options, dockAction, tab, drawerOpen, focusDrawer, revealStage}: StageLauncherProps) {
61
- const [fullscreen, setFullscreen] = React.useState(false);
62
- const exitFullscreen = React.useCallback(() => setFullscreen(false), []);
84
+ export function StageLauncher({locale, options, dockAction, tab, drawerOpen, savedDrawerSelected, editorFullscreen,
85
+ focusDrawer, revealStage}: StageLauncherProps) {
86
+ const [localDrawerSelected, setLocalDrawerSelected] = React.useState(false);
87
+ const drawerSelected = savedDrawerSelected ?? localDrawerSelected;
63
88
  const {styles, MenuButton} = options;
64
89
  const text = textFor(locale);
65
90
  const separate = dockAction?.kind === 'opening' || dockAction?.kind === 'external';
66
- const child = separate ? dockAction.mount?.ownerDocument : undefined;
67
- const mode = separate ? (fullscreen ? 'fullscreen' : 'window') :
68
- (tab?.docked ? 'tab' : (drawerOpen ? 'drawer' : null));
91
+ const mode = separate ? 'window' : (tab?.docked ? 'tab' : (drawerOpen ? 'drawer' : null));
92
+ const disabled = Boolean(editorFullscreen || mode);
69
93
  const available = {
70
94
  window: Boolean(dockAction?.external),
71
- fullscreen: Boolean(dockAction?.external),
72
95
  tab: Boolean(tab?.commands),
73
96
  drawer: true
74
97
  };
98
+ const defaultTarget = drawerSelected || !available.window ? 'drawer' : 'window';
75
99
 
76
100
  React.useLayoutEffect(() => {
77
- if (!separate) setFullscreen(false);
78
- }, [separate]);
101
+ if (savedDrawerSelected === undefined && mode && !editorFullscreen) setLocalDrawerSelected(mode === 'drawer');
102
+ }, [mode, editorFullscreen, savedDrawerSelected]);
79
103
 
80
104
  function activate(target: StageMode) {
81
- if (mode && target !== mode) return;
82
- if (separate) {
83
- child?.defaultView?.focus();
84
- return;
85
- }
86
- if (!available[target]) return;
105
+ if (disabled || !available[target]) return;
87
106
  revealStage();
88
107
  if (target === 'drawer') focusDrawer();
89
108
  else if (target === 'tab') tab?.commands?.open();
90
- else {
91
- setFullscreen(target === 'fullscreen');
92
- // Keep opening the popup on the original user gesture.
93
- dockAction?.undock();
94
- }
109
+ else dockAction?.undock();
95
110
  }
96
111
 
97
- return element(React.Fragment, null,
98
- element('div', {className: styles.stageLauncher},
112
+ const actions: Partial<Record<StageMode, () => void>> = {};
113
+ for (const target of modes) {
114
+ if (!disabled && available[target]) actions[target] = () => activate(target);
115
+ }
116
+ return element('div', {className: styles.stageLauncher},
99
117
  element('button', {
100
118
  type: 'button',
101
119
  className: styles.stageLauncherAction,
102
- disabled: !mode && !available.window,
103
- onClick: () => activate(mode ?? 'window')
104
- }, text[mode ?? 'open']),
105
- element(MenuButton, {label: text.menu, icon: '▾', className: styles.stageLauncherMenu, items: modes.map(id => ({
106
- id, label: text[id], current: mode === id, disabled: mode ? mode !== id : !available[id],
107
- onSelect: () => activate(id)
108
- }))})),
109
- mode === 'fullscreen' && dockAction?.mount &&
110
- element(PopupFullscreen, {mount: dockAction.mount, label: text.enterFullscreen,
111
- className: styles.stageFullscreenPrompt, onExit: exitFullscreen}));
112
- }
113
-
114
- function PopupFullscreen({mount, label, className, onExit}: {
115
- mount: HTMLElement;
116
- label: string;
117
- className: string;
118
- onExit(): void;
119
- }) {
120
- const child = mount.ownerDocument;
121
- const [needsGesture, setNeedsGesture] = React.useState(false);
122
- const enter = React.useCallback(async () => {
123
- try {
124
- if (!child.fullscreenElement) await child.documentElement.requestFullscreen();
125
- setNeedsGesture(false);
126
- } catch {
127
- setNeedsGesture(true);
128
- }
129
- }, [child]);
130
-
131
- React.useEffect(() => {void enter();}, [enter]);
132
- React.useEffect(() => {
133
- let wasFullscreen = Boolean(child.fullscreenElement);
134
- const changed = () => {
135
- if (child.fullscreenElement) wasFullscreen = true;
136
- else if (wasFullscreen) onExit();
137
- };
138
- child.addEventListener('fullscreenchange', changed);
139
- return () => child.removeEventListener('fullscreenchange', changed);
140
- }, [child, onExit]);
141
-
142
- // Mount a separate React portal so the child document receives the trusted click.
143
- return needsGesture ? createPortal(
144
- element('button', {type: 'button', className, onClick: enter}, label), mount
145
- ) : null;
120
+ disabled,
121
+ onClick: () => activate(defaultTarget)
122
+ }, text.open),
123
+ element(MenuButton, {label: text.menu, icon: '▾', disabled,
124
+ className: `${styles.stageLauncherMenu} ${styles.stagePresentationMenu}`,
125
+ items: stagePresentationItems(locale, mode ?? (drawerSelected ? 'drawer' : null), actions)}));
146
126
  }
@@ -0,0 +1,47 @@
1
+ import React from 'react';
2
+
3
+ export function StageResizeHandle({edge, aspect, width, limits, label, className, drawer = false}) {
4
+ const drag = React.useRef(null);
5
+ const corner = edge === 'corner';
6
+ const horizontal = edge === 'left' || edge === 'right';
7
+ const resize = next => limits.resize(Math.round(Math.max(limits.minimum, Math.min(limits.maximum, next))));
8
+ return React.createElement('div', {
9
+ className,
10
+ 'data-stage-resize': edge,
11
+ 'data-stage-drawer-resize': drawer || undefined,
12
+ role: corner ? undefined : 'separator',
13
+ 'aria-orientation': corner ? undefined : (horizontal ? 'vertical' : 'horizontal'),
14
+ 'aria-label': corner ? undefined : label,
15
+ 'aria-valuemin': corner ? undefined : limits.minimum,
16
+ 'aria-valuemax': corner ? undefined : limits.maximum,
17
+ 'aria-valuenow': corner ? undefined : width,
18
+ tabIndex: corner ? undefined : 0,
19
+ title: label,
20
+ onPointerDown: event => {
21
+ if (event.button !== 0 || drag.current) return;
22
+ drag.current = {id: event.pointerId, x: event.clientX, y: event.clientY, width};
23
+ event.currentTarget.setPointerCapture(event.pointerId);
24
+ event.preventDefault();
25
+ },
26
+ onPointerMove: event => {
27
+ const start = drag.current;
28
+ if (start?.id !== event.pointerId) return;
29
+ const dx = (event.clientX - start.x) * (edge === 'right' ? 1 : -1);
30
+ const dy = (event.clientY - start.y) * aspect * (edge === 'top' ? -1 : 1);
31
+ const delta = corner ? (Math.abs(dx) >= Math.abs(dy) ? dx : dy) : (horizontal ? dx : dy);
32
+ resize(start.width + delta);
33
+ },
34
+ onLostPointerCapture: () => {drag.current = null;},
35
+ onKeyDown: event => {
36
+ const grow = {left: 'ArrowLeft', right: 'ArrowRight', top: 'ArrowUp', bottom: 'ArrowDown'}[edge];
37
+ const shrink = {left: 'ArrowRight', right: 'ArrowLeft', top: 'ArrowDown', bottom: 'ArrowUp'}[edge];
38
+ if (event.key === grow) resize(width + 16);
39
+ else if (event.key === shrink) resize(width - 16);
40
+ else if (event.key === 'Home') resize(limits.minimum);
41
+ else if (event.key === 'End') resize(limits.maximum);
42
+ else return;
43
+ event.preventDefault();
44
+ event.stopPropagation();
45
+ }
46
+ });
47
+ }
@@ -5,6 +5,8 @@ import {createDockview, themeLight} from 'dockview';
5
5
  import {StageLauncher, type StageDockAction, type StageLauncherOptions} from './stage-launcher.ts';
6
6
 
7
7
  export type {StageDockAction, StageLauncherOptions} from './stage-launcher.ts';
8
+ export {stagePresentationItems, useStageDocumentFullscreen} from './stage-launcher.ts';
9
+ export {StageResizeHandle} from './stage-resize-handle.ts';
8
10
 
9
11
  interface StageWindowConnection<Target> {
10
12
  ready: Promise<Target>;
@@ -47,7 +49,8 @@ export function createStagePopoutHost<Request, Target extends {mount: HTMLElemen
47
49
  disableAutoResizing: true
48
50
  });
49
51
  dockview = view;
50
- view.addPanel({id: 'stage', component: 'stage', title});
52
+ const group = view.addGroup({direction: 'right', hideHeader: true});
53
+ view.addPanel({id: 'stage', component: 'stage', title, position: {referenceGroup: group}});
51
54
  removed = view.onDidRemovePanel(disconnect);
52
55
  const layout = () => {
53
56
  if (mount.clientWidth > 0 && mount.clientHeight > 0) view.layout(mount.clientWidth, mount.clientHeight);
@@ -100,7 +103,8 @@ export function stageDockActionLabel(locale: string, {drawer, detached, external
100
103
  }
101
104
 
102
105
  type StagePlacement = Pick<NonNullable<ReturnType<typeof useDockviewStage>>, 'surface' | 'inlineRef' | 'docked'> &
103
- Partial<Pick<NonNullable<ReturnType<typeof useDockviewStage>>, 'commands'>>;
106
+ Partial<Pick<NonNullable<ReturnType<typeof useDockviewStage>>,
107
+ 'commands' | 'drawerLayout' | 'updateDrawer' | 'resetDrawerPresentation'>>;
104
108
 
105
109
  export function createStageSurface(React: typeof import('react'), {
106
110
  context, EdgeDrawer, Panel
@@ -115,15 +119,27 @@ export function createStageSurface(React: typeof import('react'), {
115
119
  EdgeDrawer: ElementType;
116
120
  Panel: ElementType;
117
121
  }) {
118
- return function StageSurface({externalHost, onDockActionChange, placement, dockAction, launcher, ...props}: {
122
+ return function StageSurface({externalHost, onDockActionChange, placement, dockAction, launcher,
123
+ openDrawerRef, closeDrawerRef, editorFullscreen, ...props}: {
119
124
  placement?: StagePlacement;
120
125
  dockAction?: StageDockAction;
121
126
  launcher?: StageLauncherOptions;
127
+ openDrawerRef?: {current: (() => void) | null};
128
+ closeDrawerRef?: {current: (() => void) | null};
129
+ editorFullscreen?: boolean;
122
130
  [key: string]: any;
123
131
  }) {
124
132
  const {locale, stageDrawer, stageHidden, setStageDrawerOpen, setStageVisible} = React.useContext(context);
125
133
  const [drawerOpen, setDrawerOpen] = React.useState(false);
126
- const focusDrawer = React.useRef<() => void>(null);
134
+ const localDrawerRef = React.useRef<() => void>(null);
135
+ const focusDrawer = openDrawerRef ?? localDrawerRef;
136
+ const updateDrawer = placement?.updateDrawer;
137
+ const resetDrawerPresentation = placement?.resetDrawerPresentation;
138
+ const drawerLayout = placement?.drawerLayout;
139
+ const stageOutsideDrawer = Boolean(editorFullscreen || dockAction?.kind === 'external' || placement?.docked);
140
+ React.useLayoutEffect(() => {
141
+ if (stageOutsideDrawer) resetDrawerPresentation?.();
142
+ }, [stageOutsideDrawer, resetDrawerPresentation, drawerLayout?.open, drawerLayout?.selected]);
127
143
  const onOpenChange = React.useCallback((open: boolean) => {
128
144
  setStageDrawerOpen?.(open);
129
145
  setDrawerOpen(open);
@@ -146,19 +162,26 @@ export function createStageSurface(React: typeof import('react'), {
146
162
  }) : panel;
147
163
  const dock = stageDrawer ? React.createElement(EdgeDrawer, {
148
164
  edge: 'right',
165
+ movableStage: true,
166
+ available: !placement?.docked && (!dockAction || dockAction.kind === 'docked'),
167
+ stageDrawerLayout: drawerLayout,
168
+ updateStageDrawer: updateDrawer,
149
169
  label: japanese ? 'ステージを展開' : 'Reveal stage',
150
170
  onOpenChange,
151
171
  focusPanelRef: launcher ? focusDrawer : undefined,
172
+ closePanelRef: launcher ? closeDrawerRef : undefined,
152
173
  focusBoundary: launcher?.mount,
153
- // The menu bar launcher replaces the edge handle.
174
+ // With the launcher, the handle appears after the drawer has been opened once.
154
175
  showTrigger: !launcher,
155
176
  portalContent: Boolean(placement),
156
177
  holdOpenSelector: '[data-turbowarp-app-shell-source-chooser][role="dialog"][aria-modal="true"]'
157
178
  }, inline) : inline;
158
- const launcherView = stageDrawer && launcher ? createPortal(React.createElement(StageLauncher, {
179
+ const launcherView = launcher && (stageDrawer || editorFullscreen) ? createPortal(React.createElement(StageLauncher, {
159
180
  locale, options: launcher, dockAction,
160
181
  tab: placement?.commands ? {docked: placement.docked, commands: placement.commands} : undefined,
161
- drawerOpen: drawerOpen && !stageHidden,
182
+ drawerOpen: stageDrawer && drawerOpen && !stageHidden,
183
+ savedDrawerSelected: updateDrawer ? Boolean(drawerLayout?.selected) : undefined,
184
+ editorFullscreen,
162
185
  focusDrawer: () => focusDrawer.current?.(),
163
186
  revealStage: () => {if (stageHidden) setStageVisible?.(true);}
164
187
  }), launcher.mount) : null;
@@ -2,6 +2,8 @@ import {createLayout, createSplitter, splitAxis} from './index.ts';
2
2
  import {createTargetList} from './targets.ts';
3
3
  import type {DrawerViews} from './drawer-views.ts';
4
4
  import {availableDrawerViews, createDrawerViewBar, hasDrawerBar, readDrawerView, writeDrawerView} from './drawer-views.ts';
5
+ import {attachStageDrawerDrag} from './stage-drawer-drag.ts';
6
+ import type {StageDrawerLayout, StageDrawerPosition} from './workspace-layout.ts';
5
7
 
6
8
  export type {DrawerMenu, DrawerMenuRenderProps, DrawerRenderProps, DrawerView, DrawerViewId, DrawerViews,
7
9
  HostDrawerViewId} from './drawer-views.ts';
@@ -24,7 +26,9 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
24
26
 
25
27
  function StandardLayout({
26
28
  enabled, splitter, windowLayout, stageActionEnabled, stageDrawer = false,
27
- onPaletteModeChange, windowTools, Container, render, drawerViews = undefined as DrawerViews | undefined, ...props
29
+ onPaletteModeChange, windowTools, Container, render, drawerViews = undefined as DrawerViews | undefined,
30
+ stageDrawerLayout = undefined as StageDrawerLayout | undefined,
31
+ updateStageDrawer = undefined as ((patch: Partial<StageDrawerLayout>) => void) | undefined, ...props
28
32
  }) {
29
33
  const [showUndock, setShowUndock] = useState(false);
30
34
  const [targetsPinned, setTargetsPinned] = useState(true);
@@ -77,12 +81,16 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
77
81
  const editorSpace = targetsPinned ?
78
82
  (targetSplit?.second ?? bodyWidth - (wideDrawer ? fixedDrawerWidth : singleColumnTargetWidth)) : bodyWidth;
79
83
  const maximumStageWidth = Math.max(1, Math.floor(Math.min(editorSpace - 24,
84
+ stageDrawer ? (size?.viewportWidth ?? bodyWidth) - 12 : Infinity,
80
85
  ((size?.height ?? 640) - 112) * props.stageAspect)));
81
86
  const defaultStageWidth = Math.min(maximumStageWidth, Math.floor(Math.min(props.defaultStageWidth, 360, bodyWidth / 2)));
82
87
  const minimumStageWidth = Math.min(defaultStageWidth, 280);
83
- const stageWidth = Math.max(minimumStageWidth, Math.min(maximumStageWidth, preferredStageWidth ?? defaultStageWidth));
88
+ const preferredWidth = stageDrawer && updateStageDrawer ? stageDrawerLayout?.width : preferredStageWidth;
89
+ const resizeStage = stageDrawer && updateStageDrawer ?
90
+ (width: number | undefined) => updateStageDrawer({width}) : setPreferredStageWidth;
91
+ const stageWidth = Math.max(minimumStageWidth, Math.min(maximumStageWidth, preferredWidth ?? defaultStageWidth));
84
92
  const stageResize = plusLayout && maximumStageWidth > minimumStageWidth ?
85
- {minimum: minimumStageWidth, maximum: maximumStageWidth, resize: setPreferredStageWidth} : null;
93
+ {minimum: minimumStageWidth, maximum: maximumStageWidth, resize: resizeStage} : null;
86
94
 
87
95
  useLayoutEffect(() => {
88
96
  if (enabled) onPaletteModeChange?.(true);
@@ -94,13 +102,20 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
94
102
  if (!Observer) return;
95
103
  const measure = () => {
96
104
  const {clientWidth: width, clientHeight: height} = node;
97
- setSize(previous => previous?.width === width && previous.height === height ? previous : {width, height});
105
+ const viewportWidth = node.ownerDocument.documentElement.clientWidth;
106
+ setSize(previous => previous?.width === width && previous.height === height &&
107
+ previous.viewportWidth === viewportWidth ? previous : {width, height, viewportWidth});
98
108
  };
99
109
  const observer = new Observer(measure);
100
110
  measure();
101
111
  observer.observe(node);
102
- return () => observer.disconnect();
103
- }, []);
112
+ const view = node.ownerDocument.defaultView;
113
+ if (stageDrawer) view.addEventListener('resize', measure);
114
+ return () => {
115
+ observer.disconnect();
116
+ if (stageDrawer) view.removeEventListener('resize', measure);
117
+ };
118
+ }, [stageDrawer]);
104
119
 
105
120
  const renderEditorTabRow = (tabs, action) => element('div', {className: styles.tabRow}, tabs,
106
121
  (layoutMenu || windowTools) && element('div', {className: styles.layoutTools}, layoutMenu, windowTools), action);
@@ -122,7 +137,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
122
137
  const stageOverlaps = showStage && (!stageDrawer || stageDrawerOpen);
123
138
  const bodyStyle = {
124
139
  display: 'grid',
125
- '--plus-stage-overlap': stageOverlaps ? stageOverlap : '0px',
140
+ '--plus-stage-overlap': showStage && !stageDrawer ? stageOverlap : '0px',
126
141
  '--plus-stage-tab-inset': stageOverlaps ? stageOverlap : '3rem'
127
142
  };
128
143
  if (resizable) {
@@ -151,7 +166,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
151
166
  targetClassName: targetsPinned ? styles.standardTargets :
152
167
  `${styles.standardTargets} ${styles.retractedTargets}`,
153
168
  stageDisplayWidth: stageWidth,
154
- handleStagePreset: () => setPreferredStageWidth(null),
169
+ handleStagePreset: () => resizeStage(undefined),
155
170
  editorWidth: targetsPinned && resizable ? targetSplit.second : size?.width
156
171
  };
157
172
  };
@@ -180,14 +195,52 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
180
195
  }
181
196
 
182
197
  function EdgeDrawer({edge, label, pinned = false, onOpenChange, portalContent = false, holdOpenSelector = '',
183
- focusPanelRef = undefined, focusBoundary = undefined, showTrigger = true, children}) {
198
+ focusPanelRef = undefined, closePanelRef = undefined, focusBoundary = undefined, showTrigger = true,
199
+ movableStage = false, available = true, stageDrawerLayout = undefined as StageDrawerLayout | undefined,
200
+ updateStageDrawer = undefined as ((patch: Partial<StageDrawerLayout>) => void) | undefined, children}) {
184
201
  const [hovered, setHovered] = useState(false);
185
- const [engaged, setEngaged] = useState(false);
202
+ const [localEngaged, setLocalEngaged] = useState(false);
186
203
  const [heldOpen, setHeldOpen] = useState(false);
187
204
  const drawer = useRef(null);
188
205
  const trigger = useRef(null);
189
206
  const panel = useRef(null);
190
- const open = pinned || hovered || engaged || heldOpen;
207
+ const opened = useRef(false);
208
+ const stageDrag = useRef(null);
209
+ const engaged = updateStageDrawer ? Boolean(stageDrawerLayout?.open) : localEngaged;
210
+ const setEngaged = React.useCallback((engaged: boolean) => {
211
+ if (updateStageDrawer) updateStageDrawer({open: engaged, ...(engaged && {selected: true})});
212
+ else setLocalEngaged(engaged);
213
+ }, [updateStageDrawer]);
214
+ const selected = updateStageDrawer ? Boolean(stageDrawerLayout?.selected) : opened.current;
215
+ const open = available && (pinned || engaged || heldOpen ||
216
+ (hovered && (!updateStageDrawer || showTrigger || selected)));
217
+ const stageTrigger = movableStage && available && (showTrigger || selected);
218
+
219
+ useLayoutEffect(() => {
220
+ if (open) opened.current = true;
221
+ if (!available) {
222
+ setHovered(false);
223
+ setLocalEngaged(false);
224
+ }
225
+ }, [open, available]);
226
+
227
+ useLayoutEffect(() => {
228
+ if (!movableStage) return;
229
+ const node = drawer.current as HTMLElement;
230
+ const stage = node.closest<HTMLElement>(`.${styles.stageDrawer}`);
231
+ const editor = stage?.closest<HTMLElement>(`.${styles.standardBody}`);
232
+ if (!editor || !node.ownerDocument.defaultView?.ResizeObserver) return;
233
+ const controller = attachStageDrawerDrag(node, stage, editor, () => panel.current.focus({preventScroll: true}),
234
+ (position: StageDrawerPosition) => updateStageDrawer?.({position}));
235
+ stageDrag.current = controller;
236
+ return () => {
237
+ stageDrag.current = null;
238
+ controller.dispose();
239
+ };
240
+ }, [movableStage, updateStageDrawer]);
241
+ useLayoutEffect(() => {
242
+ stageDrag.current?.setPosition(stageDrawerLayout?.position);
243
+ }, [movableStage, stageDrawerLayout?.position, updateStageDrawer]);
191
244
 
192
245
  useLayoutEffect(() => {
193
246
  if (!holdOpenSelector) return;
@@ -211,6 +264,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
211
264
  useLayoutEffect(() => {onOpenChange?.(open);}, [open, onOpenChange]);
212
265
 
213
266
  const enter = (event: PointerEvent) => {
267
+ if (movableStage && !showTrigger && !open) return;
214
268
  if (event.pointerType === 'mouse') setHovered(true);
215
269
  };
216
270
  const leave = () => setHovered(false);
@@ -219,10 +273,14 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
219
273
  };
220
274
  const blur = (event: FocusEvent) => {
221
275
  const target = event.relatedTarget as Node;
276
+ const source = event.target as HTMLButtonElement;
277
+ // Opening the stage disables the launcher before focus moves into the drawer.
278
+ if (!target && source.disabled && focusBoundary?.contains(source)) return;
222
279
  if (!drawer.current.contains(target) && !focusBoundary?.contains(target)) setEngaged(false);
223
280
  };
224
281
 
225
282
  const focusPanel = () => {
283
+ if (!available) return;
226
284
  setEngaged(true);
227
285
  const frame = drawer.current.ownerDocument.defaultView;
228
286
  frame.requestAnimationFrame(() => {
@@ -233,12 +291,33 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
233
291
  if (!focusPanelRef) return;
234
292
  focusPanelRef.current = focusPanel;
235
293
  return () => {focusPanelRef.current = null;};
236
- }, [focusPanelRef]);
294
+ }, [focusPanelRef, available, setEngaged]);
295
+
296
+ const closePanel = React.useCallback(() => {
297
+ setHovered(false);
298
+ setEngaged(false);
299
+ const button = (showTrigger ? trigger.current : focusBoundary?.querySelector('button')) as HTMLButtonElement | undefined;
300
+ if (button?.disabled) {
301
+ button.ownerDocument.defaultView?.requestAnimationFrame(() => button.focus({preventScroll: true}));
302
+ } else button?.focus({preventScroll: true});
303
+ }, [focusBoundary, showTrigger, setEngaged]);
304
+ useLayoutEffect(() => {
305
+ if (!closePanelRef || !open) return;
306
+ closePanelRef.current = closePanel;
307
+ return () => {closePanelRef.current = null;};
308
+ }, [closePanelRef, closePanel, open]);
309
+
310
+ const closeOnEscape = event => {
311
+ if (event.key !== 'Escape' || pinned || heldOpen || !open || event.defaultPrevented ||
312
+ (movableStage && (event.target as Element).closest('[role="menu"]'))) return;
313
+ closePanel();
314
+ event.stopPropagation();
315
+ };
237
316
  useLayoutEffect(() => {
238
317
  if (!focusBoundary) return;
239
318
  focusBoundary.addEventListener('focusout', blur);
240
319
  return () => focusBoundary.removeEventListener('focusout', blur);
241
- }, [focusBoundary]);
320
+ }, [focusBoundary, setEngaged]);
242
321
 
243
322
  useLayoutEffect(() => {
244
323
  if (!portalContent) return;
@@ -254,33 +333,43 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
254
333
  node.removeEventListener('focusin', focus);
255
334
  node.removeEventListener('focusout', blur);
256
335
  };
257
- }, [portalContent, focusBoundary]);
336
+ }, [portalContent, focusBoundary, open, showTrigger, movableStage, setEngaged]);
337
+
338
+ useLayoutEffect(() => {
339
+ if (!portalContent || !movableStage || !open) return;
340
+ const node = drawer.current as HTMLElement;
341
+ node.addEventListener('keydown', closeOnEscape);
342
+ return () => node.removeEventListener('keydown', closeOnEscape);
343
+ }, [portalContent, movableStage, open, heldOpen, pinned, closePanel]);
258
344
 
259
345
  return element('div', {
260
346
  className: styles.edgeDrawer,
261
347
  ref: drawer,
262
348
  'data-edge': edge,
263
349
  'data-pinned': pinned || undefined,
350
+ 'data-movable-stage': movableStage || undefined,
351
+ 'data-stage-drawer-open': movableStage && open || undefined,
352
+ 'data-stage-drawer-unavailable': movableStage && !available || undefined,
264
353
  ...(!portalContent && {onPointerEnter: enter, onPointerLeave: leave, onFocus: focus, onBlur: blur}),
265
- onKeyDown: event => {
266
- if (event.key !== 'Escape' || pinned || heldOpen || !open || event.defaultPrevented) return;
267
- setHovered(false);
268
- setEngaged(false);
269
- // Without its own trigger, the drawer returns focus to the control that opened it.
270
- (trigger.current ?? focusBoundary?.querySelector('button'))?.focus();
271
- event.stopPropagation();
272
- }
354
+ onKeyDown: portalContent && movableStage ? undefined : closeOnEscape
273
355
  },
274
- showTrigger && element('button', {
356
+ (movableStage ? stageTrigger : showTrigger) && element('button', {
275
357
  type: 'button',
276
358
  className: styles.edgeTrigger,
277
359
  hidden: pinned,
278
360
  'aria-label': label,
279
361
  'aria-expanded': open,
362
+ 'data-stage-drawer-trigger': movableStage || undefined,
363
+ 'data-stage-drawer-trigger-collapsed': movableStage && !showTrigger || undefined,
280
364
  ref: trigger,
281
365
  onClick: focusPanel
282
- }, {left: '›', right: '‹', bottom: '⌃'}[edge]),
283
- element('div', {className: styles.edgePanel, ref: panel, tabIndex: -1, hidden: !open}, children));
366
+ }, movableStage ? null : {left: '›', right: '‹', bottom: '⌃'}[edge]),
367
+ element('div', {
368
+ className: styles.edgePanel, ref: panel, tabIndex: -1,
369
+ hidden: !movableStage && !open,
370
+ 'aria-hidden': movableStage && !open || undefined,
371
+ inert: movableStage && !open ? '' : undefined
372
+ }, children));
284
373
  }
285
374
 
286
375
  function TargetLayout({compact, render}) {
@@ -17,6 +17,10 @@ interface MenuPrimitives {
17
17
 
18
18
  const pencil = 'm4 16-1 5 5-1L21 7l-4-4L4 16Zm10-10 4 4';
19
19
  const open = 'M13 4h7v7m0-7-9 9m-1-8H4v15h15v-6';
20
+ const tabMenuIcons = {
21
+ rename: pencil,
22
+ 'new-tab': 'M3 4h18v16H3zM3 10h18M11 4l3 6m-4 5h4m-2-2v4'
23
+ };
20
24
  const iconClass = 'tw-plus-target-menu-icon';
21
25
  const svgNamespace = 'http://www.w3.org/2000/svg';
22
26
  const isJapanese = (locale: string) => /^ja(?:-|$)/i.test(locale);
@@ -24,7 +28,8 @@ export const spriteRenameLabel = (locale: string) => isJapanese(locale) ? 'ス
24
28
 
25
29
  export const SpriteTargetTabsContext = React.createContext<TargetTabs | null>(null);
26
30
 
27
- export function createRenameMenuItem(document: Document, title: string, rename: (id: string) => void): IContextMenuItemRenderer {
31
+ export function createTargetTabMenuItem(document: Document, title: string, iconName: keyof typeof tabMenuIcons,
32
+ action: (id: string) => void): IContextMenuItemRenderer {
28
33
  const element = document.createElement('button');
29
34
  element.type = 'button';
30
35
  element.className = 'dv-context-menu-item tw-plus-target-menu-button';
@@ -34,7 +39,7 @@ export function createRenameMenuItem(document: Document, title: string, rename:
34
39
  icon.setAttribute('viewBox', '0 0 24 24');
35
40
  icon.setAttribute('aria-hidden', 'true');
36
41
  const path = document.createElementNS(svgNamespace, 'path');
37
- path.setAttribute('d', pencil);
42
+ path.setAttribute('d', tabMenuIcons[iconName]);
38
43
  icon.append(path);
39
44
  element.append(icon, title);
40
45
  return {
@@ -43,7 +48,7 @@ export function createRenameMenuItem(document: Document, title: string, rename:
43
48
  if (!('panel' in props)) return;
44
49
  element.onclick = () => {
45
50
  props.close();
46
- rename(props.panel.id);
51
+ action(props.panel.id);
47
52
  };
48
53
  },
49
54
  dispose() {