@scm-manager/ui-core 3.0.0-20240024-101702

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 (128) hide show
  1. package/.storybook/.babelrc +3 -0
  2. package/.storybook/RemoveThemesPlugin.js +57 -0
  3. package/.storybook/main.js +92 -0
  4. package/.storybook/preview-head.html +25 -0
  5. package/.storybook/preview.js +95 -0
  6. package/.storybook/withApiProvider.js +46 -0
  7. package/docs/introduction.stories.mdx +64 -0
  8. package/docs/usage.stories.mdx +22 -0
  9. package/package.json +81 -0
  10. package/src/base/buttons/Button.stories.tsx +89 -0
  11. package/src/base/buttons/Button.test.stories.mdx +74 -0
  12. package/src/base/buttons/Button.tsx +143 -0
  13. package/src/base/buttons/Icon.tsx +58 -0
  14. package/src/base/buttons/a11y.test.ts +34 -0
  15. package/src/base/buttons/docs/introduction.stories.mdx +64 -0
  16. package/src/base/buttons/docs/usage.stories.mdx +22 -0
  17. package/src/base/buttons/image-snapshot.test.ts +33 -0
  18. package/src/base/buttons/index.ts +26 -0
  19. package/src/base/forms/AddListEntryForm.tsx +127 -0
  20. package/src/base/forms/ConfigurationForm.tsx +59 -0
  21. package/src/base/forms/Form.stories.tsx +453 -0
  22. package/src/base/forms/Form.tsx +215 -0
  23. package/src/base/forms/FormPathContext.tsx +73 -0
  24. package/src/base/forms/FormRow.tsx +37 -0
  25. package/src/base/forms/ScmFormContext.tsx +43 -0
  26. package/src/base/forms/ScmFormListContext.tsx +65 -0
  27. package/src/base/forms/base/Control.tsx +34 -0
  28. package/src/base/forms/base/Field.tsx +35 -0
  29. package/src/base/forms/base/field-message/FieldMessage.tsx +34 -0
  30. package/src/base/forms/base/help/Help.tsx +34 -0
  31. package/src/base/forms/base/label/Label.tsx +35 -0
  32. package/src/base/forms/checkbox/Checkbox.stories.mdx +26 -0
  33. package/src/base/forms/checkbox/Checkbox.tsx +118 -0
  34. package/src/base/forms/checkbox/CheckboxField.tsx +39 -0
  35. package/src/base/forms/checkbox/ControlledCheckboxField.stories.mdx +36 -0
  36. package/src/base/forms/checkbox/ControlledCheckboxField.tsx +82 -0
  37. package/src/base/forms/chip-input/ChipInputField.stories.tsx +75 -0
  38. package/src/base/forms/chip-input/ChipInputField.tsx +169 -0
  39. package/src/base/forms/chip-input/ControlledChipInputField.tsx +111 -0
  40. package/src/base/forms/combobox/Combobox.stories.tsx +125 -0
  41. package/src/base/forms/combobox/Combobox.tsx +223 -0
  42. package/src/base/forms/combobox/ComboboxField.tsx +62 -0
  43. package/src/base/forms/combobox/ControlledComboboxField.tsx +96 -0
  44. package/src/base/forms/headless-chip-input/ChipInput.tsx +237 -0
  45. package/src/base/forms/helpers.ts +74 -0
  46. package/src/base/forms/index.ts +85 -0
  47. package/src/base/forms/input/ControlledInputField.stories.mdx +36 -0
  48. package/src/base/forms/input/ControlledInputField.tsx +87 -0
  49. package/src/base/forms/input/ControlledSecretConfirmationField.stories.mdx +39 -0
  50. package/src/base/forms/input/ControlledSecretConfirmationField.tsx +138 -0
  51. package/src/base/forms/input/Input.stories.mdx +22 -0
  52. package/src/base/forms/input/Input.tsx +46 -0
  53. package/src/base/forms/input/InputField.stories.mdx +22 -0
  54. package/src/base/forms/input/InputField.tsx +61 -0
  55. package/src/base/forms/input/Textarea.stories.mdx +28 -0
  56. package/src/base/forms/input/Textarea.tsx +46 -0
  57. package/src/base/forms/list/ControlledList.tsx +88 -0
  58. package/src/base/forms/radio-button/ControlledRadioGroupField.tsx +94 -0
  59. package/src/base/forms/radio-button/RadioButton.stories.tsx +226 -0
  60. package/src/base/forms/radio-button/RadioButton.tsx +116 -0
  61. package/src/base/forms/radio-button/RadioButtonContext.tsx +42 -0
  62. package/src/base/forms/radio-button/RadioGroup.tsx +49 -0
  63. package/src/base/forms/radio-button/RadioGroupField.tsx +58 -0
  64. package/src/base/forms/resourceHooks.ts +164 -0
  65. package/src/base/forms/select/ControlledSelectField.tsx +87 -0
  66. package/src/base/forms/select/Select.tsx +57 -0
  67. package/src/base/forms/select/SelectField.tsx +63 -0
  68. package/src/base/forms/table/ControlledColumn.tsx +49 -0
  69. package/src/base/forms/table/ControlledTable.tsx +99 -0
  70. package/src/base/forms/variants.ts +27 -0
  71. package/src/base/helpers/devbuild.ts +44 -0
  72. package/src/base/helpers/index.ts +26 -0
  73. package/src/base/helpers/useAriaId.tsx +31 -0
  74. package/src/base/index.ts +34 -0
  75. package/src/base/layout/_helpers/with-classes.tsx +52 -0
  76. package/src/base/layout/card/Card.stories.tsx +113 -0
  77. package/src/base/layout/card/Card.tsx +76 -0
  78. package/src/base/layout/card/CardDetail.tsx +196 -0
  79. package/src/base/layout/card/CardRow.tsx +46 -0
  80. package/src/base/layout/card/CardTitle.tsx +59 -0
  81. package/src/base/layout/card-list/CardList.stories.tsx +201 -0
  82. package/src/base/layout/card-list/CardList.tsx +76 -0
  83. package/src/base/layout/collapsible/Collapsible.stories.tsx +45 -0
  84. package/src/base/layout/collapsible/Collapsible.tsx +87 -0
  85. package/src/base/layout/index.ts +93 -0
  86. package/src/base/layout/tabs/TabTrigger.tsx +46 -0
  87. package/src/base/layout/tabs/Tabs.stories.tsx +48 -0
  88. package/src/base/layout/tabs/Tabs.tsx +52 -0
  89. package/src/base/layout/tabs/TabsContent.tsx +33 -0
  90. package/src/base/layout/tabs/TabsList.tsx +41 -0
  91. package/src/base/layout/templates/data-page/DataPage.stories.tsx +201 -0
  92. package/src/base/layout/templates/data-page/DataPageHeader.tsx +100 -0
  93. package/src/base/misc/Image.tsx +32 -0
  94. package/src/base/misc/Level.tsx +40 -0
  95. package/src/base/misc/Loading.tsx +64 -0
  96. package/src/base/misc/SubSubtitle.tsx +36 -0
  97. package/src/base/misc/Subtitle.tsx +37 -0
  98. package/src/base/misc/Title.tsx +56 -0
  99. package/src/base/misc/index.ts +30 -0
  100. package/src/base/notifications/BackendErrorNotification.tsx +160 -0
  101. package/src/base/notifications/ErrorNotification.tsx +73 -0
  102. package/src/base/notifications/Notification.tsx +48 -0
  103. package/src/base/notifications/index.tsx +27 -0
  104. package/src/base/overlays/dialog/Dialog.stories.tsx +64 -0
  105. package/src/base/overlays/dialog/Dialog.tsx +85 -0
  106. package/src/base/overlays/index.ts +44 -0
  107. package/src/base/overlays/menu/Menu.stories.tsx +78 -0
  108. package/src/base/overlays/menu/Menu.tsx +213 -0
  109. package/src/base/overlays/menu/MenuTrigger.tsx +63 -0
  110. package/src/base/overlays/popover/Popover.stories.tsx +69 -0
  111. package/src/base/overlays/popover/Popover.tsx +95 -0
  112. package/src/base/overlays/tooltip/Tooltip.examples.js +41 -0
  113. package/src/base/overlays/tooltip/Tooltip.stories.mdx +52 -0
  114. package/src/base/overlays/tooltip/Tooltip.tsx +96 -0
  115. package/src/base/shortcuts/index.ts +28 -0
  116. package/src/base/shortcuts/iterator/callbackIterator.ts +220 -0
  117. package/src/base/shortcuts/iterator/keyboardIterator.test.tsx +431 -0
  118. package/src/base/shortcuts/iterator/keyboardIterator.tsx +141 -0
  119. package/src/base/shortcuts/usePauseShortcuts.ts +44 -0
  120. package/src/base/shortcuts/useShortcut.ts +110 -0
  121. package/src/base/shortcuts/useShortcutDocs.tsx +54 -0
  122. package/src/base/text/SplitAndReplace.stories.tsx +83 -0
  123. package/src/base/text/SplitAndReplace.tsx +65 -0
  124. package/src/base/text/index.ts +25 -0
  125. package/src/base/text/textSplitAndReplace.test.ts +134 -0
  126. package/src/base/text/textSplitAndReplace.ts +86 -0
  127. package/src/index.ts +25 -0
  128. package/tsconfig.json +6 -0
