@salesforce/ui-bundle-template-app-react-template-b2x 11.18.0 → 11.19.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.
Files changed (77) hide show
  1. package/dist/CHANGELOG.md +8 -0
  2. package/dist/force-app/main/default/uiBundles/reactexternalapp/package.json +4 -4
  3. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/{features/object-search/components → components}/ObjectBreadcrumb.tsx +7 -2
  4. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/api/distinctValuesService.ts +84 -0
  5. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/api/searchService.ts +71 -0
  6. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/MergedSearchResults.tsx +263 -0
  7. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/Search.tsx +185 -0
  8. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/SearchResults.tsx +77 -0
  9. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/SourceSection.tsx +166 -0
  10. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/controls/PaginationControls.tsx +185 -0
  11. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/controls/ScopeSelector.tsx +55 -0
  12. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/controls/SearchBar.tsx +55 -0
  13. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/controls/SortControl.tsx +62 -0
  14. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/ActiveFilters.tsx +61 -0
  15. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/DefaultFilterPanel.tsx +125 -0
  16. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/{object-search/components → search/components/filters}/FilterContext.tsx +7 -20
  17. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/BooleanFilter.tsx +50 -0
  18. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/DateRangeFilter.tsx +160 -0
  19. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/FilterFieldWrapper.tsx +26 -0
  20. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/MultiSelectFilter.tsx +88 -0
  21. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/NumericRangeFilter.tsx +78 -0
  22. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/SelectFilter.tsx +46 -0
  23. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/filters/inputs/TextFilter.tsx +52 -0
  24. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/components/results/DefaultResultRow.tsx +109 -0
  25. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/config.json +83 -0
  26. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/{object-search → search}/hooks/useAsyncData.ts +3 -10
  27. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/hooks/useDistinctValues.ts +59 -0
  28. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/hooks/useSearch.ts +703 -0
  29. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/index.ts +90 -0
  30. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/loadConfig.ts +14 -0
  31. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/queryBuilder.ts +156 -0
  32. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/types.ts +307 -0
  33. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/utils/debounce.ts +17 -0
  34. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/utils/fieldUtils.ts +14 -0
  35. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/utils/filterUtils.ts +285 -0
  36. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/search/utils/sortUtils.ts +34 -0
  37. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/pages/AccountObjectDetailPage.tsx +49 -16
  38. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/pages/AccountSearch.tsx +21 -293
  39. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/pages/Home.tsx +22 -7
  40. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/routes.tsx +1 -1
  41. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/{features/object-search/utils/fieldUtils.ts → utils/accountFields.ts} +9 -0
  42. package/dist/force-app/main/default/uiBundles/reactexternalapp/tsconfig.tsbuildinfo +1 -1
  43. package/dist/package-lock.json +2 -2
  44. package/dist/package.json +1 -1
  45. package/package.json +1 -1
  46. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/api/account/accountSearchService.ts +0 -46
  47. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/api/account/query/distinctAccountIndustries.graphql +0 -19
  48. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/api/account/query/distinctAccountTypes.graphql +0 -19
  49. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/api/account/query/searchAccounts.graphql +0 -51
  50. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/api/graphql-operations-types.ts +0 -11260
  51. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/api/accountSearchService.ts +0 -46
  52. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/api/query/distinctAccountIndustries.graphql +0 -19
  53. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/api/query/distinctAccountTypes.graphql +0 -19
  54. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/api/query/getAccountDetail.graphql +0 -121
  55. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/api/query/searchAccounts.graphql +0 -51
  56. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/pages/AccountObjectDetailPage.tsx +0 -355
  57. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/pages/AccountSearch.tsx +0 -304
  58. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/__examples__/pages/Home.tsx +0 -34
  59. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/api/objectSearchService.ts +0 -82
  60. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/ActiveFilters.tsx +0 -89
  61. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/PaginationControls.tsx +0 -109
  62. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/SearchBar.tsx +0 -41
  63. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/SortControl.tsx +0 -143
  64. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/BooleanFilter.tsx +0 -78
  65. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/DateFilter.tsx +0 -128
  66. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/DateRangeFilter.tsx +0 -70
  67. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/FilterFieldWrapper.tsx +0 -43
  68. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/MultiSelectFilter.tsx +0 -105
  69. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/NumericRangeFilter.tsx +0 -171
  70. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/SearchFilter.tsx +0 -52
  71. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/SelectFilter.tsx +0 -97
  72. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/components/filters/TextFilter.tsx +0 -93
  73. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/hooks/useDebouncedCallback.ts +0 -34
  74. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/hooks/useObjectSearchParams.ts +0 -254
  75. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/utils/debounce.ts +0 -25
  76. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/utils/filterUtils.ts +0 -404
  77. package/dist/force-app/main/default/uiBundles/reactexternalapp/src/features/object-search/utils/sortUtils.ts +0 -38
