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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
|
/*!
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
defineComponent,
ref,
} from 'vue';
import { IDirectiveFactory, IDirectivePrePost, Injectable } from 'angular';
import Matomo from './Matomo/Matomo';
import createVueApp from './createVueApp';
interface SingleScopeVarInfo<InjectTypes extends unknown[]> {
vue?: string;
default?: any;
transform?: (
v: unknown,
vm: any,
scope: any,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes,
otherController?: ng.IController,
...injected: InjectTypes
) => unknown;
angularJsBind?: string;
deepWatch?: boolean;
}
type ScopeMapping<InjectTypes extends unknown[]> = {
[scopeVarName: string]: SingleScopeVarInfo<InjectTypes>,
};
type AdapterFunction<InjectTypes extends unknown[], R = void> = (
scope: any,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes,
...injected: InjectTypes
) => R;
type EventAdapterFunction<InjectTypes extends unknown[], R = void> = (
$event: any,
vm: any,
scope: any,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes,
otherController?: ng.IController,
...injected: InjectTypes
) => R;
type PostCreateFunction<InjectTypes extends unknown[], R = void> = (
vm: any,
scope: any,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes,
otherController?: ng.IController,
...injected: InjectTypes
) => R;
type EventMapping<InjectTypes extends unknown[]> = {
[vueEventName: string]: EventAdapterFunction<InjectTypes>,
};
type ComponentType = ReturnType<typeof defineComponent>;
let transcludeCounter = 0;
function toKebabCase(arg: string): string {
return arg.substring(0, 1).toLowerCase() + arg.substring(1)
.replace(/[A-Z]/g, (s) => `-${s.toLowerCase()}`);
}
function toAngularJsCamelCase(arg: string): string {
return arg.substring(0, 1).toLowerCase() + arg.substring(1)
.replace(/-([a-z])/g, (s, p) => p.toUpperCase());
}
export function removeAngularJsSpecificProperties<T>(newValue: T): T {
if (typeof newValue === 'object'
&& newValue !== null
&& Object.getPrototypeOf(newValue) === Object.prototype
) {
return Object.fromEntries(Object.entries(newValue).filter((pair) => !/^\$/.test(pair[0]))) as T;
}
return newValue;
}
export default function createAngularJsAdapter<InjectTypes extends unknown[] = []>(options: {
component: ComponentType,
require?: string,
scope?: ScopeMapping<InjectTypes>,
directiveName: string,
events?: EventMapping<InjectTypes>,
$inject?: string[],
transclude?: boolean,
mountPointFactory?: AdapterFunction<InjectTypes, HTMLElement>,
postCreate?: PostCreateFunction<InjectTypes>,
noScope?: boolean,
restrict?: string,
priority?: number,
replace?: boolean,
}): Injectable<ng.IDirectiveFactory> {
const {
component,
require,
scope = {},
events = {},
$inject,
directiveName,
transclude,
mountPointFactory,
postCreate,
noScope,
restrict = 'A',
priority,
replace,
} = options;
const currentTranscludeCounter = transcludeCounter;
if (transclude) {
transcludeCounter += 1;
}
const vueToAngular: Record<string, string> = {};
const angularJsScope: Record<string, string> = {};
Object.entries(scope).forEach(([scopeVarName, info]) => {
if (!info.vue) {
info.vue = scopeVarName;
}
if (info.angularJsBind) {
angularJsScope[scopeVarName] = info.angularJsBind;
}
vueToAngular[info.vue] = scopeVarName;
});
function angularJsAdapter(...injectedServices: InjectTypes): ng.IDirective {
const adapter: ng.IDirective = {
restrict,
require,
priority,
scope: noScope ? undefined : angularJsScope,
compile: function angularJsAdapterCompile(): IDirectivePrePost {
return {
post: function angularJsAdapterLink(
ngScope: any,
ngElement: ng.IAugmentedJQuery,
ngAttrs: ng.IAttributes,
ngController?: ng.IController,
) {
const transcludeClone = transclude
? ngElement.find(`[ng-transclude][counter=${currentTranscludeCounter}]`)
: null;
// build the root vue template
let rootVueTemplate = '<root-component';
Object.entries(events).forEach((info) => {
const [eventName] = info;
rootVueTemplate += ` @${toKebabCase(eventName)}="onEventHandler('${eventName}', $event)"`;
});
Object.entries(scope).forEach(([, info]) => {
if (info.angularJsBind === '&' || info.angularJsBind === '&?') {
const eventName = toKebabCase(info.vue!);
if (!events[info.vue!]) { // pass through scope & w/o a custom event handler
rootVueTemplate += ` @${eventName}="onEventHandler('${info.vue!}', $event)"`;
}
} else {
rootVueTemplate += ` :${toKebabCase(info.vue!)}="${info.vue}"`;
}
});
rootVueTemplate += '>';
if (transclude) {
rootVueTemplate += '<div ref="transcludeTarget"/>';
}
rootVueTemplate += '</root-component>';
// build the vue app
const app = createVueApp({
template: rootVueTemplate,
data() {
const initialData: Record<string, unknown> = {};
Object.entries(scope).forEach(([scopeVarName, info]) => {
let value = removeAngularJsSpecificProperties(ngScope[scopeVarName]);
if (typeof value === 'undefined' && typeof info.default !== 'undefined') {
value = info.default instanceof Function
? info.default(ngScope, ngElement, ngAttrs, ...injectedServices)
: info.default;
}
if (info.transform) {
value = info.transform(
value,
this,
ngScope,
ngElement,
ngAttrs,
ngController,
...injectedServices,
);
}
initialData[info.vue!] = value;
});
return initialData;
},
setup() {
if (transclude) {
const transcludeTarget = ref(null);
return {
transcludeTarget,
};
}
return undefined;
},
methods: {
onEventHandler(name: string, $event: any) {
let scopePropertyName = toAngularJsCamelCase(name);
scopePropertyName = vueToAngular[scopePropertyName] || scopePropertyName;
if (ngScope[scopePropertyName]) {
ngScope[scopePropertyName]($event);
}
if (events[name]) {
events[name](
$event,
this,
ngScope,
ngElement,
ngAttrs,
ngController,
...injectedServices,
);
}
},
},
});
app.component('root-component', component);
// mount the app
const mountPoint = mountPointFactory
? mountPointFactory(ngScope, ngElement, ngAttrs, ...injectedServices)
: ngElement[0];
const vm: any = app.mount(mountPoint);
// setup watches to bind between angularjs + vue
Object.entries(scope).forEach(([scopeVarName, info]) => {
if (!info.angularJsBind || info.angularJsBind === '&' || info.angularJsBind === '&?') {
return;
}
ngScope.$watch(scopeVarName, (newValue: any, oldValue: any) => {
if (newValue === oldValue
&& JSON.stringify(vm[info.vue!]) === JSON.stringify(newValue)
) {
return; // initial
}
let newValueFinal = removeAngularJsSpecificProperties(newValue);
if (typeof info.default !== 'undefined' && typeof newValue === 'undefined') {
newValueFinal = info.default instanceof Function
? info.default(ngScope, ngElement, ngAttrs, ...injectedServices)
: info.default;
}
if (info.transform) {
newValueFinal = info.transform(
newValueFinal,
vm,
ngScope,
ngElement,
ngAttrs,
ngController,
...injectedServices,
);
}
vm[info.vue!] = newValueFinal;
}, info.deepWatch);
});
if (transclude && transcludeClone) {
$(vm.transcludeTarget).append(transcludeClone);
}
if (postCreate) {
postCreate(vm, ngScope, ngElement, ngAttrs, ngController, ...injectedServices);
}
// specifying replace: true on the directive does nothing w/ vue inside, so
// handle it here.
if (replace) {
// transfer attributes from angularjs element that are not in scope to
// mount point element
Array.from(ngElement[0].attributes).forEach((attr) => {
if (scope[attr.nodeName]) {
return;
}
if (mountPoint.firstElementChild) {
mountPoint.firstElementChild.setAttribute(attr.nodeName, attr.nodeValue!);
}
});
ngElement.replaceWith(window.$(mountPoint).children());
}
ngElement.on('$destroy', () => {
app.unmount();
});
},
};
},
};
if (transclude) {
adapter.transclude = true;
adapter.template = `<div ng-transclude counter="${currentTranscludeCounter}"/>`;
}
return adapter;
}
angularJsAdapter.$inject = $inject || [];
window.angular.module('piwikApp').directive(
directiveName,
angularJsAdapter as unknown as Injectable<IDirectiveFactory>,
);
return angularJsAdapter as unknown as Injectable<IDirectiveFactory>;
}
export function transformAngularJsBoolAttr(v: unknown): boolean|undefined {
if (typeof v === 'undefined') {
return undefined;
}
if (v === 'true') {
return true;
}
return !!v && v as number > 0 && v !== '0';
}
export function transformAngularJsIntAttr(v: unknown): number|undefined|null {
if (typeof v === 'undefined') {
return undefined;
}
if (v === null) {
return null;
}
return parseInt(v as string, 10);
}
// utility function for service adapters
export function clone<T>(p: T): T {
if (typeof p === 'undefined') {
return p;
}
return JSON.parse(JSON.stringify(p)) as T;
}
export function cloneThenApply<T>(p: T): T {
const result = clone(p);
Matomo.helper.getAngularDependency('$rootScope').$applyAsync();
return result;
}
|