@olenbetong/appframe-ds 1.7.1 → 1.8.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,183 +1,183 @@
1
- import { useCallback, useRef, useState } from "react";
2
-
3
- import type {
4
- AutocompleteChangeReason,
5
- AutocompleteFilterOptionsState,
6
- AutocompleteInputChangeReason,
7
- } from "./types.js";
8
-
9
- /**
10
- * Default label resolver: uses `label`, then `name`, then the value itself.
11
- */
12
- export function defaultGetOptionLabel(option: unknown): string {
13
- if (option == null) return "";
14
- if (typeof option === "string") return option;
15
- if (typeof option === "object") {
16
- let record = option as Record<string, unknown>;
17
- if (typeof record.label === "string") return record.label;
18
- if (typeof record.name === "string") return record.name;
19
- }
20
-
21
- return String(option);
22
- }
23
-
24
- export interface CreateFilterOptionsConfig<Option> {
25
- /**
26
- * Removes diacritics before matching.
27
- * @default true
28
- */
29
- ignoreAccents?: boolean;
30
- /**
31
- * Matches case insensitively.
32
- * @default true
33
- */
34
- ignoreCase?: boolean;
35
- /**
36
- * Where in the option label the query has to match.
37
- * @default "any"
38
- */
39
- matchFrom?: "any" | "start";
40
- /**
41
- * The maximum number of options returned.
42
- */
43
- limit?: number;
44
- /**
45
- * Trims the query before matching.
46
- * @default false
47
- */
48
- trim?: boolean;
49
- /**
50
- * Returns the string the query is matched against.
51
- */
52
- stringify?: (option: Option) => string;
53
- }
54
-
55
- /**
56
- * Creates a filter function for the `filterOptions` prop, equivalent to MUI's
57
- * `createFilterOptions`.
58
- *
59
- * @example
60
- * ```jsx
61
- * let filterOptions = createFilterOptions({ matchFrom: "start", limit: 20 });
62
- * <Combobox options={options} filterOptions={filterOptions} />
63
- * ```
64
- */
65
- export function createFilterOptions<Option>(config: CreateFilterOptionsConfig<Option> = {}) {
66
- let { ignoreAccents = true, ignoreCase = true, limit, matchFrom = "any", stringify, trim = false } = config;
67
-
68
- return (options: readonly Option[], state: AutocompleteFilterOptionsState<Option>) => {
69
- let input = trim ? state.inputValue.trim() : state.inputValue;
70
- if (ignoreCase) input = input.toLowerCase();
71
- if (ignoreAccents) input = stripDiacritics(input);
72
-
73
- let filtered = input
74
- ? options.filter((option) => {
75
- let candidate = (stringify ?? state.getOptionLabel)(option);
76
- if (ignoreCase) candidate = candidate.toLowerCase();
77
- if (ignoreAccents) candidate = stripDiacritics(candidate);
78
-
79
- return matchFrom === "start" ? candidate.startsWith(input) : candidate.includes(input);
80
- })
81
- : [...options];
82
-
83
- return typeof limit === "number" ? filtered.slice(0, limit) : filtered;
84
- };
85
- }
86
-
87
- function stripDiacritics(value: string) {
88
- return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
89
- }
90
-
91
- export const defaultFilterOptions = createFilterOptions<unknown>();
92
-
93
- export interface OptionGroup<Option> {
94
- /**
95
- * Group header text. Named `value` because Base UI uses it as the group key.
96
- */
97
- value: string;
98
- items: Option[];
99
- [key: string]: unknown;
100
- }
101
-
102
- /**
103
- * Splits an already sorted list of options into consecutive groups, the same
104
- * way MUI's `groupBy` works.
105
- */
106
- export function groupOptions<Option>(options: readonly Option[], groupBy: (option: Option) => string) {
107
- let groups: OptionGroup<Option>[] = [];
108
-
109
- for (let option of options) {
110
- let group = groupBy(option);
111
- let last = groups[groups.length - 1];
112
-
113
- if (last && last.value === group) {
114
- last.items.push(option);
115
- } else {
116
- groups.push({ value: group, items: [option] });
117
- }
118
- }
119
-
120
- return groups;
121
- }
122
-
123
- /**
124
- * State that is controlled when `controlled` is not `undefined`, and
125
- * uncontrolled otherwise.
126
- */
127
- export function useControlled<T>(controlled: T | undefined, defaultValue: T) {
128
- let [uncontrolled, setUncontrolled] = useState(defaultValue);
129
- let isControlled = useRef(controlled !== undefined).current;
130
- let value = isControlled ? (controlled as T) : uncontrolled;
131
-
132
- let setValue = useCallback(
133
- (next: T) => {
134
- if (!isControlled) setUncontrolled(next);
135
- },
136
- [isControlled],
137
- );
138
-
139
- return [value, setValue] as const;
140
- }
141
-
142
- /**
143
- * Compares two options, falling back to reference equality like MUI does.
144
- */
145
- export function areOptionsEqual<Option>(
146
- a: Option,
147
- b: Option,
148
- isOptionEqualToValue?: (option: Option, value: Option) => boolean,
149
- ) {
150
- return isOptionEqualToValue ? isOptionEqualToValue(a, b) : Object.is(a, b);
151
- }
152
-
153
- /**
154
- * Maps a Base UI change reason to the MUI-style reason.
155
- */
156
- export function mapChangeReason(reason: string, next: unknown): AutocompleteChangeReason {
157
- if (reason === "clear-press" || reason === "input-clear") return "clear";
158
- if (reason === "chip-remove-press") return "removeOption";
159
- if (next == null || (Array.isArray(next) && next.length === 0)) return "clear";
160
-
161
- return "selectOption";
162
- }
163
-
164
- function mapInputChangeReason(reason: string): AutocompleteInputChangeReason {
165
- if (reason === "input-change") return "input";
166
- if (reason === "input-clear" || reason === "clear-press") return "clear";
167
-
168
- return "reset";
169
- }
170
-
171
- /**
172
- * Keeps the input value state in sync and forwards the change to
173
- * `onInputChange` with a MUI-style reason.
174
- */
175
- export function handleInputValueChange(
176
- next: string,
177
- details: { event?: Event; reason: string },
178
- setInputValue: (value: string) => void,
179
- onInputChange?: (event: Event | undefined, value: string, reason: AutocompleteInputChangeReason) => void,
180
- ) {
181
- setInputValue(next);
182
- onInputChange?.(details.event, next, mapInputChangeReason(details.reason));
183
- }
1
+ import { useCallback, useRef, useState } from "react";
2
+
3
+ import type {
4
+ AutocompleteChangeReason,
5
+ AutocompleteFilterOptionsState,
6
+ AutocompleteInputChangeReason,
7
+ } from "./types.js";
8
+
9
+ /**
10
+ * Default label resolver: uses `label`, then `name`, then the value itself.
11
+ */
12
+ export function defaultGetOptionLabel(option: unknown): string {
13
+ if (option == null) return "";
14
+ if (typeof option === "string") return option;
15
+ if (typeof option === "object") {
16
+ let record = option as Record<string, unknown>;
17
+ if (typeof record.label === "string") return record.label;
18
+ if (typeof record.name === "string") return record.name;
19
+ }
20
+
21
+ return String(option);
22
+ }
23
+
24
+ export interface CreateFilterOptionsConfig<Option> {
25
+ /**
26
+ * Removes diacritics before matching.
27
+ * @default true
28
+ */
29
+ ignoreAccents?: boolean;
30
+ /**
31
+ * Matches case insensitively.
32
+ * @default true
33
+ */
34
+ ignoreCase?: boolean;
35
+ /**
36
+ * Where in the option label the query has to match.
37
+ * @default "any"
38
+ */
39
+ matchFrom?: "any" | "start";
40
+ /**
41
+ * The maximum number of options returned.
42
+ */
43
+ limit?: number;
44
+ /**
45
+ * Trims the query before matching.
46
+ * @default false
47
+ */
48
+ trim?: boolean;
49
+ /**
50
+ * Returns the string the query is matched against.
51
+ */
52
+ stringify?: (option: Option) => string;
53
+ }
54
+
55
+ /**
56
+ * Creates a filter function for the `filterOptions` prop, equivalent to MUI's
57
+ * `createFilterOptions`.
58
+ *
59
+ * @example
60
+ * ```jsx
61
+ * let filterOptions = createFilterOptions({ matchFrom: "start", limit: 20 });
62
+ * <Combobox options={options} filterOptions={filterOptions} />
63
+ * ```
64
+ */
65
+ export function createFilterOptions<Option>(config: CreateFilterOptionsConfig<Option> = {}) {
66
+ let { ignoreAccents = true, ignoreCase = true, limit, matchFrom = "any", stringify, trim = false } = config;
67
+
68
+ return (options: readonly Option[], state: AutocompleteFilterOptionsState<Option>) => {
69
+ let input = trim ? state.inputValue.trim() : state.inputValue;
70
+ if (ignoreCase) input = input.toLowerCase();
71
+ if (ignoreAccents) input = stripDiacritics(input);
72
+
73
+ let filtered = input
74
+ ? options.filter((option) => {
75
+ let candidate = (stringify ?? state.getOptionLabel)(option);
76
+ if (ignoreCase) candidate = candidate.toLowerCase();
77
+ if (ignoreAccents) candidate = stripDiacritics(candidate);
78
+
79
+ return matchFrom === "start" ? candidate.startsWith(input) : candidate.includes(input);
80
+ })
81
+ : [...options];
82
+
83
+ return typeof limit === "number" ? filtered.slice(0, limit) : filtered;
84
+ };
85
+ }
86
+
87
+ function stripDiacritics(value: string) {
88
+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
89
+ }
90
+
91
+ export const defaultFilterOptions = createFilterOptions<unknown>();
92
+
93
+ export interface OptionGroup<Option> {
94
+ /**
95
+ * Group header text. Named `value` because Base UI uses it as the group key.
96
+ */
97
+ value: string;
98
+ items: Option[];
99
+ [key: string]: unknown;
100
+ }
101
+
102
+ /**
103
+ * Splits an already sorted list of options into consecutive groups, the same
104
+ * way MUI's `groupBy` works.
105
+ */
106
+ export function groupOptions<Option>(options: readonly Option[], groupBy: (option: Option) => string) {
107
+ let groups: OptionGroup<Option>[] = [];
108
+
109
+ for (let option of options) {
110
+ let group = groupBy(option);
111
+ let last = groups[groups.length - 1];
112
+
113
+ if (last && last.value === group) {
114
+ last.items.push(option);
115
+ } else {
116
+ groups.push({ value: group, items: [option] });
117
+ }
118
+ }
119
+
120
+ return groups;
121
+ }
122
+
123
+ /**
124
+ * State that is controlled when `controlled` is not `undefined`, and
125
+ * uncontrolled otherwise.
126
+ */
127
+ export function useControlled<T>(controlled: T | undefined, defaultValue: T) {
128
+ let [uncontrolled, setUncontrolled] = useState(defaultValue);
129
+ let isControlled = useRef(controlled !== undefined).current;
130
+ let value = isControlled ? (controlled as T) : uncontrolled;
131
+
132
+ let setValue = useCallback(
133
+ (next: T) => {
134
+ if (!isControlled) setUncontrolled(next);
135
+ },
136
+ [isControlled],
137
+ );
138
+
139
+ return [value, setValue] as const;
140
+ }
141
+
142
+ /**
143
+ * Compares two options, falling back to reference equality like MUI does.
144
+ */
145
+ export function areOptionsEqual<Option>(
146
+ a: Option,
147
+ b: Option,
148
+ isOptionEqualToValue?: (option: Option, value: Option) => boolean,
149
+ ) {
150
+ return isOptionEqualToValue ? isOptionEqualToValue(a, b) : Object.is(a, b);
151
+ }
152
+
153
+ /**
154
+ * Maps a Base UI change reason to the MUI-style reason.
155
+ */
156
+ export function mapChangeReason(reason: string, next: unknown): AutocompleteChangeReason {
157
+ if (reason === "clear-press" || reason === "input-clear") return "clear";
158
+ if (reason === "chip-remove-press") return "removeOption";
159
+ if (next == null || (Array.isArray(next) && next.length === 0)) return "clear";
160
+
161
+ return "selectOption";
162
+ }
163
+
164
+ function mapInputChangeReason(reason: string): AutocompleteInputChangeReason {
165
+ if (reason === "input-change") return "input";
166
+ if (reason === "input-clear" || reason === "clear-press") return "clear";
167
+
168
+ return "reset";
169
+ }
170
+
171
+ /**
172
+ * Keeps the input value state in sync and forwards the change to
173
+ * `onInputChange` with a MUI-style reason.
174
+ */
175
+ export function handleInputValueChange(
176
+ next: string,
177
+ details: { event?: Event; reason: string },
178
+ setInputValue: (value: string) => void,
179
+ onInputChange?: (event: Event | undefined, value: string, reason: AutocompleteInputChangeReason) => void,
180
+ ) {
181
+ setInputValue(next);
182
+ onInputChange?.(details.event, next, mapInputChangeReason(details.reason));
183
+ }
@@ -1,4 +1,4 @@
1
- import { Button, Dropdown } from "@digdir/designsystemet-react";
1
+ import { Badge, BadgePosition, Button, Dropdown } from "@digdir/designsystemet-react";
2
2
  import {
3
3
  type GridApi,
4
4
  type GridExportMenuItemProps,
@@ -20,6 +20,8 @@ import {
20
20
  import { type DataObject, exportOptionsFromDataObject } from "@olenbetong/appframe-data";
21
21
  import { useDataObject, useLoading, usePermissions } from "@olenbetong/appframe-react";
22
22
 
23
+ import { useState } from "react";
24
+
23
25
  import { openDataObjectReportWithProgress } from "../report-downloader/index.js";
24
26
  import { useAfGridContext } from "./AfGridContext.js";
25
27
  import { addRow } from "./editing.js";
@@ -45,16 +47,30 @@ export function GridToolbarAddIfAllowedButton({ disableInsert }: { disableInsert
45
47
  ) : null;
46
48
  }
47
49
 
48
- export function GridToolbarRefreshButton() {
50
+ export type GridToolbarIconOnlyProps = {
51
+ /** Show the icon alone, with the label as its accessible name and tooltip. */
52
+ iconOnly?: boolean;
53
+ };
54
+
55
+ export function GridToolbarRefreshButton({ iconOnly }: GridToolbarIconOnlyProps = {}) {
49
56
  let dataObject = useDataObject();
50
57
  let isLoading = useLoading(dataObject);
58
+ let label = getLocalizedString("Refresh");
51
59
 
52
60
  return (
53
- <Button variant="tertiary" data-size="sm" loading={isLoading} onClick={() => dataObject.refreshDataSource()}>
61
+ <Button
62
+ variant="tertiary"
63
+ data-size="sm"
64
+ icon={iconOnly}
65
+ aria-label={iconOnly ? label : undefined}
66
+ title={iconOnly ? label : undefined}
67
+ loading={isLoading}
68
+ onClick={() => dataObject.refreshDataSource()}
69
+ >
54
70
  {/* Designsystemet prepends the spinner rather than replacing the children, so
55
71
  the icon is hidden while loading to keep the button from changing width */}
56
72
  {!isLoading && <ArrowsCirclepathIcon aria-hidden />}
57
- {getLocalizedString("Refresh")}
73
+ {!iconOnly && label}
58
74
  </Button>
59
75
  );
60
76
  }
@@ -74,13 +90,26 @@ export function GridToolbarColumnsButton() {
74
90
  * Opens the filter builder instead of the grid's own filter panel. The count
75
91
  * reflects the conditions in the builder's filter, not the header filters.
76
92
  */
77
- export function GridToolbarFilterButton() {
93
+ export function GridToolbarFilterButton({ iconOnly }: GridToolbarIconOnlyProps = {}) {
78
94
  let { openFilterBuilder, filterCount } = useAfGridContext();
95
+ let label = getLocalizedString("Filter");
96
+
97
+ if (iconOnly) {
98
+ let name = filterCount > 0 ? `${label} (${filterCount})` : label;
99
+ return (
100
+ <BadgePosition placement="top-right" overlap="circle">
101
+ {filterCount > 0 && <Badge data-color="brand" data-size="sm" count={filterCount} aria-hidden="true" />}
102
+ <Button variant="tertiary" data-size="sm" icon aria-label={name} title={name} onClick={openFilterBuilder}>
103
+ <FilterIcon aria-hidden />
104
+ </Button>
105
+ </BadgePosition>
106
+ );
107
+ }
79
108
 
80
109
  return (
81
110
  <Button variant="tertiary" data-size="sm" onClick={openFilterBuilder}>
82
111
  <FilterIcon aria-hidden />
83
- {getLocalizedString("Filter")}
112
+ {label}
84
113
  {filterCount > 0 ? ` (${filterCount})` : ""}
85
114
  </Button>
86
115
  );
@@ -160,16 +189,52 @@ export function AfGridToolbarExcelExportButton({ fileName, title }: { fileName?:
160
189
  );
161
190
  }
162
191
 
163
- export function GridToolbarMoreOptionsButton() {
192
+ export type GridToolbarMoreOptionsButtonProps = React.PropsWithChildren<{
193
+ /** Offer the column panel in the menu, for toolbars without a Columns button. */
194
+ showColumns?: boolean;
195
+ }>;
196
+
197
+ /**
198
+ * The toolbar's "more" menu: exports, density and layout reset. `children` are extra
199
+ * `Dropdown.Item`s placed first. The menu closes when an item is chosen.
200
+ */
201
+ export function GridToolbarMoreOptionsButton({ showColumns, children }: GridToolbarMoreOptionsButtonProps = {}) {
164
202
  let apiRef = useGridApiContext();
203
+ let { openColumnsPanel } = useAfGridContext();
204
+ let [open, setOpen] = useState(false);
165
205
 
166
206
  return (
167
207
  <Dropdown.TriggerContext>
168
- <Dropdown.Trigger variant="tertiary" icon data-size="sm" aria-label={getLocalizedString("More options")}>
208
+ <Dropdown.Trigger
209
+ variant="tertiary"
210
+ icon
211
+ data-size="sm"
212
+ aria-label={getLocalizedString("More options")}
213
+ title={getLocalizedString("More options")}
214
+ >
169
215
  <MenuElipsisVerticalIcon aria-hidden />
170
216
  </Dropdown.Trigger>
171
- <Dropdown placement="bottom-end" data-size="sm">
172
- <Dropdown.List>
217
+ <Dropdown
218
+ open={open}
219
+ onOpen={() => setOpen(true)}
220
+ onClose={() => setOpen(false)}
221
+ placement="bottom-end"
222
+ data-size="sm"
223
+ >
224
+ <Dropdown.List
225
+ onClick={(event) => {
226
+ if ((event.target as HTMLElement).closest("button, a")) setOpen(false);
227
+ }}
228
+ >
229
+ {children}
230
+ {showColumns && (
231
+ <Dropdown.Item>
232
+ <Dropdown.Button onClick={openColumnsPanel}>
233
+ <TableIcon aria-hidden />
234
+ {getLocalizedString("Columns")}
235
+ </Dropdown.Button>
236
+ </Dropdown.Item>
237
+ )}
173
238
  <Dropdown.Item>
174
239
  <Dropdown.Button onClick={() => apiRef.current.exportDataAsCsv()}>
175
240
  <FileCsvIcon aria-hidden />
@@ -41,7 +41,9 @@ import {
41
41
  GridToolbarColumnsButton,
42
42
  GridToolbarContainer,
43
43
  GridToolbarFilterButton,
44
+ type GridToolbarIconOnlyProps,
44
45
  GridToolbarMoreOptionsButton,
46
+ type GridToolbarMoreOptionsButtonProps,
45
47
  GridToolbarRefreshButton,
46
48
  GridToolbarResetLayoutButton,
47
49
  } from "./Toolbar.js";
@@ -109,6 +111,8 @@ export type {
109
111
  AfGridColumn,
110
112
  AfGridExcelExportOptions,
111
113
  AfGridNewItemRowPosition,
114
+ GridToolbarIconOnlyProps,
115
+ GridToolbarMoreOptionsButtonProps,
112
116
  AfGridRowAction,
113
117
  };
114
118
  export type { AfGridGrouping, AfGridGroupingProps } from "./useAfRowGrouping.js";