@koi-br/ocr-web-sdk 1.0.42 → 1.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -116,24 +116,13 @@
116
116
  @mouseleave="stopPan"
117
117
  @scroll="handleScroll"
118
118
  >
119
- <!-- 自适应宽度计算 Loading -->
120
- <div v-if="isCalculatingAutoFit && autoFitWidth" class="auto-fit-loading">
121
- <div class="loading-spinner"></div>
122
- <div class="loading-text">加载中...</div>
123
- </div>
124
-
125
- <div
126
- class="image-wrapper-container"
127
- :style="containerStyle"
128
- :class="{ 'image-hidden': !isImageReady && autoFitWidth }"
129
- >
119
+ <div class="image-wrapper-container" :style="containerStyle">
130
120
  <!-- 渲染所有图片页面 -->
131
121
  <div
132
122
  v-for="(imageUrl, pageIndex) in imageUrls"
133
123
  :key="pageIndex"
134
124
  :data-page-number="pageIndex + 1"
135
125
  class="image-page-container"
136
- :style="getPageContainerStyle(pageIndex + 1)"
137
126
  >
138
127
  <div
139
128
  class="image-wrapper"
@@ -400,48 +389,12 @@ const position = ref({ x: 0, y: 0 });
400
389
  const isPanning = ref(false);
401
390
  const lastPosition = ref({ x: 0, y: 0 });
402
391
  const initialAutoFitScale = ref<number | null>(null); // 记录初始自适应缩放比例
403
- const isCalculatingAutoFit = ref(false); // 标记是否正在计算自适应宽度(显示 loading)
404
- const isImageReady = ref(false); // 标记图片是否已准备好显示(自适应宽度计算完成)
405
-
406
- // 监听图片URL变化,当有新图片时立即隐藏(等待自适应宽度计算)
407
- watch(
408
- () => imageUrls.value,
409
- (newUrls, oldUrls) => {
410
- console.log('[ImagePreview] imageUrls changed:', {
411
- newUrls: newUrls?.length,
412
- oldUrls: oldUrls?.length,
413
- autoFitWidth: props.autoFitWidth,
414
- isImageReady: isImageReady.value,
415
- isCalculatingAutoFit: isCalculatingAutoFit.value,
416
- });
417
-
418
- // 如果有新的图片URL,且启用自适应宽度,立即隐藏图片
419
- if (newUrls && newUrls.length > 0 && props.autoFitWidth) {
420
- console.log('[ImagePreview] 设置图片隐藏,等待自适应宽度计算');
421
- isImageReady.value = false;
422
- isCalculatingAutoFit.value = true;
423
- } else if (!props.autoFitWidth) {
424
- // 如果没有启用自适应宽度,立即显示
425
- console.log('[ImagePreview] 未启用自适应宽度,立即显示图片');
426
- isImageReady.value = true;
427
- isCalculatingAutoFit.value = false;
428
- }
429
- },
430
- { immediate: true }
431
- );
432
392
  const isUserZooming = ref(false); // 标记用户是否主动缩放
433
393
 
434
394
  // 滚动翻页相关
435
395
  let scrollPagingTimer: any = null;
436
396
  const isScrollPaging = ref(false); // 标记是否正在进行滚动翻页
437
397
 
438
- // ResizeObserver 相关
439
- let resizeObserver: ResizeObserver | null = null;
440
- let resizeTimer: any = null; // handleContainerResize 内部的定时器
441
- let resizeDebounceTimer: any = null; // ResizeObserver 的防抖定时器
442
- let isResizing = false; // 标记是否正在处理 resize
443
- let lastContainerWidth = 0; // 记录上次容器宽度,用于判断是否真的变化了
444
-
445
398
  // 图片和容器引用
446
399
  const containerRef = ref<HTMLElement>();
447
400
  const imageRefs = new Map<number, HTMLImageElement>();
@@ -561,35 +514,6 @@ const getPageBlocksData = (pageNo: number) => {
561
514
  return props.blocksData.filter((block) => block.pageNo === pageNo);
562
515
  };
563
516
 
564
- // 计算指定页面缩放后的尺寸(考虑旋转)
565
- const getPageScaledSize = (pageNo: number) => {
566
- const pageSize = imageSizes.get(pageNo);
567
- if (!pageSize || pageSize.width === 0 || pageSize.height === 0) {
568
- return { width: 0, height: 0 };
569
- }
570
-
571
- const { width, height } = pageSize;
572
- const scaledWidth = width * scale.value;
573
- const scaledHeight = height * scale.value;
574
-
575
- // 如果旋转了 90 度或 270 度,交换宽高
576
- const normalizedRotation = ((rotation.value % 360) + 360) % 360;
577
- const isRotated = normalizedRotation === 90 || normalizedRotation === 270;
578
-
579
- return {
580
- width: isRotated ? scaledHeight : scaledWidth,
581
- height: isRotated ? scaledWidth : scaledHeight,
582
- };
583
- };
584
-
585
- // 获取页面容器的样式(响应式,会根据缩放和旋转自动更新)
586
- const getPageContainerStyle = (pageNo: number) => {
587
- const scaledSize = getPageScaledSize(pageNo);
588
- return {
589
- height: scaledSize.height > 0 ? `${scaledSize.height}px` : 'auto',
590
- };
591
- };
592
-
593
517
  // 隐藏定时器
