fontdue-js 3.15.0 → 3.15.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,8 @@
1
+ ## 3.15.1
2
+
3
+ - Fixed page views being recorded two to four times for one page when `tracking` is enabled, as happened under React StrictMode, when `FontdueProvider` remounted, or with more than one provider on a page. Each page load and each navigation now counts once.
4
+ - Changed the German text for checkout from “Kasse” to “Checkout”, with “Weiter zur Zahlung” on the button that continues to payment.
5
+
1
6
  ## 3.15.0
2
7
 
3
8
  - Added a `locale` option, such as `"de"`, to `FontdueProvider`, `createFontdueFetch` and the server config in `fontdue-js/server`, and to `runWithFontdue` (plus a new `runWithLocale`) in `fontdue-js/server/middleware`. Components then load the foundry’s content in that language and show their own text in it – English and German so far – and without a `locale` nothing changes. In Next.js, set it per page as well as on the layout’s provider, since a soft navigation re-renders the page without the layout.
@@ -225,7 +225,7 @@ describe('cart', () => {
225
225
  }));
226
226
  expect(html).toContain('>Zwischensumme<');
227
227
  expect(html).toContain('>Gesamt</div>');
228
- expect(html).toContain('Wird an der Kasse berechnet');
228
+ expect(html).toContain('Wird im Checkout berechnet');
229
229
  expect(html).toContain('data-label="Subtotal"');
230
230
  });
