@colixsystems/widget-sdk 0.205.1 → 0.207.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.
package/dist/contract.js CHANGED
@@ -704,6 +704,25 @@ const THEME_COMPONENTS = Object.freeze({
704
704
  }),
705
705
  targets: Object.freeze({}),
706
706
  }),
707
+ // Inline messages: `<Banner>` reads this scope directly, so it names the
708
+ // SDK component it styles and binds no widget field.
709
+ alert: Object.freeze({
710
+ label: "Alerts",
711
+ sdkComponents: Object.freeze(["Banner"]),
712
+ tokens: Object.freeze({
713
+ radius: Object.freeze({ type: "size", min: 0, max: 32, uiDefault: "radii.md" }),
714
+ borderWidth: Object.freeze({ type: "size", min: 0, max: 4 }),
715
+ infoBackground: Object.freeze({ type: "color" }),
716
+ infoTextColor: Object.freeze({ type: "color" }),
717
+ successBackground: Object.freeze({ type: "color" }),
718
+ successTextColor: Object.freeze({ type: "color" }),
719
+ warningBackground: Object.freeze({ type: "color" }),
720
+ warningTextColor: Object.freeze({ type: "color" }),
721
+ errorBackground: Object.freeze({ type: "color" }),
722
+ errorTextColor: Object.freeze({ type: "color" }),
723
+ }),
724
+ targets: Object.freeze({}),
725
+ }),
707
726
  });
708
727
 
709
728
  // sc-4505 — the value types a widget event payload field may declare. Narrower
@@ -2064,6 +2083,62 @@ const HOOKS = [
2064
2083
  requiredContextSlice: ["directory.users"],
2065
2084
  scopes: ["users.activity:*"],
2066
2085
  },
2086
+ // sc-11025 / REQ-USERMGMT-12 — online status for people who share a record.
2087
+ {
2088
+ name: "useOnlineMembers",
2089
+ signature: "useOnlineMembers(tableId, recordIds)",
2090
+ description:
2091
+ "Who is online among the members of each record the viewer is a " +
2092
+ "member of (a conversation, a team, a case), on a table that shows its " +
2093
+ "members' online status (a template table's `presence: true`, or the " +
2094
+ "table setting in the Studio). Members hold their OWN read grant on the " +
2095
+ "record, given to them by a person (a grant from a template or one " +
2096
+ "inherited from a parent row names no member). `online` is a Set of " +
2097
+ "the user ids online across the records; `byRecord[recordId]` is " +
2098
+ "{ online_user_ids, online_count } — the ids are capped at 100 per " +
2099
+ "record, so count with `online_count`. A record the viewer only reads " +
2100
+ "(through a group or a grant to everyone) or cannot read answers with " +
2101
+ "nobody. Refreshes every minute while the app is in front, on return " +
2102
+ "to it and on pull-to-refresh. `supported` is true only once the " +
2103
+ "workspace answered: it is false while the workspace does not record " +
2104
+ "user activity, when the table has not opted in, when the viewer hides " +
2105
+ "their own status (useOnlineVisibility), and in a preview — then show " +
2106
+ "NO online state at all, never \"offline\". The viewer's own id may be " +
2107
+ "in `online`; leave it out when you mean \"someone else is here\". " +
2108
+ "Never timestamps. Declare `directory.read:users`: the publish checks " +
2109
+ "do not require it for this hook, but it is the scope the hook belongs to.",
2110
+ returnShape: {
2111
+ supported: "boolean // false: render no online dots, no counts, no 'offline' state",
2112
+ online: "Set<string> // user ids online across the records",
2113
+ byRecord: "{ [recordId]: { online_user_ids: string[], online_count: number } }",
2114
+ loading: "boolean",
2115
+ error: "DirectoryError | null // reason ACTIVITY_UNAVAILABLE, ACTIVITY_DISABLED, ONLINE_STATUS_HIDDEN, PRESENCE_NOT_ENABLED or FORBIDDEN (not a live person) when refused",
2116
+ refetch: "() => Promise<void>",
2117
+ },
2118
+ requiredContextSlice: ["directory.presence"],
2119
+ scopes: ["directory.read:users"],
2120
+ },
2121
+ {
2122
+ name: "useOnlineVisibility",
2123
+ signature: "useOnlineVisibility()",
2124
+ description:
2125
+ "The viewer's own \"Show when I'm online\" switch, on by default. " +
2126
+ "`supported` is false where the workspace shows nobody online: offer " +
2127
+ "the switch only when it is true. `setShowOnline(false)` hides the " +
2128
+ "viewer from everyone, and they then see nobody online either; every " +
2129
+ "useOnlineMembers on the page re-reads. No scope: it is the viewer's " +
2130
+ "own setting.",
2131
+ returnShape: {
2132
+ supported: "boolean",
2133
+ showOnline: "boolean | null // null until known",
2134
+ loading: "boolean",
2135
+ saving: "boolean",
2136
+ error: "DirectoryError | null",
2137
+ setShowOnline: "(showOnline: boolean) => Promise<void> // rejects with DirectoryError",
2138
+ },
2139
+ requiredContextSlice: ["directory.presence"],
2140
+ scopes: null,
2141
+ },
2067
2142
  // REQ-USERMGMT / REQ-ACL-SYS M3 — AppUserGroup administration. Returns