594
518
  let hideTimer: any = null;
595
519
 
@@ -883,18 +807,10 @@ const switchToPage = (page: number) => {
883
807
  `[data-page-number="${page}"]`
884
808
  ) as HTMLElement;
885
809
  if (pageElement) {
886
- // 标记这是翻页滚动,不应该被同步滚动干扰
887
- containerRef.value.dataset.pageScrolling = 'true';
888
810
  pageElement.scrollIntoView({ behavior: "smooth", block: "start" });
889
811
  // 更新 lastScrollTop,确保滚动方向判断准确
890
812
  nextTick(() => {
891
813
  lastScrollTop = containerRef.value?.scrollTop || 0;
892
- // 延迟清除标记,确保滚动完成
893
- setTimeout(() => {
894
- if (containerRef.value) {
895
- delete containerRef.value.dataset.pageScrolling;
896
- }
897
- }, 500); // scrollIntoView 的 smooth 动画通常需要 300-500ms
898
814
  });
899
815
  }
900
816
  }
@@ -930,25 +846,13 @@ const original = () => {
930
846
 
931
847
  // 计算自适应宽度的缩放比例
932
848
  const calculateAutoFitScale = () => {
933
- console.log('[ImagePreview] calculateAutoFitScale 开始:', {
934
- autoFitWidth: props.autoFitWidth,
935
- hasContainerRef: !!containerRef.value,
936
- containerRect: containerRef.value?.getBoundingClientRect(),
937
- firstPageSize: imageSizes.get(1),
938
- rotation: rotation.value,
939
- minScale: props.minScale,
940
- maxScale: props.maxScale,
941
- });
942
-
943
849
  if (!props.autoFitWidth || !containerRef.value) {
944
- console.log('[ImagePreview] calculateAutoFitScale 返回 1 (条件不满足)');
945
850
  return 1;
946
851
  }
947
852
 
948
853
  // 使用第一页的图片尺寸作为基准(所有页面使用相同的缩放比例)
949
854
  const firstPageSize = imageSizes.get(1);
950
855
  if (!firstPageSize || firstPageSize.width === 0) {
951
- console.log('[ImagePreview] calculateAutoFitScale 返回 1 (第一页尺寸无效)', firstPageSize);
952
856
  return 1;
953
857
  }
954
858
 
@@ -958,7 +862,6 @@ const calculateAutoFitScale = () => {
958
862
  const containerWidth = containerRect.width - 4;
959
863
 
960
864
  if (containerWidth <= 0) {
961
- console.log('[ImagePreview] calculateAutoFitScale 返回 1 (容器宽度无效)', containerWidth);
962
865
  return 1;
963
866
  }
964
867
 
@@ -969,38 +872,20 @@ const calculateAutoFitScale = () => {
969
872
  const imageWidth = isRotated ? firstPageSize.height : firstPageSize.width;
970
873
 
971
874
  if (imageWidth <= 0) {
972
- console.log('[ImagePreview] calculateAutoFitScale 返回 1 (图片宽度无效)', imageWidth);
973
875
  return 1;
974
876
  }
975
877
 
976
878
  // 计算缩放比例,使图片宽度完全适应容器宽度
977
879
  const calculatedScale = containerWidth / imageWidth;
978
- const finalScale = Math.max(props.minScale, Math.min(props.maxScale, calculatedScale));
979
-
980
- console.log('[ImagePreview] calculateAutoFitScale 计算结果:', {
981
- containerWidth,
982
- imageWidth,
983
- calculatedScale,
984
- finalScale,
985
- });
986
880
 
987
881
  // 确保缩放比例在允许的范围内
988
- return finalScale;
882
+ return Math.max(props.minScale, Math.min(props.maxScale, calculatedScale));
989
883
  };
990
884
 
991
885
  // 图片加载完成处理
992
886
  const onImageLoad = (event: Event, pageNum: number) => {
993
887
  const img = event.target as HTMLImageElement;
994
888
 
995
- console.log('[ImagePreview] 图片加载完成:', {
996
- pageNum,
997
- naturalWidth: img.naturalWidth,
998
- naturalHeight: img.naturalHeight,
999
- autoFitWidth: props.autoFitWidth,
1000
- isImageReady: isImageReady.value,
1001
- isCalculatingAutoFit: isCalculatingAutoFit.value,
1002
- });
1003
-
1004
889
  // 存储该页的图片尺寸
1005
890
  imageSizes.set(pageNum, {
1006
891
  width: img.naturalWidth,
@@ -1009,69 +894,22 @@ const onImageLoad = (event: Event, pageNum: number) => {
1009
894
 
1010
895
  // 如果是第一页且启用自适应宽度,计算并设置初始缩放比例
1011
896
  if (pageNum === 1 && props.autoFitWidth) {
1012
- console.log('[ImagePreview] 第一页加载完成,开始计算自适应宽度');
1013
897
  // 重置用户缩放标记
1014
898
  isUserZooming.value = false;
1015
-
1016
- // 确保图片是隐藏的(watch 已经设置了,这里再次确认)
1017
- if (!isImageReady.value) {
1018
- isCalculatingAutoFit.value = true;
1019
- }
1020
-
1021
- // 设置超时保护,防止一直显示 loading(最多等待 3 秒)
1022
- const timeoutId = setTimeout(() => {
1023
- console.warn('自适应宽度计算超时,强制显示图片');
1024
- isCalculatingAutoFit.value = false;
1025
- isImageReady.value = true;
1026
- }, 3000);
1027
899
 
1028
900
  // 使用双重 nextTick 确保容器尺寸已确定
1029
901
  nextTick(() => {
1030
902
  nextTick(() => {
1031
903
  // 添加小延迟确保容器完全渲染
1032
904
  setTimeout(() => {
1033
- try {
1034
- console.log('[ImagePreview] onImageLoad: 开始计算自适应宽度...');
1035
- const autoScale = calculateAutoFitScale();
1036
- console.log('[ImagePreview] onImageLoad: 自适应宽度计算结果:', {
1037
- autoScale,
1038
- containerRef: !!containerRef.value,
1039
- containerWidth: containerRef.value?.getBoundingClientRect()?.width,
1040
- firstPageSize: imageSizes.get(1),
1041
- });
1042
-
1043
- if (autoScale > 0) {
1044
- scale.value = autoScale;
1045
- initialAutoFitScale.value = autoScale; // 记录初始自适应缩放比例
1046
- // 记录当前容器宽度,用于后续 resize 检查
1047
- if (containerRef.value) {
1048
- lastContainerWidth = containerRef.value.getBoundingClientRect().width;
1049
- }
1050
- console.log('[ImagePreview] onImageLoad: 缩放比例已设置:', autoScale);
1051
- } else {
1052
- console.warn('[ImagePreview] onImageLoad: 计算出的缩放比例无效:', autoScale);
1053
- }
1054
- } catch (error) {
1055
- console.error('[ImagePreview] onImageLoad: 计算自适应宽度失败:', error);
1056
- } finally {
1057
- // 清除超时保护
1058
- clearTimeout(timeoutId);
1059
- console.log('[ImagePreview] onImageLoad: 更新状态: isCalculatingAutoFit = false, isImageReady = true');
1060
- // 无论计算结果如何,都要更新状态,避免一直显示 loading
1061
- isCalculatingAutoFit.value = false;
1062
- // 使用 requestAnimationFrame 确保在下一帧显示,避免闪烁
1063
- requestAnimationFrame(() => {
1064
- isImageReady.value = true;
1065
- console.log('[ImagePreview] onImageLoad: 图片已准备好显示');
1066
- });
905
+ const autoScale = calculateAutoFitScale();
906
+ if (autoScale !== 1 && autoScale > 0) {
907
+ scale.value = autoScale;
908
+ initialAutoFitScale.value = autoScale; // 记录初始自适应缩放比例
1067
909
  }
1068
910
  }, 100); // 增加延迟,确保所有图片都已加载
1069
911
  });
1070
912
  });
1071
- } else if (!props.autoFitWidth) {
1072
- // 如果没有启用自适应宽度,立即显示图片
1073
- isImageReady.value = true;
1074
- isCalculatingAutoFit.value = false;
1075
913
  }
1076
914
 
1077
915
  // 如果第一页已经加载完成,且当前页不是第一页,也应用自适应宽度
@@ -1283,13 +1121,9 @@ const renderTextLayer = (pageNum?: number) => {
1283
1121
  hideTimer = null;
1284
1122
  }
1285
1123
 
1286
- // 清除当前页面所有文本块的高亮样式(除了当前文本块)
1287
- // 这样可以防止多个文本块同时高亮的竞态条件
1288
- clearAllHighlights(blockDiv);
1289
-
1290
- // 清除跳转高亮标志(如果之前是通过跳转高亮的)
1291
- if (isHighlighted.value) {
1292
- isHighlighted.value = false;
1124
+ // 如果有之前激活的文本块,先恢复其样式
1125
+ if (activeBlockDiv.value && activeBlockDiv.value !== blockDiv) {
1126
+ restoreBlockStyle(activeBlockDiv.value);
1293
1127
  }
1294
1128
 
1295
1129
  // 设置当前文本块为激活状态
@@ -1305,10 +1139,7 @@ const renderTextLayer = (pageNum?: number) => {
1305
1139
  blockDiv.style.setProperty("padding", "1px 3px", "important");
1306
1140
  blockDiv.style.setProperty("box-shadow", "0 0 0 2px rgba(30, 144, 255, 0.6), 0 1px 2px rgba(255, 193, 7, 0.25)", "important");
1307
1141
  } else {
1308
- // 如果没有批注,先清除可能残留的样式,再设置 hover 样式(与 PdfPreview 保持一致)
1309
- blockDiv.style.removeProperty("background-color");
1310
- blockDiv.style.removeProperty("border");
1311
- blockDiv.style.removeProperty("box-shadow");
1142
+ // 如果没有批注,使用 hover 样式(与 PdfPreview 保持一致)
1312
1143
  blockDiv.style.backgroundColor =
1313
1144
  "var(--s-color-brand-primary-transparent-3, rgba(0, 102, 255, .15))";
1314
1145
  blockDiv.style.boxShadow = "0 0 0 2px rgba(30, 144, 255, 0.6)";
@@ -1472,75 +1303,6 @@ const showAnnotationButtonForBlock = (
1472
1303
  }
1473
1304
  };
1474
1305
 
1475
- /**
1476
- * 清除指定页面所有文本块的高亮样式(除了指定的文本块)
1477
- * @param excludeBlockDiv 要排除的文本块(不清除它的样式)
1478
- * @param pageNum 要清除的页码,如果不提供则从 excludeBlockDiv 中获取
1479
- */
1480
- const clearAllHighlights = (excludeBlockDiv?: HTMLElement, pageNum?: number) => {
1481
- // 确定要清除的页码
1482
- let targetPage = pageNum;
1483
- if (!targetPage && excludeBlockDiv) {
1484
- const pageStr = excludeBlockDiv.dataset.page;
1485
- targetPage = pageStr ? parseInt(pageStr, 10) : currentPage.value;
1486
- }
1487
- if (!targetPage) {
1488
- targetPage = currentPage.value;
1489
- }
1490
-
1491
- const textLayer = textLayerRefs.get(targetPage);
1492
- if (!textLayer) return;
1493
-
1494
- const blockDivs = textLayer.querySelectorAll(".text-block");
1495
- blockDivs.forEach((div) => {
1496
- const el = div as HTMLElement;
1497
- // 如果是指定的文本块,跳过
1498
- if (excludeBlockDiv && el === excludeBlockDiv) {
1499
- return;
1500
- }
1501
-
1502
- // 检查是否有批注
1503
- const bboxStr = el.dataset.bbox;
1504
- if (!bboxStr) return;
1505
-
1506
- try {
1507
- const bbox = JSON.parse(bboxStr) as [number, number, number, number];
1508
- const pageStr = el.dataset.page;
1509
- const pageNum = pageStr ? parseInt(pageStr, 10) : undefined;
1510
- const existingAnnotation = getAnnotationForBlock(bbox, pageNum);
1511
-
1512
- if (existingAnnotation) {
1513
- // 如果有批注,恢复批注样式(不使用 hover 样式)
1514
- el.style.setProperty("background-color", "rgba(255, 243, 205, 0.5)", "important");
1515
- el.style.setProperty("border", "1px solid rgba(255, 193, 7, 0.7)", "important");
1516
- el.style.setProperty("border-radius", "3px", "important");
1517
- el.style.setProperty("padding", "1px 3px", "important");
1518
- el.style.setProperty("box-shadow", "0 1px 2px rgba(255, 193, 7, 0.25)", "important");
1519
- } else {
1520
- // 如果没有批注,清除所有高亮样式
1521
- el.style.backgroundColor = "transparent";
1522
- el.style.border = "none";
1523
- el.style.borderRadius = "2px";
1524
- el.style.padding = "0";
1525
- el.style.boxShadow = "none";
1526
- el.style.removeProperty("background-color");
1527
- el.style.removeProperty("border");
1528
- el.style.removeProperty("box-shadow");
1529
- }
1530
- } catch (error) {
1531
- // 如果解析失败,清除所有高亮样式
1532
- el.style.backgroundColor = "transparent";
1533
- el.style.border = "none";
1534
- el.style.borderRadius = "2px";
1535
- el.style.padding = "0";
1536
- el.style.boxShadow = "none";
1537
- el.style.removeProperty("background-color");
1538
- el.style.removeProperty("border");
1539
- el.style.removeProperty("box-shadow");
1540
- }
1541
- });
1542
- };
1543
-
1544
1306
  /**
1545
1307
  * 恢复文本块样式(根据是否有批注)
1546
1308
  */
@@ -1596,29 +1358,19 @@ const restoreBlockStyle = (blockDiv: HTMLElement) => {
1596
1358
  computedAfter: window.getComputedStyle(blockDiv).backgroundColor,
1597
1359
  });
1598
1360
  } else {
1599
- // 如果没有批注,恢复透明背景(清除所有高亮相关样式)
1361
+ // 如果没有批注,恢复透明背景
1600
1362
  blockDiv.style.backgroundColor = "transparent";
1601
1363
  blockDiv.style.border = "none";
1602
- blockDiv.style.borderRadius = "2px"; // 恢复默认值
1603
1364
  blockDiv.style.padding = "0";
1604
1365
  blockDiv.style.boxShadow = "none";
1605
- // 清除可能残留的样式属性
1606
- blockDiv.style.removeProperty("background-color");
1607
- blockDiv.style.removeProperty("border");
1608
- blockDiv.style.removeProperty("box-shadow");
1609
1366
  }
1610
1367
  } catch (error) {
1611
1368
  console.error("restoreBlockStyle 错误:", error);
1612
- // 如果解析失败,恢复透明背景(清除所有高亮相关样式)
1369
+ // 如果解析失败,恢复透明背景
1613
1370
  blockDiv.style.backgroundColor = "transparent";
1614
1371
  blockDiv.style.border = "none";
1615
- blockDiv.style.borderRadius = "2px"; // 恢复默认值
1616
1372
  blockDiv.style.padding = "0";
1617
1373
  blockDiv.style.boxShadow = "none";
1618
- // 清除可能残留的样式属性
1619
- blockDiv.style.removeProperty("background-color");
1620
- blockDiv.style.removeProperty("border");
1621
- blockDiv.style.removeProperty("box-shadow");
1622
1374
  }
1623
1375
  };
1624
1376
 
@@ -1656,32 +1408,19 @@ const hideAnnotationButton = () => {
1656
1408
  activeBlockDiv.value.style.boxShadow =
1657
1409
  "0 1px 2px rgba(255, 193, 7, 0.25)";
1658
1410
  } else {
1659
- // 如果没有批注,恢复透明背景(清除所有高亮相关样式)
1411
+ // 如果没有批注,恢复透明背景
1660
1412
  activeBlockDiv.value.style.backgroundColor = "transparent";
1661
1413
  activeBlockDiv.value.style.border = "none";
1662
- activeBlockDiv.value.style.borderRadius = "2px"; // 恢复默认值
1663
1414
  activeBlockDiv.value.style.padding = "0";
1664
1415
  activeBlockDiv.value.style.boxShadow = "none";
1665
- // 清除可能残留的样式属性
1666
- activeBlockDiv.value.style.removeProperty("background-color");
1667
- activeBlockDiv.value.style.removeProperty("border");
1668
- activeBlockDiv.value.style.removeProperty("box-shadow");
1669
1416
  }
1670
1417
  } catch (error) {
1671
- // 如果解析失败,恢复透明背景(清除所有高亮相关样式)
1672
1418
  activeBlockDiv.value.style.backgroundColor = "transparent";
1673
1419
  activeBlockDiv.value.style.border = "none";
1674
- activeBlockDiv.value.style.borderRadius = "2px"; // 恢复默认值
1675
1420
  activeBlockDiv.value.style.padding = "0";
1676
1421
  activeBlockDiv.value.style.boxShadow = "none";
1677
- // 清除可能残留的样式属性
1678
- activeBlockDiv.value.style.removeProperty("background-color");
1679
- activeBlockDiv.value.style.removeProperty("border");
1680
- activeBlockDiv.value.style.removeProperty("box-shadow");
1681
1422
  }
1682
1423
  }
1683
- // 清除高亮标志
1684
- isHighlighted.value = false;
1685
1424
  activeBlockDiv.value = null;
1686
1425
  }
1687
1426
  }, 300);
