@wix/auto-patterns 1.17.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 (43) hide show
  1. package/dist/cjs/dataSourceAdapters/cms/cmsAdapter.js +0 -2
  2. package/dist/cjs/dataSourceAdapters/cms/cmsAdapter.js.map +1 -1
  3. package/dist/cjs/dataSourceAdapters/cms/fetchCmsData.js.map +1 -1
  4. package/dist/cjs/dataSourceAdapters/cms/filterUtils.js.map +1 -1
  5. package/dist/cjs/dataSourceAdapters/cms/sortUtils.js.map +1 -1
  6. package/dist/cjs/hooks/useColumns.js +7 -5
  7. package/dist/cjs/hooks/useColumns.js.map +1 -1
  8. package/dist/cjs/types/types.js.map +1 -1
  9. package/dist/docs/action_cell.md +1 -1
  10. package/dist/docs/app_config_structure.md +65 -1
  11. package/dist/docs/auto-patterns-guide.md +358 -76
  12. package/dist/docs/bulk_actions.md +1 -1
  13. package/dist/docs/collection_page.md +1 -1
  14. package/dist/docs/config_schema.md +184 -0
  15. package/dist/docs/custom_overrides.md +163 -4
  16. package/dist/docs/index.md +5 -7
  17. package/dist/docs/schema_config.md +174 -0
  18. package/dist/docs/sdk_utilities.md +97 -0
  19. package/dist/docs/wix_fqdn_custom_data_source.md +201 -0
  20. package/dist/esm/dataSourceAdapters/cms/cmsAdapter.js +0 -2
  21. package/dist/esm/dataSourceAdapters/cms/cmsAdapter.js.map +1 -1
  22. package/dist/esm/dataSourceAdapters/cms/fetchCmsData.js.map +1 -1
  23. package/dist/esm/dataSourceAdapters/cms/filterUtils.js.map +1 -1
  24. package/dist/esm/dataSourceAdapters/cms/sortUtils.js.map +1 -1
  25. package/dist/esm/hooks/useColumns.js +3 -1
  26. package/dist/esm/hooks/useColumns.js.map +1 -1
  27. package/dist/esm/types/types.js.map +1 -1
  28. package/dist/types/dataSourceAdapters/cms/cmsAdapter.d.ts.map +1 -1
  29. package/dist/types/dataSourceAdapters/cms/fetchCmsData.d.ts +2 -3
  30. package/dist/types/dataSourceAdapters/cms/fetchCmsData.d.ts.map +1 -1
  31. package/dist/types/dataSourceAdapters/cms/filterUtils.d.ts +3 -4
  32. package/dist/types/dataSourceAdapters/cms/filterUtils.d.ts.map +1 -1
  33. package/dist/types/dataSourceAdapters/cms/sortUtils.d.ts +2 -3
  34. package/dist/types/dataSourceAdapters/cms/sortUtils.d.ts.map +1 -1
  35. package/dist/types/hooks/useColumns.d.ts.map +1 -1
  36. package/dist/types/types/types.d.ts +13 -3
  37. package/dist/types/types/types.d.ts.map +1 -1
  38. package/package.json +4 -4
  39. package/dist/docs/recipe-bulk-operations.md +0 -1352
  40. package/dist/docs/recipe-crud-operations.md +0 -805
  41. package/dist/docs/recipe-customization.md +0 -1703
  42. package/dist/docs/recipe-first-dashboard.md +0 -795
  43. package/dist/docs/sdk_and_schema.md +0 -215