2068
2143
  // `{ groups, loading, error, refetch, create, remove, addMember, removeMember }`.
2069
2144
  // Reads need `groups.read:*`; mutations need `groups.write:*`. Removing a
@@ -2906,6 +2981,13 @@ const PRIMITIVES = [
2906
2981
  rnComponent: null,
2907
2982
  docsUrl: null,
2908
2983
  },
2984
+ {
2985
+ name: "Banner",
2986
+ description:
2987
+ 'Themed inline message. `<Banner tone="error" title="Could not save" message={err.message} action={{ label: "Retry", onPress: save }} onDismiss={() => setErr(null)} />`. THE way to show an error, warning, success or notice that belongs to a place in the widget and stays until it is resolved: a list that failed to load, a form the user cannot submit yet, a "read-only" or "offline" notice. Render it where the problem is — above the list or form it concerns. Use `useToast()` instead for a brief confirmation of something the user just did ("Saved", "Deleted") that needs no decision and may disappear on its own; never both for one event. Its fill, text colour, border and corner radius come from the app\'s theme per tone (Design > Components > Alerts), so never hand-roll a tinted box from `View` + a border + a hex. Props: `tone` ("info" default | "success" | "warning" | "error"), `title` (optional, one short line) and `message` (wraps — never truncate it): text, or an element you built when part of it needs its own styling, `icon` (a lucide name replacing the tone\'s own glyph, or `false` for none), `action` (`{ label, onPress, accessibilityLabel?, testID? }`, ONE action such as Retry), `onDismiss` (pass it to show a close control; you hide the banner in the handler), `dismissAccessibilityLabel` (default "Dismiss" — pass a translated one), `style` (spacing around it), `testID`. An `error` is marked as an alert, and the other tones as a polite status: the web and Android announce them when they appear, while iOS reads the banner in place.',
2988
+ rnComponent: null,
2989
+ docsUrl: null,
2990
+ },
2909
2991
  {
2910
2992
  name: "Accordion",
2911
2993
  description:
@@ -3214,7 +3296,7 @@ const MANIFEST_SCHEMA = {
3214
3296
  type: "object",
3215
3297
  required: false,
3216
3298
  description:
3217
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 8 tables, 24 columns per table. RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 8 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation).",
3299
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 8 tables, 24 columns per table. RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 8 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table.",
3218
3300
  },
