@salesforcedevs/docs-components 0.53.6 → 0.54.0-alpha01

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,553 @@
1
+ import { api, track } from "lwc";
2
+ import { toJson } from "utils/normalizers";
3
+ import { FetchContent } from "./utils";
4
+ import {
5
+ CoveoAdvancedQueryXMLConfig,
6
+ DocLanguage,
7
+ DocVersion,
8
+ Labels,
9
+ TreeNode,
10
+ Header,
11
+ HistoryState,
12
+ PageReference
13
+ } from "./types";
14
+ import { SearchSyncer } from "../../utils/SearchSyncer/SearchSyncer";
15
+ import { LightningElementWithState } from "../../base-elements/lightningElementWithState/lightningElementWithState";
16
+
17
+ // TODO: Imitating from actual implementation as doc-content use it like this. We should refactor it later.
18
+ const handleContentError = (error): void => console.log(error);
19
+
20
+ export default class DocXmlContent extends LightningElementWithState<{
21
+ isFetchingDocument: boolean;
22
+ isFetchingContent: boolean;
23
+ lastHighlightedSearch: string;
24
+ }> {
25
+ @api apiDomain = "https://developer.salesforce.com";
26
+ @api coveoOrganizationId!: string;
27
+ @api coveoPublicAccessToken!: string;
28
+
29
+ @api
30
+ get labels() {
31
+ return this._labels;
32
+ }
33
+
34
+ set labels(value) {
35
+ this._labels = toJson(value);
36
+ }
37
+
38
+ private _labels: Labels = null;
39
+ private availableLanguages: Array<DocLanguage> = [];
40
+ private availableVersions: Array<DocVersion> = [];
41
+ private contentProvider: FetchContent;
42
+ private docContent = "";
43
+ private language: DocLanguage = null;
44
+ private loaded = false;
45
+ private pdfUrl = "";
46
+ private tocMap = null;
47
+ private sidebarContent: Array<TreeNode> = null;
48
+ private version: DocVersion = null;
49
+ private docTitle = "";
50
+ private analyticsEvent = "custEv_ctaLinkClick";
51
+ private _pathName = "";
52
+ private _pageHeader?: Header;
53
+ private listenerAttached = false;
54
+ private searchSyncer = new SearchSyncer({
55
+ callbacks: {
56
+ onSearchChange: (nextSearchString: string): void => {
57
+ if (nextSearchString !== this.pageReference.search) {
58
+ this.updatePageReference({
59
+ ...this.pageReference,
60
+ search: nextSearchString
61
+ });
62
+ }
63
+ if (nextSearchString !== this.state.lastHighlightedSearch) {
64
+ this.updateHighlighting(
65
+ new URLSearchParams(nextSearchString).get("q") || ""
66
+ );
67
+ }
68
+ },
69
+ onUrlChange: (nextSearchString: string): void => {
70
+ if (nextSearchString !== this.pageReference.search) {
71
+ this.updatePageReference({
72
+ ...this.pageReference,
73
+ search: nextSearchString
74
+ });
75
+ }
76
+ const nextSearchParam =
77
+ new URLSearchParams(nextSearchString).get("q") || "";
78
+ this.updateSearchInput(nextSearchParam);
79
+ if (nextSearchString !== this.state.lastHighlightedSearch) {
80
+ this.updateHighlighting(nextSearchParam);
81
+ }
82
+ }
83
+ },
84
+ eventName: "sidebarsearchchange",
85
+ historyMethod: window.history.pushState,
86
+ searchParam: "q",
87
+ shouldStopPropagation: true,
88
+ target: window
89
+ });
90
+
91
+ @track private pageReference: PageReference = {};
92
+
93
+ constructor() {
94
+ super();
95
+ this.pageReference = this.getReferenceFromUrl();
96
+ // In order to prevent dispatching unnecessary highlight changes, we
97
+ // track these items and use their previous values for comparisons in
98
+ // `renderedCallback`:
99
+ this.state = {
100
+ isFetchingContent: false,
101
+ isFetchingDocument: false,
102
+ lastHighlightedSearch: "",
103
+ internalLinkClicked: false
104
+ };
105
+ }
106
+
107
+ connectedCallback(): void {
108
+ if (!this.pageReference?.deliverable) {
109
+ window.location.href = "/docs";
110
+ return;
111
+ }
112
+
113
+ this.contentProvider = new FetchContent(this.apiDomain, this._labels);
114
+ this.fetchDocument().then(() => (this.loaded = true));
115
+ window.addEventListener("popstate", this.handlePopState);
116
+
117
+ this.searchSyncer.init();
118
+ }
119
+
120
+ renderedCallback(): void {
121
+ this.setState({ internalLinkClicked: true });
122
+ const urlSectionLink =
123
+ this.pageReference?.hash?.split("#").length > 1
124
+ ? this.pageReference.hash.split("#")[1]
125
+ : this.pageReference?.hash;
126
+
127
+ const contentEl = this.template.querySelector("doc-content");
128
+ const anchorEl =
129
+ urlSectionLink &&
130
+ (contentEl?.shadowRoot?.querySelector(`[id='${urlSectionLink}']`) ||
131
+ contentEl?.shadowRoot?.querySelector(
132
+ `[name='${urlSectionLink}']`
133
+ ));
134
+
135
+ if (anchorEl) {
136
+ anchorEl.scrollIntoView();
137
+ this.setState({ internalLinkClicked: false });
138
+ }
139
+
140
+ if (
141
+ (this.prevState.isFetchingContent &&
142
+ !this.state.isFetchingContent) ||
143
+ (this.prevState.isFetchingDocument &&
144
+ !this.state.isFetchingDocument)
145
+ ) {
146
+ const prevSearchParam =
147
+ new URLSearchParams(this.state.lastHighlightedSearch).get(
148
+ "q"
149
+ ) || "";
150
+ const nextSearchParam =
151
+ new URLSearchParams(this.pageReference.search).get("q") || "";
152
+ this.updateHighlighting(nextSearchParam);
153
+ if (prevSearchParam !== nextSearchParam) {
154
+ this.updateSearchInput(nextSearchParam);
155
+ }
156
+ }
157
+ }
158
+
159
+ disconnectedCallback(): void {
160
+ window.removeEventListener("popstate", this.handlePopState);
161
+ this.searchSyncer.dispose();
162
+ if (this.listenerAttached) {
163
+ this.pageHeader.removeEventListener(
164
+ "langchange",
165
+ this.handleLanguageChange
166
+ );
167
+ this.listenerAttached = false;
168
+ }
169
+ }
170
+
171
+ private get languageId(): string {
172
+ return this.language.id.replace("-", "_");
173
+ }
174
+
175
+ private get releaseVersionId(): string {
176
+ return this.version.id;
177
+ }
178
+
179
+ private get deliverable(): string {
180
+ return this.pageReference.deliverable;
181
+ }
182
+
183
+ private get coveoAdvancedQueryConfig(): CoveoAdvancedQueryXMLConfig {
184
+ return {
185
+ // Temporary fix for empty results on apexref page
186
+ ...(this.deliverable === "apexref"
187
+ ? { source: "Sitemap - Developer Docs Atlas - Apexref" }
188
+ : {
189
+ objecttype: "HTDeveloperDocumentsC",
190
+ sflocale__c: this.languageId,
191
+ sfrelease__c: this.releaseVersionId,
192
+ sfdelivarable__c: this.deliverable
193
+ })
194
+ };
195
+ }
196
+
197
+ private get pageHeader(): Header {
198
+ if (!this._pageHeader) {
199
+ this._pageHeader = document.querySelector("doc-header");
200
+ }
201
+
202
+ return this._pageHeader;
203
+ }
204
+
205
+ private get sidebarValue(): string {
206
+ if (this.pageReference?.contentDocumentId) {
207
+ const hashedUri = `${
208
+ this.pageReference.contentDocumentId
209
+ }${this.normalizeHash(this.pageReference.hash)}`;
210
+ if (hashedUri in this.tocMap) {
211
+ return hashedUri;
212
+ }
213
+
214
+ if (this.pageReference.contentDocumentId in this.tocMap) {
215
+ return this.pageReference.contentDocumentId;
216
+ }
217
+ }
218
+
219
+ return "";
220
+ }
221
+
222
+ private get disableVersion(): boolean {
223
+ return !this.availableVersions || this.availableVersions.length <= 1;
224
+ }
225
+
226
+ private get versionOptions(): Array<DocVersion> {
227
+ return this.disableVersion
228
+ ? this.availableVersions
229
+ : this.availableVersions.map((version) => ({
230
+ ...version,
231
+ link: {
232
+ href: this.pageReferenceToString({
233
+ ...this.pageReference,
234
+ docId: version.url
235
+ })
236
+ }
237
+ }));
238
+ }
239
+
240
+ private handlePopState = (): void =>
241
+ this.updatePageReference(this.getReferenceFromUrl());
242
+
243
+ handleSelect(event: CustomEvent<{ name: string }>): void {
244
+ event.stopPropagation();
245
+ const { name } = event.detail;
246
+
247
+ if (this.sidebarValue === name) {
248
+ return;
249
+ }
250
+
251
+ if (name) {
252
+ const hashIndex = name.indexOf("#");
253
+ this.pageReference.hash =
254
+ hashIndex > -1 ? name.slice(hashIndex) : "";
255
+
256
+ const contentId = hashIndex > -1 ? name.slice(0, hashIndex) : name;
257
+ if (this.pageReference.contentDocumentId !== contentId) {
258
+ this.pageReference.contentDocumentId = contentId;
259
+ this.fetchContent().catch(handleContentError);
260
+ }
261
+
262
+ this.updateUrl();
263
+ }
264
+ }
265
+
266
+ handleNavClick(event: CustomEvent<{ pageReference: PageReference }>): void {
267
+ event.stopPropagation();
268
+ const { pageReference } = event.detail;
269
+ this.updatePageReference(pageReference);
270
+ this.updateUrl();
271
+ }
272
+
273
+ handleLanguageChange = (event: CustomEvent<string>): Promise<void> => {
274
+ if (this.language && this.language.id === event.detail) {
275
+ return;
276
+ }
277
+
278
+ this.language = this.availableLanguages.find(
279
+ ({ id }) => id === event.detail
280
+ );
281
+ this.pageReference.docId = this.language.url;
282
+ this.updateUrl();
283
+ this.fetchDocument();
284
+ };
285
+
286
+ updatePageReference(newPageReference: PageReference): void {
287
+ this.pageReference.hash = newPageReference.hash;
288
+ this.pageReference.search = newPageReference.search;
289
+
290
+ if (this.isSamePage(newPageReference)) {
291
+ return;
292
+ }
293
+
294
+ const isSameDocId = this.pageReference.docId !== newPageReference.docId;
295
+ this.pageReference = newPageReference;
296
+
297
+ if (isSameDocId) {
298
+ this.fetchDocument();
299
+ return;
300
+ }
301
+
302
+ this.fetchContent().catch(handleContentError);
303
+ }
304
+
305
+ getReferenceFromUrl(): PageReference {
306
+ const [page, docId, deliverable, contentDocumentId] =
307
+ window.location.pathname.substr(1).split("/");
308
+
309
+ const { origin: domain, hash, search } = window.location;
310
+
311
+ return {
312
+ contentDocumentId,
313
+ deliverable,
314
+ docId,
315
+ domain,
316
+ hash,
317
+ page,
318
+ search
319
+ };
320
+ }
321
+
322
+ isSamePage(reference: PageReference): boolean {
323
+ return (
324
+ this.pageReference.contentDocumentId ===
325
+ reference.contentDocumentId &&
326
+ this.pageReference.docId === reference.docId &&
327
+ this.pageReference.page === reference.page &&
328
+ this.pageReference.deliverable === reference.deliverable
329
+ );
330
+ }
331
+
332
+ async fetchDocument(): Promise<void> {
333
+ this.setState({
334
+ isFetchingDocument: true
335
+ });
336
+ const data = await this.contentProvider.fetchDocumentData(
337
+ this.pageReference.docId
338
+ );
339
+
340
+ // This could be a 404 scenario.
341
+ if (!data) {
342
+ this.setState({
343
+ isFetchingDocument: false
344
+ });
345
+ return;
346
+ }
347
+
348
+ this.docTitle = data.docTitle;
349
+ this.tocMap = data.tocMap;
350
+ this.sidebarContent = data.toc;
351
+ this.version = data.version;
352
+ this.language = data.language;
353
+ this.availableLanguages = data.availableLanguages;
354
+ this.availableVersions = data.availableVersions;
355
+ this.pdfUrl = data.pdfUrl;
356
+
357
+ this.updateHeader();
358
+
359
+ if (this.pageReference.deliverable !== data.deliverable) {
360
+ this.pageReference.deliverable = data.deliverable;
361
+ this.updateUrl(HistoryState.REPLACE_STATE);
362
+ }
363
+
364
+ if (
365
+ this.pageReference?.contentDocumentId?.replace(/\.htm$/, "") !==
366
+ data.id
367
+ ) {
368
+ try {
369
+ await this.fetchContent();
370
+ this.setState({
371
+ isFetchingDocument: false
372
+ });
373
+ return;
374
+ } catch (error) {
375
+ this.pageReference.contentDocumentId = `${data.id}.htm`;
376
+ this.pageReference.hash = "";
377
+ this.pageReference.search = "";
378
+ this.updateUrl(HistoryState.REPLACE_STATE);
379
+ }
380
+ }
381
+
382
+ this.docContent = data.content;
383
+ this.addMetatags();
384
+ this.setState({
385
+ isFetchingDocument: false
386
+ });
387
+ }
388
+
389
+ async fetchContent(): Promise<void> {
390
+ this.setState({
391
+ isFetchingContent: true
392
+ });
393
+ const data = await this.contentProvider.fetchContent(
394
+ this.pageReference.deliverable,
395
+ this.pageReference.contentDocumentId,
396
+ {
397
+ language: this.language.id,
398
+ version: this.version.id
399
+ }
400
+ );
401
+
402
+ if (data) {
403
+ this.docContent = data.content;
404
+ this.addMetatags();
405
+
406
+ if (!this.pageReference.hash) {
407
+ window.scrollTo(0, 0);
408
+ }
409
+ }
410
+ this.setState({
411
+ isFetchingContent: false
412
+ });
413
+ }
414
+
415
+ updateHeader(): void {
416
+ if (!this.pageHeader) {
417
+ return;
418
+ }
419
+
420
+ if (this.docTitle) {
421
+ this.pageHeader.subtitle = this.docTitle;
422
+ }
423
+
424
+ if (this.pdfUrl) {
425
+ this.pageHeader.bailHref = this.pdfUrl;
426
+ this.pageHeader.bailLabel = "PDF";
427
+ }
428
+
429
+ if (!this.listenerAttached) {
430
+ this.pageHeader.addEventListener(
431
+ "langchange",
432
+ this.handleLanguageChange
433
+ );
434
+ this.listenerAttached = true;
435
+ }
436
+
437
+ this.pageHeader.languages = this.availableLanguages;
438
+ this.pageHeader.language = this.language?.id;
439
+
440
+ if (this.pageReference) {
441
+ const { docId, deliverable, page } = this.pageReference;
442
+ this.pageHeader.headerHref = `/${page}/${docId}/${deliverable}/`;
443
+ }
444
+ }
445
+
446
+ updateUrl(method = HistoryState.PUSH_STATE): void {
447
+ window.history[method](
448
+ {},
449
+ "docs",
450
+ this.pageReferenceToString(this.pageReference)
451
+ );
452
+ }
453
+
454
+ private updateHighlighting(searchParam: string): void {
455
+ this.dispatchHighlightChange(searchParam);
456
+ this.setState({
457
+ lastHighlightedSearch: this.pageReference.search
458
+ });
459
+ }
460
+
461
+ private updateSearchInput(searchParam: string): void {
462
+ this.template
463
+ .querySelector("doc-content-layout")
464
+ ?.setSidebarInputValue(searchParam);
465
+ }
466
+
467
+ private pageReferenceToString(reference: PageReference): string {
468
+ const { page, docId, deliverable, contentDocumentId, hash, search } =
469
+ reference;
470
+ return `/${page}/${docId}/${deliverable}/${contentDocumentId}${this.normalizeSearch(
471
+ search
472
+ )}${this.normalizeHash(hash)}`;
473
+ }
474
+
475
+ private normalizeUrlPart(part: string, sentinel: string): string {
476
+ return (
477
+ (part &&
478
+ (part.startsWith(sentinel) ? part : `${sentinel}${part}`)) ||
479
+ ""
480
+ );
481
+ }
482
+
483
+ private normalizeSearch(search: string): string {
484
+ return this.normalizeUrlPart(search, "?");
485
+ }
486
+
487
+ private normalizeHash(hash: string): string {
488
+ return this.normalizeUrlPart(hash, "#");
489
+ }
490
+
491
+ private getComposedTitle(
492
+ topicTitle: string | undefined,
493
+ docTitle: string | undefined
494
+ ): string {
495
+ // map to avoid duplicates
496
+ const titleMap = {};
497
+ if (topicTitle) {
498
+ // sometimes the h1 tag text (which is docSubTitle) contains text with new line character. For e.g, "Bulk API 2.0 Older\n Documentation",
499
+ // here it contains \n in the text context which needs to be removed
500
+ // also, there are multiple spaces in between the text, which needs to be replaced with a single space
501
+ const docTopicTitle = topicTitle
502
+ .replace(/[\t\r\n]/g, " ")
503
+ .replace(/ +/g, " ")
504
+ .trim();
505
+ titleMap[docTopicTitle] = true;
506
+ }
507
+
508
+ if (docTitle) {
509
+ titleMap[docTitle] = true;
510
+ }
511
+
512
+ titleMap["Salesforce Developers"] = true;
513
+
514
+ return Object.keys(titleMap).join(" | ");
515
+ }
516
+
517
+ private dispatchHighlightChange(term: string): void {
518
+ this.dispatchEvent(
519
+ new CustomEvent("highlightedtermchange", {
520
+ detail: term,
521
+ bubbles: true,
522
+ composed: true
523
+ })
524
+ );
525
+ }
526
+
527
+ addMetatags(): void {
528
+ const div = document.createElement("div");
529
+ div.innerHTML = this.docContent;
530
+ const docDescription = div.querySelector(".shortdesc")?.textContent;
531
+ const topicTitle = div.querySelector("h1")?.textContent;
532
+
533
+ const title = document.querySelector("title");
534
+ const composedTitle = this.getComposedTitle(topicTitle, this.docTitle);
535
+
536
+ if (title) {
537
+ title.textContent = composedTitle;
538
+ }
539
+ const metatitle = document.querySelector('meta[name="title"]');
540
+ if (metatitle) {
541
+ metatitle.setAttribute("content", composedTitle);
542
+ }
543
+
544
+ if (docDescription) {
545
+ const metadescription = document.querySelector(
546
+ 'meta[name="description"]'
547
+ );
548
+ if (metadescription) {
549
+ metadescription.setAttribute("content", docDescription);
550
+ }
551
+ }
552
+ }
553
+ }