@@ -0,0 +1,184 @@
1
+ ## SchemaConfig Usage
2
+
3
+ SchemaConfig provides complete collection metadata and server actions. Essential for dynamic operations and accessing collection structure information.
4
+
5
+ ### TypeScript Interface Definition
6
+
7
+ ```typescript
8
+ export interface SchemaConfig {
9
+ id: string;
10
+ fields: Record<string, Field | undefined>;
11
+ displayField: string;
12
+ idField: string;
13
+ actions: {
14
+ get: (entityId: string) => Promise<any>;
15
+ create: (newEntity: Partial<any>) => Promise<any>;
16
+ update: (updatedEntity: any) => Promise<any>;
17
+ delete: (entityId: string) => Promise<any>;
18
+ bulkDelete: (entityIds: string[]) => Promise<any>;
19
+ find: (
20
+ query: ComputedQuery<any>,
21
+ options?: {
22
+ searchableFieldIds?: string[];
23
+ filterFieldMapping?: Record<string, { fieldId: string }>;
24
+ },
25
+ ) => Promise<{ items: any[]; total: number }>;
26
+ };
27
+ }
28
+ ```
29
+
30
+ ### Supporting Type Definitions
31
+
32
+ ```typescript
33
+ export type PatternsFieldType =
34
+ | 'SHORT_TEXT'
35
+ | 'LONG_TEXT'
36
+ | 'NUMBER'
37
+ | 'BOOLEAN'
38
+ | 'DATE'
39
+ | 'DATETIME'
40
+ | 'URL'
41
+ | 'ARRAY'
42
+ | 'REFERENCE'
43
+ | 'IMAGE';
44
+
45
+ interface BaseField {
46
+ id: string;
47
+ displayName: string;
48
+ validation?: {
49
+ numberRange?: NumberRange;
50
+ stringLengthRange?: StringLengthRange;
51
+ required: boolean;
52
+ };
53
+ capabilities: {
54
+ supportedQueryOperators: QueryOperator[];
55
+ sortable: boolean;
56
+ };
57
+ }
58
+
59
+ export interface ReferenceField extends BaseField {
60
+ type: 'REFERENCE';
61
+ referenceMetadata: {
62
+ referencedCollectionId: string;
63
+ };
64
+ }
65
+
66
+ export interface NonReferenceField extends BaseField {
67
+ type: Exclude<PatternsFieldType, 'REFERENCE'>;
68
+ }
69
+
70
+ export type Field = ReferenceField | NonReferenceField;
71
+ ```
72
+
73
+ ### Key Properties
74
+
75
+ • **id** - `string`
76
+ - Collection identifier (e.g., "WixPets")
77
+ - Example: `schema.id === "WixPets"`
78
+
79
+ • **idField** - `string`
80
+ - Primary key field name (usually "_id")
81
+ - Required for all update/delete operations
82
+ - Example: `const id = item[schema.idField]`
83
+
84
+ • **displayField** - `string`
85
+ - Main field for displaying items (name, title, etc.)
86
+ - Used in UI components for item identification
87
+ - Example: `const label = item[schema.displayField]`
88
+
89
+ • **fields** - `Record<string, Field | undefined>`
90
+ - Complete field definitions with types and metadata
91
+ - Useful for dynamic form generation or validation
92
+ - Each field contains type information, validation rules, and capabilities
93
+ - Example: `schema.fields.name.type === 'SHORT_TEXT'`
94
+
95
+ • **actions** - Server operation functions
96
+ - Pre-configured API calls for CRUD operations
97
+ - Use with optimistic actions for best UX
98
+ - All actions return Promises and handle server communication
99
+ - Example: `await schema.actions.update(item)`
100
+
101
+ ### Available Schema Actions
102
+
103
+ #### Individual Entity Operations
104
+ - **schema.actions.get(entityId)** - Retrieve a single entity by ID
105
+ - **schema.actions.create(newEntity)** - Create a new entity
106
+ - **schema.actions.update(updatedEntity)** - Update an existing entity
107
+ - **schema.actions.delete(entityId)** - Delete a single entity by ID
108
+
109
+ #### Bulk Operations
110
+ - **schema.actions.bulkDelete(entityIds)** - Delete multiple entities by their IDs
111
+
112
+ #### Query Operations
113
+ - **schema.actions.find(query, options)** - Search and filter entities
114
+ - `query`: ComputedQuery object with filtering and sorting criteria
115
+ - `options.searchableFieldIds`: Array of field IDs that support text search
116
+ - `options.filterFieldMapping`: Maps filter IDs to actual field IDs for complex filtering
117
+ - Returns: `{ items: any[], total: number }`
118
+
119
+ ### Field Type Information
120
+
121
+ Each field in the `fields` record contains:
122
+
123
+ - **id**: Unique field identifier
124
+ - **displayName**: Human-readable field name
125
+ - **type**: One of the supported `PatternsFieldType` values
126
+ - **validation**: Optional validation rules including:
127
+ - `numberRange`: Min/max values for numeric fields
128
+ - `stringLengthRange`: Min/max length for text fields
129
+ - `required`: Whether the field is mandatory
130
+ - **capabilities**: Field behavior configuration:
131
+ - `supportedQueryOperators`: Array of operators this field supports for filtering
132
+ - `sortable`: Whether this field can be used for sorting
133
+
134
+ ### Reference Fields
135
+
136
+ Reference fields have additional metadata:
137
+ - **referenceMetadata.referencedCollectionId**: ID of the collection being referenced
138
+ - Used for establishing relationships between different collections
139
+
140
+ ### Schema Validation Checklist
141
+
142
+ Before using schema in operations:
143
+
144
+ ✓ Check if schema exists: `if (!schema) return;`
145
+ ✓ Verify required fields exist on items
146
+ ✓ Use `schema.idField` for ID operations
147
+ ✓ Use `schema.displayField` for UI display
148
+ ✓ Use `schema.actions` for server operations
149
+ ✓ Check field capabilities before applying filters or sorting
150
+
151
+ ### Common Usage Patterns
152
+
153
+ - **ActionCell**: Use `schema.actions.update()` or `schema.actions.delete()` for single item operations
154
+ - **BulkActions**: Use `schema.actions.bulkDelete()` for multiple items
155
+ - **Dynamic UI**: Use `schema.fields` to build forms or validate data
156
+ - **Error Messages**: Use `schema.displayField` to create meaningful user feedback
157
+ - **Field Validation**: Use `schema.fields[fieldId].validation` for form validation rules
158
+ - **Query Building**: Use `schema.fields[fieldId].capabilities.supportedQueryOperators` to build dynamic filters
159
+
160
+ ### Example Usage
161
+
162
+ ```typescript
163
+ // Using schema for dynamic operations
164
+ const handleUpdateEntity = async (updatedItem: any) => {
165
+ const schema = sdk.getSchema(collectionId);
166
+
167
+ if (!schema) {
168
+ throw new Error('Schema not available');
169
+ }
170
+
171
+ // Validate required fields
172
+ const nameField = schema.fields.name;
173
+ if (nameField?.validation?.required && !updatedItem.name) {
174
+ throw new Error(`${nameField.displayName} is required`);
175
+ }
176
+
177
+ // Perform update
178
+ await schema.actions.update(updatedItem);
179
+
180
+ // Show success message using display field
181
+ const displayValue = updatedItem[schema.displayField];
182
+ console.log(`Updated ${displayValue} successfully`);
183
+ };
184
+ ```
@@ -28,10 +28,13 @@ your-page/
28
28
  │ ├── index.tsx
