@wix/auto-patterns 1.16.0 → 1.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.
Files changed (65) hide show
  1. package/dist/cjs/components/AutoPatternsRoute/AutoPatternsRoutes.js +4 -4
  2. package/dist/cjs/components/AutoPatternsRoute/AutoPatternsRoutes.js.map +1 -1
  3. package/dist/cjs/dataSourceAdapters/cms/cmsAdapter.js +0 -2
  4. package/dist/cjs/dataSourceAdapters/cms/cmsAdapter.js.map +1 -1
  5. package/dist/cjs/dataSourceAdapters/cms/fetchCmsData.js.map +1 -1
  6. package/dist/cjs/dataSourceAdapters/cms/filterUtils.js.map +1 -1
  7. package/dist/cjs/dataSourceAdapters/cms/sortUtils.js.map +1 -1
  8. package/dist/cjs/hooks/useColumns.js +7 -5
  9. package/dist/cjs/hooks/useColumns.js.map +1 -1
  10. package/dist/cjs/hooks/useNavigationUtils.js +2 -2
  11. package/dist/cjs/hooks/useNavigationUtils.js.map +1 -1
  12. package/dist/cjs/types/actions/base.js.map +1 -1
  13. package/dist/cjs/types/types.js.map +1 -1
  14. package/dist/cjs/utils/actions/resolveAction.js +2 -1
  15. package/dist/cjs/utils/actions/resolveAction.js.map +1 -1
  16. package/dist/cjs/utils/actions/types.js.map +1 -1
  17. package/dist/docs/action_cell.md +20 -1
  18. package/dist/docs/app_config_structure.md +66 -1
  19. package/dist/docs/auto-patterns-guide.md +378 -76
  20. package/dist/docs/bulk_actions.md +1 -1
  21. package/dist/docs/collection_page.md +1 -1
  22. package/dist/docs/config_schema.md +184 -0
  23. package/dist/docs/custom_overrides.md +163 -4
  24. package/dist/docs/index.md +5 -7
  25. package/dist/docs/schema_config.md +174 -0
  26. package/dist/docs/sdk_utilities.md +97 -0
  27. package/dist/docs/wix_fqdn_custom_data_source.md +201 -0
  28. package/dist/esm/components/AutoPatternsRoute/AutoPatternsRoutes.js +1 -1
  29. package/dist/esm/components/AutoPatternsRoute/AutoPatternsRoutes.js.map +1 -1
  30. package/dist/esm/dataSourceAdapters/cms/cmsAdapter.js +0 -2
  31. package/dist/esm/dataSourceAdapters/cms/cmsAdapter.js.map +1 -1
  32. package/dist/esm/dataSourceAdapters/cms/fetchCmsData.js.map +1 -1
  33. package/dist/esm/dataSourceAdapters/cms/filterUtils.js.map +1 -1
  34. package/dist/esm/dataSourceAdapters/cms/sortUtils.js.map +1 -1
  35. package/dist/esm/hooks/useColumns.js +3 -1
  36. package/dist/esm/hooks/useColumns.js.map +1 -1
  37. package/dist/esm/hooks/useNavigationUtils.js +1 -1
  38. package/dist/esm/hooks/useNavigationUtils.js.map +1 -1
  39. package/dist/esm/types/actions/base.js.map +1 -1
  40. package/dist/esm/types/types.js.map +1 -1
  41. package/dist/esm/utils/actions/resolveAction.js +2 -1
  42. package/dist/esm/utils/actions/resolveAction.js.map +1 -1
  43. package/dist/esm/utils/actions/types.js.map +1 -1
  44. package/dist/types/dataSourceAdapters/cms/cmsAdapter.d.ts.map +1 -1
  45. package/dist/types/dataSourceAdapters/cms/fetchCmsData.d.ts +2 -3
  46. package/dist/types/dataSourceAdapters/cms/fetchCmsData.d.ts.map +1 -1
  47. package/dist/types/dataSourceAdapters/cms/filterUtils.d.ts +3 -4
  48. package/dist/types/dataSourceAdapters/cms/filterUtils.d.ts.map +1 -1
  49. package/dist/types/dataSourceAdapters/cms/sortUtils.d.ts +2 -3
  50. package/dist/types/dataSourceAdapters/cms/sortUtils.d.ts.map +1 -1
  51. package/dist/types/hooks/useColumns.d.ts.map +1 -1
  52. package/dist/types/types/actions/base.d.ts +1 -0
  53. package/dist/types/types/actions/base.d.ts.map +1 -1
  54. package/dist/types/types/types.d.ts +13 -3
  55. package/dist/types/types/types.d.ts.map +1 -1
  56. package/dist/types/utils/actions/resolveAction.d.ts +1 -0
  57. package/dist/types/utils/actions/resolveAction.d.ts.map +1 -1
  58. package/dist/types/utils/actions/types.d.ts +1 -0
  59. package/dist/types/utils/actions/types.d.ts.map +1 -1
  60. package/package.json +19 -18
  61. package/dist/docs/recipe-bulk-operations.md +0 -1352
  62. package/dist/docs/recipe-crud-operations.md +0 -786
  63. package/dist/docs/recipe-customization.md +0 -1702
  64. package/dist/docs/recipe-first-dashboard.md +0 -794
  65. package/dist/docs/sdk_and_schema.md +0 -215
