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

Notifications.store.ts « Notification « src « vue « CoreHome « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e014e9bedaf797caaae6ad342a4ec524e5eb390f (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

import {
  DeepReadonly,
  reactive,
  createVNode,
  createApp,
} from 'vue';
import NotificationComponent from './Notification.vue';
import translate from '../translate';
import Matomo from '../Matomo/Matomo';

interface Notification {
  /**
   * Only needed for persistent notifications. The id will be sent to the
   * frontend once the user closes the notifications. The notification has to
   * be registered/notified under this name.
   */
  id?: string;

  /**
   * Unique ID generated for the notification so it can be referenced specifically
   * to scroll to.
   */
  notificationInstanceId: string;

  /**
   * Determines which notification group a notification is meant to be displayed
   * in.
   */
  group?: string;

  /**
   * The title of the notification. For instance the plugin name.
   */
  title?: string;

  /**
   * The actual message that will be displayed. Must be set.
   */
  message: string;

  /**
   * Context of the notification: 'info', 'warning', 'success' or 'error'
   */
  context: 'success'|'error'|'info'|'warning';

  /**
   * The type of the notification: Either 'toast' or 'transient'. 'persistent' is valid, but
   * has no effect if only specified client side.
   */
  type: 'toast'|'persistent'|'transient';

  /**
   * If set, the close icon is not displayed.
   */
  noclear?: boolean;

  /**
   * The number of milliseconds before a toast animation disappears.
   */
  toastLength?: number;

  /**
   * Optional style/css dictionary. For instance {'display': 'inline-block'}
   */
  style?: string|Record<string, unknown>;

  /**
   * Optional CSS class to add.
   */
  class?: string;

  /**
   * If true, fades the animation in.
   */
  animate?: boolean;

  /**
   * Where to place the notification. Required if showing a toast.
   */
  placeat?: string|HTMLElement|JQuery;
}

interface NotificationsData {
  notifications: Notification[];
}

class NotificationsStore {
  private privateState: NotificationsData = reactive<NotificationsData>({
    notifications: [],
  });

  private nextNotificationId = 0;

  get state(): DeepReadonly<NotificationsData> {
    return this.privateState;
  }

  appendNotification(notification: Notification): void {
    this.checkMessage(notification.message);

    // remove existing notification before adding
    if (notification.id) {
      this.remove(notification.id);
    }
    this.privateState.notifications.push(notification);
  }

  prependNotification(notification: Notification): void {
    this.checkMessage(notification.message);

    // remove existing notification before adding
    if (notification.id) {
      this.remove(notification.id);
    }
    this.privateState.notifications.unshift(notification);
  }

  /**
   * Removes a previously shown notification having the given notification id.
   */
  remove(id: string): void {
    this.privateState.notifications = this.privateState.notifications.filter(
      (n) => n.id !== id,
    );
  }

  parseNotificationDivs(): void {
    const $notificationNodes = $('[data-role="notification"]');

    const notificationsToShow = [];
    $notificationNodes.each((index, notificationNode) => {
      const $notificationNode = $(notificationNode);
      const attributes = $notificationNode.data();
      const message = $notificationNode.html();

      if (message) {
        notificationsToShow.push({ ...attributes, message, animate: false });
      }

      $notificationNodes.remove();
    });

    notificationsToShow.forEach((n) => this.show(n));
  }

  clearTransientNotifications(): void {
    this.privateState.notifications = this.privateState.notifications.filter(
      (n) => n.type !== 'transient',
    );
  }

  /**
   * Creates a notification and shows it to the user.
   */
  show(notification: Notification): string {
    this.checkMessage(notification.message);

    let addMethod = this.appendNotification;

    let notificationPosition: typeof Notification['placeat'] = '#notificationContainer';
    if (notification.placeat) {
      notificationPosition = notification.placeat;
    } else {
      // If a modal is open, we want to make sure the error message is visible and therefore
      // show it within the opened modal
      const modalSelector = '.modal.open .modal-content';
      if (document.querySelector(modalSelector)) {
        notificationPosition = modalSelector;
        addMethod = this.prependNotification;
      }
    }

    const group = notification.group
      || (notification.placeat ? notification.placeat.toString() : '');

    this.initializeNotificationContainer(notificationPosition, group);

    const notificationInstanceId = (this.nextNotificationId += 1).toString();

    addMethod.call(this, {
      ...notification,
      noclear: !!notification.noclear,
      group,
      notificationId: notification.id,
      notificationInstanceId,
      type: notification.type || 'transient',
    });

    return notificationInstanceId;
  }

  scrollToNotification(notificationInstanceId: string) {
    setTimeout(() => {
      const element = document.querySelector(`[data-notification-instance-id='${notificationInstanceId}']`);
      if (element) {
        Matomo.helper.lazyScrollTo(element, 250);
      }
    });
  }

  /**
   * Shows a notification at a certain point with a quick upwards animation.
   */
  toast(notification: Notification): void {
    this.checkMessage(notification.message);

    const $placeat = $(notification.placeat);
    if (!$placeat.length) {
      throw new Error('A valid selector is required for the placeat option when using Notification.toast().');
    }

    const toastElement = document.createElement('div');
    toastElement.style.position = 'absolute';
    toastElement.style.top = `${$placeat.offset().top}px`;
    toastElement.style.left = `${$placeat.offset().left}px`;
    toastElement.style.zIndex = '1000';
    document.body.appendChild(toastElement);

    const app = createApp({
      render: () => createVNode(NotificationComponent, {
        ...notification,
        notificationId: notification.id,
        type: 'toast',
        onClosed: () => {
          app.unmount();
        },
      }),
    });
    app.config.globalProperties.$sanitize = window.vueSanitize;
    app.config.globalProperties.translate = translate;
    app.mount(toastElement);
  }

  private initializeNotificationContainer(
    notificationPosition: typeof Notification['placeat'],
    group: string,
  ) {
    const $container = window.$(notificationPosition);
    if ($container.children('.notification-group').length) {
      return;
    }

    // avoiding a dependency cycle. won't need to do this when NotificationGroup's do not need
    // to be dynamically initialized.
    const NotificationGroup = (window as any).CoreHome.NotificationGroup; // eslint-disable-line

    const app = createApp({
      template: '<NotificationGroup :group="group"></NotificationGroup>',
      data: () => ({ group }),
    });
    app.config.globalProperties.$sanitize = window.vueSanitize;
    app.config.globalProperties.translate = translate;
    app.component('NotificationGroup', NotificationGroup);
    app.mount($container[0]);
  }

  private checkMessage(message: string) {
    if (!message) {
      throw new Error('No message given, cannot display notification');
    }
  }
}

const instance = new NotificationsStore();
export default instance;

// parse notifications on dom load
$(() => instance.parseNotificationDivs());