line-comment-annotations.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 "@opencode-ai/ui/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. export 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. export 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. // Generic host machinery shared by the v1 and v2 annotation renderers: each
  87. // annotation key gets a detached DOM host with its own Solid root, updated in
  88. // place through a signal so Pierre can reparent the host without re-rendering.
  89. export function createLineCommentAnnotationRenderer<T, C, D>(props: {
  90. renderComment: (comment: T) => C
  91. renderDraft: (range: SelectedLineRange) => D
  92. commentElement: (view: Accessor<C>) => JSX.Element
  93. draftElement: (view: Accessor<D>) => JSX.Element
  94. }) {
  95. const nodes = new Map<
  96. string,
  97. {
  98. host: HTMLDivElement
  99. dispose: VoidFunction
  100. setMeta: (meta: LineCommentAnnotationMeta<T>) => void
  101. }
  102. >()
  103. const mount = (meta: LineCommentAnnotationMeta<T>) => {
  104. if (typeof document === "undefined") return
  105. const host = document.createElement("div")
  106. host.setAttribute("data-prevent-autofocus", "")
  107. const [current, setCurrent] = createSignal(meta)
  108. const dispose = renderSolid(() => {
  109. const active = current()
  110. if (active.kind === "comment") {
  111. const view = createMemo(() => {
  112. const next = current()
  113. if (next.kind !== "comment") return props.renderComment(active.comment)
  114. return props.renderComment(next.comment)
  115. })
  116. return props.commentElement(view)
  117. }
  118. const view = createMemo(() => {
  119. const next = current()
  120. if (next.kind !== "draft") return props.renderDraft(active.range)
  121. return props.renderDraft(next.range)
  122. })
  123. return props.draftElement(view)
  124. }, host)
  125. const node = { host, dispose, setMeta: setCurrent }
  126. nodes.set(meta.key, node)
  127. return node
  128. }
  129. const render = <A extends { metadata: LineCommentAnnotationMeta<T> }>(annotation: A) => {
  130. const meta = annotation.metadata
  131. const node = nodes.get(meta.key) ?? mount(meta)
  132. if (!node) return
  133. node.setMeta(meta)
  134. return node.host
  135. }
  136. const reconcile = <A extends { metadata: LineCommentAnnotationMeta<T> }>(annotations: A[]) => {
  137. const next = new Set(annotations.map((annotation) => annotation.metadata.key))
  138. for (const [key, node] of nodes) {
  139. if (next.has(key)) continue
  140. node.dispose()
  141. nodes.delete(key)
  142. }
  143. }
  144. const cleanup = () => {
  145. for (const [, node] of nodes) node.dispose()
  146. nodes.clear()
  147. }
  148. return { render, reconcile, cleanup }
  149. }
  150. function lineCommentElement(view: Accessor<CommentProps>) {
  151. return (
  152. <Show
  153. when={view().editor}
  154. fallback={
  155. <LineComment
  156. inline
  157. id={view().id}
  158. open={view().open}
  159. comment={view().comment}
  160. selection={view().selection}
  161. actions={view().actions}
  162. onClick={view().onClick}
  163. onMouseEnter={view().onMouseEnter}
  164. />
  165. }
  166. >
  167. <LineCommentEditor
  168. inline
  169. id={view().id}
  170. value={view().editor!.value}
  171. selection={view().editor!.selection}
  172. onInput={view().editor!.onInput}
  173. onCancel={view().editor!.onCancel}
  174. onSubmit={view().editor!.onSubmit}
  175. onPopoverFocusOut={view().editor!.onPopoverFocusOut}
  176. cancelLabel={view().editor!.cancelLabel}
  177. submitLabel={view().editor!.submitLabel}
  178. mention={view().editor!.mention}
  179. />
  180. </Show>
  181. )
  182. }
  183. function lineCommentDraftElement(view: Accessor<DraftProps>) {
  184. return (
  185. <LineCommentEditor
  186. inline
  187. value={view().value}
  188. selection={view().selection}
  189. onInput={view().onInput}
  190. onCancel={view().onCancel}
  191. onSubmit={view().onSubmit}
  192. onPopoverFocusOut={view().onPopoverFocusOut}
  193. mention={view().mention}
  194. />
  195. )
  196. }
  197. export function createLineCommentState<T>(props: LineCommentStateProps<T>) {
  198. const [state, setState] = createStore({
  199. draft: "",
  200. editing: null as T | null,
  201. })
  202. const draft = () => state.draft
  203. const setDraft = (value: string) => setState("draft", value)
  204. const editing = () => state.editing
  205. const setEditing = (value: T | null) => setState("editing", typeof value === "function" ? () => value : value)
  206. const toRange = (range: SelectedLineRange | null) => (range ? cloneSelectedLineRange(range) : null)
  207. const setSelected = (range: SelectedLineRange | null) => {
  208. const next = toRange(range)
  209. props.setSelected(next)
  210. props.syncSelected?.(toRange(next))
  211. return next
  212. }
  213. const setCommenting = (range: SelectedLineRange | null) => {
  214. const next = toRange(range)
  215. props.setCommenting(next)
  216. return next
  217. }
  218. const closeComment = () => {
  219. props.setOpened(null)
  220. }
  221. const cancelDraft = () => {
  222. setDraft("")
  223. setEditing(null)
  224. setCommenting(null)
  225. }
  226. const reset = () => {
  227. setDraft("")
  228. setEditing(null)
  229. props.setOpened(null)
  230. props.setSelected(null)
  231. props.setCommenting(null)
  232. }
  233. const openComment = (id: T, range: SelectedLineRange, options?: { cancelDraft?: boolean }) => {
  234. if (options?.cancelDraft) cancelDraft()
  235. props.setOpened(id)
  236. setSelected(range)
  237. }
  238. const toggleComment = (id: T, range: SelectedLineRange, options?: { cancelDraft?: boolean }) => {
  239. if (options?.cancelDraft) cancelDraft()
  240. const next = props.opened() === id ? null : id
  241. props.setOpened(next)
  242. setSelected(range)
  243. }
  244. const openDraft = (range: SelectedLineRange) => {
  245. const next = toRange(range)
  246. setDraft("")
  247. setEditing(null)
  248. closeComment()
  249. setSelected(next)
  250. setCommenting(next)
  251. }
  252. const openEditor = (id: T, range: SelectedLineRange, value: string) => {
  253. closeComment()
  254. setSelected(range)
  255. props.setCommenting(null)
  256. setEditing(id)
  257. setDraft(value)
  258. }
  259. const hoverComment = (range: SelectedLineRange) => {
  260. const next = toRange(range)
  261. if (!next) return
  262. if (props.hoverSelected) {
  263. props.hoverSelected(next)
  264. return
  265. }
  266. setSelected(next)
  267. }
  268. return {
  269. draft,
  270. setDraft,
  271. editing,
  272. opened: props.opened,
  273. selected: props.selected,
  274. commenting: props.commenting,
  275. isOpen: (id: T) => props.opened() === id,
  276. isEditing: (id: T) => editing() === id,
  277. closeComment,
  278. openComment,
  279. toggleComment,
  280. openDraft,
  281. openEditor,
  282. hoverComment,
  283. cancelDraft,
  284. select: setSelected,
  285. reset,
  286. }
  287. }
  288. export function createLineCommentController<T extends LineCommentShape>(
  289. props: LineCommentControllerWithSideProps<T>,
  290. ): {
  291. note: ReturnType<typeof createLineCommentState<string>>
  292. annotations: Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  293. renderAnnotation: ReturnType<
  294. typeof createManagedLineCommentAnnotationRenderer<T, CommentProps, DraftProps>
  295. >["renderAnnotation"]
  296. renderGutterUtility: ReturnType<typeof createLineCommentGutterRenderer>
  297. onLineSelected: (range: SelectedLineRange | null) => void
  298. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  299. }
  300. export function createLineCommentController<T extends LineCommentShape>(
  301. props: LineCommentControllerProps<T>,
  302. ): {
  303. note: ReturnType<typeof createLineCommentState<string>>
  304. annotations: Accessor<LineCommentAnnotation<T>[]>
  305. renderAnnotation: ReturnType<
  306. typeof createManagedLineCommentAnnotationRenderer<T, CommentProps, DraftProps>
  307. >["renderAnnotation"]
  308. renderGutterUtility: ReturnType<typeof createLineCommentGutterRenderer>
  309. onLineSelected: (range: SelectedLineRange | null) => void
  310. onLineSelectionEnd: (range: SelectedLineRange | null) => void
  311. }
  312. export function createLineCommentController<T extends LineCommentShape>(
  313. props: LineCommentControllerProps<T> | LineCommentControllerWithSideProps<T>,
  314. ) {
  315. const i18n = useI18n()
  316. const note = createLineCommentState<string>(props.state)
  317. const annotations =
  318. "getSide" in props
  319. ? createLineCommentAnnotations({
  320. comments: props.comments,
  321. getCommentId: (comment) => comment.id,
  322. getCommentSelection: (comment) => comment.selection,
  323. draftRange: note.commenting,
  324. draftKey: props.draftKey,
  325. getSide: props.getSide,
  326. })
  327. : createLineCommentAnnotations({
  328. comments: props.comments,
  329. getCommentId: (comment) => comment.id,
  330. getCommentSelection: (comment) => comment.selection,
  331. draftRange: note.commenting,
  332. draftKey: props.draftKey,
  333. })
  334. const { renderAnnotation } = createManagedLineCommentAnnotationRenderer<T, CommentProps, DraftProps>({
  335. annotations,
  336. commentElement: lineCommentElement,
  337. draftElement: lineCommentDraftElement,
  338. renderComment: (comment) => {
  339. const edit = () => note.openEditor(comment.id, comment.selection, comment.comment)
  340. const remove = () => {
  341. note.reset()
  342. props.onDelete?.(comment)
  343. }
  344. return {
  345. id: comment.id,
  346. get open() {
  347. return note.isOpen(comment.id) || note.isEditing(comment.id)
  348. },
  349. comment: comment.comment,
  350. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  351. get actions() {
  352. return props.renderCommentActions?.(comment, { edit, remove })
  353. },
  354. get editor() {
  355. return note.isEditing(comment.id)
  356. ? {
  357. get value() {
  358. return note.draft()
  359. },
  360. selection: formatSelectedLineLabel(comment.selection, i18n.t),
  361. mention: props.mention,
  362. onInput: note.setDraft,
  363. onCancel: note.cancelDraft,
  364. onSubmit: (value: string) => {
  365. props.onUpdate?.({
  366. id: comment.id,
  367. comment: value,
  368. selection: cloneSelectedLineRange(comment.selection),
  369. })
  370. note.cancelDraft()
  371. },
  372. submitLabel: props.editSubmitLabel,
  373. }
  374. : undefined
  375. },
  376. onMouseEnter: () => note.hoverComment(comment.selection),
  377. onClick: () => {
  378. if (note.isEditing(comment.id)) return
  379. note.toggleComment(comment.id, comment.selection, { cancelDraft: props.cancelDraftOnCommentToggle })
  380. },
  381. }
  382. },
  383. renderDraft: (range) => ({
  384. get value() {
  385. return note.draft()
  386. },
  387. selection: formatSelectedLineLabel(range, i18n.t),
  388. mention: props.mention,
  389. onInput: note.setDraft,
  390. onCancel: () => {
  391. note.cancelDraft()
  392. note.select(null)
  393. },
  394. onSubmit: (comment) => {
  395. props.onSubmit({ comment, selection: cloneSelectedLineRange(range) })
  396. note.cancelDraft()
  397. },
  398. onPopoverFocusOut: props.onDraftPopoverFocusOut,
  399. }),
  400. })
  401. const renderGutterUtility = createLineCommentGutterRenderer({
  402. label: props.label,
  403. getSelectedRange: () => {
  404. if (note.opened()) return null
  405. return props.getHoverSelectedRange?.() ?? note.selected()
  406. },
  407. onOpenDraft: note.openDraft,
  408. })
  409. const onLineSelected = (range: SelectedLineRange | null) => {
  410. if (!range) {
  411. note.select(null)
  412. note.cancelDraft()
  413. return
  414. }
  415. note.select(range)
  416. }
  417. const onLineSelectionEnd = (range: SelectedLineRange | null) => {
  418. if (!range) {
  419. if (props.clearSelectionOnSelectionEndNull) note.select(null)
  420. note.cancelDraft()
  421. return
  422. }
  423. note.openDraft(range)
  424. }
  425. return {
  426. note,
  427. annotations,
  428. renderAnnotation,
  429. renderGutterUtility,
  430. onLineSelected,
  431. onLineSelectionEnd,
  432. }
  433. }
  434. export function createLineCommentAnnotations<T>(
  435. props: LineCommentAnnotationsWithSideProps<T>,
  436. ): Accessor<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>
  437. export function createLineCommentAnnotations<T>(
  438. props: LineCommentAnnotationsProps<T>,
  439. ): Accessor<LineCommentAnnotation<T>[]>
  440. export function createLineCommentAnnotations<T>(
  441. props: LineCommentAnnotationsProps<T> | LineCommentAnnotationsWithSideProps<T>,
  442. ) {
  443. const line = (range: SelectedLineRange) => Math.max(range.start, range.end)
  444. if ("getSide" in props) {
  445. return createMemo<DiffLineAnnotation<LineCommentAnnotationMeta<T>>[]>(
  446. () => {
  447. const list = props.comments().map((comment) => {
  448. const range = props.getCommentSelection(comment)
  449. return {
  450. side: props.getSide(range),
  451. lineNumber: line(range),
  452. metadata: {
  453. kind: "comment",
  454. key: `comment:${props.getCommentId(comment)}`,
  455. comment,
  456. } satisfies LineCommentAnnotationMeta<T>,
  457. }
  458. })
  459. const range = props.draftRange()
  460. if (!range) return list
  461. return [
  462. ...list,
  463. {
  464. side: props.getSide(range),
  465. lineNumber: line(range),
  466. metadata: {
  467. kind: "draft",
  468. key: `draft:${props.draftKey()}`,
  469. range,
  470. } satisfies LineCommentAnnotationMeta<T>,
  471. },
  472. ]
  473. },
  474. [],
  475. // Stable identity for unchanged annotations avoids no-op diff rerenders downstream.
  476. { equals: sameAnnotationLists },
  477. )
  478. }
  479. return createMemo<LineCommentAnnotation<T>[]>(
  480. () => {
  481. const list = props.comments().map((comment) => {
  482. const range = props.getCommentSelection(comment)
  483. const entry: LineCommentAnnotation<T> = {
  484. lineNumber: line(range),
  485. metadata: {
  486. kind: "comment",
  487. key: `comment:${props.getCommentId(comment)}`,
  488. comment,
  489. },
  490. }
  491. return entry
  492. })
  493. const range = props.draftRange()
  494. if (!range) return list
  495. const draft: LineCommentAnnotation<T> = {
  496. lineNumber: line(range),
  497. metadata: {
  498. kind: "draft",
  499. key: `draft:${props.draftKey()}`,
  500. range,
  501. },
  502. }
  503. return [...list, draft]
  504. },
  505. [],
  506. { equals: sameAnnotationLists },
  507. )
  508. }
  509. type AnnotationListItem = {
  510. lineNumber: number
  511. side?: unknown
  512. metadata: { kind: string; key: string; comment?: unknown; range?: unknown }
  513. }
  514. function sameAnnotationLists(previous: AnnotationListItem[], next: AnnotationListItem[]) {
  515. if (previous.length !== next.length) return false
  516. return previous.every((item, index) => {
  517. const other = next[index]!
  518. return (
  519. item.lineNumber === other.lineNumber &&
  520. item.side === other.side &&
  521. item.metadata.kind === other.metadata.kind &&
  522. item.metadata.key === other.metadata.key &&
  523. item.metadata.comment === other.metadata.comment &&
  524. item.metadata.range === other.metadata.range
  525. )
  526. })
  527. }
  528. export function createManagedLineCommentAnnotationRenderer<T, C, D>(props: {
  529. annotations: Accessor<LineCommentAnnotation<T>[]>
  530. renderComment: (comment: T) => C
  531. renderDraft: (range: SelectedLineRange) => D
  532. commentElement: (view: Accessor<C>) => JSX.Element
  533. draftElement: (view: Accessor<D>) => JSX.Element
  534. }) {
  535. const renderer = createLineCommentAnnotationRenderer<T, C, D>({
  536. renderComment: props.renderComment,
  537. renderDraft: props.renderDraft,
  538. commentElement: props.commentElement,
  539. draftElement: props.draftElement,
  540. })
  541. createEffect(() => {
  542. renderer.reconcile(props.annotations())
  543. })
  544. onCleanup(() => {
  545. renderer.cleanup()
  546. })
  547. return {
  548. renderAnnotation: renderer.render,
  549. }
  550. }
  551. export function createLineCommentGutterRenderer(props: {
  552. label: string
  553. getSelectedRange: Accessor<SelectedLineRange | null>
  554. onOpenDraft: (range: SelectedLineRange) => void
  555. }) {
  556. return (getHoveredLine: () => HoverCommentLine | undefined) =>
  557. createHoverCommentUtility({
  558. label: props.label,
  559. getHoveredLine,
  560. onSelect: (hovered) => {
  561. const current = props.getSelectedRange()
  562. if (current && lineInSelectedRange(current, hovered.lineNumber, hovered.side)) {
  563. props.onOpenDraft(cloneSelectedLineRange(current))
  564. return
  565. }
  566. const range: SelectedLineRange = {
  567. start: hovered.lineNumber,
  568. end: hovered.lineNumber,
  569. }
  570. if (hovered.side) range.side = hovered.side
  571. props.onOpenDraft(range)
  572. },
  573. })
  574. }