@olenbetong/appframe-ds 0.3.0 → 0.4.1

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 (49) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/es/AfLookup/BoundLookup.d.ts +4 -3
  3. package/es/AfLookup/Combobox.css +1 -1
  4. package/es/AfLookup/Combobox.d.ts +22 -5
  5. package/es/AfLookup/Combobox.js +24 -72
  6. package/es/AfLookup/Lookup.css +21 -0
  7. package/es/AfLookup/Lookup.d.ts +7 -6
  8. package/es/AfLookup/Lookup.js +32 -134
  9. package/es/AfLookup/LookupEdit.d.ts +21 -0
  10. package/es/AfLookup/LookupEdit.js +49 -0
  11. package/es/AfLookup/LookupGrid.css +57 -0
  12. package/es/AfLookup/LookupGrid.d.ts +13 -0
  13. package/es/AfLookup/LookupGrid.js +27 -0
  14. package/es/AfLookup/index.d.ts +2 -0
  15. package/es/AfLookup/index.js +2 -0
  16. package/es/binding/BoundDatePicker.d.ts +1 -1
  17. package/es/binding/BoundDateTimePicker.d.ts +1 -1
  18. package/es/binding/BoundInput.d.ts +1 -1
  19. package/es/binding/BoundNumericTextField.d.ts +1 -1
  20. package/es/binding/BoundSwitch.d.ts +1 -1
  21. package/es/binding/BoundTextField.d.ts +1 -1
  22. package/es/binding/DataEditToolbar.d.ts +1 -1
  23. package/es/binding/DataEditToolbar.js +1 -1
  24. package/es/binding/DataObjectSelect.d.ts +2 -2
  25. package/es/binding/DataObjectSelect.js +2 -2
  26. package/es/layout/AppLayoutDesktop.d.ts +1 -1
  27. package/es/layout/AppLayoutDesktop.js +1 -1
  28. package/es/layout/AppLayoutMobile.d.ts +1 -1
  29. package/es/layout/AppLayoutMobile.js +3 -3
  30. package/es/layout/AppMenu.d.ts +1 -1
  31. package/es/layout/AppMenu.js +1 -1
  32. package/es/layout/AppMenuSubheader.d.ts +1 -1
  33. package/es/layout/ErrorBoundary.d.ts +4 -4
  34. package/es/layout/PageContainer.d.ts +1 -1
  35. package/es/layout/index.d.ts +1 -1
  36. package/package.json +15 -15
  37. package/scripts/copyAssets.mjs +22 -0
  38. package/src/AfLookup/BoundLookup.tsx +4 -4
  39. package/src/AfLookup/Combobox.css +1 -1
  40. package/src/AfLookup/Combobox.tsx +94 -108
  41. package/src/AfLookup/Lookup.css +21 -0
  42. package/src/AfLookup/Lookup.tsx +60 -161
  43. package/src/AfLookup/LookupEdit.tsx +131 -0
  44. package/src/AfLookup/LookupGrid.css +57 -0
  45. package/src/AfLookup/LookupGrid.tsx +98 -0
  46. package/src/AfLookup/index.ts +2 -0
  47. package/src/binding/DataObjectSelect.tsx +1 -1
  48. package/src/layout/AppLayoutMobile.tsx +1 -1
  49. package/tsconfig.build.tsbuildinfo +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @olenbetong/appframe-ds
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - f7f6cea: AfLookup now supports typeahead from the input field: typing opens the lookup popup and forwards the typed character to the combobox search field.
8
+
9
+ ## 0.4.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 46177d7: Add grid variant support to AfLookup and extract shared lookup logic.
14
+ - `@olenbetong/appframe-react`: new `useLookupState` and `useComboboxData` hooks containing the shared non-UI lookup logic (dialog state, anchor positioning, search filtering, keyboard navigation), plus the `LookupColumn` and `DistributiveOmit` types.
15
+ - `@olenbetong/appframe-mui` / `@olenbetong/appframe-ds`: the lookup popup now supports `variant="grid"` with a `columns` definition (`field`, `headerName`, `width`, `renderCell`). Grid keyboard navigation is cell-by-cell (tracks current row and column) and works while focus is in the search field.
16
+ - `@olenbetong/appframe-ds`: new `AfLookupEdit` component — an editable lookup input where the popup selects a single value (the item's `lookupField`) instead of an entire row, so typing and selecting behave the same. The existing `AfLookupEdit` in `@olenbetong/appframe-mui` now shares the same lookup state logic and supports the grid variant.
17
+
18
+ Fixes:
19
+ - The lookup dialog no longer scrolls its own content (`overflow: hidden` on `.ObLookup-dialog`), and the popup list/grid now grows and shrinks vertically when the dialog is resized (the list wrapper previously had a fixed height).
20
+ - The search field in the `appframe-ds` lookup no longer renders a label above the input; it uses an accessible label and placeholder instead.
21
+
3
22
  ## 0.3.0
4
23
 
5
24
  ### Minor Changes
@@ -1,9 +1,10 @@
1
1
  import type { CurrentRow, DataObject } from "@olenbetong/appframe-data";
2
+ import { type DistributiveOmit } from "@olenbetong/appframe-react";
2
3
  import { type AfLookupProps } from "./Lookup.js";
3
- export interface BoundLookupProps<TBoundData extends Record<string, unknown>, TLookupData extends Record<string, unknown>> extends Omit<AfLookupProps<TLookupData>, "onChange"> {
4
+ export type BoundLookupProps<TBoundData extends Record<string, unknown>, TLookupData extends Record<string, unknown>> = DistributiveOmit<AfLookupProps<TLookupData>, "onChange"> & {
4
5
  dataObject: DataObject<TLookupData>;
5
6
  displayField?: keyof TBoundData;
6
7
  getChanges: (selectedItem: TLookupData | null) => Partial<TBoundData>;
7
8
  getDisplayValue?: (currentRow: CurrentRow<TBoundData>) => string;
8
- }
9
- export declare function BoundLookup<TBoundData extends Record<string, unknown>, TLookupData extends Record<string, unknown> = any>({ dataObject, displayField, getChanges, getDisplayValue, ...props }: BoundLookupProps<TBoundData, TLookupData>): import("react/jsx-runtime").JSX.Element;
9
+ };
10
+ export declare function BoundLookup<TBoundData extends Record<string, unknown>, TLookupData extends Record<string, unknown> = any>({ dataObject, displayField, getChanges, getDisplayValue, ...props }: BoundLookupProps<TBoundData, TLookupData>): import("react").JSX.Element;
@@ -14,7 +14,7 @@
14
14
 
15
15
  .ObCombobox-listWrap {
16
16
  overflow: hidden;
17
- height: 372px;
17
+ min-height: 0;
18
18
  border: 1px solid rgb(0 0 0 / 0.12);
19
19
  border-radius: 0.25rem;
20
20
  background-color: white;
@@ -1,15 +1,32 @@
1
1
  import "./Combobox.css";
2
2
  import type { DataObject } from "@olenbetong/appframe-data";
3
- export interface ComboboxProps<T extends Record<string, unknown>> {
3
+ import { type LookupColumn } from "@olenbetong/appframe-react";
4
+ export interface ComboboxBaseProps<T extends Record<string, unknown>> {
4
5
  nullable?: boolean;
5
6
  dataObject: DataObject<T>;
6
7
  uniqueIdField?: string;
8
+ initialSearchValue?: string;
7
9
  isItemSelected?: (item: T) => boolean;
8
- renderItem: (props: React.ComponentPropsWithRef<"li"> & {
9
- item: T;
10
- }) => React.ReactNode;
11
10
  onChange?: (item: T | null) => void;
12
11
  value?: T;
13
12
  onClose?: () => void;
14
13
  }
15
- export declare function Combobox<T extends Record<string, unknown>>({ nullable, dataObject, isItemSelected, uniqueIdField, renderItem: Component, onChange, onClose, }: ComboboxProps<T>): import("react/jsx-runtime").JSX.Element;
14
+ export interface ComboboxListProps<T extends Record<string, unknown>> extends ComboboxBaseProps<T> {
15
+ /**
16
+ * Renders the popup content as a list (default).
17
+ */
18
+ variant?: "list";
19
+ renderItem: (props: React.ComponentPropsWithRef<"li"> & {
20
+ item: T;
21
+ }) => React.ReactNode;
22
+ }
23
+ export interface ComboboxGridProps<T extends Record<string, unknown>> extends ComboboxBaseProps<T> {
24
+ /**
25
+ * Renders the popup content as a grid with a header row and one column per
26
+ * entry in `columns`.
27
+ */
28
+ variant: "grid";
29
+ columns: LookupColumn<T>[];
30
+ }
31
+ export type ComboboxProps<T extends Record<string, unknown>> = ComboboxListProps<T> | ComboboxGridProps<T>;
32
+ export declare function Combobox<T extends Record<string, unknown>>(props: ComboboxProps<T>): import("react").JSX.Element;
@@ -2,12 +2,16 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import "./Combobox.css";
3
3
  import { Button, Textfield } from "@digdir/designsystemet-react";
4
4
  import { getLocalizedString } from "@olenbetong/appframe-core";
5
- import { useDataWithFilter, useDebounce, useLoading } from "@olenbetong/appframe-react";
5
+ import { useComboboxData } from "@olenbetong/appframe-react";
6
6
  import clsx from "clsx";
7
- import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
7
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
8
8
  import { VariableSizeList as VirtualList } from "react-window";
9
- export function Combobox({ nullable, dataObject, isItemSelected, uniqueIdField = "PrimKey", renderItem: Component, onChange, onClose, }) {
10
- let id = useId();
9
+ import { LookupGrid } from "./LookupGrid.js";
10
+ export function Combobox(props) {
11
+ let { nullable, dataObject, isItemSelected, uniqueIdField = "PrimKey", initialSearchValue, onChange, onClose, } = props;
12
+ let isGrid = props.variant === "grid";
13
+ let columns = isGrid ? props.columns : undefined;
14
+ let listRef = useRef(null);
11
15
  let [isDesktop, setIsDesktop] = useState(() => typeof window !== "undefined" && window.matchMedia("(width >= 768px) and (pointer: fine)").matches);
12
16
  useEffect(() => {
13
17
  let mq = window.matchMedia("(width >= 768px) and (pointer: fine)");
@@ -15,22 +19,12 @@ export function Combobox({ nullable, dataObject, isItemSelected, uniqueIdField =
15
19
  mq.addEventListener("change", handler);
16
20
  return () => mq.removeEventListener("change", handler);
17
21
  }, []);
18
- let [currentIndex, setCurrentIndex] = useState(0);
19
- let listRef = useRef(null);
20
- let [inputValue, setInputValue] = useState(() => {
21
- // Preserve filter even if the lookup is unmounted
22
- let currentFilter = dataObject.getParameter("filterString") ?? "";
23
- let filters = currentFilter.split(/\s+AND\s+/g);
24
- let wordFilters = filters.filter((filter) => filter.includes("[SearchColumn]"));
25
- let words = wordFilters.map((filter) => filter.match(/'%([^']*)%'/)?.[1] ?? "").filter(Boolean);
26
- return words.join(" ");
22
+ let { id, data, loading, inputValue, setInputValue, currentIndex, currentColumn, getItemId, handleSelectItem, handleKeyDown, } = useComboboxData({
23
+ dataObject,
24
+ uniqueIdField,
25
+ columnCount: columns?.length ?? 1,
26
+ onChange,
27
27
  });
28
- let query = useDebounce(inputValue, 300);
29
- let loading = useLoading(dataObject);
30
- let data = useDataWithFilter(dataObject, query
31
- .split(/\s+/g)
32
- .map((word) => `[SearchColumn] LIKE '%${word}%'`)
33
- .join(" AND "));
34
28
  let wrapperRef = useRef(null);
35
29
  let [height, setHeight] = useState(0);
36
30
  useLayoutEffect(() => {
@@ -44,64 +38,15 @@ export function Combobox({ nullable, dataObject, isItemSelected, uniqueIdField =
44
38
  resizeObserver.observe(wrapperRef.current);
45
39
  return () => resizeObserver.disconnect();
46
40
  }, []);
47
- // Reset current index when new data is loaded
48
- // biome-ignore lint/correctness/useExhaustiveDependencies: isn't it obvious?
49
- useEffect(() => {
50
- setCurrentIndex(0);
51
- }, [data]);
52
- let getItemId = useCallback((item) => {
53
- if (!item) {
54
- return;
55
- }
56
- let itemId = item[uniqueIdField];
57
- return `${id}-${itemId}`;
58
- }, [id, uniqueIdField]);
59
- function handleSelectItem(item) {
60
- onChange?.(item);
61
- setInputValue("");
62
- }
63
- function handleKeyDown(event) {
64
- let newIndex = null;
65
- if (event.key === "ArrowDown") {
66
- newIndex = currentIndex + 1;
67
- }
68
- else if (event.key === "ArrowUp") {
69
- newIndex = currentIndex - 1;
70
- }
71
- else if (event.key === "Home" && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
72
- newIndex = 0;
73
- }
74
- else if (event.key === "End" && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
75
- newIndex = data.length - 1;
76
- }
77
- else if (event.key === "Enter") {
78
- event.stopPropagation();
79
- event.preventDefault();
80
- handleSelectItem(data[currentIndex]);
81
- return;
82
- }
83
- if (newIndex !== null) {
84
- event.stopPropagation();
85
- event.preventDefault();
86
- if (newIndex < 0) {
87
- newIndex = data.length - 1;
88
- }
89
- else if (newIndex >= data.length) {
90
- newIndex = 0;
91
- }
92
- setCurrentIndex(newIndex);
93
- }
94
- }
95
41
  let sizeMap = useRef(new Map());
96
42
  let getItemSize = (index) => sizeMap.current.get(index) ?? 56;
97
- let setSize = (index, size) => {
43
+ let setSize = useCallback((index, size) => {
98
44
  if (sizeMap.current.get(index) !== size) {
99
45
  sizeMap.current.set(index, size);
100
46
  // listRef will not be set on the initial render, so delay resetting
101
47
  setTimeout(() => listRef.current?.resetAfterIndex(index, true));
102
48
  }
103
- };
104
- // biome-ignore lint: nested component defined for performance reasons inside render
49
+ }, []);
105
50
  let Row = ({ index, style: { height, ...style } }) => {
106
51
  let rowRef = useRef(null);
107
52
  useLayoutEffect(() => {
@@ -112,13 +57,20 @@ export function Combobox({ nullable, dataObject, isItemSelected, uniqueIdField =
112
57
  let item = data[index];
113
58
  let itemId = getItemId(item);
114
59
  let active = index === currentIndex;
115
- return (_jsx(Component, { className: clsx("ObCombobox-listItem", active && "active", isItemSelected?.(item) && "selected"), "aria-selected": active, onClick: () => handleSelectItem(item), item: item, style: {
60
+ let ItemComponent = props.renderItem;
61
+ return (_jsx(ItemComponent, { className: clsx("ObCombobox-listItem", active && "active", isItemSelected?.(item) && "selected"), "aria-selected": active, onClick: () => handleSelectItem(item), item: item, style: {
116
62
  ...style,
117
63
  padding: isDesktop ? "0 8px" : "8px",
118
64
  }, ref: rowRef, id: itemId }, itemId));
119
65
  };
120
66
  useEffect(() => listRef.current?.scrollToItem(currentIndex, "smart"), [currentIndex]);
67
+ useEffect(() => {
68
+ if (initialSearchValue !== undefined) {
69
+ setInputValue(initialSearchValue);
70
+ }
71
+ }, [initialSearchValue, setInputValue]);
121
72
  return (_jsxs("div", { className: "ObCombobox-root", id: id, onClick: (evt) => evt.stopPropagation(), children: [_jsxs("div", { className: "ObCombobox-actions", children: [nullable && (_jsx(Button, { className: "ObCombobox-clear", "data-size": isDesktop ? "sm" : "md", variant: "tertiary", onClick: () => {
122
73
  onChange?.(null);
123
- }, children: getLocalizedString("Clear") })), onClose && (_jsx(Button, { "data-size": isDesktop ? "sm" : "md", variant: "tertiary", className: "ObCombobox-close", onClick: onClose, children: getLocalizedString("Close") }))] }), _jsx(Textfield, { type: "search", className: "ObCombobox-input", label: getLocalizedString("Search"), onKeyDown: handleKeyDown, "aria-activedescendant": getItemId(data[currentIndex]) ?? "", value: inputValue, onChange: (event) => setInputValue(event.target.value) }), _jsxs("div", { className: "ObCombobox-listWrap", ref: wrapperRef, children: [loading && (_jsx("div", { className: "ObCombobox-progress", children: _jsx("div", { className: "ObCombobox-progress-bar" }) })), height > 0 && (_jsx("div", { className: "ObCombobox-list", role: "listbox", children: _jsx(VirtualList, { ref: listRef, height: height, width: "100%", itemCount: data.length, itemSize: getItemSize, overscanCount: 5, children: Row }) }))] })] }));
74
+ }, children: getLocalizedString("Clear") })), onClose && (_jsx(Button, { "data-size": isDesktop ? "sm" : "md", variant: "tertiary", className: "ObCombobox-close", onClick: onClose, children: getLocalizedString("Close") }))] }), _jsx(Textfield, { type: "search", className: "ObCombobox-input", "aria-label": getLocalizedString("Search"), placeholder: getLocalizedString("Search"), onKeyDown: handleKeyDown, "aria-activedescendant": getItemId(data[currentIndex]) ?? "", value: inputValue, onChange: (event) => setInputValue(event.target.value) }), _jsxs("div", { className: "ObCombobox-listWrap", ref: wrapperRef, children: [loading && (_jsx("div", { className: "ObCombobox-progress", children: _jsx("div", { className: "ObCombobox-progress-bar" }) })), height > 0 &&
75
+ (columns ? (_jsx(LookupGrid, { columns: columns, data: data, height: height, currentIndex: currentIndex, currentColumn: currentColumn, getItemId: getItemId, isItemSelected: isItemSelected, onSelectItem: handleSelectItem })) : (_jsx("div", { className: "ObCombobox-list", role: "listbox", children: _jsx(VirtualList, { ref: listRef, height: height, width: "100%", itemCount: data.length, itemSize: getItemSize, overscanCount: 5, children: Row }) })))] })] }));
124
76
  }
@@ -1,7 +1,28 @@
1
+ .ObLookup-inputWrap {
2
+ position: relative;
3
+
4
+ .ds-input {
5
+ padding-inline-end: var(--ObLookup-buttons-width, 3rem);
6
+ }
7
+ }
8
+
9
+ .ObLookup-buttons {
10
+ position: absolute;
11
+ inset-inline-end: 0;
12
+ inset-block-end: 0;
13
+ /* Match the .ds-input height so the buttons center on the input row,
14
+ also when a label or description is rendered above the input */
15
+ height: var(--ds-size-12, 3rem);
16
+ display: flex;
17
+ align-items: center;
18
+ padding-inline-end: var(--ds-size-1, 0.25rem);
19
+ }
20
+
1
21
  .ObLookup-dialog {
2
22
  border: 0;
3
23
  margin-block-start: 0;
4
24
  padding: 1rem;
25
+ overflow: hidden;
5
26
 
6
27
  background-color: whitesmoke;
7
28
 
@@ -1,7 +1,8 @@
1
1
  import "./Lookup.css";
2
2
  import { type TextfieldProps } from "@digdir/designsystemet-react";
3
+ import { type DistributiveOmit } from "@olenbetong/appframe-react";
3
4
  import { type ComboboxProps } from "./Combobox.js";
4
- export interface AfLookupProps<T extends Record<string, unknown>> extends Omit<ComboboxProps<T>, "value"> {
5
+ export type AfLookupProps<T extends Record<string, unknown>> = DistributiveOmit<ComboboxProps<T>, "value"> & {
5
6
  /**
6
7
  * Allows the user to enter a value manually that might not be in the list.
7
8
  */
@@ -14,16 +15,16 @@ export interface AfLookupProps<T extends Record<string, unknown>> extends Omit<C
14
15
  dialog?: Partial<React.HTMLProps<HTMLDialogElement>>;
15
16
  textField?: Partial<TextfieldProps>;
16
17
  };
17
- }
18
- export interface LookupProps<T extends Record<string, unknown>> extends Omit<ComboboxProps<T>, "value"> {
18
+ };
19
+ export type LookupProps<T extends Record<string, unknown>> = DistributiveOmit<ComboboxProps<T>, "value"> & {
19
20
  slotProps?: {
20
21
  dialog?: Partial<React.HTMLProps<HTMLDialogElement>>;
21
22
  };
22
23
  getAnchorElement?: () => Element | null;
23
- }
24
+ };
24
25
  export declare function useLookup<T extends Record<string, unknown>>({ getAnchorElement, slotProps, ...props }: LookupProps<T>): {
25
26
  open: boolean;
26
- openDialog: () => void;
27
+ openDialog: (searchValue?: string) => void;
27
28
  onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
28
29
  onChange: (item: T | null) => void;
29
30
  dialogRef: import("react").RefObject<HTMLDialogElement | null>;
@@ -31,4 +32,4 @@ export declare function useLookup<T extends Record<string, unknown>>({ getAnchor
31
32
  inputId: string;
32
33
  dialog: import("react").ReactPortal;
33
34
  };
34
- export declare function AfLookup<T extends Record<string, unknown>>({ fullWidth, label, slotProps, value, ...props }: AfLookupProps<T>): import("react/jsx-runtime").JSX.Element;
35
+ export declare function AfLookup<T extends Record<string, unknown>>({ fullWidth, label, slotProps, value, ...props }: AfLookupProps<T>): import("react").JSX.Element;
@@ -4,158 +4,56 @@ import { Button, Textfield } from "@digdir/designsystemet-react";
4
4
  import ClearIcon from "@mui/icons-material/Close";
5
5
  import SearchIcon from "@mui/icons-material/Search";
6
6
  import { getLocalizedString } from "@olenbetong/appframe-core";
7
+ import { useLookupState } from "@olenbetong/appframe-react";
7
8
  import clsx from "clsx";
8
- import { useCallback, useEffect, useId, useRef, useState } from "react";
9
- import { createPortal, flushSync } from "react-dom";
9
+ import { useRef } from "react";
10
+ import { createPortal } from "react-dom";
10
11
  import { Combobox } from "./Combobox.js";
11
12
  export function useLookup({ getAnchorElement, slotProps, ...props }) {
12
- let [open, setOpen] = useState(false);
13
- let anchorName = `--anchor-${CSS.escape(useId())}`;
14
- let dialogRef = useRef(null);
15
- let inputId = useId();
16
- let resetManualAnchor = useCallback(() => {
17
- let $dialog = dialogRef.current;
18
- if ($dialog) {
19
- $dialog.style.removeProperty("--lookup-anchor-inline-start");
20
- $dialog.style.removeProperty("--lookup-anchor-block-start");
21
- delete $dialog.dataset.anchor;
22
- }
23
- }, []);
24
- let updateManualAnchor = useCallback(() => {
25
- if (typeof window === "undefined") {
26
- return;
27
- }
28
- if (!window.matchMedia?.("(pointer: fine)").matches) {
29
- resetManualAnchor();
30
- return;
31
- }
32
- let anchorElement = getAnchorElement?.() ?? null;
33
- let $dialog = dialogRef.current;
34
- if (!$dialog || !anchorElement) {
35
- resetManualAnchor();
36
- return;
37
- }
38
- let rect = anchorElement.getBoundingClientRect();
39
- let dialogHeight = $dialog.offsetHeight || 0;
40
- let dialogWidth = $dialog.offsetWidth || 0;
41
- let top = rect.bottom + 8;
42
- let availableBelow = window.innerHeight - rect.bottom - 16;
43
- if (availableBelow < dialogHeight) {
44
- top = Math.max(16, rect.top - dialogHeight - 8);
45
- }
46
- let left = rect.left;
47
- let minInline = 16;
48
- let maxInline = window.innerWidth - dialogWidth - 16;
49
- if (Number.isFinite(maxInline)) {
50
- left = Math.min(Math.max(left, minInline), Math.max(minInline, maxInline));
51
- }
52
- $dialog.style.setProperty("--lookup-anchor-inline-start", `${Math.round(left)}px`);
53
- $dialog.style.setProperty("--lookup-anchor-block-start", `${Math.round(top)}px`);
54
- $dialog.dataset.anchor = "manual";
55
- }, [getAnchorElement, resetManualAnchor]);
56
- function handleOpen() {
57
- let $dialog = dialogRef.current;
58
- if ($dialog) {
59
- flushSync(() => {
60
- $dialog.showModal();
61
- setOpen(true);
62
- });
63
- $dialog.querySelector('input[type="search"]')?.focus();
64
- }
65
- }
66
- function handleKeyDown(event) {
67
- if (event.key === "ArrowDown" || event.key === "F4") {
68
- event.preventDefault();
69
- event.stopPropagation();
70
- handleOpen();
71
- }
72
- }
73
- let handleClose = useCallback(() => {
74
- setOpen(false);
75
- document.getElementById(inputId)?.focus();
76
- }, [inputId]);
13
+ let { open, openDialog, onKeyDown, dialogRef, anchorName, inputId } = useLookupState({
14
+ getAnchorElement,
15
+ scrollParentSelector: "[data-virtualized-scroller]",
16
+ });
17
+ let initialSearchValueRef = useRef(undefined);
77
18
  function handleChange(item) {
78
19
  props.onChange?.(item);
79
20
  dialogRef.current?.close();
80
21
  }
81
- useEffect(() => {
82
- if (!open) {
83
- resetManualAnchor();
84
- return;
85
- }
86
- let frame = requestAnimationFrame(() => {
87
- updateManualAnchor();
88
- });
89
- updateManualAnchor();
90
- let cleanupTargets = [];
91
- let listener = () => updateManualAnchor();
92
- cleanupTargets.push([window, "resize", listener, undefined]);
93
- cleanupTargets.push([window, "scroll", listener, true]);
94
- let anchorElement = getAnchorElement?.() ?? null;
95
- let scrollParent = anchorElement?.closest("[data-virtualized-scroller]") ?? null;
96
- if (scrollParent) {
97
- cleanupTargets.push([scrollParent, "scroll", listener, { passive: true }]);
98
- }
99
- for (let [target, type, handler, options] of cleanupTargets) {
100
- target.addEventListener(type, handler, options);
101
- }
102
- return () => {
103
- cancelAnimationFrame(frame);
104
- for (let [target, type, handler, options] of cleanupTargets) {
105
- target.removeEventListener(type, handler, options);
106
- }
107
- };
108
- }, [getAnchorElement, open, resetManualAnchor, updateManualAnchor]);
109
- useEffect(() => {
110
- let $dialog = dialogRef.current;
111
- if ($dialog) {
112
- let controller = new AbortController();
113
- let signal = controller.signal;
114
- let closeEvent = () => {
115
- // Wait for transition to finish before closing
116
- setTimeout(() => {
117
- handleClose();
118
- }, 150);
119
- };
120
- $dialog.addEventListener("close", closeEvent, { signal });
121
- $dialog.addEventListener("cancel", closeEvent, { signal });
122
- $dialog.addEventListener("click", (event) => {
123
- let rect = $dialog.getBoundingClientRect();
124
- if (rect.left > event.clientX ||
125
- rect.right < event.clientX ||
126
- rect.top > event.clientY ||
127
- rect.bottom < event.clientY) {
128
- $dialog.close();
129
- }
130
- }, { signal });
131
- return () => {
132
- controller.abort();
133
- };
134
- }
135
- }, [handleClose]);
22
+ function handleOpenDialog(searchValue) {
23
+ initialSearchValueRef.current = searchValue;
24
+ openDialog();
25
+ }
136
26
  return {
137
27
  open,
138
- openDialog: handleOpen,
139
- onKeyDown: handleKeyDown,
28
+ openDialog: handleOpenDialog,
29
+ onKeyDown,
140
30
  onChange: handleChange,
141
31
  dialogRef,
142
32
  anchorName,
143
33
  inputId,
144
- dialog: createPortal(_jsx("dialog", { ref: dialogRef, className: clsx("ObLookup-dialog", slotProps?.dialog?.className), onKeyDown: (evt) => evt.stopPropagation(), style: { positionAnchor: anchorName, ...slotProps?.dialog?.style }, children: open && _jsx(Combobox, { ...props, onClose: () => dialogRef.current?.close(), onChange: handleChange }) }), document.body, inputId),
34
+ dialog: createPortal(_jsx("dialog", { ref: dialogRef, className: clsx("ObLookup-dialog", slotProps?.dialog?.className), onKeyDown: (evt) => evt.stopPropagation(), style: { positionAnchor: anchorName, ...slotProps?.dialog?.style }, children: open && (_jsx(Combobox, { ...props, initialSearchValue: initialSearchValueRef.current, onClose: () => dialogRef.current?.close(), onChange: handleChange })) }), document.body, inputId),
145
35
  };
146
36
  }
147
37
  export function AfLookup({ fullWidth = false, label, slotProps, value, ...props }) {
148
38
  let { inputId, open: _open, dialog, anchorName, openDialog, onKeyDown } = useLookup(props);
149
- return (_jsxs("div", { style: { anchorName }, children: [_jsxs("div", { style: { position: "relative", display: fullWidth ? "block" : "inline-block" }, children: [_jsx(Textfield, { id: inputId, value: value ?? "", label: label, readOnly: true, onClick: openDialog, onKeyDown: onKeyDown, className: clsx(slotProps?.textField?.className, "ObLookup-input"), ...slotProps?.textField, style: { width: fullWidth ? "100%" : undefined, ...slotProps?.textField?.style } }), _jsxs("div", { style: {
150
- position: "absolute",
151
- right: 0,
152
- top: "50%",
153
- transform: "translateY(-50%)",
154
- display: "flex",
155
- alignItems: "center",
156
- }, children: [props.nullable && value && props.onChange && (_jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Clear"), onKeyDown: (evt) => evt.stopPropagation(), onClick: (evt) => {
39
+ let hasClear = !!(props.nullable && value && props.onChange);
40
+ function handleInputKeyDown(event) {
41
+ let hasModifier = event.ctrlKey || event.altKey || event.metaKey;
42
+ let isTypeaheadKey = event.key.length === 1 && !hasModifier && !event.nativeEvent.isComposing;
43
+ if (isTypeaheadKey) {
44
+ event.preventDefault();
45
+ event.stopPropagation();
46
+ openDialog(event.key);
47
+ return;
48
+ }
49
+ onKeyDown(event);
50
+ }
51
+ return (_jsxs("div", { style: { anchorName }, children: [_jsxs("div", { className: "ObLookup-inputWrap", style: {
52
+ display: fullWidth ? "block" : "inline-block",
53
+ "--ObLookup-buttons-width": hasClear ? "5.5rem" : "3rem",
54
+ }, children: [_jsx(Textfield, { id: inputId, value: value ?? "", label: label, onClick: () => openDialog(), onKeyDown: handleInputKeyDown, className: clsx(slotProps?.textField?.className, "ObLookup-input"), ...slotProps?.textField, style: { width: fullWidth ? "100%" : undefined, ...slotProps?.textField?.style } }), _jsxs("div", { className: "ObLookup-buttons", children: [hasClear && (_jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Clear"), onKeyDown: (evt) => evt.stopPropagation(), onClick: (evt) => {
157
55
  evt.stopPropagation();
158
56
  props.onChange?.(null);
159
57
  document.getElementById(inputId)?.focus();
160
- }, children: _jsx(ClearIcon, {}) })), _jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Search"), onClick: openDialog, children: _jsx(SearchIcon, {}) })] })] }), dialog] }));
58
+ }, children: _jsx(ClearIcon, {}) })), _jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Search"), onClick: () => openDialog(), children: _jsx(SearchIcon, {}) })] })] }), dialog] }));
161
59
  }
@@ -0,0 +1,21 @@
1
+ import "./Lookup.css";
2
+ import { type TextfieldProps } from "@digdir/designsystemet-react";
3
+ import type { DistributiveOmit } from "@olenbetong/appframe-react";
4
+ import type React from "react";
5
+ import type { ComboboxProps } from "./Combobox.js";
6
+ export type AfLookupEditProps<T extends Record<string, unknown>> = DistributiveOmit<ComboboxProps<T>, "value" | "onChange"> & {
7
+ /**
8
+ * Allows the user to enter a value manually that might not be in the list.
9
+ */
10
+ editable?: boolean;
11
+ fullWidth?: boolean;
12
+ label?: string;
13
+ value?: string | null;
14
+ lookupField: keyof T;
15
+ onChange?: (evt: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
16
+ slotProps?: {
17
+ dialog?: Partial<React.HTMLProps<HTMLDialogElement>>;
18
+ textField?: Partial<TextfieldProps>;
19
+ };
20
+ };
21
+ export declare function AfLookupEdit<T extends Record<string, unknown>>({ fullWidth, label, onChange, slotProps, nullable, lookupField, value, ...props }: AfLookupEditProps<T>): React.JSX.Element;
@@ -0,0 +1,49 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import "./Lookup.css";
3
+ import { Button, Textfield } from "@digdir/designsystemet-react";
4
+ import ClearIcon from "@mui/icons-material/Close";
5
+ import SearchIcon from "@mui/icons-material/Search";
6
+ import { getLocalizedString } from "@olenbetong/appframe-core";
7
+ import clsx from "clsx";
8
+ import { useLookup } from "./Lookup.js";
9
+ export function AfLookupEdit({ fullWidth = false, label, onChange, slotProps, nullable, lookupField, value, ...props }) {
10
+ let { inputId, dialog, anchorName, openDialog, onKeyDown } = useLookup({
11
+ ...props,
12
+ nullable,
13
+ slotProps: { dialog: slotProps?.dialog },
14
+ onChange: (item) => applyValue(item),
15
+ });
16
+ // The popup selects a single value from the dataset: the item's lookupField
17
+ // is written to the input through the native value setter so the same
18
+ // change event fires whether the user types or picks from the list/grid.
19
+ function applyValue(item) {
20
+ let input = document.getElementById(inputId);
21
+ let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
22
+ if (input && nativeInputValueSetter) {
23
+ nativeInputValueSetter.call(input, item ? String(item[lookupField]) : "");
24
+ input.dispatchEvent(new Event("input", { bubbles: true }));
25
+ }
26
+ }
27
+ function handleKeyDown(event) {
28
+ if (event.key === "Enter") {
29
+ event.preventDefault();
30
+ event.stopPropagation();
31
+ openDialog();
32
+ }
33
+ else {
34
+ onKeyDown(event);
35
+ }
36
+ }
37
+ let hasClear = !!(nullable && value && onChange);
38
+ return (_jsxs("div", { style: { anchorName }, children: [_jsxs("div", { className: "ObLookup-inputWrap", style: {
39
+ display: fullWidth ? "block" : "inline-block",
40
+ "--ObLookup-buttons-width": hasClear ? "5.5rem" : "3rem",
41
+ }, children: [_jsx(Textfield, { id: inputId, value: value ?? "", label: label, onChange: onChange, onKeyDown: handleKeyDown, className: clsx(slotProps?.textField?.className, "ObLookup-input"), ...slotProps?.textField, style: { width: fullWidth ? "100%" : undefined, ...slotProps?.textField?.style } }), _jsxs("div", { className: "ObLookup-buttons", children: [hasClear && (_jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Clear"), onKeyDown: (evt) => evt.stopPropagation(), onClick: (evt) => {
42
+ evt.stopPropagation();
43
+ applyValue(null);
44
+ document.getElementById(inputId)?.focus();
45
+ }, children: _jsx(ClearIcon, {}) })), _jsx(Button, { icon: true, variant: "tertiary", "data-size": "sm", "aria-label": getLocalizedString("Search"), onClick: (evt) => {
46
+ evt.stopPropagation();
47
+ openDialog();
48
+ }, children: _jsx(SearchIcon, {}) })] })] }), dialog] }));
49
+ }
@@ -0,0 +1,57 @@
1
+ .ObLookupGrid-root {
2
+ height: 100%;
3
+ overflow: hidden;
4
+ overscroll-behavior: contain;
5
+ border: 1px solid rgb(0 0 0 / 0.06);
6
+ }
7
+
8
+ .ObLookupGrid-header {
9
+ display: grid;
10
+ height: 40px;
11
+ align-items: center;
12
+ border-bottom: 1px solid rgb(0 0 0 / 0.12);
13
+ background-color: rgb(0 0 0 / 0.03);
14
+ font-weight: 600;
15
+ }
16
+
17
+ .ObLookupGrid-headerCell {
18
+ padding: 0 8px;
19
+ overflow: hidden;
20
+ text-overflow: ellipsis;
21
+ white-space: nowrap;
22
+ }
23
+
24
+ .ObLookupGrid-row {
25
+ --active-color: oklch(from var(--brand-secondary, #999) l c h / 50%);
26
+ display: grid;
27
+ align-items: center;
28
+ cursor: pointer;
29
+ border-bottom: 1px solid rgb(0 0 0 / 0.06);
30
+
31
+ &.active {
32
+ background-color: var(--active-color);
33
+ }
34
+
35
+ &:hover {
36
+ background-color: rgb(0 0 0 / 0.06);
37
+ }
38
+
39
+ &.active:hover {
40
+ background-color: oklch(from var(--active-color) calc(l + 0.1) calc(c - 0.04) h);
41
+ }
42
+ }
43
+
44
+ .ObLookupGrid-cell {
45
+ padding: 0 8px;
46
+ height: 100%;
47
+ display: flex;
48
+ align-items: center;
49
+ overflow: hidden;
50
+ text-overflow: ellipsis;
51
+ white-space: nowrap;
52
+
53
+ &.active {
54
+ outline: 2px solid oklch(from var(--brand-secondary, #666) calc(l - 0.2) c h);
55
+ outline-offset: -2px;
56
+ }
57
+ }
@@ -0,0 +1,13 @@
1
+ import "./LookupGrid.css";
2
+ import type { LookupColumn } from "@olenbetong/appframe-react";
3
+ export interface LookupGridProps<T extends Record<string, unknown>> {
4
+ columns: LookupColumn<T>[];
5
+ data: T[];
6
+ height: number;
7
+ currentIndex: number;
8
+ currentColumn: number;
9
+ getItemId: (item: T | undefined) => string | undefined;
10
+ isItemSelected?: (item: T) => boolean;
11
+ onSelectItem: (item: T) => void;
12
+ }
13
+ export declare function LookupGrid<T extends Record<string, unknown>>({ columns, data, height, currentIndex, currentColumn, getItemId, isItemSelected, onSelectItem, }: LookupGridProps<T>): import("react").JSX.Element;