@4site/engrid-scripts 0.20.8 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DonationAmount, DonationFrequency, EnForm, ProcessingFees, Country, } from "./events";
2
- import { AmountLabel, Loader, ProgressBar, UpsellLightbox, ENGrid, 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, Plaid, GiveBySelect, UrlParamsToBodyAttrs, ExitIntentLightbox, SupporterHub, FastFormFill, SetAttr, ShowIfPresent, ENValidators, CustomCurrency, VGS, PostalCodeValidator, CountryRedirect, WelcomeBack, EcardToTarget, UsOnlyForm, ThankYouPageConditionalContent, EmbeddedEcard, CheckboxLabel, UpsellCheckbox, } from ".";
2
+ import { AmountLabel, Loader, ProgressBar, UpsellLightbox, ENGrid, 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, Plaid, GiveBySelect, UrlParamsToBodyAttrs, ExitIntentLightbox, SupporterHub, FastFormFill, SetAttr, ShowIfPresent, ENValidators, CustomCurrency, VGS, PostalCodeValidator, CountryRedirect, WelcomeBack, EcardToTarget, UsOnlyForm, ThankYouPageConditionalContent, EmbeddedEcard, CheckboxLabel, UpsellCheckbox, PostDonationEmbed, } from ".";
3
3
  export class App extends ENGrid {
4
4
  constructor(options) {
5
5
  super();
@@ -275,6 +275,7 @@ export class App extends ENGrid {
275
275
  new ThankYouPageConditionalContent();
276
276
  new EmbeddedEcard();
277
277
  new CheckboxLabel();
278
+ new PostDonationEmbed();
278
279
  //Debug panel
279
280
  let showDebugPanel = this.options.Debug;
280
281
  try {
@@ -3,6 +3,8 @@ export declare class EmbeddedEcard {
3
3
  private readonly options;
4
4
  private _form;
5
5
  isSubmitting: boolean;
6
+ ecardFormActive: boolean;
7
+ iframe: HTMLIFrameElement | null;
6
8
  constructor();
7
9
  private onHostPage;
8
10
  private onEmbeddedEcardPage;
@@ -10,6 +12,8 @@ export declare class EmbeddedEcard {
10
12
  private embedEcard;
11
13
  private createIframe;
12
14
  private addEventListeners;
15
+ private validateRecipients;
16
+ private toggleEcardForm;
13
17
  private setEmbeddedEcardSessionData;
14
18
  private getEcardRecipients;
15
19
  private setupEmbeddedPage;
@@ -12,6 +12,8 @@ export class EmbeddedEcard {
12
12
  this.options = EmbeddedEcardOptionsDefaults;
13
13
  this._form = EnForm.getInstance();
14
14
  this.isSubmitting = false;
15
+ this.ecardFormActive = false;
16
+ this.iframe = null;
15
17
  // For the page hosting the embedded ecard
16
18
  if (this.onHostPage()) {
17
19
  // Clean up session variables if the page is reloaded, and it isn't a submission failure
@@ -73,7 +75,8 @@ export class EmbeddedEcard {
73
75
  </div>
74
76
  </div>`;
75
77
  container.appendChild(checkbox);
76
- container.appendChild(this.createIframe(this.options.pageUrl));
78
+ this.iframe = this.createIframe(this.options.pageUrl);
79
+ container.appendChild(this.iframe);
77
80
  (_a = document
78
81
  .querySelector(this.options.anchor)) === null || _a === void 0 ? void 0 : _a.insertAdjacentElement(this.options.placement, container);
79
82
  }
@@ -89,28 +92,64 @@ export class EmbeddedEcard {
89
92
  return iframe;
90
93
  }
91
94
  addEventListeners() {
92
- const iframe = document.querySelector(".engrid-iframe--embedded-ecard");
93
95
  const sendEcardCheckbox = document.getElementById("en__field_embedded-ecard");
94
- // Initialize based on checkbox's default state
95
- if (sendEcardCheckbox === null || sendEcardCheckbox === void 0 ? void 0 : sendEcardCheckbox.checked) {
96
+ this.toggleEcardForm(sendEcardCheckbox.checked);
97
+ sendEcardCheckbox === null || sendEcardCheckbox === void 0 ? void 0 : sendEcardCheckbox.addEventListener("change", (e) => {
98
+ const checkbox = e.target;
99
+ this.toggleEcardForm(checkbox.checked);
100
+ });
101
+ this._form.onValidate.subscribe(this.validateRecipients.bind(this));
102
+ }
103
+ validateRecipients() {
104
+ var _a, _b, _c, _d;
105
+ if (!this.ecardFormActive || !this._form.validate)
106
+ return;
107
+ this.logger.log("Validating ecard");
108
+ let embeddedEcardData = JSON.parse(sessionStorage.getItem("engrid-embedded-ecard") || "{}");
109
+ // Testing if the ecard recipient data is set and valid
110
+ if (!embeddedEcardData.formData ||
111
+ !embeddedEcardData.formData.recipients ||
112
+ embeddedEcardData.formData.recipients.length == 0 ||
113
+ embeddedEcardData.formData.recipients.some((recipient) => {
114
+ const recipientName = recipient.name;
115
+ const recipientEmail = recipient.email;
116
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
117
+ return (recipientName === "" ||
118
+ recipientEmail === "" ||
119
+ !emailRegex.test(recipientEmail));
120
+ })) {
121
+ this.logger.log("Ecard recipients validation failed");
122
+ this._form.validate = false;
123
+ this.sendPostMessage(this.iframe, "recipient_error");
124
+ const iframeDoc = ((_a = this.iframe) === null || _a === void 0 ? void 0 : _a.contentDocument) || ((_c = (_b = this.iframe) === null || _b === void 0 ? void 0 : _b.contentWindow) === null || _c === void 0 ? void 0 : _c.document);
125
+ if (!iframeDoc)
126
+ return;
127
+ const scrollTarget = iframeDoc.querySelector(".en__ecardrecipients");
128
+ if (!scrollTarget)
129
+ return;
130
+ const iframeRect = (_d = this.iframe) === null || _d === void 0 ? void 0 : _d.getBoundingClientRect();
131
+ if (!iframeRect)
132
+ return;
133
+ const elementRect = scrollTarget.getBoundingClientRect();
134
+ window.scrollTo({
135
+ top: iframeRect.top + elementRect.top + window.scrollY - 10,
136
+ behavior: "smooth",
137
+ });
138
+ }
139
+ }
140
+ toggleEcardForm(visible) {
141
+ const iframe = document.querySelector(".engrid-iframe--embedded-ecard");
142
+ this.ecardFormActive = visible;
143
+ if (visible) {
96
144
  iframe === null || iframe === void 0 ? void 0 : iframe.setAttribute("style", "display: block");
97
145
  sessionStorage.setItem("engrid-send-embedded-ecard", "true");
146
+ this.logger.log("Ecard form is visible");
98
147
  }
99
148
  else {
100
149
  iframe === null || iframe === void 0 ? void 0 : iframe.setAttribute("style", "display: none");
101
150
  sessionStorage.removeItem("engrid-send-embedded-ecard");
151
+ this.logger.log("Ecard form is hidden");
102
152
  }
103
- sendEcardCheckbox === null || sendEcardCheckbox === void 0 ? void 0 : sendEcardCheckbox.addEventListener("change", (e) => {
104
- const checkbox = e.target;
105
- if (checkbox === null || checkbox === void 0 ? void 0 : checkbox.checked) {
106
- iframe === null || iframe === void 0 ? void 0 : iframe.setAttribute("style", "display: block");
107
- sessionStorage.setItem("engrid-send-embedded-ecard", "true");
108
- }
109
- else {
110
- iframe === null || iframe === void 0 ? void 0 : iframe.setAttribute("style", "display: none");
111
- sessionStorage.removeItem("engrid-send-embedded-ecard");
112
- }
113
- });
114
153
  }
115
154
  setEmbeddedEcardSessionData() {
116
155
  let ecardVariant = document.querySelector("[name='friend.ecard']");
@@ -202,6 +241,15 @@ export class EmbeddedEcard {
202
241
  ecardVariant.dispatchEvent(new Event("input"));
203
242
  });
204
243
  });
244
+ // Remove the recipient error message when the user starts typing in the recipient fields
245
+ [recipientName, recipientEmail].forEach((el) => {
246
+ el.addEventListener("input", () => {
247
+ const recipientDetails = document.querySelector(".en__ecardrecipients__detail");
248
+ const error = document.querySelector(".engrid__recipient__error");
249
+ recipientDetails === null || recipientDetails === void 0 ? void 0 : recipientDetails.classList.remove("validationFail");
250
+ error === null || error === void 0 ? void 0 : error.classList.add("hide");
251
+ });
252
+ });
205
253
  window.addEventListener("message", (e) => {
206
254
  if (e.origin !== location.origin || !e.data.action)
207
255
  return;
@@ -236,6 +284,18 @@ export class EmbeddedEcard {
236
284
  recipientName.dispatchEvent(new Event("input"));
237
285
  recipientEmail.dispatchEvent(new Event("input"));
238
286
  break;
287
+ case "recipient_error":
288
+ const recipientDetails = document.querySelector(".en__ecardrecipients__detail");
289
+ const error = document.querySelector(".engrid__recipient__error");
290
+ if (error) {
291
+ error.classList.remove("hide");
292
+ }
293
+ else {
294
+ recipientDetails === null || recipientDetails === void 0 ? void 0 : recipientDetails.insertAdjacentHTML("afterend", "<div class='en__field__error engrid__recipient__error'>Please provide the details for your eCard recipient</div>");
295
+ }
296
+ recipientDetails === null || recipientDetails === void 0 ? void 0 : recipientDetails.classList.add("validationFail");
297
+ window.dispatchEvent(new Event("resize"));
298
+ break;
239
299
  }
240
300
  });
241
301
  this.sendPostMessage("parent", "ecard_form_ready");
@@ -256,6 +316,8 @@ export class EmbeddedEcard {
256
316
  }
257
317
  sendPostMessage(target, action, data = {}) {
258
318
  var _a;
319
+ if (!target)
320
+ return;
259
321
  const message = Object.assign({ action }, data);
260
322
  if (target === "parent") {
261
323
  window.parent.postMessage(message, location.origin);
package/dist/engrid.d.ts CHANGED
@@ -13,6 +13,7 @@ export declare abstract class ENGrid {
13
13
  static getGiftProcess(): any;
14
14
  static getPageCount(): any;
15
15
  static getPageNumber(): any;
16
+ static isThankYouPage(): boolean;
16
17
  static getPageID(): any;
17
18
  static getClientID(): any;
18
19
  static getDataCenter(): "us" | "ca";
package/dist/engrid.js CHANGED
@@ -169,6 +169,9 @@ export class ENGrid {
169
169
  return window.pageJson.pageNumber;
170
170
  return null;
171
171
  }
172
+ static isThankYouPage() {
173
+ return this.getPageNumber() === this.getPageCount();
174
+ }
172
175
  // Return the current page ID
173
176
  static getPageID() {
174
177
  if ("pageJson" in window)
package/dist/index.d.ts CHANGED
@@ -81,5 +81,6 @@ export * from "./us-only-form";
81
81
  export * from "./thank-you-page-conditional-content";
82
82
  export * from "./checkbox-label";
83
83
  export * from "./optin-ladder";
84
+ export * from "./post-donation-embed";
84
85
  export * from "./events";
85
86
  export * from "./version";
package/dist/index.js CHANGED
@@ -81,6 +81,7 @@ export * from "./us-only-form";
81
81
  export * from "./thank-you-page-conditional-content";
82
82
  export * from "./checkbox-label";
83
83
  export * from "./optin-ladder";
84
+ export * from "./post-donation-embed";
84
85
  // Events
85
86
  export * from "./events";
86
87
  // Version
@@ -0,0 +1,6 @@
1
+ export declare class PostDonationEmbed {
2
+ private logger;
3
+ constructor();
4
+ shouldRun(): boolean;
5
+ hasPostDonationTag(): boolean;
6
+ }
@@ -0,0 +1,56 @@
1
+ // This component only works on Thank You pages and the current page IS NOT embedded as an iframe.
2
+ // It searches for a post-donation tag (engrid-post-donation)
3
+ // and if it exists, it will replace it with an iframe of the current donation page, replacing the
4
+ // "/donate/2" with "/donate/1" and adding a ?chain.
5
+ // It has 2 parameters:
6
+ // 1. params: the URL parameters to pass to the iframe
7
+ // 2. amounts: comma separated list of amounts to pass to the iframe
8
+ import { ENGrid, EngridLogger } from ".";
9
+ export class PostDonationEmbed {
10
+ constructor() {
11
+ this.logger = new EngridLogger("PostDonationEmbed", "red", "white", "🖼️");
12
+ if (!this.shouldRun())
13
+ return;
14
+ this.logger.log("Post Donation Tag found");
15
+ const postDonationTag = document.querySelector("engrid-post-donation");
16
+ // Get current page URL
17
+ let currentUrl = new URL(window.location.href);
18
+ // Modify the path: replace "/donate/2" with "/donate/1"
19
+ currentUrl.pathname = currentUrl.pathname.replace("/donate/2", "/donate/1");
20
+ // Extract parameters from the <engrid-post-donation> tag
21
+ let params = postDonationTag.getAttribute("params") || "";
22
+ let amounts = postDonationTag.getAttribute("amounts");
23
+ // Format parameters correctly
24
+ let searchParams = new URLSearchParams(params.replace(/&/g, "&"));
25
+ let paramString = searchParams
26
+ .toString()
27
+ .replace(/%5B/g, "[")
28
+ .replace(/%5D/g, "]");
29
+ // Construct new URL with "chain" parameter
30
+ let newUrl = `${currentUrl.origin}${currentUrl.pathname}?chain&${paramString}`;
31
+ if (amounts) {
32
+ newUrl += `&engrid-amounts=${amounts}`;
33
+ }
34
+ // Create the iframe element
35
+ let iframe = document.createElement("iframe");
36
+ iframe.setAttribute("loading", "lazy");
37
+ iframe.setAttribute("width", "100%");
38
+ iframe.setAttribute("scrolling", "no");
39
+ iframe.setAttribute("class", "engrid-iframe thank-you-page-donation");
40
+ iframe.setAttribute("src", newUrl);
41
+ iframe.setAttribute("frameborder", "0");
42
+ iframe.setAttribute("allowfullscreen", "");
43
+ iframe.setAttribute("allowpaymentrequest", "true");
44
+ iframe.setAttribute("allow", "payment");
45
+ // Replace <engrid-post-donation> with the iframe
46
+ postDonationTag.replaceWith(iframe);
47
+ }
48
+ shouldRun() {
49
+ return (ENGrid.isThankYouPage() &&
50
+ this.hasPostDonationTag() &&
51
+ ENGrid.getBodyData("embedded") === null);
52
+ }
53
+ hasPostDonationTag() {
54
+ return !!document.querySelector("engrid-post-donation");
55
+ }
56
+ }
@@ -31,6 +31,7 @@ export declare class SwapAmounts {
31
31
  private defaultChange;
32
32
  private swapped;
33
33
  constructor();
34
+ loadAmountsFromUrl(): void;
34
35
  swapAmounts(): void;
35
36
  loadEnAmounts(amountArray: {
36
37
  amounts: [string, number];
@@ -1,5 +1,8 @@
1
1
  // This script allows you to override the default donation amounts in Engaging Networks
2
2
  // with a custom list of amounts.
3
+ // If the URL contains a query parameter "engrid-amounts" with a comma separated values, the script will load the
4
+ // amounts from the parameter and set them as the default amounts for the donation
5
+ // form.
3
6
  /**
4
7
  * Example:
5
8
  * window.EngridAmounts = {
@@ -33,6 +36,7 @@ export class SwapAmounts {
33
36
  this._frequency = DonationFrequency.getInstance();
34
37
  this.defaultChange = false;
35
38
  this.swapped = false;
39
+ this.loadAmountsFromUrl();
36
40
  if (!this.shouldRun())
37
41
  return;
38
42
  this._frequency.onFrequencyChange.subscribe(() => this.swapAmounts());
@@ -49,6 +53,25 @@ export class SwapAmounts {
49
53
  }
50
54
  });
51
55
  }
56
+ loadAmountsFromUrl() {
57
+ const urlParams = new URLSearchParams(window.location.search);
58
+ const amounts = urlParams.get("engrid-amounts");
59
+ if (amounts) {
60
+ const amountArray = amounts.split(",").map((amt) => amt.trim());
61
+ const defaultAmount = parseFloat(ENGrid.getUrlParameter("transaction.donationAmt")) || parseFloat(amountArray[0]);
62
+ const amountsObj = {};
63
+ for (let i = 0; i < amountArray.length; i++) {
64
+ amountsObj[amountArray[i].toString()] = isNaN(parseFloat(amountArray[i]))
65
+ ? amountArray[i]
66
+ : parseFloat(amountArray[i]);
67
+ }
68
+ amountsObj["Other"] = "other";
69
+ window.EngridAmounts = {
70
+ onetime: { amounts: amountsObj, default: defaultAmount },
71
+ monthly: { amounts: amountsObj, default: defaultAmount },
72
+ };
73
+ }
74
+ }
52
75
  swapAmounts() {
53
76
  if (this._frequency.frequency in window.EngridAmounts) {
54
77
  window.EngagingNetworks.require._defined.enjs.swapList("donationAmt", this.loadEnAmounts(window.EngridAmounts[this._frequency.frequency]), {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const AppVersion = "0.20.8";
1
+ export declare const AppVersion = "0.21.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const AppVersion = "0.20.8";
1
+ export const AppVersion = "0.21.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@4site/engrid-scripts",
3
- "version": "0.20.8",
3
+ "version": "0.21.0",
4
4
  "description": "Scripts for the ENGRID Project",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  "strongly-typed-events": "^2.0.9"
26
26
  },
27
27
  "homepage": "https://github.com/4site-interactive-studios/engrid#readme",
28
- "gitHead": "73c9112c8220cfe7db46ed43fbe130f9f966348a",
28
+ "gitHead": "b99b1cb751e3f396fb1f7aa99693a23f22cd778f",
29
29
  "devDependencies": {
30
30
  "nodemon": "^2.0.20"
31
31
  }