-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathdock.tsx
More file actions
1387 lines (1326 loc) · 38.8 KB
/
Copy pathdock.tsx
File metadata and controls
1387 lines (1326 loc) · 38.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import classNames from 'classnames';
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import type {
AnimationEvent as ReactAnimationEvent,
CSSProperties,
PointerEvent as ReactPointerEvent,
} from 'react';
import { CSSTransition } from 'react-transition-group';
import { Icon } from '@wordpress/components';
import {
close,
external,
grid,
list,
page,
pencil,
plus,
wordpress,
} from '@wordpress/icons';
import type { DockPaneSection } from '../../lib/state/redux/slice-ui';
import {
setDockOperationNotice,
setShareExportOpen,
setDockPaneOpen,
setDockPaneSection,
} from '../../lib/state/redux/slice-ui';
import {
readDockFullWidth,
writeDockFullWidth,
} from '../../lib/dock-full-width';
import {
getActiveClientInfo,
selectActiveSiteError,
useActiveSite,
useAppDispatch,
useAppSelector,
} from '../../lib/state/redux/store';
import { isSiteSavingDisabled } from '../../lib/state/url/router';
import { useInlineRename } from '../../lib/hooks/use-inline-rename';
import playgroundLogoUrl from '../../playground-logo.svg';
import AddressBar from '../address-bar';
import { SaveStatusIndicator } from '../browser-chrome/save-status-indicator';
import { SiteManager } from '../site-manager';
import {
useRecentAutosaveNudgeVisible,
useSetRecentAutosaveNudgeAnchor,
} from '../ensure-playground-site/recent-autosave-nudge-context';
import { listenForPointerDownAcrossIframes } from '../ensure-playground-site/listen-for-pointer-down-across-iframes';
import { TruncatedText } from '../truncated-text';
import { DockCornerLauncher } from './dock-corner-launcher';
import { DockItemButton } from './dock-item-button';
import { DockPane } from './dock-pane';
import type { DockPaneHeaderOverride } from './dock-pane';
import { DockTogglePill } from './dock-toggle-pill';
import {
DOCK_DRAG_EDGE,
DOCK_OPERATION_TOAST_MIN_HEIGHT,
getDockOperationToastStyle,
getDockPaneStyle,
} from './dock-positioning';
import { DockBlueprintIcon, DockDatabaseIcon } from './icons';
import css from './style.module.css';
type DockItem = {
section: DockPaneSection;
label: string;
ariaLabel: string;
icon: JSX.Element;
isPrimary?: boolean;
};
export type DockProps = {
paneCloseBlocked: boolean;
onPaneCloseBlockedChange: (isBlocked: boolean) => void;
};
const DRAG_THRESHOLD = 4;
const CORNER_OVERDRAG = 36;
const MOBILE_QUERY = '(max-width: 1024px)';
const DOCK_ITEMS: DockItem[] = [
{
section: 'new',
label: 'New',
ariaLabel: 'New Playground',
icon: <Icon icon={plus} size={24} />,
isPrimary: true,
},
{
section: 'playgrounds',
label: 'Playgrounds',
ariaLabel: 'Your Playgrounds',
icon: <Icon icon={grid} size={22} />,
},
{
section: 'blueprint',
label: 'Blueprint',
ariaLabel: 'Current Blueprint',
icon: <DockBlueprintIcon />,
},
{
section: 'settings',
label: 'Site Settings',
ariaLabel: 'Site Settings',
icon: <Icon icon={wordpress} size={24} />,
},
{
section: 'database',
label: 'Database',
ariaLabel: 'Database',
icon: <DockDatabaseIcon />,
},
{
section: 'files',
label: 'Files',
ariaLabel: 'Files',
icon: <Icon icon={page} size={24} />,
},
{
section: 'logs',
label: 'Logs',
ariaLabel: 'Logs',
icon: <Icon icon={list} size={24} />,
},
{
section: 'share',
label: 'Export',
ariaLabel: 'Export',
icon: <Icon icon={external} size={24} />,
},
];
const PANE_COPY: Record<
DockPaneSection,
{ title: string; description: string }
> = {
new: {
title: 'New Playground',
description: 'Spin up a fresh Playground or start from a Blueprint.',
},
playgrounds: {
title: 'Your Playgrounds',
description: 'Switch between your recent and saved Playgrounds.',
},
blueprint: {
title: 'Blueprint',
description:
'Review and edit the Blueprint that describes this Playground.',
},
settings: {
title: 'Site Settings',
description:
'Change this Playground’s WordPress, PHP, language, and network settings.',
},
database: {
title: 'Database',
description:
'Inspect and edit the SQLite database behind this Playground.',
},
files: {
title: 'Files',
description: 'Browse and edit the active Playground filesystem.',
},
logs: {
title: 'PHP error log',
description: 'Errors, warnings, and notices from your site.',
},
share: {
title: 'Export',
description: '',
},
save: {
title: 'Store permanently',
description: '',
},
};
/**
* Hosts every website tool in one bottom Dock while leaving each tool's domain
* logic in its existing component.
*/
export function Dock({
paneCloseBlocked,
onPaneCloseBlockedChange,
}: DockProps) {
const dispatch = useAppDispatch();
const dockPaneIsOpen = useAppSelector((state) => state.ui.dockPaneIsOpen);
const activeModal = useAppSelector((state) => state.ui.activeModal);
const activeSiteError = useAppSelector(selectActiveSiteError);
const section = useAppSelector((state) => state.ui.dockPaneSection);
const shareExportOpen = useAppSelector((state) => state.ui.shareExportOpen);
const [newPlaygroundHeaderOverride, setNewPlaygroundHeaderOverride] =
useState<DockPaneHeaderOverride>();
const handleNewPlaygroundHeaderChange = useCallback(
(header: DockPaneHeaderOverride | undefined) =>
setNewPlaygroundHeaderOverride(header),
[]
);
const activeSite = useActiveSite();
const clientInfo = useAppSelector(getActiveClientInfo);
const paneCopy = PANE_COPY[section];
const paneTitle = paneCopy.title;
const isMobile = useIsMobileDock();
const isEditorSection = section === 'blueprint' || section === 'files';
// Logs hold long monospace records, so they get a wider pane.
const isWideSection = section === 'logs';
const isFixedHeightSection =
section === 'new' || (section === 'share' && shareExportOpen);
const showSharedHeader = !isEditorSection;
const siteSettingsVisible = dockPaneIsOpen && section === 'settings';
const playgroundTitle =
activeSite?.metadata.storage === 'none'
? 'Unsaved Playground'
: activeSite?.metadata.name;
const savingDisabled = isSiteSavingDisabled();
const inlineRename = useInlineRename();
const canManageActiveSite = activeSite?.metadata.storage !== 'none';
const recentAutosaveNudgeVisible = useRecentAutosaveNudgeVisible();
const setRecentAutosaveNudgeAnchor = useSetRecentAutosaveNudgeAnchor();
const playgroundsButtonRef = useRef<HTMLButtonElement>(null);
const dockStatusRef = useRef<HTMLDivElement>(null);
const operationNotice = useAppSelector(
(state) => state.ui.dockOperationNotice
);
const paneRef = useRef<HTMLElement>(null);
const dockRef = useRef<HTMLElement>(null);
const operationToastRef = useRef<HTMLDivElement>(null);
const toolsRef = useRef<HTMLDivElement>(null);
const focusBeforePaneRef = useRef<HTMLElement | null>(null);
const hasOpenedPaneRef = useRef(false);
const collapseButtonRef = useRef<HTMLButtonElement>(null);
const dragCleanupRef = useRef<(() => void) | null>(null);
const dragArmedRef = useRef(false);
const draggedRef = useRef(false);
const dragSideRef = useRef<'left' | 'right' | null>(null);
const cornerDragRef = useRef<{ startX: number } | null>(null);
const cornerDraggedRef = useRef(false);
const cornerLauncherSideRef = useRef<'left' | 'right'>('left');
const cornerRectRef = useRef<DOMRect | null>(null);
const lastDockWidthRef = useRef(0);
const modeSwitchTimerRef = useRef<number | null>(null);
const closeGitHubExport = useCallback(
() => dispatch(setShareExportOpen(false)),
[dispatch]
);
const githubExportHeaderOverride = useMemo<DockPaneHeaderOverride>(
() => ({
title: 'Export to GitHub',
backLabel: 'Back to export options',
onBack: closeGitHubExport,
}),
[closeGitHubExport]
);
const paneHeaderOverride =
section === 'new'
? newPlaygroundHeaderOverride
: section === 'share' && shareExportOpen
? githubExportHeaderOverride
: undefined;
const [dockSize, setDockSize] = useState({ width: 0, height: 0 });
const [paneHeight, setPaneHeight] = useState(0);
const [operationToastHeight, setOperationToastHeight] = useState(
DOCK_OPERATION_TOAST_MIN_HEIGHT
);
const [toolsHeight, setToolsHeight] = useState(0);
const [viewportSize, setViewportSize] = useState(() => ({
width: window.innerWidth,
height: window.innerHeight,
}));
const [dockCenter, setDockCenter] = useState<number | null>(null);
const [isCollapsed, setIsCollapsed] = useState(false);
const [isFullWidth, setIsFullWidth] = useState(readDockFullWidth);
const [isDragging, setIsDragging] = useState(false);
const [cornerSide, setCornerSide] = useState<'left' | 'right' | null>(null);
const [isModeSwitching, setIsModeSwitching] = useState(false);
const [isFolding, setIsFolding] = useState(false);
const [isUnfolding, setIsUnfolding] = useState(false);
const [isMaximizing, setIsMaximizing] = useState(false);
const [paneExitComplete, setPaneExitComplete] = useState(!dockPaneIsOpen);
// Retain the full pane body until its exit motion finishes. Hiding it when
// close starts would collapse the surface to its header before it can leave.
const paneContentVisible = dockPaneIsOpen || !paneExitComplete;
useEffect(() => {
if (typeof ResizeObserver === 'undefined') {
return;
}
const observer = new ResizeObserver(() => {
const dock = dockRef.current;
const tools = toolsRef.current;
if (dock) {
setDockSize({
width: dock.offsetWidth,
height: dock.offsetHeight,
});
if (dock.offsetWidth > 0) {
lastDockWidthRef.current = dock.offsetWidth;
}
}
if (dock && tools) {
setToolsHeight(dock.offsetHeight - tools.offsetTop);
}
});
if (dockRef.current) {
observer.observe(dockRef.current);
}
if (toolsRef.current) {
observer.observe(toolsRef.current);
}
return () => observer.disconnect();
}, []);
useEffect(() => {
/** Keeps floating geometry inside the live viewport. */
const updateViewportSize = () => {
setViewportSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener('resize', updateViewportSize);
return () => window.removeEventListener('resize', updateViewportSize);
}, []);
useLayoutEffect(() => {
const pane = paneRef.current;
if (!dockPaneIsOpen || !pane) {
setPaneHeight(0);
return;
}
/** Keeps the toast above content-driven panes as their height changes. */
const updatePaneHeight = () => setPaneHeight(pane.offsetHeight);
updatePaneHeight();
if (typeof ResizeObserver === 'undefined') {
return;
}
const observer = new ResizeObserver(updatePaneHeight);
observer.observe(pane);
return () => observer.disconnect();
}, [section, dockPaneIsOpen]);
useLayoutEffect(() => {
const toast = operationToastRef.current;
if (!operationNotice || !toast) {
setOperationToastHeight(DOCK_OPERATION_TOAST_MIN_HEIGHT);
return;
}
/** Keeps viewport clamping accurate when text wraps or zoom changes. */
const updateToastHeight = () =>
setOperationToastHeight(toast.offsetHeight);
updateToastHeight();
if (typeof ResizeObserver === 'undefined') {
return;
}
const observer = new ResizeObserver(updateToastHeight);
observer.observe(toast);
return () => observer.disconnect();
}, [operationNotice]);
useEffect(() => {
if (operationNotice?.status !== 'success') {
return;
}
const timeout = window.setTimeout(() => {
dispatch(setDockOperationNotice(undefined));
}, 4000);
return () => window.clearTimeout(timeout);
}, [dispatch, operationNotice]);
useEffect(() => {
if (dockCenter === null || !dockSize.width) {
return;
}
const halfWidth = dockSize.width / 2;
const min = halfWidth + DOCK_DRAG_EDGE;
const max = Math.max(
min,
viewportSize.width - halfWidth - DOCK_DRAG_EDGE
);
const clamped = Math.min(Math.max(dockCenter, min), max);
if (clamped !== dockCenter) {
setDockCenter(clamped);
}
}, [dockCenter, dockSize.width, viewportSize.width]);
useEffect(() => {
const root = document.documentElement;
const headerHeight = Math.max(0, dockSize.height - toolsHeight);
// Desktop collapse moves the tools below the viewport without changing the
// Dock's measured height. Mobile removes the tools from layout, so its live
// measurement already is the visible height.
const visibleHeight =
isCollapsed && !isMobile ? headerHeight : dockSize.height;
if (visibleHeight > 0) {
root.style.setProperty(
'--dock-docked-height',
`${visibleHeight}px`
);
}
root.toggleAttribute('data-dock-full-width', isFullWidth && !isMobile);
return () => {
root.style.removeProperty('--dock-docked-height');
root.removeAttribute('data-dock-full-width');
};
}, [dockSize.height, isCollapsed, isFullWidth, isMobile, toolsHeight]);
useEffect(() => {
// Opening Store permanently from the visible status must not unfold a
// collapsed Dock. Tool buttons unfold explicitly in openSection().
if (!dockPaneIsOpen || section === 'save') {
return;
}
setIsCollapsed(false);
dragSideRef.current = null;
setCornerSide(null);
setIsFolding(false);
setIsMaximizing(false);
}, [section, dockPaneIsOpen]);
// The autosave nudge points at the Playgrounds button, or at the save
// status when a collapsed Dock hides the tools row. A cornered Dock shows
// neither, and the nudge then falls back to its free-floating position
// instead of pointing at nothing.
useEffect(() => {
if (cornerSide !== null) {
setRecentAutosaveNudgeAnchor(null);
} else if (isCollapsed) {
setRecentAutosaveNudgeAnchor(dockStatusRef.current);
} else {
setRecentAutosaveNudgeAnchor(playgroundsButtonRef.current);
}
return () => setRecentAutosaveNudgeAnchor(null);
}, [isCollapsed, cornerSide, setRecentAutosaveNudgeAnchor]);
// The overlay query parameter only describes New and Playgrounds. Remove it
// when that requested pane closes or another Dock destination replaces it.
useEffect(() => {
if (
dockPaneIsOpen &&
(section === 'new' || section === 'playgrounds')
) {
return;
}
const url = new URL(window.location.href);
if (!url.searchParams.has('overlay')) {
return;
}
url.searchParams.delete('overlay');
window.history.replaceState(window.history.state, '', url);
}, [section, dockPaneIsOpen]);
useEffect(() => {
if (!isMobile) {
return;
}
dragCleanupRef.current?.();
dragCleanupRef.current = null;
dragArmedRef.current = false;
dragSideRef.current = null;
cornerDragRef.current = null;
cornerDraggedRef.current = false;
setDockCenter(null);
setCornerSide(null);
setIsCollapsed(false);
setIsDragging(false);
setIsFolding(false);
setIsUnfolding(false);
setIsMaximizing(false);
}, [isMobile]);
useEffect(() => {
return () => {
dragCleanupRef.current?.();
dragCleanupRef.current = null;
if (modeSwitchTimerRef.current !== null) {
window.clearTimeout(modeSwitchTimerRef.current);
}
};
}, []);
// Keep mounted tool state out of the keyboard and accessibility trees while
// the pane is closed. React 18 does not forward the inert attribute.
useEffect(() => {
const pane = paneRef.current;
if (!pane) {
return;
}
if (dockPaneIsOpen) {
pane.removeAttribute('aria-hidden');
pane.removeAttribute('inert');
} else {
pane.setAttribute('aria-hidden', 'true');
pane.setAttribute('inert', '');
}
}, [dockPaneIsOpen]);
useEffect(() => {
/** Lets the active modal or popover consume Escape before the Dock does. */
const closeOnEscape = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || activeModal) {
return;
}
if (
document.querySelector(
'.components-popover:not(.components-tooltip), .components-modal__screen-overlay'
)
) {
return;
}
if (operationNotice) {
dispatch(setDockOperationNotice(undefined));
return;
}
if (!dockPaneIsOpen || paneCloseBlocked) {
return;
}
dispatch(setDockPaneOpen(false));
};
document.addEventListener('keydown', closeOnEscape, true);
return () =>
document.removeEventListener('keydown', closeOnEscape, true);
}, [
activeModal,
dispatch,
dockPaneIsOpen,
operationNotice,
paneCloseBlocked,
]);
useEffect(() => {
if (!operationNotice) {
return;
}
// Dismiss the toast on the next outside interaction. Pointer events inside
// the Playground iframe do not bubble to this document, so listen across frames.
return listenForPointerDownAcrossIframes((event) => {
if (operationToastRef.current?.contains(event.target as Node)) {
return;
}
dispatch(setDockOperationNotice(undefined));
});
}, [dispatch, operationNotice]);
useEffect(() => {
if (dockPaneIsOpen) {
hasOpenedPaneRef.current = true;
if (!focusBeforePaneRef.current) {
focusBeforePaneRef.current =
document.activeElement as HTMLElement | null;
}
const timer = window.setTimeout(() => {
if (
paneRef.current &&
!paneRef.current.contains(document.activeElement)
) {
paneRef.current.focus();
}
}, 120);
return () => window.clearTimeout(timer);
}
if (!hasOpenedPaneRef.current) {
return;
}
const previousFocus = focusBeforePaneRef.current;
focusBeforePaneRef.current = null;
if (previousFocus && document.contains(previousFocus)) {
previousFocus.focus();
}
if (document.activeElement === document.body) {
collapseButtonRef.current?.focus();
}
}, [section, dockPaneIsOpen]);
/** Opens one tool, or closes it when its already-active button is pressed. */
const openSection = useCallback(
(nextSection: DockPaneSection) => {
if (paneCloseBlocked) {
return;
}
if (dockPaneIsOpen && section === nextSection) {
dispatch(setDockPaneOpen(false));
return;
}
if (dockPaneIsOpen) {
focusBeforePaneRef.current =
document.activeElement as HTMLElement | null;
}
setIsCollapsed(false);
dragSideRef.current = null;
setCornerSide(null);
dispatch(setDockPaneSection(nextSection));
dispatch(setDockPaneOpen(true));
},
[dispatch, paneCloseBlocked, section, dockPaneIsOpen]
);
// The Dock can move only while it floats. Full-width and mobile modes are
// already fixed to an edge and keep their native control interactions.
const canDrag = !isMobile && !isFullWidth;
/** Reports whether a target belongs to a Dock control, including a portal. */
const isDockControlTarget = (target: EventTarget | null) =>
target instanceof Element &&
Boolean(
target.closest(
'button, a, input, textarea, select, [role="menu"], [role="menuitem"], [role="listbox"]'
)
);
/** Writes the pointer-driven grab sheen without re-rendering the Dock. */
const setDockSheen = (opacity: number, clientX?: number) => {
const dock = dockRef.current;
if (!dock) {
return;
}
dock.style.setProperty('--sheen-o', String(opacity));
if (clientX !== undefined) {
const rect = dock.getBoundingClientRect();
const x = Math.min(
Math.max(clientX - rect.left, 12),
Math.max(rect.width - 12, 12)
);
dock.style.setProperty('--sheen-x', `${x}px`);
}
};
useEffect(() => {
if (!canDrag) {
dockRef.current?.style.setProperty('--sheen-o', '0');
}
}, [canDrag]);
// Controls keep native press, selection, and motor-tolerance behavior. The
// surrounding Dock chrome remains a large drag handle without turning a small
// pointer wobble on a button into an accidental Dock move.
/** Arms a whole-surface horizontal drag and swallows clicks after real drags. */
const handleDockPointerDown = (event: ReactPointerEvent<HTMLElement>) => {
if (
!canDrag ||
event.button !== 0 ||
isDockControlTarget(event.target)
) {
return;
}
const dock = dockRef.current;
if (!dock) {
return;
}
const rect = dock.getBoundingClientRect();
const startX = event.clientX;
const startCenter = rect.left + rect.width / 2;
const initialDockCenter = dockCenter;
const halfWidth = dock.offsetWidth / 2;
const pointerId = event.pointerId;
const capturePointer = () => {
try {
dockRef.current?.setPointerCapture(pointerId);
} catch {
// Synthetic pointer events may not support capture.
}
};
capturePointer();
dragArmedRef.current = true;
draggedRef.current = false;
/** Moves the Dock and previews a corner after deliberate overdrag. */
const moveDock = (moveEvent: PointerEvent) => {
const delta = moveEvent.clientX - startX;
if (!draggedRef.current) {
if (Math.abs(delta) < DRAG_THRESHOLD) {
return;
}
draggedRef.current = true;
setIsDragging(true);
capturePointer();
}
setDockSheen(1, moveEvent.clientX);
const min = halfWidth + DOCK_DRAG_EDGE;
const max = Math.max(
min,
window.innerWidth - halfWidth - DOCK_DRAG_EDGE
);
const desiredCenter = startCenter + delta;
const side =
desiredCenter < min - CORNER_OVERDRAG
? 'left'
: desiredCenter > max + CORNER_OVERDRAG
? 'right'
: null;
dragSideRef.current = side;
if (side) {
cornerLauncherSideRef.current = side;
}
setCornerSide(side);
setDockCenter(Math.min(Math.max(desiredCenter, min), max));
};
/** Finishes a drag without also activating the pressed Dock control. */
const finishDockDrag = () => completeDockDrag(false);
/** Restores the Dock when pointer ownership ends without a pointerup. */
const cancelDockDrag = () => completeDockDrag(true);
const completeDockDrag = (cancelled: boolean) => {
dragCleanupRef.current?.();
dragCleanupRef.current = null;
// Let the next click target the restored corner launcher instead of
// staying captured by the Dock that just finished folding.
try {
dock.releasePointerCapture(pointerId);
} catch {
// Synthetic pointer events may not support capture.
}
dragArmedRef.current = false;
if (!draggedRef.current) {
return;
}
draggedRef.current = false;
const eatClick = (clickEvent: MouseEvent) => {
if (
!(clickEvent.target instanceof Node) ||
!dockRef.current?.contains(clickEvent.target)
) {
return;
}
clickEvent.stopPropagation();
clickEvent.preventDefault();
};
window.addEventListener('click', eatClick, {
capture: true,
once: true,
});
window.setTimeout(
() =>
window.removeEventListener('click', eatClick, {
capture: true,
}),
250
);
setIsDragging(false);
if (!dockRef.current?.matches(':hover')) {
setDockSheen(0);
}
if (cancelled) {
dragSideRef.current = null;
setCornerSide(null);
setDockCenter(initialDockCenter);
setDockSheen(0);
return;
}
if (dragSideRef.current !== null && dockPaneIsOpen) {
// An open pane owns the expanded Dock. Refuse a fold that would hide
// both the tool in use and its launcher.
dragSideRef.current = null;
setCornerSide(null);
setDockCenter(null);
} else if (
dragSideRef.current !== null &&
!prefersReducedMotion()
) {
setIsCollapsed(false);
setIsFolding(true);
}
};
dragCleanupRef.current?.();
dragCleanupRef.current = () => {
window.removeEventListener('pointermove', moveDock, true);
window.removeEventListener('pointerup', finishDockDrag, true);
window.removeEventListener('pointercancel', cancelDockDrag, true);
window.removeEventListener('blur', cancelDockDrag);
dock.removeEventListener('lostpointercapture', cancelDockDrag);
};
window.addEventListener('pointermove', moveDock, true);
window.addEventListener('pointerup', finishDockDrag, true);
window.addEventListener('pointercancel', cancelDockDrag, true);
window.addEventListener('blur', cancelDockDrag);
dock.addEventListener('lostpointercapture', cancelDockDrag);
};
/** Reveals the grab sheen, softened while the pointer is over a control. */
const updateDockSheen = (event: ReactPointerEvent<HTMLElement>) => {
if (dragArmedRef.current || !canDrag) {
return;
}
setDockSheen(
isDockControlTarget(event.target) ? 0.12 : 1,
event.clientX
);
};
/** Hides the sheen after the pointer leaves an idle Dock. */
const hideDockSheen = () => {
if (!dragArmedRef.current) {
setDockSheen(0);
}
};
/** Arms a drag that pulls the minimized launcher back into a full Dock. */
const handleCornerPointerDown = (
event: ReactPointerEvent<HTMLButtonElement>
) => {
if (event.button !== 0) {
return;
}
cornerDragRef.current = { startX: event.clientX };
cornerDraggedRef.current = false;
dragSideRef.current = cornerSide;
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
// Synthetic pointer events may not support capture.
}
};
/** Reveals the Dock once a launcher drag crosses the movement threshold. */
const handleCornerPointerMove = (
event: ReactPointerEvent<HTMLButtonElement>
) => {
const drag = cornerDragRef.current;
if (!drag) {
return;
}
if (
!cornerDraggedRef.current &&
Math.abs(event.clientX - drag.startX) < DRAG_THRESHOLD
) {
return;
}
if (!cornerDraggedRef.current) {
cornerDraggedRef.current = true;
setIsUnfolding(false);
setIsCollapsed(false);
setIsMaximizing(true);
setIsDragging(true);
}
const halfWidth = (lastDockWidthRef.current || 320) / 2;
const min = halfWidth + DOCK_DRAG_EDGE;
const max = Math.max(
min,
window.innerWidth - halfWidth - DOCK_DRAG_EDGE
);
const desiredCenter = event.clientX;
const side =
desiredCenter < min - CORNER_OVERDRAG
? 'left'
: desiredCenter > max + CORNER_OVERDRAG
? 'right'
: null;
dragSideRef.current = side;
if (side) {
cornerLauncherSideRef.current = side;
}
setCornerSide(side);
setDockCenter(Math.min(Math.max(desiredCenter, min), max));
};
/** Leaves the restored Dock floating, or folds it again at an armed edge. */
const handleCornerPointerUp = (
event: ReactPointerEvent<HTMLButtonElement>
) => {
if (!cornerDragRef.current) {
return;
}
try {
event.currentTarget.releasePointerCapture(event.pointerId);
} catch {
// The pointer may already have been released.
}
cornerDragRef.current = null;
if (!cornerDraggedRef.current) {
return;
}
setIsMaximizing(false);
setIsDragging(false);
if (dragSideRef.current !== null && !prefersReducedMotion()) {
setIsFolding(true);
}
};
/** Hides the tools row without hiding the address or save status. */
const toggleCollapsed = () => {
if (paneCloseBlocked) {
return;
}
if (dockPaneIsOpen) {
dispatch(setDockPaneOpen(false));
}
setIsCollapsed((collapsed) => !collapsed);
};
/** Switches between the floating Dock and a full-width bottom bar. */
const toggleFullWidth = () => {
const next = !isFullWidth;
// Snap between the two geometries instead of briefly stretching the Dock.
// Re-enable the normal collapse/corner transitions immediately afterwards.
setIsModeSwitching(true);
if (modeSwitchTimerRef.current !== null) {
window.clearTimeout(modeSwitchTimerRef.current);
}
modeSwitchTimerRef.current = window.setTimeout(() => {
setIsModeSwitching(false);
modeSwitchTimerRef.current = null;
}, 60);
if (next) {
setDockCenter(null);
dragSideRef.current = null;
setCornerSide(null);
}
setIsFullWidth(next);
writeDockFullWidth(next);
};
// Grow a clicked launcher out of its exact corner position. The nav is
// restored before this layout effect, so both source and target rectangles
// are available for one bottom-anchored Web Animations transition.
useLayoutEffect(() => {
if (!isUnfolding) {
return;
}
const dock = dockRef.current;
const source = cornerRectRef.current;
cornerRectRef.current = null;
if (!dock || !source || typeof dock.animate !== 'function') {
setIsUnfolding(false);
return;
}
const target = dock.getBoundingClientRect();
if (!target.width || !target.height) {
setIsUnfolding(false);
return;
}
const deltaX =
source.left + source.width / 2 - (target.left + target.width / 2);
const deltaY = source.bottom - target.bottom;
const scaleX = source.width / target.width;
const scaleY = source.height / target.height;
const startRadius = Math.min(480, 13 / Math.max(scaleX, 0.03));
dock.style.transformOrigin = '50% 100%';
const travel = dock.animate(
[
{
transform: `translateX(-50%) translate(${deltaX}px, ${deltaY}px) scale(${scaleX}, ${scaleY})`,
clipPath: `inset(0 round ${startRadius}px)`,
},
{
transform: `translateX(-50%) translate(${deltaX * 0.45}px, ${
deltaY * 0.85
}px) scale(${scaleX + (1 - scaleX) * 0.3}, ${
scaleY + (1 - scaleY) * 0.34
})`,
clipPath: `inset(0 round ${Math.max(
24,
startRadius * 0.4
)}px)`,
offset: 0.42,
},
{
transform: 'translateX(-50%)',
clipPath: 'inset(0 round 18px 18px 0 0)',
},
],
{ duration: 440, easing: 'cubic-bezier(0.3, 0.9, 0.3, 1)' }
);
const body = dock.querySelector<HTMLElement>(`.${css.dockBody}`);
const contentFade = body?.animate(
[
{ opacity: 0 },
{ opacity: 0, offset: 0.35 },
{ opacity: 1, offset: 0.85 },
{ opacity: 1 },
],
{ duration: 440, easing: 'linear' }
);
let finished = false;
const finish = () => {
if (finished) {
return;
}
finished = true;