fontdue-js 3.15.0-beta.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,17 @@
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
+
6
+ ## 3.15.0
7
+
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.
9
+ - Added `returnUrl` and `returnLabel` to the `storeModal` config. The order page buyers land on after paying links back to that URL instead of the foundry’s site, as long as it’s on one of the store’s allowed origins.
10
+ - Added `collapse` and `loadMoreLabel` to `CharacterViewer`. `collapse` shows only the first character group, or the grid cut to a given height, with a *Load more* button underneath.
11
+ - `StoreModal`, the font families list and `TypeTester`’s select button leave out styles set to *Unlisted*. A type tester still shows an unlisted style, without a select button.
12
+ - Fixed removing the last item a coupon applies to, or emptying a cart with a coupon on it, doing nothing in the `StoreModal` cart. The coupon now comes off with the item and the cart shows a notice saying so.
13
+ - Fixed `CharacterViewer` and the `StoreModal` breaking on a superfamily whose families are all hidden.
14
+
1
15
  ## 3.14.0
2
16
 
3
17
  - `StoreModal` puts two bundles on one row when the second directly follows the first and repeats its name plus a suffix, such as *Thin* and *Thin Italic*.
@@ -1,10 +1,13 @@
1
1
  /**
2
- * @generated SignedSource<<9e2fb92d3b6dbb2988837d16a6e95d8e>>
2
+ * @generated SignedSource<<1366f7e8c1c4f057f72ce4366915ef52>>
3
3
  * @lightSyntaxTransform
4
4
  * @nogrep
5
5
  */
6
6
  import { ConcreteRequest } from 'relay-runtime';
