Skip to content

Modules — Composable & Function API Reference

Input parameters, return types, and descriptions for all exported composables and utility functions.


Core — @mapomodule/core

useCrud<T>(endpoint: string)

Generic CRUD composable backed by $mapoFetch.

ParameterTypeDescription
endpointstringBase REST endpoint (e.g. '/api/articles/').

Returns an object with:

MemberSignatureDescription
list(params?, config?) => Promise<PaginatedResponse<T>>Fetch a paginated list. Query params are forwarded to the server.
detail(id, config?) => Promise<T>Fetch a single record by ID.
create(data, config?, opts?) => Promise<T>POST a new record. Applies multipart policy automatically when files exist.
update(id, data, config?, opts?) => Promise<T>PUT a full record.
partialUpdate(id, diff, config?, opts?) => Promise<T>PATCH a partial record.
delete(id, config?) => Promise<void>DELETE a record.
updateOrCreate(data, config?, opts?) => Promise<T>PUT if data.id is present, otherwise POST.
updateOrder(startId, endId, config?) => Promise<void>POST to {endpoint}update_order/ — used for drag-and-drop reorder.

useMapoAuth()

Authentication composable. Wraps login, logout, and user-fetching over $mapoFetch.

Parameters: none.

Returns:

MemberSignatureDescription
login(credentials: { username, password }) => Promise<void>POST credentials; confirms the session by calling fetchUser.
logout() => Promise<void>GET logout endpoint, clears the session cookie, resets useAuthStore, redirects to loginUrl.
fetchUser() => Promise<void>GET current user info and hydrate useAuthStore.

Store — @mapomodule/store

useAuthStore()

Pinia store for the authenticated user's session.

State:

FieldTypeDescription
infoMapoUser | nullFull user object returned by the backend.
rawPermissionsstring[]Flat array of permission codenames.
modelPermissionsRecord<string, ModelPermissions>Per-model CRUD permission map.
pagePermissionsRecord<string, string[]>Page-level permission map (populated when meta.permissions uses { model }).

Getters:

GetterTypeDescription
isAuthenticatedbooleantrue when info is non-null.
isLoggedInbooleanAlias for isAuthenticated.
rolestring | nullUser's primary role string.
usernamestring | nullUser's username.
permissionsstring[]Flat list of permission codenames.

Actions:

ActionSignatureDescription
setUser(user: MapoUser) => voidSet user data and parse permissions into all derived maps.
reset() => voidClear all auth state (called on logout).

useSnackStore()

Pinia store for toast notifications. Used by MapoSnackBar.

State:

FieldTypeDescription
messagesSnackMessage[]Queue of pending snack notifications.

Getters:

GetterTypeDescription
currentSnackMessage | nullLast notification in the queue, or null.

Actions:

ActionSignatureDescription
show(message: string, type?: SnackType, duration?: number) => voidPush a snack notification. type defaults to 'info'.
dismiss(id?: number) => voidRemove notification by ID, or pop the last one if id is omitted.
dismissAll() => voidClear all pending notifications at once.
ts
type SnackType = "success" | "error" | "warning" | "info";

useConfirmStore()

Pinia store for the confirmation dialog. Used by MapoConfirmDialog.

State:

FieldTypeDescription
activeRef<boolean>Whether the dialog is visible.
optionsRef<ConfirmOptions | null>Current dialog options.

Methods:

MethodSignatureDescription
ask(opts: ConfirmOptions) => Promise<boolean>Show a dialog and await the user's answer. Resolves true on confirm.
confirm() => voidResolve the pending promise as true.
cancel() => voidResolve the pending promise as false.

useSidebarStore()

Pinia store for sidebar display state, persisted in cookies.

State:

FieldTypeDescription
drawerbooleanMobile drawer visibility.
minibooleanMini (icon-only) sidebar mode.

Actions:

ActionSignatureDescription
toggleDrawer() => voidToggle drawer and persist to cookie.
toggleMini() => voidToggle mini and persist to cookie.
hydrateFromCookies() => voidRestore state from cookies (called by SSR plugin).

usePermissions()

Convenience composable with readable permission-check methods.

