-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcommon.js
More file actions
1420 lines (1230 loc) · 41.5 KB
/
common.js
File metadata and controls
1420 lines (1230 loc) · 41.5 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
/* Common utilities and initialization for the integration of the website with the apps script iframes.
*
* - Handles Google Tag Manager (GTM) loading and configuration.
* - Provides error handling for the base iframe.
* - Initializes the page, including analytics, iframe loading, and event listeners.
* - Processes messages from the embedded iframe, including URL parameter changes, analytics events, and logs.
* - Manages URL parameters and validates organization signatures.
* - Utility functions for loading states, cryptographic verification.
* To be able to use reporting based on the "item_id", create a "item_id" event-scoped custom dimension in your GTM account: https://support.google.com/analytics/answer/14239696
* - GAS frame loading: when loading explicitly or on-demand, errors are reported by rejecting the promise with an Error object that has property isIframeLoadTimeout = true.
*/
export default toast;
export const g_isProduction = ("true" === import.meta.env.VITE_IS_PRODUCTION);
export const g_langDefault = import.meta.env.VITE_LANG_DEFAULT;
export const g_strErrorOffline = "offline_mode"; //error string for offline mode requests (throws Error with this string)
const g_orgDefault = import.meta.env.VITE_ORG_DEFAULT;
const g_endpointPutLogs = import.meta.env.VITE_ENDPOINT_PUT_LOGS;
const g_firebaseProjname = import.meta.env.VITE_FIREBASE_PROJNAME;
const g_rootDomain = import.meta.env.VITE_ROOT_DOMAIN;
const g_idGTM = import.meta.env.VITE_GTM_ID; //Google Tag Manager ID
let g_lang = "";
const g_propLSLogs = "logs_captured"; //to retry failed logs from previous session
let g_logAuthEvents = false; //use url param "logauth=1" to enable
/**
* Public key for verifying signatures.
*/
//CUSTOMIZE: replace with your own public key generated from util-org-sig/readme.md
const g_publicKeyJwk = {
"kty": "EC",
"crv": "P-256",
"x": import.meta.env.VITE_PUBLIC_KEY_X,
"y": import.meta.env.VITE_PUBLIC_KEY_Y,
"ext": true
};
let g_mapsLang = {
"en": {},
"es": {}
};
let g_mapsExtra = [];
export function addTranslationMap(map) {
g_mapsExtra.push(map);
}
/**
* Parameters allowed in the URL. Others are ignored.
* Initialized during initializePage.
*/
let g_paramsClean = {
org: g_orgDefault,
sig: "",
lang: "en",
offline: "",
//CUSTOMIZE: add or modify parameters as needed
}
const g_commonStr = {
"en": {
offlineModeActive: "Offline mode",
askRetryLoad: 'There was an error loading the content. Do you want to retry?',
msgNoUser: 'Not signed in',
msgSignIn: 'Sign In',
msgSignOut: 'Sign Out',
msgErrorGeneric: 'Error',
msgPleaseRetry: 'Please retry or refresh the page.',
strAlertTitle: "ℹ️ Notice",
strYes: "Yes",
strNo: "No",
strOK: "OK",
strCancel: "Cancel",
},
"es": {
offlineModeActive: "Modo sin conexión",
askRetryLoad: 'Hubo un error al cargar el contenido. ¿Deseas reintentar?',
msgNoUser: 'No has iniciado sesión',
msgSignIn: 'Iniciar sesión',
msgSignOut: 'Cerrar sesión',
msgErrorGeneric: 'Error',
msgPleaseRetry: 'Por favor, reintenta o recarga la página.',
strAlertTitle: "ℹ️ Aviso",
strYes: "Sí",
strNo: "No",
strOK: "OK",
strCancel: "Cancelar",
}
};
addTranslationMap(g_commonStr);
export function tCommon(key, langParam) {
if (!langParam)
langParam = getLang();
if (!langParam) {
console.error("no lang in t"); //detect bad initialization
langParam = g_langDefault; //recover
}
let res = g_commonStr[langParam][key];
if (typeof res === "undefined") {
//loop through extra maps (g_mapsExtra, each is a translation with en and es) until one is found with the key
for (let i = 0; i < g_mapsExtra.length; i++) {
const mapExtra = g_mapsExtra[i];
if (g_commonStr === mapExtra)
continue; //already checked
res = mapExtra[langParam][key];
if (res !== undefined)
break;
}
if (typeof res === "undefined") {
console.error("missing common translation for", key, "in", langParam);
return "";
}
}
return res;
}
//CUSTOMIZE: replace with your own. properties are appended to each log sent to the server.
//Return null (or an empty object) if you don't want to include any.
function paramsForLogging() {
return {
};
}
export function handleloadEvent(loadEvent, data) {
let styleLoading = null;
let styleError = null;
switch (loadEvent) {
case loadEvents.LOADING:
styleError = "none";
styleLoading = "";
break;
case loadEvents.ERRORLOADING:
styleLoading = "none";
styleError = "";
break;
case loadEvents.LOADED:
styleError = "none";
if (!data || !data.dontStopProgress) {
styleLoading = "none";
}
break;
case loadEvents.FULLYLOADED:
styleLoading = "none";
styleError = "none";
break;
}
const loadingPage = document.getElementById("loadingPage");
const loadingPageError = document.getElementById("loadingPageError");
if (styleLoading !== null && loadingPage) {
loadingPage.style.display = styleLoading;
}
if (styleError !== null && loadingPageError) {
loadingPageError.style.display = styleError;
}
}
/**
* Dimensions for Google Tag Manager (GTM)
* Use for tracking custom dimensions in GTM, for example the language of the page for the current session.
* You need to first set up your custom dimensions "item_id" in your GTM account, then configure them here.
* see: https://support.google.com/analytics/answer/14239696
*/
//g_dimensionsGTM: custom dimensions for GTM. can be empty.
const g_dimensionsGTM = {
// "dimension1": null,
// "dimension2": null,
//CUSTOMIZE: replace with your own
};
/*
* Initializes custom dimensions for GTM (g_dimensionsGTM)
* called only once, during initializePage
* This function can be modified to set custom dimensions based on URL parameters or other criteria.
*/
function initializeCustomDimensions(params) {
// Example of how to set custom dimensions based on URL parameters
//g_dimensionsGTM["dimension1"] = params.dim1;
//g_dimensionsGTM["dimension2"] = params.dim2;
//CUSTOMIZE: replace with your own
// see: https://support.google.com/analytics/answer/14239696
}
/** localStorage usage
*
* localStorage["gtag_disabled"] = "1" will disable GTM loading. Useful to mark all developer/tester machines as excluded from GTM.
*/
/**
* Set to true when you need GTM to load on localhost or to bypass 'gtag_disabled'
* false is default in production. true is used for development purposes.
* NOTE: localStorage["gtag_disabled"] = "1" will disable GTM loading (unless this is set to true).
*/
const g_forceGTM = false;
let gtag = null;
let g_sourceIframe = null;
export function isOnline() {
return (g_paramsClean.offline !== "1" && navigator.onLine === true);
}
export async function serverRequest(prop, ...args) {
const strArgs = JSON.stringify(args);
if (!isOnline())
return Promise.reject(new Error(g_strErrorOffline));
await loadIframeFromCurrentUrl();
//TODO: if the frame loads ok but the .gs function never responds, we should have a timeout here to reject the promise.
return new Promise(resolve => {
const idRequest = g_callbackRunner.setCallback(function (response) {
resolve(response); //Note the response can be a success or error return from the .gs server function
});
//note we post with no domain filtering ("*") because the GAS domain varies, but we validate g_sourceIframe when its set
g_sourceIframe.postMessage({ type: "FROM_PARENT", action: "serverRequest", data: { functionName: prop, arguments: strArgs }, idRequest: idRequest }, "*");
});
}
/**
* Loads the Google Tag Manager (GTM) script
* Skips loading on localhost or when 'gtag_disabled' is set in local storage, unless g_forceGTM is true.
* Appends the GTM script to the document head.
*/
export function loadGTM() {
beforeLoadGTM();
const host = window.location.hostname;
if (!host.includes(".") || /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || localStorage.getItem("gtag_disabled") == "1") {
if (!g_forceGTM)
return; //ignore local or disabled
}
var script = document.createElement("script");
script.async = true;
script.src = "https://www.googletagmanager.com/gtag/js?id=" + g_idGTM;
document.head.appendChild(script);
}
export function isLocalhost() {
return window.location.hostname === "localhost";
}
const g_callbackRunner = createCallbackRunner();
const g_moduleLog = "frontend";
const g_maxLogsSend = 10;
let g_isSendingLogs = false;
let g_pendingLogs = [];
let g_warnedFailedLogSend = false;
function flushPendingLogs() {
if (g_isSendingLogs || g_pendingLogs.length === 0 || !isOnline())
return;
if (isLocalhost()) {
g_pendingLogs = [];
return;
}
g_isSendingLogs = true;
const payload = g_pendingLogs.splice(0, g_maxLogsSend); //pop
localStorage.setItem(g_propLSLogs, JSON.stringify(payload));
const finalize = (success) => {
g_isSendingLogs = false;
if (success) {
localStorage.removeItem(g_propLSLogs);
if (g_pendingLogs.length > 0)
flushPendingLogs();
return;
}
};
fetch(g_endpointPutLogs, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ logs: payload })
})
.then(res => {
if (!res.ok) {
if (!g_warnedFailedLogSend) {
g_warnedFailedLogSend = true; //prevent eternal logging loops
console.error("Error sending logs, status:", res.status);
}
throw new Error(`HTTP ${res.status}`);
}
return res;
})
.then(() => finalize(true))
.catch(e => {
if (!g_warnedFailedLogSend) {
g_warnedFailedLogSend = true;
console.error("Error sending logs", e);
}
finalize(false);
});
}
export function setTitle(title) {
document.title = title + " | Tutor for Me";
}
export function openUrlWithProps(dataEvent) {
const url = getUrlWithProps(dataEvent);
window.open(url, dataEvent.replacePage ? "_self" : "_blank");
}
export function getUrlWithProps(dataEvent) {
if (!dataEvent)
return;
const url = new URL(window.location.href);
if (dataEvent.pathname)
url.pathname = dataEvent.pathname;
if (dataEvent.props) {
Object.entries(dataEvent.props).forEach(([key, value]) => {
//if value is empty, remove the parameter
if (value === null || value === undefined || value === "")
url.searchParams.delete(key);
else
url.searchParams.set(key, value);
});
}
return url;
}
let g_callbackLoadEvents = null;
function setNoytifyloadEventCallback(callback) {
if (g_callbackLoadEvents)
console.warn("Overwriting existing callbackLoadEvents"); //unusual
g_callbackLoadEvents = callback;
}
function notifyloadEvent(eventType, data = null) {
if (loadEvents.ERRORLOADING === eventType && isOnline())
console.error("Error loading");
if (g_callbackLoadEvents)
g_callbackLoadEvents(eventType, data);
}
/**
* events that the iframe can send:
* - analyticsEvent
* - siteInited
* - siteFullyLoaded
* - logs
* - titleChange
* - urlParamChange
* - toggleFullscreen
* - serverResponse
* - openUrlWithProps
*/
export function processAction(data, event, callbackMessage) {
if (data.action == "siteInited") {
if (!g_sourceIframe && event)
g_sourceIframe = event.source;
function processSiteInited() {
document.documentElement.classList.remove("scrollY");
g_loadedFrame = true;
g_loadingFrame = false;
event.source.postMessage({ type: 'validateDomain' }, event.origin);
document.querySelector("iframe").style.opacity = "1";
notifyloadEvent(loadEvents.LOADED, data?.data);
}
const waitForSignal = () => {
// g_signalLoadFrame can be null if the iframe is loaded on-demand, and the page init hasnt yet been configured,
// for example when there is a sign-in flow before the page is initialized, but the browser restores the iframe from bfcache on load
if (g_signalLoadFrame) {
g_signalLoadFrame.resolve();
processSiteInited();
return;
}
//should not happen in TFM init flows because all iframes are loaded during page init, not on-demand.
console.warn("Waiting for g_signalLoadFrame...");
setTimeout(waitForSignal, 1000);
};
waitForSignal();
}
else if (data.action == "serverResponse") {
g_callbackRunner.runCallback(data.idRequest, data.data);
}
else if (data.action == "openUrlWithProps") {
const dataEvent = data.data;
if (!dataEvent)
return;
openUrlWithProps(dataEvent);
}
else if (data.action == "siteFullyLoaded") {
notifyloadEvent(loadEvents.FULLYLOADED);
}
else if (data.action == "titleChange") {
setTitle(data.data.title);
}
else if (data.action == "logs") {
const logs = data.data.logs;
if (!logs || !Array.isArray(logs) || logs.length == 0) {
console.error("Invalid logs");
return;
}
g_pendingLogs = g_pendingLogs.concat(logs); //.push( into logs
flushPendingLogs();
}
else if (data.action == "toggleFullscreen") {
toggleFullscreen();
}
else if (data.action == "analyticsEvent") {
if (gtag) {
gtag("event", "select_content", {
content_type: "button",
item_id: data.data.name
});
}
}
else if (data.action == "urlParamChange") {
const dataEvent = data.data;
if (dataEvent && typeof dataEvent === 'object' && dataEvent.urlParams) {
const urlParams = dataEvent.urlParams;
const url = new URL(window.location.href);
Object.entries(urlParams).forEach(([key, value]) => {
if (value == null) {
url.searchParams.delete(key);
g_paramsClean[key] = null;
} else {
url.searchParams.set(key, value);
g_paramsClean[key] = value;
}
});
if (dataEvent.refresh)
window.location.replace(url);
else
window.history.replaceState({}, document.title, url);
}
}
if (callbackMessage)
callbackMessage(data, event); //propagate
}
export const loadEvents = {
LOADING: "loading",
LOADED: "loaded",
FULLYLOADED: "fullyloaded",
ERRORLOADING: "error"
};
let g_iframeParamsExtra = "";
let g_initPageCalled = false;
/**
* Initializes the main page logic for the Apps Script iframe integration.
* @param {Object} options - Options for initialization
* @param {boolean} options.loadIframe - Whether to load the iframe right away. false will loadit later on-demand.
* @param {boolean} options.loadAnalytics - Whether to load analytics (can be loaded later as well)
* @param {Object} options.paramsExtra - Extra parameters to pass to the iframe URL
* @param {Function} options.callbackMessage - Callback for message events received from the iframe
* @param {Function} options.callbackContentLoaded - Callback for the content loaded event
* @param {(event: string, data?: any) => void} options.callbackLoadEvents - Callback for iframe loading events; receives (event, data) where event is one of loadEvents and data is optional (sent by the appscript)
* @param {boolean} options.captureLogs - Whether to capture logs for debugging (captures calls to console.*)
*
*/
export async function initializePage({
loadIframe,
loadAnalytics,
captureLogs,
paramsExtra,
callbackMessage,
callbackContentLoaded,
callbackLoadEvents,
} = {}) {
console.assert(!g_initPageCalled, "initializePage called multiple times");
if (g_initPageCalled)
return;
g_initPageCalled = true;
setNoytifyloadEventCallback(callbackLoadEvents);
g_iframeParamsExtra = paramsExtra || "";
if (captureLogs) {
enableLogCapture(payload => {
const paramsAppend = paramsForLogging();
if (paramsAppend)
Object.assign(payload, paramsAppend);
}, [
//CUSTOMIZE: add your own function names to ignore in the stack trace
]);
}
let initedBase = await initializeBase();
window.addEventListener("message", (event) => {
// validate the origin of the message
const allowedHostnames = [
g_firebaseProjname + ".firebaseapp.com",
g_rootDomain,
"localhost",
];
let originHostname;
try {
// This can throw if event.origin is "null" (e.g., from a sandboxed iframe)
originHostname = new URL(event.origin).hostname;
} catch (e) {
console.warn("Message from an invalid or opaque origin:", event.origin);
return;
}
const isAllowed = originHostname.endsWith(".googleusercontent.com") ||
allowedHostnames.includes(originHostname);
if (!isAllowed) {
console.warn("Message from untrusted origin:", event.origin);
return;
}
if (!event.data || event.data.type !== "FROM_IFRAME")
return;
// Walk up via .parent to see if it reaches this window
{
let w = event.source;
let ok = false;
for (let i = 0; i < 5 && w; i++) {
if (w === window) {
ok = true;
break;
}
if (w === w.parent)
break; // reached that tree's top
w = w.parent;
}
if (!ok) {
console.warn("Message from unknown origin:", event.origin);
return;
}
}
const data = event.data;
processAction(data, event, callbackMessage);
});
function onContentLoadedBase() {
if (!initedBase) {
notifyloadEvent(loadEvents.ERRORLOADING);
return;
}
if (loadAnalytics)
loadGTM();
if (callbackContentLoaded)
callbackContentLoaded();
if (loadIframe)
loadIframeFromCurrentUrl(paramsExtra).catch(err => {
if (isOnline())
console.error("Error loading iframe:", err); //errors are handled in notifyloadEvent
});
}
if (document.readyState !== "loading") {
onContentLoadedBase();
} else {
document.addEventListener("DOMContentLoaded", () => {
onContentLoadedBase();
});
}
}
export function getLang() {
if (g_lang)
return g_lang;
const params = new URLSearchParams(window.location.search);
const urlLang = params.get("lang");
if (urlLang === "en" || urlLang === "es")
return urlLang;
const stored = localStorage.getItem("lang");
if (stored)
return stored;
return navigator.language.startsWith("es") ? "es" : "en";
}
export function setLang(lang, mapTranslations) {
if (!lang)
lang = g_langDefault;
if (lang !== "en" && lang !== "es") {
console.error("invalid language in setLang: " + lang);
throw new Error("invalid language");
}
g_lang = lang;
if (mapTranslations) {
g_mapsLang = mapTranslations;
if (!haveSamePropertyNames(g_mapsLang.en, g_mapsLang.es))
console.error("EN and ES differ");
}
const elemLang = document.getElementById("language");
if (elemLang)
elemLang.value = lang;
localStorage.setItem("lang", lang);
g_paramsClean.lang = lang;
const url = new URL(window.location.href);
const langPrevURL = url.searchParams.get("lang");
if (langPrevURL && langPrevURL !== lang) {
url.searchParams.set("lang", lang);
window.history.replaceState({}, "", url.toString());
}
applyTranslations(document, g_mapsLang, lang);
}
/* supports a prop in translations, with fallback to tCommon
**/
export function t(prop, lang = null, translations = null) {
if (!translations)
translations = g_mapsLang;
if (!lang)
lang = g_lang;
if (!lang)
lang = getLang();
if (!lang) {
console.error("no lang in t");
lang = g_langDefault; //recover
}
let res = null;
if (lang == "es")
res = translations.es[prop];
else
res = translations.en[prop];
if (typeof res === "undefined") {
res = tCommon(prop, lang); //tCommon logs missing translations
}
return res;
}
let g_firstTranslationDone = false;
export function applyTranslations(root, translations, lang) {
if (!root)
root = document;
if (!translations)
translations = g_mapsLang;
if (!lang)
lang = g_lang;
let isLanding = false;
//set isLanding if the current url is the landing page (no pathname)
if (window.location.pathname === "/" || window.location.pathname === "/index.html") {
isLanding = true;
}
function detectMismatchedSEO(value, el, key) {
if (!g_firstTranslationDone && lang == "en" && el.innerHTML !== value) {
if (isLanding || el.innerHTML.trim() !== "") //avoid logging empty elements in non-landing pages
console.warn("unmatched translation for", key);
return true;
}
return false;
}
function updateElement(mapped, el, key) {
if (key.startsWith("placeholder.")) {
el.placeholder = mapped;
} else {
detectMismatchedSEO(mapped, el, key);
el.innerHTML = mapped;
}
}
root.querySelectorAll("[data-i18n]").forEach(el => {
const key = el.getAttribute("data-i18n");
let mapped = t(key, lang, translations);
if (typeof mapped === "string") {
updateElement(mapped, el, key);
return;
}
console.warn("Missing translation for", key, "in", lang);
if (lang !== "en") {
const mapped2 = t(key, "en", translations);
if (mapped2) {
updateElement(mapped2, el, key);
return;
}
}
});
g_firstTranslationDone = true;
}
/** crypto helper */
function base64UrlToArrayBuffer(base64url) {
let base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); //Base64url to standard Base64.
// Add padding if needed.
while (base64.length % 4)
base64 += "=";
const binary = window.atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
async function verifyScript(org, signatureBase64Url) {
let isValid = false;
try {
if (org && !signatureBase64Url)
return false;
const alg = "ECDSA";
const publicKey = await window.crypto.subtle.importKey(
"jwk",
g_publicKeyJwk,
{
name: alg,
namedCurve: g_publicKeyJwk.crv
},
true,
["verify"]
);
const signatureBuffer = base64UrlToArrayBuffer(signatureBase64Url);
const encoder = new TextEncoder();
const messageBuffer = encoder.encode(org);
isValid = await window.crypto.subtle.verify(
{
name: alg,
hash: { name: "SHA-256" }
},
publicKey,
signatureBuffer,
messageBuffer
);
}
catch (error) {
console.error("Error verifying script", error);
isValid = false;
}
return isValid;
}
let g_initBaseCalled = false;
async function initializeBase() {
console.assert(!g_initBaseCalled, "initializeBase called multiple times");
g_initBaseCalled = true;
const params = new URLSearchParams(window.location.search);
if (params.has("logauth")) {
g_logAuthEvents = (params.get("logauth") === "1");
}
Object.keys(g_paramsClean).forEach(key => {
if (params.has(key))
g_paramsClean[key] = params.get(key);
});
if (g_paramsClean.lang !== "en" && g_paramsClean.lang !== "es") {
console.error("Unsupported lang: " + g_paramsClean.lang);
return false;
}
if (params.has("org")) {
const isValid = await verifyScript(g_paramsClean.org, g_paramsClean.sig);
if (!isValid)
return false;
}
initializeCustomDimensions(g_paramsClean);
beforeLoadGTM();
return true;
}
let g_loadedFrame = false;
let g_loadingFrame = false;
let g_signalLoadFrame = null;
/**
* Loads the iframe from the current URL with the given extra parameters.
* if paramsExtra is not provided, uses the one set during initializePage.
* @param {string} paramsExtra - Extra parameters to append to the iframe URL.
* errors (reject or exception) due to the frame failing to load are marked with property isIframeLoadTimeout = true
* this is so you can offer the user to retry loading the iframe.
*/
export async function loadIframeFromCurrentUrl(paramsExtra = "", selector = "iframe") {
if (g_loadedFrame || g_loadingFrame)
return g_signalLoadFrame.promise;
if (!isOnline()) {
notifyloadEvent(loadEvents.ERRORLOADING);
toast(t("offlineModeActive"));
return Promise.reject(new Error(g_strErrorOffline));
}
g_loadingFrame = true;
if (!paramsExtra)
paramsExtra = g_iframeParamsExtra;
const iframeElem = document.querySelector(selector);
const setSrc = (iframeElem.src === ""); //race condition: even thou the html src is empty, the browser may restore it from bfcache with the src set.
if (!setSrc) {
console.warn("Iframe src already set, not reloading"); //remove this warning if you load the iframe on-demand and do stuff before initializePage
}
let startedRetry = false;
function executor(resolve, reject) {
if (!iframeElem) {
console.error("No iframe found");
reject(new Error("no iframe found"));
}
function setRetryMode() {
if (startedRetry)
return;
startedRetry = true;
g_loadingFrame = false;
notifyloadEvent(loadEvents.ERRORLOADING);
const errorLoad = new Error("Load timeout.");
errorLoad.isIframeLoadTimeout = true;
reject(errorLoad);
}
iframeElem.addEventListener("load", (event) => {
if (g_loadedFrame)
return;
setTimeout(() => {
if (g_loadedFrame)
return;
setRetryMode();
}, 5000);
});
setTimeout(() => {
if (g_loadedFrame || startedRetry)
return;
//in rare cases (ie frame load cancelled), the iframe load event is never called.
setRetryMode();
}, 12000);
notifyloadEvent(loadEvents.LOADING);
iframeElem.style.opacity = "0";
if (setSrc)
iframeElem.src = getScriptUrlWithParams(paramsExtra);
}
g_signalLoadFrame = makeSignal(executor);
return g_signalLoadFrame.promise;
}
export function makeSignal(executor) {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
//ensure async, so caller can assign the return value before the executor runs
queueMicrotask(() => {
if (executor) {
executor(res, rej);
}
});
});
return { promise, resolve, reject };
}
function getScriptUrlWithParams(paramsExtra) {
const strBuilder = paramsExtra ? "&" + paramsExtra : "";
const strDemo = (g_paramsClean.demo == "1") ? "&demo=1" : "";
const lang = getLang(); //g_paramsClean has the actual url param, but getLang adds a localStorage preference if url doesnt have it
let url = `https://script.google.com/macros/s/${g_paramsClean.org}/exec?lang=${lang}&session=${g_paramsClean.session}${strBuilder}${strDemo}&embed=1`;
return url;
}
let g_beforeGTMFinished = false;
function beforeLoadGTM() {
if (g_beforeGTMFinished)
return;
if (!window.dataLayer)
window.dataLayer = [];
gtag = function () {
window.dataLayer.push(arguments);
}
let dimensionsGTM = {};
Object.entries(g_dimensionsGTM).forEach(([name, value]) => {
if (typeof value !== "undefined" && value !== null && value !== "")
dimensionsGTM[name] = value;
});
gtag("js", new Date());
if (Object.keys(dimensionsGTM).length > 0)
gtag("config", g_idGTM, dimensionsGTM);
g_beforeGTMFinished = true;
}
// mini-toast.js — tiny, dependency-free toast (ESM). Import and call `toast(...)`.
// Usage:
// import toast from './mini-toast.js';
// toast('Saved', { type: 'success', position: 'center' });
const STYLE_ID = "mini-toast-style";
/** @type {Map<string, HTMLElement>} */
const containers = new Map();
/**
* @typedef {'tr'|'tl'|'br'|'bl'|'center'} ToastPosition
* @typedef {'success'|'warn'|'error'|''} ToastType
* @typedef {{
* duration?: number, // ms; 0 = sticky
* type?: ToastType,
* position?: ToastPosition,
* dismissible?: boolean, // click to close
* max?: number // stack cap per position
* }} ToastOptions
*/
/** Injects CSS once */
function injectCSS() {
if (typeof document === "undefined") return; // SSR no-op
if (document.getElementById(STYLE_ID)) return;
const s = document.createElement("style");
s.id = STYLE_ID;
s.textContent = `
._toaster{position:fixed;z-index:2147483647;display:flex;flex-direction:column;gap:8px;pointer-events:none}
._toaster.tr{top:12px;right:12px;align-items:flex-end}
._toaster.tl{top:12px;left:12px}
._toaster.br{bottom:12px;right:12px;align-items:flex-end}
._toaster.bl{bottom:12px;left:12px}
._toaster.center{top:50%;left:50%;transform:translate(-50%,-50%);align-items:center}
._toast{pointer-events:auto;max-width:min(420px,90vw);padding:10px 14px;border-radius:10px;
background:#222;color:#fff;box-shadow:0 8px 24px rgba(0,0,0,.18);
font:14px/1.35 system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
opacity:0;transform:translateY(-6px);transition:opacity .18s ease, transform .18s ease}
._toaster.center ._toast{transform:none} /* fade-only in center */
._toast.show{opacity:1;transform:translateY(0)}
._toast.hide{opacity:0;transform:translateY(-6px)}
._toast.success{background:#222}
._toast.warn{background:#ca8a04}
._toast.error{background:#dc2626}
`;
document.head.appendChild(s);
}
/** @param {ToastPosition} pos */
function getContainer(pos) {
if (containers.has(pos)) return containers.get(pos);
const el = document.createElement("div");
el.className = `_toaster ${pos}`;
document.body.appendChild(el);
containers.set(pos, el);
return el;
}
let g_textLastToast = null;
let g_msLastToast = 0;
/**
* Show a toast.
* @param {string|Node} text
* @param {ToastOptions} [opts]
* @returns {{close:()=>void, el:HTMLElement}}
*/
export function toast(text, opts = {}) {
if (typeof document === "undefined") {
const msgError = "mini-toast requires a browser environment";
console.error(msgError);
throw new Error(msgError);
}
const msNow = Date.now();
if (text == g_textLastToast && (msNow - g_msLastToast) < 1000) {
g_msLastToast = msNow;
return;
}
g_textLastToast = text;
g_msLastToast = msNow;
injectCSS();
const {