Framework
Add a contribution to an existing screen by choosing a named spot and registering a widget for it. Decide whether it belongs in a tab, menu or detail section, and check its position and permissions in the page that will host it.
The widget injection system allows modules to:
onLoad, onBeforeSave, onSave, onAfterSave)Phase A and B add two foundational capabilities:
InjectionPosition) and headless widget loading (useInjectionDataWidgets) for non-visual extension payloads such as menu items.InjectionMenuItemWidget) rendered in app chrome without patching core navigation.Use these spot IDs in widgets/injection-table.ts:
menu:sidebar:mainmenu:sidebar:settingsmenu:sidebar:profilemenu:topbar:profile-dropdownmenu:topbar:actionsYou can also target scoped IDs such as menu:sidebar:settings:<sectionId>.
Use placement on each menu item:
import { InjectionPosition } from '@open-mercato/shared/modules/widgets/injection-position'
placement: { position: InjectionPosition.Before, relativeTo: 'sign-out' }
Supported positions:
FirstLastBefore (requires relativeTo)After (requires relativeTo)If relativeTo cannot be resolved, the item is appended.
A widget mapped to a detail:<module>.<entity>:tabs spot with placement.kind: 'tab' becomes a tab of that detail page:
groupId: stable tab id (falls back to the widget id); used in ?tab= URLsgroupLabel: translation key for the tab label (falls back to the widget title)icon: optional lucide icon name ('list-checks', 'ListChecks' or 'lucide:list-checks') shown next to the labelpriority: ordering hint, higher first, default 0. The host's built-in tabs sit at 0: a positive priority places the tab before them, a negative one after, and tabs sharing a priority keep their declaration order'detail:customers.person:tabs': [
{
widgetId: 'workflows.injection.pending-work',
kind: 'tab',
groupId: 'pending-work',
groupLabel: 'workflows.pendingWork.title',
icon: 'list-checks',
priority: -10,
},
],
Every user-facing injected menu item should include:
labelKey: translation keylabel: localized fallback textFor grouped sidebar/profile items:
groupLabelKey: translation key for group labelgroupLabel: optional fallback textExample:
const widget: InjectionMenuItemWidget = {
metadata: { id: 'example.injection.example-menus' },
menuItems: [
{
id: 'example-todos-shortcut',
labelKey: 'example.menu.todosShortcut',
label: 'Example Todos',
href: '/backend/todos',
icon: 'CheckSquare',
features: ['example.todos.view'],
groupId: 'example.nav.group',
groupLabelKey: 'example.nav.group',
placement: { position: InjectionPosition.Before, relativeTo: 'sign-out' },
},
{
id: 'example-quick-add-todo',
labelKey: 'example.menu.quickAddTodo',
label: 'Quick Add Todo',
href: '/backend/todos/create',
icon: 'PlusSquare',
features: ['example.todos.manage'],
placement: { position: InjectionPosition.Before, relativeTo: 'sign-out' },
},
],
}
Use separator: true to render visual separators for dropdown-style hosts. Combine with placement to insert separators before/after specific built-in items.
Phase C adds real-time server-to-client event delivery and richer widget lifecycle handlers.
Server-side events marked with clientBroadcast: true are automatically bridged to the browser via Server-Sent Events (SSE). The flow:
example.todo.created)/api/events/stream) server-filters audience and emits only matching events to each connectionuseEventBridge() hook (mounted in AppShell) receives the eventom:event CustomEvent on windowuseAppEvent hooks receive and reactAudience filtering is enforced server-side using event payload fields:
tenantId (required)organizationId or organizationIdsrecipientUserId or recipientUserIdsrecipientRoleId or recipientRoleIdsWhen any provided audience field does not match the connection (tenant, selected organization, authenticated user, role set), the event is dropped before delivery.
In your module's events.ts, add clientBroadcast: true:
export const eventsConfig = createModuleEvents('example', {
todo: {
created: { clientBroadcast: true },
updated: { clientBroadcast: true },
deleted: { clientBroadcast: true },
},
} as const)
import { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'
// Wildcard — matches example.todo.created, example.todo.updated, etc.
useAppEvent('example.todo.*', (event) => {
console.log('Todo event:', event.id, event.payload)
refreshData()
})
// Exact match
useAppEvent('example.todo.created', (event) => {
flash('New todo created!', 'info')
})
Widgets now support additional lifecycle handlers beyond the original save/delete/load events:
| Handler | Type | Description |
|---|---|---|
onFieldChange | Action | Fires when a form field changes. Can return a warning message. |
onBeforeNavigate | Action | Navigation guard – return { ok: false } to block. |
onVisibilityChange | Action | Fires when widget visibility changes. |
onAppEvent | Action | Fires when a matching SSE event arrives. |
transformFormData | Transformer | Pipeline: transform data before save. |
transformDisplayData | Transformer | Pipeline: transform data before display. |
transformValidation | Transformer | Pipeline: transform validation errors. |
Action handlers fire independently for each widget. Transformer handlers run as a pipeline – the output of widget N becomes the input of widget N+1.
const widget: InjectionWidgetModule = {
metadata: { id: 'example.injection.phase-c-actions', /* ... */ },
Widget: ActionWidget,
eventHandlers: {
onFieldChange: async (fieldId, value) => {
if (fieldId === 'title' && typeof value === 'string' && value.toUpperCase().includes('TEST')) {
return {
message: { text: 'Title contains "TEST" — is this intentional?', severity: 'warning' },
}
}
},
onBeforeNavigate: async (target) => {
if (target.includes('/blocked')) {
return { ok: false, message: 'Navigation blocked by widget policy' }
}
return { ok: true }
},
onVisibilityChange: async (visible, context) => {
context.sharedState?.set('lastVisibility', visible)
},
onAppEvent: async (event, context) => {
context.sharedState?.set('lastEventId', event.id)
},
},
}
const widget: InjectionWidgetModule = {
metadata: { id: 'example.injection.phase-c-transformers', /* ... */ },
Widget: TransformerWidget,
eventHandlers: {
transformFormData: async (data, context) => {
const trimmed = { ...data }
for (const [key, value] of Object.entries(trimmed)) {
if (typeof value === 'string') trimmed[key] = value.trim()
}
return trimmed
},
transformDisplayData: async (data) => {
return {
...data,
title: typeof data.title === 'string' ? data.title.toUpperCase() : data.title,
}
},
transformValidation: async (errors) => {
if (!errors.title) return errors
return { ...errors }
},
},
}
Use a small test harness page that mounts the widget and calls useInjectionSpotEvents(...) to trigger each handler deterministically.
Recommended Playwright coverage:
| Test ID | What to verify |
|---|---|
TC-UMES-E03 | onFieldChange updates warning state when title contains TEST. |
TC-UMES-E04 | transformFormData trims input (" x " → "x"). |
TC-UMES-E07 | onBeforeNavigate blocks /blocked and allows safe targets. |
TC-UMES-E08 | onVisibilityChange stores latest visibility state. |
TC-UMES-E09 | onAppEvent runs when om:event (example.todo.created) is dispatched. |
TC-UMES-E10 | transformDisplayData and transformValidation mutate output as expected. |
How to run:
npx playwright test --config .ai/qa/tests/playwright.config.ts apps/mercato/src/modules/example/__integration__/TC-UMES-003.spec.ts
CrudForm emits Phase C handlers by default.
Set this variable to disable automatic emission:
NEXT_PUBLIC_OM_CRUDFORM_EXTENDED_EVENTS_ENABLED=false
When enabled (true, default), CrudForm emits:
onFieldChange on field writes (setValue)onBeforeNavigate before guarded in-form navigation and CrudForm redirectsonVisibilityChange on browser visibilitychangeonAppEvent when om:event is receivedtransformFormData before save pipelinetransformDisplayData when initial form values are appliedtransformValidation before setting form field errorsThe example module ships demo injection widgets (CRUD validation panel, sales todos tab, catalog SEO report, sample menu items).
These widgets are registered unconditionally. NEXT_PUBLIC_OM_EXAMPLE_INJECTION_WIDGETS_ENABLED
used to gate them and no longer exists – the registry is now a plain static declaration so the
module fact extractor can read it (a conditional export folded to nothing, and every entry was
invisible to generated facts).
Registering an entry is not the same as rendering one: a cross-module entry is keyed on a spot id
that only its host module renders, so it stays inert when that module is absent. To gate a widget on
another module explicitly, declare metadata.requiredModules – injection-loader.ts enforces it.
Track long-running server operations in widgets:
import { useOperationProgress } from '@open-mercato/ui/backend/injection/useOperationProgress'
function ImportProgressWidget() {
const progress = useOperationProgress('catalog.import.*')
if (progress.status === 'idle') return null
return <ProgressBar value={progress.progress} label={progress.currentStep} />
}
Phase D adds a federation-like data enrichment system. Modules can inject computed fields into other modules' API responses without modifying core code.
data/enrichers.tsafterList hook, before HTTP response_<moduleName> namespace_meta.enrichedBy tracking which enrichers ranCreate src/modules/<module>/data/enrichers.ts:
import type { ResponseEnricher } from '@open-mercato/shared/lib/crud/response-enricher'
const customerTodoCount: ResponseEnricher = {
id: 'example.customer-todo-count',
targetEntity: 'customers.person', // which entity to enrich
features: ['example.view'], // ACL gating
priority: 10, // higher = runs first
timeout: 2000, // max ms per enricher
fallback: { _example: { todoCount: 0 } }, // used on timeout/error
async enrichOne(record, context) {
const em = context.em.fork()
const count = await em.count(Todo, { organizationId: context.organizationId })
return { ...record, _example: { todoCount: count } }
},
// MUST implement for list endpoints (prevents N+1 queries)
async enrichMany(records, context) {
const em = context.em.fork()
const todos = await em.find(Todo, { organizationId: context.organizationId })
return records.map(r => ({ ...r, _example: { todoCount: todos.length } }))
},
}
export const enrichers: ResponseEnricher[] = [customerTodoCount]
Add enrichers to your makeCrudRoute call:
export const { metadata, GET, POST, PUT, DELETE } = makeCrudRoute({
// ... other config
enrichers: { entityId: 'customers.person' },
})
{
"items": [
{
"id": "abc-123",
"firstName": "John",
"_example": { "todoCount": 5, "openTodoCount": 3 }
}
],
"_meta": {
"enrichedBy": ["example.customer-todo-count"]
}
}
_<moduleName> (e.g., _example.todoCount)enrichMany() is mandatory for list endpoints (batch queries prevent N+1)fallback); set critical: true to propagate errors_)cacheableOnListHit at its false default unless the enriched output is record-pure – see belowcacheableOnListHit)When the opt-in CRUD list cache (ENABLE_CRUD_API_CACHE) is on, the factory stores the enriched list payload and partitions cache entries by the set of enrichers active for the caller (after ACL + tenant filtering). What happens on a cache hit depends on whether the active enrichers are cacheable:
cacheableOnListHit: true, the hit serves the stored enriched fields directly without re-running enrichers – this is the fast path that makes list caching actually eliminate enrichment cost.const customerStatusBadge: ResponseEnricher = {
id: 'example.customer-status-badge',
targetEntity: 'customers.person',
cacheableOnListHit: true, // pure function of the record's own cached fields → safe on a hit
// ...
}
The shipped example.customer-todo-count enricher, by contrast, reads other modules' tables, so it keeps the false default and re-runs on every hit.
Set cacheableOnListHit: true only when the enricher's output for a record is a pure function of that record's own cached state and is invalidated together with it. Leave it false (the fail-closed default) for any enricher whose output depends on data the list cache does not invalidate on:
Opting in on such an enricher would serve stale values from the shared cache entry on a hit.
src/modules/<module>/
├── data/
│ └── enrichers.ts # Response enrichers (auto-discovered)
├── widgets/
│ ├── injection/
│ │ └── <widget-name>/
│ │ ├── widget.ts # Widget definition & event handlers
│ │ └── widget.client.tsx # React component (client-side)
│ └── injection-table.ts # Spot ID → Widget ID mappings
crud-form:<entityId> (automatically derived from entityId/entityIds passed to CrudForm). Widgets can request placement.kind: 'group' to render as a side-card and column: 2 to appear in the right column. Field injection spot: crud-form:<entityId>:fields.data-table:<tableId> (or pass injectionSpotId to DataTable). Header/footer child spots: :header, :footer. Deep extension spots: :columns, :row-actions, :bulk-actions, :filters, :toolbar, :search-trailing.
:toolbar renders inside the right-side actions row alongside Refresh / Filters / Columns / Export. Suitable for full-sized toolbar buttons.:search-trailing renders inside the FilterBar, immediately to the right of the search input on the same row. Reserve it for compact triggers – AI assistants, saved-view shortcuts, focus toggles. Full-width or multi-action toolbars belong in :toolbar or :header. The slot is automatically suppressed when the host DataTable does not render a search input. Use Button variant="outline" (default size, h-9, rounded-md) with a single leading icon plus a short caption (e.g. AI) so the trigger matches the search input's h-9 row height and the toolbar's standard rounded-rectangle button radius. Resolve the spot id with DataTableInjectionSpots.searchTrailing(tableId) from @open-mercato/ui/backend/injection/spotIds.backend:record:current (mounted once per backend page with { path, query } context).backend:layout:top, backend:layout:footer (top and bottom of the main backend content area).backend:sidebar:top, backend:sidebar:footer (desktop sidebar top/bottom areas in AppShell).Component replacement uses stable handle IDs:
page:<path> for backend page-level replacement (for example page:/backend/customers/people)data-table:<tableId> for each DataTable instancecrud-form:<entityId> for each CrudForm instancesection:<scope>.<sectionName> for detail sections (for example section:ui.detail.NotesSection)widgets/components.ts (componentOverrides) and generated to .mercato/generated/component-overrides.generated.ts.section:ui.detail.NotesSectionsection:ui.detail.ActivitiesSectionsection:ui.detail.AddressesSectionsection:ui.detail.TagsSectionsection:ui.detail.CustomDataSectionsection:ui.detail.DetailFieldsSectionsection:ui.detail.AttachmentsSectionadmin.page:<path-handle>:before|after from PageInjectionBoundary (wraps every backend page).GLOBAL_MUTATION_INJECTION_SPOT_ID resolves to backend:record:current for non-CrudForm save hooks. backend-mutation:global is still mounted in AppShell as a legacy compatibility slot.wrapper overrides must be pureThe platform composes a wrapper override at most once per (wrapper, wrapped component) pair and caches the composed component, so that a wrapped subtree keeps a stable React identity instead of being torn down and remounted every time overrides re-resolve (a registry revision bump, a feature grant arriving after first paint).
A wrapper must therefore be a pure function of Original. Read any dynamic value – a feature flag, the locale, tenant configuration, the clock, request state – inside the render body of the component you return, never at composition time:
// ✅ the dynamic read happens on every render
wrapper: (Original) => function WithBanner(props) {
const t = useT()
return <><Banner text={t('acme.notice')} /><Original {...props} /></>
}
// ❌ frozen at first composition — on the server the registry outlives the
// request, so one tenant's value would render for everyone
wrapper: (Original) => {
const label = readTenantConfig().label
return (props) => <><Banner text={label} /><Original {...props} /></>
}
Phase L adds three specialized widget types for building integration modules: a multi-step wizard, pollable status badges, and an external ID mapping display.
A multi-step wizard component for integration onboarding flows (OAuth setup, API credential entry, sync configuration).
Each step is an InjectionWizardStep with:
id – unique step identifierlabel – displayed in the step indicator (supports i18n keys)description – optional subtitle textfields – optional array of InjectedField definitions (text, select, etc.)validate – optional async function returning { ok, message?, fieldErrors? }customComponent – optional React component for fully custom step contentimport { InjectionWizard } from '@open-mercato/ui/backend/injection/InjectionWizard'
import type { InjectionWizardWidget, InjectionContext } from '@open-mercato/shared/modules/widgets/injection'
const widget: InjectionWizardWidget = {
metadata: { id: 'my_module.integration.setup-wizard', title: 'Integration Setup' },
kind: 'wizard',
steps: [
{
id: 'credentials',
label: 'Credentials',
fields: [
{ id: 'apiKey', label: 'API Key', type: 'text' },
{ id: 'apiSecret', label: 'API Secret', type: 'text' },
],
validate: async (data) => {
if (!data.apiKey || !data.apiSecret) {
return { ok: false, message: 'Both fields are required.' }
}
return { ok: true }
},
},
{ id: 'scope', label: 'Scope', fields: [/* ... */] },
],
onComplete: async (allData, context) => {
// Save integration config
},
}
<InjectionWizard widget={widget} context={context} />
The wizard renders a numbered step indicator with connecting lines, validates each step before allowing progression, and calls onComplete with accumulated data from all steps. Escape cancels the wizard.
A pollable status badge for displaying integration or service health.
An InjectionStatusBadgeWidget contains a badge object with:
label – display text (supports i18n)statusLoader – async function returning { status, tooltip?, count? }pollInterval – refresh interval in seconds (default: 60)href – optional link targetStatus values and their colors:
| Status | Color |
|---|---|
healthy | Green |
warning | Yellow |
error | Red |
unknown | Gray |
import { StatusBadgeRenderer } from '@open-mercato/ui/backend/injection/StatusBadgeRenderer'
import type { InjectionStatusBadgeWidget, StatusBadgeContext } from '@open-mercato/shared/modules/widgets/injection'
const widget: InjectionStatusBadgeWidget = {
metadata: { id: 'my_module.integration.sync-status' },
kind: 'status-badge',
badge: {
label: 'Sync Engine',
pollInterval: 30,
statusLoader: async (ctx) => {
const res = await fetch('/api/integrations/health')
const data = await res.json()
return { status: data.healthy ? 'healthy' : 'error', tooltip: data.message }
},
},
}
<StatusBadgeRenderer widget={widget} context={context} />
Displays external system ID mappings from the _integrations namespace added by the external ID mapping enricher (see Data extensibility).
Each row shows:
getIntegrationTitle() from the integration registrysynced/pending/error/not_synced)buildExternalUrl is registered)The widget reads data._integrations (keyed by integration ID) and renders automatically when enriched data is available. It is registered as an injection widget at integrations.injection.external-ids.
Widget source: packages/core/src/modules/integrations/widgets/injection/external-ids/widget.client.tsx
Create src/modules/<module>/widgets/injection/<widget-name>/widget.ts:
import type { InjectionWidgetModule } from '@open-mercato/shared/modules/widgets/injection'
import MyWidgetClient from './widget.client'
const widget: InjectionWidgetModule<ContextType, DataType> = {
metadata: {
id: 'module.injection.widget-name',
title: 'Widget Title',
description: 'Widget description',
features: ['module.feature'],
priority: 100,
enabled: true,
},
Widget: MyWidgetClient,
eventHandlers: {
onLoad: async (context) => {
// Called when widget loads
console.log('Widget loaded', context)
},
onBeforeSave: async (data, context) => {
// Called before save action
// Return false to prevent save, or provide a message/field errors
if (!isValid(data)) {
return {
ok: false,
message: 'Title is required before saving',
fieldErrors: { title: 'Title is required' },
}
}
return { ok: true }
},
onSave: async (data, context) => {
// Called during save action
console.log('Saving', data)
},
onAfterSave: async (data, context) => {
// Called after successful save
console.log('Saved', data)
},
},
}
export default widget
Create src/modules/<module>/widgets/injection/<widget-name>/widget.client.tsx:
"use client"
import * as React from 'react'
import type { InjectionWidgetComponentProps } from '@open-mercato/shared/modules/widgets/injection'
export default function MyWidget({ context, data, onDataChange, disabled }: InjectionWidgetComponentProps) {
return (
<div className="rounded border border-blue-200 bg-blue-50 p-3 text-sm">
<div className="font-medium text-blue-900">My Widget</div>
<div className="text-blue-700 mt-1">
Custom content here. Context: {JSON.stringify(context)}
</div>
{disabled && <div className="text-xs text-gray-500 mt-1">Saving...</div>}
</div>
)
}
Create or edit src/modules/<module>/widgets/injection-table.ts:
import type { ModuleInjectionTable } from '@open-mercato/shared/modules/widgets/injection'
export const injectionTable: ModuleInjectionTable = {
// Map injection spot IDs to widget IDs
'crud-form:catalog.product': 'module.injection.widget-name',
// Can also inject multiple widgets
'crud-form:catalog.variant': [
'module.injection.widget-name',
'module.injection.another-widget',
],
}
export default injectionTable
On a kind: 'tab' spot, priority orders the contributed tab against the host's
built-in tabs, not just against other contributed tabs. Built-in tabs sit at 0:
priority
leaves a contributed tab where it has always been – lastexport const injectionTable: ModuleInjectionTable = {
'detail:customers.company:tabs': [
{
widgetId: 'my_module.injection.overview-tab',
priority: 100,
kind: 'tab',
groupId: 'overview',
groupLabel: 'my_module.tabs.overview',
},
],
}
Ordering a tab first does not make it the tab the page opens on – hosts keep their
own default. Link to ?tab=<groupId> to land a user on a contributed tab.
Hosts honouring this: company, person and deal detail pages in customers.
The CrudForm component automatically supports widget injection:
<CrudForm
fields={fields}
onSubmit={handleSubmit}
injectionSpotId="crud-form:catalog.product"
// ... other props
/>
Use the helper functions to generate consistent spot IDs:
import { generateCrudFormInjectionSpotId, CrudFormInjectionSpots } from '@open-mercato/ui/backend/injection/helpers'
// Basic form spot
const spotId = generateCrudFormInjectionSpotId('catalog.product')
// Result: 'crud-form:catalog.product'
// Specific locations
const beforeFieldsSpot = CrudFormInjectionSpots.beforeFields('catalog.product')
// Result: 'crud-form:catalog.product:before-fields'
const afterFieldsSpot = CrudFormInjectionSpots.afterFields('catalog.product')
// Result: 'crud-form:catalog.product:after-fields'
Called when the widget is first mounted.
Signature:
onLoad?: (context: TContext) => void | Promise<void>
Use Cases:
Called before a save action is executed. Can prevent the save by returning false or throwing an error.
Signature:
onBeforeSave?: (data: TData, context: TContext) => boolean | { ok?: boolean; message?: string; fieldErrors?: Record<string, string> } | void | Promise<boolean | { ok?: boolean; message?: string; fieldErrors?: Record<string, string> } | void>
Use Cases:
Example:
onBeforeSave: async (data, context) => {
if (!data.title || data.title.length < 10) {
alert('Title must be at least 10 characters')
return false // Prevent save
}
return true // Allow save
}
Called when save action is triggered (alongside the main save operation).
Signature:
onSave?: (data: TData, context: TContext) => void | Promise<void>
Use Cases:
Called after save completes successfully.
Signature:
onAfterSave?: (data: TData, context: TContext) => void | Promise<void>
Use Cases:
For custom components that need to trigger injection widget events:
import { useInjectionSpotEvents } from '@open-mercato/ui/backend/injection/InjectionSpot'
function MyCustomForm() {
const { triggerEvent } = useInjectionSpotEvents('crud-form:my.form')
const handleSave = async (data) => {
// Trigger onBeforeSave
const canProceed = await triggerEvent('onBeforeSave', data, context)
if (!canProceed) {
return // Blocked by widget
}
// Trigger onSave
await triggerEvent('onSave', data, context)
// Perform save
await saveData(data)
// Trigger onAfterSave
await triggerEvent('onAfterSave', data, context)
}
return <form onSubmit={handleSave}>...</form>
}
For backend pages that do not use CrudForm (for example custom detail screens), use the global mutation spot and emit the generic mutation error event.
import { useInjectionSpotEvents } from '@open-mercato/ui/backend/injection/InjectionSpot'
import {
GLOBAL_MUTATION_INJECTION_SPOT_ID,
dispatchBackendMutationError,
} from '@open-mercato/ui/backend/injection/mutationEvents'
import { withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'
const { triggerEvent } = useInjectionSpotEvents(GLOBAL_MUTATION_INJECTION_SPOT_ID)
async function runMutation(operation: () => Promise<unknown>, payload: Record<string, unknown>, context: Record<string, unknown>) {
const beforeSave = await triggerEvent('onBeforeSave', payload, context)
if (!beforeSave.ok) {
dispatchBackendMutationError({ contextId: context.formId as string, error: beforeSave.details ?? beforeSave })
throw new Error(beforeSave.message ?? 'Save blocked by validation')
}
try {
const result =
beforeSave.requestHeaders && Object.keys(beforeSave.requestHeaders).length > 0
? await withScopedApiRequestHeaders(beforeSave.requestHeaders, operation)
: await operation()
await triggerEvent('onAfterSave', payload, context)
return result
} catch (error) {
dispatchBackendMutationError({ contextId: context.formId as string, error })
throw error
}
}
This keeps API helpers generic while still enabling module-level behaviors such as conflict dialogs, validation, or save guards.
import { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'
function MyPage() {
const context = { pageId: 'my-page', userId: currentUser.id }
const [data, setData] = useState({})
return (
<div>
<InjectionSpot
spotId="page:my-page:header"
context={context}
data={data}
onDataChange={setData}
/>
{/* Rest of page */}
</div>
)
}
Here’s how injected widgets look in the admin UI:



See these modules for reference implementations:
packages/example/src/modules/example/widgets/injection/crud-validation - Basic validation widgetpackages/core/src/modules/catalog/widgets/injection/product-seo - SEO helper widget for productsThe widget injection system is integrated into the module code generator:
src/modules/<module>/widgets/injection/**/widget.ts(x) are auto-discoveredsrc/modules/<module>/widgets/injection-table.ts are auto-loadedgenerated/injection-widgets.generated.tsyarn generate to regeneratemodule.injection.widget-namedisabled prop is trueyarn generate to regenerateuseInjectionSpotEvents or InjectionSpot@open-mercato/shared/modules/widgets/injectionInjectionWidgetModule