line-comment-annotations.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import { type DiffLineAnnotation, type SelectedLineRange } from "@pierre/diffs"
  2. import { createEffect, createMemo, createSignal, onCleanup, Show, type Accessor, type JSX } from "solid-js"
  3. import { createStore } from "solid-js/store"
  4. import { render as renderSolid } from "solid-js/web"
  5. import { useI18n } from "../context/i18n"
  6. import { createHoverCommentUtility } from "../pierre/comment-hover"
  7. import { cloneSelectedLineRange, formatSelectedLineLabel, lineInSelectedRange } from "../pierre/selection-bridge"
  8. import { LineComment, LineCommentEditor, type LineCommentEditorProps } from "./line-comment"
  9. export type LineCommentAnnotationMeta<T> =
  10. | { kind: "comment"; key: string; comment: T }
  11. | { kind: "draft"; key: string; range: SelectedLineRange }
  12. export type LineCommentAnnotation<T> = {
  13. lineNumber: number
  14. side?: "additions" | "deletions"
  15. metadata: LineCommentAnnotationMeta<T>
  16. }
  17. type LineCommentAnnotationsProps<T> = {
  18. comments: Accessor<T[]>
  19. getCommentId: (comment: T) => string
  20. getCommentSelection: (comment: T) => SelectedLineRange
  21. draftRange: Accessor<SelectedLineRange | null>
  22. draftKey: Accessor<string>
  23. }
  24. type LineCommentAnnotationsWithSideProps<T> = LineCommentAnnotationsProps<T> & {
  25. getSide: (range: SelectedLineRange) => "additions" | "deletions"
  26. }
  27. type HoverCommentLine = {
  28. lineNumber: number
  29. side?: "additions" | "deletions"
  30. }
  31. type LineCommentStateProps<T> = {
  32. opened: Accessor<T | null>
  33. setOpened: (id: T | null) => void
  34. selected: Accessor<SelectedLineRange | null>
  35. setSelected: (range: SelectedLineRange | null) => void
  36. commenting: Accessor<SelectedLineRange | null>
  37. setCommenting: (range: SelectedLineRange | null) => void
  38. syncSelected?: (range: SelectedLineRange | null) => void
  39. hoverSelected?: (range: SelectedLineRange) => void
  40. }
  41. type LineCommentShape = {
  42. id: string
  43. selection: SelectedLineRange
  44. comment: string
  45. }
  46. type LineCommentControllerProps<T extends LineCommentShape> = {
  47. comments: Accessor<T[]>
  48. draftKey: Accessor<string>
  49. label: string
  50. mention?: LineCommentEditorProps["mention"]
  51. state: LineCommentStateProps<string>
  52. onSubmit: (input: { comment: string; selection: SelectedLineRange }) => void
  53. onUpdate?: (input: { id: string; comment: string; selection: SelectedLineRange }) => void
  54. onDelete?: (comment: T) => void
  55. renderCommentActions?: (comment: T, controls: { edit: VoidFunction; remove: VoidFunction }) => JSX.Element
  56. editSubmitLabel?: string
  57. onDraftPopoverFocusOut?: JSX.EventHandlerUnion<HTMLDivElement, FocusEvent>
  58. getHoverSelectedRange?: Accessor<SelectedLineRange | null>
  59. cancelDraftOnCommentToggle?: boolean
  60. clearSelectionOnSelectionEndNull?: boolean
  61. }
  62. type LineCommentControllerWithSideProps<T extends LineCommentShape> = LineCommentControllerProps<T> & {
  63. getSide: (range: SelectedLineRange) => "additions" | "deletions"
  64. }
  65. type CommentProps = {
  66. id?: string
  67. open: boolean
  68. comment: JSX.Element
  69. selection: JSX.Element
  70. actions?: JSX.Element
  71. editor?: DraftProps
  72. onClick?: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>
  73. onMouseEnter?: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>
  74. }
  75. type DraftProps = {
  76. value: string
  77. selection: JSX.Element
  78. mention?: LineCommentEditorProps["mention"]
  79. onInput: (value: string) => void
  80. onCancel: VoidFunction
  81. onSubmit: (value: string) => void
  82. onPopoverFocusOut?: JSX.EventHandlerUnion<HTMLDivElement, FocusEvent>
  83. cancelLabel?: string
  84. submitLabel?: string
  85. }
  86. export function createLineCommentAnnotationRenderer<T>(props: {
  87. renderComment: (comment: T) => CommentProps
  88. renderDraft: (range: SelectedLineRange) => DraftProps
  89. }) {
  90. const nodes = new Map<
  91. string,
  92. {
  93. host: HTMLDivElement
  94. dispose: VoidFunction
  95. setMeta: (meta: LineCommentAnnotationMeta<T>) => void
  96. }
  97. >()
  98. const mount = (meta: LineCommentAnnotationMeta<T>) => {
  99. if (typeof document === "undefined") return
  100. const host = document.createElement("div")
  101. host.setAttribute("data-prevent-autofocus", "")
  102. const [current, setCurrent] = createSignal(meta)
  103. const dispose = renderSolid(() => {
  104. const active = current()
  105. if (active.kind === "comment") {
  106. const view = createMemo(() => {
  107. const next = current()
  108. if (next.kind !== "comment") return props.renderComment(active.comment)
  109. return props.renderComment(next.comment)
  110. })
  111. return (
  112. <Show
  113. when={view().editor}
  114. fallback={
  115. <LineComment
  116. inline
  117. id={view().id}
  118. open={view().open}
  119. comment={view().comment}
  120. selection={view().selection}
  121. actions={view().actions}
  122. onClick={view().onClick}
  123. onMouseEnter={view().onMouseEnter}
  124. />
  125. }
  126. >
  127. <LineCommentEditor
  128. inline
  129. id={view().id}
  130. value={view().editor!.value}
  131. selection={view().editor!.selection}
  132. onInput={view().editor!.onInput}
  133. onCancel={view().editor!.onCancel}
  134. onSubmit={view().editor!.onSubmit}
  135. onPopoverFocusOut={view().editor!.onPopoverFocusOut}
  136. cancelLabel={view().editor!.cancelLabel}
  137. submitLabel={view().editor!.submitLabel}
  138. mention={view().editor!.mention}
  139. />
  140. </Show>
  141. )
  142. }
  143. const view = createMemo(() => {
  144. const next = current()
  145. if (next.kind !== "draft") return props.renderDraft(active.range)
  146. return props.renderDraft(next.range)
  147. })
  148. return (
  149. <LineCommentEditor
  150. inline
  151. value={view().value}
  152. selection={view().selection}
  153. onInput={view().onInput}
  154. onCancel={view().onCancel}
  155. onSubmit={view().onSubmit}
  156. onPopoverFocusOut={view().onPopoverFocusOut}
  157. mention={view().mention}
  158. />
  159. )
  160. }, host)
  161. const node = { host, dispose, setMeta: setCurrent }
  162. nodes.set(meta.key, node)
  163. return node
  164. }
  165. const render = <A extends { metadata: LineCommentAnnotationMeta<T> }>(annotation: A) => {
  166. const meta = annotation.metadata
  167. const node = nodes.get(meta.key) ?? mount(meta)
  168. if (!node) return
  169. node.setMeta(meta)
  170. return node.host
  171. }
  172. const reconcile = <A extends { metadata: LineCommentAnnotationMeta<T> }>(annotations: A[]) => {
  173. const next = new Set(annotations.map((annotation) => annotation.metadata.key))
  174. for (const [key, node] of nodes) {
  175. if (next.has(key)) continue
  176. node.dispose()
  177. nodes.delete(key)
  178. }
  179. }
  180. const cleanup = () => {
  181. for (const [, node] of nodes) node.dispose()
  182. nodes.clear()
  183. }
  184. return { render, reconcile, cleanup }
  185. }
  186. export function createLineCommentState<T>(props: LineCommentStateProps<T>) {
  187. const [state, setState] = createStore({
  188. draft: "",
  189. editing: null as T | null,
  190. })
  191. const draft = () => state.draft
  192. const setDraft = (value: string) => setState("draft", value)
  193. const editing = () => state.editing
  194. const setEditing = (value: T | null) => setState("editing", typeof value === "function" ? () => value : value)
  195. const toRange = (range: SelectedLineRange | null) => (range ? cloneSelectedLineRange(range) : null)
  196. const setSelected = (range: SelectedLineRange | null) => {
  197. const next = toRange(range)
  198. props.setSelected(next)
  199. props.syncSelected?.(toRange(next))
  200. return next
  201. }
  202. const setCommenting = (range: SelectedLineRange | null) => {
  203. const next = toRange(range)
  204. props.setCommenting(next)
  205. return next
  206. }
  207. const closeComment = () => {
  208. props.setOpened(null)
  209. }
  210. const cancelDraft = () => {
  211. setDraft("")
  212. setEditing(null)
  213. setCommenting(null)
  214. }
  215. const reset = () => {
  216. setDraft("")
  217. setEditing(null)
  218. props.setOpened(null)
  219. props.setSelected(null)
  220. props.setCommenting(null)
  221. }
  222. const openComment = (id: T, range: SelectedLineRange, options?: { cancelDraft?: boolean }) => {
  223. if (options?.cancelDraft) cancelDraft()
  224. props.setOpened(id)
  225. setSelected(range)
  226. }
  227. const toggleComment = (id: T, range: SelectedLineRange, options?: { cancelDraft?: boolean }) => {
  228. if (options?.cancelDraft) cancelDraft()
  229. const next = props.opened() === id ? null : id
  230. props.setOpened(next)
  231. setSelected(range)
  232. }
  233. const openDraft = (range: SelectedLineRange) => {
  234. const next = toRange(range)
  235. setDraft("")
  236. setEditing(null)
  237. closeComment()
  238. setSelected(next)
  239. setCommenting(next)
  240. }
  241. const openEditor = (id: T, range: SelectedLineRange, value: string) => {
  242. closeComment()
  243. setSelected(range)
  244. props.setCommenting(null)
  245. setEditing(id)
  246. setDraft(value)
  247. }
  248. const hoverComment = (range: SelectedLineRange) => {
  249. const next = toRange(range)
  250. if (!next) return
  251. if (props.hoverSelected) {
  252. props.hoverSelected(next)
  253. return
  254. }
  255. setSelected(next)
  256. }
  257. const finishSelection = (range: SelectedLineRange) => {
  258. closeComment()
  259. setSelected(range)
  260. cancelDraft()
  261. }
  262. createEffect(() => {
  263. props.commenting()
  264. setDraft("")
  265. })
  266. return {
  267. draft,
  268. setDraft,
  269. editing,
  270. opened: props.opened,
  271. selected: props.selected,
  272. commenting: props.commenting,
  273. isOpen: (id: T) => props.opened() === id,
  274. isEditing: (id: T) => editing() === id,
  275. closeComment,
  276. openComment,
  277. toggleComment,
  278. openDraft,
  279. openEditor,
  280. hoverComment,
  281. cancelDraft,
  282. finishSelection,
  283. select: setSelected,
  284. reset,
  285. }
  286. }
  287. export function createLineCommentController<T extends LineCommentShape>(
  288. props: LineCommentControllerWithSideProps<T>,
  289. ): {
  290. note: ReturnType<typeof createLineCommentState<string>>
  291. annotations: Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  292. renderAnnotation: ReturnType<typeof createManagedLineCommentAnnotationRenderer<T>>["renderAnnotation"]
  293. renderHoverUtility: ReturnType<typeof createLineCommentHoverRenderer>
  294. onLineSelected: (range: SelectedLineRange | null) => void
  295. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  296. onLineNumberSelectionEnd: (range: SelectedLineRange | null) => void
  297. }
  298. export function createLineCommentController<T extends LineCommentShape>(
  299. props: LineCommentControllerProps<T>,
  300. ): {
  301. note: ReturnType<typeof createLineCommentState<string>>
  302. annotations: Accessor<LineCommentAnnotation<T>[]>
  303. renderAnnotation: ReturnType<typeof createManagedLineCommentAnnotationRenderer<T>>["renderAnnotation"]
  304. renderHoverUtility: ReturnType<typeof createLineCommentHoverRenderer>
  305. onLineSelected: (range: SelectedLineRange | null) => void
  306. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  307. onLineNumberSelectionEnd: (range: SelectedLineRange | null) => void
  308. }
  309. export function createLineCommentController<T extends LineCommentShape>(
  310. props: LineCommentControllerProps<T> | LineCommentControllerWithSideProps<T>,
  311. ) {
  312. const i18n = useI18n()
  313. const note = createLineCommentState<string>(props.state)
  314. const annotations =
  315. "getSide" in props
  316. ? createLineCommentAnnotations({
  317. comments: props.comments,
  318. getCommentId: (comment) => comment.id,
  319. getCommentSelection: (comment) => comment.selection,
  320. draftRange: note.commenting,
  321. draftKey: props.draftKey,
  322. getSide: props.getSide,
  323. })
  324. : createLineCommentAnnotations({
  325. comments: props.comments,
  326. getCommentId: (comment) => comment.id,
  327. getCommentSelection: (comment) => comment.selection,
  328. draftRange: note.commenting,
  329. draftKey: props.draftKey,
  330. })
  331. const { renderAnnotation } = createManagedLineCommentAnnotationRenderer<T>({
  332. annotations,
  333. renderComment: (comment) => {
  334. const edit = () => note.openEditor(comment.id, comment.selection, comment.comment)
  335. const remove = () => {
  336. note.reset()
  337. props.onDelete?.(comment)
  338. }
  339. return {
  340. id: comment.id,
  341. get open() {
  342. return note.isOpen(comment.id) || note.isEditing(comment.id)
  343. },
  344. comment: comment.comment,
  345. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  346. get actions() {
  347. return props.renderCommentActions?.(comment, { edit, remove })
  348. },
  349. get editor() {
  350. return note.isEditing(comment.id)
  351. ? {
  352. get value() {
  353. return note.draft()
  354. },
  355. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  356. mention: props.mention,
  357. onInput: note.setDraft,
  358. onCancel: note.cancelDraft,
  359. onSubmit: (value: string) => {
  360. props.onUpdate?.({
  361. id: comment.id,
  362. comment: value,
  363. selection: cloneSelectedLineRange(comment.selection),
  364. })
  365. note.cancelDraft()
  366. },
  367. submitLabel: props.editSubmitLabel,
  368. }
  369. : undefined
  370. },
  371. onMouseEnter: () => note.hoverComment(comment.selection),
  372. onClick: () => {
  373. if (note.isEditing(comment.id)) return
  374. note.toggleComment(comment.id, comment.selection, { cancelDraft: props.cancelDraftOnCommentToggle })
  375. },
  376. }
  377. },
  378. renderDraft: (range) => ({
  379. get value() {
  380. return note.draft()
  381. },
  382. selection: formatSelectedLineLabel(range, i18n.t),
  383. mention: props.mention,
  384. onInput: note.setDraft,
  385. onCancel: note.cancelDraft,
  386. onSubmit: (comment) => {
  387. props.onSubmit({ comment, selection: cloneSelectedLineRange(range) })
  388. note.cancelDraft()
  389. },
  390. onPopoverFocusOut: props.onDraftPopoverFocusOut,
  391. }),
  392. })
  393. const renderHoverUtility = createLineCommentHoverRenderer({
  394. label: props.label,
  395. getSelectedRange: () => {
  396. if (note.opened()) return null
  397. return props.getHoverSelectedRange?.() ?? note.selected()
  398. },
  399. onOpenDraft: note.openDraft,
  400. })
  401. const onLineSelected = (range: SelectedLineRange | null) => {
  402. if (!range) {
  403. note.select(null)
  404. note.cancelDraft()
  405. return
  406. }
  407. note.select(range)
  408. }
  409. const onLineSelectionEnd = (range: SelectedLineRange | null) => {
  410. if (!range) {
  411. if (props.clearSelectionOnSelectionEndNull) note.select(null)
  412. note.cancelDraft()
  413. return
  414. }
  415. note.finishSelection(range)
  416. }
  417. const onLineNumberSelectionEnd = (range: SelectedLineRange | null) => {
  418. if (!range) return
  419. note.openDraft(range)
  420. }
  421. return {
  422. note,
  423. annotations,
  424. renderAnnotation,
  425. renderHoverUtility,
  426. onLineSelected,
  427. onLineSelectionEnd,
  428. onLineNumberSelectionEnd,
  429. }
  430. }
  431. export function createLineCommentAnnotations<T>(
  432. props: LineCommentAnnotationsWithSideProps<T>,
  433. ): Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  434. export function createLineCommentAnnotations<T>(
  435. props: LineCommentAnnotationsProps<T>,
  436. ): Accessor<LineCommentAnnotation<T>[]>
  437. export function createLineCommentAnnotations<T>(
  438. props: LineCommentAnnotationsProps<T> | LineCommentAnnotationsWithSideProps<T>,
  439. ) {
  440. const line = (range: SelectedLineRange) => Math.max(range.start, range.end)
  441. if ("getSide" in props) {
  442. return createMemo<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>(() => {
  443. const list = props.comments().map((comment) => {
  444. const range = props.getCommentSelection(comment)
  445. return {
  446. side: props.getSide(range),
  447. lineNumber: line(range),
  448. metadata: {
  449. kind: "comment",
  450. key: `comment:${props.getCommentId(comment)}`,
  451. comment,
  452. } satisfies LineCommentAnnotationMeta<T>,
  453. }
  454. })
  455. const range = props.draftRange()
  456. if (!range) return list
  457. return [
  458. ...list,
  459. {
  460. side: props.getSide(range),
  461. lineNumber: line(range),
  462. metadata: {
  463. kind: "draft",
  464. key: `draft:${props.draftKey()}`,
  465. range,
  466. } satisfies LineCommentAnnotationMeta<T>,
  467. },
  468. ]
  469. })
  470. }
  471. return createMemo<LineCommentAnnotation<T>[]>(() => {
  472. const list = props.comments().map((comment) => {
  473. const range = props.getCommentSelection(comment)
  474. const entry: LineCommentAnnotation<T> = {
  475. lineNumber: line(range),
  476. metadata: {
  477. kind: "comment",
  478. key: `comment:${props.getCommentId(comment)}`,
  479. comment,
  480. },
  481. }
  482. return entry
  483. })
  484. const range = props.draftRange()
  485. if (!range) return list
  486. const draft: LineCommentAnnotation<T> = {
  487. lineNumber: line(range),
  488. metadata: {
  489. kind: "draft",
  490. key: `draft:${props.draftKey()}`,
  491. range,
  492. },
  493. }
  494. return [...list, draft]
  495. })
  496. }
  497. export function createManagedLineCommentAnnotationRenderer<T>(props: {
  498. annotations: Accessor<LineCommentAnnotation<T>[]>
  499. renderComment: (comment: T) => CommentProps
  500. renderDraft: (range: SelectedLineRange) => DraftProps
  501. }) {
  502. const renderer = createLineCommentAnnotationRenderer<T>({
  503. renderComment: props.renderComment,
  504. renderDraft: props.renderDraft,
  505. })
  506. createEffect(() => {
  507. renderer.reconcile(props.annotations())
  508. })
  509. onCleanup(() => {
  510. renderer.cleanup()
  511. })
  512. return {
  513. renderAnnotation: renderer.render,
  514. }
  515. }
  516. export function createLineCommentHoverRenderer(props: {
  517. label: string
  518. getSelectedRange: Accessor<SelectedLineRange | null>
  519. onOpenDraft: (range: SelectedLineRange) => void
  520. }) {
  521. return (getHoveredLine: () => HoverCommentLine | undefined) =>
  522. createHoverCommentUtility({
  523. label: props.label,
  524. getHoveredLine,
  525. onSelect: (hovered) => {
  526. const current = props.getSelectedRange()
  527. if (current && lineInSelectedRange(current, hovered.lineNumber, hovered.side)) {
  528. props.onOpenDraft(cloneSelectedLineRange(current))
  529. return
  530. }
  531. const range: SelectedLineRange = {
  532. start: hovered.lineNumber,
  533. end: hovered.lineNumber,
  534. }
  535. if (hovered.side) range.side = hovered.side
  536. props.onOpenDraft(range)
  537. },
  538. })
  539. }