@kelpie/ui 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/api/client.d.ts +1 -1
  2. package/dist/api/resources/ai.d.ts +16 -0
  3. package/dist/api/resources/ai.d.ts.map +1 -0
  4. package/dist/api/resources/ai.js +93 -0
  5. package/dist/api/resources/ai.js.map +1 -0
  6. package/dist/api/resources/conversions.js +1 -1
  7. package/dist/api/resources/conversions.js.map +1 -1
  8. package/dist/api/resources/session.d.ts.map +1 -1
  9. package/dist/api/resources/session.js +3 -1
  10. package/dist/api/resources/session.js.map +1 -1
  11. package/dist/api/resources/workspace.d.ts +2 -2
  12. package/dist/api/resources/workspace.js +2 -2
  13. package/dist/components/ActivitiesPanel.d.ts +7 -4
  14. package/dist/components/ActivitiesPanel.d.ts.map +1 -1
  15. package/dist/components/ActivitiesPanel.js +12 -2
  16. package/dist/components/ActivitiesPanel.js.map +1 -1
  17. package/dist/components/ActivityAction.d.ts +15 -0
  18. package/dist/components/ActivityAction.d.ts.map +1 -0
  19. package/dist/components/ActivityAction.js +20 -0
  20. package/dist/components/ActivityAction.js.map +1 -0
  21. package/dist/components/AgentTasks.d.ts +5 -0
  22. package/dist/components/AgentTasks.d.ts.map +1 -1
  23. package/dist/components/AgentTasks.js +88 -10
  24. package/dist/components/AgentTasks.js.map +1 -1
  25. package/dist/components/DecisionsPanel.d.ts.map +1 -1
  26. package/dist/components/DecisionsPanel.js +3 -1
  27. package/dist/components/DecisionsPanel.js.map +1 -1
  28. package/dist/components/LinkedText.d.ts +12 -0
  29. package/dist/components/LinkedText.d.ts.map +1 -0
  30. package/dist/components/LinkedText.js +25 -0
  31. package/dist/components/LinkedText.js.map +1 -0
  32. package/dist/components/MarkdownView.d.ts +3 -1
  33. package/dist/components/MarkdownView.d.ts.map +1 -1
  34. package/dist/components/MarkdownView.js +17 -3
  35. package/dist/components/MarkdownView.js.map +1 -1
  36. package/dist/components/NotesPanel.d.ts +2 -1
  37. package/dist/components/NotesPanel.d.ts.map +1 -1
  38. package/dist/components/NotesPanel.js +6 -7
  39. package/dist/components/NotesPanel.js.map +1 -1
  40. package/dist/components/PlanPanel.d.ts.map +1 -1
  41. package/dist/components/PlanPanel.js +3 -1
  42. package/dist/components/PlanPanel.js.map +1 -1
  43. package/dist/components/RecordLinkTextarea.d.ts +12 -0
  44. package/dist/components/RecordLinkTextarea.d.ts.map +1 -0
  45. package/dist/components/RecordLinkTextarea.js +142 -0
  46. package/dist/components/RecordLinkTextarea.js.map +1 -0
  47. package/dist/components/WorkspaceSwitcher.d.ts +2 -1
  48. package/dist/components/WorkspaceSwitcher.d.ts.map +1 -1
  49. package/dist/components/WorkspaceSwitcher.js +7 -2
  50. package/dist/components/WorkspaceSwitcher.js.map +1 -1
  51. package/dist/index.d.ts +5 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +6 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/lib/fragmentTarget.d.ts +18 -0
  56. package/dist/lib/fragmentTarget.d.ts.map +1 -0
  57. package/dist/lib/fragmentTarget.js +73 -0
  58. package/dist/lib/fragmentTarget.js.map +1 -0
  59. package/dist/lib/recordLinks.d.ts +17 -0
  60. package/dist/lib/recordLinks.d.ts.map +1 -0
  61. package/dist/lib/recordLinks.js +48 -0
  62. package/dist/lib/recordLinks.js.map +1 -0
  63. package/dist/lib/recordReferences.d.ts +41 -0
  64. package/dist/lib/recordReferences.d.ts.map +1 -0
  65. package/dist/lib/recordReferences.js +92 -0
  66. package/dist/lib/recordReferences.js.map +1 -0
  67. package/dist/modules/ai.d.ts +13 -0
  68. package/dist/modules/ai.d.ts.map +1 -0
  69. package/dist/modules/ai.js +22 -0
  70. package/dist/modules/ai.js.map +1 -0
  71. package/dist/modules/aiRunner.d.ts +3 -0
  72. package/dist/modules/aiRunner.d.ts.map +1 -0
  73. package/dist/modules/aiRunner.js +66 -0
  74. package/dist/modules/aiRunner.js.map +1 -0
  75. package/dist/pages/CompanyDetail.d.ts.map +1 -1
  76. package/dist/pages/CompanyDetail.js +2 -1
  77. package/dist/pages/CompanyDetail.js.map +1 -1
  78. package/dist/pages/DealDetail.d.ts.map +1 -1
  79. package/dist/pages/DealDetail.js +2 -1
  80. package/dist/pages/DealDetail.js.map +1 -1
  81. package/dist/pages/EnquiryDetail.d.ts.map +1 -1
  82. package/dist/pages/EnquiryDetail.js +2 -1
  83. package/dist/pages/EnquiryDetail.js.map +1 -1
  84. package/dist/pages/EventDetail.d.ts.map +1 -1
  85. package/dist/pages/EventDetail.js +2 -1
  86. package/dist/pages/EventDetail.js.map +1 -1
  87. package/dist/pages/OpportunityDetail.d.ts.map +1 -1
  88. package/dist/pages/OpportunityDetail.js +2 -1
  89. package/dist/pages/OpportunityDetail.js.map +1 -1
  90. package/dist/pages/PartnershipDetail.d.ts.map +1 -1
  91. package/dist/pages/PartnershipDetail.js +2 -1
  92. package/dist/pages/PartnershipDetail.js.map +1 -1
  93. package/dist/pages/PersonDetail.d.ts.map +1 -1
  94. package/dist/pages/PersonDetail.js +2 -1
  95. package/dist/pages/PersonDetail.js.map +1 -1
  96. package/dist/pages/RaiseDetail.d.ts.map +1 -1
  97. package/dist/pages/RaiseDetail.js +2 -1
  98. package/dist/pages/RaiseDetail.js.map +1 -1
  99. package/dist/pages/SearchPage.d.ts.map +1 -1
  100. package/dist/pages/SearchPage.js +26 -14
  101. package/dist/pages/SearchPage.js.map +1 -1
  102. package/dist/pages/admin/AiPage.d.ts +2 -0
  103. package/dist/pages/admin/AiPage.d.ts.map +1 -0
  104. package/dist/pages/admin/AiPage.js +134 -0
  105. package/dist/pages/admin/AiPage.js.map +1 -0
  106. package/dist/pages/admin/McpPage.js +2 -2
  107. package/dist/pages/admin/McpPage.js.map +1 -1
  108. package/dist/pages/admin/WorkspaceSettingsPage.d.ts +5 -6
  109. package/dist/pages/admin/WorkspaceSettingsPage.d.ts.map +1 -1
  110. package/dist/pages/admin/WorkspaceSettingsPage.js +12 -17
  111. package/dist/pages/admin/WorkspaceSettingsPage.js.map +1 -1
  112. package/dist/pages/dashboard/attention.d.ts +0 -5
  113. package/dist/pages/dashboard/attention.d.ts.map +1 -1
  114. package/dist/pages/dashboard/attention.js +1 -21
  115. package/dist/pages/dashboard/attention.js.map +1 -1
  116. package/dist/pages/dashboard/sections.d.ts.map +1 -1
  117. package/dist/pages/dashboard/sections.js +6 -3
  118. package/dist/pages/dashboard/sections.js.map +1 -1
  119. package/dist/pages/handbook/HandbookPage.d.ts.map +1 -1
  120. package/dist/pages/handbook/HandbookPage.js +2 -3
  121. package/dist/pages/handbook/HandbookPage.js.map +1 -1
  122. package/dist/pages/onboarding/WorkspaceStepPage.d.ts.map +1 -1
  123. package/dist/pages/onboarding/WorkspaceStepPage.js +9 -27
  124. package/dist/pages/onboarding/WorkspaceStepPage.js.map +1 -1
  125. package/dist/pages/onboarding/onboardingRerun.d.ts +9 -0
  126. package/dist/pages/onboarding/onboardingRerun.d.ts.map +1 -1
  127. package/dist/pages/onboarding/onboardingRerun.js +11 -0
  128. package/dist/pages/onboarding/onboardingRerun.js.map +1 -1
  129. package/dist/registry/context.d.ts +3 -1
  130. package/dist/registry/context.d.ts.map +1 -1
  131. package/dist/registry/context.js +4 -0
  132. package/dist/registry/context.js.map +1 -1
  133. package/dist/registry/contributions.d.ts +38 -0
  134. package/dist/registry/contributions.d.ts.map +1 -1
  135. package/dist/registry/registry.d.ts +5 -1
  136. package/dist/registry/registry.d.ts.map +1 -1
  137. package/dist/registry/registry.js +8 -0
  138. package/dist/registry/registry.js.map +1 -1
  139. package/package.json +2 -2
  140. package/src/api/client.ts +1 -1
  141. package/src/api/resources/ai.ts +110 -0
  142. package/src/api/resources/conversions.ts +1 -1
  143. package/src/api/resources/session.ts +3 -1
  144. package/src/api/resources/workspace.ts +4 -4
  145. package/src/components/ActivitiesPanel.tsx +39 -10
  146. package/src/components/ActivityAction.tsx +33 -0
  147. package/src/components/AgentTasks.tsx +138 -10
  148. package/src/components/DecisionsPanel.tsx +9 -1
  149. package/src/components/LinkedText.tsx +51 -0
  150. package/src/components/MarkdownView.tsx +37 -7
  151. package/src/components/NotesPanel.tsx +18 -12
  152. package/src/components/PlanPanel.tsx +9 -1
  153. package/src/components/RecordLinkTextarea.tsx +257 -0
  154. package/src/components/WorkspaceSwitcher.tsx +15 -1
  155. package/src/index.ts +10 -0
  156. package/src/lib/fragmentTarget.ts +96 -0
  157. package/src/lib/recordLinks.ts +57 -0
  158. package/src/lib/recordReferences.ts +139 -0
  159. package/src/modules/ai.tsx +23 -0
  160. package/src/modules/aiRunner.ts +80 -0
  161. package/src/pages/CompanyDetail.tsx +2 -1
  162. package/src/pages/DealDetail.tsx +2 -1
  163. package/src/pages/EnquiryDetail.tsx +2 -1
  164. package/src/pages/EventDetail.tsx +2 -1
  165. package/src/pages/OpportunityDetail.tsx +2 -1
  166. package/src/pages/PartnershipDetail.tsx +2 -1
  167. package/src/pages/PersonDetail.tsx +2 -1
  168. package/src/pages/RaiseDetail.tsx +2 -1
  169. package/src/pages/SearchPage.tsx +30 -15
  170. package/src/pages/admin/AiPage.tsx +353 -0
  171. package/src/pages/admin/McpPage.tsx +11 -5
  172. package/src/pages/admin/WorkspaceSettingsPage.tsx +13 -28
  173. package/src/pages/dashboard/attention.ts +1 -24
  174. package/src/pages/dashboard/sections.tsx +9 -4
  175. package/src/pages/handbook/HandbookPage.tsx +5 -6
  176. package/src/pages/onboarding/WorkspaceStepPage.tsx +19 -43
  177. package/src/pages/onboarding/onboardingRerun.ts +14 -0
  178. package/src/registry/context.ts +6 -0
  179. package/src/registry/contributions.ts +30 -0
  180. package/src/registry/registry.ts +18 -0
