@salesforcedevs/docs-components 1.30.1-node22-3 → 1.31.0-md-alpha

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.
@@ -2,6 +2,7 @@
2
2
  import { createElement, LightningElement, api } from "lwc";
3
3
  import DocPhase from "doc/phase";
4
4
  import DxFooter from "dx/footer";
5
+ import DxIcon from "dx/icon";
5
6
  import SprigSurvey from "doc/sprigSurvey";
6
7
  import { throttle } from "throttle-debounce";
7
8
  import { pollUntil } from "dxUtils/async";
@@ -14,11 +15,19 @@ declare global {
14
15
 
15
16
  declare const Sprig: (eventType: string, eventName: string) => void;
16
17
 
18
+ type ReferenceTopic = {
19
+ link?: { href?: string };
20
+ children?: ReferenceTopic[];
21
+ };
22
+
17
23
  type ReferenceItem = {
18
24
  source: string;
19
25
  href: string;
26
+ title?: string;
20
27
  isSelected?: boolean;
21
28
  docPhase?: string | null;
29
+ referenceType?: string;
30
+ topic?: ReferenceTopic;
22
31
  };
23
32
 
24
33
  type ReferenceConfig = {
@@ -28,6 +37,7 @@ type ReferenceConfig = {
28
37
  const SCROLL_THROTTLE_DELAY = 50;
29
38
  const ELEMENT_TIMEOUT = 10000;
30
39
  const ELEMENT_CHECK_INTERVAL = 100;
40
+ const REFERENCES_SEGMENT = "/references/";
31
41
 
32
42
  export default class RedocReference extends LightningElement {
33
43
  private _referenceConfig: ReferenceConfig = { refList: [] };
@@ -38,6 +48,12 @@ export default class RedocReference extends LightningElement {
38
48
  private docPhaseWrapperElement: Element | null = null;
39
49
  private lastSidebarTop = 0;
40
50
 
51
+ /**
52
+ * History length captured at mount (pre-Redoc), used by `onBackClick` to
53
+ * distinguish in-tab navigation (> 1) from a fresh entry (=== 1).
54
+ */
55
+ private initialHistoryLength = 0;
56
+
41
57
  showError = false;
42
58
 
43
59
  @api
@@ -71,6 +87,75 @@ export default class RedocReference extends LightningElement {
71
87
  /** Optional origin URL for the footer MFE (e.g. wp-json endpoint). Passed through to dx-footer. */
72
88
  @api origin: string | null = null;
73
89
 
90
+ /**
91
+ * Project title (same value passed to `<doc-header>` as `subtitle`). Used
92
+ * inside the Redoc-rendered UI to label the parent project.
93
+ */
94
+ @api projectTitle: string | null = "All Reference";
95
+
96
+ get specTitle(): string | null {
97
+ return this.getSelectedReference()?.title ?? null;
98
+ }
99
+
100
+ /**
101
+ * Whether to show the project header (only for multi-spec reference sets).
102
+ */
103
+ get showRedocHeader(): boolean {
104
+ const refCount = this._referenceConfig?.refList?.length ?? 0;
105
+ const isMultiSpecSet = refCount > 1;
106
+ return isMultiSpecSet && !!(this.projectTitle || this.specTitle);
107
+ }
108
+
109
+ /**
110
+ * Navigates back to reference doc.
111
+ */
112
+ private onBackClick = (event: Event): void => {
113
+ event.preventDefault();
114
+ const referrerHref = this.getSameOriginReferrerHref();
115
+ if (referrerHref) {
116
+ window.location.href = referrerHref;
117
+ return;
118
+ }
119
+ const fallbackHref = this.getReferencesRootHref();
120
+ if (fallbackHref) {
121
+ window.location.href = fallbackHref;
122
+ }
123
+ };
124
+
125
+ /**
126
+ * Returns the referrer URL when the page was reached via in-tab navigation
127
+ * from a same-origin page; otherwise `null`. Both `initialHistoryLength`
128
+ * and `document.referrer` are checked since neither signal is reliable on
129
+ * its own.
130
+ */
131
+ private getSameOriginReferrerHref(): string | null {
132
+ if (this.initialHistoryLength <= 1 || !document.referrer) {
133
+ return null;
134
+ }
135
+ try {
136
+ const referrerUrl = new URL(document.referrer);
137
+ if (referrerUrl.origin !== window.location.origin) {
138
+ return null;
139
+ }
140
+ return referrerUrl.href;
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Derives the project's `.../references` root from the current URL by
148
+ * trimming any trailing reference id (and deeper segments). Returns null
149
+ * when the URL doesn't contain a `/references` segment.
150
+ */
151
+ private getReferencesRootHref(): string | null {
152
+ const { pathname } = window.location;
153
+ const idx = pathname.lastIndexOf(REFERENCES_SEGMENT);
154
+ return idx === -1
155
+ ? null
156
+ : pathname.slice(0, idx + REFERENCES_SEGMENT.length);
157
+ }
158
+
74
159
  /** When origin is provided, pass it to the footer; otherwise use dx-footer's default. */
75
160
  get effectiveFooterOrigin(): string {
76
161
  return (
@@ -79,6 +164,10 @@ export default class RedocReference extends LightningElement {
79
164
  }
80
165
 
81
166
  connectedCallback(): void {
167
+ // Snapshot history length before Redoc pushes its own hash entries,
168
+ // so it reflects real in-tab navigation rather than Redoc's churn.
169
+ this.initialHistoryLength = window.history.length;
170
+
82
171
  window.addEventListener("scroll", this.handleScrollAndResize);
83
172
  window.addEventListener("resize", this.handleScrollAndResize);
84
173
  }
@@ -304,6 +393,9 @@ export default class RedocReference extends LightningElement {
304
393
 
305
394
  this.appendFooterItems(apiContentDiv);
306
395
 
396
+ // Inject the multi-spec project header into Redoc's left menu only.
397
+ this.insertProjectHeaderInMenu(redocContainer);
398
+
307
399
  // Wait for footer to be rendered before updating styles
308
400
  requestAnimationFrame(() => {
309
401
  this.updateRedocThirdColumnStyle(redocContainer);
@@ -316,6 +408,65 @@ export default class RedocReference extends LightningElement {
316
408
  }
317
409
  }
318
410
 
411
+ /**
412
+ * Inserts the project header into Redoc for multi-spec reference sets.
413
+ */
414
+ private insertProjectHeaderInMenu(redocContainer: HTMLElement): void {
415
+ if (!this.showRedocHeader) {
416
+ return;
417
+ }
418
+
419
+ // Select the LNB and content area of Redoc and insert the requried header.
420
+ redocContainer
421
+ .querySelectorAll<HTMLElement>(".menu-content, .api-content")
422
+ .forEach((target) => {
423
+ target.insertBefore(
424
+ this.buildProjectHeaderDom(),
425
+ target.firstChild
426
+ );
427
+ });
428
+ }
429
+
430
+ /**
431
+ * Builds a fresh project-title/spec-title header DOM node.
432
+ */
433
+ private buildProjectHeaderDom(): HTMLElement {
434
+ const wrapper = document.createElement("div");
435
+ wrapper.className = "redoc-project-header";
436
+
437
+ if (this.projectTitle) {
438
+ const backLink = document.createElement("a");
439
+ backLink.className = "redoc-project-back";
440
+ backLink.href = "#";
441
+ backLink.addEventListener("click", this.onBackClick);
442
+
443
+ const icon = createElement("dx-icon", { is: DxIcon });
444
+ Object.assign(icon, {
445
+ sprite: "utility",
446
+ symbol: "back",
447
+ size: "medium"
448
+ });
449
+ icon.classList.add("redoc-project-back-arrow");
450
+
451
+ const label = document.createElement("span");
452
+ label.className = "redoc-project-title";
453
+ label.textContent = this.projectTitle;
454
+
455
+ backLink.appendChild(icon);
456
+ backLink.appendChild(label);
457
+ wrapper.appendChild(backLink);
458
+ }
459
+
460
+ if (this.specTitle) {
461
+ const specEl = document.createElement("h2");
462
+ specEl.className = "redoc-spec-title dx-text-display-7";
463
+ specEl.textContent = this.specTitle;
464
+ wrapper.appendChild(specEl);
465
+ }
466
+
467
+ return wrapper;
468
+ }
469
+
319
470
  // Waits for Redoc's API content element to be rendered
320
471
  private async waitForApiContent(
321
472
  container: HTMLElement
@@ -0,0 +1,160 @@
1
+ // Neutral shared core for the DWO unified-search UI (P4.1).
2
+ // The ONLY place a /api/search URL is built, and the ONLY place the HTTP
3
+ // contract lives. No LWC / arch / dx imports — browser DOM APIs only.
4
+
5
+ export interface SearchResult {
6
+ url: string;
7
+ title: string;
8
+ description: string | null;
9
+ locale: string;
10
+ site: string | null;
11
+ contentType: string | null;
12
+ lastmod: string | null;
13
+ score: number;
14
+ lexScore: number;
15
+ semScore: number;
16
+ matchType: string;
17
+ }
18
+
19
+ export interface FacetBucket {
20
+ value: string;
21
+ count: number;
22
+ }
23
+
24
+ export type SortOption = "relevance" | "date";
25
+
26
+ export interface SearchResponse {
27
+ query: string;
28
+ locale: string;
29
+ site: string | null;
30
+ sort: SortOption;
31
+ limit: number;
32
+ offset: number;
33
+ total: number;
34
+ count: number;
35
+ facets: { contentType: FacetBucket[] };
36
+ results: SearchResult[];
37
+ }
38
+
39
+ export interface SearchRequest {
40
+ query: string;
41
+ locale: string;
42
+ site?: string | null;
43
+ type?: string | null;
44
+ sort?: SortOption;
45
+ limit?: number;
46
+ offset?: number;
47
+ page?: number;
48
+ }
49
+
50
+ export const DEFAULT_LIMIT = 20;
51
+
52
+ export const SORT_OPTIONS: SortOption[] = ["relevance", "date"];
53
+
54
+ export function isSortOption(v: unknown): v is SortOption {
55
+ return v === "relevance" || v === "date";
56
+ }
57
+
58
+ /**
59
+ * Build the query string for a /api/search request.
60
+ * - 'q' always carries the query.
61
+ * - 'lang' (lowercased) ONLY when the query has non-whitespace content.
62
+ * - 'site' / 'type' ONLY when truthy.
63
+ * - 'sort' ONLY when it is a known SortOption (never send an unknown sort).
64
+ * - 'limit' when provided.
65
+ * - OFFSET WINS OVER PAGE: if offset is given, emit it; otherwise derive
66
+ * offset from page. Never emit both, and never emit 'page'.
67
+ */
68
+ export function buildSearchParams(req: SearchRequest): URLSearchParams {
69
+ const params = new URLSearchParams();
70
+
71
+ params.set("q", req.query);
72
+
73
+ if (req.query.trim() !== "") {
74
+ params.set("lang", req.locale.toLowerCase());
75
+ }
76
+
77
+ if (req.site) {
78
+ params.set("site", req.site);
79
+ }
80
+ if (req.type) {
81
+ params.set("type", req.type);
82
+ }
83
+ if (isSortOption(req.sort)) {
84
+ params.set("sort", req.sort);
85
+ }
86
+ if (req.limit != null) {
87
+ params.set("limit", String(req.limit));
88
+ }
89
+
90
+ if (req.offset != null) {
91
+ params.set("offset", String(req.offset));
92
+ } else if (req.page != null) {
93
+ const limit = req.limit || DEFAULT_LIMIT;
94
+ const offset = (Math.max(1, req.page) - 1) * limit;
95
+ params.set("offset", String(offset));
96
+ }
97
+
98
+ return params;
99
+ }
100
+
101
+ export function searchUrl(
102
+ req: SearchRequest,
103
+ basePath = "/api/search"
104
+ ): string {
105
+ return `${basePath}?${buildSearchParams(req)}`;
106
+ }
107
+
108
+ export class SearchHttpError extends Error {
109
+ readonly status: number;
110
+
111
+ constructor(status: number, message?: string) {
112
+ super(message ?? `Search request failed with status ${status}`);
113
+ this.name = "SearchHttpError";
114
+ this.status = status;
115
+ }
116
+ }
117
+
118
+ export async function fetchSearch(
119
+ req: SearchRequest,
120
+ opts?: { signal?: AbortSignal; basePath?: string; fetchImpl?: typeof fetch }
121
+ ): Promise<SearchResponse> {
122
+ const fetchImpl = opts?.fetchImpl ?? fetch.bind(window);
123
+ const url = searchUrl(req, opts?.basePath);
124
+
125
+ const response = await fetchImpl(url, { signal: opts?.signal });
126
+
127
+ if (!response.ok) {
128
+ throw new SearchHttpError(response.status);
129
+ }
130
+
131
+ const data = (await response.json()) as Partial<SearchResponse>;
132
+
133
+ if (
134
+ !Array.isArray(data.results) ||
135
+ typeof data.total !== "number" ||
136
+ !data.facets ||
137
+ !Array.isArray(data.facets.contentType)
138
+ ) {
139
+ throw new Error(
140
+ "Malformed search response: missing results/total/facets"
141
+ );
142
+ }
143
+
144
+ return data as SearchResponse;
145
+ }
146
+
147
+ /**
148
+ * Decode HTML entities in a backend-supplied string (a response-normalization
149
+ * concern, ported from arch/searchList). No-op on plain strings.
150
+ */
151
+ export function decodeHtmlEntities(value: unknown): string {
152
+ if (typeof value !== "string" || value.length === 0) {
153
+ return String(value ?? "");
154
+ }
155
+ if (!value.includes("&")) {
156
+ return value;
157
+ }
158
+ const doc = new DOMParser().parseFromString(value, "text/html");
159
+ return doc.documentElement.textContent ?? "";
160
+ }
@@ -0,0 +1,90 @@
1
+ // Manual mock of SearchController for wrapper-test isolation.
2
+ //
3
+ // USE THE AUTOMOCK FORM — bare jest.mock with NO factory:
4
+ //
5
+ // jest.mock("docUtils/searchController");
6
+ //
7
+ // Despite docUtils/* being remapped by jest's moduleNameMapper ($1/$2/$2),
8
+ // jest still resolves the bare jest.mock() to this adjacent __mocks__ folder
9
+ // (verified by probe). Do NOT use a factory that re-requires the BARE
10
+ // specifier `docUtils/searchController/__mocks__/searchController` — the
11
+ // mapper rewrites it to .../__mocks__/searchController/searchController and
12
+ // jest cannot find it (also verified by probe). If a factory is ever needed,
13
+ // use a RELATIVE require: require("../__mocks__/searchController").
14
+
15
+ import type {
16
+ SearchControllerArgs,
17
+ SearchViewModel
18
+ } from "docUtils/searchController";
19
+
20
+ const baseViewModel: SearchViewModel = {
21
+ status: "idle",
22
+ query: "",
23
+ locale: "en-us",
24
+ selectedType: null,
25
+ sort: "relevance",
26
+ results: [],
27
+ contentTypeFacets: [],
28
+ total: 0,
29
+ count: 0,
30
+ limit: 20,
31
+ offset: 0,
32
+ page: 1,
33
+ totalPages: 1,
34
+ errorMessage: undefined
35
+ };
36
+
37
+ export class SearchController {
38
+ // eslint-disable-next-line no-use-before-define
39
+ static instances: SearchController[] = [];
40
+
41
+ args: SearchControllerArgs;
42
+ vm: SearchViewModel = { ...baseViewModel };
43
+ private subscribers = new Set<(vm: SearchViewModel) => void>();
44
+
45
+ init = jest.fn();
46
+ setQuery = jest.fn();
47
+ setLanguage = jest.fn();
48
+ setType = jest.fn();
49
+ setSort = jest.fn();
50
+ setPage = jest.fn();
51
+ buildUrl = jest.fn(() => "/api/search?q=&lang=en-us");
52
+ dispose = jest.fn();
53
+
54
+ constructor(args: SearchControllerArgs) {
55
+ this.args = args;
56
+ this.vm = {
57
+ ...baseViewModel,
58
+ locale: args.defaultLanguage ?? baseViewModel.locale,
59
+ limit: args.limit ?? baseViewModel.limit
60
+ };
61
+ SearchController.instances.push(this);
62
+ }
63
+
64
+ get viewModel(): SearchViewModel {
65
+ return this.vm;
66
+ }
67
+
68
+ get localeOptions() {
69
+ return this.args.catalog;
70
+ }
71
+
72
+ get showLocaleSelector(): boolean {
73
+ return this.args.catalog.length > 1;
74
+ }
75
+
76
+ subscribe = jest.fn((cb: (vm: SearchViewModel) => void): (() => void) => {
77
+ this.subscribers.add(cb);
78
+ return () => {
79
+ this.subscribers.delete(cb);
80
+ };
81
+ });
82
+
83
+ /** Test helper: push a (partial) view-model to all subscribers. */
84
+ __emit(vm: Partial<SearchViewModel>): void {
85
+ this.vm = { ...this.vm, ...vm };
86
+ for (const cb of this.subscribers) {
87
+ cb(this.vm);
88
+ }
89
+ }
90
+ }