@scm-manager/ui-forms 2.44.2 → 2.44.3-20230527-064447

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.
@@ -0,0 +1,62 @@
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present Cloudogu GmbH and Contributors
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import Field from "../base/Field";
26
+ import Label from "../base/label/Label";
27
+ import Help from "../base/help/Help";
28
+ import React from "react";
29
+ import { useGeneratedId } from "@scm-manager/ui-components";
30
+ import { withForwardRef } from "../helpers";
31
+ import Combobox, { ComboboxProps } from "./Combobox";
32
+ import classNames from "classnames";
33
+
34
+ /**
35
+ * @beta
36
+ * @since 2.45.0
37
+ */
38
+ const ComboboxField = function ComboboxField<T>(
39
+ {
40
+ label,
41
+ helpText,
42
+ error,
43
+ className,
44
+ isLoading,
45
+ ...props
46
+ }: ComboboxProps<T> & { label: string; helpText?: string; error?: string; isLoading?: boolean },
47
+ ref: React.ForwardedRef<HTMLInputElement>
48
+ ) {
49
+ const labelId = useGeneratedId();
50
+ return (
51
+ <Field className={className}>
52
+ <Label id={labelId}>
53
+ {label}
54
+ {helpText ? <Help className="ml-1" text={helpText} /> : null}
55
+ </Label>
56
+ <div className={classNames("control", { "is-loading": isLoading })}>
57
+ <Combobox {...props} ref={ref} aria-labelledby={labelId} />
58
+ </div>
59
+ </Field>
60
+ );
61
+ };
62
+ export default withForwardRef(ComboboxField);
@@ -0,0 +1,96 @@
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present Cloudogu GmbH and Contributors
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import React, { ComponentProps } from "react";
26
+ import { Controller, ControllerRenderProps, Path } from "react-hook-form";
27
+ import { useScmFormContext } from "../ScmFormContext";
28
+ import { useScmFormPathContext } from "../FormPathContext";
29
+ import { defaultOptionFactory, prefixWithoutIndices } from "../helpers";
30
+ import classNames from "classnames";
31
+ import ComboboxField from "./ComboboxField";
32
+ import { Option } from "@scm-manager/ui-types";
33
+
34
+ type Props<T extends Record<string, unknown>> = Omit<
35
+ Parameters<typeof ComboboxField>[0],
36
+ "error" | "label" | keyof ControllerRenderProps
37
+ > & {
38
+ rules?: ComponentProps<typeof Controller>["rules"];
39
+ name: Path<T>;
40
+ label?: string;
41
+ optionFactory?: (val: any) => Option<unknown>;
42
+ };
43
+
44
+ /**
45
+ * @beta
46
+ * @since 2.45.0
47
+ */
48
+ function ControlledComboboxField<T extends Record<string, unknown>>({
49
+ name,
50
+ label,
51
+ helpText,
52
+ rules,
53
+ testId,
54
+ defaultValue,
55
+ readOnly,
56
+ className,
57
+ optionFactory = defaultOptionFactory,
58
+ ...props
59
+ }: Props<T>) {
60
+ const { control, t, readOnly: formReadonly, formId } = useScmFormContext();
61
+ const formPathPrefix = useScmFormPathContext();
62
+ const nameWithPrefix = formPathPrefix ? `${formPathPrefix}.${name}` : name;
63
+ const prefixedNameWithoutIndices = prefixWithoutIndices(nameWithPrefix);
64
+ const labelTranslation = label || t(`${prefixedNameWithoutIndices}.label`) || "";
65
+ const helpTextTranslation = helpText || t(`${prefixedNameWithoutIndices}.helpText`);
66
+ return (
67
+ <Controller
68
+ control={control}
69
+ name={nameWithPrefix}
70
+ rules={rules}
71
+ defaultValue={defaultValue as never}
72
+ render={({ field: { onChange, value, ...field }, fieldState }) => (
73
+ // @ts-ignore
74
+ <ComboboxField
75
+ form={formId}
76
+ readOnly={readOnly ?? formReadonly}
77
+ className={classNames("column", className)}
78
+ {...props}
79
+ {...field}
80
+ label={labelTranslation}
81
+ helpText={helpTextTranslation}
82
+ onChange={(e) => onChange(e?.value)}
83
+ value={optionFactory(value)}
84
+ error={
85
+ fieldState.error
86
+ ? fieldState.error.message || t(`${prefixedNameWithoutIndices}.error.${fieldState.error.type}`)
87
+ : undefined
88
+ }
89
+ testId={testId ?? `select-${nameWithPrefix}`}
90
+ />
91
+ )}
92
+ />
93
+ );
94
+ }
95
+
96
+ export default ControlledComboboxField;
@@ -24,25 +24,71 @@
24
24
 
