fontdue-js 3.15.0 → 3.16.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.
Files changed (35) hide show
  1. package/AGENTS.md +29 -0
  2. package/CHANGELOG.md +10 -0
  3. package/dist/__generated__/FreeDownloadFormMutation.graphql.d.ts +43 -0
  4. package/dist/__generated__/FreeDownloadFormMutation.graphql.js +98 -0
  5. package/dist/__generated__/FreeDownloadForm_Query.graphql.d.ts +46 -0
  6. package/dist/__generated__/FreeDownloadForm_Query.graphql.js +186 -0
  7. package/dist/__tests__/freeDownloadForm.test.js +222 -0
  8. package/dist/__tests__/i18nComponents.test.js +1 -1
  9. package/dist/__tests__/trackEvents.test.js +131 -0
  10. package/dist/__tests__/trackingPageViews.test.js +339 -0
  11. package/dist/__tests__/trackingRouteChanges.test.js +48 -2
  12. package/dist/components/FreeDownloadForm/FreeDownloadFormElement.d.ts +10 -0
  13. package/dist/components/FreeDownloadForm/FreeDownloadFormElement.js +17 -0
  14. package/dist/components/FreeDownloadForm/index.d.ts +21 -0
  15. package/dist/components/FreeDownloadForm/index.js +283 -0
  16. package/dist/components/FreeDownloadForm/index.server.d.ts +9 -0
  17. package/dist/components/FreeDownloadForm/index.server.js +22 -0
  18. package/dist/components/FreeDownloadForm/variables.d.ts +8 -0
  19. package/dist/components/FreeDownloadForm/variables.js +18 -0
  20. package/dist/components/Root/index.js +1 -0
  21. package/dist/components/Tracking/index.js +52 -34
  22. package/dist/components/Tracking/pageViews.d.ts +26 -0
  23. package/dist/components/Tracking/pageViews.js +94 -0
  24. package/dist/components/Tracking/routeChanges.d.ts +9 -1
  25. package/dist/components/Tracking/routeChanges.js +33 -9
  26. package/dist/components/Tracking/sendTrackEvent.d.ts +28 -0
  27. package/dist/components/Tracking/sendTrackEvent.js +68 -0
  28. package/dist/components/track.d.ts +21 -0
  29. package/dist/components/track.js +31 -0
  30. package/dist/fontdue.css +32 -0
  31. package/dist/i18n/de.js +17 -5
  32. package/dist/i18n/en.d.ts +11 -0
  33. package/dist/i18n/en.js +12 -0
  34. package/dist/version.js +1 -1
  35. package/package.json +6 -1
