@rise-x/apps-sdk 0.16.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/API.md +141 -0
  2. package/README.md +299 -10
  3. package/build/accessors.d.ts +2 -1
  4. package/build/accessors.js +10 -0
  5. package/build/breadcrumb.d.ts +49 -0
  6. package/build/breadcrumb.js +58 -0
  7. package/build/connectors/types.d.ts +8 -0
  8. package/build/connectors/types.js +36 -4
  9. package/build/connectors/work.js +30 -1
  10. package/build/index.d.ts +3 -1
  11. package/build/index.js +7 -1
  12. package/build/live/index.d.ts +43 -0
  13. package/build/live/index.js +183 -0
  14. package/build/liveChannel.d.ts +32 -0
  15. package/build/liveChannel.js +60 -0
  16. package/build/mockShell.d.ts +2 -0
  17. package/build/mockShell.js +1 -0
  18. package/build/query/index.d.ts +1 -0
  19. package/build/query/index.js +4 -2
  20. package/build/query/live.d.ts +14 -0
  21. package/build/query/live.js +115 -0
  22. package/build/shell/index.d.ts +2 -1
  23. package/build/shell/installShellBridge.d.ts +15 -1
  24. package/build/shell/installShellBridge.js +7 -1
  25. package/build/shell/liveHub.d.ts +25 -0
  26. package/build/shell/liveHub.js +201 -0
  27. package/build/shellBridge.d.ts +116 -1
  28. package/build/shellBridge.js +5 -1
  29. package/build/ui/classes.json +42 -42
  30. package/build/ui/components/ai.d.ts +68 -4
  31. package/build/ui/components/alert-dialog.d.ts +4 -4
  32. package/build/ui/components/app-frame.d.ts +47 -7
  33. package/build/ui/components/asset-pill.d.ts +8 -0
  34. package/build/ui/components/badge.d.ts +35 -2
  35. package/build/ui/components/button.d.ts +4 -4
  36. package/build/ui/components/calendar.d.ts +2 -2
  37. package/build/ui/components/chat-input.d.ts +4 -4
  38. package/build/ui/components/data-table.d.ts +128 -13
  39. package/build/ui/components/data-view.d.ts +94 -0
  40. package/build/ui/components/date-picker.d.ts +23 -1
  41. package/build/ui/components/file-upload.d.ts +9 -1
  42. package/build/ui/components/filter-bar.d.ts +89 -0
  43. package/build/ui/components/floating-panel.d.ts +53 -0
  44. package/build/ui/components/item.d.ts +1 -1
  45. package/build/ui/components/journey.d.ts +165 -0
  46. package/build/ui/components/nav.d.ts +52 -2
  47. package/build/ui/components/page-header.d.ts +8 -8
  48. package/build/ui/components/person.d.ts +14 -0
  49. package/build/ui/components/record-summary.d.ts +17 -0
  50. package/build/ui/components/search-dialog.d.ts +56 -0
  51. package/build/ui/components/statistic.d.ts +2 -1
  52. package/build/ui/components/table.d.ts +10 -3
  53. package/build/ui/components/toggle.d.ts +1 -1
  54. package/build/ui/demo.html +45923 -25459
  55. package/build/ui/index.d.ts +8 -0
  56. package/build/ui/standalone.js +984 -69
  57. package/build/ui/styles.css +1 -1
  58. package/build/ui/theme.css +11 -6
  59. package/live/package.json +8 -0
  60. package/package.json +10 -2
  61. package/template/AGENTS.md +6 -0
  62. package/template/src/App.tsx +4 -1
