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