-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathWorkspaceManager.js
More file actions
936 lines (830 loc) · 37.1 KB
/
Copy pathWorkspaceManager.js
File metadata and controls
936 lines (830 loc) · 37.1 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2014 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// @INCLUDE_IN_API_DOCS
/**
* Manages layout of panels surrounding the editor area, and size of the editor area (but not its contents).
*
* Updates panel sizes when the window is resized. Maintains the max resizing limits for panels, based on
* currently available window size.
*
* Events:
* `workspaceUpdateLayout` When workspace size changes for any reason (including panel show/hide panel resize, or the window resize).
* The 2nd arg is the available workspace height.
* The 3rd arg is a refreshHint flag for internal use (passed in to recomputeLayout)
* @module view/WorkspaceManager
*/
define(function (require, exports, module) {
const AppInit = require("utils/AppInit"),
EventDispatcher = require("utils/EventDispatcher"),
KeyBindingManager = require("command/KeyBindingManager"),
Resizer = require("utils/Resizer"),
AnimationUtils = require("utils/AnimationUtils"),
Strings = require("strings"),
PluginPanelView = require("view/PluginPanelView"),
PanelView = require("view/PanelView"),
EditorManager = require("editor/EditorManager"),
MainViewManager = require("view/MainViewManager"),
KeyEvent = require("utils/KeyEvent");
/**
* Panel ID for the default launcher panel shown when no other panels are open.
* @const
* @private
*/
const DEFAULT_PANEL_ID = "workspace.defaultPanel";
/**
* Event triggered when the workspace layout updates.
* @const
*/
const EVENT_WORKSPACE_UPDATE_LAYOUT = "workspaceUpdateLayout";
/**
* Event triggered when a panel is shown.
* @const
*/
const EVENT_WORKSPACE_PANEL_SHOWN = PanelView.EVENT_PANEL_SHOWN;
/**
* Event triggered when a panel is hidden.
* @const
*/
const EVENT_WORKSPACE_PANEL_HIDDEN = PanelView.EVENT_PANEL_HIDDEN;
/**
* Event triggered when design mode (editor collapsed, full live preview) is
* entered or exited. Payload: `(active: boolean)`.
* @const
*/
const EVENT_WORKSPACE_DESIGN_MODE_CHANGE = "workspaceDesignModeChange";
/**
* Width of the main toolbar in pixels.
* @const
* @private
*/
const MAIN_TOOLBAR_WIDTH = 30;
/**
* Returns the sidebar's rendered width, or 0 if hidden. jQuery's outerWidth()
* on a display:none element that still carries an explicit style.width returns
* that stale width rather than 0, which corrupts main-view layout math.
* @private
*/
function _getSidebarWidth() {
var sb = document.getElementById("sidebar");
if (!sb || sb.offsetWidth === 0) {
return 0;
}
return sb.offsetWidth;
}
/**
* The ".content" vertical stack (editor + all header/footer panels)
* @type {jQueryObject}
* @private
*/
var $windowContent;
/**
* The "#editor-holder": has only one visible child, the current CodeMirror instance (or the no-editor placeholder)
* @type {jQueryObject}
* @private
*/
var $editorHolder;
/**
* The "#main-toolbay": to the right side holding plugin panels and icons
* @type {jQueryObject}
* @private
*/
var $mainToolbar;
/**
* The "#main-plugin-panel": The plugin panel main container
* @type {jQueryObject}
* @private
*/
let $mainPluginPanel;
/**
* The "#plugin-icons-bar": holding all the plugin icons
* @type {jQueryObject}
* @private
*/
let $pluginIconsBar;
/**
* A map from panel ID's to all related panels
* @private
*/
var panelIDMap = {};
/**
* Have we already started listening for the end of the ongoing window resize?
* @private
* @type {boolean}
*/
var windowResizing = false;
let lastShownBottomPanelStack = [];
/** @type {jQueryObject} The single container wrapping all bottom panels */
let $bottomPanelContainer;
/** @type {jQueryObject} Chevron toggle in the status bar */
let $statusBarPanelToggle;
/** @type {boolean} True while the status bar toggle button is handling a click */
let _statusBarToggleInProgress = false;
/**
* Calculates the available height for the full-size Editor (or the no-editor placeholder),
* accounting for the current size of all visible panels, toolbar, & status bar.
* @return {number}
* @private
*/
function calcAvailableHeight() {
var availableHt = $windowContent.height();
$editorHolder.siblings().each(function (i, elem) {
var $elem = $(elem);
if ($elem.css("display") !== "none" && $elem.css("position") !== "absolute") {
availableHt -= $elem.outerHeight();
}
});
// Clip value to 0 (it could be negative if a panel wants more space than we have)
return Math.max(availableHt, 0);
}
/**
* Updates panel resize limits to disallow making panels big enough to shrink editor area below 0
* @private
*/
function updateResizeLimits() {
var editorAreaHeight = $editorHolder.height();
$editorHolder.siblings().each(function (i, elem) {
var $elem = $(elem);
if ($elem.css("display") === "none") {
$elem.data("maxsize", editorAreaHeight);
} else {
$elem.data("maxsize", editorAreaHeight + $elem.outerHeight());
}
});
var sidebarWidth = _getSidebarWidth();
var pluginIconsBarWidth = $pluginIconsBar.outerWidth() || MAIN_TOOLBAR_WIDTH;
var minToolbarWidth = ((currentlyShownPanel && currentlyShownPanel.minWidth) || 0) + pluginIconsBarWidth;
// Floor the toolbar's maxsize at its minimum width. Without the floor, a narrow
// window with a wide sidebar can drive the cap below 10px, and Resizer's drag
// logic would then squeeze the toolbar to zero and hide it.
var rawMax = window.innerWidth - sidebarWidth - 100;
$mainToolbar.data("maxsize", Math.max(minToolbarWidth, rawMax));
}
/**
* Calculates a new size for editor-holder and resizes it accordingly, then and dispatches the "workspaceUpdateLayout"
* event. (The editors within are resized by EditorManager, in response to that event).
* @private
* @param {boolean=} refreshHint true to force a complete refresh
*/
function triggerUpdateLayout(refreshHint) {
// Find how much space is left for the editor
let editorAreaHeight = calcAvailableHeight();
$editorHolder.height(editorAreaHeight); // affects size of "not-editor" placeholder as well
let pluginPanelWidth = $mainToolbar.width() - $pluginIconsBar.width();
$mainPluginPanel.width(pluginPanelWidth);
// Resize editor to fill the space
exports.trigger(EVENT_WORKSPACE_UPDATE_LAYOUT, editorAreaHeight, refreshHint);
}
/**
* Trigger editor area resize whenever the window is resized
* @private
*/
function handleWindowResize() {
// These are not initialized in Jasmine Spec Runner window until a test
// is run that creates a mock document.
if (!$windowContent || !$editorHolder) {
return;
}
// Clamp plugin panel toolbar width so it doesn't encroach into the sidebar/content area
if (currentlyShownPanel && $mainToolbar.is(":visible")) {
_clampPluginPanelWidth(currentlyShownPanel);
}
// Then coordinate sidebar width in editor mode so the three regions fit.
_ensureEditorLayoutFits();
// FIXME (issue #4564) Workaround https://github.com/codemirror/CodeMirror/issues/1787
triggerUpdateLayout();
// Re-apply maximize height when the window resizes so the panel stays maximized
if (PanelView.isMaximized() && $bottomPanelContainer && $bottomPanelContainer.is(":visible")) {
let maxHeight = $editorHolder.height() + $bottomPanelContainer.height();
$bottomPanelContainer.height(maxHeight);
triggerUpdateLayout();
}
if (!windowResizing) {
windowResizing = true;
// We don't need any fancy debouncing here - we just need to react before the user can start
// resizing any panels at the new window size. So just listen for first mousemove once the
// window resize releases mouse capture.
$(window.document).one("mousemove", function () {
windowResizing = false;
updateResizeLimits();
});
}
}
/** Trigger editor area resize whenever the given panel is shown/hidden/resized
* @private
* @param {!jQueryObject} $panel the jquery object in which to attach event handlers
*/
function listenToResize($panel) {
// Update editor height when shown/hidden, & continuously as panel is resized
$panel.on("panelCollapsed panelExpanded panelResizeUpdate", function () {
triggerUpdateLayout();
});
// Update max size of sibling panels when shown/hidden, & at *end* of resize gesture
$panel.on("panelCollapsed panelExpanded panelResizeEnd", function () {
updateResizeLimits();
});
}
/**
* Creates a new resizable panel beneath the editor area and above the status bar footer. Panel is initially invisible.
* The panel's size & visibility are automatically saved & restored as a view-state preference.
*
* @param {!string} id Unique id for this panel. Use package-style naming, e.g. "myextension.feature.panelname"
* @param {!jQueryObject} $panel DOM content to use as the panel. Need not be in the document yet. Must have an id
* attribute, for use as a preferences key.
* @param {number=} minSize @deprecated No longer used. Pass `undefined`.
* @param {string=} title Display title shown in the bottom panel tab bar.
* @param {Object=} options Optional settings:
* - {string} iconSvg Path to an SVG icon for the panel tab (e.g. "styles/images/icon.svg").
* If omitted, a generic default icon is used.
* @return {!Panel}
*/
function createBottomPanel(id, $panel, minSize, title, options) {
$bottomPanelContainer.append($panel);
$panel.hide();
updateResizeLimits();
let bottomPanel = new PanelView.Panel($panel, id, title, options);
panelIDMap[id] = bottomPanel;
return bottomPanel;
}
/**
* Destroys a bottom panel, removing it from internal registries, the tab bar, and the DOM.
* After calling this, the panel ID is no longer valid and the Panel instance should not be reused.
*
* @param {!string} id The panel ID that was passed to createBottomPanel.
*/
function destroyBottomPanel(id) {
let panel = panelIDMap[id];
if (!panel) {
return;
}
if (typeof panel.destroy === 'function') {
panel.destroy();
}
delete panelIDMap[id];
}
/**
* Creates a new resizable plugin panel associated with the given toolbar icon. Panel is initially invisible.
* The panel's size & visibility are automatically saved & restored. Only one panel can be associated with a
* toolbar icon.
*
* @param {!string} id Unique id for this panel. Use package-style naming, e.g. "myextension.panelname". will
* overwrite an existing panel id if present.
* @param {!jQueryObject} $panel DOM content to use as the panel. Need not be in the document yet. Must have an id
* attribute, for use as a preferences key.
* @param {number=} minSize Minimum height of panel in px.
* @param {!jQueryObject} $toolbarIcon An icon that should be present in main-toolbar to associate this panel to.
* The panel will be shown only if the icon is visible on the toolbar and the user clicks on the icon.
* @param {?number=} initialSize Optional Initial size of panel in px. If not given, panel will use minsize
* or current size.
* @return {!Panel}
*/
function createPluginPanel(id, $panel, minSize, $toolbarIcon, initialSize) {
if(!$toolbarIcon){
throw new Error("invalid $toolbarIcon provided to create createPluginPanel");
}
$mainPluginPanel[0].appendChild($panel[0]);
let pluginPanel = new PluginPanelView.Panel($panel, id, $toolbarIcon, minSize, initialSize);
panelIDMap[id] = pluginPanel;
pluginPanel.hide();
return pluginPanel;
}
/**
* Returns an array of all panel ID's
* @returns {Array} List of ID's of all bottom panels
*/
function getAllPanelIDs() {
var property, panelIDs = [];
for (property in panelIDMap) {
if (panelIDMap.hasOwnProperty(property)) {
panelIDs.push(property);
}
}
return panelIDs;
}
/**
* Gets the Panel interface for the given ID. Can return undefined if no panel with the ID is found.
* @param {string} panelID
* @returns {Object} Panel object for the ID or undefined
*/
function getPanelForID(panelID) {
return panelIDMap[panelID];
}
/**
* Called when an external widget has appeared and needs some of the space occupied
* by the mainview manager
* @param {boolean} refreshHint true to refresh the editor, false if not
*/
function recomputeLayout(refreshHint) {
triggerUpdateLayout(refreshHint);
updateResizeLimits();
}
/* Attach to key parts of the overall UI, once created */
AppInit.htmlReady(function () {
$windowContent = $(".content");
$editorHolder = $("#editor-holder");
$mainToolbar = $("#main-toolbar");
$mainPluginPanel = $("#main-plugin-panel");
$pluginIconsBar = $("#plugin-icons-bar");
// Sidebar show/resize steals width from the plugin-panel area. Without
// re-clamping, the main-toolbar keeps its previous (now-oversized) width
// and overlaps the sidebar/editor. Mirror the window-resize handling.
$("#sidebar").on("panelExpanded.workspace panelCollapsed.workspace panelResizeEnd.workspace",
function () {
if (currentlyShownPanel && $mainToolbar.is(":visible")) {
_clampPluginPanelWidth(currentlyShownPanel);
}
_ensureEditorLayoutFits();
triggerUpdateLayout();
updateResizeLimits();
});
// --- Create the bottom panel tabbed container ---
$bottomPanelContainer = $('<div id="bottom-panel-container" class="vert-resizable top-resizer"></div>');
let $bottomPanelTabBar = $('<div id="bottom-panel-tab-bar"></div>');
let $bottomPanelTabsOverflow = $('<div class="bottom-panel-tabs-overflow"></div>');
let $tabBarActions = $('<div class="bottom-panel-tab-bar-actions"></div>');
$tabBarActions.append(
$('<span class="bottom-panel-hide-btn"><i class="fa-solid fa-minus"></i></span>')
.attr('title', Strings.BOTTOM_PANEL_MINIMIZE)
);
$tabBarActions.append(
$('<span class="bottom-panel-maximize-btn"><i class="fa-solid fa-expand"></i></span>')
.attr('title', Strings.BOTTOM_PANEL_MAXIMIZE)
);
$bottomPanelTabBar.append($bottomPanelTabsOverflow);
$bottomPanelTabBar.append($tabBarActions);
$bottomPanelContainer.append($bottomPanelTabBar);
$bottomPanelContainer.insertBefore("#status-bar");
$bottomPanelContainer.hide();
// Initialize PanelView with container DOM references and tab bar click handlers
PanelView.init($bottomPanelContainer, $bottomPanelTabBar, $bottomPanelTabsOverflow,
$editorHolder, recomputeLayout, DEFAULT_PANEL_ID);
// Create status bar chevron toggle for bottom panel
$statusBarPanelToggle = $('<div id="status-panel-toggle" class="indicator global-indicator"><i class="fa-solid fa-angles-up"></i></div>')
.attr('title', Strings.BOTTOM_PANEL_SHOW);
$("#status-indicators").prepend($statusBarPanelToggle);
$statusBarPanelToggle.on("click", function () {
_statusBarToggleInProgress = true;
_togglePanels();
_statusBarToggleInProgress = false;
});
// Make the container resizable (not individual panels)
Resizer.makeResizable($bottomPanelContainer[0], Resizer.DIRECTION_VERTICAL, Resizer.POSITION_TOP,
200, false, undefined, true);
listenToResize($bottomPanelContainer);
// Track maximize state live during drag-resize so the icon updates
// immediately rather than waiting for mouseup. panelResizeUpdate fires
// after listenToResize's handler has already called triggerUpdateLayout(),
// so $editorHolder height is up-to-date at this point.
$bottomPanelContainer.on("panelResizeUpdate panelResizeEnd", function () {
let editorHeight = $editorHolder.height();
if (PanelView.isMaximized() && editorHeight > PanelView.MAXIMIZE_THRESHOLD) {
PanelView.exitMaximizeOnResize();
} else if (!PanelView.isMaximized() && editorHeight <= PanelView.MAXIMIZE_THRESHOLD) {
PanelView.enterMaximizeOnResize();
}
});
$bottomPanelContainer.on("panelCollapsed", function () {
$statusBarPanelToggle.find("i")
.removeClass("fa-angles-down")
.addClass("fa-angles-up");
$statusBarPanelToggle.attr("title", Strings.BOTTOM_PANEL_SHOW);
if (!_statusBarToggleInProgress) {
AnimationUtils.animateUsingClass($statusBarPanelToggle[0], "flash", 800);
}
// When the container collapses while tabs are still open, clear the
// shown stack so the Escape-key handler doesn't silently close tabs
// that the user can't even see.
let openIds = PanelView.getOpenBottomPanelIDs();
for (let i = 0; i < openIds.length; i++) {
lastShownBottomPanelStack = lastShownBottomPanelStack.filter(item => item !== openIds[i]);
}
});
$bottomPanelContainer.on("panelExpanded", function () {
$statusBarPanelToggle.find("i")
.removeClass("fa-angles-up")
.addClass("fa-angles-down");
$statusBarPanelToggle.attr("title", Strings.BOTTOM_PANEL_HIDE_TOGGLE);
if (!_statusBarToggleInProgress) {
AnimationUtils.animateUsingClass($statusBarPanelToggle[0], "flash", 800);
}
// When the container re-expands, add the open panels to the shown stack.
let openIds = PanelView.getOpenBottomPanelIDs();
for (let i = 0; i < openIds.length; i++) {
lastShownBottomPanelStack = lastShownBottomPanelStack.filter(item => item !== openIds[i]);
lastShownBottomPanelStack.push(openIds[i]);
}
});
// Sidebar is a special case: it isn't a Panel, and is not created dynamically. Need to explicitly
// listen for resize here.
listenToResize($("#sidebar"));
listenToResize($("#main-toolbar"));
// In the browser, the #titlebar contains the menubar and filename which can wrap to
// multiple lines when the .content area narrows (e.g. when a plugin side panel opens).
// The wrapping causes a transient height change that settles asynchronously after JS
// recalculates the title-wrapper width. A ResizeObserver catches the settled height
// and triggers a layout recomputation so the editor fills the correct space.
let _titlebarHeight = $("#titlebar").outerHeight();
const titlebarEl = document.getElementById("titlebar");
if (titlebarEl) {
const titlebarObserver = new ResizeObserver(function () {
let newHeight = $("#titlebar").outerHeight();
if (newHeight !== _titlebarHeight) {
_titlebarHeight = newHeight;
triggerUpdateLayout();
}
});
titlebarObserver.observe(titlebarEl);
}
});
/**
* Unit test only: allow passing in mock DOM notes, e.g. for use with SpecRunnerUtils.createMockEditor()
* @private
*/
function _setMockDOM($mockWindowContent, $mockEditorHolder, $mockMainToolbar, $mockMainPluginPanel, $mockPluginIconsBar) {
$windowContent = $mockWindowContent;
$editorHolder = $mockEditorHolder;
$mainToolbar = $mockMainToolbar;
$mainPluginPanel = $mockMainPluginPanel;
$pluginIconsBar = $mockPluginIconsBar;
}
/* Add this as a capture handler so we're guaranteed to run it before the editor does its own
* refresh on resize.
*/
window.addEventListener("resize", handleWindowResize, true);
EventDispatcher.makeEventDispatcher(exports);
PanelView.on(PanelView.EVENT_PANEL_SHOWN, (event, panelID)=>{
lastShownBottomPanelStack = lastShownBottomPanelStack.filter(item => item !== panelID);
lastShownBottomPanelStack.push(panelID);
exports.trigger(EVENT_WORKSPACE_PANEL_SHOWN, panelID);
triggerUpdateLayout();
});
PanelView.on(PanelView.EVENT_PANEL_HIDDEN, (event, panelID)=>{
lastShownBottomPanelStack = lastShownBottomPanelStack.filter(item => item !== panelID);
exports.trigger(EVENT_WORKSPACE_PANEL_HIDDEN, panelID);
triggerUpdateLayout();
});
let currentlyShownPanel = null,
panelShowInProgress = false,
initialSizeSetOnce = {};
function _getInitialSize(panel) {
let setOnce = initialSizeSetOnce[panel.panelID];
if(setOnce){
return undefined; // we haev lalready set the initial size once, let resizer figure out size to apply now.
}
initialSizeSetOnce[panel.panelID] = true;
return panel.initialSize;
}
function _clampPluginPanelWidth(panelBeingShown) {
let sidebarWidth = _getSidebarWidth();
let pluginIconsBarWidth = $pluginIconsBar.outerWidth();
let minToolbarWidth = (panelBeingShown.minWidth || 0) + pluginIconsBarWidth;
let maxToolbarWidth = Math.max(
minToolbarWidth,
window.innerWidth - sidebarWidth - 100
);
let currentWidth = $mainToolbar.width();
if (currentWidth > maxToolbarWidth || currentWidth < minToolbarWidth) {
let clampedWidth = Math.max(minToolbarWidth, Math.min(currentWidth, maxToolbarWidth));
$mainToolbar.width(clampedWidth);
$windowContent.css("right", clampedWidth);
Resizer.resyncSizer($mainToolbar[0]);
}
}
const CCB_WIDTH = 30;
const MIN_EDITOR_WIDTH = 100;
const MIN_SIDEBAR_WIDTH = 30;
/**
* In editor mode the sidebar, editor, and plugin-panel (main-toolbar) must
* share the horizontal space. Resizer's own sidebar clamp runs lazily on
* the next mousemove, and only considers percent-based max sizes — so a
* window shrink, or showing the sidebar at its remembered width, can leave
* the sidebar overlapping the live-preview panel. Here we do an eager
* coordinated shrink: clamp sidebar so sidebar + CCB + current toolbar +
* MIN_EDITOR_WIDTH fits in the window. Design mode handles its own
* geometry with !important, so this is a no-op there.
* @private
*/
function _ensureEditorLayoutFits() {
if (_isInDesignMode) {
return;
}
var $sb = $("#sidebar");
if (!$sb.length || $sb[0].offsetWidth === 0) {
return;
}
var toolbarW = $mainToolbar.is(":visible") ? $mainToolbar.width() : 0;
var maxSidebar = window.innerWidth - CCB_WIDTH - toolbarW - MIN_EDITOR_WIDTH;
var currentSb = $sb[0].offsetWidth;
if (currentSb > maxSidebar) {
var newSb = Math.max(MIN_SIDEBAR_WIDTH, maxSidebar);
$sb.width(newSb);
var resync = $sb.data("resyncSizer");
if (typeof resync === "function") {
resync();
}
// Notify listeners (CCB syncs its left offset; content tracks via forceleft).
$sb.trigger("panelResizeUpdate", [newSb]);
$sb.trigger("panelResizeEnd", [newSb]);
}
}
function _showPluginSidePanel(panelID) {
let panelBeingShown = getPanelForID(panelID);
let pluginIconsBarWidth = $pluginIconsBar.outerWidth();
let minToolbarWidth = (panelBeingShown.minWidth || 0) + pluginIconsBarWidth;
Resizer.makeResizable($mainToolbar, Resizer.DIRECTION_HORIZONTAL, Resizer.POSITION_LEFT,
minToolbarWidth, false, undefined, true,
undefined, $windowContent, undefined, _getInitialSize(panelBeingShown));
Resizer.show($mainToolbar[0]);
_clampPluginPanelWidth(panelBeingShown);
recomputeLayout(true);
}
function _hidePluginSidePanel() {
$mainToolbar.css('width', MAIN_TOOLBAR_WIDTH);
$windowContent.css('right', MAIN_TOOLBAR_WIDTH);
Resizer.removeSizable($mainToolbar[0]);
recomputeLayout(true);
}
PluginPanelView.on(PluginPanelView.EVENT_PANEL_SHOWN, (event, panelID)=>{
panelShowInProgress = true;
_showPluginSidePanel(panelID);
if(currentlyShownPanel){
currentlyShownPanel.hide();
}
currentlyShownPanel = getPanelForID(panelID);
exports.trigger(EVENT_WORKSPACE_PANEL_SHOWN, panelID);
panelShowInProgress = false;
});
PluginPanelView.on(PluginPanelView.EVENT_PANEL_HIDDEN, (event, panelID)=>{
if(!panelShowInProgress){
_hidePluginSidePanel();
currentlyShownPanel = null;
}
exports.trigger(EVENT_WORKSPACE_PANEL_HIDDEN, panelID);
});
/**
* Responsible to check if the panel is visible or not.
* Returns true if visible else false.
* @param panelID
* @returns {boolean}
*/
function isPanelVisible(panelID) {
let panel = getPanelForID(panelID);
if(panel && panel.isVisible()){
return true;
}
return false;
}
/**
* Programmatically sets the plugin panel content width to the given value in pixels.
* The total toolbar width is adjusted to account for the plugin icons bar.
* If the requested width doesn't fit, the sidebar is progressively shrunk
* (and collapsed if necessary) before clamping.
* No-op if no panel is currently visible.
* @param {number} width Desired content width in pixels
*/
function setPluginPanelWidth(width) {
if (!currentlyShownPanel) {
return;
}
var pluginIconsBarWidth = $pluginIconsBar.outerWidth();
var newToolbarWidth = width + pluginIconsBarWidth;
var minSize = currentlyShownPanel.minWidth || 0;
var minToolbarWidth = minSize + pluginIconsBarWidth;
var sidebarWidth = _getSidebarWidth();
var maxToolbarWidth = window.innerWidth - sidebarWidth - MIN_EDITOR_WIDTH;
if (newToolbarWidth > maxToolbarWidth && sidebarWidth > 0) {
var $sb = $("#sidebar");
var deficit = newToolbarWidth - maxToolbarWidth;
var newSidebarWidth = sidebarWidth - deficit;
if (newSidebarWidth >= MIN_SIDEBAR_WIDTH) {
$sb.width(newSidebarWidth);
var resync = $sb.data("resyncSizer");
if (typeof resync === "function") {
resync();
}
$sb.trigger("panelResizeUpdate", [newSidebarWidth]);
$sb.trigger("panelResizeEnd", [newSidebarWidth]);
} else {
Resizer.hide($sb[0]);
}
sidebarWidth = _getSidebarWidth();
maxToolbarWidth = window.innerWidth - sidebarWidth - MIN_EDITOR_WIDTH;
}
newToolbarWidth = Math.max(newToolbarWidth, minToolbarWidth);
newToolbarWidth = Math.min(newToolbarWidth, maxToolbarWidth);
$mainToolbar.width(newToolbarWidth);
$windowContent.css("right", newToolbarWidth);
Resizer.resyncSizer($mainToolbar[0]);
recomputeLayout(true);
}
// Design mode tracks whether the editor is fully collapsed to show only the
// live-preview panel. The flag is owned by view/CentralControlBar but mirrored
// here so other modules don't need to reach into the control bar.
let _isInDesignMode = false;
/**
* Returns true while the workspace is in design mode (editor collapsed and
* live preview expanded to fill the editor area).
* @returns {boolean}
*/
function isInDesignMode() {
return _isInDesignMode;
}
// Expose on the Phoenix global so leaf modules (e.g. KeyBindingManager) can
// check design-mode state without importing WorkspaceManager and creating a
// circular dependency.
Phoenix.isInDesignMode = isInDesignMode;
/**
* Sets the design-mode flag and fires EVENT_WORKSPACE_DESIGN_MODE_CHANGE when
* the value actually changes. Intended to be called by the control bar; other
* callers should use the dedicated toggle command instead.
* @param {boolean} active
*/
function setDesignMode(active) {
const next = !!active;
if (_isInDesignMode === next) {
return;
}
_isInDesignMode = next;
exports.trigger(EVENT_WORKSPACE_DESIGN_MODE_CHANGE, _isInDesignMode);
}
// Escape key and toggle panel special handling
let _escapeKeyConsumers = {};
/**
* If any widgets related to the editor needs to handle the escape key event, add it here. returning true from the
* registered handler will prevent primary escape key toggle panel behavior of phoenix. Note that returning true
* will no stop the event bubbling, that has to be controlled with the event parameter forwarded to the handler.
* @param {string} consumerName a unique name for your consumer
* @param {function(event)} eventHandler If the eventHandler returns true for this callback, the escape key event
* will not lead to panel toggle default behavior.
* @return {boolean} true if added
*/
function addEscapeKeyEventHandler(consumerName, eventHandler) {
if(_escapeKeyConsumers[consumerName]){
console.error("EscapeKeyEvent consumer of same name already registered: ", consumerName);
return false;
}
if(typeof eventHandler !== 'function'){
console.error(`EscapeKeyEvent invalid eventHandler: ${consumerName}, ${eventHandler}`);
return false;
}
_escapeKeyConsumers[consumerName] = eventHandler;
return true;
}
/**
* Removing the escape key event consumer.
* @param {string} consumerName used to register the consumer.
* @return {boolean} true if removed
*/
function removeEscapeKeyEventHandler(consumerName) {
if(_escapeKeyConsumers[consumerName]){
delete _escapeKeyConsumers[consumerName];
return true;
} else {
console.error("EscapeKeyEvent no such consumer to remove: ", consumerName);
}
return false;
}
/**
* Shows the default launcher panel when no other panels are open.
* @private
*/
function _showDefaultPanel() {
let defaultPanel = panelIDMap[DEFAULT_PANEL_ID];
if (defaultPanel) {
defaultPanel.show();
}
}
/**
* Toggle the bottom panel container: hide if visible, show if there are
* open panels, or show the default panel when nothing is open.
* @private
* @return {boolean} true if the toggle was handled
*/
function _togglePanels() {
if (!$bottomPanelContainer) {
return false;
}
if ($bottomPanelContainer.is(":visible")) {
// Use the helper so HIDDEN(_defaultPanelId) fires — toolbar
// buttons and menu items that mirror container visibility
// (drawer, Git icon, etc.) need this signal to deselect.
PanelView.collapseContainer();
} else if (PanelView.getActiveBottomPanel()) {
// Use the helper so SHOWN(_activeId) fires — same listeners
// need this signal to re-select after a previous collapse.
PanelView.restoreContainer();
} else {
_showDefaultPanel();
}
triggerUpdateLayout();
return true;
}
function _handleEscapeKey() {
return _togglePanels();
}
/**
* Shift+Escape: toggle focus between editor and active bottom panel
* @param event
* @returns {boolean}
* @private
*/
function _handleShiftEscape(event) {
if (!event.shiftKey) {
return false;
}
if (EditorManager.getFocusedEditor()) {
// Editor has focus — focus the panel
let activePanel = PanelView.getActiveBottomPanel();
if(!activePanel || !activePanel.isVisible()){
_togglePanels();
activePanel = PanelView.getActiveBottomPanel();
}
activePanel.focus();
} else {
// Focus is elsewhere (panel, sidebar, etc.) — focus the editor
MainViewManager.focusActivePane();
}
event.stopPropagation();
event.preventDefault();
return true;
}
// pressing escape when focused on editor will toggle the bottom panel container
// pressing shift+escape toggles focus between editor and active bottom panel
function _handleKeydown(event) {
if(event.keyCode !== KeyEvent.DOM_VK_ESCAPE || KeyBindingManager.isInOverlayMode()){
return;
}
// Shift+Escape: toggle focus between editor and active bottom panel
if (_handleShiftEscape(event)) {
return;
}
for(let consumerName of Object.keys(_escapeKeyConsumers)){
if(_escapeKeyConsumers[consumerName](event)){
return;
}
}
let focussedEditor = EditorManager.getFocusedEditor();
if(!focussedEditor || EditorManager.getFocusedInlineEditor()){
// if there is no editor in focus, we do no panel toggling
// if there is an editor with an inline widget in focus, the escape key will be
// handled by the inline widget itself first.
return;
}
const dropdownOpen = $(".dropdown.open").is(":visible");
if(dropdownOpen || focussedEditor.canConsumeEscapeKeyEvent()){
return;
}
_handleEscapeKey();
event.stopPropagation();
event.preventDefault();
}
window.document.body.addEventListener("keydown", _handleKeydown, true);
// Define public API
exports.createBottomPanel = createBottomPanel;
exports.destroyBottomPanel = destroyBottomPanel;
exports.createPluginPanel = createPluginPanel;
exports.isPanelVisible = isPanelVisible;
exports.setPluginPanelWidth = setPluginPanelWidth;
exports.recomputeLayout = recomputeLayout;
exports.getAllPanelIDs = getAllPanelIDs;
exports.getPanelForID = getPanelForID;
exports.getOpenBottomPanelIDs = PanelView.getOpenBottomPanelIDs;
exports.hideAllOpenBottomPanels = PanelView.hideAllOpenPanels;
exports.addEscapeKeyEventHandler = addEscapeKeyEventHandler;
exports.removeEscapeKeyEventHandler = removeEscapeKeyEventHandler;
exports._setMockDOM = _setMockDOM;
exports.EVENT_WORKSPACE_UPDATE_LAYOUT = EVENT_WORKSPACE_UPDATE_LAYOUT;
exports.EVENT_WORKSPACE_PANEL_SHOWN = EVENT_WORKSPACE_PANEL_SHOWN;
exports.EVENT_WORKSPACE_PANEL_HIDDEN = EVENT_WORKSPACE_PANEL_HIDDEN;
exports.EVENT_WORKSPACE_DESIGN_MODE_CHANGE = EVENT_WORKSPACE_DESIGN_MODE_CHANGE;
exports.isInDesignMode = isInDesignMode;
exports.setDesignMode = setDesignMode;
exports.DEFAULT_PANEL_ID = DEFAULT_PANEL_ID;
/**
* Constant representing the type of bottom panel
* @type {string}
*/
exports.PANEL_TYPE_BOTTOM_PANEL = PanelView.PANEL_TYPE_BOTTOM_PANEL;
/**
* Constant representing the type of plugin panel
* @type {string}
*/
exports.PANEL_TYPE_PLUGIN_PANEL = PluginPanelView.PANEL_TYPE_PLUGIN_PANEL;
});