rvlib-shipkit 2.11.0 → 2.13.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 (298) hide show
  1. package/CHANGELOG.md +56 -12
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +96 -5
  20. package/src/cli/cmd_Review.ts +8 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +9 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +61 -6
  68. package/src/home/inbox.ts +75 -4
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +110 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +9 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/content.ts +11 -1
  100. package/src/media-store/daemon.ts +56 -70
  101. package/src/media-store/hand.ts +58 -0
  102. package/src/media-store/put.ts +122 -0
  103. package/src/media-store/space.ts +73 -11
  104. package/src/pages/forward.ts +35 -0
  105. package/src/pages/frame-client.ts +118 -0
  106. package/src/pages/routes.ts +29 -0
  107. package/src/pages/unit.ts +92 -0
  108. package/src/plan/planner.ts +12 -0
  109. package/src/plan/repo-source.ts +19 -5
  110. package/src/reflect/transcript.ts +35 -10
  111. package/src/release/public-clean.ts +301 -0
  112. package/src/release/published-here.ts +22 -0
  113. package/src/release/run-bump.ts +2 -1
  114. package/src/release/run-release.ts +4 -1
  115. package/src/repo-config.ts +53 -2
  116. package/src/review/http.ts +16 -2
  117. package/src/review/media-kind.ts +3 -3
  118. package/src/review/media-read.ts +3 -3
  119. package/src/review/model.ts +24 -5
  120. package/src/review/notes.ts +77 -0
  121. package/src/review/project.ts +6 -38
  122. package/src/review/routes.ts +8 -13
  123. package/src/review/store.ts +46 -4
  124. package/src/review/trailer-media.ts +24 -3
  125. package/src/review/trailer-shots.ts +106 -0
  126. package/src/review/unit.ts +1 -1
  127. package/src/scaffold/files/agent-handoff.md +3 -0
  128. package/src/scaffold/files/agent-index.md +4 -12
  129. package/src/scaffold/project-scaffold.ts +5 -4
  130. package/src/serve/embed.ts +1 -1
  131. package/src/serve/hub-app/col-card.tsx +3 -17
  132. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  133. package/src/serve/hub-app/cols-svc.ts +12 -14
  134. package/src/serve/hub-app/dock-st.ts +4 -2
  135. package/src/serve/hub-app/dock-view.tsx +2 -0
  136. package/src/serve/hub-app/frames-st.ts +35 -0
  137. package/src/serve/hub-app/hash-route.ts +64 -1
  138. package/src/serve/hub-app/home-st.ts +31 -7
  139. package/src/serve/hub-app/home-strip.css +9 -1
  140. package/src/serve/hub-app/home-strip.tsx +7 -6
  141. package/src/serve/hub-app/home.html +5 -0
  142. package/src/serve/hub-app/hub-app.tsx +49 -5
  143. package/src/serve/hub-app/hub.css +29 -11
  144. package/src/serve/hub-app/icons.tsx +16 -1
  145. package/src/serve/hub-app/identities-st.ts +210 -0
  146. package/src/serve/hub-app/identities-view.tsx +352 -0
  147. package/src/serve/hub-app/identities.css +48 -0
  148. package/src/serve/hub-app/identity-address.ts +52 -0
  149. package/src/serve/hub-app/inbox-st.ts +59 -6
  150. package/src/serve/hub-app/inbox-view.tsx +48 -6
  151. package/src/serve/hub-app/inbox.css +12 -1
  152. package/src/serve/hub-app/index.html +3 -0
  153. package/src/serve/hub-app/keys.ts +10 -2
  154. package/src/serve/hub-app/list-walk.ts +89 -0
  155. package/src/serve/hub-app/machine-st.ts +12 -0
  156. package/src/serve/hub-app/media-view.tsx +2 -1
  157. package/src/serve/hub-app/pages-frames.tsx +134 -0
  158. package/src/serve/hub-app/pages-svc.ts +111 -0
  159. package/src/serve/hub-app/palette-st.ts +18 -3
  160. package/src/serve/hub-app/palette-view.tsx +9 -2
  161. package/src/serve/hub-app/planned-view.tsx +2 -1
  162. package/src/serve/hub-app/project-list.css +18 -14
  163. package/src/serve/hub-app/project-list.tsx +88 -49
  164. package/src/serve/hub-app/projects-svc.ts +33 -3
  165. package/src/serve/hub-app/repo-sections.ts +19 -2
  166. package/src/serve/hub-app/repo-st.ts +75 -19
  167. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  168. package/src/serve/hub-app/review/review-kit.ts +30 -7
  169. package/src/serve/hub-app/review/review-page.tsx +1 -1
  170. package/src/serve/hub-app/review/review-st.ts +33 -11
  171. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  172. package/src/serve/hub-app/review/review-views.tsx +84 -19
  173. package/src/serve/hub-app/review/thread-st.ts +1 -10
  174. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  175. package/src/serve/hub-app/review.css +17 -8
  176. package/src/serve/hub-app/site/site-part.tsx +173 -0
  177. package/src/serve/hub-app/site/site-st.ts +157 -0
  178. package/src/serve/hub-app/site.css +35 -0
  179. package/src/serve/hub-app/social/calendar.tsx +182 -0
  180. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  181. package/src/serve/hub-app/social/kit.tsx +244 -0
  182. package/src/serve/hub-app/social/post-card.tsx +456 -0
  183. package/src/serve/hub-app/social/problems.tsx +60 -0
  184. package/src/serve/hub-app/social/social-model.ts +154 -0
  185. package/src/serve/hub-app/social/social-page.tsx +674 -0
  186. package/src/serve/hub-app/social/social-st.ts +986 -0
  187. package/src/serve/hub-app/social.css +289 -0
  188. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  189. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  190. package/src/serve/hub-app/stores.css +54 -0
  191. package/src/serve/hub-app/test-view.tsx +9 -2
  192. package/src/serve/hub-app/tests-svc.ts +16 -1
  193. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  194. package/src/serve/hub-app/timeline-view.tsx +3 -2
  195. package/src/serve/hub-app/tree-build.ts +6 -0
  196. package/src/serve/hub-app/tree-row.tsx +27 -4
  197. package/src/serve/hub-app/tree-svc.ts +18 -49
  198. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  199. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  200. package/src/serve/hub-app/veille.css +84 -0
  201. package/src/serve/hub-runtime.ts +14 -9
  202. package/src/serve/project-gutter-route.ts +44 -12
  203. package/src/serve/resources-wire.ts +48 -0
  204. package/src/serve/run-lanes.ts +7 -4
  205. package/src/serve/same-origin.ts +1 -1
  206. package/src/serve/serve-hub.ts +27 -18
  207. package/src/serve/tracked-watch.ts +24 -3
  208. package/src/serve/warm-cell.ts +5 -1
  209. package/src/shipkit-files.ts +15 -4
  210. package/src/shipkit.ts +0 -1
  211. package/src/shot/box.ts +162 -0
  212. package/src/shot/browser-slot.ts +62 -0
  213. package/src/shot/client.ts +43 -7
  214. package/src/shot/clip-encoder.ts +93 -12
  215. package/src/shot/film-box.ts +188 -0
  216. package/src/shot/shooter.ts +50 -15
  217. package/src/shot/shot-ask.ts +10 -2
  218. package/src/shot/stepped-clip.ts +5 -4
  219. package/src/site/desk.ts +242 -0
  220. package/src/site/routes.ts +66 -0
  221. package/src/site/unit.ts +62 -0
  222. package/src/social/brands.ts +22 -0
  223. package/src/social/compose.ts +97 -0
  224. package/src/social/desk-index.ts +123 -0
  225. package/src/social/desk-wire.ts +64 -0
  226. package/src/social/drafts.ts +183 -0
  227. package/src/social/house.ts +24 -0
  228. package/src/social/load.ts +319 -0
  229. package/src/social/md.ts +70 -0
  230. package/src/social/media-facts.ts +53 -0
  231. package/src/social/media-kind.ts +189 -0
  232. package/src/social/media-limit.ts +42 -0
  233. package/src/social/media-of.ts +30 -0
  234. package/src/social/migrate.ts +123 -0
  235. package/src/social/open.ts +17 -0
  236. package/src/social/post-url.ts +158 -0
  237. package/src/social/presence.ts +332 -0
  238. package/src/social/public-read.ts +53 -0
  239. package/src/social/publish/bluesky.ts +168 -0
  240. package/src/social/publish/discord.ts +76 -0
  241. package/src/social/publish/index.ts +24 -0
  242. package/src/social/publish/secret.ts +13 -0
  243. package/src/social/push.ts +31 -0
  244. package/src/social/richtext.ts +37 -0
  245. package/src/social/routes.ts +180 -0
  246. package/src/social/stats.ts +134 -0
  247. package/src/social/text.ts +267 -0
  248. package/src/social/tracker-route.ts +39 -0
  249. package/src/social/tracker.ts +255 -0
  250. package/src/social/unit.ts +53 -0
  251. package/src/social/writes.ts +130 -0
  252. package/src/start-repo.ts +14 -9
  253. package/src/stores/collection.ts +27 -0
  254. package/src/stores/desk.ts +336 -0
  255. package/src/stores/model.ts +187 -0
  256. package/src/stores/routes.ts +126 -0
  257. package/src/stores/unit.ts +57 -0
  258. package/src/suite/calibrate.ts +127 -0
  259. package/src/suite/core-counters.ts +91 -0
  260. package/src/suite/judge-suites.ts +94 -34
  261. package/src/suite/suite-cli.ts +44 -10
  262. package/src/suite/suite-cpu-preload.ts +34 -9
  263. package/src/trailer/adapter.ts +4 -0
  264. package/src/trailer/build.ts +42 -11
  265. package/src/trailer/ffmpeg.ts +11 -0
  266. package/src/trailer/footage.ts +30 -13
  267. package/src/trailer/grammar.ts +18 -2
  268. package/src/trailer/graph.ts +28 -6
  269. package/src/trailer/passage.ts +21 -6
  270. package/src/trailer/plan.ts +74 -3
  271. package/src/trailer/shelf.ts +16 -0
  272. package/src/trailer/stitch.ts +67 -26
  273. package/src/trailer/url.ts +1 -1
  274. package/src/trailer/versions.ts +24 -0
  275. package/src/ts/gate-typecheck.ts +32 -0
  276. package/src/ts/typecheck-cli.ts +9 -11
  277. package/src/tui/tui-app.tsx +0 -1
  278. package/src/veille/asks.ts +155 -0
  279. package/src/veille/auto.ts +31 -0
  280. package/src/veille/batch.ts +27 -0
  281. package/src/veille/chrome.ts +127 -0
  282. package/src/veille/collection.ts +28 -0
  283. package/src/veille/desk.ts +242 -0
  284. package/src/veille/identity.ts +80 -0
  285. package/src/veille/import.ts +68 -0
  286. package/src/veille/log.ts +183 -0
  287. package/src/veille/platforms.ts +118 -0
  288. package/src/veille/reads.ts +66 -0
  289. package/src/veille/replied.ts +110 -0
  290. package/src/veille/routes.ts +185 -0
  291. package/src/veille/service.ts +81 -0
  292. package/src/veille/watch.ts +116 -0
  293. package/src/veille/worth.ts +46 -0
  294. package/src/wiki/scan-md.ts +18 -0
  295. package/src/collections/posts.ts +0 -142
  296. package/src/contracts/manifests/social.contract.ts +0 -20
  297. package/src/scaffold/files/agent-coding.md +0 -35
  298. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,986 @@
