frontile 0.18.0-beta.4 → 0.18.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.
- package/declarations/components/collections/dropdown/menu-context.d.ts +10 -0
- package/declarations/components/collections/dropdown/menu-context.d.ts.map +1 -1
- package/declarations/components/collections/dropdown/sub.d.ts +34 -0
- package/declarations/components/collections/dropdown/sub.d.ts.map +1 -1
- package/declarations/components/collections/table/cell-default.d.ts.map +1 -1
- package/declarations/components/collections/table/index.d.ts.map +1 -1
- package/declarations/components/collections/table/table.d.ts.map +1 -1
- package/declarations/components/collections/table/types.d.ts.map +1 -1
- package/declarations/components/collections/table/utils.d.ts.map +1 -1
- package/declarations/components/forms/field.d.ts.map +1 -1
- package/declarations/components/forms/form.d.ts.map +1 -1
- package/declarations/components/forms/native-select.d.ts.map +1 -1
- package/declarations/components/forms/select/select.d.ts +4 -76
- package/declarations/components/forms/select/select.d.ts.map +1 -1
- package/declarations/components/forms/select/types.d.ts.map +1 -1
- package/declarations/components/navigation/breadcrumbs/breadcrumbs.d.ts +251 -0
- package/declarations/components/navigation/breadcrumbs/breadcrumbs.d.ts.map +1 -0
- package/declarations/components/navigation/breadcrumbs/collapse.d.ts +52 -0
- package/declarations/components/navigation/breadcrumbs/collapse.d.ts.map +1 -0
- package/declarations/components/navigation/breadcrumbs/ellipsis.d.ts +56 -0
- package/declarations/components/navigation/breadcrumbs/ellipsis.d.ts.map +1 -0
- package/declarations/components/navigation/breadcrumbs/item.d.ts +100 -0
- package/declarations/components/navigation/breadcrumbs/item.d.ts.map +1 -0
- package/declarations/components/navigation/breadcrumbs/separator.d.ts +27 -0
- package/declarations/components/navigation/breadcrumbs/separator.d.ts.map +1 -0
- package/declarations/components/navigation/breadcrumbs.d.ts +6 -0
- package/declarations/components/navigation/breadcrumbs.d.ts.map +1 -0
- package/declarations/components/navigation/index.d.ts +1 -0
- package/declarations/components/navigation/index.d.ts.map +1 -1
- package/declarations/components/overlays/overlay.d.ts.map +1 -1
- package/declarations/components/overlays/tooltip.d.ts +18 -19
- package/declarations/components/overlays/tooltip.d.ts.map +1 -1
- package/declarations/components/status/progress-bar.d.ts.map +1 -1
- package/declarations/components/utilities/collapsible.d.ts.map +1 -1
- package/declarations/utils/deferred-work.d.ts +4 -1
- package/declarations/utils/deferred-work.d.ts.map +1 -1
- package/dist/components/collections/dropdown/menu-context.js.map +1 -1
- package/dist/components/collections/dropdown/sub.js +78 -13
- package/dist/components/collections/dropdown/sub.js.map +1 -1
- package/dist/components/collections/simple-table/index.js.map +1 -1
- package/dist/components/collections/table/cell-default.js +0 -2
- package/dist/components/collections/table/cell-default.js.map +1 -1
- package/dist/components/collections/table/table.js +4 -46
- package/dist/components/collections/table/table.js.map +1 -1
- package/dist/components/collections/table/utils.js +0 -2
- package/dist/components/collections/table/utils.js.map +1 -1
- package/dist/components/forms/field.js +0 -1
- package/dist/components/forms/field.js.map +1 -1
- package/dist/components/forms/form.js +1 -39
- package/dist/components/forms/form.js.map +1 -1
- package/dist/components/forms/native-select.js +0 -3
- package/dist/components/forms/native-select.js.map +1 -1
- package/dist/components/forms/select/select.js +9 -116
- package/dist/components/forms/select/select.js.map +1 -1
- package/dist/components/navigation/breadcrumbs/breadcrumbs.js +208 -0
- package/dist/components/navigation/breadcrumbs/breadcrumbs.js.map +1 -0
- package/dist/components/navigation/breadcrumbs/collapse.js +49 -0
- package/dist/components/navigation/breadcrumbs/collapse.js.map +1 -0
- package/dist/components/navigation/breadcrumbs/ellipsis.js +40 -0
- package/dist/components/navigation/breadcrumbs/ellipsis.js.map +1 -0
- package/dist/components/navigation/breadcrumbs/item.js +102 -0
- package/dist/components/navigation/breadcrumbs/item.js.map +1 -0
- package/dist/components/navigation/breadcrumbs/separator.js +24 -0
- package/dist/components/navigation/breadcrumbs/separator.js.map +1 -0
- package/dist/components/navigation/breadcrumbs.js +4 -0
- package/dist/components/navigation/breadcrumbs.js.map +1 -0
- package/dist/components/navigation/index.js +3 -0
- package/dist/components/navigation/index.js.map +1 -1
- package/dist/components/overlays/overlay.js +0 -1
- package/dist/components/overlays/overlay.js.map +1 -1
- package/dist/components/overlays/tooltip.js +19 -21
- package/dist/components/overlays/tooltip.js.map +1 -1
- package/dist/components/status/progress-bar.js +0 -3
- package/dist/components/status/progress-bar.js.map +1 -1
- package/dist/components/utilities/collapsible.js +2 -4
- package/dist/components/utilities/collapsible.js.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/navigation.js +3 -0
- package/dist/navigation.js.map +1 -1
- package/dist/utils/deferred-work.js +27 -2
- package/dist/utils/deferred-work.js.map +1 -1
- package/package.json +3 -3
|
@@ -86,12 +86,8 @@ class Form extends Component {
|
|
|
86
86
|
*/
|
|
87
87
|
constructor(owner, args) {
|
|
88
88
|
super(owner, args);
|
|
89
|
-
// Create copy of initial data
|
|
90
89
|
if (args.data) {
|
|
91
|
-
// Always store flattened snapshot for dirty tracking
|
|
92
|
-
// This ensures consistent comparison regardless of initial structure
|
|
93
90
|
this.initialDataSnapshot = flattenData(args.data);
|
|
94
|
-
// Keep uncontrolled data in original structure
|
|
95
91
|
this.uncontrolledData = {
|
|
96
92
|
...args.data
|
|
97
93
|
};
|
|
@@ -132,15 +128,12 @@ class Form extends Component {
|
|
|
132
128
|
* @returns A promise that resolves to the validation errors, if any.
|
|
133
129
|
*/
|
|
134
130
|
async validate(data) {
|
|
135
|
-
// Run validator and get issues
|
|
136
131
|
const errors = await StandardValidator.validateAll(data, this.args.schema, this.args.validate);
|
|
137
|
-
// Convert validator errors to FormErrors
|
|
138
132
|
if (errors) {
|
|
139
133
|
const formErrors = validatorToFormErrors(errors);
|
|
140
134
|
this.errors = formErrors;
|
|
141
135
|
return formErrors;
|
|
142
136
|
}
|
|
143
|
-
// Clear errors if no issues
|
|
144
137
|
this.errors = {};
|
|
145
138
|
}
|
|
146
139
|
/**
|
|
@@ -157,13 +150,10 @@ class Form extends Component {
|
|
|
157
150
|
if (!this.args.schema && !this.args.validate) {
|
|
158
151
|
return;
|
|
159
152
|
}
|
|
160
|
-
// Run validator and get issues
|
|
161
153
|
const errors = await StandardValidator.validateFieldAll(data, name, this.args.schema, this.args.validate);
|
|
162
|
-
// Convert validator errors to FormErrors
|
|
163
154
|
if (errors) {
|
|
164
155
|
const formErrors = validatorToFormErrors(errors);
|
|
165
156
|
if (formErrors[name]) {
|
|
166
|
-
// Merge with existing errors immutably
|
|
167
157
|
this.errors = {
|
|
168
158
|
...this.errors,
|
|
169
159
|
[name]: formErrors[name]
|
|
@@ -173,15 +163,6 @@ class Form extends Component {
|
|
|
173
163
|
[name]: formErrors[name]
|
|
174
164
|
};
|
|
175
165
|
}
|
|
176
|
-
// Clear field error if no issues
|
|
177
|
-
// Remove field error using immutable pattern:
|
|
178
|
-
// 1. Use destructuring to extract the field we want to remove
|
|
179
|
-
// (assigned to '_' since unused)
|
|
180
|
-
// 2. Capture all remaining fields in 'rest' using the spread operator
|
|
181
|
-
// 3. Reassign this.errors to the 'rest' object, effectively removing
|
|
182
|
-
// the field
|
|
183
|
-
// This approach maintains immutability by creating a new object rather than
|
|
184
|
-
// mutating the existing errors object with 'delete'
|
|
185
166
|
if (this.errors[name]) {
|
|
186
167
|
const {
|
|
187
168
|
[name]: _,
|
|
@@ -206,15 +187,12 @@ class Form extends Component {
|
|
|
206
187
|
if (!this.initialDataSnapshot) {
|
|
207
188
|
return dirty;
|
|
208
189
|
}
|
|
209
|
-
// Flatten current data to same representation as snapshot
|
|
210
190
|
const currentFlat = flattenData(data);
|
|
211
|
-
// Compare all keys in current data
|
|
212
191
|
for (const key in currentFlat) {
|
|
213
192
|
if (!deepEqual(currentFlat[key], this.initialDataSnapshot[key])) {
|
|
214
193
|
dirty.add(key);
|
|
215
194
|
}
|
|
216
195
|
}
|
|
217
|
-
// Check for keys in initial data that are missing in current data
|
|
218
196
|
for (const key in this.initialDataSnapshot) {
|
|
219
197
|
if (!(key in currentFlat) && this.initialDataSnapshot[key] !== undefined) {
|
|
220
198
|
dirty.add(key);
|
|
@@ -236,7 +214,7 @@ class Form extends Component {
|
|
|
236
214
|
errors
|
|
237
215
|
} = this;
|
|
238
216
|
const dirty = this.computeDirtyFields(data);
|
|
239
|
-
this.dirty = dirty;
|
|
217
|
+
this.dirty = dirty;
|
|
240
218
|
return {
|
|
241
219
|
data,
|
|
242
220
|
isValid,
|
|
@@ -254,8 +232,6 @@ class Form extends Component {
|
|
|
254
232
|
const form = event.currentTarget;
|
|
255
233
|
if (form instanceof HTMLFormElement) {
|
|
256
234
|
let data = dataFrom(event);
|
|
257
|
-
// Always unflatten form data to handle dotted field names
|
|
258
|
-
// This is safe for flat data too - keys without dots remain unchanged
|
|
259
235
|
data = unflattenData(data);
|
|
260
236
|
const resultData = this.buildFormResultData(data);
|
|
261
237
|
this.uncontrolledData = data;
|
|
@@ -277,8 +253,6 @@ class Form extends Component {
|
|
|
277
253
|
if (form instanceof HTMLFormElement) {
|
|
278
254
|
this.isLoading = true;
|
|
279
255
|
let data = dataFrom(event);
|
|
280
|
-
// Always unflatten form data to handle dotted field names
|
|
281
|
-
// This is safe for flat data too - keys without dots remain unchanged
|
|
282
256
|
data = unflattenData(data);
|
|
283
257
|
let errors;
|
|
284
258
|
if (this.validateOn.includes('submit')) {
|
|
@@ -288,14 +262,10 @@ class Form extends Component {
|
|
|
288
262
|
this.uncontrolledData = data;
|
|
289
263
|
try {
|
|
290
264
|
if (errors && this.args.onError) {
|
|
291
|
-
// Call onError handler when there are validation errors
|
|
292
265
|
await this.args.onError(errors, data, event);
|
|
293
266
|
} else if (!errors && this.args.onSubmit) {
|
|
294
|
-
// Run `onSubmit` if validation was skipped OR if validation passed
|
|
295
267
|
await this.args.onSubmit(resultData, event);
|
|
296
|
-
// Update snapshot on successful submit (new baseline)
|
|
297
268
|
this.initialDataSnapshot = flattenData(data);
|
|
298
|
-
// Clear dirty state since we've updated the baseline
|
|
299
269
|
this.dirty = new Set();
|
|
300
270
|
}
|
|
301
271
|
} finally {
|
|
@@ -313,23 +283,17 @@ class Form extends Component {
|
|
|
313
283
|
decorateMethodV2(this.prototype, "handleSubmit", [action]);
|
|
314
284
|
}
|
|
315
285
|
handleReset(event) {
|
|
316
|
-
// Clear state
|
|
317
286
|
this.errors = {};
|
|
318
287
|
this.dirty = new Set();
|
|
319
|
-
// Restore initial data
|
|
320
288
|
if (this.initialDataSnapshot) {
|
|
321
|
-
// Unflatten data if it was nested
|
|
322
289
|
const restoredData = unflattenData(this.initialDataSnapshot);
|
|
323
|
-
// For controlled forms, call onChange to let parent update state
|
|
324
290
|
if (this.isControlled && this.args.onChange) {
|
|
325
291
|
const resultData = this.buildFormResultData(restoredData);
|
|
326
292
|
this.args.onChange(resultData, event);
|
|
327
293
|
} else {
|
|
328
|
-
// For uncontrolled forms, update internal state
|
|
329
294
|
this.uncontrolledData = restoredData;
|
|
330
295
|
}
|
|
331
296
|
} else {
|
|
332
|
-
// No initial data, just clear uncontrolled data
|
|
333
297
|
this.uncontrolledData = undefined;
|
|
334
298
|
}
|
|
335
299
|
}
|
|
@@ -359,7 +323,6 @@ class Form extends Component {
|
|
|
359
323
|
}
|
|
360
324
|
}
|
|
361
325
|
/**
|
|
362
|
-
* Helper function.
|
|
363
326
|
* Converts validation type `Issues` from StandardValidator into a format
|
|
364
327
|
* suitable for the form component, type `FormErrors`.
|
|
365
328
|
*
|
|
@@ -380,7 +343,6 @@ function validatorToFormErrors(errors) {
|
|
|
380
343
|
// by construction the dotted names field lookup resolves against.
|
|
381
344
|
const fieldName = issuePathToFieldName(issue);
|
|
382
345
|
const message = issue.message;
|
|
383
|
-
// Add message to the field's errors
|
|
384
346
|
const existing = formErrors[fieldName];
|
|
385
347
|
if (existing === undefined) {
|
|
386
348
|
formErrors[fieldName] = message;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form.js","sources":["../../../src/components/forms/form.gts"],"sourcesContent":["import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { action } from '@ember/object';\nimport { hash } from '@ember/helper';\nimport { on } from '@ember/modifier';\nimport { ref } from '../../utils/ref';\nimport { dataFrom } from 'form-data-utils';\nimport {\n StandardValidator,\n issuePathToFieldName\n} from '../../utils/standard-validator';\nimport { flattenData, unflattenData, deepEqual } from '../../utils/nested-data';\nimport { Field } from './field';\n\nimport type { WithBoundArgs } from '@glint/template';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Issues, CustomValidatorFn } from '../../utils/standard-validator';\nimport type Owner from '@ember/owner';\n\n/** The form data as key/value pairs. */\ntype FormDataCompiled = ReturnType<typeof dataFrom>;\n/** The validation errors for the form, keyed by field name. */\ntype FormErrors = Record<string, string | string[] | undefined>;\n\n/**\n * The data passed to `onChange` and `onSubmit` callbacks, which is similar\n * to `FormContext` but also includes the form data.\n */\ntype FormResultData<T = FormDataCompiled> = {\n /** The form data as key/value pairs. */\n data: T;\n /** Whether the form is valid (i.e. has no validation errors). */\n isValid: boolean;\n /** Whether the form is invalid (i.e. has validation errors). */\n isInvalid: boolean;\n /** The current form validation errors. */\n errors: FormErrors;\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n dirty: Set<string>;\n};\n\n/**\n * The context yielded to the default block of the `Form` component.\n */\ninterface FormContext<T = FormDataCompiled> {\n /** The form data as key/value pairs. */\n data?: T;\n /** Whether the form is currently submitting. */\n isLoading: boolean;\n /** Whether the form is valid (i.e. has no validation errors). */\n isValid: boolean;\n /** Whether the form is invalid (i.e. has validation errors). */\n isInvalid: boolean;\n /** The current form validation errors. */\n errors: FormErrors;\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n dirty: Set<string>;\n /**\n * Resets the form to its initial state.\n * Clears all form fields, validation errors, and dirty tracking.\n */\n reset: () => void;\n /** The `Field` component, with args bound. */\n Field: WithBoundArgs<\n typeof Field,\n 'errors' | 'formData' | 'disabled' | 'validateOn' | 'validateField'\n >;\n}\n\ninterface FormSignature<T = FormDataCompiled> {\n Element: HTMLFormElement;\n Args: {\n /**\n * The standard schema to validate form data against.\n */\n schema?: StandardSchemaV1<T>;\n /**\n * Optional custom validation function. A custom validator should return\n * an array of Standard Schema issues, or `undefined` if there are none.\n * This function may be async or sync.\n */\n validate?: CustomValidatorFn<T>;\n /**\n * When to run validation.\n */\n validateOn?: ('change' | 'input' | 'blur' | 'submit')[];\n /**\n * The initial form data as key/value pairs.\n * This is primarily useful for setting default values in the form.\n * This object receives changes as the user interacts with the form.\n */\n data?: T;\n /**\n * Whether the entire form and all its fields should be disabled. This only\n * applies when using the yielded `Field` component.\n */\n disabled?: boolean;\n /**\n * Optional callback invoked on input changes within the form.\n * @param result - The current form result data.\n * @param event - The input event that triggered the change.\n * @returns A promise or void.\n */\n onChange?: (\n result: FormResultData<T>,\n event: Event\n ) => Promise<void> | void;\n /**\n * Callback invoked on form submission. If `onSubmit` returns a promise,\n * the form will be marked as `isLoading` until the promise resolves.\n * @param result - The current form result data.\n * @param event - The submit event that triggered the submission.\n * @returns A promise or void.\n */\n onSubmit: (\n result: FormResultData<T>,\n event: SubmitEvent\n ) => Promise<void> | void;\n /**\n * Optional callback invoked when validation errors occur on form submission.\n * @param errors - The validation errors found.\n * @param data - The form data that was validated.\n * @param event - The submit event that triggered the validation.\n * @returns A promise or void.\n */\n onError?: (\n errors: FormErrors,\n data: T,\n event: SubmitEvent\n ) => Promise<void> | void;\n };\n Blocks: {\n default: [FormContext<T>];\n };\n}\n\n/**\n * A form component that handles form submissions and input changes.\n *\n * @example\n * ```hbs\n * <Form\n * @data={{this.formData}}\n * @schema={{this.schema}}\n * @validate={{this.customValidator}}\n * @onSubmit={{this.onSubmit}}\n * @onChange={{this.onChange}}\n * as |form|\n * >\n * <form.Field name=\"firstName\" as |field|>\n * <field.Input />\n * </form.Field>\n * <form.Field name=\"lastName\" as |field|>\n * <field.Input />\n * </form.Field>\n * <Button type=\"submit\" @isLoading={{form.isLoading}}>\n * Submit\n * <:loading>Submitting...</:loading>\n * </Button>\n * </Form>\n * ```\n */\nclass Form<T = FormDataCompiled> extends Component<FormSignature<T>> {\n /** Whether the form is currently submitting. */\n @tracked isLoading = false;\n\n /** The current form validation errors. */\n @tracked errors: FormErrors = {};\n\n /** The current uncontrolled form data. */\n @tracked uncontrolledData?: T;\n\n /**\n * Flattened snapshot of initial data for dirty field comparison.\n * Stored in flattened form regardless of whether source data is nested or flat.\n */\n @tracked initialDataSnapshot?: Record<string, unknown>;\n\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n @tracked dirty: Set<string> = new Set();\n\n /** Reference to the form element. */\n element = ref<HTMLFormElement>();\n\n /**\n * Creates a new instance of the Form component.\n * Initializes internal state based on provided args.\n * @param owner - The owner of the component.\n * @param args - The arguments passed to the component.\n */\n constructor(owner: Owner, args: FormSignature<T>['Args']) {\n super(owner, args);\n // Create copy of initial data\n if (args.data) {\n // Always store flattened snapshot for dirty tracking\n // This ensures consistent comparison regardless of initial structure\n this.initialDataSnapshot = flattenData(\n args.data as Record<string, unknown>\n );\n\n // Keep uncontrolled data in original structure\n this.uncontrolledData = { ...args.data };\n }\n }\n\n /** Whether the form is valid (i.e. has no validation errors). */\n get isValid() {\n return Object.keys(this.errors).length === 0;\n }\n\n /** Whether the form is invalid (i.e. has validation errors). */\n get isInvalid() {\n return !this.isValid;\n }\n\n /** Whether the form is controlled (`onChange` is provided). */\n get isControlled(): boolean {\n return !!this.args.onChange;\n }\n\n /** The events on which validation should run. */\n get validateOn(): ('change' | 'input' | 'blur' | 'submit')[] {\n return this.args.validateOn ?? ['change', 'blur', 'submit'];\n }\n\n /** The events on which field-level validation should run. */\n get fieldValidateOn(): ('change' | 'input' | 'blur')[] {\n return this.validateOn.filter((e) => e !== 'submit');\n }\n\n /** The current form data, from args if controlled, or internal state if uncontrolled. */\n get currentData(): T | undefined {\n if (this.isControlled) {\n return this.args.data;\n }\n return this.uncontrolledData;\n }\n\n /**\n * Validates data against the provided schema using StandardValidator.\n * Updates the `errors` property with any validation errors found.\n *\n * @param data - The form data to validate.\n * @returns A promise that resolves to the validation errors, if any.\n */\n async validate(data: T): Promise<FormErrors | undefined> {\n // Run validator and get issues\n const errors = await StandardValidator.validateAll(\n data,\n this.args.schema,\n this.args.validate\n );\n // Convert validator errors to FormErrors\n if (errors) {\n const formErrors = validatorToFormErrors(errors);\n this.errors = formErrors;\n return formErrors;\n }\n // Clear errors if no issues\n this.errors = {};\n }\n\n /**\n * Validates a single field against the provided schema using\n * StandardValidator. Updates the `errors` property with any validation\n * errors found for the field. If the field had previous errors but\n * is now valid, those errors are cleared.\n *\n * @param data - The form data to validate against.\n * @param name - The name of the field to validate.\n * @returns A promise that resolves to errors for the field, if any.\n */\n @action\n async validateField(data: T, name: string): Promise<FormErrors | undefined> {\n if (!this.args.schema && !this.args.validate) {\n return;\n }\n // Run validator and get issues\n const errors = await StandardValidator.validateFieldAll(\n data,\n name,\n this.args.schema,\n this.args.validate\n );\n // Convert validator errors to FormErrors\n if (errors) {\n const formErrors = validatorToFormErrors(errors);\n if (formErrors[name]) {\n // Merge with existing errors immutably\n this.errors = { ...this.errors, [name]: formErrors[name] };\n }\n return { [name]: formErrors[name] };\n }\n // Clear field error if no issues\n // Remove field error using immutable pattern:\n // 1. Use destructuring to extract the field we want to remove\n // (assigned to '_' since unused)\n // 2. Capture all remaining fields in 'rest' using the spread operator\n // 3. Reassign this.errors to the 'rest' object, effectively removing\n // the field\n // This approach maintains immutability by creating a new object rather than\n // mutating the existing errors object with 'delete'\n if (this.errors[name]) {\n const { [name]: _, ...rest } = this.errors;\n this.errors = rest;\n }\n }\n\n /**\n * Computes which fields have changed from their initial values.\n * Uses deep comparison for consistency across flat and nested structures.\n * This is a pure function with no side effects.\n *\n * @param data - The current form data.\n * @returns A set of field names that have changed.\n */\n computeDirtyFields(data: T): Set<string> {\n const dirty = new Set<string>();\n\n if (!this.initialDataSnapshot) {\n return dirty;\n }\n\n // Flatten current data to same representation as snapshot\n const currentFlat = flattenData(data as Record<string, unknown>);\n\n // Compare all keys in current data\n for (const key in currentFlat) {\n if (!deepEqual(currentFlat[key], this.initialDataSnapshot[key])) {\n dirty.add(key);\n }\n }\n\n // Check for keys in initial data that are missing in current data\n for (const key in this.initialDataSnapshot) {\n if (\n !(key in currentFlat) &&\n this.initialDataSnapshot[key] !== undefined\n ) {\n dirty.add(key);\n }\n }\n\n return dirty;\n }\n\n /**\n * Builds the form result data object to pass to callbacks.\n * Also updates the dirty state as a side effect.\n *\n * @param data - The current form data.\n * @returns The form result data object.\n */\n buildFormResultData(data: T): FormResultData<T> {\n const { isValid, isInvalid, errors } = this;\n const dirty = this.computeDirtyFields(data);\n this.dirty = dirty; // Update tracked state\n return {\n data,\n isValid,\n isInvalid,\n errors,\n dirty\n };\n }\n\n /**\n * Handles the `input` event on the form element.\n * Calls the `onChange` callback with the current form data if provided.\n * Automatically unflattens dotted field names to nested structure.\n */\n @action\n handleInput(event: Event) {\n const form = event.currentTarget;\n if (form instanceof HTMLFormElement) {\n let data = dataFrom(event) as T;\n\n // Always unflatten form data to handle dotted field names\n // This is safe for flat data too - keys without dots remain unchanged\n data = unflattenData(data as Record<string, unknown>) as T;\n\n const resultData = this.buildFormResultData(data);\n this.uncontrolledData = data;\n this.args.onChange?.(resultData, event);\n }\n }\n\n /**\n * Handles the `submit` event on the form element.\n * Prevents the default form submission and calls the `onSubmit` callback\n * with the current form data. Manages the `isLoading` state during the\n * submission process. Automatically unflattens dotted field names to nested structure.\n */\n @action\n async handleSubmit(event: SubmitEvent) {\n event.preventDefault();\n const form = event.currentTarget;\n if (form instanceof HTMLFormElement) {\n this.isLoading = true;\n let data = dataFrom(event) as T;\n\n // Always unflatten form data to handle dotted field names\n // This is safe for flat data too - keys without dots remain unchanged\n data = unflattenData(data as Record<string, unknown>) as T;\n\n let errors: FormErrors | undefined;\n if (this.validateOn.includes('submit')) {\n errors = await this.validate(data);\n }\n\n const resultData = this.buildFormResultData(data);\n this.uncontrolledData = data;\n try {\n if (errors && this.args.onError) {\n // Call onError handler when there are validation errors\n await this.args.onError(errors, data, event);\n } else if (!errors && this.args.onSubmit) {\n // Run `onSubmit` if validation was skipped OR if validation passed\n await this.args.onSubmit(resultData, event);\n // Update snapshot on successful submit (new baseline)\n this.initialDataSnapshot = flattenData(\n data as Record<string, unknown>\n );\n // Clear dirty state since we've updated the baseline\n this.dirty = new Set();\n }\n } finally {\n this.isLoading = false;\n }\n }\n }\n\n /**\n * Handles the `reset` event on the form element.\n * Clears validation errors and dirty tracking.\n * Restores the form data to its initial state.\n * Calls `onChange` if the form is controlled to let parent update state.\n */\n @action\n handleReset(event: Event) {\n // Clear state\n this.errors = {};\n this.dirty = new Set();\n\n // Restore initial data\n if (this.initialDataSnapshot) {\n // Unflatten data if it was nested\n const restoredData = unflattenData(this.initialDataSnapshot) as T;\n\n // For controlled forms, call onChange to let parent update state\n if (this.isControlled && this.args.onChange) {\n const resultData = this.buildFormResultData(restoredData);\n\n this.args.onChange(resultData, event);\n } else {\n // For uncontrolled forms, update internal state\n this.uncontrolledData = restoredData;\n }\n } else {\n // No initial data, just clear uncontrolled data\n this.uncontrolledData = undefined;\n }\n }\n\n /**\n * Resets the form to its initial state.\n * This method calls the native form reset() to clear all form controls,\n * triggering a `reset` event that is handled in `handleReset`.\n */\n @action\n reset() {\n this.element?.current?.reset();\n }\n\n <template>\n {{! @glint-nocheck component generics (field) trigger: type instantiation is excessively deep and possibly infinite }}\n <form\n {{this.element.setup}}\n {{on \"input\" this.handleInput}}\n {{on \"submit\" this.handleSubmit}}\n {{on \"reset\" this.handleReset}}\n ...attributes\n >\n {{yield\n (hash\n data=this.currentData\n isLoading=this.isLoading\n isValid=this.isValid\n isInvalid=this.isInvalid\n errors=this.errors\n dirty=this.dirty\n reset=this.reset\n Field=(component\n Field\n errors=this.errors\n formData=this.currentData\n disabled=@disabled\n validateOn=this.fieldValidateOn\n validateField=this.validateField\n )\n )\n to=\"default\"\n }}\n </form>\n </template>\n}\n\n/**\n * Helper function.\n * Converts validation type `Issues` from StandardValidator into a format\n * suitable for the form component, type `FormErrors`.\n *\n * For example, an issue with path `['email']` will be converted\n * to a form error for the field `email`, `{\"email\": \"error message\" }`.\n * Numeric path segments are kept, so an issue with path\n * `['items', 0, 'name']` becomes `{\"items.0.name\": \"error message\"}`.\n *\n * @param errors - The validation issues to convert.\n * @returns A mapping of field names to their validation error messages.\n */\nfunction validatorToFormErrors(errors: Issues): FormErrors {\n const formErrors: FormErrors = {};\n\n for (const issue of errors) {\n if (!issue.path || issue.path.length === 0) continue;\n\n // `issuePathToFieldName` is shared with\n // `StandardValidator.filterFieldIssues`, so the keys written here are\n // by construction the dotted names field lookup resolves against.\n const fieldName = issuePathToFieldName(issue);\n const message = issue.message;\n\n // Add message to the field's errors\n const existing = formErrors[fieldName];\n if (existing === undefined) {\n formErrors[fieldName] = message;\n } else if (Array.isArray(existing)) {\n existing.push(message);\n } else {\n formErrors[fieldName] = [existing, message];\n }\n }\n\n return formErrors;\n}\n\nexport {\n Form,\n type FormContext,\n type FormSignature,\n type FormDataCompiled,\n type FormResultData,\n type FormErrors\n};\nexport default Form;\n"],"names":["Form","Component","g","prototype","tracked","i","Set","element","ref","constructor","owner","args","data","initialDataSnapshot","flattenData","uncontrolledData","isValid","Object","keys","errors","length","isInvalid","isControlled","onChange","validateOn","fieldValidateOn","filter","e","currentData","validate","StandardValidator","validateAll","schema","formErrors","validatorToFormErrors","validateField","name","validateFieldAll","_","rest","n","action","computeDirtyFields","dirty","currentFlat","key","deepEqual","add","undefined","buildFormResultData","handleInput","event","form","currentTarget","HTMLFormElement","dataFrom","unflattenData","resultData","handleSubmit","preventDefault","isLoading","includes","onError","onSubmit","handleReset","restoredData","reset","current","setComponentTemplate","precompileTemplate","strictMode","scope","on","hash","Field","issue","path","fieldName","issuePathToFieldName","message","existing","Array","isArray","push"],"mappings":";;;;;;;;;;;;;;AAgJA;;;;;;;;;;;;;;;;;;;;;;;;;AAyBC;AACD,MAAMA,IAAA,SAAmCC,UAAwB;AAAA,EAAA;IAAAC,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,WAAA,EAAA,CAE9DC,OAAA,CAAA,EAAA,YAAA;AAAA,MAAA,OAAoB,KAAA;AAAA,IAAA,CAAA,CAAA;AAAA;EAAA,UAAA,IAAAC,2BAAA,CAAA,IAAA,EAAA,WAAA,CAAA,EAAA,MAAA;AADrB;AAAA,EAAA;IAAAH,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,QAAA,EAAA,CAICC,OAAA,CAAA,EAAA,YAAA;AAAA,MAAA,OAA6B,EAAC;AAAA,IAAA,CAAA,CAAA;AAAA;EAAA,OAAA,IAAAC,2BAAA,CAAA,IAAA,EAAA,QAAA,CAAA,EAAA,MAAA;AAD/B;AAAA,EAAA;IAAAH,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,kBAAA,EAAA,CAICC,OAAA,CAAA,CAAA;AAAA;EAAA,iBAAA,IAAAC,2BAAA,CAAA,IAAA,EAAA,kBAAA,CAAA,EAAA,MAAA;AADD;AAAA,EAAA;IAAAH,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,qBAAA,EAAA,CAOCC,OAAA,CAAA,CAAA;AAAA;EAAA,oBAAA,IAAAC,2BAAA,CAAA,IAAA,EAAA,qBAAA,CAAA,EAAA,MAAA;AAJD;;;AAGC;AAHD,EAAA;IAAAH,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,OAAA,EAAA,CAWCC,OAAA,CAAA,EAAA,YAAA;MAAA,OAA6B,IAAIE,GAAA,EAAA;AAAA,IAAA,CAAA,CAAA;AAAA;EAAA,MAAA,IAAAD,2BAAA,CAAA,IAAA,EAAA,OAAA,CAAA,EA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,CAAA,MAAO,IAAIE,KAAA,CAAMC,OAAO,CAACF,QAAA,CAAA,EAAW;AAClCA,MAAAA,QAAA,CAASG,IAAI,CAACJ,OAAA,CAAA;AAChB,IAAA,CAAA,MAAO;MACL9C,UAAU,CAAC4C,UAAU,GAAG,CAACG,QAAA,EAAUD,OAAA,CAAQ;AAC7C,IAAA;AACF,EAAA;AAEA,EAAA,OAAO9C,UAAA;AACT;;"}
|
|
1
|
+
{"version":3,"file":"form.js","sources":["../../../src/components/forms/form.gts"],"sourcesContent":["import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { action } from '@ember/object';\nimport { hash } from '@ember/helper';\nimport { on } from '@ember/modifier';\nimport { ref } from '../../utils/ref';\nimport { dataFrom } from 'form-data-utils';\nimport {\n StandardValidator,\n issuePathToFieldName\n} from '../../utils/standard-validator';\nimport { flattenData, unflattenData, deepEqual } from '../../utils/nested-data';\nimport { Field } from './field';\n\nimport type { WithBoundArgs } from '@glint/template';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Issues, CustomValidatorFn } from '../../utils/standard-validator';\nimport type Owner from '@ember/owner';\n\n/** The form data as key/value pairs. */\ntype FormDataCompiled = ReturnType<typeof dataFrom>;\n/** The validation errors for the form, keyed by field name. */\ntype FormErrors = Record<string, string | string[] | undefined>;\n\n/**\n * The data passed to `onChange` and `onSubmit` callbacks, which is similar\n * to `FormContext` but also includes the form data.\n */\ntype FormResultData<T = FormDataCompiled> = {\n /** The form data as key/value pairs. */\n data: T;\n /** Whether the form is valid (i.e. has no validation errors). */\n isValid: boolean;\n /** Whether the form is invalid (i.e. has validation errors). */\n isInvalid: boolean;\n /** The current form validation errors. */\n errors: FormErrors;\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n dirty: Set<string>;\n};\n\n/**\n * The context yielded to the default block of the `Form` component.\n */\ninterface FormContext<T = FormDataCompiled> {\n /** The form data as key/value pairs. */\n data?: T;\n /** Whether the form is currently submitting. */\n isLoading: boolean;\n /** Whether the form is valid (i.e. has no validation errors). */\n isValid: boolean;\n /** Whether the form is invalid (i.e. has validation errors). */\n isInvalid: boolean;\n /** The current form validation errors. */\n errors: FormErrors;\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n dirty: Set<string>;\n /**\n * Resets the form to its initial state.\n * Clears all form fields, validation errors, and dirty tracking.\n */\n reset: () => void;\n /** The `Field` component, with args bound. */\n Field: WithBoundArgs<\n typeof Field,\n 'errors' | 'formData' | 'disabled' | 'validateOn' | 'validateField'\n >;\n}\n\ninterface FormSignature<T = FormDataCompiled> {\n Element: HTMLFormElement;\n Args: {\n /**\n * The standard schema to validate form data against.\n */\n schema?: StandardSchemaV1<T>;\n /**\n * Optional custom validation function. A custom validator should return\n * an array of Standard Schema issues, or `undefined` if there are none.\n * This function may be async or sync.\n */\n validate?: CustomValidatorFn<T>;\n /**\n * When to run validation.\n */\n validateOn?: ('change' | 'input' | 'blur' | 'submit')[];\n /**\n * The initial form data as key/value pairs.\n * This is primarily useful for setting default values in the form.\n * This object receives changes as the user interacts with the form.\n */\n data?: T;\n /**\n * Whether the entire form and all its fields should be disabled. This only\n * applies when using the yielded `Field` component.\n */\n disabled?: boolean;\n /**\n * Optional callback invoked on input changes within the form.\n * @param result - The current form result data.\n * @param event - The input event that triggered the change.\n * @returns A promise or void.\n */\n onChange?: (\n result: FormResultData<T>,\n event: Event\n ) => Promise<void> | void;\n /**\n * Callback invoked on form submission. If `onSubmit` returns a promise,\n * the form will be marked as `isLoading` until the promise resolves.\n * @param result - The current form result data.\n * @param event - The submit event that triggered the submission.\n * @returns A promise or void.\n */\n onSubmit: (\n result: FormResultData<T>,\n event: SubmitEvent\n ) => Promise<void> | void;\n /**\n * Optional callback invoked when validation errors occur on form submission.\n * @param errors - The validation errors found.\n * @param data - The form data that was validated.\n * @param event - The submit event that triggered the validation.\n * @returns A promise or void.\n */\n onError?: (\n errors: FormErrors,\n data: T,\n event: SubmitEvent\n ) => Promise<void> | void;\n };\n Blocks: {\n default: [FormContext<T>];\n };\n}\n\n/**\n * A form component that handles form submissions and input changes.\n *\n * @example\n * ```hbs\n * <Form\n * @data={{this.formData}}\n * @schema={{this.schema}}\n * @validate={{this.customValidator}}\n * @onSubmit={{this.onSubmit}}\n * @onChange={{this.onChange}}\n * as |form|\n * >\n * <form.Field name=\"firstName\" as |field|>\n * <field.Input />\n * </form.Field>\n * <form.Field name=\"lastName\" as |field|>\n * <field.Input />\n * </form.Field>\n * <Button type=\"submit\" @isLoading={{form.isLoading}}>\n * Submit\n * <:loading>Submitting...</:loading>\n * </Button>\n * </Form>\n * ```\n */\nclass Form<T = FormDataCompiled> extends Component<FormSignature<T>> {\n /** Whether the form is currently submitting. */\n @tracked isLoading = false;\n\n /** The current form validation errors. */\n @tracked errors: FormErrors = {};\n\n /** The current uncontrolled form data. */\n @tracked uncontrolledData?: T;\n\n /**\n * Flattened snapshot of initial data for dirty field comparison.\n * Stored in flattened form regardless of whether source data is nested or flat.\n */\n @tracked initialDataSnapshot?: Record<string, unknown>;\n\n /**\n * The set of fields that have changed from their initial values.\n * For flat data structures: contains top-level keys (e.g., \"firstName\", \"email\")\n * For nested data structures: contains dotted paths (e.g., \"user.name.first\", \"profile.email\")\n */\n @tracked dirty: Set<string> = new Set();\n\n /** Reference to the form element. */\n element = ref<HTMLFormElement>();\n\n /**\n * Creates a new instance of the Form component.\n * Initializes internal state based on provided args.\n * @param owner - The owner of the component.\n * @param args - The arguments passed to the component.\n */\n constructor(owner: Owner, args: FormSignature<T>['Args']) {\n super(owner, args);\n if (args.data) {\n this.initialDataSnapshot = flattenData(\n args.data as Record<string, unknown>\n );\n\n this.uncontrolledData = { ...args.data };\n }\n }\n\n /** Whether the form is valid (i.e. has no validation errors). */\n get isValid() {\n return Object.keys(this.errors).length === 0;\n }\n\n /** Whether the form is invalid (i.e. has validation errors). */\n get isInvalid() {\n return !this.isValid;\n }\n\n /** Whether the form is controlled (`onChange` is provided). */\n get isControlled(): boolean {\n return !!this.args.onChange;\n }\n\n /** The events on which validation should run. */\n get validateOn(): ('change' | 'input' | 'blur' | 'submit')[] {\n return this.args.validateOn ?? ['change', 'blur', 'submit'];\n }\n\n /** The events on which field-level validation should run. */\n get fieldValidateOn(): ('change' | 'input' | 'blur')[] {\n return this.validateOn.filter((e) => e !== 'submit');\n }\n\n /** The current form data, from args if controlled, or internal state if uncontrolled. */\n get currentData(): T | undefined {\n if (this.isControlled) {\n return this.args.data;\n }\n return this.uncontrolledData;\n }\n\n /**\n * Validates data against the provided schema using StandardValidator.\n * Updates the `errors` property with any validation errors found.\n *\n * @param data - The form data to validate.\n * @returns A promise that resolves to the validation errors, if any.\n */\n async validate(data: T): Promise<FormErrors | undefined> {\n const errors = await StandardValidator.validateAll(\n data,\n this.args.schema,\n this.args.validate\n );\n if (errors) {\n const formErrors = validatorToFormErrors(errors);\n this.errors = formErrors;\n return formErrors;\n }\n this.errors = {};\n }\n\n /**\n * Validates a single field against the provided schema using\n * StandardValidator. Updates the `errors` property with any validation\n * errors found for the field. If the field had previous errors but\n * is now valid, those errors are cleared.\n *\n * @param data - The form data to validate against.\n * @param name - The name of the field to validate.\n * @returns A promise that resolves to errors for the field, if any.\n */\n @action\n async validateField(data: T, name: string): Promise<FormErrors | undefined> {\n if (!this.args.schema && !this.args.validate) {\n return;\n }\n const errors = await StandardValidator.validateFieldAll(\n data,\n name,\n this.args.schema,\n this.args.validate\n );\n if (errors) {\n const formErrors = validatorToFormErrors(errors);\n if (formErrors[name]) {\n this.errors = { ...this.errors, [name]: formErrors[name] };\n }\n return { [name]: formErrors[name] };\n }\n if (this.errors[name]) {\n const { [name]: _, ...rest } = this.errors;\n this.errors = rest;\n }\n }\n\n /**\n * Computes which fields have changed from their initial values.\n * Uses deep comparison for consistency across flat and nested structures.\n * This is a pure function with no side effects.\n *\n * @param data - The current form data.\n * @returns A set of field names that have changed.\n */\n computeDirtyFields(data: T): Set<string> {\n const dirty = new Set<string>();\n\n if (!this.initialDataSnapshot) {\n return dirty;\n }\n\n const currentFlat = flattenData(data as Record<string, unknown>);\n\n for (const key in currentFlat) {\n if (!deepEqual(currentFlat[key], this.initialDataSnapshot[key])) {\n dirty.add(key);\n }\n }\n\n for (const key in this.initialDataSnapshot) {\n if (\n !(key in currentFlat) &&\n this.initialDataSnapshot[key] !== undefined\n ) {\n dirty.add(key);\n }\n }\n\n return dirty;\n }\n\n /**\n * Builds the form result data object to pass to callbacks.\n * Also updates the dirty state as a side effect.\n *\n * @param data - The current form data.\n * @returns The form result data object.\n */\n buildFormResultData(data: T): FormResultData<T> {\n const { isValid, isInvalid, errors } = this;\n const dirty = this.computeDirtyFields(data);\n this.dirty = dirty;\n return {\n data,\n isValid,\n isInvalid,\n errors,\n dirty\n };\n }\n\n /**\n * Handles the `input` event on the form element.\n * Calls the `onChange` callback with the current form data if provided.\n * Automatically unflattens dotted field names to nested structure.\n */\n @action\n handleInput(event: Event) {\n const form = event.currentTarget;\n if (form instanceof HTMLFormElement) {\n let data = dataFrom(event) as T;\n data = unflattenData(data as Record<string, unknown>) as T;\n\n const resultData = this.buildFormResultData(data);\n this.uncontrolledData = data;\n this.args.onChange?.(resultData, event);\n }\n }\n\n /**\n * Handles the `submit` event on the form element.\n * Prevents the default form submission and calls the `onSubmit` callback\n * with the current form data. Manages the `isLoading` state during the\n * submission process. Automatically unflattens dotted field names to nested structure.\n */\n @action\n async handleSubmit(event: SubmitEvent) {\n event.preventDefault();\n const form = event.currentTarget;\n if (form instanceof HTMLFormElement) {\n this.isLoading = true;\n let data = dataFrom(event) as T;\n data = unflattenData(data as Record<string, unknown>) as T;\n\n let errors: FormErrors | undefined;\n if (this.validateOn.includes('submit')) {\n errors = await this.validate(data);\n }\n\n const resultData = this.buildFormResultData(data);\n this.uncontrolledData = data;\n try {\n if (errors && this.args.onError) {\n await this.args.onError(errors, data, event);\n } else if (!errors && this.args.onSubmit) {\n await this.args.onSubmit(resultData, event);\n this.initialDataSnapshot = flattenData(\n data as Record<string, unknown>\n );\n this.dirty = new Set();\n }\n } finally {\n this.isLoading = false;\n }\n }\n }\n\n /**\n * Handles the `reset` event on the form element.\n * Clears validation errors and dirty tracking.\n * Restores the form data to its initial state.\n * Calls `onChange` if the form is controlled to let parent update state.\n */\n @action\n handleReset(event: Event) {\n this.errors = {};\n this.dirty = new Set();\n\n if (this.initialDataSnapshot) {\n const restoredData = unflattenData(this.initialDataSnapshot) as T;\n\n if (this.isControlled && this.args.onChange) {\n const resultData = this.buildFormResultData(restoredData);\n\n this.args.onChange(resultData, event);\n } else {\n this.uncontrolledData = restoredData;\n }\n } else {\n this.uncontrolledData = undefined;\n }\n }\n\n /**\n * Resets the form to its initial state.\n * This method calls the native form reset() to clear all form controls,\n * triggering a `reset` event that is handled in `handleReset`.\n */\n @action\n reset() {\n this.element?.current?.reset();\n }\n\n <template>\n {{! @glint-nocheck component generics (field) trigger: type instantiation is excessively deep and possibly infinite }}\n <form\n {{this.element.setup}}\n {{on \"input\" this.handleInput}}\n {{on \"submit\" this.handleSubmit}}\n {{on \"reset\" this.handleReset}}\n ...attributes\n >\n {{yield\n (hash\n data=this.currentData\n isLoading=this.isLoading\n isValid=this.isValid\n isInvalid=this.isInvalid\n errors=this.errors\n dirty=this.dirty\n reset=this.reset\n Field=(component\n Field\n errors=this.errors\n formData=this.currentData\n disabled=@disabled\n validateOn=this.fieldValidateOn\n validateField=this.validateField\n )\n )\n to=\"default\"\n }}\n </form>\n </template>\n}\n\n/**\n * Converts validation type `Issues` from StandardValidator into a format\n * suitable for the form component, type `FormErrors`.\n *\n * For example, an issue with path `['email']` will be converted\n * to a form error for the field `email`, `{\"email\": \"error message\" }`.\n * Numeric path segments are kept, so an issue with path\n * `['items', 0, 'name']` becomes `{\"items.0.name\": \"error message\"}`.\n *\n * @param errors - The validation issues to convert.\n * @returns A mapping of field names to their validation error messages.\n */\nfunction validatorToFormErrors(errors: Issues): FormErrors {\n const formErrors: FormErrors = {};\n\n for (const issue of errors) {\n if (!issue.path || issue.path.length === 0) continue;\n\n // `issuePathToFieldName` is shared with\n // `StandardValidator.filterFieldIssues`, so the keys written here are\n // by construction the dotted names field lookup resolves against.\n const fieldName = issuePathToFieldName(issue);\n const message = issue.message;\n\n const existing = formErrors[fieldName];\n if (existing === undefined) {\n formErrors[fieldName] = message;\n } else if (Array.isArray(existing)) {\n existing.push(message);\n } else {\n formErrors[fieldName] = [existing, message];\n }\n }\n\n return formErrors;\n}\n\nexport {\n Form,\n type FormContext,\n type FormSignature,\n type FormDataCompiled,\n type FormResultData,\n type FormErrors\n};\nexport default Form;\n"],"names":["Form","Component","g","prototype","tracked","i","Set","element","ref","constructor","owner","args","data","initialDataSnapshot","flattenData","uncontrolledData","isValid","Object","keys","errors","length","isInvalid","isControlled","onChange","validateOn","fieldValidateOn","filter","e","currentData","validate","StandardValidator","validateAll","schema","formErrors","validatorToFormErrors","validateField","name","validateFieldAll","_","rest","n","action","computeDirtyFields","dirty","currentFlat","key","deepEqual","add","undefined","buildFormResultData","handleInput","event","form","currentTarget","HTMLFormElement","dataFrom","unflattenData","resultData","handleSubmit","preventDefault","isLoading","includes","onError","onSubmit","handleReset","restoredData","reset","current","setComponentTemplate","precompileTemplate","strictMode","scope","on","hash","Field","issue","path","fieldName","issuePathToFieldName","message","existing","Array","isArray","push"],"mappings":";;;;;;;;;;;;;;AAgJA;;;;;;;;;;;;;;;;;;;;;;;;;AAyBC;AACD,MAAMA,IAAA,SAAmCC,UAAwB;AAAA,EAAA;IAAAC,eAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,WAAA,EAAA,CAE9DC,OAAA,CAAA,EAAA,YAAA;AAAA,MAAA,OAAoB,KAAA;AAAA,IAAA,CAAA,CAAA;AAAA;EAAA,UAAA,IAAAC,2BAAA,CAAA,IAA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A8BA;MAAAC,UAAA,EAAA,IAAA;AAAAC,MAAAA,KAAA,EAAAA,OAAA;QAAAC,EAAA;QAAAC,IAAA;AAAAC,QAAAA;AAAA,OAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AACZ;AAEA;;;;;;;;;;;AAWC;AACD,SAASxC,qBAAAA,CAAsBf,MAAc,EAAG;EAC9C,MAAMc,aAAyB,EAAC;AAEhC,EAAA,KAAK,MAAM0C,SAASxD,MAAA,EAAQ;AAC1B,IAAA,IAAI,CAACwD,MAAMC,IAAI,IAAID,MAAMC,IAAI,CAACxD,MAAM,KAAK,CAAA,EAAG;AAE5C;AACA;AACA;AACA,IAAA,MAAMyD,YAAYC,oBAAA,CAAqBH,KAAA,CAAA;AACvC,IAAA,MAAMI,OAAA,GAAUJ,MAAMI,OAAO;AAE7B,IAAA,MAAMC,QAAA,GAAW/C,UAAU,CAAC4C,SAAA,CAAU;IACtC,IAAIG,aAAahC,SAAA,EAAW;AAC1Bf,MAAAA,UAAU,CAAC4C,UAAU,GAAGE,OAAA;IAC1B,CAAA,MAAO,IAAIE,KAAA,CAAMC,OAAO,CAACF,QAAA,CAAA,EAAW;AAClCA,MAAAA,QAAA,CAASG,IAAI,CAACJ,OAAA,CAAA;AAChB,IAAA,CAAA,MAAO;MACL9C,UAAU,CAAC4C,UAAU,GAAG,CAACG,QAAA,EAAUD,OAAA,CAAQ;AAC7C,IAAA;AACF,EAAA;AAEA,EAAA,OAAO9C,UAAA;AACT;;"}
|
|
@@ -15,7 +15,6 @@ import { a as decorateMethodV2, d as decorateFieldV2, i as initializeDeferredDec
|
|
|
15
15
|
class NativeSelect extends Component {
|
|
16
16
|
constructor(owner, args) {
|
|
17
17
|
super(owner, args);
|
|
18
|
-
// Runtime warnings for incorrect API usage
|
|
19
18
|
this.validateArgs();
|
|
20
19
|
}
|
|
21
20
|
validateArgs() {
|
|
@@ -33,7 +32,6 @@ class NativeSelect extends Component {
|
|
|
33
32
|
if (this.args.selectionMode === 'multiple') {
|
|
34
33
|
return this.args.selectedKeys || [];
|
|
35
34
|
} else {
|
|
36
|
-
// Single mode: convert selectedKey to array for ListManager
|
|
37
35
|
const singleArgs = this.args;
|
|
38
36
|
return singleArgs.selectedKey ? [singleArgs.selectedKey] : [];
|
|
39
37
|
}
|
|
@@ -78,7 +76,6 @@ class NativeSelect extends Component {
|
|
|
78
76
|
if (option && option.selected && option.value !== '') {
|
|
79
77
|
newSelectedKeys.push(option.value);
|
|
80
78
|
}
|
|
81
|
-
// handle allowEmpty
|
|
82
79
|
if (this.args.selectionMode !== 'multiple' && this.args.allowEmpty === true && option && option.selected && option.value === '') {
|
|
83
80
|
newSelectedKeys = [];
|
|
84
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-select.js","sources":["../../../src/components/forms/native-select.gts"],"sourcesContent":["import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { hash } from '@ember/helper';\nimport { action } from '@ember/object';\nimport { on } from '@ember/modifier';\nimport { assert } from '@ember/debug';\nimport type Owner from '@ember/owner';\nimport {\n useStyles,\n type NativeSelectSlots,\n type NativeSelectVariants,\n type SlotsToClasses\n} from '@frontile/theme';\nimport { FormControl, type FormControlSharedArgs } from './form-control';\nimport {\n ListManager,\n keyAndLabelForItem,\n type ListItem\n} from '../../utils/listManager';\nimport { IconChevronUpDown } from '../../-private/icons';\nimport type { WithBoundArgs } from '@glint/template';\n\ntype ItemCompBounded = WithBoundArgs<typeof NativeSelectItem, 'manager'>;\ntype ItemCompBoundedWithItem = WithBoundArgs<\n typeof NativeSelectItem,\n 'manager' | 'item'\n>;\n\n// Base interface for shared properties\ninterface BaseArgs<T> extends FormControlSharedArgs {\n /**\n * Keys of the options that cannot be selected. Disabled options are still\n * rendered and announced, they just cannot be picked.\n */\n disabledKeys?: string[];\n\n /**\n * Renders an extra empty option, letting the user clear the selection.\n * Label it with the placeholder argument.\n *\n * @defaultValue false\n */\n allowEmpty?: boolean;\n\n /**\n * Collection used to render the options. Strings and numbers become both the\n * key and the label; objects use key or id for the key and label, value,\n * name or title for the label. Use the :item block when your data does not\n * follow those conventions.\n */\n items?: T[];\n\n /**\n * Id applied to the select element and referenced by its label. One is\n * generated when omitted.\n */\n id?: string;\n\n /**\n * Name of the select element, used when the surrounding form is submitted.\n */\n name?: string;\n\n /**\n * The size of the control.\n *\n * @defaultValue 'md'\n */\n size?: NativeSelectVariants['size'];\n\n /**\n * Per-slot class overrides: base, innerContainer, input, startContent,\n * endContent and icon.\n */\n classes?: SlotsToClasses<NativeSelectSlots>;\n\n /**\n * Placeholder text used when `allowEmpty` is set to `true`.\n */\n placeholder?: string;\n\n /**\n * Called with the key of an option whenever it is acted upon, including when\n * the same option is picked again. Use onSelectionChange to track state.\n */\n onAction?: (key: string) => void;\n\n /**\n * @internal\n */\n onItemsChange?: (items: ListItem[], action: 'add' | 'remove') => void;\n\n /**\n * Controls pointer-events property of startContent.\n * If you want to pass the click event to the input, set it to `none`.\n *\n * @defaultValue 'auto'\n */\n startContentPointerEvents?: 'none' | 'auto';\n\n /**\n * Controls pointer-events property of endContent.\n * Defauled to `none` to pass the click event to the input. If your content\n * needs to capture events, consider adding `pointer-events-auto` class to that\n * element only.\n *\n * @defaultValue 'none'\n */\n endContentPointerEvents?: 'none' | 'auto';\n}\n\n// Single selection mode interface\ninterface SingleNativeSelectArgs<T> extends BaseArgs<T> {\n /**\n * Whether one option or several can be selected. Multiple renders the native\n * multi-select list box and switches to selectedKeys.\n *\n * @defaultValue 'single'\n */\n selectionMode?: 'single' | undefined;\n\n /**\n * The selected key in single selection mode. The component is controlled:\n * update this from onSelectionChange.\n */\n selectedKey?: string | null;\n\n /**\n * Not available in single selection mode; use selectedKey.\n */\n selectedKeys?: never;\n\n /**\n * Called with the newly selected key, or null when the selection is cleared\n * through the allowEmpty option.\n */\n onSelectionChange?: (key: string | null) => void;\n}\n\n// Multiple selection mode interface\ninterface MultipleNativeSelectArgs<T> extends BaseArgs<T> {\n /**\n * Whether one option or several can be selected. Multiple renders the native\n * multi-select list box and switches to selectedKeys.\n *\n * @defaultValue 'single'\n */\n selectionMode: 'multiple';\n\n /**\n * Not available in multiple selection mode; use selectedKeys.\n */\n selectedKey?: never;\n\n /**\n * The selected keys in multiple selection mode. The component is controlled:\n * update this from onSelectionChange.\n */\n selectedKeys?: string[];\n\n /**\n * Called with every selected key each time the selection changes.\n */\n onSelectionChange?: (keys: string[]) => void;\n}\n\n// Union type for the component\ntype Args<T> = SingleNativeSelectArgs<T> | MultipleNativeSelectArgs<T>;\n\ninterface NativeSelectSignature<T> {\n Args: Args<T>;\n Element: HTMLSelectElement;\n Blocks: {\n item: [\n { item: T; key: string; label: string; Item: ItemCompBoundedWithItem }\n ];\n default: [{ Item: ItemCompBounded }];\n startContent: [];\n endContent: [];\n };\n}\n\nclass NativeSelect<T = unknown> extends Component<NativeSelectSignature<T>> {\n constructor(owner: Owner, args: Args<T>) {\n super(owner, args);\n // Runtime warnings for incorrect API usage\n this.validateArgs();\n }\n\n validateArgs() {\n if (this.args.selectionMode === 'multiple') {\n if (\n typeof (this.args as unknown as Record<string, unknown>)[\n 'selectedKey'\n ] !== 'undefined'\n ) {\n console.warn(\n 'WARNING: selectedKey is not supported in multiple selection mode. Use selectedKeys instead.'\n );\n }\n } else {\n if (\n typeof (this.args as unknown as Record<string, unknown>)[\n 'selectedKeys'\n ] !== 'undefined'\n ) {\n console.warn(\n 'WARNING: selectedKeys is deprecated for single selection mode. Use selectedKey instead.'\n );\n }\n }\n }\n\n get normalizedSelectedKeys(): string[] {\n if (this.args.selectionMode === 'multiple') {\n return this.args.selectedKeys || [];\n } else {\n // Single mode: convert selectedKey to array for ListManager\n const singleArgs = this.args as SingleNativeSelectArgs<T>;\n return singleArgs.selectedKey ? [singleArgs.selectedKey] : [];\n }\n }\n\n listManager = new ListManager({\n selectionMode: this.args.selectionMode,\n selectedKeys: this.normalizedSelectedKeys,\n disabledKeys: this.args.disabledKeys,\n allowEmpty: this.args.allowEmpty,\n onSelectionChange: (keys: string[]) => this.handleSelectionChange(keys),\n onAction: this.args.onAction,\n onListItemsChange: this.args.onItemsChange\n });\n\n handleSelectionChange(keys: string[]) {\n if (this.args.selectionMode === 'multiple') {\n if (typeof this.args.onSelectionChange === 'function') {\n (this.args.onSelectionChange as (keys: string[]) => void)(keys);\n }\n } else {\n const singleKey: string | null = keys.length > 0 ? keys[0] || null : null;\n if (typeof this.args.onSelectionChange === 'function') {\n (this.args.onSelectionChange as (key: string | null) => void)(\n singleKey\n );\n }\n }\n }\n\n get classes() {\n const { nativeSelect } = useStyles();\n return nativeSelect({\n size: this.args.size\n });\n }\n\n get isMultiple() {\n return this.args.selectionMode === 'multiple';\n }\n\n @action\n handleOnChange(event: Event) {\n const selectElement = event.target as HTMLSelectElement;\n let newSelectedKeys: string[] = [];\n\n for (let i = 0; i < selectElement.options.length; i++) {\n const option = selectElement.options[i];\n if (option && option.selected && option.value !== '') {\n newSelectedKeys.push(option.value);\n }\n\n // handle allowEmpty\n if (\n this.args.selectionMode !== 'multiple' &&\n this.args.allowEmpty === true &&\n option &&\n option.selected &&\n option.value === ''\n ) {\n newSelectedKeys = [];\n }\n }\n\n this.handleSelectionChange(newSelectedKeys);\n }\n\n <template>\n <FormControl\n @id={{@id}}\n @size={{@size}}\n @label={{@label}}\n @isRequired={{@isRequired}}\n @description={{@description}}\n @errors={{@errors}}\n @isInvalid={{@isInvalid}}\n @class={{this.classes.base class=@classes.base}}\n data-component=\"native-select\"\n data-part=\"base\"\n as |c|\n >\n <div\n class={{this.classes.innerContainer class=@classes.innerContainer}}\n data-part=\"inner-container\"\n >\n {{#if (has-block \"startContent\")}}\n <div\n data-part=\"start-content\"\n class={{this.classes.startContent\n class=@classes.startContent\n startContentPointerEvents=(if\n @startContentPointerEvents @startContentPointerEvents \"auto\"\n )\n }}\n >\n {{yield to=\"startContent\"}}\n </div>\n {{/if}}\n <select\n {{this.listManager.setup\n selectedKeys=this.normalizedSelectedKeys\n disabledKeys=@disabledKeys\n selectionMode=@selectionMode\n allowEmpty=@allowEmpty\n onListItemsChange=@onItemsChange\n isKeyboardEventsEnabled=false\n }}\n {{on \"change\" this.handleOnChange}}\n multiple={{this.isMultiple}}\n data-test-id=\"native-select\"\n data-part=\"input\"\n class={{this.classes.input\n class=@classes.input\n hasStartContent=(has-block \"startContent\")\n hasEndContent=true\n }}\n id={{c.id}}\n name={{@name}}\n aria-invalid={{if c.isInvalid \"true\"}}\n aria-describedby={{c.describedBy @description c.isInvalid}}\n ...attributes\n >\n {{#if this.args.allowEmpty}}\n <NativeSelectItem @manager={{this.listManager}} @key=\"\">\n {{this.args.placeholder}}\n </NativeSelectItem>\n {{/if}}\n {{#each @items as |item|}}\n {{#let (keyAndLabelForItem item) as |keyLabel|}}\n {{#if (has-block \"item\")}}\n {{yield\n (hash\n item=item\n key=keyLabel.key\n label=keyLabel.label\n Item=(component\n NativeSelectItem manager=this.listManager item=item\n )\n )\n to=\"item\"\n }}\n {{else}}\n <NativeSelectItem\n @manager={{this.listManager}}\n @key={{keyLabel.key}}\n @item={{item}}\n >\n {{keyLabel.label}}\n </NativeSelectItem>\n {{/if}}\n {{/let}}\n {{/each}}\n\n {{yield\n (hash Item=(component NativeSelectItem manager=this.listManager))\n to=\"default\"\n }}\n </select>\n <div\n data-part=\"end-content\"\n class={{this.classes.endContent\n class=@classes.endContent\n endContentPointerEvents=(if\n @endContentPointerEvents @endContentPointerEvents \"none\"\n )\n }}\n >\n {{yield to=\"endContent\"}}\n\n <IconChevronUpDown\n data-part=\"icon\"\n class={{this.classes.icon class=@classes.icon}}\n />\n </div>\n </div>\n </FormControl>\n </template>\n}\n\nexport interface SelectItemSignature {\n Args: {\n /**\n * The ListManager that tracks selection for the parent select. It is bound\n * for you on the yielded Item component.\n */\n manager: ListManager;\n\n /**\n * Value of the rendered option, and the key reported by onSelectionChange,\n * selectedKey or selectedKeys, and disabledKeys.\n */\n key: string;\n\n /**\n * Text representation of the option, used for matching. Defaults to the\n * option's rendered text content.\n */\n textValue?: string;\n\n /**\n * The entry of `@items` this option renders, remembered on the registered\n * list item so a selection can hand it back. Bound for you on the Item\n * yielded from the `:item` block; block-form options have no such entry.\n */\n item?: unknown;\n };\n Element: HTMLOptionElement;\n Blocks: {\n default: [];\n selectedIcon: [];\n start: [];\n end: [];\n };\n}\n\nclass NativeSelectItem extends Component<SelectItemSignature> {\n @tracked listItem?: ListItem;\n\n get manager(): ListManager {\n assert(\n `SelectItem does not have a listManager; Missing argument @manager`,\n this.args.manager\n );\n\n return this.args.manager;\n }\n\n get key(): string {\n if (this.args.key !== '') {\n assert(\n `Argument @key is undefined or null, @key must be provided in Select.Item component`,\n this.args.key\n );\n }\n\n return this.args.key;\n }\n\n @action\n onRegister(item: ListItem) {\n this.listItem = item;\n }\n\n <template>\n <option\n {{this.manager.setupItem\n key=this.key\n textValue=@textValue\n item=@item\n onRegister=this.onRegister\n }}\n data-selected=\"{{this.listItem.isSelected}}\"\n data-key={{this.key}}\n selected={{this.listItem.isSelected}}\n value={{this.key}}\n disabled={{this.listItem.isDisabled}}\n ...attributes\n >\n {{yield}}\n </option>\n </template>\n}\n\nexport { NativeSelect, type NativeSelectSignature, type ListItem };\nexport default NativeSelect;\n"],"names":["NativeSelect","Component","constructor","owner","args","validateArgs","selectionMode","console","warn","normalizedSelectedKeys","selectedKeys","singleArgs","selectedKey","listManager","ListManager","disabledKeys","allowEmpty","onSelectionChange","keys","handleSelectionChange","onAction","onListItemsChange","onItemsChange","singleKey","length","classes","nativeSelect","useStyles","size","isMultiple","handleOnChange","event","selectElement","target","newSelectedKeys","i","options","option","selected","value","push","n","prototype","action","setComponentTemplate","precompileTemplate","strictMode","scope","FormControl","on","NativeSelectItem","keyAndLabelForItem","hash","IconChevronUpDown","g","tracked","manager","assert","key","onRegister","item","listItem"],"mappings":";;;;;;;;;;;;;;AAsLA,MAAMA,YAAA,SAAkCC,UAAgC;AACtEC,EAAAA,WAAAA,CAAYC,KAAY,EAAEC,IAAa,EAAE;AACv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,CAACsD,GAAG,KAAK,EAAA,EAAI;MACxBD,MAAA,CACE,oFAAoF,EACpF,IAAI,CAACrD,IAAI,CAACsD,GAAG,CAAA;AAEjB,IAAA;AAEA,IAAA,OAAO,IAAI,CAACtD,IAAI,CAACsD,GAAG;AACtB,EAAA;EAGAC,UAAAA,CAAWC,IAAc,EAAE;IACzB,IAAI,CAACC,QAAQ,GAAGD,IAAA;AAClB,EAAA;AAAA,EAAA;IAAAnB,gBAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,YAAA,EAAA,CAHCC,MAAA,CAAA,CAAA;AAAA;AAKD,EAAA;IAAAC,oBAAA,CAAAC,kBAAA,CAAA,uTAAA,EAiBA;MAAAC,UAAA,EAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AACZ;;"}
|
|
1
|
+
{"version":3,"file":"native-select.js","sources":["../../../src/components/forms/native-select.gts"],"sourcesContent":["import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { hash } from '@ember/helper';\nimport { action } from '@ember/object';\nimport { on } from '@ember/modifier';\nimport { assert } from '@ember/debug';\nimport type Owner from '@ember/owner';\nimport {\n useStyles,\n type NativeSelectSlots,\n type NativeSelectVariants,\n type SlotsToClasses\n} from '@frontile/theme';\nimport { FormControl, type FormControlSharedArgs } from './form-control';\nimport {\n ListManager,\n keyAndLabelForItem,\n type ListItem\n} from '../../utils/listManager';\nimport { IconChevronUpDown } from '../../-private/icons';\nimport type { WithBoundArgs } from '@glint/template';\n\ntype ItemCompBounded = WithBoundArgs<typeof NativeSelectItem, 'manager'>;\ntype ItemCompBoundedWithItem = WithBoundArgs<\n typeof NativeSelectItem,\n 'manager' | 'item'\n>;\n\ninterface BaseArgs<T> extends FormControlSharedArgs {\n /**\n * Keys of the options that cannot be selected. Disabled options are still\n * rendered and announced, they just cannot be picked.\n */\n disabledKeys?: string[];\n\n /**\n * Renders an extra empty option, letting the user clear the selection.\n * Label it with the placeholder argument.\n *\n * @defaultValue false\n */\n allowEmpty?: boolean;\n\n /**\n * Collection used to render the options. Strings and numbers become both the\n * key and the label; objects use key or id for the key and label, value,\n * name or title for the label. Use the :item block when your data does not\n * follow those conventions.\n */\n items?: T[];\n\n /**\n * Id applied to the select element and referenced by its label. One is\n * generated when omitted.\n */\n id?: string;\n\n /**\n * Name of the select element, used when the surrounding form is submitted.\n */\n name?: string;\n\n /**\n * The size of the control.\n *\n * @defaultValue 'md'\n */\n size?: NativeSelectVariants['size'];\n\n /**\n * Per-slot class overrides: base, innerContainer, input, startContent,\n * endContent and icon.\n */\n classes?: SlotsToClasses<NativeSelectSlots>;\n\n /**\n * Placeholder text used when `allowEmpty` is set to `true`.\n */\n placeholder?: string;\n\n /**\n * Called with the key of an option whenever it is acted upon, including when\n * the same option is picked again. Use onSelectionChange to track state.\n */\n onAction?: (key: string) => void;\n\n /**\n * @internal\n */\n onItemsChange?: (items: ListItem[], action: 'add' | 'remove') => void;\n\n /**\n * Controls pointer-events property of startContent.\n * If you want to pass the click event to the input, set it to `none`.\n *\n * @defaultValue 'auto'\n */\n startContentPointerEvents?: 'none' | 'auto';\n\n /**\n * Controls pointer-events property of endContent.\n * Defauled to `none` to pass the click event to the input. If your content\n * needs to capture events, consider adding `pointer-events-auto` class to that\n * element only.\n *\n * @defaultValue 'none'\n */\n endContentPointerEvents?: 'none' | 'auto';\n}\n\ninterface SingleNativeSelectArgs<T> extends BaseArgs<T> {\n /**\n * Whether one option or several can be selected. Multiple renders the native\n * multi-select list box and switches to selectedKeys.\n *\n * @defaultValue 'single'\n */\n selectionMode?: 'single' | undefined;\n\n /**\n * The selected key in single selection mode. The component is controlled:\n * update this from onSelectionChange.\n */\n selectedKey?: string | null;\n\n /**\n * Not available in single selection mode; use selectedKey.\n */\n selectedKeys?: never;\n\n /**\n * Called with the newly selected key, or null when the selection is cleared\n * through the allowEmpty option.\n */\n onSelectionChange?: (key: string | null) => void;\n}\n\ninterface MultipleNativeSelectArgs<T> extends BaseArgs<T> {\n /**\n * Whether one option or several can be selected. Multiple renders the native\n * multi-select list box and switches to selectedKeys.\n *\n * @defaultValue 'single'\n */\n selectionMode: 'multiple';\n\n /**\n * Not available in multiple selection mode; use selectedKeys.\n */\n selectedKey?: never;\n\n /**\n * The selected keys in multiple selection mode. The component is controlled:\n * update this from onSelectionChange.\n */\n selectedKeys?: string[];\n\n /**\n * Called with every selected key each time the selection changes.\n */\n onSelectionChange?: (keys: string[]) => void;\n}\n\ntype Args<T> = SingleNativeSelectArgs<T> | MultipleNativeSelectArgs<T>;\n\ninterface NativeSelectSignature<T> {\n Args: Args<T>;\n Element: HTMLSelectElement;\n Blocks: {\n item: [\n { item: T; key: string; label: string; Item: ItemCompBoundedWithItem }\n ];\n default: [{ Item: ItemCompBounded }];\n startContent: [];\n endContent: [];\n };\n}\n\nclass NativeSelect<T = unknown> extends Component<NativeSelectSignature<T>> {\n constructor(owner: Owner, args: Args<T>) {\n super(owner, args);\n this.validateArgs();\n }\n\n validateArgs() {\n if (this.args.selectionMode === 'multiple') {\n if (\n typeof (this.args as unknown as Record<string, unknown>)[\n 'selectedKey'\n ] !== 'undefined'\n ) {\n console.warn(\n 'WARNING: selectedKey is not supported in multiple selection mode. Use selectedKeys instead.'\n );\n }\n } else {\n if (\n typeof (this.args as unknown as Record<string, unknown>)[\n 'selectedKeys'\n ] !== 'undefined'\n ) {\n console.warn(\n 'WARNING: selectedKeys is deprecated for single selection mode. Use selectedKey instead.'\n );\n }\n }\n }\n\n get normalizedSelectedKeys(): string[] {\n if (this.args.selectionMode === 'multiple') {\n return this.args.selectedKeys || [];\n } else {\n const singleArgs = this.args as SingleNativeSelectArgs<T>;\n return singleArgs.selectedKey ? [singleArgs.selectedKey] : [];\n }\n }\n\n listManager = new ListManager({\n selectionMode: this.args.selectionMode,\n selectedKeys: this.normalizedSelectedKeys,\n disabledKeys: this.args.disabledKeys,\n allowEmpty: this.args.allowEmpty,\n onSelectionChange: (keys: string[]) => this.handleSelectionChange(keys),\n onAction: this.args.onAction,\n onListItemsChange: this.args.onItemsChange\n });\n\n handleSelectionChange(keys: string[]) {\n if (this.args.selectionMode === 'multiple') {\n if (typeof this.args.onSelectionChange === 'function') {\n (this.args.onSelectionChange as (keys: string[]) => void)(keys);\n }\n } else {\n const singleKey: string | null = keys.length > 0 ? keys[0] || null : null;\n if (typeof this.args.onSelectionChange === 'function') {\n (this.args.onSelectionChange as (key: string | null) => void)(\n singleKey\n );\n }\n }\n }\n\n get classes() {\n const { nativeSelect } = useStyles();\n return nativeSelect({\n size: this.args.size\n });\n }\n\n get isMultiple() {\n return this.args.selectionMode === 'multiple';\n }\n\n @action\n handleOnChange(event: Event) {\n const selectElement = event.target as HTMLSelectElement;\n let newSelectedKeys: string[] = [];\n\n for (let i = 0; i < selectElement.options.length; i++) {\n const option = selectElement.options[i];\n if (option && option.selected && option.value !== '') {\n newSelectedKeys.push(option.value);\n }\n\n if (\n this.args.selectionMode !== 'multiple' &&\n this.args.allowEmpty === true &&\n option &&\n option.selected &&\n option.value === ''\n ) {\n newSelectedKeys = [];\n }\n }\n\n this.handleSelectionChange(newSelectedKeys);\n }\n\n <template>\n <FormControl\n @id={{@id}}\n @size={{@size}}\n @label={{@label}}\n @isRequired={{@isRequired}}\n @description={{@description}}\n @errors={{@errors}}\n @isInvalid={{@isInvalid}}\n @class={{this.classes.base class=@classes.base}}\n data-component=\"native-select\"\n data-part=\"base\"\n as |c|\n >\n <div\n class={{this.classes.innerContainer class=@classes.innerContainer}}\n data-part=\"inner-container\"\n >\n {{#if (has-block \"startContent\")}}\n <div\n data-part=\"start-content\"\n class={{this.classes.startContent\n class=@classes.startContent\n startContentPointerEvents=(if\n @startContentPointerEvents @startContentPointerEvents \"auto\"\n )\n }}\n >\n {{yield to=\"startContent\"}}\n </div>\n {{/if}}\n <select\n {{this.listManager.setup\n selectedKeys=this.normalizedSelectedKeys\n disabledKeys=@disabledKeys\n selectionMode=@selectionMode\n allowEmpty=@allowEmpty\n onListItemsChange=@onItemsChange\n isKeyboardEventsEnabled=false\n }}\n {{on \"change\" this.handleOnChange}}\n multiple={{this.isMultiple}}\n data-test-id=\"native-select\"\n data-part=\"input\"\n class={{this.classes.input\n class=@classes.input\n hasStartContent=(has-block \"startContent\")\n hasEndContent=true\n }}\n id={{c.id}}\n name={{@name}}\n aria-invalid={{if c.isInvalid \"true\"}}\n aria-describedby={{c.describedBy @description c.isInvalid}}\n ...attributes\n >\n {{#if this.args.allowEmpty}}\n <NativeSelectItem @manager={{this.listManager}} @key=\"\">\n {{this.args.placeholder}}\n </NativeSelectItem>\n {{/if}}\n {{#each @items as |item|}}\n {{#let (keyAndLabelForItem item) as |keyLabel|}}\n {{#if (has-block \"item\")}}\n {{yield\n (hash\n item=item\n key=keyLabel.key\n label=keyLabel.label\n Item=(component\n NativeSelectItem manager=this.listManager item=item\n )\n )\n to=\"item\"\n }}\n {{else}}\n <NativeSelectItem\n @manager={{this.listManager}}\n @key={{keyLabel.key}}\n @item={{item}}\n >\n {{keyLabel.label}}\n </NativeSelectItem>\n {{/if}}\n {{/let}}\n {{/each}}\n\n {{yield\n (hash Item=(component NativeSelectItem manager=this.listManager))\n to=\"default\"\n }}\n </select>\n <div\n data-part=\"end-content\"\n class={{this.classes.endContent\n class=@classes.endContent\n endContentPointerEvents=(if\n @endContentPointerEvents @endContentPointerEvents \"none\"\n )\n }}\n >\n {{yield to=\"endContent\"}}\n\n <IconChevronUpDown\n data-part=\"icon\"\n class={{this.classes.icon class=@classes.icon}}\n />\n </div>\n </div>\n </FormControl>\n </template>\n}\n\nexport interface SelectItemSignature {\n Args: {\n /**\n * The ListManager that tracks selection for the parent select. It is bound\n * for you on the yielded Item component.\n */\n manager: ListManager;\n\n /**\n * Value of the rendered option, and the key reported by onSelectionChange,\n * selectedKey or selectedKeys, and disabledKeys.\n */\n key: string;\n\n /**\n * Text representation of the option, used for matching. Defaults to the\n * option's rendered text content.\n */\n textValue?: string;\n\n /**\n * The entry of `@items` this option renders, remembered on the registered\n * list item so a selection can hand it back. Bound for you on the Item\n * yielded from the `:item` block; block-form options have no such entry.\n */\n item?: unknown;\n };\n Element: HTMLOptionElement;\n Blocks: {\n default: [];\n selectedIcon: [];\n start: [];\n end: [];\n };\n}\n\nclass NativeSelectItem extends Component<SelectItemSignature> {\n @tracked listItem?: ListItem;\n\n get manager(): ListManager {\n assert(\n `SelectItem does not have a listManager; Missing argument @manager`,\n this.args.manager\n );\n\n return this.args.manager;\n }\n\n get key(): string {\n if (this.args.key !== '') {\n assert(\n `Argument @key is undefined or null, @key must be provided in Select.Item component`,\n this.args.key\n );\n }\n\n return this.args.key;\n }\n\n @action\n onRegister(item: ListItem) {\n this.listItem = item;\n }\n\n <template>\n <option\n {{this.manager.setupItem\n key=this.key\n textValue=@textValue\n item=@item\n onRegister=this.onRegister\n }}\n data-selected=\"{{this.listItem.isSelected}}\"\n data-key={{this.key}}\n selected={{this.listItem.isSelected}}\n value={{this.key}}\n disabled={{this.listItem.isDisabled}}\n ...attributes\n >\n {{yield}}\n </option>\n </template>\n}\n\nexport { NativeSelect, type NativeSelectSignature, type ListItem };\nexport default NativeSelect;\n"],"names":["NativeSelect","Component","constructor","owner","args","validateArgs","selectionMode","console","warn","normalizedSelectedKeys","selectedKeys","singleArgs","selectedKey","listManager","ListManager","disabledKeys","allowEmpty","onSelectionChange","keys","handleSelectionChange","onAction","onListItemsChange","onItemsChange","singleKey","length","classes","nativeSelect","useStyles","size","isMultiple","handleOnChange","event","selectElement","target","newSelectedKeys","i","options","option","selected","value","push","n","prototype","action","setComponentTemplate","precompileTemplate","strictMode","scope","FormControl","on","NativeSelectItem","keyAndLabelForItem","hash","IconChevronUpDown","g","tracked","manager","assert","key","onRegister","item","listItem"],"mappings":";;;;;;;;;;;;;;AAkLA,MAAMA,YAAA,SAAkCC,UAAgC;AACtEC,EAAAA,WAAAA,CAAYC,KAAY,EAAEC,IAAa,EAAE;AACvC,IAAA,KAAK,CAACD,KAAA,EAAOC,IAAA,CAAA;IACb,IAAI,CAACC,YAAY,EAAA;AACnB,E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,CAAA;AAEjB,IAAA;AAEA,IAAA,OAAO,IAAI,CAACtD,IAAI,CAACsD,GAAG;AACtB,EAAA;EAGAC,UAAAA,CAAWC,IAAc,EAAE;IACzB,IAAI,CAACC,QAAQ,GAAGD,IAAA;AAClB,EAAA;AAAA,EAAA;IAAAnB,gBAAA,CAAA,IAAA,CAAAC,SAAA,EAAA,YAAA,EAAA,CAHCC,MAAA,CAAA,CAAA;AAAA;AAKD,EAAA;IAAAC,oBAAA,CAAAC,kBAAA,CAAA,uTAAA,EAiBA;MAAAC,UAAA,EAAA;KAAU,CAAA,EAAV,IAAW,CAAA;AAAD;AACZ;;"}
|
|
@@ -23,42 +23,11 @@ import { d as decorateFieldV2, i as initializeDeferredDecorator, a as decorateMe
|
|
|
23
23
|
|
|
24
24
|
const and = (a, b) => Boolean(a) && Boolean(b);
|
|
25
25
|
/*
|
|
26
|
-
* Internal
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* 1. **External → Internal (Initialization & Updates)**
|
|
32
|
-
* - Parent passes `@selectedKey` or `@selectedKeys` as arguments
|
|
33
|
-
* - Constructor initializes internal tracked properties (`_selectedKey` or `_selectedKeys`)
|
|
34
|
-
* - Modifiers (`updateSingleSelectValue`, `updateMultipleSelectValue`) sync internal state
|
|
35
|
-
* when parent updates the arguments
|
|
36
|
-
*
|
|
37
|
-
* 2. **Internal State Management**
|
|
38
|
-
* - `_selectedKey` / `_selectedKeys`: Internal tracked state (prefixed with underscore)
|
|
39
|
-
* - These serve as the "source of truth" for rendering and reactivity
|
|
40
|
-
* - Getters (`getSelectedKey`, `selectedKeys`) expose this internal state to the template
|
|
41
|
-
*
|
|
42
|
-
* 3. **Internal → External (User Interactions)**
|
|
43
|
-
* - User interactions trigger selection change handlers
|
|
44
|
-
* - Handlers update internal `_selectedKey` / `_selectedKeys` for immediate UI update
|
|
45
|
-
* - Handlers call parent's `@onSelectionChange` callback to notify of state change
|
|
46
|
-
* - Parent updates its state, which flows back through step 1
|
|
47
|
-
*
|
|
48
|
-
* ### Why Both Internal State AND Callbacks?
|
|
49
|
-
* - **Internal state:** Enables immediate, responsive UI updates (`_selectedKey` / `_selectedKeys`)
|
|
50
|
-
* - **Parent callback:** Enables parent to take action when changes occur (`@onSelectionChange`)
|
|
51
|
-
* - This pattern provides both responsive UX and parent inclusion over state
|
|
52
|
-
*
|
|
53
|
-
* ### Example Flow
|
|
54
|
-
* ```
|
|
55
|
-
* User clicks item
|
|
56
|
-
* → onSelectionChange handler
|
|
57
|
-
* → Updates _selectedKey (immediate UI update)
|
|
58
|
-
* → Calls parent's @onSelectionChange callback
|
|
59
|
-
* → Parent updates its @selectedKey state
|
|
60
|
-
* → updateSingleSelectValue modifier syncs _selectedKey with new arg value
|
|
61
|
-
* ```
|
|
26
|
+
* Internal `_selectedKey` / `_selectedKeys` are the source of truth for
|
|
27
|
+
* rendering. `@selectedKey(s)` seeds them in the constructor and the
|
|
28
|
+
* `updateSingle/MultipleSelectValue` modifiers keep them synced whenever the
|
|
29
|
+
* arg changes; user interactions update them directly for an immediate UI
|
|
30
|
+
* response, then call `@onSelectionChange` so the parent can update its copy.
|
|
62
31
|
*/ /**
|
|
63
32
|
* A dropdown selection component: a custom listbox in a popover, backed by a
|
|
64
33
|
* visually hidden native `<select>` so the value submits with a form.
|
|
@@ -107,25 +76,13 @@ class Select extends Component {
|
|
|
107
76
|
* Internal tracked state for multiple selection mode.
|
|
108
77
|
* Source of truth for rendering. Synced with @selectedKeys via the updateMultipleSelectValue modifier.
|
|
109
78
|
*/
|
|
110
|
-
/**
|
|
111
|
-
* Initializes the component and sets up initial selection state.
|
|
112
|
-
*
|
|
113
|
-
* **Initialization:**
|
|
114
|
-
* 1. Determines selection mode (single vs multiple)
|
|
115
|
-
* 2. Copies external arg values (@selectedKey or @selectedKeys) to internal tracked state
|
|
116
|
-
* 3. Logs warnings if incorrect args are used for the selection mode
|
|
117
|
-
*
|
|
118
|
-
* Note: After instantiation, modifiers keep internal state synced with external arguments.
|
|
119
|
-
*/
|
|
120
79
|
constructor(owner, args) {
|
|
121
80
|
super(owner, args);
|
|
122
|
-
// Initialize based on mode
|
|
123
81
|
if (this.args.selectionMode === 'multiple') {
|
|
124
82
|
this._selectedKeys = this.args.selectedKeys || [];
|
|
125
83
|
} else {
|
|
126
84
|
this._selectedKey = this.args.selectedKey || null;
|
|
127
85
|
}
|
|
128
|
-
// Runtime warnings for incorrect API usage
|
|
129
86
|
this.validateArgs();
|
|
130
87
|
}
|
|
131
88
|
validateArgs() {
|
|
@@ -146,20 +103,6 @@ class Select extends Component {
|
|
|
146
103
|
containerRef = ref();
|
|
147
104
|
triggerRef = ref();
|
|
148
105
|
chipsContainerRef = ref();
|
|
149
|
-
/**
|
|
150
|
-
* Handles selection changes from the Listbox component.
|
|
151
|
-
*
|
|
152
|
-
* **Flow:**
|
|
153
|
-
* 1. Updates internal state (`_selectedKey` or `_selectedKeys`) for immediate UI updates
|
|
154
|
-
* 2. Calls parent's `@onSelectionChange` callback to notify of the change
|
|
155
|
-
* 3. Parent updates its state, which flows back via modifier to complete the cycle
|
|
156
|
-
*
|
|
157
|
-
* **Side effects:**
|
|
158
|
-
* - Clears filter value (for searchable selects)
|
|
159
|
-
* - Triggers form input event for native form integration
|
|
160
|
-
*
|
|
161
|
-
* @param keys - Array of selected keys from Listbox (converted to single value in single mode)
|
|
162
|
-
*/
|
|
163
106
|
onSelectionChange = keys => {
|
|
164
107
|
if (this.args.selectionMode === 'multiple') {
|
|
165
108
|
this._selectedKeys = keys;
|
|
@@ -177,16 +120,7 @@ class Select extends Component {
|
|
|
177
120
|
triggerFormInputEvent(this.containerRef.current);
|
|
178
121
|
};
|
|
179
122
|
/**
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
* This is similar to `onSelectionChange` but accepts a single key directly
|
|
183
|
-
* rather than an array, matching the native select's single-value API.
|
|
184
|
-
*
|
|
185
|
-
* **Flow:**
|
|
186
|
-
* 1. Updates internal `_selectedKey` for immediate UI update
|
|
187
|
-
* 2. Calls parent's `@onSelectionChange` callback
|
|
188
|
-
*
|
|
189
|
-
* @param key - The selected key, or null if cleared
|
|
123
|
+
* Like `onSelectionChange`, but for the native `<select>`'s single-value API.
|
|
190
124
|
*/
|
|
191
125
|
onSingleSelectionChange = key => {
|
|
192
126
|
this._selectedKey = key;
|
|
@@ -248,39 +182,15 @@ class Select extends Component {
|
|
|
248
182
|
this.removeSelectedKey(last.key);
|
|
249
183
|
}
|
|
250
184
|
}
|
|
251
|
-
/**
|
|
252
|
-
* Returns current selection as an array for template rendering.
|
|
253
|
-
*
|
|
254
|
-
* Normalizes both single and multiple selection modes to a consistent array interface:
|
|
255
|
-
* - Multiple mode: Returns `_selectedKeys` directly
|
|
256
|
-
* - Single mode: Converts `_selectedKey` to array format (or empty array if null)
|
|
257
|
-
*
|
|
258
|
-
* Note: Always returns internal tracked state rather than arguments. External updates
|
|
259
|
-
* sync through modifiers to maintain consistency.
|
|
260
|
-
*
|
|
261
|
-
* @returns Array of selected keys (empty array if none selected)
|
|
262
|
-
*/
|
|
185
|
+
/** Current selection normalized to an array, for template rendering. */
|
|
263
186
|
get selectedKeys() {
|
|
264
187
|
if (this.args.selectionMode === 'multiple') {
|
|
265
188
|
return this._selectedKeys;
|
|
266
189
|
} else {
|
|
267
|
-
// Single mode: convert selectedKey to array for internal use
|
|
268
190
|
const key = this.getSelectedKey;
|
|
269
191
|
return key ? [key] : [];
|
|
270
192
|
}
|
|
271
193
|
}
|
|
272
|
-
/**
|
|
273
|
-
* Returns the selected key for single selection mode.
|
|
274
|
-
*
|
|
275
|
-
* **Returns:**
|
|
276
|
-
* - Single mode: Returns `_selectedKey` (string or null)
|
|
277
|
-
* - Multiple mode: Returns null (not applicable)
|
|
278
|
-
*
|
|
279
|
-
* Note: Always returns internal tracked state rather than arguments. External updates
|
|
280
|
-
* sync through modifiers to maintain consistency.
|
|
281
|
-
*
|
|
282
|
-
* @returns The selected key, or null if none selected or in multiple mode
|
|
283
|
-
*/
|
|
284
194
|
get getSelectedKey() {
|
|
285
195
|
return this._selectedKey;
|
|
286
196
|
}
|
|
@@ -629,32 +539,15 @@ class Select extends Component {
|
|
|
629
539
|
}
|
|
630
540
|
return 'first';
|
|
631
541
|
}
|
|
632
|
-
/**
|
|
633
|
-
* Syncs internal `_selectedKeys` with external `@selectedKeys` argument.
|
|
634
|
-
*
|
|
635
|
-
* Runs whenever `@selectedKeys` changes:
|
|
636
|
-
* - Updates `_selectedKeys` to match the new external value
|
|
637
|
-
* - Normalizes undefined/null to empty array
|
|
638
|
-
*
|
|
639
|
-
* This enables UI updates when the external value changes.
|
|
640
|
-
*/
|
|
542
|
+
/** Syncs internal `_selectedKeys` whenever `@selectedKeys` changes. */
|
|
641
543
|
updateMultipleSelectValue = modifier((_, [selectedKeys]) => {
|
|
642
544
|
if (selectedKeys !== undefined && selectedKeys !== null) {
|
|
643
545
|
this._selectedKeys = selectedKeys;
|
|
644
546
|
} else {
|
|
645
|
-
// NOTE: is this the right behavior?
|
|
646
547
|
this._selectedKeys = [];
|
|
647
548
|
}
|
|
648
549
|
});
|
|
649
|
-
/**
|
|
650
|
-
* Syncs internal `_selectedKey` with external `@selectedKey` argument.
|
|
651
|
-
*
|
|
652
|
-
* Runs whenever `@selectedKey` changes:
|
|
653
|
-
* - Updates `_selectedKey` to match the new external value
|
|
654
|
-
* - Handles null values for cleared selections
|
|
655
|
-
*
|
|
656
|
-
* This enables UI updates when the external value changes.
|
|
657
|
-
*/
|
|
550
|
+
/** Syncs internal `_selectedKey` whenever `@selectedKey` changes. */
|
|
658
551
|
updateSingleSelectValue = modifier((_, [selectedKey]) => {
|
|
659
552
|
if (selectedKey !== undefined) {
|
|
660
553
|
this._selectedKey = selectedKey;
|