@@ -0,0 +1,453 @@
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
+ /* eslint-disable no-console */
25
+ import React, { useRef, useState } from "react";
26
+ import { storiesOf } from "@storybook/react";
27
+ import Form from "./Form";
28
+ import FormRow from "./FormRow";
29
+ import ControlledInputField from "./input/ControlledInputField";
30
+ import ControlledSecretConfirmationField from "./input/ControlledSecretConfirmationField";
31
+ import ControlledCheckboxField from "./checkbox/ControlledCheckboxField";
32
+ import ControlledList from "./list/ControlledList";
33
+ import ControlledSelectField from "./select/ControlledSelectField";
34
+ import ControlledColumn from "./table/ControlledColumn";
35
+ import ControlledTable from "./table/ControlledTable";
36
+ import AddListEntryForm from "./AddListEntryForm";
37
+ import { ScmFormListContextProvider } from "./ScmFormListContext";
38
+ import { HalRepresentation } from "@scm-manager/ui-types";
39
+ import ControlledChipInputField from "./chip-input/ControlledChipInputField";
40
+ import Combobox from "./combobox/Combobox";
41
+ import ControlledComboboxField from "./combobox/ControlledComboboxField";
42
+ import { defaultOptionFactory } from "./helpers";
43
+ import ChipInput from "./headless-chip-input/ChipInput";
44
+
45
+ export type SimpleWebHookConfiguration = {
46
+ urlPattern: string;
47
+ executeOnEveryCommit: boolean;
48
+ sendCommitData: boolean;
49
+ method: string;
50
+ headers: WebhookHeader[];
51
+ };
52
+
53
+ export type WebhookHeader = {
54
+ key: string;
55
+ value: string;
56
+ concealed: boolean;
57
+ };
58
+
59
+ storiesOf("Forms", module)
60
+ .add("Creation", () => (
61
+ <Form
62
+ onSubmit={console.log}
63
+ translationPath={["sample", "form"]}
64
+ defaultValues={{
65
+ name: "",
66
+ password: "",
67
+ active: true,
68
+ }}
69
+ >
70
+ <FormRow>
71
+ <ControlledInputField rules={{ required: true }} name="name" />
72
+ </FormRow>
73
+ <FormRow>
74
+ <ControlledSecretConfirmationField name="password" />
75
+ </FormRow>
76
+ <FormRow>
77
+ <ControlledCheckboxField name="active" />
78
+ </FormRow>
79
+ </Form>
80
+ ))
81
+ .add("Editing", () => (
82
+ <Form
83
+ onSubmit={console.log}
84
+ translationPath={["sample", "form"]}
85
+ defaultValues={{
86
+ name: "trillian",
87
+ password: "secret",
88
+ passwordConfirmation: "",
89
+ active: true,
90
+ }}
91
+ >
92
+ <FormRow>
93
+ <ControlledInputField name="name" />
94
+ </FormRow>
95
+ <FormRow>
96
+ <ControlledSecretConfirmationField name="password" />
97
+ </FormRow>
98
+ <FormRow>
99
+ <ControlledCheckboxField name="active" />
100
+ </FormRow>
101
+ </Form>
102
+ ))
103
+ .add("Reset", () => {
104
+ type FormType = {
105
+ name: string;
106
+ password: string;
107
+ passwordConfirmation: string;
108
+ active: boolean;
109
+ date: string;
110
+ };
111
+ const [defaultValues, setValues] = useState({
112
+ name: "trillian",
113
+ password: "secret",
114
+ passwordConfirmation: "secret",
115
+ active: true,
116
+ date: "",
117
+ });
118
+ const resetValues = useRef({
119
+ name: "",
120
+ password: "",
121
+ passwordConfirmation: "",
122
+ active: false,
123
+ date: "",
124
+ });
125
+ return (
126
+ <Form<FormType>
127
+ onSubmit={(vals) => {
128
+ console.log(vals);
129
+ setValues(vals);
130
+ }}
131
+ translationPath={["sample", "form"]}
132
+ defaultValues={defaultValues as HalRepresentation & FormType}
133
+ withResetTo={resetValues.current}
134
+ withDiscardChanges
135
+ >
136
+ <FormRow>
137
+ <ControlledInputField name="name" />
138
+ </FormRow>
139
+ <FormRow>
140
+ <ControlledSecretConfirmationField name="password" rules={{ required: true }} />
141
+ </FormRow>
142
+ <FormRow>
143
+ <ControlledCheckboxField name="active" />
144
+ </FormRow>
145
+ <FormRow>
146
+ <ControlledInputField name="date" type="date" />
147
+ </FormRow>
148
+ </Form>
149
+ );
150
+ })
151
+ .add("Layout", () => (
152
+ <Form
153
+ onSubmit={console.log}
154
+ translationPath={["sample", "form"]}
155
+ defaultValues={{
156
+ name: "",
157
+ password: "",
158
+ method: "",
159
+ }}
160
+ >
161
+ <FormRow>
162
+ <ControlledInputField name="name" />
163
+ <ControlledSelectField name="method">
164
+ {["", "post", "get", "put"].map((value) => (
165
+ <option value={value} key={value}>
166
+ {value}
167
+ </option>
168
+ ))}
169
+ </ControlledSelectField>
170
+ <ControlledSecretConfirmationField name="password" />
171
+ </FormRow>
172
+ </Form>
173
+ ))
174
+ .add("GlobalConfiguration", () => (
175
+ <Form
176
+ onSubmit={console.log}
177
+ translationPath={["sample", "form"]}
178
+ defaultValues={{
179
+ url: "",
180
+ filter: "",
181
+ username: "",
182
+ password: "",
183
+ roleLevel: "",
184
+ updateIssues: false,
185
+ disableRepoConfig: false,
186
+ }}
187
+ >
188
+ {({ watch }) => (
189
+ <>
190
+ <FormRow>
191
+ <ControlledInputField name="url" label="URL" helpText="URL of Jira installation (with context path)." />
192
+ </FormRow>
193
+ <FormRow>
194
+ <ControlledInputField name="filter" label="Project Filter" helpText="Filters for jira project key." />
195
+ </FormRow>
196
+ <FormRow>
197
+ <ControlledCheckboxField
198
+ name="updateIssues"
199
+ label="Update Jira Issues"
200
+ helpText="Enable the automatic update function."
201
+ />
202
+ </FormRow>
203
+ <FormRow hidden={watch("filter")}>
204
+ <ControlledInputField
205
+ name="username"
206
+ label="Username"
207
+ helpText="Jira username for connection."
208
+ className="is-half"
209
+ />
210
+ <ControlledInputField
211
+ name="password"
212
+ label="Password"
213
+ helpText="Jira password for connection."
214
+ type="password"
215
+ className="is-half"
216
+ />
217
+ </FormRow>
218
+ <FormRow hidden={watch("filter")}>
219
+ <ControlledInputField
220
+ name="roleLevel"
221
+ label="Role Visibility"
222
+ helpText="Defines for which Project Role the comments are visible."
223
+ />
224
+ </FormRow>
225
+ <FormRow>
226
+ <ControlledCheckboxField
227
+ name="disableRepoConfig"
228
+ label="Do not allow repository configuration"
229
+ helpText="Do not allow repository owners to configure jira instances."
230
+ />
231
+ </FormRow>
232
+ </>
233
+ )}
234
+ </Form>
235
+ ))
236
+ .add("RepoConfiguration", () => (
237
+ <Form
238
+ onSubmit={console.log}
239
+ translationPath={["sample", "form"]}
240
+ defaultValues={{
241
+ url: "",
242
+ option: "",
243
+ anotherOption: "",
244
+ disableA: false,
245
+ disableB: false,
246
+ disableC: true,
247
+ labels: ["test"],
248
+ people: [{ displayName: "Trillian", id: 2 }],
249
+ author: null,
250
+ }}
251
+ >
252
+ <ControlledInputField name="url" />
253
+ <ControlledInputField name="option" />
254
+ <ControlledInputField name="anotherOption" />
255
+ <ControlledCheckboxField name="disableA" />
256
+ <ControlledCheckboxField name="disableB" />
257
+ <ControlledCheckboxField name="disableC" />
258
+ <ControlledChipInputField name="labels" />
259
+ <ControlledChipInputField
260
+ name="people"
261
+ optionFactory={(person) => ({ label: person.displayName, value: person })}
262
+ >
263
+ <Combobox
264
+ options={[
265
+ { label: "Zenod", value: { id: 1, displayName: "Zenod" } },
266
+ { label: "Arthur", value: { id: 3, displayName: "Arthur" } },
267
+ { label: "Cookie Monster", value: { id: 4, displayName: "Cookie Monster" } },
268
+ ]}
269
+ />
270
+ </ControlledChipInputField>
271
+ <ControlledComboboxField
272
+ options={["Zenod", "Arthur", "Trillian"].map(defaultOptionFactory)}
273
+ name="author"
274
+ nullable
275
+ />
276
+ </Form>
277
+ ))
278
+ .add("ReadOnly", () => (
279
+ <Form
280
+ onSubmit={console.log}
281
+ translationPath={["sample", "form"]}
282
+ defaultValues={{
283
+ name: "trillian",
284
+ password: "secret",
285
+ active: true,
286
+ labels: ["test", "hero"],
287
+ }}
288
+ readOnly
289
+ >
290
+ <FormRow>
291
+ <ControlledInputField name="name" />
292
+ </FormRow>
293
+ <FormRow>
294
+ <ControlledSecretConfirmationField name="password" />
295
+ </FormRow>
296
+ <FormRow>
297
+ <ControlledCheckboxField name="active" />
298
+ </FormRow>
299
+ <FormRow>
300
+ <ControlledChipInputField name="labels" aria-label="Test" placeholder="New label..." />
301
+ </FormRow>
302
+ </Form>
303
+ ))
304
+ .add("Nested", () => (
305
+ <Form
306
+ onSubmit={console.log}
307
+ translationPath={["sample", "form"]}
308
+ defaultValues={{
309
+ webhooks: [
310
+ {
311
+ urlPattern: "https://hitchhiker.com",
312
+ executeOnEveryCommit: false,
313
+ sendCommitData: false,
314
+ method: "post",
315
+ headers: [
316
+ {
317
+ key: "test",
318
+ value: "val",
319
+ concealed: false,
320
+ },
321
+ {
322
+ key: "secret",
323
+ value: "password",
324
+ concealed: true,
325
+ },
326
+ ],
327
+ },
328
+ {
329
+ urlPattern: "http://test.com",
330
+ executeOnEveryCommit: false,
331
+ sendCommitData: false,
332
+ method: "get",
333
+ headers: [
334
+ {
335
+ key: "other",
336
+ value: "thing",
337
+ concealed: true,
338
+ },
339
+ {
340
+ key: "stuff",
341
+ value: "haha",
342
+ concealed: false,
343
+ },
344
+ ],
345
+ },
346
+ ],
347
+ }}
348
+ withResetTo={{
349
+ webhooks: [
350
+ {
351
+ urlPattern: "https://other.com",
352
+ executeOnEveryCommit: true,
353
+ sendCommitData: true,
354
+ method: "get",
355
+ headers: [
356
+ {
357
+ key: "change",
358
+ value: "new",
359
+ concealed: true,
360
+ },
361
+ ],
362
+ },
363
+ {
364
+ urlPattern: "http://things.com",
365
+ executeOnEveryCommit: false,
366
+ sendCommitData: true,
367
+ method: "put",
368
+ headers: [
369
+ {
370
+ key: "stuff",
371
+ value: "haha",
372
+ concealed: false,
373
+ },
374
+ ],
375
+ },
376
+ ],
377
+ }}
378
+ >
379
+ <ScmFormListContextProvider name="webhooks">
380
+ <ControlledList withDelete>
381
+ {({ value: webhook }) => (
382
+ <>
383
+ <FormRow>
384
+ <ControlledSelectField name="method">
385
+ {["post", "get", "put"].map((value) => (
386
+ <option value={value} key={value}>
387
+ {value}
388
+ </option>
389
+ ))}
390
+ </ControlledSelectField>
391
+ <ControlledInputField name="urlPattern" />
392
+ </FormRow>
393
+ <FormRow>
394
+ <ControlledCheckboxField name="executeOnEveryCommit" />
395
+ </FormRow>
396
+ <FormRow>
397
+ <ControlledCheckboxField name="sendCommitData" />
398
+ </FormRow>
399
+ <details className="has-background-dark-25 mb-2 p-2">
400
+ <summary className="is-clickable">Headers</summary>
401
+ <div>
402
+ <ScmFormListContextProvider name="headers">
403
+ <ControlledTable withDelete>
404
+ <ControlledColumn name="key" />
405
+ <ControlledColumn name="value" />
406
+ <ControlledColumn name="concealed">{(value) => (value ? <b>Hallo</b> : null)}</ControlledColumn>
407
+ </ControlledTable>
408
+ <AddListEntryForm defaultValues={{ key: "", value: "", concealed: false }}>
409
+ <FormRow>
410
+ <ControlledInputField
411
+ name="key"
412
+ rules={{
413
+ validate: (newKey) =>
414
+ !(webhook as SimpleWebHookConfiguration).headers.some(({ key }) => newKey === key),
415
+ required: true,
416
+ }}
417
+ />
418
+ </FormRow>
419
+ <FormRow>
420
+ <ControlledInputField name="value" />
421
+ </FormRow>
422
+ <FormRow>
423
+ <ControlledCheckboxField name="concealed" />
424
+ </FormRow>
425
+ </AddListEntryForm>
426
+ </ScmFormListContextProvider>
427
+ </div>
428
+ </details>
429
+ </>
430
+ )}
431
+ </ControlledList>
432
+ </ScmFormListContextProvider>
433
+ </Form>
434
+ ))
435
+ .add("Controlled Chip Input with add", () => {
436
+ const ref = useRef<HTMLInputElement>(null);
437
+ return (
438
+ <Form
439
+ onSubmit={console.log}
440
+ translationPath={["sample", "form"]}
441
+ defaultValues={{
442
+ branches: ["main", "develop"],
443
+ }}
444
+ >
445
+ <FormRow>
446
+ <ControlledChipInputField name="branches" ref={ref} />
447
+ </FormRow>
448
+ <FormRow>
449
+ <ChipInput.AddButton inputRef={ref}>Add</ChipInput.AddButton>
450
+ </FormRow>
451
+ </Form>
452
+ );
453
+ });
@@ -0,0 +1,215 @@
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, { FC, useCallback, useEffect, useState } from "react";
26
+ import { DeepPartial, SubmitHandler, useForm, UseFormReturn } from "react-hook-form";
27
+ import { ErrorNotification } from "../notifications";
28
+ import { Level } from "../misc";
29
+ import { ScmFormContextProvider } from "./ScmFormContext";
30
+ import { useTranslation } from "react-i18next";
31
+ import { Button } from "../buttons";
32
+ import styled from "styled-components";
33
+ import { setValues } from "./helpers";
34
+
35
+ type RenderProps<T extends Record<string, unknown>> = Omit<
36
+ UseFormReturn<T>,
37
+ "register" | "unregister" | "handleSubmit" | "control"
38
+ >;
39
+
40
+ const ButtonsContainer = styled.div`
41
+ display: flex;
42
+ gap: 0.75rem;
43
+ `;
44
+
45
+ const SuccessNotification: FC<{ label?: string; hide: () => void }> = ({ label, hide }) => {
46
+ if (!label) {
47
+ return null;
48
+ }
49
+
50
+ return (
51
+ <div className="notification is-success">
52
+ <button className="delete" onClick={hide} />
53
+ {label}
54
+ </div>
55
+ );
56
+ };
57
+
58
+ type Props<FormType extends Record<string, unknown>, DefaultValues extends FormType> = {
59
+ children: ((renderProps: RenderProps<FormType>) => React.ReactNode | React.ReactNode[]) | React.ReactNode;
60
+ translationPath: [namespace: string, prefix: string];
61
+ onSubmit: SubmitHandler<FormType>;
62
+ defaultValues: DefaultValues;
63
+ readOnly?: boolean;
64
+ submitButtonTestId?: string;
65
+ /**
66
+ * Renders a button which resets the form to its default.
67
+ * This reflects the default browser behavior for a form *reset*.
68
+ *
69
+ * @since 2.43.0
70
+ */
71
+ withDiscardChanges?: boolean;
72
+ /**
73
+ * Renders a button which acts as if a user manually updated all fields to supplied values.
74
+ * The default use-case for this is to clear forms and this is also how the button is labelled.
75
+ * You can also use it to reset the form to an original state, but it is then advised to change the button label
76
+ * to *Reset to Defaults* by defining the *reset* translation in the form's translation object's root.
77
+ *
78
+ * > *Important Note:* This mechanism cannot be used to change the number of items in lists,
79
+ * > neither on the root level nor nested.
80
+ * > It is therefore advised not to use this property when lists or nested forms are involved.
81
+ *
82
+ * @since 2.43.0
83
+ */
84
+ withResetTo?: DefaultValues;
85
+ /**
86
+ * Message to display after a successful submit if no translation key is defined.
87
+ *
88
+ * If this is not supplied and the root level `submit-success-notification` translation key is not set,
89
+ * no message is displayed at all.
90
+ *
91
+ * @since 2.43.0
92
+ */
93
+ successMessageFallback?: string;
94
+ };
95
+
96
+ /**
97
+ * @beta
98
+ * @since 2.41.0
99
+ */
100
+ function Form<FormType extends Record<string, unknown>, DefaultValues extends FormType = FormType>({
101
+ children,
102
+ onSubmit,
103
+ defaultValues,
104
+ translationPath,
105
+ readOnly,
106
+ withResetTo,
107
+ withDiscardChanges,
108
+ successMessageFallback,
109
+ submitButtonTestId,
110
+ }: Props<FormType, DefaultValues>) {
111
+ const form = useForm<FormType>({
112
+ mode: "onChange",
113
+ defaultValues: defaultValues as DeepPartial<FormType>,
114
+ });
115
+ const { formState, handleSubmit, reset, setValue } = form;
116
+ const [ns, prefix] = translationPath;
117
+ const { t } = useTranslation(ns, { keyPrefix: prefix });
118
+ const [defaultTranslate] = useTranslation("commons", { keyPrefix: "form" });
119
+ const translateWithFallback = useCallback<typeof t>(
120
+ (key, ...args) => {
121
+ const translation = t(key, ...(args as any));
122
+ if (translation === `${prefix}.${key}`) {
123
+ return "";
124
+ }
125
+ return translation;
126
+ },
127
+ [prefix, t]
128
+ );
129
+ const { isDirty, isValid, isSubmitting, isSubmitSuccessful } = formState;
130
+ const [error, setError] = useState<Error | null | undefined>();
131
+ const [showSuccessNotification, setShowSuccessNotification] = useState(false);
132
+ const submitButtonLabel = t("submit", { defaultValue: defaultTranslate("submit") });
133
+ const resetButtonLabel = t("reset", { defaultValue: defaultTranslate("reset") });
134
+ const discardChangesButtonLabel = t("discardChanges", { defaultValue: defaultTranslate("discardChanges") });
135
+ const successNotification = translateWithFallback("submit-success-notification", {
136
+ defaultValue: successMessageFallback,
137
+ });
138
+ const overwriteValues = useCallback(() => {
139
+ if (withResetTo) {
140
+ setValues(withResetTo, setValue);
141
+ }
142
+ }, [setValue, withResetTo]);
143
+
144
+ // See https://react-hook-form.com/api/useform/reset/
145
+ useEffect(() => {
146
+ if (isSubmitSuccessful) {
147
+ setShowSuccessNotification(true);
148
+ }
149
+ }, [isSubmitSuccessful]);
150
+
151
+ useEffect(() => reset(defaultValues as never), [defaultValues, reset]);
152
+
153
+ useEffect(() => {
154
+ if (isDirty) {
155
+ setShowSuccessNotification(false);
156
+ }
157
+ }, [isDirty]);
158
+
159
+ const submit = useCallback(
160
+ async (data) => {
161
+ setError(null);
162
+ try {
163
+ return await onSubmit(data);
164
+ } catch (e) {
165
+ if (e instanceof Error) {
166
+ setError(e);
167
+ } else {
168
+ throw e;
169
+ }
170
+ }
171
+ },
172
+ [onSubmit]
173
+ );
174
+
175
+ return (
176
+ <ScmFormContextProvider {...form} readOnly={isSubmitting || readOnly} t={translateWithFallback} formId={prefix}>
177
+ <form onSubmit={handleSubmit(submit)} onReset={() => reset()} id={prefix} noValidate></form>
178
+ {showSuccessNotification ? (
179
+ <SuccessNotification label={successNotification} hide={() => setShowSuccessNotification(false)} />
180
+ ) : null}
181
+ {typeof children === "function" ? children(form) : children}
182
+ {error ? <ErrorNotification error={error} /> : null}
183
+ {!readOnly ? (
184
+ <Level
185
+ right={
186
+ <ButtonsContainer>
187
+ <Button
188
+ type="submit"
189
+ variant="primary"
190
+ testId={submitButtonTestId ?? "submit-button"}
191
+ disabled={!isDirty || !isValid}
192
+ isLoading={isSubmitting}
193
+ form={prefix}
194
+ >
195
+ {submitButtonLabel}
196
+ </Button>
197
+ {withDiscardChanges ? (
198
+ <Button type="reset" form={prefix} testId={`${prefix}-discard-changes-button`}>
199
+ {discardChangesButtonLabel}
200
+ </Button>
201
+ ) : null}
202
+ {withResetTo ? (
203
+ <Button form={prefix} onClick={overwriteValues} testId={`${prefix}-reset-button`}>
204
+ {resetButtonLabel}
205
+ </Button>
206
+ ) : null}
207
+ </ButtonsContainer>
208
+ }
209
+ />
210
+ ) : null}
211
+ </ScmFormContextProvider>
212
+ );
213
+ }
214
+
215
+ export default Form;