@notis_ai/cli 0.2.27 → 0.2.29

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 (53) hide show
  1. package/README.md +2 -2
  2. package/config/notis_app_design_rules.json +5 -123
  3. package/dist/agent-hooks/notis-agent-hook.mjs +453 -109
  4. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  5. package/dist/base-skills/notis-spaces/SKILL.md +13 -19
  6. package/dist/base-skills/notis-spaces/references/design.md +11 -45
  7. package/dist/base-skills/notis-spaces/references/sdk.md +94 -68
  8. package/dist/base-skills/notis-spaces/references/views.md +12 -1
  9. package/dist/sdk/src/components/NotisCommentBoundary.tsx +43 -83
  10. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +28 -8
  11. package/dist/sdk/src/components/SelectionActionBar.tsx +383 -0
  12. package/dist/sdk/src/components/selectionId.ts +6 -0
  13. package/dist/sdk/src/hooks/useCollectionInteractions.ts +5 -2
  14. package/dist/sdk/src/runtime.ts +5 -0
  15. package/dist/sdk/src/space.ts +4 -0
  16. package/dist/sdk/src/ui/icons.tsx +11 -2
  17. package/dist/sdk/src/words/actions.ts +9 -1
  18. package/dist/sdk/src/words/keymap.ts +3 -0
  19. package/dist/space-harness/host.js +181 -141
  20. package/dist/space-sdk/dist/{chunk-BWHAORT4.js → chunk-BFGB6XXC.js} +2 -2
  21. package/dist/space-sdk/dist/index.js +2 -2
  22. package/dist/space-sdk/dist/ui.js +14 -11
  23. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -10
  24. package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +7 -0
  25. package/dist/space-sdk/src/runtime.d.ts +5 -0
  26. package/dist/space-sdk/src/space.ts +4 -0
  27. package/dist/space-sdk/src/tailwind-candidates.d.ts +126 -17
  28. package/dist/space-sdk/src/ui/blocks/DataTable.d.ts +86 -0
  29. package/dist/space-sdk/src/ui/blocks/InfoTip.d.ts +25 -0
  30. package/dist/space-sdk/src/ui/blocks/Meter.d.ts +39 -0
  31. package/dist/space-sdk/src/ui/blocks/blocks.d.ts +1 -1
  32. package/dist/space-sdk/src/ui/blocks/index.d.ts +6 -0
  33. package/dist/space-sdk/src/ui/charts/Chart.d.ts +15 -2
  34. package/dist/space-sdk/src/ui/charts/StatRow.d.ts +4 -3
  35. package/dist/space-sdk/src/ui/charts/chartData.d.ts +6 -0
  36. package/dist/space-sdk/src/ui/comments/useComments.d.ts +19 -1
  37. package/dist/space-sdk/src/ui/icons.d.ts +1 -1
  38. package/dist/space-sdk/src/ui/index.d.ts +2 -2
  39. package/dist/space-sdk/src/ui/list/Row.d.ts +10 -3
  40. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +14 -0
  41. package/dist/space-sdk/src/words/actions.ts +9 -1
  42. package/dist/space-sdk/src/words/keymap.ts +3 -0
  43. package/dist/view-renderer/dist/host.js +253 -213
  44. package/dist/view-renderer/src/renderer.js +38 -2
  45. package/package.json +3 -3
  46. package/src/command-specs/computer.js +3 -3
  47. package/src/command-specs/spaces.js +28 -8
  48. package/src/command-specs/tools.js +1 -1
  49. package/src/runtime/app-platform.js +74 -11
  50. package/src/runtime/space-fixture-broker.js +23 -2
  51. package/src/runtime/space-verification.js +62 -10
  52. package/template/components/ui/button.tsx +1 -1
  53. package/template/components/ui/native-select.tsx +1 -1
@@ -1 +1 @@
1
- {"schema":1,"stamp":1794314726,"commit":"7fda8d9020cc8bd18b3698e1ca4eb134d399b157"}
1
+ {"schema":1,"stamp":1794497594,"commit":"ca87a334f8e4899af09347a9c5362d62856c6e7c"}
@@ -128,39 +128,33 @@ with them. When it is not, write your own layout on the hooks and blocks
128
128
  `EmptyState`, `Notice`): your markup, the host's keys and words