1
+ // the Communications and Social pages as state (wiki build/shipkit/social.md, The desks in the hub): one desk read from
2
+ // the hub for both, what each page picked, the list's view, the folds he set, the editor, his notes, the writes. A
3
+ // pick goes through RepoSt (showComms, showSocial), the one writer of the address
4
+ import { makeAutoObservable, runInAction } from 'mobx'
5
+ import { compose, messageLength } from '../../../social/compose.ts'
6
+ import { deskOfWire, type Wire } from '../../../social/desk-wire.ts'
7
+ import { identityAddress } from '../identity-address.ts'
8
+ import { SEARCH_KEY } from '../keys.ts'
9
+ import { reach } from '../reach.ts'
10
+ import type { RepoSt } from '../repo-st.ts'
11
+ import { copyText, postJson } from '../review/review-kit.ts'
12
+ import {
13
+ caption,
14
+ commsQuery,
15
+ countsOf,
16
+ draftWaiting,
17
+ FAMS,
18
+ LEGAL,
19
+ legalLive,
20
+ ME,
21
+ partsOf,
22
+ readCommsQuery,
23
+ waiting,
24
+ type CommsView,
25
+ type DeskAccount,
26
+ type DeskIdentity,
27
+ type DeskJson,
28
+ type Draft,
29
+ type Fam,
30
+ type Media,
31
+ type Picture,
32
+ type Place,
33
+ type SocialPost,
34
+ type Timeline,
35
+ } from './social-model.ts'
36
+
37
+ /** a heading's text and title as he types them in the editor, until saved */
38
+ export type DraftEdit = { text: string; tags: string; title: string | null }
39
+ /** a post URL of ours the tracker saw that no opened message took: « seen, which post? » */
40
+ export type SeenPost = { identity: string; platform: string; url: string; at: number }
41
+ type TrackerView = { seen: SeenPost[]; stamp: number; debug: Record<string, string[]> }
42
+ const TRACKER_MS = 4000
43
+ /** past this, a pending first read says what it waits on */
44
+ const SLOW_MS = 3000
45
+
46
+ /** where a pick goes when the desk is read by another page than the repo's own (the home's identity view): its
47
+ * address moves there, never the repo's */
48
+ export type SocialNav = {
49
+ social(identity: string, account: string | null, place: string | null): void
50
+ draft(slug: string): void
51
+ }
52
+
53
+ /** his note on a draft, an item of the review store */
54
+ export type DraftNote = { id: string; at: string; text: string; state: string; answer?: string }
55
+
56
+ const VIEW = 'hub:comms-view'
57
+ const SERIES = 'hub:comms-series'
58
+ const CALENDAR = 'hub:comms-calendar'
59
+ const FOLDS = 'hub:social-folds'
60
+
61
+ const kept = <T>(key: string, fallback: T): T => {
62
+ try {
63
+ const raw = localStorage.getItem(key)
64
+ return raw == null ? fallback : (JSON.parse(raw) as T)
65
+ } catch {
66
+ return fallback
67
+ }
68
+ }
69
+ const keep = (key: string, v: unknown): void => {
70
+ try {
71
+ localStorage.setItem(key, JSON.stringify(v))
72
+ } catch {
73
+ // private mode: it lasts for this page
74
+ }
75
+ }
76
+
77
+ export class SocialSt {
78
+ desk: DeskJson | null = null
79
+ /** the url and ETag of the desk held: « not modified » keeps it, nothing draws again */
80
+ deskHeld: { url: string; tag: string } | null = null
81
+ loadError: string | null = null
82
+ /** the desk's first read has waited past SLOW_MS: the words say what it waits on */
83
+ slow = false
84
+ /** the live numbers apart, by identity then account: a slow platform never holds the desk */
85
+ stats: Record<string, Record<string, string>> = {}
86
+
87
+ // Communications
88
+ draftSlug: string | null = null
89
+ /** one message of a series opened alone, by its name; null, the whole draft */
90
+ draftPart: string | null = null
91
+ fam: Fam | null = null
92
+ channel: string | null = null
93
+ newestFirst = true
94
+ /** the identity the list keeps; null, every one */
95
+ who: string | null = null
96
+ draftQuery = ''
97
+ calendarOpen = true
98
+ /** the drafts whose sub entries he folded in the list */
99
+ foldedSeries: Record<string, true> = {}
100
+
101
+ // Social
102
+ identity: string | null = null
103
+ /** null the identity's card, LEGAL its company, else an account */
104
+ account: string | null = null
105
+ /** null the whole account, ME its own profile, else one of its places */
106
+ place: string | null = null
107
+ accountQuery = ''
108
+ showRejected = false
109
+ /** the cards he folded or opened, by card (`notes`, `setup/<account>`…); unset, the card's default */
110
+ folds: Record<string, boolean> = {}
111
+
112
+ // both
113
+ busy = false
114
+ error: string | null = null
115
+ /** the URL fields as typed, until saved */
116
+ urls: Record<string, string> = {}
117
+ /** a URL field's refused save, by its key: shown under it, what he typed kept */
118
+ urlErrors: Record<string, string> = {}
119
+ /** the value last copied, a moment */
120
+ copiedKey: string | null = null
121
+ lightbox: { slug: string; name: string } | null = null
122
+ /** a « Publish » in flight, by `<key>/<slug>`: each locks its own line only */
123
+ publishing: Record<string, true> = {}
124
+ publishError: Record<string, string> = {}
125
+ /** the headings open in the editor, `<heading key>/<slug>` */
126
+ edits: Record<string, DraftEdit> = {}
127
+ notes: Record<string, DraftNote[]> = {}
128
+ toast: string | null = null
129
+ /** the phone shows one pane at a time: the list, or what it opened */
130
+ phonePane: 'list' | 'detail' = 'list'
131
+ /** the post tracker by identity: the URLs waiting for a line, its stamp, its last steps by platform */
132
+ tracker: Record<string, TrackerView> = {}
133
+ /** the line whose « search » runs, and what each found, by `<key>/<slug>` */
134
+ searching: string | null = null
135
+ searched: Record<string, string> = {}
136
+ /** the shown page's search box: `/` focuses it, never the tree's filter */
137
+ searchEl: HTMLInputElement | null = null
138
+ private started = 0
139
+ private trackerTimer: ReturnType<typeof setInterval> | null = null
140
+ private toastTimer: ReturnType<typeof setTimeout> | null = null
141
+ private copyTimer: ReturnType<typeof setTimeout> | null = null
142
+
143
+ constructor(
144
+ private readonly st: RepoSt,
145
+ private readonly nav: SocialNav | null = null,
146
+ ) {
147
+ const v = kept<Partial<CommsView>>(VIEW, {})
148
+ this.fam = v.fam ?? null
149
+ this.channel = v.channel ?? null
150
+ this.newestFirst = v.newestFirst ?? true
151
+ this.who = v.who ?? null
152
+ for (const slug of kept<unknown[]>(SERIES, [])) if (typeof slug === 'string') this.foldedSeries[slug] = true
153
+ this.calendarOpen = kept<boolean>(CALENDAR, true)
154
+ for (const [k, x] of Object.entries(kept<Record<string, unknown>>(FOLDS, {}))) if (typeof x === 'boolean') this.folds[k] = x
155
+ makeAutoObservable<this, 'st' | 'nav' | 'started' | 'toastTimer' | 'copyTimer' | 'trackerTimer' | 'onBack'>(this, { st: false, nav: false, started: false, toastTimer: false, copyTimer: false, trackerTimer: false, onBack: false, searchEl: false })
156
+ }
157
+
158
+ /** the home's view of an identity, every account its own page; null off the home (a hub of its own, a frame) */
159
+ homeLink(identity: string): string | null {
160
+ return this.st.home.machine == null || this.st.home.embedded ? null : identityAddress({ id: identity, part: null, place: null })
161
+ }
162
+
163
+ /** the home's view of an identity, in place */
164
+ openHome(identity: string): void {
165
+ this.st.home.openIdentity({ id: identity, part: null, place: null })
166
+ }
167
+
168
+ /** the repo whose desk this reads */
169
+ get repoName(): string {
170
+ return this.st.name
171
+ }
172
+
173
+ /** the page laid out for a phone (the review page's switch) */
174
+ get phone(): boolean {
175
+ return this.st.review.phone.on
176
+ }
177
+
178
+ // ── the desk ─────────────────────────────────────────────────────────
179
+
180
+ /** a page shows: read the desk and the numbers, and again when the window comes back */
181
+ start(): void {
182
+ if (this.started++ === 0) {
183
+ window.addEventListener('focus', this.onBack)
184
+ this.trackerTimer = setInterval(() => void this.loadTracker(), TRACKER_MS)
185
+ }
186
+ void this.load()
187
+ void this.loadStats()
188
+ void this.loadTracker()
189
+ }
190
+
191
+ stop(): void {
192
+ if (--this.started === 0) {
193
+ window.removeEventListener('focus', this.onBack)
194
+ if (this.trackerTimer) clearInterval(this.trackerTimer)
195
+ this.trackerTimer = null
196
+ }
197
+ }
198
+
199
+ /** the tracker's state; a stamp that moved means it wrote a line, so the desk is read again and the card greens */
200
+ async loadTracker(): Promise<void> {
201
+ try {
202
+ const r = await reach(this.st.url('/api/social/tracker.json'))
203
+ if (!r.ok) return
204
+ const body = (await r.json()) as Record<string, TrackerView>
205
+ const moved = Object.entries(body).some(([id, v]) => this.tracker[id] !== undefined && this.tracker[id]!.stamp !== v.stamp)
206
+ runInAction(() => (this.tracker = body))
207
+ if (moved) await this.load()
208
+ } catch {
209
+ // the tracker is a help: the page works without it
210
+ }
211
+ }
212
+
213
+ /** « Post » clicked: the tracker takes a post seen next on this platform for this message */
214
+ opened(p: SocialPost): void {
215
+ void postJson(this.st.url('/api/social/opened'), { slug: p.slug, key: p.key }).catch((e: unknown) => runInAction(() => (this.error = (e as Error).message)))
216
+ }
217
+
218
+ /** the URLs the tracker saw on this message's platform while its line waits */
219
+ seenFor(p: SocialPost): SeenPost[] {
220
+ return p.posted === '' ? (this.tracker[p.identity]?.seen ?? []).filter((s) => s.platform === p.platform) : []
221
+ }
222
+
223
+ /** the tooltip of a URL field: what the tracker last did on its platform */
224
+ debugFor(p: SocialPost): string | undefined {
225
+ const lines = this.tracker[p.identity]?.debug[p.platform]
226
+ return lines?.length ? `the post tracker, its last steps:\n${lines.join('\n')}` : undefined
227
+ }
228
+
229
+ /** « here »: a seen URL written on this line */
230
+ async takeSeen(s: SeenPost, p: SocialPost): Promise<void> {
231
+ await this.write('seen-take', { url: s.url, slug: p.slug, key: p.key })
232
+ await this.loadTracker()
233
+ }
234
+
235
+ /** « ✕ »: a seen URL forgotten */
236
+ async dropSeen(s: SeenPost): Promise<void> {
237
+ try {
238
+ await postJson(this.st.url('/api/social/seen-drop'), { url: s.url })
239
+ } catch (e) {
240
+ runInAction(() => (this.error = (e as Error).message))
241
+ }
242
+ await this.loadTracker()
243
+ }
244
+
245
+ /** « search »: the post URLs of this platform in a copy of the identity's Chrome History, since its last open */
246
+ async searchHistory(p: SocialPost): Promise<void> {
247
+ const k = this.postKey(p)
248
+ this.searching = k
249
+ this.error = null
250
+ try {
251
+ const r = await postJson<{ counts: Record<string, number> }>(this.st.url('/api/social/history'), { identity: p.identity, platform: p.platform })
252
+ const n = (x: string): number => r.counts[x] ?? 0
253
+ runInAction(() => (this.searched[k] = n('record') + n('seen') + n('known') === 0 ? 'nothing new' : `${n('record')} written · ${n('seen')} seen · ${n('known')} already there`))
254
+ await this.load()
255
+ await this.loadTracker()
256
+ } catch (e) {
257
+ runInAction(() => (this.error = (e as Error).message))
258
+ } finally {
259
+ runInAction(() => (this.searching = null))
260
+ }
261
+ }
262
+
263
+ private readonly onBack = (): void => void this.load()
264
+
265
+ /** what the page says while the desk is not read yet: never a bare « loading… » */
266
+ get waitText(): string {
267
+ return this.slow
268
+ ? `still waiting on the hub of ${this.st.name} for its desk: a hub loads its repo on the first request after the daemon restarts, and the page says why if it gives up`
269
+ : `reading the desk of ${this.st.name}…`
270
+ }
271
+
272
+ async load(): Promise<void> {
273
+ const slow = this.desk == null ? setTimeout(() => runInAction(() => (this.slow = true)), SLOW_MS) : null
274
+ try {
275
+ const url = this.st.url('/api/social/desk.json')
276
+ const held = this.desk != null && this.deskHeld?.url === url ? this.deskHeld : null
277
+ const r = await reach(url, { cache: 'no-store', headers: held ? { 'If-None-Match': held.tag } : {} })
278
+ if (r.status === 304 && held) {
279
+ runInAction(() => (this.loadError = null))
280
+ return
281
+ }
282
+ if (!r.ok) {
283
+ const text = await r.text()
284
+ let said = text.slice(0, 400)
285
+ try { said = (JSON.parse(text) as { error?: string }).error ?? said } catch { /* a plain text answer says it as it is */ }
286
+ throw new Error(`the desk of ${this.st.name} answered ${r.status}: ${said}`)
287
+ }
288
+ const body = (await r.json()) as Wire<DeskJson>
289
+ const desk = deskOfWire<DeskJson>(body)
290
+ const tag = r.headers.get('ETag')
291
+ runInAction(() => {
292
+ this.desk = desk
293
+ this.deskHeld = tag ? { url, tag } : null
294
+ this.loadError = null
295
+ })
296
+ } catch (e) {
297
+ runInAction(() => (this.loadError = (e as Error).message))
298
+ } finally {
299
+ if (slow != null) clearTimeout(slow)
300
+ runInAction(() => (this.slow = false))
301
+ }
302
+ }
303
+
304
+ async loadStats(): Promise<void> {
305
+ try {
306
+ const r = await reach(this.st.url('/api/social/stats.json'))
307
+ if (!r.ok) return
308
+ const body = (await r.json()) as Record<string, Record<string, string>>
309
+ runInAction(() => (this.stats = body))
310
+ } catch {
311
+ // the numbers are a nicety: the cards show without them
312
+ }
313
+ }
314
+
315
+ get identities(): DeskIdentity[] {
316
+ return this.desk?.identities ?? []
317
+ }
318
+
319
+ /** the identity this repo speaks as */
320
+ get own(): DeskIdentity | null {
321
+ return this.identities.find((i) => i.id === this.desk?.speaksAs) ?? null
322
+ }
323
+
324
+ /** every identity, the repo's own first */
325
+ get identitiesOwnFirst(): DeskIdentity[] {
326
+ const own = this.own
327
+ return own ? [own, ...this.identities.filter((i) => i !== own)] : this.identities
328
+ }
329
+
330
+ identityOf(id: string): DeskIdentity | null {
331
+ return this.identities.find((i) => i.id === id) ?? null
332
+ }
333
+
334
+ accountOf(identity: string, id: string): DeskAccount | null {
335
+ return this.identityOf(identity)?.accounts.find((a) => a.id === id) ?? null
336
+ }
337
+
338
+ /** a message's account, on its speaker's identity */
339
+ postAccount(p: SocialPost): DeskAccount | null {
340
+ return this.accountOf(p.identity, p.platform)
341
+ }
342
+
343
+ get errors(): string[] {
344
+ return this.desk?.errors ?? []
345
+ }
346
+
347
+ statOf(a: DeskAccount): string | undefined {
348
+ return this.stats[a.identity]?.[a.id]
349
+ }
350
+
351
+ // ── Communications: the list ─────────────────────────────────────────
352
+
353
+ get drafts(): Draft[] {
354
+ const by = this.newestFirst ? -1 : 1
355
+ return [...(this.desk?.drafts ?? [])].sort((x, y) => by * x.slug.localeCompare(y.slug))
356
+ }
357
+
358
+ get family(): (typeof FAMS)[Fam] | null {
359
+ return this.fam === null ? null : FAMS[this.fam]
360
+ }
361
+
362
+ /** a message to an account of the family the list keeps; every one with no family */
363
+ inFamilyPost(p: SocialPost): boolean {
364
+ return this.family === null || this.postAccount(p)?.family === this.family
365
+ }
366
+
367
+ familyPosts(d: Draft): SocialPost[] {
368
+ return d.posts.filter((p) => this.inFamilyPost(p))
369
+ }
370
+
371
+ private kept(d: Draft): boolean {
372
+ return (this.family === null || this.familyPosts(d).length > 0) && (this.channel === null || d.posts.some((p) => p.platform === this.channel)) && (this.who === null || d.identity === this.who)
373
+ }
374
+
375
+ /** every platform some draft writes for, the family's only, in the accounts' order */
376
+ get channels(): string[] {
377
+ const used = new Set(this.drafts.filter((d) => this.who === null || d.identity === this.who).flatMap((d) => this.familyPosts(d).map((p) => p.platform)))
378
+ const order = this.identitiesOwnFirst.flatMap((i) => i.accounts.map((a) => a.id))
379
+ return [...new Set([...order.filter((id) => used.has(id)), ...[...used].sort()])]
380
+ }
381
+
382
+ /** the identities a filter offers, each with its drafts in this repo */
383
+ get speakers(): { id: string; name: string; n: number }[] {
384
+ return this.identitiesOwnFirst.map((i) => ({ id: i.id, name: i.name, n: this.drafts.filter((d) => d.identity === i.id).length }))
385
+ }
386
+
387
+ get visibleDrafts(): Draft[] {
388
+ const q = this.draftQuery.trim().toLowerCase()
389
+ return this.drafts.filter((d) => this.kept(d) && (!q || `${d.slug} ${d.title} ${d.posts.map((p) => p.platform).join(' ')}`.toLowerCase().includes(q)))
390
+ }
391
+
392
+ /** the list's totals: the drafts its view keeps, and those with a message of the family still to post */
393
+ get listTotals(): { drafts: number; waiting: number } {
394
+ const kept = this.drafts.filter((d) => this.kept(d))
395
+ return { drafts: kept.length, waiting: kept.filter((d) => d.status !== 'rejected' && this.familyPosts(d).some((p) => p.posted === '')).length }
396
+ }
397
+
398
+ /** the draft shown is always one the view keeps */
399
+ get currentDraft(): Draft | null {
400
+ const kept = this.drafts.filter((d) => this.kept(d))
401
+ return kept.find((d) => d.slug === this.draftSlug) ?? kept[0] ?? null
402
+ }
403
+
404
+ get currentPart(): string | null {
405
+ const d = this.currentDraft
406
+ return d && this.draftPart !== null && partsOf(d).includes(this.draftPart) ? this.draftPart : null
407
+ }
408
+
409
+ isDraft(d: Draft): boolean {
410
+ return d.slug === this.currentDraft?.slug
411
+ }
412
+
413
+ /** the messages the middle shows: the part opened, else every one */
414
+ shownMessages(d: Draft): SocialPost[] {
415
+ const part = this.isDraft(d) ? this.currentPart : null
416
+ return part === null ? d.posts : d.posts.filter((p) => p.name === part)
417
+ }
418
+
419
+ listCounts(d: Draft, part?: string): { posted: number; of: number } {
420
+ return countsOf(this.familyPosts(d).filter((p) => part === undefined || p.name === part))
421
+ }
422
+
423
+ /** a series' messages the list keeps: those with a message to the family */
424
+ listParts(d: Draft): string[] {
425
+ const names = new Set(this.familyPosts(d).map((p) => p.name))
426
+ return partsOf(d).filter((x) => names.has(x))
427
+ }
428
+
429
+ seriesFolded(d: Draft): boolean {
430
+ return this.foldedSeries[d.slug] === true
431
+ }
432
+
433
+ /** the sub entries the list shows under a draft: none while folded, unless one of them is open */
434
+ shownParts(d: Draft): string[] {
435
+ const parts = this.listParts(d)
436
+ if (!this.seriesFolded(d)) return parts
437
+ return this.isDraft(d) && this.currentPart !== null ? parts.filter((x) => x === this.currentPart) : []
438
+ }
439
+
440
+ flipSeries(d: Draft): void {
441
+ if (this.seriesFolded(d)) delete this.foldedSeries[d.slug]
442
+ else this.foldedSeries[d.slug] = true
443
+ keep(SERIES, Object.keys(this.foldedSeries))
444
+ }
445
+
446
+ get allFolded(): boolean {
447
+ return this.drafts.every((d) => partsOf(d).length === 0 || this.seriesFolded(d))
448
+ }
449
+
450
+ foldAll(fold: boolean): void {
451
+ this.foldedSeries = fold ? Object.fromEntries(this.drafts.filter((d) => partsOf(d).length > 0).map((d) => [d.slug, true as const])) : {}
452
+ keep(SERIES, Object.keys(this.foldedSeries))
453
+ }
454
+
455
+ setDraftQuery(q: string): void {
456
+ this.draftQuery = q
457
+ }
458
+
459
+ flipCalendar(): void {
460
+ this.calendarOpen = !this.calendarOpen
461
+ keep(CALENDAR, this.calendarOpen)
462
+ }
463
+
464
+ /** the list's view as the address carries it */
465
+ get commsAddress(): string {
466
+ return commsQuery({ fam: this.fam, channel: this.channel, newestFirst: this.newestFirst, who: this.who })
467
+ }
468
+
469
+ /** an address's query: a key it leaves out keeps what the page remembers */
470
+ applyCommsAddress(q: string): void {
471
+ this.applyView(readCommsQuery(q))
472
+ }
473
+
474
+ private applyView(v: Partial<CommsView>): void {
475
+ if (v.fam !== undefined) this.fam = v.fam
476
+ if (v.newestFirst !== undefined) this.newestFirst = v.newestFirst
477
+ if (v.who !== undefined) this.who = v.who
478
+ if (v.channel !== undefined) this.channel = v.channel
479
+ // a channel outside the family would hide every draft
480
+ if (this.channel !== null && this.desk != null && !this.channels.includes(this.channel)) this.channel = null
481
+ keep(VIEW, { fam: this.fam, channel: this.channel, newestFirst: this.newestFirst, who: this.who })
482
+ }
483
+
484
+ /** a filter, the order: the view changes, the address follows it */
485
+ setView(v: Partial<CommsView>): void {
486
+ this.applyView(v)
487
+ this.st.showComms(this.draftSlug, this.draftPart)
488
+ }
489
+
490
+ /** a draft, or one message of its series: the list stops hiding a draft opened from elsewhere */
491
+ selectDraft(slug: string | null, part: string | null): void {
492
+ this.draftSlug = slug
493
+ this.draftPart = part
494
+ const d = slug == null ? undefined : this.drafts.find((x) => x.slug === slug)
495
+ if (d) {
496
+ const clear: Partial<CommsView> = {}
497
+ if (this.family !== null && this.familyPosts(d).length === 0) clear.fam = null
498
+ if (this.channel !== null && !d.posts.some((p) => p.platform === this.channel)) clear.channel = null
499
+ if (this.who !== null && d.identity !== this.who) clear.who = null
500
+ if (Object.keys(clear).length > 0) this.applyView(clear)
501
+ }
502
+ }
503
+
504
+ /** a click on a draft, a series' message, a calendar dot */
505
+ pickDraft(slug: string, part: string | null = null): void {
506
+ this.phonePane = 'detail'
507
+ this.st.showComms(slug, part)
508
+ }
509
+
510
+ /** the arrows through the list as it shows: a draft, its sub entries unless folded, the next draft */
511
+ moveDraft(delta: number): void {
512
+ const rows = this.visibleDrafts.flatMap((d) => [{ slug: d.slug, part: null as string | null }, ...this.shownParts(d).map((part) => ({ slug: d.slug, part }))])
513
+ const at = rows.findIndex((r) => r.slug === this.currentDraft?.slug && r.part === this.currentPart)
514
+ const next = rows[Math.max(0, Math.min(rows.length - 1, Math.max(0, at) + delta))]
515
+ if (next) this.st.showComms(next.slug, next.part)
516
+ }
517
+
518
+ /** → and ← as a file tree: → opens a folded series, then goes to its first message; ← on a message goes back to
519
+ * its series, then folds it */
520
+ treeStep(dir: 1 | -1): void {
521
+ const d = this.currentDraft
522
+ if (d == null) return
523
+ const parts = partsOf(d)
524
+ const part = this.currentPart
525
+ if (parts.length === 0) return
526
+ if (dir === 1) {
527
+ if (part !== null) return
528
+ if (this.seriesFolded(d)) this.flipSeries(d)
529
+ else this.st.showComms(d.slug, parts[0]!)
530
+ } else if (part !== null) this.st.showComms(d.slug, null)
531
+ else if (!this.seriesFolded(d)) this.flipSeries(d)
532
+ }
533
+
534
+ /** the calendar of the identity the list keeps, else the repo's */
535
+ get timeline(): Timeline | null {
536
+ const t = this.desk?.timelines ?? {}
537
+ return t[this.who ?? this.desk?.speaksAs ?? ''] ?? Object.values(t)[0] ?? null
538
+ }
539
+
540
+ get timelineIdentity(): string {
541
+ return this.who ?? this.desk?.speaksAs ?? Object.keys(this.desk?.timelines ?? {})[0] ?? ''
542
+ }
543
+
544
+ // ── Social ───────────────────────────────────────────────────────────
545
+
546
+ /** the identity the page shows: the one picked, else the repo's */
547
+ get socialIdentity(): DeskIdentity | null {
548
+ return this.identityOf(this.identity ?? '') ?? this.own ?? this.identities[0] ?? null
549
+ }
550
+
551
+ get onLegal(): boolean {
552
+ return this.account === LEGAL && this.socialIdentity?.legal != null
553
+ }
554
+
555
+ get currentAccount(): DeskAccount | null {
556
+ if (this.account == null || this.account === LEGAL) return null
557
+ return this.socialIdentity?.accounts.find((a) => a.id === this.account) ?? null
558
+ }
559
+
560
+ get onIdentity(): boolean {
561
+ return !this.onLegal && this.currentAccount == null
562
+ }
563
+
564
+ get currentPlace(): Place | null {
565
+ return this.currentAccount?.places.find((x) => x.id === this.place) ?? null
566
+ }
567
+
568
+ selectSocial(identity: string | null, account: string | null, place: string | null): void {
569
+ this.identity = identity
570
+ this.account = account
571
+ this.place = place
572
+ }
573
+
574
+ /** a click on an identity, the company, an account or one of its places */
575
+ pickSocial(identity: string, account: string | null = null, place: string | null = null): void {
576
+ this.phonePane = account == null && identity !== this.socialIdentity?.id ? 'list' : 'detail'
577
+ this.showSocial(identity, account, place)
578
+ }
579
+
580
+ private showSocial(identity: string, account: string | null, place: string | null): void {
581
+ if (this.nav != null) this.nav.social(identity, account, place)
582
+ else this.st.showSocial(identity, account, place)
583
+ }
584
+
585
+ visibleAccounts(i: DeskIdentity): DeskAccount[] {
586
+ const q = this.accountQuery.trim().toLowerCase()
587
+ return i.accounts.filter((a) => !q || `${a.id} ${a.name} ${a.handle}`.toLowerCase().includes(q))
588
+ }
589
+
590
+ setAccountQuery(q: string): void {
591
+ this.accountQuery = q
592
+ }
593
+
594
+ /** ↑ ↓ through the identity's accounts */
595
+ moveAccount(delta: number): void {
596
+ const i = this.socialIdentity
597
+ if (i == null) return
598
+ const ids = [...(i.legal ? [LEGAL] : []), ...this.visibleAccounts(i).map((a) => a.id)]
599
+ const at = ids.indexOf(this.account ?? '')
600
+ const next = ids[Math.max(0, Math.min(ids.length - 1, at + delta))]
601
+ if (next != null && next !== this.account) this.showSocial(i.id, next, null)
602
+ }
603
+
604
+ identityTotals(i: DeskIdentity): { online: number; of: number; waiting: number } {
605
+ return {
606
+ online: i.accounts.filter((a) => a.live !== '').length,
607
+ of: i.accounts.length,
608
+ waiting: (this.desk?.drafts ?? []).filter((d) => d.identity === i.id && draftWaiting(d)).length,
609
+ }
610
+ }
611
+
612
+ legalLive(i: DeskIdentity): boolean {
613
+ return legalLive(i.legal)
614
+ }
615
+
616
+ /** a row's messages: the account's own profile (ME), a place's, else every one */
617
+ private inPlace(a: DeskAccount, place: string | null): SocialPost[] {
618
+ if (place === null) return a.posts
619
+ return a.posts.filter((p) => p.place === (place === ME ? '' : place))
620
+ }
621
+
622
+ counts(a: DeskAccount, place: string | null = null): { waiting: number; posted: number } {
623
+ const ps = this.inPlace(a, place)
624
+ return { waiting: ps.filter(waiting).length, posted: ps.filter((p) => p.posted !== '').length }
625
+ }
626
+
627
+ /** green: the account online for its own row, a message posted for a place */
628
+ placeDone(a: DeskAccount, place: string): boolean {
629
+ return place === ME ? a.live !== '' : this.inPlace(a, place).some((p) => p.posted !== '')
630
+ }
631
+
632
+ placeName(a: DeskAccount, place: string): string {
633
+ return place === '' ? 'my profile' : (a.places.find((x) => x.id === place)?.name ?? place)
634
+ }
635
+
636
+ /** waiting first, then posted; rejected only when asked */
637
+ shownPosts(a: DeskAccount): SocialPost[] {
638
+ const rank = (p: SocialPost): number => (waiting(p) ? 0 : p.posted !== '' ? 1 : 2)
639
+ return this.inPlace(a, this.place)
640
+ .filter((p) => this.showRejected || p.status !== 'rejected')
641
+ .sort((x, y) => rank(x) - rank(y))
642
+ }
643
+
644
+ rejectedCount(a: DeskAccount): number {
645
+ return this.inPlace(a, this.place).filter((p) => p.status === 'rejected').length
646
+ }
647
+
648
+ setShowRejected(on: boolean): void {
649
+ this.showRejected = on
650
+ }
651
+
652
+ /** a step's `[[draft:<slug>]]`: that draft's message to the account */
653
+ refDraft(a: DeskAccount, ref: string): SocialPost | null {
654
+ const slug = /^draft:(.+)$/.exec(ref)?.[1]
655
+ return slug == null ? null : (a.posts.find((p) => p.slug === slug) ?? null)
656
+ }
657
+
658
+ isOpen(card: string, init: boolean): boolean {
659
+ return this.folds[card] ?? init
660
+ }
661
+
662
+ flipFold(card: string, init: boolean): void {
663
+ this.folds[card] = !this.isOpen(card, init)
664
+ keep(FOLDS, this.folds)
665
+ }
666
+
667
+ showPhoneList(): void {
668
+ this.phonePane = 'list'
669
+ }
670
+
671
+ // ── the page's keys ──────────────────────────────────────────────────
672
+
673
+ /** the lightbox's arrows and Escape first, then the list's arrows; true when the page used the key */
674
+ key(e: Pick<KeyboardEvent, 'key'>, page: 'comms' | 'social'): boolean {
675
+ const lb = this.lightbox
676
+ if (lb) {
677
+ if (e.key === 'Escape') this.closeLightbox()
678
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') this.stepLightbox(e.key === 'ArrowLeft' ? -1 : 1)
679
+ else return false
680
+ return true
681
+ }
682
+ if (e.key === SEARCH_KEY && this.searchEl != null) {
683
+ this.searchEl.focus()
684
+ return true
685
+ }
686
+ if (page === 'social') {
687
+ if (e.key === 'ArrowUp' || e.key === 'k') this.moveAccount(-1)
688
+ else if (e.key === 'ArrowDown' || e.key === 'j') this.moveAccount(1)
689
+ else return false
690
+ return true
691
+ }
692
+ if (e.key === 'ArrowUp' || e.key === 'k') this.moveDraft(-1)
693
+ else if (e.key === 'ArrowDown' || e.key === 'j') this.moveDraft(1)
694
+ else if (e.key === 'ArrowRight') this.treeStep(1)
695
+ else if (e.key === 'ArrowLeft') this.treeStep(-1)
696
+ else return false
697
+ return true
698
+ }
699
+
700
+ // ── files the hub serves ─────────────────────────────────────────────
701
+
702
+ mediaUrl(slug: string, m: Pick<Media, 'name'>): string {
703
+ return this.st.url(`/api/social/media/${slug}/${encodeURIComponent(m.name)}`)
704
+ }
705
+
706
+ pictureUrl(identity: string, file: string): string {
707
+ return this.st.url(`/api/social/picture/${identity}/${file.split('/').map(encodeURIComponent).join('/')}`)
708
+ }
709
+
710
+ previewUrl(slug: string): string {
711
+ return this.st.url(`/api/social/preview/${slug}`)
712
+ }
713
+
714
+ /** a file in VS Code: a file joins the open window, a folder would replace it */
715
+ editorUrl(abs: string): string {
716
+ return `vscode://file${encodeURI(abs)}`
717
+ }
718
+
719
+ /** a path from the repo's root, as he reads it */
720
+ repoPath(abs: string): string {
721
+ const root = this.desk?.root ?? ''
722
+ return root && abs.startsWith(`${root}/`) ? abs.slice(root.length + 1) : abs
723
+ }
724
+
725
+ // ── the lightbox ─────────────────────────────────────────────────────
726
+
727
+ openLightbox(slug: string, name: string): void {
728
+ this.lightbox = { slug, name }
729
+ }
730
+
731
+ closeLightbox(): void {
732
+ this.lightbox = null
733
+ }
734
+
735
+ get lightboxDraft(): Draft | null {
736
+ return this.desk?.drafts.find((d) => d.slug === this.lightbox?.slug) ?? null
737
+ }
738
+
739
+ stepLightbox(by: number): void {
740
+ const lb = this.lightbox
741
+ const list = this.lightboxDraft?.media ?? []
742
+ if (!lb || list.length === 0) return
743
+ const at = Math.max(0, list.findIndex((m) => m.name === lb.name))
744
+ const next = list[(at + by + list.length) % list.length]
745
+ if (next) this.lightbox = { slug: lb.slug, name: next.name }
746
+ }
747
+
748
+ // ── the clipboard ────────────────────────────────────────────────────
749
+
750
+ private copied(key: string): void {
751
+ this.copiedKey = key
752
+ if (this.copyTimer) clearTimeout(this.copyTimer)
753
+ this.copyTimer = setTimeout(() => runInAction(() => (this.copiedKey = null)), 1500)
754
+ }
755
+
756
+ say(words: string): void {
757
+ this.toast = words
758
+ if (this.toastTimer) clearTimeout(this.toastTimer)
759
+ this.toastTimer = setTimeout(() => runInAction(() => (this.toast = null)), 1800)
760
+ }
761
+
762
+ async copy(text: string, key: string): Promise<void> {
763
+ const ok = await copyText(text)
764
+ runInAction(() => (ok ? this.copied(key) : (this.error = 'the clipboard refused it')))
765
+ }
766
+
767
+ /** the image itself on the clipboard, as a png (the one image type every browser pastes): a jpg is redrawn first.
768
+ * The item takes the blob as a promise, so Safari still counts the click as the gesture */
769
+ async copyImage(url: string, key: string): Promise<void> {
770
+ try {
771
+ const png = (async (): Promise<Blob> => {
772
+ const blob = await (await fetch(url)).blob()
773
+ if (blob.type === 'image/png') return blob
774
+ const bmp = await createImageBitmap(blob)
775
+ const c = document.createElement('canvas')
776
+ c.width = bmp.width
777
+ c.height = bmp.height
778
+ c.getContext('2d')?.drawImage(bmp, 0, 0)
779
+ return await new Promise<Blob>((ok, no) => c.toBlob((b) => (b ? ok(b) : no(new Error('no png'))), 'image/png'))
780
+ })()
781
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
782
+ runInAction(() => this.copied(key))
783
+ } catch (e) {
784
+ runInAction(() => (this.error = `copy image: ${(e as Error).message}`))
785
+ }
786
+ }
787
+
788
+ /** a page that takes no text: the composed text on the clipboard first, and a word that says so */
789
+ async copyCaption(p: SocialPost): Promise<void> {
790
+ if (await copyText(caption(p))) this.say('caption copied')
791
+ else runInAction(() => (this.error = 'the clipboard refused the caption'))
792
+ }
793
+
794
+ clearError(): void {
795
+ this.error = null
796
+ }
797
+
798
+ // ── the writes: each one a commit of its own paths on the server ─────
799
+
800
+ private async write(path: string, body: unknown, field?: string): Promise<boolean> {
801
+ this.busy = true
802
+ this.error = null
803
+ let ok = true
804
+ try {
805
+ await postJson(this.st.url(`/api/social/${path}`), body)
806
+ } catch (e) {
807
+ ok = false
808
+ runInAction(() => {
809
+ if (field) this.urlErrors[field] = (e as Error).message
810
+ else this.error = (e as Error).message
811
+ })
812
+ }
813
+ await this.load()
814
+ runInAction(() => {
815
+ if (field && ok) {
816
+ delete this.urls[field]
817
+ delete this.urlErrors[field]
818
+ }
819
+ this.busy = false
820
+ })
821
+ return ok
822
+ }
823
+
824
+ urlField(key: string, saved: string): string {
825
+ return this.urls[key] ?? saved
826
+ }
827
+
828
+ setUrl(key: string, url: string): void {
829
+ this.urls[key] = url
830
+ delete this.urlErrors[key]
831
+ }
832
+
833
+ postKey(p: SocialPost): string {
834
+ return `${p.key}/${p.slug}`
835
+ }
836
+
837
+ /** a post's URL field left: saved when it changed; emptied, it waits again */
838
+ async savePosted(p: SocialPost): Promise<void> {
839
+ const k = this.postKey(p)
840
+ const typed = this.urls[k]
841
+ if (typed === undefined || typed.trim() === p.posted) return
842
+ await this.write('posted', { slug: p.slug, key: p.key, url: typed.trim() }, k)
843
+ }
844
+
845
+ /** the profile URL field left: saved when it changed; emptied, the account is still to create */
846
+ async saveLive(a: DeskAccount): Promise<void> {
847
+ const k = `${a.identity}/${a.id}`
848
+ const typed = this.urls[k]
849
+ if (typed === undefined || typed.trim() === a.live) return
850
+ await this.write('live', { identity: a.identity, account: a.id, url: typed.trim() }, k)
851
+ void this.loadStats()
852
+ }
853
+
854
+ async toggleStep(a: DeskAccount, index: number): Promise<void> {
855
+ const step = a.steps[index]
856
+ if (step == null) return
857
+ await this.write('step', { identity: a.identity, account: a.id, index, done: !step.done })
858
+ }
859
+
860
+ /** a public act: asked first, then the message posts as its identity and its link lands in the draft */
861
+ async publish(a: DeskAccount, p: SocialPost): Promise<void> {
862
+ const k = this.postKey(p)
863
+ const who = this.identityOf(p.identity)?.name ?? p.identity
864
+ if (this.publishing[k] || !confirm(`Publish « ${p.name || p.title || p.slug} » on ${a.name} as ${who}, in public?`)) return
865
+ this.publishing[k] = true
866
+ delete this.publishError[k]
867
+ try {
868
+ await postJson(this.st.url('/api/social/publish'), { slug: p.slug, key: p.key })
869
+ } catch (e) {
870
+ runInAction(() => (this.publishError[k] = (e as Error).message))
871
+ }
872
+ await this.load()
873
+ runInAction(() => delete this.publishing[k])
874
+ }
875
+
876
+ /** « Open all »: every write page of one card tiled on the Mac in the identity's Chrome profile, its media in the
877
+ * Finder below; the vertical's pages take no text, so the caption the three share goes on the clipboard first */
878
+ async openAll(p: SocialPost): Promise<void> {
879
+ this.error = null
880
+ if (!p.prefilled) await this.copyCaption(p)
881
+ try {
882
+ await postJson(this.st.url('/api/social/open-all'), { slug: p.slug, from: p.from })
883
+ } catch (e) {
884
+ runInAction(() => (this.error = (e as Error).message))
885
+ }
886
+ }
887
+
888
+ /** a media file shown in the Finder */
889
+ async reveal(slug: string, m: Media): Promise<void> {
890
+ try {
891
+ await postJson(this.st.url('/api/social/reveal'), { slug, name: m.name })
892
+ } catch (e) {
893
+ runInAction(() => (this.error = (e as Error).message))
894
+ }
895
+ }
896
+
897
+ // ── the editor ───────────────────────────────────────────────────────
898
+
899
+ /** a message's editor key: its heading's, shared by every account of a group */
900
+ editKey(p: SocialPost): string {
901
+ return `${p.from}/${p.slug}`
902
+ }
903
+
904
+ edit(p: SocialPost): DraftEdit | null {
905
+ return this.edits[this.editKey(p)] ?? null
906
+ }
907
+
908
+ /** its text opened in the editor, and its title where the heading has one or is the vertical */
909
+ startEdit(p: SocialPost): void {
910
+ const vertical = p.from.split('/')[0] === 'vertical'
911
+ this.edits[this.editKey(p)] = { text: p.body, tags: p.tags.join(' '), title: p.title !== '' || vertical ? p.title : null }
912
+ }
913
+
914
+ typeEdit(p: SocialPost, v: Partial<DraftEdit>): void {
915
+ const e = this.edit(p)
916
+ if (e) this.edits[this.editKey(p)] = { ...e, ...v }
917
+ }
918
+
919
+ cancelEdit(p: SocialPost): void {
920
+ delete this.edits[this.editKey(p)]
921
+ }
922
+
923
+ /** its length on its account, live while the editor holds it: a group's text as that account takes it */
924
+ length(p: SocialPost): number {
925
+ const e = this.edit(p)
926
+ if (e == null) return p.length
927
+ const tags = e.tags.split(/\s+/).filter(Boolean)
928
+ const made = compose(p.platform, { text: e.text, tags, footer: p.footer }, { max: this.postAccount(p)?.max ?? null, saturday: new Date().getDay() === 6 })
929
+ return messageLength(p.platform, made.text)
930
+ }
931
+
932
+ /** the editor's text into draft.md (a commit of the draft alone); the box closes on the text as saved */
933
+ async saveEdit(p: SocialPost): Promise<void> {
934
+ const e = this.edit(p)
935
+ if (e == null || e.text.trim() === '' || this.busy) return
936
+ if (await this.write('text', { slug: p.slug, key: p.from, text: e.text, tags: e.tags, ...(e.title === null ? {} : { title: e.title }) })) runInAction(() => this.cancelEdit(p))
937
+ }
938
+
939
+ // ── his notes on a draft ─────────────────────────────────────────────
940
+
941
+ async loadNotes(slug: string): Promise<void> {
942
+ try {
943
+ const r = await reach(this.st.url(`/api/social/notes?slug=${encodeURIComponent(slug)}`))
944
+ const body = (await r.json()) as { notes?: DraftNote[]; error?: string }
945
+ if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`)
946
+ runInAction(() => (this.notes[slug] = body.notes ?? []))
947
+ } catch (e) {
948
+ runInAction(() => (this.error = (e as Error).message))
949
+ }
950
+ }
951
+
952
+ /** his note raised into the review store, or his reply on its open thread; true once it is there */
953
+ async sendNote(d: Draft, text: string): Promise<boolean> {
954
+ if (text.trim() === '' || this.busy) return false
955
+ this.busy = true
956
+ try {
957
+ await postJson(this.st.url('/api/social/notes'), { slug: d.slug, title: d.title, text })
958
+ await this.loadNotes(d.slug)
959
+ return true
960
+ } catch (e) {
961
+ runInAction(() => (this.error = (e as Error).message))
962
+ return false
963
+ } finally {
964
+ runInAction(() => (this.busy = false))
965
+ }
966
+ }
967
+
968
+ /** a note's card on the review page: the hub's own, or the host's when the page sits in another tool's frame */
969
+ openNote(id: string): void {
970
+ if (this.st.home.embedded && window.parent !== window) window.parent.postMessage({ shipkit: 'show', page: 'review', hash: `#page:review:${id}` }, location.origin)
971
+ else this.st.showReview(id)
972
+ }
973
+
974
+ /** a draft named on the Social page, opened in Communications */
975
+ openDraft(slug: string): void {
976
+ this.phonePane = 'detail'
977
+ if (this.nav != null) this.nav.draft(slug)
978
+ else if (this.st.home.embedded && window.parent !== window) window.parent.postMessage({ shipkit: 'show', page: 'comms', hash: `#page:comms:${slug}` }, location.origin)
979
+ else this.st.showComms(slug, null)
980
+ }
981
+
982
+ /** a picture of an identity: its url, and whether it is a clip */
983
+ picture(i: DeskIdentity, f: Picture): { url: string; clip: boolean } {
984
+ return { url: this.pictureUrl(i.id, f.file), clip: f.file.endsWith('.mp4') }
985
+ }
986
+ }