@@ -1968,33 +1707,6 @@ const saveAnnotation = () => {
1968
1707
  * 处理滚动事件(隐藏批注按钮和文本块高亮,以及滚动翻页)
1969
1708
  */
1970
1709
  const handleScroll = (e: Event) => {
1971
- const container = e.target as HTMLElement;
1972
-
1973
- // 检查是否是同步滚动触发的
1974
- const isSyncing = container?.dataset?.syncingScroll === 'true';
1975
- if (isSyncing) {
1976
- // 即使是被同步滚动触发的,也应该立即更新页码(但不触发翻页动画)
1977
- // 使用 requestAnimationFrame 确保在浏览器渲染后立即更新
1978
- if (
1979
- props.enableScrollPaging &&
1980
- totalPages.value > 1 &&
1981
- !isScrollPaging.value
1982
- ) {
1983
- // 立即更新页码,不等待防抖
1984
- requestAnimationFrame(() => {
1985
- updateCurrentPageFromScroll();
1986
- // 清除标记(在页码更新后)
1987
- delete container.dataset.syncingScroll;
1988
- });
1989
- } else {
1990
- // 如果没有启用滚动翻页,立即清除标记
1991
- delete container.dataset.syncingScroll;
1992
- }
1993
-
1994
- // 同步滚动时,不执行其他逻辑(如隐藏批注按钮等)
1995
- return;
1996
- }
1997
-
1998
1710
  if (hideTimer) {
1999
1711
  clearTimeout(hideTimer);
2000
1712
  }
@@ -2016,74 +1728,23 @@ const handleScroll = (e: Event) => {
2016
1728
  scale.value = initialAutoFitScale.value;
2017
1729
  }
2018
1730
 
2019
- // 滚动翻页功能(用户主动滚动时)
1731
+ // 滚动翻页功能
2020
1732
  if (
2021
1733
  props.enableScrollPaging &&
2022
1734
  totalPages.value > 1 &&
2023
1735
  !isScrollPaging.value
2024
1736
  ) {
2025
- // 立即更新页码(使用 requestAnimationFrame 确保在渲染后更新)
2026
- requestAnimationFrame(() => {
2027
- updateCurrentPageFromScroll();
2028
- });
2029
- // 同时使用防抖处理其他逻辑(如事件触发)
2030
1737
  handleScrollPaging(e);
2031
1738
  }
2032
1739
  };
2033
1740
 
2034
-
2035
1741
  // 记录上次滚动位置,用于判断滚动方向
2036
1742
  let lastScrollTop = 0;
2037
1743
 
2038
- /**
2039
- * 根据滚动位置更新当前页码
2040
- * 通过找到距离视口中心最近的页面来确定当前页
2041
- * 使用 getBoundingClientRect() 获取实际渲染位置(考虑了 transform: scale)
2042
- */
2043
- const updateCurrentPageFromScroll = () => {
2044
- if (!containerRef.value) return;
2045
-
2046
- const container = containerRef.value;
2047
- const containerRect = container.getBoundingClientRect();
2048
- const containerTop = containerRect.top;
2049
- const containerHeight = container.clientHeight;
2050
- const containerCenter = containerTop + containerHeight / 2;
2051
-
2052
- // 遍历所有页面,找到距离视口中心最近的页面
2053
- let closestPage = 1;
2054
- let closestDistance = Infinity;
2055
-
2056
- for (let pageNum = 1; pageNum <= totalPages.value; pageNum++) {
2057
- const pageElement = container.querySelector(
2058
- `[data-page-number="${pageNum}"]`
2059
- ) as HTMLElement;
2060
-
2061
- if (pageElement) {
2062
- // 使用 getBoundingClientRect() 获取实际渲染位置(考虑了 transform: scale)
2063
- // 而不是使用 offsetTop(不考虑 transform)
2064
- const pageRect = pageElement.getBoundingClientRect();
2065
- const pageTop = pageRect.top;
2066
- const pageHeight = pageRect.height;
2067
- const pageCenter = pageTop + pageHeight / 2;
2068
- const distance = Math.abs(pageCenter - containerCenter);
2069
-
2070
- if (distance < closestDistance) {
2071
- closestDistance = distance;
2072
- closestPage = pageNum;
2073
- }
2074
- }
2075
- }
2076
-
2077
- // 只有当页码真正改变时才更新
2078
- if (closestPage !== currentPage.value) {
2079
- currentPage.value = closestPage;
2080
- emit("page-change", closestPage, totalPages.value);
2081
- }
2082
- };
2083
-
2084
1744
  /**
2085
1745
  * 处理滚动翻页(通过滚动位置判断当前页)
2086
- * 使用视口中心最近的页面来确定当前页,更准确
1746
+ * 向下滑动:当视口顶部到达下一页的顶部时,切换到下一页
1747
+ * 向上滑动:当视口底部到达上一页的底部时,切换到上一页
2087
1748
  */
2088
1749
  const handleScrollPaging = (e: Event) => {
2089
1750
  const container = e.target as HTMLElement;
@@ -2100,16 +1761,80 @@ const handleScrollPaging = (e: Event) => {
2100
1761
  }
2101
1762
 
2102
1763
  // 使用防抖,避免频繁触发
2103
- // 减少延迟到50ms,提高响应速度
2104
1764
  scrollPagingTimer = setTimeout(() => {
2105
1765
  // 再次检查是否正在翻页
2106
1766
  if (isScrollPaging.value) {
2107
1767
  return;
2108
1768
  }
2109
1769
 
2110
- // 更新当前页码(基于视口中心最近的页面)
2111
- updateCurrentPageFromScroll();
2112
- }, 50);
1770
+ const scrollTop = container.scrollTop;
1771
+ const clientHeight = container.clientHeight;
1772
+ const scrollBottom = scrollTop + clientHeight;
1773
+
1774
+ // 判断滚动方向
1775
+ const isScrollingDown = scrollTop > lastScrollTop;
1776
+ lastScrollTop = scrollTop;
1777
+
1778
+ // 获取当前页的元素
1779
+ const currentPageElement = container.querySelector(
1780
+ `[data-page-number="${currentPage.value}"]`
1781
+ ) as HTMLElement;
1782
+
1783
+ if (!currentPageElement) return;
1784
+
1785
+ const currentPageTop = currentPageElement.offsetTop;
1786
+ const currentPageHeight = currentPageElement.offsetHeight;
1787
+ const currentPageBottom = currentPageTop + currentPageHeight;
1788
+
1789
+ let newPage = currentPage.value;
1790
+
1791
+ if (isScrollingDown) {
1792
+ // 向下滑动:当视口顶部到达或超过下一页的顶部时,切换到下一页
1793
+ if (currentPage.value < totalPages.value) {
1794
+ const nextPageElement = container.querySelector(
1795
+ `[data-page-number="${currentPage.value + 1}"]`
1796
+ ) as HTMLElement;
1797
+
1798
+ if (nextPageElement) {
1799
+ const nextPageTop = nextPageElement.offsetTop;
1800
+ // 当视口顶部到达或超过下一页的顶部时,切换到下一页
1801
+ if (scrollTop >= nextPageTop) {
1802
+ newPage = currentPage.value + 1;
1803
+ }
1804
+ }
1805
+ }
1806
+ } else {
1807
+ // 向上滑动:当视口底部到达或超过上一页的底部时,切换到上一页
1808
+ if (currentPage.value > 1) {
1809
+ const prevPageElement = container.querySelector(
1810
+ `[data-page-number="${currentPage.value - 1}"]`
1811
+ ) as HTMLElement;
1812
+
1813
+ if (prevPageElement) {
1814
+ const prevPageTop = prevPageElement.offsetTop;
1815
+ const prevPageHeight = prevPageElement.offsetHeight;
1816
+ const prevPageBottom = prevPageTop + prevPageHeight;
1817
+
1818
+ // 当视口底部到达或超过上一页的底部时,切换到上一页
1819
+ if (scrollBottom <= prevPageBottom) {
1820
+ newPage = currentPage.value - 1;
1821
+ }
1822
+ }
1823
+ }
1824
+ }
1825
+
1826
+ // 如果页码发生变化,更新当前页
1827
+ if (newPage !== currentPage.value) {
1828
+ isScrollPaging.value = true;
1829
+ currentPage.value = newPage;
1830
+ emit("page-change", newPage, totalPages.value);
1831
+
1832
+ // 延迟解锁,确保页面切换完成
1833
+ setTimeout(() => {
1834
+ isScrollPaging.value = false;
1835
+ }, 100);
1836
+ }
1837
+ }, 100);
2113
1838
  };