Parameters: none.

Returns:

MethodSignatureDescription
canView(model: string) => booleanCheck view_<model> permission.
canAdd(model: string) => booleanCheck add_<model> permission.
canChange(model: string) => booleanCheck change_<model> permission.
canDelete(model: string) => booleanCheck delete_<model> permission.
checkPermission(codename: string) => booleanCheck an arbitrary permission codename.
hasRole(role: string) => booleanCheck if the user has a specific role string.

Utils — @mapomodule/utils

debounce(fn, ms)

ParameterTypeDescription
fnT extends (...args: unknown[]) => unknownFunction to debounce.
msnumberDelay in milliseconds.

Returns: (...args: Parameters<T>) => void — A new function that resets the timer on each call and executes fn only after ms ms of silence.


deepMerge(base, override)

ParameterTypeDescription
baseT extends Record<string, unknown>Base object.
overridePartial<T>Values to merge in.

Returns: T — A new object with override recursively merged into base. Arrays are replaced, not merged.


objectDiff(base, current)

ParameterTypeDescription
baseT extends Record<string, unknown>Original snapshot.
currentTCurrent state.

Returns: Partial<T> — Only the properties that differ between base and current, recursively.


deepClone(value)

ParameterTypeDescription
valueTAny value to clone.

Returns: T — A deep clone using structured cloning. Does not handle class instances, Maps, Sets, or circular references.


formatDate(date, format?)

ParameterTypeDefaultDescription
datestring | DateDate to format.
formatstring'YYYY-MM-DD'Format string. Tokens: YYYY, MM, DD, HH, mm, ss.

Returns: string — Formatted date string.


normalizeEndpoint(endpoint)

ParameterTypeDescription
endpointstringAPI path.

Returns: string — Endpoint with exactly one leading and one trailing slash (e.g. /api/articles/).


getNestedValue(obj, path)

ParameterTypeDescription
objunknownObject to read from.
pathstringDot-notation path (e.g. 'user.profile.name').

Returns: unknown — Value at the path, or undefined if any segment is missing.


setNestedValue(obj, path, value)

ParameterTypeDescription
objT extends Record<string, unknown>Object to copy from.
pathstringDot-notation path.
valueunknownValue to set.

Returns: T — New object with the value set at the given path (immutable).


setNestedValueMutating(obj, path, value)

ParameterTypeDescription
objRecord<string, unknown>Object to mutate directly.
pathstringDot-notation path.
valueunknownValue to set.

Returns: void — Mutates obj in-place, creating intermediate objects as needed. Prefer this for Vue reactive proxies.


isFile(value) / isBlob(value) / isFileOrBlob(value)

Type guards.

FunctionReturnsDescription
isFile(value: unknown)value is Filetrue if value is a File.
isBlob(value: unknown)value is Blobtrue if value is a Blob.
isFileOrBlob(value: unknown)value is File | Blobtrue if value is either.

findPropPaths(obj, predicate, _prefix?)

ParameterTypeDescription
objunknownObject to search recursively.
predicate(val: unknown) => booleanTest function.
_prefixstringInternal: dot-notation prefix for recursion.

Returns: string[] — All dot-notation paths where predicate(value) returns true.


filesInObject(obj)

ParameterTypeDescription
objunknownObject to search.

Returns: string[] — Dot-notation paths of all File or Blob values found anywhere in the object tree.


filterObj(obj, keys)

ParameterTypeDescription
objT extends Record<string, unknown>Source object.
keys(keyof T)[]Keys to keep.

Returns: Partial<T> — Shallow copy containing only the listed keys.


slotNamespace(slots, prefix)

ParameterTypeDescription
slotsSlotsVue slots object.
prefixstringPrefix to filter and strip (e.g. 'sidebar:').

Returns: Slots — New slots object containing only slots whose name starts with prefix, with the prefix removed.


buildRouteTree(routes)

ParameterTypeDescription
routesRouteRecordNormalized[]Vue Router normalized route records.

Returns: MenuNode[] — Tree of navigation nodes built from route meta fields (label, icon, parent, hidden, sidebarFooter).


calcMaxMenuNestDepth(nodes, depth?)