25
25
  import React, {
26
26
  ButtonHTMLAttributes,
27
+ ComponentType,
28
+ Context,
27
29
  createContext,
28
30
  HTMLAttributes,
29
- InputHTMLAttributes,
30
31
  KeyboardEventHandler,
31
32
  LiHTMLAttributes,
33
+ ReactElement,
34
+ RefObject,
32
35
  useCallback,
33
36
  useContext,
34
37
  useMemo,
38
+ useRef,
35
39
  } from "react";
36
40
  import { Slot } from "@radix-ui/react-slot";
41
+ import { Option } from "@scm-manager/ui-types";
42
+ import { mergeRefs, withForwardRef } from "../helpers";
37
43
 
38
- type ChipInputContextType = {
39
- add(newValue: string): void;
44
+ type ChipInputContextType<T> = {
45
+ add(newValue: Option<T>): void;
40
46
  remove(index: number): void;
47
+ inputRef: RefObject<HTMLInputElement>;
41
48
  disabled?: boolean;
42
49
  readOnly?: boolean;
43
- value: string[];
44
50
  };
45
- const ChipInputContext = createContext<ChipInputContextType>(null as unknown as ChipInputContextType);
51
+
52
+ const ChipInputContext = createContext<ChipInputContextType<never>>(null as unknown as ChipInputContextType<never>);
53
+
54
+ function getChipInputContext<T>() {
55
+ return ChipInputContext as unknown as Context<ChipInputContextType<T>>;
56
+ }
57
+
58
+ type CustomNewChipInputProps<T> = {
59
+ onChange: (newValue: Option<T>) => void;
60
+ value?: Option<T> | null;
61
+ readOnly?: boolean;
62
+ disabled?: boolean;
63
+ ref?: React.Ref<HTMLInputElement>;
64
+ className?: string;
65
+ placeholder?: string;
66
+ id?: string;
67
+ "aria-describedby"?: string;
68
+ };
69
+
70
+ const DefaultNewChipInput = React.forwardRef<HTMLInputElement, CustomNewChipInputProps<string>>(
71
+ ({ onChange, value, ...props }, ref) => {
72
+ const handleKeyDown = useCallback<KeyboardEventHandler<HTMLInputElement>>(
73
+ (e) => {
74
+ if (e.key === "Enter") {
75
+ e.preventDefault();
76
+ if (e.currentTarget.value) {
77
+ onChange({ label: e.currentTarget.value, value: e.currentTarget.value });
78
+ }
79
+ return false;
80
+ }
81
+ },
82
+ [onChange]
83
+ );
84
+
85
+ return (
86
+ <div className="is-flex-grow-1">
87
+ <input onKeyDown={handleKeyDown} {...props} ref={ref} />
88
+ </div>
89
+ );
90
+ }
91
+ );
46
92
 
47
93
  type ChipDeleteProps = {
48
94
  asChild?: boolean;
@@ -65,31 +111,33 @@ export const ChipDelete = React.forwardRef<HTMLButtonElement, ChipDeleteProps>((
65
111
  });
66
112
 
67
113
  type NewChipInputProps = {
68
- asChild?: boolean;
69
- } & Omit<InputHTMLAttributes<HTMLInputElement>, "onKeyDown" | "disabled" | "readOnly">;
114
+ children?: ReactElement | null;
115
+ ref?: React.Ref<HTMLInputElement>;
116
+ className?: string;
117
+ placeholder?: string;
118
+ id?: string;
119
+ "aria-describedby"?: string;
120
+ };
70
121
 
71
122
  /**
72
123
  * @beta
73
124
  * @since 2.44.0
74
125
  */
75
- export const NewChipInput = React.forwardRef<HTMLInputElement, NewChipInputProps>(({ asChild, ...props }, ref) => {
76
- const { add, value, disabled, readOnly } = useContext(ChipInputContext);
77
- const handleKeyDown = useCallback<KeyboardEventHandler<HTMLInputElement>>(
78
- (e) => {
79
- if (e.key === "Enter") {
80
- e.preventDefault();
81
- const newValue = e.currentTarget.value.trim();
82
- if (newValue && !value?.includes(newValue)) {
83
- add(newValue);
84
- e.currentTarget.value = "";
85
- }
86
- return false;
87
- }
88
- },
89
- [add, value]
90
- );
91
- const Comp = asChild ? Slot : "input";
92
- return <Comp {...props} onKeyDown={handleKeyDown} readOnly={readOnly} disabled={disabled} ref={ref} />;
126
+ export const NewChipInput = withForwardRef(function NewChipInput<T>(
127
+ props: NewChipInputProps,
128
+ ref: React.ForwardedRef<HTMLInputElement>
129
+ ) {
130
+ const { add, disabled, readOnly, inputRef } = useContext(getChipInputContext<T>());
131
+
132
+ const Comp = props.children ? Slot : DefaultNewChipInput;
133
+ return React.createElement(Comp as unknown as ComponentType<CustomNewChipInputProps<T>>, {
134
+ ...props,
135
+ onChange: add,
136
+ readOnly,
137
+ disabled,
138
+ value: null,
139
+ ref: mergeRefs(ref, inputRef),
140
+ });
93
141
  });
94
142
 
95
143
  type ChipProps = { asChild?: boolean } & LiHTMLAttributes<HTMLLIElement>;
@@ -104,48 +152,68 @@ export const Chip = React.forwardRef<HTMLLIElement, ChipProps>(({ asChild, ...pr
104
152
  return <Comp {...props} ref={ref} />;
105
153
  });
106
154
 
107
- type Props = {
108
- value?: string[];
109
- onChange?: (newValue: string[]) => void;
155
+ type Props<T> = {
156
+ value?: Option<T>[] | null;
157
+ onChange?: (newValue?: Option<T>[]) => void;
110
158
  readOnly?: boolean;
111
159
  disabled?: boolean;
160
+ isNewItemDuplicate?: (existingItem: Option<T>, newItem: Option<T>) => boolean;
112
161
  } & Omit<HTMLAttributes<HTMLUListElement>, "onChange">;
113
162
 
114
163
  /**
115
164
  * @beta
116
165
  * @since 2.44.0
117
166
  */
118
- const ChipInput = React.forwardRef<HTMLUListElement, Props>(
119
- ({ children, value = [], disabled, readOnly, onChange, ...props }, ref) => {
120
- const isInactive = useMemo(() => disabled || readOnly, [disabled, readOnly]);
121
- const add = useCallback(
122
- (newValue: string) => !isInactive && onChange && onChange([...value, newValue]),
123
- [isInactive, onChange, value]
124
- );
125
- const remove = useCallback(
126
- (index: number) => !isInactive && onChange && onChange(value?.filter((_, itdx) => itdx !== index)),
127
- [isInactive, onChange, value]
128
- );
129
- return (
130
- <ChipInputContext.Provider
131
- value={useMemo(
132
- () => ({
133
- value,
134
- disabled,
135
- readOnly,
136
- add,
137
- remove,
138
- }),
139
- [add, disabled, readOnly, remove, value]
140
- )}
141
- >
142
- <ul {...props} ref={ref}>
143
- {children}
144
- </ul>
145
- </ChipInputContext.Provider>
146
- );
147
- }
148
- );
167
+ const ChipInput = withForwardRef(function ChipInput<T>(
168
+ { children, value = [], disabled, readOnly, onChange, isNewItemDuplicate, ...props }: Props<T>,
169
+ ref: React.ForwardedRef<HTMLUListElement>
170
+ ) {
171
+ const inputRef = useRef<HTMLInputElement>(null);
172
+ const isInactive = useMemo(() => disabled || readOnly, [disabled, readOnly]);
173
+ const add = useCallback<(newValue: Option<T>) => void>(
174
+ (newItem) => {
175
+ if (
176
+ !isInactive &&
177
+ !value?.some((item) =>
178
+ isNewItemDuplicate
179
+ ? isNewItemDuplicate(item, newItem)
180
+ : item.label === newItem.label || item.value === newItem.value
181
+ )
182
+ ) {
183
+ if (onChange) {
184
+ onChange([...(value ?? []), newItem]);
185
+ }
186
+ if (inputRef.current) {
187
+ inputRef.current.value = "";
188
+ }
189
+ }
190
+ },
191
+ [isInactive, isNewItemDuplicate, onChange, value]
192
+ );
193
+ const remove = useCallback(
194
+ (index: number) => !isInactive && onChange && onChange(value?.filter((_, itdx) => itdx !== index)),
195
+ [isInactive, onChange, value]
196
+ );
197
+ const Context = getChipInputContext<T>();
198
+ return (
199
+ <Context.Provider
200
+ value={useMemo(
201
+ () => ({
202
+ disabled,
203
+ readOnly,
204
+ add,
205
+ remove,
206
+ inputRef,
207
+ }),
208
+ [add, disabled, readOnly, remove]
209
+ )}
210
+ >
211
+ <ul {...props} ref={ref}>
212
+ {children}
213
+ </ul>
214
+ </Context.Provider>
215
+ );
216
+ });
149
217
 
150
218
  export default Object.assign(ChipInput, {
151
219
  Chip: Object.assign(Chip, {
package/src/helpers.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  */
24
24
 
25
25
  import { UseFormReturn } from "react-hook-form";
26
+ import { ForwardedRef, forwardRef, MutableRefObject, Ref, RefCallback } from "react";
26
27
 
27
28
  export function prefixWithoutIndices(path: string): string {
28
29
  return path.replace(/(\.\d+)/g, "");
@@ -49,3 +50,25 @@ export function setValues<T>(newValues: T, setValue: UseFormReturn<T>["setValue"
49
50
  }
50
51
  }
51
52
  }
53
+
54
+ export function withForwardRef<T extends { name: string }>(component: T): T {
55
+ return forwardRef(component as unknown as any) as any;
56
+ }
57
+
58
+ export const defaultOptionFactory = (item: any) =>
59
+ typeof item === "object" && item !== null && "value" in item && typeof item["label"] === "string"
60
+ ? item
61
+ : { label: item as string, value: item };
62
+
63
+ export function mergeRefs<T>(...refs: Array<RefCallback<T> | MutableRefObject<T> | ForwardedRef<T>>) {
64
+ return (el: T) =>
65
+ refs.forEach((ref) => {
66
+ if (ref) {
67
+ if (typeof ref === "function") {
68
+ ref(el);
69
+ } else {
70
+ ref.current = el;
71
+ }
72
+ }
73
+ });
74
+ }
package/src/index.ts CHANGED
@@ -35,10 +35,13 @@ import ControlledTable from "./table/ControlledTable";
35
35
  import ControlledColumn from "./table/ControlledColumn";
36
36
  import AddListEntryForm from "./AddListEntryForm";
37
37
  import { ScmNestedFormPathContextProvider } from "./FormPathContext";
38
+ import ControlledComboboxField from "./combobox/ControlledComboboxField";
38
39
 
40
+ export { default as Combobox } from "./combobox/Combobox";
39
41
  export { default as ConfigurationForm } from "./ConfigurationForm";
40
42
  export { default as SelectField } from "./select/SelectField";
41
43
  export { default as ChipInputField } from "./chip-input/ChipInputField";
44
+ export { default as ComboboxField } from "./combobox/ComboboxField";
42
45
  export { default as Select } from "./select/Select";
43
46
  export * from "./resourceHooks";
44
47
 
@@ -56,4 +59,5 @@ export const Form = Object.assign(FormCmp, {
56
59
  Column: ControlledColumn,
57
60
  }),
58
61
  ChipInput: ControlledChipInputField,
62
+ Combobox: ControlledComboboxField,
59
63
  });