File size: 6,576 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 | import { useCallback, useRef, useState } from 'react';
import { BookNote } from '@/types/book';
import { Point, TextSelection, snapRangeToWords } from '@/utils/sel';
import { useEnv } from '@/context/EnvContext';
import { useReaderStore } from '@/store/readerStore';
import { useSettingsStore } from '@/store/settingsStore';
import { useBookDataStore } from '@/store/bookDataStore';
interface HandlePositions {
start: Point;
end: Point;
}
interface UseAnnotationEditorProps {
bookKey: string;
annotation: BookNote;
getAnnotationText: (range: Range) => Promise<string>;
setSelection: React.Dispatch<React.SetStateAction<TextSelection | null>>;
}
export const useAnnotationEditor = ({
bookKey,
annotation,
getAnnotationText,
setSelection,
}: UseAnnotationEditorProps) => {
const { envConfig } = useEnv();
const { settings } = useSettingsStore();
const { getConfig, saveConfig, updateBooknotes } = useBookDataStore();
const { getView, getViewsById } = useReaderStore();
const view = getView(bookKey);
const editingAnnotationRef = useRef(annotation);
const [handlePositions, setHandlePositions] = useState<HandlePositions | null>(null);
const getHandlePositionsFromRange = useCallback(
(range: Range, isVertical: boolean): HandlePositions | null => {
const gridFrame = document.querySelector(`#gridcell-${bookKey}`);
if (!gridFrame) return null;
const rects = Array.from(range.getClientRects());
if (rects.length === 0) return null;
const firstRect = rects[0]!;
const lastRect = rects[rects.length - 1]!;
const frameElement = range.commonAncestorContainer.ownerDocument?.defaultView?.frameElement;
const frameRect = frameElement?.getBoundingClientRect() ?? { top: 0, left: 0 };
return {
start: {
x: frameRect.left + (isVertical ? firstRect.right : firstRect.left),
y: frameRect.top + firstRect.top,
},
end: {
x: frameRect.left + (isVertical ? lastRect.left : lastRect.right),
y: frameRect.top + lastRect.bottom,
},
};
},
[bookKey],
);
const handleAnnotationRangeChange = useCallback(
async (startPoint: Point, endPoint: Point, isVertical: boolean, isDragging: boolean) => {
if (!editingAnnotationRef.current || !view) return;
const contents = view.renderer.getContents();
if (!contents || contents.length === 0) return;
// the point is from viewport, need to adjust to each content's coordinate
const findPositionAtPoint = (doc: Document, x: number, y: number) => {
const frameElement = doc.defaultView?.frameElement;
const frameRect = frameElement?.getBoundingClientRect() ?? { top: 0, left: 0 };
const adjustedX = x - frameRect.left;
const adjustedY = y - frameRect.top;
if (doc.caretPositionFromPoint) {
const pos = doc.caretPositionFromPoint(adjustedX, adjustedY);
if (pos) return { node: pos.offsetNode, offset: pos.offset };
}
if (doc.caretRangeFromPoint) {
const range = doc.caretRangeFromPoint(adjustedX, adjustedY);
if (range) return { node: range.startContainer, offset: range.startOffset };
}
return null;
};
let startPos = null;
let endPos = null;
let targetDoc: Document | null = null;
let targetIndex = 0;
for (const content of contents) {
const { doc, index } = content;
if (!doc) continue;
const sp = findPositionAtPoint(doc, startPoint.x, startPoint.y);
const ep = findPositionAtPoint(doc, endPoint.x, endPoint.y);
if (sp && ep) {
startPos = sp;
endPos = ep;
targetDoc = doc;
targetIndex = index ?? 0;
break;
}
}
if (!startPos || !endPos || !targetDoc) return;
const newRange = targetDoc.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) {
console.warn('Range is collapsed');
return;
}
snapRangeToWords(newRange);
} catch (e) {
console.warn('Failed to create range:', e);
return;
}
const newPositions = getHandlePositionsFromRange(newRange, isVertical);
if (newPositions) {
setHandlePositions(newPositions);
}
const newCfi = view.getCFI(targetIndex, newRange);
const newText = await getAnnotationText(newRange);
if (newCfi && newText) {
const config = getConfig(bookKey)!;
const { booknotes: annotations = [] } = config;
const existingIndex = annotations.findIndex(
(a) => a.id === editingAnnotationRef.current.id && !a.deletedAt,
);
if (existingIndex !== -1) {
const updatedAnnotation: BookNote = {
...annotations[existingIndex]!,
cfi: newCfi,
text: newText,
updatedAt: Date.now(),
};
const views = getViewsById(bookKey.split('-')[0]!);
views.forEach((v) => v?.addAnnotation(editingAnnotationRef.current, true));
views.forEach((v) => v?.addAnnotation(updatedAnnotation));
editingAnnotationRef.current = updatedAnnotation;
if (!isDragging) {
annotations[existingIndex] = updatedAnnotation;
const updatedConfig = updateBooknotes(bookKey, annotations);
if (updatedConfig) {
saveConfig(envConfig, bookKey, updatedConfig, settings);
}
setSelection({
key: bookKey,
annotated: true,
text: newText,
cfi: newCfi,
range: newRange,
index: targetIndex,
});
}
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[bookKey, getHandlePositionsFromRange, getAnnotationText, setSelection],
);
return {
handlePositions,
setHandlePositions,
getHandlePositionsFromRange,
handleAnnotationRangeChange,
};
};
|