@reykjavik/webtools 0.1.5 → 0.1.7

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
@@ -3,9 +3,19 @@
3
3
  ## Upcoming...
4
4
 
5
5
  - ... <!-- Add new lines here. -->
6
- - feat: Relax the Next.js peerDependency version to include v11
7
6
 
8
- ## 0.1.0 – 0.1.5
7
+ ## 0.1.7
8
+
9
+ _2023-04-19_
10
+
11
+ - `@reykjavik/webtools/next/SiteImprove`:
12
+ - feat: Auto-track outbound link clicks, also for late-injected elements.
13
+ - feat: Add `pingSiteImproveOutbound` helper
14
+ - fix: Strip pageview ref URLs on history back/forward traversal
15
+ - `@reykjavik/webtools/next/http`
16
+ - fix: Make `ErrorProps` accept `HTTP_ERROR_ALL`
17
+
18
+ ## 0.1.0 – 0.1.6
9
19
 
10
20
  _2023-03-24_
11
21
 
package/README.md CHANGED
@@ -29,7 +29,7 @@ yarn add @reykjavik/webtools
29
29
  - [`@reykjavik/webtools/next/SiteImprove`](#reykjavikwebtoolsnextsiteimprove)
30
30
  - [`SiteImprove` component](#siteimprove-component)
31
31
  - [`pingSiteImprove` helper](#pingsiteimprove-helper)
32
- - [Changelog](#changelog)
32
+ - [`pingSiteImproveOutbound` helper](#pingsiteimproveoutbound-helper)
33
33
 
34
34
  <!-- prettier-ignore-start -->
35
35
 
@@ -399,6 +399,8 @@ applications and perform custom event tracking.
399
399
  A component for loading a SiteImprove analytics script and set up page-view
400
400
  tracking across Next.js routes.
401
401
 
402
+ It also automatically logs all out-öbound link clicks.
403
+
402
404
  ```js
403
405
  import { SiteImprove } from '@reykjavik/webtools/next/SiteImprove';
404
406
 
@@ -446,7 +448,26 @@ const handleSubmit = () => {
446
448
  };
447
449
  ```
448
450
 
449
- In dev mode it only logs tracking events to the console.
451
+ ### `pingSiteImproveOutbound` helper
452
+
453
+ **Syntax:** `pingSiteImproveOutbound(ourl: string): void`
454
+
455
+ A small helper for reporting to SiteImrove when the user is programmatically
456
+ being sent to a different URL/resource.
457
+
458
+ ```js
459
+ import { pingSiteImproveOutbound } from '@reykjavik/webtools/next/SiteImprove';
460
+
461
+ const handleSubmit = () => {
462
+ // perform submit action...
463
+ if (success) {
464
+ const fileUrl ='/download/report.pdf'
465
+ pingSiteImproveOutbound(fileUrl);
466
+ document.location.href = fileUrl
467
+ }
468
+ };
469
+
470
+
450
471
 
451
472
  ---
452
473
 
@@ -454,3 +475,4 @@ In dev mode it only logs tracking events to the console.
454
475
 
455
476
  See
456
477
  [CHANGELOG.md](https://github.com/reykjavikcity/webtools/blob/main/CHANGELOG.md)
478
+ ```
@@ -9,21 +9,34 @@ declare global {
9
9
  * just-in-time.
10
10
  */
11
11
  _jit_defined_?: true;
12
+ core?: {
13
+ data: Array<SiteImproveEvent>;
14
+ };
12
15
  };
13
16
  }
14
17
  }
15
- type SiteImproveEvent = SiteImprovePageView | SiteImproveCustomEvent;
18
+ type SiteImproveEvent = SiteImprovePageView | SiteImproveRequest | SiteImproveCustomEvent;
16
19
  type SiteImprovePageView = [
17
20
  type: 'trackdynamic',
18
21
  data: {
19
22
  /** New page URL */
20
23
  url: string;
21
24
  /** The previous (referer) URL */
22
- ref: string;
25
+ ref?: string;
23
26
  /** New page title */
24
27
  title?: string;
25
28
  }
26
29
  ];
30
+ type SiteImproveRequest = [
31
+ type: 'request',
32
+ data: {
33
+ /** Outbound URL */
34
+ ourl: string;
35
+ /** The current page URL */
36
+ ref: string;
37
+ autoonclick?: 1;
38
+ }
39
+ ];
27
40
  type SiteImproveCustomEvent = [
28
41
  type: 'event',
29
42
  category: string,
@@ -78,4 +91,11 @@ export declare const SiteImprove: (props: SiteImproveProps) => JSX.Element | nul
78
91
  * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimprove-helper
79
92
  */
80
93
  export declare const pingSiteImprove: (category: string, action: string, label?: string) => void;
94
+ /**
95
+ * A small helper for reporting to SiteImrove when the user is programmatically
96
+ * being sent to a different URL/resource.
97
+ *
98
+ * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimproveoutbound-helper
99
+ */
100
+ export declare const pingSiteImproveOutbound: (ourl: string) => void;
81
101
  export {};
@@ -1,6 +1,6 @@
1
1
  import React, { useEffect } from 'react';
2
- import { Router } from 'next/router';
3
- import Script from 'next/script';
2
+ import { Router } from 'next/router.js';
3
+ import Script from 'next/script.js';
4
4
  import { useCookieHubConsent } from '../CookieHubConsent.js';
5
5
  // END: Mock typing of SiteImprove's event tracking API
6
6
  // --------------------------------------------------------------------------
@@ -40,11 +40,44 @@ const sendRoutingEvent = (url) => _emitEvent([
40
40
  'trackdynamic',
41
41
  {
42
42
  url,
43
- ref: refUrl,
43
+ // On `history.back()`/`history.forward()` the URL change happens before
44
+ // `routeChangeStart`, so `refUrl` and `url` become the same.
45
+ // in that case we suppress the `ref`
46
+ ref: refUrl !== url ? refUrl : undefined,
44
47
  title: document.title,
45
48
  },
46
49
  ]);
47
50
  // ---------------------------------------------------------------------------
51
+ const logOutboundLinks = () => {
52
+ const captureLinkClicks = (e) => {
53
+ const link = e.target.closest('a[href]');
54
+ if (!link || link.$$bound) {
55
+ return;
56
+ }
57
+ link.$$bound = true;
58
+ // Waiting for the bubble phase allows other click handlers to preventDefault()
59
+ link.addEventListener('click', (e) => {
60
+ var _a, _b;
61
+ if (e.defaultPrevented) {
62
+ return;
63
+ }
64
+ // Skip logging outbound request if SiteImprove has already done so.
65
+ // BTW, SiteImprove binds its autoonclick handlers on "mousedown"
66
+ // so they're guaranteed to have run before our "click" listener.
67
+ const events = (_b = (_a = window._sz) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.data;
68
+ const [type, data] = (events && events[events.length - 1]) || [];
69
+ if (type === 'request' && data.autoonclick && data.ourl === link.href) {
70
+ return;
71
+ }
72
+ pingSiteImproveOutbound(link.href);
73
+ });
74
+ };
75
+ const { body } = document;
76
+ // bind 'click' listener to the capture phase
77
+ body.addEventListener('click', captureLinkClicks, true);
78
+ return () => body.removeEventListener('click', captureLinkClicks, true);
79
+ };
80
+ // ---------------------------------------------------------------------------
48
81
  const idToken = '[ACCOUNT_ID]';
49
82
  const scriptUrlTemplate = `https://siteimproveanalytics.com/js/siteanalyze_${idToken}.js`;
50
83
  /**
@@ -59,25 +92,28 @@ export const SiteImprove = (props) => {
59
92
  (analytics === undefined && props.hasConstented);
60
93
  useEffect(() => {
61
94
  if (consented) {
95
+ if (process.env.NODE_ENV !== 'production') {
96
+ console.info('Mock loading SiteImprove in development mode.', props.scriptUrl || props.accountId);
97
+ if (!window._sz) {
98
+ setTimeout(() => {
99
+ window._sz = window._sz || [];
100
+ }, 300);
101
+ }
102
+ }
62
103
  const routerEvents = Router.events;
63
104
  routerEvents.on('routeChangeStart', captureRefUrl);
64
105
  routerEvents.on('routeChangeComplete', sendRoutingEvent);
106
+ const stopLoggingOutboundLinks = logOutboundLinks();
65
107
  return () => {
66
108
  routerEvents.off('routeChangeStart', captureRefUrl);
67
109
  routerEvents.off('routeChangeComplete', sendRoutingEvent);
110
+ stopLoggingOutboundLinks();
68
111
  };
69
112
  }
70
- }, [consented]);
71
- if (!consented) {
72
- return null;
73
- }
74
- if (process.env.NODE_ENV !== 'production') {
75
- console.info('Mock loading SiteImprove in development mode.');
76
- if (!window._sz) {
77
- setTimeout(() => {
78
- window._sz = window._sz || [];
79
- }, 300);
80
- }
113
+ },
114
+ // eslint-disable-next-line react-hooks/exhaustive-deps
115
+ [consented]);
116
+ if (!consented || process.env.NODE_ENV !== 'production') {
81
117
  return null;
82
118
  }
83
119
  const scriptUrl = props.scriptUrl != null
@@ -94,7 +130,21 @@ export const SiteImprove = (props) => {
94
130
  export const pingSiteImprove = (category, action, label) => {
95
131
  if (process.env.NODE_ENV === 'development' &&
96
132
  (!window._sz || window._sz._jit_defined_)) {
97
- console.warn('`pingSiteImprove` Was called before SiteImprove script was loaded.');
133
+ console.warn('`pingSiteImprove` was called before SiteImprove script was loaded.');
98
134
  }
99
135
  _emitEvent(['event', category, action, label]);
100
136
  };
137
+ // ---------------------------------------------------------------------------
138
+ /**
139
+ * A small helper for reporting to SiteImrove when the user is programmatically
140
+ * being sent to a different URL/resource.
141
+ *
142
+ * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimproveoutbound-helper
143
+ */
144
+ export const pingSiteImproveOutbound = (ourl) => {
145
+ if (process.env.NODE_ENV === 'development' &&
146
+ (!window._sz || window._sz._jit_defined_)) {
147
+ console.warn('`pingSiteImproveOutbound` was called before SiteImprove script was loaded.');
148
+ }
149
+ _emitEvent(['request', { ourl, ref: document.location.href }]);
150
+ };
@@ -2,21 +2,20 @@
2
2
  import React, { FunctionComponent } from 'react';
3
3
  import { Cleanup } from '@reykjavik/hanna-utils';
4
4
  import { ServerResponse } from 'http';
5
- import type { AppType } from 'next/app';
6
- import type { HTTP_418_ImATeapot, HTTP_ERROR, TTLConfig } from '../http.js';
7
- type HTTP_ERROR_all = HTTP_ERROR | typeof HTTP_418_ImATeapot;
5
+ import type { AppType } from 'next/app.js';
6
+ import type { HTTP_ERROR_ALL, TTLConfig } from '../http.js';
8
7
  export * from '../http.js';
9
8
  type NextContextLike = {
10
9
  res: ServerResponse;
11
10
  };
12
11
  export type ErrorProps = {
13
- statusCode: HTTP_ERROR_all;
12
+ statusCode: HTTP_ERROR_ALL;
14
13
  message?: string;
15
14
  };
16
15
  type ErrorizedPageProps<EP extends ErrorProps = ErrorProps> = {
17
16
  __error: ErrorProps;
18
17
  } & Omit<EP, keyof ErrorProps>;
19
- type ShowErrorPageFn<EP extends ErrorProps = ErrorProps> = (response: ServerResponse | NextContextLike, error: (ErrorProps extends EP ? HTTP_ERROR_all : never) | EP,
18
+ type ShowErrorPageFn<EP extends ErrorProps = ErrorProps> = (response: ServerResponse | NextContextLike, error: (ErrorProps extends EP ? HTTP_ERROR_ALL : never) | EP,
20
19
  /** Defaults to `"2s"`. Gets forwarded on to the `cacheControl` helper from `@reykjavik/webtools/http` */
21
20
  ttl?: TTLConfig) => {
22
21
  props: ErrorizedPageProps<EP>;
@@ -9,21 +9,34 @@ declare global {
9
9
  * just-in-time.
10
10
  */
11
11
  _jit_defined_?: true;
12
+ core?: {
13
+ data: Array<SiteImproveEvent>;
14
+ };
12
15
  };
13
16
  }
14
17
  }
15
- type SiteImproveEvent = SiteImprovePageView | SiteImproveCustomEvent;
18
+ type SiteImproveEvent = SiteImprovePageView | SiteImproveRequest | SiteImproveCustomEvent;
16
19
  type SiteImprovePageView = [
17
20
  type: 'trackdynamic',
18
21
  data: {
19
22
  /** New page URL */
20
23
  url: string;
21
24
  /** The previous (referer) URL */
22
- ref: string;
25
+ ref?: string;
23
26
  /** New page title */
24
27
  title?: string;
25
28
  }
26
29
  ];
30
+ type SiteImproveRequest = [
31
+ type: 'request',
32
+ data: {
33
+ /** Outbound URL */
34
+ ourl: string;
35
+ /** The current page URL */
36
+ ref: string;
37
+ autoonclick?: 1;
38
+ }
39
+ ];
27
40
  type SiteImproveCustomEvent = [
28
41
  type: 'event',
29
42
  category: string,
@@ -78,4 +91,11 @@ export declare const SiteImprove: (props: SiteImproveProps) => JSX.Element | nul
78
91
  * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimprove-helper
79
92
  */
80
93
  export declare const pingSiteImprove: (category: string, action: string, label?: string) => void;
94
+ /**
95
+ * A small helper for reporting to SiteImrove when the user is programmatically
96
+ * being sent to a different URL/resource.
97
+ *
98
+ * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimproveoutbound-helper
99
+ */
100
+ export declare const pingSiteImproveOutbound: (ourl: string) => void;
81
101
  export {};
@@ -26,10 +26,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.pingSiteImprove = exports.SiteImprove = void 0;
29
+ exports.pingSiteImproveOutbound = exports.pingSiteImprove = exports.SiteImprove = void 0;
30
30
  const react_1 = __importStar(require("react"));
31
- const router_1 = require("next/router");
32
- const script_1 = __importDefault(require("next/script"));
31
+ const router_js_1 = require("next/router.js");
32
+ const script_js_1 = __importDefault(require("next/script.js"));
33
33
  const CookieHubConsent_js_1 = require("../CookieHubConsent.js");
34
34
  // END: Mock typing of SiteImprove's event tracking API
35
35
  // --------------------------------------------------------------------------
@@ -69,11 +69,44 @@ const sendRoutingEvent = (url) => _emitEvent([
69
69
  'trackdynamic',
70
70
  {
71
71
  url,
72
- ref: refUrl,
72
+ // On `history.back()`/`history.forward()` the URL change happens before
73
+ // `routeChangeStart`, so `refUrl` and `url` become the same.
74
+ // in that case we suppress the `ref`
75
+ ref: refUrl !== url ? refUrl : undefined,
73
76
  title: document.title,
74
77
  },
75
78
  ]);
76
79
  // ---------------------------------------------------------------------------
80
+ const logOutboundLinks = () => {
81
+ const captureLinkClicks = (e) => {
82
+ const link = e.target.closest('a[href]');
83
+ if (!link || link.$$bound) {
84
+ return;
85
+ }
86
+ link.$$bound = true;
87
+ // Waiting for the bubble phase allows other click handlers to preventDefault()
88
+ link.addEventListener('click', (e) => {
89
+ var _a, _b;
90
+ if (e.defaultPrevented) {
91
+ return;
92
+ }
93
+ // Skip logging outbound request if SiteImprove has already done so.
94
+ // BTW, SiteImprove binds its autoonclick handlers on "mousedown"
95
+ // so they're guaranteed to have run before our "click" listener.
96
+ const events = (_b = (_a = window._sz) === null || _a === void 0 ? void 0 : _a.core) === null || _b === void 0 ? void 0 : _b.data;
97
+ const [type, data] = (events && events[events.length - 1]) || [];
98
+ if (type === 'request' && data.autoonclick && data.ourl === link.href) {
99
+ return;
100
+ }
101
+ (0, exports.pingSiteImproveOutbound)(link.href);
102
+ });
103
+ };
104
+ const { body } = document;
105
+ // bind 'click' listener to the capture phase
106
+ body.addEventListener('click', captureLinkClicks, true);
107
+ return () => body.removeEventListener('click', captureLinkClicks, true);
108
+ };
109
+ // ---------------------------------------------------------------------------
77
110
  const idToken = '[ACCOUNT_ID]';
78
111
  const scriptUrlTemplate = `https://siteimproveanalytics.com/js/siteanalyze_${idToken}.js`;
79
112
  /**
@@ -88,31 +121,34 @@ const SiteImprove = (props) => {
88
121
  (analytics === undefined && props.hasConstented);
89
122
  (0, react_1.useEffect)(() => {
90
123
  if (consented) {
91
- const routerEvents = router_1.Router.events;
124
+ if (process.env.NODE_ENV !== 'production') {
125
+ console.info('Mock loading SiteImprove in development mode.', props.scriptUrl || props.accountId);
126
+ if (!window._sz) {
127
+ setTimeout(() => {
128
+ window._sz = window._sz || [];
129
+ }, 300);
130
+ }
131
+ }
132
+ const routerEvents = router_js_1.Router.events;
92
133
  routerEvents.on('routeChangeStart', captureRefUrl);
93
134
  routerEvents.on('routeChangeComplete', sendRoutingEvent);
135
+ const stopLoggingOutboundLinks = logOutboundLinks();
94
136
  return () => {
95
137
  routerEvents.off('routeChangeStart', captureRefUrl);
96
138
  routerEvents.off('routeChangeComplete', sendRoutingEvent);
139
+ stopLoggingOutboundLinks();
97
140
  };
98
141
  }
99
- }, [consented]);
100
- if (!consented) {
101
- return null;
102
- }
103
- if (process.env.NODE_ENV !== 'production') {
104
- console.info('Mock loading SiteImprove in development mode.');
105
- if (!window._sz) {
106
- setTimeout(() => {
107
- window._sz = window._sz || [];
108
- }, 300);
109
- }
142
+ },
143
+ // eslint-disable-next-line react-hooks/exhaustive-deps
144
+ [consented]);
145
+ if (!consented || process.env.NODE_ENV !== 'production') {
110
146
  return null;
111
147
  }
112
148
  const scriptUrl = props.scriptUrl != null
113
149
  ? props.scriptUrl
114
150
  : scriptUrlTemplate.replace(idToken, props.accountId);
115
- return (react_1.default.createElement(script_1.default, { type: "text/javascript", strategy: "afterInteractive", src: scriptUrl, onLoad: props.onLoad, onError: props.onError }));
151
+ return (react_1.default.createElement(script_js_1.default, { type: "text/javascript", strategy: "afterInteractive", src: scriptUrl, onLoad: props.onLoad, onError: props.onError }));
116
152
  };
117
153
  exports.SiteImprove = SiteImprove;
118
154
  // ---------------------------------------------------------------------------
@@ -124,8 +160,23 @@ exports.SiteImprove = SiteImprove;
124
160
  const pingSiteImprove = (category, action, label) => {
125
161
  if (process.env.NODE_ENV === 'development' &&
126
162
  (!window._sz || window._sz._jit_defined_)) {
127
- console.warn('`pingSiteImprove` Was called before SiteImprove script was loaded.');
163
+ console.warn('`pingSiteImprove` was called before SiteImprove script was loaded.');
128
164
  }
129
165
  _emitEvent(['event', category, action, label]);
130
166
  };
131
167
  exports.pingSiteImprove = pingSiteImprove;
168
+ // ---------------------------------------------------------------------------
169
+ /**
170
+ * A small helper for reporting to SiteImrove when the user is programmatically
171
+ * being sent to a different URL/resource.
172
+ *
173
+ * @see https://github.com/reykjavikcity/webtools/tree/v0.1##pingsiteimproveoutbound-helper
174
+ */
175
+ const pingSiteImproveOutbound = (ourl) => {
176
+ if (process.env.NODE_ENV === 'development' &&
177
+ (!window._sz || window._sz._jit_defined_)) {
178
+ console.warn('`pingSiteImproveOutbound` was called before SiteImprove script was loaded.');
179
+ }
180
+ _emitEvent(['request', { ourl, ref: document.location.href }]);
181
+ };
182
+ exports.pingSiteImproveOutbound = pingSiteImproveOutbound;
package/next/http.d.ts CHANGED
@@ -2,21 +2,20 @@
2
2
  import React, { FunctionComponent } from 'react';
3
3
  import { Cleanup } from '@reykjavik/hanna-utils';
4
4
  import { ServerResponse } from 'http';
5
- import type { AppType } from 'next/app';
6
- import type { HTTP_418_ImATeapot, HTTP_ERROR, TTLConfig } from '../http.js';
7
- type HTTP_ERROR_all = HTTP_ERROR | typeof HTTP_418_ImATeapot;
5
+ import type { AppType } from 'next/app.js';
6
+ import type { HTTP_ERROR_ALL, TTLConfig } from '../http.js';
8
7
  export * from '../http.js';
9
8
  type NextContextLike = {
10
9
  res: ServerResponse;
11
10
  };
12
11
  export type ErrorProps = {
13
- statusCode: HTTP_ERROR_all;
12
+ statusCode: HTTP_ERROR_ALL;
14
13
  message?: string;
15
14
  };
16
15
  type ErrorizedPageProps<EP extends ErrorProps = ErrorProps> = {
17
16
  __error: ErrorProps;
18
17
  } & Omit<EP, keyof ErrorProps>;
19
- type ShowErrorPageFn<EP extends ErrorProps = ErrorProps> = (response: ServerResponse | NextContextLike, error: (ErrorProps extends EP ? HTTP_ERROR_all : never) | EP,
18
+ type ShowErrorPageFn<EP extends ErrorProps = ErrorProps> = (response: ServerResponse | NextContextLike, error: (ErrorProps extends EP ? HTTP_ERROR_ALL : never) | EP,
20
19
  /** Defaults to `"2s"`. Gets forwarded on to the `cacheControl` helper from `@reykjavik/webtools/http` */
21
20
  ttl?: TTLConfig) => {
22
21
  props: ErrorizedPageProps<EP>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reykjavik/webtools",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Misc. JS/TS helpers used by Reykjavík City's web dev teams.",
5
5
  "main": "index.js",
6
6
  "repository": "ssh://git@github.com:reykjavikcity/webtools.git",