code.tsx 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. import { type FileContents, File, FileOptions, LineAnnotation, type SelectedLineRange } from "@pierre/diffs"
  2. import { ComponentProps, createEffect, createMemo, createSignal, onCleanup, onMount, Show, splitProps } from "solid-js"
  3. import { Portal } from "solid-js/web"
  4. import { createDefaultOptions, styleVariables } from "../pierre"
  5. import { getWorkerPool } from "../pierre/worker"
  6. import { Icon } from "./icon"
  7. type SelectionSide = "additions" | "deletions"
  8. export type CodeProps<T = {}> = FileOptions<T> & {
  9. file: FileContents
  10. annotations?: LineAnnotation<T>[]
  11. selectedLines?: SelectedLineRange | null
  12. commentedLines?: SelectedLineRange[]
  13. onRendered?: () => void
  14. onLineSelectionEnd?: (selection: SelectedLineRange | null) => void
  15. class?: string
  16. classList?: ComponentProps<"div">["classList"]
  17. }
  18. function findElement(node: Node | null): HTMLElement | undefined {
  19. if (!node) return
  20. if (node instanceof HTMLElement) return node
  21. return node.parentElement ?? undefined
  22. }
  23. function findLineNumber(node: Node | null): number | undefined {
  24. const element = findElement(node)
  25. if (!element) return
  26. const line = element.closest("[data-line]")
  27. if (!(line instanceof HTMLElement)) return
  28. const value = parseInt(line.dataset.line ?? "", 10)
  29. if (Number.isNaN(value)) return
  30. return value
  31. }
  32. function findSide(node: Node | null): SelectionSide | undefined {
  33. const element = findElement(node)
  34. if (!element) return
  35. const code = element.closest("[data-code]")
  36. if (!(code instanceof HTMLElement)) return
  37. if (code.hasAttribute("data-deletions")) return "deletions"
  38. return "additions"
  39. }
  40. type FindHost = {
  41. element: () => HTMLElement | undefined
  42. open: () => void
  43. close: () => void
  44. next: (dir: 1 | -1) => void
  45. isOpen: () => boolean
  46. }
  47. const findHosts = new Set<FindHost>()
  48. let findTarget: FindHost | undefined
  49. let findCurrent: FindHost | undefined
  50. let findInstalled = false
  51. function isEditable(node: unknown): boolean {
  52. if (!(node instanceof HTMLElement)) return false
  53. if (node.closest("[data-prevent-autofocus]")) return true
  54. if (node.isContentEditable) return true
  55. return /^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(node.tagName)
  56. }
  57. function hostForNode(node: unknown): FindHost | undefined {
  58. if (!(node instanceof Node)) return
  59. for (const host of findHosts) {
  60. const el = host.element()
  61. if (el && el.isConnected && el.contains(node)) return host
  62. }
  63. }
  64. function installFindShortcuts() {
  65. if (findInstalled) return
  66. if (typeof window === "undefined") return
  67. findInstalled = true
  68. window.addEventListener(
  69. "keydown",
  70. (event) => {
  71. if (event.defaultPrevented) return
  72. const mod = event.metaKey || event.ctrlKey
  73. if (!mod) return
  74. const key = event.key.toLowerCase()
  75. if (key === "g") {
  76. const host = findCurrent
  77. if (!host || !host.isOpen()) return
  78. event.preventDefault()
  79. event.stopPropagation()
  80. host.next(event.shiftKey ? -1 : 1)
  81. return
  82. }
  83. if (key !== "f") return
  84. const current = findCurrent
  85. if (current && current.isOpen()) {
  86. event.preventDefault()
  87. event.stopPropagation()
  88. current.open()
  89. return
  90. }
  91. const host =
  92. hostForNode(document.activeElement) ?? hostForNode(event.target) ?? findTarget ?? Array.from(findHosts)[0]
  93. if (!host) return
  94. event.preventDefault()
  95. event.stopPropagation()
  96. host.open()
  97. },
  98. { capture: true },
  99. )
  100. }
  101. export function Code<T>(props: CodeProps<T>) {
  102. let wrapper!: HTMLDivElement
  103. let container!: HTMLDivElement
  104. let findInput: HTMLInputElement | undefined
  105. let findOverlay!: HTMLDivElement
  106. let findOverlayFrame: number | undefined
  107. let findOverlayScroll: HTMLElement[] = []
  108. let observer: MutationObserver | undefined
  109. let renderToken = 0
  110. let selectionFrame: number | undefined
  111. let dragFrame: number | undefined
  112. let dragStart: number | undefined
  113. let dragEnd: number | undefined
  114. let dragMoved = false
  115. let lastSelection: SelectedLineRange | null = null
  116. let pendingSelectionEnd = false
  117. const [local, others] = splitProps(props, [
  118. "file",
  119. "class",
  120. "classList",
  121. "annotations",
  122. "selectedLines",
  123. "commentedLines",
  124. "onRendered",
  125. ])
  126. const [rendered, setRendered] = createSignal(0)
  127. const [findOpen, setFindOpen] = createSignal(false)
  128. const [findQuery, setFindQuery] = createSignal("")
  129. const [findIndex, setFindIndex] = createSignal(0)
  130. const [findCount, setFindCount] = createSignal(0)
  131. let findMode: "highlights" | "overlay" = "overlay"
  132. let findHits: Range[] = []
  133. const [findPos, setFindPos] = createSignal<{ top: number; right: number }>({ top: 8, right: 8 })
  134. const file = createMemo(
  135. () =>
  136. new File<T>(
  137. {
  138. ...createDefaultOptions<T>("unified"),
  139. ...others,
  140. },
  141. getWorkerPool("unified"),
  142. ),
  143. )
  144. const getRoot = () => {
  145. const host = container.querySelector("diffs-container")
  146. if (!(host instanceof HTMLElement)) return
  147. const root = host.shadowRoot
  148. if (!root) return
  149. return root
  150. }
  151. const applyScheme = () => {
  152. const host = container.querySelector("diffs-container")
  153. if (!(host instanceof HTMLElement)) return
  154. const scheme = document.documentElement.dataset.colorScheme
  155. if (scheme === "dark" || scheme === "light") {
  156. host.dataset.colorScheme = scheme
  157. return
  158. }
  159. host.removeAttribute("data-color-scheme")
  160. }
  161. const supportsHighlights = () => {
  162. const g = globalThis as unknown as { CSS?: { highlights?: unknown }; Highlight?: unknown }
  163. return typeof g.Highlight === "function" && g.CSS?.highlights != null
  164. }
  165. const clearHighlightFind = () => {
  166. const api = (globalThis as { CSS?: { highlights?: { delete: (name: string) => void } } }).CSS?.highlights
  167. if (!api) return
  168. api.delete("opencode-find")
  169. api.delete("opencode-find-current")
  170. }
  171. const clearOverlayScroll = () => {
  172. for (const el of findOverlayScroll) el.removeEventListener("scroll", scheduleOverlay)
  173. findOverlayScroll = []
  174. }
  175. const clearOverlay = () => {
  176. if (findOverlayFrame !== undefined) {
  177. cancelAnimationFrame(findOverlayFrame)
  178. findOverlayFrame = undefined
  179. }
  180. findOverlay.innerHTML = ""
  181. }
  182. const renderOverlay = () => {
  183. if (findMode !== "overlay") {
  184. clearOverlay()
  185. return
  186. }
  187. clearOverlay()
  188. if (findHits.length === 0) return
  189. const base = wrapper.getBoundingClientRect()
  190. const current = findIndex()
  191. const frag = document.createDocumentFragment()
  192. for (let i = 0; i < findHits.length; i++) {
  193. const range = findHits[i]
  194. const active = i === current
  195. for (const rect of Array.from(range.getClientRects())) {
  196. if (!rect.width || !rect.height) continue
  197. const el = document.createElement("div")
  198. el.style.position = "absolute"
  199. el.style.left = `${Math.round(rect.left - base.left)}px`
  200. el.style.top = `${Math.round(rect.top - base.top)}px`
  201. el.style.width = `${Math.round(rect.width)}px`
  202. el.style.height = `${Math.round(rect.height)}px`
  203. el.style.borderRadius = "2px"
  204. el.style.backgroundColor = active ? "var(--surface-warning-strong)" : "var(--surface-warning-base)"
  205. el.style.opacity = active ? "0.55" : "0.35"
  206. if (active) el.style.boxShadow = "inset 0 0 0 1px var(--border-warning-base)"
  207. frag.appendChild(el)
  208. }
  209. }
  210. findOverlay.appendChild(frag)
  211. }
  212. function scheduleOverlay() {
  213. if (findMode !== "overlay") return
  214. if (!findOpen()) return
  215. if (findOverlayFrame !== undefined) return
  216. findOverlayFrame = requestAnimationFrame(() => {
  217. findOverlayFrame = undefined
  218. renderOverlay()
  219. })
  220. }
  221. const syncOverlayScroll = () => {
  222. if (findMode !== "overlay") return
  223. const root = getRoot()
  224. const next = root
  225. ? Array.from(root.querySelectorAll("[data-code]")).filter(
  226. (node): node is HTMLElement => node instanceof HTMLElement,
  227. )
  228. : []
  229. if (next.length === findOverlayScroll.length && next.every((el, i) => el === findOverlayScroll[i])) return
  230. clearOverlayScroll()
  231. findOverlayScroll = next
  232. for (const el of findOverlayScroll) el.addEventListener("scroll", scheduleOverlay, { passive: true })
  233. }
  234. const clearFind = () => {
  235. clearHighlightFind()
  236. clearOverlay()
  237. clearOverlayScroll()
  238. findHits = []
  239. setFindCount(0)
  240. setFindIndex(0)
  241. }
  242. const getScrollParent = (el: HTMLElement): HTMLElement | undefined => {
  243. let parent = el.parentElement
  244. while (parent) {
  245. const style = getComputedStyle(parent)
  246. if (style.overflowY === "auto" || style.overflowY === "scroll") return parent
  247. parent = parent.parentElement
  248. }
  249. }
  250. const positionFindBar = () => {
  251. if (typeof window === "undefined") return
  252. const root = getScrollParent(wrapper) ?? wrapper
  253. const rect = root.getBoundingClientRect()
  254. const title = parseFloat(getComputedStyle(root).getPropertyValue("--session-title-height"))
  255. const header = Number.isNaN(title) ? 0 : title
  256. setFindPos({
  257. top: Math.round(rect.top) + header - 4,
  258. right: Math.round(window.innerWidth - rect.right) + 8,
  259. })
  260. }
  261. const scanFind = (root: ShadowRoot, query: string) => {
  262. const needle = query.toLowerCase()
  263. const out: Range[] = []
  264. const cols = Array.from(root.querySelectorAll("[data-column-content]")).filter(
  265. (node): node is HTMLElement => node instanceof HTMLElement,
  266. )
  267. for (const col of cols) {
  268. const text = col.textContent
  269. if (!text) continue
  270. const hay = text.toLowerCase()
  271. let idx = hay.indexOf(needle)
  272. if (idx === -1) continue
  273. const nodes: Text[] = []
  274. const ends: number[] = []
  275. const walker = document.createTreeWalker(col, NodeFilter.SHOW_TEXT)
  276. let node = walker.nextNode()
  277. let pos = 0
  278. while (node) {
  279. if (node instanceof Text) {
  280. pos += node.data.length
  281. nodes.push(node)
  282. ends.push(pos)
  283. }
  284. node = walker.nextNode()
  285. }
  286. if (nodes.length === 0) continue
  287. const locate = (at: number) => {
  288. let lo = 0
  289. let hi = ends.length - 1
  290. while (lo < hi) {
  291. const mid = (lo + hi) >> 1
  292. if (ends[mid] >= at) hi = mid
  293. else lo = mid + 1
  294. }
  295. const prev = lo === 0 ? 0 : ends[lo - 1]
  296. return { node: nodes[lo], offset: at - prev }
  297. }
  298. while (idx !== -1) {
  299. const start = locate(idx)
  300. const end = locate(idx + query.length)
  301. const range = document.createRange()
  302. range.setStart(start.node, start.offset)
  303. range.setEnd(end.node, end.offset)
  304. out.push(range)
  305. idx = hay.indexOf(needle, idx + query.length)
  306. }
  307. }
  308. return out
  309. }
  310. const scrollToRange = (range: Range) => {
  311. const start = range.startContainer
  312. const el = start instanceof Element ? start : start.parentElement
  313. el?.scrollIntoView({ block: "center", inline: "center" })
  314. }
  315. const setHighlights = (ranges: Range[], index: number) => {
  316. const api = (globalThis as unknown as { CSS?: { highlights?: any }; Highlight?: any }).CSS?.highlights
  317. const Highlight = (globalThis as unknown as { Highlight?: any }).Highlight
  318. if (!api || typeof Highlight !== "function") return false
  319. api.delete("opencode-find")
  320. api.delete("opencode-find-current")
  321. const active = ranges[index]
  322. if (active) api.set("opencode-find-current", new Highlight(active))
  323. const rest = ranges.filter((_, i) => i !== index)
  324. if (rest.length > 0) api.set("opencode-find", new Highlight(...rest))
  325. return true
  326. }
  327. const applyFind = (opts?: { reset?: boolean; scroll?: boolean }) => {
  328. if (!findOpen()) return
  329. const query = findQuery().trim()
  330. if (!query) {
  331. clearFind()
  332. return
  333. }
  334. const root = getRoot()
  335. if (!root) return
  336. findMode = supportsHighlights() ? "highlights" : "overlay"
  337. const ranges = scanFind(root, query)
  338. const total = ranges.length
  339. const desired = opts?.reset ? 0 : findIndex()
  340. const index = total ? Math.min(desired, total - 1) : 0
  341. findHits = ranges
  342. setFindCount(total)
  343. setFindIndex(index)
  344. const active = ranges[index]
  345. if (findMode === "highlights") {
  346. clearOverlay()
  347. clearOverlayScroll()
  348. if (!setHighlights(ranges, index)) {
  349. findMode = "overlay"
  350. clearHighlightFind()
  351. syncOverlayScroll()
  352. scheduleOverlay()
  353. }
  354. if (opts?.scroll && active) {
  355. scrollToRange(active)
  356. }
  357. return
  358. }
  359. clearHighlightFind()
  360. syncOverlayScroll()
  361. if (opts?.scroll && active) {
  362. scrollToRange(active)
  363. }
  364. scheduleOverlay()
  365. }
  366. const closeFind = () => {
  367. setFindOpen(false)
  368. clearFind()
  369. if (findCurrent === host) findCurrent = undefined
  370. }
  371. const stepFind = (dir: 1 | -1) => {
  372. if (!findOpen()) return
  373. const total = findCount()
  374. if (total <= 0) return
  375. const index = (findIndex() + dir + total) % total
  376. setFindIndex(index)
  377. const active = findHits[index]
  378. if (!active) return
  379. if (findMode === "highlights") {
  380. if (!setHighlights(findHits, index)) {
  381. findMode = "overlay"
  382. applyFind({ reset: true, scroll: true })
  383. return
  384. }
  385. scrollToRange(active)
  386. return
  387. }
  388. clearHighlightFind()
  389. syncOverlayScroll()
  390. scrollToRange(active)
  391. scheduleOverlay()
  392. }
  393. const host: FindHost = {
  394. element: () => wrapper,
  395. isOpen: () => findOpen(),
  396. next: stepFind,
  397. open: () => {
  398. if (findCurrent && findCurrent !== host) findCurrent.close()
  399. findCurrent = host
  400. findTarget = host
  401. if (!findOpen()) setFindOpen(true)
  402. requestAnimationFrame(() => {
  403. applyFind({ scroll: true })
  404. findInput?.focus()
  405. findInput?.select()
  406. })
  407. },
  408. close: closeFind,
  409. }
  410. onMount(() => {
  411. findMode = supportsHighlights() ? "highlights" : "overlay"
  412. installFindShortcuts()
  413. findHosts.add(host)
  414. if (!findTarget) findTarget = host
  415. onCleanup(() => {
  416. findHosts.delete(host)
  417. if (findCurrent === host) {
  418. findCurrent = undefined
  419. clearHighlightFind()
  420. }
  421. if (findTarget === host) findTarget = undefined
  422. })
  423. })
  424. createEffect(() => {
  425. if (!findOpen()) return
  426. const update = () => positionFindBar()
  427. requestAnimationFrame(update)
  428. window.addEventListener("resize", update, { passive: true })
  429. const root = getScrollParent(wrapper) ?? wrapper
  430. const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(() => update())
  431. observer?.observe(root)
  432. onCleanup(() => {
  433. window.removeEventListener("resize", update)
  434. observer?.disconnect()
  435. })
  436. })
  437. const applyCommentedLines = (ranges: SelectedLineRange[]) => {
  438. const root = getRoot()
  439. if (!root) return
  440. const existing = Array.from(root.querySelectorAll("[data-comment-selected]"))
  441. for (const node of existing) {
  442. if (!(node instanceof HTMLElement)) continue
  443. node.removeAttribute("data-comment-selected")
  444. }
  445. for (const range of ranges) {
  446. const start = Math.max(1, Math.min(range.start, range.end))
  447. const end = Math.max(range.start, range.end)
  448. for (let line = start; line <= end; line++) {
  449. const nodes = Array.from(root.querySelectorAll(`[data-line="${line}"]`))
  450. for (const node of nodes) {
  451. if (!(node instanceof HTMLElement)) continue
  452. node.setAttribute("data-comment-selected", "")
  453. }
  454. }
  455. }
  456. }
  457. const lineCount = () => {
  458. const text = local.file.contents
  459. const total = text.split("\n").length - (text.endsWith("\n") ? 1 : 0)
  460. return Math.max(1, total)
  461. }
  462. const applySelection = (range: SelectedLineRange | null) => {
  463. const root = getRoot()
  464. if (!root) return false
  465. const lines = lineCount()
  466. if (root.querySelectorAll("[data-line]").length < lines) return false
  467. if (!range) {
  468. file().setSelectedLines(null)
  469. return true
  470. }
  471. const start = Math.min(range.start, range.end)
  472. const end = Math.max(range.start, range.end)
  473. if (start < 1 || end > lines) {
  474. file().setSelectedLines(null)
  475. return true
  476. }
  477. if (!root.querySelector(`[data-line="${start}"]`) || !root.querySelector(`[data-line="${end}"]`)) {
  478. file().setSelectedLines(null)
  479. return true
  480. }
  481. const normalized = (() => {
  482. if (range.endSide != null) return { start: range.start, end: range.end }
  483. if (range.side !== "deletions") return range
  484. if (root.querySelector("[data-deletions]") != null) return range
  485. return { start: range.start, end: range.end }
  486. })()
  487. file().setSelectedLines(normalized)
  488. return true
  489. }
  490. const notifyRendered = () => {
  491. observer?.disconnect()
  492. observer = undefined
  493. renderToken++
  494. const token = renderToken
  495. const lines = lineCount()
  496. const isReady = (root: ShadowRoot) => root.querySelectorAll("[data-line]").length >= lines
  497. const notify = () => {
  498. if (token !== renderToken) return
  499. observer?.disconnect()
  500. observer = undefined
  501. requestAnimationFrame(() => {
  502. if (token !== renderToken) return
  503. applySelection(lastSelection)
  504. applyFind({ reset: true })
  505. local.onRendered?.()
  506. })
  507. }
  508. const root = getRoot()
  509. if (root && isReady(root)) {
  510. notify()
  511. return
  512. }
  513. if (typeof MutationObserver === "undefined") return
  514. const observeRoot = (root: ShadowRoot) => {
  515. if (isReady(root)) {
  516. notify()
  517. return
  518. }
  519. observer?.disconnect()
  520. observer = new MutationObserver(() => {
  521. if (token !== renderToken) return
  522. if (!isReady(root)) return
  523. notify()
  524. })
  525. observer.observe(root, { childList: true, subtree: true })
  526. }
  527. if (root) {
  528. observeRoot(root)
  529. return
  530. }
  531. observer = new MutationObserver(() => {
  532. if (token !== renderToken) return
  533. const root = getRoot()
  534. if (!root) return
  535. observeRoot(root)
  536. })
  537. observer.observe(container, { childList: true, subtree: true })
  538. }
  539. const updateSelection = () => {
  540. const root = getRoot()
  541. if (!root) return
  542. const selection =
  543. (root as unknown as { getSelection?: () => Selection | null }).getSelection?.() ?? window.getSelection()
  544. if (!selection || selection.isCollapsed) return
  545. const domRange =
  546. (
  547. selection as unknown as {
  548. getComposedRanges?: (options?: { shadowRoots?: ShadowRoot[] }) => Range[]
  549. }
  550. ).getComposedRanges?.({ shadowRoots: [root] })?.[0] ??
  551. (selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined)
  552. const startNode = domRange?.startContainer ?? selection.anchorNode
  553. const endNode = domRange?.endContainer ?? selection.focusNode
  554. if (!startNode || !endNode) return
  555. if (!root.contains(startNode) || !root.contains(endNode)) return
  556. const start = findLineNumber(startNode)
  557. const end = findLineNumber(endNode)
  558. if (start === undefined || end === undefined) return
  559. const startSide = findSide(startNode)
  560. const endSide = findSide(endNode)
  561. const side = startSide ?? endSide
  562. const selected: SelectedLineRange = {
  563. start,
  564. end,
  565. }
  566. if (side) selected.side = side
  567. if (endSide && side && endSide !== side) selected.endSide = endSide
  568. setSelectedLines(selected)
  569. }
  570. const setSelectedLines = (range: SelectedLineRange | null) => {
  571. lastSelection = range
  572. applySelection(range)
  573. }
  574. const scheduleSelectionUpdate = () => {
  575. if (selectionFrame !== undefined) return
  576. selectionFrame = requestAnimationFrame(() => {
  577. selectionFrame = undefined
  578. updateSelection()
  579. if (!pendingSelectionEnd) return
  580. pendingSelectionEnd = false
  581. props.onLineSelectionEnd?.(lastSelection)
  582. })
  583. }
  584. const updateDragSelection = () => {
  585. if (dragStart === undefined || dragEnd === undefined) return
  586. const start = Math.min(dragStart, dragEnd)
  587. const end = Math.max(dragStart, dragEnd)
  588. setSelectedLines({ start, end })
  589. }
  590. const scheduleDragUpdate = () => {
  591. if (dragFrame !== undefined) return
  592. dragFrame = requestAnimationFrame(() => {
  593. dragFrame = undefined
  594. updateDragSelection()
  595. })
  596. }
  597. const lineFromMouseEvent = (event: MouseEvent) => {
  598. const path = event.composedPath()
  599. let numberColumn = false
  600. let line: number | undefined
  601. for (const item of path) {
  602. if (!(item instanceof HTMLElement)) continue
  603. numberColumn = numberColumn || item.dataset.columnNumber != null
  604. if (line === undefined && item.dataset.line) {
  605. const parsed = parseInt(item.dataset.line, 10)
  606. if (!Number.isNaN(parsed)) line = parsed
  607. }
  608. if (numberColumn && line !== undefined) break
  609. }
  610. return { line, numberColumn }
  611. }
  612. const handleMouseDown = (event: MouseEvent) => {
  613. if (props.enableLineSelection !== true) return
  614. if (event.button !== 0) return
  615. const { line, numberColumn } = lineFromMouseEvent(event)
  616. if (numberColumn) return
  617. if (line === undefined) return
  618. dragStart = line
  619. dragEnd = line
  620. dragMoved = false
  621. }
  622. const handleMouseMove = (event: MouseEvent) => {
  623. if (props.enableLineSelection !== true) return
  624. if (dragStart === undefined) return
  625. if ((event.buttons & 1) === 0) {
  626. dragStart = undefined
  627. dragEnd = undefined
  628. dragMoved = false
  629. return
  630. }
  631. const { line } = lineFromMouseEvent(event)
  632. if (line === undefined) return
  633. dragEnd = line
  634. dragMoved = true
  635. scheduleDragUpdate()
  636. }
  637. const handleMouseUp = () => {
  638. if (props.enableLineSelection !== true) return
  639. if (dragStart === undefined) return
  640. if (!dragMoved) {
  641. pendingSelectionEnd = false
  642. const line = dragStart
  643. setSelectedLines({ start: line, end: line })
  644. props.onLineSelectionEnd?.(lastSelection)
  645. dragStart = undefined
  646. dragEnd = undefined
  647. dragMoved = false
  648. return
  649. }
  650. pendingSelectionEnd = true
  651. scheduleDragUpdate()
  652. scheduleSelectionUpdate()
  653. dragStart = undefined
  654. dragEnd = undefined
  655. dragMoved = false
  656. }
  657. const handleSelectionChange = () => {
  658. if (props.enableLineSelection !== true) return
  659. if (dragStart === undefined) return
  660. const selection = window.getSelection()
  661. if (!selection || selection.isCollapsed) return
  662. scheduleSelectionUpdate()
  663. }
  664. createEffect(() => {
  665. const current = file()
  666. onCleanup(() => {
  667. current.cleanUp()
  668. })
  669. })
  670. createEffect(() => {
  671. observer?.disconnect()
  672. observer = undefined
  673. container.innerHTML = ""
  674. file().render({
  675. file: local.file,
  676. lineAnnotations: local.annotations,
  677. containerWrapper: container,
  678. })
  679. applyScheme()
  680. setRendered((value) => value + 1)
  681. notifyRendered()
  682. })
  683. createEffect(() => {
  684. if (typeof document === "undefined") return
  685. if (typeof MutationObserver === "undefined") return
  686. const root = document.documentElement
  687. const monitor = new MutationObserver(() => applyScheme())
  688. monitor.observe(root, { attributes: true, attributeFilter: ["data-color-scheme"] })
  689. applyScheme()
  690. onCleanup(() => monitor.disconnect())
  691. })
  692. createEffect(() => {
  693. rendered()
  694. const ranges = local.commentedLines ?? []
  695. requestAnimationFrame(() => applyCommentedLines(ranges))
  696. })
  697. createEffect(() => {
  698. setSelectedLines(local.selectedLines ?? null)
  699. })
  700. createEffect(() => {
  701. if (props.enableLineSelection !== true) return
  702. container.addEventListener("mousedown", handleMouseDown)
  703. container.addEventListener("mousemove", handleMouseMove)
  704. window.addEventListener("mouseup", handleMouseUp)
  705. document.addEventListener("selectionchange", handleSelectionChange)
  706. onCleanup(() => {
  707. container.removeEventListener("mousedown", handleMouseDown)
  708. container.removeEventListener("mousemove", handleMouseMove)
  709. window.removeEventListener("mouseup", handleMouseUp)
  710. document.removeEventListener("selectionchange", handleSelectionChange)
  711. })
  712. })
  713. onCleanup(() => {
  714. observer?.disconnect()
  715. clearOverlayScroll()
  716. clearOverlay()
  717. if (findCurrent === host) {
  718. findCurrent = undefined
  719. clearHighlightFind()
  720. }
  721. if (selectionFrame !== undefined) {
  722. cancelAnimationFrame(selectionFrame)
  723. selectionFrame = undefined
  724. }
  725. if (dragFrame !== undefined) {
  726. cancelAnimationFrame(dragFrame)
  727. dragFrame = undefined
  728. }
  729. dragStart = undefined
  730. dragEnd = undefined
  731. dragMoved = false
  732. lastSelection = null
  733. pendingSelectionEnd = false
  734. })
  735. const FindBar = (barProps: { class: string; style?: ComponentProps<"div">["style"] }) => (
  736. <div class={barProps.class} style={barProps.style} onPointerDown={(e) => e.stopPropagation()}>
  737. <Icon name="magnifying-glass" size="small" class="text-text-weak shrink-0" />
  738. <input
  739. ref={findInput}
  740. placeholder="Find"
  741. value={findQuery()}
  742. class="w-40 bg-transparent outline-none text-14-regular text-text-strong placeholder:text-text-weak"
  743. onInput={(e) => {
  744. setFindQuery(e.currentTarget.value)
  745. setFindIndex(0)
  746. applyFind({ reset: true, scroll: true })
  747. }}
  748. onKeyDown={(e) => {
  749. if (e.key === "Escape") {
  750. e.preventDefault()
  751. closeFind()
  752. return
  753. }
  754. if (e.key !== "Enter") return
  755. e.preventDefault()
  756. stepFind(e.shiftKey ? -1 : 1)
  757. }}
  758. />
  759. <div class="shrink-0 text-12-regular text-text-weak tabular-nums text-right" style={{ width: "10ch" }}>
  760. {findCount() ? `${findIndex() + 1}/${findCount()}` : "0/0"}
  761. </div>
  762. <div class="flex items-center">
  763. <button
  764. type="button"
  765. class="size-6 grid place-items-center rounded text-text-weak hover:bg-surface-base-hover hover:text-text-strong disabled:opacity-40 disabled:pointer-events-none"
  766. disabled={findCount() === 0}
  767. aria-label="Previous match"
  768. onClick={() => stepFind(-1)}
  769. >
  770. <Icon name="chevron-down" size="small" class="rotate-180" />
  771. </button>
  772. <button
  773. type="button"
  774. class="size-6 grid place-items-center rounded text-text-weak hover:bg-surface-base-hover hover:text-text-strong disabled:opacity-40 disabled:pointer-events-none"
  775. disabled={findCount() === 0}
  776. aria-label="Next match"
  777. onClick={() => stepFind(1)}
  778. >
  779. <Icon name="chevron-down" size="small" />
  780. </button>
  781. </div>
  782. <button
  783. type="button"
  784. class="size-6 grid place-items-center rounded text-text-weak hover:bg-surface-base-hover hover:text-text-strong"
  785. aria-label="Close search"
  786. onClick={closeFind}
  787. >
  788. <Icon name="close-small" size="small" />
  789. </button>
  790. </div>
  791. )
  792. return (
  793. <div
  794. data-component="code"
  795. style={styleVariables}
  796. class="relative outline-none"
  797. classList={{
  798. ...(local.classList || {}),
  799. [local.class ?? ""]: !!local.class,
  800. }}
  801. ref={wrapper}
  802. tabIndex={0}
  803. onPointerDown={() => {
  804. findTarget = host
  805. wrapper.focus({ preventScroll: true })
  806. }}
  807. onFocus={() => {
  808. findTarget = host
  809. }}
  810. >
  811. <Show when={findOpen()}>
  812. <Portal>
  813. <FindBar
  814. class="fixed z-50 flex h-8 items-center gap-2 rounded-md border border-border-base bg-background-base px-3 shadow-md"
  815. style={{
  816. top: `${findPos().top}px`,
  817. right: `${findPos().right}px`,
  818. }}
  819. />
  820. </Portal>
  821. </Show>
  822. <div ref={container} />
  823. <div ref={findOverlay} class="pointer-events-none absolute inset-0 z-0" />
  824. </div>
  825. )
  826. }