3219
3301
  translations: {
3220
3302
  type: "object",
@@ -3365,10 +3447,11 @@ const WIDGET_CONTEXT_SHAPE = {
3365
3447
  "{ me(), users: { list(query?) -> Promise<{ data, meta }>, get(id), invite(body), deactivate(id), reactivate(id) }, " +
3366
3448
  "groups: { list(query?) -> Promise<{ data, meta }>, create(body), remove(id), addMember(groupId, userId), removeMember(groupId, userId), listMine() }, " +
3367
3449
  "invites: { list(), revoke(id), resend(id) }, " +
3368
- "bankid: { status() -> { linked, available }, startLink() -> { order_ref, qr, ... }, collect(orderRef), cancel(orderRef), unlink() } }. " +
3369
- "users backs useDirectory() + useUsers(); groups backs useGroups(); invites backs useInvites() (list/resend/revoke pending invites, gated by users.write:* + the users.write capability); bankid backs useBankIdLink() (REQ-BANKID-AUTH — self-service account linking, JWT-gated, no widget scope). List methods return the { data, meta } envelope verbatim (hooks unwrap res.data); rows/bodies are snake_case. Reads gated by directory.read:users / users.read:* / groups.read:*; mutations by users.write:* / groups.write:* (destructive user removal by users.delete:*).",
3450
+ "bankid: { status() -> { linked, available }, startLink() -> { order_ref, qr, ... }, collect(orderRef), cancel(orderRef), unlink() }, " +
3451
+ "presence: { online(tableId, recordIds) -> { data: [{ record_id, online_user_ids, online_count }] }, me() -> { show_online }, setShowOnline(bool) -> { show_online } } }. " +
3452
+ "users backs useDirectory() + useUsers(); groups backs useGroups(); invites backs useInvites() (list/resend/revoke pending invites, gated by users.write:* + the users.write capability); bankid backs useBankIdLink() (REQ-BANKID-AUTH — self-service account linking, JWT-gated, no widget scope); presence backs useOnlineMembers() + useOnlineVisibility() (session-gated, no scope header). List methods return the { data, meta } envelope verbatim (hooks unwrap res.data); rows/bodies are snake_case. Reads gated by directory.read:users / users.read:* / groups.read:*; mutations by users.write:* / groups.write:* (destructive user removal by users.delete:*).",
3370
3453
  required: true,
3371
- fields: { users: "object", groups: "object", invites: "object", bankid: "object" },
3454
+ fields: { users: "object", groups: "object", invites: "object", bankid: "object", presence: "object" },
3372
3455
  },
3373
3456
  assets: {
3374
3457
  description:
@@ -5460,7 +5543,14 @@ const CONTRACT = deepFreeze({
5460
5543
  // and `useInactiveUsers` read user activity through the new
5461
5544
  // `ctx.directory.users.activity` / `.inactive` / `.remind`, behind the
5462
5545
  // new `users.activity:*` scope.
5463
- version: "1.164.0",
5546
+ // 1.165.0: additive (sc-11025) — `useOnlineMembers(tableId, recordIds)`
5547
+ // and `useOnlineVisibility()` read who of a record's members is online
5548
+ // and the viewer's own switch, through the new `ctx.directory.presence`.
5549
+ // A `datastoreTemplate` table may declare `presence: true`.
5550
+ // 1.166.0: additive (sc-10927) — the `Banner` primitive (a themed inline
5551
+ // error, warning, success or notice) and the `alert` component scope it
5552
+ // reads.
5553
+ version: "1.166.0",
5464
5554
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
5465
5555
  hooks: HOOKS,
5466
5556
  primitives: PRIMITIVES,
package/dist/host.d.ts CHANGED
@@ -39,6 +39,12 @@ export type ThemeWidgetStyles = Record<string, ThemeComponentStyle>;
39
39
  */
40
40
  export function normaliseThemeComponents(raw: unknown): ThemeComponents;
41
41
 
42
+ /**
43
+ * What each token of the `alert` component scope resolves to while unset,
44
+ * keyed by token name: the values `<Banner>` paints an unthemed app with.
45
+ */
46
+ export function bannerScopeDefaults(theme: unknown): Record<string, string | number>;
47
+
42
48
  /** Minimum contrast: `text` for labels (WCAG 1.4.3), `boundary` for edges (1.4.11). */
43
49
  export const INK_CONTRAST: Readonly<{ text: number; boundary: number }>;
44
50
 
package/dist/host.js CHANGED
@@ -55,6 +55,10 @@ export {
55
55
  TOAST_DEFAULTS,
56
56
  } from "./toast-host.js";
57
57
 
58
+ // What each `alert` scope token resolves to while unset, for the Studio's
59
+ // Design page to preview beside its controls.
60
+ export { bannerScopeDefaults } from "./banner-tokens.js";
61
+
58
62
  // REQ-NAV-STRUCTURE: the navigation resolver both hosts draw their chrome from.
59
63
  // `normaliseNavigation` turns a stored `theme_config.navigation` block into the
60
64
  // resolved `{ menuType }` — always `sidebar` since sc-7352 retired the other
package/dist/index.d.ts CHANGED
@@ -235,6 +235,12 @@ export interface WidgetDatastoreTemplateTable {
235
235
  suffix: string;
236
236
  /** REQ-ACL-05: when true, the row creator gets full RWD+G on the new record. */
237
237
  grantCreatorPermissions?: boolean;
238
+ /**
239
+ * When true, the people who share a row see which of each other are online
240
+ * (`useOnlineMembers`), while the workspace records user activity. An
241
+ * upgrade that declares it turns it on for the existing table.
242
+ */
243
+ presence?: boolean;
238
244
  /**
239
245
  * REQ-TEMPLATES-ACL: optional table-level public grant. Omitted means
240
246
  * the table starts purely per-record (record-level grants are the only
@@ -1118,6 +1124,48 @@ export function useInactiveUsers(query?: {
1118
1124
  remind(id: string, message: { title: string; body: string }): Promise<void>;
1119
1125
  };
1120
1126
 
1127
+ /** One record's online members, as `useOnlineMembers` reports them. */
1128
+ export interface RecordOnlineMembers {
1129
+ /** At most 100 ids; `online_count` counts them all. */
1130
+ online_user_ids: string[];
1131
+ online_count: number;
1132
+ }
1133
+
1134
+ /**
1135
+ * Who is online among the members of records the viewer is a member of, on a
1136
+ * table that shows its members' online status (template `presence: true` or
1137
+ * the Studio table setting). Members hold their own read grant, given by a
1138
+ * person; a record the viewer only reads answers with nobody. `supported` is
1139
+ * false while the workspace does not record activity, the table has not opted
1140
+ * in, the viewer hides their own status, or in a preview: then show no online
1141
+ * state at all. Refreshes every minute while the app is in front.
1142
+ */
1143
+ export function useOnlineMembers(
1144
+ tableId: string | null | undefined,
1145
+ recordIds: string[] | null | undefined,
1146
+ ): {
1147
+ supported: boolean;
1148
+ /** User ids online across the records. */
1149
+ online: Set<string>;
1150
+ byRecord: Record<string, RecordOnlineMembers>;
1151
+ loading: boolean;
1152
+ /** `reason` when refused: ACTIVITY_UNAVAILABLE, ACTIVITY_DISABLED, ONLINE_STATUS_HIDDEN, PRESENCE_NOT_ENABLED or FORBIDDEN. */
1153
+ error: DirectoryError | null;
1154
+ refetch(): Promise<void>;
1155
+ };
1156
+
1157
+ /** The viewer's own "Show when I'm online" switch; offer it only when `supported`. */
1158
+ export function useOnlineVisibility(): {
1159
+ supported: boolean;
1160
+ /** Null until known. */
1161
+ showOnline: boolean | null;
1162
+ loading: boolean;
1163
+ saving: boolean;
1164
+ error: DirectoryError | null;
1165
+ /** Save the switch; every switch and useOnlineMembers on the page follows. Rejects with DirectoryError. */
1166
+ setShowOnline(showOnline: boolean): Promise<void>;
1167
+ };
1168
+
1121
1169
  export function useDatastoreMutation<T = unknown>(
1122
1170
  table: string,
1123
1171
  ): MutationApi<T>;
@@ -3523,6 +3571,40 @@ export const Tabs: (props: {
3523
3571
  testID?: string;
3524
3572
  }) => any;
3525
3573
 
3574
+ export type BannerTone = "info" | "success" | "warning" | "error";
3575
+
3576
+ /**
3577
+ * Themed inline message: an error, warning, success or notice that stays in
3578
+ * place until it is resolved. Its fill, text colour, border and corners come
3579
+ * from the theme's `alert` scope, so every banner in the app matches. An
3580
+ * `error` is marked as an alert and the other tones as a polite status: the
3581
+ * web and Android announce them when they appear, iOS reads them in place.
3582
+ * For a brief confirmation that may disappear on its own, use `useToast()`.
3583
+ *
3584
+ * @example
3585
+ * <Banner tone="error" message={error.message} action={{ label: "Retry", onPress: refetch }} />
3586
+ */
3587
+ export const Banner: (props: {
3588
+ /** Default "info". */
3589
+ tone?: BannerTone;
3590
+ /** Text is themed; an element renders as given. */
3591
+ title?: ReactNode;
3592
+ /** Text wraps onto as many lines as it needs; an element renders as given. */
3593
+ message?: ReactNode;
3594
+ /** A lucide name replacing the tone's glyph, or `false` for none. */
3595
+ icon?: string | false | null;
3596
+ action?: { label: string; onPress: () => void; accessibilityLabel?: string; testID?: string };
3597
+ /** Shows a close control; hide the banner in the handler. */
3598
+ onDismiss?: () => void;
3599
+ /** Default "Dismiss". */
3600
+ dismissAccessibilityLabel?: string;
3601
+ /** For hosts rendering outside a widget context; widgets omit it. */
3602
+ theme?: any;
3603
+ style?: any;
3604
+ /** The action and close control default to `<testID>-action` / `<testID>-dismiss`. */
3605
+ testID?: string;
3606
+ }) => any;
3607
+
3526
3608
  /**
3527
3609
  * Themed collapsible sections. The surface comes from the theme's `card`
3528
3610
  * scope and the headers and dividers from its `list` scope, so every
package/dist/index.js CHANGED
@@ -129,6 +129,8 @@ export {
129
129
  useUserActivity,
130
130
  useInactiveUsers,
131
131
  } from "./stats-hooks.js";
132
+ // sc-11025 — one source, bound to how each platform says the app is in front.
133
+ export { useOnlineMembers, useOnlineVisibility } from "./presence.js";
132
134
  // sc-6607 — `<Overlay>` is one shared component (./overlay-view.js) bound to
133
135
  // each platform's primitives, so a widget's modal escapes its container box
134
136
  // identically on the Player and the Expo export.
@@ -268,6 +270,8 @@ export { Accordion, AccordionItem } from "./accordion.js";
268
270
  export { Tabs } from "./tabs.js";
269
271
  // Themed loading states; follow the theme's `loading` scope.
270
272
  export { Spinner, Skeleton } from "./loading.js";
273
+ // A themed inline message; follows the theme's `alert` scope.
274
+ export { Banner } from "./banner.js";
271
275
  // The semantic text tiers, shared with the built-in widgets.
272
276
  export {
273
277
  textRoleStyle,
@@ -127,6 +127,8 @@ export {
127
127
  useUserActivity,
128
128
  useInactiveUsers,
129
129
  } from "./stats-hooks.js";
130
+ // sc-11025 — see the note on the web mirror in ./index.js.
131
+ export { useOnlineMembers, useOnlineVisibility } from "./presence.native.js";
130
132
  // sc-6607 — see the note on the web mirror in ./index.js.
131
133
  export { Overlay } from "./overlay.native.js";
132
134
  // sc-8104 — see the note on the web mirror in ./index.js.
@@ -261,6 +263,8 @@ export { Accordion, AccordionItem } from "./accordion.native.js";
261
263
  export { Tabs } from "./tabs.native.js";
262
264
  // Themed loading states; follow the theme's `loading` scope.
263
265
  export { Spinner, Skeleton } from "./loading.native.js";
266
+ // A themed inline message; follows the theme's `alert` scope.
267
+ export { Banner } from "./banner.native.js";
264
268
  // The semantic text tiers, shared with the built-in widgets.
265
269
  export {
266
270
  textRoleStyle,
@@ -0,0 +1,239 @@
1
+ // sc-11025 — who is online among the people who share a record, and the
2
+ // viewer's own "Show when I'm online" switch. One source for both entries:
3
+ // ./presence.js and ./presence.native.js only bind how each platform says
4
+ // the app is in front.
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6
+ import { toDirectoryError, useRefresh, useWidgetContextOrThrow } from "./hooks.js";
7
+
8
+ // Recorded activity moves about once a minute, so polling faster shows nothing new.
9
+ export const PRESENCE_REFRESH_MS = 60 * 1000;
10
+ // Before the feature reaches a workspace, ask again only this seldom.
11
+ export const PRESENCE_UNAVAILABLE_RETRY_MS = 10 * 60 * 1000;
12
+ // The server answers at most this many records per call.
13
+ const RECORDS_PER_CALL = 100;
14
+
15
+ const NO_RECORDS = Object.freeze({});
16
+
17
+ /**
18
+ * How a read leaves the hook asking again. `live`: every minute and on
19
+ * return. `refused` (setting off, hidden, table not opted in): on return
20
+ * only. `unavailable` (not released): every ten minutes, never on return.
21
+ */
22
+ const CADENCE = {
23
+ live: { everyMs: PRESENCE_REFRESH_MS, onReturn: true },
24
+ refused: { everyMs: null, onReturn: true },
25
+ unavailable: { everyMs: PRESENCE_UNAVAILABLE_RETRY_MS, onReturn: false },
26
+ };
27
+
28
+ function cadenceAfter(error) {
29
+ if (!error || !(error.status === 401 || error.status === 403)) return "live";
30
+ return error.reason === "ACTIVITY_UNAVAILABLE" ? "unavailable" : "refused";
31
+ }
32
+
33
+ // A changed switch re-reads every presence read and updates every switch.
34
+ const presenceReaders = new Set();
35
+ const visibilityHolders = new Set();
36
+
37
+ function presenceClient(ctx) {
38
+ const presence = ctx.directory && ctx.directory.presence;
39
+ return presence && typeof presence.online === "function" ? presence : null;
40
+ }
41
+
42
+ function uniqueIds(recordIds) {
43
+ if (!Array.isArray(recordIds)) return [];
44
+ return [...new Set(recordIds.filter((id) => typeof id === "string" && id))].sort();
45
+ }
46
+
47
+ async function readOnline(presence, tableId, ids) {
48
+ const calls = [];
49
+ for (let i = 0; i < ids.length; i += RECORDS_PER_CALL) {
50
+ calls.push(presence.online(tableId, ids.slice(i, i + RECORDS_PER_CALL)));
51
+ }
52
+ const pages = await Promise.all(calls);
53
+ const byRecord = {};
54
+ for (const page of pages) {
55
+ for (const entry of (page && Array.isArray(page.data) ? page.data : [])) {
56
+ byRecord[entry.record_id] = {
57
+ online_user_ids: entry.online_user_ids,
58
+ online_count: entry.online_count,
59
+ };
60
+ }
61
+ }
62
+ return byRecord;
63
+ }
64
+
65
+ /** Runs `onTick` on the cadence's timer while in front, and on return when it says so. */
66
+ function useWhileInFront(appInFront, onTick, cadence) {
67
+ const tickRef = useRef(onTick);
68
+ tickRef.current = onTick;
69
+ const { everyMs, onReturn } = CADENCE[cadence];
70
+ useEffect(() => {
71
+ let timer = null;
72
+ let inFront = appInFront.isActive();
73
+ const start = () => {
74
+ if (everyMs && !timer) timer = setInterval(() => tickRef.current(), everyMs);
75
+ };
76
+ const stop = () => {
77
+ clearInterval(timer);
78
+ timer = null;
79
+ };
80
+ if (inFront) start();
81
+ const unsubscribe = appInFront.subscribe((active) => {
82
+ if (active === inFront) return;
83
+ inFront = active;
84
+ if (!active) return stop();
85
+ if (onReturn) tickRef.current();
86
+ return start();
87
+ });
88
+ return () => {
89
+ stop();
90
+ if (typeof unsubscribe === "function") unsubscribe();
91
+ };
92
+ }, [appInFront, everyMs, onReturn]);
93
+ }
94
+
95
+ /**
96
+ * Bind the presence hooks to a platform's notion of "the app is in front":
97
+ * `{ isActive(): boolean, subscribe(onChange(active)): unsubscribe }`.
98
+ */
99
+ export function makePresenceHooks(appInFront) {
100
+ /**
101
+ * Who is online among the members of each record the viewer is a member
102
+ * of. Returns `{ supported, online, byRecord, loading, error, refetch }`:
103
+ * `online` is a Set of the user ids online across the records,
104
+ * `byRecord[id]` is `{ online_user_ids, online_count }` (ids capped at 100).
105
+ * `supported` is true only once the workspace answered; while it is false
106
+ * the widget shows no online state at all.
107
+ */
108
+ function useOnlineMembers(tableId, recordIds) {
109
+ const ctx = useWidgetContextOrThrow("useOnlineMembers");
110
+ const presence = presenceClient(ctx);
111
+ const presenceRef = useRef(presence);
112
+ presenceRef.current = presence;
113
+ const hasPresence = presence !== null;
114
+ const ids = uniqueIds(recordIds);
115
+ const key = tableId && ids.length > 0 ? `${tableId}:${ids.join(",")}` : null;
116
+ const requestRef = useRef(null);
117
+ requestRef.current = key === null ? null : { tableId, ids };
118
+ const [state, setState] = useState({ tableId: null, supported: false, byRecord: NO_RECORDS, error: null });
119
+ const runRef = useRef(0);
120
+
121
+ const read = useCallback(async () => {
122
+ const run = ++runRef.current;
123
+ const client = presenceRef.current;
124
+ const request = requestRef.current;
125
+ if (!client || !request) {
126
+ setState((prev) => (prev.tableId === null ? prev : { tableId: null, supported: false, byRecord: NO_RECORDS, error: null }));
127
+ return;
128
+ }
129
+ try {
130
+ const byRecord = await readOnline(client, request.tableId, request.ids);
131
+ if (runRef.current === run) setState({ tableId: request.tableId, supported: true, byRecord, error: null });
132
+ } catch (err) {
133
+ if (runRef.current !== run) return;
134
+ const error = toDirectoryError(err);
135
+ setState((prev) =>
136
+ cadenceAfter(error) === "live"
137
+ ? { ...(prev.tableId === request.tableId ? prev : { supported: false, byRecord: NO_RECORDS }), tableId: request.tableId, error }
138
+ : { tableId: request.tableId, supported: false, byRecord: NO_RECORDS, error },
139
+ );
140
+ }
141
+ }, []);
142
+
143
+ useEffect(() => {
144
+ read();
145
+ // eslint-disable-next-line react-hooks/exhaustive-deps
146
+ }, [key, hasPresence]);
147
+ useEffect(() => {
148
+ presenceReaders.add(read);
149
+ return () => presenceReaders.delete(read);
150
+ }, [read]);
151
+ useRefresh(read);
152
+ useWhileInFront(appInFront, read, key !== null && hasPresence ? cadenceAfter(state.error) : "refused");
153
+
154
+ // Another set of records of the same table keeps showing the last answer.
155
+ const current = key !== null && state.tableId === tableId;
156
+ const byRecord = current ? state.byRecord : NO_RECORDS;
157
+ const online = useMemo(
158
+ () => new Set(Object.values(byRecord).flatMap((entry) => entry.online_user_ids || [])),
159
+ [byRecord],
160
+ );
161
+ return {
162
+ supported: current && state.supported,
163
+ online,
164
+ byRecord,
165
+ loading: key !== null && hasPresence && !current,
166
+ error: current ? state.error : null,
167
+ refetch: read,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * The viewer's own "Show when I'm online" switch: `{ supported, showOnline,
173
+ * loading, saving, error, setShowOnline }`. `supported` is false where the
174
+ * workspace shows nobody online, so the switch is not offered there.
175
+ * `setShowOnline(bool)` saves it, updates every switch on the page and
176
+ * re-asks every presence read; hiding also hides everyone from the viewer.
177
+ */
178
+ function useOnlineVisibility() {
179
+ const ctx = useWidgetContextOrThrow("useOnlineVisibility");
180
+ const presence = presenceClient(ctx);
181
+ const presenceRef = useRef(presence);
182
+ presenceRef.current = presence;
183
+ const hasPresence = presence !== null;
184
+ const [state, setState] = useState({ loading: hasPresence, supported: false, showOnline: null, error: null });
185
+ const [saving, setSaving] = useState(false);
186
+
187
+ const read = useCallback(async () => {
188
+ const client = presenceRef.current;
189
+ if (!client || typeof client.me !== "function") {
190
+ setState({ loading: false, supported: false, showOnline: null, error: null });
191
+ return;
192
+ }
193
+ try {
194
+ const own = await client.me();
195
+ setState({ loading: false, supported: true, showOnline: own.show_online === true, error: null });
196
+ } catch (err) {
197
+ const error = toDirectoryError(err);
198
+ setState((prev) =>
199
+ cadenceAfter(error) === "live"
200
+ ? { ...prev, loading: false, error }
201
+ : { loading: false, supported: false, showOnline: null, error },
202
+ );
203
+ }
204
+ }, []);
205
+
206
+ useEffect(() => {
207
+ read();
208
+ // eslint-disable-next-line react-hooks/exhaustive-deps
209
+ }, [hasPresence]);
210
+ useRefresh(read);
211
+ useEffect(() => {
212
+ const holder = (showOnline) => setState((prev) => ({ ...prev, showOnline, error: null }));
213
+ visibilityHolders.add(holder);
214
+ return () => visibilityHolders.delete(holder);
215
+ }, []);
216
+
217
+ const setShowOnline = useCallback(async (showOnline) => {
218
+ const client = presenceRef.current;
219
+ if (!client || typeof client.setShowOnline !== "function") {
220
+ throw new Error("useOnlineVisibility: host did not inject ctx.directory.presence.setShowOnline");
221
+ }
222
+ setSaving(true);
223
+ let saved;
224
+ try {
225
+ saved = (await client.setShowOnline(showOnline === true)).show_online === true;
226
+ } catch (err) {
227
+ throw toDirectoryError(err);
228
+ } finally {
229
+ setSaving(false);
230
+ }
231
+ for (const holder of visibilityHolders) holder(saved);
232
+ for (const reader of presenceReaders) reader();
233
+ }, []);
234
+
235
+ return { ...state, saving, setShowOnline };
236
+ }
237
+
238
+ return { useOnlineMembers, useOnlineVisibility };
239
+ }
@@ -0,0 +1,18 @@
1
+ // sc-11025 — the presence hooks bound to the web: the page is in front while
2
+ // it is visible.
3
+ import { makePresenceHooks } from "./presence-hooks.js";
4
+
5
+ const visible = () =>
6
+ typeof document === "undefined" || document.visibilityState !== "hidden";
7
+
8
+ const appInFront = {
9
+ isActive: visible,
10
+ subscribe(onChange) {
11
+ if (typeof document === "undefined") return () => {};
12
+ const handler = () => onChange(visible());
13
+ document.addEventListener("visibilitychange", handler);
14
+ return () => document.removeEventListener("visibilitychange", handler);
15
+ },
16
+ };
17
+
18
+ export const { useOnlineMembers, useOnlineVisibility } = makePresenceHooks(appInFront);
@@ -0,0 +1,16 @@
1
+ // sc-11025 — the presence hooks bound to the device: the app is in front
2
+ // unless AppState says "background" ("inactive" is a passing overlay).
3
+ import { AppState } from "react-native";
4
+ import { makePresenceHooks } from "./presence-hooks.js";
5
+
6
+ const inFront = (state) => state !== "background";
7
+
8
+ export const appInFront = {
9
+ isActive: () => inFront(AppState.currentState),
10
+ subscribe(onChange) {
11
+ const subscription = AppState.addEventListener("change", (state) => onChange(inFront(state)));
12
+ return () => subscription?.remove();
13
+ },
14
+ };
15
+
16
+ export const { useOnlineMembers, useOnlineVisibility } = makePresenceHooks(appInFront);
@@ -0,0 +1,28 @@
1
+ // The label colour for a fill an author chose. Picked by contrast between a
2
+ // FIXED dark and a fixed light: the theme's own text colour is light on a
3
+ // dark theme, so it cannot stand in for "the dark option".
4
+
5
+ import { DEFAULT_THEME_TOKENS } from "./_theme-tokens.js";
6
+ import { contrastRatio, hexAlphaPercent, isHexColor, mixHex } from "./contract.js";
7
+
8
+ export const INK_DARK = DEFAULT_THEME_TOKENS.colors.onSurface;
9
+ export const INK_LIGHT = "#ffffff";
10
+
11
+ /** A fill as the opaque colour it shows once painted over `surface`. */
12
+ export function compositeOver(fill, surface) {
13
+ if (!isHexColor(fill)) return fill;
14
+ const backdrop = isHexColor(surface) ? surface : DEFAULT_THEME_TOKENS.colors.surface;
15
+ return mixHex(backdrop, fill, hexAlphaPercent(fill) / 100);
16
+ }
17
+
18
+ /**
19
+ * Whichever of the dark and light ink has the higher contrast on `fill`. A
20
+ * translucent fill is measured as it appears over `surface`.
21
+ */
22
+ export function readableInk(fill, surface) {
23
+ if (!isHexColor(fill)) return INK_DARK;
24
+ const painted = compositeOver(fill, surface);
25
+ return contrastRatio(painted, INK_DARK) >= contrastRatio(painted, INK_LIGHT)
26
+ ? INK_DARK
27
+ : INK_LIGHT;
28
+ }
@@ -3,7 +3,8 @@
3
3
  // the same numbers and tests can pin them without a renderer.
4
4
 
5
5
  import { DEFAULT_THEME_TOKENS } from "./_theme-tokens.js";
6
- import { CONTRACT, contrastRatio } from "./contract.js";
6
+ import { CONTRACT } from "./contract.js";
7
+ import { readableInk } from "./readable-ink.js";
7
8
 
8
9
  export const TAB_STYLES = CONTRACT.themeComponentTabStyles;
9
10
 
@@ -56,7 +57,7 @@ export function resolveTabsTokens(theme, overrides) {
56
57
  pick(overrides, scope, "activeTextColor") ??
57
58
  (style === "pill"
58
59
  ? ownAccent
59
- ? readableOn(ownAccent, colors)
60
+ ? readableInk(ownAccent, colors.surface)
60
61
  : colors.onPrimary
61
62
  : activeColor),
62
63
  textColor: pick(overrides, scope, "textColor") ?? colors.onSurfaceMuted,
@@ -66,10 +67,3 @@ export function resolveTabsTokens(theme, overrides) {
66
67
  rule: colors.border,
67
68
  };
68
69
  }
69
-
70
- // A chosen accent carries the label that reads best on it, dark or light.
71
- function readableOn(fill, colors) {
72
- const dark = colors.onSurface;
73
- const light = "#ffffff";
74
- return contrastRatio(fill, dark) >= contrastRatio(fill, light) ? dark : light;
75
- }