ParameterTypeDefaultDescription
nodesMenuNode[]Array of menu nodes to traverse.
depthnumber1Starting depth.

Returns: number — Maximum nesting depth in the tree (root level = 1).


JSON Schema Helpers — @mapomodule/utils/jsonSchema

resolveSchema(schema, defs, seen?, depth?)

ParameterTypeDefaultDescription
schemaJSONSchemaSchema node to resolve.
defsRecord<string, JSONSchema>Flat map of named definitions from the root schema.
seenWeakSet<JSONSchema>new WeakSet()Cycle detection set.
depthnumber0Recursion depth, capped at 32.

Returns: JSONSchema — Fully resolved schema with all $ref, anyOf, and oneOf pointers expanded and nullable patterns unwrapped.


extractDefs(schema)

ParameterTypeDescription
schemaJSONSchemaRoot schema document.

Returns: Record<string, JSONSchema> — All named sub-schemas from $defs or definitions.


getDefaultForSchema(schema)

ParameterTypeDescription
schemaJSONSchemaResolved schema node.

Returns: unknown — A sensible default value inferred from the schema type ({}, [], '', 0, false, null).


matchesSchema(value, schema)

ParameterTypeDescription
valueunknownData value to test.
schemaJSONSchemaSchema to validate against.

Returns: booleantrue if the value satisfies all schema constraints.


applyConditionals(schema, value, resolver?)

ParameterTypeDescription
schemaJSONSchemaBase schema with conditional keywords.
valueunknownCurrent form data used to evaluate if / then / else.
resolver(s: JSONSchema) => JSONSchemaOptional $ref resolver for conditional branches.

Returns: JSONSchema — Merged schema after applying all matching if/then/else, dependentSchemas, and dependentRequired branches. Iterates up to 8 times for cascading rules.


hasConditionals(schema)

ParameterTypeDescription
schemaJSONSchemaSchema to inspect.

Returns: booleantrue if the schema contains any conditional keywords (if, dependentSchemas, dependentRequired).


Form — @mapomodule/form

useMapoForm(options)

Core composable powering MapoForm. Provides dirty tracking, validation, and submit flows.

OptionTypeDefaultDescription
modelRef<T>requiredReactive form model.
fieldsMaybeRef<FieldDescriptor<T>[]>requiredField descriptors (static or reactive).
errorsRef<Record<string, string[]>>{}Server-side validation errors.
languagesstring[][]Available language codes.
currentLangRef<string>ref('')Active language ref.
immediatebooleanfalseValidate immediately on mount.
debouncenumber300Global validator debounce (ms).
registryFieldRegistryrequiredField component registry.

Returns:

MemberTypeDescription
isDirtyComputedRef<boolean>true when model differs from the last save baseline.
isLoadingRef<boolean>true while async validators are running.
readonlyRef<boolean>Controls read-only mode for all fields.
currentLangRef<string>Active language.
getFieldValue(key) => unknownGet a field's value by key or descriptor.
setFieldValue(key, val) => voidSet a field's value.
getClientError(key) => string | undefinedGet the first client-side error for a field.
markTouched(key) => voidMark a field as touched (triggers immediate validation).
isTouched(key) => booleanCheck if a field has been touched.
validateClient() => { valid: boolean, errors: Record<string, string> }Run all client validators synchronously.
resetDirty() => voidReset the dirty-tracking baseline (call after a successful save).
getPatch() => Partial<T>Return only changed fields since the last resetDirty.
submit(handler: (payload, isNew) => Promise<void>, isNew?: boolean) => Promise<void>Validate all fields, then call handler. On success calls resetDirty and clears touched state. No-op if already loading.

useFormFromSchema(schema, options?)

Generates a FieldDescriptor[] array from a JSON Schema document.

ParameterTypeDefaultDescription
schemaJSONSchemarequiredJSON Schema document (Pydantic v2, DRF Spectacular, or plain).
options.excludestring[][]Top-level keys to skip (e.g. ['id', 'created_at']).
options.overridesRecord<string, Partial<FieldDescriptor>>{}Per-field descriptor overrides applied after schema mapping.

