#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
feat(annotate): add Arrow and Polyline tools (#8578)
Reece Browne909e2657ef52
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 44dc109471..be5f3251af 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -1993,6 +1993,7 @@ insertText = "Insert Text"line = "Line"lineArrow = "Arrow"moreActions = "More actions"+multiClickShapeHint = "Double-click or press Enter to finish"noBackground = "No background"note = "Note"notesStamps = "Notes & Stamps"diff --git a/frontend/src/editor/core/components/annotation/shared/MultiClickShapeHint.tsx b/frontend/src/editor/core/components/annotation/shared/MultiClickShapeHint.tsxnew file mode 100644index 0000000000..d185f11fe0--- /dev/null+++ b/frontend/src/editor/core/components/annotation/shared/MultiClickShapeHint.tsx@@ -0,0 +1,129 @@+import { useEffect, useRef, useState, type RefObject } from "react";+import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";+import type { AnnotationAPI } from "@editor/components/viewer/viewerTypes";+import { PAGE_POINTER_LAYER_CLASS } from "@editor/components/viewer/ViewerPointerProviders";++interface HintAnchor {+ layer: HTMLElement;+ /** Fractions of the page layer, so the hint stays on the point across zoom. */+ x: number;+ y: number;+}++interface MultiClickShapeHintProps {+ /** True while a polyline or polygon tool is active. */+ active: boolean;+ annotationApiRef: RefObject<AnnotationAPI | null>;+}++/**+ * Tooltip beside the first point of a polyline or polygon in progress, telling+ * the user how to finish it. Hidden once the shape is created or the tool changes.+ */+export function MultiClickShapeHint({+ active,+ annotationApiRef,+}: MultiClickShapeHintProps) {+ const { t } = useTranslation();+ const [anchor, setAnchor] = useState<HintAnchor | null>(null);++ useEffect(() => {+ if (!active) {+ setAnchor(null);+ return;+ }+ // Capture phase: runs before the page layer's own listener adds the vertex.+ const onClick = (event: MouseEvent) => {+ const layer = (event.target as HTMLElement | null)?.closest<HTMLElement>(+ `.${PAGE_POINTER_LAYER_CLASS}`,+ );+ if (!layer) return;+ setAnchor((current) => {+ if (current) return current;+ const rect = layer.getBoundingClientRect();+ return {+ layer,+ x: (event.clientX - rect.left) / rect.width,+ y: (event.clientY - rect.top) / rect.height,+ };+ });+ };+ document.addEventListener("click", onClick, true);+ const unsubscribe = annotationApiRef.current?.onAnnotationEvent?.(+ (event) => {+ if (event.type === "create") setAnchor(null);+ },+ );+ return () => {+ document.removeEventListener("click", onClick, true);+ if (typeof unsubscribe === "function") unsubscribe();+ };+ }, [active, annotationApiRef]);++ // The hint takes no pointer events so clicks reach the page beneath it, which+ // also means it never sees hover; track the cursor against its box instead.+ const hintRef = useRef<HTMLDivElement>(null);+ const [isUnderCursor, setIsUnderCursor] = useState(false);++ useEffect(() => {+ if (!anchor) {+ setIsUnderCursor(false);+ return;+ }+ const onPointerMove = (event: PointerEvent) => {+ const rect = hintRef.current?.getBoundingClientRect();+ setIsUnderCursor(+ !!rect &&+ event.clientX >= rect.left &&+ event.clientX <= rect.right &&+ event.clientY >= rect.top &&+ event.clientY <= rect.bottom,+ );+ };+ document.addEventListener("pointermove", onPointerMove, {+ capture: true,+ passive: true,+ });+ return () =>+ document.removeEventListener("pointermove", onPointerMove, {+ capture: true,+ });+ }, [anchor]);++ if (!anchor || !anchor.layer.isConnected) return null;++ return createPortal(+ <div+ ref={hintRef}+ // Keeps the interaction manager from treating the hint as part of the page.+ data-no-interaction+ style={{+ opacity: isUnderCursor ? 0.15 : 1,+ transition: "opacity 120ms ease",+ position: "absolute",+ left: `${anchor.x * 100}%`,+ top: `${anchor.y * 100}%`,+ transform: "translate(12px, calc(-100% - 8px))",+ pointerEvents: "none",+ whiteSpace: "nowrap",+ zIndex: 10,+ padding: "4px 8px",+ backgroundColor:+ "color-mix(in srgb, var(--c-primary) 12%, var(--c-surface))",+ color: "var(--c-text)",+ border: "1px solid var(--tooltip-border)",+ borderRadius: "var(--radius-sm)",+ boxShadow: "var(--shadow-md)",+ fontSize: "0.75rem",+ fontWeight: 500,+ }}+ >+ {t(+ "annotation.multiClickShapeHint",+ "Double-click or press Enter to finish",+ )}+ </div>,+ anchor.layer,+ );+}diff --git a/frontend/src/editor/core/components/viewer/AnnotationAPIBridge.tsx b/frontend/src/editor/core/components/viewer/AnnotationAPIBridge.tsxindex 0a0076553d..88a083ab67 100644--- a/frontend/src/editor/core/components/viewer/AnnotationAPIBridge.tsx+++ b/frontend/src/editor/core/components/viewer/AnnotationAPIBridge.tsx@@ -323,8 +323,11 @@ const TOOL_DEFAULT_BUILDERS: Record<AnnotationToolId, ToolDefaultsBuilder> = {polyline: (options) => ({type: PdfAnnotationSubtype.POLYLINE,color: options?.color ?? "#1565c0",+ strokeColor: options?.color ?? "#1565c0",opacity: options?.opacity ?? 1,borderWidth: options?.borderWidth ?? 2,+ strokeWidth: options?.borderWidth ?? 2,+ lineWidth: options?.borderWidth ?? 2,...withCustomData(options),}),polygon: (options) => ({diff --git a/frontend/src/editor/core/components/viewer/CommentsSidebar.tsx b/frontend/src/editor/core/components/viewer/CommentsSidebar.tsxindex 84e92758b2..fbd1c79415 100644--- a/frontend/src/editor/core/components/viewer/CommentsSidebar.tsx+++ b/frontend/src/editor/core/components/viewer/CommentsSidebar.tsx@@ -143,8 +143,8 @@ const TOOL_ICON_MAP: Record<string, IconName> = {inkHighlighter: "brush",square: "square",circle: "circle",- line: "polyline",- lineArrow: "polyline",+ line: "slash",+ lineArrow: "move-up-right",polyline: "polyline",polygon: "triangle",text: "type",@@ -159,7 +159,8 @@ const TOOL_ICON_MAP: Record<string, IconName> = {function getIconByType(type: number | undefined): IconName {if (type === 1) return "message-square";if (type === 3) return "sticky-note";- if (type === 4 || type === 8) return "polyline";+ if (type === 4) return "slash";+ if (type === 8) return "polyline";if (type === 5) return "square";if (type === 6) return "circle";if (type === 7 || type === 8) return "triangle";diff --git a/frontend/src/editor/core/components/viewer/ViewerPointerProviders.tsx b/frontend/src/editor/core/components/viewer/ViewerPointerProviders.tsxindex e065d9f433..a6e9452aa0 100644--- a/frontend/src/editor/core/components/viewer/ViewerPointerProviders.tsx+++ b/frontend/src/editor/core/components/viewer/ViewerPointerProviders.tsx@@ -10,6 +10,24 @@ import {// lets a one-finger drag scroll the document. Pinned by viewerPanConfig.test.ts.export const POINTER_MODE = "pointerMode";+/** Class on every page's pointer layer; the touch-action rule in core/styles/theme.css selects on it too. */+export const PAGE_POINTER_LAYER_CLASS = "pdf-page-pointer-layer";++/**+ * Commits an in-progress polyline or polygon. EmbedPDF finishes those shapes+ * only on a double-click, which it reads off the page pointer layer; pages with+ * no shape in progress ignore the event.+ */+export function finishPendingPageShape(): void {+ document+ .querySelectorAll(`.${PAGE_POINTER_LAYER_CLASS}`)+ .forEach((layer) =>+ layer.dispatchEvent(+ new MouseEvent("dblclick", { bubbles: true, cancelable: true }),+ ),+ );+}+function useActiveInteractionMode(documentId: string): string | null {const { provides: interactionManager } = useInteractionManagerCapability();const [mode, setMode] = useState<string | null>(null);@@ -58,7 +76,7 @@ export function ViewerPagePointerProvider({documentId={documentId}pageIndex={pageIndex}// Consumed by the touch-action rule in core/styles/theme.css.- className="pdf-page-pointer-layer"+ className={PAGE_POINTER_LAYER_CLASS}>{children}</PagePointerProvider>diff --git a/frontend/src/editor/core/components/viewer/annotationTools.ts b/frontend/src/editor/core/components/viewer/annotationTools.tsindex c19628ad10..646a9e4e84 100644--- a/frontend/src/editor/core/components/viewer/annotationTools.ts+++ b/frontend/src/editor/core/components/viewer/annotationTools.ts@@ -4,6 +4,7 @@ import type {} from "@embedpdf/plugin-annotation";import { PdfAnnotationSubtype } from "@embedpdf/models";import type { PdfAnnotationObject } from "@embedpdf/models";+import { clickToClickLineHandler } from "@editor/components/viewer/clickToClickLineHandler";// LooseAnnotationTool bypasses strict Partial<T> defaults typing from the library:// EmbedPDF accepts extra runtime properties (borderWidth, textColor, finishOnDoubleClick,@@ -419,4 +420,15 @@ export function registerAnnotationTools(borderWidth: 2,},});++ // Line and arrow draw click-then-click as well as by dragging.+ for (const id of ["line", "lineArrow"]) {+ const tool = annotationApi.getTool?.(id);+ if (tool?.pointerHandler) {+ annotationApi.addTool({+ ...tool,+ pointerHandler: clickToClickLineHandler(tool.pointerHandler),+ });+ }+ }}diff --git a/frontend/src/editor/core/components/viewer/clickToClickLineHandler.ts b/frontend/src/editor/core/components/viewer/clickToClickLineHandler.tsnew file mode 100644index 0000000000..285a217ce4--- /dev/null+++ b/frontend/src/editor/core/components/viewer/clickToClickLineHandler.ts@@ -0,0 +1,67 @@+import type { HandlerFactory } from "@embedpdf/plugin-annotation";+import type { PdfAnnotationObject, Position } from "@embedpdf/models";++// EmbedPDF's line handler treats a release within this many page units of the+// press as a click rather than a drag.+const CLICK_DISTANCE = 5;++const wrapped = new WeakSet<object>();++const distance = (a: Position, b: Position) => Math.hypot(a.x - b.x, a.y - b.y);++/**+ * Lets a line be drawn click-then-click on top of EmbedPDF's press-drag-release+ * line handler. The first click's release is withheld, so the line stays in+ * progress with its preview following the cursor, and the next click away from+ * the start commits it. A drag still draws the line in one gesture.+ */+export function clickToClickLineHandler<+ A extends PdfAnnotationObject,+ TId extends string,+>(base: HandlerFactory<A, TId>): HandlerFactory<A, TId> {+ if (wrapped.has(base)) return base;+ const factory: HandlerFactory<A, TId> = {+ annotationType: base.annotationType,+ create(context) {+ const inner = base.create(context);+ let start: Position | null = null;+ let awaitingEnd = false;+ const reset = () => {+ start = null;+ awaitingEnd = false;+ };+ return {+ ...inner,+ onPointerDown(pos, evt, modeId) {+ // The second click's press would restart the line; only its release matters.+ if (awaitingEnd) return;+ start = pos;+ inner.onPointerDown?.(pos, evt, modeId);+ },+ onPointerUp(pos, evt, modeId) {+ if (!start) return;+ if (distance(pos, start) < CLICK_DISTANCE) {+ awaitingEnd = true;+ return;+ }+ reset();+ inner.onPointerUp?.(pos, evt, modeId);+ },+ onPointerCancel(pos, evt, modeId) {+ reset();+ inner.onPointerCancel?.(pos, evt, modeId);+ },+ onHandlerActiveStart(modeId) {+ reset();+ inner.onHandlerActiveStart?.(modeId);+ },+ onHandlerActiveEnd(modeId) {+ reset();+ inner.onHandlerActiveEnd?.(modeId);+ },+ };+ },+ };+ wrapped.add(factory);+ return factory;+}diff --git a/frontend/src/editor/core/icons/icons.ts b/frontend/src/editor/core/icons/icons.tsindex 3bc2b64296..eb9dc07979 100644--- a/frontend/src/editor/core/icons/icons.ts+++ b/frontend/src/editor/core/icons/icons.ts@@ -204,6 +204,7 @@ import MonitorCloud from "lucide-static/icons/monitor-cloud.svg?react";import MonitorSmartphone from "lucide-static/icons/monitor-smartphone.svg?react";import Moon from "lucide-static/icons/moon.svg?react";import Move from "lucide-static/icons/move.svg?react";+import MoveUpRight from "lucide-static/icons/move-up-right.svg?react";import Music from "lucide-static/icons/music.svg?react";import Network from "lucide-static/icons/network.svg?react";import Newspaper from "lucide-static/icons/newspaper.svg?react";@@ -277,6 +278,7 @@ import Shrink from "lucide-static/icons/shrink.svg?react";import Sigma from "lucide-static/icons/sigma.svg?react";import Signature from "lucide-static/icons/signature.svg?react";import Siren from "lucide-static/icons/siren.svg?react";+import Slash from "lucide-static/icons/slash.svg?react";import SlidersHorizontal from "lucide-static/icons/sliders-horizontal.svg?react";import Sparkle from "lucide-static/icons/sparkle.svg?react";import Sparkles from "lucide-static/icons/sparkles.svg?react";@@ -635,6 +637,7 @@ export const ICONS = {"monitor-smartphone": { Component: MonitorSmartphone, kind: "lucide" },moon: { Component: Moon, kind: "lucide" },move: { Component: Move, kind: "lucide" },+ "move-up-right": { Component: MoveUpRight, kind: "lucide" },music: { Component: Music, kind: "lucide" },network: { Component: Network, kind: "lucide" },newspaper: { Component: Newspaper, kind: "lucide" },@@ -708,6 +711,7 @@ export const ICONS = {sigma: { Component: Sigma, kind: "lucide" },signature: { Component: Signature, kind: "lucide" },siren: { Component: Siren, kind: "lucide" },+ slash: { Component: Slash, kind: "lucide" },"sliders-horizontal": { Component: SlidersHorizontal, kind: "lucide" },sparkle: { Component: Sparkle, kind: "lucide" },sparkles: { Component: Sparkles, kind: "lucide" },diff --git a/frontend/src/editor/core/tools/annotate/AnnotationPanel.tsx b/frontend/src/editor/core/tools/annotate/AnnotationPanel.tsxindex f3c3087caf..3f1897cb32 100644--- a/frontend/src/editor/core/tools/annotate/AnnotationPanel.tsx+++ b/frontend/src/editor/core/tools/annotate/AnnotationPanel.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import type React from "react";import { useTranslation } from "react-i18next";import {@@ -22,6 +22,8 @@ import {import { ImageUploader } from "@editor/components/annotation/shared/ImageUploader";import { SuggestedToolsSection } from "@editor/components/tools/shared/SuggestedToolsSection";import { DrawingControls } from "@editor/components/annotation/shared/DrawingControls";+import { finishPendingPageShape } from "@editor/components/viewer/ViewerPointerProviders";+import { MultiClickShapeHint } from "@editor/components/annotation/shared/MultiClickShapeHint";import type {AnnotationToolId,AnnotationAPI,@@ -279,7 +281,17 @@ export function AnnotationPanel(props: AnnotationPanelProps) {label: t("annotation.circle", "Circle"),icon: "circle",},- { id: "line", label: t("annotation.line", "Line"), icon: "polyline" },+ { id: "line", label: t("annotation.line", "Line"), icon: "slash" },+ {+ id: "lineArrow",+ label: t("annotation.lineArrow", "Arrow"),+ icon: "move-up-right",+ },+ {+ id: "polyline",+ label: t("annotation.polyline", "Polyline"),+ icon: "polyline",+ },{id: "polygon",label: t("annotation.polygon", "Polygon"),@@ -334,6 +346,27 @@ export function AnnotationPanel(props: AnnotationPanelProps) {const annotationsVisible = viewerContext?.isAnnotationsVisible ?? true;+ const isMultiClickShape =+ annotationsVisible &&+ (activeTool === "polyline" || activeTool === "polygon");++ useEffect(() => {+ if (!isMultiClickShape) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Enter") return;+ const target = event.target as HTMLElement | null;+ if (+ target?.closest("input, textarea, select, [contenteditable='true']")+ ) {+ return;+ }+ event.preventDefault();+ finishPendingPageShape();+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [isMultiClickShape]);+const handleConfirmClearDocumentAnnotations = async () => {if (isClearingDocumentAnnotations || isApplyingChanges) {return;@@ -1253,6 +1286,10 @@ export function AnnotationPanel(props: AnnotationPanelProps) {{t("annotation.shapes", "Shapes")}</Text>{renderToolButtons(shapeTools)}+ <MultiClickShapeHint+ active={isMultiClickShape}+ annotationApiRef={annotationApiRef}+ /></Box><Box>diff --git a/frontend/src/editor/core/tools/annotate/useAnnotationStyleState.ts b/frontend/src/editor/core/tools/annotate/useAnnotationStyleState.tsindex d09937b908..25e0848759 100644--- a/frontend/src/editor/core/tools/annotate/useAnnotationStyleState.ts+++ b/frontend/src/editor/core/tools/annotate/useAnnotationStyleState.ts@@ -71,6 +71,8 @@ export interface AnnotationStyleStateReturn {getActiveColor: (target: string | null) => string;}+const ARROW_LINE_WIDTH = 3;+export const useAnnotationStyleState = (cssToPdfSize?: (size: Size) => Size,): AnnotationStyleStateReturn => {@@ -189,7 +191,10 @@ export const useAnnotationStyleState = (color: shapeStrokeColor,strokeColor: shapeStrokeColor,opacity: shapeStrokeOpacity / 100,- borderWidth: shapeThickness,+ // The arrowhead is drawn at 9x the line width, so the shape+ // thickness makes it oversized.+ borderWidth:+ toolId === "lineArrow" ? ARROW_LINE_WIDTH : shapeThickness,...metadata,};case "stamp": {