package/API.md ADDED
@@ -0,0 +1,141 @@
1
+ # @rise-x/apps-sdk API summary
2
+
3
+ Read this before you write app code. It lists the calls most apps need and the
4
+ rules that make them work, for the SDK version installed next to it. For
5
+ anything it leaves out, follow the pointers in "Where to look next".
6
+
7
+ ## Import paths
8
+
9
+ - `@rise-x/apps-sdk`: shell hooks and accessors, lifecycle hook types, `createMockShell`.
10
+ - `@rise-x/apps-sdk/dependencies`: `useAppDependencies()`, the ids from `rise-x-app.json` with bound calls.
11
+ - `@rise-x/apps-sdk/query`: react-query hooks over the connectors. Mount no provider of your own.
12
+ - `@rise-x/apps-sdk/connectors`: `flows`, `work`, `assets`, `agents`, `attachments`, `integrations`, `vectorStores`, `ConnectorError`.
13
+ - `@rise-x/apps-sdk/live`: live events and editor locks.
14
+ - `@rise-x/apps-sdk/ui`: the design system components.
15
+
16
+ To reach the platform, use the first that fits: a declared dependency, a query
17
+ hook, a connector, and only then `getShellApiV4(key)`.
18
+
19
+ ## Shell hooks and accessors (`@rise-x/apps-sdk`)
20
+
21
+ - `useShellUser()` returns `{ id, name, email? } | null`.
22
+ - `useShellEnvironment()` returns `{ id, name, slug } | null`.
23
+ - `useShellNavigate()` returns react-router's `navigate` function.
24
+ - `getShellApiV4(key)` with `key` `'apps' | 'work' | 'config' | 'attachment' | 'asset'`, and `getShellApi()`: raw axios clients, the last resort.
25
+ - `getShellAi()` and `getShellLive()` return `null` on a host without that feature.
26
+
27
+ ## Dependencies (`@rise-x/apps-sdk/dependencies`)
28
+
29
+ ```ts
30
+ import { useAppDependencies, type BoundFlowDependency } from '@rise-x/apps-sdk/dependencies';
31
+
32
+ type AppDeps = { tasks: BoundFlowDependency }; // a type alias: an interface fails the constraint
33
+ const { tasks } = useAppDependencies<AppDeps>(); // throws ConnectorError when no manifest is built in
34
+ const created = await tasks.work.start({ data: { title: 'New task' } });
35
+ ```
36
+
37
+ An undeclared alias reads as `undefined`; `getAppDependency(alias)` throws for one instead.
38
+
39
+ - `flow`: `dep.flowOriginId`, `dep.flow.get()`, `dep.flow.getConfig()`, `dep.work.start(args?)`, `dep.work.list(args?)`, `dep.work.iterate(args?)`, `dep.work.search(args?)`.
40
+ - `assetType`: `dep.flowOriginId`, `dep.assets.list()`, `.iterate()`, `.search()`, `.quickSearch()`, `.create()`.
41
+ - `agent`: `dep.agentId`, `dep.agent.get()`, `.run({ message })`, `.createChat()`, `.listChats()`.
42
+ - `integration`: `dep.integrationId`, `dep.endpointId`, `dep.integration.invoke({ data? })`.
43
+ - Each bound call takes the generic call's arguments minus the ref. On `dep.work.search` and `dep.assets.search`, `filter` is optional: the call adds the `flowOriginId` pin and ands your filter with it.
44
+
45
+ ## Query hooks (`@rise-x/apps-sdk/query`)
46
+
47
+ Read hooks take an optional last `SdkQueryOptions` (`enabled`, `staleTime`,
48
+ `retry`, and others). Their `error` is a `ConnectorError`. Defaults: `staleTime`
49
+ 30 s, `gcTime` 5 min, no refetch on window focus.
50
+
51
+ - Flows: `useFlows(args?)`, `useFlow(flowId)`, `useFlowConfig(flowId)`, `useFlowLayout(layoutId)`, `useFlowTask({ flow, task })`.
52
+ - Work: `useWork(workId)` (`WorkDetail | null`), `useWorkData(workId, { path? })`, `useWorkSearch(args)` and `useWorkRows(args)` (infinite), `useRelatedWork(args)`, `useWorkAudit(workId)`.
53
+ - Assets: `useAssetTypes()`, `useAsset(id)`, `useAssetSearch(args)` and `useAssetRows(args)` (infinite), `useAssetQuickSearch(args)`, `useRelatedAssets(args)`.
54
+ - Agents: `useAgents(args?)`, `useAgent(id)`, `useAgentChats(args?)`, `useAgentChat(id)`, `useAgentChatMessages(id, args?)`.
55
+ - Mutations: `useStartWork`, `usePatchWorkData` (`{ workId, originId, path, value }`), `useSubmitWork` (`{ workId, actionName, stepName? }`), `useDeleteWork` (`{ workId }`), and the asset and agent ones. On success they refresh the queries the write affects.
56
+ - Connector calls refresh nothing. Take `const client = useAppQueryClient()` in the component body, and after a raw connector write call `invalidateAppSdkQueries(client)`.
57
+ - `dedupeRows(query.data)` flattens the pages of an infinite hook and drops repeated rows.
58
+ - `useLiveInvalidation({ flowOriginIds? })` marks work and asset queries stale when a live event reports a change.
59
+
60
+ ```tsx
61
+ const { tasks } = useAppDependencies<AppDeps>();
62
+ const search = useWorkSearch({
63
+ filter: { and: [
64
+ { field: 'flowOriginId', operator: 'equals', values: [tasks.flowOriginId] },
65
+ { field: 'flowState', operator: 'notEquals', values: ['Complete'] }, // not done
66
+ ] },
67
+ fields: ['flowState', 'data.title'], // data.* arrives under row.data, prefix stripped
68
+ });
69
+ const rows = dedupeRows(search.data); // WorkSummary[]; key them by row.id
70
+ ```
71
+
72
+ ## Connectors (`@rise-x/apps-sdk/connectors`)
73
+
74
+ Work:
75
+ - `work.start({ flowId, stepName?, data? })` returns the new `WorkDetail`. `flowId` takes a flow id or a flow origin id.
76
+ - `work.get(id)` returns `WorkDetail | null` (`null` only on a 404): `status`, `state`, `flowOriginId`, `actions`, `attachments`.
77
+ - `work.getData(id, { path? })` returns the data document, or the subtree at `path`.
78
+ - `work.patchData(id, { originId, path, value, operation? })` writes one field. `operation` defaults to `'Set'`.
79
+ - `work.submit({ workId, actionName, stepName? })` runs an action and returns the `WorkDetail` after the flow engine ran. Leave `stepName` out: the SDK sends the name of the action set that offers the action.
80
+ - `work.delete(id)` soft-deletes the item.
81
+ - `work.search({ filter, fields?, sort?, page?, pageSize?, includeTotalCount? })` returns `{ items: WorkSummary[], page, pageSize, hasMore, totalCount? }`.
82
+ - `work.list({ flow, stepIds?, properties?, showCompleted?, sort?, pageSize?, skip? })` returns `{ items: WorkRow[], skip, pageSize, hasMore }`. `work.iterate({ ..., maxItems? })` yields every row.
83
+ - `work.getMyAccess(id)`, `work.listRelated({ workId, relationships })`, and `work.getAudit(id)` cover access, related items, and history.
84
+
85
+ Flows: `flows.list({ search?, statuses? })` lists work flows only. `flows.get(ref)`
86
+ returns the flow with its steps and throws on a 404. `flows.getConfig(ref)` and
87
+ `flows.getLayout(layoutId)` return `null` on a 404. `flows.flattenLayoutFields(layout)`
88
+ lists a layout's fields with their data paths. `flows.findTask({ flow, task })`
89
+ returns `{ flow, step, task } | null`.
90
+
91
+ Assets: `assets.types()` returns `AssetType[]`, with the origin id at
92
+ `type.flow.flowOriginId`. `assets.get(id)`, `assets.search({ filter, ... })` (same
93
+ shape as `work.search`), `assets.quickSearch({ search?, type?, typeOriginId? })`,
94
+ `assets.list({ type, ... })`, and `assets.iterate(...)` read. `assets.create({ type })`
95
+ and `assets.startEdit({ assetId, flowOriginId })` return a draft `WorkDetail`: fill
96
+ it with `work.patchData` and save it with `work.submit`. `assets.clone(id)` and
97
+ `assets.delete(id)` complete the set.
98
+
99
+ Agents: `agents.run({ agentId, message, chatId?, context?, attachments?, vectorStoreIds? })`
100
+ streams `AgentRunEvent`s. `agents.createChat({ agentId })` returns a session whose
101
+ `send(message)` keeps the chat id between turns. `collectAgentReply(events)`
102
+ resolves to `{ text, delta, done, reason, error, chatId }`, and `streamAgentReply(events)`
103
+ yields the same snapshot as the reply grows. `agents.list`, `get`, `create`,
104
+ `update`, `delete`, and the chat calls manage agents and their chats.
105
+
106
+ Others: `attachments.getBlob({ id, resourceId })` returns `Blob | null`,
107
+ `attachments.upload({ workId, files, folder })`, `attachments.delete({ id })`.
108
+ `integrations.invoke({ integrationId, endpointId, data? })` returns
109
+ `{ statusCode, success, response, items, message, executionTimeMs }`. `vectorStores` creates and fills
110
+ vector stores for agents.
111
+
112
+ Errors: every connector call rejects with a `ConnectorError`. Check `code`:
113
+ `NOT_FOUND` (a 404), `HTTP_ERROR` (other non-2xx, with `status`), `NETWORK_ERROR`,
114
+ `ABORTED`, `INVALID_ARG`, `SHELL_UNAVAILABLE`, and others.
115
+
116
+ ```ts
117
+ // Submit the action the user picked, by its event name, from the item's own list.
118
+ const detail = await work.get(workId);
119
+ if (!detail) throw new Error(`Work item ${workId} not found`);
120
+ const chosen = detail.actions.find((a) => a.id === pickedActionId);
121
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this item`);
122
+ await work.patchData(workId, { originId: detail.flowOriginId!, path: '$.title', value: title });
123
+ await work.submit({ workId, actionName: chosen.eventName ?? chosen.name! });
124
+ ```
125
+
126
+ ## Work item rules
127
+
128
+ - `status` is the record's lifecycle: `Open` after `work.start`, `Deleted` after a delete. A finished item can still read `Open`, so never read done from `status`.
129
+ - Done is the flow's position: `flowState` is `'Complete'` on a `work.search` row, and the same value is `state` on `work.get`.
130
+ - `work.patchData` changes a field and runs no action. `work.submit` moves the step: approve, reject, send back, finish. Await `patchData` first: submit merges no data, and the platform checks the action's condition against the saved data.
131
+ - Take `actionName` from the item's own `actions`, as `eventName ?? name` of the action the user picked. Never guess a name or take `actions[0]`. The platform rejects a name that is not an action of the step with a 403 and leaves the item unchanged.
132
+ - `work.submit` reads the item and its flow config, finds the action set that offers the action, and sends that action set's name as `stepName`. Pass `stepName` only to pick between two action sets that offer the same action: the `name` of the entry in `flows.getConfig(detail.flowId)`'s `tasks[].actionSets` whose `id` is the picked action's `actionSetId`. Never pass a step or task name: with `Submit`, the platform answers 200 and the item doesn't move.
133
+ - `work.list` and `work.iterate` filter strictly by flow origin id. A concrete flow id returns an empty list, not an error. Pass the flow object or `dep.flowOriginId`.
134
+ - `work.search` and `assets.search` need a `flowOriginId` `equals` or `in` condition at the top level or under `and`. Without it the server returns a 400.
135
+ - `work.delete` is a soft delete: `status` and `flowState` become `Deleted`, and the record stays. A second delete rejects with `NOT_FOUND`. The SDK has no restore call. `work.search` leaves deleted items out unless the filter names `status`.
136
+ - Key rows by `id`. `displayName` can repeat, and `workCode` can be missing.
137
+
138
+ ## Where to look next
139
+
140
+ - README sections: "Choosing an API", "Bound connectors", "Work — items (read + write)", "Assets — typed records", "Agents — configurable AI", "Query layer (react-query)", "Live events and presence", "UI components".
141
+ - Types: `build/connectors/types.d.ts` (`WorkDetail`, `WorkSummary`, `WorkRow`, `AssetType`), `build/connectors/work.d.ts`, `build/connectors/search.d.ts`, `build/dependencies/bound.d.ts`, `build/query/index.d.ts`, `build/live/index.d.ts`.
package/README.md CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  SDK for building federated apps on top of the Rise-X Diana shell.
4
4
 
5
- - **Runtime hooks/accessors** — `useShellUser`, `useShellEnvironment`, `useShellNavigate`, `getShellApi`, `getShellApiV4`, `getShellAi`.
5
+ - **Runtime hooks/accessors** — `useShellUser`, `useShellEnvironment`, `useShellNavigate`, `getShellApi`, `getShellApiV4`, `getShellAi`, `getShellLive`.
6
6
  - **App dependencies** — `rise-x-app.json` declares the flows, asset types, agents, and integration endpoints the app depends on, one id (or id pair) per environment; `@rise-x/apps-sdk/dependencies` reads them back as `deps.<alias>`, with the connector calls that take that ref pre-filled. This is the first choice for any Rise-X object the app knows at authoring time.
7
7
  - **Connectors** — `@rise-x/apps-sdk/connectors` exposes typed, higher-level API wrappers (`flows`, `work`, `assets`, `agents`, `integrations`) so apps don't hand-roll multi-step API calls. Use them for what a declared dependency can't express.
8
+ - **Live events and presence** — `@rise-x/apps-sdk/live` lets an app hear about other people's changes and see who is editing, over the host's own connection instead of polling; `useLiveInvalidation` on `@rise-x/apps-sdk/query` keeps the query cache current from the same events.
8
9
  - **Lifecycle hooks** — `onInstall`, `onUpdate`, `onUninstall` that apps export from a federated `./lifecycle` module; the shell invokes them best-effort.
9
10
  - **Standalone-dev mock** — `createMockShell` for running an app outside the shell.
10
11
  - **Shell-side installer** — `@rise-x/apps-sdk/shell` exposes `installShellBridge` for the host to wire the bridge.
@@ -600,7 +601,7 @@ design mocks** without repo access:
600
601
  The file is pretty-printed and starts with a navigation guide plus a JSON
601
602
  table of contents (`<script type="application/json" id="demo-toc">`) listing
602
603
  every section, screen, and the `data-slot` components each section
603
- demonstrates. Read the first ~80 lines for the TOC, then grep:
604
+ demonstrates. The guide names the line the TOC ends on — read that far, then grep:
604
605
 
605
606
  | To find | Grep for |
606
607
  | --- | --- |
@@ -740,6 +741,34 @@ everything. Pass `moreLabel` on `AppRail` to localise the label. Don't hand-roll
740
741
  a tab bar, and don't write your own breakpoints around the frame; compose inside
741
742
  it.
742
743
 
744
+ From the `2xl` width up the rail is **the user's to size**: 248px by default,
745
+ dragged anywhere from 200 to 420 by its right edge, or collapsed to 52px of
746
+ icons (click the edge, release a drag under 150px, or press ⌘. / Ctrl+.). The
747
+ size is remembered per `storageKey` (pass your app's id) and nothing else ever
748
+ changes it — not navigation, not opening a panel. Collapsed, a `NavItem` shows
749
+ its icon with the label as a tooltip, a `NavSection` becomes a hairline, and a
750
+ `NavGroup` with an `icon` becomes one button that opens its items as a list
751
+ beside the rail:
752
+
753
+ ```tsx
754
+ <AppRail storageKey="order-book">
755
+ <Nav>
756
+ <NavItem current><LineChart />Market</NavItem>
757
+ <NavGroup title="Offers" icon={<Tag />} more={<NavItem><Tag />All offers</NavItem>}>
758
+ <NavItem dot="needs">Spodumene SC6.0</NavItem>
759
+ </NavGroup>
760
+ </Nav>
761
+ </AppRail>
762
+ ```
763
+
764
+ The rail is the app's **menu of pages** — Overview, Records, People,
765
+ Settings — never a list of records or a to-do list. What waits on the user
766
+ belongs on a page (an Overview's "Waiting on you"), with at most a count
767
+ `Badge` on that page's item. Give every top-level item an icon; collapsed, the
768
+ icon is all there is. `dot` is for "needs you" (`needs`) or "running"
769
+ (`working`) only. Below `2xl` the
770
+ rail is the strip or the tab bar and neither collapses nor resizes.
771
+
743
772
  Rendering an `AppFrame` anywhere in the app is the signal that the app owns
744
773
  its layout: the next-gen shell detects it and hands over the full-bleed
745
774
  region. Apps without one are compensated — the host pads and scrolls the
@@ -769,6 +798,100 @@ Requirements in the app:
769
798
  It's a snapshot, not the source of truth: verify in a host (or deployed)
770
799
  before release.
771
800
 
801
+ #### Lists (`DataTable` / `DataView`)
802
+
803
+ Every list of records is a `DataTable`, and every table ships the same
804
+ toolbar — nothing to opt into:
805
+
806
+ - **Filters**, inferred from the columns (numbers, dates — `Date` values or
807
+ ISO strings — up to 12 names or
808
+ other words as a pick list — even when each appears once — and references
809
+ such as `REC-0412` or longer lists as text). Pass `filters` to
810
+ choose them; `meta: { filter: false }` leaves a column out.
811
+ - **A menu on every column header**: sort ascending or descending, filter by
812
+ this column, hide it. Plain-text headers get it automatically; a custom
813
+ header keeps it by rendering `DataTableColumnHeader`.
814
+ - **View**: the columns shown, and **Reset view** (columns and sort back to
815
+ default). Hiding every column shows an empty state with *Show all columns*.
816
+
817
+ Search stays opt-in (`searchable`): it only covers the rows already loaded.
818
+
819
+ Bulk actions: `enableRowSelection` (or `(row) => boolean`, so only rows the
820
+ action applies to can be ticked) plus `bulkActions={(rows, clear) => …}` —
821
+ the action shows in a bar that rises below the list, with the count and
822
+ clear, while anything is ticked. Ticks stay on their record across a refresh:
823
+ rows are named by their `id` field, or pass `getRowId`. A table inside a `FloatingPanelSection` sits bare; the section never
824
+ adds a second tile.
825
+
826
+ A list that needs more than one layout is a `DataView` — Table, Board
827
+ (kanban) and Calendar behind the one toolbar, so filters and sort carry
828
+ across layouts. The calendar shows 3 days, a week or a month (its own switch,
829
+ beside Today); 3 days and Week are a time grid placed by `calendar.date` and
830
+ `calendar.end`, and hovering an entry shows all its details. View is per layout — table columns, board card fields,
831
+ calendar entry details and weekends — each with Reset view:
832
+
833
+ ```tsx
834
+ <DataView
835
+ views={['table', 'board']} // only what the list needs
836
+ columns={columns}
837
+ data={orders}
838
+ onRowClick={(o) => openOrder(o.id)}
839
+ board={{ groupBy: 'status', groups: [{ value: 'Open', intent: 'waiting' }, …] }}
840
+ calendar={{ date: 'due', title: 'name' }} // when 'calendar' is in views
841
+ />
842
+ ```
843
+
844
+ **Ask before adding layouts.** Which views a list offers is a product
845
+ decision: ask the app's owner whether it needs Table, Board and/or Calendar.
846
+ A board needs a column that moves through stages; a calendar needs a date
847
+ people plan by. One layout is a plain `DataTable`.
848
+
849
+ #### Breadcrumb (`useShellBreadcrumb`)
850
+
851
+ **Required, on every page.** The shell's breadcrumb is always your app's name,
852
+ then the page, then anything deeper (the Home pill sits before it):
853
+
854
+ | Where | Declare | The strip shows |
855
+ | --- | --- | --- |
856
+ | the default page | `[{ label: 'Overview' }]` | `Invoice Audit / Overview` |
857
+ | any other page | `[{ label: 'Records' }]` | `Invoice Audit / Records` |
858
+ | deeper | `[{ label: 'Records', onClick }, { label: 'REC-0412' }]` | `Invoice Audit / Records / REC-0412` |
859
+
860
+ - The app's name comes from the shell and is **never a link** — it isn't a
861
+ page. There is no "app name alone" state: the default page declares itself
862
+ like any other.
863
+ - The page crumb uses the same words as your rail; the last crumb uses the
864
+ same words as the page title and is never a link. Every page crumb before
865
+ it takes `onClick` and goes back there.
866
+ - Don't name an app page "Home" — the Home pill is Rise-X's. Use "Overview".
867
+ - Never a crumb for a tab, a filter, a search, a dialog, a drawer or a wizard
868
+ step — they change what is shown, not where the user is.
869
+
870
+ Apps route inside themselves, so crumbs take `onClick`:
871
+
872
+ ```tsx
873
+ import { useShellBreadcrumb } from '@rise-x/apps-sdk';
874
+
875
+ const back = useShellBreadcrumb([
876
+ { label: 'My offers', onClick: () => go('offers') },
877
+ { label: offer.title },
878
+ ]);
879
+ // → Order Book / My offers / Spodumene SC6.0 · CIF Qingdao
880
+
881
+ // The page's back link, from the same trail — never written separately:
882
+ {back && <PageHeaderBack onClick={back.onClick}>{back.label}</PageHeaderBack>}
883
+ ```
884
+
885
+ The hook returns the trail's parent crumb (or `null` on a top-level page).
886
+ Drawing the back link from it makes the link and the strip's crumb one step,
887
+ so they can never point to different places. In the shell the link hides on
888
+ wide screens and shows on a phone.
889
+
890
+ Keep labels short: a crumb truncates at 180px (the current one at 300px), and
891
+ a trail past four crumbs shows only the first and the last two. `badge` (a
892
+ string, or `{ label, tone }`) shows on the current crumb, e.g. *Test mode*.
893
+ Outside a shell that supports it, the hook does nothing.
894
+
772
895
  #### `MapView`
773
896
 
774
897
  The one component with a real library behind it. It renders a Leaflet basemap
@@ -982,12 +1105,22 @@ await work.patchData(created.id, {
982
1105
  });
983
1106
 
984
1107
  // Complete a task action. Patch data first — submit does not merge data.
985
- const action = detail.actions[0];
986
- const actionName = action?.eventName ?? action?.name;
987
- if (!actionName) throw new Error('work item has no available action');
988
- await work.submit({ workId: created.id, actionName });
989
-
990
- // Remove a work item (no server-side undo).
1108
+ // Submit the action the user picked, found by id in the item's own list; never
1109
+ // guess a name or take actions[0]. A missing action is normal (someone else moved
1110
+ // the step): tell the user and refresh, never skip it silently.
1111
+ // `pickedActionId` is the `id` of the action the user clicked, from a button
1112
+ // the app rendered for each entry of `detail.actions`.
1113
+ // Leave `stepName` out: submit reads the work and its flow config and sends the
1114
+ // name of the action set that offers the action. Pass one only to pick between
1115
+ // two action sets that offer the same action: the `name` of the `actionSets`
1116
+ // entry in flows.getConfig(detail.flowId) whose `id` is chosen.actionSetId.
1117
+ // A step or task name moves nothing.
1118
+ const chosen = detail.actions.find((a) => a.id === pickedActionId);
1119
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this item`);
1120
+ await work.submit({ workId: created.id, actionName: chosen.eventName ?? chosen.name! });
1121
+
1122
+ // Soft-delete a work item: its status becomes Deleted and the record stays.
1123
+ // A second delete rejects with NOT_FOUND. The SDK has no restore call.
991
1124
  await work.delete(created.id);