@@ -0,0 +1,283 @@
1
+ 'use client';
2
+
3
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
4
+ import _FreeDownloadForm_Query from "../../__generated__/FreeDownloadForm_Query.graphql.js";
5
+ import _FreeDownloadFormMutation from "../../__generated__/FreeDownloadFormMutation.graphql.js";
6
+ import React, { useState, useRef, useCallback, useId } from 'react';
7
+ import { commitMutation, graphql, useRelayEnvironment, useLazyLoadQuery, usePreloadedQuery } from 'react-relay';
8
+ // The script-injecting reCAPTCHA wrapper – see ../Recaptcha.
9
+ import { ReCAPTCHA } from '../Recaptcha.js';
10
+ import { useLocale } from '../LocaleContext.js';
11
+ import TextField from '../TextField/index.js';
12
+ import Checkbox from '../Checkbox/index.js';
13
+ import FreeDownloadFormQueryNode from '../../__generated__/FreeDownloadForm_Query.graphql.js';
14
+ import loadSerializableQuery from '../../relay/loadSerializableQuery.js';
15
+ import useSerializablePreloadedQuery from '../../relay/useSerializablePreloadedQuery.js';
16
+ import { EnsureFontdueContext, LazyQueryBoundary } from '../FontdueContextProvider/index.js';
17
+ import { orderTrackingInput } from '../Cart/orderTracking.js';
18
+ import { freeDownloadFormQueryVariables } from './variables.js';
19
+ import { useRecaptchaTimeout, isRecaptchaScriptLoaded } from '../../hooks/useRecaptchaTimeout.js';
20
+ import { useT } from '../../i18n/useT.js';
21
+
22
+ // The free download form: a collection's free fonts (a font is free when
23
+ // its price is zero) for a name, an email and the licence agreement. The
24
+ // server completes an order of its own – separate from the cart – and emails
25
+ // the receipt with the download link, so the form ends on "check your
26
+ // email" rather than starting a download.
27
+ const createFreeOrderMutation = (_FreeDownloadFormMutation.hash && _FreeDownloadFormMutation.hash !== "ec63092778be13d53040086da58031ff" && console.error("The definition of 'FreeDownloadFormMutation' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _FreeDownloadFormMutation);
28
+ const firstErrors = errors => Object.values(errors ?? {}).flatMap(messages => messages ?? []).filter(message => !!message);
29
+ const FreeDownloadFormComponent = _ref => {
30
+ var _data$viewer, _data$viewer2;
31
+ let {
32
+ data,
33
+ agreementLabel,
34
+ downloadLabel: downloadLabelProp,
35
+ newsletterCheckboxChecked = false
36
+ } = _ref;
37
+ const [email, setEmail] = useState('');
38
+ const [name, setName] = useState('');
39
+ const [newsletterOptIn, setNewsletterOptIn] = useState(newsletterCheckboxChecked);
40
+ const [agreed, setAgreed] = useState(false);
41
+ const [highlightMissing, setHighlightMissing] = useState(false);
42
+ const [errors, setErrors] = useState([]);
43
+ const [submitting, setSubmitting] = useState(false);
44
+ const [sentTo, setSentTo] = useState(null);
45
+ const [recaptchaToken, setRecaptchaToken] = useState(null);
46
+ const [pendingSubmit, setPendingSubmit] = useState(false);
47
+ const recaptchaRef = useRef(null);
48
+ const newsletterLabelRef = useRef(null);
49
+ const environment = useRelayEnvironment();
50
+ const recaptchaTimeout = useRecaptchaTimeout();
51
+ const locale = useLocale();
52
+ const t = useT();
53
+ const idPrefix = useId();
54
+ const download = (_data$viewer = data.viewer) === null || _data$viewer === void 0 ? void 0 : _data$viewer.freeDownload;
55
+ const settings = (_data$viewer2 = data.viewer) === null || _data$viewer2 === void 0 ? void 0 : _data$viewer2.settings;
56
+ const newsletterRequired = (download === null || download === void 0 ? void 0 : download.newsletter) === 'REQUIRED';
57
+ const recaptchaEnabled = (settings === null || settings === void 0 ? void 0 : settings.recaptchaEnabled) ?? false;
58
+ const recaptchaSiteKey = settings === null || settings === void 0 ? void 0 : settings.recaptchaSiteKey;
59
+ const downloadLabel = downloadLabelProp ?? t('freeDownload.download');
60
+ const submitForm = useCallback(token => {
61
+ var _newsletterLabelRef$c, _newsletterLabelRef$c2;
62
+ if (!download) return;
63
+ recaptchaTimeout.clear();
64
+ setSubmitting(true);
65
+ setPendingSubmit(false);
66
+ setErrors([]);
67
+ const failed = messages => {
68
+ var _recaptchaRef$current;
69
+ setErrors(messages);
70
+ setSubmitting(false);
71
+ (_recaptchaRef$current = recaptchaRef.current) === null || _recaptchaRef$current === void 0 ? void 0 : _recaptchaRef$current.reset();
72
+ setRecaptchaToken(null);
73
+ };
74
+ commitMutation(environment, {
75
+ mutation: createFreeOrderMutation,
76
+ variables: {
77
+ input: {
78
+ collectionId: download.fontCollection.id,
79
+ name,
80
+ email,
81
+ licenseAgreed: agreed,
82
+ newsletterOptIn,
83
+ // The checkbox's wording, kept with the subscriber's consent.
84
+ newsletterOptInLabel: newsletterOptIn ? ((_newsletterLabelRef$c = newsletterLabelRef.current) === null || _newsletterLabelRef$c === void 0 ? void 0 : (_newsletterLabelRef$c2 = _newsletterLabelRef$c.textContent) === null || _newsletterLabelRef$c2 === void 0 ? void 0 : _newsletterLabelRef$c2.trim()) || undefined : undefined,
85
+ recaptchaToken: token ?? undefined,
86
+ tracking: orderTrackingInput()
87
+ }
88
+ },
89
+ onCompleted: (res, graphqlErrors) => {
90
+ var _res$createFreeOrder;
91
+ if (graphqlErrors && graphqlErrors.length > 0) {
92
+ failed([graphqlErrors[0].message]);
93
+ } else if (!((_res$createFreeOrder = res.createFreeOrder) !== null && _res$createFreeOrder !== void 0 && _res$createFreeOrder.success)) {
94
+ var _res$createFreeOrder2;
95
+ failed(firstErrors((_res$createFreeOrder2 = res.createFreeOrder) === null || _res$createFreeOrder2 === void 0 ? void 0 : _res$createFreeOrder2.errors));
96
+ } else {
97
+ setSubmitting(false);
98
+ setSentTo(email);
99
+ }
100
+ },
101
+ onError: _ref2 => {
102
+ let {
103
+ message
104
+ } = _ref2;
105
+ return failed([message]);
106
+ }
107
+ });
108
+ }, [environment, download, name, email, agreed, newsletterOptIn, recaptchaTimeout]);
109
+ const abortRecaptcha = useCallback(() => {
110
+ var _recaptchaRef$current2;
111
+ recaptchaTimeout.clear();
112
+ setPendingSubmit(false);
113
+ setRecaptchaToken(null);
114
+ (_recaptchaRef$current2 = recaptchaRef.current) === null || _recaptchaRef$current2 === void 0 ? void 0 : _recaptchaRef$current2.reset();
115
+ setErrors([t('recaptcha.unavailable')]);
116
+ }, [recaptchaTimeout, t]);
117
+ const handleRecaptchaChange = useCallback(token => {
118
+ setRecaptchaToken(token);
119
+ if (token && pendingSubmit) submitForm(token);
120
+ }, [pendingSubmit, submitForm]);
121
+ if (!download) {
122
+ return /*#__PURE__*/React.createElement("div", {
123
+ className: "free-download free-download--unavailable"
124
+ }, /*#__PURE__*/React.createElement("p", null, t('freeDownload.unavailable')));
125
+ }
126
+ const handleSubmit = event => {
127
+ event.preventDefault();
128
+ if (!agreed || newsletterRequired && !newsletterOptIn) {
129
+ setHighlightMissing(true);
130
+ return;
131
+ }
132
+ if (recaptchaEnabled && recaptchaSiteKey && !recaptchaToken) {
133
+ var _recaptchaRef$current3;
134
+ setPendingSubmit(true);
135
+ setErrors([]);
136
+ recaptchaTimeout.start(() => {
137
+ if (isRecaptchaScriptLoaded()) return;
138
+ abortRecaptcha();
139
+ });
140
+ (_recaptchaRef$current3 = recaptchaRef.current) === null || _recaptchaRef$current3 === void 0 ? void 0 : _recaptchaRef$current3.execute();
141
+ return;
142
+ }
143
+ submitForm(recaptchaToken);
144
+ };
145
+ if (sentTo) {
146
+ return /*#__PURE__*/React.createElement("div", {
147
+ className: "free-download free-download--sent"
148
+ }, /*#__PURE__*/React.createElement("p", null, t('freeDownload.sent', {
149
+ email: sentTo
150
+ })));
151
+ }
152
+ const freeStyles = download.wholeCollection ? null : download.items.flatMap(item => item.fontStyles.map(style => style.name));
153
+
154
+ // "Desktop, Web and App", each name linking its license.
155
+ const lastIndex = download.licenses.length - 1;
156
+ const licenseLinks = download.licenses.map((license, index) => /*#__PURE__*/React.createElement(React.Fragment, {
157
+ key: license.id
158
+ }, index > 0 && (index === lastIndex ? ` ${t('freeDownload.and')} ` : ', '), license.url ? /*#__PURE__*/React.createElement("a", {
159
+ href: license.url,
160
+ target: "_blank",
161
+ rel: "noreferrer"
162
+ }, license.name) : license.name));
163
+ const newsletterLabel = settings === null || settings === void 0 ? void 0 : settings.newsletterOptInLabel;
164
+ const agreementId = `${idPrefix}-agreement`;
165
+ const newsletterId = `${idPrefix}-newsletter`;
166
+ const disabled = !name || !email || !agreed || newsletterRequired && !newsletterOptIn;
167
+ return /*#__PURE__*/React.createElement("div", {
168
+ className: "free-download"
169
+ }, errors.length > 0 && /*#__PURE__*/React.createElement("div", {
170
+ className: "free-download__errors"
171
+ }, errors.map(message => /*#__PURE__*/React.createElement("p", {
172
+ key: message
173
+ }, message))), /*#__PURE__*/React.createElement("form", {
174
+ className: "free-download__form",
175
+ onSubmit: handleSubmit
176
+ }, freeStyles && freeStyles.length > 0 && /*#__PURE__*/React.createElement("p", {
177
+ className: "free-download__styles"
178
+ }, t('freeDownload.freeStyles', {
179
+ styles: freeStyles.join(', ')
180
+ })), /*#__PURE__*/React.createElement("div", {
181
+ className: "free-download__section"
182
+ }, /*#__PURE__*/React.createElement(TextField, {
183
+ label: t('customerFields.nameRequired'),
184
+ value: name,
185
+ onChange: value => setName(value),
186
+ autocomplete: "name",
187
+ placeholder: t('customerFields.namePlaceholder')
188
+ })), /*#__PURE__*/React.createElement("div", {
189
+ className: "free-download__section"
190
+ }, /*#__PURE__*/React.createElement(TextField, {
191
+ label: t('customerFields.emailRequired'),
192
+ type: "email",
193
+ value: email,
194
+ onChange: value => setEmail(value),
195
+ autocomplete: "email",
196
+ placeholder: t('customerFields.emailPlaceholder')
197
+ })), /*#__PURE__*/React.createElement("div", {
198
+ className: "free-download__agreement free-download__checkbox-field",
199
+ "data-highlighted": highlightMissing && !agreed
200
+ }, /*#__PURE__*/React.createElement(Checkbox, {
201
+ id: agreementId,
202
+ checked: agreed,
203
+ onChange: event => setAgreed(event.target.checked)
204
+ }), agreementLabel ? /*#__PURE__*/React.createElement("label", {
205
+ htmlFor: agreementId,
206
+ dangerouslySetInnerHTML: {
207
+ __html: agreementLabel
208
+ }
209
+ }) : /*#__PURE__*/React.createElement("label", {
210
+ htmlFor: agreementId
211
+ }, t.rich('freeDownload.agreement', {
212
+ licenses: /*#__PURE__*/React.createElement(React.Fragment, null, licenseLinks),
213
+ count: download.licenses.length
214
+ }))), (newsletterRequired || newsletterLabel) && /*#__PURE__*/React.createElement("div", {
215
+ className: "free-download__newsletter-opt-in free-download__checkbox-field",
216
+ "data-highlighted": highlightMissing && newsletterRequired && !newsletterOptIn
217
+ }, /*#__PURE__*/React.createElement(Checkbox, {
218
+ id: newsletterId,
219
+ checked: newsletterOptIn,
220
+ onChange: event => setNewsletterOptIn(event.target.checked)
221
+ }), /*#__PURE__*/React.createElement("label", {
222
+ htmlFor: newsletterId,
223
+ ref: newsletterLabelRef
224
+ }, newsletterLabel ? /*#__PURE__*/React.createElement("span", {
225
+ dangerouslySetInnerHTML: {
226
+ __html: newsletterLabel
227
+ }
228
+ }) : t('freeDownload.newsletter'), newsletterRequired && /*#__PURE__*/React.createElement("span", {
229
+ className: "free-download__required"
230
+ }, ' ', t('freeDownload.newsletterRequired')))), recaptchaEnabled && recaptchaSiteKey && /*#__PURE__*/React.createElement(ReCAPTCHA, {
231
+ ref: recaptchaRef,
232
+ sitekey: recaptchaSiteKey,
233
+ hl: locale,
234
+ size: "invisible",
235
+ onChange: handleRecaptchaChange,
236
+ onExpired: () => setRecaptchaToken(null),
237
+ onErrored: () => pendingSubmit && abortRecaptcha()
238
+ }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("button", {
239
+ className: "submit-button",
240
+ type: "submit",
241
+ disabled: submitting || pendingSubmit || disabled
242
+ }, submitting || pendingSubmit ? t('common.submittingDots') : downloadLabel, /*#__PURE__*/React.createElement("span", {
243
+ className: "submit-button__arrow"
244
+ }, " \u2192")))));
245
+ };
246
+ const query = (_FreeDownloadForm_Query.hash && _FreeDownloadForm_Query.hash !== "db8a8700fc4dd6730be1e38ac3289d20" && console.error("The definition of 'FreeDownloadForm_Query' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _FreeDownloadForm_Query);
247
+ // Pass the same `collectionId` / `collectionSlug` as the form's props.
248
+ export async function loadFreeDownloadFormQuery(variables, options) {
249
+ return loadSerializableQuery(FreeDownloadFormQueryNode, freeDownloadFormQueryVariables(variables), options);
250
+ }
251
+ export function FreeDownloadFormPreloadedQueryRenderer(_ref3) {
252
+ let {
253
+ preloadedQuery,
254
+ ...rest
255
+ } = _ref3;
256
+ const queryRef = useSerializablePreloadedQuery(preloadedQuery, 'store-or-network', query);
257
+ const data = usePreloadedQuery(query, queryRef);
258
+ return /*#__PURE__*/React.createElement(FreeDownloadFormComponent, _extends({
259
+ data: data
260
+ }, rest));
261
+ }
262
+ function FreeDownloadFormLazyQueryRenderer(props) {
263
+ const data = useLazyLoadQuery(query, freeDownloadFormQueryVariables(props));
264
+ return /*#__PURE__*/React.createElement(FreeDownloadFormComponent, _extends({
265
+ data: data
266
+ }, props));
267
+ }
268
+ // Accepts an optional preloaded query (server-side preload path) or fetches
269
+ // lazily on mount, like TestFontsForm.
270
+ export default function FreeDownloadForm(_ref4) {
271
+ var _props$preloadedQuery;
272
+ let {
273
+ config,
274
+ locale,
275
+ ...props
276
+ } = _ref4;
277
+ return /*#__PURE__*/React.createElement(EnsureFontdueContext, {
278
+ config: config,
279
+ locale: locale ?? ((_props$preloadedQuery = props.preloadedQuery) === null || _props$preloadedQuery === void 0 ? void 0 : _props$preloadedQuery.locale)
280
+ }, props.preloadedQuery ? /*#__PURE__*/React.createElement(FreeDownloadFormPreloadedQueryRenderer, _extends({}, props, {
281
+ preloadedQuery: props.preloadedQuery
282
+ })) : /*#__PURE__*/React.createElement(LazyQueryBoundary, null, /*#__PURE__*/React.createElement(FreeDownloadFormLazyQueryRenderer, props)));
283
+ }
@@ -0,0 +1,9 @@
1
+ import React from 'react';
2
+ import { FreeDownloadForm_props } from './index.js';
3
+ import { Config } from '../ConfigContext.js';
4
+ export type { FreeDownloadFormPreloadedQuery } from './index.js';
5
+ export declare function loadFreeDownloadFormQuery(): never;
6
+ export default function FreeDownloadForm(props: FreeDownloadForm_props & {
7
+ config?: Config;
8
+ locale?: string;
9
+ }): Promise<React.JSX.Element>;
@@ -0,0 +1,22 @@
1
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
2
+ import React from 'react';
3
+ import loadSerializableQuery from '../../relay/loadSerializableQuery.js';
4
+ import { FreeDownloadFormPreloadedQueryRenderer } from './index.js';
5
+ import { freeDownloadFormQueryVariables } from './variables.js';
6
+ import FreeDownloadFormQueryNode from '../../__generated__/FreeDownloadForm_Query.graphql.js';
7
+ // Stub for the RSC export condition. See FontdueProvider/index.server.tsx
8
+ // for the rationale.
9
+ export function loadFreeDownloadFormQuery() {
10
+ throw new Error("loadFreeDownloadFormQuery isn't needed in React Server Components — " + 'the <FreeDownloadForm> server entrypoint awaits its query automatically. ' + 'Drop the manual call.');
11
+ }
12
+
13
+ // Next RSC variant: awaits the query on the server and hands the response to
14
+ // the client renderer, like TestFontsForm's.
15
+ export default async function FreeDownloadForm(props) {
16
+ const preloadedQuery = await loadSerializableQuery(FreeDownloadFormQueryNode, freeDownloadFormQueryVariables(props), {
17
+ locale: props.locale
18
+ });
19
+ return /*#__PURE__*/React.createElement(FreeDownloadFormPreloadedQueryRenderer, _extends({
20
+ preloadedQuery: preloadedQuery
21
+ }, props));
22
+ }
@@ -0,0 +1,8 @@
1
+ export interface FreeDownloadFormCollectionProps {
2
+ collectionId?: string;
3
+ collectionSlug?: string;
4
+ }
5
+ export declare const freeDownloadFormQueryVariables: ({ collectionId, collectionSlug, }: FreeDownloadFormCollectionProps) => {
6
+ collectionId: string | null;
7
+ collectionSlug: string | null;
8
+ };
@@ -0,0 +1,18 @@
1
+ // Shared by the client component and the RSC entry (index.server.tsx), so it
2
+ // lives outside the 'use client' module: a server component can't call a
3
+ // function imported from one.
4
+
5
+ const present = value => {
6
+ const trimmed = value === null || value === void 0 ? void 0 : value.trim();
7
+ return trimmed ? trimmed : null;
8
+ };
9
+ export const freeDownloadFormQueryVariables = _ref => {
10
+ let {
11
+ collectionId,
12
+ collectionSlug
13
+ } = _ref;
14
+ return {
15
+ collectionId: present(collectionId),
16
+ collectionSlug: present(collectionSlug)
17
+ };
18
+ };
@@ -24,6 +24,7 @@ const customElementMap = {
24
24
  // @ts-ignore
25
25
  'fontdue-cookie-notification': /*#__PURE__*/lazy(() => retryImport(() => import('../CookieNotification/index.js'))),
26
26
  'fontdue-font-families': /*#__PURE__*/lazy(() => retryImport(() => import('../FontFamilies/index.js'))),
27
+ 'fontdue-free-download-form': /*#__PURE__*/lazy(() => retryImport(() => import('../FreeDownloadForm/FreeDownloadFormElement.js'))),
27
28
  'fontdue-customer-login-form': /*#__PURE__*/lazy(() => retryImport(() => import('../CustomerLoginForm/index.js'))),
28
29
  // Script tag only: CustomerSignIn isn't in the npm package's `exports` yet.
29
30
  'fontdue-customer-sign-in': /*#__PURE__*/lazy(() => retryImport(() => import('../CustomerSignIn/CustomerSignInElement.js'))),
@@ -4,7 +4,7 @@ import { useContext, useEffect } from 'react';
4
4
  import ConfigContext from '../ConfigContext.js';
5
5
  import { useFontdueUrl } from '../UrlContext.js';
6
6
  import { hasConsent, onConsent, setClientAnonymousId, setEntryAttribution } from '../ConsentBanner/consent.js';
7
- import { trackRouteChanges } from './routeChanges.js';
7
+ import { claimPageView, entryPageView, watchNavigation } from './pageViews.js';
8
8
  function getCampaignDataFromUrl() {
9
9
  const urlParams = new URLSearchParams(window.location.search);
10
10
  const campaign = {};
@@ -92,6 +92,35 @@ async function postPageView(baseUrl, body, anonymousId) {
92
92
  async function sendPageView(baseUrl, anonymousId) {
93
93
  return postPageView(baseUrl, buildPageViewBody(), anonymousId);
94
94
  }
95
+
96
+ // The first page view of the page load. Runs once per page (see pageViews.ts).
97
+ function sendEntryPageView(baseUrl, consentRequired) {
98
+ // Generate client-side anonymous ID for cookieless tracking when consent is required
99
+ const clientAnonymousId = consentRequired ? crypto.randomUUID() : undefined;
100
+ if (clientAnonymousId) {
101
+ setClientAnonymousId(clientAnonymousId);
102
+ }
103
+
104
+ // Only send the client ID when in cookieless mode (consent required but not yet granted)
105
+ const analyticsConsent = hasConsent('analytics');
106
+ const effectiveAnonymousId = clientAnonymousId && !analyticsConsent ? clientAnonymousId : undefined;
107
+
108
+ // Capture the entry page view once, then send it. Before consent the server
109
+ // records but does not forward it.
110
+ const entryBody = buildPageViewBody();
111
+ const pageViewPromise = postPageView(baseUrl, entryBody, effectiveAnonymousId);
112
+
113
+ // Publish this captured entry attribution so the consent banner can attach
114
+ // it to the `Consent Granted` event when the visitor grants consent. That
115
+ // event is a normal tracking event on the existing pipeline; the server
116
+ // forwards it and each destination decides how to represent it (Meta reads
117
+ // it as the attributed entry page view). Capturing once preserves the
118
+ // arrival attribution even if the visitor has since navigated.
119
+ if (consentRequired) {
120
+ setEntryAttribution(entryBody);
121
+ }
122
+ return pageViewPromise;
123
+ }
95
124
  const Tracking = () => {
96
125
  const config = useContext(ConfigContext);
97
126
  const url = useFontdueUrl();
@@ -99,30 +128,19 @@ const Tracking = () => {
99
128
  var _config$tracking$segm, _config$tracking$segm2;
100
129
  if (!config.tracking.enabled) return;
101
130
 
102
- // Generate client-side anonymous ID for cookieless tracking when consent is required
103
- const clientAnonymousId = config.tracking.consentRequired ? crypto.randomUUID() : undefined;
104
- if (clientAnonymousId) {
105
- setClientAnonymousId(clientAnonymousId);
106
- }
107
-
108
- // Only send the client ID when in cookieless mode (consent required but not yet granted)
109
- const analyticsConsent = hasConsent('analytics');
110
- const effectiveAnonymousId = clientAnonymousId && config.tracking.consentRequired && !analyticsConsent ? clientAnonymousId : undefined;
131
+ // React runs this effect more often than the page changes (StrictMode's
132
+ // double mount, a remount, a second provider), so what counts as a page
133
+ // view is decided page-wide in pageViews.ts rather than per mount. Claim
134
+ // the URL first: a mount on a page already counted then sends nothing.
135
+ const isNewPageView = claimPageView(window.location.href);
136
+ const {
137
+ entry,
138
+ isNew: isEntry
139
+ } = entryPageView(() => sendEntryPageView(url, config.tracking.consentRequired));
111
140
 
112
- // Capture the entry page view once, then send it. Before consent the server
113
- // records but does not forward it.
114
- const entryBody = buildPageViewBody();
115
- const pageViewPromise = postPageView(url, entryBody, effectiveAnonymousId);
116
-
117
- // Publish this captured entry attribution so the consent banner can attach
118
- // it to the `Consent Granted` event when the visitor grants consent. That
119
- // event is a normal tracking event on the existing pipeline; the server
120
- // forwards it and each destination decides how to represent it (Meta reads
121
- // it as the attributed entry page view). Capturing once preserves the
122
- // arrival attribution even if the visitor has since navigated.
123
- if (config.tracking.consentRequired) {
124
- setEntryAttribution(entryBody);
125
- }
141
+ // Mounted after the entry, on a URL nobody has reported: a navigation that
142
+ // happened while no tracker was watching history.
143
+ if (!isEntry && isNewPageView) sendPageView(url);
126
144
 
127
145
  // Segment SDK for device-mode integrations (e.g. Google Tag Manager)
128
146
  // The analytics factory is provided by the entry point — it calls AnalyticsBrowser.load()
@@ -134,10 +152,14 @@ const Tracking = () => {
134
152
  };
135
153
  let consentCleanup;
136
154
  if (loadAnalytics) {
155
+ // Once per page load, like the entry page view it follows. Every mount
156
+ // registers it, so a StrictMode re-run keeps a live consent listener.
137
157
  const fireSegmentPage = async () => {
158
+ if (entry.segmentPageSent) return;
159
+ entry.segmentPageSent = true;
138
160
  try {
139
161
  const analytics = loadAnalytics();
140
- const anonymousId = await pageViewPromise;
162
+ const anonymousId = await entry.anonymousId;
141
163
  if (anonymousId) {
142
164
  await analytics.setAnonymousId(anonymousId);
143
165
  }
@@ -155,18 +177,14 @@ const Tracking = () => {
155
177
  }
156
178
  }
157
179
 
158
- // Track client-side route changes
159
- const untrackRouteChanges = trackRouteChanges({
160
- history,
161
- window,
162
- currentUrl: () => window.location.href,
163
- onNavigate: () => {
164
- sendPageView(url);
165
- }
180
+ // Track client-side route changes (one history watcher for the page,
181
+ // however many trackers are mounted)
182
+ const unwatchNavigation = watchNavigation(() => {
183
+ sendPageView(url);
166
184
  });
167
185
  return () => {
168
186
  var _consentCleanup;
169
- untrackRouteChanges();
187
+ unwatchNavigation();
170
188
  (_consentCleanup = consentCleanup) === null || _consentCleanup === void 0 ? void 0 : _consentCleanup();
171
189
  };
172
190
  }, []);
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Record `url` as a page view if it is a new one. Returns true when the caller
3
+ * should report it, false when it was the last page view reported already.
4
+ */
5
+ export declare function claimPageView(url: string): boolean;
6
+ /** The entry page view: the first page view of this page load. */
7
+ export type EntryPageView = {
8
+ /** The anonymous id the server answered the entry page view with. */
9
+ anonymousId: Promise<string | null>;
10
+ /** Set once the Segment SDK's own page call has gone out for the entry. */
11
+ segmentPageSent: boolean;
12
+ };
13
+ /**
14
+ * The entry page view for this page load. `send` posts it and runs only on the
15
+ * first call (`isNew: true`); every later call – a StrictMode re-run, a
16
+ * remount, a second provider – gets the same entry back without sending.
17
+ */
18
+ export declare function entryPageView(send: () => Promise<string | null>): {
19
+ entry: EntryPageView;
20
+ isNew: boolean;
21
+ };
22
+ /**
23
+ * Report a page view through `report` for each client-side navigation, until
24
+ * the returned cleanup runs.
25
+ */
26
+ export declare function watchNavigation(report: () => void): () => void;
@@ -0,0 +1,94 @@
1
+ // Page-view bookkeeping for the whole page, shared by every Tracking instance.
2
+ //
3
+ // A page view belongs to the page, not to a React component, so this state
4
+ // lives at module level rather than in the component. React mounts the Tracking
5
+ // component more often than the page changes – StrictMode mounts, unmounts and
6
+ // mounts it again; a provider rendered by a page rather than the layout
7
+ // remounts with every navigation; a Suspense or Activity boundary, or a parent
8
+ // changing its key, can remount it; a site may render more than one
9
+ // FontdueProvider, and Astro renders one React tree per island – and each of
10
+ // those used to send its own entry page view and wrap history for its own
11
+ // copy of every navigation (FD-1207). Module state is shared by all of them,
12
+ // the same way the Redux store and Relay environment singletons are (see the
13
+ // multi-island contract in FontdueContextProvider). It is only ever touched
14
+ // from effects, so it never runs on the server and can't leak between
15
+ // requests.
16
+ import { trackRouteChanges } from './routeChanges.js';
17
+
18
+ // The last URL reported as a page view, by anyone on the page. A URL is a new
19
+ // page view only when it differs from this, so a mount or a history write that
20
+ // lands on the URL already counted adds nothing, while going back to an
21
+ // earlier page (A → B → A) still counts: B moved this on.
22
+ let lastTrackedUrl = null;
23
+
24
+ /**
25
+ * Record `url` as a page view if it is a new one. Returns true when the caller
26
+ * should report it, false when it was the last page view reported already.
27
+ */
28
+ export function claimPageView(url) {
29
+ if (url === lastTrackedUrl) return false;
30
+ lastTrackedUrl = url;
31
+ return true;
32
+ }
33
+
34
+ /** The entry page view: the first page view of this page load. */
35
+
36
+ let entry = null;
37
+
38
+ /**
39
+ * The entry page view for this page load. `send` posts it and runs only on the
40
+ * first call (`isNew: true`); every later call – a StrictMode re-run, a
41
+ * remount, a second provider – gets the same entry back without sending.
42
+ */
43
+ export function entryPageView(send) {
44
+ if (entry !== null) return {
45
+ entry,
46
+ isNew: false
47
+ };
48
+ entry = {
49
+ anonymousId: send(),
50
+ segmentPageSent: false
51
+ };
52
+ return {
53
+ entry,
54
+ isNew: true
55
+ };
56
+ }
57
+
58
+ // One history watcher for the page, however many Tracking instances are
59
+ // mounted. Each instance registers how to report a page view; a navigation is
60
+ // reported once, through the earliest instance still mounted. The watcher is
61
+ // installed with the first registration and removed with the last.
62
+ const reporters = [];
63
+ let stopWatching = null;
64
+
65
+ /**
66
+ * Report a page view through `report` for each client-side navigation, until
67
+ * the returned cleanup runs.
68
+ */
69
+ export function watchNavigation(report) {
70
+ // A distinct wrapper per registration, so the same function registered twice
71
+ // still unregisters one at a time.
72
+ const reporter = () => report();
73
+ reporters.push(reporter);
74
+ if (stopWatching === null) {
75
+ stopWatching = trackRouteChanges({
76
+ history,
77
+ window,
78
+ currentUrl: () => window.location.href,
79
+ claim: claimPageView,
80
+ onNavigate: () => {
81
+ var _reporters$;
82
+ return (_reporters$ = reporters[0]) === null || _reporters$ === void 0 ? void 0 : _reporters$.call(reporters);
83
+ }
84
+ });
85
+ }
86
+ return () => {
87
+ const index = reporters.indexOf(reporter);
88
+ if (index !== -1) reporters.splice(index, 1);
89
+ if (reporters.length === 0 && stopWatching !== null) {
90
+ stopWatching();
91
+ stopWatching = null;
92
+ }
93
+ };
94
+ }
@@ -7,6 +7,14 @@ export type RouteChangeOptions = {
7
7
  currentUrl: () => string;
8
8
  /** Called once per navigation to a URL different from the previous one. */
9
9
  onNavigate: () => void;
10
+ /**
11
+ * Decides whether a URL is a new page view, and records it as reported when
12
+ * it is. Defaults to comparing against the last URL this watcher reported,
13
+ * starting from `currentUrl()`; the Tracking component passes the page-wide
14
+ * guard in `pageViews.ts` instead, so the entry view and every watcher share
15
+ * one idea of what has been counted.
16
+ */
17
+ claim?: (url: string) => boolean;
10
18
  /** Overridable so tests can run the check synchronously. */
11
19
  defer?: (callback: () => void) => void;
12
20
  };
@@ -15,5 +23,5 @@ export type RouteChangeOptions = {
15
23
  *
16
24
  * Returns a cleanup function that restores the original History methods.
17
25
  */
18
- export declare function trackRouteChanges({ history, window: windowLike, currentUrl, onNavigate, defer, }: RouteChangeOptions): () => void;
26
+ export declare function trackRouteChanges({ history, window: windowLike, currentUrl, onNavigate, claim, defer, }: RouteChangeOptions): () => void;
19
27
  export {};