129
129
  ([the sample](references/views.md#a-view-of-your-own)). Both are normal
130
130
  choices; do not bend a request into `ListReader` because it is the closest
131
- piece, and do not hand-roll what a piece already does well.
132
-
133
- When you start from a piece, change it as shallowly as the design allows:
134
- options (`density`, `openAs`, `layout`, `look`, `autoOpen`, `search`,
135
- `actions`, an action's `key`), then slots (`row`, `reader`, `tabs`, `create`,
136
- `viewMenu`, `infoLine`, `readerLabel`, `readerActions`, `crumbLabel`,
137
- `renderTile`, `empty`), then your own layout on the hooks. A rewrite of a piece
138
- stops receiving that piece's fixes, so do it when the design needs it, not by
139
- default.
131
+ piece, and do not hand-roll what a piece already does well. A piece you rewrite
132
+ stops receiving that piece's fixes.
140
133
 
141
134
  ## Rules the pieces cannot hold for you
142
135
 
136
+ - Sidebar children are for short lists people navigate: a few sub-Spaces, or a
137
+ `collection` whose records stay few (folders of notes). A database that grows
138
+ every week is listed in the view, never as sidebar rows
139
+ ([Records in the sidebar](references/views.md#records-in-the-sidebar)).
143
140
  - Standard actions (`archive`, `complete`, `star`, `delete`...) take Notis's
144
141
  words, key and toast: give only `id` and `run`. A Space's own action, label or
145
142
  text brings an `{ en, fr }` pair; no English literal in JSX.
146
143
  - Never add `keydown` listeners on `window` or `document`; use `useShortcut` or
147
144
  the hooks above. Never portal to `document.body`; use `Menu`, `Popover`,
148
145
  `Tooltip`, or `useLayerRoot()` as the container.
149
- - No in-page title: the host top bar shows Space / view and the open item. Never
150
- render an `h1`, a page description, a heading block or a second search field;
151
- `ListReader` `search` uses the top bar. The Space fills the frame; a centred
152
- column is for a reading, writing or focus layout.
153
- - Colours from theme tokens (`hsl(var(--primary))`, `text-foreground`,
154
- `bg-muted`), never hex, palette hues or raw rgb. A highlight is a ring on all
146
+ - The host top bar shows Space / view and the open item, and `ListReader`
147
+ `search` uses it, so a Space draws no second search field. The Space fills
148
+ the frame.
149
+ - Colours from the theme tokens of the host and `toolkit.css`, never hex,
150
+ palette hues or raw rgb. A highlight is a ring on all
155
151
  four sides, never a coloured or thicker edge on one side. No fixed viewport
156
152
  heights (`h-screen`, `vh`): use `h-full`, `flex-1`, `min-h-0`.
157
153
  - The design check (run by every `notis spaces build`, and by the server on
158
154
  publish) and `notis spaces verify` (390 and 1440 px, EN and FR) must pass
159
155
  before any deploy. Its errors protect the host: frame, theme, keys, layers and
160
- words. Its warnings are the default look (borders, shadows, gradients,
161
- dividers, serif, a centred column, tiles outside galleries) and the toolkit
162
- pieces a hand-made pattern could use; they never block. Keep a warning when
163
- the view's design calls for it, and fix it when it was an accident.
156
+ words. Its warnings name the toolkit pieces a hand-made pattern could
157
+ use; they never block.
164
158
  - A Space updates in place: pull it, change it, deploy it to the same Space ID.
165
159
  Never ship a change as a new Space or a Store copy.
166
160
 
@@ -2,47 +2,18 @@
2
2
 
3
3
  Decide what the view is for before choosing how to build it: what the person
4
4
  does there, what they look at first, how dense or calm it should be. Then take
5
- what fits from `@notis/sdk/ui`: a stock piece when the view is a stock shape, or
6
- your own layout on the hooks and blocks when it is not (the choice in
7
- [SKILL.md](../SKILL.md#three-layers)). Either way the host frame, theme tokens,
8
- keyboard engine and EN/FR words stay Notis's.
9
-
10
- ## Pick the piece
11
-
12
- | The view shows | Start from |
13
- | --- | --- |
14
- | A list beside an open item (tickets, notes, inbox) | `ListReader` ([sample](views.md#write-the-view)) |
15
- | The same records as a table | `ListReader` with `layout: 'table'` |
16
- | A gallery where each item has a picture or a mark (competitors, integrations, skills to discover) | `ListReader` with `layout: 'tiles'` and `renderTile` |
17
- | Items on dates | `CalendarView` (month, week, agenda) |
18
- | Items over time, by lane | `TimelineView` |
19
- | Items by stage, moved from one stage to the next (a sales funnel, a production pipeline) | `BoardView`: one column per stage, `onMove` to move tiles |
20
- | Numbers over a period | `Section kind="bar"` with `PeriodPicker`, `StatRow`, `Section kind="chart"` with `Chart`, `Section kind="data"` with `ChartTable`, top to bottom, full width |
21
- | One record as the page | `DocumentPage` (see [SDK](sdk.md#first-party-record-components)). Pick its `width` for the page: `standard` (the default) is a centred 900 px reading column for a page read as text, `wide` (1200 px) or `full` for a record that is a working surface such as a wide table or board |
22
- | A form or settings page | `Section kind="form"`, `Button`, `NativeSelect`, `SegmentedControl`, `Notice`, `EmptyState` |
23
- | A list on your own layout | `useListKeys`, `useSelection`, `Row`, `SelectionBar`, `Panels` |
24
- | Files or pictures attached to an item, or a picture to open full screen | `AttachmentGallery` (opens `ImageViewer` on its images); `ImageViewer` alone for one picture ([SDK](sdk.md#toolkit-pieces)) |
25
- | Anything none of these fit: one record at a time, a focus or practice screen, a canvas, a planner, a page laid out like a magazine, a mix of blocks | Your own layout on `useShortcut`, `Section`, `Button`, `EmptyState`, `Notice` and the hooks above ([sample](views.md#a-view-of-your-own)) |
26
-
27
- The table is a starting point, not a menu to fit the request into. If a stock
28
- piece would make the view worse for what the person does there, write your own.
5
+ what fits from `@notis/sdk/ui` ([SDK](sdk.md#toolkit-pieces)). The host frame,
6
+ theme tokens, keyboard engine and EN/FR words stay Notis's.
29
7
 
30
8
  Floating UI comes from `Menu`, `Popover` and `Tooltip`; they open inside the
31
9
  Space and pick up its theme. Open as Side, Center or Full belongs to the list
32
- (`openAs`, `OpenAsMenu`); a Space does not build its own reader frame.
10
+ (`openAs`, `OpenAsMenu`).
33
11
 
34
12
  ## Layout
35
13
 
36
14
  The host top bar shows the title: Space / view with the view icon, and the
37
- description as a tooltip. A Space never renders an h1, a description, a heading
38
- block or its own search field; set `search` on `ListReader`. The Space fills the
39
- frame with no outer padding wrapper; a centred column (`mx-auto` with `max-w-*`)
40
- is for a reading, writing or focus layout, and the reader article gets its
41
- measure from the toolkit. The default look is flat: list toolbars are one 44px
42
- tab row with a "+" at the right end, sections have no boxes. A view of your own
43
- may depart from that look (cards, a border, a shadow, a different type scale)
44
- when its design calls for it; the design check warns so you decide, and never
45
- blocks it.
15
+ description as a tooltip. A Space does not draw its own search field; set
16
+ `search` on `ListReader`. The Space fills the frame.
46
17
 
47
18
  - **Crumb.** An open item adds its name to the top bar crumb ("Product /
48
19
  Tickets / PRO-002") in every open mode; `crumbLabel` on `ListReader` names it,
@@ -66,12 +37,6 @@ blocks it.
66
37
  - **Drag to select.** A list that selects several gets the Manager's marquee
67
38
  for free: a drag from empty space selects the rows under it. Do not build
68
39
  your own.
69
- - **Sections.** A dashboard, form or settings page is a stack of `Section`
70
- kinds, full width: `bar` for the period and filters, `stats`, `chart`, `data`
71
- for a table and `form`. A section title and count sit in its head; the page
72
- itself has no title. Put the bar's pills and picker in its `tabs` slot as
73
- they are: a `TabRow` folds what does not fit into More and other controls
74
- scroll in the one row, so add no wrapper or overflow CSS of your own.
75
40
 
76
41
  Do not rebuild what the host already shows: the sidebar, top bar, title, search
77
42
  field, folder tree, chat, help sheet or selection bar. Let the phone layout come from
@@ -127,14 +92,15 @@ multi-field edit or a destructive confirmation.
127
92
  ## Look at the result
128
93
 
129
94
  `notis spaces build` runs the design check and reports each rule broken by file
130
- and line; the server runs it again on publish. Errors block; warnings are the
131
- default look and the toolkit pieces you could use, and they never block. Passing
132
- it does not prove the design is good. Then run `notis spaces verify`, which draws every view at 390
95
+ and line; the server runs it again on publish. Errors block; warnings name toolkit
96
+ pieces you could use, and they never block. Passing it does not prove the design
97
+ is good. Then run `notis spaces verify`, which draws every view at 390
133
98
  and 1440 px in EN and FR, once with data and once while the reads are still
134
99
  pending, and actually look at both images:
135
100
 
136
- - Does the layout fit what the person does here, or did the request get bent
137
- into the nearest stock piece?
101
+ - Does the first screen answer the one question the person opens the page for,
102
+ and does what needs action stand out?
103
+ - Do counts agree across sections?
138
104
  - Does the view fill the host frame, also while loading?
139
105
  - Does the pending image keep the final layout: same tab row and panes, a
140
106
  skeleton where content will be, no Loading text and no empty state? Fix every
@@ -37,60 +37,6 @@ Text a person writes and reviews:
37
37
  are gone reads Text changed. Do not build your own highlights. Pins on a page
38
38
  use `useComments` with `CommentPane` (see Comments under Toolkit pieces).
39
39
 
40
- ## Records and declared reads
41
-
42
- | API | Use |
43
- | --- | --- |
44
- | `useViewParams<typeof definition>()` | `{params, invalid, missing, declared, ready, setParams}` for declared typed URL params. Unknown names are dropped; invalid values use their declared default. `setParams(changes, {replace?})` changes this view's own params (`null` removes one) and keeps the same Space and record open. |
45
- | `useShown<Row>(name, options?)` | Execute the native list in `shows[name]` with current params. Options: `sorts`, `pageSize`, `offset`, `includeContent`, `allPages` (every page, for a whole count or a local search); rows are in `data?.rows` and the schema revision a write needs in `data?.schema_revision`, with `loading`, `hasData`, `isFetching`, `error`, `refetch` (resolves to the read's error, or null when it succeeded; it never rejects). |
46
- | `useShownAvailable(name)` | Check whether this host exposes the declared native list. A record Site can expose only its exact server-pinned row scope. |
47
- | `useAction<Inputs, Result>(name)` / `useActionQuery<Result>(name, inputs, options?)` | Call a declared action (`call(inputs, options)`); read the result of a declared read action. Never call account-wide tools from a Space. When a read action answers with native rows, pass `rows: { binding, at, query? }` (`at`: the answer field holding them, `''` for a bare list; `query`: the native query it runs) so native writes to that database show in it at once too; without it the read only refreshes after the write. A failed call throws a `SpaceActionError`; its `code` is `rate_limited` when the provider refused it for sending too fast (it did not run, and Notis already waited and retried safe calls), so offer a retry after a few seconds instead of adding your own limiter, and `read_timeout` when a read took too long. |
48
- | `useNativeMutation(binding, operation)` | Insert, update or delete one row of a linked database through the action that declares `LOCAL_NOTIS_DATABASE_INSERT`, `_UPDATE` or `_DELETE` on that binding with `request: { $input: 'request' }`. `mutate(input, {schemaRevision, requestId, showIn?})` returns the receipt (`record_key`, `revision`). The write shows in every list of that database at once, before the server answers: an edited row changes where it is (and moves to its sorted place, or leaves a `useNativeDocuments` read whose filter no longer keeps it), a new row joins the reads whose filter it passes and the `shows` lists named by `showIn` (by default the view's only list over that database), and a delete moves the record to the bin and leaves every list. A failed write puts the server's rows back. Do not keep your own copy of the change on top. One new request ID per effect. An insert action takes no `content_markdown`: insert, then save the body with `useNativeDocumentBody` and the record's revision. |
49
- | `useNativeDelete(binding)` | Trash many rows of one linked database (a deck and its slides, a multi-select). `deleteMany(inputs, {schemaRevision, requestId})` hides every row from the lists at once, runs the writes a few at a time, each with the request ID `${requestId}:${record_key}` (a retry with the same `requestId` replays instead of trashing twice), refreshes the lists once at the end and brings back the rows whose write failed. It never throws for a failed row: it resolves to `{done, failed}`; say how many failed. Use it rather than a loop of `mutate`. |
50
- | `useNativeDocumentBody(binding, recordKey, {readAction, writeAction?, enabled?})` | Markdown body adapter. Keep drafts in the view; save with the original content, record/schema revisions and stable request ID. Rich editing normally uses `DocumentEditor`. |
51
- | `useNotis()` | Host resource, Space labels, route and ready state. Use `resource.id` for the current Space identity. |
52
-
53
- Keep hooks unconditional. `loading` means no first successful read;
54
- `isFetching` includes a silent refresh. Do not copy rows into mount-only state
55
- or clear them on error ([loading rules](design.md#loading-empty-and-error)).
56
- `Skeleton` and `ViewSkeleton` come from `@notis/sdk`; `ViewSkeleton`'s `label`
57
- names what loads (`{ en: 'Loading meetings', fr: 'Chargement des réunions' }`),
58
- said in the Space's language, default Loading content. Its shapes are
59
- measured from the view at verify time and drawn from the release; `skeletonKey`
60
- (default `main`) names the region when a view has several separately loading
61
- parts, and `variant` only draws the fallback before the first measured release.
62
-
63
- For another explicitly idempotent read use `useActionQuery`, or
64
- `useQuery(keyArray, readCallback, { readOnly: true })` with every input in the
65
- key. Call declared read actions inside a custom read with
66
- `{ readOnly: true, dedupe: true }`; never mark a whole tool family read-only.
67
- `useQueryClient().prefetch(...)` with the exact foreground key prepares a small
68
- known read after render or on hover; never prefetch a write, a polling action or
69
- a fan-out aggregate. The host keeps one in-memory cache per account, Space,
70
- version and permission; do not add module-global or `localStorage` caches of
71
- user data.
72
-
73
- ## First-party record components
74
-
75
- | Component | Contract |
76
- | --- | --- |
77
- | `<DocumentPage recordKey>` | A record as the view's main content: save state, menu, cover, icon, title, meta, properties that save automatically, collaborative body. Slots `breadcrumb`, `actions`, `menuItems`, `aboveBody`, `belowBody`; toggles `share` (off by default, never for a report record), `header`, `meta`, `properties`, `width` (`standard` 900 px centred column by default, `wide` 1200 px, `full`); `viewer: 'html'` shows a record whose one stored `.html` file is the page; `onSaved`; `layout`. Pair with `DocumentPageSkeleton` and `usePrefetchRecord()`. It is the usual `reader` slot of `ListReader`; there it takes no `breadcrumb`, because the top bar crumb already names the open record. A page with a `breadcrumb` (a record opened from the view) names the top bar crumb leaf with its title itself; `topBarTitle` overrides that, and `onTitle` hears the title. |
78
- | `<DocumentEditor recordKey>` | Native collaborative body, properties, images and attachments. With separate properties use `showProperties={false}`. |
79
- | `<RecordProperties recordKey>` | Native revision-checked property editing. |
80
- | `<HtmlFrame recordKey>` | Attached HTML under viewer CSP and an opaque-origin sandbox. Source cannot relax that boundary. `onReady` is called once per page after it has loaded and painted, or when the record cannot load: keep a slide hidden until then instead of showing a half-drawn page. `presentation={{ onAction }}` turns the pointer into a laser dot inside the page, keeps its buttons and links clickable, and hands the presenter's keys and plain clicks back as `next`, `previous`, `first`, `last` or `stop`; the page can send the same actions, so treat them as navigation only. |
81
- | `<ReportFrame recordKey>` | A report row's saved independent implementation in its database's current view. |
82
- | `<ShareControl recordKey>` | Private/shared record Site, copy link and revoke. |
83
- | `<SpacePageFrame href>` | Another Notis Space page, live in this view: `href` is a Notis link (a path or a full link of this origin, such as a Page property). The Portal shows only that page's view (no sidebar, top bar or chat) with the viewer's own session and permissions. `interactive` (default `false`) lets it take clicks and keys; off, the view around it (a deck's arrows and swipes) keeps them. `title`, `className` (sizes the box it fills). Any other link, and every verify or build preview, shows a card with the title, the path and Open page. |
84
-
85
- In its own Space's view, a record's Site is a row of the top bar Share panel, not
86
- a toolbar button. The published Space declares the database binding; the server
87
- rechecks record scope and binding revision. A Site exposes read-only body and
88
- property snapshots and HTML for its pinned record, including a declared
89
- non-collection record param. A report row cannot be shared as a Site; a report
90
- saved as an HTML file can. A Site has no upload, collaboration credential,
91
- authoring controls or sharing mutation. No credentials or filesystem URLs belong
92
- in component props.
93
-
94
40
  ## Toolkit pieces
95
41
 
96
42
  From `@notis/sdk/ui`. Their props live in the piece types; read them there
@@ -109,7 +55,10 @@ rather than from a copy.
109
55
  `auto` for a move the list makes itself, or `url`), `renderTile` (tiles), `look` (`two-tone` keeps
110
56
  the list tinted) and `autoOpen` (opens the first item). It has no toolbar or
111
57
  header slot. `Row` takes `wrap` (title lines) and `now` (a fixed clock for
112
- relative times). Drag to select is automatic on a list that selects several
58
+ relative times); a `Row` drawn on its own (a short "Needs action" list)
59
+ takes `onPress` and `pressLabel` and opens something on press, so never wrap
60
+ a row in a button of your own. A `labels` entry with a tone draws as a small
61
+ tinted pill. Drag to select is automatic on a list that selects several
113
62
  (`selectable` or a bulk action): a drag from empty space selects the rows
114
63
  under it, as in the Manager; `dragSelect={false}` turns it off. Reorder is
115
64
  off until the view passes `reorder={{ onReorder, canReorder }}`: a row then
@@ -136,17 +85,34 @@ rather than from a copy.
136
85
  only reads. Use it rather than columns of your own.
137
86
  - **Time and numbers**: `PeriodPicker` with `usePeriod`, `DayPicker`,
138
87
  `CalendarView`, `TimelineView`, `Chart`, `StatRow`, `ChartTable`,
139
- `RenderChartData`. `Chart` stacks bars or areas (`stacked`) and runs bars
140
- left to right (`horizontal`): each label on up to two lines before its bar
141
- in a measured axis, and its value after it; `labelFormat` gives that short
88
+ `RenderChartData`, `Meter`, `DataTable`, `formatDuration`. `Chart` stacks
89
+ bars or areas (`stacked`) and runs bars left to right (`horizontal`): each
90
+ label on up to two lines before its bar in a measured axis, and its value after it; `labelFormat` gives that short
142
91
  value ("1.2k") while `format` stays the exact tooltip and table text. Draw
143
92
  category bars this way rather than with your own recharts. For a chart of
144
93
  your own, `ChartContainer` takes `aspect` or `height`; `ChartTooltipContent`
145
94
  and `ChartLegend` also work outside it; `<Bar shape={barShape}
146
95
  label={{ content: barLabel }} />` keeps zero bars and their value labels. A
147
- sparkline `null` is a gap. `PeriodPicker` without the `custom` preset offers
148
- presets only.
149
- - **Floating**: `Menu`, `Popover`, `Tooltip`.
96
+ sparkline `null` is a gap. `domain={[min, max]}` fixes the value scale (a
97
+ percentage on 0 to 100) and `valueAxis` draws it on the left through
98
+ `labelFormat` (without a `domain` its top rises to a round quarter); x labels thin out with the room and never run off the edge. `PeriodPicker` without the `custom` preset offers
99
+ presets only. `Meter` is a labelled capacity bar (`label`, `value`, `max`,
100
+ `valueText`, `hint`); at or past `limit` (a tick named by `limitLabel`) it
101
+ turns destructive. Set `limit` only to a threshold the data has (a memory
102
+ reserve, a quota), never to `max`: a full meter is not red by itself. `DataTable` is a read-only table with the `ChartTable`
103
+ look for rows that are not figures: `columns` (`id`, `label`, `cell`, `align`, `width`,
104
+ `mono`, `primary`, `hideBelow`), `rows` or `groups` (`key`, `label`, `rows`),
105
+ `rowKey`, and `onRowPress` with `rowLabel` to open a row (the primary cell
106
+ then sits inside the row's button: text and icons only, no link). The primary
107
+ column never gets under its `minWidth` (120 px by default): the last
108
+ columns that do not fit hide on their own.
109
+ `formatDuration(ms, locale, { units, smallest })` writes "1 h 31 min" (FR
110
+ "4 j 6 h").
111
+ - **Floating**: `Menu`, `Popover`, `Tooltip`, `InfoTip`. `InfoTip` is the
112
+ info button beside a label (a figure's `about`, a section heading, a meter):
113
+ `label` names what it explains and the children are one or two sentences
114
+ that open on press or tap. A `Tooltip` never shows on touch, so explanations
115
+ go in an `InfoTip`.
150
116
  - **Files and pictures**: `AttachmentGallery` and `ImageViewer`, the ones
151
117
  Notis conversations use. `AttachmentGallery` draws a row of file cards
152
118
  (`items`: `url`, `name`, `type` or `kind`, `size`, `thumbnailUrl`); an
@@ -158,7 +124,10 @@ rather than from a copy.
158
124
  picture that opens full screen. Do not build your own lightbox.
159
125
  - **Comments**: `useComments` with `CommentPane` and `CommentPins` give review
160
126
  threads on a Comments database (pins, zones, replies, asks, Resolve, Copy
161
- changes). For comments on a whole record with nothing to pin on, pass no
127
+ changes). A comment is signed with the viewer's first name; when the
128
+ Comments database's Author is a choice list, give it a `Person` option, which
129
+ signs anyone it does not name (without it the comment saves with no author).
130
+ Pass `me` only to sign with a fixed name. For comments on a whole record with nothing to pin on, pass no
162
131
  `anchors` and `columns.anchor: null`: the pane offers New comment itself.
163
132
  To let people attach pictures and files to a comment or a reply
164
133
  (paste, drop or the paperclip), give the Comments database a files column
@@ -181,11 +150,10 @@ rather than from a copy.
181
150
  previews, a timer). The browser asks once to place windows on screens; the
182
151
  desktop app never asks. Leaving the view closes the audience window.
183
152
  - **Blocks**: `Section`, `Badge`, `Button`, `ToggleGroup`, `SegmentedControl`,
184
- `NativeSelect`, `EmptyState`, `Notice`, `Metric`. A page is a stack of
185
- `Section`s, full width and without boxes: `kind` is `bar` (period and
186
- filters), `stats`, `chart`, `data` (a table) or `form`, and its head takes
187
- `title`, `count`, `meta`, `tabs` and `actions`. There is no page heading and
188
- no card: the host top bar shows the title. One toggle is a `Button` with
153
+ `NativeSelect`, `EmptyState`, `Notice`, `Metric`. A `Section`'s `kind`
154
+ is `bar` (period and filters), `stats`, `chart`, `data` (a table) or `form`,
155
+ and its head takes `title`, `count`, `meta`, `tabs` and `actions`. There is no
156
+ page heading: the host top bar shows the title. One toggle is a `Button` with
189
157
  `pressed`; several with any number on (filters, chart series) are a
190
158
  `ToggleGroup`; tabs and filters over a whole list or section are pills
191
159
  (`TabRow`); a `SegmentedControl` is only a mode switch inside a section.
@@ -216,7 +184,65 @@ Move to triage, and a Space whose first stop has a name passes
216
184
  A status maps to one of ten groups (`backlog`, `todo`, `active`, `review`,
217
185
  `waiting`, `done`, `cancelled`, `failed`, and `up`/`down` for a service), each
218
186
  with its icon, words and the one status palette: pass the Space's own status to
219
- `Row` or `StatusIcon` (with `label` for its own name), never a colour.
187
+ `Row` or `StatusIcon` (with `label` for its own name).
188
+
189
+ ## Records and declared reads
190
+
191
+ | API | Use |
192
+ | --- | --- |
193
+ | `useViewParams<typeof definition>()` | `{params, invalid, missing, declared, ready, setParams}` for declared typed URL params. Unknown names are dropped; invalid values use their declared default. `setParams(changes, {replace?})` changes this view's own params (`null` removes one) and keeps the same Space and record open. |
194
+ | `useShown<Row>(name, options?)` | Execute the native list in `shows[name]` with current params. Options: `sorts`, `pageSize`, `offset`, `includeContent`, `allPages` (every page, for a whole count or a local search); rows are in `data?.rows` and the schema revision a write needs in `data?.schema_revision`, with `loading`, `hasData`, `isFetching`, `error`, `refetch` (resolves to the read's error, or null when it succeeded; it never rejects). |
195
+ | `useShownAvailable(name)` | Check whether this host exposes the declared native list. A record Site can expose only its exact server-pinned row scope. |
196
+ | `useAction<Inputs, Result>(name)` / `useActionQuery<Result>(name, inputs, options?)` | Call a declared action (`call(inputs, options)`); read the result of a declared read action. Never call account-wide tools from a Space. When a read action answers with native rows, pass `rows: { binding, at, query? }` (`at`: the answer field holding them, `''` for a bare list; `query`: the native query it runs) so native writes to that database show in it at once too; without it the read only refreshes after the write. A failed call throws a `SpaceActionError`; its `code` is `rate_limited` when the provider refused it for sending too fast (it did not run, and Notis already waited and retried safe calls), so offer a retry after a few seconds instead of adding your own limiter, and `read_timeout` when a read took too long. |
197
+ | `useNativeMutation(binding, operation)` | Insert, update or delete one row of a linked database through the action that declares `LOCAL_NOTIS_DATABASE_INSERT`, `_UPDATE` or `_DELETE` on that binding with `request: { $input: 'request' }`. `mutate(input, {schemaRevision, requestId, showIn?})` returns the receipt (`record_key`, `revision`). The write shows in every list of that database at once, before the server answers: an edited row changes where it is (and moves to its sorted place, or leaves a `useNativeDocuments` read whose filter no longer keeps it), a new row joins the reads whose filter it passes and the `shows` lists named by `showIn` (by default the view's only list over that database), and a delete moves the record to the bin and leaves every list. A failed write puts the server's rows back. Do not keep your own copy of the change on top. One new request ID per effect. An insert action takes no `content_markdown`: insert, then save the body with `useNativeDocumentBody` and the record's revision. |
198
+ | `useNativeDelete(binding)` | Trash many rows of one linked database (a deck and its slides, a multi-select). `deleteMany(inputs, {schemaRevision, requestId})` hides every row from the lists at once, runs the writes a few at a time, each with the request ID `${requestId}:${record_key}` (a retry with the same `requestId` replays instead of trashing twice), refreshes the lists once at the end and brings back the rows whose write failed. It never throws for a failed row: it resolves to `{done, failed}`; say how many failed. Use it rather than a loop of `mutate`. |
199
+ | `useNativeDocumentBody(binding, recordKey, {readAction, writeAction?, enabled?})` | Markdown body adapter. Keep drafts in the view; save with the original content, record/schema revisions and stable request ID. Rich editing normally uses `DocumentEditor`. |
200
+ | `useNotis()` | Host resource, Space labels, route and ready state. Use `resource.id` for the current Space identity. |
201
+
202
+ Keep hooks unconditional. `loading` means no first successful read;
203
+ `isFetching` includes a silent refresh. Do not copy rows into mount-only state
204
+ or clear them on error ([loading rules](design.md#loading-empty-and-error)).
205
+ `Skeleton` and `ViewSkeleton` come from `@notis/sdk`; `ViewSkeleton`'s `label`
206
+ names what loads (`{ en: 'Loading meetings', fr: 'Chargement des réunions' }`),
207
+ said in the Space's language, default Loading content. Its shapes are
208
+ measured from the view at verify time and drawn from the release; `skeletonKey`
209
+ (default `main`) names the region when a view has several separately loading
210
+ parts, and `variant` only draws the fallback before the first measured release.
211
+ A region that only shows on another tab or page is measured when the
212
+ verification fixtures list that tab's params in `context.skeletonParams`. A Space
213
+ with editor-only parts gets the skeleton of its public view, the one visitors
214
+ see: an editors' page that loads differently keeps a plain loading state of its own.
215
+
216
+ For another explicitly idempotent read use `useActionQuery`, or
217
+ `useQuery(keyArray, readCallback, { readOnly: true })` with every input in the
218
+ key. Call declared read actions inside a custom read with
219
+ `{ readOnly: true, dedupe: true }`; never mark a whole tool family read-only.
220
+ `useQueryClient().prefetch(...)` with the exact foreground key prepares a small
221
+ known read after render or on hover; never prefetch a write, a polling action or
222
+ a fan-out aggregate. The host keeps one in-memory cache per account, Space,
223
+ version and permission; do not add module-global or `localStorage` caches of
224
+ user data.
225
+
226
+ ## First-party record components
227
+
228
+ | Component | Contract |
229
+ | --- | --- |
230
+ | `<DocumentPage recordKey>` | A record as the view's main content: save state, menu, cover, icon, title, meta, properties that save automatically, collaborative body. Slots `breadcrumb`, `actions`, `menuItems`, `aboveBody`, `belowBody`; toggles `share` (off by default, never for a report record), `header`, `meta`, `properties`, `width` (`standard` 900 px centred column by default, `wide` 1200 px, `full`); `viewer: 'html'` shows a record whose one stored `.html` file is the page; `onSaved`; `layout`. Pair with `DocumentPageSkeleton` and `usePrefetchRecord()`. It is the usual `reader` slot of `ListReader`; there it takes no `breadcrumb`, because the top bar crumb already names the open record. A page with a `breadcrumb` (a record opened from the view) names the top bar crumb leaf with its title itself; `topBarTitle` overrides that, and `onTitle` hears the title. |
231
+ | `<DocumentEditor recordKey>` | Native collaborative body, properties, images and attachments. With separate properties use `showProperties={false}`. |
232
+ | `<RecordProperties recordKey>` | Native revision-checked property editing. |
233
+ | `<HtmlFrame recordKey>` | Attached HTML under viewer CSP and an opaque-origin sandbox. Source cannot relax that boundary. `onReady` is called once per page after it has loaded and painted, or when the record cannot load: keep a slide hidden until then instead of showing a half-drawn page. `presentation={{ onAction }}` turns the pointer into a laser dot inside the page, keeps its buttons and links clickable, and hands the presenter's keys and plain clicks back as `next`, `previous`, `first`, `last` or `stop`; the page can send the same actions, so treat them as navigation only. |
234
+ | `<ReportFrame recordKey>` | A report row's saved independent implementation in its database's current view. |
235
+ | `<ShareControl recordKey>` | Private/shared record Site, copy link and revoke. |
236
+ | `<SpacePageFrame href>` | Another Notis Space page, live in this view: `href` is a Notis link (a path or a full link of this origin, such as a Page property). The Portal shows only that page's view (no sidebar, top bar or chat) with the viewer's own session and permissions. `interactive` (default `false`) lets it take clicks and keys; off, the view around it (a deck's arrows and swipes) keeps them. `title`, `className` (sizes the box it fills). Any other link, and every verify or build preview, shows a card with the title, the path and Open page. |
237
+
238
+ In its own Space's view, a record's Site is a row of the top bar Share panel, not
239
+ a toolbar button. The published Space declares the database binding; the server
240
+ rechecks record scope and binding revision. A Site exposes read-only body and
241
+ property snapshots and HTML for its pinned record, including a declared
242
+ non-collection record param. A report row cannot be shared as a Site; a report
243
+ saved as an HTML file can. A Site has no upload, collaboration credential,
244
+ authoring controls or sharing mutation. No credentials or filesystem URLs belong
245
+ in component props.
220
246
 
221
247
  ## Navigation
222
248
 
@@ -84,6 +84,17 @@ The saved `read` action is deliberately constrained to one native record for
84
84
  body and record-Site reads; `shows.notes` owns the Editor's collection list. Keep
85
85
  both tied to the same declared resource.
86
86
 
87
+ ## Records in the sidebar
88
+
89
+ `collection` lists the database's records as rows under the Space in the
90
+ sidebar. Declare it only when the list stays short and people navigate it like
91
+ pages: folders of a notes Space, the chapters of a guide, a handful of decks.
92
+ Leave it out when records keep coming (candidates, leads, tickets, meetings,
93
+ logs, anything a skill or automation adds every week): show them in the view
94
+ with `shows` and a `ListReader` or table, which has search, filters and tabs.
95
+ The sidebar lists a row's first 10 records and a Show more row adds 10 at a
96
+ time, so a long collection still works, but it buries every Space below it.
97
+
87
98
  A Site of the whole Space (or of one of its pages) runs each `shows` list
88
99
  through such an action too, and that one-record action refuses the list's
89
100
  request. Publishing is then refused with `site_list_action_required`. For a
@@ -166,7 +177,7 @@ no title, heading or search field of its own. `archive` is a standard action: it
166
177
  brings its own words and key. `pin` is the Space's own: it brings its EN and FR
167
178
  words and a key the clash check accepts. Add `tabs` for real saved filters and
168
179
  `create` for a "+" that makes a record. Other kinds of view start from their own
169
- piece; see [Design](design.md#pick-the-piece).
180
+ piece; see [the toolkit pieces](sdk.md#toolkit-pieces).
170
181
 
171
182
  ## A view of your own
172
183
 
@@ -1,8 +1,12 @@
1
1
  'use client';
2
- import React, { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
2
+ import React, { useRef, useState, type CSSProperties, type ReactNode } from 'react';
3
3
  import type { ContextResource } from '../runtime';
4
- import { NotisSelectionBoundary } from './NotisSelectionBoundary';
4
+ import { NotisSelectionBoundary, quoteResourceFor } from './NotisSelectionBoundary';
5
5
  import { useAgentContext } from '../hooks/useAgentContext';
6
+ import { useNotisRuntime } from '../provider';
7
+ import { COMMENT_GLYPH, SELECTION_BAR_WORDS, SelectionActionBar, citeSelectionAction, useSelectionAnchor } from './SelectionActionBar';
8
+ import { newSelectionId } from './selectionId';
9
+ import { useToolkitLocale } from '../ui/engine/hooks';
6
10
 
7
11
  export interface NotisCommentBoxProps {
8
12
  quote?: string;
@@ -22,7 +26,7 @@ export function NotisCommentBox({ quote, value, onChange, onSubmit, onCancel, pe
22
26
  className={`flex min-w-0 flex-col gap-2 rounded-xl border p-2.5 text-sm shadow-lg ${className}`}>
23
27
  <div className="flex min-w-0 items-center gap-2">
24
28
  {quote && <blockquote title={quote} className="min-w-0 flex-1 truncate border-l-2 border-current/40 pl-2 opacity-70">{quote}</blockquote>}
25
- <button type="button" aria-label="Cancel comment" onClick={onCancel} disabled={pending} className="ml-auto flex size-7 shrink-0 items-center justify-center rounded-lg opacity-70 hover:bg-white/10 hover:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:opacity-40 [@media(pointer:coarse)]:size-9">
29
+ <button type="button" aria-label="Cancel comment" onClick={onCancel} disabled={pending} className="ml-auto flex size-7 shrink-0 items-center justify-center rounded-lg opacity-70 hover:bg-white/10 hover:opacity-100 disabled:opacity-40 [@media(pointer:coarse)]:size-9">
26
30
  <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="m6 6 12 12M18 6 6 18" /></svg>
27
31
  </button>
28
32
  </div>
@@ -34,7 +38,7 @@ export function NotisCommentBox({ quote, value, onChange, onSubmit, onCancel, pe
34
38
  <span className="text-xs opacity-60">⌘ / Ctrl ↵ to add</span>
35
39
  <button type="button" disabled={pending || !value.trim()} onClick={onSubmit}
36
40
  style={{ background: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))', color: 'hsl(var(--sidebar-background, 0 0% 7.5%))' }}
37
- className="min-h-8 shrink-0 rounded-lg px-2.5 text-sm font-medium hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:opacity-40 [@media(pointer:coarse)]:min-h-9">{pending ? 'Adding…' : 'Add to chat'}</button>
41
+ className="min-h-8 shrink-0 rounded-lg px-2.5 text-sm font-medium hover:opacity-90 disabled:opacity-40 [@media(pointer:coarse)]:min-h-9">{pending ? 'Adding…' : 'Add to chat'}</button>
38
42
  </div>
39
43
  </div>;
40
44
  }
@@ -48,20 +52,6 @@ export interface NotisCommentBoundaryProps {
48
52
  renderComment?: (props: NotisCommentBoxProps) => ReactNode;
49
53
  }
50
54
 
51
- type SelectionRect = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>;
52
-
53
- /** Place the tile after the final selected line, otherwise below (or above near the viewport bottom). */
54
- export function getCommentActionPosition(rects: SelectionRect[], viewport: { width: number; height: number }, rightBoundary = viewport.width, trailing: SelectionRect[] = []) {
55
- const last = rects[rects.length - 1];
56
- const size = 32, gap = 8;
57
- const clampX = (x: number) => Math.max(gap, Math.min(viewport.width - size - gap, x));
58
- const clampY = (y: number) => Math.max(gap, Math.min(viewport.height - size - gap, y));
59
- const beside = { left: last.right + gap, top: clampY((last.top + last.bottom - size) / 2) };
60
- const overlapsText = trailing.some(rect => rect.left < beside.left + size && rect.right > beside.left && rect.top < beside.top + size && rect.bottom > beside.top);
61
- if (beside.left + size <= Math.min(viewport.width, rightBoundary) - gap && !overlapsText) return beside;
62
- return { left: clampX(last.right - size), top: clampY(last.bottom + gap + size <= viewport.height - gap ? last.bottom + gap : last.top - size - gap) };
63
- }
64
-
65
55
  /** Browser paragraph selection may include an adjacent block's empty starting boundary. */
66
56
  export function getOwnedCommentRange(selected: Range, content: Element): Range | null {
67
57
  const owned = content.ownerDocument.createRange();
@@ -88,85 +78,55 @@ export function getOwnedCommentRange(selected: Range, content: Element): Range |
88
78
  /** Selection-to-chat convenience. No annotation database, polling or background attachment. */
89
79
  export function NotisCommentBoundary({ resource, children, className, commentClassName, renderComment }: NotisCommentBoundaryProps) {
90
80
  const context = useAgentContext();
81
+ // A host without a chat (a public Site) offers Comment alone: Cite would have nowhere to go.
82
+ const canCite = Boolean(useNotisRuntime()?.addContext);
91
83
  const root = useRef<HTMLDivElement>(null);
92
- const [selection, setSelection] = useState<{ id: string; text: string; resource?: ContextResource | null; top: number; left: number } | null>(null);
93
- const [editing, setEditing] = useState(false);
94
- const editingRef = useRef(false);
84
+ const locale = useToolkitLocale();
85
+ const [barSize, setBarSize] = useState({ width: 176, height: 32 });
86
+ // The quote being commented on, frozen when the editor opens: typing moves the browser selection into the editor.
87
+ const [editing, setEditing] = useState<{ id: string; text: string; resource: ContextResource | null; top: number; left: number } | null>(null);
95
88
  const [comment, setComment] = useState('');
96
89
  const [pending, setPending] = useState(false);
97
90
  const [error, setError] = useState('');
98
- useEffect(() => {
99
- const node = root.current;
100
- if (!node) return;
101
- const document = node.ownerDocument;
102
- const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
103
- const clearInvalidSelection = () => {
104
- // Opening the editor focuses its input and collapses the browser range.
105
- // Keep the captured quote/editor; only the unopened action follows live selection.
106
- if (editingRef.current) return;
107
- const selected = scope.getSelection?.() || document.defaultView?.getSelection();
108
- const content = node.firstElementChild;
109
- if (!selected?.rangeCount || selected.isCollapsed || !selected.toString().trim()
110
- || !content || !getOwnedCommentRange(selected.getRangeAt(0), content)) setSelection(null);
111
- };
112
- document.addEventListener('selectionchange', clearInvalidSelection);
113
- if (scope !== (document as unknown as ShadowRoot)) scope.addEventListener('selectionchange', clearInvalidSelection);
114
- return () => {
115
- document.removeEventListener('selectionchange', clearInvalidSelection);
116
- if (scope !== (document as unknown as ShadowRoot)) scope.removeEventListener('selectionchange', clearInvalidSelection);
117
- };
118
- }, []);
119
- const open = () => { editingRef.current = true; setEditing(true); };
120
- const capture = (target: EventTarget | null) => {
121
- // Clicking the action/editor must not unmount it before its click runs.
122
- if (editing || (target instanceof Element && target.closest('[data-notis-comment-ui]'))) return;
123
- const node = root.current;
124
- const scope = node?.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
125
- const selected = scope?.getSelection?.() || window.getSelection();
126
- if (!node || !selected?.rangeCount || selected.isCollapsed) { setSelection(null); return; }
127
- const content = node.firstElementChild;
128
- const range = content ? getOwnedCommentRange(selected.getRangeAt(0), content) : null;
129
- if (!range) { setSelection(null); return; }
130
- const start = range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer as Element : range.startContainer.parentElement;
131
- const end = range.endContainer.nodeType === Node.ELEMENT_NODE ? range.endContainer as Element : range.endContainer.parentElement;
132
- if (!node.contains(range.startContainer) || !node.contains(range.endContainer)
133
- || start?.closest('input,textarea,button,[contenteditable],[data-notis-comment-ui]')
134
- || end?.closest('input,textarea,button,[contenteditable],[data-notis-comment-ui]')) { setSelection(null); return; }
135
- const rect = range.getBoundingClientRect();
136
- const lines = Array.from(range.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0);
137
- const boundary = node.firstElementChild?.getBoundingClientRect();
138
- const trailing: DOMRect[] = [];
139
- const endBlock = end?.closest('p,li,h1,h2,h3,h4,h5,h6,td,th,div');
140
- if (endBlock && node.contains(endBlock)) {
141
- const remainder = range.cloneRange();
142
- remainder.selectNodeContents(endBlock);
143
- remainder.setStart(range.endContainer, range.endOffset);
144
- trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
145
- }
146
- const position = getCommentActionPosition(lines.length ? lines : [rect], { width: window.innerWidth, height: window.innerHeight }, boundary?.width ? boundary.right : window.innerWidth, trailing);
147
- setSelection({ id: crypto.randomUUID(), text: selected.toString().trim(), resource: resource ? JSON.parse(JSON.stringify(resource)) : null, ...position });
91
+ // The same bar placement as every quoting surface; a selection spilling over the boundary only by whitespace is
92
+ // clipped to it, and one that takes a neighbour's words is refused.
93
+ const { anchor, dismiss } = useSelectionAnchor(root, {
94
+ enabled: !editing,
95
+ barSize,
96
+ clip: (range, node) => node.firstElementChild ? getOwnedCommentRange(range, node.firstElementChild) : null,
97
+ // A comment boundary never quotes a selection that starts or ends on a button, as before the shared bar.
98
+ exclude: 'button',
99
+ });
100
+ const ownResource = () => resource ? JSON.parse(JSON.stringify(resource)) as ContextResource : null;
101
+ const open = () => {
102
+ if (!anchor) return;
103
+ setEditing({ id: newSelectionId(), text: anchor.text, resource: ownResource(), top: anchor.top, left: anchor.left });
148
104
  };
149
- const close = () => { editingRef.current = false; setEditing(false); setSelection(null); setComment(''); setError(''); };
105
+ const close = () => { setEditing(null); dismiss(); setComment(''); setError(''); };
150
106
  const submit = async () => {
151
- if (!selection || !comment.trim() || pending) return;
107
+ if (!editing || !comment.trim() || pending) return;
152
108
  setPending(true); setError('');
153
109
  try {
154
- const added = await context.add({ id: selection.id, kind: 'comment', title: selection.resource?.label || 'Comment', icon: 'phosphor:chat-text', text: selection.text, comment, resource: selection.resource });
110
+ const added = await context.add({ id: editing.id, kind: 'comment', title: editing.resource?.label || 'Comment', icon: 'phosphor:chat-text', text: editing.text, comment, resource: editing.resource });
155
111
  if (!added) throw new Error('The comment could not be added to chat.');
156
112
  close();
157
113
  } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not add this comment.'); }
158
114
  finally { setPending(false); }
159
115
  };
160
- const editorProps: NotisCommentBoxProps = { quote: selection?.text, value: comment, onChange: setComment, onSubmit: () => void submit(), onCancel: close, pending, error, className: commentClassName };
161
- return <div ref={root} className="contents" onMouseUp={event => capture(event.target)} onDoubleClick={event => capture(event.target)} onKeyUp={event => { if (!editing && (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a'))) capture(event.target); }}>
116
+ const cite = async (range: Range, text: string) => {
117
+ // The quote copy would make: the innermost boundary's resource, else this boundary's.
118
+ const named = quoteResourceFor(range) ?? ownResource();
119
+ try { await context.add({ id: newSelectionId(), text, ...(named ? { resource: named } : {}) }); } catch { /* No chat in this host: copy still quotes. */ }
120
+ };
121
+ const editorProps: NotisCommentBoxProps = { quote: editing?.text, value: comment, onChange: setComment, onSubmit: () => void submit(), onCancel: close, pending, error, className: commentClassName };
122
+ return <div ref={root} className="contents" data-notis-comment-boundary>
162
123
  <NotisSelectionBoundary resource={resource} className={className} style={className ? undefined : { display: 'contents' }}>{children}</NotisSelectionBoundary>
163
- {selection && <div data-notis-comment-ui className="fixed z-50 max-h-[calc(100dvh-1rem)]" style={{ overflow: editing ? 'auto' : 'visible', top: editing ? Math.min(selection.top, Math.max(8, window.innerHeight - 320)) : selection.top, left: `clamp(8px, ${selection.left}px, calc(100vw - ${editing ? 'min(20rem, calc(100vw - 1rem))' : '2rem'} - 8px))`, width: editing ? 'min(20rem, calc(100vw - 1rem))' : undefined } as CSSProperties}>
164
- {editing ? (renderComment ? renderComment(editorProps) : <NotisCommentBox {...editorProps} />) : <button type="button" aria-label="Comment" title="Comment" onMouseDown={event => event.preventDefault()} onClick={open}
165
- style={{ background: 'hsl(var(--sidebar-background, 0 0% 7.5%))', color: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))' }}
166
- className="relative flex size-8 items-center justify-center rounded-lg ring-1 ring-white/15 hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current">
167
- <svg aria-hidden="true" width="18" height="18" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H40A16,16,0,0,0,24,64V224a15.85,15.85,0,0,0,9.24,14.5A16.13,16.13,0,0,0,40,240a15.89,15.89,0,0,0,10.25-3.78l.09-.07L83,208H216a16,16,0,0,0,16-16V64A16,16,0,0,0,216,48ZM40,224h0ZM216,192H80a8,8,0,0,0-5.23,1.95L40,224V64H216ZM88,112a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H96A8,8,0,0,1,88,112Zm0,32a8,8,0,0,1,8-8h64a8,8,0,1,1,0,16H96A8,8,0,0,1,88,144Z" /></svg>
168
- <span aria-hidden="true" className="absolute left-1/2 top-1/2 hidden size-12 -translate-x-1/2 -translate-y-1/2 [@media(pointer:coarse)]:block" />
169
- </button>}
124
+ {anchor && !editing && <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={[
125
+ ...(canCite ? [citeSelectionAction(locale, anchor, root, dismiss, (range, text) => void cite(range, text))] : []),
126
+ { key: 'comment', label: SELECTION_BAR_WORDS.comment[locale], icon: COMMENT_GLYPH, onSelect: open },
127
+ ]} />}
128
+ {editing && <div data-notis-comment-ui className="fixed z-50 max-h-[calc(100dvh-1rem)]" style={{ overflow: 'auto', top: Math.min(editing.top, Math.max(8, window.innerHeight - 320)), left: `clamp(8px, ${editing.left}px, calc(100vw - min(20rem, calc(100vw - 1rem)) - 8px))`, width: 'min(20rem, calc(100vw - 1rem))' } as CSSProperties}>
129
+ {renderComment ? renderComment(editorProps) : <NotisCommentBox {...editorProps} />}
170
130
  </div>}
171
131
  </div>;
172
132
  }