This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. Kept in sync with AGENTS.md — edit both together.
VEF Framework is a React 19 application framework published to npm under @vef-framework-react/* (with external consumers). It is a pnpm-workspace monorepo built on TypeScript and Vite. Backwards-incompatible changes affect downstream apps, so prefer additive changes and surface breaking ones explicitly.
pnpm playground— Start the playground dev serverpnpm test— Run all testspnpm test:watch— Tests in watch modepnpm test:coverage— Coverage report (informational only; not a CI gate)vitest run path/to/file.test.ts— Run a single test file
pnpm typecheck— Typecheck all packagespnpm typecheck:<pkg>— Typecheck one package (core/components/hooks/shared/dev/starter/form-editor/approval/approval-flow-editor/calendar)pnpm lint— ESLint--fixacross the repoeslint --fix <file>— Lint a single file
pnpm build— Build all packagespnpm build:<pkg>— Build one package (core/components/hooks/shared/dev/starter/calendar; plusbuild:playground)pnpm clean— Clean all package build outputspnpm clean:modules— Drop allnode_modulesandpnpm-lock.yaml
pnpm deps:check— Check inter-package dependency consistencypnpm deps:check:apply— Apply recommended fixespnpm sync-meta— Sync package metadata across the monorepo
Publishing is CI-triggered by pushing a v* tag (.github/workflows/release.yml) — not by a local pnpm pub. Flow:
pnpm version:patch|minor|major— bump root + every package (--no-git-tag-version, so no commit/tag).- Commit the bump as
chore(release): vX.Y.Z. git tag -a vX.Y.Z -m vX.Y.Z— the tag must equal the rootpackage.jsonversion (CI hard-fails otherwise).git push --follow-tags— thev*tag firesrelease.yml:install --frozen-lockfile→ tag/version check →typecheck→lint→test→build→pnpm publish→ GitHub Release (notes via git-cliff from Conventional Commits).
- Land feature commits before the
chore(release)commit so git-cliff picks them up. - Don't publish with
pnpm pub/pnpm release:*for a real release — they publish from your machine (local npm auth, skipping CI gates) and double-publish if combined with the tag flow; a published version can't be re-published. - A failed CI gate blocks the publish but the tag remains — delete the tag, fix, re-tag.
- CI authenticates by npm trusted publishing (the job's OIDC token; no npm token secret exists). Each package's npm settings name
coldsmirk/vef-framework-react/release.ymlas its trusted publisher, and npm attaches provenance, which rejects apackage.jsonwithoutrepository(keepurlanddirectory). A new package needs its trusted publisher configured on npmjs.com before CI can publish it; npm offers that setting only once the package exists, so a new package's first version is published by hand. - If one package's publish fails mid-run (for example a transient Sigstore
TLOG_CREATE_ENTRY_ERROR (409)), re-run the failed job:pnpm publish -rskips versions already on the registry.
Scripts: pnpm version:patch|minor|major (bump only) · pnpm release:patch|minor|major (local bump + build + publish, the non-CI path) · pnpm pub (local publish, no bump) · pnpm unpub (roll back, see scripts/unpublish.ts).
- pnpm workspaces; inter-package deps use
workspace:* - Source packages:
packages/*. Demo app:playground/. Plugins:plugins/. - Build orchestration via
pnpm --filter=./packages/* <cmd> - Source resolution: package
exportsinclude a"vef"condition pointing atsrc; the playground's Vite config and the Vitest config resolve through it (Vitest also via explicitsrcpath aliases) to the unbuilt sources for HMR / fast tests without rebuilds.
Packages publish under @vef-framework-react/* as dual ESM/CJS with TypeScript declarations.
| Package | Purpose |
|---|---|
| core | API client (TanStack Query + axios), HttpClient with BusinessError / token refresh, state utilities (Jotai / Zustand / XState), Immer, selector-based contexts, resumable chunked-upload Uploader, SSE client |
| components | antd v6 + Emotion UI library (100+ components), TanStack Form integration, semantic color/scene system, custom motion/typography components |
| hooks | Reusable React hook library (permission / event / code-set / upload / deep-compare / etc.) |
| shared | Pure-function utilities (tree, chrono, color, equal, key, path, string, event, task, format) |
| starter | Ready-to-use layouts and auth components on top of TanStack Router, plus the headless login flow (useLoginFlow) and single sign-on landing page |
| form-editor | Visual form schema editor; linkage expressions are plain JavaScript via new Function. Published under @vef-framework-react/form-editor; treat exported APIs and schema shapes as external surface. Targets forms with 100s of fields. |
| approval-flow-editor | Visual approval flow editor on @xyflow/react v12 (ReactFlow) + elkjs auto-layout (excluded from test scope — visual canvas) |
| approval-form-bridge | Projection bridge from form-editor schemas to the Go approval form contract: projectFormSchema (one walk → backend FormDefinition + flow-editor formFields, conservation errors for unprojectable keyed fields), createApprovalRegistries (approval profile — no switch / button), validateApprovalSchema save gate, and its projection layer alone (validateApprovalProjection) for FormEditor's validate |
| calendar | Work calendar year/month views and override management, reusable window-rule editing and summaries, and server-backed window previews and status indicators |
| approval | Ready-to-use approval engine pages on the Go approval module: runtime pages (initiate / task center / my instances with the action-complete instance detail), management pages (flow list + full-screen designer wizard absorbing form-editor + approval-flow-editor, categories, delegations, admin console), ApprovalProvider host plugins (org pickers, option / lookup API catalog and FormServices, form globals), typed API layer mirroring the Go DTOs, and the progress-annotated flow-graph viewer |
| dev | Shared ESLint / Stylelint / Commitlint configs, Vite plugins, TypeScript configs |
-
Business approval forms register a
BusinessKindRendererunderApprovalPlugins.businessKinds[kind]. ItsStartFormandDetailViewexposeBusinessFormHandle.collect()on the suppliedhandle. Collect validates local input and returns the data for onestart,resubmit, orprocess_taskrequest. A missing renderer disables the action. The designer useslist_business_kindsfor the field catalog, deploys business versions with JSON storage and an empty form schema, and checks conditions, personnel, field permissions and rollback options against the backend contract. Aggregate conditions use the projected or business form fields. Scalar conditions can also reference runtime globals. The wizard checks static title references at business kind selection or during ordinary form design. -
Instance voiding uses the current flow policy and the detail's server-resolved actions. Direct voids require
approval.instance.voidand preview withadmin.plan_void. The built-inapproval.void_requestrenderer receives avoidTargetfrom the target detail, previews withmy.plan_void, and submits through the ordinary start or resubmit action. A host can override this renderer inApprovalPlugins.businessKinds. A target renderer can supplyBusinessKindRenderer.VoidOptions({ value, onChange }). Changes to those options always fetch a fresh plan, including on returned requests. Renderers can callonAvailabilityChange(false, reason)to show why submission or resubmission is disabled. Read-only details show the live plan for pending requests and the recorded outcome for settled requests. Hidden fields are omitted, including the link when the target ID is hidden. -
Host form documents may use a host format when the Go backend installs
vef.ProvideApprovalFormSchemaParser. Supply a stableApprovalPlugins.formSchemaAdapterthat treats its input as immutable, returns native schemas unchanged and returnsundefinedfor unsupported documents.useFormSchema(document)shares one result per object within the provider, including empty results. The publicInstanceFormPanel, start drawer, personal and admin detail forms, and annotation field pickers and anchors use this resolution. Unsupported documents render the empty state. The query cache retains the wire document. The built-in flow designer edits native schemas directly. -
Idempotent approval submissions accept an optional
idempotencyKeyonapproval/instance.startandresubmit(at most 128 characters, scoped to the instance tenant). The built-in forms reuse a key when retrying the same submission and generate a fresh key for a new session or a changed payload. A replay returns the original instance in its current state forstartand empty success forresubmit. Reusing a key with a different applicant, operation or submission returns 40041, shown inline. Hosts with their own forms supply the key. A business kind with its own command ID should use that ID as its idempotency key. -
Approval annotations come from the viewer-specific detail. Use
useAnnotations(detail),AnnotationList,AnnotationComposer, andAnnotationResponseComposerfor inline business views. Draft saves and deletes useapproval.annotation.write. A task decision publishes its drafts and an applicant resubmission publishes response drafts. A field filter can select a whole field, a row, a column, or a cell. Node audiences select approval and handle nodes. -
Form field extras use the optional
FormRenderer.renderFieldExtra({ key, type, label, row, column })render prop. It runs for visible keyed fields after linkage and field permissions. A subform has one whole-field slot. Both layouts expose row and cell slots with zero-based row indices. Desktop tables also expose column-header slots. A column uses its template field key. Returningnullkeeps the original layout. -
API Client (
packages/core/src/api/client.ts) wrapsHttpClient+QueryClient.createQueryFninjects an invocation-isolatedAbortSignal; its factory runs once per query execution and must keep cross-request state or side effects outside the factory.createMutationFnreuses a handler for each HTTP error-feedback mode, passes mutation meta to that handler, andexecuteMutation()runs mutations imperatively. -
CRUD reads take their filters in
meta: every CRUD read (find_page/find_all/find_one/find_tree) decodes its search struct (crud.Sortable, anapi.M) from the request'smeta, beside the pagination, never fromparams, where the backend drops it as unmapped. Each package's API layer therefore folds the filters intometa(toCrudReadMetain approval / cron / integration); sent asparams, afind_oneid would come back as an arbitrary row. Custom RPC actions are the opposite: their params structs embedapi.Pand readparams. -
HTTP errors split into
BusinessError(API returned a non-OK business code; carriescode/message/data) and network errors (axios errors for 4xx/5xx, timeouts). -
Token refresh coordination (
packages/core/src/http/client.ts): on a 401 with a configuredtokenExpiredCode,HttpClientpublishes one shared refresh promise. Concurrent new requests wait through request-scoped, abort-aware waiters and resume with the renewed token; canceling a waiter or the triggering 401 caller does not cancel the global refresh. After a successful refresh, a live triggering request retries with the renewed token; an automatic refresh failure callsonUnauthenticatedonce even if that caller was canceled.ensureTokenRefreshed(false)suppresses the callback only when it owns the refresh cycle. -
Login flow (
packages/starter/src/components/login/use-login-flow.ts): authentication is a loop, not a request — the backend answers a login with either a session or a challenge, and answering a challenge yields the same two outcomes again.useLoginFlowowns that loop headlessly (challenge cycle, error normalization, credential encryption, the store write, navigation), so<Login>and an application's own login screen are consumers rather than reimplementations. It never rejects — failures surface througherror; the store write is not overridable (the route guards read it) whileonAuthenticatedreplaces navigation and the welcome notification. The store write is also the success boundary: a failure after it (a rejectingonAuthenticated, a failed invalidation or navigation) goes toonErroralone, never toerror, which would otherwise render "登录失败" over an authenticated session on a form that can no longer accomplish anything.cancelis likewise ignored whilepending: an answer already submitted will still be applied. A URL-suppliedredirectis narrowed to a rooted internal path before navigation (redirectTo, being the application's own, is not) — on the single sign-on route the search is whatever the originating system appended. Establishing a session drops the previous identity's menus before the layout guard can read them.LoginChallengeOutletis the shared renderer lookup, including the alert shown for a challenge type no renderer is registered for; it renders each renderer as an element with a per-type key, never by calling it — a plain call would run every renderer's hooks in the outlet's one hook list, so a chain such as department selection followed by a forced password change would crash on the second challenge.autoResolveanswers selected challenges without presenting them, keyed by type and deliberately partial where the renderer registry is exhaustive: presenting a challenge is mandatory, answering one on the user's behalf is opt-in per type, so a second factor can never be resolved from ambient data. Each type is attempted once — a silent answer the server rejects falls through to the renderer instead of retrying, which would loop against the backend's brute-force guard. -
Single sign-on (
packages/starter/src/components/sso,createSsoRouteOptions): a trust-login handoff is an ordinary login carrying a one-time code instead of a password, so everything after the exchange is the shared login flow — challenge chain included, because the originating system authenticated the user but did not satisfy this application's login policy.useSsoLoginadds only what is specific to a handoff: reading it out of the URL (readHandoff, defaulting to the framework'sapp_id+codeconvention), spending it exactly once per mount, and clearing it from the address bar. Two details are load-bearing there. The clear happens before the exchange, not after: by the time the exchange settles the browser may already be on the destination, where rewriting the URL to its bare pathname would discard that page's own query and hash. AndSsoLoginFlow.searchis a snapshot taken at mount, because@tanstack/historypatcheshistory.replaceState— clearing the URL notifies the router and empties its live search, which a landing page or an auto-resolver still needs to read.statushas a terminal state: a spent handoff that produced neither a session nor a pending challenge (the user cancelled, or the result carried nothing) reportsfailed, since the one-time code is gone and nothing can restart it.publicKeyis accepted here too — a handoff meets the samepassword_changechallenge a password login does, and without the key its renderer would submit the new password in clear text. The route deliberately has nobeforeLoadbouncing an authenticated visitor: a handoff names the user it is for and may arrive at a tab signed in as somebody else, so it always exchanges and replaces the session.<SsoLogin>is a plain default page taking no slots; an application-specific screen is written overuseSsoLoginand passed tocreateSsoRouteOptionsascomponent.<SsoLogin>pairsonResolveChallengewithchallengeRenderersthe way<Login>does — renderers without a dispatcher put a challenge on screen whose submit button can never do anything.createLoginRouteOptionsandcreateSsoRouteOptionsare the same shape: each takes either the default page's props or acomponentreplacing the page, as a discriminated union rather than an optional prop that would leave the others silently dead; the custom-page member forbids every default-page prop explicitly (Partial<Record<keyof …Props, never>>) because excess-property checking catches an inline literal but not a pre-built value, where the surplus props would be dropped in silence. The route keeps what no screen should restate — for login theredirectcontract (defaulted andcatch-guarded) and the already-authenticated guard, for single sign-on the pass-through search. -
Path parameters:
:paramNamein the URL is substituted fromparams—/users/:id+{ id: 123 }→/users/123. -
Query remounts: VEF no longer enables
experimental_prefetchInRenderon its default QueryClient. An enabled query that failed before receiving data retries when its observer remounts. Hosts readingresult.promisemust migrate touseSuspenseQueryfrom@tanstack/react-queryfor Suspense or read the query observer'sdatafor ordinary rendering and effects. -
Inline HTTP errors: set
meta.shouldShowErrorFeedback: falseon the query or mutation whose UI displays every failure. Other callers of the same API keep global feedback by default. The API client appliesskipErrorMessage: trueto HTTP requests for that invocation; direct HTTP callers can set the same request option. This suppresses global warning and error messages for that request. Errors still reject, and token refresh, expired-login handling and access-denied callbacks still run. -
Auth skip: set header
X-Skip-Authentication: "1"to bypass Bearer injection for a single request. -
Body encoding (
packages/core/src/http/body-encoding.ts): legacy request-only encoding remains available throughbodyEncoding: "base64" | "gzip+base64"onpost/put(ordefaultBodyEncoding), with"none"as a per-request opt-out; integration script saves usegzip+base64. Client-wideprotectedBodyEncoding: { encoding: "aes-gcm+base64", key }is a separate mandatory bidirectional mode: every JSON request body is AES-GCM protected regardless of a legacy per-request override, every envelope/error response must carry the sameX-Body-Encoding, and the response interceptor decrypts before business/error handling. Multipart/binary bodies remain native. The wire body is raw standard padded Base64 with no JSON wrapper:Base64(12-byte random nonce || ciphertext || 16-byte tag). KeeptransformRequest: [body => body]for every pre-encoded request, because axios otherwise JSON-stringifies a base64 string underapplication/jsonand adds quotes. The Go backend also supportssm4-gcm+base64, but this browser package deliberately does not ship an SM4 implementation; AES-GCM is the supported interoperable path, run on Web Crypto where the runtime exposescrypto.subtleand on@noble/cipherselsewhere: browsers exposecrypto.subtleonly in secure contexts, so a page served over plain HTTP would otherwise be unable to construct the client. Both produce identical bytes, and the nonce sourcegetRandomValuesis available in either context. Working over HTTP is not being secure over HTTP — a browser-held symmetric key is extractable, and without TLS anyone on the path reads it from the bundle — so HTTPS is still what provides confidentiality.client.node.test.tspins wire and crypto interoperability against a real HTTP server;body-encoding.test.tspins the portable cipher against Web Crypto withcrypto.subtlehidden. -
File preview bridge: the framework bundles no viewer library.
components/file-previewdefines theFilePreviewTarget/FilePreviewHandlercontract; the app installs a preview host viaFilePreviewProvider, and<Upload>(and everything built on it) dispatches non-image files to it as normalized targets (toFilePreviewTargetreadsUploadedFileMeta— stamped byFileUploadon upload and byStoredFileUploadon hydrate). Images keep the built-inImagemodal; without an accepting provider the framework warns and never navigates directly to a URL whose authentication requirements it cannot prove. Private files are fetched or downloaded by the host throughHttpClient.requestFile(url)/HttpClient.download(url)(Bearer + 401 refresh +Content-Dispositionfilename). Reference integration: playground's@file-viewer/reacthost atplayground/src/components/file-viewer-preview-host.tsx, mounted around the authenticated layout inpages/_layout/route.tsx(try it atsys/file-preview-demo); the viewer's renderer preset is registered byfileViewerRenderers()inplayground/vite.config.ts. -
Storage-backed upload fields:
StoredFileUpload(components) is the controlled core — value in, value out, where the value is storage object keys: a single key string whenmaxCountis 1, an array otherwise, which is exactly what the Goapproval.FieldUploadkind validates. It owns key hydration, the registry filename lookup, and that single-vs-multi shape, so every binding is a thin wrapper:UploadFieldbinds it to TanStack form state, and the form designer'suploadfield (form-editor/components/upload-field, palette groupdate-file, projected to the approvaluploadkind by the bridge'sKIND_BY_TYPE) binds it to the renderer's value/onChange props. The mobile registry reuses the same renderer deliberately — a file picker is a native OS surface, and omitting it would render "未知字段类型" instead of a working control. -
State management: Jotai for atomic state, Zustand for stores (with
createStore/createPersistedStoremiddleware stack incore/store), XState for complex machines (withuseActor+ selector incore/state-machine). Pick by complexity. -
Forms: TanStack Form is wrapped by
packages/components/src/form/*and surfaced throughFormModal/FormDrawer/Crud. -
Application-wide component defaults:
ConfigProvider'scomponents(in starter,App/ThemeConfigProvider) is a per-component whitelist, not a pass-through.defaultablePropKeysincomponents/config-provider/component-defaults.tsis the entire surface an application can default;ComponentDefaultsis derived from it andresolveComponentDefaultspicks by it at runtime, so the type and the enforcement cannot drift and a pre-built value cannot smuggle a non-whitelisted prop. A prop qualifies only when its right value depends on the business rather than the design system, stays correct wherever the framework itself renders the component, does not restyle it, and does not bypass a framework pipeline — soprefixCls, raw theme tokens,componentSize,variant,locale, overlay containers, and the modal / drawer / popover interaction conventions have no global entry point (a single instance may still pass a prop explicitly). Entries backed by an antd component route into antd's ownConfigProvidercomponent config, because the re-exported antd components have no wrapper that could read a context; framework-owned components resolve theirs withuseDefaultProps(name, props)— explicit non-undefinedprop > application default > destructuring default, returningpropsitself when nothing is configured. A composite forwardsundefinedinstead of baking in a default, so one entry covers everything built on the consumer; a composite that also reads the prop itself resolves it with the same entry (CrudresolvesProTable.rowKeyfor its delete bookkeeping).useFormLayoutapplies theFormentry to fields rendered outside aForm. Starter's theme store persists only the user's explicit picks (optionalcolorScheme, partialcolors);defaultThemefills the rest through context (useEffectiveColorScheme/useEffectiveThemeColors), so a changed application default reaches every user who never picked their own — seeding the store could not, since it hydrates at import time. -
Linkage expressions:
form-editorconditions, assignment expressions, and script actions are all plain JavaScript compiled throughnew Function(engine/linkage/default-evaluator.ts) withfield/$form,$vars,$user,$node,$applicant,$globals, aDate$now, and (inside effect action sequences)$stepsin scope; hosts swap in their own runtime viaLinkageEvaluators. StructuredDynamicValueslots support"literal","reference"(dot-path reads withoutnew Function), and"expression". Expression inputs are CodeMirror (CodeEditorfrom components) with completion off.approval-flow-editorcondition expressions use the Go engine's own syntax — edited as plain text (no highlighting), validated and evaluated on the backend; itsCONDITION_OPERATORSvocabulary lives inapproval-flow-editor/src/types.ts, and the per-field operator compatibility table (getOperatorsForField/isOperatorValidForFieldinapproval-flow-editor/src/shared/condition-operators.ts, distinguishing single-valueselectfrom multi-valueselectviaFormFieldDefinition.isMultiple, set by the bridge and Go parser forcheckbox-group,multi-select, andtree-multi-select, supporting ordering/emptiness ondateanddatetime, and limitingdaterangetois_empty/is_not_empty) stays in lockstep with Goapproval/condition.go(ConditionOperatorsForField/IsOperatorValidForField) and is enforced by bothflow-validation.ts(condition_operator_not_allowed) and Go deploy validation (ValidateConditionFields, reported asapproval.ErrInvalidFlowDesign). Date granularity (DateGranularity = "year" | "quarter" | "month" | "day", omitted ="day", shared format constants and strict parse/format helpers in@vef-framework-react/shared/utils/chrono.ts:YYYY,YYYY-Qn,YYYY-MM,YYYY-MM-DD) applies todateanddaterangeon PC, mobile, approval projection (FormFieldDefinition.granularity), and flow condition inputs, whiledatetimeprojects to its owndatetimekind (YYYY-MM-DD HH:mm:ss). -
Global context injection:
FormRenderer'sevaluationContextcarries host runtime context into every expression, script, and — via a$-rootedsourceKeylike$applicant.departmentId— visual leaf condition. The roots are one table,CONTEXT_SLOTSinengine/linkage/scope.ts($vars/$user/$node/$applicant/$globals, plus$formfor the values): the leaf resolver, the validator (an unknown root issource_scope_unknown), dependency tracking, and key renames all read it, and every path segment is read as an own property — a prototype member such as$user.constructornever resolves.$useris whoever views the form now;$applicantis the subject it is filled on behalf of — in a workflow the initiator — and is the same for every viewer of a record, which is why an approval form must never put the initiator in$user.$globalsare read-only host attributes, unlike the schema's own writable$vars. The designer'scontextSources(LinkageContextSource[]) declares those paths as system variables: the sidebar's 数据 tab lists them with design-time preview samples (laid over the host context in the preview only, never stored), and the condition builder offers them as a 系统变量 group. The approval package wires this end to end:InstanceFormPaneltakes the instance'sapplicantandglobals(the start form's frommy.get_start_form, which resolves the applicant exactly as starting does, so$applicantreads identically at initiation and on every detail view), and the designer offers the four applicant attributes plusApprovalPlugins.formGlobals. A host rendering its own designer usesApprovalFormEditor, the design-time counterpart ofInstanceFormPanel:FormEditorwired fromApprovalProviderwith those system variables and the approval projection check (validateApprovalProjection) fixed, and registries, services, evaluators and the API and dictionary catalogs taken from the provider unless passed explicitly. Host globals reach a form only by opt-in: the Go resolver implementsapproval.FormGlobalsExposernaming the keys, andformGlobalsmust stay in lockstep with them.approval-flow-editormirrors this withEditorPlugins.globalSubjects(FormFieldDefinition[]), layered between the built-in applicant subjects and form fields; the Go engine resolves them fromInstance.Globals, a server-side snapshot supplied by the host'sInstanceGlobalsResolverat instance start (never from the client request — globals steer routing). The two built-in applicant subjects are not reachable that way — the engine resolves them before globals, deliberately, since the same instance column also drives assignee resolution and the initiator check — so making them selectable rather than typed goes throughEditorPlugins.pickersinstead:applicantIdtakes the user picker andapplicantDepartmentIdthe department one, for the operators that compare a whole id, degrading to free text where a picker is unwired. -
Option hierarchy and tree select controls:
FieldOptionsupportsdisabled,description, and nestedchildrenacross all four option sources (static,ref,codeSet,remote), with tree-wide value uniqueness checked recursively (findDuplicateOptionValuesoverwalkOptionTree).RemoteOptionMappingaddschildrenKey(nested mode, default"children") andparentKey(flat-to-tree mode, taking precedence overchildrenKey; missing/empty/self/cyclic parents become roots without looping), alongsidedisabledKeyanddescriptionKey(all active inmapRemoteResponseToOptions, with matching default placeholders inRemoteOptionSourceEditor). Runtime preserves full option trees: flat selection controls (select,multi-select,radio,checkbox-group) read top-level entries only throughuseTopLevelFieldOptions, whiletree-select(scalar) andtree-multi-select(strict non-cascading multi-value array,columnType: "json") consume the full tree and supportleafOnly(leafOnlyEntry, data-contract synced between matching tree twins, isolated from flat choice families).disabledoptions cannot be picked while already-stored values keep rendering;descriptionrenders as secondary muted text and participates in search. PC (OptionTreeSelectinrender/parts/option-tree-select.tsx, shared across runtime controls,TypedLiteralInput, and canvasSampleCell) and mobile (MobileTreeSelectInput/MobileTreeMultiSelectInput) sharefilterOptionTree(retaining a matched node's entire subtree, withshowSearch.filterTreeNode: falseon PC) anduseOptionTreeExpansion(recomputing initial expansion on open, async option arrival, and query change while keeping browse and search expansion isolated and never resetting on selection changes); underleafOnly, clicking a non-leaf node expands it on both PC (treeExpandAction="click") and mobile.OptionListEditoredits both flat and hierarchical lists through one pre-order row model keyed by stable ephemeral row IDs (reusingsortable-rowsdrag helpers in flat mode) so focus, open details, and collapse state follow logical rows across delete, move, indent, and outdent. Runtime value normalization, permission bridge, and approval projection shareselectableOptionsForField(tree controls flatten in pre-order honoringleafOnly, flat controls and fixed-row subforms take top-level only), strippingdisabled/description/childrento plain{ label, value }and carrying normalizedchildrenKey/parentKeyinoptionSource.mapping. -
Remote option data sources: a
RemoteDataSourceRequestcarriesresource/action/versionplusparams, and each parameter is aDynamicValue— the same{ kind: "literal" } | { kind: "reference" } | { kind: "expression" }union linkage action values use, so oneDynamicValueEditorserves both and the two cannot drift. References and expressions are evaluated by the form runtime before the request reaches the host service (engine/data-source-params.ts), soFormServices.requestonly ever sees plain data plus{ signal }(andDataSourceProvidermaps array or paginated.itemspayloads intoFieldOption[]viamapRemoteResponseToOptions); the option cache is keyed on the resolved request, which is what makes a bound parameter changing re-fetch while an unrelated keystroke does not — cascading falls out of the cache key rather than needing its own channel. The values subscription is gated onschemaHasBoundParams, so a form that binds nothing keeps its selects out of the keystroke re-render path. Host services are not wired by default:FormRendererandFormEditortakeservices(FormServices) as a prop andApprovalProviderpassesplugins.servicesthrough to the instance form and the designer — withoutservices.request, every remote source resolves to[], which reads as "the framework never fetches" rather than as missing configuration. A host API catalog replaces hand-typed endpoints:FormEditor'sdataSourceApis(DataSourceApi[],ApprovalPlugins.dataSourceApisin approval) makes the remote option-source editors lead with a picker; a pick copies the endpoint, mapping, and declared-parameter defaults into the schema, so the stored request stays self-contained and the runtime, the request service, and the bridge projection never need the catalog — a stored request is recognized as an API again by its endpoint (resource+action+version). Mappings are normalized (normalizeOptionMapping) wherever they are stored, resolved, or projected: a blank key means the default, but a mapper readingmapping.labelKey ?? "label"would take""literally. Parameter names in the editor are draft-buffered and committed only when non-blank and unique, so a rename in progress can never collapse two rows into one record key. Evaluators are the opposite: they default throughresolveLinkageEvaluators, and the param scope must resolve through it too — reading the host's raw overrides instead makes a bound parameter silently unresolvable on every form that does not override, while linkage expressions keep working. The approval projection carries the source through to the backend:projectFormSchemaenumerates a static source (inline or via aref) intooptionsas before, and now emits an unresolvable one asApprovalFormField.optionSource— the post-dereference{ kind: "remote", request?, mapping? }, mirroring the GoFieldOptionSource. Params travel unevaluated, since neither the backend nor a list-rendering consumer holds form values to evaluate them against; the GoRemoteOptionRequest.HasBoundParams(true for both"reference"and"expression"params) tells a consumer whether one lookup can translate a whole column or the option set is per-row. It exists so a list view can render a stored value as its label instead of its raw value — the backend still validates againstoptionsalone, so a remote field accepts any submitted value andoptions_not_statickeeps warning about exactly that. -
Form action sequences (
FormServices,commit,SequenceController): effect rules run ordered action sequences (runtime/action-executor.ts, with a synchronous fast-path for sync-only rules and a singlefinallysettlement point so any throw still releases slots, busy counts, and submit gates) acrossapi_call,select_record,set_fields,set_variable,refresh_data_source,alert,navigate,submit, andreset, returning a typedSequenceOutcome("completed" | "stopped" | "aborted" | "failed"). They share one hostFormServicesinterface (request,navigate,notify;notifydefaults to framework toast messages; preview runs realrequestand mapsnavigateto a preview toast while the designer gatesapi_call/navigateon hostserviceCapabilities, keeps already-stored unwired actions editable, and marks them当前宿主不支持). Every step reads live environment state (disabled,$vars,evaluators,fieldPermissions,services,knownOptions) through one stableSequenceEnvrather than trigger-time snapshots.commit(FieldComponentConfig.commit: "entry" | "change", default"change") separates explicit completion from per-keystrokechange: single-line text and number inputs commit on IME-safe Enter (guardingcompositionstart..end,isComposing,key === "Process", and Safari's post-compositionendkeyCode === 229; preventing outer form submit; number flushes its draft first) or dirty blur,textareacommits on dirty blur, and selection controls commit on user change; programmatic writes never firecommitorchange. Event triggers accept an optionalwhenguard (preserved across trigger switches viaswitchRuleTrigger, with control-specificcommithints); condition triggers carry rule-levelretrigger: "edge" | "always". Earlier step outputs (output, minted rule-unique by default and propagated downstream on rename viarenameStepOutputInRule) feed later actions via$steps.<name>[.path](with per-actiononError: "stop" | "continue").select_recordauto-selects 1 record, notifies + obeyswhenNone("stop"/"continue") on 0 records, and opens a picker on >1 records (PCModalwith frameworkTableinside a singleScrollArea, semantic<table>withoutrole="option", scoped keyboard navigation withscrollIntoView({ block: "nearest" }), close-transition retention, and trigger-focus restoration; mobilePopupcard list contained insideuseMobileScopeContainer).SequenceController(runtime/sequence-controller.ts) enforces single-flight per(scope, ownerField, rule), staleness discard when re-resolvedapi_callinputs diverge on settle, aborts on supersede / external reset / unmount / subform row deletion (with live shifted-index prefix reads for surviving sibling rows; aresetaction aborts other runs viaabortOtherswhile continuing its own sequence), and a unified submit gate via polymorphic<Form component={FormSurface}>(no form-instance mutation) that coalesces concurrent external submits onto one Promise, cancels waiting submits on reset, releases a calling sequence's request gate vialeaveSubmitGate()onsubmit(preventing multi-rule or recursive-lifecycle deadlocks), blocks submission quietly wheneverbeforeSubmitends with any outcome other than"completed", keepsgetSubmitValues()synchronous while exposingFormRendererApi.waitForPendingSequences()(awaited byInstanceDetailPanel's reject path before reading values), renders per-field busy indicators (useFieldBusy+<Spin size="small" />in label / cell-status slots, never overlaid on control suffixes), and enforces disabled-form read-only rules (set_fieldsskipped;select_record/submit/resethalt the sequence). Every programmatic write passes throughwriteFieldValue/normalizeFieldValue(runtime/field-write.ts), guarded by the singleisWritableTargetFieldpredicate shared with validation and designer pickers, normalizing values to the exact shapes GovalidateFormFieldaccepts and clearing broken references. In the designer (editor/properties/entries/linkage/*),RuleListEditorrenders field, container, and form-event rules as a compact two-lineDataListRowlist (trigger summary fromtrigger-summary.ts, single- or multi-step action summary fromaction-summary.ts, issue marker & count, hover/focus duplicate and delete; rows are memoized on primitive summaries and stable callbacks). Draft-modal lifecycle (monotonic session keys,editingId, close-transition mount retention, row-ref maps, and scroll+open diagnostic jumps) is shared throughuseDraftSession(editor/properties/use-draft-session.ts) across data sources, variables (useDataEntryEditor), and linkage rule lists. Clicking a row,新建…规则, or a template opens one rule at a time in a single-layer 960pxRuleDraftModal(DraftModal:structuredClonedraft, dirty-close confirmation, single undo step on确定, live draft diagnostics viauseDraftRuleIssues, and rule-wide step-output draft validation/pruning/rename-apply helpers instep-output-drafts.tsthat block确定and focus the offending step).useScopeFieldOptionsanduseFieldOptionsReferenceScope(editor/properties/scope-fields.ts) provide the single path shared byNodeReferenceScopeProvider,useLinkageEditorModel, andRuleDraftModal, subscribing to$varsonly while a picker or open rule dialog is mounted so variable or unrelated scope edits never re-render closed rule rows. Inside the rule dialog, action sequences are drag-sortable, collapsible with plain-Chinese one-line summaries (single-step expanded, multi-step collapsed so a full pipeline fits on one screen), confirm before deleting a referenced step or moving a producer past its consumer, and edit all steps — includingapi_call,select_record, andset_fields— directly in place with no second modal on top.CatalogRemoteRequestEditorserves both remote option sources andapi_call;ReferenceScopeProvider/ReferencePicker(editor/properties/reference-scope.tsx) is the single grouped candidate picker shared byConditionEditorandDynamicValueEditor(fields,$vars.*, system variables, and earlier step outputs withapi.fieldsinherited acrossselect_recordplus inline sub-path input for undeclared APIs);set_fieldsoffers sortable mappings, target-typed literals (TypedLiteralInput), and"按名称匹配"(matchStepFieldsToTargets, which leaves the rule's own field out so a lookup that finds nothing never clears what was just typed);select_recordoffers declared-field column picking, drag-sorting, and live auto-inferred column previews (collectInferredSelectRecordColumns); and"查询并回填"(templates.ts) is offered as a pure rule factory only on writable leaf fields whenserviceCapabilities.hasRequestis true.engine/linkage/action-descriptors.ts(ACTION_DESCRIPTORS, internal to the package) is the single traversal table shared by validation, key rename, reference pruning, date-literal checks/scrubs, clone/move remapping, and bound-parameter scanning, whileengine/linkage/step-schema.tsholds the pure designer step analysis/matching helpers. -
Data-dictionary option sources: a selection field can take its options from a host data dictionary —
{ kind: "codeSet", codeSet }, the fourthFieldOptionSourcearm (数据字典 in the designer). There is deliberately no form-level list of dictionaries to maintain:FormRenderer(and the designer canvas) collect every key the presentation's fields read, subform templates and fixed-row subform sources included (collectCodeSets), andCodeSetProviderloads them in one batched call throughcodeSetQueryFn— the prop, elseAppContext.codeSetQueryFn, under the same[queryFn.key, sortedKeys]query keyuseCodeSetQuerybuilds, so a dictionary the application already loaded is served from the TanStack cache. The load runs in a sibling that mounts only when there is a key and a query function, so a form reading no dictionary never needs aQueryClient(form-editor specs render without one).CodeSetProviderpreserves nestedchildren,disabled, anddescriptionfrom each loaded dictionary: flat selection controls and fixed-row subforms consume top-level entries only whiletree-selectandtree-multi-selectconsume the full hierarchy. PC table-variant subform cells render the exact same leaf field components (and per-rowSubformRowController/DataSourceParamScopeProvider) as stacked subforms (with the canvasSampleCellalso reading throughuseFieldOptions), so all four option sources (static,ref,remote,codeSet), bound parameters, and original option value types behave identically across layouts. The designer picks from the host catalogFormEditor.codeSets(ApprovalPlugins.codeSets; design-time only — the schema stores the key) or takes a typed key committed on blur, since every committed key is a dictionary the canvas loads. Approval projects it asoptionSource: { kind: "codeSet", codeSet }(an unpicked one keeps its kind and drops the blank key, as Go'somitemptydoes), and unlike a remote source it is checked: the Go backend validates a submitted value against the dictionary through the host'smold.CodeSetLoader, so it raises nooptions_not_staticwarning. -
Detail-table row modes (
SubformRows):SubformBase.rowsis a discriminated union ({ mode: "dynamic", min?, max?, addLabel? } | { mode: "fixed", source, itemKey, headerLabel?, headerWidth?, required? }; omittedrowsis dynamic). Fixed-row subforms (also offered in the palette via thematrixTableDefinitionpreset withpaletteId: "matrix-table"— atype: "subform"factory, not a second node type) model checklist/matrix tables whose rows come from anyFieldOptionSource(static,ref,codeSet, orremote, edited through the sharedOptionSourceEditorwith bulk-paste support on static lists). Each row snapshots{ value, label }underrow[itemKey](reserved inside the subform's key scope viacollectScopeKeysand never included incolumnsor aggregate pickers). At runtime on PC,variant: "table"renders every template cell directly editable against the outer form (render/subform-table.tsx, sharingSubformRowController's per-row linkage, bound-parameter scope, memoization, and direct cell validation withstack, with no per-row edit/save/operation column): fixed rows prepend a read-only header column with no add/delete controls, while dynamic rows show a bottom add button (rows.addLabel, respectingmax) and a compact trailing delete action whenrows.length > min; PCstackand mobile render each row as a titled card in fixed mode with no add/delete controls. At runtime (useFixedSubformRows), non-empty storeddefaultValueslock the subform to its stored snapshot (never callinguseFieldOptionseven when bound params change), while fresh fills resolve the source, rebuild rows on bound-param changes preserving surviving cells byvalue, and clear to[]on error sorows.requiredblocks submission. Approval projects fixed-row tables withApprovalFormField.fixedRows(itemKey, optionalheaderLabel, anditemsXOR post-dereferencesource), mirroring Goformeditorparity fixtures; Go validates each source kind (staticexact order/value/label,codeSetunique + dictionary membership,remoteunique + shape) and materializes<itemKey>_value/<itemKey>_labelTEXT NOT NULLcolumns undertablestorage. -
Cross-device data-contract consistency: PC and mobile presentations may arrange different layout trees, but a keyed node (same value scope and key) binds one shared data contract. In
form-editor, editing any data-contract property (key,granularity,validate,dataSource,leafOnly,columnType, numberprecision, uploadmaxCount, or subformrowsmode /itemKey/source/required/ dynamicmin/max) via the store (setFieldKey,setDateGranularity,editField,updateBlock, backed byengine/schema/contract-sync.ts) propagates to its same-scope, same-key twin on the opposite presentation within the same undo step, while leaving purely presentational properties (label,placeholder,headerLabel,headerWidth,addLabel,variant, layout sizing, and template column trees) device-local and leaving absent twins untouched. At publish/deploy, bothapproval-form-bridge(contract-compare.ts) and Gointernal/approval/formeditor(contract_compare.go) project both devices and structurally compare their data contracts (stripping display-only fields includinglabel,placeholder,validation.message,fixedRows.headerLabel, and field/column order), reporting residual divergences with dedicated error codes (cross_device_kind_mismatch,cross_device_options_mismatch,cross_device_validation_mismatch,cross_device_storage_mismatch,cross_device_table_mismatch,cross_device_table_rows_mismatch) pinned by shared parity fixtures. -
Designer diagnostics: one surface per editor.
FormEditor's footer chip opens every issue — its ownvalidateSchemaplus the host'svalidate(SchemaValidator, called only for a schema free of structural errors; approval passesvalidateApprovalProjection) — with plain designer-Chinese linkage messages (engine/validation.ts), and each locatable one jumps directly to its node,数据entry modal, or exact linkage rule and action step (pendingLinkageFocuswithruleIndexswitches to the联动tab or the表单tab for form events, opens that rule's dialog, and expands, scrolls to, and briefly highlights the step; omittingruleIndex— as the字段联动overview does — lands on the field's联动tab or scrolls a container's linkage section into view without opening a dialog;editor/issue-location.tsnames nodes through the sharednodeDisplayName/nodeDefinitionhelpers inengine/schema/walk.ts— label → key → field-registry definition name, mapping fixed-row subforms to thematrix-tablepreset矩阵表格— used consistently across outline, linkage overview, container properties/linkage, and diagnostics, e.g.工号 · 规则 1 · 步骤 3(设置字段),弹性布局 · 规则 1 · 步骤 1(调用接口),数据源「…」, with the raw path kept as a tooltip; a host path that is a field-key chain such aslines.pricelocates the field). Node removal previews (engine/schema/removal-impact.ts+editor/remove-node-confirm.tsx) report both dropped rules and partial impacts (removedset_fieldswrite items and cleared references on surviving rules, nodes, and data sources). The publish gate reads the same merged list.approval-flow-editorhas the equivalent toolbar indicator, so the approval wizard renders no issue banners above either editor (they would eat canvas height) and only says, beside the disabled 下一步, why the step cannot advance. -
Shared flows:
Flow.isShared(the GoFlow.IsShared, set byCreateFlowParams.isSharedand fixed at creation) offers a flow to every tenant, whileFlow.tenantIdstays the real tenant that owns and manages it; each instance runs in the tenant that started it. There is no reserved shared tenant and no shared category: a shared flow sits under one of its owner's categories, and a shared code is unique across every tenant's shared flows (ErrSharedFlowCodeExists, 40026), while a tenant flow of the same code replaces the shared one in its tenant. Tenancy splits by side. Self-service calls carry no tenant: a start runs in the tenant the caller acts in, soApprovalInitiatePage/StartInstanceDrawertake notenantIdand the list shows exactly what a start accepts — the tenant's own flows plus the ones other tenants share — while the othermy.*lists (task center, my instances) read the caller's own work in every tenant — cross-tenant views are the admin console's. Definitions are managed across tenants, gated by permission:ApprovalFlowPage/ApprovalCategoryPage'stenantIdis the tenant the page manages, filtering its list (find_flows/find_treelist every tenant when it is omitted) and stamping what it creates; the backend never checks it against the caller's own tenant.find_flowslists the flows a tenant owns, its shared ones included;FlowSearch.includeSharedadds other tenants' shared flows whose code the tenant has not taken — the flows a start by code finds there, which is what a host picker of a tenant's usable flows wants. The designer's basic step carries the 全局流程 switch (disabled once the flow exists), and the designer derives shared mode from it —flow.isSharedwhen editing, the draft while creating — passing it asEditorPlugins.shared: a shared flow may route work to people of other tenants than the one that starts it, who act on it from their own (the backend's tenant guard lets the people a task or copy was routed to through; administration stays within the instance's tenant), so nothing is disabled or flagged for it. Users and departments belong to one tenant each, so with the host'sApprovalPlugins.tenants(TenantOption[],EditorPlugins.tenants) wired, an assignee or CC row picking them asks for the 机构 first and the picker is handed the pick asPickerProps.tenantId— disabled until one is chosen. The pick is stored astenantIdon the rule (designer-only: the backend keeps it with the definition and never reads it); changing the tenant clears the ids, switching a row between user and department keeps it, and roles and host catalogs are never per tenant. Withouttenantsa shared flow picks people through the plain pickers, and the node-admin and fallback-user lists are not tenant-aware yet. Categories never span tenants, so the designer's category picker, the category form's parent picker and the delegation picker all read the one tenant they are given. -
Sortable lists: a dnd-kit sortable drag moves the rows' elements as it goes and puts them back only when it is canceled, so a list must end up rendered in the order left on screen. Commit a drop with core's
moveSortableItem(form-editor rows:useSortableRows/reorderRows), nevermoveDragItem, which keeps the old order when the pointer is released off every row. Key rows by identity, never by position. An order that may be taken back — a confirm after the drop — is rendered first and asked about second, asActionsEditordoes, since React cannot put back rows it never moved. -
Editor perf at scale: the form/flow editors target 100s of fields — keep per-keystroke render and per-frame drag cheap (structural sharing in
packages/form-editor/src/engine/schema/mutate.ts, memoized canvas rows, and don't let$vars/ expression-scope changes bust cellmemo). Discrete-action tree walks (drop / duplicate) are not hot paths; don't pre-optimize them.
- Vite for all packages via
defineBuildConfig()(scripts/build-config.ts) - Auto-externalizes deps/peerDeps; Emotion CSS-in-JS transform;
.d.tsvia unplugin-dts - Requires Node 22+. pnpm version is auto-tracked from
package.json#packageManager(CI usespnpm/action-setup@v4).
Vitest 4 + jsdom + @testing-library/react. Test files: ./packages/**/*.test.{ts,tsx}. Global setup at ./scripts/test-setup.ts (browser-API mocks, localStorage polyfill, jsdom virtual-console filter). The root vitest.config.ts enables globals: true, so describe / it / beforeEach / expect / vi are available without imports.
Conventions below follow Testing Library, Kent C. Dodds' Testing Trophy, and the practices of React Aria / Radix / Mantine / TanStack. Existing specs are being aligned; new specs follow these from day one.
- Test behavior, not implementation. Assert on what a caller observes, not internal state, private fields, or refactor-fragile structure.
- Confidence over coverage. Prefer integration-level tests (render → interact → assert). Coverage is a side-effect of good tests.
- One concept per
it. Unrelated assertions belong in separateitblocks. - No flaky tests. No performance assertions, time-of-day logic, or real-clock
setTimeoutwaits.
Specs are colocated next to the source: <name>.test.ts(x) when the source is <name>.ts(x), or index.test.ts(x) when the source is index.ts(x). No __tests__/ directories.
Reach for these patterns before inventing new ones:
- Pure utility —
packages/shared/src/utils/tree.test.ts - Hook with
apiClientinjection —packages/hooks/src/use-has-fetching/index.test.ts(passesapiClienttorenderHook, builds aqueryFnviaapiClient.createQueryFn) - Component (antd + permission) —
packages/components/src/permission-gate/index.test.tsx - Component (form submit lifecycle) —
packages/components/src/form-modal/index.test.tsx - Component (async UI gated by
Promise.withResolvers) —packages/components/src/action-button/index.test.tsx(loading state under a deferred onClick) vi.hoisted+vi.mockfor a CJS package —packages/core/src/http/client.test.ts(axios)vi.mockfor a typed SDK module —packages/core/src/sse/client.test.ts- In-repo dependency mock at the package boundary —
packages/components/src/file-upload/index.test.tsx(mockscore/Uploader) - Fake-driver scripted backend —
packages/core/src/storage/uploader.test.ts - Manual
defer<T>()for deterministic async ordering —packages/core/src/http/client.test.ts,packages/core/src/storage/uploader.test.ts
globals: trueis on — new specs omitdescribe/it/expect/viimports. Existing explicit imports are kept; do not bulk-rename old specs purely to drop them.- Component and hook specs go through the package's
test-utils.tsx(packages/components/test-utils.tsx,packages/hooks/test-utils.tsx) —render/renderHookfrom that module installConfigProvider/AppContextProvider/ApiClientProvider. Bypassing the wrapper makes antd and permission-aware code misfire. - Pull
screen,waitFor,act,within, etc. from the sametest-utils.tsx(it re-exports* from "@testing-library/react"). - Specs that touch
useApiClient/useMutation/useQuerypassapiClienttorender/renderHook; the wrapper installsApiClientProvider(which providesQueryClientProvider). UsecreateTestApiClient()for an isolated per-test instance — its defaultbaseUrlishttp://vef-test.invalidso any leaked real network call fails loudly. packages/starter/test-utils.tsxdiffers from the others: it mounts what is under test as the only route of a router (renderRouterHook/renderInRouter), becauseRouterProviderrenders a route tree rather than its children, so a Testing Librarywrappercannot host one. It renders underStrictModeon purpose — double-invoked effects are what a "run this once" guard has to survive. The default memory history never toucheswindow.location, which also means it never writes there: anything asserting on the address bar must passhistory: "browser", or the assertion holds regardless of what the code does.- Packages without a local
test-utils.tsx(currentlycore,shared, andform-editor) import directly from@testing-library/react. They have no provider requirements —core/state-machine/index.test.ts,core/context/disabled.test.tsx, andcore/context/context-selector.test.tsxare the canonical examples.packages/form-editor/test-utils.tsholds no wrapper either: itsdragSortableRowruns a real dnd-kit drag in jsdom, which is how a spec sees the rows as a drag leaves them.
describe(module name)→ optionaldescribe("when <condition>")→it("<observable outcome>"). Descriptions read as sentences:it("renders the dialog"),it("throws when X is missing"). Do not prefix with "should" — third-person verb or imperative statement only.- Separate happy path, edge cases, and errors into distinct
describeblocks. - One
itper case — do not useit.each(it collapses semantically distinct cases under one description and obscures which row failed). - Prefer accessible queries:
getByRole/findByRole>getByLabelText>getByText>getByTestId. See Testing Library priority. queryBy*is only for absence assertions (expect(queryBy...).not.toBeInTheDocument()).findBy*already waits — do not wrap it inwaitFor.- Don't query by CSS class unless the class is a documented contract (e.g.
vef-btn-loading).
userEventonly. FreshuserEvent.setup()per test.userEventfires the full pointer/focus chain and flushes microtasks;fireEventdoes not, which silently breaks antd popover / popconfirm transitions. The repo currently has zerofireEventusage — even antd's hidden<Upload>input is driven byuser.upload(input, file)(seepackages/components/src/file-upload/index.test.tsx). If a new spec genuinely needsfireEvent, justify the exception in the PR description.await findBy*for elements appearing async;await waitFor(() => expect(...))for non-element state.Promise.withResolvers()(or a hand-rolleddefer<T>()) gates async flow under test (action-button,http/client,uploader).- Timer-driven code:
vi.useFakeTimers()/vi.useRealTimers(); flush viavi.runAllTimers(),vi.runAllTimersAsync(), orvi.advanceTimersByTime(ms). Usevi.useFakeTimers({ shouldAdvanceTime: true })when the code under test mixes a realawaitwith fake intervals. vi.spyOn(target, "method")overvi.fnwhenever you want the original implementation to still run (e.g. silencingconsole.warnwhile observing calls — seesilenceConsoleinhttp/client.test.ts). Reach forvi.fnwhen constructing a replacement from scratch.- Never
await new Promise(r => setTimeout(r, ms))— it's flaky, slow, and not what user-visible behavior depends on. Use microtask flushes (await Promise.resolve()) for ordering and fake timers for delay-sensitive code.
- Plain
expect().to*+ jest-dom matchers (toBeInTheDocument,toHaveTextContent,toHaveAttribute,toBeDisabled,toHaveValue). No custom matchers. - Snapshot tests only for stable structural output (e.g. generated schema). Never for rendered DOM.
- Mock the network layer (
axios/fetch/ event-source) and side-effect entry points of third-party SDKs. vi.hoistedis required when avi.mockfactory needs to reference an outer variable — Vitest hoistsvi.mockto file-top, andvi.hoistedis the only legal way to share state with the factory. Seehttp/client.test.ts.- Browser APIs (
ResizeObserver,IntersectionObserver,matchMedia,localStorage) are already mocked globally inscripts/test-setup.ts— do not duplicate. - Do not mock internal modules. Test through the public API. The fake-driver pattern in
uploader.test.tsis canonical: construct a typed fake of the boundary, script its responses, record calls for assertion. - A dependency from another in-repo package counts as a boundary — mocking it is fine when that dependency has its own thorough coverage (e.g.
components/file-uploadmockingcore/Uploader). - Per-test mock isolation: the project does not run
test.concurrent, so two patterns coexist legitimately:- Boundary mocks created once (
vi.hoistedinstances, module-scopedvi.fn()likemockHasPermissioninpermission-gate) — cleared inbeforeEachviamockClear()/mockReset(). Required forvi.mockfactories; acceptable elsewhere. - State-carrying fakes (call counters, captured payloads, in-memory queues like
use-deep-memo'sfactoryCallCount) — must be re-created insidebeforeEach. If a counter or buffer survives between tests, isolation is gone.
- Boundary mocks created once (
- Reset shared state in
afterEachviavi.restoreAllMocks()/vi.clearAllTimers().
renderHookfrom the package's localtest-utils.tsx. The legacy@testing-library/react-hooksis not used.actwrapping is implicit for Testing-Library-triggered updates — wrap manually only when the React warning explicitly asks.- Read latest value via
result.currentat each assertion point. Don't destructure into a stale binding.
- Pure re-export modules:
core/common,core/dnd,core/immer,core/motion,core/state - Pure antd pass-through components (no behavior beyond a wrapper)
- Pure style / animation components
- Excluded from coverage (existing specs still run in
pnpm test):starter,dev,plugins,playground, and the visual canvas inapproval-flow-editor.form-editorIS in test scope (heavily tested) — just without an aggregate threshold yet. - Generated artifacts (
dist/,.d.ts)
- Package-level thresholds enforced via
vitest.config.tsforshared/hooks/core. Values reflect the measured baseline minus ~5% buffer; raised stage by stage as new specs land.componentsandform-editorare coverage-measured but have no aggregate threshold by design — tracked per-component/feature. - CI gates on
pnpm typecheck && pnpm lint && pnpm test.pnpm test:coverageruns as an informational artifact only. - New components and hooks ship with a spec. Exceptions justified in the PR description.
- When modifying any
packages/{shared,hooks,core,components,form-editor}/**source, update the corresponding spec. Before renaming exports or changing prop types, search for specs asserting the old contract. - Use
test:prefix for test-only commits (Conventional Commits, enforced by commitlint).
- Single-line only. One Conventional Commits header (
type(scope): subject); no blank line, no body — enforced by commitlint'sbody-empty/footer-emptyrules (rootcommitlint.config.tsand@vef-framework-react/dev'sdefineCommitlintConfig). Pass exactly one-m(keep under ~100 chars). Flag breaking changes with the header!(feat!:,feat(scope)!:) — theBREAKING CHANGE:footer is rejected. Extra rationale goes in the PR description or chat, never the commit body. test:prefix marks test-only commits (commitlint-enforced).
- Filenames: kebab-case. React components: PascalCase.
- No leading-underscore identifiers (e.g.
_handleSubmit). A_prefix is reserved solely for intentionally-unused params/vars (the ESLint^_ignore pattern) — never as a naming style for real, used bindings. - Comments, JSDoc, and inline docs: English only.
- When wrapping a same-named component from another package, alias the imported inner component as
XxxInternal. - Imports sorted by perfectionist plugin: type imports first, then external, then internal (alphabetical within group).
- Strict mode; TypeScript 6+. Avoid
any—no-explicit-anyis off (a convention, not lint-enforced), so prefer precise types / generics and narrow casts rather than reaching forany - Prefer
interfaceovertypefor object shapes - Array types:
T[]for simple,Array<T>for complex (array-simple rule) - Max 5 function parameters
- Type safety is not negotiable: prefer an exhaustive
switch(withassert-never/exhaustive()) overas/ widening casts on discriminated unions — never loosen types with a cast where a switch type-checks.
- No class components, no
defaultProps, prefer hooks - No unnecessary
useMemo/useCallback - JSX props sorted:
key/reffirst, then alphabetical, callbacks last
@stylistic/eslint-plugin: 2-space indent, double quotes, semicolons, 120-char line width.
- Antd styles live in the
antdCSS layer; VEF styles already have higher priority — don't use!importantor&&to override antd. - Use
globalCssVarsfrom@vef-framework-react/componentsfor theme variables. Brand-coloured text and glyphs takecolorPrimaryText, nevercolorPrimary, which is unreadable as text on dark surfaces; fills, borders and rings takecolorPrimary. - Many CSS vars (
colorText,colorBorder,colorBgContainer) auto-adapt to light/dark — no.darkoverrides needed. - Use
html.dark &only for properties that genuinely differ between themes (gradients, shadows, glass effects).
- Pre-commit (
lint-staged): runseslint --fixon staged.js/.ts/.tsx/.json/.mdfiles - Pre-push (
.husky/pre-push): runspnpm typecheck && pnpm testbefore any push
.github/workflows/test.yml runs on every PR and push to main:
- Gating:
pnpm typecheck→pnpm lint→pnpm test - Informational:
pnpm test:coverage(uploaded as artifact but not gating)
.github/workflows/release.yml runs on a pushed v* tag — re-runs the gates, then pnpm publish and a GitHub Release (see Release).
Every package is React 19 — apply these by default when writing or reviewing any component / hook (not only for big refactors):
/vercel-react-best-practices— performance & re-render patterns (memoization, derived state, effect deps, large lists)/vercel-composition-patterns— component API design (compound components, avoid boolean-prop sprawl, lift state, React 19 APIs)/ant-design— antd 6.x decision guide (component selection, theming/tokens, performance, CRUD / ProComponents); the UI layer is antd v6 + Emotion/frontend-design— visual design, styling, UI aesthetics/web-design-guidelines— UI code review (performance, forms, animations; accessibility is not prioritized for this project)- ReactFlow v12 (
@xyflow/react) best practices when working inapproval-flow-editor(its only consumer) - No
tanstack-formskill exists — forms go through the@vef-framework-react/componentsform wrapper (packages/components/src/form/*)