-
Notifications
You must be signed in to change notification settings - Fork 7
/
notification.js
416 lines (366 loc) · 12.7 KB
/
notification.js
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { ajv } from "./data-validation";
import { library, icon } from "@fortawesome/fontawesome-svg-core";
import {
faCircleXmark,
faFlask,
faCodePullRequest,
faHourglassHalf,
} from "@fortawesome/free-solid-svg-icons";
import { html, nothing, render, LitElement } from "lit";
import styleSheet from "./notification.css";
import { AddonBase, addUtmParameters, getLinkWithFilename } from "./utils";
export class NotificationElement extends LitElement {
/** @static @property {string} - registered HTML element tag name */
static elementName = "readthedocs-notification";
/** @static @property {Object} - Lit reactive properties */
static properties = {
config: { state: true },
urls: { state: true },
highest_version: { state: true },
dismissedTimestamp: { state: true },
autoDismissed: { state: true },
localStorageKey: { state: true },
};
/** @static @property {Object} - Lit stylesheets to apply to elements */
static styles = styleSheet;
constructor() {
super();
this.timerID = null;
this.config = null;
this.urls = {
build: null,
external: null,
stable: null,
};
this.readingLatestVersion = false;
this.readingStableVersion = false;
this.stableVersionAvailable = false;
// This will store information like user dimissing the notification. Any Notification sharing
// the same localStorageKey will be affected.
this.localStorageKey = null;
this.dismissedTimestamp = null;
this.autoDismissed = false;
// Trigger the auto-dismiss timer at startup
this.triggerAutoDismissTimer();
}
loadDismissedTimestamp(config) {
// Check if this notification (as determined by localStorageKey) has been dismissed already.
// Once a notification has been dismissed, it stays dismissed. This information however is not passed
// over different subdomains, so if a notification has been dismissed on a PR build, it will not affect
// other builds.
this.localStorageKey = this.getLocalStorageKeyFromConfig(this.config);
const notificationStorage =
NotificationAddon.getLocalStorage()[this.localStorageKey];
if (notificationStorage && notificationStorage.dismissedTimestamp) {
this.dismissedTimestamp = notificationStorage.dismissedTimestamp;
}
}
triggerAutoDismissTimer() {
if (!document.hidden && !this.autoDismissed) {
clearTimeout(this.timerID);
this.timerID = setTimeout(() => {
this.autoDismissed = true;
this.requestUpdate();
}, 5000);
}
}
clearAutoDismissTimer() {
clearTimeout(this.timerID);
this.timerID = null;
}
_handleMouseEnter = (e) => {
// Stop the timer when notification is hovered (mouseenter event)
clearTimeout(this.timerID);
this.timerID = null;
};
_handleMouseLeave = (e) => {
// Start the timer when the notification is hovered away (mouseleave)
this.triggerAutoDismissTimer();
};
_handleVisibilityChange = (e) => {
if (document.hidden) {
// Page is hidden. The user is not looking at it.
// Clear the timeout to hide the notification.
this.clearAutoDismissTimer();
} else {
// Page became visible.
// Trigger a timeout to hide the notification.
this.triggerAutoDismissTimer();
}
};
connectedCallback() {
super.connectedCallback();
document.addEventListener("visibilitychange", this._handleVisibilityChange);
this.addEventListener("mouseenter", this._handleMouseEnter);
this.addEventListener("mouseleave", this._handleMouseLeave);
}
disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("mouseenter", this._handleMouseEnter);
this.removeEventListener("mouseleave", this._handleMouseLeave);
document.removeEventListener(
"visibilitychange",
this._handleVisibilityChange,
);
clearTimeout(this.timerID);
this.timerID = null;
}
loadConfig(config) {
// Validate the config object before assigning it to the Addon.
// Later, ``render()`` method will check whether this object exists and (not) render
// accordingly
if (!NotificationAddon.isEnabled(config)) {
return;
}
this.config = config;
if (
this.config.addons.external_version_warning.enabled &&
this.config.versions.current.type === "external"
) {
this.urls = {
// NOTE: point users to the new beta dashboard for now so we promote it more.
// We will revert this once we are fully migrated to the new dashboard.
build: config.builds.current.urls.build
.replace("readthedocs.org", "app.readthedocs.org")
.replace("readthedocs.com", "app.readthedocs.com")
.replace("app.app.", "app."),
external: config.versions.current.urls.vcs,
};
}
if (
config.addons.non_latest_version_warning.enabled &&
config.projects.current.versioning_scheme !==
"single_version_without_translations" &&
config.versions.current.type !== "external"
) {
this.calculateStableLatestVersionWarning();
}
this.loadDismissedTimestamp(this.config);
}
getLocalStorageKeyFromConfig(config) {
const projectSlug = config.projects.current.slug;
const languageCode = config.projects.current.language.code;
const versionSlug = config.versions.current.slug;
return `${projectSlug}-${languageCode}-${versionSlug}-notification`;
}
firstUpdated() {
// Add CSS classes to the element on ``firstUpdated`` because we need the
// HTML element to exist in the DOM before being able to add tag attributes.
this.className = this.className || "raised toast";
}
render() {
if (this.autoDismissed) {
return nothing;
}
// The element doesn't yet have our config, don't render it.
if (this.config === null) {
// nothing is a special Lit response type
return nothing;
}
// This notification has been dimissed, so don't render it
if (this.dismissedTimestamp) {
return nothing;
}
if (this.config.versions.current.type === "external") {
if (this.config.addons.external_version_warning.enabled) {
return this.renderExternalVersionWarning();
}
} else if (
this.config.addons.non_latest_version_warning.enabled &&
(this.readingLatestVersion || this.stableVersionAvailable)
) {
return this.renderStableLatestVersionWarning();
}
return nothing;
}
calculateStableLatestVersionWarning() {
// The logic is pretty simple:
// - if the user is reading the "latest" version: shows a notification to warn
// the user about reading the latest development version.
// - if the user is reading a non-"stable" version: shows a notification to warn
// the user about reading a version that may be old.
//
// This does not cover all the cases where this notification could be useful,
// but users with different needs should be able to implement their own custom logic.
const stableVersion = this.config.versions.active.find(
(version) => version.slug === "stable",
);
const latestVersion = this.config.versions.active.find(
(version) => version.slug === "latest",
);
const currentVersion = this.config.versions.current;
// Current version is "latest" or its alias
if (
currentVersion.slug === "latest" ||
(latestVersion !== undefined &&
latestVersion.aliases.find(
(version) => version.slug === currentVersion.slug,
) !== undefined)
) {
this.readingLatestVersion = true;
}
// Current version is "stable" or its alias
if (
currentVersion.slug === "stable" ||
(stableVersion !== undefined &&
stableVersion.aliases.find(
(version) => version.slug === currentVersion.slug,
) !== undefined)
) {
this.readingStableVersion = true;
}
if (stableVersion !== undefined) {
this.stableVersionAvailable = true;
this.urls.stable = getLinkWithFilename(stableVersion.urls.documentation);
}
}
renderStableLatestVersionWarning() {
library.add(faHourglassHalf);
library.add(faFlask);
if (this.readingLatestVersion && this.stableVersionAvailable) {
const iconFlask = icon(faFlask, {
classes: ["header", "icon"],
});
return html`
<div>
${iconFlask.node[0]}
<div class="title">
This is the <span>latest development version</span>
${this.renderCloseButton()}
</div>
<div class="content">
Some features may not yet be available in the published stable
version. Read the
<a href="${this.urls.stable}"
>stable version of this documentation</a
>.
</div>
</div>
`;
}
if (!this.readingStableVersion && this.stableVersionAvailable) {
const iconHourglassHalf = icon(faHourglassHalf, {
classes: ["header", "icon"],
});
return html`
<div>
${iconHourglassHalf.node[0]}
<div class="title">
This <em>may</em> be an
<span>old version of this documentation</span>
${this.renderCloseButton()}
</div>
<div class="content">
You may be reading an old version of this documentation. Read the
<a href="${this.urls.stable}"
>latest stable version of this documentation</a
>.
</div>
</div>
`;
}
return nothing;
}
renderExternalVersionWarning() {
library.add(faCodePullRequest);
const iconPullRequest = icon(faCodePullRequest, {
title: "This version is a pull request version",
classes: ["header", "icon"],
});
return html`
<div>
${iconPullRequest.node[0]}
<div class="title">
This page was created from a pull request build
${this.renderCloseButton()}
</div>
<div class="content">
See the
<a href="${addUtmParameters(this.urls.build, "notification")}"
>build's detail page</a
>
or
<a href="${this.urls.external}"
>pull request #${this.config.versions.current.slug}</a
>
for more information.
</div>
</div>
`;
}
renderCloseButton() {
library.add(faCircleXmark);
const xmark = icon(faCircleXmark, {
title: "Close notification",
});
return html`
<a href="#" class="right" @click=${this.closeNotification}>
${xmark.node[0]}
</a>
`;
}
closeNotification(e) {
// Avoid going back to the top of the page when closing the notification
e.preventDefault();
// Store the information about dismissal in the Local Storage
// Make sure to store the timestamp, so that we have the option to maybe add a TTL on the dismissal
this.dismissedTimestamp = Date.now();
const dismissedObj = {
[this.localStorageKey]: { dismissedTimestamp: this.dismissedTimestamp },
};
NotificationAddon.setLocalStorage(dismissedObj);
// Avoid event propagation
return false;
}
}
/**
* Notification addon
*
* Currently this addon is used to warn readers that the documentation is built
* from a pull request.
*
* The default implementation is a floating element, but this can also be hard
* coded into the page from the author or theme author. If there is a hardcoded
* element, we do not inject a new element, but the web component is
* initialized as normal by the browser.
*
* We load the param ``config`` into the elements after creation and API
* response, as this is needed to give hardcoded elements access to ``config``
*
* @param {Object} config - Addon configuration object
*/
export class NotificationAddon extends AddonBase {
static jsonValidationURI =
"http://v1.schemas.readthedocs.org/addons.notifications.json";
static addonName = "Notification";
constructor(config) {
super();
// If there are no elements found, inject one
let elems = document.querySelectorAll("readthedocs-notification");
if (!elems.length) {
elems = [new NotificationElement()];
document.body.append(elems[0]);
elems[0].requestUpdate();
}
for (const elem of elems) {
elem.loadConfig(config);
}
}
/**
* Test if addon is enabled in the configuration
*
* @param {Object} config - Addon configuration object
*/
static isEnabled(config) {
if (!super.isConfigValid(config)) {
return false;
}
return (
(config.addons.external_version_warning.enabled === true &&
config.versions.current.type === "external") ||
(config.addons.non_latest_version_warning.enabled === true &&
config.versions.current.type !== "external")
);
}
}
customElements.define("readthedocs-notification", NotificationElement);