@olenbetong/appframe-ds 1.7.0 → 1.7.2

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,286 +1,286 @@
1
- import "./Autocomplete.css";
2
-
3
- import { Combobox as BaseCombobox } from "@base-ui/react/combobox";
4
- import { ChipRemovable } from "@digdir/designsystemet-react";
5
- import { ChevronDownIcon } from "@navikt/aksel-icons";
6
- import { useEffect, useId, useMemo, useRef } from "react";
7
-
8
- import { AutocompleteFrame } from "./AutocompleteFrame.js";
9
- import type { AutocompleteBaseProps, AutocompleteChangeReason, AutocompleteValue } from "./types.js";
10
- import {
11
- areOptionsEqual,
12
- defaultFilterOptions,
13
- defaultGetOptionLabel,
14
- groupOptions,
15
- handleInputValueChange,
16
- mapChangeReason,
17
- useControlled,
18
- } from "./utils.js";
19
- import { getLocalizedString } from "../i18n.js";
20
-
21
- export interface ComboboxProps<Option, Multiple extends boolean | undefined = false> extends AutocompleteBaseProps<
22
- Option,
23
- Multiple
24
- > {
25
- /**
26
- * The selected option(s). Use together with `onChange` for a controlled
27
- * component.
28
- */
29
- value?: AutocompleteValue<Option, Multiple>;
30
- /**
31
- * The initially selected option(s) when uncontrolled.
32
- */
33
- defaultValue?: AutocompleteValue<Option, Multiple>;
34
- /**
35
- * Called when the selection changes.
36
- */
37
- onChange?: (
38
- event: Event | undefined,
39
- value: AutocompleteValue<Option, Multiple>,
40
- reason: AutocompleteChangeReason,
41
- ) => void;
42
- }
43
-
44
- /**
45
- * A select-from-a-list input built on Base UI's `Combobox`, styled with
46
- * Designsystemet tokens. The user must pick one of the options — free text is
47
- * only used to filter the list.
48
- *
49
- * The API follows MUI's `Autocomplete`: `options`, `value`/`onChange`,
50
- * `getOptionLabel`, `isOptionEqualToValue`, `filterOptions`, `renderOption`,
51
- * `groupBy` and `multiple` all behave the same way. Designsystemet field props
52
- * (`label`, `description`, `error`, `data-size`, `data-color`) are supported on
53
- * top.
54
- *
55
- * Use `Autocomplete` instead when the input should accept free text and the
56
- * options are only suggestions.
57
- *
58
- * @example
59
- * ```jsx
60
- * <Combobox
61
- * label="Country"
62
- * options={countries}
63
- * getOptionLabel={(country) => country.name}
64
- * isOptionEqualToValue={(a, b) => a.id === b.id}
65
- * value={country}
66
- * onChange={(_event, value) => setCountry(value)}
67
- * />
68
- * ```
69
- */
70
- export function Combobox<Option, Multiple extends boolean | undefined = false>(props: ComboboxProps<Option, Multiple>) {
71
- let {
72
- options,
73
- multiple,
74
- value: valueProp,
75
- defaultValue,
76
- onChange,
77
- inputValue: inputValueProp,
78
- onInputChange,
79
- getOptionLabel = defaultGetOptionLabel,
80
- getOptionKey,
81
- getOptionDisabled,
82
- isOptionEqualToValue,
83
- groupBy,
84
- filterOptions,
85
- renderOption,
86
- renderChipLabel,
87
- noOptionsText,
88
- loadingText,
89
- loading,
90
- limit = -1,
91
- autoHighlight,
92
- openOnFocus = true,
93
- open,
94
- defaultOpen,
95
- onOpenChange,
96
- modal,
97
- disabled,
98
- readOnly,
99
- required,
100
- name,
101
- id: idProp,
102
- className,
103
- style,
104
- controlClassName,
105
- popupClassName,
106
- fullWidth,
107
- disableClearable,
108
- placeholder,
109
- inputRef,
110
- "aria-label": ariaLabel,
111
- "data-size": size,
112
- "data-color": color,
113
- } = props;
114
-
115
- let generatedId = useId();
116
- let id = idProp ?? generatedId;
117
-
118
- let emptyValue = (multiple ? [] : null) as AutocompleteValue<Option, Multiple>;
119
- let [value, setValue] = useControlled(valueProp, defaultValue ?? emptyValue);
120
- // The input shows the selected option's label. Base UI keeps it in sync while
121
- // the user interacts, but not when the selection is set from the outside.
122
- let selectedLabel = multiple || value == null ? "" : getOptionLabel(value as Option);
123
- let [inputValue, setInputValue] = useControlled(inputValueProp, selectedLabel);
124
- // `null` until the first sync, so a value that is already set on mount is synced too.
125
- let previousLabel = useRef<string | null>(null);
126
-
127
- useEffect(() => {
128
- if (previousLabel.current === selectedLabel) return;
129
-
130
- let firstSync = previousLabel.current === null;
131
- previousLabel.current = selectedLabel;
132
-
133
- // Nothing to correct on mount when no option is selected, and blanking the input would
134
- // throw away an initial `inputValue` the caller set deliberately.
135
- if (firstSync && selectedLabel === "") return;
136
-
137
- setInputValue(selectedLabel);
138
- // `setInputValue` is a no-op when the caller controls `inputValue`, so the label has to
139
- // be reported instead — otherwise a controlled input stays empty next to a selected
140
- // value. Mirrors MUI, which reports the same thing with the reason `"reset"`.
141
- onInputChange?.(undefined, selectedLabel, "reset");
142
- }, [selectedLabel, setInputValue, onInputChange]);
143
-
144
- let filteredOptions = useMemo(() => {
145
- let filter = (filterOptions ?? defaultFilterOptions) as (
146
- options: readonly Option[],
147
- state: { inputValue: string; getOptionLabel: (option: Option) => string },
148
- ) => Option[];
149
-
150
- return filter(options, { inputValue, getOptionLabel });
151
- }, [options, inputValue, filterOptions, getOptionLabel]);
152
-
153
- let filteredItems = useMemo(
154
- () => (groupBy ? groupOptions(filteredOptions, groupBy) : filteredOptions),
155
- [filteredOptions, groupBy],
156
- );
157
-
158
- let selectedOptions = useMemo(() => (multiple ? ((value ?? []) as Option[]) : []), [multiple, value]) as Option[];
159
-
160
- function handleValueChange(next: any, details: { event?: Event; reason: string }) {
161
- let deselected = multiple && Array.isArray(next) && next.length < selectedOptions.length;
162
- let reason = deselected ? "removeOption" : mapChangeReason(details.reason, next);
163
-
164
- setValue(next as AutocompleteValue<Option, Multiple>);
165
- onChange?.(details.event, next as AutocompleteValue<Option, Multiple>, reason);
166
- }
167
-
168
- function handleRemoveChip(option: Option) {
169
- let next = selectedOptions.filter((item) => !areOptionsEqual(item, option, isOptionEqualToValue));
170
- setValue(next as AutocompleteValue<Option, Multiple>);
171
- onChange?.(undefined, next as AutocompleteValue<Option, Multiple>, "removeOption");
172
- }
173
-
174
- let chips =
175
- multiple && selectedOptions.length > 0
176
- ? selectedOptions.map((option) => (
177
- <ChipRemovable
178
- key={getOptionKey?.(option) ?? getOptionLabel(option)}
179
- data-size={size}
180
- disabled={disabled || readOnly}
181
- onClick={() => handleRemoveChip(option)}
182
- >
183
- {renderChipLabel?.(option) ?? getOptionLabel(option)}
184
- </ChipRemovable>
185
- ))
186
- : undefined;
187
-
188
- function renderItem(option: Option, index: number) {
189
- let selected = multiple
190
- ? selectedOptions.some((item) => areOptionsEqual(item, option, isOptionEqualToValue))
191
- : value != null && areOptionsEqual(value as Option, option, isOptionEqualToValue);
192
-
193
- return (
194
- <BaseCombobox.Item
195
- key={getOptionKey?.(option) ?? getOptionLabel(option)}
196
- className="ObAutocomplete-item"
197
- value={option}
198
- index={index}
199
- disabled={getOptionDisabled?.(option)}
200
- >
201
- {multiple && (
202
- <BaseCombobox.ItemIndicator className="ObAutocomplete-itemIndicator">✓</BaseCombobox.ItemIndicator>
203
- )}
204
- <span className="ObAutocomplete-itemContent">
205
- {renderOption?.(option, { index, inputValue, selected }) ?? getOptionLabel(option)}
206
- </span>
207
- </BaseCombobox.Item>
208
- );
209
- }
210
-
211
- function renderListItem(item: any, index: number) {
212
- if (!groupBy) return renderItem(item as Option, index);
213
-
214
- return (
215
- <BaseCombobox.Group key={item.value} items={item.items}>
216
- <BaseCombobox.GroupLabel className="ObAutocomplete-groupLabel">{item.value}</BaseCombobox.GroupLabel>
217
- <BaseCombobox.Collection>
218
- {(option: Option, optionIndex: number) => renderItem(option, optionIndex)}
219
- </BaseCombobox.Collection>
220
- </BaseCombobox.Group>
221
- );
222
- }
223
-
224
- return (
225
- <BaseCombobox.Root
226
- items={options as any}
227
- filteredItems={filteredItems as any}
228
- filter={null}
229
- multiple={multiple as any}
230
- value={value as any}
231
- onValueChange={handleValueChange}
232
- inputValue={inputValue}
233
- onInputValueChange={(next, details) => handleInputValueChange(next, details, setInputValue, onInputChange)}
234
- itemToStringLabel={getOptionLabel as (option: unknown) => string}
235
- isItemEqualToValue={isOptionEqualToValue as ((option: unknown, value: unknown) => boolean) | undefined}
236
- disabled={disabled}
237
- readOnly={readOnly}
238
- required={required}
239
- name={name}
240
- id={id}
241
- open={open}
242
- defaultOpen={defaultOpen}
243
- onOpenChange={(nextOpen) => onOpenChange?.(nextOpen)}
244
- openOnInputClick={openOnFocus}
245
- autoHighlight={autoHighlight}
246
- limit={limit}
247
- modal={modal}
248
- >
249
- <AutocompleteFrame
250
- id={id}
251
- label={props.label}
252
- description={props.description}
253
- error={props.error}
254
- className={className}
255
- style={style}
256
- controlClassName={controlClassName}
257
- popupClassName={popupClassName}
258
- fullWidth={fullWidth}
259
- size={size}
260
- color={color}
261
- disabled={disabled}
262
- readOnly={readOnly}
263
- required={required}
264
- placeholder={placeholder}
265
- loading={loading}
266
- disableClearable={disableClearable}
267
- inputRef={inputRef}
268
- aria-label={ariaLabel}
269
- chips={chips}
270
- trigger={
271
- <BaseCombobox.Trigger
272
- className="ObAutocomplete-button ObAutocomplete-trigger"
273
- disabled={disabled || readOnly}
274
- aria-label={getLocalizedString("Open")}
275
- >
276
- <ChevronDownIcon aria-hidden fontSize="1.25em" />
277
- </BaseCombobox.Trigger>
278
- }
279
- emptyContent={
280
- loading ? (loadingText ?? getLocalizedString("Loading")) : (noOptionsText ?? getLocalizedString("No options"))
281
- }
282
- renderListItem={renderListItem}
283
- />
284
- </BaseCombobox.Root>
285
- );
286
- }
1
+ import "./Autocomplete.css";
2
+
3
+ import { Combobox as BaseCombobox } from "@base-ui/react/combobox";
4
+ import { ChipRemovable } from "@digdir/designsystemet-react";
5
+ import { ChevronDownIcon } from "@navikt/aksel-icons";
6
+ import { useEffect, useId, useMemo, useRef } from "react";
7
+
8
+ import { AutocompleteFrame } from "./AutocompleteFrame.js";
9
+ import type { AutocompleteBaseProps, AutocompleteChangeReason, AutocompleteValue } from "./types.js";
10
+ import {
11
+ areOptionsEqual,
12
+ defaultFilterOptions,
13
+ defaultGetOptionLabel,
14
+ groupOptions,
15
+ handleInputValueChange,
16
+ mapChangeReason,
17
+ useControlled,
18
+ } from "./utils.js";
19
+ import { getLocalizedString } from "../i18n.js";
20
+
21
+ export interface ComboboxProps<Option, Multiple extends boolean | undefined = false> extends AutocompleteBaseProps<
22
+ Option,
23
+ Multiple
24
+ > {
25
+ /**
26
+ * The selected option(s). Use together with `onChange` for a controlled
27
+ * component.
28
+ */
29
+ value?: AutocompleteValue<Option, Multiple>;
30
+ /**
31
+ * The initially selected option(s) when uncontrolled.
32
+ */
33
+ defaultValue?: AutocompleteValue<Option, Multiple>;
34
+ /**
35
+ * Called when the selection changes.
36
+ */
37
+ onChange?: (
38
+ event: Event | undefined,
39
+ value: AutocompleteValue<Option, Multiple>,
40
+ reason: AutocompleteChangeReason,
41
+ ) => void;
42
+ }
43
+
44
+ /**
45
+ * A select-from-a-list input built on Base UI's `Combobox`, styled with
46
+ * Designsystemet tokens. The user must pick one of the options — free text is
47
+ * only used to filter the list.
48
+ *
49
+ * The API follows MUI's `Autocomplete`: `options`, `value`/`onChange`,
50
+ * `getOptionLabel`, `isOptionEqualToValue`, `filterOptions`, `renderOption`,
51
+ * `groupBy` and `multiple` all behave the same way. Designsystemet field props
52
+ * (`label`, `description`, `error`, `data-size`, `data-color`) are supported on
53
+ * top.
54
+ *
55
+ * Use `Autocomplete` instead when the input should accept free text and the
56
+ * options are only suggestions.
57
+ *
58
+ * @example
59
+ * ```jsx
60
+ * <Combobox
61
+ * label="Country"
62
+ * options={countries}
63
+ * getOptionLabel={(country) => country.name}
64
+ * isOptionEqualToValue={(a, b) => a.id === b.id}
65
+ * value={country}
66
+ * onChange={(_event, value) => setCountry(value)}
67
+ * />
68
+ * ```
69
+ */
70
+ export function Combobox<Option, Multiple extends boolean | undefined = false>(props: ComboboxProps<Option, Multiple>) {
71
+ let {
72
+ options,
73
+ multiple,
74
+ value: valueProp,
75
+ defaultValue,
76
+ onChange,
77
+ inputValue: inputValueProp,
78
+ onInputChange,
79
+ getOptionLabel = defaultGetOptionLabel,
80
+ getOptionKey,
81
+ getOptionDisabled,
82
+ isOptionEqualToValue,
83
+ groupBy,
84
+ filterOptions,
85
+ renderOption,
86
+ renderChipLabel,
87
+ noOptionsText,
88
+ loadingText,
89
+ loading,
90
+ limit = -1,
91
+ autoHighlight,
92
+ openOnFocus = true,
93
+ open,
94
+ defaultOpen,
95
+ onOpenChange,
96
+ modal,
97
+ disabled,
98
+ readOnly,
99
+ required,
100
+ name,
101
+ id: idProp,
102
+ className,
103
+ style,
104
+ controlClassName,
105
+ popupClassName,
106
+ fullWidth,
107
+ disableClearable,
108
+ placeholder,
109
+ inputRef,
110
+ "aria-label": ariaLabel,
111
+ "data-size": size,
112
+ "data-color": color,
113
+ } = props;
114
+
115
+ let generatedId = useId();
116
+ let id = idProp ?? generatedId;
117
+
118
+ let emptyValue = (multiple ? [] : null) as AutocompleteValue<Option, Multiple>;
119
+ let [value, setValue] = useControlled(valueProp, defaultValue ?? emptyValue);
120
+ // The input shows the selected option's label. Base UI keeps it in sync while
121
+ // the user interacts, but not when the selection is set from the outside.
122
+ let selectedLabel = multiple || value == null ? "" : getOptionLabel(value as Option);
123
+ let [inputValue, setInputValue] = useControlled(inputValueProp, selectedLabel);
124
+ // `null` until the first sync, so a value that is already set on mount is synced too.
125
+ let previousLabel = useRef<string | null>(null);
126
+
127
+ useEffect(() => {
128
+ if (previousLabel.current === selectedLabel) return;
129
+
130
+ let firstSync = previousLabel.current === null;
131
+ previousLabel.current = selectedLabel;
132
+
133
+ // Nothing to correct on mount when no option is selected, and blanking the input would
134
+ // throw away an initial `inputValue` the caller set deliberately.
135
+ if (firstSync && selectedLabel === "") return;
136
+
137
+ setInputValue(selectedLabel);
138
+ // `setInputValue` is a no-op when the caller controls `inputValue`, so the label has to
139
+ // be reported instead — otherwise a controlled input stays empty next to a selected
140
+ // value. Mirrors MUI, which reports the same thing with the reason `"reset"`.
141
+ onInputChange?.(undefined, selectedLabel, "reset");
142
+ }, [selectedLabel, setInputValue, onInputChange]);
143
+
144
+ let filteredOptions = useMemo(() => {
145
+ let filter = (filterOptions ?? defaultFilterOptions) as (
146
+ options: readonly Option[],
147
+ state: { inputValue: string; getOptionLabel: (option: Option) => string },
148
+ ) => Option[];
149
+
150
+ return filter(options, { inputValue, getOptionLabel });
151
+ }, [options, inputValue, filterOptions, getOptionLabel]);
152
+
153
+ let filteredItems = useMemo(
154
+ () => (groupBy ? groupOptions(filteredOptions, groupBy) : filteredOptions),
155
+ [filteredOptions, groupBy],
156
+ );
157
+
158
+ let selectedOptions = useMemo(() => (multiple ? ((value ?? []) as Option[]) : []), [multiple, value]) as Option[];
159
+
160
+ function handleValueChange(next: any, details: { event?: Event; reason: string }) {
161
+ let deselected = multiple && Array.isArray(next) && next.length < selectedOptions.length;
162
+ let reason = deselected ? "removeOption" : mapChangeReason(details.reason, next);
163
+
164
+ setValue(next as AutocompleteValue<Option, Multiple>);
165
+ onChange?.(details.event, next as AutocompleteValue<Option, Multiple>, reason);
166
+ }
167
+
168
+ function handleRemoveChip(option: Option) {
169
+ let next = selectedOptions.filter((item) => !areOptionsEqual(item, option, isOptionEqualToValue));
170
+ setValue(next as AutocompleteValue<Option, Multiple>);
171
+ onChange?.(undefined, next as AutocompleteValue<Option, Multiple>, "removeOption");
172
+ }
173
+
174
+ let chips =
175
+ multiple && selectedOptions.length > 0
176
+ ? selectedOptions.map((option) => (
177
+ <ChipRemovable
178
+ key={getOptionKey?.(option) ?? getOptionLabel(option)}
179
+ data-size={size}
180
+ disabled={disabled || readOnly}
181
+ onClick={() => handleRemoveChip(option)}
182
+ >
183
+ {renderChipLabel?.(option) ?? getOptionLabel(option)}
184
+ </ChipRemovable>
185
+ ))
186
+ : undefined;
187
+
188
+ function renderItem(option: Option, index: number) {
189
+ let selected = multiple
190
+ ? selectedOptions.some((item) => areOptionsEqual(item, option, isOptionEqualToValue))
191
+ : value != null && areOptionsEqual(value as Option, option, isOptionEqualToValue);
192
+
193
+ return (
194
+ <BaseCombobox.Item
195
+ key={getOptionKey?.(option) ?? getOptionLabel(option)}
196
+ className="ObAutocomplete-item"
197
+ value={option}
198
+ index={index}
199
+ disabled={getOptionDisabled?.(option)}
200
+ >
201
+ {multiple && (
202
+ <BaseCombobox.ItemIndicator className="ObAutocomplete-itemIndicator">✓</BaseCombobox.ItemIndicator>
203
+ )}
204
+ <span className="ObAutocomplete-itemContent">
205
+ {renderOption?.(option, { index, inputValue, selected }) ?? getOptionLabel(option)}
206
+ </span>
207
+ </BaseCombobox.Item>
208
+ );
209
+ }
210
+
211
+ function renderListItem(item: any, index: number) {
212
+ if (!groupBy) return renderItem(item as Option, index);
213
+
214
+ return (
215
+ <BaseCombobox.Group key={item.value} items={item.items}>
216
+ <BaseCombobox.GroupLabel className="ObAutocomplete-groupLabel">{item.value}</BaseCombobox.GroupLabel>
217
+ <BaseCombobox.Collection>
218
+ {(option: Option, optionIndex: number) => renderItem(option, optionIndex)}
219
+ </BaseCombobox.Collection>
220
+ </BaseCombobox.Group>
221
+ );
222
+ }
223
+
224
+ return (
225
+ <BaseCombobox.Root
226
+ items={options as any}
227
+ filteredItems={filteredItems as any}
228
+ filter={null}
229
+ multiple={multiple as any}
230
+ value={value as any}
231
+ onValueChange={handleValueChange}
232
+ inputValue={inputValue}
233
+ onInputValueChange={(next, details) => handleInputValueChange(next, details, setInputValue, onInputChange)}
234
+ itemToStringLabel={getOptionLabel as (option: unknown) => string}
235
+ isItemEqualToValue={isOptionEqualToValue as ((option: unknown, value: unknown) => boolean) | undefined}
236
+ disabled={disabled}
237
+ readOnly={readOnly}
238
+ required={required}
239
+ name={name}
240
+ id={id}
241
+ open={open}
242
+ defaultOpen={defaultOpen}
243
+ onOpenChange={(nextOpen) => onOpenChange?.(nextOpen)}
244
+ openOnInputClick={openOnFocus}
245
+ autoHighlight={autoHighlight}
246
+ limit={limit}
247
+ modal={modal}
248
+ >
249
+ <AutocompleteFrame
250
+ id={id}
251
+ label={props.label}
252
+ description={props.description}
253
+ error={props.error}
254
+ className={className}
255
+ style={style}
256
+ controlClassName={controlClassName}
257
+ popupClassName={popupClassName}
258
+ fullWidth={fullWidth}
259
+ size={size}
260
+ color={color}
261
+ disabled={disabled}
262
+ readOnly={readOnly}
263
+ required={required}
264
+ placeholder={placeholder}
265
+ loading={loading}
266
+ disableClearable={disableClearable}
267
+ inputRef={inputRef}
268
+ aria-label={ariaLabel}
269
+ chips={chips}
270
+ trigger={
271
+ <BaseCombobox.Trigger
272
+ className="ObAutocomplete-button ObAutocomplete-trigger"
273
+ disabled={disabled || readOnly}
274
+ aria-label={getLocalizedString("Open")}
275
+ >
276
+ <ChevronDownIcon aria-hidden fontSize="1.25em" />
277
+ </BaseCombobox.Trigger>
278
+ }
279
+ emptyContent={
280
+ loading ? (loadingText ?? getLocalizedString("Loading")) : (noOptionsText ?? getLocalizedString("No options"))
281
+ }
282
+ renderListItem={renderListItem}
283
+ />
284
+ </BaseCombobox.Root>
285
+ );
286
+ }
@@ -1,4 +1,4 @@
1
- export * from "./Autocomplete.js";
2
- export * from "./Combobox.js";
3
- export type * from "./types.js";
4
- export { createFilterOptions, type CreateFilterOptionsConfig } from "./utils.js";
1
+ export * from "./Autocomplete.js";
2
+ export * from "./Combobox.js";
3
+ export type * from "./types.js";
4
+ export { createFilterOptions, type CreateFilterOptionsConfig } from "./utils.js";