29
29
  │ ├── name.ts
30
30
  │ └── date.ts
31
- └── customComponents/ // Custom entity page components
31
+ ├── customComponents/ // Custom entity page components
32
+ │ ├── index.tsx
33
+ │ ├── CustomNameField.tsx
34
+ │ └── InfoCard.tsx
35
+ └── customDataSources/ // Custom data sources
32
36
  ├── index.tsx
33
- ├── CustomNameField.tsx
34
- └── InfoCard.tsx
37
+ └── myCustomDataSource.ts
35
38
  ```
36
39
 
37
40
  ### Importing Overrides in Your Page
@@ -43,8 +46,9 @@ import * as modals from './components/modals';
43
46
  import * as actions from './components/actions';
44
47
  import * as columns from './components/columns';
45
48
  import * as components from './components/customComponents';
49
+ import * as customDataSources from './components/customDataSources';
46
50
 
47
- <PatternsWizardOverridesProvider value={{ modals, actions, columns, components }}>
51
+ <PatternsWizardOverridesProvider value={{ modals, actions, columns, components, customDataSources }}>
48
52
  <AutoPatternsApp configuration={config as AppConfig} />
49
53
  </PatternsWizardOverridesProvider>
50
54
  ```
@@ -58,6 +62,7 @@ For example:
58
62
  - Adding a new modal → Update `./components/modals/index.tsx`
59
63
  - Adding a new column override → Update `./components/columns/index.tsx`
60
64
  - Adding a new custom component → Update `./components/customComponents/index.tsx`
65
+ - Adding a new custom data source → Update `./components/customDataSources/index.tsx`
61
66
 
