This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
app.js
1383 lines (1306 loc) · 42.5 KB
/
app.js
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
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* global window, document, navigator, fetch, CustomEvent */
/* eslint-disable no-console, no-alert */
'use strict';
(() => {
/**
* @typedef {Object.<string, string>} elemAttr
* @description The name and value of the attribute to set on an element.
*/
/**
* @typedef {Object.<string, Function>} elemLstnr
* @description The event name and listener to register on an element.
*/
/**
* @typedef {Object} elemConfig
* @description The configuration of an element to add.
* @prop {string} tag The tag name (mandatory)
* @prop {string} text The text content (optional)
* @prop {elemAttr[]} attrs The attributes (optional)
* @prop {elemLstnr[]} lstnrs The event listeners (optional)
*/
/**
* @typedef {Object} pluginButton
* @description The configuration for a plugin button. This can be used as
* a shorthand for {@link elemConfig}.
* @prop {string} text The button text
* @prop {Function} action The click listener
* @prop {boolean|Function} isPressed Determines whether the button is pressed
*/
/**
* @typedef {Object} plugin
* @description The plugin configuration.
* @prop {string} id The plugin ID (mandatory)
* @prop {pluginButton} button A button configuration object (optional)
* @prop {boolean} override=false True to replace an existing plugin (optional)
* @prop {elemConfig[]} elements An array of elements to add (optional)
* @prop {Function} condition Determines whether to show this plugin (optional).
* This function is expected to return a boolean when called with the sidekick as argument.
* @prop {Function} callback A function called after adding the plugin (optional).
* This function is called with the sidekick and the newly added plugin as arguments.
*/
/**
* @typedef {Object} sidekickConfig
* @description The sidekick configuration.
* before creating the {@link Sidekick}.
* @prop {string} owner The GitHub owner or organization (mandatory)
* @prop {string} repo The GitHub owner or organization (mandatory)
* @prop {string} ref=main The Git reference or branch (optional)
* @prop {string} project The name of the Helix project used in the sharing link (optional)
* @prop {plugin[]} plugins An array of plugin configurations (optional)
* @prop {string} outerHost The outer CDN's host name (optional)
* @prop {string} host The production host name to publish content to (optional)
* @prop {boolean} byocdn=false <pre>true</pre> if the production host is a 3rd party CDN
* @prop {boolean} hlx3=false <pre>true</pre> if the project is running on Helix 3
* @prop {boolean} devMode=false Loads configuration and plugins from the developmemt environment
*/
/**
* @external
* @name "window.hlx.sidekickConfig"
* @type {sidekickConfig}
* @description The global variable holding the initial sidekick configuration.
*/
/**
* @external
* @name "window.hlx.sidekick"
* @type {Sidekick}
* @description The global variable referencing the {@link Sidekick} singleton.
*/
/**
* @external
* @name "window.hlx.sidekickScript"
* @type {Element}
* @description The <pre>script</pre> element which loaded the sidekick application.
*/
/**
* @event Sidekick#shown
* @type {Sidekick} The sidekick
* @description This event is fired when the sidekick has been shown.
*/
/**
* @event Sidekick#hidden
* @type {Sidekick} The sidekick
* @description This event is fired when the sidekick has been hidden.
*/
/**
* @event Sidekick#pluginused
* @type {Object} The plugin used
* @property {string} id The plugin ID
* @property {Element} button The button element
* @description This event is fired when a sidekick plugin has been used.
*/
/**
* @event Sidekick#contextloaded
* @type {Object} The context object
* @property {sidekickConfig} config The sidekick configuration
* @property {Location} location The sidekick location
* @description This event is fired when the context has been loaded.
*/
/**
* @event Sidekick#statusfetched
* @type {Object} The status object
* @description This event is fired when the status has been fetched.
*/
/**
* @event Sidekick#envswitched
* @type {Object} The environment object
* @property {string} sourceUrl The URL of the source environment
* @property {string} targetUrl The URL of the target environment
* @description This event is fired when the environment has been switched
*/
/**
* @event Sidekick#updated
* @type {string} The updated path
* @description This event is fired when a path has been updated.
*/
/**
* @event Sidekick#published
* @type {string} The published path
* @description This event is fired when a path has been published.
*/
/**
* Mapping between the plugin IDs that will be treated as environments
* and their corresponding host properties in the config.
* @private
* @type {Object}
*/
const ENVS = {
edit: 'editor',
preview: 'innerHost',
live: 'outerHost',
prod: 'host',
};
/**
* The URL of the development environment.
* @see {@link https://github.com/adobe/helix-cli|Helix CLI}).
* @private
* @type {URL}
*/
const DEV_URL = new URL('http://localhost:3000');
/**
* Checks if the current location is an editor URL (SharePoint or Google Docs).
* @private
* @param {Location} loc The location object
* @returns {boolean} <code>true</code> if editor URL, else <code>false</code>
*/
function isEditor(loc) {
return /.*\.sharepoint\.com/.test(loc.host)
|| loc.host === 'docs.google.com';
}
/**
* Checks if a Helix host name matches another, regardless of ref.
* @private
* @param {string} baseHost The base host
* @param {string} host The host to match against the base host
* @returns {boolean} <code>true</code> if the hosts match, else <code>false</code>
*/
function matchHelixHost(baseHost, host) {
if (!baseHost || !host) {
return false;
}
const compHost = (host.split('--').length === 3)
? host.substring(host.indexOf('--') + 2)
: host;
return baseHost === compHost || baseHost.endsWith(compHost);
}
/**
* Returns the sidekick configuration.
* @private
* @param {sidekickConfig} cfg The sidekick config (defaults to {@link window.hlx.sidekickConfig})
* @returns {Object} The sidekick configuration
*/
function initConfig(cfg) {
const config = cfg || (window.hlx && window.hlx.sidekickConfig) || {};
const {
owner,
repo,
ref = 'main',
outerHost,
host,
project,
hlx3 = false,
} = config;
const innerPrefix = owner && repo ? `${ref}--${repo}--${owner}` : null;
const publicHost = host && host.startsWith('http') ? new URL(host).host : host;
const scriptUrl = window.hlx.sidekickScript && window.hlx.sidekickScript.src;
let innerHost;
if (hlx3) {
innerHost = 'hlx3.page';
}
if (!innerHost && scriptUrl) {
// get hlx domain from script src (used for branch deployment testing)
const scriptHost = new URL(scriptUrl).host;
if (scriptHost && scriptHost !== 'www.hlx.live' && !scriptHost.startsWith(DEV_URL.host)) {
// keep only 1st and 2nd level domain
innerHost = scriptHost.split('.')
.reverse()
.splice(0, 2)
.reverse()
.join('.');
}
}
if (!innerHost) {
// fall back to hlx.page
innerHost = 'hlx.page';
}
innerHost = innerPrefix ? `${innerPrefix}.${innerHost}` : null;
let liveHost = outerHost;
if (!liveHost && publicHost && owner && repo) {
liveHost = `${repo}--${owner}.hlx.live`;
if (hlx3) {
// always use branch name in hlx3 outer CDN
liveHost = `${ref}--${liveHost}`;
}
}
return {
...config,
ref,
innerHost,
outerHost: liveHost,
scriptUrl,
host: publicHost,
project: project || '',
hlx3,
};
}
/**
* Returns the location of the current document.
* @private
* @returns {Location} The location object
*/
function getLocation() {
// first check if there is a test location
const $test = document.getElementById('sidekick_test_location');
if ($test) {
try {
return new URL($test.value);
} catch (e) {
return null;
}
}
// fall back to window location
const {
hash, host, hostname, href, origin, pathname, port, protocol, search,
} = window.location;
// replace single - with 2
const makeHostHelixCompliant = (ahost) => {
if (ahost.match(/^.*?--.*?--.*?\./gm)) {
return ahost;
}
return ahost
.replace(/^([^-.]+)-([^-.]+)-([^-.]+)\./gm, '$1-$2--$3.')
.replace(/^([^-.]+)-([^-.]+)\./gm, '$1--$2.');
};
const newHost = makeHostHelixCompliant(hostname);
return {
hash,
host: host.replace(hostname, newHost),
hostname: newHost,
href: href.replace(hostname, newHost),
origin: origin.replace(hostname, newHost),
pathname,
port,
protocol,
search,
};
}
/**
* Makes the given element accessible by setting a title attribute
* based on its :before CSS style or text content, and enabling
* keyboard access.
* @private
* @param {HTMLElement} elem The element
* @returns {HTMLElement} The element
*/
function makeAccessible(elem) {
if (elem.tagName === 'A' || elem.tagName === 'BUTTON') {
const ensureTitle = (tag) => {
if (!tag.title) {
// wait for computed style to be available
setTimeout(() => {
let title = window.getComputedStyle(tag, ':before').getPropertyValue('content');
title = title !== 'normal' && title !== 'none'
? title.substring(1, title.length - 1)
: '';
if (!title) {
title = tag.textContent;
}
tag.setAttribute('title', title);
}, 200);
}
};
ensureTitle(elem);
elem.setAttribute('tabindex', '0');
}
return elem;
}
/**
* Extends a tag.
* @private
* @param {HTMLElement} tag The tag to extend
* @param {elemConfig} config The tag configuration object
* @returns {HTMLElement} The extended tag
*/
function extendTag(tag, config) {
if (typeof config.attrs === 'object') {
for (const [key, value] of Object.entries(config.attrs)) {
tag.setAttribute(key, value);
}
}
if (typeof config.lstnrs === 'object') {
for (const [name, fn] of Object.entries(config.lstnrs)) {
if (typeof fn === 'function') {
tag.addEventListener(name, fn);
}
}
}
if (typeof config.text === 'string') {
tag.textContent = config.text;
}
return tag;
}
/**
* Creates a tag.
* @private
* @param {elemConfig} config The tag configuration
* @returns {HTMLElement} The new tag
*/
function createTag(config) {
if (typeof config.tag !== 'string') {
return null;
}
const el = document.createElement(config.tag);
return extendTag(el, config);
}
/**
* Creates a tag with the given name, attributes and listeners,
* and appends it to the parent element.
* @private
* @param {HTMLElement} parent The parent element
* @param {elemConfig} config The tag configuration
* @param {HTMLElement} before The element to insert before (optional)
* @returns {HTMLElement} The new tag
*/
function appendTag(parent, config, before) {
return makeAccessible(before
? parent.insertBefore(createTag(config), before)
: parent.appendChild(createTag(config)));
}
/**
* Returns the share URL for the sidekick bookmarklet.
* @private
* @param {Object} config The sidekick configuration
* @param {string} from The URL of the referrer page
* @returns {string} The share URL
*/
function getShareUrl(config, from) {
const shareUrl = new URL('https://www.hlx.live/tools/sidekick/');
shareUrl.search = new URLSearchParams([
['project', config.project || ''],
['from', from || ''],
['giturl', `https://github.com/${config.owner}/${config.repo}/tree/${config.ref}`],
]).toString();
return shareUrl.toString();
}
/**
* Creates a share URL for this sidekick and either invokes the
* Web Share API or copies it to the clipboard.
* @private
* @param {Sidekick} sk The sidekick
*/
function shareSidekick(sk) {
const { config } = sk;
const shareUrl = getShareUrl(config);
if (navigator.share) {
navigator.share({
title: `Sidekick for ${config.project}`,
text: `Check out this helper bookmarklet for ${config.project}`,
url: shareUrl,
});
} else {
navigator.clipboard.writeText(shareUrl);
sk.notify('Sharing URL copied to clipboard');
}
}
/**
* Checks for sidekick updates and informs the user.
* @private
* @param {Sidekick} sk The sidekick
*/
function checkForUpdates(sk) {
const indicators = [
// legacy config
typeof window.hlxSidekickConfig === 'object' || sk.config.compatMode,
// legacy script host
!sk.config.scriptUrl || new URL(sk.config.scriptUrl).host === 'www.hlx.page',
// update flag
sk.updateRequired = false,
];
if (indicators.includes(true)) {
window.setTimeout(() => {
if (window.confirm('Apologies, but your Helix Sidekick Bookmarklet needs to be updated one more time …\n\nThis time we made sure we will never have to ask you again. Promised! :)')) {
sk.showModal('Please wait …', true);
window.location.href = getShareUrl(sk.config, sk.location.href);
}
}, 1000);
}
}
/**
* Fires an event with the given name.
* @private
* @param {Sidekick} sk The sidekick
* @param {string} name The name of the event
* @param {Object} data The data to pass to event listeners (defaults to {@link Sidekick})
*/
function fireEvent(sk, name, data) {
try {
sk.root.dispatchEvent(new CustomEvent(name, {
detail: {
data: data || sk,
},
}));
} catch (e) {
console.warn('failed to fire event', name, data);
}
}
/**
* Compares source and preview last modified dates.
* @private
* @param {Sidekick} sidekick The sidekick
*/
async function checkLastModified({ detail = {} }) {
const { data: status = {} } = detail;
const pLastMod = (status.preview && status.preview.lastModified) || null;
const sLastMod = (status.source && status.source.lastModified) || null;
console.log('preview up to date?', new Date(pLastMod) > new Date(sLastMod));
// TODO: do something with it
}
/**
* Determines whether to open a new tab or reuse the existing window.
* @private
* @param {Event} evt The event
* @returns <pre>true</pre> if a new tab should be opened, else <pre>false</pre>
*/
function newTab(evt) {
return evt.metaKey || evt.shiftKey || evt.which === 2;
}
/**
* Creates an Admin URL for an API and path.
* @private
* @param {Object} config The sidekick configuration
* @param {string} api The API endpoint to call
* @param {string} path The current path
* @returns {string} The admin URL
*/
function getAdminUrl({ owner, repo, ref }, api, path) {
return new URL([
'https://admin.hlx3.page/',
api,
`/${owner}`,
`/${repo}`,
`/${ref}`,
path,
].join(''));
}
/**
* Check for Helix 3 related issues.
* @private
* @param {Sidekick} sk The sidekick
*/
async function checkForHelix3(sk) {
// check if current inner cdn url is hlx3 url
if (sk.config.hlx3
&& sk.location.hostname.endsWith('.page')
&& !sk.location.hostname.endsWith('hlx3.page')) {
if (window.confirm('This Helix Sidekick Bookmarklet can only work on a Helix 3 site.\n\nPress OK to be taken to the Helix 3 version of this page now.')) {
sk.switchEnv('preview');
}
}
}
/**
* Adds the following environment plugins to the sidekick:
* Edit, Preview, Live and Production
* @private
* @param {Sidekick} sk The sidekick
*/
function addEnvPlugins(sk) {
// edit
sk.add({
id: 'edit',
condition: (sidekick) => sidekick.isEditor() || sidekick.isHelix(),
button: {
action: async (evt) => {
if (evt.target.classList.contains('pressed')) {
return;
}
sk.switchEnv('edit', newTab(evt));
},
isPressed: (sidekick) => sidekick.isEditor(),
},
});
// preview
sk.add({
id: 'preview',
condition: (sidekick) => sidekick.isEditor() || sidekick.isHelix(),
button: {
action: async (evt) => {
if (evt.target.classList.contains('pressed')) {
return;
}
sk.switchEnv('preview', newTab(evt));
},
isPressed: (sidekick) => sidekick.isInner(),
},
});
// live
sk.add({
id: 'live',
condition: (sidekick) => sidekick.config.outerHost
&& (sidekick.isEditor() || sidekick.isHelix()),
button: {
action: async (evt) => {
if (evt.target.classList.contains('pressed')) {
return;
}
sk.switchEnv('live', newTab(evt));
},
isPressed: (sidekick) => sidekick.isOuter(),
},
});
// production
sk.add({
id: 'prod',
condition: (sidekick) => sidekick.config.host
&& sidekick.config.host !== sidekick.config.outerHost
&& (sidekick.isEditor() || sidekick.isHelix()),
button: {
action: async (evt) => {
if (evt.target.classList.contains('pressed')) {
return;
}
sk.switchEnv('prod', newTab(evt));
},
isPressed: (sidekick) => sidekick.isProd(),
},
});
}
/**
* Adds the reload plugin to the sidekick.
* @private
* @param {Sidekick} sk The sidekick
*/
function addReloadPlugin(sk) {
sk.add({
id: 'reload',
condition: (s) => s.config.innerHost && (s.isInner() || s.isDev()),
button: {
action: async (evt) => {
const { location } = sk;
sk.showModal('Please wait …', true);
try {
const resp = await sk.update(location.pathname);
if (!resp.ok && resp.status >= 400) {
console.error(resp);
throw new Error(resp);
}
console.log(`reloading ${location.href}`);
if (newTab(evt)) {
window.open(window.location.href);
sk.hideModal();
} else {
window.location.reload();
}
} catch (e) {
sk.showModal(
`Failed to reload ${location.pathname}. Please try again later.`,
true,
0,
);
}
},
},
});
}
/**
* Adds the publish plugin to the sidekick.
* @private
* @param {Sidekick} sk The sidekick
*/
function addPublishPlugin(sk) {
sk.add({
id: 'publish',
condition: (sidekick) => sidekick.isHelix() && sidekick.config.host
&& !(sidekick.config.byocdn && sidekick.location.host === sidekick.config.host),
button: {
action: async (evt) => {
const { config, location } = sk;
const path = location.pathname;
sk.showModal(`Publishing ${path}`, true);
let urls = [path];
// purge dependencies
if (Array.isArray(window.hlx.dependencies)) {
urls = urls.concat(window.hlx.dependencies);
}
const results = await Promise.all(urls.map((url) => sk.publish(url)));
if (results.every((res) => res && res.ok)) {
sk.showModal('Please wait …', true);
// fetch and redirect to production
const prodURL = `https://${config.byocdn ? config.outerHost : config.host}${path}`;
await fetch(prodURL, { cache: 'reload', mode: 'no-cors' });
console.log(`redirecting to ${prodURL}`);
if (newTab(evt)) {
window.open(prodURL);
sk.hideModal();
} else {
window.location.href = prodURL;
}
} else {
console.error(results);
sk.showModal('Failed to publish page. Please try again later.', true, 0);
}
},
},
});
}
/**
* The sidekick provides helper tools for authors.
*/
class Sidekick {
/**
* Creates a new sidekick.
* @param {sidekickConfig} cfg The sidekick config
*/
constructor(cfg) {
this.root = appendTag(document.body, {
tag: 'div',
attrs: {
class: 'hlx-sk hlx-sk-hidden hlx-sk-empty',
},
lstnrs: {
statusfetched: checkLastModified,
},
});
this.status = {};
this.loadContext(cfg);
this.fetchStatus();
this.loadCSS();
// share button
const share = appendTag(this.root, {
tag: 'button',
text: '<',
attrs: {
class: 'share',
},
lstnrs: {
click: () => shareSidekick(this),
},
});
appendTag(share, {
tag: 'span',
attrs: {
class: 'dots',
},
});
// close button
appendTag(this.root, {
tag: 'button',
text: '✕',
attrs: {
class: 'close',
},
lstnrs: {
click: () => this.hide(),
},
});
// default plugins
addEnvPlugins(this);
addReloadPlugin(this);
addPublishPlugin(this);
// custom plugins
if (this.config.plugins && Array.isArray(this.config.plugins)) {
this.config.plugins.forEach((plugin) => this.add(plugin));
}
if (this.config.compatMode
&& (this.isHelix() || this.isEditor())
&& (this.config.devMode || this.config.innerHost)) {
// load custom plugins in compatibility mode
let prefix = (this.isEditor() ? `https://${this.config.innerHost}` : '');
if (this.config.devMode || this.config.pluginHost) {
// TODO: remove support for pluginHost
if (this.config.pluginHost) {
console.warn('pluginHost is deprecated, use devMode instead');
}
prefix = this.config.pluginHost || DEV_URL.origin;
}
appendTag(document.head, {
tag: 'script',
attrs: {
src: `${prefix}/tools/sidekick/plugins.js`,
},
});
}
checkForHelix3(this);
checkForUpdates(this);
}
/**
* Fetches the status for the current resource.
* @fires Sidekick#statusfetched
* @returns {Sidekick} The sidekick
*/
async fetchStatus() {
const { owner, repo, ref } = this.config;
if (!owner || !repo || !ref) {
return this;
}
if (!this.status.apiUrl) {
const { href, pathname } = this.location;
const apiUrl = getAdminUrl(this.config, 'preview', this.isEditor() ? '/' : pathname);
if (this.isEditor()) {
apiUrl.search = new URLSearchParams([
['editUrl', href],
]).toString();
}
this.status.apiUrl = apiUrl.toString();
}
fetch(this.status.apiUrl, { cache: 'no-store' })
.then((resp) => resp.json())
.then((json) => Object.assign(this.status, json))
.then((json) => fireEvent(this, 'statusfetched', json))
.catch((e) => console.error('failed to fetch status', e));
return this;
}
/**
* Loads the sidekick configuration and retrieves the location of the current document.
* @param {sidekickConfig} cfg The sidekick config
* @fires Sidekick#contextloaded
* @returns {Sidekick} The sidekick
*/
loadContext(cfg) {
this.config = initConfig(cfg);
this.location = getLocation();
fireEvent(this, 'contextloaded', {
config: this.config,
location: this.location,
});
return this;
}
/**
* Shows the sidekick.
* @fires Sidekick#shown
* @returns {Sidekick} The sidekick
*/
show() {
if (this.root.classList.contains('hlx-sk-hidden')) {
this.root.classList.remove('hlx-sk-hidden');
}
fireEvent(this, 'shown');
return this;
}
/**
* Hides the sidekick.
* @fires Sidekick#hidden
* @returns {Sidekick} The sidekick
*/
hide() {
if (!this.root.classList.contains('hlx-sk-hidden')) {
this.root.classList.add('hlx-sk-hidden');
}
this.hideModal();
fireEvent(this, 'hidden');
return this;
}
/**
* Shows/hides the sidekick.
* @returns {Sidekick} The sidekick
*/
toggle() {
if (this.root.classList.contains('hlx-sk-hidden')) {
this.show();
} else {
this.hide();
}
return this;
}
/**
* Adds a plugin to the sidekick.
* @param {plugin} plugin The plugin configuration.
* @returns {HTMLElement} The plugin
*/
add(plugin) {
if (typeof plugin === 'object') {
plugin.enabled = typeof plugin.condition === 'undefined'
|| (typeof plugin.condition === 'function' && plugin.condition(this));
// find existing plugin
let $plugin = this.get(plugin.id);
let $pluginContainer = this.root;
if (ENVS[plugin.id]) {
// find or create environment plugin container
$pluginContainer = this.root.querySelector(':scope .env');
if (!$pluginContainer) {
$pluginContainer = appendTag(this.root, {
tag: 'div',
attrs: {
class: 'env',
},
});
}
}
const pluginCfg = {
tag: 'div',
attrs: {
class: plugin.id,
},
};
if (!$plugin && plugin.enabled) {
// add new plugin
$plugin = appendTag($pluginContainer, pluginCfg);
// remove empty text
if (this.root.classList.contains('hlx-sk-empty')) {
this.root.classList.remove('hlx-sk-empty');
}
} else if ($plugin) {
if (!plugin.enabled) {
// remove existing plugin
$plugin.remove();
} else if (plugin.override) {
// replace existing plugin
const $existingPlugin = $plugin;
$plugin = appendTag($existingPlugin.parentElement, pluginCfg, $existingPlugin);
$existingPlugin.remove();
}
}
if (!plugin.enabled) {
return null;
}
// add elements
if (Array.isArray(plugin.elements)) {
plugin.elements.forEach((elem) => appendTag($plugin, elem));
}
// add or update button
if (plugin.button) {
const buttonCfg = {
tag: 'button',
text: plugin.button.text,
lstnrs: {
click: (e) => plugin.button.action(e, this),
auxclick: (e) => plugin.button.action(e, this),
},
};
let $button = $plugin ? $plugin.querySelector(':scope button') : null;
if ($button) {
// extend existing button
extendTag($button, buttonCfg);
} else {
// add button
$button = appendTag($plugin, buttonCfg);
}
// check if button is pressed
if ((typeof plugin.button.isPressed === 'boolean' && !!plugin.button.isPressed)
|| (typeof plugin.button.isPressed === 'function' && plugin.button.isPressed(this))) {
$button.classList.add('pressed');
}
// fire event when plugin button is clicked
$button.addEventListener('click', () => fireEvent(this, 'pluginused', {
id: plugin.id,
button: $button,
}));
}
if (typeof plugin.callback === 'function') {
plugin.callback(this, $plugin);
}
return $plugin;
}
return null;
}
/**
* Returns the sidekick plugin with the specified ID.
* @param {string} id The plugin ID
* @returns {HTMLElement} The plugin
*/
get(id) {
return this.root.querySelector(`:scope .${id}`);
}
/**
* Removes the plugin with the specified ID from the sidekick.
* @param {string} id The plugin ID
* @returns {Sidekick} The sidekick
*/
remove(id) {
const $plugin = this.get(id);
if ($plugin) {
$plugin.remove();
}
return this;
}
/**
* Checks if the current location is an editor URL (SharePoint or Google Docs).
* @returns {boolean} <code>true</code> if editor URL, else <code>false</code>
*/
isEditor() {
return isEditor(this.location);
}
/**
* Checks if the current location is a development URL.
* @returns {boolean} <code>true</code> if development URL, else <code>false</code>
*/
isDev() {
const { location } = this;
return [
'', // for unit testing
DEV_URL.host, // for development and browser testing
].includes(location.host);
}
/**
* Checks if the current location is an inner CDN URL.
* @returns {boolean} <code>true</code> if inner CDN URL, else <code>false</code>
*/
isInner() {
const { config, location } = this;
return matchHelixHost(config.innerHost, location.host);
}
/**
* Checks if the current location is an outer CDN URL.
* @returns {boolean} <code>true</code> if outer CDN URL, else <code>false</code>
*/
isOuter() {
const { config, location } = this;
return matchHelixHost(config.outerHost, location.host);
}
/**
* Checks if the current location is a production URL.
* @returns {boolean} <code>true</code> if production URL, else <code>false</code>