Returns: FieldDescriptor[] — Ready to pass to MapoForm or MapoDetail.


useFormDraft(options)

Persists the form model to localStorage with debounce and TTL.

OptionTypeDefaultDescription
modelRef<T>requiredForm model to persist.
isDirtyRef<boolean>requiredDirty flag (draft is only saved when dirty).
keystringrequiredUnique storage key (prefixed as mapo:draft:<key>).
debouncenumber2000Write delay in milliseconds.
ttlnumber86400000Draft TTL in milliseconds (default 24 h).
onRestore(draft: T, savedAt: Date) => voidCallback fired on mount when a valid draft exists. savedAt is the timestamp of the last write.

Returns:

MemberSignatureDescription
clearDraft() => voidRemove draft from localStorage.
getDraft() => DraftEntry | nullGet the raw draft entry (includes savedAt timestamp).
hasDraft() => booleantrue if a non-expired draft exists.

useUnsavedChangesGuard(isDirty, options?)

Registers browser beforeunload and Vue Router beforeRouteLeave guards.

ParameterTypeDefaultDescription
isDirtyRef<boolean>requiredDirty flag from the form.
options.messagestring'You have unsaved changes.'Confirmation message shown to the user.
options.enabledRef<boolean> | () => boolean() => trueWhether the guard is active.

Returns: void — Guards are registered automatically and cleaned up on onBeforeUnmount.


useFocusMode()

Shared state for the MapoFocusPortal / MapoRepeater focus-mode integration.

Parameters: none.

Returns:

MemberTypeDescription
focusTargetDeepReadonly<ShallowRef<FocusTarget | null>>The currently focused repeater item, or null.
isActiveRef<boolean>true when focus mode is active.
enter(target: FocusTarget) => voidOpen focus mode on a specific item.
exit() => voidClose focus mode and restore the previous view.

Progressive Disclosure Helpers

Condition builders for the showWhen field descriptor option.

when(...conditions)

ParameterTypeDescription
conditionsCondition<TModel>[]Conditions to combine with AND.

Returns: Condition<TModel> — A new condition that is true when all inputs are true.


whenAny(...conditions)

ParameterTypeDescription
conditionsCondition<TModel>[]Conditions to combine with OR.

Returns: Condition<TModel> — A new condition that is true when at least one input is true.


whenNot(condition)

ParameterTypeDescription
conditionCondition<TModel>Condition to negate.

Returns: Condition<TModel> — A new condition that is true when the input is false.


matchesField(key, matcher)

ParameterTypeDescription
keystringDot-notation path to the model field.
matcherunknown | MatcherLiteral value for equality, or a matcher function (val) => boolean.

Returns: Condition<TModel> — A condition that is true when the field value satisfies the matcher.


Matcher Factories

FactorySignatureDescription
isOneOf(options: T[]) => Matchertrue if value is in the options array.
isNoneOf(options: T[]) => Matchertrue if value is NOT in the options array.
isNotEmpty() => Matchertrue if value is non-empty (non-null, non-"", non-[]).
isEmpty() => Matchertrue if value is empty.
greaterThan(n: number) => Matchertrue if numeric value > n.
lessThan(n: number) => Matchertrue if numeric value < n.
matches(pattern: RegExp) => Matchertrue if String(value) matches the regex.

defineFormField(type, entry, opts?)

Registers a custom field component in the global field registry. Must be called from a Nuxt plugin.

ParameterTypeDescription
typestringField type name (used as descriptor.type).
entryFieldComponentEntryAsync or sync function returning the Vue component.
opts.attrsRecord<string, unknown>Default descriptor.attrs values merged at render time.
opts.accessorFieldAccessorCustom { get(model, key), set(model, key, val) } accessor.
opts.overridebooleanAllow replacing an existing registration without a warning.

Returns: void.


provideCurrentLang(lang) / useCurrentLang(fallback?)

Language context helpers for nested field components.

FunctionParametersReturnsDescription
provideCurrentLanglang: Ref<string>voidProvide the active language to descendants.
useCurrentLangfallback?: Ref<string>Ref<string>Inject the current language, falling back to fallback or ref('').

Released under the MIT License.