2114
1839
 
2115
1840
  /**
@@ -2369,99 +2094,6 @@ watch(
2369
2094
  { deep: true }
2370
2095
  );
2371
2096
 
2372
- /**
2373
- * 处理容器尺寸变化,重新计算自适应缩放比例
2374
- */
2375
- const handleContainerResize = () => {
2376
- // 如果禁用了自适应宽度,或者用户主动缩放过,不自动调整
2377
- if (!props.autoFitWidth || isUserZooming.value) {
2378
- return;
2379
- }
2380
-
2381
- // 如果第一页图片还没有加载完成,不处理
2382
- const firstPageSize = imageSizes.get(1);
2383
- if (!firstPageSize || firstPageSize.width === 0) {
2384
- return;
2385
- }
2386
-
2387
- // 如果正在计算中或正在处理 resize,跳过(避免重复计算)
2388
- if (isCalculatingAutoFit.value || isResizing) {
2389
- return;
2390
- }
2391
-
2392
- // 检查容器尺寸是否真的变化了(避免无意义的重复计算)
2393
- if (containerRef.value) {
2394
- const currentWidth = containerRef.value.getBoundingClientRect().width;
2395
- // 如果宽度变化小于 5px,认为是渲染抖动,不处理
2396
- if (Math.abs(currentWidth - lastContainerWidth) < 5) {
2397
- return;
2398
- }
2399
- lastContainerWidth = currentWidth;
2400
- }
2401
-
2402
- console.log('[ImagePreview] handleContainerResize 被调用:', {
2403
- autoFitWidth: props.autoFitWidth,
2404
- isUserZooming: isUserZooming.value,
2405
- isImageReady: isImageReady.value,
2406
- isCalculatingAutoFit: isCalculatingAutoFit.value,
2407
- hasFirstPageSize: !!imageSizes.get(1),
2408
- containerWidth: containerRef.value?.getBoundingClientRect()?.width,
2409
- });
2410
-
2411
- // 标记正在处理 resize
2412
- isResizing = true;
2413
-
2414
- // 清除之前的定时器
2415
- if (resizeTimer) {
2416
- clearTimeout(resizeTimer);
2417
- resizeTimer = null;
2418
- }
2419
-
2420
- // 隐藏图片,显示 loading
2421
- console.log('[ImagePreview] handleContainerResize: 开始重新计算');
2422
- isImageReady.value = false;
2423
- isCalculatingAutoFit.value = true;
2424
-
2425
- // 立即计算并应用新的缩放比例,避免过渡期间露出底色
2426
- // 使用 requestAnimationFrame 确保在浏览器重绘前更新
2427
- requestAnimationFrame(() => {
2428
- try {
2429
- console.log('[ImagePreview] handleContainerResize: 开始计算自适应宽度...');
2430
- const newScale = calculateAutoFitScale();
2431
- console.log('[ImagePreview] handleContainerResize: 计算结果:', newScale);
2432
-
2433
- if (newScale > 0) {
2434
- // 即使变化很小也立即更新,确保过渡期间图片始终填满容器
2435
- scale.value = newScale;
2436
- initialAutoFitScale.value = newScale;
2437
- }
2438
- } catch (error) {
2439
- console.error('[ImagePreview] handleContainerResize: 计算失败:', error);
2440
- }
2441
-
2442
- // 在过渡动画完成后再次检查,确保最终状态正确(处理过渡动画期间的连续变化)
2443
- resizeTimer = setTimeout(() => {
2444
- try {
2445
- const finalScale = calculateAutoFitScale();
2446
- if (finalScale > 0 && Math.abs(finalScale - scale.value) > 0.01) {
2447
- scale.value = finalScale;
2448
- initialAutoFitScale.value = finalScale;
2449
- }
2450
- } catch (error) {
2451
- console.error('[ImagePreview] handleContainerResize: 最终计算失败:', error);
2452
- } finally {
2453
- // 计算完成后,显示图片并隐藏 loading
2454
- console.log('[ImagePreview] handleContainerResize: 更新状态完成');
2455
- isCalculatingAutoFit.value = false;
2456
- isResizing = false; // 重置标记
2457
- requestAnimationFrame(() => {
2458
- isImageReady.value = true;
2459
- });
2460
- }
2461
- }, 350); // 350ms 延迟,略大于过渡动画时间(300ms),确保过渡完成后稳定
2462
- });
2463
- };
2464
-
2465
2097
  /**
2466
2098
  * 组件挂载时的初始化
2467
2099
  */
