@estiva-app/ui 0.85.0 → 0.86.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.
@@ -0,0 +1,83 @@
1
+ import type { LinkState, Linked, LinkedConversation, LinkedKind } from './linked';
2
+ /** A person as interop names them: a profile, possibly empty. */
3
+ export interface LinkedProfile {
4
+ displayName?: string;
5
+ picture?: string;
6
+ }
7
+ /** One of interop's resolved slots. */
8
+ export interface LinkedSlot {
9
+ value: string;
10
+ label?: string;
11
+ colour?: string;
12
+ isPubkey?: boolean;
13
+ field?: string;
14
+ }
15
+ /** One of interop's resolved actions: what the file's own app lets a reader change. */
16
+ export interface LinkedAction {
17
+ id: string;
18
+ label: string;
19
+ control: string;
20
+ field?: string;
21
+ current?: string;
22
+ options?: {
23
+ value: string;
24
+ label: string;
25
+ colour?: string;
26
+ }[];
27
+ }
28
+ /** The part of interop's `ForeignObject` a link is built from. */
29
+ export interface LinkedSource {
30
+ ref: string;
31
+ address?: string;
32
+ eventId?: string;
33
+ kind: number;
34
+ widget: string | string[];
35
+ noun?: string;
36
+ appName?: string;
37
+ slots: Record<string, LinkedSlot | undefined>;
38
+ meta: LinkedSlot[];
39
+ children?: LinkedSource[];
40
+ people?: Record<string, LinkedProfile>;
41
+ actions: LinkedAction[];
42
+ parentField?: string;
43
+ openUrl?: string;
44
+ unreachable?: boolean;
45
+ archived?: unknown;
46
+ /** When it last changed, in seconds (interop 0.64). */
47
+ changedAt?: number;
48
+ }
49
+ /** `T` is the app's own object type (interop's `ForeignObject`), so `hrefOf` takes it as it is. */
50
+ export interface LinkedFromOptions<T extends LinkedSource = LinkedSource> {
51
+ /**
52
+ * Where a file opens in this app: the linked file itself (`top`), or one of
53
+ * the rows on its card. Another app's address comes from a manifest anyone
54
+ * may publish, so the app keeps it to https.
55
+ */
56
+ hrefOf: (object: T, top: boolean) => string;
57
+ /** A message's words for a one-line preview: marks stripped, references read as words. */
58
+ previewText: (body: string, people: Record<string, LinkedProfile> | undefined) => string;
59
+ /** The workspace's people, for the owner picker's options. */
60
+ directory?: Record<string, LinkedProfile>;
61
+ /**
62
+ * Changes the file from its card. Without it the values read as words
63
+ * (Decided 16 Oct: any reader may change a file from its card; words only in
64
+ * a preview and for a file that cannot be read). An archived file's read as
65
+ * words whatever is passed: its page is read-only.
66
+ */
67
+ onAct?: (actionId: string, value: string) => void;
68
+ /** What was said about it, when the app has read that. */
69
+ conversation?: LinkedConversation;
70
+ }
71
+ /** The file a reference names, as the kit's chip, row and card draw it. */
72
+ export declare function linkedFrom<T extends LinkedSource>(object: T, options: LinkedFromOptions<T>): Linked;
73
+ /**
74
+ * Where a reference's read stands, for the kit: `undefined` is still read,
75
+ * `null` an answer of nothing. `unread` is what the app knows from the address
76
+ * alone, for those two. Nothing, and a file the reader may not read, draw
77
+ * alike: "not available." (Miky, 15 Oct).
78
+ */
79
+ export declare function linkStateFrom<T extends LinkedSource>(object: T | null | undefined, unread: {
80
+ kind: LinkedKind;
81
+ noun: string;
82
+ }, options: LinkedFromOptions<T>): LinkState;
83
+ //# sourceMappingURL=linkedFrom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"linkedFrom.d.ts","sourceRoot":"","sources":["../src/linkedFrom.ts"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/ui",
3
- "version": "0.85.0",
3
+ "version": "0.86.0",
4
4
  "description": "Estiva's design tokens (the contract) and a small set of primitives (a convenience) for every Estiva app.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/registry.json CHANGED