@@ -0,0 +1,257 @@
1
+ import { formatRecordLinkToken, isRecordReferenceType } from '@kelpie/schemas'
2
+ import type { RecordReferenceType } from '@kelpie/schemas'
3
+ import { useEffect, useId, useRef, useState } from 'react'
4
+ import type { KeyboardEvent } from 'react'
5
+
6
+ import { useSearch } from '../api/resources/search.ts'
7
+
8
+ /**
9
+ * A textarea that links records: type `[[` and a few letters, pick a record, and
10
+ * a `[[type:id|Label]]` token goes in where the brackets were.
11
+ *
12
+ * The choices come from `GET /v1/search`, the same public endpoint the search
13
+ * page uses, so anything search finds can be linked. `@` is not a trigger. It is
14
+ * kept for naming workspace members.
15
+ */
16
+
17
+ /** How many choices the list shows. Search ranks them, so the best come first. */
18
+ const MAX_CHOICES = 8
19
+
20
+ const TYPE_LABELS: Readonly<Partial<Record<RecordReferenceType, string>>> = {
21
+ handbook_page: 'Handbook',
22
+ person: 'Person',
23
+ role: 'Role',
24
+ company: 'Company',
25
+ enquiry: 'Enquiry',
26
+ deal: 'Deal',
27
+ opportunity: 'Opportunity',
28
+ raise: 'Raise',
29
+ partnership: 'Partnership',
30
+ event: 'Event',
31
+ decision: 'Decision',
32
+ note: 'Note',
33
+ plan_item: 'Plan item',
34
+ list: 'List',
35
+ form: 'Form',
36
+ }
37
+
38
+ interface Choice {
39
+ readonly targetType: RecordReferenceType
40
+ readonly targetId: string
41
+ readonly title: string
42
+ readonly subtitle: string | null
43
+ }
44
+
45
+ /** An open `[[`: where it starts, and what has been typed after it. */
46
+ interface Trigger {
47
+ readonly start: number
48
+ readonly query: string
49
+ }
50
+
51
+ /**
52
+ * The `[[` the caret is in, if any. A `]` or a line break after the brackets
53
+ * closes it, so finished tokens and ordinary brackets never reopen the list.
54
+ */
55
+ function openTrigger(value: string, caret: number): Trigger | null {
56
+ const before = value.slice(0, caret)
57
+ const start = before.lastIndexOf('[[')
58
+
59
+ if (start === -1) {
60
+ return null
61
+ }
62
+
63
+ const query = before.slice(start + 2)
64
+
65
+ return /[\]\n]/u.test(query) ? null : { start, query }
66
+ }
67
+
68
+ export interface RecordLinkTextareaProps {
69
+ readonly value: string
70
+ readonly onChange: (value: string) => void
71
+ readonly rows?: number
72
+ readonly placeholder?: string
73
+ readonly autoFocus?: boolean
74
+ readonly className?: string
75
+ readonly ariaLabel?: string
76
+ readonly spellCheck?: boolean
77
+ }
78
+
79
+ export function RecordLinkTextarea({
80
+ value,
81
+ onChange,
82
+ rows,
83
+ placeholder,
84
+ autoFocus,
85
+ className,
86
+ ariaLabel,
87
+ spellCheck,
88
+ }: RecordLinkTextareaProps): React.JSX.Element {
89
+ const textarea = useRef<HTMLTextAreaElement>(null)
90
+ const listId = useId()
91
+ const [caret, setCaret] = useState(0)
92
+ const [active, setActive] = useState(0)
93
+ // The `[[` the user closed with Escape. It stays closed until they type
94
+ // somewhere else, so Escape is not undone by the next keystroke.
95
+ const [dismissedAt, setDismissedAt] = useState<number | null>(null)
96
+ const [pendingCaret, setPendingCaret] = useState<number | null>(null)
97
+
98
+ const trigger = openTrigger(value, caret)
99
+ const open = trigger !== null && trigger.start !== dismissedAt
100
+ const search = useSearch(open ? trigger.query : '')
101
+
102
+ const choices: Choice[] = open
103
+ ? (search.results?.groups ?? [])
104
+ .flatMap((group): Choice[] => {
105
+ const targetType = group.collection
106
+
107
+ return isRecordReferenceType(targetType)
108
+ ? group.items.map((item) => ({
109
+ targetType,
110
+ targetId: item.id,
111
+ title: item.title,
112
+ subtitle: item.subtitle,
113
+ }))
114
+ : []
115
+ })
116
+ .slice(0, MAX_CHOICES)
117
+ : []
118
+
119
+ // Put the caret after an inserted token once React has written the new value.
120
+ useEffect(() => {
121
+ if (pendingCaret !== null && textarea.current !== null) {
122
+ textarea.current.setSelectionRange(pendingCaret, pendingCaret)
123
+ setCaret(pendingCaret)
124
+ setPendingCaret(null)
125
+ }
126
+ }, [pendingCaret, value])
127
+
128
+ function readCaret(): void {
129
+ const element = textarea.current
130
+
131
+ if (element !== null) {
132
+ setCaret(element.selectionStart)
133
+ }
134
+ }
135
+
136
+ function choose(choice: Choice): void {
137
+ if (trigger === null) {
138
+ return
139
+ }
140
+
141
+ const token = formatRecordLinkToken({
142
+ targetType: choice.targetType,
143
+ targetId: choice.targetId,
144
+ label: choice.title,
145
+ })
146
+ const next = value.slice(0, trigger.start) + token + value.slice(caret)
147
+
148
+ onChange(next)
149
+ setPendingCaret(trigger.start + token.length)
150
+ setActive(0)
151
+ }
152
+
153
+ function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>): void {
154
+ if (!open) {
155
+ return
156
+ }
157
+
158
+ if (event.key === 'Escape') {
159
+ event.preventDefault()
160
+ setDismissedAt(trigger.start)
161
+
162
+ return
163
+ }
164
+
165
+ if (choices.length === 0) {
166
+ return
167
+ }
168
+
169
+ if (event.key === 'ArrowDown') {
170
+ event.preventDefault()
171
+ setActive((current) => (current + 1) % choices.length)
172
+ } else if (event.key === 'ArrowUp') {
173
+ event.preventDefault()
174
+ setActive((current) => (current - 1 + choices.length) % choices.length)
175
+ } else if (event.key === 'Enter' || event.key === 'Tab') {
176
+ const choice = choices[Math.min(active, choices.length - 1)]
177
+
178
+ if (choice !== undefined) {
179
+ event.preventDefault()
180
+ choose(choice)
181
+ }
182
+ }
183
+ }
184
+
185
+ const activeChoice = open && choices.length > 0 ? Math.min(active, choices.length - 1) : null
186
+
187
+ return (
188
+ <div className="relative">
189
+ <textarea
190
+ ref={textarea}
191
+ value={value}
192
+ onChange={(event) => {
193
+ onChange(event.target.value)
194
+ setCaret(event.target.selectionStart)
195
+ setActive(0)
196
+ }}
197
+ onKeyDown={onKeyDown}
198
+ onKeyUp={readCaret}
199
+ onClick={readCaret}
200
+ onSelect={readCaret}
201
+ rows={rows}
202
+ placeholder={placeholder}
203
+ autoFocus={autoFocus}
204
+ className={className}
205
+ aria-label={ariaLabel}
206
+ spellCheck={spellCheck}
207
+ role="combobox"
208
+ aria-autocomplete="list"
209
+ aria-expanded={open}
210
+ aria-controls={listId}
211
+ aria-activedescendant={activeChoice === null ? undefined : `${listId}-${String(activeChoice)}`}
212
+ />
213
+ {open && (
214
+ <div
215
+ id={listId}
216
+ role="listbox"
217
+ aria-label="Link a record"
218
+ className="absolute right-0 left-0 z-20 mt-1 max-h-64 overflow-y-auto rounded-md border border-border bg-surface-raised py-1 shadow-lg"
219
+ >
220
+ {trigger.query.trim().length === 0 ? (
221
+ <p className="px-3 py-1.5 text-[12px] text-ink-faint">Type to find a record to link</p>
222
+ ) : search.isLoading ? (
223
+ <p className="px-3 py-1.5 text-[12px] text-ink-faint">Searching…</p>
224
+ ) : choices.length === 0 ? (
225
+ <p className="px-3 py-1.5 text-[12px] text-ink-faint">No records match</p>
226
+ ) : (
227
+ choices.map((choice, index) => (
228
+ <div
229
+ key={`${choice.targetType}:${choice.targetId}`}
230
+ id={`${listId}-${String(index)}`}
231
+ role="option"
232
+ aria-selected={index === activeChoice}
233
+ // mousedown, not click: a click would blur the textarea first.
234
+ onMouseDown={(event) => {
235
+ event.preventDefault()
236
+ choose(choice)
237
+ }}
238
+ onMouseEnter={() => {
239
+ setActive(index)
240
+ }}
241
+ className={`flex cursor-pointer items-baseline gap-2 px-3 py-1.5 text-[13px] ${
242
+ index === activeChoice ? 'bg-surface-sunken' : ''
243
+ }`}
244
+ >
245
+ <span className="truncate text-ink">{choice.title}</span>
246
+ <span className="shrink-0 text-[11px] text-ink-faint">
247
+ {TYPE_LABELS[choice.targetType] ?? choice.targetType}
248
+ {choice.subtitle === null ? '' : ` · ${choice.subtitle}`}
249
+ </span>
250
+ </div>
251
+ ))
252
+ )}
253
+ </div>
254
+ )}
255
+ </div>
256
+ )
257
+ }
@@ -2,12 +2,14 @@ import { useEffect, useRef, useState } from 'react'
2
2
  import { useNavigate } from 'react-router'
