@salesforcedevs/docs-components 1.32.0-alpha.9 → 1.32.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,12 +1,15 @@
1
1
  /* eslint-disable @lwc/lwc/no-document-query */
2
- import { LightningElement, api, track } from "lwc";
3
- import { closest } from "kagekiri";
4
- import { fetchHasResults } from "dxUtils/data360Search";
2
+ import { LightningElement, api, createElement, track } from "lwc";
3
+ import { closest, querySelector } from "kagekiri";
5
4
  import { toJson, normalizeBoolean } from "dxUtils/normalizers";
6
5
  import { highlightTerms } from "dxUtils/highlight";
7
6
  import { SearchSyncer } from "docUtils/searchSyncer";
8
7
  import type { OptionWithLink } from "typings/custom";
9
8
  import { buildDocLinkClickHandler } from "dxUtils/analytics";
9
+ import ContentActionToolbar from "doc/contentActionToolbar";
10
+
11
+ const CONTENT_ACTION_TOOLBAR_TAG = "doc-content-action-toolbar";
12
+ const PAGE_HEADING_SELECTOR = "h1, doc-heading";
10
13
 
11
14
  type AnchorMap = { [key: string]: { intersect: boolean; id: string } };
12
15
 
@@ -29,6 +32,35 @@ const HIGHLIGHTABLE_SELECTOR = [
29
32
  ].join(",");
30
33
  export const OBSERVER_ATTACH_WAIT_TIME = 500;
31
34
 
