@donotdev/crud 0.3.1 → 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.d.ts +8 -0
- package/dist/CrudService.cache.d.ts.map +1 -1
- package/dist/CrudService.cache.js +1 -1
- package/dist/CrudService.d.ts +7 -2
- package/dist/CrudService.d.ts.map +1 -1
- package/dist/CrudService.internal.js +2 -2
- package/dist/CrudService.js +1 -1
- package/dist/CrudService.mutations.js +1 -1
- package/dist/CrudService.optimistic.js +1 -1
- package/dist/CrudService.queries.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/FieldRegistry.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.d.ts.map +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/FormLayout.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/complex/ControlledTimestampField.js +1 -1
- package/dist/components/controlled/complex/index.js +1 -1
- package/dist/components/controlled/fieldOptions.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/ControlledMultiFileField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiImageField.js +1 -1
- package/dist/components/controlled/file/index.js +1 -1
- package/dist/components/controlled/index.js +1 -1
- package/dist/components/controlled/input/ControlledCheckboxField.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/ControlledPriceField.js +1 -1
- package/dist/components/controlled/input/ControlledRangeField.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/input/ControlledTextareaField.js +1 -1
- package/dist/components/controlled/input/index.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/select/ControlledYearField.js +1 -1
- package/dist/components/controlled/select/index.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/BadgeFieldDisplay.js +1 -1
- package/dist/components/fields/display/ButtonFieldDisplay.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/DropdownDisplay.js +1 -1
- package/dist/components/fields/display/FileFieldDisplay.js +1 -1
- package/dist/components/fields/display/GeoPointFieldDisplay.js +1 -1
- package/dist/components/fields/display/HiddenFieldDisplay.js +1 -1
- package/dist/components/fields/display/ImageFieldDisplay.js +1 -1
- package/dist/components/fields/display/LinkFieldDisplay.js +1 -1
- package/dist/components/fields/display/MapFieldDisplay.js +1 -1
- package/dist/components/fields/display/MultiDropdownDisplay.js +1 -1
- package/dist/components/fields/display/MultiInputTextFieldDisplay.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/PhoneNumberDisplay.js +1 -1
- package/dist/components/fields/display/RadioFieldDisplay.js +1 -1
- package/dist/components/fields/display/RangeFieldDisplay.js +1 -1
- package/dist/components/fields/display/ReferenceFieldDisplay.js +1 -1
- package/dist/components/fields/display/RichTextDisplay.js +2 -2
- package/dist/components/fields/display/TextAreaDisplay.js +1 -1
- package/dist/components/fields/display/TextFieldDisplay.js +1 -1
- package/dist/components/fields/display/TimestampFieldDisplay.js +1 -1
- package/dist/components/fields/display/index.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/CheckboxFieldComponent.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/HiddenFieldComponent.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/SwitchFieldComponent.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/index.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/components/index.js +1 -1
- package/dist/contexts/UploadContext.js +1 -1
- package/dist/contexts/index.js +1 -1
- package/dist/fieldTypeRegistry.js +1 -1
- package/dist/fieldTypeRegistry.store.js +1 -1
- package/dist/forms/FormNavigation.js +1 -1
- package/dist/forms/childRows.js +1 -1
- package/dist/forms/extend.js +1 -1
- package/dist/forms/hooks/index.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/index.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/index.js +1 -1
- package/dist/forms/utils/isFieldEditable.js +1 -1
- package/dist/forms/utils/translateFieldLabel.js +1 -1
- package/dist/forms/utils/validateEntity.js +1 -1
- package/dist/forms/utils/writableFields.js +1 -1
- package/dist/hooks/index.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/useFieldConditions.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/index.js +1 -1
- package/dist/registerBuiltinFieldTypes.js +1 -1
- package/dist/stores/FormStore.js +1 -1
- package/dist/stores/UploadStore.js +1 -1
- package/dist/stores/index.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/types.d.ts +4 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/useBaseCrudList.js +1 -1
- package/dist/useCrud.js +1 -1
- package/dist/useCrudCardList.js +1 -1
- package/dist/useCrudDoc.d.ts +8 -1
- package/dist/useCrudDoc.d.ts.map +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/fileStorage.js +1 -1
- package/dist/utils/filterUrl.js +1 -1
- package/dist/utils/imageProcessing.js +1 -1
- package/dist/utils/imageStorage.js +1 -1
- package/dist/utils/imageUtils.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/routeRecord.d.ts +21 -0
- package/dist/utils/routeRecord.d.ts.map +1 -0
- package/dist/utils/routeRecord.js +1 -0
- package/dist/utils/sanitizeHtml.js +1 -1
- package/dist/utils/scopeUtils.js +1 -1
- package/dist/utils/uploadValidation.js +1 -1
- package/dist/utils/useRowTranslator.js +1 -1
- package/dist/workflows/WorkflowPersistence.js +1 -1
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/useEntityWorkflow.js +1 -1
- package/guidelines/COMPONENTS.md +1 -1
- package/guidelines/CRUD.md +6 -2
- package/guidelines/GOTCHAS.md +2 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useMemo as q,useEffect as A,useId as zt,useRef as v,useState as ke,createElement as Ht}from"react";import{useForm as qt}from"react-hook-form";import{toast as je,ToastAction as _t}from"@donotdev/components";import{createSchemas as Jt,statusOf as Xt,useTranslation as Gt}from"@donotdev/core";import{childRowsKey as Qt,extensionMintKey as nt,useFormStore as l,useFormStatus as Yt,useUploadProgress as Zt}from"../../stores";import{useExtensionRows as er}from"../../hooks/useExtensionRows";import{getCrudServiceInstance as ce}from"../../useCrud";import{hasChildEdits as Q,mergeBatches as tr,pickFields as Y,rebaseChildEdits as rr,schemasOf as nr,writableFields as or}from"../childRows";import{extensionFields as sr,extensionWritable as ot,extensionsSignature as ir,resolveExtensions as cr,setAtPath as ar,splitExtensionField as Oe,withoutLinkField as lr}from"../extend";import{useFormNavigation as ur}from"../FormNavigation";import{getLoadedUploadStore as Ie}from"../../stores/uploadStoreRef";import{checkForBlobUrls as dr,isStorageUrl as fr}from"../../utils/uploadValidation";import{injectScope as Ve}from"../../utils/scopeUtils";import{getFieldsForOperation as mr,translateFieldLabel as gr}from"../utils";import{createConditionAwareResolver as st,getFormConditionStates as Ce}from"../utils/conditionAwareResolver";import{buildInitialFromRecord as it,buildSchemaDefaults as ct}from"../utils/buildInitialValues";const at="@childRows",xe="@record",pr=o=>new Set([...o].map(b=>Oe(b)?.[1]??b)),Pe=(o,b,c)=>pr(ot(o,b,c));function $(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function lt(o){return $(o)?o.updatedAt:void 0}function ut(o,b){const c={...o};for(const U of Object.keys(b)){const E=o[U],T=b[U];T!==null&&typeof T=="object"&&!Array.isArray(T)&&E!==null&&typeof E=="object"&&!Array.isArray(E)?c[U]=ut(E,T):c[U]=T}return c}function ae(o){if(o==null)return o;if(typeof o=="string")return o.startsWith("blob:")?null:o;if(Array.isArray(o)){const b=o.map(ae).filter(c=>c!==null);return b.length>0?b:null}if(typeof o=="object"){const b=o;if("fullUrl"in b&&typeof b.fullUrl=="string")return fr(b.fullUrl)?b:null;const c={};for(const[U,E]of Object.entries(b))c[U]=ae(E);return c}return o}function Mr(o,b={}){const{formId:c,operation:U,defaultValues:E,viewerRole:T,mode:dt="onBlur",t:ft,loading:Ae=!1,successPath:mt,extend:Ue}=b,_=ur(),w=T??"guest",gt=ir(Ue),m=q(()=>cr(o,Ue,w).filter(e=>e.readable),[o,gt,w]),{t:pt}=Gt([o.namespace,"crud",...m.map(e=>e.entity.namespace)]),S=ft??pt,u=U??(E?"edit":"create"),Z=E?.id,Me=er(m,u==="edit"&&Z?[Z]:[],!Ae),le=e=>Z?Me[e]?.byRecord.get(Z):void 0,L=e=>u==="edit"&&le(e)?"edit":"create",ee=m.map(e=>le(e.key)),ht=m.map(e=>`${e.key}:${L(e.key)}`).join("|"),W=Ae||Object.values(Me).some(e=>e.loading),bt=Yt(c??""),wt=Zt(c??""),k=E,$e=Xt(k),C=q(()=>or(o,w,u),[o,w,u]),St=q(()=>{const e=st(o,u,C,k),r=(n,s,i)=>e(u==="edit"?n:Ve(n,o.scope),s,i);if(m.length===0)return r;const t=m.map(n=>({key:n.key,resolve:st(lr(n),L(n.key),Pe(n,w,L(n.key)))}));return async(n,s,i)=>{const a=await r(n,s,i),h={...a.errors},g={...a.values},p={criteriaMode:i.criteriaMode,fields:i.fields,shouldUseNativeValidation:i.shouldUseNativeValidation};for(const{key:I,resolve:D}of t){const z=n[I],y=await D($(z)?z:{},s,p);Object.keys(y.errors).length>0?h[I]=y.errors:g[I]=y.values}return Object.keys(h).length>0?{values:{},errors:h}:{values:g,errors:{}}}},[o,u,C,k,m,ht,w]),te=q(()=>ct(o,C),[o,C]),R=q(()=>{if(W)return;const e=u==="edit"?k?it(o,k,{fields:C,keepId:!0}):void 0:k?Y({...te,...k},C):te;if(!e||m.length===0)return e;const r={...e};return m.forEach((t,n)=>{const s=ee[n],i=Pe(t,w,s?"edit":"create");r[t.key]=s?it(t.entity,s,{fields:i,keepId:!0}):ct(t.entity,i)}),r},[W,u,te,o,k,C,w,m,...ee]),ue=q(()=>{if(u!=="edit"||W||!k)return;const e={...k};return m.forEach((r,t)=>{const n=ee[t];n&&(e[r.key]=n)}),e},[u,W,k,m,...ee]),[yt,de]=ke(null),fe=yt??ue,me=v(fe);me.current=fe;const ge=e=>{const r=Y(e,C);u==="edit"&&Object.hasOwn(e,"id")&&(r.id=e.id);for(const t of m){const n=e[t.key];if(!$(n))continue;const s=L(t.key),i=Y(n,Pe(t,w,s));s==="edit"&&Object.hasOwn(n,"id")&&(i.id=n.id),r[t.key]=i}return r},d=qt({defaultValues:u==="create"?R:void 0,mode:dt,resolver:St,shouldUnregister:!1,shouldFocusError:!1});A(()=>{let e=Ce(o,d.getValues()),r=!0,t=!1;const n=new Set,s=async()=>{if(!t){t=!0;try{for(;r&&n.size>0;){const a=[...n];if(n.clear(),await d.trigger(a),!r)return;for(const h of Ce(o,d.getValues()))h.visible||d.clearErrors(h.name)}}finally{t=!1}}},i=d.watch(()=>{const a=Ce(o,d.getValues()),h=a.filter((g,p)=>g.visible!==e[p]?.visible||g.required!==e[p]?.required);e=a;for(const g of h){const p=g.name;g.visible||d.clearErrors(p),n.add(p)}n.size>0&&s()});return()=>{r=!1,n.clear(),i.unsubscribe()}},[o,d]);const x=v(d);A(()=>{x.current=d},[d]);const re=v(null);A(()=>{if(u==="edit"&&R){const e=R.id??null;e&&e!==re.current?(x.current.reset(R),re.current=e):!e&&re.current===null&&(x.current.reset(R),re.current="initialized")}},[u,R]);const j=E?.id,pe=`${o.name.toLowerCase()}-form-draft${c?`-${c}`:""}`,F=u==="create"?pe:j?`${pe}-${j}`:`${pe}-edit`,K=v(!1),P=zt(),O=u==="edit"?j:void 0,J=e=>O?Object.keys(e).flatMap(r=>{const[t,n,s,i]=r.split("\0");return t===P&&n===O&&s&&i?[[r,s,i]]:[]}):[],Te=()=>{const{childEdits:e,childWriters:r}=l.getState();return J(e).flatMap(([t,n,s])=>{const i=e[t];if(!Q(i))return[];const a=r[t];if(!a)throw new Error(`useEntityForm(${o.name}): joined rows ${n}.${s} have edits but no useChildRows registered how to write them.`);return[{key:t,collection:n,field:s,writer:a,edits:i}]})},Le=()=>{const{childEdits:e,childDrafts:r}=l.getState(),t={};for(const[n,s,i]of J(r))t[s]={...t[s],[i]:r[n]};for(const[n,s,i]of J(e)){const a=e[n];Q(a)&&(t[s]={...t[s],[i]:a})}return Object.keys(t).length>0?t:void 0},vt=e=>{if(!(e===void 0||!O)&&$(e)){for(const[r,t]of Object.entries(e))if($(t))for(const[n,s]of Object.entries(t))l.getState().setChildDraft(Qt(P,O,r,n),s)}},M=v(new Map),ne=v(null),he=()=>{if(M.current.size===0)return;const e={};for(const[r,t]of M.current)e[r]=t.get();return e},We=(e=!0)=>{const r=he(),t=Le(),n=e&&u==="edit"?me.current:void 0;return!t&&!n?r:{...r,...t&&{[at]:t},...n&&{[xe]:n}}},Rt=e=>{e!==void 0&&(!$(e)||!O||e.id!==O||de(e))},Et=()=>{const e=x.current;return Object.keys(e.getValues()).some(r=>e.getFieldState(r).isDirty)},Ke=()=>Et()||[...M.current.values()].some(e=>e.edited())||Le()!==void 0,Ft=e=>{if(ne.current=e??null,!!e){for(const[r,t]of M.current)r in e&&t.restore(e[r]);vt(e[at]),Rt(e[xe])}},Be=()=>{ne.current=null,de(null);for(const r of M.current.values())r.reset();const e=l.getState();for(const[r]of J(e.childEdits))e.setChildEdits(r,null);for(const[r]of J(e.childDrafts))e.setChildDraft(r,null)},oe=v(()=>{}),[Dt]=ke(()=>({register:(e,r)=>{M.current.set(e,r);const t=ne.current;return t&&e in t&&r.restore(t[e]),()=>{M.current.get(e)===r&&M.current.delete(e)}},changed:()=>oe.current()})),Ne=v(W);Ne.current&&!W&&(K.current=!1),Ne.current=W;const kt=e=>{l.getState().clearDraft(F),x.current.reset(e),Be()},[be,ze]=ke(null);A(()=>{if(!be)return;ze(null);const{base:e,conflict:r}=be;if(!Ke()){l.getState().clearDraft(F),ne.current=null,de(null);return}je({toastType:r?"warning":"info",title:S(r?"crud:draft.conflict":"crud:draft.restored"),description:S(r?"crud:draft.conflictDescription":"crud:draft.restoredDescription"),action:Ht(_t,{altText:S("crud:draft.discard"),onClick:()=>kt(e)},S("crud:draft.discard")),duration:r?1/0:8e3})},[be]),A(()=>{if(K.current)return;const e=l.getState().loadDraft(F),r=t=>{if(!e)return;const n=e.extras?.[xe];d.reset(t);const s=ge(ut(t,e.data));for(const[i,a]of Object.entries(s))d.setValue(i,a,{shouldDirty:!0});Ft(e.extras),ze({base:t,conflict:u==="edit"&&n!==void 0&<(n)!==lt(ue)})};if(u==="create"&&R){e?r(R):d.reset(R),K.current=!0;return}u==="edit"&&R&&(r(R),K.current=!0)},[u,E,F,d,R,ue,S,te]);const B=v(null),se=()=>{B.current&&clearTimeout(B.current),B.current=null},He=()=>{if(!Ke()){l.getState().clearDraft(F);return}l.getState().saveDraft(F,ae(ge(x.current.getValues())),o.name,j,We())},qe=()=>{He()},we=v(qe);we.current=qe,oe.current=()=>{K.current&&(se(),B.current=setTimeout(()=>{B.current=null,we.current()},3e3))},A(()=>{const e=d.watch(()=>oe.current()),r=we.current;return()=>{e.unsubscribe(),B.current&&(se(),r())}},[d,F,o.name,j]);const _e=v(w);_e.current=w,A(()=>{if(O)return l.getState().openRecord({formKey:P,collection:o.collection,recordId:O,viewerRole:_e.current,submitting:!1,changed:()=>oe.current()}),()=>l.getState().closeRecord(P)},[P,o.collection,O]),A(()=>{l.getState().updateOpenRecord(P,{viewerRole:w})},[P,w]);const N=v(null),X=v(!1),jt=async e=>{if(!c)return{};const r=Ie();if(!r)return{};const t=r.getState(),n=l.getState();if(!t.hasPendingUploads(c))return{};const s=setInterval(()=>{const i=r.getState().getTotalProgress(c);l.getState().setUploading(c,i)},200);try{return n.setUploading(c,0),await t.uploadAll(c,e),e?.aborted?null:r.getState().getResults(c)}catch(i){const h=r.getState().uploads[c];h&&Object.entries(h).forEach(([p,I])=>{I.status==="error"&&I.error&&d.setError(p,{type:"upload",message:I.error})});const g=i instanceof Error?i.message:S("crud:form.uploadFailed");return l.getState().setError(c,g),null}finally{clearInterval(s)}},Je=(e,r)=>{let t={...e};for(const[n,s]of Object.entries(r)){const i=Oe(n);t=i&&m.some(a=>a.key===i[0])?ar(t,n,s):{...t,[n]:s}}return t},Se=(e,r)=>{const t={...r};for(const[n,s]of Object.entries(e.fields))if(s.type==="price"&&n in t){const i=t[n];(i==null||i.amount==null)&&(t[n]=null)}return t},Ot=(e,r)=>{if(typeof HTMLFormElement>"u"||!(r instanceof HTMLFormElement))return;const t=Object.keys(e).filter(s=>s!=="root"),n=r.querySelectorAll("input, textarea, select, button, [tabindex]");for(const s of n){const i=s.getAttribute("name");if(!(!(s.getAttribute("aria-invalid")==="true"||i!==null&&t.some(h=>i===h||i.startsWith(`${h}.`)))||s.matches(':disabled, input[type="hidden"]')||s.closest('[hidden], [inert], [aria-hidden="true"]')||s.getClientRects().length===0)&&(s.focus(),s.ownerDocument.activeElement===s)){s.scrollIntoView({behavior:"smooth",block:"center"});return}}},ye=v(null),ve=v(null),Re=v(!1),Ee=`record\0${F}`,Fe=()=>m.filter(e=>L(e.key)==="edit"?e.update:e.create),It=(e,r)=>Fe().map(t=>{const n=L(t.key),s=new Set([...ot(t,w,n)].map(p=>Oe(p)?.[1]??p)),i=e[t.key],a=Se(t.entity,Y($(i)?i:{},s)),h=nr(t.entity),g=le(t.key);if(g)return{collection:t.entity.collection,updates:[{id:g.id,patch:a,stored:g}],schemas:h};if(!r)throw new Error(`useEntityForm(${o.name}): inserting extension "${t.key}" on create needs the record id: pendingWrites({ recordId }) (pre-mint it).`);return{collection:t.entity.collection,inserts:[Ve({...a,id:l.getState().mintId(nt(t.entity.collection,r)),[t.field]:r},t.entity.scope)],schemas:h,...u==="create"&&{dependsOn:[o.collection]}}}),Vt=async()=>{const e=ce();if(!e)throw new Error(S("crud:form.saveFailed"));if(u!=="edit"||!j)throw new Error(`useEntityForm(${o.name}): remove() needs an edited record (defaultValues.id).`);await e.remove(o.collection,j),l.getState().clearDraft(F)},Xe=(e={})=>{Re.current=!0;const r=ye.current??Te(),t=ve.current??x.current.getValues();return tr([...It(t,O??e.recordId),...r.flatMap(({writer:n,edits:s})=>n.batches(s))])},Ge=e=>{let r=0;for(const{writer:n,edits:s}of e){const i=n.errors(s),a=Object.keys(i).length;a!==0&&(r+=a)}if(r===0)return!1;const t=S("crud:childRows.invalidRows",{count:r});return c?l.getState().setError(c,t):je({toastType:"error",title:t,duration:8e3}),!0},Ct=()=>!C.has("status")&&$e!==null?{status:$e}:{},xt=async e=>{const r=ce();if(!r)throw new Error(S("crud:form.saveFailed"));const t=Jt(o),n=Y(e,C);if(u==="edit"&&!j)throw new Error(`useEntityForm(${o.name}): the default writer needs defaultValues.id in edit mode.`);const s=u==="create"&&Fe().length>0?l.getState().mintId(Ee):void 0,i=u==="edit"&&j?{collection:o.collection,updates:[{id:j,patch:n,stored:me.current}],schemas:t}:{collection:o.collection,inserts:[Ve({...n,...Ct(),...s&&{id:s}},o.scope)],schemas:t};return r.bulkAcross([i,...Xe({recordId:s})])},Pt=d.handleSubmit,At=(e,r,t)=>async n=>{let s;n?.preventDefault?.();const i=n?.currentTarget;if(X.current)return;const a=c?l.getState():null,h=structuredClone(x.current.getValues()),g=Te().filter(({edits:p})=>Q(p));return await Pt(async(p,I)=>{if(X.current||Ge(g))return;X.current=!0,N.current?.abort();const D=new AbortController;N.current=D;let z=null;try{c&&a&&a.startSubmit(c);const y=await jt(D.signal);if(y===null||D.signal.aborted)return;c&&a&&a.setSubmitting(c);const Lt=Je(p,y),H=Se(o,Lt);for(const f of m){const V=H[f.key];$(V)&&(H[f.key]=Se(f.entity,V))}if(dr(H).length>0){c&&a&&a.setError(c,S("crud:form.reuploadFiles"));return}if(D.signal.aborted)return;const Wt=Je(h,structuredClone(y));K.current&&(se(),He());const Kt=new Map(Object.entries(he()??{}).map(([f,V])=>[f,JSON.stringify(V)])),Ze=t&&"successPath"in t?t.successPath:mt;if(_&&Ze!==null){const f=_.currentPath(),V=Ze??_.parentPath();V!==f&&(z=f,_.navigate(V))}if(ye.current=g,ve.current=H,Re.current=!1,l.getState().updateOpenRecord(P,{submitting:!0}),s=e?await e(H,I):await xt(H),[...g.map(({collection:f})=>f),...Fe().map(f=>f.entity.collection)].length>0&&!Re.current)throw new Error(S("crud:childRows.notSaved"));let et=!1;for(const{key:f,collection:V,edits:Nt}of g){const rt=l.getState().childEdits[f],G=rt?rr(rt,Nt):null;et||=!!G&&Q(G),l.getState().setChildEdits(f,G&&Q(G)?G:null),ce()?.invalidateCollection(V)}for(const f of m)ce()?.invalidateCollection(f.entity.collection);const Bt=l.getState().mintedIds[Ee],tt=O??Bt;l.getState().releaseMintedIds([Ee,...tt?m.map(f=>nt(f.entity.collection,tt)):[]]);const ie=x.current,De=ie.getValues();ie.reset(Wt,{keepValues:!0}),ie.reset(De,{keepDefaultValues:!0}),se(),Object.keys(De).some(f=>ie.getFieldState(f).isDirty)||Object.entries(he()??{}).some(([f,V])=>Kt.get(f)!==JSON.stringify(V))||et?l.getState().saveDraft(F,ae(ge(De)),o.name,j,We(!1)):l.getState().clearDraft(F),c&&a&&a.setSuccess(c)}catch(y){throw z!==null&&_?.navigate(z),c&&a&&a.setError(c,y instanceof Error?y.message:S("crud:form.saveFailed"),y),y}finally{if(X.current=!1,ye.current=null,ve.current=null,l.getState().updateOpenRecord(P,{submitting:!1}),N.current===D&&(N.current=null),c){const y=l.getState().forms[c]?.status;(y==="uploading"||y==="validating"||y==="submitting")&&l.getState().reset(c)}}},p=>{const I=Object.keys(p).filter(D=>D!=="root");je({toastType:"error",title:S("crud:form.validationFailed"),description:S("crud:form.fixFields",{fields:I.map(D=>gr(D,o.fields[D],S)).join(", ")}),duration:8e3}),Ge(g),Ot(p,i),r?.(p)})(n),s},Ut=()=>{l.getState().clearDraft(F),Be(),d.reset(R),K.current=!1},Qe=()=>{N.current?.abort(),c&&(l.getState().cleanup(c),Ie()?.getState().cleanup(c))};A(()=>Qe,[]);const Mt=()=>{N.current?.abort(),c&&(Ie()?.getState().abortAll(c),l.getState().reset(c)),X.current=!1},Ye=mr(o,{operation:u,viewerRole:w,availableFields:void 0}),$t=m.length===0?Ye:[...Ye,...m.flatMap(e=>sr(e,w,L(e.key)))],Tt=d.formState.isSubmitted||Object.keys(d.formState.touchedFields||{}).length>0;return{...d,handleSubmit:At,fields:$t,operation:u,record:fe,entity:o,t:S,viewerRole:w,formId:c,formStatus:c?bt:"idle",uploadProgress:c?wt:0,cleanup:Qe,cancel:Mt,isDirty:d.formState.isDirty,hasUserInteracted:Tt,resetForm:Ut,originalValues:R,draftState:Dt,pendingWrites:Xe,remove:Vt}}export{Mr as useEntityForm};
|
|
1
|
+
"use client";import{useMemo as B,useEffect as C,useId as Ht,useRef as S,useState as De,createElement as Jt}from"react";import{useForm as Gt}from"react-hook-form";import{toast as Re,ToastAction as Qt}from"@donotdev/components";import{createSchemas as Xt,statusOf as Yt,useTranslation as Zt}from"@donotdev/core";import{childRowsKey as _t,extensionMintKey as st,useFormStore as l,useFormStatus as er,useUploadProgress as tr}from"../../stores";import{useExtensionRows as rr}from"../../hooks/useExtensionRows";import{getCrudServiceInstance as ce}from"../../useCrud";import{hasChildEdits as Z,mergeBatches as nr,pickFields as _,rebaseChildEdits as or,schemasOf as ir,writableFields as sr}from"../childRows";import{extensionFields as ar,extensionWritable as at,extensionsSignature as cr,resolveExtensions as lr,setAtPath as ur,splitExtensionField as Ie,withoutLinkField as dr}from"../extend";import{useFormNavigation as fr}from"../FormNavigation";import{getLoadedUploadStore as Ae}from"../../stores/uploadStoreRef";import{checkForBlobUrls as mr,isStorageUrl as gr}from"../../utils/uploadValidation";import{injectScope as Ve}from"../../utils/scopeUtils";import{getFieldsForOperation as pr,translateFieldLabel as yr}from"../utils";import{createConditionAwareResolver as ct,getFormConditionStates as xe}from"../utils/conditionAwareResolver";import{buildInitialFromRecord as lt,buildSchemaDefaults as ut}from"../utils/buildInitialValues";const dt="@childRows",Ce="@record",hr=o=>new Set([...o].map(y=>Ie(y)?.[1]??y)),$e=(o,y,a)=>hr(at(o,y,a));function M(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function ft(o){return M(o)?o.updatedAt:void 0}function mt(o,y){const a={...o};for(const $ of Object.keys(y)){const F=o[$],T=y[$];T!==null&&typeof T=="object"&&!Array.isArray(T)&&F!==null&&typeof F=="object"&&!Array.isArray(F)?a[$]=mt(F,T):a[$]=T}return a}function le(o){if(o==null)return o;if(typeof o=="string")return o.startsWith("blob:")?null:o;if(Array.isArray(o)){const y=o.map(le).filter(a=>a!==null);return y.length>0?y:null}if(typeof o=="object"){const y=o;if("fullUrl"in y&&typeof y.fullUrl=="string")return gr(y.fullUrl)?y:null;const a={};for(const[$,F]of Object.entries(y))a[$]=le(F);return a}return o}function br(o,y={}){const{formId:a,operation:$,defaultValues:F,viewerRole:T,mode:gt="onBlur",t:pt,loading:Ue=!1,successPath:yt,toasts:Me=!0,extend:Te}=y,K=fr(),b=T??"guest",ht=cr(Te),p=B(()=>lr(o,Te,b).filter(e=>e.readable),[o,ht,b]),{t:bt}=Zt([o.namespace,"crud",...p.map(e=>e.entity.namespace)]),h=pt??bt,u=$??(F?"edit":"create"),ee=F?.id,Pe=rr(p,u==="edit"&&ee?[ee]:[],!Ue),ue=e=>ee?Pe[e]?.byRecord.get(ee):void 0,P=e=>u==="edit"&&ue(e)?"edit":"create",te=p.map(e=>ue(e.key)),St=p.map(e=>`${e.key}:${P(e.key)}`).join("|"),L=Ue||Object.values(Pe).some(e=>e.loading),vt=er(a??""),wt=tr(a??""),j=F,Le=Yt(j),A=B(()=>sr(o,b,u),[o,b,u]),We=S(h);We.current=h;const kt=B(()=>{const e=(n,s)=>We.current(n,s),r=ct(o,u,A,e,j),t=(n,s,c)=>r(u==="edit"?n:Ve(n,o.scope),s,c);if(p.length===0)return t;const i=p.map(n=>({key:n.key,resolve:ct(dr(n),P(n.key),$e(n,b,P(n.key)),e)}));return async(n,s,c)=>{const k=await t(n,s,c),g={...k.errors},f={...k.values},G={criteriaMode:c.criteriaMode,fields:c.fields,shouldUseNativeValidation:c.shouldUseNativeValidation};for(const{key:E,resolve:Q}of i){const v=n[E],X=await Q(M(v)?v:{},s,G);Object.keys(X.errors).length>0?g[E]=X.errors:f[E]=X.values}return Object.keys(g).length>0?{values:{},errors:g}:{values:f,errors:{}}}},[o,u,A,j,p,St,b]),re=B(()=>ut(o,A),[o,A]),w=B(()=>{if(L)return;const e=u==="edit"?j?lt(o,j,{fields:A,keepId:!0}):void 0:j?_({...re,...j},A):re;if(!e||p.length===0)return e;const r={...e};return p.forEach((t,i)=>{const n=te[i],s=$e(t,b,n?"edit":"create");r[t.key]=n?lt(t.entity,n,{fields:s,keepId:!0}):ut(t.entity,s)}),r},[L,u,re,o,j,A,b,p,...te]),de=B(()=>{if(u!=="edit"||L||!j)return;const e={...j};return p.forEach((r,t)=>{const i=te[t];i&&(e[r.key]=i)}),e},[u,L,j,p,...te]),[Et,fe]=De(null),me=Et??de,ge=S(me);ge.current=me;const pe=e=>{const r=_(e,A);u==="edit"&&Object.hasOwn(e,"id")&&(r.id=e.id);for(const t of p){const i=e[t.key];if(!M(i))continue;const n=P(t.key),s=_(i,$e(t,b,n));n==="edit"&&Object.hasOwn(i,"id")&&(s.id=i.id),r[t.key]=s}return r},d=Gt({defaultValues:u==="create"?w:void 0,mode:gt,resolver:kt,shouldUnregister:!1,shouldFocusError:!1});C(()=>{let e=xe(o,d.getValues()),r=!0,t=!1;const i=new Set,n=async()=>{if(!t){t=!0;try{for(;r&&i.size>0;){const c=[...i];if(i.clear(),await d.trigger(c),!r)return;for(const k of xe(o,d.getValues()))k.visible||d.clearErrors(k.name)}}finally{t=!1}}},s=d.watch(()=>{const c=xe(o,d.getValues()),k=c.filter((g,f)=>g.visible!==e[f]?.visible||g.required!==e[f]?.required);e=c;for(const g of k){const f=g.name;g.visible||d.clearErrors(f),i.add(f)}i.size>0&&n()});return()=>{r=!1,i.clear(),s.unsubscribe()}},[o,d]);const V=S(d);C(()=>{V.current=d},[d]);const ne=S(null);C(()=>{if(u==="edit"&&w){const e=w.id??null;e&&e!==ne.current?(V.current.reset(w),ne.current=e):!e&&ne.current===null&&(V.current.reset(w),ne.current="initialized")}},[u,w]);const D=F?.id,ye=`${o.name.toLowerCase()}-form-draft${a?`-${a}`:""}`,O=u==="create"?ye:D?`${ye}-${D}`:`${ye}-edit`,W=S(!1),x=Ht(),R=u==="edit"?D:void 0,H=e=>R?Object.keys(e).flatMap(r=>{const[t,i,n,s]=r.split("\0");return t===x&&i===R&&n&&s?[[r,n,s]]:[]}):[],Ne=()=>{const{childEdits:e,childWriters:r}=l.getState();return H(e).flatMap(([t,i,n])=>{const s=e[t];if(!Z(s))return[];const c=r[t];if(!c)throw new Error(`useEntityForm(${o.name}): joined rows ${i}.${n} have edits but no useChildRows registered how to write them.`);return[{key:t,collection:i,field:n,writer:c,edits:s}]})},ze=()=>{const{childEdits:e,childDrafts:r}=l.getState(),t={};for(const[i,n,s]of H(r))t[n]={...t[n],[s]:r[i]};for(const[i,n,s]of H(e)){const c=e[i];Z(c)&&(t[n]={...t[n],[s]:c})}return Object.keys(t).length>0?t:void 0},Ft=e=>{if(!(e===void 0||!R)&&M(e)){for(const[r,t]of Object.entries(e))if(M(t))for(const[i,n]of Object.entries(t))l.getState().setChildDraft(_t(x,R,r,i),n)}},U=S(new Map),oe=S(null),he=()=>{if(U.current.size===0)return;const e={};for(const[r,t]of U.current)e[r]=t.get();return e},qe=(e=!0)=>{const r=he(),t=ze(),i=e&&u==="edit"?ge.current:void 0;return!t&&!i?r:{...r,...t&&{[dt]:t},...i&&{[Ce]:i}}},Ot=e=>{e!==void 0&&(!M(e)||!R||e.id!==R||fe(e))},jt=()=>{const e=V.current;return Object.keys(e.getValues()).some(r=>e.getFieldState(r).isDirty)},Be=()=>jt()||[...U.current.values()].some(e=>e.edited())||ze()!==void 0,Dt=e=>{if(oe.current=e??null,!!e){for(const[r,t]of U.current)r in e&&t.restore(e[r]);Ft(e[dt]),Ot(e[Ce])}},Ke=()=>{oe.current=null,fe(null);for(const r of U.current.values())r.reset();const e=l.getState();for(const[r]of H(e.childEdits))e.setChildEdits(r,null);for(const[r]of H(e.childDrafts))e.setChildDraft(r,null)},ie=S(()=>{}),[Rt]=De(()=>({register:(e,r)=>{U.current.set(e,r);const t=oe.current;return t&&e in t&&r.restore(t[e]),()=>{U.current.get(e)===r&&U.current.delete(e)}},changed:()=>ie.current()})),He=S(L);He.current&&!L&&(W.current=!1),He.current=L;const It=e=>{l.getState().clearDraft(O),V.current.reset(e),Ke()},[be,Je]=De(null);C(()=>{if(!be)return;Je(null);const{base:e,conflict:r}=be;if(!Be()){l.getState().clearDraft(O),oe.current=null,fe(null);return}Me&&Re({toastType:r?"warning":"info",title:h(r?"crud:draft.conflict":"crud:draft.restored"),description:h(r?"crud:draft.conflictDescription":"crud:draft.restoredDescription"),action:Jt(Qt,{altText:h("crud:draft.discard"),onClick:()=>It(e)},h("crud:draft.discard")),duration:r?1/0:8e3})},[be]),C(()=>{if(W.current)return;const e=l.getState().loadDraft(O),r=t=>{if(!e)return;const i=e.extras?.[Ce];d.reset(t);const n=pe(mt(t,e.data));for(const[s,c]of Object.entries(n))d.setValue(s,c,{shouldDirty:!0});Dt(e.extras),Je({base:t,conflict:u==="edit"&&i!==void 0&&ft(i)!==ft(de)})};if(u==="create"&&w){e?r(w):d.reset(w),W.current=!0;return}u==="edit"&&w&&(r(w),W.current=!0)},[u,F,O,d,w,de,h,re]);const N=S(null),se=()=>{N.current&&clearTimeout(N.current),N.current=null},Ge=()=>{if(!Be()){l.getState().clearDraft(O);return}l.getState().saveDraft(O,le(pe(V.current.getValues())),o.name,D,qe())},Qe=()=>{Ge()},Se=S(Qe);Se.current=Qe,ie.current=()=>{W.current&&(se(),N.current=setTimeout(()=>{N.current=null,Se.current()},3e3))},C(()=>{const e=d.watch(()=>ie.current()),r=Se.current;return()=>{e.unsubscribe(),N.current&&(se(),r())}},[d,O,o.name,D]);const Xe=S(b);Xe.current=b,C(()=>{if(R)return l.getState().openRecord({formKey:x,collection:o.collection,recordId:R,viewerRole:Xe.current,submitting:!1,changed:()=>ie.current()}),()=>l.getState().closeRecord(x)},[x,o.collection,R]),C(()=>{l.getState().updateOpenRecord(x,{viewerRole:b})},[x,b]);const z=S(null),J=S(!1),At=async e=>{if(!a)return{};const r=Ae();if(!r)return{};const t=r.getState(),i=l.getState();if(!t.hasPendingUploads(a))return{};const n=setInterval(()=>{const s=r.getState().getTotalProgress(a);l.getState().setUploading(a,s)},200);try{return i.setUploading(a,0),await t.uploadAll(a,e),e?.aborted?null:r.getState().getResults(a)}catch(s){const c=r.getState().uploads[a];c&&Object.entries(c).forEach(([g,f])=>{f.status==="error"&&f.error&&d.setError(g,{type:"upload",message:f.error})});const k=s instanceof Error?s.message:h("crud:form.uploadFailed");return l.getState().setError(a,k),null}finally{clearInterval(n)}},Ye=(e,r)=>{let t={...e};for(const[i,n]of Object.entries(r)){const s=Ie(i);t=s&&p.some(c=>c.key===s[0])?ur(t,i,n):{...t,[i]:n}}return t},ve=(e,r)=>{const t={...r};for(const[i,n]of Object.entries(e.fields))if(n.type==="price"&&i in t){const s=t[i];(s==null||s.amount==null)&&(t[i]=null)}return t},Vt=(e,r)=>{if(typeof HTMLFormElement>"u"||!(r instanceof HTMLFormElement))return;const t=Object.keys(e).filter(n=>n!=="root"),i=r.querySelectorAll("input, textarea, select, button, [tabindex]");for(const n of i){const s=n.getAttribute("name");if(!(!(n.getAttribute("aria-invalid")==="true"||s!==null&&t.some(c=>s===c||s.startsWith(`${c}.`)))||n.matches(':disabled, input[type="hidden"]')||n.closest('[hidden], [inert], [aria-hidden="true"]')||n.getClientRects().length===0)&&(n.focus(),n.ownerDocument.activeElement===n)){n.scrollIntoView({behavior:"smooth",block:"center"});return}}},we=S(null),ke=S(null),Ee=S(!1),Fe=`record\0${O}`,Oe=()=>p.filter(e=>P(e.key)==="edit"?e.update:e.create),xt=(e,r)=>Oe().map(t=>{const i=P(t.key),n=new Set([...at(t,b,i)].map(f=>Ie(f)?.[1]??f)),s=e[t.key],c=ve(t.entity,_(M(s)?s:{},n)),k=ir(t.entity),g=ue(t.key);if(g)return{collection:t.entity.collection,updates:[{id:g.id,patch:c,stored:g}],schemas:k};if(!r)throw new Error(`useEntityForm(${o.name}): inserting extension "${t.key}" on create needs the record id: pendingWrites({ recordId }) (pre-mint it).`);return{collection:t.entity.collection,inserts:[Ve({...c,id:l.getState().mintId(st(t.entity.collection,r)),[t.field]:r},t.entity.scope)],schemas:k,...u==="create"&&{dependsOn:[o.collection]}}}),Ct=async()=>{const e=ce();if(!e)throw new Error(h("crud:form.saveFailed"));if(u!=="edit"||!D)throw new Error(`useEntityForm(${o.name}): remove() needs an edited record (defaultValues.id).`);await e.remove(o.collection,D),l.getState().clearDraft(O)},Ze=(e={})=>{Ee.current=!0;const r=we.current??Ne(),t=ke.current??V.current.getValues();return nr([...xt(t,R??e.recordId),...r.flatMap(({writer:i,edits:n})=>i.batches(n))])},_e=e=>{let r=0;for(const{writer:i,edits:n}of e){const s=i.errors(n),c=Object.keys(s).length;c!==0&&(r+=c)}if(r===0)return!1;const t=h("crud:childRows.invalidRows",{count:r});return a?l.getState().setError(a,t):Re({toastType:"error",title:t,duration:8e3}),!0},$t=()=>!A.has("status")&&Le!==null?{status:Le}:{},Ut=async e=>{const r=ce();if(!r)throw new Error(h("crud:form.saveFailed"));const t=Xt(o),i=_(e,A);if(u==="edit"&&!D)throw new Error(`useEntityForm(${o.name}): the default writer needs defaultValues.id in edit mode.`);const n=u==="create"&&Oe().length>0?l.getState().mintId(Fe):void 0,s=u==="edit"&&D?{collection:o.collection,updates:[{id:D,patch:i,stored:ge.current}],schemas:t}:{collection:o.collection,inserts:[Ve({...i,...$t(),...n&&{id:n}},o.scope)],schemas:t};return r.bulkAcross([s,...Ze({recordId:n})])},Mt=d.handleSubmit,Tt=(e,r,t)=>async i=>{let n;i?.preventDefault?.();const s=i?.currentTarget;if(J.current)return;const c=a?l.getState():null,k=structuredClone(V.current.getValues()),g=Ne().filter(({edits:f})=>Z(f));return await Mt(async(f,G)=>{if(J.current||_e(g))return;J.current=!0,z.current?.abort();const E=new AbortController;z.current=E;let Q=null;try{a&&c&&c.startSubmit(a);const v=await At(E.signal);if(v===null||E.signal.aborted)return;a&&c&&c.setSubmitting(a);const X=Ye(f,v),q=ve(o,X);for(const m of p){const I=q[m.key];M(I)&&(q[m.key]=ve(m.entity,I))}if(mr(q).length>0){a&&c&&c.setError(a,h("crud:form.reuploadFiles"));return}if(E.signal.aborted)return;const zt=Ye(k,structuredClone(v));W.current&&(se(),Ge());const qt=new Map(Object.entries(he()??{}).map(([m,I])=>[m,JSON.stringify(I)])),rt=t&&"successPath"in t?t.successPath:yt;if(K&&rt!==null){const m=K.currentPath(),I=rt??K.parentPath();I!==m&&(Q=m,K.navigate(I))}if(we.current=g,ke.current=q,Ee.current=!1,l.getState().updateOpenRecord(x,{submitting:!0}),n=e?await e(q,G):await Ut(q),[...g.map(({collection:m})=>m),...Oe().map(m=>m.entity.collection)].length>0&&!Ee.current)throw new Error(h("crud:childRows.notSaved"));let nt=!1;for(const{key:m,collection:I,edits:Kt}of g){const it=l.getState().childEdits[m],Y=it?or(it,Kt):null;nt||=!!Y&&Z(Y),l.getState().setChildEdits(m,Y&&Z(Y)?Y:null),ce()?.invalidateCollection(I)}for(const m of p)ce()?.invalidateCollection(m.entity.collection);const Bt=l.getState().mintedIds[Fe],ot=R??Bt;l.getState().releaseMintedIds([Fe,...ot?p.map(m=>st(m.entity.collection,ot)):[]]);const ae=V.current,je=ae.getValues();ae.reset(zt,{keepValues:!0}),ae.reset(je,{keepDefaultValues:!0}),se(),Object.keys(je).some(m=>ae.getFieldState(m).isDirty)||Object.entries(he()??{}).some(([m,I])=>qt.get(m)!==JSON.stringify(I))||nt?l.getState().saveDraft(O,le(pe(je)),o.name,D,qe(!1)):l.getState().clearDraft(O),a&&c&&c.setSuccess(a)}catch(v){throw Q!==null&&K?.navigate(Q),a&&c&&c.setError(a,v instanceof Error?v.message:h("crud:form.saveFailed"),v),v}finally{if(J.current=!1,we.current=null,ke.current=null,l.getState().updateOpenRecord(x,{submitting:!1}),z.current===E&&(z.current=null),a){const v=l.getState().forms[a]?.status;(v==="uploading"||v==="validating"||v==="submitting")&&l.getState().reset(a)}}},f=>{const G=Object.keys(f).filter(E=>E!=="root");Me&&Re({toastType:"error",title:h("crud:form.validationFailed"),description:h("crud:form.fixFields",{fields:G.map(E=>yr(E,o.fields[E],h)).join(", ")}),duration:8e3}),_e(g),Vt(f,s),r?.(f)})(i),n},Pt=()=>{l.getState().clearDraft(O),Ke(),d.reset(w),W.current=!1},et=()=>{z.current?.abort(),a&&(l.getState().cleanup(a),Ae()?.getState().cleanup(a))};C(()=>et,[]);const Lt=()=>{z.current?.abort(),a&&(Ae()?.getState().abortAll(a),l.getState().reset(a)),J.current=!1},tt=pr(o,{operation:u,viewerRole:b,availableFields:void 0}),Wt=p.length===0?tt:[...tt,...p.flatMap(e=>ar(e,b,P(e.key)))],Nt=d.formState.isSubmitted||Object.keys(d.formState.touchedFields||{}).length>0;return{...d,handleSubmit:Tt,fields:Wt,operation:u,record:me,entity:o,t:h,viewerRole:b,formId:a,formStatus:a?vt:"idle",uploadProgress:a?wt:0,cleanup:et,cancel:Lt,isDirty:d.formState.isDirty,hasUserInteracted:Nt,resetForm:Pt,originalValues:w,draftState:Rt,pendingWrites:Ze,remove:Ct}}export{br as useEntityForm};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as
|
|
1
|
+
"use client";import{useEffect as p,useRef as a,useState as y}from"react";function S(d,o,n,f){const[i,u]=y(n),r=a(i),c=a(n),g=a(f.parse);p(()=>{c.current=n,g.current=f.parse});const{draftState:s}=d;return p(()=>s.register(o,{get:()=>r.current,edited:()=>JSON.stringify(r.current)!==JSON.stringify(c.current),restore:t=>{let e;try{e=g.current(t)}catch{return}r.current=e,u(e)},reset:()=>{r.current=c.current,u(c.current)}}),[s,o]),[i,t=>{const e=typeof t=="function"?t(r.current):t;r.current=e,u(e),s.changed()}]}export{S as useFormDraftState};
|
package/dist/forms/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useEntityForm as
|
|
1
|
+
import{useEntityForm as a}from"./hooks/useEntityForm";import{FormNavigationProvider as t,useFormNavigation as s}from"./FormNavigation";import{useFormDraftState as e}from"./hooks/useFormDraftState";import{useEntityField as r}from"./hooks/useEntityField";import{useController as i}from"./hooks/useController";import{EMPTY_VALUE as o,fromInputValue as l,isFieldEditable as m,getFieldsForOperation as n,validateEntity as F,translateFieldLabel as d,translateLabel as u}from"./utils";export{o as EMPTY_VALUE,t as FormNavigationProvider,l as fromInputValue,n as getFieldsForOperation,m as isFieldEditable,d as translateFieldLabel,u as translateLabel,i as useController,r as useEntityField,a as useEntityForm,e as useFormDraftState,s as useFormNavigation,F as validateEntity};
|
package/dist/forms/types.d.ts
CHANGED
|
@@ -152,6 +152,15 @@ export interface UseEntityFormOptions<E extends AnyEntity, Op extends FieldOpera
|
|
|
152
152
|
* Needs the router access `@donotdev/ui` provides; without it the form stays.
|
|
153
153
|
*/
|
|
154
154
|
successPath?: string | null;
|
|
155
|
+
/**
|
|
156
|
+
* The form's own toasts: "fields to correct" when a submit fails validation,
|
|
157
|
+
* and "draft restored" (default `true`). `false`: neither; the field messages,
|
|
158
|
+
* the scroll to the first one and the draft restoring itself remain (a form in
|
|
159
|
+
* a sheet or dialog). Success toasts have their own opt-outs:
|
|
160
|
+
* `showSuccessToast` per mutation, `setHideSuccessToasts` on the CRUD store.
|
|
161
|
+
* @default true
|
|
162
|
+
*/
|
|
163
|
+
toasts?: boolean;
|
|
155
164
|
/**
|
|
156
165
|
* 1:1 extensions edited with the record (a record split across two tables,
|
|
157
166
|
* e.g. `{ offer: { entity: productOfferEntity, field: 'productId' } }`): their
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/forms/types.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAC9D,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,kBAAkB,EAClB,qBAAqB,EACrB,SAAS,EACT,WAAW,EACZ,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,KAAK,EACV,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,WAAW,EACX,gBAAgB,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AEG;IACH,SAAS,EAAE,OAAO,CAAC;IAEnB;;;;;;;OAOG;IACH,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE;QAClB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;KACpB,KAAK,MAAM,GAAG,YAAY,CAAC;CAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createStatus as
|
|
1
|
+
import{createStatus as p}from"@donotdev/core";import{EMPTY_VALUE as d}from"./emptyValue";const b=new Set(["text","textarea","email","url","tel","iban","password","color"]);function a(s,i,c){const{fields:l,keepId:f=!1}=c,t=Object.fromEntries(Object.entries(i).filter(([e])=>l.has(e)||f&&e==="id"));return Object.entries(s.fields).forEach(([e,r])=>{if(!l.has(e))return;const n=t[e],o=!(e in t)||n===null||n===void 0;if(e==="status"&&o)t[e]=p(void 0);else if(b.has(r.type))(o||n==="")&&(t[e]=d);else if(r.type==="switch"){if(n==null){const u=r.options?.fieldSpecific;t[e]=u?.uncheckedValue??!1}}else o&&(r.type==="price"?t[e]=null:r.type==="checkbox"||r.type==="boolean"?t[e]=!1:(r.type==="number"||r.type==="range"||r.type==="rating")&&(t[e]=void 0))}),t}function h(s,i){return a(s,{},{fields:i})}export{a as buildInitialFromRecord,h as buildSchemaDefaults};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { FieldValues, Resolver } from 'react-hook-form';
|
|
2
2
|
import type { AnyEntity } from '@donotdev/core';
|
|
3
|
+
import { type ErrorTranslate } from './fieldErrorMessages';
|
|
3
4
|
/** Evaluate only validation-relevant conditions against the complete retained form. */
|
|
4
5
|
export declare function getFormConditionStates(entity: AnyEntity, values: Record<string, unknown>): {
|
|
5
6
|
name: string;
|
|
@@ -17,19 +18,22 @@ export declare function getFormConditionStates(entity: AnyEntity, values: Record
|
|
|
17
18
|
* (`updateCheck` on the base row): a draft, or leaving draft for a visible status,
|
|
18
19
|
* checks the whole form; any other edit checks only the fields that differ from the
|
|
19
20
|
* base row (rule 2: an update validates what changes).
|
|
21
|
+
* Error messages are translated (`translateFieldErrors`: required, format, the
|
|
22
|
+
* entity's own message keys), never the schemas' English or valibot's raw text.
|
|
20
23
|
*
|
|
21
24
|
* @template T - Form state the resolver reads
|
|
22
25
|
* @template TOutput - Values it outputs (`onValid`'s), `T` by default
|
|
23
26
|
* @param entity - Entity from `defineEntity()`
|
|
24
27
|
* @param operation - Form operation
|
|
25
28
|
* @param written - Field names the form writes (companions included)
|
|
29
|
+
* @param t - Form translation function (entity namespace + `crud`) for error messages
|
|
26
30
|
* @param base - The row the form starts from: the stored row on edit, the caller's
|
|
27
31
|
* defaults on create (its status is read when form state has none)
|
|
28
32
|
* @returns React Hook Form resolver
|
|
29
33
|
*
|
|
30
|
-
* @version 0.
|
|
34
|
+
* @version 0.5.0
|
|
31
35
|
* @since 0.2.4
|
|
32
36
|
* @author AMBROISE PARK Consulting
|
|
33
37
|
*/
|
|
34
|
-
export declare function createConditionAwareResolver<T extends FieldValues, TOutput = T>(entity: AnyEntity, operation: 'create' | 'edit', written: ReadonlySet<string>, base?: Readonly<Record<string, unknown>> | null): Resolver<T, unknown, TOutput>;
|
|
38
|
+
export declare function createConditionAwareResolver<T extends FieldValues, TOutput = T>(entity: AnyEntity, operation: 'create' | 'edit', written: ReadonlySet<string>, t: ErrorTranslate, base?: Readonly<Record<string, unknown>> | null): Resolver<T, unknown, TOutput>;
|
|
35
39
|
//# sourceMappingURL=conditionAwareResolver.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conditionAwareResolver.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/conditionAwareResolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"conditionAwareResolver.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/conditionAwareResolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,WAAW,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAU1E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,EAAwB,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEjF,uFAAuF;AACvF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;IAWxF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,4BAA4B,CAC1C,CAAC,SAAS,WAAW,EACrB,OAAO,GAAG,CAAC,EAEX,MAAM,EAAE,SAAS,EACjB,SAAS,EAAE,QAAQ,GAAG,MAAM,EAC5B,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,EAC5B,CAAC,EAAE,cAAc,EACjB,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,GAC9C,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAqF/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{valibotResolver as
|
|
1
|
+
import{valibotResolver as R}from"@hookform/resolvers/valibot";import{createSchemas as w,evaluateFieldConditions as x,i18nFieldName as S,createStatus as A,statusCan as I,updateCheck as M}from"@donotdev/core";import{translateFieldErrors as z}from"./fieldErrorMessages";function g(u,m){return Object.entries(u.fields).filter(([,i])=>i.conditions?.visible||i.conditions?.required).map(([i,a])=>{const o=x(a.conditions,m);return{name:i,visible:o.visible,required:a.conditions?.required?o.required:a.validation?.required}})}function H(u,m,i,a,o){const n={...u,fields:Object.fromEntries(Object.entries(u.fields).filter(([s])=>i.has(s)))},C=w(n);let j,h,p=[];return async(s,E,k)=>{const b=g(n,s),y={...s,status:s.status??o?.status};let c,l=null;if(m==="edit"){const e=M(y,o);c=e.schemaKey,e.schemaKey==="update"&&!e.whole&&(l=Object.keys(n.fields).filter(d=>[d,S(d)].some(r=>JSON.stringify(s[r])!==JSON.stringify(o?.[r]))))}else c=I(A(y),"saveIncomplete")?"draft":"create";const q=JSON.stringify([c,b,l]);if(q!==j){const e=C[c];if(!("entries"in e)||typeof e.entries!="object"||e.entries===null)throw new Error("Expected an object write schema");const d=new Set(Object.keys(e.entries));p=b.filter(t=>!t.visible&&d.has(t.name)).flatMap(({name:t})=>n.fields[t]?.i18n===!0?[t,S(t)].filter(f=>d.has(f)):[t]);const r={...n.fields};if(l)for(const t of Object.keys(r))l.includes(t)||delete r[t];for(const[t,f]of Object.entries(r)){const O=b.find(K=>K.name===t);O&&(O.visible?f.conditions?.required&&(r[t]={...f,validation:{...f.validation,required:O.required}}):delete r[t])}const J=w({...n,fields:r})[c];h=R(J),j=q}const F=Object.fromEntries(p.filter(e=>Object.hasOwn(s,e)).map(e=>[e,s[e]])),v=await h(s,E,k);if(Object.keys(v.errors).length>0){const e=z(v.errors,s,n,a);return{values:{},errors:e}}const N=l?Object.fromEntries(Object.entries(s).filter(([e])=>i.has(e))):{};return{errors:{},values:{...N,...F,...v.values}}}}export{H as createConditionAwareResolver,g as getFormConditionStates};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const n=null;function t(l){return l===""?null:l}export{n as EMPTY_VALUE,t as fromInputValue};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AnyEntity, EntityField, FieldType } from '@donotdev/core';
|
|
2
|
+
/** Translation function of the form (`form.t`: entity namespace + `crud`). */
|
|
3
|
+
export type ErrorTranslate = (key: string, options?: Record<string, unknown>) => string;
|
|
4
|
+
/** Error leaf of React Hook Form (`{ type, message, ref }`). */
|
|
5
|
+
interface ErrorLeaf {
|
|
6
|
+
type?: unknown;
|
|
7
|
+
message: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Translated message of one field error.
|
|
11
|
+
*
|
|
12
|
+
* @param name - Field name (label fallback)
|
|
13
|
+
* @param field - Entity field (`undefined`: only rules 1 and 5 apply)
|
|
14
|
+
* @param error - Error of the resolver: valibot issue `type` and message
|
|
15
|
+
* @param value - The value that failed
|
|
16
|
+
* @param t - Form translation function
|
|
17
|
+
* @param namespace - Entity namespace (labels and the entity's message keys)
|
|
18
|
+
* @returns Translated message
|
|
19
|
+
*/
|
|
20
|
+
export declare function fieldErrorMessage(name: string, field: EntityField<FieldType> | undefined, error: ErrorLeaf, value: unknown, t: ErrorTranslate, namespace: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* Resolver errors with translated messages (see file overview). Nested errors (object
|
|
23
|
+
* and array fields) are translated with their root field and their own value.
|
|
24
|
+
*
|
|
25
|
+
* @param errors - Errors of the resolver (React Hook Form shape)
|
|
26
|
+
* @param values - The values the resolver validated
|
|
27
|
+
* @param entity - The entity the values belong to
|
|
28
|
+
* @param t - Form translation function
|
|
29
|
+
* @returns The same errors with translated messages
|
|
30
|
+
*/
|
|
31
|
+
export declare function translateFieldErrors<E extends Record<string, unknown>>(errors: E, values: Readonly<Record<string, unknown>>, entity: AnyEntity, t: ErrorTranslate): E;
|
|
32
|
+
export {};
|
|
33
|
+
//# sourceMappingURL=fieldErrorMessages.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fieldErrorMessages.d.ts","sourceRoot":"","sources":["../../../src/forms/utils/fieldErrorMessages.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAIxE,8EAA8E;AAC9E,MAAM,MAAM,cAAc,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC;AAmBxF,gEAAgE;AAChE,UAAU,SAAS;IACjB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,WAAW,CAAC,SAAS,CAAC,GAAG,SAAS,EACzC,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,OAAO,EACd,CAAC,EAAE,cAAc,EACjB,SAAS,EAAE,MAAM,GAChB,MAAM,CA6BR;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpE,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EACzC,MAAM,EAAE,SAAS,EACjB,CAAC,EAAE,cAAc,GAChB,CAAC,CAqCH"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i18nFieldName as x}from"@donotdev/core";import{translateFieldLabel as g}from"./translateFieldLabel";const y=new Set(["date","datetime-local","timestamp","time","week","month"]),h=/^[\w.-]+$/,v=s=>s==null||s==="",c=s=>typeof s=="object"&&s!==null;function p(s,n,r,u,e,m){const t=g(s,n,(a,l)=>e(a,{ns:m,...l}));if(v(u))return e("crud:text.required",{field:t});const d=e("crud:text.invalid",{field:t}),i=n?.validation;return i?.schema?h.test(r.message)?e(r.message,{ns:m,field:t,defaultValue:d}):d:r.type==="min_length"&&i?.minLength!==void 0?e("crud:text.minLength",{field:t,min:i.minLength}):r.type==="max_length"&&i?.maxLength!==void 0?e("crud:text.maxLength",{field:t,max:i.maxLength}):r.type==="min_value"&&i?.min!==void 0?e("crud:number.min",{field:t,min:i.min}):r.type==="max_value"&&i?.max!==void 0?e("crud:number.max",{field:t,max:i.max}):n?.type==="tel"?e("crud:text.phone",{field:t}):n?.type==="email"?e("crud:text.email",{field:t}):n?.type==="url"?e("crud:text.url",{field:t}):n&&y.has(n.type)?e("crud:date.format",{field:t}):d}function b(s,n,r,u){const e={};for(const[m,t]of Object.entries(s)){const d=r.fields[m]??Object.entries(r.fields).find(([a])=>x(a)===m)?.[1],i=(a,l)=>Array.isArray(a)?a.map((o,f)=>i(o,Array.isArray(l)?l[f]:void 0)):c(a)?typeof a.message=="string"?{...a,message:p(m,d,{type:a.type,message:a.message},l,u,r.namespace)}:Object.fromEntries(Object.entries(a).map(([o,f])=>[o,o==="ref"?f:i(f,c(l)?l[o]:void 0)])):a;e[m]=i(t,n[m])}return e}export{p as fieldErrorMessage,b as translateFieldErrors};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeEntity as
|
|
1
|
+
import{describeEntity as m,describeField as F,isFieldVisible as g}from"@donotdev/core";const f=new WeakMap;function v(i){if("fields"in i&&"name"in i&&typeof i.name=="string"){const t=i;return{fields:t.fields,descriptors:m(t).fields}}const s=i;let e=f.get(s);return e||(e=Object.fromEntries(Object.entries(s).map(([t,n])=>[t,F(t,n,"<fields>")])),f.set(s,e)),{fields:s,descriptors:e}}function w(i,s){const{operation:e,viewerRole:t,availableFields:n}=s,d=t??"guest",{fields:p,descriptors:b}=v(i),l=[];for(const[o,u]of Object.entries(p)){const r=b[o],c=r.visibleAt;if(!g(c,d)||e==="create"&&c==="technical"||r.write==="never"&&c!=="technical"||e==="edit"&&n&&!n.includes(o))continue;const a=r.editableFor(d,e);l.push({name:o,config:u,editable:a,written:a||r.write==="derived"})}return l}export{w as getFieldsForOperation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EMPTY_VALUE as
|
|
1
|
+
import{EMPTY_VALUE as a,fromInputValue as t}from"./emptyValue";import{isFieldEditable as e}from"./isFieldEditable";import{getFieldsForOperation as s}from"./getFieldsForOperation";import{validateEntity as i}from"./validateEntity";import{translateFieldLabel as r,translateLabel as l}from"./translateFieldLabel";export{a as EMPTY_VALUE,t as fromInputValue,s as getFieldsForOperation,e as isFieldEditable,r as translateFieldLabel,l as translateLabel,i as validateEntity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeEntity as d}from"@donotdev/core";function
|
|
1
|
+
import{describeEntity as d}from"@donotdev/core";function o(e,i,r,n){const t=d(e).fields[i];if(!t)throw new Error(`isFieldEditable: entity "${e.name}" has no field "${i}".`);return t.editableFor(r,n)}export{o as isFieldEditable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{translateEntityLabel as
|
|
1
|
+
import{translateEntityLabel as l}from"@donotdev/core";function n(t,a){return l(t,a)}function s(t,a,e){const r=a?.label||t;return n(r,e)}export{s as translateFieldLabel,n as translateLabel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as o from"valibot";import{createSchemas as p}from"@donotdev/core";function
|
|
1
|
+
import*as o from"valibot";import{createSchemas as p}from"@donotdev/core";function i(t,r,c="create"){const e=p(t),u={create:e.create,draft:e.draft,update:e.update,full:e.get}[c],s=o.safeParse(u,r);return s.success?{success:!0,data:s.output}:{success:!1,issues:s.issues.map(a=>({path:a.path?.map(m=>m.key).join(".")||"",message:a.message}))}}export{i as validateEntity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describeEntity as a}from"@donotdev/core";import{getFieldsForOperation as
|
|
1
|
+
import{describeEntity as a}from"@donotdev/core";import{getFieldsForOperation as s}from"./getFieldsForOperation";function m(t,r,i){const{fields:o}=a(t);return new Set(s(t,{operation:i,viewerRole:r}).filter(e=>e.written).flatMap(e=>{const n=o[e.name]?.companion;return n?[e.name,n]:[e.name]}))}export{m as writableFields};
|
package/dist/hooks/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useFileUpload as
|
|
1
|
+
import{useFileUpload as e}from"./useFileUpload";import{useEntityFavorites as s}from"./useEntityFavorites";import{useCrudFilters as o}from"./useCrudFilters";import{useCrudPageSize as r}from"./useCrudPageSize";import{useRelatedItems as i}from"./useRelatedItems";import{useFieldConditions as a}from"./useFieldConditions";import{useReferenceResolver as t}from"./useReferenceResolver";import{useChildRows as u,useJoinedForm as m}from"./useChildRows";export{u as useChildRows,o as useCrudFilters,r as useCrudPageSize,s as useEntityFavorites,a as useFieldConditions,e as useFileUpload,m as useJoinedForm,t as useReferenceResolver,i as useRelatedItems};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as
|
|
1
|
+
"use client";import{useEffect as W,useMemo as Ee,useRef as be,useState as B}from"react";import{generateUUID as Re,REMOVED_STATUS as Ce,useTranslation as Se}from"@donotdev/core";import{EMPTY_CHILD_EDITS as M,applyChildEdits as xe,childEditsBatches as ee,childEditsErrors as te,childRowsAccess as je,countChildEdits as Oe,hasChildEdits as I,parentCollectionOf as $e,parseChildEdits as ke,rebaseChildEdits as ne,reconcileChildEdits as Me,removeChildRows as se,setChildValues as re,writableFields as oe}from"../forms/childRows";import{extensionFieldName as Ie,extensionFields as De,extensionWritable as Fe,extensionsSignature as Te,resolveExtensions as Ue,splitExtensionField as P}from"../forms/extend";import{translateFieldLabel as qe}from"../forms/utils/translateFieldLabel";import{buildSchemaDefaults as Ae}from"../forms/utils/buildInitialValues";import{childRowsKey as Ke,extensionMintKey as Le,useFormStore as R}from"../stores";import{getCrudServiceInstance as Ve,useCrud as _e}from"../useCrud";import{useCrudList as We}from"../useCrudList";import{useExtensionRows as Be}from"./useExtensionRows";function ie(o,d){const C=d?$e(o,d.field):null,f=d?.value??null;return R(c=>{if(C===null||f===null)return null;for(let w=c.openRecords.length-1;w>=0;w--){const b=c.openRecords[w];if(b.collection===C&&b.recordId===f)return b}return null})}function Pe(o,d,C={}){const f=ie(o,d),c=C.viewerRole??f?.viewerRole??"guest",w=je(o,c),b=d?d.value:void 0,D=b!==null,h=d&&d.value!==null?{field:d.field,value:d.value}:void 0,le=Te(C.extend),m=Ee(()=>Ue(o,C.extend,c),[o,le,c]),{t:F}=Se(["crud",o.namespace,...m.map(e=>e.entity.namespace)]),p=We(o.collection,{entity:o,enabled:D,pagination:"client",...d&&{queryOptions:{where:[{field:d.field,operator:"==",value:b}]}}}),{bulk:ae}=_e(o.collection,{entity:o}),H=D&&p.data!==null&&!p.loading&&!p.error,x=Be(m,p.items.map(e=>e.id),H),J=Object.values(x).some(e=>e.loading),de=Object.values(x).find(e=>e.error)?.error??null,u=f&&h?Ke(f.formKey,h.value,o.collection,h.field):null,ce=R(e=>u===null?void 0:e.childEdits[u]),[N,T]=B(M),[ue,j]=B(!1),y=u===null?N:ce??M,S=e=>{if(u===null||!f){T(e);return}const t=R.getState().childEdits[u]??M,n=e(t);n!==t&&(R.getState().setChildEdits(u,I(n)?n:null),f.changed())},O={},U=m.length===0?p.items:p.items.map(e=>{const t={...e};for(const n of m){if(!n.readable)continue;const a=x[n.key]?.byRecord.get(e.id)??null;if(t[n.key]=a,!!a){(O[e.id]??={})[n.key]=a.id;for(const[s,r]of Object.entries(a))t[Ie(n.key,s)]=r}}return t}),q=xe(U,y),A=q.base,fe=m.length===0?q.items:q.items.map(e=>{const t=y.changes[e.id];if(!t)return e;const n={...e};for(const[a,s]of Object.entries(t)){const r=P(a);if(!r)continue;const[i,v]=r,E=n[i];n[i]={...typeof E=="object"&&E!==null?E:{},[v]:s}}return n}),$={entity:o,...h&&{parent:h},extensions:m,extensionIds:O,savedRows:new Map(U.map(e=>[e.id,e])),mintId:e=>R.getState().mintId(e)},K=e=>{const t=P(e),n=t?m.find(a=>a.key===t[0]):void 0;return n&&t?{entity:n.entity,field:t[1]}:{entity:o,field:e}},L=e=>{const t={};for(const[n,a]of Object.entries(e)){t[n]={};for(const[s,r]of Object.entries(a)){const i=K(s),v=(E,l)=>F(E,{ns:i.entity.namespace,...l});t[n][s]=F(r==="required"?"crud:childRows.required":"crud:childRows.invalidValue",{field:qe(i.field,i.entity.fields[i.field],v)})}}return t},Y=L(te($,y,c)),z=Object.keys(Y).length,g=be({context:$,viewerRole:c,messagesOf:L,describe:K});g.current={context:$,viewerRole:c,messagesOf:L,describe:K};const[G]=B(()=>({entity:o,describe:e=>g.current.describe(e),errors:e=>g.current.messagesOf(te(g.current.context,e,g.current.viewerRole)),batches:e=>ee(g.current.context,e,g.current.viewerRole)}));W(()=>{if(u===null)return;const e=R.getState();e.setChildWriter(u,G);const t=e.childDrafts[u];if(t!==void 0){e.setChildDraft(u,null);try{const n=ke(g.current.context,t,g.current.viewerRole);e.setChildEdits(u,I(n)?n:null)}catch{}}},[u,G,o.collection]);const V=m.flatMap(e=>Object.entries(O).flatMap(([t,n])=>n[e.key]?[Le(e.entity.collection,t)]:[])),he=V.join("|");W(()=>{V.length>0&&R.getState().releaseMintedIds(V)},[he]);const Q=H&&!J,X=f?f.submitting:ue;W(()=>{!Q||X||S(e=>Me(e,U))},[Q,X,p.items,x,u,f]);const _=()=>{if(b===null)throw new Error(`useChildRows(${o.name}): the parent record is not created yet (parent.value is null).`)},Z=e=>new Set(m.flatMap(t=>[...Fe(t,c,e!==null&&O[e]?.[t.key]?"edit":"create")])),me=e=>{if(_(),!w.create)throw new Error(`useChildRows(${o.name}): the viewer may not add rows.`);const t=oe(o,c,"create"),n=new Set([...t,...Z(null)]);for(const r of e){const i=Object.keys(r).filter(v=>v!==d?.field&&!n.has(v));if(i.length>0)throw new Error(`useChildRows(${o.name}): fields not writable on create: ${i.join(", ")}.`)}const a=Ae(o,t),s=e.map(r=>({...a,...r,id:Re(),...h&&{[h.field]:h.value}}));return S(r=>({...r,added:[...r.added,...s]})),s.map(r=>r.id)},we=(e,t)=>{_();const n=A.find(i=>i.id===e);if(!n)throw new Error(`useChildRows(${o.name}): no row "${e}".`);const a=y.added.some(i=>i.id===e);if(Object.keys(t).some(i=>!P(i))&&!(a?w.create:w.update))throw new Error(`useChildRows(${o.name}): the viewer may not edit rows.`);const s=new Set([...oe(o,c,a?"create":"edit"),...Z(a?null:e)]),r=Object.keys(t).filter(i=>!s.has(i));if(r.length>0)throw new Error(`useChildRows(${o.name}): fields not writable: ${r.join(", ")}.`);S(i=>re(i,n,t))},pe=e=>{const t=new Set(y.added.map(n=>n.id));if(!w.delete&&e.some(n=>!t.has(n)))throw new Error(`useChildRows(${o.name}): the viewer may not delete rows.`);S(n=>se(n,e))},ve=e=>{const t=new Set(y.added.map(s=>s.id)),n=e.filter(s=>!t.has(s));if(n.length>0&&!w.update)throw new Error(`useChildRows(${o.name}): the viewer may not remove rows.`);const a=n.map(s=>{const r=A.find(i=>i.id===s);if(!r)throw new Error(`useChildRows(${o.name}): no row "${s}".`);return r});S(s=>a.reduce((r,i)=>re(r,i,{status:Ce}),se(s,e.filter(r=>t.has(r)))))},ye=()=>S(()=>M),ge=async()=>{if(f)throw new Error(`useChildRows(${o.name}).save(): the rows are joined to the form open on the parent; its Save writes them.`);if(_(),z>0)throw new Error(F("crud:childRows.invalidRows",{count:z}));const e=N;if(m.length>0){const s=Ve();if(!s)throw new Error(`useChildRows(${o.name}).save(): the CRUD service is not ready.`);j(!0);try{await s.bulkAcross(ee($,e,c)),T(r=>ne(r,e));return}finally{j(!1)}}const t=new Set(e.added.map(s=>s.id)),n=new Set(e.removed),a=Object.entries(e.changes).filter(([s])=>!t.has(s)&&!n.has(s)).map(([s,r])=>({id:s,patch:r}));j(!0);try{const s=await ae({inserts:e.added.map(({id:l,...k})=>({...k,...e.changes[l],...h&&{[h.field]:h.value}})),updates:a,deletes:e.removed}),r=new Set(s.failed.flatMap(l=>{const k=l.op==="insert"&&l.index!==void 0?e.added[l.index]:void 0;return k?[k.id]:[]})),i=new Set(s.failed.flatMap(l=>l.op!=="insert"&&l.id!==void 0?[l.id]:[])),v=l=>r.has(l)||i.has(l),E={changes:Object.fromEntries(Object.entries(e.changes).filter(([l])=>!v(l))),added:e.added.filter(l=>!v(l.id)),removed:e.removed.filter(l=>!v(l))};return T(l=>I(E)?ne(l,E):l),s}finally{j(!1)}};return{items:fe,base:A,edits:y,pendingCount:Oe(y),hasEdits:I(y),errors:Y,add:me,update:we,remove:ve,delete:pe,discard:ye,save:ge,refresh:p.refresh,loading:D&&(p.loading||J),error:p.error??de,joined:u!==null,access:w,extensionFields:m.flatMap(e=>De(e,c,"edit"))}}export{Pe as useChildRows,ie as useJoinedForm};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as o,useEffect as y,useSyncExternalStore as
|
|
1
|
+
import{useCallback as o,useEffect as y,useSyncExternalStore as S}from"react";import{getEntityByCollection as F}from"@donotdev/core";import{peekFilters as f,useCrudStore as s}from"../CrudStore";const h={};function m(l){const{collection:t,urlSync:r,entity:n}=l;if(r===!1)s.getState().setFilterUrlSync(t,null);else if(r===!0){const e=n??F(t);if(!e)throw new Error(`useCrudFilters: urlSync on "${t}" needs the entity whose fields the URL params encode (pass \`entity\`).`);s.getState().setFilterUrlSync(t,e)}y(()=>{s.getState().syncFiltersFromUrl(t)},[t]);const i=S(s.subscribe,()=>f(t),()=>h),a=o(e=>{s.getState().setFilters(t,e)},[t]),c=s(e=>e.collections[t]?.ui?.showFavoritesOnly??!1),u=o(e=>{s.getState().setShowFavoritesOnly(t,e)},[t]);return{filters:i,setFilters:a,showFavoritesOnly:c,setShowFavoritesOnly:u}}export{m as useCrudFilters};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCrudStore as i}from"../CrudStore";const
|
|
1
|
+
import{useCrudStore as i}from"../CrudStore";const s=12;function S(o){const{collection:t,defaultPageSize:a=s}=o;return{pageSize:i(e=>e.collections[t]?.ui?.pageSize??a),setPageSize:e=>{i.getState().setPageSize(t,e)}}}export{S as useCrudPageSize};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as
|
|
1
|
+
import{useCallback as o}from"react";import{useLocalStorage as p}from"@donotdev/core";function y(s={}){const{storageKey:l,collection:u="entities"}=s,d=l||`favorites-${u}`,{value:i,setValue:a,isLoaded:c}=p(d,{defaultValue:[]}),n=o(e=>i.includes(e),[i]),v=o(e=>{a(t=>t.includes(e)?t.filter(r=>r!==e):[...t,e])},[a]),f=o(e=>{a(t=>t.includes(e)?t:[...t,e])},[a]),F=o(e=>{a(t=>t.filter(r=>r!==e))},[a]),m=o(()=>{a([])},[a]),g=o(e=>i.includes(e.id),[i]);return{favorites:i,isFavorite:n,toggleFavorite:v,addFavorite:f,removeFavorite:F,clearFavorites:m,favoritesFilter:g,isLoaded:c}}export{y as useEntityFavorites};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useMemo as h,useRef as w}from"react";import{createSchemas as
|
|
1
|
+
"use client";import{useMemo as h,useRef as w}from"react";import{createSchemas as g,useQuery as S}from"@donotdev/core";import{useCrudStore as E}from"../CrudStore";import{EMPTY_OPTIMISTIC as I,getCrudServiceInstance as k}from"../useCrud";import{EXTENSION_IN_CHUNK as p}from"../forms/extend";import{mergeWithOptimistic as x}from"../utils/mergeWithOptimistic";import{injectScopeFilter as C}from"../utils/scopeUtils";const M={},d=[];function R(e,l,u){const o=e.entity.collection,a=h(()=>g(e.entity),[e.entity]),c=E(n=>n.collections[o]?.optimistic||I),t=[...new Set(l)].sort(),i=u&&e.readable&&t.length>0,m=S({queryKey:["crud",o,"extend",e.field,t],queryFn:async()=>{const n=k();if(!n)throw new Error("CRUD service is not ready");const s=[];for(let r=0;r<t.length;r+=p)s.push(t.slice(r,r+p));return(await Promise.all(s.map(r=>n.query(o,C({where:[{field:e.field,operator:"in",value:r}]},e.entity.scope),a.get)))).flatMap(r=>r.items)},enabled:i}),y=new Set(t),f=new Map;for(const n of x(i?m.data??d:d,i?c:M)){const s=n[e.field];typeof s=="string"&&y.has(s)&&f.set(s,n)}return{byRecord:f,loading:i&&m.isLoading,error:i?m.error??null:null}}function N(e,l,u){const o=e.map(t=>t.key).join("|"),a=w(o);if(a.current!==o)throw new Error(`extend: the extension keys changed while mounted ("${a.current}" \u2192 "${o}"). Keep the same keys, or remount (React key).`);const c={};for(const t of e)c[t.key]=R(t,l,u);return c}export{N as useExtensionRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useCallback as u,useMemo as
|
|
1
|
+
"use client";import{useCallback as u,useMemo as a}from"react";import{useWatch as f}from"react-hook-form";import{evaluateFieldConditions as l}from"@donotdev/core";const m={};function p(s,i){const n=a(()=>s.filter(o=>o.config.conditions),[s]),r=u(o=>{if(n.length===0)return m;const c={};for(const t of n){const e=t.scope?o[t.scope]:o;c[t.name]=l(t.config.conditions,typeof e=="object"&&e!==null?e:{})}return c},[n]);return f({control:i,compute:r})}export{p as useFieldConditions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect as
|
|
1
|
+
"use client";import{useEffect as R,useRef as $}from"react";import{handleError as M}from"@donotdev/core";import{useUploadContext as I}from"../contexts/UploadContext";import{useUploadStore as s,useFieldFiles as N,generateStandaloneFormId as q}from"../stores/UploadStore";let j=0;function A(e){if(e){const r=e.split("/").pop()?.split("?")[0];if(r)return`file-${r}`}j+=1;const l=typeof performance<"u"?performance.now():Date.now(),n=Math.random().toString(36).slice(2,11);return`file-${j}-${l}-${n}`}function Q(e,l,n){return l.length>0&&!l.some(r=>{if(r.endsWith("/*")){const i=r.slice(0,-2);return e.type.startsWith(i)}return e.type===r})?{valid:!1,error:`File type ${e.type} not accepted`}:e.size>n?{valid:!1,error:`File exceeds ${(n/1048576).toFixed(0)}MB limit`}:{valid:!0}}function P(e){if(!e)return null;const l=(Array.isArray(e)?e:[e]).map(n=>typeof n=="object"&&n!==null?n.fullUrl??n.url??"":"").filter(Boolean);return l.length>0?l.join(","):null}function T(e){return e?(Array.isArray(e)?e:[e]).filter(l=>{if(typeof l!="object"||l===null)return!1;const n=l;return n.fullUrl||n.url}).map((l,n)=>{const r=l,i=r.fullUrl??r.url??"",E=r.thumbUrl??i,b=r.filename??i.split("/").pop()?.split("?")[0]??"existing";return{id:`${A(i)}-existing-${n}`,file:new File([],b),previewURL:E||i,status:"complete",progress:100,uploaded:l,error:null}}):[]}function L(e,l,n){const r=(n?e.filter(i=>!i.error):e.filter(i=>i.uploaded&&!i.error)).map(i=>i.uploaded?i.uploaded:n?{fullUrl:i.previewURL,thumbUrl:i.previewURL}:null).filter(i=>i!==null);return l?r.length>0?r:null:r[0]??null}function V({name:e,value:l,onChange:n,multiple:r=!1,maxFiles:i=10,maxSize:E=10*1024*1024,accept:b=[],uploadFn:F}){const o=I(),g=$(null);!o&&!g.current&&(g.current=q());const u=o??g.current,S=!!o,d=N(u,e),w=$(null);R(()=>{const t=P(l);if(t===w.current)return;w.current=t;const a=T(l);s.getState().setFieldFiles(u,e,a)},[l,u,e]),R(()=>{if(d.length===0&&!l)return;const t=L(d,r,S),a=P(t);if(a!==w.current&&(w.current=a,n(t),o)){const f=L(d,r,!1);s.getState().setResult(o,e,f)}},[d,r,S,n,e,o,l]),R(()=>{if(!o||!e)return;const t=s.getState();return t.registerUpload(o,e,async(a,f)=>{if(!F||f?.aborted)return;const h=s.getState().getFieldFiles(o,e).filter(c=>c.status!=="complete");if(h.length===0)return;for(const c of h)s.getState().markFileUploading(o,e,c.id);const x=await Promise.allSettled(h.map(async c=>{if(f?.aborted)throw new Error("Upload cancelled");try{const y=await F(c.file,v=>{s.getState().updateFileProgress(o,e,c.id,v)});return s.getState().updateFileResult(o,e,c.id,y),{id:c.id,error:null}}catch(y){const v=y instanceof Error?y.message:"Upload failed";return s.getState().updateFileError(o,e,c.id,v),{id:c.id,error:v}}})),m=s.getState().getFieldFiles(o,e),p=L(m,r,!1);s.getState().setResult(o,e,p);const U=x.filter(c=>c.status==="fulfilled"&&c.value.error!=null);if(U.length>0)throw new Error(`${U.length} file(s) failed to upload`)},()=>s.getState().getFieldFiles(o,e).some(a=>a.status!=="complete")),()=>{t.unregisterUpload(o,e)}},[o,e,F,r]),R(()=>()=>{const t=o??g.current;t&&s.getState().clearFieldFiles(t,e),g.current&&(s.getState().cleanup(g.current),g.current=null)},[o,e]);function k(t){const a=s.getState(),f=a.getFieldFiles(u,e),h=(r?i:1)-f.length;if(h<=0){M(new Error("Maximum files reached"),{userMessage:r?`Maximum ${i} files allowed`:"Only one file allowed",severity:"warning",showNotification:!0});return}const x=t.slice(0,h),m=[];for(const p of x){const U=Q(p,b,E);if(!U.valid){M(new Error(U.error),{userMessage:U.error,severity:"warning",showNotification:!0});continue}m.push({id:A(),file:p,previewURL:URL.createObjectURL(p),status:"pending",progress:null,uploaded:null,error:null})}if(m.length!==0&&(r?a.addFileEntries(u,e,m):(a.getFieldFiles(u,e).forEach(p=>{p.previewURL.startsWith("blob:")&&URL.revokeObjectURL(p.previewURL)}),a.setFieldFiles(u,e,m)),!S&&F))for(const p of m)z(p)}function O(t){s.getState().removeFileEntry(u,e,t)}function W(t){s.getState().reorderFileEntries(u,e,t)}async function z(t){if(F){s.getState().markFileUploading(u,e,t.id);try{const a=await F(t.file,f=>{s.getState().updateFileProgress(u,e,t.id,f)});s.getState().updateFileResult(u,e,t.id,a)}catch(a){const f=a instanceof Error?a.message:"Upload failed";s.getState().updateFileError(u,e,t.id,f)}}}const B=d.some(t=>t.status==="pending"),C=d.some(t=>t.status==="uploading"),D=d.length>0?d.reduce((t,a)=>t+(a.progress??0),0)/d.length:0;return{files:d,addFiles:k,removeFile:O,reorderFiles:W,hasPending:B,isUploading:C,progress:D,formId:u,isDeferred:S}}export{V as useFileUpload};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useMemo as
|
|
1
|
+
"use client";import{useMemo as p}from"react";import{describeEntity as R}from"@donotdev/core";import{buildReferenceLabel as $}from"../components/controlled/select/ControlledReferenceField";import{useCrudList as r}from"../useCrudList";import{resolveReferenceEntity as h}from"../utils/referenceEntity";const v=4;function w(s){const t=new Map,{fields:l}=R(s);for(const[o,i]of Object.entries(s.fields)){const e=l[o]?.value.ref;if(e!==void 0&&!t.has(e)){const n=i.options?.fieldSpecific;t.set(e,{collection:e,entity:h(e,`${s.name}.${i.name}`),labelFields:n?.labelFields,displayField:n?.displayField})}}if(t.size>v)throw new Error(`useReferenceResolver: entity "${s.name}" references ${t.size} collections (${[...t.keys()].join(", ")}); at most ${v} are resolved.`);return Array.from(t.values())}function E(s,t=!0){const l=p(()=>w(s),[s]),o=l[0],i=l[1],e=l[2],n=l[3],{items:f}=r(o?.entity?o.collection:"__disabled_0__",{enabled:t&&!!o?.entity,entity:o?.entity}),{items:a}=r(i?.entity?i.collection:"__disabled_1__",{enabled:t&&!!i?.entity,entity:i?.entity}),{items:d}=r(e?.entity?e.collection:"__disabled_2__",{enabled:t&&!!e?.entity,entity:e?.entity}),{items:m}=r(n?.entity?n.collection:"__disabled_3__",{enabled:t&&!!n?.entity,entity:n?.entity}),F=[{info:o,items:f},{info:i,items:a},{info:e,items:d},{info:n,items:m}];return p(()=>{const y={};for(const{info:c,items:_}of F){if(!c||!_.length)continue;const b={};for(const u of _)b[u.id]=$(u,c.labelFields,c.displayField);y[c.collection]=b}return y},[o?.collection,f,i?.collection,a,e?.collection,d,n?.collection,m])}export{E as useReferenceResolver};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useMemo as
|
|
1
|
+
"use client";import{useMemo as p}from"react";function N(o,e,t,n,h={}){const{limit:a=3,tolerance:m=.2}=h,c=p(()=>{if(!e||!t||t.length===0||n.length===0)return[];const b=e.id;return t.filter(f=>f.id===b?!1:n.some(s=>{const r=o.fields[s];if(!r)return!1;const i=e[s],u=f[s];if(i==null||u==null)return!1;if(r.type==="number"||r.type==="range"||r.type==="year"){const l=Number(i),g=Number(u);if(isNaN(l)||isNaN(g))return!1;const d=Math.abs(l*m);return Math.abs(g-l)<=d}return String(i)===String(u)})).slice(0,a)},[e,t,n,o.fields,a,m]);return{items:c,hasItems:c.length>0}}export{N as useRelatedItems};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./useCrud";export*from"./useCrudList";export*from"./useCrudDoc";export*from"./useCrudCardList";export*from"./components";export*from"./stores";import{FunctionsAdapter as
|
|
1
|
+
export*from"./useCrud";export*from"./useCrudList";export*from"./useCrudDoc";export*from"./useCrudCardList";export*from"./components";export*from"./stores";import{FunctionsAdapter as e}from"./adapters/FunctionsAdapter";import{getCrudService as a}from"./CrudService";import{useCrudStore as s}from"./CrudStore";import{OPTIMISTIC_STATUSES as r,CRUD_OPERATION as t}from"./types";import{loadDeterministicRange as i,upsertDeterministic as o,appendToCollection as l}from"./utils/collections";import{getFieldRegistry as d,registerFieldType as p,isFieldTypeRegistered as m}from"./FieldRegistry";import{registerBuiltinFieldType as u,getFieldTypeMetadata as F,getFilterType as n,getDisplayFormatter as f,isFilterable as g,clearFieldTypeRegistry as y}from"./fieldTypeRegistry";import{useEntityForm as c,useEntityField as S,useController as T,FormNavigationProvider as C,useFormNavigation as R,useFormDraftState as v,EMPTY_VALUE as E,fromInputValue as b,isFieldEditable as U,getFieldsForOperation as P,validateEntity as h,translateFieldLabel as k,translateLabel as w}from"./forms";import{UploadProvider as I,useUploadContext as D}from"./contexts";import{useFileUpload as W,useEntityFavorites as x,useRelatedItems as A,useCrudFilters as L,useCrudPageSize as O,useFieldConditions as B,useReferenceResolver as M,useChildRows as N,useJoinedForm as V}from"./hooks";import{isStorageUrl as _,validatePicture as z,checkForBlobUrls as J,hasBlobUrls as Y}from"./utils/uploadValidation";import{defineWorkflow as j,useEntityWorkflow as q,saveWorkflowState as G,loadWorkflowState as H,clearWorkflowState as K}from"./workflows";import{formatValue as Q}from"./components/DisplayFieldRenderer";import{buildReferenceLabel as X}from"./components/controlled/select/ControlledReferenceField";import{matchesFilter as Z}from"./utils/matchesFilter";import{applyFilters as $,applySearch as ee,applySort as ae,getSearchableFields as se}from"./utils/clientListProcessing";export{t as CRUD_OPERATION,E as EMPTY_VALUE,C as FormNavigationProvider,e as FunctionsAdapter,r as OPTIMISTIC_STATUSES,I as UploadProvider,l as appendToCollection,$ as applyFilters,ee as applySearch,ae as applySort,X as buildReferenceLabel,J as checkForBlobUrls,y as clearFieldTypeRegistry,K as clearWorkflowState,j as defineWorkflow,Q as formatValue,b as fromInputValue,a as getCrudService,f as getDisplayFormatter,d as getFieldRegistry,F as getFieldTypeMetadata,P as getFieldsForOperation,n as getFilterType,se as getSearchableFields,Y as hasBlobUrls,U as isFieldEditable,m as isFieldTypeRegistered,g as isFilterable,_ as isStorageUrl,i as loadDeterministicRange,H as loadWorkflowState,Z as matchesFilter,u as registerBuiltinFieldType,p as registerFieldType,G as saveWorkflowState,k as translateFieldLabel,w as translateLabel,o as upsertDeterministic,N as useChildRows,T as useController,L as useCrudFilters,O as useCrudPageSize,s as useCrudStore,x as useEntityFavorites,S as useEntityField,c as useEntityForm,q as useEntityWorkflow,B as useFieldConditions,W as useFileUpload,v as useFormDraftState,R as useFormNavigation,V as useJoinedForm,M as useReferenceResolver,A as useRelatedItems,D as useUploadContext,h as validateEntity,z as validatePicture};
|