File size: 10,256 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | import { useCallback, useRef } from 'react';
import { BookNote } from '@/types/book';
import { Point, TextSelection, snapRangeToWords } from '@/utils/sel';
import { useEnv } from '@/context/EnvContext';
import { useSettingsStore } from '@/store/settingsStore';
import { useBookDataStore } from '@/store/bookDataStore';
import { useReaderStore } from '@/store/readerStore';
import { uniqueId } from '@/utils/misc';
interface UseInstantAnnotationProps {
bookKey: string;
getAnnotationText: (range: Range) => Promise<string>;
setSelection: React.Dispatch<React.SetStateAction<TextSelection | null>>;
}
export const useInstantAnnotation = ({ bookKey, getAnnotationText }: UseInstantAnnotationProps) => {
const { envConfig } = useEnv();
const { settings } = useSettingsStore();
const { getConfig, saveConfig, updateBooknotes } = useBookDataStore();
const { getView, getViewsById, getViewSettings } = useReaderStore();
const startPointRef = useRef<Point | null>(null);
const startDocRef = useRef<Document | null>(null);
const startIndexRef = useRef<number>(0);
const previewAnnotationRef = useRef<BookNote | null>(null);
const annotationIdRef = useRef<string>(uniqueId());
const isInstantAnnotationEnabled = useCallback(() => {
const viewSettings = getViewSettings(bookKey);
return (
viewSettings?.enableAnnotationQuickActions &&
viewSettings?.annotationQuickAction === 'highlight'
);
}, [bookKey, getViewSettings]);
const clearPreviewAnnotation = useCallback(() => {
if (previewAnnotationRef.current) {
const views = getViewsById(bookKey.split('-')[0]!);
views.forEach((v) => v?.addAnnotation(previewAnnotationRef.current!, true));
previewAnnotationRef.current = null;
}
}, [bookKey, getViewsById]);
const findPositionAtPoint = useCallback((doc: Document, x: number, y: number) => {
if (doc.caretPositionFromPoint) {
const pos = doc.caretPositionFromPoint(x, y);
if (pos) return { node: pos.offsetNode, offset: pos.offset };
}
if (doc.caretRangeFromPoint) {
const range = doc.caretRangeFromPoint(x, y);
if (range) return { node: range.startContainer, offset: range.startOffset };
}
return null;
}, []);
const isSelectableContent = useCallback(
(doc: Document, x: number, y: number): boolean => {
const pos = findPositionAtPoint(doc, x, y);
if (!pos) return false;
// Must be a text node
if (pos.node.nodeType !== Node.TEXT_NODE) return false;
const textNode = pos.node as Text;
const textLength = textNode.length;
if (textLength === 0) return false;
// Create a range around the caret position to get the character bounds
const range = doc.createRange();
try {
// Get bounds of character at or after the caret position
const startOffset = Math.min(pos.offset, textLength - 1);
const endOffset = Math.min(pos.offset + 1, textLength);
range.setStart(textNode, startOffset);
range.setEnd(textNode, endOffset);
const rects = range.getClientRects();
for (const rect of rects) {
const tolerance = 20;
if (
x >= rect.left - tolerance &&
x <= rect.right + tolerance &&
y >= rect.top - tolerance &&
y <= rect.bottom + tolerance
) {
return true;
}
}
} catch {
return false;
}
return false;
},
[findPositionAtPoint],
);
const createRangeFromPoints = useCallback(
(doc: Document, startPoint: Point, endPoint: Point) => {
const startPos = findPositionAtPoint(doc, startPoint.x, startPoint.y);
const endPos = findPositionAtPoint(doc, endPoint.x, endPoint.y);
if (!startPos || !endPos) return null;
const newRange = doc.createRange();
try {
const positionComparison = startPos.node.compareDocumentPosition(endPos.node);
const needsSwap =
positionComparison & Node.DOCUMENT_POSITION_PRECEDING ||
(startPos.node === endPos.node && startPos.offset > endPos.offset);
if (needsSwap) {
newRange.setStart(endPos.node, endPos.offset);
newRange.setEnd(startPos.node, startPos.offset);
} else {
newRange.setStart(startPos.node, startPos.offset);
newRange.setEnd(endPos.node, endPos.offset);
}
if (newRange.collapsed) {
return null;
}
snapRangeToWords(newRange);
return newRange;
} catch (e) {
console.warn('Failed to create range:', e);
return null;
}
},
[findPositionAtPoint],
);
const createAnnotation = useCallback((cfi: string, text?: string) => {
const style = settings.globalReadSettings.highlightStyle;
const color = settings.globalReadSettings.highlightStyles[style];
const annotation: BookNote = {
id: annotationIdRef.current,
type: 'annotation',
cfi,
style,
color,
text: text ?? '',
note: '',
createdAt: Date.now(),
updatedAt: Date.now(),
};
return annotation;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleInstantAnnotationPointerDown = useCallback(
(doc: Document, index: number, ev: PointerEvent) => {
if (!isInstantAnnotationEnabled()) return false;
// Only handle primary button (left click / touch / stylus)
if (ev.button !== 0) return false;
if (!isSelectableContent(doc, ev.clientX, ev.clientY)) return false;
startPointRef.current = { x: ev.clientX, y: ev.clientY };
startDocRef.current = doc;
startIndexRef.current = index;
previewAnnotationRef.current = null;
annotationIdRef.current = uniqueId();
return true;
},
[isInstantAnnotationEnabled, isSelectableContent],
);
const handleInstantAnnotationPointerMove = useCallback(
(doc: Document, index: number, ev: PointerEvent) => {
if (!isInstantAnnotationEnabled()) return false;
const view = getView(bookKey);
if (!startPointRef.current || !startDocRef.current || !view) {
return false;
}
const endPoint: Point = { x: ev.clientX, y: ev.clientY };
const startPoint = startPointRef.current;
const deltaX = Math.abs(endPoint.x - startPoint.x);
const deltaY = Math.abs(endPoint.y - startPoint.y);
const distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
// need a longer horizontal or vertical drag to avoid accidental selections
if (distance < 20 || (deltaX / deltaY < 5 && deltaY / deltaX < 5 && distance < 30)) {
return false;
}
const newRange = createRangeFromPoints(doc, startPoint, endPoint);
if (!newRange) return false;
const cfi = view.getCFI(index, newRange);
if (!cfi) return false;
clearPreviewAnnotation();
const annotation = createAnnotation(cfi);
const views = getViewsById(bookKey.split('-')[0]!);
views.forEach((v) => v?.addAnnotation(annotation));
previewAnnotationRef.current = annotation;
return true;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isInstantAnnotationEnabled, createRangeFromPoints],
);
const handleInstantAnnotationPointerCancel = useCallback(() => {
if (!isInstantAnnotationEnabled()) return false;
startPointRef.current = null;
startDocRef.current = null;
clearPreviewAnnotation();
return true;
}, [isInstantAnnotationEnabled, clearPreviewAnnotation]);
const handleInstantAnnotationPointerUp = useCallback(
async (doc: Document, index: number, ev: PointerEvent) => {
if (!isInstantAnnotationEnabled()) return false;
const view = getView(bookKey);
if (!startPointRef.current || !view) {
startPointRef.current = null;
startDocRef.current = null;
clearPreviewAnnotation();
return false;
}
const endPoint: Point = { x: ev.clientX, y: ev.clientY };
const startPoint = startPointRef.current;
startPointRef.current = null;
startDocRef.current = null;
const distance = Math.sqrt(
Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2),
);
if (distance < 10) {
clearPreviewAnnotation();
return false;
}
const newRange = createRangeFromPoints(doc, startPoint, endPoint);
if (!newRange) {
clearPreviewAnnotation();
return false;
}
const text = await getAnnotationText(newRange);
const cfi = view.getCFI(index, newRange);
if (!text || !cfi || text.trim().length === 0) {
clearPreviewAnnotation();
return false;
}
clearPreviewAnnotation();
const annotation = createAnnotation(cfi, text);
const views = getViewsById(bookKey.split('-')[0]!);
views.forEach((v) => v?.addAnnotation(annotation));
const config = getConfig(bookKey)!;
const { booknotes: annotations = [] } = config;
const existingIndex = annotations.findIndex(
(a) => a.cfi === cfi && a.type === 'annotation' && a.style && !a.deletedAt,
);
if (existingIndex !== -1) {
annotations[existingIndex] = {
...annotations[existingIndex]!,
...annotation,
id: annotations[existingIndex]!.id,
};
} else {
annotations.push(annotation);
}
const updatedConfig = updateBooknotes(bookKey, annotations);
if (updatedConfig) {
saveConfig(envConfig, bookKey, updatedConfig, settings);
}
return true;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isInstantAnnotationEnabled, createRangeFromPoints, getAnnotationText, clearPreviewAnnotation],
);
const cancelInstantAnnotation = useCallback(() => {
startPointRef.current = null;
startDocRef.current = null;
clearPreviewAnnotation();
}, [clearPreviewAnnotation]);
return {
isInstantAnnotationEnabled,
handleInstantAnnotationPointerDown,
handleInstantAnnotationPointerMove,
handleInstantAnnotationPointerCancel,
handleInstantAnnotationPointerUp,
cancelInstantAnnotation,
};
};
|