package/dist/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [11.19.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.18.0...v11.19.0) (2026-07-10)
7
+
8
+ **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
9
+
10
+
11
+
12
+
13
+
6
14
  ## [11.18.0](https://github.com/salesforce-experience-platform-emu/webapps/compare/v11.17.1...v11.18.0) (2026-07-10)
7
15
 
8
16
  **Note:** Version bump only for package @salesforce/ui-bundle-template-base-sfdx-project
@@ -18,8 +18,8 @@
18
18
  "graphql:schema": "node scripts/get-graphql-schema.mjs"
19
19
  },
20
20
  "dependencies": {
21
- "@salesforce/platform-sdk": "^11.18.0",
22
- "@salesforce/ui-bundle": "^11.18.0",
21
+ "@salesforce/platform-sdk": "^11.19.0",
22
+ "@salesforce/ui-bundle": "^11.19.0",
23
23
  "@tailwindcss/vite": "^4.1.17",
24
24
  "class-variance-authority": "^0.7.1",
25
25
  "clsx": "^2.1.1",
@@ -46,8 +46,8 @@
46
46
  "@graphql-eslint/eslint-plugin": "^4.1.0",
47
47
  "@graphql-tools/utils": "^11.0.0",
48
48
  "@playwright/test": "^1.49.0",
49
- "@salesforce/graphiti": "^11.18.0",
50
- "@salesforce/vite-plugin-ui-bundle": "^11.18.0",
49
+ "@salesforce/graphiti": "^11.19.0",
50
+ "@salesforce/vite-plugin-ui-bundle": "^11.19.0",
51
51
  "@testing-library/jest-dom": "^6.6.3",
52
52
  "@testing-library/react": "^16.1.0",
53
53
  "@testing-library/user-event": "^14.5.2",
@@ -6,9 +6,14 @@ import {
6
6
  BreadcrumbLink,
7
7
  BreadcrumbSeparator,
8
8
  BreadcrumbPage,
9
- } from "../../../components/ui/breadcrumb";
10
- import { Skeleton } from "../../../components/ui/skeleton";
9
+ } from "./ui/breadcrumb";
10
+ import { Skeleton } from "./ui/skeleton";
11
11
 
