@marktiderman/genesis-core
2.22.0Foundation · CoreessentialPlatform-agnostic providers, hooks, and data layer. Use anywhere — web, native, Node.
Genesis's platform-agnostic data layer: the `DataProvider` contract, providers (`createSupabaseProvider`, `createMockProvider`), the React roots that put a provider in context, and the hooks that read and write through it (`useResource`, `useOne`, `useResourceForm`).
`GenesisProvider` without `queryClient` starts a second cache, so invalidating a key in app code doesn't refresh Genesis lists and vice versa. In an app that has a `QueryClientProvider`, do this:
pnpm add @marktiderman/genesis-coreComponents (5)
- AppearancePreferencesProviderBeta
Serves a person's appearance and density to the tree, resolved in the written order. Reads the store once on mount (and on its `subscribe`), keeps a copy on the device, and writes both when the person changes a value.
- DataProviderRoot
- GenesisProvider
Convenience root: a `QueryClientProvider`, storage, and a data provider (yours, or a mock built from datasets). It creates its own `QueryClient` unless you pass `queryClient`; an app that already has one should pass it, or mount `DataPro...
- ViewerScope
Keeps one viewer's cached data from ever showing to the next. Children render only once the viewer is known, under a key of that viewer, so a sign-out or a new person signing in unmounts every screen and its queries before the cache is e...
- WorkspaceScopeBeta
`ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and `timeZone`), so every view with `scope: ["...
Hooks (28)
- useAggregate
Totals over a resource's rows (count, and sum, average, lowest or highest of a field), through the data provider: its `aggregate`, or `resolveAggregate`'s fallback. Cached under the resource's key, so any write to the resource through Ge...
- useAppearancePreferences
The person's appearance and density, resolved, with setters. Throws outside an `AppearancePreferencesProvider`; a component that works with or without one reads `useOptionalAppearancePreferences`.
- useBoardColumns
Load a board: one request per column page, each with the shared filters, sort and search plus the column's value. Columns page on their own (`loadMore`), and the pages a column has loaded reset when the filters, sort or search change.
- useCapabilities
What the data provider can do for `resource` (`provider.capabilities`), cached per provider and resource. `data` stays undefined for a provider that doesn't report capabilities, so a UI keeps its defaults.
- useDataProvider
- useDraft
Autosave one draft row: saved a moment after each change, one write at a time, added on the first save that has something in it, merged into a row another tab started (`adopt`), and started again when the server's copy wins (`revision`)....
- useInfiniteResource
- useLinkOptions
The rows a link can point at, for a picker: listed through the data provider with `filters`, searched on the server with `search` across `searchFields` (else the naming field), sorted by `orderBy` (else the naming field) then the key, `p...
- useListState
A list's state, held for one list (ADR 0017): from the URL when it has one, and the person's store. The URL follows each change (replacing the entry: a filter isn't a page) and the state follows the URL back (Back, Forward, a link to the...
- useLiveInvalidation
Subscribes while mounted and `enabled`, and invalidates `queryKey` (a prefix) once per burst of events that `accept` lets through. While the page is hidden the queries are only marked stale; they refetch when it is shown again (TanStack ...
- useOne
Fetch a single record by id, powered by TanStack Query.
- useOptionalAppearancePreferences
Like `useAppearancePreferences`, but null outside a provider: for a component (a shell, a theme provider) that keeps its own behaviour when an app hasn't set preferences up.
- useOptionalDataProvider
The data provider when there is one, else null: for a screen that also works over rows it was given (a `ResourceView` with `rows`), where nothing is read or run through a provider.
- useOptionalViewerScope
Like useViewerScope, or null outside a ViewerScope.
- usePersistedUiState
- useRelationLabel
A linked row's words for a `relation` cell: `undefined` while they load, `null` when there are none (the row is hidden from this viewer, gone, unnamed, or the read failed), so a screen shows its own words then, never the raw id. Cached p...
- useResource
- useResourceForm
- useSegmentCounts
Each segment's row count for a view's list (ADR 0017), for the segments that ask for one (`count: true`): the list's other filters (scope, the screen's, the declared filters) plus the segment's own, counted through the provider (estimate...
- useStorage
- useUnsavedChangesGuard
Warns before unsaved changes are lost, without depending on a router.
- useViewBoard
A view's rows as board columns, with moves:
- useViewCalendarRange
A view's rows in one calendar window, for a screen that places them itself (a custom view, ADR 0019). ResourceCalendar loads its rows through it.
- useViewer
The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can sit in a memo's dependencies.
- useViewerScope
The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it.
- useWizard
- useWorkspace
The nearest `WorkspaceScope`'s workspaces, or null outside one.
- useWrite
A one-off write that isn't a resource page's create, update or remove: a database function, `createOrAdopt`, several writes in a row. It invalidates what it made stale and reports failures in plain words.
Other exports (73)
aggregateProblems · APPEARANCES · blankValues · BOARD_NONE · BOARD_PAGE · boardColumnFilter · buildArrayItemDefaults · CALENDAR_LIMIT · callRpc · classifyError · clearViewerCache · createLocalStorageAdapter · createMemoryStorageAdapter · createMockProvider · createNoopStorageAdapter · createOrAdopt · createSupabaseProvider · DataReadError · DataWriteError · decodeRecordKey · DEFAULT_DRAFT_DELAY_MS · DEFAULT_LIVE_DEBOUNCE_MS · DEFAULT_LIVE_RESYNC_MS · DEFAULT_RPC_MESSAGES · DEFAULT_UNDO_DELAY_MS · DEFAULT_UNSAVED_CHANGES_MESSAGE · defaultErrorReporter · defineAppearancePreferences · defineQueryKeys · defineResource · DENSITIES · DRAFT_NOT_SAVED · DraftController · dropPendingWrites · encodeRecordKey · errorMessages · fieldControl · fieldErrorsFromPostgrest · flushPendingWrites · GENESIS_APPEARANCE_DEFAULTS · getErrorReporter · isAppearance · isDataReadError · isDataWriteError · isDensity · isNetworkFailure · isSafeUrl · keyFields · loadRelationLabel · NO_ROWS_MATCHED · NO_VIEWER · normalizeLinkUrl · pendingWriteCount · readFailureMessage · readOutcomeFromCode · relationNamingField · rememberedWorkspaceId · reportError · requireDataProvider · resolveAggregate · resolveAppearancePreferences · resourceKeys · RPC_FAILED · scopeClock · setErrorReporter · stableJson · titleCase · toAggregateValues · toAppearancePreferenceValues · toDataWriteError · WRITE_FAILED · writeConflict · writeOutcomeFromCode
And 159 types.
Components (2)
- DataProviderRoot
- GenesisProvider
Convenience root: a `QueryClientProvider`, storage, and a data provider (yours, or a mock built from datasets). It creates its own `QueryClient` unless you pass `queryClient`; an app that already has one should pass it, or mount `DataPro...
Hooks (3)
- useDataProvider
- useOptionalDataProvider
The data provider when there is one, else null: for a screen that also works over rows it was given (a `ResourceView` with `rows`), where nothing is read or run through a provider.
- useStorage
Other exports (20)
aggregateProblems · callRpc · createMockProvider · createOrAdopt · createSupabaseProvider · DataReadError · DataWriteError · DEFAULT_RPC_MESSAGES · fieldErrorsFromPostgrest · isDataReadError · isDataWriteError · NO_ROWS_MATCHED · readFailureMessage · readOutcomeFromCode · requireDataProvider · resolveAggregate · RPC_FAILED · toAggregateValues · toDataWriteError · writeOutcomeFromCode
And 59 types.
Components (2)
- ViewerScope
Keeps one viewer's cached data from ever showing to the next. Children render only once the viewer is known, under a key of that viewer, so a sign-out or a new person signing in unmounts every screen and its queries before the cache is e...
- WorkspaceScopeBeta
`ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and `timeZone`), so every view with `scope: ["...
Hooks (23)
- useAggregate
Totals over a resource's rows (count, and sum, average, lowest or highest of a field), through the data provider: its `aggregate`, or `resolveAggregate`'s fallback. Cached under the resource's key, so any write to the resource through Ge...
- useBoardColumns
Load a board: one request per column page, each with the shared filters, sort and search plus the column's value. Columns page on their own (`loadMore`), and the pages a column has loaded reset when the filters, sort or search change.
- useCapabilities
What the data provider can do for `resource` (`provider.capabilities`), cached per provider and resource. `data` stays undefined for a provider that doesn't report capabilities, so a UI keeps its defaults.
- useDraft
Autosave one draft row: saved a moment after each change, one write at a time, added on the first save that has something in it, merged into a row another tab started (`adopt`), and started again when the server's copy wins (`revision`)....
- useInfiniteResource
- useLinkOptions
The rows a link can point at, for a picker: listed through the data provider with `filters`, searched on the server with `search` across `searchFields` (else the naming field), sorted by `orderBy` (else the naming field) then the key, `p...
- useListState
A list's state, held for one list (ADR 0017): from the URL when it has one, and the person's store. The URL follows each change (replacing the entry: a filter isn't a page) and the state follows the URL back (Back, Forward, a link to the...
- useLiveInvalidation
Subscribes while mounted and `enabled`, and invalidates `queryKey` (a prefix) once per burst of events that `accept` lets through. While the page is hidden the queries are only marked stale; they refetch when it is shown again (TanStack ...
- useOne
Fetch a single record by id, powered by TanStack Query.
- useOptionalViewerScope
Like useViewerScope, or null outside a ViewerScope.
- usePersistedUiState
- useRelationLabel
A linked row's words for a `relation` cell: `undefined` while they load, `null` when there are none (the row is hidden from this viewer, gone, unnamed, or the read failed), so a screen shows its own words then, never the raw id. Cached p...
- useResource
- useResourceForm
- useSegmentCounts
Each segment's row count for a view's list (ADR 0017), for the segments that ask for one (`count: true`): the list's other filters (scope, the screen's, the declared filters) plus the segment's own, counted through the provider (estimate...
- useUnsavedChangesGuard
Warns before unsaved changes are lost, without depending on a router.
- useViewBoard
A view's rows as board columns, with moves:
- useViewCalendarRange
A view's rows in one calendar window, for a screen that places them itself (a custom view, ADR 0019). ResourceCalendar loads its rows through it.
- useViewer
The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can sit in a memo's dependencies.
- useViewerScope
The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it.
- useWizard
- useWorkspace
The nearest `WorkspaceScope`'s workspaces, or null outside one.
- useWrite
A one-off write that isn't a resource page's create, update or remove: a database function, `createOrAdopt`, several writes in a row. It invalidates what it made stale and reports failures in plain words.
Other exports (25)
blankValues · BOARD_NONE · BOARD_PAGE · boardColumnFilter · buildArrayItemDefaults · CALENDAR_LIMIT · clearViewerCache · DEFAULT_DRAFT_DELAY_MS · DEFAULT_LIVE_DEBOUNCE_MS · DEFAULT_LIVE_RESYNC_MS · DEFAULT_UNDO_DELAY_MS · DEFAULT_UNSAVED_CHANGES_MESSAGE · DRAFT_NOT_SAVED · DraftController · dropPendingWrites · flushPendingWrites · isNetworkFailure · loadRelationLabel · NO_VIEWER · pendingWriteCount · relationNamingField · rememberedWorkspaceId · scopeClock · stableJson · WRITE_FAILED
And 53 types.
Other exports (3)
createLocalStorageAdapter · createMemoryStorageAdapter · createNoopStorageAdapter
And 1 types.
Other exports (12)
DataReadError · DataWriteError · decodeRecordKey · defineResource · encodeRecordKey · fieldControl · isDataReadError · isDataWriteError · keyFields · NO_ROWS_MATCHED · readFailureMessage · writeConflict
And 26 types.
Other exports (4)
cacheScope · indexedDbLocalCache · memoryLocalCache · persistOffline
And 9 types.
Other exports (1)
renderSlot
And 3 types.
Other exports (5)
isPathActive · resolveNavigation · resolveNavigationZones · splitTabBarItems · TAB_BAR_MAX
And 6 types.
Other exports (16)
DEFAULT_WORKSPACE_KIND_LABELS · defaultWorkspace · filterWorkspaces · groupWorkspaces · hasWorkspaceBadge · keepSection · orderedWorkspaces · pathInWorkspace · resolveWorkspaceAppearance · resolveWorkspaceBrand · WORKSPACE_KIND_ORDER · WORKSPACE_SWITCHER_SEARCH_THRESHOLD · workspaceAt · workspaceBadgeLabel · workspaceHref · workspaceInitials
And 6 types.
Other exports (14)
accessRules · ContractError · declaredFunctions · expectAccessRulesCover · expectAllowed · expectBinned · expectNeverShows · expectPlainMessage · expectRefused · expectSees · expectServerOwned · FIXTURE_USERS · fixtureAccessToken · isRefusal
And 6 types.
Other exports (29)
addDays · addMonths · addWeeks · dayIn · dayRangeIn · daysBetween · daysInMonth · deviceTimeZone · eachDay · expandRecurrence · instantIn · isDay · isTimeZone · monthGridRange · monthRange · parseRRule · personDay · personTimeZone · quarterRange · rangeIn · readEventTime · startOfDayIn · startOfMonth · startOfQuarter · startOfWeek · wallClock · wallTimeIn · weekdayOf · weeksRange
And 12 types.
Other exports (6)
dayLabel · embedSnippet · prefilledUrl · readinessChip · readinessOf · SAVE_STATE_LABEL
And 9 types.
Other exports (4)
DEFAULT_GALLERY_RATIO · GALLERY_DEFAULTS · galleryItemRatio · justifyRows
And 4 types.
Other exports (61)
applicableListState · boardChoices · boardProblems · calendarEvents · calendarLanes · calendarProblems · calendarWindow · cascadeSelection · createLocalSavedViewStore · decodeFilterValue · defineRecordView · defineView · defineWidget · defineWorkspace · deriveDisplay · displayZone · encodeFilterValue · eventDays · eventDots · filterOptionLabel · filterParams · filterValueFor · galleryProblems · groupRows · groupTotals · inboxProblems · initialExpanded · initialsOf · isFilterSet · isRecordView · isWidget · isWorkspace · laneKeys · LIST_URL_KEYS · listUrlParams · NO_VIEWER · placeEvents · plural · readListUrl · RECORD_OPEN_MODES · resolveChartSeries · resolveProgress · resolveStreak · resolveWidgetAccess · resolveWidgetRequest · rowPicture · sameFormValue · scopeFilter · scopeValues · setExpanded · shiftAnchor · singular · timeStorage · toWidgetText · treeRows · valueText · ViewDefinitionError · warnOnce · whereParams · widgetProblems · windowBounds
And 108 types.
Hooks (1)
- useThreadJump
Other exports (6)
DEFAULT_THREAD_LABELS · formatInboxTime · formatMessageTime · isDelivered · JUMP_SETTLE_MS · readReceiptFor
And 11 types.
Other exports (6)
ROW_ACTION_ACCENTS · ROW_ACTION_TONES · rowActionLabel · rowActionPlaced · rowActionSwipe · rowActionTone
And 5 types.
Other exports (2)
isSafeUrl · normalizeLinkUrl
Other exports (4)
csvField · exportCsv · parseCsv · toCsv
And 2 types.
Other exports (54)
canStepNumber · carouselIndex · carouselOffset · chartDomain · chartPosition · chartSeriesColor · chartSummary · chartTokenOf · clampNumber · clampRange · commitNumberDraft · customViewStatus · dateOfDay · dayInRange · dayOfDate · DEFAULT_MAX_FILE_SIZE · defaultChartToken · dropIndex · fieldAccept · fieldArrayAddLabel · fieldArrayLimits · fileProblem · filterOptions · formatFileSize · formatTimeOfDay · formatTrend · groupNotificationsByDay · matchesQuery · monthWeeks · movedAnnouncement · moveItem · NOTIFICATION_DAY_BUCKETS · notificationDayBucket · OTP_PATTERN_DIGITS · otpComplete · otpSlots · parseNumberInput · parseTimeOfDay · pickRangeDay · readNumberDraft · sanitizeOtp · snapToStep · STATUS_BADGE_TONES · statusBadgeLabel · stepNumber · stepState · stripOtpSeparators · timeOfDate · timeSlots · timeToValue · weekdayDays · withTimeOfDay · wizardProgressLabel · wizardStepFields
And 14 types.
Other exports (7)
classifyError · defaultErrorReporter · errorMessages · getErrorReporter · isDevelopment · reportError · setErrorReporter
And 6 types.