62
67
  Without updating the index files, your implementations won't be available to the `PatternsWizardOverridesProvider`.
63
68
 
@@ -509,3 +514,157 @@ PatternsWizardOverridesProvider
509
514
  ```
510
515
 
511
516
  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.
517
+
518
+ ## Custom Data Sources
519
+
520
+ Custom data sources allow you to connect AutoPatternsApp to any data source beyond the default CMS collections. This enables you to integrate with external APIs, custom databases, or any other data sources that require custom implementation.
521
+
522
+ ### Configuration Structure
523
+
524
+ When implementing a custom data source, you need to modify the `collection` configuration in your AppConfig:
525
+
526
+ ```json
527
+ {
528
+ "collection": {
529
+ "collectionId": "myCustomCollection",
530
+ "entityTypeSource": "custom",
531
+ "custom": {
532
+ "id": "myCustomDataSource"
533
+ }
534
+ }
535
+ }
536
+ ```
537
+
538
+ **Key Properties:**
539
+ - `entityTypeSource`: Must be set to `"custom"` instead of `"cms"`
540
+ - `custom.id`: A unique identifier for your custom data source implementation
541
+
542
+ ### Custom Data Source Override Structure
543
+
544
+ Custom data sources are implemented through the `customDataSources` property in your `PatternsWizardOverridesProvider`:
545
+
546
+ ```tsx
547
+ <PatternsWizardOverridesProvider value={{
548
+ customDataSources: {
549
+ myCustomDataSource: async (collectionId: string, context: any) => {
550
+ return customSchemaConfig; // Must return a SchemaConfig object
551
+ }
552
+ }
553
+ }}>
554
+ <AutoPatternsApp configuration={config as AppConfig} />
555
+ </PatternsWizardOverridesProvider>
556
+ ```
557
+
558
+ ### Implementation Components
559
+
560
+ #### Custom Data Source Function
561
+
562
+ You must implement a custom data source function that:
563
+ - Takes `collectionId` and `context` parameters
564
+ - Returns a Promise that resolves to a `SchemaConfig` object
565
+ - The `SchemaConfig` object must include:
566
+ - **id**: Collection identifier
567
+ - **fields**: Field definitions with types and metadata
568
+ - **displayField**: Primary field for displaying items
569
+ - **idField**: Primary key field name
570
+ - **actions**: CRUD operation functions that handle:
571
+ - Individual entity operations (get, create, update, delete)
572
+ - Bulk operations (bulkDelete)
573
+ - Query operations with pagination, search, filtering, and sorting
574
+
575
+ ### Example Implementation Structure
576
+
577
+ ```tsx
578
+ // customDataSources/myCustomDataSource.ts
579
+ export const myCustomDataSource = async (collectionId: string, context: any) => {
580
+ return {
581
+ id: 'myCustomCollection',
582
+ fields: {
583
+ // Field definitions based on your data source schema
584
+ },
585
+ displayField: 'name',
586
+ idField: '_id',
587
+ actions: {
588
+ get: async (entityId: string) => { /* Implementation */ },
589
+ create: async (newEntity: any) => { /* Implementation */ },
590
+ update: async (updatedEntity: any) => { /* Implementation */ },
591
+ delete: async (entityId: string) => { /* Implementation */ },
592
+ bulkDelete: async (entityIds: string[]) => { /* Implementation */ },
593
+ find: async (query: Query, options?: any) => { /* Implementation */ }
594
+ }
595
+ };
596
+ };
597
+ ```
598
+
599
+ ### Field Type Mapping
600
+
601
+ When implementing custom data sources, you need to map your data source field types to AutoPatterns field types:
602
+
603
+ - **Text fields** → `'SHORT_TEXT'` or `'LONG_TEXT'`
604
+ - **Numeric fields** → `'NUMBER'`
605
+ - **Boolean fields** → `'BOOLEAN'`
606
+ - **Date fields** → `'DATE'` or `'DATETIME'`
607
+ - **Image fields** → `'IMAGE'`
608
+ - **Array fields** → `'ARRAY'`
609
+ - **Reference fields** → `'REFERENCE'`
610
+ - **URL fields** → `'URL'`
611
+
612
+ ### Error Handling
613
+
614
+ Custom data sources should include proper error handling:
615
+
616
+ ```tsx
617
+ actions: {
618
+ get: async (entityId: string) => {
619
+ try {
620
+ const result = await yourDataSourceCall(entityId);
621
+ return result;
622
+ } catch (error) {
623
+ throw new Error(`Failed to fetch entity: ${error.message}`);
624
+ }
625
+ }
626
+ }
627
+ ```
628
+
629
+ ### Validation Requirements
630
+
631
+ - **Function Signature**: Custom data source must be a function with signature `(collectionId: string, context: any) => Promise<SchemaConfig>`
632
+ - **Return Type**: Must return a Promise that resolves to a complete SchemaConfig object
633
+ - All schema actions must return Promises
634
+ - Field IDs must match between schema definition and data source responses
635
+ - The `find` action must support the complete Query interface
636
+ - Custom data sources must handle pagination, search, and filtering
637
+ - Error responses should be meaningful and actionable
638
+
639
+ ### Folder Structure for Custom Data Sources
640
+
641
+ ```
642
+ your-page/
643
+ ├── page.tsx // Your main page component
644
+ ├── MyCollectionConfig.patterns.json // Configuration file
645
+ └── components/ // Page-specific components folder
646
+ ├── index.tsx // Exports all overrides for easy importing
647
+ ├── customDataSources/ // Custom data sources
648
+ │ ├── index.tsx
649
+ │ └── myCustomDataSource.ts
650
+ ├── actions/ // Custom actions
651
+ │ ├── index.tsx
652
+ │ └── myCustomAction.tsx
653
+ └── columns/ // Column overrides
654
+ ├── index.tsx
655
+ └── myColumn.tsx
656
+ ```
657
+
658
+ ### Registering Custom Data Sources
659
+
660
+ In your page component, import and register your custom data sources:
661
+
662
+ ```tsx
663
+ import * as customDataSources from './components/customDataSources';
664
+
665
+ <PatternsWizardOverridesProvider value={{ customDataSources }}>
666
+ <AutoPatternsApp configuration={config as AppConfig} />
667
+ </PatternsWizardOverridesProvider>
668
+ ```
669
+
670
+ **Important:** Every time you create a new custom data source, you must add a corresponding export line to the `./components/customDataSources/index.tsx` file. For example, if you create `myDataSource.ts`, you must add `export * from './myDataSource';` to the index file.
@@ -30,10 +30,6 @@ This index maps user requests to the appropriate section IDs for fetching releva
30
30
  **Topics**: Page-level actions, create actions, custom collection actions, action menus
31
31
  **Keywords**: page-level actions, collection actions, create actions, adding new items, primaryActions, secondaryActions, action menus, custom actions, navigation
32
32
 
33
- ### ID: `sdk_and_schema`
34
- **Topics**: SDK utilities, optimistic actions, schema usage, filters, server operations
35
- **Keywords**: SDK utilities, programmatic operations, optimistic actions, immediate UI updates, schema access, collection metadata, server operations, data manipulation, filters configuration, error handling, toast notifications
36
-
37
33
  ### ID: `action_cell`
38
34
  **Topics**: Row-level actions, update/delete actions, custom row actions, action cell configuration
39
35
  **Keywords**: row actions, item-level operations, edit, delete, actionCell, row-level operations, update actions, delete confirmations, custom row actions, inline actions, secondary actions
@@ -58,15 +54,17 @@ This index maps user requests to the appropriate section IDs for fetching releva
58
54
  **Topics**: Customization, overrides, custom components, column customization, folder structure
59
55
  **Keywords**: customization, custom functionality, overrides, extending functionality, custom components, custom rendering, column overrides, folder structure, organization, row data access
60
56
 
57
+ ### ID: `wix_fqdn_custom_data_source`
58
+ **Topics**: FQDN-based custom data sources, Wix Business API integration, schema mapping, custom data source implementation
59
+ **Keywords**: FQDN, Wix Business API, custom data source, schema mapping, client library, field type mapping, custom implementation, entityTypeSource custom, Business API integration, schema extraction
60
+
61
61
  ---
62
62
 
63
63
  ## Recipe Section IDs (Step-by-Step Guides)
64
64
 
65
65
  | Recipe Topic | Section ID | Use Case |
66
66
  |--------------|------------|----------|
67
- | 🚀 First Dashboard | `recipe-first-dashboard` | Complete setup from scratch |
68
- | ⚡ CRUD Operations | `recipe-crud-operations` | Add Create/Edit/Delete functionality |
69
- | 📦 Bulk Operations | `recipe-bulk-operations` | Multi-select and bulk actions |
67
+ | 🚀 First Dashboard | `recipe-first-dashboard` | Complete setup from scratch, replacing existing pages with dashboard pages, creating new dashboard pages, setting up collection management interfaces, building admin panels, or implementing any data-driven dashboard interface |
70
68
  | 🎨 Complete Customization | `recipe-customization` | Basic to advanced customization and integrations |
71
69
 
72
70
  ## LLM Usage Instructions
@@ -0,0 +1,174 @@
1
+ ## SchemaConfig Usage
2
+
3
+ SchemaConfig provides complete collection metadata and server actions. Essential for dynamic operations and accessing collection structure information.
4
+
5
+ ### TypeScript Interface Definition
6
+
7
+ ```typescript
8
+ export interface SchemaConfig {
9
+ id: string;
10
+ fields: Record<string, Field | undefined>;
11
+ displayField: string;
12
+ idField: string;
13
+ actions: {
14
+ get: (entityId: string) => Promise<any>;
15
+ create: (newEntity: Partial<any>) => Promise<any>;
16
+ update: (updatedEntity: any) => Promise<any>;
17
+ delete: (entityId: string) => Promise<any>;
18
+ bulkDelete: (entityIds: string[]) => Promise<any>;
19
+ find: (
20
+ query: Query,
21
+ options?: {
22
+ searchableFieldIds?: string[];
23
+ filterFieldMapping?: Record<string, { fieldId: string }>;
24
+ },
25
+ ) => Promise<{ items: any[]; total: number }>;
26
+ };
27
+ }
28
+
29
+ export interface Query {
30
+ limit: number; // Maximum number of items to return per request (controls page size)
31
+ offset: number; // Number of items to skip from the beginning (for pagination)
32
+ page: number; // Current page number (1-based, works with limit for pagination)
33
+ search?: string; // Text search query applied to searchable fields
34
+ cursor?: string | null; // Cursor-based pagination token (alternative to offset-based pagination)
35
+ filters: Record<string, any>; // Field-specific filter conditions (keys = field IDs, values = filter criteria)
36
+ sort?: { // Sorting configuration for result ordering
37
+ fieldName: string; // Field ID to sort by (must be sortable per field capabilities)
38
+ order: 'asc' | 'desc'; // Sort direction
39
+ }[];
40
+ }
41
+ ```
42
+
43
+ ### Supporting Type Definitions
44
+
45
+ ```typescript
46
+ export type PatternsFieldType =
47
+ | 'SHORT_TEXT'
48
+ | 'LONG_TEXT'
49
+ | 'NUMBER'
50
+ | 'BOOLEAN'
51
+ | 'DATE'
52
+ | 'DATETIME'
53
+ | 'URL'
54
+ | 'ARRAY'
55
+ | 'REFERENCE'
56
+ | 'IMAGE';
57
+
58
+ interface BaseField {
59
+ id: string;
60
+ displayName: string;
61
+ validation?: {
62
+ numberRange?: NumberRange;
63
+ stringLengthRange?: StringLengthRange;
64
+ required: boolean;
65
+ };
66
+ capabilities: {
67
+ supportedQueryOperators: QueryOperator[];
68
+ sortable: boolean;
69
+ };
70
+ }
71
+
72
+ export interface ReferenceField extends BaseField {
73
+ type: 'REFERENCE';
74
+ referenceMetadata: {
75
+ referencedCollectionId: string;
76
+ };
77
+ }
78
+
79
+ export interface NonReferenceField extends BaseField {
80
+ type: Exclude<PatternsFieldType, 'REFERENCE'>;
81
+ }
82
+
83
+ export type Field = ReferenceField | NonReferenceField;
84
+ ```
85
+
86
+ ### Key Properties
87
+
88
+ • **id** - `string`
89
+ - Collection identifier (e.g., "WixPets")
90
+ - Example: `schema.id === "WixPets"`
91
+
92
+ • **idField** - `string`
93
+ - Primary key field name (usually "_id")
94
+ - Required for all update/delete operations
95
+ - Example: `const id = item[schema.idField]`
96
+
97
+ • **displayField** - `string`
98
+ - Main field for displaying items (name, title, etc.)
99
+ - Used in UI components for item identification
100
+ - Example: `const label = item[schema.displayField]`
101
+
102
+ • **fields** - `Record<string, Field | undefined>`
103
+ - Complete field definitions with types and metadata
104
+ - Useful for dynamic form generation or validation
105
+ - Each field contains type information, validation rules, and capabilities
106
+ - Example: `schema.fields.name.type === 'SHORT_TEXT'`
107
+
108
+ • **actions** - Server operation functions
109
+ - Pre-configured API calls for CRUD operations
110
+ - Use with optimistic actions for best UX
111
+ - All actions return Promises and handle server communication
112
+ - Example: `await schema.actions.update(item)`
113
+
114
+ ### Available Schema Actions
115
+
116
+ #### Individual Entity Operations
117
+ - **schema.actions.get(entityId)** - Retrieve a single entity by ID
118
+ - **schema.actions.create(newEntity)** - Create a new entity
119
+ - **schema.actions.update(updatedEntity)** - Update an existing entity
120
+ - **schema.actions.delete(entityId)** - Delete a single entity by ID
121
+
122
+ #### Bulk Operations
123
+ - **schema.actions.bulkDelete(entityIds)** - Delete multiple entities by their IDs
124
+
125
+ #### Query Operations
126
+ - **schema.actions.find(query, options)** - Search and filter entities
127
+ - `query`: Query object with pagination, filtering, sorting, and search criteria (see Query Interface section)
128
+ - `options.searchableFieldIds`: Array of field IDs that support text search
129
+ - `options.filterFieldMapping`: Maps filter IDs to actual field IDs for complex filtering
130
+ - Returns: `{ items: any[], total: number }`
131
+
132
+ ### Field Type Information
133
+
134
+ Each field in the `fields` record contains:
135
+
136
+ - **id**: Unique field identifier
137
+ - **displayName**: Human-readable field name
138
+ - **type**: One of the supported `PatternsFieldType` values
139
+ - **validation**: Optional validation rules including:
140
+ - `numberRange`: Min/max values for numeric fields
141
+ - `stringLengthRange`: Min/max length for text fields
142
+ - `required`: Whether the field is mandatory
143
+ - **capabilities**: Field behavior configuration:
144
+ - `supportedQueryOperators`: Array of operators this field supports for filtering
145
+ - `sortable`: Whether this field can be used for sorting
146
+
147
+ ### Reference Fields
148
+
149
+ Reference fields have additional metadata:
150
+ - **referenceMetadata.referencedCollectionId**: ID of the collection being referenced
151
+ - Used for establishing relationships between different collections
152
+
153
+ ### Schema Validation Checklist
154
+
155
+ Before using schema in operations:
156
+
157
+ ✓ Check if schema exists: `if (!schema) return;`
158
+ ✓ Verify required fields exist on items
159
+ ✓ Use `schema.idField` for ID operations
160
+ ✓ Use `schema.displayField` for UI display
161
+ ✓ Use `schema.actions` for server operations
162
+ ✓ Check field capabilities before applying filters or sorting
163
+
164
+ ### Common Usage Patterns
165
+
166
+ - **ActionCell**: Use `schema.actions.update()` or `schema.actions.delete()` for single item operations
167
+ - **BulkActions**: Use `schema.actions.bulkDelete()` for multiple items
168
+ - **Dynamic UI**: Use `schema.fields` to build forms or validate data
169
+ - **Error Messages**: Use `schema.displayField` to create meaningful user feedback
170
+ - **Field Validation**: Use `schema.fields[fieldId].validation` for form validation rules
171
+ - **Query Building**: Use `schema.fields[fieldId].capabilities.supportedQueryOperators` to build dynamic filters
172
+ - **Data Fetching**: Use `schema.actions.find()` with Query interface for complex data retrieval with pagination, search, and filtering
173
+ - **Pagination**: Combine `limit`, `offset`, and `page` properties in Query for consistent pagination behavior
174
+ - **Search Implementation**: Use `search` property with `searchableFieldIds` option for full-text search across multiple fields
@@ -0,0 +1,97 @@
1
+ ## SDK Utilities
2
+
3
+ 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).
4
+
5
+ ### Key SDK Utilities
6
+ The only functions exist in sdk are:
7
+
8
+ • **closeModal** - `closeModal(): void`
9
+ - Closes the currently open modal
10
+ - Example: `sdk.closeModal()` after saving or canceling
11
+
12
+ • **getOptimisticActions** - `getOptimisticActions(collectionId): OptimisticActions`
13
+ - Provides optimistic UI updates for immediate user feedback
14
+ - Supports create, update, delete operations with automatic rollback on failure
15
+ - Example: `sdk.getOptimisticActions(sdk.collectionId).updateOne(item, { ... })`
16
+
17
+ • **getSchema** - `getSchema(collectionId): SchemaConfig | undefined`
18
+ - Access to collection schema information (fields, types, validation)
19
+ - Useful for dynamic operations based on collection structure
20
+ - Example: `const schema = sdk.getSchema(sdk.collectionId)`
21
+
22
+ • **collectionId** - `string`
23
+ - Current collection context identifier
24
+ - Available in all action contexts for referencing the active collection
25
+ - Example: `sdk.collectionId` to get the current collection ID
26
+
27
+ ---
28
+
29
+ ## OptimisticActions
30
+
31
+ Provides immediate UI updates with automatic server synchronization and error recovery.
32
+
33
+ ### Usage Rules
34
+
35
+ **Use OptimisticActions for:**
36
+ - Data modification operations (create, update, delete)
37
+ - Operations requiring immediate visual feedback
38
+
39
+ **Do NOT use for:**
40
+ - Read-only operations
41
+ - Operations requiring server confirmation first
42
+
43
+ ### Core Pattern
44
+
45
+ ```typescript
46
+ // Get instances from SDK (see SDK Utilities section)
47
+ const optimisticActions = sdk.getOptimisticActions(sdk.collectionId);
48
+ const schema = sdk.getSchema(sdk.collectionId);
49
+
50
+ optimisticActions.operation(items, {
51
+ submit: async (items) => schema.actions.serverMethod(items),
52
+ successToast: 'Success message',
53
+ errorToast: (err, {retry}) => ({ text: 'Error message', action: { text: 'Retry', onClick: retry }})
54
+ });
55
+ ```
56
+
57
+ ### Available Operations
58
+
59
+ #### Create Operations
60
+ - `createOne(item: T, params: OptimisticParams<T>): void`
61
+ - `createMany(items: T[], params: OptimisticParams<T>): void`
62
+
63
+ #### Update Operations
64
+ - `updateOne(item: T, params: OptimisticParams<T>): void`
65
+ - `updateMany(items: T[], params: OptimisticParams<T>): void`
66
+ - `updateAll(transformFn: (item: T) => Partial<T>, params: OptimisticParams<T>): void`
67
+
68
+ #### Delete Operations
69
+ - `deleteOne(item: T, params: OptimisticParams<T> & { showUndoToast: true }): void`
70
+ - `deleteMany(items: T[], params: OptimisticParams<T> & { showUndoToast: true }): void`
71
+ - `deleteAll(params: OptimisticParams<T> & { showUndoToast: true }): void`
72
+
73
+ ### Type Definitions
74
+
75
+ ```typescript
76
+ interface OptimisticParams<T> {
77
+ submit: (items: T[]) => Promise<any>;
78
+ successToast: string | ToastConfig;
79
+ errorToast: (error: Error, actions: { retry: () => void }) => ToastConfig | string;
80
+ showUndoToast?: boolean; // Required: true for delete operations
81
+ }
82
+
83
+ interface ToastConfig {
84
+ text: string;
85
+ action?: { text: string; onClick: () => void };
86
+ }
87
+ ```
88
+
89
+ ### Validation Requirements
90
+
91
+ **Before using optimistic actions:**
92
+ - Verify `sdk.getOptimisticActions(collectionId)` returns valid instance
93
+ - Verify `sdk.getSchema(collectionId)` returns valid schema
94
+ - For delete operations: `showUndoToast: true` is mandatory
95
+ - All `submit` functions must return a Promise
96
+
97
+ **SDK Parameter:** Available in custom actions and modals. See SDK Utilities section for complete interface.