@dile/crud 2.16.1 → 2.17.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.
@@ -72,6 +72,10 @@ export class DileCrudActions extends DileI18nMixin(LitElement) {
72
72
  loading: { type: Boolean },
73
73
  fullWidth: { type: Boolean, reflect: true, attribute: 'full-width' },
74
74
  maxItems: { type: Number },
75
+ /** Validation rules of the action forms, by action name: `{ ActionName: { field: rules } }` (needs the DileFormValidation mixin of @dile/validation in the form) */
76
+ validationSchemas: { type: Object },
77
+ /** Validation messages handed to the action forms together with validationSchemas */
78
+ validationMessages: { type: Object },
75
79
  };
76
80
  }
77
81
 
@@ -196,6 +200,7 @@ export class DileCrudActions extends DileI18nMixin(LitElement) {
196
200
  }
197
201
  }));
198
202
  this.confirmElement.open();
203
+ this.updateComplete.then(() => this.applyActionValidationSchema());
199
204
  let listOptions = this.shadowRoot.querySelector('dile-crud-list-options');
200
205
  if (listOptions) {
201
206
  listOptions.close();
@@ -206,7 +211,11 @@ export class DileCrudActions extends DileI18nMixin(LitElement) {
206
211
  return this.shadowRoot.querySelector(`[action="${this.selection}"]`);
207
212
  }
208
213
 
209
- doAction() {
214
+ async doAction() {
215
+ if (!(await this.validateActionForm())) {
216
+ this.confirmElement?.resetProcessing();
217
+ return;
218
+ }
210
219
  this.loading = true;
211
220
  this.dispatchEvent(new CustomEvent('crud-action-start', {
212
221
  bubbles: true,
@@ -264,6 +273,51 @@ export class DileCrudActions extends DileI18nMixin(LitElement) {
264
273
  return actionForm;
265
274
  }
266
275
 
276
+ /**
277
+ * Validates the form of the selected action with its validate() method, if it has one (DileForm).
278
+ * When it is not valid, dispatches crud-action-invalid and the confirm stays open.
279
+ * @returns {Promise<boolean>} true when the action can be sent
280
+ */
281
+ async validateActionForm() {
282
+ const form = this.selectedActionForm;
283
+ if (!form || typeof form.validate !== 'function') {
284
+ return true;
285
+ }
286
+ await this.applyActionValidationSchema(form);
287
+ if (form.language === undefined && this.language) {
288
+ form.language = this.language;
289
+ }
290
+ const { valid, errors } = await form.validate();
291
+ if (!valid) {
292
+ this.dispatchEvent(new CustomEvent('crud-action-invalid', {
293
+ bubbles: true,
294
+ composed: true,
295
+ detail: {
296
+ action: this.selection,
297
+ errors,
298
+ }
299
+ }));
300
+ }
301
+ return valid;
302
+ }
303
+
304
+ /** Hands the schema of the selected action (validationSchemas) to its form with setValidationSchema() */
305
+ async applyActionValidationSchema(form = this.selectedActionForm) {
306
+ if (!form) {
307
+ return;
308
+ }
309
+ if (form.localName.includes('-')) {
310
+ await customElements.whenDefined(form.localName);
311
+ }
312
+ const schema = this.validationSchemas?.[this.selection] || null;
313
+ if (typeof form.setValidationSchema === 'function') {
314
+ form.setValidationSchema(schema, { operation: this.selection, messages: this.validationMessages });
315
+ } else if (schema && !this._validationSchemaWarned) {
316
+ this._validationSchemaWarned = true;
317
+ console.warn(`[dile-crud-actions] There are validation rules for the action "${this.selection}" but its form <${form.localName}> has no setValidationSchema() method. Apply the DileFormValidation mixin of @dile/validation to the form so the rules are used.`);
318
+ }
319
+ }
320
+
267
321
  cancelAction() {
268
322
  this.loading = false;
269
323
  if (this.confirmElement) {
@@ -73,6 +73,12 @@ export class DileAjaxForm extends DileI18nMixin(LitElement) {
73
73
  cancelIcon: { type: Object },
74
74
  disableClearAfterInsert: { type: Boolean },
75
75
  hideActions: { type: Boolean },
76
+ /** Sends the form without calling its validate() method */
77
+ skipValidation: { type: Boolean },
78
+ /** Validation rules `{ field: rules }` handed to the form with setValidationSchema() (needs the DileFormValidation mixin of @dile/validation) */
79
+ validationSchema: { type: Object },
80
+ /** Validation messages handed to the form together with validationSchema */
81
+ validationMessages: { type: Object },
76
82
  _loading: { state: true },
77
83
  };
78
84
  }
@@ -86,6 +92,9 @@ export class DileAjaxForm extends DileI18nMixin(LitElement) {
86
92
  }
87
93
 
88
94
  updated(changedProperties) {
95
+ if (changedProperties.has('validationSchema') || changedProperties.has('validationMessages') || changedProperties.has('operation')) {
96
+ this.applyValidationSchema();
97
+ }
89
98
  if (changedProperties.has('relatedId') || changedProperties.has('endpoint')) {
90
99
  if(this.loadOnInit) {
91
100
  this.loadData();
@@ -214,6 +223,9 @@ export class DileAjaxForm extends DileI18nMixin(LitElement) {
214
223
  }
215
224
 
216
225
  async sendData() {
226
+ if (!(await this.validateForm())) {
227
+ return;
228
+ }
217
229
  // Forms can implement an optional async prepareData() to compute data before getData() is called
218
230
  if (typeof this.form.prepareData === 'function') {
219
231
  await this.form.prepareData();
@@ -222,6 +234,49 @@ export class DileAjaxForm extends DileI18nMixin(LitElement) {
222
234
  this.ajaxsave.generateRequest();
223
235
  }
224
236
 
237
+ /**
238
+ * Validates the form with its validate() method, if it has one (DileForm).
239
+ * When the form is not valid, shows a feedback message and dispatches dile-ajax-form-invalid.
240
+ * @returns {Promise<boolean>} true when the form can be sent
241
+ */
242
+ async validateForm() {
243
+ const form = this.form;
244
+ if (this.skipValidation || !form || typeof form.validate !== 'function') {
245
+ return true;
246
+ }
247
+ await this.applyValidationSchema();
248
+ if (form.language === undefined && this.language) {
249
+ form.language = this.language;
250
+ }
251
+ const { valid, errors } = await form.validate();
252
+ if (!valid) {
253
+ this.feedback.negativeFeedbackWithDelay(this.translations?.validation_error_feedback || 'Please review the errors in the form', 5000);
254
+ this.dispatchEvent(new CustomEvent('dile-ajax-form-invalid', {
255
+ bubbles: true,
256
+ composed: true,
257
+ detail: { errors }
258
+ }));
259
+ }
260
+ return valid;
261
+ }
262
+
263
+ /** Hands validationSchema to the form with setValidationSchema(schema, { operation }) */
264
+ async applyValidationSchema() {
265
+ const form = this.form;
266
+ if (!form) {
267
+ return;
268
+ }
269
+ if (form.localName.includes('-')) {
270
+ await customElements.whenDefined(form.localName);
271
+ }
272
+ if (typeof form.setValidationSchema === 'function') {
273
+ form.setValidationSchema(this.validationSchema || null, { operation: this.operation, messages: this.validationMessages });
274
+ } else if (this.validationSchema && !this._validationSchemaWarned) {
275
+ this._validationSchemaWarned = true;
276
+ console.warn(`[dile-ajax-form] validationSchema is set but the form <${form.localName}> has no setValidationSchema() method. Apply the DileFormValidation mixin of @dile/validation to the form so the rules are used.`);
277
+ }
278
+ }
279
+
225
280
  doErrorGet(e) {
226
281
  this.responseAdapter.setResponse(e.detail);
227
282
  let msg = this._customErrorMessage();
@@ -49,9 +49,12 @@ export class DileConfirmedAjaxForm extends DileAjaxForm {
49
49
  this.confirmDialog = this.shadowRoot.getElementById('confirmDialog');
50
50
  }
51
51
 
52
- doAction() {
52
+ async doAction() {
53
53
  this.feedback.clear();
54
- this.confirmDialog.open();
54
+ // Validate before asking for confirmation, so the user doesn't confirm an invalid form
55
+ if (await this.validateForm()) {
56
+ this.confirmDialog.open();
57
+ }
55
58
  }
56
59
 
57
60
  onConfirmAccepted() {
@@ -246,6 +246,9 @@ export class DileCrud extends DileI18nMixin(DileCrudMixin(LitElement)) {
246
246
  .formTemplate=${this.config.templates.insertForm}
247
247
  actionLabel=${this.insertLabelComputed(this.config.labels.insertAction, this.translations)}
248
248
  formIdentifier="${this.config.formIds.insertForm}"
249
+ .validationSchema=${this.config.validation?.insert}
250
+ .validationMessages=${this.config.validation?.messages}
251
+ language="${this.language}"
249
252
  @crud-insert-success="${this.modalInsertSuccess}"
250
253
  belongsTo=${this.belongsTo}
251
254
  relationId=${this.relationId}
@@ -25,6 +25,10 @@ export class DileCrudInsert extends DileI18nMixin(LitElement) {
25
25
  buttonSmall: { type: Boolean },
26
26
  responseAdapter: { type: Object},
27
27
  formIdentifier: { type: String },
28
+ /** Validation rules `{ field: rules }` for the form (see dile-ajax-form validationSchema) */
29
+ validationSchema: { type: Object },
30
+ /** Validation messages for the form (see dile-ajax-form validationMessages) */
31
+ validationMessages: { type: Object },
28
32
  sendDataAsFormData: { type: Boolean },
29
33
  showCancelButton: { type: Boolean },
30
34
  };
@@ -67,6 +71,8 @@ export class DileCrudInsert extends DileI18nMixin(LitElement) {
67
71
  ?buttonSmall="${this.buttonSmall}"
68
72
  .responseAdapter="${this.responseAdapter}"
69
73
  formIdentifier="${this.formIdentifier}"
74
+ .validationSchema=${this.validationSchema}
75
+ .validationMessages=${this.validationMessages}
70
76
  language="${this.language}"
71
77
  ?sendDataAsFormData=${this.sendDataAsFormData}
72
78
  ?showCancelButton=${this.showCancelButton}
@@ -1,12 +1,16 @@
1
1
  import { LitElement, html, css } from 'lit';
2
- import { DileEmmitChange } from '@dile/ui/mixins/form/index.js';
2
+ import { DileEmmitChange, DileNativeValidity } from '@dile/ui/mixins/form/index.js';
3
3
  import { DileAxios } from '../../../lib/DileAxios.js';
4
4
  import '@dile/ui/components/select/select.js';
5
5
  import '@dile/ui/components/spinner/spinner-horizontal.js';
6
6
  import { labelStyles } from '@dile/ui/components/input/src/label-styles.js';
7
7
  import { messageStyles } from '@dile/ui/components/input/src/message-styles.js';
8
8
 
9
- export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement)) {
9
+ export class DileSelectAjaxSimple extends DileAxios(DileNativeValidity(DileEmmitChange(LitElement))) {
10
+ static get formAssociated() {
11
+ return true;
12
+ }
13
+
10
14
 
11
15
  static get styles() {
12
16
  return [
@@ -46,6 +50,8 @@ export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement))
46
50
  label: { type: String },
47
51
  endpoint: { type: String },
48
52
  value: { type: String },
53
+ /** Marks the field as required: shows the required indicator in the label and sets aria-required */
54
+ required: { type: Boolean, reflect: true },
49
55
  disabled: { type: Boolean },
50
56
  errored: { type: Boolean },
51
57
  message: { type: String },
@@ -76,6 +82,17 @@ export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement))
76
82
  this.loading = false;
77
83
  this.ajaxError = false;
78
84
  this.data = [];
85
+ this.internals = this.attachInternals();
86
+ }
87
+
88
+ firstUpdated() {
89
+ this._defaultValue = this.value;
90
+ }
91
+
92
+ /** Called by the browser when the owner form is reset: restores the initial value */
93
+ formResetCallback() {
94
+ super.formResetCallback?.();
95
+ this.value = this._defaultValue;
79
96
  }
80
97
 
81
98
  connectedCallback() {
@@ -85,6 +102,7 @@ export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement))
85
102
 
86
103
  updated(changedProperties) {
87
104
  if (changedProperties.has('value')) {
105
+ this.internals.setFormValue(this.value ?? '');
88
106
  this.selectCurrentValue();
89
107
  this.emmitChange();
90
108
  }
@@ -207,7 +225,7 @@ export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement))
207
225
 
208
226
  render() {
209
227
  return html`
210
- ${this.label ? html`<label>${this.label}</label>` : ''}
228
+ ${this.label ? html`<label class="field-label">${this.label}</label>` : ''}
211
229
  ${this.loading
212
230
  ? html`<div class="spinner-container"><dile-spinner-horizontal active></dile-spinner-horizontal></div>`
213
231
  : this.ajaxError
@@ -220,6 +238,7 @@ export class DileSelectAjaxSimple extends DileAxios(DileEmmitChange(LitElement))
220
238
  value="${this.value ?? ''}"
221
239
  ?disabled=${this.disabled}
222
240
  ?errored=${this.errored}
241
+ ?required=${this.required}
223
242
  message="${this.message || ''}"
224
243
  @element-changed=${this.onSelected}
225
244
  >
@@ -352,6 +352,8 @@ export class DileCrudSingle extends DileI18nMixin(DileCrudMixin(LitElement)) {
352
352
  language="${this.language}"
353
353
  .element=${this.element}
354
354
  .responseAdapter=${this.config.responseAdapter}
355
+ .validationSchemas=${this.config.validation?.actions}
356
+ .validationMessages=${this.config.validation?.messages}
355
357
  ></dile-crud-single-actions>
356
358
  `
357
359
  }
@@ -42,6 +42,10 @@ export class DileStepForm extends LitElement {
42
42
  /** The form of this step receives the data returned when another step is saved */
43
43
  refreshOnSave: { type: Boolean },
44
44
  sendDataAsFormData: { type: Boolean },
45
+ /** Saves the step without calling the validate() method of its form */
46
+ skipValidation: { type: Boolean },
47
+ /** Also validates the form when the alternative exit is used (by default a draft is saved without validation) */
48
+ validateAlternativeExit: { type: Boolean },
45
49
  responseAdapter: { type: Object },
46
50
  language: { type: String },
47
51
  loading: { type: Boolean },
@@ -58,6 +62,8 @@ export class DileStepForm extends LitElement {
58
62
  this.defaultLabels = {};
59
63
  this.refreshOnSave = false;
60
64
  this.sendDataAsFormData = false;
65
+ this.skipValidation = false;
66
+ this.validateAlternativeExit = false;
61
67
  this.language = "en";
62
68
  this.loading = false;
63
69
  this.alternativeExitRequested = false;
@@ -127,13 +133,16 @@ export class DileStepForm extends LitElement {
127
133
  this.submit(true);
128
134
  }
129
135
 
130
- submit(alternativeExit) {
136
+ async submit(alternativeExit) {
131
137
  const form = this.form;
132
138
  if (!form) {
133
139
  throw new Error(
134
140
  `[dile-step-form] No element with slot="form" was found in step ${this.step + 1}. The form element must have the slot="form" attribute.`,
135
141
  );
136
142
  }
143
+ if (!(await this.validateForm(alternativeExit))) {
144
+ return;
145
+ }
137
146
  const data = form.getData();
138
147
  if (alternativeExit && this.alternativeExitField) {
139
148
  data[this.alternativeExitField] = true;
@@ -144,6 +153,33 @@ export class DileStepForm extends LitElement {
144
153
  this.elajax.generateRequest();
145
154
  }
146
155
 
156
+ /**
157
+ * Validates the form of the step with its validate() method, if it has one (DileForm).
158
+ * The alternative exit (e.g. "Save as draft") is not validated unless validateAlternativeExit is set.
159
+ * When the form is not valid, dispatches dile-step-form-invalid and the step is not saved.
160
+ * @returns {Promise<boolean>} true when the step can be saved
161
+ */
162
+ async validateForm(alternativeExit = false) {
163
+ const form = this.form;
164
+ if (this.skipValidation || (alternativeExit && !this.validateAlternativeExit) || typeof form?.validate !== 'function') {
165
+ return true;
166
+ }
167
+ if (form.language === undefined && this.language) {
168
+ form.language = this.language;
169
+ }
170
+ const { valid, errors } = await form.validate();
171
+ if (!valid) {
172
+ this.dispatchEvent(
173
+ new CustomEvent("dile-step-form-invalid", {
174
+ bubbles: true,
175
+ composed: true,
176
+ detail: { step: this.step, errors },
177
+ }),
178
+ );
179
+ }
180
+ return valid;
181
+ }
182
+
147
183
  setLoading(loading) {
148
184
  this.loading = loading;
149
185
  this.dispatchEvent(
@@ -25,6 +25,10 @@ export class DileCrudUpdate extends DileI18nMixin(LitElement) {
25
25
  buttonSmall: { type: Boolean },
26
26
  responseAdapter: { type: Object },
27
27
  formIdentifier: { type: String },
28
+ /** Validation rules `{ field: rules }` for the form (see dile-ajax-form validationSchema) */
29
+ validationSchema: { type: Object },
30
+ /** Validation messages for the form (see dile-ajax-form validationMessages) */
31
+ validationMessages: { type: Object },
28
32
  sendDataAsFormData: { type: Boolean },
29
33
  showCancelButton: { type: Boolean },
30
34
  data: { type: Object },
@@ -72,6 +76,8 @@ export class DileCrudUpdate extends DileI18nMixin(LitElement) {
72
76
  ?loadOnInit="${this.loadOnInit}"
73
77
  .responseAdapter="${this.responseAdapter}"
74
78
  formIdentifier="${this.formIdentifier}"
79
+ .validationSchema=${this.validationSchema}
80
+ .validationMessages=${this.validationMessages}
75
81
  language="${this.language}"
76
82
  ?sendDataAsFormData=${this.sendDataAsFormData}
77
83
  ?showCancelButton=${this.showCancelButton}
@@ -29,6 +29,8 @@ export const DileCrudMixin = (superclass) => class extends superclass {
29
29
  .formActionsTemplate=${this.config.templates.formActions}
30
30
  language="${this.language}"
31
31
  .responseAdapter=${this.config.responseAdapter}
32
+ .validationSchemas=${this.config.validation?.actions}
33
+ .validationMessages=${this.config.validation?.messages}
32
34
  ></dile-crud-actions>
33
35
  `
34
36
  }
@@ -47,6 +49,8 @@ export const DileCrudMixin = (superclass) => class extends superclass {
47
49
  .formActionsTemplate=${this.config.templates.formActions}
48
50
  language="${this.language}"
49
51
  .responseAdapter=${this.config.responseAdapter}
52
+ .validationSchemas=${this.config.validation?.actions}
53
+ .validationMessages=${this.config.validation?.messages}
50
54
  ></dile-crud-single-action-dispatcher>
51
55
  `
52
56
  }
@@ -66,6 +70,9 @@ export const DileCrudMixin = (superclass) => class extends superclass {
66
70
  .formTemplate=${this.config.templates.updateForm}
67
71
  actionLabel="${this.updateLabelComputed(this.config.labels.updateAction, this.translations)}"
68
72
  formIdentifier="${this.config.formIds.updateForm}"
73
+ .validationSchema=${this.config.validation?.update}
74
+ .validationMessages=${this.config.validation?.messages}
75
+ language="${this.language}"
69
76
  @crud-update-success="${this.modalUpdateSuccess}"
70
77
  ></dile-crud-update>
71
78
  </dile-modal>
@@ -86,6 +86,9 @@ export const defaultConfig = {
86
86
  labels: {
87
87
 
88
88
  },
89
+ // Optional validation rules, used by forms with the DileFormValidation mixin of @dile/validation:
90
+ // { insert: { field: rules }, update: { field: rules }, actions: { ActionName: { field: rules } }, messages: { rule: 'message' } }
91
+ validation: null,
89
92
  formIds: {
90
93
  insertForm: 'insertform',
91
94
  updateForm: 'updateform',
package/lib/i18n/en.js CHANGED
@@ -15,6 +15,7 @@ export const translations = {
15
15
  ajax_form_not_supported: "Operation not supported in dile-ajax-form use 'insert' or 'update'",
16
16
  success_operation: (operation) => operation == 'insert' ? 'The new item has been created' : 'Item updated successfully',
17
17
  error_operation: (operation) => `${operation == 'insert' ? 'Insertion' : 'Update'} error`,
18
+ validation_error_feedback: "Please review the errors in the form",
18
19
  send_label: "Send",
19
20
  insert_label: "Create",
20
21
  update_label: "Update",
package/lib/i18n/es.js CHANGED
@@ -15,6 +15,7 @@ export const translations = {
15
15
  ajax_form_not_supported: "Operación no soportada por dile-ajax-form. Elige entre 'insert' o 'update'",
16
16
  success_operation: (operation) => `${operation == 'insert' ? 'Inserción' : 'Actualización'} completada con éxito`,
17
17
  error_operation: (operation) => `Se ha producido un error en la ${operation == 'insert' ? 'inserción' : 'actualización'}`,
18
+ validation_error_feedback: "Revisa los errores del formulario",
18
19
  send_label: "Enviar",
19
20
  insert_label: "Crear",
20
21
  update_label: "Actualizar",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dile/crud",
3
- "version": "2.16.1",
3
+ "version": "2.17.0",
4
4
  "description": "Components to create a generic crud system based on Web Components and Lit",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -26,12 +26,12 @@
26
26
  "homepage": "https://dile-components.com/",
27
27
  "dependencies": {
28
28
  "@dile/image-cropper": "^0.1.1",
29
- "@dile/ui": "^3.22.1",
30
- "axios": "^1.19.0",
29
+ "@dile/ui": "^3.24.0",
30
+ "axios": "^1.21.1",
31
31
  "lit": "^2.7.0 || ^3.0.0"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"
35
35
  },
36
- "gitHead": "cef9349e18ff89a24a206a541f8129fd30ccb553"
36
+ "gitHead": "67268dcc3bb2972b55da7d971a20ddbfa0bcbd0d"
37
37
  }