@@ -1,1702 +0,0 @@
1
- # Recipe: Complete Customization Guide
2
-
3
- **Use Case**: "I want to customize my dashboard - from basic styling to complex custom behavior and integrations"
4
-
5
- This comprehensive guide covers customization from basic visual changes to advanced programmatic control.
6
-
7
- ---
8
-
9
- # AppConfig Structure
10
-
11
- ## ⚠️ Configuration Rules
12
-
13
- - **Configuration must come only from a JSON file** - never inline or from other sources
14
- - **DO NOT fill optional fields unless explicitly requested** - leave optional properties undefined to avoid unnecessary complexity
15
- - **After each configuration change, verify that the configuration strictly aligns with the structure described below** - any configuration entries not defined in this structure must be removed
16
- - **When generating config for the first time, select up to 3 columns from the schema that best represent the entity**
17
-
18
- ## ⚠️ Common Configuration Mistakes to Avoid
19
-
20
- - Adding more than two pages
21
- - Mixing page types in a single configuration
22
- - Including undefined optional fields
23
- - Selecting too many initial columns
24
- - Not designating exactly one page as `appMainPage: true`
25
- - Missing or inconsistent page relationships (parentPageId/entityPageId)
26
- - Setting `stickyColumns` to invalid values (negative, zero, or exceeding column count)
27
-
28
- ```ts
29
- export interface AppConfig {
30
- pages: {
31
- id: string; // Page unique identifier (must be unique across the app)
32
- type: 'collectionPage' | 'entityPage'; // Defines page type
33
- appMainPage?: boolean; // Designates this page as the main page (exactly one page must have this set to true)
34
- collectionPage?: {
35
- route: {
36
- path: string; // Route path for the collection page (e.g., '/')
37
- };
38
- title: {
39
- text: string; // Main page title
40
- hideTotal?: boolean; // Hide total items in header. Default: true
41
- };
42
- subtitle?: {
43
- text: string; // Optional page subtitle
44
- };
45
- actions?: { // Defines page-level actions for the collection page
46
- primaryActions?: {
47
- type: 'action' | 'menu'; // Type of primary actions layout
48
- action?: { // Required when type is 'action'
49
- item: {
50
- id: string; // Unique identifier for the action
51
- type: 'create' | 'custom'; // Action type
52
- label?: string; // Text displayed for the action
53
- collection: {
54
- collectionId: string; // ID of the Wix Data collection
55
- entityTypeSource: 'cms'; // Data source type. Always 'cms'
56
- };
57
- create?: { // Required when type is 'create'
58
- mode: 'page'; // Create mode
59
- page: {
60
- id: string; // Entity page ID to navigate to for creation
61
- };
62
- };
63
- };
64
- };
65
- menu?: { // Required when type is 'menu'
66
- label: string; // Label for the group
67
- items: {}[]; // Array of action configurations, same structure as action.item, can include dividers
68
- };
69
- };
70
- secondaryActions?: {
71
- type: 'action' | 'menu'; // Type of secondary actions layout, same structure as primaryActions
72
- action?: {}; // Same structure as primaryActions.action
73
- menu?: {}; // Same structure as primaryActions.menu
74
- };
75
- };
76
- components: [
77
- {
78
- entityPageId?: string; // ID of the entity page to navigate to when clicking a row
79
- collection: {
80
- collectionId: string; // ID of the Wix Data collection
81
- entityTypeSource: 'cms'; // Data source type. Always 'cms'
82
- reflectQueryInUrl?: boolean; // Reflects query state (search, filters, sorting) in the browser URL. Default: false
83
- selectAllScope?: 'page' | 'all'; // Controls "Select All" scope. 'all' selects entire collection, 'page' selects only visible items. Default: 'all'
84
- selectionUpdateMode?: 'preserve' | 'clear'; // Controls selection behavior when data changes. 'preserve' maintains selections, 'clear' clears them. Default: 'clear'
85
- };
86
- filters?: {
87
- panelTitle?: string; // Title of the filters panel
88
- items: {
89
- id: string; // Unique identifier for the filter item
90
- fieldId: string; // ID of the field to filter by (must be a valid type: NUMBER, DATETIME, BOOLEAN, ARRAY, ARRAY_STRING)
91
- displayName?: string; // Display name of the filter item
92
- openByDefault?: boolean; // Whether the filter item is open by default in the panel (accordion is open)
93
- sectionTitle?: string; // Title of the filter section. Required if more than one section exists to prevent confusion
94
- tagLabel?: string; // Label shown in Tag component in the table/grid when the filter is applied (e.g., "Age: 7")
95
- numberConfig?: {
96
- min?: number; // Minimum value
97
- max?: number; // Maximum value
98
- allowedDecimals?: true; // Decimal precision allowed
99
- };
100
- dateConfig?: {
101
- mode?: 'ONLY_PREDEFINED' | 'ONLY_CUSTOM' | 'COMBINE'; // Determines filter behavior
102
- presets?: (
103
- | 'SEVEN_DAYS'
104
- | 'FOURTEEN_DAYS'
105
- | 'MONTH'
106
- | 'TODAY'
107
- | 'TOMORROW'
108
- | 'NEXT_THREE_DAYS'
109
- | 'NEXT_SEVEN_DAYS'
110
- | 'NEXT_THIRTY_DAYS'
111
- )[]; // Shown only if mode includes predefined presets (COMBINE or ONLY_PREDEFINED)
112
- includeTime?: boolean; // Whether to allow time selection. Default is true
113
- };
114
- booleanConfig?: {
115
- trueLabel?: string; // Label shown for the true value
116
- falseLabel?: string; // Label shown for the false value
117
- };
118
- enumConfig?: {
119
- options: {
120
- value: string; // Enum option value
121
- label: string; // Enum option label
122
- }[];
123
- selectionMode: 'single' | 'multiple'; // Selection behavior
124
- optionType?:
125
- | 'checkbox'
126
- | 'inlineCheckbox'
127
- | 'radio'
128
- | 'select'; // Option rendering style
129
- };
130
- }[];
131
- };
132
- actionCell?: {
133
- primaryAction?: {
134
- item: {
135
- id: string; // Unique identifier for the action
136
- type: 'update' | 'delete' | 'custom'; // Action type
137
- label?: string; // Text displayed for the action
138
- disabled?: boolean; // Whether the action is disabled
139
- tooltip?: string; // Tooltip text shown on hover
140
- update?: { // Required when type is 'update'
141
- mode: 'page'; // Update mode
142
- page?: { // Required when mode is 'page'
143
- id: string; // Entity page ID to navigate to
144
- };
145
- };
146
- delete?: { // Required when type is 'delete'
147
- mode: 'modal'; // Currently only 'modal' is supported
148
- modal: {
149
- title?: {
150
- text: string; // Modal title
151
- };
152
- description?: {
153
- text: string; // Modal description
154
- };
155
- actions?: {
156
- submit?: {
157
- text: string; // Submit button text
158
- };
159
- cancel?: {
160
- text: string; // Cancel button text
161
- };
162
- };
163
- feedback?: {
164
- successToast?: {
165
- text: string; // Success message
166
- };
167
- errorToast?: {
168
- text: string; // Error message
169
- };
170
- };
171
- };
172
- };
173
- };
174
- };
175
- secondaryActions?: {
176
- items: {}[]; // Array of action configurations, same structure as primaryAction.item, can include dividers
177
- inlineCount?: number; // How many secondary actions to show inline before showing popover
178
- inlineAlwaysVisible?: boolean; // Whether to always show inline actions (not just on hover)
179
- };
180
- };
181
- bulkActionToolbar?: {
182
- primaryActions?: ({
183
- type: 'action' | 'menu'; // Type of bulk action item
184
- action?: { // Required when type is 'action'
185
- item: {
186
- id: string; // Unique identifier for the bulk action
187
- type: 'bulkDelete' | 'custom'; // Bulk action type
188
- label?: string; // Text displayed for the action
189
- bulkDelete?: { // Required when type is 'bulkDelete'
190
- mode: 'modal'; // Currently only 'modal' is supported
191
- modal: {
192
- title?: {
193
- text: string; // Modal title
194
- };
195
- description?: {
196
- text: string; // Modal description
197
- };
198
- actions?: {
199
- submit?: {
200
- text: string; // Submit button text
201
- };
202
- cancel?: {
203
- text: string; // Cancel button text
204
- };
205
- };
206
- feedback?: {
207
- successToast?: {
208
- text: string; // Success message
209
- };
210
- errorToast?: {
211
- text: string; // Error message
212
- };
213
- };
214
- };
215
- };
216
- };
217
- };
218
- menu?: { // Required when type is 'menu'
219
- label: string; // Label for the dropdown group
220
- items: {}[] // Array of bulk actions configurations, same structure as action.item, can include dividers
221
- };
222
- })[];
223
- secondaryActions?: {}[]; // Array of bulk actions configurations, same structure as primaryActions[].menu.items, can include dividers
224
- };
225
- toolbarTitle?: {
226
- title: string; // Toolbar title above the table/grid
227
- subtitle?: {
228
- text: string; // Toolbar subtitle
229
- };
230
- showTotal?: boolean; // Show total items on toolbar. Default: false
231
- };
232
- search?: {
233
- shown?: boolean; // Show/hide the search
234
- };
235
- emptyState?: {
236
- title?: string; // Empty state title
237
- subtitle?: string; // Empty state subtitle
238
- image?: {
239
- id: string; // Image ID for empty state
240
- };
241
- addNewCta?: {
242
- id?: string; // Add New CTA ID
243
- text?: string; // Add New CTA text
244
- };
245
- customCta?: {
246
- id?: string; // Custom CTA ID
247
- };
248
- };
249
- layout: [ // Array of layout items that define what components to render
250
- {
251
- type: 'Table'; // Layout item type for table rendering
252
- table?: {
253
- columns: {
254
- id: string; // Field ID from the collection
255
- name: string; // Column title displayed
256
- width: string; // The width of the column (required in types)
257
- sortable?: boolean; // If the column is sortable
258
- defaultSortOrder?: 'asc' | 'desc'; // Optional default sort order
259
- sortMode?: 'asc' | 'desc'; // Optional sorting mode
260
- reorderDisabled?: boolean; // Whether column reordering is disabled
261
- hideable?: boolean; // Whether column can be hidden
262
- defaultHidden?: boolean; // Whether column is hidden by default
263
- hiddenFromCustomColumnsSelection?: boolean; // Whether column is hidden from custom columns selection
264
- }[];
265
- customColumns?: {
266
- enabled: boolean; // Enable user customization (hide/reorder columns)
267
- };
268
- stickyColumns?: number; // Number of columns to make sticky from the start. Sticky columns remain visible when horizontally scrolling.
269
- };
270
- },
271
- {
272
- type: 'Grid'; // Layout item type for grid rendering
273
- grid?: {
274
- item: {
275
- titleFieldId: string; // Field ID to display as the item title
276
- subtitleFieldId?: string; // Field ID for the item subtitle
277
- imageFieldId?: string; // Field ID for the item image
278
- /**
279
- * Controls which content is shown in the card (preset):
280
- * - 'full': Shows both title and subtitle.
281
- * - 'title': Shows only the title.
282
- * - 'empty': Hides both title and subtitle (card appears visually empty except for image or other content).
283
- */
284
- cardContentMode?: 'full' | 'title' | 'empty';
285
- imagePlacement?: 'top' | 'side';
286
- };
287
- };
288
- }
289
- ]; // End of layout array
290
- }
291
- ]; // End of components array
292
- };
293
- entityPage?: {
294
- route: {
295
- path: string; // Route path for the entity page (e.g., '/product/:entityId')
296
- params: {
297
- id: string; // Maps dynamic parameter in path to its identifier
298
- };
299
- };
300
- title?: {
301
- text: string; // Entity page title
302
- };
303
- subtitle?: {
304
- text: string; // Entity page subtitle
305
- };
306
- parentPageId?: string; // ID of the parent collection page
307
- layout?: {
308
- // Main layout section
309
- main: {
310
- type: 'card'; // Type of the card
311
- card: {
312
- title: {
313
- text: string; // Title of the card
314
- };
315
- subtitle?: {
316
- text: string; // Subtitle of the card
317
- };
318
- children: LayoutContent[]; // Array of content items that can be fields, nested containers, or components
319
- };
320
- }[];
321
- // Sidebar layout section
322
- sidebar?: {
323
- type: 'card';
324
- card: {
325
- title: {
326
- text: string; // Title of the card
327
- };
328
- subtitle?: {
329
- text: string; // Subtitle of the card
330
- };
331
- children: LayoutContent[]; // Array of content items that can be fields, nested containers, or components
332
- };
333
- }[];
334
- };
335
- collectionId: string; // Related collection ID
336
- entityTypeSource: 'cms'; // Data source type. Always 'cms'
337
- };
338
- }[];
339
- }
340
-
341
- type LayoutContent =
342
- | {
343
- type: 'field';
344
- field: {
345
- span?: number;
346
- fieldId: string;
347
- };
348
- }
349
- | {
350
- type: 'container';
351
- container: {
352
- span?: number;
353
- children: LayoutContent[];
354
- };
355
- }
356
- | {
357
- type: 'component';
358
- component: {
359
- span?: number;
360
- componentId: string;
361
- };
362
- };
363
- ```
364
-
365
- ---
366
-
367
- # Custom Overrides
368
-
369
- ## ⚠️ Override Rules
370
-
371
- - **Custom overrides are restricted to the defined areas only** - attempting to override or modify any other aspect of `AutoPatternsApp` is prohibited and can cause unexpected behavior
372
- - **Always verify override implementation** - when implementing custom overrides, you MUST ensure they are correctly imported and passed to the `PatternsWizardOverridesProvider`
373
-
374
- The `PatternsWizardOverridesProvider` allows you to inject custom code to override default behaviors or add additional functionality. Below are the areas where overrides can be applied:
375
-
376
- > **Note:** These are the only areas where overrides are supported. Avoid attempting to override or modify other parts of the system, as this is not supported and may lead to unexpected behavior.
377
-
378
- ## Folder Structure Organization
379
-
380
- All custom overrides (components, modals, actions, columns, and other customizations) should be created in a `components` folder inside your page directory, not in a global `/src/components` folder. This keeps page-specific customizations organized alongside their respective pages.
381
-
382
- ### Recommended Structure:
383
-
384
- ```
385
- your-page/
386
- ├── page.tsx // Your main page component
387
- ├── MyCollectionConfig.patterns.json // Configuration file
388
- └── components/ // Page-specific components folder
389
- ├── index.tsx // Exports all overrides for easy importing
390
- ├── actions/ // Custom actions
391
- │ ├── index.tsx
392
- │ └── myCustomAction.tsx
393
- ├── columns/ // Column overrides
394
- │ ├── index.tsx
395
- │ ├── name.ts
396
- │ └── date.ts
397
- └── customComponents/ // Custom entity page components
398
- ├── index.tsx
399
- ├── CustomNameField.tsx
400
- └── InfoCard.tsx
401
- ```
402
-
403
- ### Importing Overrides in Your Page
404
-
405
- In your page component, import from the local components folder:
406
-
407
- ```tsx
408
- import * as modals from './components/modals';
409
- import * as actions from './components/actions';
410
- import * as columns from './components/columns';
411
- import * as components from './components/customComponents';
412
-
413
- <PatternsWizardOverridesProvider value={{ modals, actions, columns, components }}>
414
- <AutoPatternsApp configuration={config as AppConfig} />
415
- </PatternsWizardOverridesProvider>
416
- ```
417
-
418
- ### Important: Updating Index Files
419
-
420
- **When adding any new implementation (action, modal, column, or component), you MUST update the corresponding `index.tsx` file to export your new implementation.** The main page component imports from these index files, so they serve as the central export point for each type of override.
421
-
422
- For example:
423
- - Adding a new action → Update `./components/actions/index.tsx`
424
- - Adding a new modal → Update `./components/modals/index.tsx`
425
- - Adding a new column override → Update `./components/columns/index.tsx`
426
- - Adding a new custom component → Update `./components/customComponents/index.tsx`
427
-
428
- Without updating the index files, your implementations won't be available to the `PatternsWizardOverridesProvider`.
429
-
430
- ## ⚠️ Common Override Mistakes to Avoid
431
-
432
- - Attempting to override unsupported areas
433
- - Invalid column rendering functions
434
- - Missing index file exports for new implementations
435
- - Incorrect import paths or naming mismatches
436
-
437
- ## Columns
438
-
439
- Each column in the table has a default rendering based on its field type. You can override this rendering by providing a custom function for the `column.id`. This allows you to customize how specific columns are displayed.
440
-
441
- **Enhanced Column Overrides**: Column override can receive both the individual column `value` and the entire `row` data, enabling you to create complex columns that combine multiple field values from the same row.
442
-
443
- ### Function Signature
444
-
445
- ```typescript
446
- function columnOverride({ value, row }) {
447
- // value: The individual column value
448
- // row: The entire row object containing all field values
449
- return <YourCustomRendering />;
450
- }
451
- ```
452
-
453
- ### Understanding Row Data
454
-
455
- **Important**: The `row` object contains all field values from the entity, where each property corresponds to a **field ID** from the collection schema. To access specific field values, use the exact field ID as defined in your collection schema.
456
-
457
- For example, if your collection schema has these fields:
458
- ```json
459
- {
460
- "fields": [
461
- { "key": "name", "displayName": "Pet Name", "type": "TEXT" },
462
- { "key": "age", "displayName": "Age", "type": "NUMBER" },
463
- { "key": "isVaccinated", "displayName": "Vaccinated", "type": "BOOLEAN" },
464
- { "key": "lastActivity", "displayName": "Last Activity", "type": "DATETIME" }
465
- ]
466
- }
467
- ```
468
-
469
- Then in your column override, you access these values using the field IDs:
470
- ```typescript
471
- export function myColumn({ value, row }) {
472
- // Access field values using their schema field IDs
473
- const petName = row.name; // "name" field ID
474
- const petAge = row.age; // "age" field ID
475
- const isVaccinated = row.isVaccinated; // "isVaccinated" field ID
476
- const lastActivity = row.lastActivity; // "lastActivity" field ID
477
-
478
- return <YourCustomRendering />;
479
- }
480
- ```
481
-
482
- ### Use Cases for Row Data Access
483
-
484
- 1. **Complex Display Columns**: Combine multiple fields into a single display (e.g., "Name (Age)" combining name and age fields)
485
- 2. **Conditional Rendering**: Show different content based on other field values in the same row
486
- 3. **Calculated Columns**: Create computed values using multiple row fields
487
- 4. **Cross-Field Validation Display**: Show validation status based on relationships between fields
488
-
489
- ### Example: Defining and Using Column Overrides
490
-
491
- In `components/columns/name.tsx`:
492
-
493
- ```ts
494
- import React from 'react';
495
-
496
- export function name({ value, row }) {
497
- // Simple value formatting
498
- return <strong>{value}</strong>;
499
- }
500
- ```
501
-
502
- In `components/columns/petInfo.tsx`:
503
-
504
- ```ts
505
- import React from 'react';
506
- import { Box, Text } from '@wix/design-system';
507
-
508
- export function petInfo({ value, row }) {
509
- // Complex column combining multiple row values
510
- return (
511
- <Box direction="vertical" gap={1}>
512
- <Text weight="bold">{row.name}</Text>
513
- <Text size="small" skin="disabled">
514
- {row.age} years old • {row.type}
515
- </Text>
516
- {row.isVaccinated && (
517
- <Text size="tiny" skin="success">✓ Vaccinated</Text>
518
- )}
519
- </Box>
520
- );
521
- }
522
- ```
523
-
524
- In `components/columns/status.tsx`:
525
-
526
- ```ts
527
- import React from 'react';
528
- import { Badge } from '@wix/design-system';
529
-
530
- export function status({ value, row }) {
531
- // Conditional rendering based on multiple row fields
532
- if (row.isVaccinated && row.age > 1) {
533
- return <Badge skin="success">Ready for Adoption</Badge>;
534
- } else if (!row.isVaccinated) {
535
- return <Badge skin="warning">Needs Vaccination</Badge>;
536
- } else {
537
- return <Badge skin="neutral">Too Young</Badge>;
538
- }
539
- }
540
- ```
541
-
542
- In `components/columns/fullName.tsx`:
543
-
544
- ```ts
545
- import React from 'react';
546
-
547
- export function fullName({ value, row }) {
548
- // Calculated column using multiple fields
549
- return `${row.name} (owned by ${row.owner})`;
550
- }
551
- ```
552
-
553
- In `components/columns/date.tsx`:
554
-
555
- ```ts
556
- import React from 'react';
557
-
558
- export function date({ value, row }) {
559
- // Access to other row data for enhanced date formatting
560
- const isRecent = row.lastActivity && new Date(row.lastActivity) > new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
561
-
562
- return (
563
- <span style={{ color: isRecent ? 'green' : 'inherit' }}>
564
- <em>{new Date(value).toLocaleDateString()}</em>
565
- {isRecent && ' (Recent)'}
566
- </span>
567
- );
568
- }
569
- ```
570
-
571
- In `components/columns/index.tsx`:
572
-
573
- ```ts
574
- export * from './name';
575
- export * from './petInfo';
576
- export * from './status';
577
- export * from './fullName';
578
- export * from './date';
579
- ```
580
-
581
- **Important:** Every time you add a new column override file, you must add a corresponding export line to this `index.tsx` file. For example, if you create `price.tsx`, you must add `export * from './price';` to the index file.
582
-
583
- In the `PatternsWizardOverridesProvider`:
584
-
585
- ```tsx
586
- import * as columns from './components/columns';
587
-
588
- <PatternsWizardOverridesProvider value={{ columns }}>
589
- <AutoPatternsApp configuration={config as AppConfig} />
590
- </PatternsWizardOverridesProvider>
591
- ```
592
-
593
- ### Visual Representation
594
-
595
- ```
596
- your-page/
597
- └── components/
598
- └── columns/
599
- ├── index.tsx // Exports all column overrides
600
- ├── name.tsx // Simple value formatting
601
- ├── petInfo.tsx // Complex multi-field column
602
- ├── status.tsx // Conditional rendering column
603
- ├── fullName.tsx // Calculated column
604
- └── date.tsx // Enhanced formatting with row context
605
-
606
- PatternsWizardOverridesProvider
607
- └── value.columns
608
- ├── name
609
- ├── petInfo
610
- ├── status
611
- ├── fullName
612
- └── date
613
- ```
614
-
615
- ### Key Benefits of Row Data Access
616
-
617
- 1. **Reduced Configuration Complexity**: Instead of adding multiple columns, create one complex column that shows related information
618
- 2. **Better User Experience**: Present related data together in a logical, readable format
619
- 3. **Dynamic Content**: Show different content based on the state of other fields
620
- 4. **Data Relationships**: Highlight relationships between different field values in the same entity
621
-
622
- ### Important Guidelines
623
-
624
- - **Performance**: Remember that column functions are called for every row, so keep calculations lightweight
625
- - **Consistency**: When using row data, ensure the column header accurately represents what's displayed
626
- - **Accessibility**: Maintain proper semantic structure when combining multiple values
627
-
628
- ## Components
629
-
630
- Components allow you to create custom rendering for specific elements in the entity page. Each component has a unique `componentId` that corresponds to the ID specified in the layout configuration.
631
-
632
- The custom components receive two essential props:
633
-
634
- 1. **form**: An instance of `UseFormReturn` from react-hook-form (re-exported through `@wix/auto-patterns/form`), giving you access to the form control, methods, and state.
635
- 2. **entity**: A key-value object where keys are field IDs from the collection schema and values are the current field values, providing access to the entity's data.
636
-
637
- Custom components can serve two main purposes:
638
-
639
- ### 1. Standalone Custom Components
640
-
641
- These components can display custom UI elements like notifications, information cards, or any other custom content that isn't directly tied to specific fields. These are useful for adding unique UI elements that enhance the entity page experience.
642
-
643
- ### 2. Field Rendering Overrides
644
-
645
- You can use custom components to override the default rendering of one or more fields. This allows you to:
646
- - Apply custom validation logic
647
- - Create custom input components
648
- - Combine multiple fields into a single UI component
649
- - Add field-specific functionality not available in the default renderers
650
-
651
- ### Using the useController Hook for Field Overrides
652
-
653
- When creating field overrides, use the `useController` hook from `@wix/auto-patterns/form` (a re-export of react-hook-form's hook) to connect your custom component to the form state:
654
-
655
- ```tsx
656
- import { useController } from '@wix/auto-patterns/form'; // Always import from this path, not react-hook-form
657
- ```
658
-
659
- The hook requires:
660
- - **name**: The field name you want to edit (should match the schema field ID)
661
- - **control**: Retrieved from `form.control`
662
- - **defaultValue**: Set from `entity?.[fieldId]` when it exists
663
-
664
- ### Example: Defining a Custom Component
665
-
666
- Here's an example of a custom component that overrides the rendering of the "name" field:
667
-
668
- ```tsx
669
- import React, { FC } from 'react';
670
- import { Box, Card, FormField, Input, Text } from '@wix/design-system';
671
- import { useController } from '@wix/auto-patterns/form';
672
- import { CustomComponentProps } from '@wix/auto-patterns/types';
673
-
674
- export const customNameField: FC<CustomComponentProps> = ({ form, entity }) => {
675
- // Create a controller for the name field
676
- const controller = useController({
677
- name: 'name', // Field ID from the schema
678
- control: form.control, // Form control
679
- defaultValue: entity?.name, // Default value from entity
680
- });
681
-
682
- return (
683
- <FormField
684
- label="Name"
685
- required={true}
686
- charCount={100}
687
- // Connect field state to UI
688
- status={controller.fieldState.invalid ? 'error' : undefined}
689
- statusMessage={controller.fieldState.error?.message}
690
- dataHook={`short-text-${controller.field.name}`}
691
- >
692
- <Input
693
- // Connect field value and onChange
694
- value={controller.field.value}
695
- onChange={(e) => controller.field.onChange(e.target.value)}
696
- dataHook={`short-text-${controller.field.name}`}
697
- />
698
- </FormField>
699
- );
700
- };
701
- ```
702
-
703
-
704
- ### Example: Standalone Component (Not Field-Specific)
705
-
706
- Custom components can also be used to add UI elements not tied to specific fields:
707
-
708
- ```tsx
709
- import React, { FC } from 'react';
710
- import { Box, Card, Text, Button } from '@wix/design-system';
711
- import { CustomComponentProps } from '@wix/auto-patterns/types';
712
-
713
- export const infoCard: FC<CustomComponentProps> = ({ entity }) => {
714
- return (
715
- <Card>
716
- <Card.Content>
717
- <Box direction="vertical" gap={2}>
718
- <Text weight="bold">Important Information</Text>
719
- <Text>
720
- This custom component can display additional information or functionality
721
- that isn't directly tied to a specific field.
722
- </Text>
723
- {entity?.isVaccinated ? (
724
- <Text skin="success">This pet is vaccinated</Text>
725
- ) : (
726
- <Text skin="warning">This pet needs vaccination</Text>
727
- )}
728
- </Box>
729
- </Card.Content>
730
- </Card>
731
- );
732
- };
733
- ```
734
-
735
- ### Connecting Components in the Provider
736
-
737
- In your main page file, import and provide these components via the `PatternsWizardOverridesProvider`:
738
-
739
- ```tsx
740
- import * as components from './components';
741
-
742
- <PatternsWizardOverridesProvider value={{ components }}>
743
- <AutoPatternsApp configuration={config as AppConfig} />
744
- </PatternsWizardOverridesProvider>
745
- ```
746
-
747
- ### Important Guidelines for Custom Components
748
-
749
- 1. **Always import from `@wix/auto-patterns/form`** instead of directly from `react-hook-form`
750
- 2. **Follow react-hook-form best practices** - the underlying infrastructure is built on react-hook-form
751
- 3. **Handle form state properly**:
752
- - Use `controller.fieldState.invalid` for error state
753
- - Use `controller.fieldState.error?.message` for error messages
754
- - Connect `controller.field.value` to input values
755
- - Use `controller.field.onChange` for change handlers
756
- 4. **Component rendering**:
757
- - Choose appropriate design-system components based on the field type
758
- - For text fields: `Input`
759
- - For multi-line text: `InputArea`
760
- - For checkboxes: `Checkbox`
761
- - For dates: `DatePicker`
762
- - For dropdowns: `Dropdown`
763
-
764
- **Important:** Every time you create a new custom component, you must add a corresponding export line to the `./components/customComponents/index.tsx` file. For example, if you create `StatusIndicator.tsx`, you must add `export * from './StatusIndicator';` to the index file.
765
-
766
- ### Understanding Reactivity in Custom Components
767
-
768
- 5. **Reactivity and field value changes (IMPORTANT)**:
769
- - **NEVER rely on the `entity` object for reactive UI** - it is not reactive to form changes
770
- - For any reactive UI that needs to respond to field value changes in real-time:
771
- - Use `form.watch('fieldName')` to observe field changes reactively
772
- - Use `useController` hook when you need both read and write access to a field
773
-
774
- #### Common Reactivity Issues and Solutions
775
-
776
- ##### Example: Conditional Display Based on Field Value
777
-
778
- ```tsx
779
- // ❌ INCORRECT APPROACH (Non-reactive)
780
- const CustomComponent: FC<CustomComponentProps> = ({ form, entity }) => {
781
- // This won't update when the user changes the name in the form
782
- const showSpecialMessage = entity?.name === 'special';
783
-
784
- return (
785
- <Box>
786
- <Input
787
- value={form.getValues('name')}
788
- onChange={(e) => form.setValue('name', e.target.value)}
789
- />
790
-
791
- {showSpecialMessage && (
792
- <Text>Special message for special name!</Text>
793
- )}
794
- </Box>
795
- );
796
- };
797
- ```
798
-
799
- ```tsx
800
- // ✅ CORRECT APPROACH (Reactive)
801
- const CustomComponent: FC<CustomComponentProps> = ({ form, entity }) => {
802
- // This WILL update whenever the name field changes
803
- const nameValue = form.watch('name');
804
- const showSpecialMessage = nameValue === 'special';
805
-
806
- return (
807
- <Box>
808
- <Input
809
- value={nameValue}
810
- onChange={(e) => form.setValue('name', e.target.value)}
811
- />
812
-
813
- {showSpecialMessage && (
814
- <Text>Special message for special name!</Text>
815
- )}
816
- </Box>
817
- );
818
- };
819
- ```
820
-
821
-
822
- ##### When to Use the Entity Object
823
-
824
- The `entity` object is useful for:
825
- - Setting initial values
826
- - Accessing read-only data that doesn't change
827
- - Comparing form state with original values (e.g., detecting if changes were made)
828
- - Initializing form fields with useController's defaultValue parameter
829
-
830
- ```tsx
831
- // Example: Proper use of entity object with useController
832
- const CustomComponent: FC<CustomComponentProps> = ({ form, entity }) => {
833
- // Use entity for initialization via defaultValue
834
- const controller = useController({
835
- name: 'name', // Field ID from the schema
836
- control: form.control,
837
- defaultValue: entity?.name // Initialize from entity
838
- });
839
-
840
- // Use watch for reactive updates
841
- const currentName = controller.field.value;
842
- const hasChanges = entity?.name !== currentName;
843
-
844
- return (
845
- <Box>
846
- <FormField label="Name">
847
- <Input
848
- value={currentName}
849
- onChange={(e) => controller.field.onChange(e.target.value)}
850
- />
851
- </FormField>
852
- {hasChanges && (
853
- <Text size="small">Original value: {entity?.name}</Text>
854
- )}
855
- </Box>
856
- );
857
- };
858
- ```
859
-
860
- ### Visual Representation
861
-
862
- ```
863
- your-page/
864
- └── components/
865
- ├── index.tsx // Exports all component overrides
866
- ├── customNameField.tsx // Field override component
867
- ├── combinedNameFields.tsx // Multiple fields override
868
- └── infoCard.tsx // Standalone component
869
-
870
- PatternsWizardOverridesProvider
871
- └── value.components
872
- ├── customNameField
873
- ├── combinedNameFields
874
- └── infoCard
875
- ```
876
-
877
- By using these component overrides, you can tailor the behavior and appearance of your `AutoPatternsApp` to meet specific requirements beyond what the default rendering provides.
878
-
879
- ---
880
-
881
- # Collection Page Configuration
882
-
883
- ## ⚠️ Collection Page Rules
884
-
885
- - **Components array inside collectionPage must contain exactly one component with a layout array**
886
- - **All collection pages with tables/grids must reference their corresponding entity page via `entityPageId`** in the collection configuration
887
- - **Enable `customColumns` only based on strict logic** - enable if more than 5 columns are defined OR user explicitly requests it, otherwise disable
888
- - **Row click behavior**: By default, clicking a table row navigates to the entity page. Use `onRowClick` configuration only when custom row click behavior is explicitly required
889
- - **When generating config for first time, select up to 3 columns from the schema that best represent the entity**
890
-
891
- ## Components Array
892
-
893
- * Must include **exactly one item**.
894
- * Each component must have:
895
- * `collection`: Collection configuration with `collectionId` and `entityTypeSource: 'cms'`
896
- * `layout`: Array of layout items that determine what components to render
897
-
898
- ## Layout Array
899
-
900
- The `layout` array contains the rendering components for the collection. Each layout item has:
901
- * `type`: Either 'Table' or 'Grid'
902
- * Component-specific configuration (`table` or `grid` object)
903
-
904
- ### Layout Item Types:
905
-
906
- 1. **Table Layout Item** (`type: 'Table'`):
907
- * `table` field contains table-specific configuration
908
- * Used for displaying collection in a **table view**
909
- * Includes columns, actionCell, bulkActionToolbar, etc.
910
-
911
- 2. **Grid Layout Item** (`type: 'Grid'`):
912
- * `grid` field contains grid-specific configuration
913
- * Used for **grid (card) view** of collection
914
- * Includes item configuration for title/subtitle/image fields
915
-
916
- ### Table/Grid View Switch Behavior:
917
- * When **both** Table and Grid layout items are present in the layout array, AutoPatterns automatically adds a Table/Grid view switch control so users can toggle between the two views
918
- * Users can toggle between table and grid views
919
-
920
- ## Table Configuration
921
-
922
- * Used for displaying collection in a **table view**.
923
- * **customColumns.enabled** logic:
924
- * Enable if:
925
- * More than **5 columns** are defined
926
- * OR user **explicitly** requests it
927
- * Otherwise, **disable** (false)
928
-
929
- ## Grid Configuration
930
-
931
- * Used for **grid (card) view** of collection.
932
- * `item.title`, `item.subtitle`, `item.image` fields are **Field IDs** from the schema.
933
- * If the user does not specify, **select the most relevant fields automatically**.
934
- * For grid components, it is strongly recommended to implement a primary action cell with an `update` action that navigates to the entity page. This provides users with an intuitive way to access detailed information and edit individual entities directly from the grid view.
935
-
936
- ---
937
-
938
- # Collection Page Actions
939
-
940
- ## ⚠️ Required Actions
941
-
942
- - **Every collection page must include a create action that navigates to the entity page for adding new entities** - this is essential for user workflow
943
-
944
- The `actions` property is an optional object within the `collectionPage` configuration, but it is strongly recommended to always include primaryActions with a create action for better user experience.
945
-
946
- ## `primaryActions` and `secondaryActions` Structure
947
-
948
- Both `primaryActions` and `secondaryActions` are optional and share the same underlying structure for defining how actions are displayed. They can be configured in one of two ways:
949
-
950
- ### A. Action Layout (`type: "action"`)
951
- * **Description**: This layout is used to display a single, prominent page-level action. For example, a "Create New Item" button.
952
- * **`action.item`**: Contains the configuration for the single action.
953
-
954
- ### B. Action Menu Layout (`type: "menu"`)
955
- * **Description**: This layout groups several page-level actions, often rendered as a dropdown menu or a set of related buttons under a common label.
956
- * **`menu.label`**: A string that serves as the title or accessible label for the group of actions.
957
- * **`menu.items`**: A flat array of action configurations, which can include divider objects for visual separation.
958
-
959
- ## Individual Action Configuration
960
-
961
- Each individual action, whether standalone in an `action` layout or part of an `items` array in a `menu` layout, is defined by the action item structure (see `AppConfig Structure`).
962
-
963
- In addition to these common properties, each action item must specify a `type` which determines the action's behavior and additional required configuration.
964
-
965
- ### 1. `type: "create"`
966
- * **Purpose**: Navigates to an entity page, allowing the user to create a new item in the specified collection.
967
- * **Details**:
968
- * `create.mode`: Must be `'page'`.
969
- * `create.page.id`: Must be the `id` of an existing `entityPage` in your `AppConfig`. This entity page should be set up to handle the creation of new entities for the `collection.collectionId`.
970
-
971
- ### 2. `type: "custom"`
972
- * **Purpose**: Executes custom JavaScript logic defined in your application's overrides.
973
- * **Details**:
974
- * The `custom` object in the configuration is typically empty. The functionality is determined by a custom action resolver function that you implement and register in the `actions` section of your `PatternsWizardOverridesProvider`. The `id` of this action item must exactly match the name (key) of the registered custom action resolver. The resolver will receive parameters including `collectionId`.
975
-
976
- ### 3. `type: "divider"`
977
- * **Purpose**: Creates a visual separator between action groups in menus and lists.
978
- * **Details**:
979
- * Divider actions require no additional configuration beyond `{ "type": "divider" }`.
980
- * Used within flat arrays to create logical groupings.
981
-
982
- ## Note on `secondaryActions`
983
-
984
- `secondaryActions` follow the exact same structural rules (`type: "action"` or `type: "menu"`) and use the same action item options as `primaryActions`. They are typically used for less prominent or less frequently used page-level actions, often rendered in a secondary position or within a "more options" style menu.
985
-
986
- ## Custom Collection Page Action Configuration
987
-
988
- Custom collection page actions execute JavaScript code that you define for collection-level operations. These actions receive parameters that give them access to collection context and utilities. Here's how to implement a custom collection page action:
989
-
990
- 1. First, create the actions folder structure in your page folder:
991
- ```
992
- your-page/
993
- ├── page.tsx
994
- └── components/
995
- └── actions/
996
- ├── index.tsx // Exports all actions
997
- └── exportCollection.tsx // Your custom collection action
998
- ```
999
-
1000
- 2. Create your collection action handler in `exportCollection.tsx`:
1001
- ```typescript
1002
- import { CustomActionCollectionPageActionResolver } from '@wix/auto-patterns';
1003
- import React from 'react';
1004
- import { Download } from '@wix/ui-icons-common';
1005
-
1006
- // IMPORTANT: Function name MUST match the action id in your configuration
1007
- export const exportCollection: CustomActionCollectionPageActionResolver = (params) => {
1008
- const { actionParams, sdk } = params;
1009
- const { collectionId } = actionParams;
1010
-
1011
- return {
1012
- label: 'Export Collection',
1013
- icon: <Download />,
1014
- onClick: () => {
1015
- // sdk is provided to custom action resolvers (see SDK Utilities section)
1016
- const optimisticActions = sdk.getOptimisticActions(collectionId);
1017
- const schema = sdk.getSchema(collectionId);
1018
-
1019
- // Example: Mark entire collection as exported
1020
- optimisticActions.updateAll(
1021
- (item) => ({ lastExported: new Date() }),
1022
- {
1023
- submit: async () => {
1024
- // Your collection export logic here
1025
- console.log(`Exporting collection: ${collectionId}`);
1026
- // Export and update all items on server
1027
- return await schema.actions.bulkUpdate({ lastExported: new Date() });
1028
- },
1029
- successToast: 'Collection exported successfully',
1030
- errorToast: (err, {retry}) => ({
1031
- text: 'Export failed',
1032
- action: { text: 'Retry', onClick: retry }
1033
- })
1034
- }
1035
- );
1036
- },
1037
- };
1038
- };
1039
- ```
1040
-
1041
- 3. Export your action in `actions/index.tsx`:
1042
- ```typescript
1043
- export * from './exportCollection';
1044
- ```
1045
-
1046
- 4. Configure the action in your JSON configuration:
1047
- ```json
1048
- {
1049
- "id": "exportCollection", // MUST match the function name exactly
1050
- "type": "custom", // REQUIRED: Must be exactly "custom"
1051
- "label": "Export Collection", // Optional: Displayed text
1052
- "collection": {
1053
- "collectionId": "WixPets",
1054
- "entityTypeSource": "cms"
1055
- }
1056
- }
1057
- ```
1058
-
1059
- 5. Register your action in the `PatternsWizardOverridesProvider`:
1060
- ```typescript
1061
- import * as actions from './components/actions';
1062
-
1063
- <PatternsWizardOverridesProvider value={{ actions }}>
1064
- <AutoPatternsApp configuration={config as AppConfig} />
1065
- </PatternsWizardOverridesProvider>
1066
- ```
1067
-
1068
- ## Key Points for Custom Collection Page Actions:
1069
- - The action `id` in the configuration MUST exactly match the function name exported from your actions folder
1070
- - The function name and file name should follow a consistent naming convention (e.g., camelCase)
1071
- - The implementation must be exported as a named export (not default export)
1072
- - The implementation must use the `CustomActionCollectionPageActionResolver` type
1073
- - Access collection context through `actionParams.collectionId`
1074
-
1075
- ---
1076
-
1077
- ## Custom Row Click Actions
1078
-
1079
- In addition to page-level actions, you can also customize what happens when users click on individual rows in your collection table. By default, clicking a row navigates to the entity page, but you can override this behavior with custom logic.
1080
-
1081
- **Before You Start:**
1082
- - Only configure `onRowClick` if you need custom behavior (e.g., opening modals, side panels, custom actions)
1083
- - If you just want navigation to entity page, don't configure `onRowClick` - it's the default behavior
1084
- - Once you configure `onRowClick`, you must provide a complete working implementation
1085
-
1086
- ### Configuration
1087
-
1088
- Row click actions are configured at the table level using the `onRowClick` property:
1089
-
1090
- ```json
1091
- {
1092
- "type": "Table",
1093
- "table": {
1094
- "columns": [...],
1095
- "onRowClick": {
1096
- "id": "handleRowClick", // MUST match the function name exactly
1097
- "type": "custom", // REQUIRED: Must be exactly "custom"
1098
- }
1099
- }
1100
- }
1101
- ```
1102
-
1103
- ### Implementation Requirements
1104
-
1105
- ⚠️ **CRITICAL**: When you configure `onRowClick` in your JSON, you MUST provide a complete working implementation. The Auto Patterns framework cannot function without it.
1106
-
1107
- Custom row click actions use the `CustomActionCollectionPageActionOnRowClickResolver` type and MUST return a `ResolvedAction` object with all required properties:
1108
-
1109
- #### Required Return Object Structure:
1110
- ```typescript
1111
- return {
1112
- label: string, // REQUIRED: Action label
1113
- icon: ReactElement, // REQUIRED: Icon component
1114
- onClick: () => void // REQUIRED: Click handler function
1115
- };
1116
- ```
1117
-
1118
- #### Complete Implementation Example:
1119
-
1120
- ```typescript
1121
- import { CustomActionCollectionPageActionOnRowClickResolver } from '@wix/auto-patterns';
1122
- import React from 'react';
1123
- import { More } from '@wix/wix-ui-icons-common';
1124
-
1125
- // IMPORTANT: Function name MUST match the action id in your configuration
1126
- export const handleRowClick: CustomActionCollectionPageActionOnRowClickResolver = (params) => {
1127
- const { actionParams, sdk } = params;
1128
- const { item } = actionParams; // The clicked row's data
1129
-
1130
- return {
1131
- label: 'View Details', // REQUIRED
1132
- icon: <More />, // REQUIRED
1133
- onClick: () => { // REQUIRED
1134
- // Your custom row click logic here
1135
- console.log('Row clicked:', item);
1136
-
1137
- // Example: Show a custom modal, perform an action, etc.
1138
- // You can access all SDK utilities here (see SDK Utilities section)
1139
- const optimisticActions = sdk.getOptimisticActions(sdk.collectionId);
1140
- const schema = sdk.getSchema(sdk.collectionId);
1141
-
1142
- // Your custom logic...
1143
- },
1144
- };
1145
- };
1146
- ```
1147
-
1148
- ### Common Use Cases and Complete Examples
1149
-
1150
- #### 1. Opening a Side Panel Modal
1151
-
1152
- This is a complete working example for opening a side panel when clicking a row:
1153
-
1154
- **Step 1: Create the row click action** (`components/actions/openSidePanel.tsx`):
1155
- ```typescript
1156
- import { CustomActionCollectionPageActionOnRowClickResolver } from '@wix/auto-patterns';
1157
- import React from 'react';
1158
- import { More } from '@wix/wix-ui-icons-common';
1159
-
1160
- export const openSidePanel: CustomActionCollectionPageActionOnRowClickResolver = (params) => {
1161
- const { actionParams, sdk } = params;
1162
- const { item } = actionParams;
1163
-
1164
- return {
1165
- label: 'View Details',
1166
- icon: <More />,
1167
- onClick: () => {
1168
- // Open a custom modal with the item data
1169
- // You need to implement the modal opening mechanism
1170
- // This could be through a modal context, state management, etc.
1171
- console.log('Opening side panel for:', item);
1172
-
1173
- // Example: Using a global modal state (you need to implement this)
1174
- // window.dispatchEvent(new CustomEvent('openSidePanel', { detail: item }));
1175
-
1176
- // Or use a modal service/context that you've set up
1177
- // modalService.openSidePanel(item);
1178
- },
1179
- };
1180
- };
1181
- ```
1182
-
1183
- **Step 2: Configure in JSON**:
1184
- ```json
1185
- {
1186
- "type": "Table",
1187
- "table": {
1188
- "onRowClick": {
1189
- "id": "openSidePanel",
1190
- "type": "custom"
1191
- },
1192
- "columns": [...]
1193
- }
1194
- }
1195
- ```
1196
-
1197
- **Step 3: Export and Register**:
1198
- ```typescript
1199
- // components/actions/index.tsx
1200
- export * from './openSidePanel';
1201
-
1202
- // page.tsx
1203
- import * as actions from './components/actions';
1204
-
1205
- <PatternsWizardOverridesProvider value={{ actions }}>
1206
- <AutoPatternsApp configuration={config as AppConfig} />
1207
- </PatternsWizardOverridesProvider>
1208
- ```
1209
-
1210
- #### 2. Direct Data Manipulation
1211
-
1212
- ```typescript
1213
- export const quickToggle: CustomActionCollectionPageActionOnRowClickResolver = (params) => {
1214
- const { actionParams, sdk } = params;
1215
- const { item } = actionParams;
1216
-
1217
- return {
1218
- label: 'Quick Toggle',
1219
- icon: <Toggle />,
1220
- onClick: () => {
1221
- const optimisticActions = sdk.getOptimisticActions(sdk.collectionId);
1222
- const schema = sdk.getSchema(sdk.collectionId);
1223
-
1224
- // Example: Toggle a boolean field
1225
- const updatedItem = { ...item, isActive: !item.isActive };
1226
-
1227
- optimisticActions.updateOne(updatedItem, {
1228
- submit: async (items) => schema.actions.update(items[0]),
1229
- successToast: `${item.name} toggled successfully`,
1230
- errorToast: (err, {retry}) => ({
1231
- text: 'Toggle failed',
1232
- action: { text: 'Retry', onClick: retry }
1233
- })
1234
- });
1235
- },
1236
- };
1237
- };
1238
- ```
1239
-
1240
- ### Default vs Custom Behavior
1241
-
1242
- **Default Behavior (when `onRowClick` is not configured):**
1243
- - Clicking a row automatically navigates to the entity page
1244
- - Uses the `entityPageId` configuration to determine the target page
1245
- - Passes the selected item's data to the entity page
1246
-
1247
- **Custom Behavior (when `onRowClick` is configured):**
1248
- - Default navigation is **disabled**
1249
- - Your custom action function is executed instead
1250
- - You have complete control over the row click behavior
1251
- - You can still navigate to the entity page programmatically if needed using the SDK navigation utilities
1252
-
1253
- ### Key Points for Custom Row Click Actions:
1254
- - **MANDATORY IMPLEMENTATION**: If you configure `onRowClick` in JSON, you MUST provide a complete working implementation - the framework cannot function without it
1255
- - The action `id` in the configuration MUST exactly match the function name exported from your actions folder
1256
- - The implementation must use the `CustomActionCollectionPageActionOnRowClickResolver` type
1257
- - **Required Return Object**: Must return an object with `label`, `icon`, and `onClick` properties - all are required
1258
- - Access the clicked item's data through `actionParams.item`
1259
- - The implementation must be exported as a named export and registered in your `PatternsWizardOverridesProvider`
1260
- - When `onRowClick` is configured, the default navigation to entity page is completely disabled
1261
- - **Complete Setup Required**: You need to create the action file, export it in the index, and register it in the provider - missing any step will cause errors
1262
-
1263
- ## Validation Checklist for Collection Page Actions
1264
-
1265
- ✓ Every collection page must include a create action.
1266
- ✓ `actions` is an optional property of `collectionPage`.
1267
- ✓ `primaryActions` and `secondaryActions` (if defined) have a valid `type` ("action" or "menu").
1268
- ✓ If `type: "action"`, `action.item` is a valid action item configuration.
1269
- ✓ If `type: "menu"`, `menu.items` is an array of valid action item configurations that can include dividers.
1270
- ✓ Each action item contains a unique `id`, and the full `collection` object (`collectionId`, `entityTypeSource: 'cms'`).
1271
- ✓ Each action item has a supported `type` (`create`, `custom`) and its corresponding configuration block (e.g., `create` block for `type: "create"`).
1272
- ✓ `create` actions specify a `create.page.id` that matches an existing `entityPage` ID in the configuration.
1273
- ✓ `custom` actions (identified by their main `id`) correspond to an action resolver function name registered in the `actions` override.
1274
- ✓ Divider actions use `{ "type": "divider" }` format and require no additional properties.
1275
- ✓ If `onRowClick` is configured in table layout, it must have a valid `id` and `type: "custom"`.
1276
- ✓ **CRITICAL**: Custom row click actions must have corresponding implementations registered in the `actions` override - configuration without implementation will cause errors.
1277
- ✓ Custom row click action implementations must return an object with `label`, `icon`, and `onClick` properties - all are required.
1278
- ✓ Custom row click action implementations must be exported as named exports and included in the actions index file.
1279
- ✓ `onRowClick` is optional - when not configured, rows navigate to entity page by default.
1280
- ✓ **IMPORTANT**: Configuring `onRowClick` completely disables default navigation - you must handle all row click logic in your custom implementation.
1281
-
1282
- ---
1283
-
1284
- ## SDK Utilities
1285
-
1286
- The `sdk` parameter provides access to Auto Patterns utilities and context. Available in custom actions across all action types (ActionCell, BulkActions, CollectionPage actions, and EntityPage Actions).
1287
-
1288
- ### Key SDK Utilities
1289
- The only functions exist in sdk are:
1290
-
1291
- • **closeModal** - `closeModal(): void`
1292
- - Closes the currently open modal
1293
- - Example: `sdk.closeModal()` after saving or canceling
1294
-
1295
- • **getOptimisticActions** - `getOptimisticActions(collectionId): OptimisticActions`
1296
- - Provides optimistic UI updates for immediate user feedback
1297
- - Supports create, update, delete operations with automatic rollback on failure
1298
- - Example: `sdk.getOptimisticActions(sdk.collectionId).updateOne(item, { ... })`
1299
-
1300
- • **getSchema** - `getSchema(collectionId): SchemaConfig | undefined`
1301
- - Access to collection schema information (fields, types, validation)
1302
- - Useful for dynamic operations based on collection structure
1303
- - Example: `const schema = sdk.getSchema(sdk.collectionId)`
1304
-
1305
- • **collectionId** - `string`
1306
- - Current collection context identifier
1307
- - Available in all action contexts for referencing the active collection
1308
- - Example: `sdk.collectionId` to get the current collection ID
1309
-
1310
- ---
1311
-
1312
- ## OptimisticActions
1313
-
1314
- Provides immediate UI updates with automatic server synchronization and error recovery.
1315
-
1316
- ### Usage Rules
1317
-
1318
- **Use OptimisticActions for:**
1319
- - Data modification operations (create, update, delete)
1320
- - Operations requiring immediate visual feedback
1321
-
1322
- **Do NOT use for:**
1323
- - Read-only operations
1324
- - Operations requiring server confirmation first
1325
-
1326
- ### Core Pattern
1327
-
1328
- ```typescript
1329
- // Get instances from SDK (see SDK Utilities section)
1330
- const optimisticActions = sdk.getOptimisticActions(sdk.collectionId);
1331
- const schema = sdk.getSchema(sdk.collectionId);
1332
-
1333
- optimisticActions.operation(items, {
1334
- submit: async (items) => schema.actions.serverMethod(items),
1335
- successToast: 'Success message',
1336
- errorToast: (err, {retry}) => ({ text: 'Error message', action: { text: 'Retry', onClick: retry }})
1337
- });
1338
- ```
1339
-
1340
- ### Available Operations
1341
-
1342
- #### Create Operations
1343
- - `createOne(item: T, params: OptimisticParams<T>): void`
1344
- - `createMany(items: T[], params: OptimisticParams<T>): void`
1345
-
1346
- #### Update Operations
1347
- - `updateOne(item: T, params: OptimisticParams<T>): void`
1348
- - `updateMany(items: T[], params: OptimisticParams<T>): void`
1349
- - `updateAll(transformFn: (item: T) => Partial<T>, params: OptimisticParams<T>): void`
1350
-
1351
- #### Delete Operations
1352
- - `deleteOne(item: T, params: OptimisticParams<T> & { showUndoToast: true }): void`
1353
- - `deleteMany(items: T[], params: OptimisticParams<T> & { showUndoToast: true }): void`
1354
- - `deleteAll(params: OptimisticParams<T> & { showUndoToast: true }): void`
1355
-
1356
- ### Type Definitions
1357
-
1358
- ```typescript
1359
- interface OptimisticParams<T> {
1360
- submit: (items: T[]) => Promise<any>;
1361
- successToast: string | ToastConfig;
1362
- errorToast: (error: Error, actions: { retry: () => void }) => ToastConfig | string;
1363
- showUndoToast?: boolean; // Required: true for delete operations
1364
- }
1365
-
1366
- interface ToastConfig {
1367
- text: string;
1368
- action?: { text: string; onClick: () => void };
1369
- }
1370
- ```
1371
-
1372
- ### Validation Requirements
1373
-
1374
- **Before using optimistic actions:**
1375
- - Verify `sdk.getOptimisticActions(collectionId)` returns valid instance
1376
- - Verify `sdk.getSchema(collectionId)` returns valid schema
1377
- - For delete operations: `showUndoToast: true` is mandatory
1378
- - All `submit` functions must return a Promise
1379
-
1380
- **SDK Parameter:** Available in custom actions and modals. See SDK Utilities section for complete interface.
1381
-
1382
- ---
1383
-
1384
- ## SchemaConfig Usage
1385
-
1386
- SchemaConfig provides complete collection metadata and server actions. Essential for dynamic operations and accessing collection structure information.
1387
-
1388
- ### Key Properties
1389
-
1390
- • **id** - `string`
1391
- - Collection identifier (e.g., "WixPets")
1392
- - Example: `schema.id === "WixPets"`
1393
-
1394
- • **idField** - `string`
1395
- - Primary key field name (usually "_id")
1396
- - Required for all update/delete operations
1397
- - Example: `const id = item[schema.idField]`
1398
-
1399
- • **displayField** - `string`
1400
- - Main field for displaying items (name, title, etc.)
1401
- - Used in UI components for item identification
1402
- - Example: `const label = item[schema.displayField]`
1403
-
1404
- • **fields** - `Record<string, Field | undefined>`
1405
- - Complete field definitions with types and metadata
1406
- - Useful for dynamic form generation or validation
1407
- - Example: `schema.fields.name.type === 'TEXT'`
1408
-
1409
- • **actions** - Server operation functions
1410
- - Pre-configured API calls for CRUD operations
1411
- - Use with optimistic actions for best UX
1412
- - Example: `await schema.actions.update(item)`
1413
-
1414
- ### Available Schema Actions
1415
-
1416
- - schema.actions.create(item) // Create single item
1417
- - schema.actions.update(item) // Update single item
1418
- - schema.actions.delete(itemId) // Delete by ID
1419
- - schema.actions.bulkUpdate(updates) // Update multiple items
1420
- - schema.actions.bulkDelete(itemIds) // Delete multiple items
1421
-
1422
- ### Schema Validation Checklist
1423
-
1424
- Before using schema in operations:
1425
-
1426
- ✓ Check if schema exists: `if (!schema) return;`
1427
- ✓ Verify required fields exist on items
1428
- ✓ Use `schema.idField` for ID operations
1429
- ✓ Use `schema.displayField` for UI display
1430
- ✓ Use `schema.actions` for server operations
1431
-
1432
- ### Common Usage Patterns
1433
-
1434
- - **ActionCell**: Use `schema.actions.update()` or `schema.actions.delete()` for single item operations
1435
- - **BulkActions**: Use `schema.actions.bulkUpdate()` or `schema.actions.bulkDelete()` for multiple items
1436
- - **Dynamic UI**: Use `schema.fields` to build forms or validate data
1437
- - **Error Messages**: Use `schema.displayField` to create meaningful user feedback
1438
-
1439
- ---
1440
-
1441
- ## Filters Configuration Notes
1442
-
1443
- To configure filters in a `collectionPage`, add a `filters` property inside the page's component configuration object. Each filter must reference a valid field by its `fieldId`, and the supported types are:
1444
-
1445
- * `numberConfig`: used with fields of type `NUMBER`
1446
- * `dateConfig`: used with fields of type `DATETIME`
1447
- * `booleanConfig`: used with fields of type `BOOLEAN`
1448
- * `enumConfig`: used with fields of type `ARRAY` or `ARRAY_STRING`
1449
-
1450
- ### Enum Configuration Implementation
1451
-
1452
- When implementing enum filters, you must ask the user to provide the possible option values. Never invent or assume enum values. Here's how to properly handle enumConfig:
1453
-
1454
- #### Example: User-Provided Enum Implementation
1455
-
1456
- 1. First, collect the possible values from the user:
1457
- ```
1458
- User requests: "I need a filter for pet types."
1459
- You ask: "What are the possible values for pet types that should be available in the filter?"
1460
- User responds: "dog, cat, bird, rabbit, fish"
1461
- ```
1462
-
1463
- 2. Then, create the `enumConfig` structure:
1464
- ```json
1465
- "enumConfig": {
1466
- "options": [
1467
- { "value": "dog", "label": "Dog" },
1468
- { "value": "cat", "label": "Cat" },
1469
- { "value": "bird", "label": "Bird" },
1470
- { "value": "rabbit", "label": "Rabbit" },
1471
- { "value": "fish", "label": "Fish" }
1472
- ],
1473
- "selectionMode": "multiple",
1474
- "optionType": "checkbox"
1475
- }
1476
- ```
1477
-
1478
- Notice how the `label` is derived from the `value` by capitalizing the first letter. The user's exact values become the `value` property.
1479
-
1480
- ### Grouping Filters with Section Title
1481
-
1482
- * Filters can be grouped by sections using the `sectionTitle` property.
1483
- * If multiple filter items share the same `sectionTitle`, they will be displayed together in a grouped section in the UI.
1484
- * Filters without a `sectionTitle` will appear in a default section or be displayed individually.
1485
- * Grouping helps maintain clarity, especially when dealing with multiple filter options.
1486
-
1487
- ### Key Guidelines
1488
-
1489
- * **openByDefault**: Automatically expands the filter accordion when the filters panel is opened.
1490
- * **tagLabel**: Specifies the label displayed in a Tag component on the table or grid once the filter is active. For example, if the tagLabel is "Age", the filter display might show: `Age: 7`.
1491
- * **maxInlineFilters**: Limits the number of filters shown inline in the table toolbar. Others are accessible via the panel. Default is 0.
1492
- * **dateConfig.mode**:
1493
-
1494
- * `ONLY_PREDEFINED`: user can select only from preset options
1495
- * `ONLY_CUSTOM`: user must select a custom date range manually (no presets)
1496
- * `COMBINE`: both options available
1497
- * **dateConfig.presets** must be omitted if mode is `ONLY_CUSTOM`.
1498
- * **dateConfig.includeTime**: Controls whether time selection is also enabled alongside date (default is `true`).
1499
-
1500
- ---
1501
-
1502
- # Entity Page Configuration
1503
-
1504
- ## ⚠️ Entity Page Requirements
1505
-
1506
- All entity pages must have:
1507
- - **A route path with descriptive segment and dynamic parameter** (e.g., `/product/:entityId`, `/pet/:entityId`) - **never just `/:entityId`** as this conflicts with collection page routing
1508
- - **A matching `route.params` configuration** that maps the dynamic parameter
1509
- - **A reference to their parent collection page via `parentPageId`**
1510
-
1511
- ## Overview
1512
-
1513
- * Displays details for a **single entity**.
1514
- * Always tied to a single Wix collection.
1515
- * `entityTypeSource` is always `'cms'`.
1516
-
1517
- > The custom actions must be defined inside the `moreActions` array.
1518
-
1519
- > Note: You do not need to define a custom action to navigate to the entity page. This behavior is built-in — clicking on a row in the collection table automatically navigates to the corresponding entity page.
1520
-
1521
- ## Entity Page Layout Configuration
1522
-
1523
- ### Grid System
1524
-
1525
- - **12-Column Grid**: The layout uses a 12-column grid system.
1526
- - The `span` property controls how many columns an item occupies (1-12).
1527
- - When items in a row exceed 12 columns total, the next item wraps to a new line.
1528
- - Example: If an item has `span: 8` and the next has `span: 5`, the second item will start a new line.
1529
-
1530
- ### Layout Structure
1531
-
1532
- - **Main Section**: Contains primary entity information and most important fields.
1533
- - **Sidebar Section**: Contains secondary information, metadata, or supporting content.
1534
- - Both sections support cards that can contain fields, containers, and components.
1535
-
1536
- ### Detailed Layout Content Types
1537
-
1538
- 1. **Field Type**:
1539
- ```typescript
1540
- {
1541
- type: 'field';
1542
- field: {
1543
- span?: number; // How many columns this field occupies (1-12)
1544
- fieldId: string; // Must match a valid field ID from the collection schema
1545
- };
1546
- }
1547
- ```
1548
-
1549
- 2. **Container Type** (for grouping related fields):
1550
- ```typescript
1551
- {
1552
- type: 'container';
1553
- container: {
1554
- span?: number; // How many columns this container occupies (1-12)
1555
- children: LayoutContent[]; // Can nest fields, other containers, or components
1556
- };
1557
- }
1558
- ```
1559
-
1560
- 3. **Component Type** (for custom rendering):
1561
- ```typescript
1562
- {
1563
- type: 'component';
1564
- component: {
1565
- span?: number; // How many columns this component occupies (1-12)
1566
- componentId: string; // ID matching a component override implementation
1567
- };
1568
- }
1569
- ```
1570
-
1571
- ### Layout Best Practices
1572
-
1573
- 1. **Field Grouping**:
1574
- - Group related fields using containers
1575
- - Place frequently used fields at the top
1576
- - Consider the natural flow of data entry
1577
-
1578
- 2. **Main vs. Sidebar Usage**:
1579
- - Main section: Put primary entity information
1580
- - Sidebar: Place secondary information and metadata
1581
-
1582
- 3. **Responsive Considerations**:
1583
- - Use appropriate spans for different field types
1584
- - Text fields often benefit from larger spans
1585
- - Boolean fields can use smaller spans
1586
-
1587
- 4. **Nested Containers**:
1588
- - Use containers to create logical groupings
1589
- - Don't nest containers too deeply for clarity
1590
- - Consider using cards for major sections instead of deeply nested containers
1591
-
1592
- 5. **Image Handling**:
1593
- - For image fields, consider providing more space (larger span)
1594
- - Images are automatically rendered with proper controls when using the field type
1595
-
1596
- ## ⚠️ Common Entity Page Layout Mistakes to Avoid
1597
-
1598
- - Using incorrect span values causing unexpected layout breaks
1599
- - Referencing non-existent field IDs in the layout
1600
- - Creating overly complex nested container structures
1601
- - Failing to properly register component overrides
1602
- - Confusing main and sidebar section usage (putting main content in sidebar)
1603
- - Exceeding 12 total columns in a row without realizing content will wrap
1604
- - Forgetting to specify the `collectionPagePath` value
1605
- - Missing required `type: 'card'` structure in layout sections
1606
-
1607
- ---
1608
-
1609
- ## Entity Page Actions: `moreActions` Support
1610
-
1611
- Entity pages in AutoPatternsApp support not only a primary action (such as "Save" or "Delete") but also a flexible set of **more actions** (sometimes called "secondary actions" or `moreActions`). These allow you to provide additional contextual actions for the entity, such as custom logic, or grouped actions.
1612
-
1613
- > **Note:** All custom actions for entity pages must be placed in the `moreActions` array. Do not place custom actions as primary actions on entity pages. The `moreActions` array is the only supported location for custom actions on entity pages.
1614
-
1615
- ### Configuration Structure
1616
-
1617
- - The `moreActions` property on the entity page is an **array** of action configurations that can include divider objects for visual separation.
1618
- - Each action in `moreActions` is a Custom Action (type: "custom") or a Divider (type: "divider")
1619
-
1620
- #### Example: Adding custom actions with dividers to an entity page
1621
- ```json
1622
- {
1623
- "type": "entityPage",
1624
- "entityPage": {
1625
- // ... other config ...
1626
- "moreActions": [
1627
- {
1628
- "id": "sendEmail",
1629
- "type": "custom",
1630
- "label": "Send Email"
1631
- },
1632
- {
1633
- "id": "exportData",
1634
- "type": "custom",
1635
- "label": "Export Data"
1636
- },
1637
- { "type": "divider" },
1638
- {
1639
- "id": "archiveEntity",
1640
- "type": "custom",
1641
- "label": "Archive"
1642
- }
1643
- ]
1644
- }
1645
- }
1646
- ```
1647
-
1648
- ---
1649
-
1650
- ### CustomEntityPageMoreActionsActionResolver
1651
-
1652
- The `CustomEntityPageMoreActionsActionResolver` type is used to implement custom actions for the `moreActions` menu on entity pages in AutoPatternsApp. Each action in the `moreActions` array must have a corresponding resolver function registered in your overrides.
1653
-
1654
- #### Function Signature
1655
-
1656
- ```typescript
1657
- import { CustomEntityPageMoreActionsActionResolver } from '@wix/auto-patterns/types';
1658
-
1659
- export const myMoreAction: CustomEntityPageMoreActionsActionResolver = (params) => {
1660
- const { actionParams: { entity, form } , sdk } = params;
1661
-
1662
- return {
1663
- label: 'My More Action',
1664
- icon: <MyIcon />, // optional
1665
- onClick: () => {
1666
- // Your custom logic here
1667
- },
1668
- };
1669
- };
1670
- ```
1671
-
1672
- - **entity**: The current entity data (all field values). In actionParams.
1673
- - **form**: The react-hook-form instance for the entity page. In actionParams.
1674
- - **sdk**: The AutoPatterns SDK (see SDK Utilities section).
1675
-
1676
- ---
1677
-
1678
- #### Key Points for CustomEntityPageMoreActionsActionResolver
1679
-
1680
- - The action `id` in the configuration MUST exactly match the function name exported from your actions folder.
1681
- - The implementation must use the `CustomEntityPageMoreActionsActionResolver` type.
1682
- - The implementation must be exported as a named export (not default export).
1683
- - The function receives `{ actionParams, sdk }` as parameters.
1684
- - The returned object must include at least a `label` and an `onClick` handler (optionally an `icon`).
1685
-
1686
- ---
1687
-
1688
- #### Validation Checklist for More Actions
1689
-
1690
- ✓ Each action in `moreActions` has a unique `id` and correct `type` value
1691
- ✓ Each action type only includes its required field(s)
1692
- ✓ Custom actions match implementations in overrides
1693
- ✓ The resolver is exported and registered in the `actions` property of your `PatternsWizardOverridesProvider`
1694
- ✓ The function signature matches `CustomEntityPageMoreActionsActionResolver`
1695
- ✓ The returned object includes `label`, `onClick`, and optionally `icon`
1696
-
1697
- ---
1698
-
1699
- **Summary:**
1700
- The `CustomEntityPageMoreActionsActionResolver` enables you to add custom, contextual actions to the "More Actions" menu on your entity pages. Implement the resolver, export it, and reference it by `id` in your config for seamless integration.
1701
-
1702
- ---