992
1125
 
993
1126
  // Paginated listing — `properties` shapes each row's `data` subtree.
@@ -1110,8 +1243,11 @@ const related = await assets.listRelated({ assetId: detail.id, relationships: ['
1110
1243
  // fill it with work.patchData(), save it with work.submit().
1111
1244
  const draft = await assets.create({ type: supplier });
1112
1245
  await work.patchData(draft.id, { originId: draft.flowOriginId!, path: '$.supplier.name', value: 'Acme' });
1113
- const submitAction = draft.actions[0];
1114
- await work.submit({ workId: draft.id, actionName: submitAction.eventName ?? submitAction.name! });
1246
+ // Save with the action the user picked from the draft's own `actions`, found by
1247
+ // id, as in the work example; never take actions[0].
1248
+ const chosen = draft.actions.find((a) => a.id === pickedActionId);
1249
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this draft`);
1250
+ await work.submit({ workId: draft.id, actionName: chosen.eventName ?? chosen.name! });
1115
1251
 
1116
1252
  const editDraft = await assets.startEdit({ assetId: detail.id, flowOriginId: detail.flowOriginId! });
1117
1253
  await assets.clone(detail.id);
@@ -1670,6 +1806,148 @@ Details worth knowing:
1670
1806
  use the infinite hooks instead) and the SSE streams (`agents.run`,
1671
1807
  chat `send`) stay on the connectors.
1672
1808
 
1809
+ ## Live events and presence (`@rise-x/apps-sdk/live`)
1810
+
1811
+ The host holds one connection to the platform's event hub. Through the bridge
1812
+ (`getLive()`, bridge v5) an app hears about other people's changes and sees who
1813
+ is editing, without opening a connection of its own or polling. The host
1814
+ translates the hub's events into the SDK's own `LiveEvent`s, so an app never
1815
+ depends on the platform's wire names.
1816
+
1817
+ ### Keep the query cache current
1818
+
1819
+ An app that renders with this SDK's query hooks needs one line, near its root:
1820
+
1821
+ ```tsx
1822
+ import { useLiveInvalidation } from '@rise-x/apps-sdk/query';
1823
+
1824
+ function App() {
1825
+ const deps = useAppDependencies();
1826
+ useLiveInvalidation({ flowOriginIds: [deps.riskFlow.flowOriginId] });
1827
+ // …
1828
+ }
1829
+ ```
1830
+
1831
+ A change marks the work item's or asset's queries and the listings stale (only
1832
+ the ones on screen refetch), a delete drops the item's queries, and a `resync`
1833
+ marks every work and asset query stale. A burst, such as a form saved one field
1834
+ at a time, is collected for 300 ms and refreshes once. `flowOriginIds` skips
1835
+ data writes in other flows; a change that names no flow always counts.
1836
+
1837
+ ### Handle events yourself
1838
+
1839
+ ```tsx
1840
+ import { useLiveEvents, useLiveStatus } from '@rise-x/apps-sdk/live';
1841
+
1842
+ useLiveEvents((event) => {
1843
+ switch (event.type) {
1844
+ case 'workData': // a write: event.path, operation, hasValue, value, flowOriginId, userId
1845
+ case 'workUpdated': // created, submitted, moved to another step: read the work
1846
+ case 'workDeleted':
1847
+ if (held.has(event.workId)) reread(event.workId);
1848
+ break;
1849
+ case 'resync': // the connection came back: re-read what you show
1850
+ rereadEverythingShown();
1851
+ break;
1852
+ }
1853
+ });
1854
+
1855
+ const status = useLiveStatus();
1856
+ ```
1857
+
1858
+ | Event | When | Carries |
1859
+ | --- | --- | --- |
1860
+ | `workData` | a write to a work item's data | `workId`, `path`, `operation`, `hasValue`, `value`, `flowOriginId`, `userId`, `updateId` |
1861
+ | `workUpdated` | a create, a submit, a step move, a bulk write | `workId`, `displayName` |
1862
+ | `workDeleted` | a delete | `workId` |
1863
+ | `assetUpdated` / `assetDeleted` | an asset created, changed or deleted | `assetId`, and `displayName` on an update |
1864
+ | `lock` | a user took or released a component lock | `workId`, `userId`, `displayName`, `componentId`, `dataPath`, `at`, `locked` |
1865
+ | `resync` | the connection came back | nothing |
1866
+
1867
+ `useLiveStatus()` is `connecting` until the first connection, `reconnecting`
1868
+ while the host retries one that dropped, `disconnected` after a close, and
1869
+ `connected` while events arrive. Each return to `connected` sends one `resync`,
1870
+ and so does the host replacing its connection (an environment switch).
1871
+ `unavailable` means the host offers no live events at all.
1872
+
1873
+ Treat an event as a reason to re-read, never as the data:
1874
+
1875
+ - **Not every change sends one.** A change to a work item's properties (rather
1876
+ than its data) and a removed attachment send nothing. Keep a re-read for when
1877
+ the window regains focus.
1878
+ - **Your own writes come back.** `userId` says who wrote. A write that reaches a
1879
+ user twice (directly and through a group) is reported once, but a
1880
+ `workUpdated` or `workDeleted` can still arrive twice.
1881
+ - **Events arrive for everything the user can see**, in every ecosystem they
1882
+ belong to. Act on the ids and flows you hold.
1883
+ - **`hasValue: false` means read the path.** An object or list value, a delivery
1884
+ through a group, and an operation outside `WorkPatchOperationName` carry no
1885
+ value. A very large write can fail to arrive, so re-read by id rather than
1886
+ trusting `value`.
1887
+ - **Nothing is replayed.** Events sent while the connection was down are lost;
1888
+ `resync` says when to re-read.
1889
+
1890
+ Re-read by id (`work.getData(id)`) rather than through a search: a search can
1891
+ lag a write, the document does not.
1892
+
1893
+ ### Show who is editing
1894
+
1895
+ ```tsx
1896
+ import { useComponentLock, useWorkLocks } from '@rise-x/apps-sdk/live';
1897
+
1898
+ // A fixed GUID for this editor, the same in every session.
1899
+ const RISK_EDITOR = '6f1c2a4e-0b7d-4c55-9a51-3f0e8d2b7c19';
1900
+
1901
+ function RiskEditor({ workId, open }: { workId: string; open: boolean }) {
1902
+ useComponentLock(workId, RISK_EDITOR, open);
1903
+ const editing = useWorkLocks(workId).filter((lock) => lock.userId !== me.id);
1904
+ // …
1905
+ }
1906
+ ```
1907
+
1908
+ - `useComponentLock(workId, componentId, active, dataPath?)` takes the user's
1909
+ lock while `active`, says it again every `LOCK_REFRESH_MS` (one minute) and
1910
+ after a reconnect, and releases it when `active` ends or the component
1911
+ unmounts. `getShellLive()?.setComponentLock({ workId, componentId, dataPath,
1912
+ locked })` does the same by hand.
1913
+ - `useWorkLocks(workId)` is everyone's locks on the work, yours included: it
1914
+ starts from a read of the work (`WorkDetail.activeLocks`) and follows `lock`
1915
+ events.
1916
+ - Locks are advisory: they never block a write. They go over the host's
1917
+ connection, so without one a lock call rejects (`useComponentLock` ignores
1918
+ that) and the app keeps working.
1919
+ - The platform keeps **one lock per user per work**. A lock this app takes and
1920
+ one the host's own editor takes for the same user replace each other, and
1921
+ releasing either clears it. Within one app, several `useComponentLock` holds
1922
+ on a work stack: the newest shows, and releasing it takes the previous one
1923
+ again.
1924
+ - A lock from a closed browser can linger on the platform: compare `at` with the
1925
+ age you are willing to believe.
1926
+
1927
+ ### Hosts without live events, and standalone dev
1928
+
1929
+ On a host that predates bridge v5, or one that offers no live events,
1930
+ `getShellLive()` is null, `useLiveStatus()` is `unavailable`, and every hook
1931
+ does nothing, so keep the app's own reads for those hosts. A connection that is
1932
+ only down is different: `getShellLive()` still answers, its status is
1933
+ `disconnected` until the connection is back, and a `resync` follows.
1934
+
1935
+ Under `pnpm start`, give the mock shell a channel and drive it by hand:
1936
+
1937
+ ```ts
1938
+ import { createLiveChannel, createMockShell } from '@rise-x/apps-sdk';
1939
+
1940
+ const live = createLiveChannel({ status: 'connected' });
1941
+ createMockShell({ live });
1942
+
1943
+ live.emit({ type: 'workUpdated', workId: 'w1' });
1944
+ live.setStatus('reconnecting');
1945
+ live.setStatus('connected'); // sends a resync
1946
+ ```
1947
+
1948
+ Pass `setComponentLock` to `createLiveChannel` to see the locks the app sends;
1949
+ without it, a lock call rejects.
1950
+
1673
1951
  ## Shell-side (host) wiring
1674
1952
 
1675
1953
  ```ts
@@ -1697,6 +1975,17 @@ endpoint) to route asset search independently.
1697
1975
  and router `navigate` into the bridge via `getMutableShell` — also exported from
1698
1976
  `@rise-x/apps-sdk/shell`.
1699
1977
 
1978
+ The same keeper reports the hub connection for live events (bridge v5):
1979
+ `_setLiveConnection(connection, state)` whenever the connection or its state changes.
1980
+ `connection` is anything with SignalR's `on` / `off` / `invoke` (a `HubConnection` as is),
1981
+ or null while there is none; `state` is the connection's own `connecting`, `connected`,
1982
+ `reconnecting` or `disconnected`. The bridge does the rest the same way in every host: it
1983
+ maps the hub's events to `LiveEvent`s, moves its handlers to a new connection, turns the
1984
+ state into the status apps see (with a `resync` on each return to `connected` and on a
1985
+ replaced connection), reports a write delivered twice once, and sends locks over the hub.
1986
+ A host with no hub passes `live: false` to `installShellBridge`, and `getLive()` answers
1987
+ null.
1988
+
1700
1989
  The shell's `RemoteAppLoader` additionally wraps every mounted app in a
1701
1990
  per-app `QueryClient` (built with `createAppQueryClient` from
1702
1991
  `@rise-x/apps-sdk/query`), which is what the SDK's query hooks pick up
@@ -1,8 +1,9 @@
1
1
  import type { AxiosInstance } from "axios";
2
- import type { DianaShell, ShellAiApi, ShellEnvironment, ShellUser, V4ApiKey } from "./shellBridge";
2
+ import type { DianaShell, LiveApi, ShellAiApi, ShellEnvironment, ShellUser, V4ApiKey } from "./shellBridge";
3
3
  export declare function getShellApi(): AxiosInstance;
4
4
  export declare function getShellApiV4(name: V4ApiKey): AxiosInstance;
5
5
  export declare function getShell(): DianaShell | null;
6
6
  export declare function getShellUser(): ShellUser | null;
7
7
  export declare function getShellAi(): ShellAiApi | null;
8
+ export declare function getShellLive(): LiveApi | null;
8
9
  export declare function getShellEnvironment(): ShellEnvironment | null;
@@ -5,6 +5,7 @@ exports.getShellApiV4 = getShellApiV4;
5
5
  exports.getShell = getShell;
6
6
  exports.getShellUser = getShellUser;
7
7
  exports.getShellAi = getShellAi;
8
+ exports.getShellLive = getShellLive;
8
9
  exports.getShellEnvironment = getShellEnvironment;
9
10
  const _internal_1 = require("./_internal");
10
11
  function getShellApi() {
@@ -35,6 +36,15 @@ function getShellAi() {
35
36
  return null;
36
37
  return shell.getAi();
37
38
  }
39
+ // The host's live events and component locks, or null when the shell is missing, predates bridge
40
+ // v5 (no getLive), or offers no live events. Feature-detected so a v5-built app degrades cleanly
41
+ // on an older host.
42
+ function getShellLive() {
43
+ const shell = getShell();
44
+ if (!shell || typeof shell.getLive !== "function")
45
+ return null;
46
+ return shell.getLive();
47
+ }
38
48
  function getShellEnvironment() {
39
49
  return getShell()?.getEnvironment() ?? null;
40
50
  }
@@ -0,0 +1,49 @@
1
+ /** Plain data, so it crosses the module-federation boundary; the shell draws
2
+ * every crumb badge the same way. Honoured on the current (last) crumb only. */
3
+ export type ShellBreadcrumbBadge = string | {
4
+ label: string;
5
+ tone?: "neutral" | "success" | "warning" | "error" | "info";
6
+ };
7
+ /**
8
+ * One crumb an app adds after its own name. Apps route inside themselves, so
9
+ * a crumb takes `onClick` rather than a shell path. The last crumb is the
10
+ * current page and is never clickable.
11
+ */
12
+ export interface ShellBreadcrumbItem {
13
+ label: string;
14
+ onClick?: () => void;
15
+ badge?: ShellBreadcrumbBadge;
16
+ }
17
+ /**
18
+ * Set the trail after the app's name in the shell's breadcrumb — always the
19
+ * page, then anything deeper: `Order Book / My offers / Spodumene SC6.0`. The
20
+ * shell provides the app name itself, and it is never a link. Every page sets
21
+ * at least its own crumb, the default page included. Returns a function that
22
+ * clears it.
23
+ *
24
+ * Safe to call unconditionally: outside a shell that supports it (standalone
25
+ * dev, an older host) it no-ops.
26
+ */
27
+ export declare function setShellBreadcrumb(items: ShellBreadcrumbItem[]): () => void;
28
+ /** The page's way back, read from its own trail. */
29
+ export interface ShellBreadcrumbBack {
30
+ label: string;
31
+ onClick: () => void;
32
+ }
33
+ /**
34
+ * React form of `setShellBreadcrumb`: declares the trail for as long as the
35
+ * calling component is mounted. Re-sent only when a label, badge or the
36
+ * presence of a click changes, so it is cheap to call with inline arrays;
37
+ * clicks always reach the latest callbacks.
38
+ *
39
+ * Returns the trail's parent crumb — the one before the current page — or
40
+ * null when there is none. Render the page's back link from it, so the back
41
+ * link and the strip's crumb are the same step by construction:
42
+ *
43
+ * const back = useShellBreadcrumb([{ label: 'Records', onClick: list }, { label: id }]);
44
+ * {back && <PageHeaderBack onClick={back.onClick}>{back.label}</PageHeaderBack>}
45
+ *
46
+ * In the shell the back link then hides on wide screens (the strip is the way
47
+ * back) and shows on a phone; standalone it always shows.
48
+ */
49
+ export declare function useShellBreadcrumb(items: ShellBreadcrumbItem[]): ShellBreadcrumbBack | null;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setShellBreadcrumb = setShellBreadcrumb;
4
+ exports.useShellBreadcrumb = useShellBreadcrumb;
5
+ const react_1 = require("react");
6
+ const accessors_1 = require("./accessors");
7
+ /**
8
+ * Set the trail after the app's name in the shell's breadcrumb — always the
9
+ * page, then anything deeper: `Order Book / My offers / Spodumene SC6.0`. The
10
+ * shell provides the app name itself, and it is never a link. Every page sets
11
+ * at least its own crumb, the default page included. Returns a function that
12
+ * clears it.
13
+ *
14
+ * Safe to call unconditionally: outside a shell that supports it (standalone
15
+ * dev, an older host) it no-ops.
16
+ */
17
+ function setShellBreadcrumb(items) {
18
+ const shell = (0, accessors_1.getShell)();
19
+ const set = shell?.setAppBreadcrumb;
20
+ return typeof set === "function" ? set(items) : () => { };
21
+ }
22
+ /**
23
+ * React form of `setShellBreadcrumb`: declares the trail for as long as the
24
+ * calling component is mounted. Re-sent only when a label, badge or the
25
+ * presence of a click changes, so it is cheap to call with inline arrays;
26
+ * clicks always reach the latest callbacks.
27
+ *
28
+ * Returns the trail's parent crumb — the one before the current page — or
29
+ * null when there is none. Render the page's back link from it, so the back
30
+ * link and the strip's crumb are the same step by construction:
31
+ *
32
+ * const back = useShellBreadcrumb([{ label: 'Records', onClick: list }, { label: id }]);
33
+ * {back && <PageHeaderBack onClick={back.onClick}>{back.label}</PageHeaderBack>}
34
+ *
35
+ * In the shell the back link then hides on wide screens (the strip is the way
36
+ * back) and shows on a phone; standalone it always shows.
37
+ */
38
+ function useShellBreadcrumb(items) {
39
+ const latest = (0, react_1.useRef)({ items });
40
+ latest.current = { items };
41
+ const key = JSON.stringify(items, (_key, value) => typeof value === "function" ? true : value);
42
+ (0, react_1.useEffect)(() => {
43
+ return setShellBreadcrumb(latest.current.items.map((item, index) => ({
44
+ ...item,
45
+ onClick: item.onClick
46
+ ? () => latest.current.items[index]?.onClick?.()
47
+ : undefined,
48
+ })));
49
+ }, [key]);
50
+ const parentIndex = items.length - 2;
51
+ const parent = parentIndex >= 0 ? items[parentIndex] : undefined;
52
+ return parent?.onClick
53
+ ? {
54
+ label: parent.label,
55
+ onClick: () => latest.current.items[parentIndex]?.onClick?.(),
56
+ }
57
+ : null;
58
+ }