@donotdev/crud 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CrudService.bulk.js +1 -1
- package/dist/CrudService.bulkAcross.js +1 -1
- package/dist/CrudService.bulkReconciliation.js +1 -1
- package/dist/CrudService.cache.js +1 -1
- package/dist/CrudService.internal.js +2 -2
- package/dist/CrudService.mutations.js +1 -1
- package/dist/CrudService.optimistic.js +1 -1
- package/dist/CrudService.subscriptions.js +1 -1
- package/dist/CrudService.writeRules.js +1 -1
- package/dist/CrudStore.js +1 -1
- package/dist/adapters/FunctionsAdapter.js +1 -1
- package/dist/components/CrudButton.js +1 -1
- package/dist/components/CrudCard.js +1 -1
- package/dist/components/DateFilter.js +1 -1
- package/dist/components/DisplayFieldRenderer.js +1 -1
- package/dist/components/DisplayThumbnail.js +1 -1
- package/dist/components/EntityFilters.js +1 -1
- package/dist/components/FormFieldRenderer.js +1 -1
- package/dist/components/SortableCardList.js +1 -1
- package/dist/components/YearFilter.js +1 -1
- package/dist/components/controlled/complex/ControlledAddressField.js +1 -1
- package/dist/components/controlled/complex/ControlledDateField.js +1 -1
- package/dist/components/controlled/complex/ControlledFieldArrayField.js +1 -1
- package/dist/components/controlled/complex/ControlledGeoPointField.js +1 -1
- package/dist/components/controlled/complex/ControlledMapField.js +1 -1
- package/dist/components/controlled/complex/ControlledMultiInputField.js +1 -1
- package/dist/components/controlled/complex/ControlledRichTextField.js +1 -1
- package/dist/components/controlled/file/ControlledDocumentField.js +1 -1
- package/dist/components/controlled/file/ControlledFileField.js +1 -1
- package/dist/components/controlled/file/ControlledImageField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiDocumentField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiImageField.js +1 -1
- package/dist/components/controlled/input/ControlledCurrencyField.js +1 -1
- package/dist/components/controlled/input/ControlledDurationField.js +1 -1
- package/dist/components/controlled/input/ControlledGdprConsentField.js +1 -1
- package/dist/components/controlled/input/ControlledNumberField.js +1 -1
- package/dist/components/controlled/input/ControlledPasswordField.js +1 -1
- package/dist/components/controlled/input/ControlledPhoneField.js +1 -1
- package/dist/components/controlled/input/ControlledRatingField.js +1 -1
- package/dist/components/controlled/input/ControlledSwitchField.js +1 -1
- package/dist/components/controlled/input/ControlledTextField.js +1 -1
- package/dist/components/controlled/select/ControlledComboboxField.js +1 -1
- package/dist/components/controlled/select/ControlledDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledMultiDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledRadioField.js +1 -1
- package/dist/components/controlled/select/ControlledReferenceField.js +1 -1
- package/dist/components/controlled/types.js +1 -1
- package/dist/components/fields/display/AvatarFieldDisplay.js +1 -1
- package/dist/components/fields/display/CheckboxFieldDisplay.js +1 -1
- package/dist/components/fields/display/DateFieldDisplay.js +1 -1
- package/dist/components/fields/display/FileFieldDisplay.js +1 -1
- package/dist/components/fields/display/LinkFieldDisplay.js +1 -1
- package/dist/components/fields/display/NumberFieldDisplay.js +1 -1
- package/dist/components/fields/display/PasswordFieldDisplay.js +1 -1
- package/dist/components/fields/display/ReferenceFieldDisplay.js +1 -1
- package/dist/components/fields/display/TextAreaDisplay.js +1 -1
- package/dist/components/fields/display/TextFieldDisplay.js +1 -1
- package/dist/components/form/fields/AddressFieldComponent.js +1 -1
- package/dist/components/form/fields/AvatarFieldComponent.js +1 -1
- package/dist/components/form/fields/BadgeFieldComponent.js +1 -1
- package/dist/components/form/fields/ButtonFieldComponent.js +1 -1
- package/dist/components/form/fields/ComboboxComponent.js +1 -1
- package/dist/components/form/fields/CurrencyFieldComponent.js +1 -1
- package/dist/components/form/fields/DateFieldComponent.js +1 -1
- package/dist/components/form/fields/DocumentFieldComponent.js +1 -1
- package/dist/components/form/fields/DropdownComponent.js +1 -1
- package/dist/components/form/fields/DurationFieldComponent.js +1 -1
- package/dist/components/form/fields/FileFieldComponent.js +1 -1
- package/dist/components/form/fields/GdprConsentFieldComponent.js +1 -1
- package/dist/components/form/fields/GeoPointFieldComponent.js +1 -1
- package/dist/components/form/fields/ImageFieldComponent.js +1 -1
- package/dist/components/form/fields/MapFieldComponent.js +1 -1
- package/dist/components/form/fields/MultiDropdownComponent.js +1 -1
- package/dist/components/form/fields/MultiInputTextFieldComponent.js +1 -1
- package/dist/components/form/fields/NumberFieldComponent.js +1 -1
- package/dist/components/form/fields/PasswordFieldComponent.js +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.d.ts +19 -0
- package/dist/components/form/fields/PhoneNumberComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.js +1 -1
- package/dist/components/form/fields/PriceFieldComponent.js +1 -1
- package/dist/components/form/fields/RadioFieldComponent.js +1 -1
- package/dist/components/form/fields/RangeFieldComponent.js +1 -1
- package/dist/components/form/fields/RatingFieldComponent.js +1 -1
- package/dist/components/form/fields/ReferenceFieldComponent.js +1 -1
- package/dist/components/form/fields/RichTextComponent.js +1 -1
- package/dist/components/form/fields/TextAreaComponent.js +1 -1
- package/dist/components/form/fields/TextFieldComponent.js +1 -1
- package/dist/components/form/fields/TimestampFieldComponent.js +1 -1
- package/dist/components/form/fields/internal/InlineFieldRow.js +1 -1
- package/dist/components/form/fields/internal/TiptapEditor.js +2 -2
- package/dist/components/form/internal/ImageViewerDialog.js +1 -1
- package/dist/fieldTypeRegistry.store.js +1 -1
- package/dist/forms/extend.js +1 -1
- package/dist/forms/hooks/useController.js +1 -1
- package/dist/forms/hooks/useEntityField.js +1 -1
- package/dist/forms/hooks/useEntityForm.d.ts.map +1 -1
- package/dist/forms/hooks/useEntityForm.js +1 -1
- package/dist/forms/hooks/useFormDraftState.js +1 -1
- package/dist/forms/types.d.ts +9 -0
- package/dist/forms/types.d.ts.map +1 -1
- package/dist/forms/utils/buildInitialValues.js +1 -1
- package/dist/forms/utils/conditionAwareResolver.d.ts +6 -2
- package/dist/forms/utils/conditionAwareResolver.d.ts.map +1 -1
- package/dist/forms/utils/conditionAwareResolver.js +1 -1
- package/dist/forms/utils/emptyValue.js +1 -1
- package/dist/forms/utils/fieldErrorMessages.d.ts +33 -0
- package/dist/forms/utils/fieldErrorMessages.d.ts.map +1 -0
- package/dist/forms/utils/fieldErrorMessages.js +1 -0
- package/dist/forms/utils/getFieldsForOperation.js +1 -1
- package/dist/forms/utils/isFieldEditable.js +1 -1
- package/dist/forms/utils/validateEntity.js +1 -1
- package/dist/forms/utils/writableFields.js +1 -1
- package/dist/hooks/useChildRows.js +1 -1
- package/dist/hooks/useCrudFilters.js +1 -1
- package/dist/hooks/useCrudPageSize.js +1 -1
- package/dist/hooks/useEntityFavorites.js +1 -1
- package/dist/hooks/useExtensionRows.js +1 -1
- package/dist/hooks/useFileUpload.js +1 -1
- package/dist/hooks/useReferenceResolver.js +1 -1
- package/dist/hooks/useRelatedItems.js +1 -1
- package/dist/stores/FormStore.js +1 -1
- package/dist/stores/UploadStore.js +1 -1
- package/dist/stores/uploadStoreRef.js +1 -1
- package/dist/symbol-index.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/useBaseCrudList.js +1 -1
- package/dist/useCrud.js +1 -1
- package/dist/useCrudCardList.js +1 -1
- package/dist/useCrudDoc.js +1 -1
- package/dist/useCrudList.js +1 -1
- package/dist/useServerPrefetch.js +1 -1
- package/dist/utils/clientListProcessing.js +1 -1
- package/dist/utils/collections.js +1 -1
- package/dist/utils/filterUrl.js +1 -1
- package/dist/utils/imageProcessing.js +1 -1
- package/dist/utils/matchesFilter.js +1 -1
- package/dist/utils/mergeWithOptimistic.js +1 -1
- package/dist/utils/referenceEntity.js +1 -1
- package/dist/utils/uploadValidation.js +1 -1
- package/dist/utils/useRowTranslator.js +1 -1
- package/dist/workflows/defineWorkflow.js +1 -1
- package/dist/workflows/useEntityWorkflow.js +1 -1
- package/guidelines/CRUD.md +3 -1
- package/guidelines/GOTCHAS.md +2 -0
- package/package.json +3 -3
package/dist/useBaseCrudList.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useMemo as j,useCallback as $,useRef as x,useState as ee,useEffect as te}from"react";import{isClient as se,useQuery as re}from"@donotdev/core";import{useCrudStore as ie}from"./CrudStore";import{CRUD_OPERATION as K}from"./types";import{useCrud as k,getCrudServiceInstance as oe,EMPTY_OPTIMISTIC as ae}from"./useCrud";import{useServerPrefetch as ne}from"./useServerPrefetch";import{mergeWithOptimistic as le}from"./utils/mergeWithOptimistic";import{injectScopeFilter as ce,getCurrentScopeValue as ue}from"./utils/scopeUtils";import{useRowTranslator as me}from"./utils/useRowTranslator";const pe=1e3;function de(
|
|
1
|
+
import{useMemo as j,useCallback as $,useRef as x,useState as ee,useEffect as te}from"react";import{isClient as se,useQuery as re}from"@donotdev/core";import{useCrudStore as ie}from"./CrudStore";import{CRUD_OPERATION as K}from"./types";import{useCrud as k,getCrudServiceInstance as oe,EMPTY_OPTIMISTIC as ae}from"./useCrud";import{useServerPrefetch as ne}from"./useServerPrefetch";import{mergeWithOptimistic as le}from"./utils/mergeWithOptimistic";import{injectScopeFilter as ce,getCurrentScopeValue as ue}from"./utils/scopeUtils";import{useRowTranslator as me}from"./utils/useRowTranslator";const pe=1e3;function de(_,y,t,f={}){const C=f.enabled??!0,M=k("status"),c=M==="ready",B=k(_,f),{error:I,invalidate:P,_collection:d,_schemas:T,_cacheOptions:v,_scope:S}=B,q=ie(e=>e.collections[d]?.optimistic||ae),w=x(new Map([[1,null]])),O=x(0),[E,N]=ee(!1),a=t?.mode==="auto"?E?"server":"client":t?.mode??"client",U=ue(S),g=j(()=>{if(!c||!T)return null;const e=oe();if(!e)return null;const h=T.get,n=ce(f.queryOptions,S);if(!t)return e.getListQueryOptions(d,n,h,v,y);if(a==="client"){const l=t.mode==="auto"&&!n?.limit?{...n,limit:pe}:n;return e.getListQueryOptions(d,l,h,v,y)}const u=w.current,m=O.current,{page:p,pageSize:s}=t;let o,r;if(u.has(p))o=u.get(p)??void 0,r=s;else if(p>m&&u.has(m)){const l=p-m;o=u.get(m)??void 0,r=l*s}else o=void 0,r=p*s;return e.getListQueryOptions(d,{...n,limit:r,startAfter:o},h,v,y)},[c,d,v,T?"hasSchema":"noSchema",y,a,t?.page,t?.pageSize,f.queryOptions,S?.provider,U]),{data:i,isLoading:W,isFetching:Y,error:G,refetch:z}=re({queryKey:g?.queryKey??["crud",d,"disabled"],queryFn:g?.queryFn??(()=>Promise.resolve({items:[]})),staleTime:g?.staleTime,enabled:C&&!!g});ne(g,C,S);const L=!se();te(()=>{t?.mode==="auto"&&!E&&i&&i.total!=null&&i.total>i.items.length&&N(!0)},[i,t?.mode,E]);const D=me(_,f),F=j(()=>{if(!i||!c)return{items:[],total:void 0};let e=i.items;if(a==="server"&&t&&e.length>0){const s=w.current,o=O.current,{page:r,pageSize:l}=t,J=e.length;if(Math.ceil(J/l)>1||r>o){const A=s.has(r)?r:o+1;for(let b=A;b<=r;b++){const V=(b-A+1)*l-1;if(V<e.length){const Z=e[V];s.set(b+1,Z.id)}}}i.lastVisible&&s.set(r+1,i.lastVisible),O.current=Math.max(o,r);const R=s.has(r)?0:(r-o-1)*l,X=R+l;e=e.slice(R,X)}const h=le(e,q),n=new Set(e.map(s=>s.id));let u=0,m=0;for(const[s,o]of Object.entries(q))o.operation===K.ADD&&!n.has(s)?u++:o.operation===K.DELETE&&n.has(s)&&m++;const p=(i.total??e.length)+u-m;return{items:h.map(D),total:p}},[i,q,D,c,a,t?.page,t?.pageSize]),Q=$(async()=>{c&&(a==="server"&&(w.current=new Map([[1,null]]),O.current=0),await P(),await z())},[P,z,c,a]);if(!c){const e=async()=>{};return{status:M,data:{items:[],total:void 0},items:[],loading:!0,fetching:!1,error:I,mutate:e,refresh:e,isAvailable:!1,effectiveMode:a}}const H=F?.items??[];return{status:M,data:F,items:H,loading:L?C&&i===void 0:W,fetching:L?!1:Y,error:L?null:G??I,mutate:Q,refresh:Q,isAvailable:!0,effectiveMode:a}}export{de as useBaseCrudList};
|
package/dist/useCrud.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as L,useMemo as U,useCallback as n}from"react";import{useFeatureConsent as W,AtomicBulkError as Z,FRAMEWORK_FEATURES as H,FEATURE_STATUS as f,handleError as J,isClient as Q,createSchemas as V,DEGRADED_CRUD_API as X,getGlobalSingleton as $}from"@donotdev/core";import{getCrudService as F}from"./CrudService";import{useCrudStore as m}from"./CrudStore";import{injectScope as C,injectScopeFilter as ee}from"./utils/scopeUtils";const te={},re={};function M(){return $("crud-service",()=>({service:null,initPromise:null,errorNotified:!1}))}function i(){return y()}function y(){const u=M(),o=u.service??F();return o.attachProvider()?(u.service||(o.setStore(m),u.service=o),o):null}function se(u,o={}){const v=W(H.CRUD),N=m(e=>e.crudService),A=v&&!N&&!y(),b=v?A?f.INITIALIZING:f.READY:f.DEGRADED,S=u==="status",p=!S&&typeof u=="object"?u:o.entity,r=S?"__status__":typeof u=="string"?u:u.collection,l=p?.scope,_=o.noCache??!1,E=o.staleTime,h=U(()=>({noCache:_,staleTime:E}),[_,E]),
|
|
1
|
+
"use client";import{useEffect as L,useMemo as U,useCallback as n}from"react";import{useFeatureConsent as W,AtomicBulkError as Z,FRAMEWORK_FEATURES as H,FEATURE_STATUS as f,handleError as J,isClient as Q,createSchemas as V,DEGRADED_CRUD_API as X,getGlobalSingleton as $}from"@donotdev/core";import{getCrudService as F}from"./CrudService";import{useCrudStore as m}from"./CrudStore";import{injectScope as C,injectScopeFilter as ee}from"./utils/scopeUtils";const te={},re={};function M(){return $("crud-service",()=>({service:null,initPromise:null,errorNotified:!1}))}function i(){return y()}function y(){const u=M(),o=u.service??F();return o.attachProvider()?(u.service||(o.setStore(m),u.service=o),o):null}function se(u,o={}){const v=W(H.CRUD),N=m(e=>e.crudService),A=v&&!N&&!y(),b=v?A?f.INITIALIZING:f.READY:f.DEGRADED,S=u==="status",p=!S&&typeof u=="object"?u:o.entity,r=S?"__status__":typeof u=="string"?u:u.collection,l=p?.scope,_=o.noCache??!1,E=o.staleTime,h=U(()=>({noCache:_,staleTime:E}),[_,E]),a=U(()=>{if(!S){if(o.schema){const e=o.schema;return{create:e,draft:e,update:e,get:e,list:e,listCard:e,delete:e}}if(p)return V(p)}},[S,o.schema,p?.name,r]),Y=m(e=>e.collections[r]?.loading||!1),T=m(e=>e.collections[r]?.error||null);L(()=>{if(!Q()||!v||!a)return;const{crudService:e}=m.getState(),s=y();if(s){e||m.getState().setCrudService(s);return}const t=M();e||t.service||t.initPromise||(t.initPromise=(async()=>{try{if(t.service||m.getState().crudService)return;const c=F();t.service=c,c.setStore(m),await c.initialize(),t.errorNotified=!1,m.getState().setCrudService(c)}catch(c){t.errorNotified||(J(c,{userMessage:"Failed to initialize CRUD service.",context:{collection:r},severity:"error"}),t.errorNotified=!0)}finally{t.initPromise=null}})())},[v,r,a?"hasSchema":"noSchema"]);const D=A||Y,G=b===f.READY,O=n(async e=>{const s=i();return!s||!a?null:s.get(r,e,a.get,h)},[r,a?"hasSchema":"noSchema",h]),d=a,j=n(async(e,s,t)=>{const c=i();if(!c||!d)return;const g=C(s,l);return c.set(r,e,g,d.create,{...t,readSchema:d.get})},[r,a?"hasSchema":"noSchema",l?.provider]),x=n(async(e,s,t)=>{const c=i();if(!(!c||!d))return c.update(r,e,s,d.update,{...t,readSchema:d.get})},[r,a]),q=n(async e=>{const s=i();!s||!d||await s.remove(r,e)},[r,a]),z=n(async(e,s)=>{const t=i();t&&await t.delete(r,e,s)},[r]),B=n(async(e,s)=>{const t=i();if(!t||!d)return"";const c=C(e,l);return t.add(r,c,d.create,{...s,readSchema:d.get})},[r,a?"hasSchema":"noSchema",l?.provider]),I=n(async(e,s)=>{const t=i();if(!t){if(s?.execution==="atomic")throw new Z("CRUD service is unavailable","not-committed");return{results:{}}}return t.bulkAcross(e,s)},[]),R=n(async(e,s)=>{const t=i();if(!t||!a)return{insertedIds:[],updatedIds:[],deletedIds:[],failed:[]};const c={inserts:e.inserts?.map(g=>C(g,l)),updates:e.updates,deletes:e.deletes};return t.bulk(r,c,{create:a.create,draft:a.draft,update:a.update},s)},[r,a?"hasSchema":"noSchema",l?.provider]),K=n(async e=>{const s=i();if(!s||!a)return[];const t=ee(e,l);return(await s.query(r,t,a.get,h)).items},[r,a?"hasSchema":"noSchema",h,l?.provider]),P=n((e,s)=>{const t=i();return!t||!a?()=>{}:t.subscribe(r,e,s,a.get)},[r,a?"hasSchema":"noSchema"]),k=n((e,s)=>{const t=i();return!t||!a?()=>{}:t.subscribeToCollection(r,e,s,a.get)},[r,a?"hasSchema":"noSchema"]),w=n(async()=>{const e=i();e&&await e.invalidateCollection(r)},[r]);return S?b:G?{status:f.READY,loading:D,error:T,get:O,set:j,update:x,remove:q,delete:z,add:B,bulk:R,bulkAcross:I,query:K,subscribe:P,subscribeToCollection:k,invalidate:w,isAvailable:!0,_collection:r,_schemas:a,_cacheOptions:h,_scope:l}:{...X,status:b,loading:D,error:T,subscribe:P,subscribeToCollection:k,invalidate:w,bulk:R,bulkAcross:I,_collection:r,_schemas:a,_cacheOptions:h,_scope:l}}export{te as EMPTY_DATA,re as EMPTY_OPTIMISTIC,i as getCrudServiceInstance,se as useCrud};
|
package/dist/useCrudCardList.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useMemo as d}from"react";import{useCrudFilters as p}from"./hooks/useCrudFilters";import{useBaseCrudList as f}from"./useBaseCrudList";import{applyFilters as h,applySearch as y,applySort as g}from"./utils/clientListProcessing";function C(
|
|
1
|
+
import{useMemo as d}from"react";import{useCrudFilters as p}from"./hooks/useCrudFilters";import{useBaseCrudList as f}from"./useBaseCrudList";import{applyFilters as h,applySearch as y,applySort as g}from"./utils/clientListProcessing";function C(a,t={}){const o={enabled:t.enabled,queryOptions:t.queryOptions,schema:t.schema,entity:t.entity,staleTime:t.staleTime,noCache:t.noCache,translate:t.translate},e=f(a,"listCard",null,o),s=typeof a=="string"?null:a,n=typeof a=="string"?a:a.collection,{filters:l}=p({collection:n}),i=t.clientSort===null?null:t.clientSort??s?.defaultSort??null,{processed:u,filteredTotal:c}=d(()=>{let r=e.items;s&&Object.keys(l).length>0&&(r=h(r,l,s)),s&&t.searchQuery&&(r=y(r,t.searchQuery,s));const m=r.length;return i&&(r=g(r,i)),{processed:r,filteredTotal:m}},[e.items,l,t.searchQuery,i,s]);return{status:e.status,data:e.data?{items:e.data.items}:null,items:e.items,processed:u,filteredTotal:c,loading:e.loading,fetching:e.fetching,error:e.error,mutate:e.mutate,refresh:e.refresh,isAvailable:e.isAvailable}}export{C as useCrudCardList};
|
package/dist/useCrudDoc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as q,useEffect as w,useMemo as x}from"react";import{FEATURE_STATUS as b,isClient as L,isNextJs as N,useQuery as O,useQueryClient as Q}from"@donotdev/core";import{cachedListRow as U}from"./CrudService.cache";import{useCrudStore as K}from"./CrudStore";import{useCrud as D,getCrudServiceInstance as P}from"./useCrud";import{useServerPrefetch as k}from"./useServerPrefetch";import{applyOptimisticToDoc as G}from"./utils/mergeWithOptimistic";import{isRouteRecord as J}from"./utils/routeRecord";import{useRowTranslator as M}from"./utils/useRowTranslator";function Y(
|
|
1
|
+
import{useCallback as q,useEffect as w,useMemo as x}from"react";import{FEATURE_STATUS as b,isClient as L,isNextJs as N,useQuery as O,useQueryClient as Q}from"@donotdev/core";import{cachedListRow as U}from"./CrudService.cache";import{useCrudStore as K}from"./CrudStore";import{useCrud as D,getCrudServiceInstance as P}from"./useCrud";import{useServerPrefetch as k}from"./useServerPrefetch";import{applyOptimisticToDoc as G}from"./utils/mergeWithOptimistic";import{isRouteRecord as J}from"./utils/routeRecord";import{useRowTranslator as M}from"./utils/useRowTranslator";function Y(m,e,l={}){const r=l.enabled??!0,s=D("status"),u=s===b.READY,{_collection:a,_schemas:d,_cacheOptions:F,_scope:I}=D(m,l),p=K(o=>e?o.collections[a]?.optimistic[e]:void 0),f=u?P():null,t=f&&d&&e?f.getDocQueryOptions(a,e,d.get,F):null,R=Q(),c=t&&e?U(R,a,e):void 0,{data:i,isLoading:E,isFetching:S,error:_,refetch:h}=O({queryKey:t?.queryKey??["crud",a,"get",null],queryFn:t?.queryFn??(()=>Promise.resolve(null)),staleTime:t?.staleTime,...c&&{initialData:c.data,initialDataUpdatedAt:c.updatedAt},enabled:r&&!!t});k(t,r,I);const y=M(m,l),g=x(()=>y(G(i??null,p)),[y,i,p]),n=!L(),v=!!t,A=q(async()=>{v&&await h()},[h,v]),T=i!==void 0&&g===null,C=u&&T&&!n&&!N()&&!!e&&J(a,e);return w(()=>{if(!C)return;const o=document.createElement("meta");return o.name="robots",o.content="noindex",document.head.append(o),()=>o.remove()},[C]),u?{status:s,data:g,loading:n?r&&!!t&&i===void 0:E,fetching:n?!1:S,notFound:T,error:n?null:_,refresh:A,isAvailable:!0}:{status:s,data:null,loading:s===b.INITIALIZING&&r&&!!e,fetching:!1,notFound:!1,error:null,refresh:A,isAvailable:!1}}export{Y as useCrudDoc};
|
package/dist/useCrudList.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useMemo as h}from"react";import{useCrudFilters as g}from"./hooks/useCrudFilters";import{useBaseCrudList as S}from"./useBaseCrudList";import{applyFilters as C,applySearch as T,applySort as b}from"./utils/clientListProcessing";function Q(
|
|
1
|
+
import{useMemo as h}from"react";import{useCrudFilters as g}from"./hooks/useCrudFilters";import{useBaseCrudList as S}from"./useBaseCrudList";import{applyFilters as C,applySearch as T,applySort as b}from"./utils/clientListProcessing";function Q(s,e={}){const i=e.pagination??"auto",n=e.page??1,p=e.pageSize??10,c={mode:i,page:n,pageSize:p},u={enabled:e.enabled,queryOptions:e.queryOptions,schema:e.schema,entity:e.entity,staleTime:e.staleTime,noCache:e.noCache,translate:e.translate},l=S(s,"list",c,u),a=typeof s=="string"?null:s,m=typeof s=="string"?s:s.collection,{filters:o}=g({collection:m}),r=e.clientSort===null?null:e.clientSort??a?.defaultSort??null,{processed:d,filteredTotal:y}=h(()=>{let t=l.items;a&&Object.keys(o).length>0&&(t=C(t,o,a)),a&&e.searchQuery&&(t=T(t,e.searchQuery,a));const f=t.length;return r&&(t=b(t,r)),{processed:t,filteredTotal:f}},[l.items,o,e.searchQuery,r,a]);return{...l,processed:d,filteredTotal:y}}export{Q as useCrudList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hasProvider as u,isClient as a,useAuthSessionSnapshot as c,useQueryClient as i}from"@donotdev/core";import{getCrudServiceInstance as h}from"./useCrud";function f(
|
|
1
|
+
import{hasProvider as u,isClient as a,useAuthSessionSnapshot as c,useQueryClient as i}from"@donotdev/core";import{getCrudServiceInstance as h}from"./useCrud";function f(r,n,o){const s=i(),e=c();if(a()||!n||!r||o)return;const t=s.getQueryState(r.queryKey);if(!(t&&(t.data!==void 0||t.error)||!(!u("auth")||e?.user===null||e?.user&&e.accessToken&&h()?.bindRequestAccessToken(s,e.accessToken))))throw s.fetchQuery(r).then(()=>{},()=>{})}export{f as useServerPrefetch};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeEntity as u}from"@donotdev/core";import{matchesFilter as f}from"./matchesFilter";import"../fieldTypeRegistry.store";function d(t,n,s){const
|
|
1
|
+
import{describeEntity as u}from"@donotdev/core";import{matchesFilter as f}from"./matchesFilter";import"../fieldTypeRegistry.store";function d(t,n,s){const o=Object.entries(n);return o.length===0?t:t.filter(r=>o.every(([l,c])=>{const e=s.fields[l],i=e?.type||"text";return f(r[l],c,i,e?.filter)}))}function a(t){if(t.search?.fields&&t.search.fields.length>0)return t.search.fields;const n=[],{fields:s}=u(t);for(const[o,r]of Object.entries(s))r.visibleAt==="hidden"||r.visibleAt==="technical"||r.value.kind==="text"&&n.push(o);return n}function m(t,n,s){if(!n||n.trim()==="")return t;const o=n.toLowerCase(),r=a(s);return r.length===0?t.filter(l=>Object.values(l).some(c=>c==null?!1:String(c).toLowerCase().includes(o))):t.filter(l=>r.some(c=>{const e=l[c];return e==null?!1:typeof e=="object"&&"formatted_address"in e?String(e.formatted_address).toLowerCase().includes(o):String(e).toLowerCase().includes(o)}))}function p(t,n){if(typeof n=="function")return[...t].sort(n);const{field:s,direction:o="asc"}=n,r=o==="desc"?-1:1;return[...t].sort((l,c)=>{const e=l[s],i=c[s];return e==null&&i==null?0:e==null?1:i==null?-1:typeof e=="number"&&typeof i=="number"?(e-i)*r:typeof e=="object"&&"amount"in e&&typeof i=="object"&&"amount"in i?(e.amount-i.amount)*r:e instanceof Date&&i instanceof Date?(e.getTime()-i.getTime())*r:String(e).localeCompare(String(i))*r})}export{d as applyFilters,m as applySearch,p as applySort,a as getSearchableFields};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCrudService as
|
|
1
|
+
import{getCrudService as i}from"../CrudService";async function p(e,t){const a=i(),s=[],o=t.range?.start??1,r=t.range?.end??28;for(let c=o;c<=r;c++){const m=String(c),n=await a.get(t.path(e),m,t.schema);n&&s.push(n)}return s}async function d(e,t,a){const s=i();for(const o of a){const r=t.idOf(o);await s.set(t.path(e),r,o,t.schema)}}async function h(e,t,a){const s=i();if(t.idFrom){const o=t.idFrom(a);await s.set(t.path(e),o,a,t.schema);return}return s.add(t.path(e),a,t.schema)}export{h as appendToCollection,p as loadDeterministicRange,d as upsertDeterministic};
|
package/dist/utils/filterUrl.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFilterType as g}from"../fieldTypeRegistry.store";const d=new Set(["select","multiselect","reference"]),c="f_";function m(
|
|
1
|
+
import{getFilterType as g}from"../fieldTypeRegistry.store";const d=new Set(["select","multiselect","reference"]),c="f_";function m(t,i){const e=t.fields[i];return e?g(e.type):void 0}function h(t,i){if(!t.startsWith(c))return!1;const e=t.slice(c.length);if(e in i.fields)return m(i,e)!=="range";const r=/^(.+)_(min|max)$/.exec(e);return!!r&&m(i,r[1])==="range"}function u(t,i,e){[...new Set(t.keys())].filter(r=>h(r,e)).forEach(r=>t.delete(r));for(const[r,n]of Object.entries(i)){if(!(r in e.fields))continue;const s=`${c}${r}`;typeof n=="string"?n!==""&&t.append(s,n):Array.isArray(n)?n.forEach(a=>t.append(s,a)):(n.min&&t.set(`${s}_min`,n.min),n.max&&t.set(`${s}_max`,n.max))}}function p(t,i){const e=new URLSearchParams(t),r={};for(const n of Object.keys(i.fields)){const s=`${c}${n}`,a=m(i,n);if(a==="range"){const o=e.get(`${s}_min`),l=e.get(`${s}_max`);(o||l)&&(r[n]={...o?{min:o}:{},...l?{max:l}:{}});continue}const f=e.getAll(s).filter(o=>o!=="");f.length!==0&&(r[n]=a!==void 0&&d.has(a)||f.length>1?f:f[0])}return r}function _(t,i){const e=new URLSearchParams;return u(e,t,i),e.sort(),e.toString()}export{c as FILTER_PARAM_PREFIX,_ as encodeFilterParams,p as readFilterParams,u as writeFilterParams};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"valibot";const E=e.pipe(e.number(),e.minValue(.1),e.maxValue(1)),y=e.pipe(e.number(),e.integer(),e.minValue(16),e.maxValue(8192)),I=e.strictObject({maxWidth:e.optional(y),maxHeight:e.optional(y),thumbWidth:e.optional(y),thumbHeight:e.optional(y),aspectRatio:e.optional(e.union([e.literal("original"),e.pipe(e.number(),e.minValue(.1),e.maxValue(10))])),quality:e.optional(E),thumbQuality:e.optional(E),background:e.optional(e.pipe(e.string(),e.minLength(1)))});function Q(t){if(typeof t!="object"||t===null)return;const a=t.image;if(a!==void 0)return e.parse(I,a)}const v=new WeakMap;function S(t){return JSON.stringify({maxWidth:t.maxWidth,maxHeight:t.maxHeight,thumbWidth:t.thumbWidth,thumbHeight:t.thumbHeight,aspectRatio:t.aspectRatio,quality:t.quality,thumbQuality:t.thumbQuality,background:t.background,crop:t.crop})}async function j(t,a={}){const r=S(a),h=v.get(t);if(h?.has(r))return h.get(r);const{maxWidth:u=1920,maxHeight:
|
|
1
|
+
import*as e from"valibot";const E=e.pipe(e.number(),e.minValue(.1),e.maxValue(1)),y=e.pipe(e.number(),e.integer(),e.minValue(16),e.maxValue(8192)),I=e.strictObject({maxWidth:e.optional(y),maxHeight:e.optional(y),thumbWidth:e.optional(y),thumbHeight:e.optional(y),aspectRatio:e.optional(e.union([e.literal("original"),e.pipe(e.number(),e.minValue(.1),e.maxValue(10))])),quality:e.optional(E),thumbQuality:e.optional(E),background:e.optional(e.pipe(e.string(),e.minLength(1)))});function Q(t){if(typeof t!="object"||t===null)return;const a=t.image;if(a!==void 0)return e.parse(I,a)}const v=new WeakMap;function S(t){return JSON.stringify({maxWidth:t.maxWidth,maxHeight:t.maxHeight,thumbWidth:t.thumbWidth,thumbHeight:t.thumbHeight,aspectRatio:t.aspectRatio,quality:t.quality,thumbQuality:t.thumbQuality,background:t.background,crop:t.crop})}async function j(t,a={}){const r=S(a),h=v.get(t);if(h?.has(r))return h.get(r);const{maxWidth:u=1920,maxHeight:n=1440,thumbWidth:i=300,thumbHeight:l=225,aspectRatio:g=4/3,quality:d=.85,thumbQuality:p=.65,background:m="#FFFFFF",crop:o}=a;return new Promise((b,w)=>{const s=new Image,F=new FileReader;F.onload=c=>{s.src=c.target?.result},F.onerror=()=>w(new Error("Failed to read file")),s.onload=async()=>{try{const c=o?o.width:s.width,W=o?o.height:s.height,H=g==="original",f=H?c/W:g,{width:R,height:M}=q(c,W,u,n,f),O=await B(s,R,M,f,d,m,o),V=H?q(c,W,i,l,f):{width:i,height:l},P=await B(s,V.width,V.height,f,p,m,o),k={fullBlob:O,thumbBlob:P,width:R,height:M};let x=v.get(t);x||(x=new Map,v.set(t,x)),x.set(r,k),b(k)}catch(c){w(c)}},s.onerror=()=>w(new Error("Failed to load image")),F.readAsDataURL(t)})}function q(t,a,r,h,u){let n=t,i=a;n>r&&(i=r/n*i,n=r),i>h&&(n=h/i*n,i=h);const l=n/i;return Math.abs(l-u)>.01&&(l>u?i=n/u:n=i*u),{width:Math.round(n),height:Math.round(i)}}async function B(t,a,r,h,u,n,i){const l=document.createElement("canvas"),g=l.getContext("2d");if(!g)throw new Error("Failed to get canvas context");l.width=a,l.height=r,n!=="transparent"&&(g.fillStyle=n,g.fillRect(0,0,a,r));let d,p,m,o;if(i)d=i.x,p=i.y,m=i.width,o=i.height;else{const b=t.width/t.height;m=t.width,o=t.height,d=0,p=0,b>h?(m=t.height*h,d=(t.width-m)/2):b<h&&(o=t.width/h,p=(t.height-o)/2)}return g.drawImage(t,d,p,m,o,0,0,a,r),new Promise((b,w)=>{l.toBlob(s=>{s?b(s):w(new Error("Failed to convert canvas to blob"))},"image/webp",u)})}function z(t,a){return t.type.startsWith("image/")?a&&t.size>a?{valid:!1,error:`File size exceeds ${(a/1048576).toFixed(1)}MB limit`}:{valid:!0}:{valid:!1,error:"File must be an image"}}export{I as imageProcessingOptionsSchema,j as processImage,Q as readImageProcessingOptions,z as validateImageFile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFilterType as D}from"../fieldTypeRegistry.store";const b=new Set(["select","multiselect","reference"]);function x(
|
|
1
|
+
import{getFilterType as D}from"../fieldTypeRegistry.store";const b=new Set(["select","multiselect","reference"]);function x(t,n,e){if(t==null)return!1;const w=(Array.isArray(t)?t:[t]).map(String);if(e!==void 0&&w.includes(e))return!0;const y=new Set(n.map(String));return w.some(N=>y.has(N))}function I(t,n,e,w){if(!n)return!0;const y=w?.wildcard;if(Array.isArray(n)){if(n.length===0)return!0;const r=D(e);if(!(r==="range"&&(e==="date"||e==="datetime-local"||e==="timestamp")))return r&&b.has(r)?x(t,n,y):n.some(a=>{if(typeof a=="object"&&"date"in a){const u=a.date;if(t==null)return!1;const i=t instanceof Date?t:new Date(t);return isNaN(i.getTime())?!1:i.toISOString().split("T")[0]===u}return String(t)===String(a)});if(t==null)return!1;const o=t instanceof Date?t:new Date(t);if(isNaN(o.getTime()))return!1;const c=o.toISOString().split("T")[0];return n.some(a=>typeof a=="string"?c===a:typeof a=="object"&&"date"in a?c===a.date:!1)}if(typeof n=="object"&&"date"in n&&!("min"in n)&&!Array.isArray(n)){if(!(D(e)==="range"&&(e==="date"||e==="datetime-local"||e==="timestamp")))return!1;const r=n.date;if(!r)return!0;if(t==null)return!1;const o=t instanceof Date?t.toISOString().split("T")[0]:new Date(t).toISOString().split("T")[0];if((e==="datetime-local"||e==="timestamp")&&n.time){const c=t instanceof Date?t.toISOString().slice(11,16):new Date(t).toISOString().slice(11,16);return o===r&&c===n.time}return o===r}if(typeof n=="object"&&"min"in n){const r=D(e);if(!r)return!0;const o=r==="range"&&(e==="date"||e==="datetime-local"||e==="timestamp"),c=r==="range"&&!o,a=e==="price",u=a&&t!=null&&typeof t=="object"?Number(t.amount):c&&t!=null?typeof t=="number"?t:Number(t):NaN;if(c||a){if(typeof n.min=="object"&&n.min!==null&&"date"in n.min)return!1;const i=n,d=typeof i.min=="string"&&i.min!=="",g=typeof i.max=="string"&&i.max!=="";return d&&!g?t==null||isNaN(u)?!1:u>=Number(i.min):!d&&g?t==null?!0:isNaN(u)?!1:u<=Number(i.max):d&&g?t==null||isNaN(u)?!1:u>=Number(i.min)&&u<=Number(i.max):!0}if(o){if(typeof n.min=="object"&&n.min!==null&&"date"in n.min&&!("min"in n.min)){const s=n,l=s.min,m=s.max,S=l?.date&&l.date!=="",T=m?.date&&m.date!=="";if(S&&!T){if(t==null)return!1;const f=t instanceof Date?t:new Date(t);if(isNaN(f.getTime()))return!1;const p=new Date(l.date+(l.time?`T${l.time}:00`:"T00:00:00"));return f>=p}if(!S&&T&&m){if(t==null)return!0;const f=t instanceof Date?t:new Date(t);if(isNaN(f.getTime()))return!1;const p=new Date(m.date+(m.time?`T${m.time}:00`:"T23:59:59"));return f<=p}if(S&&T&&m){if(t==null)return!1;const f=t instanceof Date?t:new Date(t);if(isNaN(f.getTime()))return!1;const p=new Date(l.date+(l.time?`T${l.time}:00`:"T00:00:00")),j=new Date(m.date+(m.time?`T${m.time}:00`:"T23:59:59"));return f>=p&&f<=j}return!0}const i=n,d=typeof i.min=="string"&&i.min!=="",g=typeof i.max=="string"&&i.max!=="";if(d&&!g){if(t==null)return!1;const s=t instanceof Date?t:new Date(t);return isNaN(s.getTime())?!1:s>=new Date(i.min)}if(!d&&g){if(t==null)return!0;const s=t instanceof Date?t:new Date(t);return isNaN(s.getTime())?!1:s<=new Date(i.max)}if(d&&g){if(t==null)return!1;const s=t instanceof Date?t:new Date(t);return isNaN(s.getTime())?!1:s>=new Date(i.min)&&s<=new Date(i.max)}return!0}}if(typeof n=="string"&&D(e)==="rating"){if(t==null)return!1;const r=Number(n),o=typeof t=="number"?t:Number(t);return isNaN(r)||isNaN(o)?!1:o>=r}const N=D(e);return N?N==="address"?t==null?!1:typeof t=="object"&&"formatted_address"in t?String(t.formatted_address).toLowerCase().includes(String(n).toLowerCase()):!1:b.has(N)?x(t,[n],y):t==null?!1:String(t).toLowerCase().includes(String(n).toLowerCase()):!0}export{I as matchesFilter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CRUD_OPERATION as a}from"../types";function n(o,
|
|
1
|
+
import{CRUD_OPERATION as a}from"../types";function n(o,t){const s=[],c=new Set;for(const p of o){const i=t[p.id];i?.operation!==a.DELETE&&(i?.operation===a.UPDATE&&i.optimisticData?s.push(i.optimisticData):s.push(p),c.add(p.id))}for(const[p,i]of Object.entries(t))i.operation===a.ADD&&!c.has(p)&&i.optimisticData&&s.push(i.optimisticData);return s}function D(o,t){return t?t.operation===a.DELETE?null:t.operation===a.UPDATE&&t.optimisticData?o?{...o,...t.optimisticData}:t.optimisticData:t.operation===a.ADD&&!o&&t.optimisticData?t.optimisticData:o:o}export{D as applyOptimisticToDoc,n as mergeWithOptimistic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getEntityByCollection as
|
|
1
|
+
import{getEntityByCollection as e}from"@donotdev/core";const c=new Set;function n(t,o){return e(t)}export{n as resolveReferenceEntity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";function u(
|
|
1
|
+
"use client";function u(r){return!r||typeof r!="string"?!1:r.startsWith("https://")&&!r.startsWith("blob:")}function h(r){return!(!r||typeof r!="object"||!u(r.fullUrl)||r.thumbUrl&&!u(r.thumbUrl))}function i(r,l=""){const t=[];if(r==null)return t;if(typeof r=="string")return r.startsWith("blob:")&&t.push(l||"root"),t;if(typeof r!="object")return t;if(Array.isArray(r))r.forEach((s,o)=>{const n=l?`${l}[${o}]`:`[${o}]`;t.push(...i(s,n))});else{const s=r;if(s.fullUrl!==void 0&&s.thumbUrl!==void 0){const o=s.fullUrl,n=s.thumbUrl,e=typeof o=="string"&&!u(o),c=n&&typeof n=="string"&&!u(n);if(e||c){const f=l||"root";t.push(`${f}.fullUrl or ${f}.thumbUrl contains blob URL`)}}else Object.entries(s).forEach(([o,n])=>{const e=l?`${l}.${o}`:o;t.push(...i(n,e))})}return t}function b(r){return i(r).length>0}export{i as checkForBlobUrls,b as hasBlobUrls,u as isStorageUrl,h as validatePicture};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as u,useMemo as f}from"react";import{getTranslatedFieldNames as m,translateRow as c,useTranslation as g}from"@donotdev/core";const p=
|
|
1
|
+
import{useCallback as u,useMemo as f}from"react";import{getTranslatedFieldNames as m,translateRow as c,useTranslation as g}from"@donotdev/core";const p=e=>e;function d(e,n){const{language:o}=g(),r=n.translate??!0,s=(typeof e=="string"?n.entity:e)?.fields??null,a=f(()=>s?m(s):[],[s]),l=r&&a.length>0,i=u(t=>t&&typeof t=="object"?c(t,a,o):t,[a,o]);return l?i:p}export{d as useRowTranslator};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e
|
|
1
|
+
function n(e){return e}export{n as defineWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useState as g,useCallback as p,useMemo as h,useEffect as L,useRef as M}from"react";import{evaluateCondition as R}from"@donotdev/core";import{saveWorkflowState as K,loadWorkflowState as j,clearWorkflowState as C}from"./WorkflowPersistence";function V(e,
|
|
1
|
+
"use client";import{useState as g,useCallback as p,useMemo as h,useEffect as L,useRef as M}from"react";import{evaluateCondition as R}from"@donotdev/core";import{saveWorkflowState as K,loadWorkflowState as j,clearWorkflowState as C}from"./WorkflowPersistence";function V(e,I={}){const{onComplete:m,onStepChange:f,defaultValues:y}=I,w=M(m);w.current=m;const[a,v]=g(()=>{if(e.persist){const t=j(e.persistKey??e.id);if(t)return t.stepData}if(y){const t={};for(const r of e.steps)if(r.entity&&r.fields){const o={};for(const i of r.fields)i in y&&(o[i]=y[i]);Object.keys(o).length>0&&(t[r.id]=o)}return t}return{}}),[s,S]=g(()=>{if(e.persist){const t=j(e.persistKey??e.id);if(t)return t.currentStepIndex}return 0}),[k,x]=g(!1),l=h(()=>{const t={};for(const[r,o]of Object.entries(a))for(const[i,c]of Object.entries(o))t[i]=c,t[`${r}.${i}`]=c;return t},[a]),n=h(()=>e.steps.filter(t=>t.conditions?.visible?R(t.conditions.visible,l):!0),[e.steps,l]),O=n[s]??n[0],b=s===0,d=s===n.length-1;L(()=>{e.persist&&K(e.persistKey??e.id,{currentStepIndex:s,stepData:a,savedAt:Date.now()})},[e.persist,e.persistKey,e.id,s,a]);const W=p(async t=>{const r=n[s];if(!r)return!1;if(t&&v(i=>({...i,[r.id]:{...i[r.id],...t}})),r.validation?.validate){const i={...l,...t??{}};if(r.validation.validate(i)!==!0)return!1}if(r.after){const i={};await r.after({data:t??a[r.id]??{},allData:{...l,...t??{}},next:{prefill:c=>{const u=n[s+1];u&&(i[u.id]=c)}}}),Object.keys(i).length>0&&v(c=>{const u={...c};for(const[D,G]of Object.entries(i))u[D]={...u[D],...G};return u})}if(d){x(!0);try{const i={...l,...t??{}},c=w.current??e.onComplete;return c&&await c(i),e.persist&&C(e.persistKey??e.id),!0}catch{return!1}finally{x(!1)}}const o=s+1;return S(o),f?.(s,o),!0},[n,s,l,a,d,e,f]),N=p(()=>{if(b)return;const t=s-1;S(t),f?.(s,t)},[s,b,f]),A=p(()=>{if(!n[s]?.allowSkip||d)return;const t=s+1;S(t),f?.(s,t)},[n,s,d,f]),E=p(t=>{t>=0&&t<n.length&&(f?.(s,t),S(t))},[n.length,s,f]),P=p(()=>{e.persist&&K(e.persistKey??e.id,{currentStepIndex:s,stepData:a,savedAt:Date.now()})},[e,s,a]),$=p(()=>{C(e.persistKey??e.id)},[e]),F=p((t,r)=>{v(o=>({...o,[t]:{...o[t],...r}}))},[]);return{currentStep:O,currentStepIndex:s,visibleSteps:n,stepData:a,allData:l,goNext:W,goPrevious:N,skipStep:A,goToStep:E,isFirst:b,isLast:d,isSubmitting:k,canGoNext:!k,persistNow:P,clearPersisted:$,prefillStep:F}}export{V as useEntityWorkflow};
|
package/guidelines/CRUD.md
CHANGED
|
@@ -57,7 +57,8 @@ The `status` field is auto-added by `defineEntity()` with sensible defaults:
|
|
|
57
57
|
**Status matrix (SSOT: `STATUS_MATRIX`, `@donotdev/types`).** One table says what each status can do: `draft` (read: admin, saveIncomplete, holdIncomplete), `available` (read: guest, isDefault), `deleted` (read: admin, holdIncomplete, isRemoved). App-added statuses behave like `available`. Code asks it (`statusCan(status, capability)`, `statusReadableBy(status, role)`, `statusesThat(capability)`), never names a status; the entity-derived types (rows, forms, inputs) read the same columns.
|
|
58
58
|
1. Create validates everything. 2. Update validates what changes (a required field it sends cannot be emptied, except on a draft). 3. `delete(id)` is the hard delete; `remove(id)` the logical delete (the `isRemoved` status, nothing else validated). 4. A row is read only by roles that reach its status's `read` role. 5. A status that `saveIncomplete` saves without its required fields; leaving a status that may `holdIncomplete` for one that may not checks the whole record. 6. Apps add statuses; they are strict like `available`. 7. No status sent → the `isDefault` status; the caller overrides it (`defaultValues.status`, payload `status`). 8. Fields the entity does not have are not written and warn the user (client toast, server log). 9. Field behaviour comes from the entity (`editable`, `visibility`, `computed` / `generated`).
|
|
59
59
|
An update needs the stored row (its status, and the whole-record check): writers take the caller's (`bulkAcross` update `stored`, the form's `record`), else the cache, else read it once.
|
|
60
|
-
- **`tel`:** international (`+` country code, 8 to 15 digits, as E.164: `+33 6 12 34 56 78`, `+33612345678`) or French national (`06 12 34 56 78`, `0612345678`, `06.12.34.56.78`); spaces, dots or dashes between digits. `validation.pattern` replaces the rule. The phone field stores `<dial code> <number
|
|
60
|
+
- **`tel`:** international (`+` country code, 8 to 15 digits, as E.164: `+33 6 12 34 56 78`, `+33612345678`) or French national (`06 12 34 56 78`, `0612345678`, `06.12.34.56.78`); spaces, dots or dashes between digits. `validation.pattern` replaces the rule. The phone field stores `<dial code> <number>` with separators stripped and the trunk `0` dropped (`06.12.34.56.78` → `+33 612345678`); a number typed with the selected dial code (`+33 6 12…`, `+33612…`, `0033612…`) keeps one dial code, one with another `+` code is stored as typed (`+447911123456`); nothing typed, or the dial code alone (`+33`), stores `null`.
|
|
61
|
+
- **Error messages (entity forms):** translated, never the schemas' English or valibot's raw text (`Invalid type: Expected string but received null`). Empty value (`null`, `''`) → `crud:text.required`; a `validation.schema` message is a key of the entity namespace (`v.regex(SIRET, 'siretFormat')` → `t('siretFormat')`, a sentence or a missing key → `crud:text.invalid`); `minLength` / `maxLength` / `min` / `max` → `crud:text.minLength` / `maxLength`, `crud:number.min` / `max`; `tel` → `crud:text.phone`, `email` → `crud:text.email`, `url` → `crud:text.url`, date and time types → `crud:date.format`; anything else → `crud:text.invalid`. `createSchemas` (shared with the server) keeps its messages.
|
|
61
62
|
|
|
62
63
|
If you don't define `status` in your fields at all, the full default is added automatically. If you define it, your properties are merged on top of defaults:
|
|
63
64
|
|
|
@@ -288,6 +289,7 @@ const form = useEntityForm(productEntity, {
|
|
|
288
289
|
- **Edit stored values.** Read with `useCrudDoc(entity, id, { translate: false })` before passing `defaultValues`; do not save translated record content back as the default-language value.
|
|
289
290
|
- **Submit through `form.handleSubmit`.** It validates/orchestrates the form; your submit callback performs the CRUD write (or omit it: `form.handleSubmit()` is the default writer, record + joined child rows in one `bulkAcross` — see [Child rows](#child-rows-saved-with-their-record); with a callback, add `form.pendingWrites()` to your write when child rows join the form or `extend` is set; record + 1:1 extensions with `extend`, see [1:1 extension](#11-extension-extend)). Reject on a failed write so submission does not acknowledge it as saved. Success acknowledges the editor snapshot taken before async validation, with pending upload previews replaced by the submitted stored assets. Upload normalization alone stays clean; later edits (including changes to upload fields) stay visible, dirty and in the local draft. Right before your callback runs, the editor is written to the local draft (no 3s autosave wait), so a rejected write keeps every edit even if the page has unmounted; success clears it.
|
|
290
291
|
- **Saving leaves the page by default (optimistic).** Once validation and uploads pass, the form navigates to `successPath` before your callback runs: omitted = the previous breadcrumb (nearest existing parent route, else `/`), a path = that path. If the callback rejects, it navigates back to the page it left and the draft restores the edits. Same option on `EntityFormRenderer` (`successPath`). Router access comes from `@donotdev/ui` (`UIProviders` fills crud's `FormNavigationProvider`); without it the form stays. Pass `successPath: null` to stay: dialogs, wizards, settings pages, create flows that open the new record, pages with other unsaved state (e.g. pending table edits), and **every** form of a nested submit (leaving unmounts the inner form and cancels its save). Per submit: `form.handleSubmit(onValid, onInvalid, { successPath })` overrides the hook option for that submit (key present wins, `undefined` = previous breadcrumb) — e.g. Save on a draft passes `null`, Publish on the same form passes nothing.
|
|
292
|
+
- **Toasts are opt-out.** A submit that fails validation toasts the fields to correct, and a restored draft toasts "Draft restored"; `useEntityForm(entity, { toasts: false })` drops both (field messages, the scroll to the first one and the draft restoring stay), e.g. a form in a sheet. Success toasts: `{ showSuccessToast: false }` per mutation, `useCrudStore.getState().setHideSuccessToasts(true)` globally.
|
|
291
293
|
- **Page state saved by the same Save goes in the form's draft.** `const [ids, setIds] = useFormDraftState(form, 'productIds', initialIds, { parse })` is `useState` kept in the form's draft: autosaved with it, written at submit, restored with the form ("Draft restored" toast), reset by Discard / `resetForm`, cleared on success, kept on failure (also after the page left optimistically). Use it for product lists or pending table edits a page Save writes; values must be JSON. A value different from `initial` is an edit (it keeps the draft like a dirty field). `parse` (required) validates the value read back from browser storage (untrusted, possibly from an older page version) and may adjust it (e.g. drop pending edits that already equal the loaded record); if it throws, the slot keeps `initial` and a warning is logged.
|
|
292
294
|
- **A draft exists only while the page holds edits.** Edited = a field dirty in React Hook Form (against `defaultValues`, which always stay the base: the stored record on edit, the caller/schema defaults on create), a `useFormDraftState` slot different from its initial value, or joined child rows with edits. Autosave and the submit-time save write the draft only then, and clear it otherwise. A restored draft is applied as dirty edits on top of the base (`isDirty` / `dirtyFields` are right at once); one with no edit against the base is cleared without a toast.
|
|
293
295
|
- **Create defaults do not disable drafts.** With `operation: 'create'`, caller defaults override schema defaults, then restored drafts merge onto that base (nested objects merge; arrays replace). Discard restores the schema/caller base. Draft autosaving is browser-local only, including edits made while a submission is pending; it performs no CRUD writes. Leaving the page (unmount) writes a pending 3s autosave immediately, so an accidental leave keeps the last edits; the "Draft restored" toast offers Discard on return. There is no leave-time prompt.
|
package/guidelines/GOTCHAS.md
CHANGED
|
@@ -31,6 +31,8 @@ status: { visibility: 'technical' }
|
|
|
31
31
|
|
|
32
32
|
**Empty is `null`, never `''`.** Entity forms store an empty text input as `null` (form state, validated data, adapter payload); `''` exists only in the DOM. An optional field left empty passes its format rules; a `required` field left empty fails.
|
|
33
33
|
|
|
34
|
+
**Custom schema messages are i18n keys.** A `validation.schema` message (`v.regex(SIRET, 'siretFormat')`) is shown as `t('siretFormat')` in the entity namespace; add the key to the entity locales, or the form shows `crud:text.invalid`. A sentence as message is never shown. See CRUD → Validation rules (error messages).
|
|
35
|
+
|
|
34
36
|
**Field `type` is a closed union.** Built-ins plus the custom types declared in `CustomFieldOptionsMap` (module augmentation of `@donotdev/core`). A typo or an undeclared custom type fails typecheck; a declared type with no `registerFieldType()` throws at render. No text-input fallback.
|
|
35
37
|
|
|
36
38
|
**`datetime-local` stores an ISO instant, displays local time.** The form shows the viewer's local wall time and saves `toISOString()` (UTC). Do not convert in the app.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donotdev/crud",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -56,8 +56,8 @@
|
|
|
56
56
|
"@dnd-kit/core": "^6.3.1",
|
|
57
57
|
"@dnd-kit/sortable": "^10.0.0",
|
|
58
58
|
"@dnd-kit/utilities": "^3.2.2",
|
|
59
|
-
"@donotdev/components": "^0.3.
|
|
60
|
-
"@donotdev/core": "^0.3.
|
|
59
|
+
"@donotdev/components": "^0.3.4",
|
|
60
|
+
"@donotdev/core": "^0.3.3",
|
|
61
61
|
"react-easy-crop": "^5.5.7"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|