@@ -4,9 +4,9 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.85.0",
8
- "exports": 206,
9
- "typeExports": 206,
7
+ "packageVersion": "0.86.0",
8
+ "exports": 208,
9
+ "typeExports": 211,
10
10
  "files": null
11
11
  },
12
12
  "storybook": {
@@ -4571,6 +4571,25 @@
4571
4571
  "app": null,
4572
4572
  "looks": []
4573
4573
  },
4574
+ {
4575
+ "name": "linkedFrom",
4576
+ "repo": "estiva-ui",
4577
+ "kind": "helper",
4578
+ "importPath": "@estiva-app/ui",
4579
+ "sourceFile": "src/linkedFrom.ts",
4580
+ "purpose": "The file a reference names, as the kit's chip, row and card draw it.",
4581
+ "purposeFrom": "comment",
4582
+ "props": [],
4583
+ "variants": [],
4584
+ "ownsBehaviours": [],
4585
+ "status": "stable",
4586
+ "migrationStage": null,
4587
+ "docsId": null,
4588
+ "storyId": null,
4589
+ "docPage": null,
4590
+ "app": null,
4591
+ "looks": []
4592
+ },
4574
4593
  {
4575
4594
  "name": "LinkedIcon",
4576
4595
  "repo": "estiva-ui",
@@ -4821,6 +4840,25 @@
4821
4840
  "app": null,
4822
4841
  "looks": []
4823
4842
  },