231
231
  it('renders the totals in English with no locale, as before', () => {
@@ -0,0 +1,339 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ // One page view per navigation, end to end through `<FontdueProvider>`: the
4
+ // entry view the Tracking component sends on mount and the views it sends for
5
+ // client-side navigation must not double up however React mounts it –
6
+ // StrictMode's mount/unmount/mount, a remount of the provider, or more than one
7
+ // provider on the page. Each test loads the provider fresh (`vi.resetModules`)
8
+ // so module-level tracking state starts clean, the way it does on a page load.
9
+
10
+ import React, { StrictMode, act } from 'react';
11
+ import { createRoot } from 'react-dom/client';
12
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
13
+ const {
14
+ serverTracking,
15
+ query
16
+ } = vi.hoisted(() => ({
17
+ serverTracking: {
18
+ enabled: true,
19
+ consentRequired: false
20
+ },
21
+ // Set to make the provider's query suspend on its next render.
22
+ query: {
23
+ pending: null
24
+ }
25
+ }));
26
+
27
+ // The provider's query and fragments are stubbed: every fragment reads as the
28
+ // server's tracking config, which is all ServerConfigProvider needs.
29
+ vi.mock('react-relay', async importActual => {
30
+ // react-relay is CommonJS: its named exports sit under `default` here.
31
+ const actual = await importActual();
32
+ return {
33
+ ...actual,
34
+ ...actual.default,
35
+ graphql: () => ({}),
36
+ useLazyLoadQuery: () => {
37
+ if (query.pending) throw query.pending;
38
+ return {
39
+ viewer: {}
40
+ };
41
+ },
42
+ useFragment: () => ({
43
+ fontdueConfig: {
44
+ tracking: {
45
+ ...serverTracking
46
+ }
47
+ }
48
+ })
49
+ };
50
+ });
51
+
52
+ // The other aux UI the provider mounts beside Tracking has nothing to do with
53
+ // page views.
54
+ vi.mock('../components/ThemeConfig/index.js', () => ({
55
+ default: () => null
56
+ }));
57
+ vi.mock('../components/TestModeBanner/index.js', () => ({
58
+ default: () => null
59
+ }));
60
+ vi.mock('../components/ConsentBanner/index.js', () => ({
61
+ default: () => null
62
+ }));
63
+ vi.mock('../components/FontdueAdminToolbar/index.js', () => ({
64
+ default: () => null
65
+ }));
66
+ const API = 'https://api.foundry.test';
67
+ // happy-dom's document lives at localhost; history refuses other origins.
68
+ const ORIGIN = window.location.origin;
69
+ let fetchMock;
70
+ let roots = [];
71
+ // History as the page had it before any provider wrapped it, for moving the
72
+ // URL without telling the trackers (a browser's back button does that).
73
+ let originalReplaceState;
74
+
75
+ /** Paths of every page view posted so far, in order. */
76
+ function pageViews() {
77
+ return fetchMock.mock.calls.filter(_ref => {
78
+ let [url] = _ref;
79
+ return String(url).endsWith('/api/track/page');
80
+ }).map(_ref2 => {
81
+ let [, init] = _ref2;
82
+ return JSON.parse(init.body).properties.path;
83
+ });
84
+ }
85
+
86
+ /** Let the trackers' deferred URL checks and any lazy imports settle. */
87
+ async function settle() {
88
+ await act(async () => {
89
+ await new Promise(resolve => setTimeout(resolve, 20));
90
+ });
91
+ }
92
+ async function loadProvider() {
93
+ const {
94
+ default: FontdueProvider
95
+ } = await import('../components/FontdueProvider/index.js');
96
+ return FontdueProvider;
97
+ }
98
+ async function mount(FontdueProvider) {
99
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
100
+ const container = document.createElement('div');
101
+ document.body.appendChild(container);
102
+ const root = createRoot(container);
103
+ roots.push(root);
104
+ await render(root, FontdueProvider, options);
105
+ return root;
106
+ }
107
+ async function render(root, FontdueProvider) {
108
+ let {
109
+ strict = true,
110
+ config = {}
111
+ } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
112
+ const tree = /*#__PURE__*/React.createElement(FontdueProvider, {
113
+ url: API,
114
+ config: config
115
+ }, null);
116
+ await act(async () => {
117
+ root.render(strict ? /*#__PURE__*/React.createElement(StrictMode, null, tree) : tree);
118
+ });
119
+ await settle();
120
+ }
121
+ async function unmount(root) {
122
+ await act(async () => {
123
+ root.unmount();
124
+ });
125
+ roots = roots.filter(r => r !== root);
126
+ }
127
+
128
+ /** A router navigation: push the new URL, then rewrite the entry in place. */
129
+ async function navigate(path) {
130
+ await act(async () => {
131
+ history.pushState({}, '', `${ORIGIN}${path}`);
132
+ // Next's App Router rewrites the current entry with its own state after
133
+ // committing a navigation (and on every later tree update).
134
+ history.replaceState({
135
+ __NA: true
136
+ }, '', `${ORIGIN}${path}`);
137
+ });
138
+ await settle();
139
+ }
140
+
141
+ /** Back/forward: the browser moves the URL, then fires popstate. */
142
+ async function popstate(path) {
143
+ await act(async () => {
144
+ originalReplaceState.call(history, {}, '', `${ORIGIN}${path}`);
145
+ window.dispatchEvent(new PopStateEvent('popstate'));
146
+ });
147
+ await settle();
148
+ }
149
+
150
+ // Transform the lazily imported Tracking module up front, so the first test's
151
+ // mount doesn't outlast `settle` while it compiles.
152
+ beforeAll(async () => {
153
+ await import('../components/Tracking/index.js');
154
+ });
155
+ beforeEach(() => {
156
+ vi.resetModules();
157
+ serverTracking.enabled = true;
158
+ serverTracking.consentRequired = false;
159
+ query.pending = null;
160
+ document.cookie = '_fontdue_cc=; max-age=0; path=/';
161
+ fetchMock = vi.fn(async () => ({
162
+ json: async () => ({
163
+ anonymous_id: 'anon-1'
164
+ })
165
+ }));
166
+ vi.stubGlobal('fetch', fetchMock);
167
+ originalReplaceState = History.prototype.replaceState;
168
+ originalReplaceState.call(history, {}, '', `${ORIGIN}/?gclid=abc`);
169
+ });
170
+ afterEach(async () => {
171
+ for (const root of [...roots]) await unmount(root);
172
+ // Drop any wrapper a tracker left on the instance, so the next test starts
173
+ // from the prototype's methods.
174
+ delete history.pushState;
175
+ delete history.replaceState;
176
+ vi.unstubAllGlobals();
177
+ });
178
+ describe('page views through FontdueProvider', () => {
179
+ it('sends one entry page view under StrictMode', async () => {
180
+ const FontdueProvider = await loadProvider();
181
+ await mount(FontdueProvider);
182
+ expect(pageViews()).toEqual(['/']);
183
+ });
184
+ it('ignores the router rewriting the entry URL in place', async () => {
185
+ const FontdueProvider = await loadProvider();
186
+ await mount(FontdueProvider);
187
+ await act(async () => {
188
+ history.replaceState({
189
+ __NA: true
190
+ }, '', window.location.href);
191
+ });
192
+ await settle();
193
+ expect(pageViews()).toEqual(['/']);
194
+ });
195
+ it('sends one page view per client-side navigation, back and forward included', async () => {
196
+ const FontdueProvider = await loadProvider();
197
+ await mount(FontdueProvider);
198
+ await navigate('/typefaces/boxal');
199
+ await navigate('/test-fonts');
200
+ await popstate('/typefaces/boxal');
201
+ expect(pageViews()).toEqual(['/', '/typefaces/boxal', '/test-fonts', '/typefaces/boxal']);
202
+ });
203
+ it('counts a return to the entry page after navigating away', async () => {
204
+ const FontdueProvider = await loadProvider();
205
+ await mount(FontdueProvider);
206
+ await navigate('/typefaces/boxal');
207
+ await navigate('/');
208
+ expect(pageViews()).toEqual(['/', '/typefaces/boxal', '/']);
209
+ });
210
+ it('does not count the entry again when the provider remounts on the same page', async () => {
211
+ // A remount – a Suspense or Activity boundary revealing the provider again,
212
+ // a parent changing its key – is not a new page view.
213
+ const FontdueProvider = await loadProvider();
214
+ const root = await mount(FontdueProvider);
215
+ await unmount(root);
216
+ await mount(FontdueProvider);
217
+ expect(pageViews()).toEqual(['/']);
218
+ });
219
+ it('does not count the entry again when the provider query suspends again', async () => {
220
+ // Tracking is lazy-loaded inside the provider's Suspense boundary. A
221
+ // re-render that suspends again hides the committed tree behind the
222
+ // fallback until the data arrives; that must not read as a new entry.
223
+ const FontdueProvider = await loadProvider();
224
+ const root = await mount(FontdueProvider);
225
+ let resolve;
226
+ query.pending = new Promise(r => resolve = r);
227
+ await render(root, FontdueProvider, {
228
+ config: {
229
+ typeTester: {}
230
+ }
231
+ });
232
+ query.pending = null;
233
+ await act(async () => resolve());
234
+ await settle();
235
+ expect(pageViews()).toEqual(['/']);
236
+ });
237
+ it('counts a navigation once when the provider remounts with it', async () => {
238
+ // A provider rendered by a page rather than the layout unmounts and mounts
239
+ // again with the navigation that replaces the page, while the history
240
+ // write that announced it is still waiting to be checked.
241
+ const FontdueProvider = await loadProvider();
242
+ const root = await mount(FontdueProvider, {
243
+ strict: false
244
+ });
245
+ await act(async () => {
246
+ history.pushState({}, '', `${ORIGIN}/typefaces/boxal`);
247
+ root.unmount();
248
+ });
249
+ roots = roots.filter(r => r !== root);
250
+ await mount(FontdueProvider, {
251
+ strict: false
252
+ });
253
+ expect(pageViews()).toEqual(['/', '/typefaces/boxal']);
254
+ });
255
+ it('counts each view once with two providers on the page', async () => {
256
+ const FontdueProvider = await loadProvider();
257
+ await mount(FontdueProvider);
258
+ await mount(FontdueProvider);
259
+ await navigate('/typefaces/boxal');
260
+ expect(pageViews()).toEqual(['/', '/typefaces/boxal']);
261
+ });
262
+ it('keeps tracking the next navigation after one of two providers unmounts', async () => {
263
+ const FontdueProvider = await loadProvider();
264
+ const first = await mount(FontdueProvider);
265
+ await mount(FontdueProvider);
266
+ await unmount(first);
267
+ await navigate('/typefaces/boxal');
268
+ expect(pageViews()).toEqual(['/', '/typefaces/boxal']);
269
+ });
270
+ it('stops tracking navigation once every provider has unmounted', async () => {
271
+ const FontdueProvider = await loadProvider();
272
+ const root = await mount(FontdueProvider);
273
+ await unmount(root);
274
+ await navigate('/typefaces/boxal');
275
+ expect(pageViews()).toEqual(['/']);
276
+ });
277
+ it('sends one cookieless entry view with one client anonymous id under StrictMode', async () => {
278
+ var _consent$getEntryAttr;
279
+ serverTracking.consentRequired = true;
280
+ const FontdueProvider = await loadProvider();
281
+ await mount(FontdueProvider);
282
+ const entryBodies = fetchMock.mock.calls.filter(_ref3 => {
283
+ let [url] = _ref3;
284
+ return String(url).endsWith('/api/track/page');
285
+ }).map(_ref4 => {
286
+ let [, init] = _ref4;
287
+ return JSON.parse(init.body);
288
+ });
289
+ expect(entryBodies).toHaveLength(1);
290
+ const consent = await import('../components/ConsentBanner/consent.js');
291
+ expect(entryBodies[0].anonymous_id).toBe(consent.getClientAnonymousId());
292
+ expect((_consent$getEntryAttr = consent.getEntryAttribution()) === null || _consent$getEntryAttr === void 0 ? void 0 : _consent$getEntryAttr.properties.path).toBe('/');
293
+ });
294
+ });
295
+ describe('the Segment SDK page call for the entry', () => {
296
+ function segmentStub() {
297
+ const analytics = {
298
+ setAnonymousId: vi.fn(async () => {}),
299
+ page: vi.fn(async () => {})
300
+ };
301
+ const load = vi.fn(() => analytics);
302
+ return {
303
+ analytics,
304
+ load,
305
+ config: {
306
+ tracking: {
307
+ segment: {
308
+ analytics: load
309
+ }
310
+ }
311
+ }
312
+ };
313
+ }
314
+ it('goes out once under StrictMode', async () => {
315
+ const segment = segmentStub();
316
+ const FontdueProvider = await loadProvider();
317
+ await mount(FontdueProvider, {
318
+ config: segment.config
319
+ });
320
+ expect(segment.load).toHaveBeenCalledTimes(1);
321
+ expect(segment.analytics.page).toHaveBeenCalledTimes(1);
322
+ expect(segment.analytics.setAnonymousId).toHaveBeenCalledWith('anon-1');
323
+ });
324
+ it('goes out once when consent is granted after a StrictMode mount', async () => {
325
+ serverTracking.consentRequired = true;
326
+ const segment = segmentStub();
327
+ const FontdueProvider = await loadProvider();
328
+ await mount(FontdueProvider, {
329
+ config: segment.config
330
+ });
331
+ expect(segment.analytics.page).not.toHaveBeenCalled();
332
+ const consent = await import('../components/ConsentBanner/consent.js');
333
+ await act(async () => {
334
+ consent.setConsent(['analytics']);
335
+ });
336
+ await settle();
337
+ expect(segment.analytics.page).toHaveBeenCalledTimes(1);
338
+ });
339
+ });
@@ -6,6 +6,7 @@ import { trackRouteChanges } from '../components/Tracking/routeChanges.js';
6
6
  // synchronously so each call's effect can be asserted in order.
7
7
  function setup() {
8
8
  let startUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'https://foundry.test/fonts';
9
+ let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
9
10
  let url = startUrl;
10
11
  const listeners = {};
11
12
  const history = {
@@ -26,9 +27,10 @@ function setup() {
26
27
  window: windowLike,
27
28
  currentUrl: () => url,
28
29
  onNavigate,
29
- defer: callback => {
30
+ defer: options.defer ?? (callback => {
30
31
  callback();
31
- }
32
+ }),
33
+ claim: options.claim
32
34
  });
33
35
  return {
34
36
  history,
@@ -107,4 +109,48 @@ describe('trackRouteChanges', () => {
107
109
  t.navigate('https://foundry.test/cart');
108
110
  expect(t.onNavigate).not.toHaveBeenCalled();
109
111
  });
112
+ it('drops a check still pending when cleanup runs', () => {
113
+ // A provider can unmount in the same commit as the navigation it was told
114
+ // about; its deferred check must not report that navigation afterwards.
115
+ const pending = [];
116
+ const t = setup('https://foundry.test/fonts', {
117
+ defer: callback => pending.push(callback)
118
+ });
119
+ t.navigate('https://foundry.test/cart');
120
+ t.cleanup();
121
+ pending.forEach(callback => callback());
122
+ expect(t.onNavigate).not.toHaveBeenCalled();
123
+ });
124
+ it('leaves a wrapper added after its own in place on cleanup', () => {
125
+ const t = setup();
126
+ const ours = t.history.pushState;
127
+ const laterWrapper = vi.fn(function () {
128
+ return ours(...arguments);
129
+ });
130
+ t.history.pushState = laterWrapper;
131
+ t.cleanup();
132
+
133
+ // Restoring the original would silently unhook whoever wrapped us.
134
+ expect(t.history.pushState).toBe(laterWrapper);
135
+ t.navigate('https://foundry.test/cart');
136
+ expect(laterWrapper).toHaveBeenCalledTimes(1);
137
+ expect(t.onNavigate).not.toHaveBeenCalled();
138
+ });
139
+ it('asks a shared claim whether each URL is new', () => {
140
+ // The Tracking component shares one claim across every watcher and the
141
+ // entry page view, so a URL another one already reported isn't repeated.
142
+ const claimed = new Set(['https://foundry.test/fonts', 'https://foundry.test/cart']);
143
+ const claim = vi.fn(url => {
144
+ if (claimed.has(url)) return false;
145
+ claimed.add(url);
146
+ return true;
147
+ });
148
+ const t = setup('https://foundry.test/fonts', {
149
+ claim
150
+ });
151
+ t.navigate('https://foundry.test/cart');
152
+ t.navigate('https://foundry.test/about');
153
+ expect(claim).toHaveBeenCalledWith('https://foundry.test/cart');
154
+ expect(t.onNavigate).toHaveBeenCalledTimes(1);
155
+ });
110
156
  });
@@ -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 {};
@@ -17,16 +17,20 @@ export function trackRouteChanges(_ref) {
17
17
  window: windowLike,
18
18
  currentUrl,
19
19
  onNavigate,
20
+ claim = lastUrlClaim(currentUrl()),
20
21
  defer = callback => {
21
22
  setTimeout(callback, 0);
22
23
  }
23
24
  } = _ref;
24
- // The caller has already reported the URL we start on, so it is the first
25
- // thing we compare against.
26
- let lastUrl = currentUrl();
25
+ // Set on cleanup. A check deferred before then must not fire afterwards: a
26
+ // provider that unmounts with the navigation it announced would otherwise
27
+ // report it from beyond the grave while its replacement reports it too.
28
+ let stopped = false;
27
29
  const handleRouteChange = () => {
30
+ if (stopped) return;
28
31
  // Defer slightly to let document.title update
29
32
  defer(() => {
33
+ if (stopped) return;
30
34
  const url = currentUrl();
31
35
 
32
36
  // A history entry gets rewritten in place for all sorts of reasons that
@@ -38,25 +42,45 @@ export function trackRouteChanges(_ref) {
38
42
  // URL that actually differs from the last one we reported can be a new
39
43
  // page view. Note this compares against the *previous* URL rather than
40
44
  // every URL seen, so A → B → A is three page views, as it should be.
41
- if (url === lastUrl) return;
42
- lastUrl = url;
45
+ if (!claim(url)) return;
43
46
  onNavigate();
44
47
  });
45
48
  };
46
49
  const originalPushState = history.pushState.bind(history);
47
50
  const originalReplaceState = history.replaceState.bind(history);
48
- history.pushState = function () {
51
+ const wrappedPushState = function () {
49
52
  originalPushState(...arguments);
50
53
  handleRouteChange();
51
54
  };
52
- history.replaceState = function () {
55
+ const wrappedReplaceState = function () {
53
56
  originalReplaceState(...arguments);
54
57
  handleRouteChange();
55
58
  };
59
+ history.pushState = wrappedPushState;
60
+ history.replaceState = wrappedReplaceState;
56
61
  windowLike.addEventListener('popstate', handleRouteChange);
57
62
  return () => {
58
- history.pushState = originalPushState;
59
- history.replaceState = originalReplaceState;
63
+ stopped = true;
64
+ // Put the originals back only while our wrappers are still the outermost.
65
+ // If something wrapped history after us (a router patching it, say),
66
+ // restoring would silently remove its wrapper too; ours stays in its chain
67
+ // instead, passing calls straight through now that it is stopped.
68
+ if (history.pushState === wrappedPushState) history.pushState = originalPushState;
69
+ if (history.replaceState === wrappedReplaceState) {
70
+ history.replaceState = originalReplaceState;
71
+ }
60
72
  windowLike.removeEventListener('popstate', handleRouteChange);
61
73
  };
74
+ }
75
+
76
+ // The default `claim`: a URL is new when it differs from the last one claimed.
77
+ // The caller has already reported the URL we start on, so it is the first thing
78
+ // we compare against.
79
+ function lastUrlClaim(startUrl) {
80
+ let lastUrl = startUrl;
81
+ return url => {
82
+ if (url === lastUrl) return false;
83
+ lastUrl = url;
84
+ return true;
85
+ };
62
86
  }
package/dist/i18n/de.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // exactly the English keys: a missing or extra key fails `npm run build-ts`.
3
3
  //
4
4
  // Glossary – keep these consistent across the catalogue:
5
- // cart → Warenkorb; checkout → Kasse (button: „Zur Kasse“)
5
+ // cart → Warenkorb; checkout → Checkout (button to payment: „Weiter zur Zahlung“)
6
6
  // order → Bestellung; add to cart → „In den Warenkorb“
7
7
  // license → Lizenz; licensee → Lizenznehmer
8
8
  // style → Schnitt (Schnitte); font → Font (Fonts)
@@ -54,7 +54,7 @@ const de = {
54
54
  // TODO(proofread): the index of every typeface; „Alle Kollektionen“ is the literal.
55
55
  'storeModal.allCollections': 'Alle Schriften',
56
56
  'storeModal.buyingOptions': 'Kaufoptionen',
57
- 'storeModal.checkout': 'Kasse',
57
+ 'storeModal.checkout': 'Checkout',
58
58
  'storeModal.review': 'Überprüfen',
59
59
  // Follows the family's name: „Helvetica Familie“.
60
60
  // TODO(proofread): or hyphenated („Helvetica-Familie“), which the code can't do yet.
@@ -96,7 +96,7 @@ const de = {
96
96
  // to say plainly that the order costs money.
97
97
  'cart.submitPayment': 'Zahlungspflichtig bestellen',
98
98
  'cart.proceed': 'Weiter',
99
- 'cart.proceedToCheckout': 'Weiter zur Kasse',
99
+ 'cart.proceedToCheckout': 'Weiter zum Checkout',
100
100
  'cart.paymentRetry': 'Ihre Zahlung konnte nicht abgeschlossen werden. Bitte geben Sie Ihre Kartendaten erneut ein und versuchen Sie es noch einmal.',
101
101
  'cart.subtotal': 'Zwischensumme',
102
102
  'cart.discountApplied': 'Rabatt',
@@ -105,7 +105,7 @@ const de = {
105
105
  'cart.vat': 'USt.',
106
106
  'cart.taxNotApplicable': '{tax} entfällt',
107
107
  'cart.tax': 'Steuer',
108
- 'cart.calculatedAtCheckout': 'Wird an der Kasse berechnet',
108
+ 'cart.calculatedAtCheckout': 'Wird im Checkout berechnet',
109
109
  'cart.total': 'Gesamt',
110
110
  'cart.totalIncludingGst': 'Gesamt inkl. GST',
111
111
  'cart.empty': 'Ihr Warenkorb ist leer',
@@ -148,7 +148,7 @@ const de = {
148
148
  'checkout.paymentFailed': 'Die Zahlung ist fehlgeschlagen. Bitte versuchen Sie es mit einer anderen Zahlungsart.',
149
149
  'checkout.save': 'Speichern',
150
150
  'checkout.continue': 'Weiter',
151
- 'checkout.checkout': 'Zur Kasse',
151
+ 'checkout.checkout': 'Weiter zur Zahlung',
152
152
  'checkout.licenseeSelf': 'Sie selbst',
153
153
  // TODO(proofread): „Ihr Kunde“ is the masculine generic; „Ihre Kundschaft“ or
154
154
  // „Auftraggeber*in“ if the foundry prefers.
package/dist/version.js CHANGED
@@ -8,4 +8,4 @@
8
8
  // (Fontage.ClientVersions) to spot sites that need to upgrade before a
9
9
  // feature that depends on a newer client can work for them.
10
10
  export const CLIENT_VERSION_HEADER = 'fontdue-client-version';
11
- export const version = "3.15.0";
11
+ export const version = "3.15.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fontdue-js",
3
- "version": "3.15.0",
3
+ "version": "3.15.1",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "build": "npm run relay && run-p build-js build-css build-ts",