3
3
 
4
4
  import { useAccountWorkspaces, useSession, useSwitchWorkspace } from '../api/resources/session.ts'
5
+ import { ONBOARDING_NEW_WORKSPACE_ENTRY } from '../pages/onboarding/onboardingRerun.ts'
5
6
 
6
7
  /**
7
8
  * Header control: the workspace this session is in, and a menu to move it.
8
9
  *
9
10
  * The list and the switch both live under `/v1/auth`, so a suspended current
10
- * workspace still lets the reader see the other memberships and leave.
11
+ * workspace still lets the reader see the other memberships and leave. The
12
+ * last item opens the create form for another workspace.
11
13
  */
12
14
 
13
15
  export function WorkspaceSwitcher(): React.JSX.Element | null {
@@ -124,6 +126,18 @@ export function WorkspaceSwitcher(): React.JSX.Element | null {
124
126
  </button>
125
127
  )
126
128
  })}
129
+ <button
130
+ type="button"
131
+ role="menuitem"
132
+ disabled={switchWorkspace.isPending}
133
+ onClick={() => {
134
+ setOpen(false)
135
+ void navigate(ONBOARDING_NEW_WORKSPACE_ENTRY)
136
+ }}
137
+ className="mt-1 block w-full border-t border-border px-3 py-1.5 pt-2 text-left text-[13px] text-ink hover:bg-surface-sunken disabled:opacity-60"
138
+ >
139
+ New workspace
140
+ </button>
127
141
  {switchWorkspace.error !== null && (
128
142
  <p className="border-t border-border px-3 py-1.5 text-[12px] text-danger">
129
143
  {switchWorkspace.error.message}
package/src/index.ts CHANGED
@@ -208,6 +208,9 @@ export type { ThemePreference } from './lib/theme.ts'
208
208
 
209
209
  export { EXTENSIBLE_RECORD_TYPES, NAV_SLOTS } from './registry/contributions.ts'
210
210
  export type {
211
+ AgentRunner,
212
+ AgentRunnerAvailability,
213
+ AgentRunnerProgress,
211
214
  AuthMethod,
212
215
  AuthMethodContext,
213
216
  DashboardCard,
@@ -227,6 +230,7 @@ export { NO_UI_MODULES, UiModuleError, inSlotOrder, registerUiModules } from './
227
230
  export type { UiExtensions, UiModule, UiModuleContext } from './registry/registry.ts'
228
231
 
229
232
  export {
233
+ useAgentRunner,
230
234
  useAuthMethods,
231
235
  useDashboardCards,
232
236
  useModuleRoutes,
@@ -239,3 +243,9 @@ export {
239
243
 
240
244
  export { UiExtensionProvider } from './registry/UiExtensionProvider.tsx'
241
245
  export type { UiExtensionProviderProps } from './registry/UiExtensionProvider.tsx'
246
+
247
+ // The optional `ai` module's UI. An assembly that lists `createAiModule()` on
248
+ // the server lists `aiUi` in its `uiModules`.
249
+ export { aiUi } from './modules/ai.tsx'
250
+ export { AiPage } from './pages/admin/AiPage.tsx'
251
+ export { useAiRuns, useAiSettings, useDisableAi, useSaveAiSettings } from './api/resources/ai.ts'
@@ -0,0 +1,96 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import type { RefObject } from 'react'
3
+ import { useLocation } from 'react-router'
4
+
5
+ /**
6
+ * A row a link can point at: `/companies/com_1#note_1` opens the company and
7
+ * brings note `note_1` into view.
8
+ *
9
+ * Notes, Decisions and Plan items have no page of their own, so a link to one
10
+ * opens the record it is on with the item's id as the fragment. The row whose id
11
+ * matches scrolls to the middle of the screen and is highlighted for a moment, so
12
+ * the reader sees which one was meant. A row on a later page of its panel is not
13
+ * on screen, and nothing happens.
14
+ */
15
+
16
+ /** How long the highlight stays, in milliseconds. */
17
+ const HIGHLIGHT_MS = 2000
18
+
19
+ export interface FragmentTarget<T extends HTMLElement> {
20
+ readonly ref: RefObject<T | null>
21
+ readonly highlighted: boolean
22
+ }
23
+
24
+ export function useFragmentTarget<T extends HTMLElement>(id: string): FragmentTarget<T> {
25
+ const { hash } = useLocation()
26
+ const ref = useRef<T>(null)
27
+ const [highlighted, setHighlighted] = useState(false)
28
+ const targeted = hash === `#${id}`
29
+
30
+ useEffect(() => {
31
+ if (!targeted) {
32
+ return undefined
33
+ }
34
+
35
+ const element = ref.current
36
+
37
+ // jsdom has no layout, and so no `scrollIntoView`.
38
+ if (element !== null && typeof element.scrollIntoView === 'function') {
39
+ element.scrollIntoView({ block: 'center', behavior: 'smooth' })
40
+ }
41
+
42
+ setHighlighted(true)
43
+
44
+ const timer = window.setTimeout(() => {
45
+ setHighlighted(false)
46
+ }, HIGHLIGHT_MS)
47
+
48
+ return () => {
49
+ window.clearTimeout(timer)
50
+ }
51
+ }, [targeted])
52
+
53
+ return { ref, highlighted }
54
+ }
55
+
56
+ /**
57
+ * The detail-page tab that holds a row with this id prefix. Every record page
58
+ * names these three tabs the same.
59
+ */
60
+ const TAB_BY_PREFIX: readonly (readonly [string, string])[] = [
61
+ ['note_', 'notes'],
62
+ ['dec_', 'decisions'],
63
+ ['plan_', 'plan'],
64
+ ]
65
+
66
+ function tabForHash(hash: string): string | undefined {
67
+ const id = hash.startsWith('#') ? hash.slice(1) : hash
68
+
69
+ return TAB_BY_PREFIX.find(([prefix]) => id.startsWith(prefix))?.[1]
70
+ }
71
+
72
+ /**
73
+ * A detail page's active tab, opened on the tab a fragment points into.
74
+ *
75
+ * `/companies/com_1#note_1` must land on Notes, or the row it names is not on
76
+ * screen to scroll to. The fragment picks the tab on the first render and again
77
+ * whenever it changes, so a link to another note on the same page switches too.
78
+ * Anything else starts on Overview, and a click on a tab still wins.
79
+ */
80
+ export function useRecordTab(): readonly [string, (tab: string) => void] {
81
+ const { hash } = useLocation()
82
+ const [tab, setTab] = useState(() => tabForHash(hash) ?? 'overview')
83
+
84
+ useEffect(() => {
85
+ const fromHash = tabForHash(hash)
86
+
87
+ if (fromHash !== undefined) {
88
+ setTab(fromHash)
89
+ }
90
+ }, [hash])
91
+
92
+ return [tab, setTab]
93
+ }
94
+
95
+ /** The classes a highlighted row adds. */
96
+ export const FRAGMENT_HIGHLIGHT = 'bg-accent-soft/40 ring-2 ring-accent/40'
@@ -0,0 +1,57 @@
1
+ import type { RecordReference, RecordReferenceType, RecordTargetType } from '@kelpie/schemas'
2
+
3
+ /**
4
+ * Where each kind of record lives. A Candidate has no page of its own: it is
5
+ * reached through its Role. An Attendance is reached through its Event. A Note,
6
+ * Decision or Plan item is reached on the page of the record it is on; see
7
+ * `attachedHref`.
8
+ */
9
+ const ROUTES: Readonly<Record<RecordReferenceType, string | undefined>> = {
10
+ person: '/people',
11
+ company: '/companies',
12
+ deal: '/deals',
13
+ opportunity: '/opportunities',
14
+ partnership: '/partnerships',
15
+ raise: '/fundraising',
16
+ enquiry: '/enquiries',
17
+ candidate: undefined,
18
+ event: '/events',
19
+ attendance: undefined,
20
+ role: '/hiring',
21
+ handbook_page: '/handbook',
22
+ list: '/lists',
23
+ form: '/forms',
24
+ note: undefined,
25
+ decision: undefined,
26
+ plan_item: undefined,
27
+ }
28
+
29
+ /**
30
+ * @returns The record's page, or undefined when it has none. A row without a
31
+ * link renders as plain text rather than as a link to nowhere.
32
+ */
33
+ export function targetHref(targetType: RecordReferenceType, targetId: string): string | undefined {
34
+ const route = ROUTES[targetType]
35
+
36
+ return route === undefined ? undefined : `${route}/${targetId}`
37
+ }
38
+
39
+ /**
40
+ * A Note, Decision or Plan item: the page of the record it is on, with its own
41
+ * id as the fragment, which the panel on that page scrolls to and highlights.
42
+ */
43
+ export function attachedHref(
44
+ id: string,
45
+ parent: { readonly type: RecordTargetType; readonly id: string },
46
+ ): string | undefined {
47
+ const page = targetHref(parent.type, parent.id)
48
+
49
+ return page === undefined ? undefined : `${page}#${id}`
50
+ }
51
+
52
+ /** Where a cited record opens, or undefined when it has nowhere to open. */
53
+ export function referenceHref(reference: RecordReference): string | undefined {
54
+ return reference.parent === null
55
+ ? targetHref(reference.targetType, reference.targetId)
56
+ : attachedHref(reference.targetId, reference.parent)
57
+ }
@@ -0,0 +1,139 @@
1
+ import { splitRecordLinkTokens } from '@kelpie/schemas'
2
+ import type { RecordLinkToken, RecordReference } from '@kelpie/schemas'
3
+ import type { Link, Parent, PhrasingContent, Root, Text } from 'mdast'
4
+
5
+ import { referenceHref } from './recordLinks.ts'
6
+
7
+ /**
8
+ * Turning the record ids a text cites into something a person can follow.
9
+ *
10
+ * The server already found the ids and named them (`references` on an activity
11
+ * or a note). This side only finds each named id in the text by string match.
12
+ * An id the server did not name stays as it is: it is not a record in this
13
+ * workspace, and a link to it would go nowhere.
14
+ *
15
+ * Text cites a record in two ways, and one pass reads both. A `[[type:id|Label]]`
16
+ * link token is read first, so the id inside it is never matched a second time as
17
+ * a bare id. The text between tokens is then searched for bare ids. A token the
18
+ * server named shows the record's current name; one it did not name shows the
19
+ * token's label as plain text, because the record is gone.
20
+ */
21
+
22
+ export type TextSegment =
23
+ | { readonly kind: 'text'; readonly text: string }
24
+ | { readonly kind: 'reference'; readonly reference: RecordReference }
25
+ | { readonly kind: 'unresolved'; readonly token: RecordLinkToken }
26
+
27
+ /** What an unresolved token shows: its label, or its id when it has none. */
28
+ export function unresolvedLabel(token: RecordLinkToken): string {
29
+ return token.label ?? token.targetId
30
+ }
31
+
32
+ function escapeForPattern(value: string): string {
33
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
34
+ }
35
+
36
+ /**
37
+ * `text` cut into plain runs and cited records, in order.
38
+ *
39
+ * @returns One text segment holding all of `text` when nothing is cited.
40
+ */
41
+ export function splitOnReferences(
42
+ text: string,
43
+ references: readonly RecordReference[],
44
+ ): readonly TextSegment[] {
45
+ const byTokenId = new Map(references.map((reference) => [reference.targetId, reference]))
46
+
47
+ return splitRecordLinkTokens(text).flatMap((segment): readonly TextSegment[] => {
48
+ if (segment.kind === 'text') {
49
+ return splitOnBareIds(segment.text, references)
50
+ }
51
+
52
+ const reference = byTokenId.get(segment.token.targetId)
53
+
54
+ return reference === undefined
55
+ ? [{ kind: 'unresolved', token: segment.token }]
56
+ : [{ kind: 'reference', reference }]
57
+ })
58
+ }
59
+
60
+ /** Bare ids only. Every segment it returns is `text` or `reference`. */
61
+ function splitOnBareIds(text: string, references: readonly RecordReference[]): TextSegment[] {
62
+ if (references.length === 0) {
63
+ return text.length === 0 ? [] : [{ kind: 'text', text }]
64
+ }
65
+
66
+ const byId = new Map(references.map((reference) => [reference.targetId, reference]))
67
+ // Longest first, so an id can never lose to a shorter one it starts with.
68
+ const ids = [...byId.keys()].sort((left, right) => right.length - left.length)
69
+ const pattern = new RegExp(`(${ids.map(escapeForPattern).join('|')})`)
70
+ const segments: TextSegment[] = []
71
+
72
+ // `split` with one capture group puts each match at an odd index.
73
+ text.split(pattern).forEach((part, index) => {
74
+ const reference = index % 2 === 1 ? byId.get(part) : undefined
75
+
76
+ if (reference !== undefined) {
77
+ segments.push({ kind: 'reference', reference })
78
+ } else if (part.length > 0) {
79
+ segments.push({ kind: 'text', text: part })
80
+ }
81
+ })
82
+
83
+ return segments
84
+ }
85
+
86
+ /** A cited record as a Markdown node: a link to its page, or its name when it has none. */
87
+ function referenceNode(reference: RecordReference): Link | Text {
88
+ const href = referenceHref(reference)
89
+ const name: Text = { type: 'text', value: reference.name }
90
+
91
+ return href === undefined ? name : { type: 'link', url: href, title: null, children: [name] }
92
+ }
93
+
94
+ /** Node types whose text must stay as written: a link cannot hold a link, and code is literal. */
95
+ const LEAVE_ALONE = new Set(['link', 'linkReference', 'code', 'inlineCode'])
96
+
97
+ function isParent(node: { readonly type: string }): node is Parent {
98
+ return 'children' in node && Array.isArray(node.children)
99
+ }
100
+
101
+ function rewriteChildren(parent: Parent, references: readonly RecordReference[]): void {
102
+ const rewritten: Parent['children'] = []
103
+
104
+ for (const child of parent.children) {
105
+ if (child.type === 'text') {
106
+ for (const segment of splitOnReferences(child.value, references)) {
107
+ rewritten.push(
108
+ segment.kind === 'text'
109
+ ? ({ type: 'text', value: segment.text } satisfies PhrasingContent)
110
+ : segment.kind === 'reference'
111
+ ? referenceNode(segment.reference)
112
+ : ({ type: 'text', value: unresolvedLabel(segment.token) } satisfies PhrasingContent),
113
+ )
114
+ }
115
+ } else {
116
+ if (isParent(child) && !LEAVE_ALONE.has(child.type)) {
117
+ rewriteChildren(child, references)
118
+ }
119
+
120
+ rewritten.push(child)
121
+ }
122
+ }
123
+
124
+ parent.children = rewritten
125
+ }
126
+
127
+ /**
128
+ * A remark plugin: every cited record in the Markdown's text, bare id or link
129
+ * token, becomes a link to the record, labelled with its name. The source string
130
+ * is not touched, so what the author wrote is still what is stored and edited.
131
+ */
132
+ export function remarkRecordReferences(
133
+ references: readonly RecordReference[],
134
+ ): () => (tree: Root) => void {
135
+ // Runs even with no references: a token must still lose its brackets.
136
+ return () => (tree) => {
137
+ rewriteChildren(tree, references)
138
+ }
139
+ }
@@ -0,0 +1,23 @@
1
+ import { AiPage } from '../pages/admin/AiPage.tsx'
2
+ import type { UiModule } from '../registry/registry.ts'
3
+ import { aiRunner } from './aiRunner.ts'
4
+
5
+ /**
6
+ * The UI half of the optional `ai` module in `@kelpie/server`.
7
+ *
8
+ * Not registered by default. An assembly that lists `createAiModule()` on the
9
+ * server lists `aiUi` in `kelpie.ui.config.ts`, the same pairing any module
10
+ * uses. One Admin nav item, after MCP, and one page. On record pages it is the
11
+ * Agent menu's runner: Run dispatches straight to the "Kelpie AI" agent row, and
12
+ * stays disabled until AI is enabled and has a key. Preview's Run… still lists
13
+ * every registered agent, Kelpie AI included.
14
+ */
15
+ export const aiUi: UiModule = {
16
+ id: 'ai',
17
+
18
+ register(context) {
19
+ context.nav('admin', { id: 'ai', label: 'AI', to: '/admin/ai', order: 550 })
20
+ context.route({ path: 'admin/ai', element: <AiPage /> })
21
+ context.agentRunner(aiRunner)
22
+ },
23
+ }