-
-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmanager.ts
More file actions
327 lines (269 loc) · 8.49 KB
/
manager.ts
File metadata and controls
327 lines (269 loc) · 8.49 KB
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
import { scheduleOnce } from '@ember/runloop';
import { service } from '@ember/service';
import { isEmpty } from '@ember/utils';
import { assert } from '@ember/debug';
import type ApplicationInstance from '@ember/application/instance';
import type RouterService from '@ember/routing/router-service';
import type Owner from '@ember/owner';
import { setOwner } from '@ember/owner';
import { associateDestroyableChild } from '@ember/destroyable';
import type {
FastBootDocument,
PageTitleToken,
PageTitleConfig,
} from '../private-types.ts';
const isFastBoot = typeof FastBoot !== 'undefined';
const RouterEvent = {
ROUTE_DID_CHANGE: 'routeDidChange',
} as const;
function hasResolveRegistration(owner: Owner): owner is ApplicationInstance {
return `resolveRegistration` in owner;
}
function hasPageTitleConfig(
fromEnv: unknown,
): fromEnv is { pageTitle: PageTitleConfig } {
if (typeof fromEnv !== 'object') return false;
if (fromEnv === null) return false;
// all properties on the pageTitle config are optional,
// so we can't check for more
return 'pageTitle' in fromEnv;
}
const configKeys = ['separator', 'prepend', 'replace'] as const;
/**
@internal
*/
export class PageTitleManager {
@service('router') declare router: RouterService;
// in fastboot context "document" is instance of
// ember-fastboot/simple-dom document
@service('-document') private declare document: FastBootDocument;
tokens: PageTitleToken[] = [];
_defaultConfig: PageTitleConfig = {
// The default separator to use between tokens.
separator: ' | ',
// The default prepend value to use.
prepend: true,
// The default replace value to use.
replace: null,
};
constructor(owner: Owner) {
setOwner(this, owner);
associateDestroyableChild(this, owner);
this._validateExistingTitleElement();
if (hasResolveRegistration(owner)) {
const config = owner.resolveRegistration('config:environment');
if (hasPageTitleConfig(config)) {
configKeys.forEach((key) => {
if (!isEmpty(config.pageTitle[key])) {
const configValue = config.pageTitle[key];
// SAFETY: how is one supposed to iterate over keys for an object and have it
// known to the compiler that both objects, having the same shape,
// will have the same type per-value?
// as-is, the `configValue` is a union of all value-types from the object.
(this._defaultConfig[key] as PageTitleConfig[typeof key]) =
configValue;
}
});
}
}
this.router.on(RouterEvent.ROUTE_DID_CHANGE, this.scheduleTitleUpdate);
}
applyTokenDefaults(token: PageTitleToken) {
const defaultSeparator = this._defaultConfig.separator;
const defaultPrepend = this._defaultConfig.prepend;
const defaultReplace = this._defaultConfig.replace;
token.previous ??= null;
token.next ??= null;
if (token.separator == null) {
token.separator = defaultSeparator;
}
if (token.prepend == null && defaultPrepend != null) {
token.prepend = defaultPrepend;
}
if (token.replace == null && defaultReplace != null) {
token.replace = defaultReplace;
}
}
inheritFromPrevious(token: PageTitleToken) {
const previous = token.previous;
if (previous) {
if (token.separator == null) {
token.separator = previous.separator;
}
if (token.prepend == null) {
token.prepend = previous.prepend;
}
}
}
push(token: PageTitleToken) {
const tokenForId = this._findTokenById(token.id);
if (tokenForId) {
const index = this.tokens.indexOf(tokenForId);
const tokens = [...this.tokens];
const previous = tokenForId.previous;
token.previous = previous;
token.next = tokenForId.next;
this.inheritFromPrevious(token);
this.applyTokenDefaults(token);
tokens.splice(index, 1, token);
this.tokens = tokens;
return;
}
const previous = this.tokens.slice(-1)[0];
if (previous) {
token.previous = previous ?? null;
previous.next = token;
this.inheritFromPrevious(token);
}
this.applyTokenDefaults(token);
this.tokens = [...this.tokens, token];
}
remove(id: PageTitleToken['id']) {
const token = this._findTokenById(id);
if (!token) return;
const { next, previous } = token;
if (next) {
next.previous = previous;
}
if (previous) {
previous.next = next;
}
token.previous = token.next = null;
const tokens = [...this.tokens];
tokens.splice(tokens.indexOf(token), 1);
this.tokens = tokens;
}
get visibleTokens(): PageTitleToken[] {
const tokens = this.tokens;
let i = tokens ? tokens.length : 0;
const visible = [];
while (i--) {
const token = tokens[i];
if (!token) continue;
if (token.replace) {
visible.unshift(token);
break;
} else {
visible.unshift(token);
}
}
return visible;
}
get sortedTokens(): PageTitleToken[] {
const visible = this.visibleTokens;
if (!visible) return [];
let appending = true;
let group: PageTitleToken[] = [];
const groups = [group];
const frontGroups: PageTitleToken[] = [];
visible.forEach((token) => {
if (token.front) {
frontGroups.unshift(token);
} else if (token.prepend) {
if (appending) {
appending = false;
group = [];
groups.push(group);
}
group.unshift(token);
} else {
if (!appending) {
appending = true;
group = [];
groups.push(group);
}
group.push(token);
}
});
return frontGroups.concat(groups.reduce((E, group) => E.concat(group), []));
}
scheduleTitleUpdate = () => {
// eslint-disable-next-line ember/no-runloop
scheduleOnce('afterRender', this, this._updateTitle);
};
toString(): string {
const tokens = this.sortedTokens;
const title = [];
for (let i = 0, len = tokens.length; i < len; i++) {
const token = tokens[i];
if (!token) continue;
if (token.title) {
title.push(token.title);
if (i + 1 < len) {
title.push(token.separator);
}
}
}
return title.join('');
}
willDestroy() {
super.willDestroy();
this.router.off(RouterEvent.ROUTE_DID_CHANGE, this.scheduleTitleUpdate);
}
private _updateTitle() {
const toBeTitle = this.toString();
if (isFastBoot) {
this.updateFastbootTitle(toBeTitle);
} else {
/**
* When rendering app with "?fastboot=false" (http://ember-fastboot.com/docs/user-guide#disabling-fastboot)
* We will not have <title> element present in DOM.
*
* But this is fine as by HTML spec,
* one is created upon assigning "document.title" value;
*
* https://html.spec.whatwg.org/multipage/dom.html#dom-tree-accessors
*/
this.document.title = toBeTitle;
}
this.titleDidUpdate(toBeTitle);
}
/**
* Validate if there's more than one title element present.
*
* Example: ember-cli-head can cause conflicting updates.
* @private
*/
private _validateExistingTitleElement() {
if (isFastBoot) {
return;
}
assert(
'[ember-page-title]: Multiple title elements found. Check for other addons like ember-cli-head updating <title> as well.',
document.head.querySelectorAll('title').length <= 1,
);
}
/**
* Find token by id
*
* @param {String} id
* @private
*/
private _findTokenById(id: PageTitleToken['id']) {
return this.tokens.find((token) => token.id === id);
}
updateFastbootTitle(toBeTitle: string) {
if (!isFastBoot) {
return;
}
const headElement = this.document.head;
const headChildNodes = headElement.childNodes;
// Remove existing title elements from previous render cycle
for (let i = 0; i < headChildNodes.length; i++) {
const node = headChildNodes[i];
if (!node) continue;
if (node.nodeName.toLowerCase() === 'title') {
headElement.removeChild(node);
}
}
// Add title element with latest value
const titleEl = this.document.createElement('title');
const titleContents = this.document.createTextNode(toBeTitle);
titleEl.appendChild(titleContents);
headElement.appendChild(titleEl);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
titleDidUpdate(_title: string) {
// default is empty, meant to be overriden by user if desired
}
}