Welcome to mirror list, hosted at ThFree Co, Russian Federation.

createAngularJsAdapter.ts « src « vue « CoreHome « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d1806e84b55e6c19e4be02aa27973ba2a94ca961 (plain)
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
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

import {
  createApp,
  defineComponent,
  ref,
  ComponentPublicInstance,
} from 'vue';
import translate from './translate';

interface SingleScopeVarInfo {
  vue?: string;
  default?: any; // eslint-disable-line
  transform?: (v: unknown) => unknown;
  angularJsBind?: string;
}

type ScopeMapping = { [scopeVarName: string]: SingleScopeVarInfo };

type AdapterFunction<InjectTypes, R = void> = (
  scope: ng.IScope,
  element: ng.IAugmentedJQuery,
  attrs: ng.IAttributes,
  ...injected: InjectTypes,
) => R;

type EventAdapterFunction<InjectTypes, R = void> = (
  $event: any, // eslint-disable-line
  vm: ComponentPublicInstance,
  scope: ng.IScope,
  element: ng.IAugmentedJQuery,
  attrs: ng.IAttributes,
  otherController: ng.IControllerService,
  ...injected: InjectTypes,
) => R;

type PostCreateFunction<InjectTypes, R = void> = (
  vm: ComponentPublicInstance,
  scope: ng.IScope,
  element: ng.IAugmentedJQuery,
  attrs: ng.IAttributes,
  otherController: ng.IControllerService,
  ...injected: InjectTypes,
) => R;

type EventMapping<InjectTypes> = { [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 default function createAngularJsAdapter<InjectTypes = []>(options: {
  component: ComponentType,
  require?: string,
  scope?: ScopeMapping,
  directiveName: string,
  events?: EventMapping<InjectTypes>,
  $inject?: string[],
  transclude?: boolean,
  mountPointFactory?: AdapterFunction<InjectTypes, HTMLElement>,
  postCreate?: PostCreateFunction<InjectTypes>,
  noScope?: boolean,
  restrict?: string,
}): ng.IDirectiveFactory {
  const {
    component,
    require,
    scope = {},
    events = {},
    $inject,
    directiveName,
    transclude,
    mountPointFactory,
    postCreate,
    noScope,
    restrict = 'A',
  } = options;

  const currentTranscludeCounter = transcludeCounter;
  if (transclude) {
    transcludeCounter += 1;
  }

  const angularJsScope = {};
  Object.entries(scope).forEach(([scopeVarName, info]) => {
    if (!info.vue) {
      info.vue = scopeVarName;
    }
    if (info.angularJsBind) {
      angularJsScope[scopeVarName] = info.angularJsBind;
    }
  });

  function angularJsAdapter(...injectedServices: InjectTypes) {
    const adapter: ng.IDirective = {
      restrict,
      require,
      scope: noScope ? undefined : angularJsScope,
      compile: function angularJsAdapterCompile() {
        return {
          post: function angularJsAdapterLink(
            ngScope: ng.IScope,
            ngElement: ng.IAugmentedJQuery,
            ngAttrs: ng.IAttributes,
            ngController: ng.IControllerService,
          ) {
            const clone = 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 += ` @${eventName}="onEventHandler('${eventName}', $event)"`;
            });
            Object.entries(scope).forEach(([key, info]) => {
              if (info.angularJsBind === '&') {
                const eventName = toKebabCase(key);
                if (!events[eventName]) { // pass through scope & w/o a custom event handler
                  rootVueTemplate += ` @${eventName}="onEventHandler('${eventName}', $event)"`;
                }
              } else {
                rootVueTemplate += ` :${info.vue}="${info.vue}"`;
              }
            });
            rootVueTemplate += '>';
            if (transclude) {
              rootVueTemplate += '<div ref="transcludeTarget"/>';
            }
            rootVueTemplate += '</root-component>';

            // build the vue app
            const app = createApp({
              template: rootVueTemplate,
              data() {
                const initialData = {};
                Object.entries(scope).forEach(([scopeVarName, info]) => {
                  let value = 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);
                  }
                  initialData[info.vue] = value;
                });
                return initialData;
              },
              setup() {
                if (transclude) {
                  const transcludeTarget = ref(null);
                  return {
                    transcludeTarget,
                  };
                }

                return undefined;
              },
              methods: {
                onEventHandler(name: string, $event: any) { // eslint-disable-line
                  const scopePropertyName = toAngularJsCamelCase(name);
                  if (ngScope[scopePropertyName]) {
                    ngScope[scopePropertyName]($event);
                  }

                  if (events[name]) {
                    events[name](
                      $event,
                      this,
                      ngScope,
                      ngElement,
                      ngAttrs,
                      ngController,
                      ...injectedServices,
                    );
                  }
                },
              },
            });
            app.config.globalProperties.$sanitize = window.vueSanitize;
            app.config.globalProperties.translate = translate;
            app.component('root-component', component);

            // mount the app
            const mountPoint = mountPointFactory
              ? mountPointFactory(ngScope, ngElement, ngAttrs, ...injectedServices)
              : ngElement[0];
            const vm = app.mount(mountPoint);

            // setup watches to bind between angularjs + vue
            Object.entries(scope).forEach(([scopeVarName, info]) => {
              if (!info.angularJsBind || info.angularJsBind === '&') {
                return;
              }

              ngScope.$watch(scopeVarName, (newValue: any) => { // eslint-disable-line
                let newValueFinal = 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[scopeVarName] = newValueFinal;
              });
            });

            if (transclude) {
              $(vm.transcludeTarget).append(clone);
            }

            if (postCreate) {
              postCreate(vm, ngScope, ngElement, ngAttrs, ngController, ...injectedServices);
            }

            ngElement.on('$destroy', () => {
              app.unmount();
            });
          },
        };
      },
    };

    if (transclude) {
      adapter.transclude = true;
      adapter.template = `<div ng-transclude counter="${currentTranscludeCounter}"/>`;
    }

    return adapter;
  }

  angularJsAdapter.$inject = $inject || [];

  angular.module('piwikApp').directive(directiveName, angularJsAdapter);

  return angularJsAdapter;
}