@salesforcedevs/docs-components 1.3.169 → 1.3.171-alpha.0

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.
@@ -1,11 +1,11 @@
1
1
  /* eslint-disable @lwc/lwc/no-inner-html */
2
2
  import { createElement, LightningElement, api, track } from "lwc";
3
3
  import { DocContent, PageReference } from "typings/custom";
4
- import ContentCallout from "doc/contentCallout";
5
4
  import CodeBlock from "dx/codeBlock";
6
- import ContentMedia from "doc/contentMedia";
7
5
  import Button from "dx/button";
8
6
  import { highlightTerms } from "dxUtils/highlight";
7
+ import ContentCallout from "doc/contentCallout";
8
+ import ContentMedia from "doc/contentMedia";
9
9
 
10
10
  const HIGHLIGHTABLE_SELECTOR = [
11
11
  "p",
@@ -86,7 +86,7 @@ export default class Content extends LightningElement {
86
86
  }
87
87
 
88
88
  renderPaginationButton(anchorEl: HTMLElement) {
89
- const isNext = anchorEl.textContent.includes("Next →");
89
+ const isNext = anchorEl.textContent!.includes("Next →");
90
90
  anchorEl.innerHTML = "";
91
91
  const buttonEl = createElement("dx-button", { is: Button });
92
92
  const params = isNext
@@ -116,7 +116,7 @@ export default class Content extends LightningElement {
116
116
  const codeBlockEls = divEl.querySelectorAll(".codeSection");
117
117
  codeBlockEls.forEach((codeBlockEl) => {
118
118
  codeBlockEl.setAttribute("lwc:dom", "manual");
119
- const classList = codeBlockEl.firstChild.classList;
119
+ const classList = (codeBlockEl.firstChild as any).classList;
120
120
  let language = "";
121
121
  for (const key in classList) {
122
122
  if (typeof classList[key] === "string") {
@@ -160,7 +160,7 @@ export default class Content extends LightningElement {
160
160
 
161
161
  let flag = 1;
162
162
  for (let i: number = 0; i < detailEls.length; i++) {
163
- flag &= detailEls[i].innerHTML.trim() === "";
163
+ flag &= (detailEls[i].innerHTML.trim() === "") as any; // Dark Magic TM
164
164
  }
165
165
 
166
166
  if (flag) {
@@ -170,7 +170,7 @@ export default class Content extends LightningElement {
170
170
  });
171
171
  }
172
172
 
173
- const type = calloutEl.querySelector("h4").textContent;
173
+ const type = calloutEl.querySelector("h4")!.textContent!;
174
174
  const typeLower = type.toLowerCase();
175
175
  Object.assign(calloutCompEl, {
176
176
  title: type,
@@ -184,10 +184,10 @@ export default class Content extends LightningElement {
184
184
  // Modify links to work with any domain, links that start with "#" are excluded
185
185
  const anchorEls = divEl.querySelectorAll("a:not([href^='#'])");
186
186
 
187
- anchorEls.forEach((anchorEl) => {
187
+ anchorEls.forEach((anchorEl: any) => {
188
188
  if (
189
- anchorEl.textContent.includes("Next →") ||
190
- anchorEl.textContent.includes("← Previous")
189
+ anchorEl.textContent!.includes("Next →") ||
190
+ anchorEl.textContent!.includes("← Previous")
191
191
  ) {
192
192
  if (this.showPaginationButtons) {
193
193
  this.renderPaginationButton(anchorEl);
@@ -326,8 +326,7 @@ export default class Content extends LightningElement {
326
326
 
327
327
  handleNavClick(event: InputEvent) {
328
328
  event.preventDefault();
329
- // eslint-disable-next-line no-use-before-define
330
- const target = event.currentTarget.dataset.id;
329
+ const target = (event.currentTarget! as any).dataset.id;
331
330
  const [page, docId, deliverable, tempContentDocumentId] =
332
331
  target.split("/");
333
332
  const [contentDocumentId, hash] = tempContentDocumentId.split("#");
@@ -3,7 +3,7 @@ import { LightningElement, api, track } from "lwc";
3
3
  import { closest } from "kagekiri";
4
4
  import { toJson } from "dxUtils/normalizers";
5
5
  import { highlightTerms } from "dxUtils/highlight";
6
- import { SearchSyncer } from "docUtils/SearchSyncer";
6
+ import { SearchSyncer } from "docUtils/searchSyncer";
7
7
 
8
8
  type AnchorMap = { [key: string]: { intersect: boolean; id: string } };
9
9
 
@@ -26,9 +26,9 @@ const HIGHLIGHTABLE_SELECTOR = [
26
26
  export const OBSERVER_ATTACH_WAIT_TIME = 500;
27
27
 
28
28
  export default class ContentLayout extends LightningElement {
29
- @api sidebarValue: string;
30
- @api sidebarHeader: string;
31
- @api tocTitle: string;
29
+ @api sidebarValue!: string;
30
+ @api sidebarHeader!: string;
31
+ @api tocTitle!: string;
32
32
  @api enableSlotChange = false;
33
33
  @api coveoOrganizationId!: string;
34
34
  @api coveoPublicAccessToken!: string;
@@ -41,7 +41,7 @@ export default class ContentLayout extends LightningElement {
41
41
  return this._breadcrumbs;
42
42
  }
43
43
 
44
- set breadcrumbs(value): [] {
44
+ set breadcrumbs(value) {
45
45
  if (value) {
46
46
  this._breadcrumbs = toJson(value);
47
47
  }
@@ -52,7 +52,7 @@ export default class ContentLayout extends LightningElement {
52
52
  return this._sidebarContent;
53
53
  }
54
54
 
55
- set sidebarContent(value) {
55
+ set sidebarContent(value: any) {
56
56
  this._sidebarContent = toJson(value);
57
57
  }
58
58
 
@@ -67,7 +67,9 @@ export default class ContentLayout extends LightningElement {
67
67
 
68
68
  @api
69
69
  setSidebarInputValue(searchTerm: string): void {
70
- this.template.querySelector("dx-sidebar")?.setInputValue(searchTerm);
70
+ (this.template.querySelector("dx-sidebar") as any)?.setInputValue(
71
+ searchTerm
72
+ );
71
73
  }
72
74
 
73
75
  @track
@@ -76,11 +78,11 @@ export default class ContentLayout extends LightningElement {
76
78
  private _breadcrumbs = null;
77
79
 
78
80
  @track
79
- private _tocOptions: Array<unknown>;
81
+ private _tocOptions!: Array<unknown>;
80
82
 
81
83
  private tocOptionIdsSet = new Set();
82
84
  private anchoredElements: AnchorMap = {};
83
- private lastScrollPosition: number;
85
+ private lastScrollPosition!: number;
84
86
  private observer?: IntersectionObserver;
85
87
  private hasRendered: boolean = false;
86
88
  private contentLoaded: boolean = false;
@@ -105,7 +107,8 @@ export default class ContentLayout extends LightningElement {
105
107
  target: window
106
108
  });
107
109
  private tocValue?: string = undefined;
108
- private observerTimerId = null;
110
+ // eslint-disable-next-line no-undef
111
+ private observerTimerId?: NodeJS.Timeout;
109
112
  private didScrollToSelectedHash = false;
110
113
  private _scrollInterval = 0;
111
114
 
@@ -203,9 +206,9 @@ export default class ContentLayout extends LightningElement {
203
206
  ".sticky-doc-header"
204
207
  ) as HTMLElement;
205
208
 
206
- const docPhaseEl = this.template
207
- .querySelector("[name=doc-phase]")!
208
- .assignedElements()[0] as HTMLSlotElement;
209
+ const docPhaseEl = (
210
+ this.template.querySelector("[name=doc-phase]")! as any
211
+ ).assignedElements()[0] as HTMLSlotElement;
209
212
 
210
213
  if (!sidebarEl || !globalNavEl || !contextNavEl || !docHeaderEl) {
211
214
  console.warn("One or more required elements are missing.");
@@ -247,7 +250,7 @@ export default class ContentLayout extends LightningElement {
247
250
  document.querySelectorAll("doc-heading")
248
251
  );
249
252
  docHeadingEls.forEach((docHeadingEl) => {
250
- docHeadingEl.style.scrollMarginTop = `${
253
+ (docHeadingEl as any).style.scrollMarginTop = `${
251
254
  globalNavHeight +
252
255
  docHeaderHeight +
253
256
  docPhaseEl.getBoundingClientRect().height
@@ -255,9 +258,8 @@ export default class ContentLayout extends LightningElement {
255
258
  });
256
259
 
257
260
  // Adjust right nav bar position when doc phase is present
258
- const rightNavBarEl = this.template.querySelector(
259
- ".right-nav-bar"
260
- );
261
+ const rightNavBarEl =
262
+ this.template.querySelector(".right-nav-bar");
261
263
 
262
264
  if (rightNavBarEl) {
263
265
  rightNavBarEl.style.top = `${
@@ -291,7 +293,7 @@ export default class ContentLayout extends LightningElement {
291
293
  entries.forEach(
292
294
  (entry) =>
293
295
  (this.anchoredElements[
294
- entry.target.getAttribute("id")
296
+ entry.target.getAttribute("id")!
295
297
  ].intersect = entry.isIntersecting)
296
298
  );
297
299
  this.calculateActualSection();
@@ -303,10 +305,9 @@ export default class ContentLayout extends LightningElement {
303
305
 
304
306
  // Note: We are doing document.querySelectorAll as a quick fix as we are not getting heading elements reference this.querySelectorAll
305
307
  const headingElements = document.querySelectorAll(TOC_HEADER_TAG);
306
-
307
- for (const headingElement of headingElements) {
308
+ for (const headingElement of headingElements as any) {
308
309
  // Add headingElements to intersectionObserver for highlighting respective RNB item when user scroll
309
- const id = headingElement.getAttribute("id");
310
+ const id = headingElement.getAttribute("id")!;
310
311
  this.anchoredElements[id] = {
311
312
  id,
312
313
  intersect: false
@@ -320,23 +321,26 @@ export default class ContentLayout extends LightningElement {
320
321
  };
321
322
 
322
323
  onSlotChange(event: Event): void {
323
- const slotElements = (event.target as HTMLSlotElement).assignedElements();
324
+ const slotElements = (
325
+ event.target as HTMLSlotElement
326
+ ).assignedElements();
324
327
 
325
328
  if (slotElements.length) {
326
329
  this.contentLoaded = true;
327
330
  const slotContentElement = slotElements[0];
328
- const headingElements = slotContentElement.ownerDocument?.getElementsByTagName(
329
- TOC_HEADER_TAG
330
- );
331
+ const headingElements =
332
+ slotContentElement.ownerDocument?.getElementsByTagName(
333
+ TOC_HEADER_TAG
334
+ );
331
335
 
332
- for (const headingElement of headingElements) {
336
+ for (const headingElement of headingElements as any) {
333
337
  // Sometimes elements hash is not being set when slot content is wrapped with div
334
338
  headingElement.hash = headingElement.attributes.hash?.nodeValue;
335
339
  }
336
340
 
337
341
  const tocOptions = [];
338
342
 
339
- for (const headingElement of headingElements) {
343
+ for (const headingElement of headingElements as any) {
340
344
  headingElement.id = headingElement.hash;
341
345
 
342
346
  // Update tocOptions from anchorTags only for H2, consider default as 2 as per component
@@ -362,7 +366,7 @@ export default class ContentLayout extends LightningElement {
362
366
  private disconnectObserver(): void {
363
367
  if (this.observer) {
364
368
  this.observer.disconnect();
365
- this.observer = null;
369
+ this.observer = undefined;
366
370
  }
367
371
  }
368
372
 
@@ -387,15 +391,15 @@ export default class ContentLayout extends LightningElement {
387
391
  globalNavEl.offsetHeight +
388
392
  contextNavEl.offsetHeight;
389
393
 
390
- const docPhaseEl = this.template
391
- .querySelector("[name=doc-phase]")!
392
- .assignedElements()[0] as HTMLSlotElement;
394
+ const docPhaseEl = (
395
+ this.template.querySelector("[name=doc-phase]")! as any
396
+ ).assignedElements()[0] as HTMLSlotElement;
393
397
 
394
398
  const offset = docPhaseEl
395
399
  ? headerHeight + docPhaseEl.offsetHeight
396
400
  : headerHeight;
397
401
 
398
- for (const headingElement of headingElements) {
402
+ for (const headingElement of headingElements as any) {
399
403
  if (headingElement.getAttribute("id") === hash) {
400
404
  this.scrollIntoViewWithOffset(headingElement, offset);
401
405
  break;
@@ -432,14 +436,14 @@ export default class ContentLayout extends LightningElement {
432
436
  this.lastScrollPosition = currentScrollPosition;
433
437
  }
434
438
 
435
- private calculatePreviousElementId(): string {
439
+ private calculatePreviousElementId(): string | undefined {
436
440
  const keys = Object.keys(this.anchoredElements);
437
441
  const currentIndex = keys.findIndex((id) => this.tocValue === id);
438
442
 
439
443
  return currentIndex > 0 ? keys[currentIndex - 1] : undefined;
440
444
  }
441
445
 
442
- private assignElementId(id: string): void {
446
+ private assignElementId(id: string | undefined): void {
443
447
  // Change toc(RNB) highlight only for H2
444
448
  if (this.tocOptionIdsSet.has(id)) {
445
449
  this.tocValue = id;
@@ -11,12 +11,14 @@ export const ariaLevels = Object.keys(ariaDisplayLevels);
11
11
 
12
12
  export const displayLevels = Object.values(ariaDisplayLevels);
13
13
 
14
+ // @ts-ignore: Really Dark Magic (TM) to do with ariaLevel needing explicit getter/setters
14
15
  export default class Heading extends LightningElement {
15
16
  @api title: string = "";
16
17
  @api hash: string | null = null;
17
18
 
18
19
  @api
19
20
  private get ariaLevel(): string {
21
+ // Really Dark Magic (TM)
20
22
  return this._ariaLevel || "2";
21
23
  }
22
24
  private set ariaLevel(value: string | null) {
@@ -11,7 +11,7 @@ export default class Toc extends LightningElement {
11
11
  const newPageReference = { ...this.pageReference };
12
12
  // When moving to the new navigation component
13
13
  //const target = event.detail.name.split('-')
14
- const target = event.currentTarget.dataset.id.split("-");
14
+ const target = (event.currentTarget as any).dataset.id.split("-");
15
15
  newPageReference.contentDocumentId = target[0] + ".htm";
16
16
  newPageReference.hash = target[1];
17
17
  this.dispatchEvent(
@@ -64,7 +64,7 @@ export interface Header extends Element {
64
64
  bailHref: string;
65
65
  bailLabel: string;
66
66
  languages: Array<DocLanguage>;
67
- language: string;
67
+ language?: string;
68
68
  headerHref: string;
69
69
  }
70
70
 
@@ -12,15 +12,15 @@ import {
12
12
  PageReference,
13
13
  TocMap
14
14
  } from "./types";
15
- import { SearchSyncer } from "docUtils/SearchSyncer";
16
15
  import { LightningElementWithState } from "docBaseElements/lightningElementWithState";
17
16
  import { oldVersionDocInfo } from "docUtils/utils";
18
17
  import { Breadcrumb, DocPhaseInfo, Language } from "typings/custom";
19
18
  import { track as trackGTM } from "dxUtils/analytics";
20
19
  import { CoveoAnalyticsClient } from "coveo.analytics";
20
+ import { SearchSyncer } from "docUtils/searchSyncer";
21
21
 
22
22
  // TODO: Imitating from actual implementation as doc-content use it like this. We should refactor it later.
23
- const handleContentError = (error): void => console.log(error);
23
+ const handleContentError = (error: any): void => console.log(error);
24
24
 
25
25
  const PIXEL_PER_CHARACTER_MAP: { [key: string]: number } = {
26
26
  default: 7.7,
@@ -31,6 +31,7 @@ export default class DocXmlContent extends LightningElementWithState<{
31
31
  isFetchingDocument: boolean;
32
32
  isFetchingContent: boolean;
33
33
  lastHighlightedSearch: string;
34
+ internalLinkClicked: boolean;
34
35
  }> {
35
36
  @api apiDomain = "https://developer.salesforce.com";
36
37
  @api coveoOrganizationId!: string;
@@ -60,14 +61,14 @@ export default class DocXmlContent extends LightningElementWithState<{
60
61
 
61
62
  private availableLanguages: Array<DocLanguage> = [];
62
63
  private availableVersions: Array<DocVersion> = [];
63
- private contentProvider: FetchContent;
64
+ private contentProvider?: FetchContent;
64
65
  private docContent = "";
65
- private language: DocLanguage = null;
66
+ private language?: DocLanguage | null = null;
66
67
  private loaded = false;
67
68
  private pdfUrl = "";
68
69
  private tocMap: TocMap = {};
69
- private sidebarContent: Array<TreeNode> = null;
70
- private version: DocVersion = null;
70
+ private sidebarContent: Array<TreeNode> | null = null;
71
+ private version: DocVersion | null = null;
71
72
  private docTitle = "";
72
73
  private _pathName = "";
73
74
  private _pageHeader?: Header;
@@ -174,8 +175,8 @@ export default class DocXmlContent extends LightningElementWithState<{
174
175
  renderedCallback(): void {
175
176
  this.setState({ internalLinkClicked: true });
176
177
  const urlSectionLink =
177
- this.pageReference?.hash?.split("#").length > 1
178
- ? this.pageReference.hash.split("#")[1]
178
+ this.pageReference?.hash?.split("#").length! > 1
179
+ ? this.pageReference.hash!.split("#")[1]
179
180
  : this.pageReference?.hash;
180
181
 
181
182
  const contentEl = this.template.querySelector("doc-content");
@@ -223,15 +224,15 @@ export default class DocXmlContent extends LightningElementWithState<{
223
224
  }
224
225
  }
225
226
 
226
- private get languageId(): string {
227
- return this.language.id.replace("-", "_");
227
+ private get languageId(): string | undefined {
228
+ return this.language?.id.replace("-", "_");
228
229
  }
229
230
 
230
- private get releaseVersionId(): string {
231
- return this.version.id;
231
+ private get releaseVersionId(): string | undefined {
232
+ return this.version?.id;
232
233
  }
233
234
 
234
- private get deliverable(): string {
235
+ private get deliverable(): string | undefined {
235
236
  return this.pageReference.deliverable;
236
237
  }
237
238
 
@@ -252,10 +253,11 @@ export default class DocXmlContent extends LightningElementWithState<{
252
253
  }
253
254
 
254
255
  private get coveoAdvancedQueryConfig(): CoveoAdvancedQueryXMLConfig {
255
- const config: { locale: string; topicid: string; version?: string } = {
256
- locale: this.languageId,
257
- topicid: this.deliverable
258
- };
256
+ const config: { locale?: string; topicid?: string; version?: string } =
257
+ {
258
+ locale: this.languageId,
259
+ topicid: this.deliverable
260
+ };
259
261
 
260
262
  if (this.releaseVersionId && this.releaseVersionId !== "noversion") {
261
263
  config.version = this.releaseVersionId;
@@ -266,7 +268,7 @@ export default class DocXmlContent extends LightningElementWithState<{
266
268
 
267
269
  private get pageHeader(): Header {
268
270
  if (!this._pageHeader) {
269
- this._pageHeader = document.querySelector("doc-header");
271
+ this._pageHeader = document.querySelector("doc-header")!;
270
272
  }
271
273
 
272
274
  return this._pageHeader;
@@ -309,7 +311,7 @@ export default class DocXmlContent extends LightningElementWithState<{
309
311
 
310
312
  private get breadcrumbPixelPerCharacter() {
311
313
  return (
312
- PIXEL_PER_CHARACTER_MAP[this.language.id] ||
314
+ PIXEL_PER_CHARACTER_MAP[this.language!.id] ||
313
315
  PIXEL_PER_CHARACTER_MAP.default
314
316
  );
315
317
  }
@@ -358,7 +360,7 @@ export default class DocXmlContent extends LightningElementWithState<{
358
360
  this.updateUrl();
359
361
  }
360
362
 
361
- handleLanguageChange = (event: CustomEvent<string>): Promise<void> => {
363
+ handleLanguageChange = (event: any) => {
362
364
  if (this.language && this.language.id === event.detail) {
363
365
  return;
364
366
  }
@@ -366,7 +368,7 @@ export default class DocXmlContent extends LightningElementWithState<{
366
368
  this.language = this.availableLanguages.find(
367
369
  ({ id }) => id === event.detail
368
370
  );
369
- this.pageReference.docId = this.language.url;
371
+ this.pageReference.docId = this.language!.url;
370
372
 
371
373
  trackGTM(event.target!, "custEv_ctaLinkClick", {
372
374
  click_text: event.detail,
@@ -453,8 +455,8 @@ export default class DocXmlContent extends LightningElementWithState<{
453
455
  this.setState({
454
456
  isFetchingDocument: true
455
457
  });
456
- const data = await this.contentProvider.fetchDocumentData(
457
- this.pageReference.docId
458
+ const data = await this.contentProvider!.fetchDocumentData(
459
+ this.pageReference.docId!
458
460
  );
459
461
 
460
462
  // This could be a 404 scenario.
@@ -517,12 +519,12 @@ export default class DocXmlContent extends LightningElementWithState<{
517
519
  this.setState({
518
520
  isFetchingContent: true
519
521
  });
520
- const data = await this.contentProvider.fetchContent(
521
- this.pageReference.deliverable,
522
- this.pageReference.contentDocumentId,
522
+ const data = await this.contentProvider!.fetchContent(
523
+ this.pageReference.deliverable!,
524
+ this.pageReference.contentDocumentId!,
523
525
  {
524
- language: this.language.id,
525
- version: this.version.id
526
+ language: this.language!.id,
527
+ version: this.version!.id
526
528
  }
527
529
  );
528
530
 
@@ -586,23 +588,26 @@ export default class DocXmlContent extends LightningElementWithState<{
586
588
  }
587
589
 
588
590
  private updateSearchInput(searchParam: string): void {
589
- this.template
590
- .querySelector("doc-content-layout")
591
- ?.setSidebarInputValue(searchParam);
591
+ (
592
+ this.template.querySelector("doc-content-layout") as any
593
+ )?.setSidebarInputValue(searchParam);
592
594
  }
593
595
 
594
596
  private pageReferenceToString(reference: PageReference): string {
595
597
  const { page, docId, deliverable, contentDocumentId, hash, search } =
596
598
  reference;
597
599
  return `/${page}/${docId}/${deliverable}/${contentDocumentId}${this.normalizeSearch(
598
- search
600
+ search!
599
601
  )}${this.normalizeHash(hash)}`;
600
602
  }
601
603
 
602
- private normalizeUrlPart(part: string, sentinel: string): string {
604
+ private normalizeUrlPart(
605
+ part: string | undefined,
606
+ sentinel: string
607
+ ): string {
603
608
  return (
604
609
  (part &&
605
- (part.startsWith(sentinel) ? part : `${sentinel}${part}`)) ||
610
+ (part.startsWith(sentinel!) ? part : `${sentinel}${part}`)) ||
606
611
  ""
607
612
  );
608
613
  }
@@ -611,16 +616,16 @@ export default class DocXmlContent extends LightningElementWithState<{
611
616
  return this.normalizeUrlPart(search, "?");
612
617
  }
613
618
 
614
- private normalizeHash(hash: string): string {
619
+ private normalizeHash(hash?: string): string {
615
620
  return this.normalizeUrlPart(hash, "#");
616
621
  }
617
622
 
618
623
  private getComposedTitle(
619
- topicTitle: string | undefined,
624
+ topicTitle: string | null | undefined,
620
625
  docTitle: string | undefined
621
626
  ): string {
622
627
  // map to avoid duplicates
623
- const titleMap = {};
628
+ const titleMap: { [key: string]: any } = {};
624
629
  if (topicTitle) {
625
630
  // sometimes the h1 tag text (which is docSubTitle) contains text with new line character. For e.g, "Bulk API 2.0 Older\n Documentation",
626
631
  // here it contains \n in the text context which needs to be removed
@@ -757,7 +762,7 @@ export default class DocXmlContent extends LightningElementWithState<{
757
762
  const headTag = document.getElementsByTagName("head");
758
763
  // this checks if the selected version is not the latest version,
759
764
  // then it adds the noindex, follow meta tag to the older version pages.
760
- const versionId = this.version.id;
765
+ const versionId = this.version!.id;
761
766
  const docId = this.pageReference.docId;
762
767
 
763
768
  // SEO fix:
package/LICENSE DELETED
@@ -1,12 +0,0 @@
1
- Copyright (c) 2020, Salesforce.com, Inc.
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5
-
6
- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7
-
8
- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9
-
10
- * Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11
-
12
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -1,85 +0,0 @@
1
- export interface SearchSyncerConstructorArgs {
2
- callbacks: {
3
- onSearchChange?: (nextSearchString: string) => unknown;
4
- onUrlChange?: (nextSearchString: string) => unknown;
5
- };
6
- eventName: string;
7
- historyMethod?:
8
- | typeof window.history.pushState
9
- | typeof window.history.replaceState;
10
- searchParam: string;
11
- shouldStopPropagation?: boolean;
12
- target: EventTarget;
13
- }
14
-
15
- export class SearchSyncer {
16
- private callbacks: SearchSyncerConstructorArgs["callbacks"];
17
- private eventName: SearchSyncerConstructorArgs["eventName"];
18
- private historyMethod: SearchSyncerConstructorArgs["historyMethod"];
19
- private searchParam: SearchSyncerConstructorArgs["searchParam"];
20
- private shouldStopPropagation: SearchSyncerConstructorArgs["shouldStopPropagation"];
21
- private target: SearchSyncerConstructorArgs["target"];
22
-
23
- constructor({
24
- callbacks = {},
25
- eventName,
26
- historyMethod = window.history.pushState,
27
- searchParam,
28
- shouldStopPropagation = true,
29
- target
30
- }: SearchSyncerConstructorArgs) {
31
- this.callbacks = callbacks;
32
- this.eventName = eventName;
33
- this.historyMethod = historyMethod.bind(window.history);
34
- this.searchParam = searchParam;
35
- this.shouldStopPropagation = shouldStopPropagation;
36
- this.target = target;
37
- }
38
-
39
- public init = (): void => {
40
- this.target.addEventListener(this.eventName, this.handleSearchChange);
41
- this.target.addEventListener("popstate", this.handlePopState);
42
- };
43
-
44
- public dispose = (): void => {
45
- this.target.removeEventListener(
46
- this.eventName,
47
- this.handleSearchChange
48
- );
49
- this.target.removeEventListener("popstate", this.handlePopState);
50
- this.target = undefined;
51
- this.callbacks.onSearchChange = undefined;
52
- this.callbacks.onUrlChange = undefined;
53
- };
54
-
55
- private handleSearchChange = (event: Event): void => {
56
- if (this.shouldStopPropagation) {
57
- event.stopPropagation();
58
- }
59
-
60
- const { detail: searchTerm } = event as CustomEvent<string>;
61
- const fullUrl = new URL(window.location.href);
62
- const { searchParams } = fullUrl;
63
-
64
- if (searchTerm) {
65
- searchParams.set(this.searchParam, searchTerm);
66
- } else {
67
- searchParams.delete(this.searchParam);
68
- }
69
-
70
- const nextSearchString = searchParams.toString();
71
-
72
- if (this.callbacks.onSearchChange) {
73
- this.callbacks.onSearchChange(nextSearchString);
74
- }
75
-
76
- fullUrl.search = nextSearchString;
77
- this.historyMethod({}, "", fullUrl.toString());
78
- };
79
-
80
- private handlePopState = (): void => {
81
- if (this.callbacks.onUrlChange) {
82
- this.callbacks.onUrlChange(window.location.search);
83
- }
84
- };
85
- }