@@ -2471,68 +2103,19 @@ onMounted(() => {
2471
2103
  if (firstPageImage && firstPageImage.complete && props.autoFitWidth) {
2472
2104
  const firstPageSize = imageSizes.get(1);
2473
2105
  if (firstPageSize && firstPageSize.width > 0) {
2474
- // 隐藏图片,显示 loading
2475
- isImageReady.value = false;
2476
- isCalculatingAutoFit.value = true;
2477
-
2478
- // 设置超时保护,防止一直显示 loading(最多等待 3 秒)
2479
- const timeoutId = setTimeout(() => {
2480
- console.warn('自适应宽度计算超时,强制显示图片');
2481
- isCalculatingAutoFit.value = false;
2482
- isImageReady.value = true;
2483
- }, 3000);
2484
-
2485
2106
  nextTick(() => {
2486
2107
  nextTick(() => {
2487
2108
  setTimeout(() => {
2488
- try {
2489
- const autoScale = calculateAutoFitScale();
2490
- if (autoScale > 0) {
2491
- scale.value = autoScale;
2492
- initialAutoFitScale.value = autoScale;
2493
- }
2494
- } catch (error) {
2495
- console.warn('计算自适应宽度失败:', error);
2496
- } finally {
2497
- // 清除超时保护
2498
- clearTimeout(timeoutId);
2499
- // 无论计算结果如何,都要更新状态,避免一直显示 loading
2500
- isCalculatingAutoFit.value = false;
2501
- requestAnimationFrame(() => {
2502
- isImageReady.value = true;
2503
- });
2109
+ const autoScale = calculateAutoFitScale();
2110
+ if (autoScale !== 1 && autoScale > 0) {
2111
+ scale.value = autoScale;
2112
+ initialAutoFitScale.value = autoScale;
2504
2113
  }
2505
2114
  }, 100);
2506
2115
  });
2507
2116
  });
2508
2117
  }
2509
- } else if (!props.autoFitWidth) {
2510
- // 如果没有启用自适应宽度,立即显示图片
2511
- isImageReady.value = true;
2512
2118
  }
2513
-
2514
- // 监听容器尺寸变化(用于响应外部收起/展开操作)
2515
- nextTick(() => {
2516
- if (containerRef.value && typeof ResizeObserver !== 'undefined') {
2517
- resizeObserver = new ResizeObserver((entries) => {
2518
- // 使用防抖,避免频繁触发
2519
- if (resizeDebounceTimer) {
2520
- clearTimeout(resizeDebounceTimer);
2521
- }
2522
- resizeDebounceTimer = setTimeout(() => {
2523
- // 使用 entries 参数立即获取新尺寸,避免延迟
2524
- for (const entry of entries) {
2525
- // 立即响应尺寸变化,避免过渡期间露出底色
2526
- handleContainerResize();
2527
- }
2528
- }, 100); // 100ms 防抖,避免频繁触发
2529
- });
2530
- resizeObserver.observe(containerRef.value);
2531
- } else {
2532
- // 降级方案:监听窗口大小变化
2533
- window.addEventListener('resize', handleContainerResize);
2534
- }
2535
- });
2536
2119
  });
2537
2120
 
2538
2121
  /**
@@ -2547,20 +2130,6 @@ onBeforeUnmount(() => {
2547
2130
  clearTimeout(scrollPagingTimer);
2548
2131
  scrollPagingTimer = null;
2549
2132
  }
2550
- if (resizeTimer) {
2551
- clearTimeout(resizeTimer);
2552
- resizeTimer = null;
2553
- }
2554
- if (resizeDebounceTimer) {
2555
- clearTimeout(resizeDebounceTimer);
2556
- resizeDebounceTimer = null;
2557
- }
2558
- if (resizeObserver) {
2559
- resizeObserver.disconnect();
2560
- resizeObserver = null;
2561
- }
2562
- // 移除窗口 resize 监听器(降级方案)
2563
- window.removeEventListener('resize', handleContainerResize);
2564
2133
  });
2565
2134
 
2566
2135
  defineExpose({
@@ -2569,7 +2138,6 @@ defineExpose({
2569
2138
  goToPage: switchToPage, // 暴露翻页方法给父组件
2570
2139
  getCurrentPage: () => currentPage.value, // 获取当前页码
2571
2140
  getTotalPages: () => totalPages.value, // 获取总页数
2572
- getContainer: () => containerRef.value, // 暴露容器引用,用于同步滚动
2573
2141
  });
2574
2142
  </script>
2575
2143
 
@@ -2588,47 +2156,6 @@ defineExpose({
2588
2156
  overflow: auto;
2589
2157
  }
2590
2158
 
2591
- // 自适应宽度计算 Loading
2592
- .auto-fit-loading {
2593
- position: absolute;
2594
- top: 50%;
2595
- left: 50%;
2596
- transform: translate(-50%, -50%);
2597
- z-index: 1000;
2598
- display: flex;
2599
- flex-direction: column;
2600
- align-items: center;
2601
- gap: 12px;
2602
- padding: 20px 30px;
2603
- }
2604
-
2605
- .loading-spinner {
2606
- width: 32px;
2607
- height: 32px;
2608
- border: 3px solid #e5e7eb;
2609
- border-top-color: #1890ff;
2610
- border-radius: 50%;
2611
- animation: spin 0.8s linear infinite;
2612
- }
2613
-
2614
- @keyframes spin {
2615
- to {
2616
- transform: rotate(360deg);
2617
- }
2618
- }
2619
-
2620
- .loading-text {
2621
- font-size: 14px;
2622
- color: #666;
2623
- white-space: nowrap;
2624
- }
2625
-
2626
- // 图片隐藏状态(自适应宽度计算完成前)
2627
- // 使用 display: none 确保图片完全不可见,不会在加载过程中显示
2628
- .image-wrapper-container.image-hidden {
2629
- display: none !important;
2630
- }
2631
-
2632
2159
  // 页码信息样式
2633
2160
  .page-info {
2634
2161
  display: inline-flex;
@@ -2681,8 +2208,6 @@ defineExpose({
2681
2208
  margin: 0;
2682
2209
  padding: 0;
2683
2210
  line-height: 0;
2684
- // 添加平滑过渡,避免切换时露出底色
2685
- transition: transform 0.3s ease;
2686
2211
 
2687
2212
  img {
2688
2213
  display: block; // 移除图片底部默认间隙