WhiteboardPane.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { useCallback, useEffect, useRef, useState, type PointerEventHandler } from "react";
  2. import {
  3. EraserIcon,
  4. ImagePlusIcon,
  5. PaletteIcon,
  6. PencilIcon,
  7. Redo2Icon,
  8. Trash2Icon,
  9. Undo2Icon,
  10. } from "lucide-react";
  11. import { ControlHintTooltip } from "@/ControlHintTooltip.js";
  12. import { Button } from "@/components/ui/button.js";
  13. import { Input } from "@/components/ui/input.js";
  14. import { cn } from "@/components/lib/utils.js";
  15. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  16. import {
  17. WHITEBOARD_DEFAULT_COLOR,
  18. createWhiteboardStroke,
  19. dispatchWhiteboardAddToChat,
  20. drawWhiteboardDocument,
  21. type WhiteboardPoint,
  22. type WhiteboardStroke,
  23. type WhiteboardTool,
  24. } from "@/lib/whiteboard.js";
  25. import { buildWhiteboardWorkspaceKey } from "@/lib/whiteboard.js";
  26. import { useWhiteboardStore } from "@/store/whiteboardStore.js";
  27. const WHITEBOARD_SWATCHES = ["#111827", "#2563eb", "#16a34a", "#dc2626", "#ca8a04", "#7c3aed"];
  28. export function WhiteboardPane({
  29. workspacePath,
  30. workspaceIdentity,
  31. boardId,
  32. }: {
  33. workspacePath: string;
  34. workspaceIdentity?: string;
  35. boardId: string;
  36. }) {
  37. const { intl } = useZCodeIntl();
  38. const workspaceKey = buildWhiteboardWorkspaceKey({ workspacePath, workspaceIdentity });
  39. const board = useWhiteboardStore((state) => state.workspaces[workspaceKey]?.boardsById[boardId]);
  40. const renameBoard = useWhiteboardStore((state) => state.renameBoard);
  41. const addStroke = useWhiteboardStore((state) => state.addStroke);
  42. const undoStroke = useWhiteboardStore((state) => state.undoStroke);
  43. const redoStroke = useWhiteboardStore((state) => state.redoStroke);
  44. const clearBoard = useWhiteboardStore((state) => state.clearBoard);
  45. const canvasRef = useRef<HTMLCanvasElement | null>(null);
  46. const draftStrokeRef = useRef<WhiteboardStroke | null>(null);
  47. const activePointerIdRef = useRef<number | null>(null);
  48. const [tool, setTool] = useState<WhiteboardTool>("pen");
  49. const [color, setColor] = useState(WHITEBOARD_DEFAULT_COLOR);
  50. const [strokeWidth, setStrokeWidth] = useState(5);
  51. const [nameDraft, setNameDraft] = useState("");
  52. const renderCanvas = useCallback(
  53. (draftStroke: WhiteboardStroke | null = draftStrokeRef.current) => {
  54. if (!board) {
  55. return;
  56. }
  57. const canvas = canvasRef.current;
  58. if (!canvas) {
  59. return;
  60. }
  61. const pixelRatio = Math.max(1, window.devicePixelRatio || 1);
  62. const targetWidth = Math.round(board.width * pixelRatio);
  63. const targetHeight = Math.round(board.height * pixelRatio);
  64. if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
  65. canvas.width = targetWidth;
  66. canvas.height = targetHeight;
  67. }
  68. const context = canvas.getContext("2d");
  69. if (!context) {
  70. return;
  71. }
  72. drawWhiteboardDocument(context, board, {
  73. draftStroke,
  74. scale: pixelRatio,
  75. });
  76. },
  77. [board],
  78. );
  79. useEffect(() => {
  80. draftStrokeRef.current = null;
  81. renderCanvas(null);
  82. }, [board, renderCanvas]);
  83. useEffect(() => {
  84. setNameDraft(board?.name ?? "");
  85. }, [board?.id, board?.name]);
  86. const getCanvasPoint = useCallback(
  87. (event: React.PointerEvent<HTMLCanvasElement>): WhiteboardPoint | null => {
  88. if (!board) {
  89. return null;
  90. }
  91. const rect = event.currentTarget.getBoundingClientRect();
  92. if (rect.width <= 0 || rect.height <= 0) {
  93. return null;
  94. }
  95. return {
  96. x: Math.min(
  97. board.width,
  98. Math.max(0, ((event.clientX - rect.left) / rect.width) * board.width),
  99. ),
  100. y: Math.min(
  101. board.height,
  102. Math.max(0, ((event.clientY - rect.top) / rect.height) * board.height),
  103. ),
  104. };
  105. },
  106. [board],
  107. );
  108. const handlePointerDown: PointerEventHandler<HTMLCanvasElement> = useCallback(
  109. (event) => {
  110. if (!board || event.button !== 0) {
  111. return;
  112. }
  113. const point = getCanvasPoint(event);
  114. if (!point) {
  115. return;
  116. }
  117. event.preventDefault();
  118. event.currentTarget.setPointerCapture(event.pointerId);
  119. activePointerIdRef.current = event.pointerId;
  120. draftStrokeRef.current = createWhiteboardStroke({
  121. color,
  122. points: [point],
  123. tool,
  124. width: tool === "eraser" ? Math.max(14, strokeWidth * 3) : strokeWidth,
  125. });
  126. renderCanvas();
  127. },
  128. [board, color, getCanvasPoint, renderCanvas, strokeWidth, tool],
  129. );
  130. const handlePointerMove: PointerEventHandler<HTMLCanvasElement> = useCallback(
  131. (event) => {
  132. if (!board || activePointerIdRef.current !== event.pointerId || !draftStrokeRef.current) {
  133. return;
  134. }
  135. const point = getCanvasPoint(event);
  136. if (!point) {
  137. return;
  138. }
  139. event.preventDefault();
  140. draftStrokeRef.current = {
  141. ...draftStrokeRef.current,
  142. points: [...draftStrokeRef.current.points, point],
  143. };
  144. renderCanvas();
  145. },
  146. [board, getCanvasPoint, renderCanvas],
  147. );
  148. const finishPointerStroke = useCallback(
  149. (event: React.PointerEvent<HTMLCanvasElement>) => {
  150. if (activePointerIdRef.current !== event.pointerId) {
  151. return;
  152. }
  153. const stroke = draftStrokeRef.current;
  154. activePointerIdRef.current = null;
  155. draftStrokeRef.current = null;
  156. if (event.currentTarget.hasPointerCapture(event.pointerId)) {
  157. event.currentTarget.releasePointerCapture(event.pointerId);
  158. }
  159. if (!stroke || stroke.points.length === 0) {
  160. renderCanvas(null);
  161. return;
  162. }
  163. addStroke({
  164. boardId,
  165. stroke,
  166. workspaceIdentity,
  167. workspacePath,
  168. });
  169. },
  170. [addStroke, boardId, renderCanvas, workspaceIdentity, workspacePath],
  171. );
  172. if (!board) {
  173. return (
  174. <div className="flex h-full items-center justify-center bg-panel px-4 text-ui-base text-foreground-subtle">
  175. {intl.formatMessage({ id: "whiteboard.missing" })}
  176. </div>
  177. );
  178. }
  179. const canUndo = board.strokes.length > 0;
  180. const canRedo = board.undoneStrokes.length > 0;
  181. const addToChatLabel = intl.formatMessage({ id: "whiteboard.addToChat" });
  182. return (
  183. <div className="flex h-full min-h-0 flex-col bg-panel text-foreground">
  184. <div className="flex min-h-10 items-center gap-2 border-b border-border px-2">
  185. <Input
  186. value={nameDraft}
  187. onBlur={() => {
  188. if (!nameDraft.trim()) {
  189. setNameDraft(board.name);
  190. }
  191. }}
  192. onChange={(event) => {
  193. const nextName = event.target.value;
  194. setNameDraft(nextName);
  195. if (!nextName.trim()) {
  196. return;
  197. }
  198. renameBoard({
  199. boardId,
  200. name: nextName,
  201. workspaceIdentity,
  202. workspacePath,
  203. });
  204. }}
  205. aria-label={intl.formatMessage({ id: "whiteboard.nameLabel" })}
  206. className="max-w-48"
  207. />
  208. <div className="ml-auto flex min-w-0 items-center gap-1">
  209. <ControlHintTooltip title={addToChatLabel}>
  210. <Button
  211. type="button"
  212. variant="ghost"
  213. size="icon-md"
  214. aria-label={addToChatLabel}
  215. onClick={() =>
  216. dispatchWhiteboardAddToChat({
  217. boardId,
  218. workspaceIdentity,
  219. workspacePath,
  220. })
  221. }
  222. >
  223. <ImagePlusIcon className="size-4" />
  224. </Button>
  225. </ControlHintTooltip>
  226. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.tool.pen" })}>
  227. <Button
  228. type="button"
  229. variant={tool === "pen" ? "secondary" : "ghost"}
  230. size="icon-md"
  231. aria-pressed={tool === "pen"}
  232. aria-label={intl.formatMessage({ id: "whiteboard.tool.pen" })}
  233. onClick={() => setTool("pen")}
  234. >
  235. <PencilIcon className="size-4" />
  236. </Button>
  237. </ControlHintTooltip>
  238. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.tool.eraser" })}>
  239. <Button
  240. type="button"
  241. variant={tool === "eraser" ? "secondary" : "ghost"}
  242. size="icon-md"
  243. aria-pressed={tool === "eraser"}
  244. aria-label={intl.formatMessage({ id: "whiteboard.tool.eraser" })}
  245. onClick={() => setTool("eraser")}
  246. >
  247. <EraserIcon className="size-4" />
  248. </Button>
  249. </ControlHintTooltip>
  250. <div className="hidden items-center gap-1 sm:flex">
  251. {WHITEBOARD_SWATCHES.map((swatch) => (
  252. <ControlHintTooltip
  253. key={swatch}
  254. title={intl.formatMessage({ id: "whiteboard.color" })}
  255. >
  256. <button
  257. type="button"
  258. aria-label={intl.formatMessage({ id: "whiteboard.color" })}
  259. aria-pressed={color === swatch}
  260. onClick={() => setColor(swatch)}
  261. className={cn(
  262. "size-5 rounded-full border border-border transition-shadow",
  263. color === swatch && "ring-2 ring-brand ring-offset-1 ring-offset-panel",
  264. )}
  265. style={{ backgroundColor: swatch }}
  266. />
  267. </ControlHintTooltip>
  268. ))}
  269. </div>
  270. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.strokeWidth" })}>
  271. <input
  272. type="range"
  273. min="2"
  274. max="18"
  275. value={strokeWidth}
  276. aria-label={intl.formatMessage({ id: "whiteboard.strokeWidth" })}
  277. onChange={(event) => setStrokeWidth(Number(event.target.value))}
  278. className="hidden h-7 w-20 accent-primary md:block"
  279. />
  280. </ControlHintTooltip>
  281. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.undo" })}>
  282. <Button
  283. type="button"
  284. variant="ghost"
  285. size="icon-md"
  286. disabled={!canUndo}
  287. aria-label={intl.formatMessage({ id: "whiteboard.undo" })}
  288. onClick={() => undoStroke({ boardId, workspaceIdentity, workspacePath })}
  289. >
  290. <Undo2Icon className="size-4" />
  291. </Button>
  292. </ControlHintTooltip>
  293. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.redo" })}>
  294. <Button
  295. type="button"
  296. variant="ghost"
  297. size="icon-md"
  298. disabled={!canRedo}
  299. aria-label={intl.formatMessage({ id: "whiteboard.redo" })}
  300. onClick={() => redoStroke({ boardId, workspaceIdentity, workspacePath })}
  301. >
  302. <Redo2Icon className="size-4" />
  303. </Button>
  304. </ControlHintTooltip>
  305. <ControlHintTooltip title={intl.formatMessage({ id: "whiteboard.clear" })}>
  306. <Button
  307. type="button"
  308. variant="ghost"
  309. size="icon-md"
  310. disabled={!canUndo}
  311. aria-label={intl.formatMessage({ id: "whiteboard.clear" })}
  312. onClick={() => clearBoard({ boardId, workspaceIdentity, workspacePath })}
  313. >
  314. <Trash2Icon className="size-4" />
  315. </Button>
  316. </ControlHintTooltip>
  317. </div>
  318. </div>
  319. <div className="flex min-h-0 flex-1 items-center justify-center bg-background-alt p-3">
  320. <div className="relative aspect-[16/10] max-h-full w-full overflow-hidden rounded-lg border border-border bg-white shadow-sm">
  321. <canvas
  322. ref={canvasRef}
  323. className="h-full w-full touch-none"
  324. aria-label={intl.formatMessage({ id: "whiteboard.canvasLabel" })}
  325. onPointerDown={handlePointerDown}
  326. onPointerMove={handlePointerMove}
  327. onPointerUp={finishPointerStroke}
  328. onPointerCancel={finishPointerStroke}
  329. onLostPointerCapture={finishPointerStroke}
  330. />
  331. <div className="pointer-events-none absolute left-2 top-2 flex size-6 items-center justify-center rounded-full border border-border bg-surface/90 text-foreground-subtle shadow-sm sm:hidden">
  332. <PaletteIcon className="size-3.5" />
  333. </div>
  334. </div>
  335. </div>
  336. </div>
  337. );
  338. }