-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.ts
248 lines (225 loc) · 6.84 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import type {
GtmIdContainer,
GtmQueryParams,
GtmSupportOptions,
LoadScriptOptions,
} from '@gtm-support/core';
import { GtmSupport as GtmPlugin, loadScript } from '@gtm-support/core';
import type { App, Plugin } from 'vue';
import { getCurrentInstance, nextTick } from 'vue';
import type {
ErrorTypes,
NavigationFailure,
RouteLocationNormalized,
Router,
} from 'vue-router';
// eslint-disable-next-line jsdoc/require-jsdoc
type IgnoredViews =
| string[]
| ((to: RouteLocationNormalized, from: RouteLocationNormalized) => boolean);
/**
* Options passed to the plugin.
*/
export interface VueGtmUseOptions extends GtmSupportOptions {
/**
* Pass the router instance to automatically sync with router.
*/
vueRouter?: Router;
/**
* Derive additional event data after navigation.
*/
vueRouterAdditionalEventData?: (
to: RouteLocationNormalized,
from: RouteLocationNormalized,
) => Record<string, any> | Promise<Record<string, any>>;
/**
* Don't trigger events for specified router names.
*/
ignoredViews?: IgnoredViews;
/**
* Whether or not call `trackView` in `Vue.nextTick`.
*/
trackOnNextTick?: boolean;
}
let gtmPlugin: GtmPlugin | undefined;
/**
* Installation procedure.
*
* @param app The Vue app instance.
* @param options Configuration options.
*/
function install(app: App, options: VueGtmUseOptions = { id: '' }): void {
// Apply default configuration
options = { trackOnNextTick: false, ...options };
// Add to vue prototype and also from globals
gtmPlugin = new GtmPlugin(options);
app.config.globalProperties.$gtm = gtmPlugin;
// Check if plugin is running in a real browser or e.g. in SSG mode
if (gtmPlugin.isInBrowserContext()) {
// Handle vue-router if defined
if (options.vueRouter) {
initVueRouterGuard(
app,
options.vueRouter,
options.ignoredViews,
options.trackOnNextTick,
options.vueRouterAdditionalEventData,
);
}
// Load GTM script when enabled
if (gtmPlugin.options.enabled && gtmPlugin.options.loadScript) {
if (Array.isArray(options.id)) {
options.id.forEach((id: string | GtmIdContainer) => {
if (typeof id === 'string') {
loadScript(id, options as LoadScriptOptions);
} else {
const newConf: VueGtmUseOptions = {
...options,
};
if (id.queryParams != null) {
newConf.queryParams = {
...newConf.queryParams,
...id.queryParams,
} as GtmQueryParams;
}
loadScript(id.id, newConf as LoadScriptOptions);
}
});
} else {
loadScript(options.id, options as LoadScriptOptions);
}
}
}
app.provide('gtm', options);
}
// eslint-disable-next-line jsdoc/require-jsdoc
type NavigationFailureType =
| ErrorTypes.NAVIGATION_ABORTED
| ErrorTypes.NAVIGATION_CANCELLED
| ErrorTypes.NAVIGATION_DUPLICATED;
/**
* Initialize the router guard.
*
* @param app The Vue app instance.
* @param vueRouter The Vue router instance to attach the guard.
* @param ignoredViews An array of route name that will be ignored.
* @param trackOnNextTick Whether or not to call `trackView` in `Vue.nextTick`.
* @param deriveAdditionalEventData Callback to derive additional event data.
*/
function initVueRouterGuard(
app: App,
vueRouter: Exclude<VueGtmUseOptions['vueRouter'], undefined>,
ignoredViews: VueGtmUseOptions['ignoredViews'] = [],
trackOnNextTick: VueGtmUseOptions['trackOnNextTick'],
deriveAdditionalEventData: VueGtmUseOptions['vueRouterAdditionalEventData'] = () => ({}),
): void {
// eslint-disable-next-line jsdoc/require-jsdoc
function isNavigationFailure(
failure: void | NavigationFailure | undefined,
navigationFailureType: NavigationFailureType,
): boolean {
if (!(failure instanceof Error)) {
return false;
}
return !!(failure.type & navigationFailureType);
}
vueRouter.afterEach(async (to, from, failure) => {
// Ignore some routes
if (
typeof to.name !== 'string' ||
(Array.isArray(ignoredViews) && ignoredViews.includes(to.name)) ||
(typeof ignoredViews === 'function' && ignoredViews(to, from))
) {
return;
}
// Dispatch vue event using meta gtm value if defined otherwise fallback to route name
const name: string =
to.meta && typeof to.meta.gtm === 'string' && !!to.meta.gtm
? to.meta.gtm
: to.name;
if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */)) {
if (gtmPlugin?.debugEnabled()) {
console.log(
`[VueGtm]: '${name}' not tracked due to navigation aborted`,
);
}
} else if (isNavigationFailure(failure, 8 /* NAVIGATION_CANCELLED */)) {
if (gtmPlugin?.debugEnabled()) {
console.log(
`[VueGtm]: '${name}' not tracked due to navigation cancelled`,
);
}
}
const additionalEventData: Record<string, any> = {
...(await deriveAdditionalEventData(to, from)),
...(to.meta?.gtmAdditionalEventData as Record<string, any>),
};
const baseUrl: string = vueRouter.options?.history?.base ?? '';
let fullUrl: string = baseUrl;
if (!fullUrl.endsWith('/')) {
fullUrl += '/';
}
fullUrl += to.fullPath.startsWith('/')
? to.fullPath.substring(1)
: to.fullPath;
if (trackOnNextTick) {
void nextTick(() => {
gtmPlugin?.trackView(name, fullUrl, additionalEventData);
});
} else {
gtmPlugin?.trackView(name, fullUrl, additionalEventData);
}
});
}
/**
* Create the Vue GTM instance.
*
* @param options Options.
* @returns The Vue GTM plugin instance.
*/
export function createGtm(options: VueGtmUseOptions): VueGtmPlugin {
return { install: (app: App) => install(app, options) };
}
// @ts-expect-error: assume that `vue` already brings this dependency
declare module '@vue/runtime-core' {
// eslint-disable-next-line jsdoc/require-jsdoc
export interface ComponentCustomProperties {
/**
* The Vue GTM Plugin instance.
*/
$gtm: GtmPlugin;
}
}
/**
* Vue GTM Plugin.
*/
export type VueGtmPlugin = Plugin;
const _default: VueGtmPlugin = { install };
export {
GtmSupport,
assertIsGtmId,
hasScript,
loadScript,
} from '@gtm-support/core';
export type {
DataLayerObject,
GtmIdContainer,
GtmQueryParams,
GtmSupportOptions,
LoadScriptOptions,
TrackEventOptions,
} from '@gtm-support/core';
export { GtmPlugin };
export default _default;
/**
* Returns GTM plugin instance to be used via Composition API inside setup method.
*
* @returns The Vue GTM instance if the it was installed, otherwise `undefined`.
*/
export function useGtm(): GtmPlugin | undefined {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return (
getCurrentInstance()?.appContext?.app?.config?.globalProperties?.$gtm ??
gtmPlugin
);
}