-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathTextBoxes.svelte
More file actions
697 lines (616 loc) · 22.7 KB
/
Copy pathTextBoxes.svelte
File metadata and controls
697 lines (616 loc) · 22.7 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<script lang="ts">
import { clamp, promptConfirmation } from '$lib/util';
import type { Page } from '$lib/types';
import { settings, volumes } from '$lib/settings';
import {
showCropper,
openCreateModal,
openUpdateModal,
expandTextBoxBounds,
sendQuickCapture,
getLastCardInfo,
getCardAgeInMin,
extractFieldValues,
getModelConfig,
blobToBase64,
type VolumeMetadata
} from '$lib/anki-connect';
import { db } from '$lib/catalog/db';
import { layoutLines, getDefaultMeasurer, type LineLayout } from '$lib/reader/line-coords-layout';
import { dedupeBlocks } from '$lib/reader/block-dedupe';
interface ContextMenuData {
x: number;
y: number;
lines: string[];
imgElement: HTMLElement | null;
textBox?: [number, number, number, number]; // [xmin, ymin, xmax, ymax] for initial crop
pageIndex?: number;
}
interface Props {
page: Page;
src?: File;
volumeUuid: string;
/** 0-based page index within the volume */
pageIndex?: number;
/** Force text visibility (for placeholder/missing pages) */
forceVisible?: boolean;
/** Callback when context menu should be shown */
onContextMenu?: (data: ContextMenuData) => void;
}
let { page, src, volumeUuid, pageIndex, forceVisible = false, onContextMenu }: Props = $props();
interface TextBoxData {
left: string;
top: string;
width: string;
height: string;
fontSize: string;
writingMode: string;
lines: string[];
area: number;
useMinDimensions: boolean;
isOriginalMode: boolean;
/** Per-line positions/sizes from lines_coords (auto mode only);
* null falls back to legacy hover-fit auto rendering */
lineLayouts: LineLayout[] | null;
blockIndex: number; // Original index in page.blocks
}
let textBoxes = $derived(
dedupeBlocks(page.blocks)
.map(({ block, blockIndex }) => {
const { img_height, img_width } = page;
const { box, font_size, lines, vertical } = block;
let [_xmin, _ymin, _xmax, _ymax] = box;
// Replace manual ellipsis with proper ellipsis character (…)
// Handle both ASCII periods (...) and full-width periods (...)
const processedLines = lines.map((line) =>
line.replace(/\.\.\./g, '…').replace(/.../g, '…')
);
const isOriginalMode = $settings.fontSize === 'original';
const isAutoMode = $settings.fontSize === 'auto';
// Auto mode: derive per-line position/size from the OCR line quads.
// mokuro's block font_size overstates the true character size (it is
// the quad width, furigana included), so rendering it as-is overflows
// the box; the quads themselves are accurate. Null (no lines_coords,
// e.g. pre-lines_coords imports) → legacy hover-fit auto below.
const lineLayouts = isAutoMode
? layoutLines(block, processedLines, getDefaultMeasurer())
: null;
// Only expand bounding boxes for legacy hover-fit auto sizing;
// per-line layout and manual font sizes use exact OCR bounding boxes
let xmin, ymin, xmax, ymax;
if (isAutoMode && !lineLayouts) {
// Expand bounding box by 10% (5% on each side) to give text more room
const originalWidth = _xmax - _xmin;
const originalHeight = _ymax - _ymin;
const expansionX = originalWidth * 0.05;
const expansionY = originalHeight * 0.05;
xmin = clamp(_xmin - expansionX, 0, img_width);
ymin = clamp(_ymin - expansionY, 0, img_height);
xmax = clamp(_xmax + expansionX, 0, img_width);
ymax = clamp(_ymax + expansionY, 0, img_height);
} else {
xmin = _xmin;
ymin = _ymin;
xmax = _xmax;
ymax = _ymax;
}
const width = xmax - xmin;
const height = ymax - ymin;
const area = width * height;
// Determine font size based on setting
let fontSize: string;
if ($settings.fontSize === 'auto' || $settings.fontSize === 'original') {
fontSize = `${font_size}px`;
} else {
fontSize = `${$settings.fontSize}pt`;
}
const textBox: TextBoxData = {
left: `${xmin}px`,
top: `${ymin}px`,
width: `${width}px`,
height: `${height}px`,
fontSize,
writingMode: vertical ? 'vertical-rl' : 'horizontal-tb',
lines: processedLines,
area,
useMinDimensions: $settings.fontSize !== 'auto' && !isOriginalMode,
isOriginalMode,
lineLayouts,
blockIndex
};
return textBox;
})
.sort(({ area: a }, { area: b }) => {
return b - a;
})
);
let fontWeight = $derived($settings.boldFont ? 'bold' : '400');
let display = $derived($settings.displayOCR ? 'block' : 'none');
let alwaysShowOCR = $derived($settings.alwaysShowOCR);
let border = $derived($settings.textBoxBorders ? '1px solid red' : 'none');
let contenteditable = $derived($settings.textEditable);
// Double-tap trigger: enabled if triggerMethod is 'doubleTap' or 'both' (legacy)
let doubleTapEnabled = $derived(
$settings.ankiConnectSettings.triggerMethod === 'doubleTap' ||
$settings.ankiConnectSettings.triggerMethod === 'both'
);
let ankiTags = $derived($settings.ankiConnectSettings.tags);
let cardMode = $derived($settings.ankiConnectSettings.cardMode);
let volumeMetadata = $derived<VolumeMetadata>({
seriesTitle: $volumes[volumeUuid]?.series_title,
volumeTitle: $volumes[volumeUuid]?.volume_title
});
// Load volume cover image from DB and add to metadata
async function getMetadataWithCover(): Promise<VolumeMetadata> {
try {
const dbVolume = await db.volumes.get(volumeUuid);
if (dbVolume?.thumbnail) {
const coverImage = await blobToBase64(dbVolume.thumbnail);
if (coverImage) {
return { ...volumeMetadata, coverImage };
}
}
} catch {
// Fall through to return metadata without cover
}
return volumeMetadata;
}
// Track adjusted font sizes for each textbox
let adjustedFontSizes = $state<Map<number, string>>(new Map());
// Track which textboxes need word wrapping enabled
let needsWrapping = $state<Set<number>>(new Set());
// Track which textboxes have been processed
let processedTextBoxes = $state<Set<number>>(new Set());
// Calculate optimal font size for a textbox using binary search
// Two-phase approach: scale up until overflow, then find the goldilocks size
function calculateOptimalFontSize(element: HTMLDivElement, initialFontSize: string) {
// Parse the initial font size to get numeric value
const match = initialFontSize.match(/(\d+(?:\.\d+)?)(px|pt)/);
if (!match) return null;
const originalSize = parseFloat(match[1]);
const unit = match[2];
const minFontSize = 8; // Minimum font size in px
const maxFontSize = 200; // Maximum font size to try when scaling up
// Convert to px for consistent handling, rounding to integer
// Integer font sizes ensure the binary search always makes progress
let originalInPx = Math.round(unit === 'pt' ? originalSize * 1.333 : originalSize);
// Guard against invalid font sizes that would cause infinite loops
// (0, negative, NaN, or Infinity would break the binary search)
if (!Number.isFinite(originalInPx) || originalInPx < minFontSize) {
originalInPx = minFontSize;
}
// Check if content overflows at a given font size
const isOverflowingAt = (size: number) => {
element.style.fontSize = `${size}px`;
return (
element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth
);
};
// Binary search to find the largest font size that fits
// Searches between low (fits) and high (overflows or max)
const findOptimalSize = () => {
// Phase 1: Find upper bound by scaling up until overflow
let low = minFontSize;
let high = originalInPx;
// If original fits, try scaling up to find the true max
if (!isOverflowingAt(originalInPx)) {
// Double until we overflow or hit max
high = originalInPx;
while (!isOverflowingAt(high) && high < maxFontSize) {
low = high;
high = Math.min(high * 2, maxFontSize);
}
// If we're at max and still not overflowing, use max
if (!isOverflowingAt(high)) {
return high;
}
} else {
// Original overflows, check if min fits
if (isOverflowingAt(minFontSize)) {
return minFontSize;
}
low = minFontSize;
high = originalInPx;
}
// Phase 2: Binary search between low (fits) and high (overflows)
while (high - low > 1) {
const mid = Math.floor((low + high) / 2);
if (isOverflowingAt(mid)) {
high = mid;
} else {
low = mid;
}
}
return low;
};
// Step 1: Find optimal size without wrapping
element.style.whiteSpace = 'nowrap';
element.style.wordWrap = 'normal';
element.style.overflowWrap = 'normal';
const noWrapSize = findOptimalSize();
// Step 2: Only try wrapping if it could give us 1.3x the font size
// Quick check: would 1.3x the noWrapSize overflow with wrapping?
element.style.whiteSpace = 'normal';
element.style.wordWrap = 'break-word';
element.style.overflowWrap = 'break-word';
const thresholdSize = noWrapSize * 1.3;
if (!isOverflowingAt(thresholdSize)) {
// Wrapping allows at least 1.3x - search for the actual optimal wrap size
const wrapSize = findOptimalSize();
return {
finalSize: wrapSize,
useWrapping: true,
originalInPx
};
}
// Wrapping doesn't help enough, use nowrap
return {
finalSize: noWrapSize,
useWrapping: false,
originalInPx
};
}
// Handle hover event to calculate resize on demand (only for auto font sizing)
function handleTextBoxHover(element: HTMLDivElement, params: [number, string]) {
const [index, initialFontSize] = params;
const calculate = () => {
// Skip if already processed, OCR is hidden, using manual font size, or
// the box is laid out per-line from lines_coords (no fitting needed)
if (
processedTextBoxes.has(index) ||
display !== 'block' ||
$settings.fontSize !== 'auto' ||
element.classList.contains('perLine')
)
return;
// Mark as processed immediately to prevent duplicate calculations
processedTextBoxes.add(index);
// Use requestAnimationFrame to ensure the DOM is fully rendered
requestAnimationFrame(() => {
const result = calculateOptimalFontSize(element, initialFontSize);
if (!result) return;
const { finalSize, useWrapping, originalInPx } = result;
// Apply final settings
if (useWrapping) {
needsWrapping.add(index);
element.style.whiteSpace = 'normal';
element.style.wordWrap = 'break-word';
element.style.overflowWrap = 'break-word';
} else {
element.style.whiteSpace = 'nowrap';
element.style.wordWrap = 'normal';
element.style.overflowWrap = 'normal';
}
element.style.fontSize = `${finalSize}px`;
// Store adjusted size if it changed
if (finalSize < originalInPx) {
adjustedFontSizes.set(index, `${finalSize}px`);
}
});
};
element.addEventListener('mouseenter', calculate);
// touchstart fires before long-press reveals the text box
element.addEventListener('touchstart', calculate, { passive: true });
return {
destroy() {
element.removeEventListener('mouseenter', calculate);
element.removeEventListener('touchstart', calculate);
}
};
}
function getImageUrlFromElement(element: HTMLElement): string | null {
// Traverse up to find the MangaPage div with background-image
let current: HTMLElement | null = element;
while (current) {
const bgImage = getComputedStyle(current).backgroundImage;
if (bgImage && bgImage !== 'none') {
// Extract URL from "url(...)"
const match = bgImage.match(/url\(["']?(.+?)["']?\)/);
if (match) {
return match[1];
}
}
current = current.parentElement;
}
return null;
}
function getSelectedText(): string {
// Get actual selected text from the DOM
const selection = window.getSelection();
return selection?.toString().trim() || '';
}
async function onUpdateCard(event: Event, lines: string[], blockIndex: number) {
if (!$settings.ankiConnectSettings.enabled) return;
const selectedText = getSelectedText();
const fullSentence = lines.join(' ');
// Get the original block's bounding box for initial crop
const block = page.blocks[blockIndex];
const textBox = block ? expandTextBoxBounds(block, page) : undefined;
// Get image URL
const url =
getImageUrlFromElement(event.target as HTMLElement) ||
(src ? URL.createObjectURL(src) : null);
if (!url) return;
// Get current page number for {page} template
// Use the explicit pageIndex prop (0-based) when available, otherwise fall back to progress
const pageNumber = pageIndex != null ? pageIndex + 1 : $volumes[volumeUuid]?.progress || 1;
// Load cover image for {cover} template support
const metadataWithCover = await getMetadataWithCover();
if (cardMode === 'update') {
// Update mode: fetch previous card values with retry
const maxRetries = 3;
let lastCard = null;
let lastError = '';
for (let attempt = 0; attempt < maxRetries; attempt++) {
lastCard = await getLastCardInfo();
if (!lastCard || !lastCard.noteId) {
lastError = 'No recent card found to update';
// Wait before retry (except on last attempt)
if (attempt < maxRetries - 1) {
await new Promise((r) => setTimeout(r, 500));
}
continue;
}
if (!lastCard.modelName) {
lastError = 'Could not detect card note type';
// Wait before retry
if (attempt < maxRetries - 1) {
await new Promise((r) => setTimeout(r, 500));
}
continue;
}
// Success - break out of retry loop
lastError = '';
break;
}
if (lastError || !lastCard?.noteId || !lastCard?.modelName) {
const { showSnackbar } = await import('$lib/util');
showSnackbar(`Error: ${lastError || 'Failed to fetch card info'}`);
return;
}
const cardAge = getCardAgeInMin(lastCard.noteId);
if (cardAge >= 5) {
// Card too old
const { showSnackbar } = await import('$lib/util');
showSnackbar(`Last card is ${cardAge} minutes old (max 5 min)`);
return;
}
const previousValues = extractFieldValues(lastCard);
// Get the model config to check for quickCapture setting
const modelConfig = getModelConfig(lastCard.modelName, 'update');
const hasConfig = !!modelConfig;
const quickCapture = modelConfig?.quickCapture ?? false;
if (quickCapture) {
// Quick capture: send directly without modal
await sendQuickCapture(
'update',
url,
selectedText || fullSentence,
fullSentence,
metadataWithCover,
textBox,
previousValues,
lastCard.noteId,
lastCard.tags,
lastCard.modelName,
page.img_path
);
} else {
// Show modal in update mode - use the card's model name
// (also shown if quickCapture but no config exists)
openUpdateModal(
url,
previousValues,
lastCard.noteId,
lastCard.modelName,
lastCard.tags, // existing tags from the card
selectedText || fullSentence,
fullSentence,
ankiTags,
metadataWithCover,
undefined,
textBox,
pageNumber,
page.img_path
);
}
} else {
// Create mode
const { selectedModel } = $settings.ankiConnectSettings;
const modelConfig = getModelConfig(selectedModel, 'create');
const quickCapture = modelConfig?.quickCapture ?? false;
if (quickCapture) {
await sendQuickCapture(
'create',
url,
selectedText || fullSentence,
fullSentence,
metadataWithCover,
textBox,
undefined, // previousValues
undefined, // previousCardId
undefined, // previousTags
undefined, // modelName
page.img_path
);
} else {
// Show modal (also shown if quickCapture but no config exists)
openCreateModal(
url,
selectedText || fullSentence,
fullSentence,
ankiTags,
metadataWithCover,
undefined,
textBox,
pageNumber,
page.img_path
);
}
}
}
function handleContextMenu(event: MouseEvent, lines: string[], blockIndex: number) {
// Only show custom context menu if enabled in settings
if (!$settings.textBoxContextMenu) return;
event.preventDefault();
// Get text box bounds with padding
const block = page.blocks[blockIndex];
const textBox = block ? expandTextBoxBounds(block, page) : undefined;
onContextMenu?.({
x: event.clientX,
y: event.clientY,
lines,
imgElement: event.target as HTMLElement,
textBox,
pageIndex
});
}
function onDoubleTap(event: Event, lines: string[], blockIndex: number) {
// Always stop propagation to prevent zoom from triggering
event.stopPropagation();
if (doubleTapEnabled) {
event.preventDefault();
onUpdateCard(event, lines, blockIndex);
}
}
function onCopy(event: ClipboardEvent) {
// Strip line breaks from copied text (Ctrl+C default behavior)
const selection = window.getSelection()?.toString() || '';
const stripped = selection.replace(/[\n\r\t]/g, '');
event.clipboardData?.setData('text/plain', stripped);
event.preventDefault();
}
</script>
{#each textBoxes as { fontSize, height, left, lines, top, width, writingMode, useMinDimensions, isOriginalMode, lineLayouts, blockIndex }, index (`${volumeUuid}-textBox-${index}`)}
{@const usePerLine = lineLayouts !== null}
<div
use:handleTextBoxHover={[index, fontSize]}
class="textBox"
class:originalMode={isOriginalMode}
class:perLine={usePerLine}
class:forceVisible
class:alwaysVisible={alwaysShowOCR}
style:width={usePerLine ? width : isOriginalMode || useMinDimensions ? undefined : width}
style:height={usePerLine ? height : isOriginalMode || useMinDimensions ? undefined : height}
style:min-width={isOriginalMode ? undefined : useMinDimensions ? width : undefined}
style:min-height={isOriginalMode ? undefined : useMinDimensions ? height : undefined}
style:left
style:top
style:font-size={adjustedFontSizes.get(index) || fontSize}
style:font-weight={fontWeight}
style:display
style:border
style:writing-mode={writingMode}
role="none"
oncontextmenu={(e) => handleContextMenu(e, lines, blockIndex)}
ondblclick={(e) => onDoubleTap(e, lines, blockIndex)}
oncopy={onCopy}
{contenteditable}
>
<p>
{#if usePerLine && lineLayouts}
{#each lines as line, lineIndex}{#if !lineLayouts[lineIndex].hidden}<span
class="ocr-line positionedLine"
class:wrappedLine={lineLayouts[lineIndex].wrap}
style:left={`${lineLayouts[lineIndex].left}px`}
style:top={`${lineLayouts[lineIndex].top}px`}
style:width={lineLayouts[lineIndex].wrap
? `${lineLayouts[lineIndex].width}px`
: undefined}
style:height={lineLayouts[lineIndex].wrap
? `${lineLayouts[lineIndex].height}px`
: undefined}
style:font-size={`${lineLayouts[lineIndex].fontSize}px`}>{line}</span
>{/if}{/each}
{:else}
{#each lines as line}<span class="ocr-line">{line}</span>{/each}
{/if}
</p>
</div>
{/each}
<style>
.textBox {
color: black;
padding: 0;
position: absolute;
line-height: 1.1em;
font-size: 16pt;
font-family: 'Noto Sans JP', sans-serif;
/* Word wrapping controlled dynamically by JavaScript */
border: 1px solid rgba(0, 0, 0, 0);
z-index: 11;
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
box-sizing: border-box;
}
.textBox:focus,
.textBox:hover {
background: rgb(255, 255, 255);
border: 1px solid rgba(0, 0, 0, 0);
}
.textBox p {
visibility: hidden;
/* Word wrapping controlled dynamically by JavaScript */
letter-spacing: 0.1em;
line-height: 1.1em;
background-color: rgb(255, 255, 255);
font-weight: var(--bold);
font-family: 'Noto Sans JP', sans-serif;
z-index: 11;
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
.textBox:focus p,
.textBox:hover p {
visibility: visible;
}
/* Force visibility for placeholder/missing pages, or when always-show OCR is enabled */
.textBox.forceVisible,
.textBox.alwaysVisible {
background: rgb(255, 255, 255);
}
.textBox.forceVisible p,
.textBox.alwaysVisible p {
visibility: visible;
}
/* Original mode: no size constraints, allow overflow */
.textBox.originalMode {
overflow: visible;
white-space: nowrap;
}
.textBox.originalMode p {
white-space: nowrap;
}
/* Original mode with lines_coords: each line is placed at its detected quad
with a geometry-derived font size. line-height 1 keeps the column/row no
thicker than the font size; letter-spacing 0 because the print's tracking
is already baked into the quad length the size was fitted to. */
.textBox.perLine .ocr-line.positionedLine {
position: absolute;
line-height: 1;
letter-spacing: 0;
white-space: nowrap;
}
/* A quad that captured multiple print columns (base text + furigana):
the text flows inside the full quad bbox at the block's reference size,
wrapping into columns/rows instead of shrinking onto one line. */
.textBox.perLine .ocr-line.positionedLine.wrappedLine {
white-space: normal;
line-break: anywhere;
}
/* Use CSS-generated newline instead of <br/> so DOM walkers
(Migaku/Yomitan) see one continuous text node per textbox
and don't treat line breaks as sentence boundaries. */
.textBox .ocr-line:not(:last-child)::after {
content: '\A';
white-space: pre;
}
</style>