-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.ts
More file actions
543 lines (460 loc) · 13.6 KB
/
Copy pathapp.ts
File metadata and controls
543 lines (460 loc) · 13.6 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
import {
DonationAmount,
DonationFrequency,
EnForm,
ProcessingFees,
Country,
} from "./events";
import {
AmountLabel,
Loader,
ProgressBar,
UpsellLightbox,
ENGrid,
Options,
OptionsDefaults,
setRecurrFreq,
PageBackground,
MediaAttribution,
ApplePay,
A11y,
CapitalizeFields,
Ecard,
ClickToExpand,
Advocacy,
DataAttributes,
LiveVariables,
iFrame,
InputPlaceholders,
InputHasValueAndFocus,
ShowHideRadioCheckboxes,
AutoCountrySelect,
SkipToMainContentLink,
SrcDefer,
NeverBounce,
AutoYear,
Autocomplete,
RememberMe,
TranslateFields,
ShowIfAmount,
EngridLogger,
OtherAmount,
MinMaxAmount,
Ticker,
DataReplace,
DataHide,
AddNameToMessage,
ExpandRegionName,
AppVersion,
UrlToForm,
RequiredIfVisible,
TidyContact,
DataLayer,
LiveCurrency,
Autosubmit,
EventTickets,
SwapAmounts,
DebugPanel,
DebugHiddenFields,
FreshAddress,
BrandingHtml,
CountryDisable,
PremiumGift,
DigitalWallets,
MobileCTA,
LiveFrequency,
UniversalOptIn,
StripeFinancialConnections,
GiveBySelect,
UrlParamsToBodyAttrs,
ExitIntentLightbox,
SupporterHub,
FastFormFill,
SetAttr,
ShowIfPresent,
ENValidators,
CustomCurrency,
VGS,
PostalCodeValidator,
CountryRedirect,
WelcomeBack,
EcardToTarget,
UsOnlyForm,
ThankYouPageConditionalContent,
EmbeddedEcard,
CheckboxLabel,
UpsellCheckbox,
PostDonationEmbed,
FrequencyUpsell,
CustomPremium,
PreferredPaymentMethod,
} from ".";
export class App extends ENGrid {
// Events
private _form: EnForm = EnForm.getInstance();
private _fees: ProcessingFees = ProcessingFees.getInstance();
private _amount: DonationAmount = DonationAmount.getInstance(
"transaction.donationAmt",
"transaction.donationAmt.other"
);
private _frequency: DonationFrequency = DonationFrequency.getInstance();
private _country: Country = Country.getInstance();
private _dataLayer: DataLayer;
private options: Options;
private logger = new EngridLogger("App", "black", "white", "🍏");
constructor(options: Options) {
super();
const loader = new Loader();
this.options = { ...OptionsDefaults, ...options };
// Add Options to window
window.EngridOptions = this.options;
this._dataLayer = DataLayer.getInstance();
// If there's a ?pbedit query string, redirect to the page builder to edit on EN
if (
ENGrid.getUrlParameter("pbedit") === true ||
ENGrid.getUrlParameter("pbedit") === "true"
) {
window.location.href = `https://${ENGrid.getDataCenter()}.engagingnetworks.app/index.html#pages/${ENGrid.getPageID()}/edit`;
return;
}
if (loader.reload()) return;
// Turn Debug ON if you use local assets
if (
ENGrid.getBodyData("assets") === "local" &&
ENGrid.getUrlParameter("debug") !== "false" &&
ENGrid.getUrlParameter("debug") !== "log"
) {
window.EngridOptions.Debug = true;
}
// Document Load
if (document.readyState !== "loading") {
this.run();
} else {
document.addEventListener("DOMContentLoaded", () => {
this.run();
});
}
// Window Resize
window.onresize = () => {
this.onResize();
};
}
private run() {
if (
!ENGrid.checkNested(
window.EngagingNetworks,
"require",
"_defined",
"enjs"
)
) {
this.logger.danger("Engaging Networks JS Framework NOT FOUND");
setTimeout(() => {
this.run();
}, 100);
return;
}
// If there's an option object on the page, override the defaults
if (window.hasOwnProperty("EngridPageOptions")) {
this.options = { ...this.options, ...window.EngridPageOptions };
// Add Options to window
window.EngridOptions = this.options;
}
// If there's no pageJson.pageType, add a big red warning to the console
if (!ENGrid.checkNested(window, "pageJson", "pageType")) {
window.setTimeout(() => {
console.log(
"%c ⛔️ pageJson.pageType NOT FOUND - Go to the Account Settings and Expose the Transaction Details %s",
"background-color: red; color: white; font-size: 22px; font-weight: bold;",
"https://knowledge.engagingnetworks.net/datareports/expose-transaction-details-pagejson"
);
}, 2000);
}
if (this.options.Debug || App.getUrlParameter("debug") == "true")
// Enable debug if available is the first thing
App.setBodyData("debug", "");
new Advocacy();
new InputPlaceholders();
new InputHasValueAndFocus();
// Give By Select
new GiveBySelect();
new ShowHideRadioCheckboxes("transaction.giveBySelect", "giveBySelect-");
new ShowHideRadioCheckboxes("transaction.inmem", "inmem-");
new ShowHideRadioCheckboxes("transaction.recurrpay", "recurrpay-");
new ShowHideRadioCheckboxes("transaction.shipenabled", "shipenabled-");
// Automatically show/hide all radios
let radioFields: string[] = [];
const allRadios: NodeListOf<HTMLInputElement> =
document.querySelectorAll("input[type=radio]");
allRadios.forEach((radio) => {
if ("name" in radio && radioFields.includes(radio.name) === false) {
radioFields.push(radio.name);
}
});
radioFields.forEach((field) => {
new ShowHideRadioCheckboxes(
field,
"engrid__" + field.replace(/\./g, "") + "-"
);
});
// Automatically show/hide all checkboxes
const allCheckboxes: NodeListOf<HTMLInputElement> =
document.querySelectorAll("input[type=checkbox]");
allCheckboxes.forEach((checkbox) => {
if ("name" in checkbox) {
new ShowHideRadioCheckboxes(
checkbox.name,
"engrid__" + checkbox.name.replace(/\./g, "") + "-"
);
}
});
// Client onSubmit and onError functions
this._form.onSubmit.subscribe(() => this.onSubmit());
this._form.onError.subscribe(() => this.onError());
this._form.onValidate.subscribe(() => this.onValidate());
// Event Listener Examples
this._amount.onAmountChange.subscribe((s) =>
this.logger.success(`Live Amount: ${s}`)
);
this._frequency.onFrequencyChange.subscribe((s) => {
this.logger.success(`Live Frequency: ${s}`);
setTimeout(() => {
this._amount.load();
}, 150);
});
this._form.onSubmit.subscribe((s) =>
this.logger.success("Submit: " + JSON.stringify(s))
);
this._form.onError.subscribe((s) =>
this.logger.danger("Error: " + JSON.stringify(s))
);
this._country.onCountryChange.subscribe((s) =>
this.logger.success(`Country: ${s}`)
);
window.enOnSubmit = () => {
this._form.submit = true;
this._form.submitPromise = false;
this._form.dispatchSubmit();
ENGrid.watchForError(ENGrid.enableSubmit);
if (!this._form.submit) return false;
if (this._form.submitPromise) return this._form.submitPromise;
this.logger.success("enOnSubmit Success");
// If all validation passes, we'll watch for Digital Wallets Errors, which
// will not reload the page (thanks EN), so we will enable the submit button if
// an error is programmatically thrown by the Digital Wallets
return true;
};
window.enOnError = () => {
this._form.dispatchError();
};
window.enOnValidate = () => {
this._form.validate = true;
this._form.validatePromise = false;
this._form.dispatchValidate();
if (!this._form.validate) return false;
if (this._form.validatePromise) return this._form.validatePromise;
this.logger.success("Validation Passed");
return true;
};
new DataAttributes();
// Country Redirect
new CountryRedirect();
// iFrame Logic
new iFrame();
// Live Variables
new LiveVariables(this.options);
// Dynamically set Recurrency Frequency
new setRecurrFreq();
// Upsell Checkbox
new UpsellCheckbox();
// Upsell Lightbox
new UpsellLightbox();
// Amount Labels
new AmountLabel();
// Engrid Data Replacement
new DataReplace();
// ENgrid Hide Script
new DataHide();
// Autosubmit script
new Autosubmit();
// Adjust display of event tickets.
new EventTickets();
// Swap Amounts
new SwapAmounts();
// On the end of the script, after all subscribers defined, let's load the current frequency
// The amount will be loaded by the frequency change event
// This timeout is needed because when you have alternative amounts, EN is slower than Engrid
// about 20% of the time and we get a race condition if the client is also using the SwapAmounts feature
window.setTimeout(() => {
this._frequency.load();
}, 1000);
// Fast Form Fill
new FastFormFill();
// Currency Related Components
new LiveCurrency();
new CustomCurrency();
// Auto Country Select
new AutoCountrySelect();
// Add Image Attribution
if (this.options.MediaAttribution) new MediaAttribution();
// Apple Pay
if (this.options.applePay) new ApplePay();
// Capitalize Fields
if (this.options.CapitalizeFields) new CapitalizeFields();
// Auto Year Class
if (this.options.AutoYear) new AutoYear();
// Autocomplete Class
new Autocomplete();
// Ecard Class
new Ecard();
// Click To Expand
if (this.options.ClickToExpand) new ClickToExpand();
if (this.options.SkipToMainContentLink) new SkipToMainContentLink();
if (this.options.SrcDefer) new SrcDefer();
// Progress Bar
if (this.options.ProgressBar) new ProgressBar();
// RememberMe
try {
// Accessing window.localStorage will throw an exception if it isn't permitted due to security reasons
// For example, this happens in Firefox when cookies are disabled. If it isn't available, we shouldn't
// bother with enabling RememberMe
if (
this.options.RememberMe &&
typeof this.options.RememberMe === "object" &&
window.localStorage
) {
new RememberMe(this.options.RememberMe);
}
} catch (e) {}
if (this.options.NeverBounceAPI)
new NeverBounce(
this.options.NeverBounceAPI,
this.options.NeverBounceDateField,
this.options.NeverBounceStatusField,
this.options.NeverBounceDateFormat
);
// FreshAddress
if (this.options.FreshAddress) new FreshAddress();
new ShowIfAmount();
new OtherAmount();
new MinMaxAmount();
new Ticker();
new A11y();
new AddNameToMessage();
new ExpandRegionName();
// Page Background
new PageBackground();
// Url Params to Form Fields
new UrlToForm();
// Required if Visible Fields
new RequiredIfVisible();
// EN Custom Validators (behind a feature flag, off by default)
new ENValidators();
//Debug hidden fields
if (this.options.Debug) new DebugHiddenFields();
// TidyContact
if (this.options.TidyContact) new TidyContact();
// Translate Fields
if (this.options.TranslateFields) new TranslateFields();
// Country Disable
new CountryDisable();
// Premium Gift Features
new PremiumGift();
// Custom Premium filtering (frequency/amount-based visibility)
new CustomPremium();
// Supporter Hub Features
new SupporterHub();
// Digital Wallets Features
if (ENGrid.getPageType() === "DONATION") {
new DigitalWallets();
new PreferredPaymentMethod();
}
// Mobile CTA
new MobileCTA();
// Live Frequency
new LiveFrequency();
// Universal Opt In
new UniversalOptIn();
new StripeFinancialConnections();
//Exit Intent Lightbox
new ExitIntentLightbox();
new UrlParamsToBodyAttrs();
new SetAttr();
new ShowIfPresent();
new PostalCodeValidator();
// Very Good Security
new VGS();
new WelcomeBack();
new EcardToTarget();
new UsOnlyForm();
new ThankYouPageConditionalContent();
new EmbeddedEcard();
new CheckboxLabel();
new PostDonationEmbed();
new FrequencyUpsell();
//Debug panel
let showDebugPanel = this.options.Debug;
try {
// accessing storage can throw an exception if it isn't available in Firefox
if (
!showDebugPanel &&
window.sessionStorage.hasOwnProperty(DebugPanel.debugSessionStorageKey)
) {
showDebugPanel = true;
}
} catch (e) {}
if (showDebugPanel) {
new DebugPanel(this.options.PageLayouts);
}
if (ENGrid.getUrlParameter("development") === "branding") {
new BrandingHtml().show();
}
ENGrid.setBodyData("js-loading", "finished");
window.EngridVersion = AppVersion;
this.logger.success(`VERSION: ${AppVersion}`);
// Window Load
let onLoad = typeof window.onload === "function" ? window.onload : null;
if (document.readyState !== "loading") {
this.onLoad();
} else {
window.onload = (e: Event) => {
this.onLoad();
if (onLoad) {
onLoad.bind(window, e);
}
};
}
}
private onLoad() {
if (this.options.onLoad) {
this.options.onLoad();
}
}
private onResize() {
if (this.options.onResize) {
this.options.onResize();
}
}
private onValidate() {
if (this.options.onValidate) {
this.logger.log("Client onValidate Triggered");
this.options.onValidate();
}
}
private onSubmit() {
if (this.options.onSubmit) {
this.logger.log("Client onSubmit Triggered");
this.options.onSubmit();
}
}
private onError() {
if (this.options.onError) {
this.logger.danger("Client onError Triggered");
this.options.onError();
}
}
public static log(message: string) {
const logger = new EngridLogger("Client", "brown", "aliceblue", "🍪");
logger.log(message);
}
}