35
+ const DEFAULT_READING_TIME_LOCALE = "en-us";
36
+
37
+ /**
38
+ * Localized "minute read" templates. `{minutes}` is replaced with the rounded
39
+ * reading-time value. Only displayed when reading time is greater than 1, so
40
+ * plural forms are always appropriate. Keys match the locales declared in
41
+ * sfdocs (and the doc-locale-banner) so that a localized document automatically
42
+ * gets a localized reading-time label.
43
+ */
44
+ export const READING_TIME_LABELS: Record<string, string> = {
45
+ "en-us": "{minutes} minute read",
46
+ "ja-jp": "読了時間 {minutes} 分",
47
+ "zh-cn": "阅读时间 {minutes} 分钟",
48
+ "zh-tw": "閱讀時間 {minutes} 分鐘",
49
+ "fr-fr": "Lecture de {minutes} minutes",
50
+ "de-de": "{minutes} Minuten Lesezeit",
51
+ "it-it": "{minutes} minuti di lettura",
52
+ "ko-kr": "읽는 데 {minutes}분",
53
+ "pt-br": "{minutes} minutos de leitura",
54
+ "es-mx": "{minutes} minutos de lectura",
55
+ "es-es": "{minutes} minutos de lectura",
56
+ "ru-ru": "Время чтения: {minutes} мин",
57
+ "fi-fi": "{minutes} minuutin lukuaika",
58
+ "da-dk": "{minutes} minutters læsning",
59
+ "sv-se": "{minutes} minuters läsning",
60
+ "nl-nl": "{minutes} minuten leestijd",
61
+ "nb-no": "{minutes} minutters lesetid"
62
+ };
63
+
32
64
  export default class ContentLayout extends LightningElement {
33
65
  @api sidebarValue!: string;
34
66
  @api sidebarHeader!: string;
@@ -43,15 +75,6 @@ export default class ContentLayout extends LightningElement {
43
75
  @api brand: any;
44
76
  @api emptyStateMessage?: string;
45
77
 
46
- @api
47
- get enableDataCloudSearch() {
48
- return this._enableDataCloudSearch;
49
- }
50
- set enableDataCloudSearch(value) {
51
- this._enableDataCloudSearch = normalizeBoolean(value);
52
- }
53
- private _enableDataCloudSearch = false;
54
-
55
78
  // This is needed for now to prevent failing snapshot tests due to links in the footer
56
79
  @api
57
80
  get showFooter() {
@@ -76,6 +99,17 @@ export default class ContentLayout extends LightningElement {
76
99
  /** Optional origin URL for the footer MFE (e.g. wp-json endpoint). Passed through to dx-footer. */
77
100
  @api origin: string | null = null;
78
101
 
102
+ /** Controls whether the content action toolbar is displayed. */
103
+ @api
104
+ get showContentActionToolbar() {
105
+ return this._showContentActionToolbar;
106
+ }
107
+ set showContentActionToolbar(value) {
108
+ this._showContentActionToolbar = normalizeBoolean(value);
109
+ this.updateContentActionToolbar();
110
+ }
111
+ private _showContentActionToolbar = false;
112
+
79
113
  @api
80
114
  get breadcrumbs() {
81
115
  return this._breadcrumbs;
@@ -118,35 +152,9 @@ export default class ContentLayout extends LightningElement {
118
152
  );
119
153
  }
120
154
 
121
- /** Show Data 360 sidebar only when not using old sidebar and the page has searchable results. */
122
- protected get showDataCloudSidebar(): boolean {
123
- return (
124
- this.enableDataCloudSearch &&
125
- !this.useOldSidebar &&
126
- this.hasDataCloudResults === true
127
- );
128
- }
129
-
130
- /** Show legacy sidebar when explicitly requested or when Data 360 has no results. Don't show until we know (avoids flash). */
131
- protected get showOldSidebar(): boolean {
132
- return (
133
- this.useOldSidebar === true ||
134
- !this.enableDataCloudSearch ||
135
- this.hasDataCloudResults === false
136
- );
137
- }
138
-
139
- /** Show a space-holding placeholder while we're deciding which sidebar to show (avoids layout shift). */
140
- protected get showSidebarPlaceholder(): boolean {
141
- return !this.showDataCloudSidebar && !this.showOldSidebar;
142
- }
143
-
144
155
  @track
145
156
  protected _sidebarContent: unknown;
146
157
 
147
- @track
148
- protected hasDataCloudResults: boolean | null = null;
149
-
150
158
  protected _breadcrumbs = null;
151
159
 
152
160
  @track
@@ -159,6 +167,7 @@ export default class ContentLayout extends LightningElement {
159
167
  protected hasRendered: boolean = false;
160
168
  protected contentLoaded: boolean = false;
161
169
  protected sidebarOpen: boolean = false;
170
+ protected contentActionToolbarElement: HTMLElement | null = null;
162
171
 
163
172
  get shouldDisplayFeedback() {
164
173
  return this.contentLoaded && typeof Sprig !== "undefined";
@@ -209,6 +218,19 @@ export default class ContentLayout extends LightningElement {
209
218
  return this.readingTime != null && this.readingTime > 1;
210
219
  }
211
220
 
221
+ /**
222
+ * Localized "X minute read" string for the current document language.
223
+ * Falls back to the default (en-us) template when the language is missing
224
+ * or has no translation.
225
+ */
226
+ get readingTimeLabel(): string {
227
+ const localeKey = (this.language || "").toLowerCase();
228
+ const template =
229
+ READING_TIME_LABELS[localeKey] ||
230
+ READING_TIME_LABELS[DEFAULT_READING_TIME_LOCALE];
231
+ return template.replace("{minutes}", String(this.readingTime));
232
+ }
233
+
212
234
  /** When origin is provided, pass it to the footer; otherwise use dx-footer's default. */
213
235
  get effectiveFooterOrigin(): string {
214
236
  return (
@@ -217,11 +239,6 @@ export default class ContentLayout extends LightningElement {
217
239
  }
218
240
 
219
241
  connectedCallback(): void {
220
- if (this.enableDataCloudSearch && !this.useOldSidebar) {
221
- fetchHasResults().then((hasResults: boolean) => {
222
- this.hasDataCloudResults = hasResults;
223
- });
224
- }
225
242
  const hasParentHighlightListener = closest(
226
243
  "doc-xml-content",
227
244
  this.template.host
@@ -256,6 +273,8 @@ export default class ContentLayout extends LightningElement {
256
273
  window.addEventListener("scroll", this.adjustNavPosition);
257
274
  window.addEventListener("resize", this.adjustNavPosition);
258
275
 
276
+ this.updateContentActionToolbar();
277
+
259
278
  if (!this.hasRendered) {
260
279
  this.hasRendered = true;
261
280
  this.restoreScroll();
@@ -265,6 +284,44 @@ export default class ContentLayout extends LightningElement {
265
284
  }
266
285
  }
267
286
 
287
+ /**
288
+ * Inserts the content action toolbar into the slotted content immediately
289
+ * after the first heading (any level) found inside the content body. This is
290
+ * the page's H1 when present, otherwise the first heading in document order.
291
+ */
292
+ protected updateContentActionToolbar(): void {
293
+ if (!this.showContentActionToolbar || !this.sidebarValue) {
294
+ this.removeContentActionToolbar();
295
+ return;
296
+ }
297
+
298
+ const heading = querySelector(
299
+ PAGE_HEADING_SELECTOR,
300
+ this.template.host
301
+ ) as HTMLElement | null;
302
+
303
+ if (!heading) {
304
+ return;
305
+ }
306
+
307
+ const toolbar = (this.contentActionToolbarElement ??
308
+ createElement(CONTENT_ACTION_TOOLBAR_TAG, {
309
+ is: ContentActionToolbar
310
+ })) as HTMLElement & { pageUrl?: string };
311
+
312
+ toolbar.pageUrl = this.sidebarValue;
313
+
314
+ if (toolbar.previousElementSibling !== heading) {
315
+ heading.parentNode?.insertBefore(toolbar, heading.nextSibling);
316
+ }
317
+
318
+ this.contentActionToolbarElement = toolbar;
319
+ }
320
+
321
+ protected removeContentActionToolbar(): void {
322
+ this.contentActionToolbarElement?.remove();
323
+ }
324
+
268
325
  disconnectedCallback(): void {
269
326
  this.disconnectObserver();
270
327
  window.removeEventListener(
@@ -280,6 +337,9 @@ export default class ContentLayout extends LightningElement {
280
337
 
281
338
  // Remove link click handler
282
339
  this.template.removeEventListener("click", this.handleLinkClick);
340
+
341
+ this.removeContentActionToolbar();
342
+ this.contentActionToolbarElement = null;
283
343
  }
284
344
 
285
345
  restoreScroll() {
@@ -298,9 +358,7 @@ export default class ContentLayout extends LightningElement {
298
358
  We have to account for the global nav changing height due to animations.
299
359
  */
300
360
  adjustNavPosition = () => {
301
- const sidebarEl =
302
- this.template.querySelector("dx-sidebar") ||
303
- this.template.querySelector("dx-sidebar-old");
361
+ const sidebarEl = this.template.querySelector("dx-sidebar-old");
304
362
  const globalNavEl = document.querySelector(
305
363
  "hgf-c360nav"
306
364
  ) as HTMLElement;
@@ -524,6 +582,7 @@ export default class ContentLayout extends LightningElement {
524
582
 
525
583
  onSlotChange(): void {
526
584
  this.updateRNB();
585
+ this.updateContentActionToolbar();
527
586
  this.contentLoaded = true;
528
587
  }
529
588
 
@@ -13,7 +13,6 @@
13
13
  onclick={onLinkClick}
14
14
  class="dev-center-content"
15
15
  >
16
- <dx-icon symbol="back"></dx-icon>
17
16
  <dx-icon
18
17
  class="brand-icon"
19
18
  lwc:if={devCenter.icon}
@@ -1,7 +1,6 @@
1
1
  <template>
2
2
  <div class="content">
3
3
  <dx-sidebar-old
4
- lwc:if={useOldSidebar}
5
4
  class="is-sticky left-nav-bar"
6
5
  trees={sidebarContent}
7
6
  value={sidebarValue}
@@ -16,16 +15,6 @@
16
15
  >
17
16
  <slot name="sidebar-header" slot="version-picker"></slot>
18
17
  </dx-sidebar-old>
19
- <dx-sidebar
20
- lwc:else
21
- class="is-sticky left-nav-bar"
22
- trees={sidebarContent}
23
- value={sidebarValue}
24
- header={sidebarHeader}
25
- ontogglesidebar={onToggleSidebar}
26
- >
27
- <slot name="sidebar-header" slot="version-picker"></slot>
28
- </dx-sidebar>
29
18
  <div class="content-body-doc-phase-container">
30
19
  <div class="doc-phase-wrapper">
31
20
  <slot name="doc-phase"></slot>
@@ -52,7 +41,7 @@
52
41
  ></path>
53
42
  </g>
54
43
  </svg>
55
- {readingTime} minute read
44
+ {readingTimeLabel}
56
45
  </div>
57
46
  <slot onslotchange={onSlotChange}></slot>
58
47
  <doc-sprig-survey
@@ -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
@@ -2,7 +2,6 @@
2
2
  <doc-content-layout
3
3
  lwc:if={displayContent}
4
4
  lwc:ref="docContentLayout"
5
- enable-data-cloud-search
6
5
  sidebar-header={docTitle}
7
6
  sidebar-content={sidebarContent}
8
7
  sidebar-value={sidebarValue}
@@ -254,6 +254,17 @@ export default class DocXmlContent extends LightningElementWithState<{
254
254
  return this.pageReference.deliverable;
255
255
  }
256
256
 
257
+ private get useOldSidebar(): boolean {
258
+ // Coveo is enabled and the version is greater than 51 (within the latest 3 versions)
259
+ // TODO: we need a better fix for version number check
260
+ return !(
261
+ !this.version?.releaseVersion ||
262
+ (this.version?.releaseVersion &&
263
+ parseInt(this.version.releaseVersion.replace("v", ""), 10) >=
264
+ 53)
265
+ );
266
+ }
267
+
257
268
  private get pageHeader(): Header {
258
269
  if (!this._pageHeader) {
259
270
  this._pageHeader = document.querySelector("doc-header")!;
@@ -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
+ }