line-comment-annotations.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. return {
  263. draft,
  264. setDraft,
  265. editing,
  266. opened: props.opened,
  267. selected: props.selected,
  268. commenting: props.commenting,
  269. isOpen: (id: T) => props.opened() === id,
  270. isEditing: (id: T) => editing() === id,
  271. closeComment,
  272. openComment,
  273. toggleComment,
  274. openDraft,
  275. openEditor,
  276. hoverComment,
  277. cancelDraft,
  278. finishSelection,
  279. select: setSelected,
  280. reset,
  281. }
  282. }
  283. export function createLineCommentController<T extends LineCommentShape>(
  284. props: LineCommentControllerWithSideProps<T>,
  285. ): {
  286. note: ReturnType<typeof createLineCommentState<string>>
  287. annotations: Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  288. renderAnnotation: ReturnType<typeof createManagedLineCommentAnnotationRenderer<T>>["renderAnnotation"]
  289. renderHoverUtility: ReturnType<typeof createLineCommentHoverRenderer>
  290. onLineSelected: (range: SelectedLineRange | null) => void
  291. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  292. onLineNumberSelectionEnd: (range: SelectedLineRange | null) => void
  293. }
  294. export function createLineCommentController<T extends LineCommentShape>(
  295. props: LineCommentControllerProps<T>,
  296. ): {
  297. note: ReturnType<typeof createLineCommentState<string>>
  298. annotations: Accessor<LineCommentAnnotation<T>[]>
  299. renderAnnotation: ReturnType<typeof createManagedLineCommentAnnotationRenderer<T>>["renderAnnotation"]
  300. renderHoverUtility: ReturnType<typeof createLineCommentHoverRenderer>
  301. onLineSelected: (range: SelectedLineRange | null) => void
  302. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  303. onLineNumberSelectionEnd: (range: SelectedLineRange | null) => void
  304. }
  305. export function createLineCommentController<T extends LineCommentShape>(
  306. props: LineCommentControllerProps<T> | LineCommentControllerWithSideProps<T>,
  307. ) {
  308. const i18n = useI18n()
  309. const note = createLineCommentState<string>(props.state)
  310. const annotations =
  311. "getSide" in props
  312. ? createLineCommentAnnotations({
  313. comments: props.comments,
  314. getCommentId: (comment) => comment.id,
  315. getCommentSelection: (comment) => comment.selection,
  316. draftRange: note.commenting,
  317. draftKey: props.draftKey,
  318. getSide: props.getSide,
  319. })
  320. : createLineCommentAnnotations({
  321. comments: props.comments,
  322. getCommentId: (comment) => comment.id,
  323. getCommentSelection: (comment) => comment.selection,
  324. draftRange: note.commenting,
  325. draftKey: props.draftKey,
  326. })
  327. const { renderAnnotation } = createManagedLineCommentAnnotationRenderer<T>({
  328. annotations,
  329. renderComment: (comment) => {
  330. const edit = () => note.openEditor(comment.id, comment.selection, comment.comment)
  331. const remove = () => {
  332. note.reset()
  333. props.onDelete?.(comment)
  334. }
  335. return {
  336. id: comment.id,
  337. get open() {
  338. return note.isOpen(comment.id) || note.isEditing(comment.id)
  339. },
  340. comment: comment.comment,
  341. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  342. get actions() {
  343. return props.renderCommentActions?.(comment, { edit, remove })
  344. },
  345. get editor() {
  346. return note.isEditing(comment.id)
  347. ? {
  348. get value() {
  349. return note.draft()
  350. },
  351. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  352. mention: props.mention,
  353. onInput: note.setDraft,
  354. onCancel: note.cancelDraft,
  355. onSubmit: (value: string) => {
  356. props.onUpdate?.({
  357. id: comment.id,
  358. comment: value,
  359. selection: cloneSelectedLineRange(comment.selection),
  360. })
  361. note.cancelDraft()
  362. },
  363. submitLabel: props.editSubmitLabel,
  364. }
  365. : undefined
  366. },
  367. onMouseEnter: () => note.hoverComment(comment.selection),
  368. onClick: () => {
  369. if (note.isEditing(comment.id)) return
  370. note.toggleComment(comment.id, comment.selection, { cancelDraft: props.cancelDraftOnCommentToggle })
  371. },
  372. }
  373. },
  374. renderDraft: (range) => ({
  375. get value() {
  376. return note.draft()
  377. },
  378. selection: formatSelectedLineLabel(range, i18n.t),
  379. mention: props.mention,
  380. onInput: note.setDraft,
  381. onCancel: note.cancelDraft,
  382. onSubmit: (comment) => {
  383. props.onSubmit({ comment, selection: cloneSelectedLineRange(range) })
  384. note.cancelDraft()
  385. },
  386. onPopoverFocusOut: props.onDraftPopoverFocusOut,
  387. }),
  388. })
  389. const renderHoverUtility = createLineCommentHoverRenderer({
  390. label: props.label,
  391. getSelectedRange: () => {
  392. if (note.opened()) return null
  393. return props.getHoverSelectedRange?.() ?? note.selected()
  394. },
  395. onOpenDraft: note.openDraft,
  396. })
  397. const onLineSelected = (range: SelectedLineRange | null) => {
  398. if (!range) {
  399. note.select(null)
  400. note.cancelDraft()
  401. return
  402. }
  403. note.select(range)
  404. }
  405. const onLineSelectionEnd = (range: SelectedLineRange | null) => {
  406. if (!range) {
  407. if (props.clearSelectionOnSelectionEndNull) note.select(null)
  408. note.cancelDraft()
  409. return
  410. }
  411. note.finishSelection(range)
  412. }
  413. const onLineNumberSelectionEnd = (range: SelectedLineRange | null) => {
  414. if (!range) return
  415. note.openDraft(range)
  416. }
  417. return {
  418. note,
  419. annotations,
  420. renderAnnotation,
  421. renderHoverUtility,
  422. onLineSelected,
  423. onLineSelectionEnd,
  424. onLineNumberSelectionEnd,
  425. }
  426. }
  427. export function createLineCommentAnnotations<T>(
  428. props: LineCommentAnnotationsWithSideProps<T>,
  429. ): Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  430. export function createLineCommentAnnotations<T>(
  431. props: LineCommentAnnotationsProps<T>,
  432. ): Accessor<LineCommentAnnotation<T>[]>
  433. export function createLineCommentAnnotations<T>(
  434. props: LineCommentAnnotationsProps<T> | LineCommentAnnotationsWithSideProps<T>,
  435. ) {
  436. const line = (range: SelectedLineRange) => Math.max(range.start, range.end)
  437. if ("getSide" in props) {
  438. return createMemo<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>(() => {
  439. const list = props.comments().map((comment) => {
  440. const range = props.getCommentSelection(comment)
  441. return {
  442. side: props.getSide(range),
  443. lineNumber: line(range),
  444. metadata: {
  445. kind: "comment",
  446. key: `comment:${props.getCommentId(comment)}`,
  447. comment,
  448. } satisfies LineCommentAnnotationMeta<T>,
  449. }
  450. })
  451. const range = props.draftRange()
  452. if (!range) return list
  453. return [
  454. ...list,
  455. {
  456. side: props.getSide(range),
  457. lineNumber: line(range),
  458. metadata: {
  459. kind: "draft",
  460. key: `draft:${props.draftKey()}`,
  461. range,
  462. } satisfies LineCommentAnnotationMeta<T>,
  463. },
  464. ]
  465. })
  466. }
  467. return createMemo<LineCommentAnnotation<T>[]>(() => {
  468. const list = props.comments().map((comment) => {
  469. const range = props.getCommentSelection(comment)
  470. const entry: LineCommentAnnotation<T> = {
  471. lineNumber: line(range),
  472. metadata: {
  473. kind: "comment",
  474. key: `comment:${props.getCommentId(comment)}`,
  475. comment,
  476. },
  477. }
  478. return entry
  479. })
  480. const range = props.draftRange()
  481. if (!range) return list
  482. const draft: LineCommentAnnotation<T> = {
  483. lineNumber: line(range),
  484. metadata: {
  485. kind: "draft",
  486. key: `draft:${props.draftKey()}`,
  487. range,
  488. },
  489. }
  490. return [...list, draft]
  491. })
  492. }
  493. export function createManagedLineCommentAnnotationRenderer<T>(props: {
  494. annotations: Accessor<LineCommentAnnotation<T>[]>
  495. renderComment: (comment: T) => CommentProps
  496. renderDraft: (range: SelectedLineRange) => DraftProps
  497. }) {
  498. const renderer = createLineCommentAnnotationRenderer<T>({
  499. renderComment: props.renderComment,
  500. renderDraft: props.renderDraft,
  501. })
  502. createEffect(() => {
  503. renderer.reconcile(props.annotations())
  504. })
  505. onCleanup(() => {
  506. renderer.cleanup()
  507. })
  508. return {
  509. renderAnnotation: renderer.render,
  510. }
  511. }
  512. export function createLineCommentHoverRenderer(props: {
  513. label: string
  514. getSelectedRange: Accessor<SelectedLineRange | null>
  515. onOpenDraft: (range: SelectedLineRange) => void
  516. }) {
  517. return (getHoveredLine: () => HoverCommentLine | undefined) =>
  518. createHoverCommentUtility({
  519. label: props.label,
  520. getHoveredLine,
  521. onSelect: (hovered) => {
  522. const current = props.getSelectedRange()
  523. if (current && lineInSelectedRange(current, hovered.lineNumber, hovered.side)) {
  524. props.onOpenDraft(cloneSelectedLineRange(current))
  525. return
  526. }
  527. const range: SelectedLineRange = {
  528. start: hovered.lineNumber,
  529. end: hovered.lineNumber,
  530. }
  531. if (hovered.side) range.side = hovered.side
  532. props.onOpenDraft(range)
  533. },
  534. })
  535. }