4843
+ {
4844
+ "name": "linkStateFrom",
4845
+ "repo": "estiva-ui",
4846
+ "kind": "helper",
4847
+ "importPath": "@estiva-app/ui",
4848
+ "sourceFile": "src/linkedFrom.ts",
4849
+ "purpose": "Where a reference's read stands, for the kit: `undefined` is still read, `null` an answer of nothing.",
4850
+ "purposeFrom": "comment",
4851
+ "props": [],
4852
+ "variants": [],
4853
+ "ownsBehaviours": [],
4854
+ "status": "stable",
4855
+ "migrationStage": null,
4856
+ "docsId": null,
4857
+ "storyId": null,
4858
+ "docPage": null,
4859
+ "app": null,
4860
+ "looks": []
4861
+ },
4824
4862
  {
4825
4863
  "name": "LinkUnavailable",
4826
4864
  "repo": "estiva-ui",
package/src/LinkCard.mdx CHANGED
@@ -44,6 +44,7 @@ const linked = {
44
44
  - The picker offers only the options it is given: to let the reader set nobody as the owner, include an option for it.
45
45
  - `linked.latest` is drawn whenever it is given: pass it only to a reader who may read it.
46
46
  - `linked.conversation.unread` only for a member of it.
47
+ - **From interop's projection, build it with `linkStateFrom(object, unread, options)`** (or `linkedFrom` for a read object), so every app draws one thing as one card: its key, its 7 most recently changed items, a ring over all of them, and pickers through its own actions when `options.onAct` is passed (words once it is archived). The app passes `hrefOf(object, top)`, `previewText(body, people)` and, for a link not yet read, its kind and noun.
47
48
 
48
49
  ## What it owns
49
50
 
package/src/index.ts CHANGED
@@ -103,6 +103,15 @@ export {
103
103
  type StatusColour,
104
104
  type UnavailableMemory,
105
105
  } from './linked'
106
+ export {
107
+ linkedFrom,
108
+ linkStateFrom,
109
+ type LinkedAction,
110
+ type LinkedFromOptions,
111
+ type LinkedProfile,
112
+ type LinkedSlot,
113
+ type LinkedSource,
114
+ } from './linkedFrom'
106
115
  export { CommentCount, LinkedIcon, LinkKey, LinkPickers, ProgressRing, StatusMark, type LinkPickersProps } from './LinkParts'
107
116
  export { LinkChip, type LinkChipProps } from './LinkChip'
108
117
  export { LinkRow, LinkUnavailable, type LinkRowProps, type LinkUnavailableProps } from './LinkRow'
@@ -0,0 +1,193 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * One file, one card, in every app (5ebf2756): what the card built from
4
+ * interop's projection shows — its key, its most recently changed items and
5
+ * how many of all of them are done, pickers for a reader who may change it,
6
+ * words for an archived file and for one whose app shares no control.
7
+ */
8
+ import { cleanup, render, screen, within } from '@testing-library/react'
9
+ import userEvent from '@testing-library/user-event'
10
+ import { afterEach, describe, expect, it, vi } from 'vitest'
11
+ import { LinkCard } from './LinkCard'
12
+ import { LinkChip } from './LinkChip'
13
+ import { linkStateFrom, type LinkedFromOptions, type LinkedSource } from './linkedFrom'
14
+
15
+ afterEach(cleanup)
16
+
17
+ const OWNER = 'a'.repeat(64)
18
+ const OTHER = 'b'.repeat(64)
19
+ const PEOPLE = { [OWNER]: { displayName: 'Person one' }, [OTHER]: { displayName: 'Person two' } }
20
+
21
+ const STATUSES = [
22
+ { value: 'todo', label: 'Todo', colour: 'neutral' },
23
+ { value: 'doing', label: 'Doing', colour: 'blue' },
24
+ { value: 'done', label: 'Done', colour: 'green' },
25
+ { value: 'dropped', label: 'Dropped', colour: 'muted' },
26
+ ]
27
+
28
+ function item(n: number, status: (typeof STATUSES)[number], changedAt: number): LinkedSource {
29
+ return {
30
+ ref: `2:${OWNER}:item-${n}`,
31
+ address: `2:${OWNER}:item-${n}`,
32
+ kind: 2,
33
+ widget: 'row',
34
+ slots: { title: { value: `Item ${n}`, field: 'title' }, status: { value: status.label, colour: status.colour, field: 'status' } },
35
+ meta: [
36
+ { value: `ABC-${n}`, field: 'ref' },
37
+ { value: OWNER, field: 'assignee', isPubkey: true, label: 'Assignee' },
38
+ ],
39
+ people: PEOPLE,
40
+ actions: [],
41
+ changedAt,
42
+ }
43
+ }
44
+
45
+ const [TODO, DOING, DONE, DROPPED] = STATUSES
46
+
47
+ /** Nine items: 3 done, 1 dropped. Items 8 and 9 changed in the same second. */
48
+ const ITEMS = [
49
+ item(1, DONE, 100),
50
+ item(2, DONE, 200),
51
+ item(3, TODO, 900),
52
+ item(4, DOING, 400),
53
+ item(5, DROPPED, 500),
54
+ item(6, TODO, 600),
55
+ item(7, DONE, 50),
56
+ item(9, TODO, 800),
57
+ item(8, DOING, 800),
58
+ ]
59
+
60
+ const GROUP: LinkedSource = {
61
+ ref: `1:${OWNER}:group`,
62
+ address: `1:${OWNER}:group`,
63
+ kind: 1,
64
+ widget: 'card',
65
+ slots: {
66
+ title: { value: 'Group one', field: 'title' },
67
+ subtitle: { value: 'What the group is for.' },
68
+ status: { value: 'Doing', colour: 'blue', field: 'status' },
69
+ },
70
+ meta: [
71
+ { value: 'ABC', field: 'key' },
72
+ { value: OWNER, field: 'lead', isPubkey: true, label: 'Lead' },
73
+ ],
74
+ children: ITEMS,
75
+ people: PEOPLE,
76
+ actions: [
77
+ { id: 'set-status', label: 'Status', control: 'select', field: 'status', current: 'doing', options: STATUSES },
78
+ { id: 'set-lead', label: 'Lead', control: 'pubkey', field: 'lead', current: OWNER },
79
+ ],
80
+ }
81
+
82
+ const options = (more: Partial<LinkedFromOptions> = {}): LinkedFromOptions => ({
83
+ hrefOf: (object, top) => `#${top ? 'top' : 'row'}-${object.address}`,
84
+ previewText: (body) => body.replace(/\*/g, ''),
85
+ directory: PEOPLE,
86
+ ...more,
87
+ })
88
+
89
+ const UNREAD = { kind: 'file' as const, noun: 'File' }
90
+
91
+ const rowTitles = () =>
92
+ screen
93
+ .getAllByRole('link')
94
+ .map((link) => link.textContent ?? '')
95
+ .filter((text) => /^ABC-\d/.test(text) || /^Item \d/.test(text))
96
+
97
+ describe('a card built from interop’s projection', () => {
98
+ it('lists the 7 most recently changed items, newest first, a tie going to the address', () => {
99
+ render(<LinkCard link={linkStateFrom(GROUP, UNREAD, options())} />)
100
+ const rows = rowTitles().map((text) => text.match(/Item \d/)?.[0])
101
+ expect(rows).toEqual(['Item 3', 'Item 8', 'Item 9', 'Item 6', 'Item 5', 'Item 4', 'Item 2'])
102
+ })
103
+
104
+ it('keeps the order it was given when nothing says when an item changed', () => {
105
+ const unknown = ITEMS.map(({ changedAt: _, ...rest }) => rest)
106
+ render(<LinkCard link={linkStateFrom({ ...GROUP, children: unknown }, UNREAD, options())} />)
107
+ const rows = rowTitles().map((text) => text.match(/Item \d/)?.[0])
108
+ expect(rows).toEqual(['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7'])
109
+ })
110
+
111
+ it('counts every item in its ring, listed or not, a dropped one in the total and not as done', () => {
112
+ render(<LinkCard link={linkStateFrom(GROUP, UNREAD, options())} />)
113
+ expect(screen.getByText('3/9')).toBeTruthy()
114
+ })
115
+
116
+ it('shows its key before its title, in the card and in the chip', () => {
117
+ render(<LinkCard link={linkStateFrom(GROUP, UNREAD, options())} />)
118
+ expect(screen.getByText('ABC')).toBeTruthy()
119
+ cleanup()
120
+ render(<LinkChip link={linkStateFrom(GROUP, UNREAD, options())} />)
121
+ expect(screen.getByText('ABC')).toBeTruthy()
122
+ })
123
+
124
+ it('lets a reader who may change it pick a status and a lead, through the app’s own actions', async () => {
125
+ const user = userEvent.setup()
126
+ const onAct = vi.fn()
127
+ render(<LinkCard link={linkStateFrom(GROUP, UNREAD, options({ onAct }))} />)
128
+ await user.click(screen.getByRole('combobox', { name: 'Status' }))
129
+ await user.click(await screen.findByRole('option', { name: /Done/ }))
130
+ expect(onAct).toHaveBeenCalledWith('set-status', 'done')
131
+ await user.click(screen.getByRole('combobox', { name: 'Lead' }))
132
+ await user.click(await screen.findByRole('option', { name: /Person two/ }))
133
+ expect(onAct).toHaveBeenCalledWith('set-lead', OTHER)
134
+ })
135
+
136
+ it('shows an archived file’s status and lead as words, even to a reader who could change them', () => {
137
+ render(<LinkCard link={linkStateFrom({ ...GROUP, archived: { by: OWNER, at: 1 } }, UNREAD, options({ onAct: vi.fn() }))} />)
138
+ expect(screen.queryByRole('combobox')).toBeNull()
139
+ expect(screen.getAllByText('Doing').length).toBeGreaterThan(0)
140
+ })
141
+
142
+ it('names the owner as words when the file’s app shares no control for it', () => {
143
+ const card = render(<LinkCard link={linkStateFrom({ ...GROUP, children: [], actions: [] }, UNREAD, options({ onAct: vi.fn() }))} />)
144
+ expect(screen.queryByRole('combobox')).toBeNull()
145
+ expect(within(card.container).getByText('Person one')).toBeTruthy()
146
+ })
147
+
148
+ it('opens the file and each row where the app says', () => {
149
+ render(<LinkCard link={linkStateFrom(GROUP, UNREAD, options())} />)
150
+ expect(screen.getByRole('link', { name: /Group one/ }).getAttribute('href')).toBe(`#top-${GROUP.address}`)
151
+ expect(screen.getByRole('link', { name: /Item 3/ }).getAttribute('href')).toBe(`#row-2:${OWNER}:item-3`)
152
+ })
153
+ })
154
+
155
+ describe('a file the reader cannot read', () => {
156
+ it('is not available, and opens in its app only at an https address', () => {
157
+ const stub: LinkedSource = { ...GROUP, unreachable: true, noun: 'group', appName: 'App one', openUrl: 'https://app.example/x' }
158
+ render(<LinkCard link={linkStateFrom(stub, UNREAD, options())} />)
159
+ expect(screen.getByText(/Group — not available/)).toBeTruthy()
160
+ expect(screen.getByRole('link', { name: /App one/ }).getAttribute('href')).toBe('https://app.example/x')
161
+ cleanup()
162
+ render(<LinkCard link={linkStateFrom({ ...stub, openUrl: 'javascript:alert(1)' }, UNREAD, options())} />)
163
+ expect(screen.queryByRole('link')).toBeNull()
164
+ })
165
+
166
+ it('is named by its address when its app gives it no noun', () => {
167
+ render(<LinkCard link={linkStateFrom({ ...GROUP, unreachable: true, appName: 'App one' }, { kind: 'file', noun: 'Record' }, options())} />)
168
+ expect(screen.getByText('Record — not available.')).toBeTruthy()
169
+ })
170
+
171
+ it('reads as the address says while it loads and when nothing came back', () => {
172
+ render(<LinkCard link={linkStateFrom(null, { kind: 'file', noun: 'Record' }, options())} />)
173
+ expect(screen.getByText('Record — not available.')).toBeTruthy()
174
+ })
175
+ })
176
+
177
+ describe('a message', () => {
178
+ it('is drawn as its author’s words, through the app’s preview', () => {
179
+ const message: LinkedSource = {
180
+ ref: 'e'.repeat(64),
181
+ eventId: 'e'.repeat(64),
182
+ kind: 9,
183
+ widget: ['message', 'card'],
184
+ slots: { title: { value: OTHER, isPubkey: true, field: 'pubkey' }, body: { value: 'Ship it **today**' } },
185
+ meta: [],
186
+ people: PEOPLE,
187
+ actions: [],
188
+ }
189
+ render(<LinkCard link={linkStateFrom(message, UNREAD, options())} />)
190
+ expect(screen.getByText('Person two')).toBeTruthy()
191
+ expect(screen.getByText('Ship it today')).toBeTruthy()
192
+ })
193
+ })
@@ -0,0 +1,286 @@
1
+ /**
2
+ * What a link stands for, built from `@estiva-app/interop`'s projection of the
3
+ * file — the one builder Peek, Ship and Leaf share, so one file draws as one
4
+ * card in every app (5ebf2756; why:
5
+ * https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-edits-a-document-with-one-shared-editor.md).
6
+ *
7
+ * The package depends on neither interop nor protocol: {@link LinkedSource} is
8
+ * the part of interop's `ForeignObject` this reads, so any interop version's
9
+ * object fits, and what needs the protocol (where a link opens, a message's
10
+ * words, what an address is before it is read) is the app's, passed in.
11
+ */
12
+ import { thingKindOf } from './KindIcon'
13
+ import type { LinkState, Linked, LinkedChild, LinkedConversation, LinkedKind, LinkedPicker, StatusColour } from './linked'
14
+
15
+ /** A person as interop names them: a profile, possibly empty. */
16
+ export interface LinkedProfile {
17
+ displayName?: string
18
+ picture?: string
19
+ }
20
+
21
+ /** One of interop's resolved slots. */
22
+ export interface LinkedSlot {
23
+ value: string
24
+ label?: string
25
+ colour?: string
26
+ isPubkey?: boolean
27
+ field?: string
28
+ }
29
+
30
+ /** One of interop's resolved actions: what the file's own app lets a reader change. */
31
+ export interface LinkedAction {
32
+ id: string
33
+ label: string
34
+ control: string
35
+ field?: string
36
+ current?: string
37
+ options?: { value: string; label: string; colour?: string }[]
38
+ }
39
+
40
+ /** The part of interop's `ForeignObject` a link is built from. */
41
+ export interface LinkedSource {
42
+ ref: string
43
+ address?: string
44
+ eventId?: string
45
+ kind: number
46
+ widget: string | string[]
47
+ noun?: string
48
+ appName?: string
49
+ slots: Record<string, LinkedSlot | undefined>
50
+ meta: LinkedSlot[]
51
+ children?: LinkedSource[]
52
+ people?: Record<string, LinkedProfile>
53
+ actions: LinkedAction[]
54
+ parentField?: string
55
+ openUrl?: string
56
+ unreachable?: boolean
57
+ archived?: unknown
58
+ /** When it last changed, in seconds (interop 0.64). */
59
+ changedAt?: number
60
+ }
61
+
62
+ /** `T` is the app's own object type (interop's `ForeignObject`), so `hrefOf` takes it as it is. */
63
+ export interface LinkedFromOptions<T extends LinkedSource = LinkedSource> {
64
+ /**
65
+ * Where a file opens in this app: the linked file itself (`top`), or one of
66
+ * the rows on its card. Another app's address comes from a manifest anyone
67
+ * may publish, so the app keeps it to https.
68
+ */
69
+ hrefOf: (object: T, top: boolean) => string
70
+ /** A message's words for a one-line preview: marks stripped, references read as words. */
71
+ previewText: (body: string, people: Record<string, LinkedProfile> | undefined) => string
72
+ /** The workspace's people, for the owner picker's options. */
73
+ directory?: Record<string, LinkedProfile>
74
+ /**
75
+ * Changes the file from its card. Without it the values read as words
76
+ * (Decided 16 Oct: any reader may change a file from its card; words only in
77
+ * a preview and for a file that cannot be read). An archived file's read as
78
+ * words whatever is passed: its page is read-only.
79
+ */
80
+ onAct?: (actionId: string, value: string) => void
81
+ /** What was said about it, when the app has read that. */
82
+ conversation?: LinkedConversation
83
+ }
84
+
85
+ /** How many of a file's items its card lists: the most recently changed (Miky, 21 Oct). */
86
+ const CARD_ROWS = 7
87
+
88
+ const KIND_PAGE = 30842
89
+ const KIND_CHANNEL = 39000
90
+
91
+ const COLOURS: readonly StatusColour[] = ['neutral', 'blue', 'green', 'muted']
92
+
93
+ function colourOf(colour: string | undefined): StatusColour | undefined {
94
+ return COLOURS.find((known) => known === colour)
95
+ }
96
+
97
+ /** The icon a file draws by its event kind; a document draws a page. */
98
+ function linkedKindOfKind(kind: number): LinkedKind {
99
+ return kind === KIND_PAGE ? 'page' : thingKindOf(kind)
100
+ }
101
+
102
+ /** The manifest's `message` widget, wherever it sits in the fallback chain (§13.3). */
103
+ function isMessage(object: LinkedSource): boolean {
104
+ return (Array.isArray(object.widget) ? object.widget : [object.widget]).includes('message')
105
+ }
106
+
107
+ /** What a file is called, by its noun or its app: "Topic", "Estiva Ship". */
108
+ function nounOf(object: { noun?: string; appName?: string }): string | undefined {
109
+ if (object.noun) return object.noun.charAt(0).toUpperCase() + object.noun.slice(1)
110
+ return object.appName
111
+ }
112
+
113
+ function titleOf(object: LinkedSource): string {
114
+ const title = object.slots.title
115
+ if (title?.isPubkey) return object.people?.[title.value]?.displayName ?? '—'
116
+ return title?.value || nounOf(object) || 'Untitled'
117
+ }
118
+
119
+ function idOf(object: LinkedSource): string {
120
+ return object.address ?? object.eventId ?? object.ref
121
+ }
122
+
123
+ /** What the reader calls it, quietly before the title: an issue's ref ("WBD-5"), a project's key ("WBD"). */
124
+ function keyOf(object: LinkedSource): string | undefined {
125
+ return object.meta.find((slot) => (slot.field === 'ref' || slot.field === 'key') && !slot.isPubkey && slot.value)?.value
126
+ }
127
+
128
+ /** The person a file names in its owner's place (its assignee, its lead). */
129
+ function ownerSlotOf(object: LinkedSource): LinkedSlot | undefined {
130
+ return object.meta.find((slot) => slot.isPubkey && slot.value && slot.field !== object.slots.title?.field)
131
+ }
132
+
133
+ /**
134
+ * The items its card lists. A project's are its 7 most recently changed
135
+ * issues, newest first and the same 7 in every app (a tie goes to the
136
+ * address); a Folder's are its files in the Folder's own order (Miky, 16 Oct,
137
+ * ship#310). Interop has already left out what is archived.
138
+ */
139
+ function listedOf(object: LinkedSource): LinkedSource[] {
140
+ const children = object.children ?? []
141
+ if (object.kind === KIND_CHANNEL) return children
142
+ // An interop before 0.64 says nothing of when an item changed: its own order, rather than the addresses'.
143
+ if (children.some((child) => child.changedAt === undefined)) return children.slice(0, CARD_ROWS)
144
+ return [...children]
145
+ .sort((a, b) => (b.changedAt ?? 0) - (a.changedAt ?? 0) || (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0))
146
+ .slice(0, CARD_ROWS)
147
+ }
148
+
149
+ function childrenOf<T extends LinkedSource>(object: T, options: LinkedFromOptions<T>): LinkedChild[] | undefined {
150
+ // An object's children are objects of its own type: interop's are `ForeignObject`s.
151
+ const listed = listedOf(object) as T[]
152
+ if (!listed.length) return undefined
153
+ return listed.map((child) => {
154
+ const status = child.slots.status
155
+ const owner = ownerSlotOf(child)
156
+ const person = owner ? child.people?.[owner.value] : undefined
157
+ const key = keyOf(child)
158
+ return {
159
+ id: idOf(child),
160
+ title: titleOf(child),
161
+ href: options.hrefOf(child, false),
162
+ ...(key ? { key } : {}),
163
+ status: { label: status?.value ?? nounOf(child) ?? 'File', colour: colourOf(status?.colour) ?? 'muted' },
164
+ ...(person?.displayName ? { owner: { name: person.displayName, ...(person.picture ? { picture: person.picture } : {}) } } : {}),
165
+ }
166
+ })
167
+ }
168
+
169
+ /**
170
+ * How far along it is, when every item has a status: the green ones over all
171
+ * of them, listed or not. A cancelled issue is muted, so it counts in the total
172
+ * and not as done (Miky, 21 Oct).
173
+ */
174
+ function doneOf(object: LinkedSource): { done: number; total: number } | undefined {
175
+ const children = object.children
176
+ if (!children?.length || children.some((child) => !child.slots.status)) return undefined
177
+ return { done: children.filter((child) => child.slots.status?.colour === 'green').length, total: children.length }
178
+ }
179
+
180
+ function statusOf(object: LinkedSource, onAct: LinkedFromOptions['onAct']): LinkedPicker | undefined {
181
+ const { slots } = object
182
+ const action = object.actions.find((one) => one.control === 'select' && one.field && one.field === slots.status?.field)
183
+ if (action) {
184
+ return {
185
+ value: action.current,
186
+ options: (action.options ?? []).map((option) => ({ value: option.value, label: option.label, colour: colourOf(option.colour) })),
187
+ ...(onAct ? { onChange: (value: string) => onAct(action.id, value) } : {}),
188
+ }
189
+ }
190
+ if (!slots.status) return undefined
191
+ return { value: slots.status.value, options: [{ value: slots.status.value, label: slots.status.value, colour: colourOf(slots.status.colour) }] }
192
+ }
193
+
194
+ function ownerOf(object: LinkedSource, options: Pick<LinkedFromOptions, 'directory'>, onAct: LinkedFromOptions['onAct']): { owner: LinkedPicker; ownerLabel?: string } | undefined {
195
+ const { slots, people } = object
196
+ // Who owns it: the manifest's person control that is neither the title nor the move (FOL-4).
197
+ const action = object.actions.find(
198
+ (one) => one.control === 'pubkey' && one.field && one.field !== slots.title?.field && one.field !== object.parentField,
199
+ )
200
+ if (action) {
201
+ const known = { ...options.directory }
202
+ // The holder stays pickable while the directory loads, or once they have left it: the object names them.
203
+ if (action.current && !known[action.current]) known[action.current] = people?.[action.current] ?? {}
204
+ return {
205
+ owner: {
206
+ value: action.current || undefined,
207
+ options: [
208
+ { value: '', label: 'Unassigned' },
209
+ ...Object.entries(known)
210
+ // The em dash for an unnameable person, never the key (FEE-1).
211
+ .map(([pubkey, profile]) => ({ value: pubkey, label: profile.displayName ?? '—', picture: profile.picture }))
212
+ .sort((a, b) => a.label.localeCompare(b.label)),
213
+ ],
214
+ ...(onAct ? { onChange: (value: string) => onAct(action.id, value) } : {}),
215
+ },
216
+ ownerLabel: object.meta.find((slot) => slot.field === action.field)?.label ?? action.label,
217
+ }
218
+ }
219
+ // No owner the reader's app may change: the one the file names, as words.
220
+ const slot = ownerSlotOf(object)
221
+ if (!slot) return undefined
222
+ const person = people?.[slot.value]
223
+ return {
224
+ owner: { value: slot.value, options: [{ value: slot.value, label: person?.displayName ?? '—', ...(person?.picture ? { picture: person.picture } : {}) }] },
225
+ ...(slot.label ? { ownerLabel: slot.label } : {}),
226
+ }
227
+ }
228
+
229
+ /** The file a reference names, as the kit's chip, row and card draw it. */
230
+ export function linkedFrom<T extends LinkedSource>(object: T, options: LinkedFromOptions<T>): Linked {
231
+ const { slots, people } = object
232
+ const id = idOf(object)
233
+ const href = options.hrefOf(object, true)
234
+ if (isMessage(object) && slots.title?.isPubkey) {
235
+ // A message is titled by its author (RIC-11): drawn with their face, then its opening words.
236
+ const person = people?.[slots.title.value]
237
+ const name = person?.displayName ?? '—'
238
+ const body = slots.body?.value ? options.previewText(slots.body.value, people) : ''
239
+ return { id, kind: 'message', title: name, href, author: { name, ...(person?.picture ? { picture: person.picture } : {}) }, ...(body ? { body } : {}) }
240
+ }
241
+ const onAct = object.archived ? undefined : options.onAct
242
+ const key = keyOf(object)
243
+ const status = statusOf(object, onAct)
244
+ const owner = ownerOf(object, options, onAct)
245
+ const children = childrenOf(object, options)
246
+ const done = doneOf(object)
247
+ return {
248
+ id,
249
+ kind: linkedKindOfKind(object.kind),
250
+ title: titleOf(object),
251
+ href,
252
+ ...(key ? { key } : {}),
253
+ // Interop reads every file kind's summary into its subtitle (SPEC §6.12).
254
+ ...(slots.subtitle?.value ? { summary: slots.subtitle.value } : {}),
255
+ ...(status ? { status } : {}),
256
+ ...(owner ?? {}),
257
+ ...(options.conversation ? { conversation: options.conversation } : {}),
258
+ ...(children ? { children } : {}),
259
+ ...(done ? { done } : {}),
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Where a reference's read stands, for the kit: `undefined` is still read,
265
+ * `null` an answer of nothing. `unread` is what the app knows from the address
266
+ * alone, for those two. Nothing, and a file the reader may not read, draw
267
+ * alike: "not available." (Miky, 15 Oct).
268
+ */
269
+ export function linkStateFrom<T extends LinkedSource>(
270
+ object: T | null | undefined,
271
+ unread: { kind: LinkedKind; noun: string },
272
+ options: LinkedFromOptions<T>,
273
+ ): LinkState {
274
+ if (object === undefined) return { state: 'loading', kind: unread.kind }
275
+ if (object === null) return { state: 'unavailable', kind: unread.kind, noun: unread.noun }
276
+ if (object.unreachable) {
277
+ const href = object.openUrl && /^https:\/\//i.test(object.openUrl) ? object.openUrl : undefined
278
+ return {
279
+ state: 'unavailable',
280
+ kind: linkedKindOfKind(object.kind),
281
+ noun: (object.noun && nounOf(object)) || unread.noun,
282
+ ...(href ? { openIn: { app: object.appName ?? 'its app', href } } : {}),
283
+ }
284
+ }
285
+ return { state: 'ready', linked: linkedFrom(object, options) }
286
+ }