-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathmain.js
More file actions
1596 lines (1467 loc) · 72.4 KB
/
main.js
File metadata and controls
1596 lines (1467 loc) · 72.4 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . 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.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global path*/
//jshint-ignore:no-start
define(function (require, exports, module) {
const ExtensionUtils = require("utils/ExtensionUtils"),
EditorManager = require("editor/EditorManager"),
FileViewController = require("project/FileViewController"),
DocumentManager = require("document/DocumentManager"),
ExtensionInterface = require("utils/ExtensionInterface"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Menus = require("command/Menus"),
WorkspaceManager = require("view/WorkspaceManager"),
AppInit = require("utils/AppInit"),
ModalBar = require("widgets/ModalBar").ModalBar,
PreferencesManager = require("preferences/PreferencesManager"),
ProjectManager = require("project/ProjectManager"),
MainViewManager = require("view/MainViewManager"),
Strings = require("strings"),
Mustache = require("thirdparty/mustache/mustache"),
Metrics = require("utils/Metrics"),
CONSTANTS = require("LiveDevelopment/LivePreviewConstants"),
LiveDevelopment = require("LiveDevelopment/main"),
LiveDevServerManager = require("LiveDevelopment/LiveDevServerManager"),
MultiBrowserLiveDev = require("LiveDevelopment/LiveDevMultiBrowser"),
NativeApp = require("utils/NativeApp"),
StringUtils = require("utils/StringUtils"),
FileSystem = require("filesystem/FileSystem"),
DropdownButton = require("widgets/DropdownButton"),
BrowserStaticServer = require("./BrowserStaticServer"),
NodeStaticServer = require("./NodeStaticServer"),
MarkdownSync = require("./MarkdownSync"),
LivePreviewSettings = require("./LivePreviewSettings"),
NodeUtils = require("utils/NodeUtils"),
TrustProjectHTML = require("text!./trust-project.html"),
panelHTML = require("text!./panel.html"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
utils = require('./utils');
const KernalModeTrust = window.KernalModeTrust;
if(!KernalModeTrust){
throw new Error("KernalModeTrust is not defined. Cannot boot without trust ring");
}
const StateManager = PreferencesManager.stateManager;
const STATE_CUSTOM_SERVER_BANNER_ACK = "customServerBannerDone";
const PREF_MD_THEME = "mdViewerTheme";
PreferencesManager.definePreference(PREF_MD_THEME, "string", "light", {
description: Strings.MD_VIEWER_THEME_DESCRIPTION
});
let customServerModalBar;
const isBrowser = !Phoenix.isNativeApp;
const StaticServer = Phoenix.isNativeApp? NodeStaticServer : BrowserStaticServer;
const EVENT_EMBEDDED_IFRAME_WHO_AM_I = 'whoAmIframePhoenix';
const EVENT_EMBEDDED_IFRAME_FOCUS_EDITOR = 'embeddedIframeFocusEditor';
const PREVIEW_TRUSTED_PROJECT_KEY = "preview_trusted";
const PREVIEW_PROJECT_README_KEY = "preview_readme";
// holds the dropdown instance
let $dropdown = null;
const PREFERENCE_LIVE_PREVIEW_MODE = "livePreviewMode";
// live preview element highlights preference (whether on hover or click)
const PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT = CONSTANTS.PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT;
PreferencesManager.definePreference(PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT, "string", CONSTANTS.HIGHLIGHT_HOVER, {
description: Strings.LIVE_DEV_SETTINGS_ELEMENT_HIGHLIGHT_PREFERENCE,
values: [CONSTANTS.HIGHLIGHT_HOVER, CONSTANTS.HIGHLIGHT_CLICK]
});
// live preview ruler lines preference (show/hide ruler lines on element selection)
const PREFERENCE_SHOW_RULER_LINES = CONSTANTS.PREFERENCE_SHOW_RULER_LINES;
PreferencesManager.definePreference(PREFERENCE_SHOW_RULER_LINES, "boolean", false, {
description: Strings.LIVE_DEV_SETTINGS_SHOW_RULER_LINES_PREFERENCE
});
// live preview link editor and preview preference
const PREFERENCE_LIVE_PREVIEW_SYNC = CONSTANTS.PREFERENCE_LIVE_PREVIEW_SYNC;
PreferencesManager.definePreference(PREFERENCE_LIVE_PREVIEW_SYNC, "boolean", true, {
description: Strings.LIVE_DEV_SETTINGS_LINK_EDITOR_AND_PREVIEW_PREFERENCE
});
const LIVE_PREVIEW_PANEL_ID = "live-preview-panel";
const LIVE_PREVIEW_IFRAME_ID = "panel-live-preview-frame";
const MDVIEWR_IFRAME_ID = "panel-md-preview-frame";
const _sandboxAttr = Phoenix.isTestWindow ? "" :
'sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-scripts allow-forms allow-modals allow-pointer-lock"';
const LIVE_PREVIEW_IFRAME_HTML = `
<iframe id="${LIVE_PREVIEW_IFRAME_ID}" title="Live Preview" style="border: none"
width="100%" height="100%" seamless="true"
src='about:blank'
${_sandboxAttr}>
</iframe>
`;
// Mdviewer renders untrusted markdown — tighter sandbox than live preview:
// no allow-same-origin (prevents malicious scripts from accessing Phoenix context),
// no allow-forms, allow-pointer-lock (not needed for markdown editing).
// Communication works via MarkdownSync's own message handler (bypasses EventManager origin check).
const _mdSandboxAttr = Phoenix.isTestWindow ? "" :
'sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox allow-modals allow-clipboard-read allow-clipboard-write"';
const MDVIEWR_IFRAME_HTML = `
<iframe id="${MDVIEWR_IFRAME_ID}" title="Markdown Preview" style="border: none"
width="100%" height="100%" seamless="true"
src='about:blank'
${_mdSandboxAttr}
allow="clipboard-read; clipboard-write">
</iframe>
`;
if(Phoenix.isTestWindow) {
// for integ tests
window._livePreviewIntegTest = {
urlLoadCount: 0,
STATE_CUSTOM_SERVER_BANNER_ACK
};
}
// jQuery objects
let $icon,
$settingsIcon,
$iframe,
$panel,
$pinUrlBtn,
$livePreviewPopBtn,
$reloadBtn,
$chromeButton,
$safariButton,
$edgeButton,
$firefoxButton,
$chromeButtonBallast,
$safariButtonBallast,
$edgeButtonBallast,
$firefoxButtonBallast,
$panelTitle,
$modeBtn,
$previewBtn;
let customLivePreviewBannerShown = false;
// live Preview overlay variables (overlays are shown when live preview is connecting or there's a syntax error)
let $statusOverlay = null; // reference to the static overlay element
let $statusOverlayMessage = null; // reference to the message span
let $statusOverlayClose = null; // reference to the close button
let shouldShowSyncErrorOverlay = true; // once user closes the overlay we don't show them again
let shouldShowConnectingOverlay = true;
let connectingOverlayTimer = null; // this is needed as we show the connecting overlay after 3s
let connectingOverlayTimeDuration = 3000;
function _getLiveEditEntitlement() {
// in community edition, this may not be present;
return KernalModeTrust.EntitlementsManager && KernalModeTrust.EntitlementsManager.getLiveEditEntitlement();
}
let isProEditUser = false;
// this is called everytime there is a change in entitlements
async function _entitlementsChanged() {
try {
const entitlement = await _getLiveEditEntitlement();
const wasProEditUser = isProEditUser;
isProEditUser = entitlement && entitlement.activated;
// Sync edit mode with md iframe on entitlement change
if (_isMdviewrActive && $iframe && $iframe[0] && $iframe[0].contentWindow) {
if (isProEditUser && !wasProEditUser) {
// Just got pro — switch to edit mode
$iframe[0].contentWindow.postMessage(
{ type: "MDVIEWR_SET_EDIT_MODE", editMode: true }, "*");
} else if (!isProEditUser && wasProEditUser) {
// Lost pro — switch to reader mode
$iframe[0].contentWindow.postMessage(
{ type: "MDVIEWR_SET_EDIT_MODE", editMode: false }, "*");
}
}
} catch (error) {
console.error("Error updating pro user status:", error);
isProEditUser = false;
}
}
StaticServer.on(EVENT_EMBEDDED_IFRAME_WHO_AM_I, function () {
if($iframe && $iframe[0]) {
const iframeDom = $iframe[0];
iframeDom.contentWindow.postMessage({
type: "WHO_AM_I_RESPONSE",
isTauri: Phoenix.isNativeApp,
platform: Phoenix.platform,
isPhoenixEmbeddedIframe: true
}, "*"); // this is not sensitive info, and is only dispatched if requested by the iframe
}
});
StaticServer.on(EVENT_EMBEDDED_IFRAME_FOCUS_EDITOR, function () {
const editor = EditorManager.getActiveEditor();
editor.focus();
});
/**
* this function is responsible to check whether to show the overlay or not and how it should be shown
* because if user has closed the overlay manually, we don't show it again
* secondly, for connecting overlay we show that after a 3s timer, but sync error overlay is shown immediately
* @param {String} textMessage - the text that is written inside the overlay
* @param {Number} status - 1 for connect, 4 for sync error but we match it using MultiBrowserLiveDev
*/
function _handleOverlay(textMessage, status) {
if (!$panel) { return; }
// remove any existing overlay & timer
_hideOverlay();
if(LivePreviewSettings.isUsingCustomServer()){
return;
}
// we dont show the overlays for non HTML-type files
const currentDocument = DocumentManager.getCurrentDocument();
if (!currentDocument || !currentDocument.file) { return; }
const filePath = currentDocument.file.fullPath;
if (!utils.isHTMLFile(filePath)) { return; }
// to not show the overlays if user has already closed it before
if(status === MultiBrowserLiveDev.STATUS_CONNECTING && !shouldShowConnectingOverlay) { return; }
if(status === MultiBrowserLiveDev.STATUS_SYNC_ERROR && !shouldShowSyncErrorOverlay) { return; }
// for connecting status, we delay showing the overlay by 3 seconds
if(status === MultiBrowserLiveDev.STATUS_CONNECTING) {
connectingOverlayTimer = setTimeout(() => {
// before creating the overlays we need to do a recheck for custom server
// cause project prefs sometimes takes time to reload which causes overlays to appear for custom servers
if(LivePreviewSettings.isUsingCustomServer()){
connectingOverlayTimer = null;
return;
}
_showOverlay(textMessage, status);
connectingOverlayTimer = null;
}, connectingOverlayTimeDuration);
return;
}
// for sync error status, show immediately
_showOverlay(textMessage, status);
}
/**
* this function is init the overlay.
* so overlay is shown when the live preview is connecting or live preview stopped because of some syntax error
*/
function _initOverlay() {
if (!$panel) { return; }
$statusOverlay = $panel.find(".live-preview-status-overlay");
$statusOverlayMessage = $statusOverlay.find(".live-preview-overlay-message");
$statusOverlayClose = $statusOverlay.find(".live-preview-overlay-close");
$statusOverlayClose.on("click", () => {
const currentStatue = $statusOverlay.data("status");
if(currentStatue === MultiBrowserLiveDev.STATUS_CONNECTING) {
shouldShowConnectingOverlay = false;
} else if(currentStatue === MultiBrowserLiveDev.STATUS_SYNC_ERROR) {
shouldShowSyncErrorOverlay = false;
}
_hideOverlay();
});
}
/**
* Show the overlay with the given message and status
* @param {String} textMessage - the text that is written inside the overlay
* @param {Number} status - 1 for connect, 4 for sync error but we match it using MultiBrowserLiveDev
*/
function _showOverlay(textMessage, status) {
if (!$statusOverlay) { return; }
$statusOverlayMessage.text(textMessage);
$statusOverlay.data("status", status);
// @devansh - commenting this out to not show the status overlays, need to fix later
// the issue is that status overlay - conneting status was never getting removed on devices with
// slow connections or sites with heavy videos...
// $statusOverlay.removeClass("forced-hidden");
}
/**
* responsible to hide the overlay
*/
function _hideOverlay() {
_clearConnectingOverlayTimer();
if ($statusOverlay) {
$statusOverlay.addClass("forced-hidden");
}
}
/**
* This is a helper function that just checks that if connectingOverlayTimer exists, we clear it
*/
function _clearConnectingOverlayTimer() {
if (connectingOverlayTimer) {
clearTimeout(connectingOverlayTimer);
connectingOverlayTimer = null;
}
}
/**
* Hide the play button and mode dropdown when mdviewer is active,
* since MD files have their own Edit/Reader toggle in the iframe toolbar.
* Does not hide in custom server mode (handled by _isMdviewrActive being false).
*/
function _updateLPControlsForMdviewer() {
if ($previewBtn) {
$previewBtn.toggle(!_isMdviewrActive);
}
if ($modeBtn) {
$modeBtn.toggle(!_isMdviewrActive);
}
}
function _updateModeButton(mode) {
if ($modeBtn) {
if (mode === "highlight") {
$modeBtn[0].textContent = Strings.LIVE_PREVIEW_MODE_HIGHLIGHT;
} else if (mode === "edit") {
$modeBtn[0].textContent = Strings.LIVE_PREVIEW_MODE_EDIT;
} else {
$modeBtn[0].textContent = Strings.LIVE_PREVIEW_MODE_PREVIEW;
}
}
}
function _initializeMode() {
const currentMode = LiveDevelopment.getCurrentMode();
// when in preview mode, we need to give the play button a selected state
if (currentMode === LiveDevelopment.CONSTANTS.LIVE_PREVIEW_MODE) {
$previewBtn.addClass('selected');
} else {
$previewBtn.removeClass('selected');
}
_updateModeButton(currentMode);
}
function _showModeSelectionDropdown(event) {
const isEditFeaturesActive = isProEditUser;
const currentMode = LiveDevelopment.getCurrentMode();
const items = [
Strings.LIVE_PREVIEW_MODE_PREVIEW,
Strings.LIVE_PREVIEW_MODE_HIGHLIGHT,
Strings.LIVE_PREVIEW_MODE_EDIT
];
// Only add edit-specific options when in edit mode and edit features are active
const isEditMode = currentMode === LiveDevelopment.CONSTANTS.LIVE_EDIT_MODE;
if (isEditFeaturesActive && isEditMode) {
items.push("---");
items.push(Strings.LIVE_PREVIEW_EDIT_HIGHLIGHT_ON);
items.push(Strings.LIVE_PREVIEW_SHOW_RULER_LINES);
}
$dropdown = new DropdownButton.DropdownButton("", items, function(item, index) {
if (item === Strings.LIVE_PREVIEW_MODE_PREVIEW) {
// using empty spaces to keep content aligned
return currentMode === LiveDevelopment.CONSTANTS.LIVE_PREVIEW_MODE ?
`✓ ${item}` : `${'\u00A0'.repeat(4)}${item}`;
} else if (item === Strings.LIVE_PREVIEW_MODE_HIGHLIGHT) {
return currentMode === LiveDevelopment.CONSTANTS.LIVE_HIGHLIGHT_MODE ?
`✓ ${item}` : `${'\u00A0'.repeat(4)}${item}`;
} else if (item === Strings.LIVE_PREVIEW_MODE_EDIT) {
const checkmark = currentMode === LiveDevelopment.CONSTANTS.LIVE_EDIT_MODE ?
"✓ " : `${'\u00A0'.repeat(4)}`;
const crownIcon = !isEditFeaturesActive ?
' <span style="color: #FBB03B; border: 1px solid #FBB03B; padding: 2px 4px; border-radius: 10px; font-size: 9px; margin-left: 12px;"><i class="fas fa-crown"></i> Pro</span>' : '';
return {
html: `${checkmark}${item}${crownIcon}`,
enabled: true
};
} else if (item === Strings.LIVE_PREVIEW_EDIT_HIGHLIGHT_ON) {
const isHoverMode =
PreferencesManager.get(PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT) === CONSTANTS.HIGHLIGHT_HOVER;
if(isHoverMode) {
return `✓ ${Strings.LIVE_PREVIEW_EDIT_HIGHLIGHT_ON}`;
}
return `${'\u00A0'.repeat(4)}${Strings.LIVE_PREVIEW_EDIT_HIGHLIGHT_ON}`;
} else if (item === Strings.LIVE_PREVIEW_SHOW_RULER_LINES) {
const isEnabled = PreferencesManager.get(PREFERENCE_SHOW_RULER_LINES);
if(isEnabled) {
return `✓ ${Strings.LIVE_PREVIEW_SHOW_RULER_LINES}`;
}
return `${'\u00A0'.repeat(4)}${Strings.LIVE_PREVIEW_SHOW_RULER_LINES}`;
}
return item;
});
// Append to document body for absolute positioning
$("body").append($dropdown.$button);
// Position the dropdown at the mouse coordinates
$dropdown.$button.css({
position: "absolute",
left: event.pageX + "px",
top: event.pageY + "px",
zIndex: 1000
});
// Add a custom class to override the max-height
$dropdown.dropdownExtraClasses = "mode-context-menu";
$dropdown.showDropdown();
$(".mode-context-menu").css("max-height", "300px");
// handle the option selection
$dropdown.on("select", function (e, item, index) {
if (index === 0) {
LiveDevelopment.setMode(LiveDevelopment.CONSTANTS.LIVE_PREVIEW_MODE);
} else if (index === 1) {
LiveDevelopment.setMode(LiveDevelopment.CONSTANTS.LIVE_HIGHLIGHT_MODE);
} else if (index === 2) {
if (!LiveDevelopment.setMode(LiveDevelopment.CONSTANTS.LIVE_EDIT_MODE)) {
if(KernalModeTrust.ProDialogs) {
KernalModeTrust.ProDialogs.showProUpsellDialog(
KernalModeTrust.ProDialogs.UPSELL_TYPE_LIVE_EDIT);
} else {
Metrics.countEvent(Metrics.EVENT_TYPE.PRO, "proUpsellDlg", "fail");
}
}
} else if (item === Strings.LIVE_PREVIEW_EDIT_HIGHLIGHT_ON) {
// Don't allow edit highlight toggle if edit features are not active
if (!isEditFeaturesActive) {
return;
}
// Toggle between hover and click
const currMode = PreferencesManager.get(PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT);
const newMode = (currMode !== CONSTANTS.HIGHLIGHT_CLICK) ?
CONSTANTS.HIGHLIGHT_CLICK : CONSTANTS.HIGHLIGHT_HOVER;
PreferencesManager.set(PREFERENCE_PROJECT_ELEMENT_HIGHLIGHT, newMode);
return; // Don't dismiss highlights for this option
} else if (item === Strings.LIVE_PREVIEW_SHOW_RULER_LINES) {
// Don't allow ruler lines toggle if edit features are not active
if (!isEditFeaturesActive) {
return;
}
// Toggle ruler lines on/off
const currentValue = PreferencesManager.get(PREFERENCE_SHOW_RULER_LINES);
PreferencesManager.set(PREFERENCE_SHOW_RULER_LINES, !currentValue);
return; // Don't dismiss highlights for this option
}
});
// Remove the button after the dropdown is hidden
$dropdown.$button.css({
display: "none"
});
}
/**
* to close the overflow button's dropdown
*/
function _closeDropdown() {
if ($dropdown) {
if ($dropdown.$button) {
$dropdown.$button.remove();
}
$dropdown = null;
}
}
function _handleLPModeBtnClick(e) {
e.stopPropagation();
$dropdown ? _closeDropdown() : _showModeSelectionDropdown(e);
}
function _getTrustProjectPage() {
const trustProjectMessage = StringUtils.format(Strings.TRUST_PROJECT,
path.basename(ProjectManager.getProjectRoot().fullPath));
const templateVars = {
trustProjectMessage,
Strings: Strings
};
return Mustache.render(TrustProjectHTML, templateVars);
}
function _isProjectPreviewTrusted() {
// We Do not show a trust project window before executing a live preview in desktop builds as in
// desktop, each project will have its on live preview `server:port` domain isolation.
// Live preview is almost the same as opening a url in the browser. The user opening a project by going though
// a lot of selection folder picker dialogs should be regarded as enough confirmation that the user
// intents to open that file for preview via a browser url. The browser security sandbox should
// take care of most of the security issues as much as any other normal browsing in a browser.
// Showing a trust window is UI friction for 99% of users. The user confirm dialog also relies on the user
// taking the decision that an anti-virus/firewall would make- which is not going to end well; and a lot of
// our users are school students or new devs, who we should assist. Phoenix trust model will heavily rely on
// us doing the necessary sand boxing whenever possible.
// A compromised project can have special html that can instruct phoenix to change editor selections and
// edit only the project files. We will have safeguards in place to detect anomalous large change requests
// to mitigate DOS attacks coming from the live preview in the future. A malicious project changing its on
// text only using its own code should be an acceptable risk for now as it cant affect anything else in the
// system.
if(Phoenix.isTestWindow || Phoenix.isNativeApp){ // for test windows, we trust all test files
return true;
}
// In browsers, The url bar will show up as phcode.dev for live previews and there is a chance that
// a malicious project can appear as `phcode.dev` when user live previews. So for every live preview
// popout tab which shows `phcode.dev` in browser address bar, we will show a trust live preview
// confirm dialog every single time when user opens live preivew project.
// Further, since all live previews for all projects uses the same phcode.live domain,
// untrusted projects can access data of past opened projects. Future plans for browser versions
// include adopting a similar approach to desktop to dynamically generate URLs in the format
// `project-name.phcode.live` preventing the past data access problem in browser. This will also let us drop the
// trust project screen an work the same as desktop apps.
const projectPath = ProjectManager.getProjectRoot().fullPath;
if(projectPath === ProjectManager.getWelcomeProjectPath() ||
projectPath === ProjectManager.getExploreProjectPath()){
return true;
}
const isTrustedProject = `${PREVIEW_TRUSTED_PROJECT_KEY}-${projectPath}`;
return !!PhStore.getItem(isTrustedProject);
}
window._trustCurrentProjectForLivePreview = function () {
$iframe.attr('srcdoc', null);
const projectPath = ProjectManager.getProjectRoot().fullPath;
const isTrustedProjectKey = `${PREVIEW_TRUSTED_PROJECT_KEY}-${projectPath}`;
PhStore.setItem(isTrustedProjectKey, true);
_loadPreview(true);
};
function _setProjectReadmePreviewdOnce() {
const projectPath = ProjectManager.getProjectRoot().fullPath;
const previewReadmeKey = `${PREVIEW_PROJECT_README_KEY}-${projectPath}`;
PhStore.setItem(previewReadmeKey, true);
}
function _isProjectReadmePreviewdOnce() {
const projectPath = ProjectManager.getProjectRoot().fullPath;
const previewReadmeKey = `${PREVIEW_PROJECT_README_KEY}-${projectPath}`;
return !!PhStore.getItem(previewReadmeKey);
}
ExtensionInterface.registerExtensionInterface(
ExtensionInterface._DEFAULT_EXTENSIONS_INTERFACE_NAMES.PHOENIX_LIVE_PREVIEW, exports);
/**
* @private
* @return {StaticServerProvider} The singleton StaticServerProvider initialized
* on app ready.
*/
function _createStaticServer() {
var config = {
pathResolver: ProjectManager.makeProjectRelativeIfPossible,
root: ProjectManager.getProjectRoot().fullPath
};
return new StaticServer.StaticServer(config);
}
// Templates
ExtensionUtils.loadStyleSheet(module, "live-preview.css");
// Other vars
let panel,
urlPinned,
currentLivePreviewURL = "",
currentPreviewFile = '',
_loadGeneration = 0,
_isMdviewrActive = false,
$mdviewrIframe = null; // persistent md iframe, survives HTML preview switches
function _blankIframe() {
// we have to remove the dom node altog as at time chrome fails to clear workers if we just change
// src. so we delete the node itself to eb thorough.
// Don't destroy the persistent md iframe — just hide it
if ($mdviewrIframe && $iframe[0] === $mdviewrIframe[0]) {
MarkdownSync.deactivate();
_isMdviewrActive = false;
_updateLPControlsForMdviewer();
$mdviewrIframe.hide();
let newIframe = $(LIVE_PREVIEW_IFRAME_HTML);
$mdviewrIframe.after(newIframe);
$iframe = newIframe;
} else {
let newIframe = $(LIVE_PREVIEW_IFRAME_HTML);
newIframe.insertAfter($iframe);
$iframe.remove();
$iframe = newIframe;
}
}
let panelShownAtStartup;
function _setPanelVisibility(isVisible) {
if (isVisible) {
panelShownAtStartup = true;
$icon.toggleClass("active");
panel.show();
_loadPreview(true, true);
_showCustomServerBannerIfNeeded();
} else {
$icon.toggleClass("active");
_blankIframe();
panel.hide();
}
}
function _startOrStopLivePreviewIfRequired(explicitClickOnLPIcon) {
let visible = panel && panel.isVisible();
if(visible && (LiveDevelopment.isInactive() || explicitClickOnLPIcon)) {
LiveDevelopment.openLivePreview();
} else if(!visible && LiveDevelopment.isActive()
&& !StaticServer.hasActiveLivePreviews()) {
LiveDevelopment.closeLivePreview();
}
}
function _toggleVisibilityOnClick() {
let visible = !panel.isVisible();
_setPanelVisibility(visible);
_startOrStopLivePreviewIfRequired(true);
}
function _togglePinUrl() {
let pinStatus = $pinUrlBtn.hasClass('pin-icon');
if(pinStatus){
$pinUrlBtn.removeClass('pin-icon').addClass('unpin-icon');
} else {
$pinUrlBtn.removeClass('unpin-icon').addClass('pin-icon');
}
urlPinned = !pinStatus;
LiveDevelopment.setLivePreviewPinned(urlPinned, currentPreviewFile);
_loadPreview(true);
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "pinURLBtn", "click");
}
const ALLOWED_BROWSERS_NAMES = [`chrome`, `firefox`, `safari`, `edge`, `browser`, `browserPrivate`];
function _popoutLivePreview(browserName) {
// We cannot use $iframe.src here if panel is hidden
const openURL = StaticServer.getTabPopoutURL(currentLivePreviewURL);
if(browserName && ALLOWED_BROWSERS_NAMES.includes(browserName)){
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "popout", browserName);
NodeUtils.openUrlInBrowser(openURL, browserName)
.then(()=>{
_loadPreview(true);
_setPanelVisibility(false);
})
.catch(err=>{
console.error("Error opening url in browser: ", browserName, err);
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "popFail", browserName);
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
StringUtils.format(Strings.LIVE_DEV_OPEN_ERROR_TITLE, browserName),
StringUtils.format(Strings.LIVE_DEV_OPEN_ERROR_MESSAGE, browserName)
);
});
} else {
NativeApp.openURLInDefaultBrowser(openURL, "livePreview");
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "popoutBtn", "click");
_loadPreview(true);
_setPanelVisibility(false);
}
}
function _setTitle(fileName, fullPath, currentLivePreviewURL) {
let message = Strings.LIVE_DEV_SELECT_FILE_TO_PREVIEW,
tooltip = message;
if(fileName){
message = `${fileName}`;
tooltip = StringUtils.format(Strings.LIVE_DEV_TOOLTIP_SHOW_IN_EDITOR, fileName);
}
if(currentLivePreviewURL){
tooltip = `${tooltip}\n${currentLivePreviewURL}`;
}
$panelTitle.text(currentLivePreviewURL || message);
$panelTitle.attr("title", tooltip);
$panelTitle.attr("data-fullPath", fullPath);
}
function _showOpenBrowserIcons() {
if(!Phoenix.isNativeApp) {
return;
}
// only in desktop builds we show open with browser icons
$chromeButton.removeClass("forced-hidden");
$chromeButtonBallast.removeClass("forced-hidden");
$chromeButtonBallast.addClass("forced-inVisible");
$edgeButton.removeClass("forced-hidden");
$edgeButtonBallast.removeClass("forced-hidden");
$edgeButtonBallast.addClass("forced-inVisible");
$firefoxButton.removeClass("forced-hidden");
$firefoxButtonBallast.removeClass("forced-hidden");
$firefoxButtonBallast.addClass("forced-inVisible");
if (brackets.platform === "mac") {
$safariButton.removeClass("forced-hidden");
$safariButtonBallast.removeClass("forced-hidden");
$safariButtonBallast.addClass("forced-inVisible");
}
}
/**
* Handle preview button click - toggles between preview mode and the user's default mode.
* PRO users toggle between preview and edit mode.
* community users toggle between preview and highlight mode.
*/
function _handlePreviewBtnClick() {
if($previewBtn.hasClass('selected')) {
$previewBtn.removeClass('selected');
const defaultMode = isProEditUser ? 'edit' : 'highlight';
PreferencesManager.set(PREFERENCE_LIVE_PREVIEW_MODE, defaultMode);
} else {
// Currently NOT in preview mode - switch to preview
$previewBtn.addClass('selected');
PreferencesManager.set(PREFERENCE_LIVE_PREVIEW_MODE, "preview");
}
}
async function _createExtensionPanel() {
let templateVars = {
Strings: Strings,
livePreview: Strings.LIVE_DEV_STATUS_TIP_OUT_OF_SYNC,
clickToReload: Strings.LIVE_DEV_CLICK_TO_RELOAD_PAGE,
clickToPreview: Strings.LIVE_PREVIEW_MODE_TOGGLE_PREVIEW,
livePreviewSettings: Strings.LIVE_DEV_SETTINGS,
livePreviewConfigureModes: Strings.LIVE_PREVIEW_CONFIGURE_MODES,
clickToPopout: Strings.LIVE_DEV_CLICK_POPOUT,
openInChrome: Strings.LIVE_DEV_OPEN_CHROME,
openInSafari: Strings.LIVE_DEV_OPEN_SAFARI,
openInEdge: Strings.LIVE_DEV_OPEN_EDGE,
openInFirefox: Strings.LIVE_DEV_OPEN_FIREFOX,
clickToPinUnpin: Strings.LIVE_DEV_CLICK_TO_PIN_UNPIN
};
const PANEL_MIN_SIZE = 50;
const INITIAL_PANEL_SIZE = document.body.clientWidth/2.5;
$icon = $("#toolbar-go-live");
$icon.click(_toggleVisibilityOnClick);
$panel = $(Mustache.render(panelHTML, templateVars));
$iframe = $panel.find("#panel-live-preview-frame");
$pinUrlBtn = $panel.find("#pinURLButton");
$reloadBtn = $panel.find("#reloadLivePreviewButton");
$livePreviewPopBtn = $panel.find("#livePreviewPopoutButton");
$chromeButton = $panel.find("#chromeButton");
$safariButton = $panel.find("#safariButton");
$edgeButton = $panel.find("#edgeButton");
$firefoxButton = $panel.find("#firefoxButton");
// ok i dont know enough CSS to do this without these Ballast/ this works for the limited dev time I have.
$chromeButtonBallast = $panel.find("#chromeButtonBallast");
$safariButtonBallast = $panel.find("#safariButtonBallast");
$edgeButtonBallast = $panel.find("#edgeButtonBallast");
$firefoxButtonBallast = $panel.find("#firefoxButtonBallast");
$panelTitle = $panel.find("#panel-live-preview-title");
$settingsIcon = $panel.find("#livePreviewSettingsBtn");
$modeBtn = $panel.find("#livePreviewModeBtn");
$previewBtn = $panel.find("#previewModeLivePreviewButton");
// Markdown theme toggle — persist user choice
MarkdownSync.setThemeToggleHandler((theme) => {
PreferencesManager.set(PREF_MD_THEME, theme);
});
$panel.find(".live-preview-settings-banner-btn").on("click", ()=>{
CommandManager.execute(Commands.FILE_LIVE_FILE_PREVIEW_SETTINGS);
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "settingsBtnBanner", "click");
});
$panel.find(".custom-server-banner-close-icon").on("click", ()=>{
$panel.find(".live-preview-custom-banner").addClass("forced-hidden");
});
$iframe[0].onload = function () {
$iframe.attr('srcdoc', null);
};
$panelTitle.on("click", ()=>{
const fullPath = $panelTitle.attr("data-fullPath");
const openPanes = MainViewManager.findInAllWorkingSets(fullPath);
let paneToUse = MainViewManager.ACTIVE_PANE;
if(openPanes.length) {
paneToUse = openPanes[0].paneId;
}
FileViewController.openFileAndAddToWorkingSet(fullPath, paneToUse);
});
$chromeButton.on("click", ()=>{
_popoutLivePreview("chrome");
});
$safariButton.on("click", ()=>{
_popoutLivePreview("safari");
});
$edgeButton.on("click", ()=>{
_popoutLivePreview("edge");
});
$firefoxButton.on("click", ()=>{
_popoutLivePreview("firefox");
});
$modeBtn.on("click", _handleLPModeBtnClick);
$previewBtn.on("click", _handlePreviewBtnClick);
_showOpenBrowserIcons();
$settingsIcon.click(()=>{
CommandManager.execute(Commands.FILE_LIVE_FILE_PREVIEW_SETTINGS);
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "settingsBtn", "click");
});
const popoutSupported = Phoenix.isNativeApp
|| Phoenix.browser.desktop.isChromeBased || Phoenix.browser.desktop.isFirefox;
if(!popoutSupported){
// live preview can be popped out currently in only chrome based browsers. The cross domain iframe
// that serves the live preview(phcode.live) is sandboxed to the tab in which phcode.dev resides.
// all iframes in the tab can communicate between each other, but when you popout another tab, it forms
// its own sandbox and firefox/safari prevents communication from iframe in one tab to another. chrome
// doesn't seem to enforce this restriction. Since this is a core usecase, we will try to enable this
// workflow whenever possible.
$livePreviewPopBtn.addClass("forced-hidden");
}
panel = WorkspaceManager.createPluginPanel(LIVE_PREVIEW_PANEL_ID, $panel,
PANEL_MIN_SIZE, $icon, INITIAL_PANEL_SIZE);
WorkspaceManager.recomputeLayout(false);
$pinUrlBtn.click(_togglePinUrl);
$livePreviewPopBtn.click(_popoutLivePreview);
$reloadBtn.click(()=>{
if (_isMdviewrActive && urlPinned) {
// When pinned, just re-send the pinned document's content
MarkdownSync.resendContent();
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "reloadBtn", "click");
return;
}
if (_isMdviewrActive) {
MarkdownSync.reloadCurrentFile();
}
_loadPreview(true, true);
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "reloadBtn", "click");
});
// init the status overlay
_initOverlay();
}
function _loadMdviewrPreview(previewDetails, force) {
const currentDoc = DocumentManager.getCurrentDocument();
if (!currentDoc) {
return;
}
// Only render markdown files — skip binary, json, and other non-markdown files
// (can happen when previewDetails is stale from async getPreviewDetails)
if (!utils.isMarkdownFile(currentDoc.file.fullPath)) {
return;
}
const mdFileURL = encodeURI(previewDetails.URL);
const baseURL = mdFileURL.substring(0, mdFileURL.lastIndexOf("/") + 1);
currentPreviewFile = previewDetails.fullPath;
if (!urlPinned) {
currentLivePreviewURL = mdFileURL;
}
let relativeOrFullPath = ProjectManager.makeProjectRelativeIfPossible(previewDetails.fullPath);
relativeOrFullPath = Phoenix.app.getDisplayPath(relativeOrFullPath);
_setTitle(relativeOrFullPath, currentPreviewFile, "");
if (_isMdviewrActive) {
if (urlPinned) {
return;
}
// Mdviewr iframe already loaded, just update the sync for the new document
MarkdownSync.activate(currentDoc, $iframe, baseURL);
return;
}
// Reuse persistent md iframe if it exists (e.g. returning from HTML preview)
if ($mdviewrIframe && $mdviewrIframe[0].parentNode) {
// Hide the current HTML iframe and show the md iframe
if ($iframe[0] !== $mdviewrIframe[0]) {
$iframe.remove();
}
$mdviewrIframe.show();
$iframe = $mdviewrIframe;
} else if (panel.isVisible()) {
// First time: create the md iframe (tighter sandbox for untrusted content)
const mdviewrURL = StaticServer.getMdviewrURL();
let newIframe = $(MDVIEWR_IFRAME_HTML);
newIframe.insertAfter($iframe);
$iframe.remove();
$iframe = newIframe;
$mdviewrIframe = newIframe;
if (_isProjectPreviewTrusted()) {
$iframe.attr('src', mdviewrURL);
}
}
_isMdviewrActive = true;
MarkdownSync.activate(currentDoc, $iframe, baseURL);
// Apply persisted theme preference
const savedTheme = PreferencesManager.get(PREF_MD_THEME) || "light";
MarkdownSync.sendThemeOverride(savedTheme);
// Sync preview mode and edit mode for reuse case where iframe is already ready
_updateLPControlsForMdviewer();
Metrics.countEvent(Metrics.EVENT_TYPE.LIVE_PREVIEW, "render", "mdviewr");
}
async function _loadPreview(force, isReload) {
// we wait till the first server ready event is received till we render anything. else a 404-page may
// briefly flash on first load of phoenix as we try to load the page before the server is available.
const isPreviewLoadable = panel.isVisible() || StaticServer.hasActiveLivePreviews();
if(!isPreviewLoadable){
return;
}
const thisGeneration = ++_loadGeneration;
// panel-live-preview-title
let previewDetails = await StaticServer.getPreviewDetails();
if(thisGeneration !== _loadGeneration) {
return; // A newer _loadPreview call has been made; this one is stale
}
if(urlPinned && !force) {
return;
}
// When md viewer is pinned, block ALL preview loads — the previewDetails
// would be for the current editor file, not the pinned file
if(urlPinned && _isMdviewrActive) {
return;
}
// Use mdviewr for markdown files (unless custom server is configured)
if(previewDetails.isMarkdownFile && !previewDetails.isCustomServer && !previewDetails.isNoPreview) {
_loadMdviewrPreview(previewDetails, force);
return;
}
// Switching away from mdviewr to non-markdown preview
// Hide the md iframe instead of destroying it so cache is preserved
if(_isMdviewrActive) {
MarkdownSync.deactivate();
_isMdviewrActive = false;
if ($mdviewrIframe) {
$mdviewrIframe.hide();
}
_updateLPControlsForMdviewer();
}
let newSrc = encodeURI(previewDetails.URL);
if($iframe.attr('src') === newSrc && !force){
// we already have this url loaded in previews!
return;
}
// we have to create a new iframe on every switch as we use cross domain iframes for phcode.live which
// the browser sandboxes strictly and sometimes it wont allow a src change on our iframe causing live
// preview breaks sporadically. to alleviate this, we create a new iframe every time.
if(!urlPinned) {
currentLivePreviewURL = newSrc;
currentPreviewFile = previewDetails.fullPath;
}
if(isReload && previewDetails.isHTMLFile){
LiveDevelopment.openLivePreview();
}
let relativeOrFullPath= ProjectManager.makeProjectRelativeIfPossible(currentPreviewFile);
relativeOrFullPath = Phoenix.app.getDisplayPath(relativeOrFullPath);
_setTitle(relativeOrFullPath, currentPreviewFile,
previewDetails.isCustomServer ? currentLivePreviewURL : "");
if(panel.isVisible()) {
if(!customLivePreviewBannerShown && LivePreviewSettings.isUsingCustomServer()
&& previewDetails.isCustomServer) {
customLivePreviewBannerShown = true;
$panel.find(".live-preview-custom-banner").removeClass("forced-hidden");
$panel.find(".live-preview-banner-message").text(
StringUtils.format(Strings.LIVE_PREVIEW_CUSTOM_SERVER_BANNER,
LivePreviewSettings.getCustomServeBaseURL())
);
}