7
- export type StripeProviderCreateCheckoutSessionMutation$variables = Record<PropertyKey, never>;
7
+ export type StripeProviderCreateCheckoutSessionMutation$variables = {
8
+ returnLabel?: string | null;
9
+ returnUrl?: string | null;
10
+ };
8
11
  export type StripeProviderCreateCheckoutSessionMutation$data = {
9
12
  readonly createOrderCheckoutSession: {
10
13
  readonly order: {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @generated SignedSource<<9e2fb92d3b6dbb2988837d16a6e95d8e>>
2
+ * @generated SignedSource<<1366f7e8c1c4f057f72ce4366915ef52>>
3
3
  * @lightSyntaxTransform
4
4
  * @nogrep
5
5
  */
@@ -10,30 +10,49 @@
10
10
 
11
11
  const node = function () {
12
12
  var v0 = {
13
- "alias": null,
14
- "args": null,
15
- "concreteType": "StripeCheckoutSession",
16
- "kind": "LinkedField",
17
- "name": "stripeCheckoutSession",
18
- "plural": false,
19
- "selections": [{
13
+ "defaultValue": null,
14
+ "kind": "LocalArgument",
15
+ "name": "returnLabel"
16
+ },
17
+ v1 = {
18
+ "defaultValue": null,
19
+ "kind": "LocalArgument",
20
+ "name": "returnUrl"
21
+ },
22
+ v2 = [{
23
+ "kind": "Variable",
24
+ "name": "returnLabel",
25
+ "variableName": "returnLabel"
26
+ }, {
27
+ "kind": "Variable",
28
+ "name": "returnUrl",
29
+ "variableName": "returnUrl"
30
+ }],
31
+ v3 = {
20
32
  "alias": null,
21
33
  "args": null,
22
- "kind": "ScalarField",
23
- "name": "clientSecret",
34
+ "concreteType": "StripeCheckoutSession",
35
+ "kind": "LinkedField",
36
+ "name": "stripeCheckoutSession",
37
+ "plural": false,
38
+ "selections": [{
39
+ "alias": null,
40
+ "args": null,
41
+ "kind": "ScalarField",
42
+ "name": "clientSecret",
43
+ "storageKey": null
44
+ }],
24
45
  "storageKey": null
25
- }],
26
- "storageKey": null
27
- };
46
+ };
28
47
  return {
29
48
  "fragment": {
30
- "argumentDefinitions": [],
49
+ "argumentDefinitions": [v0 /*: any*/, v1 /*: any*/],
31
50
  "kind": "Fragment",
32
51
  "metadata": null,
33
52
  "name": "StripeProviderCreateCheckoutSessionMutation",
34
53
  "selections": [{
35
54
  "alias": null,
36
- "args": null,
55
+ "args": v2 /*: any*/,
37
56
  "concreteType": "CreateOrderCheckoutSessionPayload",
38
57
  "kind": "LinkedField",
39
58
  "name": "createOrderCheckoutSession",
@@ -45,7 +64,7 @@ const node = function () {
45
64
  "kind": "LinkedField",
46
65
  "name": "order",
47
66
  "plural": false,
48
- "selections": [v0 /*: any*/],
67
+ "selections": [v3 /*: any*/],
49
68
  "storageKey": null
50
69
  }],
51
70
  "storageKey": null
@@ -55,12 +74,12 @@ const node = function () {
55
74
  },
56
75
  "kind": "Request",
57
76
  "operation": {
58
- "argumentDefinitions": [],
77
+ "argumentDefinitions": [v1 /*: any*/, v0 /*: any*/],
59
78
  "kind": "Operation",
60
79
  "name": "StripeProviderCreateCheckoutSessionMutation",
61
80
  "selections": [{
62
81
  "alias": null,
63
- "args": null,
82
+ "args": v2 /*: any*/,
64
83
  "concreteType": "CreateOrderCheckoutSessionPayload",
65
84
  "kind": "LinkedField",
66
85
  "name": "createOrderCheckoutSession",
@@ -72,7 +91,7 @@ const node = function () {
72
91
  "kind": "LinkedField",
73
92
  "name": "order",
74
93
  "plural": false,
75
- "selections": [v0 /*: any*/, {
94
+ "selections": [v3 /*: any*/, {
76
95
  "alias": null,
77
96
  "args": null,
78
97
  "kind": "ScalarField",
@@ -85,14 +104,14 @@ const node = function () {
85
104
  }]
86
105
  },
87
106
  "params": {
88
- "cacheID": "0ece78edfb78a66584361cee7d83e6a2",
107
+ "cacheID": "694e81728d2fe3f137af118dc09961ca",
89
108
  "id": null,
90
109
  "metadata": {},
91
110
  "name": "StripeProviderCreateCheckoutSessionMutation",
92
111
  "operationKind": "mutation",
93
- "text": "mutation StripeProviderCreateCheckoutSessionMutation {\n createOrderCheckoutSession {\n order {\n stripeCheckoutSession {\n clientSecret\n }\n id\n }\n }\n}\n"
112
+ "text": "mutation StripeProviderCreateCheckoutSessionMutation(\n $returnUrl: String\n $returnLabel: String\n) {\n createOrderCheckoutSession(returnUrl: $returnUrl, returnLabel: $returnLabel) {\n order {\n stripeCheckoutSession {\n clientSecret\n }\n id\n }\n }\n}\n"
94
113
  }
95
114
  };
96
115
  }();
97
- node.hash = "2ca9a7fcfed1292117e3cd6d0d95cca6";
116
+ node.hash = "182092b555f884405afb61050ed98b79";
98
117
  export default node;
@@ -0,0 +1,66 @@
1
+ // `storeModal.returnUrl` as checkout hands it to the order page that payment
2
+ // returns to, for that page's link back.
3
+
4
+ import { describe, expect, it } from 'vitest';
5
+ import { checkoutReturnParams, withCheckoutReturn } from '../components/Cart/checkoutReturn.js';
6
+ const page = 'https://ornaments.example.com/draw?tool=box';
7
+ const completeUrl = 'https://store.example.com/orders/1';
8
+ describe('checkoutReturnParams', () => {
9
+ it('is null when the site sets no return URL', () => {
10
+ expect(checkoutReturnParams(undefined, page)).toEqual({
11
+ returnUrl: null,
12
+ returnLabel: null
13
+ });
14
+ expect(checkoutReturnParams({
15
+ returnLabel: 'Back'
16
+ }, page)).toEqual({
17
+ returnUrl: null,
18
+ returnLabel: null
19
+ });
20
+ });
21
+ it('keeps an absolute URL as given, with its label', () => {
22
+ expect(checkoutReturnParams({
23
+ returnUrl: 'https://ornaments.example.com/',
24
+ returnLabel: 'Back to Ornaments'
25
+ }, page)).toEqual({
26
+ returnUrl: 'https://ornaments.example.com/',
27
+ returnLabel: 'Back to Ornaments'
28
+ });
29
+ });
30
+ it('resolves a relative URL against the page the store modal is on', () => {
31
+ expect(checkoutReturnParams({
32
+ returnUrl: '/'
33
+ }, page)).toEqual({
34
+ returnUrl: 'https://ornaments.example.com/',
35
+ returnLabel: null
36
+ });
37
+ expect(checkoutReturnParams({
38
+ returnUrl: '?from=checkout'
39
+ }, page).returnUrl).toBe('https://ornaments.example.com/draw?from=checkout');
40
+ });
41
+ it('is null rather than throwing for a value that is no URL', () => {
42
+ expect(checkoutReturnParams({
43
+ returnUrl: 'http://[bad'
44
+ }, page).returnUrl).toBeNull();
45
+ });
46
+ });
47
+ describe('withCheckoutReturn', () => {
48
+ it('leaves the order page URL alone when the site sets no return URL', () => {
49
+ expect(withCheckoutReturn(completeUrl, undefined, page)).toBe(completeUrl);
50
+ });
51
+ it('carries the return URL and label as query parameters', () => {
52
+ const url = new URL(withCheckoutReturn(completeUrl, {
53
+ returnUrl: '/?purchased=1',
54
+ returnLabel: 'Back to Ornaments'
55
+ }, page));
56
+ expect(url.origin + url.pathname).toBe(completeUrl);
57
+ expect(url.searchParams.get('return_url')).toBe('https://ornaments.example.com/?purchased=1');
58
+ expect(url.searchParams.get('return_label')).toBe('Back to Ornaments');
59
+ });
60
+ it('omits the label when the site sets none', () => {
61
+ const url = new URL(withCheckoutReturn(completeUrl, {
62
+ returnUrl: '/'
63
+ }, page));
64
+ expect(url.searchParams.has('return_label')).toBe(false);
65
+ });
66
+ });
@@ -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
  });
@@ -0,0 +1,17 @@
1
+ import { StoreModalConfig } from '../StoreModal/types.js';
2
+ type ReturnConfig = Pick<StoreModalConfig, 'returnUrl' | 'returnLabel'> | undefined;
3
+ /**
4
+ * `storeModal.returnUrl` as the server takes it: absolute, resolved against
5
+ * the page the store modal is on, or null when the site sets none.
6
+ */
7
+ export declare function checkoutReturnParams(config: ReturnConfig, pageUrl: string): {
8
+ returnUrl: string | null;
9
+ returnLabel: string | null;
10
+ };
11
+ /**
12
+ * The order page URL payment returns to, carrying where that page's link back
13
+ * should go (`return_url`, `return_label`). The server ignores a URL that
14
+ * isn't on the store's allowed origins and links to the foundry's site.
15
+ */
16
+ export declare function withCheckoutReturn(completeUrl: string, config: ReturnConfig, pageUrl: string): string;
17
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `storeModal.returnUrl` as the server takes it: absolute, resolved against
3
+ * the page the store modal is on, or null when the site sets none.
4
+ */
5
+ export function checkoutReturnParams(config, pageUrl) {
6
+ if (!(config !== null && config !== void 0 && config.returnUrl)) return {
7
+ returnUrl: null,
8
+ returnLabel: null
9
+ };
10
+ try {
11
+ return {
12
+ returnUrl: new URL(config.returnUrl, pageUrl).href,
13
+ returnLabel: config.returnLabel ?? null
14
+ };
15
+ } catch {
16
+ return {
17
+ returnUrl: null,
18
+ returnLabel: null
19
+ };
20
+ }
21
+ }
22
+
23
+ /**
24
+ * The order page URL payment returns to, carrying where that page's link back
25
+ * should go (`return_url`, `return_label`). The server ignores a URL that
26
+ * isn't on the store's allowed origins and links to the foundry's site.
27
+ */
28
+ export function withCheckoutReturn(completeUrl, config, pageUrl) {
29
+ const {
30
+ returnUrl,
31
+ returnLabel
32
+ } = checkoutReturnParams(config, pageUrl);
33
+ if (!returnUrl) return completeUrl;
34
+ const url = new URL(completeUrl);
35
+ url.searchParams.set('return_url', returnUrl);
36
+ if (returnLabel) url.searchParams.set('return_label', returnLabel);
37
+ return url.href;
38
+ }
@@ -110,6 +110,8 @@ export declare const makeConfig: (config?: Config) => {
110
110
  indexExcludeTags: string[] | undefined;
111
111
  productLicensesPosition: "bottom" | "top";
112
112
  hideAllCollections: boolean;
113
+ returnUrl: string | undefined;
114
+ returnLabel: string | undefined;
113
115
  };
114
116
  stripe: {
115
117
  appearance: Appearance | null;
@@ -192,6 +194,8 @@ declare const _default: React.Context<{
192
194
  indexExcludeTags: string[] | undefined;
193
195
  productLicensesPosition: "bottom" | "top";
194
196
  hideAllCollections: boolean;
197
+ returnUrl: string | undefined;
198
+ returnLabel: string | undefined;
195
199
  };
196
200
  stripe: {
197
201
  appearance: Appearance | null;
@@ -91,7 +91,7 @@ export const mergeConfig = (base, override) => {
91
91
  return deepMerge(base, override);
92
92
  };
93
93
  export const makeConfig = config => {
94
- var _config$form, _config$testFonts, _config$testFonts2, _config$storeModal, _config$storeModal2, _config$storeModal3, _config$storeModal4, _config$stripe, _config$tracking, _config$tracking2, _config$tracking3, _config$tracking4, _config$preview, _config$preview2, _config$preview3;
94
+ var _config$form, _config$testFonts, _config$testFonts2, _config$storeModal, _config$storeModal2, _config$storeModal3, _config$storeModal4, _config$storeModal5, _config$storeModal6, _config$stripe, _config$tracking, _config$tracking2, _config$tracking3, _config$tracking4, _config$preview, _config$preview2, _config$preview3;
95
95
  return {
96
96
  typeTester: makeTypeTesterConfig(config === null || config === void 0 ? void 0 : config.typeTester),
97
97
  form: {
@@ -108,7 +108,9 @@ export const makeConfig = config => {
108
108
  indexLayout: (config === null || config === void 0 ? void 0 : (_config$storeModal = config.storeModal) === null || _config$storeModal === void 0 ? void 0 : _config$storeModal.indexLayout) ?? 'styled-aa',
109
109
  indexExcludeTags: config === null || config === void 0 ? void 0 : (_config$storeModal2 = config.storeModal) === null || _config$storeModal2 === void 0 ? void 0 : _config$storeModal2.indexExcludeTags,
110
110
  productLicensesPosition: (config === null || config === void 0 ? void 0 : (_config$storeModal3 = config.storeModal) === null || _config$storeModal3 === void 0 ? void 0 : _config$storeModal3.productLicensesPosition) ?? 'top',
111
- hideAllCollections: (config === null || config === void 0 ? void 0 : (_config$storeModal4 = config.storeModal) === null || _config$storeModal4 === void 0 ? void 0 : _config$storeModal4.hideAllCollections) ?? false
111
+ hideAllCollections: (config === null || config === void 0 ? void 0 : (_config$storeModal4 = config.storeModal) === null || _config$storeModal4 === void 0 ? void 0 : _config$storeModal4.hideAllCollections) ?? false,
112
+ returnUrl: config === null || config === void 0 ? void 0 : (_config$storeModal5 = config.storeModal) === null || _config$storeModal5 === void 0 ? void 0 : _config$storeModal5.returnUrl,
113
+ returnLabel: config === null || config === void 0 ? void 0 : (_config$storeModal6 = config.storeModal) === null || _config$storeModal6 === void 0 ? void 0 : _config$storeModal6.returnLabel
112
114
  },
113
115
  stripe: {
114
116
  appearance: (config === null || config === void 0 ? void 0 : (_config$stripe = config.stripe) === null || _config$stripe === void 0 ? void 0 : _config$stripe.appearance) ?? null
@@ -3,4 +3,13 @@ export interface StoreModalConfig {
3
3
  indexExcludeTags?: string[] | undefined;
4
4
  productLicensesPosition?: 'bottom' | 'top';
5
5
  hideAllCollections?: boolean;
6
+ /**
7
+ * Where the order page's link back goes once the buyer has paid, instead of
8
+ * the foundry's site – the page this store modal is embedded in, say.
9
+ * Relative URLs resolve against the current page. Must be on one of the
10
+ * store's allowed origins; anything else is refused.
11
+ */
12
+ returnUrl?: string;
13
+ /** The text of that link. Defaults to "Back to <host>". */
14
+ returnLabel?: string;
6
15
  }
@@ -6,6 +6,7 @@ import { Elements, EmbeddedCheckoutProvider } from '@stripe/react-stripe-js';
6
6
  import { loadStripe } from '@stripe/stripe-js';
7
7
  import { parseCustomProperties } from '../../utils.js';
8
8
  import ConfigContext from '../ConfigContext.js';
9
+ import { checkoutReturnParams } from '../Cart/checkoutReturn.js';
9
10
  import { useLocale } from '../LocaleContext.js';
10
11
  import { stripeElementsLocale } from '../../locale.js';
11
12
  import StoreModalPageContainer from '../elements/StoreModalPageContainer/index.js';
@@ -28,7 +29,8 @@ const StripeProvider = _ref => {
28
29
  // All hooks must be called before any conditional returns (React rules of hooks)
29
30
  const environment = useRelayEnvironment();
30
31
  const {
31
- stripe: config
32
+ stripe: config,
33
+ storeModal: storeModalConfig
32
34
  } = useContext(ConfigContext);
33
35
  const stripeLocale = stripeElementsLocale(useLocale());
34
36
  const [checkoutError, setCheckoutError] = useState(null);
@@ -54,8 +56,10 @@ const StripeProvider = _ref => {
54
56
  const fetchClientSecret = useCallback(() => {
55
57
  return new Promise((resolve, reject) => {
56
58
  commitMutation(environment, {
57
- mutation: (_StripeProviderCreateCheckoutSessionMutation.hash && _StripeProviderCreateCheckoutSessionMutation.hash !== "2ca9a7fcfed1292117e3cd6d0d95cca6" && console.error("The definition of 'StripeProviderCreateCheckoutSessionMutation' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _StripeProviderCreateCheckoutSessionMutation),
58
- variables: {},
59
+ mutation: (_StripeProviderCreateCheckoutSessionMutation.hash && _StripeProviderCreateCheckoutSessionMutation.hash !== "182092b555f884405afb61050ed98b79" && console.error("The definition of 'StripeProviderCreateCheckoutSessionMutation' appears to have changed. Run `relay-compiler` to update the generated files to receive the expected data."), _StripeProviderCreateCheckoutSessionMutation),
60
+ // Stripe returns to the order page; this names where that page's link
61
+ // back goes (`storeModal.returnUrl`).
62
+ variables: checkoutReturnParams(storeModalConfig, window.location.href),
59
63
  onCompleted: (response, errors) => {
60
64
  var _response$createOrder, _response$createOrder2, _response$createOrder3;
61
65
  const clientSecret = (_response$createOrder = response.createOrderCheckoutSession) === null || _response$createOrder === void 0 ? void 0 : (_response$createOrder2 = _response$createOrder.order) === null || _response$createOrder2 === void 0 ? void 0 : (_response$createOrder3 = _response$createOrder2.stripeCheckoutSession) === null || _response$createOrder3 === void 0 ? void 0 : _response$createOrder3.clientSecret;
@@ -76,7 +80,7 @@ const StripeProvider = _ref => {
76
80
  }
77
81
  });
78
82
  });
79
- }, [environment]);
83
+ }, [environment, storeModalConfig === null || storeModalConfig === void 0 ? void 0 : storeModalConfig.returnUrl, storeModalConfig === null || storeModalConfig === void 0 ? void 0 : storeModalConfig.returnLabel]);
80
84
  const options = {
81
85
  appearance: config.appearance ?? {
82
86
  theme: 'flat',
@@ -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
  }
@@ -80,6 +80,7 @@ import { Check, X } from '../Icons/index.js';
80
80
  import ConfigContext from '../ConfigContext.js';
81
81
  import { Price } from '../Price/index.js';
82
82
  import { sendOrderTracking } from '../Cart/orderTracking.js';
83
+ import { withCheckoutReturn } from '../Cart/checkoutReturn.js';
83
84
  import { trackPaymentInfoEntered } from '../Cart/storefrontEvents.js';
84
85
  import { validateAddressElements, validateElements } from '../../stripeElements.js';
85
86
  import { useRecaptchaTimeout, isRecaptchaScriptLoaded } from '../../hooks/useRecaptchaTimeout.js';
@@ -285,6 +286,9 @@ export default function StoreModalUnifiedCheckout(_ref2) {
285
286
  }));
286
287
  }, [setLicenseeIdentity]);
287
288
  const environment = useRelayEnvironment();
289
+ const {
290
+ storeModal: storeModalConfig
291
+ } = useContext(ConfigContext);
288
292
 
289
293
  // Capture analytics consent + attribution on the order for the purchase
290
294
  // event the server emits on completion (from a Stripe webhook, where no
@@ -623,6 +627,9 @@ export default function StoreModalUnifiedCheckout(_ref2) {
623
627
  }
624
628
  setCompleting(true);
625
629
  setError(null);
630
+
631
+ // The order page, told where its link back goes (`storeModal.returnUrl`).
632
+ const completeUrl = withCheckoutReturn(order.completeUrl, storeModalConfig, window.location.href);
626
633
  const processPayment = () => {
627
634
  var _billingIdentity$stre, _billingIdentity$stre2;
628
635
  if (order.canCompleteWithCoupon) {
@@ -635,7 +642,7 @@ export default function StoreModalUnifiedCheckout(_ref2) {
635
642
  setError(errors[0].message);
636
643
  return;
637
644
  }
638
- window.location.href = order.completeUrl;
645
+ window.location.href = completeUrl;
639
646
  }
640
647
  });
641
648
  return;
@@ -644,7 +651,7 @@ export default function StoreModalUnifiedCheckout(_ref2) {
644
651
  stripe === null || stripe === void 0 ? void 0 : stripe.confirmPayment({
645
652
  elements,
646
653
  confirmParams: {
647
- return_url: order.completeUrl,
654
+ return_url: completeUrl,
648
655
  payment_method_data: {
649
656
  billing_details: {
650
657
  email: billingIdentity.email,
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-beta.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-beta.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",