12
+ /**
13
+ * Home → List → Record breadcrumb for object pages. Previously imported from
14
+ * feature-react-object-search; inlined here so the app no longer depends on
15
+ * that feature.
16
+ */
12
17
  interface ObjectBreadcrumbProps {
13
18
  listPath: string;
14
19
  listLabel: string;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Fetches distinct values for a picklist field via the uiapi aggregate
3
+ * `groupBy` query.
4
+ *
5
+ * Used by the auto-render pathway when a picklist filter does not declare
6
+ * inline `options`. Each call hits the GraphQL endpoint once and returns the
7
+ * sorted set of distinct values plus their display labels.
8
+ */
9
+
10
+ import { createDataSDK } from "@salesforce/platform-sdk";
11
+
12
+ export interface PicklistOption {
13
+ value: string;
14
+ label: string;
15
+ }
16
+
17
+ const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
18
+
19
+ function assertValidIdentifier(name: string, kind: string): void {
20
+ if (!KEY_PATTERN.test(name)) {
21
+ throw new Error(
22
+ `Invalid ${kind} "${name}". Must match /^[A-Za-z_][A-Za-z0-9_]*$/ to be a valid GraphQL identifier.`,
23
+ );
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Builds and executes a `uiapi.aggregate.<objectName>(groupBy: { <field>: { group: true } })`
29
+ * query and extracts the distinct values.
30
+ */
31
+ export async function fetchDistinctValues(
32
+ objectName: string,
33
+ fieldName: string,
34
+ ): Promise<PicklistOption[]> {
35
+ assertValidIdentifier(objectName, "objectName");
36
+ assertValidIdentifier(fieldName, "fieldName");
37
+
38
+ const document = `query DistinctValues {
39
+ uiapi {
40
+ aggregate {
41
+ ${objectName}(groupBy: { ${fieldName}: { group: true } }) {
42
+ edges {
43
+ node {
44
+ aggregate @optional {
45
+ ${fieldName} @optional {
46
+ value
47
+ displayValue
48
+ label
49
+ }
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }`;
57
+
58
+ const data = await createDataSDK();
59
+ const response = await data.graphql!.query<unknown>({ query: document });
60
+
61
+ if (response.errors?.length) {
62
+ throw new Error(response.errors.map((e) => e.message).join("; "));
63
+ }
64
+
65
+ const root = response.data as Record<string, unknown> | undefined;
66
+ const aggregate = (root?.uiapi as Record<string, unknown> | undefined)?.aggregate as
67
+ | Record<string, unknown>
68
+ | undefined;
69
+ const objectAgg = aggregate?.[objectName] as
70
+ | { edges?: Array<{ node?: { aggregate?: Record<string, unknown> } }> }
71
+ | undefined;
72
+ const edges = objectAgg?.edges ?? [];
73
+
74
+ return edges
75
+ .map((edge) => {
76
+ const field = edge?.node?.aggregate?.[fieldName] as
77
+ | { value?: string | null; displayValue?: string | null; label?: string | null }
78
+ | undefined;
79
+ const value = field?.value;
80
+ if (value == null || value === "") return null;
81
+ return { value, label: field?.label ?? field?.displayValue ?? value };
82
+ })
83
+ .filter((opt): opt is PicklistOption => opt !== null);
84
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Executes a search request and parses results into a per-source map.
3
+ *
4
+ * Today there's only one adapter — SObjects via the platform-sdk uiapi GraphQL
5
+ * bridge. Future adapters (CMS, REST, etc.) can run alongside this one and
6
+ * have their results merged into the same `Record<sourceKey, SourceResult>`
7
+ * by the hook.
8
+ */
9
+
10
+ import { createDataSDK } from "@salesforce/platform-sdk";
11
+ import { buildSearchQuery, type SourceRequest } from "../queryBuilder";
12
+ import type { SourceResult } from "../types";
13
+
14
+ interface RawSourceResult {
15
+ edges?: Array<{ node?: unknown }> | null;
16
+ pageInfo?: {
17
+ hasNextPage?: boolean | null;
18
+ hasPreviousPage?: boolean | null;
19
+ startCursor?: string | null;
20
+ endCursor?: string | null;
21
+ } | null;
22
+ totalCount?: number | null;
23
+ }
24
+
25
+ /**
26
+ * Runs a single multi-aliased GraphQL request against uiapi.query.
27
+ *
28
+ * Returns a plain object keyed by source.key. A source whose alias is missing
29
+ * from the response (e.g. due to a partial GraphQL error) is omitted; the
30
+ * caller can detect this by `result[sourceKey] == null`.
31
+ */
32
+ export async function runSearch(requests: SourceRequest[]): Promise<Record<string, SourceResult>> {
33
+ const { document, variables } = buildSearchQuery(requests);
34
+
35
+ const data = await createDataSDK();
36
+ const response = await data.graphql!.query<unknown, Record<string, unknown>>({
37
+ query: document,
38
+ variables,
39
+ });
40
+
41
+ if (response.errors?.length) {
42
+ throw new Error(response.errors.map((e) => e.message).join("; "));
43
+ }
44
+
45
+ const root = response.data as Record<string, unknown> | undefined;
46
+ const queryRoot = (root?.uiapi as Record<string, unknown> | undefined)?.query as
47
+ | Record<string, RawSourceResult | null | undefined>
48
+ | undefined;
49
+
50
+ const out: Record<string, SourceResult> = {};
51
+ for (const request of requests) {
52
+ const raw = queryRoot?.[request.source.key];
53
+ if (raw == null) continue;
54
+ const nodes = (raw.edges ?? [])
55
+ .map((edge) => edge?.node)
56
+ .filter((node): node is unknown => node != null);
57
+ out[request.source.key] = {
58
+ nodes,
59
+ pageInfo: raw.pageInfo
60
+ ? {
61
+ hasNextPage: raw.pageInfo.hasNextPage ?? false,
62
+ hasPreviousPage: raw.pageInfo.hasPreviousPage ?? false,
63
+ startCursor: raw.pageInfo.startCursor ?? null,
64
+ endCursor: raw.pageInfo.endCursor ?? null,
65
+ }
66
+ : null,
67
+ totalCount: raw.totalCount ?? null,
68
+ };
69
+ }
70
+ return out;
71
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Merged results layout — a single combined grid across every in-scope source,
3
+ * driven by one global pager over the cumulative result set.
4
+ *
5
+ * This is the counterpart to {@link SearchResults} (which renders one stacked
6
+ * section per source). Use it when you want a unified "search everything" grid:
7
+ * heterogeneous cards laid out together, one shared pagination control, and a
8
+ * single results count — the layout the drop-in `<Search>` renders when the
9
+ * config sets `pagination.mode: "merged"`, and the same shape most apps
10
+ * hand-build on top of `useSearch`.
11
+ *
12
+ * It reads three aggregate accessors off the {@link SearchHandle}
13
+ * (`mergedResults`, `globalPagination`, `inScopeSources`), so it honours the
14
+ * config's `pagination.mode` / `mergeOrder` automatically. For a true combined
15
+ * grid, pair it with `pagination.mode: "merged"` (see the feature README, §9).
16
+ *
17
+ * Layout, top to bottom:
18
+ * - **Single-source filter chrome** — when the scope is narrowed to one
19
+ * source (selected or `lockedScope`), that source's filter panel + sort +
20
+ * active-filter chips render here. Under "All", per-source filters can't be
21
+ * combined across heterogeneous objects, so this row is omitted.
22
+ * - **Results count** — the cumulative in-scope total, on its own row directly
23
+ * above the grid, in every scope. Hidden when there are no results.
24
+ * - **The grid** — one card per `mergedResults` item, rendered via the
25
+ * per-source `renderResult[sourceKey]` callback. In a mixed grid (2+ sources
26
+ * in scope) each card is topped with an auto source badge — the source's
27
+ * `labelSingular` (falling back to `label`), colored from a palette by its
28
+ * config order — so heterogeneous results stay self-identifying with no
29
+ * configuration. Skeletons while loading; an empty-state message when there
30
+ * are none.
31
+ * - **Global pager** — one {@link PaginationControls} over the cumulative set.
32
+ */
33
+
34
+ import type { ReactNode } from "react";
35
+ import { AlertCircle } from "lucide-react";
36
+ import { Alert, AlertDescription, AlertTitle } from "../../../components/ui/alert";
37
+ import { Skeleton } from "../../../components/ui/skeleton";
38
+ import { ActiveFilters } from "./filters/ActiveFilters";
39
+ import { DefaultFilterPanel } from "./filters/DefaultFilterPanel";
40
+ import { FilterProvider, FilterResetButton } from "./filters/FilterContext";
41
+ import { PaginationControls } from "./controls/PaginationControls";
42
+ import { SortControl } from "./controls/SortControl";
43
+ import { DefaultResultRow } from "./results/DefaultResultRow";
44
+ import { ALL_SCOPE, type SearchHandle, type SourceController } from "../types";
45
+
46
+ type ResultRenderer = ((node: unknown) => ReactNode) | false;
47
+
48
+ export interface MergedSearchResultsProps {
49
+ handle: SearchHandle;
50
+ /**
51
+ * Per source key: how to render one node in the merged grid. Falls back to
52
+ * the built-in {@link DefaultResultRow} for any source without an entry.
53
+ * Pass `false` to skip a source's cards entirely.
54
+ */
55
+ renderResult?: Record<string, ResultRenderer>;
56
+ /** Message shown when there are no results. Defaults to "No results found." */
57
+ emptyMessage?: string;
58
+ /** Number of skeleton placeholders to show while loading. Defaults to `pageSize`. */
59
+ skeletonCount?: number;
60
+ /** Extra classes on the grid container. Defaults to a responsive 1/2/3-column grid. */
61
+ gridClassName?: string;
62
+ /** Extra classes on the outer wrapper. */
63
+ className?: string;
64
+ }
65
+
66
+ const DEFAULT_GRID_CLASS = "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3";
67
+
68
+ /**
69
+ * Palette for the auto source badges in a mixed grid. A source's color is its
70
+ * index in the config's `sources` array, wrapped around the palette — so badges
71
+ * stay stable and distinct without any per-source configuration. Add more
72
+ * entries here if you routinely mix more source types than there are colors.
73
+ */
74
+ const BADGE_PALETTE = [
75
+ "bg-blue-100 text-blue-700",
76
+ "bg-amber-100 text-amber-700",
77
+ "bg-purple-100 text-purple-700",
78
+ "bg-pink-100 text-pink-700",
79
+ "bg-emerald-100 text-emerald-700",
80
+ "bg-sky-100 text-sky-700",
81
+ ] as const;
82
+
83
+ export function MergedSearchResults({
84
+ handle,
85
+ renderResult,
86
+ emptyMessage,
87
+ skeletonCount,
88
+ gridClassName = DEFAULT_GRID_CLASS,
89
+ className,
90
+ }: MergedSearchResultsProps) {
91
+ const { globalPagination: page, mergedResults, loading, error } = handle;
92
+
93
+ // A single source is in scope when the scope is narrowed (selected from the
94
+ // dropdown) or locked (`lockedScope` / restrictTo). Its filter chrome can
95
+ // render meaningfully; under "All" it can't (heterogeneous sources).
96
+ const singleSourceInScope = handle.scope !== ALL_SCOPE;
97
+ const soleController = singleSourceInScope ? handle.inScopeSources[0] : undefined;
98
+ // Per-card source badges only make sense when the grid is genuinely mixed —
99
+ // a single-source grid (narrowed or locked) has one type throughout.
100
+ const showSourceBadges = !singleSourceInScope;
101
+ // Assign each source a stable badge color by its declaration order. Badges
102
+ // only show in "All" scope, where `inScopeSources` is every source in config
103
+ // order, so the index here is the source's config position.
104
+ const badgeColorByKey: Record<string, string> = {};
105
+ handle.inScopeSources.forEach((controller, i) => {
106
+ badgeColorByKey[controller.config.key] = BADGE_PALETTE[i % BADGE_PALETTE.length];
107
+ });
108
+
109
+ const skeletons = skeletonCount ?? page.pageSize;
110
+
111
+ return (
112
+ <div className={`space-y-6 ${className ?? ""}`}>
113
+ {soleController && <SingleSourceChrome controller={soleController} />}
114
+
115
+ {error && (
116
+ <Alert variant="destructive" role="alert">
117
+ <AlertCircle />
118
+ <AlertTitle>Search failed</AlertTitle>
119
+ <AlertDescription>{error}</AlertDescription>
120
+ </Alert>
121
+ )}
122
+
123
+ {/* Results count — its own row, directly above the grid, in every scope.
124
+ Hidden when there are none (the empty state covers that case). */}
125
+ {!loading && !error && page.totalCount > 0 && (
126
+ <p className="text-sm text-muted-foreground" role="status">
127
+ {page.totalCount} result{page.totalCount === 1 ? "" : "s"}
128
+ </p>
129
+ )}
130
+
131
+ {loading ? (
132
+ <div className={gridClassName}>
133
+ {Array.from({ length: Math.min(skeletons, 6) }, (_, i) => (
134
+ <Skeleton key={i} className="h-48 w-full rounded-lg" />
135
+ ))}
136
+ </div>
137
+ ) : mergedResults.length === 0 ? (
138
+ <p className="py-12 text-center text-sm text-muted-foreground">
139
+ {emptyMessage ?? "No results found."}
140
+ </p>
141
+ ) : (
142
+ <div className={gridClassName}>
143
+ {mergedResults.map(({ sourceKey, node }, i) => {
144
+ const override = renderResult?.[sourceKey];
145
+ if (override === false) return null;
146
+ const source = handle.sources[sourceKey]?.config;
147
+ const rendered = override ? (
148
+ override(node)
149
+ ) : source ? (
150
+ <DefaultResultRow node={node} source={source} />
151
+ ) : null;
152
+ const badge =
153
+ showSourceBadges && source ? (
154
+ <SourceBadge
155
+ label={source.labelSingular ?? source.label}
156
+ colorClass={badgeColorByKey[sourceKey]}
157
+ />
158
+ ) : null;
159
+ return (
160
+ <div
161
+ key={getItemKey(sourceKey, node, i)}
162
+ className="flex flex-col gap-1.5 [&>:last-child]:min-h-0 [&>:last-child]:flex-1"
163
+ >
164
+ {badge}
165
+ {rendered}
166
+ </div>
167
+ );
168
+ })}
169
+ </div>
170
+ )}
171
+
172
+ {page.totalCount > 0 && (
173
+ <PaginationControls
174
+ pageIndex={page.pageIndex}
175
+ pageCount={page.pageCount}
176
+ hasNextPage={page.hasNextPage}
177
+ hasPreviousPage={page.hasPreviousPage}
178
+ pageSize={page.pageSize}
179
+ pageSizeOptions={page.pageSizeOptions}
180
+ onNextPage={page.goToNextPage}
181
+ onPreviousPage={page.goToPreviousPage}
182
+ onGoToPage={page.goToPage}
183
+ onPageSizeChange={page.setPageSize}
184
+ disabled={loading || !!error}
185
+ />
186
+ )}
187
+ </div>
188
+ );
189
+ }
190
+
191
+ function getItemKey(sourceKey: string, node: unknown, fallback: number): string {
192
+ const id = node && typeof node === "object" ? (node as { Id?: unknown }).Id : undefined;
193
+ return typeof id === "string" ? `${sourceKey}:${id}` : `${sourceKey}:${fallback}`;
194
+ }
195
+
196
+ interface SourceBadgeProps {
197
+ label: string;
198
+ colorClass: string;
199
+ }
200
+
201
+ /**
202
+ * Auto source badge shown above each card in a mixed grid — the source's
203
+ * `labelSingular` (falling back to `label`), colored from {@link BADGE_PALETTE}
204
+ * by its config order. Identifies which object type a heterogeneous card came
205
+ * from with no per-app config.
206
+ */
207
+ function SourceBadge({ label, colorClass }: SourceBadgeProps) {
208
+ return (
209
+ <span className={`w-fit rounded-full px-2.5 py-0.5 text-xs font-medium ${colorClass}`}>
210
+ {label}
211
+ </span>
212
+ );
213
+ }
214
+
215
+ interface SingleSourceChromeProps {
216
+ controller: SourceController;
217
+ }
218
+
219
+ /**
220
+ * Filter panel + sort + active-filter chips for the one source in scope. Shown
221
+ * whenever the search is narrowed to a single object (selected or locked).
222
+ * Hidden under "All", where heterogeneous per-source filters can't be combined.
223
+ */
224
+ function SingleSourceChrome({ controller }: SingleSourceChromeProps) {
225
+ const { config: source, filters, sort } = controller;
226
+ const showFilterPanel = (source.filterBy?.length ?? 0) > 0;
227
+ const showSortControl = (source.sortBy?.length ?? 0) > 0;
228
+ const showActiveChips = filters.active.length > 0;
229
+
230
+ if (!showFilterPanel && !showSortControl && !showActiveChips) return null;
231
+
232
+ return (
233
+ <div className="flex flex-col gap-4">
234
+ {showFilterPanel && (
235
+ <FilterProvider
236
+ filters={filters.active}
237
+ onFilterChange={filters.set}
238
+ onFilterRemove={filters.remove}
239
+ onReset={() => filters.active.forEach((f) => filters.remove(f.field))}
240
+ >
241
+ <div className="rounded-md border p-3 space-y-3">
242
+ <div className="flex items-center justify-between">
243
+ <h3 className="text-sm font-semibold">Filters</h3>
244
+ <FilterResetButton size="sm" />
245
+ </div>
246
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
247
+ <DefaultFilterPanel source={source} />
248
+ </div>
249
+ </div>
250
+ </FilterProvider>
251
+ )}
252
+
253
+ {(showSortControl || showActiveChips) && (
254
+ <div className="flex flex-wrap items-center gap-2">
255
+ {showSortControl && source.sortBy && (
256
+ <SortControl configs={source.sortBy} sort={sort.current} onSortChange={sort.set} />
257
+ )}
258
+ {showActiveChips && <ActiveFilters filters={filters.active} onRemove={filters.remove} />}
259
+ </div>
260
+ )}
261
+ </div>
262
+ );
263
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Drop-in search component. Given a `SearchConfig`, renders a complete
3
+ * search experience: search bar, an aggregate result count, and results.
4
+ *
5
+ * The results layout follows the config's pagination mode — no separate prop:
6
+ * - `pagination.mode: "per-source"` (default): one stacked section per
7
+ * source, each with its own filters, sort, and pagination.
8
+ * - `pagination.mode: "merged"`: a single combined grid across every in-scope
9
+ * source, driven by one global pager over the cumulative result set (with a
10
+ * results count and, under a single scope, that source's filter chrome).
11
+ *
12
+ * The simplest possible integration:
13
+ *
14
+ * ```tsx
15
+ * import { Search, config } from ".../features/search";
16
+ * export default function MySearchPage() {
17
+ * return <Search config={config} />;
18
+ * }
19
+ * ```
20
+ *
21
+ * Override slots:
22
+ * - `renderResult[sourceKey]` — replace the default row renderer for one
23
+ * source. Pass `false` to hide that source entirely.
24
+ * - `renderFilters[sourceKey]` — replace the default filter sidebar for
25
+ * one source. Pass `false` to suppress filters for that source.
26
+ * - `renderHeader` — replace the default header (title + subtitle).
27
+ * - `searchPlaceholder` — placeholder text for the search input.
28
+ * - `title`, `subtitle` — defaults passed to the built-in header.
29
+ */
30
+
31
+ import { useMemo, type ReactNode } from "react";
32
+ import { useSearch } from "../hooks/useSearch";
33
+ import { SearchBar } from "./controls/SearchBar";
34
+ import { ScopeSelector } from "./controls/ScopeSelector";
35
+ import { SearchResults } from "./SearchResults";
36
+ import { MergedSearchResults } from "./MergedSearchResults";
37
+ import { ALL_SCOPE } from "../types";
38
+ import type { SearchConfig, SearchHandle, SObjectSourceConfig } from "../types";
39
+
40
+ type ResultRenderer = ((node: unknown) => ReactNode) | false;
41
+ type FilterRenderer = (() => ReactNode) | false;
42
+
43
+ /**
44
+ * Locks the search to a single source. Reuses the same shared `config.json`
45
+ * but shows only results matching the given (kind, key) tuple.
46
+ *
47
+ * When set:
48
+ * - The scope dropdown is hidden.
49
+ * - URL `?scope=` is not written (the page route already implies the source).
50
+ * - Only the matching source is fetched and rendered.
51
+ */
52
+ export interface RestrictTo {
53
+ kind: SObjectSourceConfig["kind"];
54
+ key: string;
55
+ }
56
+
57
+ interface SearchProps {
58
+ config: SearchConfig;
59
+ renderResult?: Record<string, ResultRenderer>;
60
+ renderFilters?: Record<string, FilterRenderer>;
61
+ emptyMessages?: Record<string, string>;
62
+ searchPlaceholder?: string;
63
+ title?: string;
64
+ subtitle?: string;
65
+ /**
66
+ * Lock the search to a single source by `(kind, key)`. Hides the scope
67
+ * dropdown and forces results to that one source. Useful for embedding
68
+ * a single-object search inside a page where the source is implicit.
69
+ */
70
+ restrictTo?: RestrictTo;
71
+ /**
72
+ * Show the source-scope dropdown next to the search bar.
73
+ * Defaults to `true` when the config has 2+ sources, `false` otherwise
74
+ * (a one-source dropdown would be redundant). Always hidden when
75
+ * `restrictTo` is set.
76
+ */
77
+ showScopeSelector?: boolean;
78
+ /** Label for the "search everything" entry in the scope dropdown. */
79
+ allScopeLabel?: string;
80
+ /** Optional override for the entire header region. */
81
+ renderHeader?: (handle: SearchHandle) => ReactNode;
82
+ className?: string;
83
+ }
84
+
85
+ export function Search({
86
+ config,
87
+ renderResult,
88
+ renderFilters,
89
+ emptyMessages,
90
+ searchPlaceholder = "Search…",
91
+ title = "Search",
92
+ subtitle,
93
+ restrictTo,
94
+ showScopeSelector,
95
+ allScopeLabel,
96
+ renderHeader,
97
+ className,
98
+ }: SearchProps) {
99
+ // Resolve restrictTo to a lockedScope value, surfacing a clear error if
100
+ // the (kind, key) pair doesn't match any source. Memoize so it's
101
+ // stable across renders.
102
+ const lockedScope = useMemo<string | undefined>(() => {
103
+ if (!restrictTo) return undefined;
104
+ const match = config.sources.find(
105
+ (s) => s.kind === restrictTo.kind && s.key === restrictTo.key,
106
+ );
107
+ if (!match) {
108
+ console.warn(
109
+ `<Search restrictTo>: no source with kind="${restrictTo.kind}" and key="${restrictTo.key}" in config. Falling back to "all".`,
110
+ );
111
+ return undefined;
112
+ }
113
+ return match.key;
114
+ }, [restrictTo, config.sources]);
115
+
116
+ const handle = useSearch(config, { lockedScope });
117
+ // The results layout follows the pagination mode — a "merged" config means a
118
+ // single combined grid, "per-source" (default) means one section per source.
119
+ // There is no separate `layout` prop: the two would only ever be set in lockstep.
120
+ const merged = config.pagination?.mode === "merged";
121
+ const totalResults = Object.values(handle.sources).reduce(
122
+ (acc, controller) => acc + (controller.result?.totalCount ?? 0),
123
+ 0,
124
+ );
125
+ const shouldShowScope = !handle.scopeLocked && (showScopeSelector ?? config.sources.length >= 2);
126
+ // The aggregate count is only meaningful when results from more than one
127
+ // source are combined. With a single configured source, a locked scope, or
128
+ // a specific source picked in the dropdown, exactly one source is on screen
129
+ // and that source's own section already shows its count — so suppress the
130
+ // redundant total here.
131
+ const sourcesInScope = handle.scope === ALL_SCOPE ? config.sources.length : 1;
132
+ // In merged mode the results grid renders its own count row directly above the
133
+ // grid (in every scope), so the inline aggregate here would be redundant.
134
+ const showTotalResults = !merged && sourcesInScope >= 2;
135
+
136
+ return (
137
+ <div className={`max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6 space-y-6 ${className ?? ""}`}>
138
+ {renderHeader ? (
139
+ renderHeader(handle)
140
+ ) : (
141
+ <header className="space-y-2">
142
+ <h1 className="text-2xl font-bold">{title}</h1>
143
+ {subtitle && <p className="text-sm text-muted-foreground">{subtitle}</p>}
144
+ </header>
145
+ )}
146
+
147
+ <div className="flex flex-wrap items-center gap-3">
148
+ <SearchBar value={handle.q} onChange={handle.setQ} placeholder={searchPlaceholder} />
149
+ {shouldShowScope && (
150
+ <ScopeSelector
151
+ config={config}
152
+ scope={handle.scope}
153
+ onScopeChange={handle.setScope}
154
+ allLabel={allScopeLabel}
155
+ />
156
+ )}
157
+ </div>
158
+
159
+ {merged ? (
160
+ <MergedSearchResults
161
+ handle={handle}
162
+ renderResult={renderResult}
163
+ emptyMessage={emptyMessages?.[handle.scope]}
164
+ />
165
+ ) : (
166
+ <>
167
+ {/* Aggregate count on its own row, directly above the results —
168
+ only in "All" scope, where the per-source sections don't each
169
+ carry a single meaningful total. */}
170
+ {showTotalResults && !handle.loading && (
171
+ <p className="text-sm text-muted-foreground" role="status">
172
+ {totalResults} total result{totalResults === 1 ? "" : "s"}
173
+ </p>
174
+ )}
175
+ <SearchResults
176
+ handle={handle}
177
+ renderResult={renderResult}
178
+ renderFilters={renderFilters}
179
+ emptyMessages={emptyMessages}
180
+ />
181
+ </>
182
+ )}
183
+ </div>
184
+ );
185
+ }