Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat(webui): improve page range dragging and add range panning

myhloli9881ceb2824b
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 1385cf3f..bef942a2 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -483,7 +483,7 @@ def build_gradio_app(
# 用 JSON 文本承载前端状态,保持现有事件输入契约。
page_metadata = gr.Textbox(value="{}", visible=False)
page_selection = gr.Textbox(value="{}", visible=False)
- # 通过子 HTML 的明确状态控制显隐,保留原生滑块的交互状态。
+ # 摘要控制显隐,选页组件本地预览手势并在松手时原子提交两端。
with gr.Column(min_width=0, elem_classes=["mineru-kit-page-range"]):
page_summary = gr.HTML(value="", elem_classes=["mineru-page-summary"])
with gr.Row(elem_classes=["mineru-page-inputs"]):
@@ -517,30 +517,19 @@ def build_gradio_app(
min_width=0,
elem_classes=["mineru-page-preset"],
)
- with gr.Row(elem_classes=["mineru-page-sliders"]):
- page_handle_a = gr.Slider(
- minimum=1,
- # 新版 Gradio 拒绝零跨度,单页与空状态仍保持禁用和值为 1。
- maximum=2,
- value=1,
- step=1,
- precision=0,
- label=i18n("mineru.start_page"),
- interactive=False,
- container=False,
- elem_classes=["mineru-page-handle-a"],
- )
- page_handle_b = gr.Slider(
- minimum=1,
- maximum=2,
- value=1,
- step=1,
- precision=0,
- label=i18n("mineru.end_page"),
- interactive=False,
- container=False,
- elem_classes=["mineru-page-handle-b"],
- )
+ page_control = gr.HTML(
+ value="{}",
+ html_template=_resource_text("gradio_page_control.html"),
+ js_on_load=(
+ "("
+ + _resource_text("gradio_page_control.js").replace(
+ "__MINERU_PAGE_RANGE_MODEL__", _resource_text("gradio_page_range_model.js")
+ )
+ + f")({{element, props, trigger, watch, maxPages: {json.dumps(max_pages)}}})"
+ ),
+ apply_default_css=False,
+ elem_classes=["mineru-page-control"],
+ )
page_notice = gr.HTML(value="", visible=False, elem_classes=["mineru-page-notice"])
with gr.Row(elem_classes=["mineru-actions"]):
convert_button = gr.Button(
@@ -933,16 +922,14 @@ def build_gradio_app(
tier_control,
page_metadata,
page_selection,
- page_handle_a,
- page_handle_b,
+ page_control,
tier_selection,
source_ready,
page_start,
page_end,
]
range_outputs = [
- page_handle_a,
- page_handle_b,
+ page_control,
page_summary,
page_range,
page_selection,
@@ -955,15 +942,16 @@ def build_gradio_app(
page_end,
page_preset,
]
- range_script = _resource_text("gradio_page_range.js")
+ range_script = _resource_text("gradio_page_range.js").replace(
+ "__MINERU_PAGE_RANGE_MODEL__", _resource_text("gradio_page_range_model.js")
+ )
# 共用一个 always_last 事件流,避免文件、元数据、清除与拖动的并行回调互相覆盖。
gr.on(
triggers=[
input_file.change,
tier_control.input,
page_metadata.change,
- page_handle_a.input,
- page_handle_b.input,
+ page_control.input,
source_ready.change,
page_start.submit,
page_start.blur,
diff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.css
index 2105061b..6cefae66 100644
--- a/mineru/resources/gradio_app.css
+++ b/mineru/resources/gradio_app.css
@@ -55,7 +55,7 @@ body.dark .gradio-container {
padding: 0 !important;
gap: 0 !important;
}
-/* 两个原生 range 共用同一条轨道;仅滑块接收指针,保留原生键盘交互。 */
+/* 两端共用本地交互轨道,透明热区扩大到 44px,原生 range 保留键盘与读屏语义。 */
.mineru-kit-page-range {
--page-accent: #316ede; --page-bg: #fff; --page-text: #25252a; --page-muted: #72727c;
--page-border: #e0e1e6; --page-track: #e8e9ef; --page-hover: #edf0f6;
@@ -115,7 +115,12 @@ body.dark .gradio-container {
}
.mineru-kit-page-range .mineru-page-preset:hover:not(:disabled) { background: var(--page-hover) !important; }
.mineru-page-preset:disabled, .mineru-page-number input:disabled { opacity: .6; }
-.mineru-page-sliders { position: relative !important; height: 48px; min-height: 48px !important; gap: 0 !important; margin-top: 7px; }
+.mineru-page-control { padding: 0 !important; border: 0 !important; overflow: visible !important; }
+.mineru-page-control .html-container { padding: 0 !important; }
+.mineru-page-sliders {
+ position: relative; height: 48px; min-height: 48px; margin-top: 7px;
+ touch-action: pan-y; user-select: none; cursor: pointer;
+}
.mineru-page-sliders::before {
content: ""; position: absolute; left: 14px; right: 14px; top: 17px; height: 14px; border-radius: 99px;
background: linear-gradient(to right,
@@ -123,34 +128,32 @@ body.dark .gradio-container {
var(--page-accent) var(--range-start, 0%), var(--page-accent) var(--range-end, 100%),
var(--page-track) var(--range-end, 100%));
}
-.mineru-page-sliders > .form { position: static !important; }
-.mineru-page-handle-a, .mineru-page-handle-b {
- position: absolute !important; inset: 0; width: 100% !important; min-width: 0 !important;
- padding: 0 !important; border: 0 !important; background: transparent !important; pointer-events: none;
-}
-.mineru-page-handle-a .head, .mineru-page-handle-b .head,
-.mineru-page-sliders .min_value, .mineru-page-sliders .max_value { display: none !important; }
+.mineru-page-handle-a, .mineru-page-handle-b { position: absolute; inset: 0; pointer-events: none; }
.mineru-page-sliders input[type="range"] {
position: absolute; inset: 0; width: 100%; height: 48px; padding: 0; margin: 0;
- appearance: none; pointer-events: none; background: transparent !important;
-}
-.mineru-page-sliders input[type="range"]::-webkit-slider-runnable-track { height: 14px; background: transparent !important; }
-.mineru-page-sliders input[type="range"]::-moz-range-track,
-.mineru-page-sliders input[type="range"]::-moz-range-progress { height: 14px; background: transparent !important; }
-.mineru-page-sliders input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none; pointer-events: auto; width: 28px; height: 28px; margin-top: -7px;
- border: 0; border-radius: 50%; background: radial-gradient(circle, var(--page-accent) 0 3px, #fff 3.5px);
- box-shadow: 0 2px 7px #00000020; cursor: grab;
-}
-.mineru-page-sliders input[type="range"]::-moz-range-thumb {
- pointer-events: auto; width: 28px; height: 28px; border: 0; border-radius: 50%;
- background: radial-gradient(circle, var(--page-accent) 0 3px, #fff 3.5px); box-shadow: 0 2px 7px #00000020; cursor: grab;
-}
-.mineru-page-sliders input[type="range"]:disabled::-webkit-slider-thumb { pointer-events: none; }
-.mineru-page-sliders input[type="range"]:disabled::-moz-range-thumb { pointer-events: none; }
-.mineru-page-handle-a { z-index: 2; }
-.mineru-page-handle-b { z-index: 3; }
-.mineru-page-handle-a:focus-within, .mineru-page-handle-b:focus-within { z-index: 4; }
+ opacity: 0; pointer-events: none;
+}
+.mineru-page-thumb {
+ position: absolute; left: calc(14px + (100% - 28px) * var(--page-position, 0)); top: 10px;
+ width: 28px; height: 28px; transform: translateX(-50%); border-radius: 50%;
+ background: radial-gradient(circle, var(--page-accent) 0 3px, #fff 3.5px);
+ box-shadow: 0 2px 7px #00000020; transition: box-shadow .12s ease, scale .12s ease;
+}
+.mineru-page-sliders[data-keyboard="true"] input:focus-visible + .mineru-page-thumb {
+ outline: 2px solid var(--page-accent); outline-offset: 3px;
+}
+.mineru-page-sliders[data-active="a"] .mineru-page-handle-a,
+.mineru-page-sliders[data-active="b"] .mineru-page-handle-b { z-index: 2; }
+.mineru-page-sliders[data-active="a"] .mineru-page-handle-a .mineru-page-thumb,
+.mineru-page-sliders[data-active="b"] .mineru-page-handle-b .mineru-page-thumb,
+.mineru-page-sliders[data-active="pan"] .mineru-page-thumb,
+.mineru-page-sliders[data-active="pending"] .mineru-page-thumb {
+ box-shadow: 0 0 0 5px color-mix(in srgb, var(--page-accent) 14%, transparent), 0 3px 8px #00000025;
+}
+.mineru-page-sliders[data-hover="pan"], .mineru-page-sliders[data-hover="a"],
+.mineru-page-sliders[data-hover="b"], .mineru-page-sliders[data-hover="pending"] { cursor: grab; }
+.mineru-page-sliders[data-active]:not([data-active=""]) { cursor: grabbing; }
+.mineru-page-sliders[data-disabled="true"] { cursor: default; }
@media (pointer: coarse) {
.mineru-page-number label { min-height: 44px; }
.mineru-kit-page-range .mineru-page-number input { width: 40px !important; height: 28px; min-height: 28px; font-size: 16px; }
diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.js
index bb6707c7..fa82aa7a 100644
--- a/mineru/resources/gradio_app.js
+++ b/mineru/resources/gradio_app.js
@@ -1,6 +1,6 @@
(viewerEntry) => {
const preview = __MINERU_PDF_PREVIEW__;
- const APP_SCRIPT_VERSION = "v9-page-capsule";
+ const APP_SCRIPT_VERSION = "v10-page-gestures";
if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {
preview("setup", viewerEntry);
return;
@@ -50,27 +50,12 @@
});
};
- // 原生 range 的值更新后重画共用轨道,不修改组件值或触发额外事件。
- const refreshPageRangeTrack = () => {
- const track = document.querySelector(".mineru-page-sliders");
- const handleA = track?.querySelector('.mineru-page-handle-a input[type="range"]');
- const handleB = track?.querySelector('.mineru-page-handle-b input[type="range"]');
- if (!handleA || !handleB) {
- return;
- }
- const span = Math.max(1, Number(handleA.max) - 1);
- const start = Math.min(Number(handleA.value), Number(handleB.value));
- const end = Math.max(Number(handleA.value), Number(handleB.value));
- track.style.setProperty("--range-start", `${(start - 1) / span * 100}%`);
- track.style.setProperty("--range-end", `${(end - 1) / span * 100}%`);
- };
-
// 自定义 HTML 由 Gradio 动态重绘,统一在 DOM 变更后补本地化和忽略状态。
const refreshMineruCustomHtml = () => {
statusTimer.sync();
localizeMineruCustomText();
applyOfficePreviewNoticePreference();
- refreshPageRangeTrack();
+ window.__mineruPageRange?.localize();
};
refreshMineruCustomHtml();
@@ -84,10 +69,10 @@
attributeFilter: ["title", "aria-label", "data-mineru-i18n-en", "data-mineru-i18n-zh"],
};
const uiObserver = new MutationObserver((mutations) => {
- // 本地计时与排队动画的文字变化无需重新扫描整页,避免递归本地化。
+ // 本地计时、选页预览与排队动画无需重新扫描整页,避免递归本地化。
if (mutations.every(({ target }) => {
const element = target.nodeType === 1 ? target : target.parentElement;
- return element?.closest?.("[data-mineru-local-timer], [data-mineru-local-animation]");
+ return element?.closest?.("[data-mineru-local-timer], [data-mineru-local-animation], [data-mineru-page-live]");
})) {
return;
}
@@ -132,38 +117,4 @@
return;
}
});
-
-
- // 拖动时下一帧读取 Gradio 已同步的值;键盘输入也走同一条路径。
- document.addEventListener("input", (event) => {
- if (event.target instanceof Element && event.target.closest(".mineru-page-sliders")) {
- requestAnimationFrame(refreshPageRangeTrack);
- }
- });
-
- // 优先命中离指针最近的物理滑块;重合时按当前起止角色决定左右半边的命中目标。
- document.addEventListener("pointermove", (event) => {
- if (event.buttons || !(event.target instanceof Element)) {
- return;
- }
- const track = event.target.closest(".mineru-page-sliders");
- const rootA = track?.querySelector(".mineru-page-handle-a");
- const rootB = track?.querySelector(".mineru-page-handle-b");
- const handleA = rootA?.querySelector('input[type="range"]');
- const handleB = rootB?.querySelector('input[type="range"]');
- if (!handleA || !handleB) {
- return;
- }
- const bounds = handleA.getBoundingClientRect();
- const span = Math.max(1, Number(handleA.max) - 1);
- const centerA = bounds.left + 14 + (Number(handleA.value) - 1) / span * (bounds.width - 28);
- const centerB = bounds.left + 14 + (Number(handleB.value) - 1) / span * (bounds.width - 28);
- const startHandle = track.closest(".mineru-kit-page-range")
- ?.querySelector("[data-start-handle]")?.getAttribute("data-start-handle") || "a";
- const preferA = handleA.value === handleB.value
- ? (event.clientX < centerA ? startHandle === "a" : startHandle !== "a")
- : Math.abs(event.clientX - centerA) < Math.abs(event.clientX - centerB);
- rootA.style.zIndex = preferA ? "5" : "2";
- rootB.style.zIndex = preferA ? "2" : "5";
- });
}
diff --git a/mineru/resources/gradio_page_control.html b/mineru/resources/gradio_page_control.html
new file mode 100644
index 00000000..0e43f45d
--- /dev/null
+++ b/mineru/resources/gradio_page_control.html
@@ -0,0 +1,10 @@
+<div class="mineru-page-sliders" data-active="">
+ <div class="mineru-page-handle-a">
+ <input type="range" min="1" max="2" step="1" value="1" disabled aria-label="起始页" />
+ <span class="mineru-page-thumb" aria-hidden="true"></span>
+ </div>
+ <div class="mineru-page-handle-b">
+ <input type="range" min="1" max="2" step="1" value="1" disabled aria-label="结束页" />
+ <span class="mineru-page-thumb" aria-hidden="true"></span>
+ </div>
+</div>
diff --git a/mineru/resources/gradio_page_control.js b/mineru/resources/gradio_page_control.js
new file mode 100644
index 00000000..3a1c6e50
--- /dev/null
+++ b/mineru/resources/gradio_page_control.js
@@ -0,0 +1,176 @@
+// 指针拖动只更新本地外观,松手后通过一个组件值原子提交两端。
+({ element, props, trigger, watch, maxPages }) => {
+ const { move, translate } = (__MINERU_PAGE_RANGE_MODEL__)();
+ const rail = element.querySelector(".mineru-page-sliders");
+ const inputs = ["a", "b"].map(handle => element.querySelector(`.mineru-page-handle-${handle} input`));
+ let committed = JSON.parse(props.value || "{}");
+ let drag = null;
+ let visual = [1, 1];
+ // 词典由应用初始化;组件先挂载时保留已有无障碍标签。
+ const text = (key, values) => window.__mineruI18n?.text(key, values) || "";
+ // 只更新变化的叶节点,不派发 input,不让 Gradio 每帧重建摘要。
+ const setText = (selector, value) => {
+ const node = element.closest(".mineru-kit-page-range")?.querySelector(selector);
+ if (node && value && node.textContent !== value) node.textContent = value;
+ };
+ // 平移只取整一次偏移量,避免两个浮点端点分别舍入后偶发多选一页。
+ const snap = (a, b) => {
+ const count = Math.max(1, committed.page_count || 1);
+ if (drag?.handle === "pan") return translate(...drag.initial, Math.round(a - drag.initial[0]), count);
+ const handle = drag?.handle === "b" ? "b" : "a";
+ return move(Math.round(a), Math.round(b), handle, Math.round(handle === "a" ? a : b), count, maxPages);
+ };
+ // 连续位置负责跟手;数字、无障碍值和页数始终采用整数。
+ const render = (a, b) => {
+ visual = [a, b];
+ const count = committed.page_count || 0;
+ const span = Math.max(1, count - 1);
+ const values = snap(a, b);
+ const start = Math.min(...values);
+ const end = Math.max(...values);
+ const startHandle = a < b ? "a" : b < a ? "b" : committed.start_handle || "a";
+ rail.style.setProperty("--range-start", `${(Math.min(a, b) - 1) / span * 100}%`);
+ rail.style.setProperty("--range-end", `${(Math.max(a, b) - 1) / span * 100}%`);
+ rail.dataset.active = drag?.handle || "";
+ rail.dataset.disabled = String(count < 2);
+ for (const [index, input] of inputs.entries()) {
+ const handle = index === 0 ? "a" : "b";
+ input.parentElement.style.setProperty("--page-position", String((visual[index] - 1) / span));
+ input.max = String(Math.max(2, count));
+ input.value = String(values[index]);
+ input.disabled = count < 2;
+ const label = text(startHandle === handle ? "start_page" : "end_page");
+ if (label && input.getAttribute("aria-label") !== label) input.setAttribute("aria-label", label);
+ }
+ const root = element.closest(".mineru-kit-page-range");
+ for (const [selector, value] of [[".mineru-page-start input", start], [".mineru-page-end input", end]]) {
+ const input = root?.querySelector(selector);
+ if (input && input !== document.activeElement) input.value = String(value);
+ }
+ if (count) {
+ setText(".mineru-page-selected-count", String(end - start + 1));
+ setText(".mineru-page-interval", start === end ? text("page_single", { page: start })
+ : text("page_interval", { start, end }));
+ }
+ };
+ // 取消捕获先清空拖动态,防止 lostpointercapture 二次提交。
+ const release = () => {
+ const previous = drag;
+ drag = null;
+ if (previous && rail.hasPointerCapture(previous.id)) rail.releasePointerCapture(previous.id);
+ };
+ // 取消、窗口失焦和文件切换恢复最后的正式范围,不提交半途选择。
+ const cancel = () => {
+ release();
+ render(committed.handle_a || 1, committed.handle_b || 1);
+ };
+ // 一次 input 携带完整范围,整段平移不能拆成两个可能相互覆盖的事件。
+ const commit = () => {
+ const [a, b] = snap(...visual);
+ release();
+ if (a === committed.handle_a && b === committed.handle_b) { render(a, b); return; }
+ committed = { ...committed, handle_a: a, handle_b: b,
+ start_handle: a < b ? "a" : b < a ? "b" : committed.start_handle };
+ render(a, b);
+ props.value = JSON.stringify(committed);
+ trigger("input");
+ };
+ // 外部数字输入、快捷选择及文件切换会同步状态;无关回执不打断手势。
+ const sync = () => {
+ const next = JSON.parse(props.value || "{}");
+ const changed = ["path", "page_count", "handle_a", "handle_b", "start_handle"]
+ .some(key => next[key] !== committed[key]);
+ committed = next;
+ if (changed) release();
+ if (!drag) render(committed.handle_a || 1, committed.handle_b || 1);
+ };
+ // 中段只在端点命中区之外启用;接近或重合时优先保留端点的可抓取性。
+ const hit = (x, bounds) => {
+ const span = Math.max(1, committed.page_count - 1);
+ const centers = visual.map(value => bounds.left + 14 + (value - 1) / span * (bounds.width - 28));
+ const distances = centers.map(center => Math.abs(x - center));
+ if (Math.abs(centers[0] - centers[1]) < 1 && Math.min(...distances) <= 22) return "pending";
+ if (Math.min(...distances) <= 22) return distances[0] <= distances[1] ? "a" : "b";
+ if (x > Math.min(...centers) && x < Math.max(...centers)) return "pan";
+ return distances[0] <= distances[1] ? "a" : "b";
+ };
+ // 同一指针保持物理端点身份;重合时由第一次有效移动方向决定起止端。
+ const preview = event => {
+ if (!drag || event.pointerId !== drag.id) return;
+ const delta = (event.clientX - drag.x) / drag.width * (committed.page_count - 1);
+ if (drag.handle === "pending") {
+ if (Math.abs(event.clientX - drag.x) < 2) return;
+ const start = committed.start_handle || "a";
+ drag.handle = delta < 0 ? start : start === "a" ? "b" : "a";
+ inputs[drag.handle === "a" ? 0 : 1].focus({ preventScroll: true });
+ }
+ if (drag.handle === "pan") render(...translate(...drag.initial, delta, committed.page_count));
+ else {
+ const index = drag.handle === "a" ? 0 : 1;
+ render(...move(...visual, drag.handle, drag.initial[index] + delta, committed.page_count, maxPages));
+ }
+ };
+ rail.addEventListener("pointerdown", event => {
+ if (event.button !== 0 || event.isPrimary === false || drag || (committed.page_count || 0) < 2) return;
+ event.preventDefault();
+ rail.dataset.keyboard = "false";
+ const bounds = rail.getBoundingClientRect();
+ const handle = hit(event.clientX, bounds);
+ const width = Math.max(1, bounds.width - 28);
+ drag = { id: event.pointerId, x: event.clientX, width, handle, initial: [...visual] };
+ rail.setPointerCapture(event.pointerId);
+ if (handle === "a" || handle === "b") {
+ const index = handle === "a" ? 0 : 1;
+ const center = bounds.left + 14 + (visual[index] - 1) / (committed.page_count - 1) * width;
+ // 命中透明热区时不跳动;点击轨道空白处才直接定位最近端点。
+ if (Math.abs(event.clientX - center) > 22) {
+ render(...move(...visual, handle, 1 + (event.clientX - bounds.left - 14) / width
+ * (committed.page_count - 1), committed.page_count, maxPages));
+ drag.initial = [...visual];
+ }
+ inputs[index].focus({ preventScroll: true });
+ } else {
+ inputs[committed.start_handle === "b" ? 1 : 0].focus({ preventScroll: true });
+ }
+ render(...visual);
+ });
+ rail.addEventListener("pointermove", event => {
+ if (drag) { preview(event); return; }
+ if (committed.page_count > 1) rail.dataset.hover = hit(event.clientX, rail.getBoundingClientRect());
+ });
+ rail.addEventListener("pointerleave", () => { delete rail.dataset.hover; });
+ rail.addEventListener("pointerup", event => {
+ if (!drag || event.pointerId !== drag.id) return;
+ preview(event);
+ commit();
+ });
+ rail.addEventListener("pointercancel", event => { if (drag?.id === event.pointerId) cancel(); });
+ rail.addEventListener("lostpointercapture", event => { if (drag?.id === event.pointerId) cancel(); });
+ // 原生 range 保留焦点和读屏语义;方向键逐页、Home/End 到文档边界。
+ for (const [index, input] of inputs.entries()) {
+ // 指针聚焦不保留键盘焦点环;Tab 进入时仍给出清晰的焦点提示。
+ input.addEventListener("focus", () => { rail.dataset.keyboard = String(!drag); });
+ input.addEventListener("keydown", event => {
+ if (event.key === "Escape") { if (drag) { event.preventDefault(); cancel(); } return; }
+ if (input.disabled || drag) return;
+ const value = Math.round(visual[index]);
+ const keys = { ArrowLeft: value - 1, ArrowDown: value - 1, ArrowRight: value + 1,
+ ArrowUp: value + 1, Home: 1, End: committed.page_count, PageDown: value - 10, PageUp: value + 10 };
+ if (!Object.hasOwn(keys, event.key)) return;
+ event.preventDefault();
+ rail.dataset.keyboard = "true";
+ render(...move(...visual, index === 0 ? "a" : "b", keys[event.key], committed.page_count, maxPages));
+ commit();
+ });
+ // 辅助技术直接修改原生值时也经过相同的限制和原子提交。
+ input.addEventListener("input", () => {
+ if (drag || input.disabled) return;
+ render(...move(...visual, index === 0 ? "a" : "b", Number(input.value), committed.page_count, maxPages));
+ commit();
+ });
+ }
+ window.addEventListener("blur", cancel);
+ watch(["value"], sync);
+ window.__mineruPageRange = { localize: sync };
+ sync();
+}
diff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.js
index c9a50673..0d2f76e6 100644
--- a/mineru/resources/gradio_page_range.js
+++ b/mineru/resources/gradio_page_range.js
@@ -1,4 +1,4 @@
-(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, handleAValue, handleBValue, tierSelection, sourceReady,
+(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, selection, tierSelection, sourceReady,
startValue = null, endValue = null, preset = false) => {
// 纯前端状态转换:经原生组件事件读写值,不逐次向 Python 发送拖动请求。
// 内部元数据使用 JSON 文本,避免不同 Gradio 版本的 JSON 组件封装差异。
@@ -6,6 +6,8 @@
metadata = JSON.parse(metadata || "{}");
previous = JSON.parse(previous || "{}");
tierSelection = JSON.parse(tierSelection);
+ selection = JSON.parse(selection || "{}");
+ const { clamp, move } = (__MINERU_PAGE_RANGE_MODEL__)();
// 统一构造原生组件的局部更新,未指定属性保持不变。
const update = (props = {}) => ({ __type__: "update", ...props });
// 页数读取错误只作为普通文本显示,禁止把异常内容解释为 HTML。
@@ -39,27 +41,23 @@
const count = state.page_count || 0;
if (count > 0 && !fileChanged && !initialized) {
- // 物理滑块只受文档边界约束;交叉时不交换组件值,保持鼠标和焦点所在的实体。
- const clamp = (value) => Math.min(count, Math.max(1, Math.round(value)));
- // 超限时把另一滑块推到拖动端附近,方向由实际位置而不是起止角色决定。
- const linkedPosition = (active, other) => maxPages !== null && Math.abs(active - other) + 1 > maxPages
- ? active + Math.sign(other - active) * (maxPages - 1)
- : other;
// 数字输入和滑块复用同一端点更新;交叉后仍以当前语义角色定位物理滑块。
const moveHandle = (handle, value) => {
- const active = `handle_${handle}`;
- const other = handle === "a" ? "handle_b" : "handle_a";
- state[active] = clamp(value);
- state[other] = linkedPosition(state[active], state[other]);
+ [state.handle_a, state.handle_b] = move(
+ state.handle_a, state.handle_b, handle, Math.round(value), count, maxPages
+ );
};
if (preset) {
state.handle_a = 1;
state.handle_b = Math.min(count, maxPages ?? count);
state.start_handle = "a";
- } else if (Number.isFinite(handleAValue) && handleAValue !== state.handle_a) {
- moveHandle("a", handleAValue);
- } else if (Number.isFinite(handleBValue) && handleBValue !== state.handle_b) {
- moveHandle("b", handleBValue);
+ } else if (selection.path === path && selection.page_count === count
+ && Number.isFinite(selection.handle_a) && Number.isFinite(selection.handle_b)
+ && (selection.handle_a !== state.handle_a || selection.handle_b !== state.handle_b)) {
+ // 整段平移必须接收同一提交中的两端;旧文件手势和越界输入不能污染新状态。
+ state.handle_a = clamp(Math.round(selection.handle_a), count);
+ state.handle_b = clamp(Math.round(selection.handle_b), count);
+ moveHandle("a", state.handle_a);
} else if (Number.isFinite(startValue) && startValue !== Math.min(state.handle_a, state.handle_b)) {
moveHandle(state.start_handle, startValue);
} else if (Number.isFinite(endValue) && endValue !== Math.max(state.handle_a, state.handle_b)) {
@@ -80,7 +78,7 @@
const end = Math.max(state.handle_a, state.handle_b);
const selected = end - start + 1;
const limitText = maxPages === null ? text("page_unlimited") : text("page_limit", { count: maxPages });
- const selectionText = `<span class="mineru-page-selected-count">${count ? selected : "–"}</span> / `
+ const selectionText = `<span class="mineru-page-selected-count" data-mineru-page-live>${count ? selected : "–"}</span> / `
+ text("page_count", { count: count || "–" });
const intervalText = count ? (start === end ? text("page_single", { page: start }) : text("page_interval", { start, end }))
: text(state.error ? "page_read_failed_short" : "reading_pages");
@@ -89,17 +87,14 @@
+ `<span class="mineru-page-limit" title="${escapeHtml(limitText)}">${limitText}</span></span>`
+ `<span class="mineru-page-selection">${selectionText}</span>`
+ `</div>`
- + `<div class="mineru-page-axis"><span>1</span><span class="mineru-page-interval" aria-live="polite">${intervalText}</span>`
+ + `<div class="mineru-page-axis"><span>1</span><span class="mineru-page-interval" data-mineru-page-live>${intervalText}</span>`
+ `<span>${count || "–"}</span></div>`;
const notice = needsRange && !count ? message(state.error) : "";
const range = count ? (start === end ? String(start) : `${start}-${end}`) : "";
- // 新版 Gradio 要求非零跨度;单页时禁用滑块,实际页数和提交范围仍为 1。
- const slider = (value, label) => update({ minimum: 1, maximum: Math.max(2, count), value, interactive, label });
// 数字框确认输入时夹紧到真实页数;单页保持可见但不可编辑。
const number = (value, label) => update({ minimum: 1, maximum: Math.max(1, count), value, interactive, label });
return [
- slider(state.handle_a, state.start_handle === "a" ? text("start_page") : text("end_page")),
- slider(state.handle_b, state.start_handle === "b" ? text("start_page") : text("end_page")),
+ update({ value: JSON.stringify(state) }),
summary, range, JSON.stringify(state),
update({ interactive: Boolean(path) && sourceReady === path && (!needsRange || count > 0) }),
update({ value: escapeHtml(notice), visible: Boolean(notice) }),
diff --git a/mineru/resources/gradio_page_range_model.js b/mineru/resources/gradio_page_range_model.js
new file mode 100644
index 00000000..0c9dfe49
--- /dev/null
+++ b/mineru/resources/gradio_page_range_model.js
@@ -0,0 +1,19 @@
+// 拖动预览与正式提交共用边界算法,物理端点交叉时不交换身份。
+() => {
+ // 连续坐标只限制文档边界,取整由提交入口统一完成。
+ const clamp = (value, count) => Math.max(1, Math.min(count, value));
+ // 超出页数上限时同步推移另一端,保留当前拖动端的跟手位置。
+ const move = (a, b, handle, value, count, limit) => {
+ const active = clamp(value, count);
+ let other = handle === "a" ? b : a;
+ const distance = (limit ?? count) - 1;
+ if (Math.abs(active - other) > distance) other = active + Math.sign(other - active) * distance;
+ return handle === "a" ? [active, other] : [other, active];
+ };
+ // 整段移动共用一个偏移量,到达文档边界时保持选区长度。
+ const translate = (a, b, delta, count) => {
+ const offset = Math.max(1 - Math.min(a, b), Math.min(count - Math.max(a, b), delta));
+ return [a + offset, b + offset];
+ };
+ return { clamp, move, translate };
+}
diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.py
index a9fcd287..51462829 100644
--- a/tests/unittest/test_kit_gradio.py
+++ b/tests/unittest/test_kit_gradio.py
@@ -1239,8 +1239,8 @@ def test_gradio_tier_slider_uses_available_tiers_and_preserves_selection(
assert label_event["backend_fn"] is False
assert label_event["queue"] is False
assert label_event["trigger_mode"] == "always_last"
- assert label_event["outputs"][7:9] == [slider._id, label._id]
- preference = demo.blocks[label_event["outputs"][9]]
+ assert label_event["outputs"][6:8] == [slider._id, label._id]
+ preference = demo.blocks[label_event["outputs"][8]]
assert preference.visible is False
assert json.loads(preference.value) == {"tier": default_tier, "locked": False}
assert preference._id in label_event["inputs"]
diff --git a/tests/unittest/test_kit_gradio_i18n.cjs b/tests/unittest/test_kit_gradio_i18n.cjs
index 8051eabc..29ed0119 100644
--- a/tests/unittest/test_kit_gradio_i18n.cjs
+++ b/tests/unittest/test_kit_gradio_i18n.cjs
@@ -15,25 +15,25 @@ for (const [languages, language, expected] of [
assert.equal(i18n.resolveLocale(), expected);
assert.equal(i18n.text("force_ocr_info"), messages.force_ocr_info[expected === "zh" ? 1 : 0]);
assert.ok(i18n.text("failed", { error: "$& 文件.pdf" }).includes("$& 文件.pdf"));
- const range = vm.runInContext(resource("gradio_page_range.js"), context);
+ const range = vm.runInContext(resource("gradio_page_range.js")
+ .replace("__MINERU_PAGE_RANGE_MODEL__", resource("gradio_page_range_model.js")), context);
const out = range(["flash", "standard"], ["csv"], 20, "/test.pdf", 1,
- JSON.stringify({ path: "/test.pdf", page_count: 10 }), "{}", 1, 1,
+ JSON.stringify({ path: "/test.pdf", page_count: 10 }), "{}", "{}",
JSON.stringify({ tier: "standard", locked: false }));
- assert.equal(out[0].label, i18n.text("start_page"));
- assert.equal(out[3], "1-10");
- assert.ok(out[2].includes(i18n.text("page_limit", { count: 20 })));
- assert.equal(out[8].props.selected_tier, "standard");
- assert.equal(out[8].props.locked, false);
- assert.ok(!out[2].includes("<strong>"));
- assert.ok(!out[2].includes(i18n.text("start_page")));
- assert.ok(!out[2].includes(i18n.text("end_page")));
+ assert.equal(out[2], "1-10");
+ assert.ok(out[1].includes(i18n.text("page_limit", { count: 20 })));
+ assert.equal(out[7].props.selected_tier, "standard");
+ assert.equal(out[7].props.locked, false);
+ assert.ok(!out[1].includes("<strong>"));
+ assert.ok(!out[1].includes(i18n.text("start_page")));
+ assert.ok(!out[1].includes(i18n.text("end_page")));
for (const [position, tier] of ["flash", "basic", "standard", "advanced"].entries()) {
const labels = expected === "zh"
? ["flash · 极速", "basic · 中", "standard · 高", "advanced · 极高"]
: ["flash", "basic · medium", "standard · high", "advanced · xhigh"];
const result = range(["flash", "basic", "standard", "advanced"], ["csv"], null, null, position,
- "{}", "{}", 1, 1, JSON.stringify({ tier, locked: false }));
- assert.equal(result[8].props.selected_tier, tier);
+ "{}", "{}", "{}", JSON.stringify({ tier, locked: false }));
+ assert.equal(result[7].props.selected_tier, tier);
assert.equal(i18n.text(`tier_compact_${tier}`), labels[position]);
}
const download = vm.runInContext(resource("gradio_download.js"), context);
diff --git a/tests/unittest/test_kit_gradio_page_control.cjs b/tests/unittest/test_kit_gradio_page_control.cjs
new file mode 100644
index 00000000..8cb98dea
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_page_control.cjs
@@ -0,0 +1,191 @@
+// 执行真实手势控制器,检查提交次数、捕获生命周期和连续位置,不复制生产算法。
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+// 从资源文件加载同一份控制器及共享约束。
+const resource = name => fs.readFileSync(path.join(__dirname, "../../mineru/resources", name), "utf8");
+const script = resource("gradio_page_control.js").replace("__MINERU_PAGE_RANGE_MODEL__", resource("gradio_page_range_model.js"));
+
+// 最小 DOM 仅记录浏览器 API 的输入输出,事件回调由生产控制器注册。
+function node() {
+ return {
+ dataset: {}, events: {}, attrs: {}, value: "1", disabled: false,
+ style: { values: {},
+ // 记录连续位置,检查拖动时不会提前吸附整数。
+ setProperty(key, value) { this.values[key] = value; } },
+ // 保留无障碍名称以验证交叉后的语义。
+ setAttribute(key, value) { this.attrs[key] = value; },
+ // 读取旧名称,确保未变化时不产生多余 DOM 属性更新。
+ getAttribute(key) { return this.attrs[key]; },
+ // 同一元素只为每种测试事件安装一个控制器回调。
+ addEventListener(name, callback) { this.events[name] = callback; },
+ // 轨道有效宽度 470px,每页正好对应 10px。
+ getBoundingClientRect() { return { left: 0, width: 498 }; },
+ // 记录并检查捕获归属,不模拟原生拖动算法。
+ setPointerCapture(id) { this.capture = id; },
+ // 只允许当前捕获指针释放控制权。
+ hasPointerCapture(id) { return this.capture === id; },
+ // 记录已释放,供取消和换文件断言。
+ releasePointerCapture() { this.capture = null; },
+ // 测试焦点不触发额外的 Gradio 提交。
+ focus() {},
+ };
+}
+
+// 每个实例保存独立 props、回执和输入节点,便于重放文件切换竞态。
+function setup(a = 1, b = 20, count = 48, limit = 20) {
+ const rail = node();
+ const inputs = [node(), node()];
+ inputs.forEach(input => { input.parentElement = node(); });
+ const leaves = Object.fromEntries([".mineru-page-start input", ".mineru-page-end input", ".mineru-page-selected-count",
+ ".mineru-page-interval"].map(key => [key, node()]));
+ const props = { value: JSON.stringify({ path: "/test.pdf", page_count: count, handle_a: a, handle_b: b,
+ start_handle: a <= b ? "a" : "b" }) };
+ const submissions = [];
+ const window = { events: {}, __mineruI18n: { text: (key, values) => key + JSON.stringify(values || {}) },
+ // 窗口失焦必须恢复正式值。
+ addEventListener(name, callback) { this.events[name] = callback; } };
+ let watcher;
+ vm.runInNewContext(`(${script})`, { window, document: {} })({
+ element: {
+ // 数字和摘要位于选页组件共同的父容器。
+ closest() { return { querySelector: key => leaves[key] }; },
+ querySelector: selector => selector === ".mineru-page-sliders" ? rail
+ : inputs[selector.includes("-a ") ? 0 : 1],
+ },
+ props, maxPages: limit,
+ trigger: event => submissions.push({ event, state: JSON.parse(props.value) }),
+ watch: (_keys, callback) => { watcher = callback; },
+ });
+ return { rail, inputs, props, submissions, leaves, window,
+ // 按页坐标重放真实指针事件,可额外指定取消与多指属性。
+ pointer(type, page, patch = {}) {
+ rail.events[type]({ button: 0, pointerId: 7, isPrimary: true, clientX: 14 + (page - 1) * 10,
+ preventDefault() {}, ...patch });
+ },
+ // 输入回执沿用同一实例,确认相同状态不会打断拖动。
+ update(patch) { props.value = JSON.stringify({ ...JSON.parse(props.value), ...patch }); watcher(); },
+ // 原生键盘入口沿用相同的边界与提交逻辑。
+ key(index, key) { inputs[index].events.keydown({ key, preventDefault() {} }); },
+ // 返回当前可见整数值,连续位置另由 CSS 变量验证。
+ values() { return inputs.map(input => Number(input.value)); },
+ };
+}
+
+let ui = setup();
+ui.pointer("pointerdown", 20);
+ui.pointer("pointermove", 30.4);
+assert.deepEqual(ui.values(), [11, 30]);
+assert.equal(ui.submissions.length, 0);
+assert.equal(JSON.parse(ui.props.value).handle_b, 20);
+assert(Math.abs(Number(ui.inputs[1].parentElement.style.values["--page-position"]) - 29.4 / 47) < 1e-10);
+ui.update({});
+assert.deepEqual(ui.values(), [11, 30]);
+ui.pointer("pointerup", 30.4);
+assert.equal(ui.submissions.length, 1);
+assert.deepEqual([ui.submissions[0].state.handle_a, ui.submissions[0].state.handle_b], [11, 30]);
+assert.equal(ui.rail.capture, null);
+
+// 中段原子平移,正反方向在边界处保持 20 页;越过边界后回移仍以按下点为基准。
+ui.pointer("pointerdown", 20);
+assert.equal(ui.rail.dataset.active, "pan");
+ui.pointer("pointermove", 30);
+assert.deepEqual(ui.values(), [21, 40]);
+ui.pointer("pointermove", 90);
+assert.deepEqual(ui.values(), [29, 48]);
+ui.pointer("pointermove", -90);
+assert.deepEqual(ui.values(), [1, 20]);
+ui.pointer("pointerup", 30);
+assert.deepEqual(ui.values(), [21, 40]);
+assert.equal(ui.submissions.length, 2);
+ui = setup(30, 11);
+ui.pointer("pointerdown", 20);
+ui.pointer("pointerup", 30);
+assert.deepEqual(ui.values(), [40, 21]);
+assert.equal(ui.submissions[0].state.start_handle, "b");
+
+// 半页附近的浮点舍入误差不能让平移临时多选一页。
+ui = setup();
+ui.pointer("pointerdown", 10);
+ui.pointer("pointermove", 10.5 - Number.EPSILON * 4);
+assert.equal(ui.values()[1] - ui.values()[0] + 1, 20);
+ui.pointer("pointerup", 10.5 - Number.EPSILON * 4);
+const snapped = JSON.parse(ui.props.value);
+assert.equal(snapped.handle_b - snapped.handle_a + 1, 20);
+
+// 透明热区按下不跳动;交叉后继续控制同一个物理端点。
+ui = setup();
+ui.pointer("pointerdown", 2.8);
+assert.deepEqual(ui.values(), [1, 20]);
+ui.pointer("pointermove", 31.8);
+assert.deepEqual(ui.values(), [30, 20]);
+ui.pointer("pointerup", 41.8);
+assert.deepEqual(ui.values(), [40, 21]);
+assert.equal(ui.submissions[0].state.start_handle, "b");
+assert.equal(ui.inputs[0].attrs["aria-label"], "end_page{}");
+
+// 重合端点向左选起点、向右选终点;不足 2px 的点击不改变范围。
+for (const [target, expected] of [[10, [10, 20]], [30, [20, 30]], [20.1, [20, 20]]]) {
+ ui = setup(20, 20);
+ ui.pointer("pointerdown", 20);
+ ui.pointer("pointerup", target);
+ assert.deepEqual(ui.values(), expected);
+}
+
+// 点击未选中的轨道移动最近端点;松手一次提交,多指不会抢占当前手势。
+ui = setup();
+ui.pointer("pointerdown", 35);
+assert.deepEqual(ui.values(), [16, 35]);
+ui.pointer("pointerdown", 48, { pointerId: 8, isPrimary: false });
+ui.pointer("pointermove", 48, { pointerId: 8 });
+ui.pointer("pointerup", 48, { pointerId: 8 });
+assert.deepEqual(ui.values(), [16, 35]);
+ui.pointer("pointerup", 35);
+assert.equal(ui.submissions.length, 1);
+
+// 取消、失去捕获、Escape 和窗口失焦都回滚本地预览,不产生提交。
+for (const reason of ["pointercancel", "lostpointercapture", "Escape", "blur"]) {
+ ui = setup();
+ ui.pointer("pointerdown", 20);
+ ui.pointer("pointermove", 35);
+ if (reason === "Escape") ui.key(1, reason);
+ else if (reason === "blur") ui.window.events.blur();
+ else ui.pointer(reason, 35);
+ ui.pointer("pointerup", 35);
+ assert.deepEqual(ui.values(), [1, 20]);
+ assert.equal(ui.submissions.length, 0);
+}
+
+// 换文件会取消旧捕获,迟到的松手不能把旧范围写入新文档。
+ui = setup();
+ui.pointer("pointerdown", 20);
+ui.pointer("pointermove", 35);
+ui.update({ path: "/new.pdf", page_count: 12, handle_a: 1, handle_b: 12 });
+ui.pointer("pointerup", 35);
+assert.deepEqual(ui.values(), [1, 12]);
+assert.equal(ui.submissions.length, 0);
+ui.key(1, "ArrowLeft");
+assert.deepEqual(ui.values(), [1, 11]);
+assert.equal(ui.submissions.length, 1);
+ui.key(1, "Home");
+assert.deepEqual(ui.values(), [1, 1]);
+ui.key(0, "End");
+assert.deepEqual(ui.values(), [12, 1]);
+
+// 单页禁用;单页上限仍可移动;不设上限时拖动端点不推动另一端。
+ui = setup(1, 1, 1);
+ui.pointer("pointerdown", 20);
+ui.pointer("pointerup", 30);
+ui.key(0, "End");
+assert(ui.inputs.every(input => input.disabled));
+assert.equal(ui.submissions.length, 0);
+ui = setup(1, 1, 48, 1);
+ui.pointer("pointerdown", 1);
+ui.pointer("pointerup", 40);
+assert.deepEqual(ui.values(), [40, 40]);
+ui = setup(1, 48, 48, null);
+ui.pointer("pointerdown", 1);
+ui.pointer("pointerup", 40);
+assert.deepEqual(ui.values(), [40, 48]);
+console.log("Page range gestures passed: preview, atomic commit, pan, crossing, capture, cancel and keyboard.");
diff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjs
index 282e7262..8578bc55 100644
--- a/tests/unittest/test_kit_gradio_page_range.cjs
+++ b/tests/unittest/test_kit_gradio_page_range.cjs
@@ -7,7 +7,10 @@ Object.defineProperty(globalThis, "navigator", { value: { languages: ["zh-CN"] }
global.window = { __mineruI18n: vm.runInThisContext(fs.readFileSync(
path.join(__dirname, "../../mineru/resources/gradio_i18n.js"), "utf8"
))(JSON.parse(fs.readFileSync(0, "utf8"))) };
-const reduce = vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_page_range.js"), "utf8"));
+const modelSource = fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_page_range_model.js"), "utf8");
+const model = vm.runInThisContext(modelSource)();
+const reduce = vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_page_range.js"), "utf8")
+ .replace("__MINERU_PAGE_RANGE_MODEL__", modelSource));
const tiers = ["flash", "basic", "standard", "advanced"];
// 使用 Python 测试传入的统一格式集合,测试和产品代码均不维护另一份后缀清单。
const flashOnlyExtensions = JSON.parse(process.argv[2]);
@@ -24,21 +27,26 @@ function createUi(limit = 20, availableTiers = tiers) {
state,
step(action, patch = {}) {
// 应用本次输入事件,并保留 Gradio update 的跳过语义。
+ if (action === "a" || action === "b") {
+ const [a, b] = model.move(state.a, state.b, action, patch[action], state.previous.page_count, limit);
+ patch = { ...patch, a, b };
+ }
Object.assign(state, patch);
if (action === "clear") state.file = null;
const result = reduce(
availableTiers, flashOnlyExtensions, limit, state.file, state.position,
- JSON.stringify(state.metadata), JSON.stringify(state.previous), state.a, state.b,
+ JSON.stringify(state.metadata), JSON.stringify(state.previous),
+ JSON.stringify({ ...state.previous, handle_a: state.a, handle_b: state.b }),
JSON.stringify(state.tierSelection), (typeof state.file === "string" ? state.file : state.file?.path) || "",
state.start, state.end, action === "preset"
);
- if ("value" in result[0]) state.a = result[0].value;
- if ("value" in result[1]) state.b = result[1].value;
- if (result[4].__type__ !== "update") state.previous = JSON.parse(result[4]);
- if ("value" in result[7]) state.position = result[7].value;
- state.tierSelection = JSON.parse(result[9]);
- state.start = result[10].value;
- state.end = result[11].value;
+ state.a = JSON.parse(result[0].value).handle_a;
+ state.b = JSON.parse(result[0].value).handle_b;
+ if (result[3].__type__ !== "update") state.previous = JSON.parse(result[3]);
+ if ("value" in result[6]) state.position = result[6].value;
+ state.tierSelection = JSON.parse(result[8]);
+ state.start = result[9].value;
+ state.end = result[10].value;
return result;
},
upload(count, filename = "/report.pdf") {
@@ -54,23 +62,23 @@ for (const extension of flashOnlyExtensions.flatMap((extension) => [extension, e
const ui = createUi();
ui.step("tier", { position: 3 });
const out = ui.step("file", { file: { path: `/source.${extension}` } });
- assert.equal(out[7].value, 3);
- assert.equal(out[8].props.locked, true);
- assert.equal(out[7].visible, undefined);
- assert.equal(out[8].props.selected_tier, "flash");
- assert.equal(out[5].interactive, true);
- assert.equal(out[3], "");
- assert.match(out[2], /data-range-visible="false"/);
+ assert.equal(out[6].value, 3);
+ assert.equal(out[7].props.locked, true);
+ assert.equal(out[6].visible, undefined);
+ assert.equal(out[7].props.selected_tier, "flash");
+ assert.equal(out[4].interactive, true);
+ assert.equal(out[2], "");
+ assert.match(out[1], /data-range-visible="false"/);
assert.deepEqual(ui.state.tierSelection, { tier: "advanced", locked: true });
// 即使模拟一个已经排队的高档位 input,也不能改变锁定值或恢复偏好。
- assert.equal(ui.step("tier", { position: 1 })[7].value, 3);
+ assert.equal(ui.step("tier", { position: 1 })[6].value, 3);
ui.step("file", { file: `/another.${extension}` });
assert.equal(ui.state.tierSelection.tier, "advanced");
const cleared = ui.step("clear");
- assert.equal(cleared[7].value, 3);
- assert.equal(cleared[8].props.locked, false);
- assert.equal(cleared[8].props.selected_tier, "advanced");
- assert.equal(cleared[5].interactive, false);
+ assert.equal(cleared[6].value, 3);
+ assert.equal(cleared[7].props.locked, false);
+ assert.equal(cleared[7].props.selected_tier, "advanced");
+ assert.equal(cleared[4].interactive, false);
}
// 切回任意 PDF/图片后在同一次事件恢复档位,PDF 等待页数、图片可立即转换。
@@ -78,10 +86,10 @@ for (const extension of tieredExtensions.flatMap((extension) => [extension, exte
const ui = createUi();
ui.step("file", { file: "/source.csv" });
const out = ui.step("file", { file: { path: `/source.${extension}` } });
- assert.equal(out[7].value, 2);
- assert.equal(out[8].props.locked, false);
- assert.equal(out[8].props.selected_tier, "standard");
- assert.equal(out[5].interactive, extension.toLowerCase() !== "pdf");
+ assert.equal(out[6].value, 2);
+ assert.equal(out[7].props.locked, false);
+ assert.equal(out[7].props.selected_tier, "standard");
+ assert.equal(out[4].interactive, extension.toLowerCase() !== "pdf");
assert.deepEqual(ui.state.tierSelection, { tier: "standard", locked: false });
}
@@ -90,18 +98,18 @@ for (const availableTiers of [["standard"], ["basic", "standard", "advanced"], [
const ui = createUi(20, availableTiers);
const originalPosition = ui.state.position;
const out = ui.step("file", { file: "/source.csv" });
- assert.equal(out[8].props.locked, true);
- assert.equal(out[7].value, originalPosition);
- assert.equal(out[7].visible, undefined);
- assert.equal(out[5].interactive, true);
- assert.equal(out[6].visible, false);
- assert.equal(out[8].props.selected_tier, "flash");
+ assert.equal(out[7].props.locked, true);
+ assert.equal(out[6].value, originalPosition);
+ assert.equal(out[6].visible, undefined);
+ assert.equal(out[4].interactive, true);
+ assert.equal(out[5].visible, false);
+ assert.equal(out[7].props.selected_tier, "flash");
const restored = ui.step("file", { file: "/source.png" });
- assert.equal(restored[7].value, originalPosition);
- assert.equal(restored[8].props.locked, false);
- assert.equal(restored[7].visible, undefined);
- assert.equal(restored[5].interactive, true);
- assert.equal(restored[6].visible, false);
+ assert.equal(restored[6].value, originalPosition);
+ assert.equal(restored[7].props.locked, false);
+ assert.equal(restored[6].visible, undefined);
+ assert.equal(restored[4].interactive, true);
+ assert.equal(restored[5].visible, false);
}
// 文件连续切换与旧 PDF 元数据晚到时,锁定状态和偏好只跟随当前文件。
@@ -114,60 +122,58 @@ for (const availableTiers of [["standard"], ["basic", "standard", "advanced"], [
assert.equal(ui.state.position, 3);
assert.equal(ui.state.tierSelection.tier, "advanced");
let out = ui.step("file", { file: "/new.pdf" });
- assert.equal(out[7].value, 3);
- assert.equal(out[5].interactive, false);
- assert.match(out[2], /data-range-visible="true"/);
- assert.match(out[2], /正在读取/);
- assert.equal(out[3], "");
- assert.equal(out[6].visible, false);
+ assert.equal(out[6].value, 3);
+ assert.equal(out[4].interactive, false);
+ assert.match(out[1], /data-range-visible="true"/);
+ assert.match(out[1], /正在读取/);
+ assert.equal(out[2], "");
+ assert.equal(out[5].visible, false);
out = ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100, error: "" } });
- assert.equal(out[5].interactive, false);
+ assert.equal(out[4].interactive, false);
out = ui.step("metadata", { metadata: { path: "/new.pdf", page_count: 12, error: "" } });
- assert.equal(out[5].interactive, true);
- assert.equal(out[3], "1-12");
+ assert.equal(out[4].interactive, true);
+ assert.equal(out[2], "1-12");
ui.step("tier", { position: 1 });
ui.step("file", { file: "/second.csv" });
- assert.equal(ui.step("clear")[7].value, 1);
+ assert.equal(ui.step("clear")[6].value, 1);
// 会话互不共享偏好。
assert.equal(createUi().state.tierSelection.tier, "standard");
}
// 同时检查组件身份、语义角色、提交范围及无障碍标签,不能只验证排序后的数字。
function assertSelection(result, a, b, startHandle) {
- const state = JSON.parse(result[4]);
+ const state = JSON.parse(result[3]);
const start = Math.min(a, b);
const end = Math.max(a, b);
- assert.equal(result[0].value, a);
- assert.equal(result[1].value, b);
+ assert.equal(JSON.parse(result[0].value).handle_a, a);
+ assert.equal(JSON.parse(result[0].value).handle_b, b);
assert.equal(state.handle_a, a);
assert.equal(state.handle_b, b);
assert.equal(state.start_handle, startHandle);
- assert.equal(result[0].label, startHandle === "a" ? "起始页" : "结束页");
- assert.equal(result[1].label, startHandle === "b" ? "起始页" : "结束页");
- assert.equal(result[3], start === end ? String(start) : `${start}-${end}`);
- assert(result[2].includes(`>${end - start + 1}</span> / ${state.page_count} 页`));
- assert(result[2].includes(start === end ? `第 ${start} 页` : `第 ${start}–${end} 页`));
- assert(result[2].includes(`data-start-handle="${startHandle}"`));
- assert.equal(result[10].value, start);
- assert.equal(result[11].value, end);
+ assert.equal(JSON.parse(result[0].value).start_handle, startHandle);
+ assert.equal(result[2], start === end ? String(start) : `${start}-${end}`);
+ assert(result[1].includes(`>${end - start + 1}</span> / ${state.page_count} 页`));
+ assert(result[1].includes(start === end ? `第 ${start} 页` : `第 ${start}–${end} 页`));
+ assert(result[1].includes(`data-start-handle="${startHandle}"`));
+ assert.equal(result[9].value, start);
+ assert.equal(result[10].value, end);
}
let ui = createUi();
-assert.match(ui.step("file")[2], /data-range-visible="false"/);
+assert.match(ui.step("file")[1], /data-range-visible="false"/);
let out = ui.step("file", { file: { path: "/report.pdf" } });
-assert.equal(out[5].interactive, false);
-assert.match(out[2], /data-range-visible="true"/);
-assert.match(out[2], /正在读取/);
-assert.equal(out[6].visible, false);
-assert.equal(out[0].interactive, false);
+assert.equal(out[4].interactive, false);
+assert.match(out[1], /data-range-visible="true"/);
+assert.match(out[1], /正在读取/);
+assert.equal(out[5].visible, false);
+assert.equal(JSON.parse(out[0].value).page_count, 0);
out = ui.upload(100);
-assert.equal(out[0].minimum, 1);
-assert.equal(out[1].maximum, 100);
-assert.equal(out[3], "1-20");
+assert.equal(JSON.parse(out[0].value).page_count, 100);
+assert.equal(out[2], "1-20");
for (const [action, value, expected] of [
["b", 40, "21-40"], ["a", 15, "15-34"], ["a", 20, "20-34"], ["b", 35, "20-35"]
]) {
- assert.equal(ui.step(action, { [action]: value })[3], expected);
+ assert.equal(ui.step(action, { [action]: value })[2], expected);
}
// 原左滑块保持 A 身份连续穿越:20→40→60→30,超限时推动 B 而不是交换物理值。
@@ -176,7 +182,7 @@ assertSelection(ui.step("a", { a: 60 }), 60, 41, "b");
const crossedState = { ...ui.state.previous };
// Flash 同样显示滑块,选区与角色原样保留,切回高档位不重置。
assertSelection(ui.step("tier", { position: 0 }), 60, 41, "b");
-assert.match(ui.step("tier", { position: 0 })[2], /data-range-visible="true"/);
+assert.match(ui.step("tier", { position: 0 })[1], /data-range-visible="true"/);
assert.deepEqual(ui.state.previous, crossedState);
assertSelection(ui.step("tier", { position: 3 }), 60, 41, "b");
assertSelection(ui.step("a", { a: 30 }), 30, 41, "a");
@@ -203,21 +209,21 @@ assertSelection(ui.step("b", { b: 500 }), 81, 100, "a");
// 换文件后旧页数响应不能覆盖新状态,已缓存页数不受晚到响应污染。
ui.step("file", { file: { path: "/new.pdf" } });
out = ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100 } });
-assert.equal(out[5].interactive, false);
-assert.equal(JSON.parse(out[4]).page_count, 0);
+assert.equal(out[4].interactive, false);
+assert.equal(JSON.parse(out[3]).page_count, 0);
out = ui.upload(12, "/new.pdf");
-assert.equal(out[3], "1-12");
+assert.equal(out[2], "1-12");
assertSelection(out, 1, 12, "a");
ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100 } });
-assert.equal(ui.step("tier", { position: 2 })[3], "1-12");
+assert.equal(ui.step("tier", { position: 2 })[2], "1-12");
out = ui.step("file", { file: { path: "/sample.csv" } });
-assert.match(out[2], /data-range-visible="false"/);
-assert.equal(out[3], "");
-assert.equal(out[5].interactive, true);
+assert.match(out[1], /data-range-visible="false"/);
+assert.equal(out[2], "");
+assert.equal(out[4].interactive, true);
out = ui.step("clear");
-assert.equal(out[5].interactive, false);
-assert.equal(JSON.parse(out[4]).path, "");
-assert.equal(JSON.parse(out[4]).start_handle, "a");
+assert.equal(out[4].interactive, false);
+assert.equal(JSON.parse(out[3]).path, "");
+assert.equal(JSON.parse(out[3]).start_handle, "a");
// 不限页数时跨越不能移动对端;上限为 1 时两个实体一起移动并保留重合角色。
ui = createUi(null);
@@ -234,18 +240,18 @@ assertSelection(ui.step("b", { b: 10 }), 10, 10, "a");
ui = createUi();
ui.step("file", { file: { path: "/bad.pdf" } });
out = ui.step("metadata", { metadata: { path: "/bad.pdf", page_count: 0, error: "<bad>" } });
-assert.equal(out[5].interactive, false);
-assert.match(out[2], /无法读取页数/);
-assert.equal(out[6].value, "&lt;bad&gt;");
+assert.equal(out[4].interactive, false);
+assert.match(out[1], /无法读取页数/);
+assert.equal(out[5].value, "&lt;bad&gt;");
out = ui.step("tier", { position: 0 });
-assert.equal(out[5].interactive, false);
-assert.equal(out[6].visible, true);
-assert.equal(out[6].value, "&lt;bad&gt;");
+assert.equal(out[4].interactive, false);
+assert.equal(out[5].visible, true);
+assert.equal(out[5].value, "&lt;bad&gt;");
// 精确输入与滑块共用物理端点;快捷选择一次恢复两端,包含已交叉和单页上限。
ui = createUi();
out = ui.upload(48);
-assert.equal(out[12].value, "前 20 页");
+assert.equal(out[11].value, "前 20 页");
assertSelection(ui.step("end", { end: 30 }), 11, 30, "a");
assertSelection(ui.step("start", { start: 5 }), 5, 24, "a");
assertSelection(ui.step("start", { start: 10 }), 10, 24, "a");
@@ -257,29 +263,37 @@ assertSelection(ui.step("preset"), 1, 20, "a");
assertSelection(ui.step("end", { end: 999 }), 29, 48, "a");
assertSelection(ui.step("start", { start: 0 }), 1, 20, "a");
ui = createUi(null);
-assert.equal(ui.upload(48)[12].value, "全部");
+assert.equal(ui.upload(48)[11].value, "全部");
ui.step("end", { end: 20 });
assertSelection(ui.step("preset"), 1, 48, "a");
ui = createUi(20);
out = ui.upload(12);
-assert.equal(out[12].value, "全部");
+assert.equal(out[11].value, "全部");
out = ui.upload(1, "/single.pdf");
-assert.equal(out[10].interactive, false);
-assert.equal(out[11].maximum, 1);
-assert.equal(out[12].interactive, false);
+assert.equal(out[9].interactive, false);
+assert.equal(out[10].maximum, 1);
+assert.equal(out[11].interactive, false);
ui = createUi(1);
ui.upload(48);
assertSelection(ui.step("end", { end: 40 }), 40, 40, "a");
assertSelection(ui.step("preset"), 1, 1, "a");
+// 一次提交的两端必须同时生效,保持平移长度和交叉后的物理身份。
+ui = createUi();
+ui.upload(48);
+assertSelection(ui.step("pair", { a: 21, b: 40 }), 21, 40, "a");
+assertSelection(ui.step("pair", { a: 48, b: 29 }), 48, 29, "b");
+assertSelection(ui.step("pair", { a: 25, b: 6 }), 25, 6, "b");
+// 外部异常端点仍须经过边界和上限校验。
+assertSelection(ui.step("pair", { a: 999, b: -100 }), 48, 29, "b");
+
// 确定性遍历总页数和上限:物理值允许倒序,排序后的范围、角色与上限必须一致。
for (const count of [1, 12, 20, 100]) {
for (const limit of [null, 1, 20, 250]) {
ui = createUi(limit);
out = ui.upload(count);
assert.equal(ui.state.b, Math.min(count, limit ?? count));
- assert.equal(out[1].interactive, count > 1);
- assert.equal(out[1].maximum, Math.max(2, count));
+ assert.equal(JSON.parse(out[0].value).page_count, count);
let seed = 7;
for (let step = 0; step < 1000; step++) {
seed = (seed * 16807) % 2147483647;
diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.py
index 56a9ca3c..9aa29691 100644
--- a/tests/unittest/test_kit_gradio_page_range.py
+++ b/tests/unittest/test_kit_gradio_page_range.py
@@ -312,20 +312,17 @@ def test_metadata_does_not_read_non_pdf(monkeypatch: pytest.MonkeyPatch) -> None
def test_native_range_components_and_frontend_only_events(tmp_path: Path) -> None:
- """双滑块联动与档位切换不请求 Python,公开转换输入在页码之后增加 OCR 开关。"""
+ """选页手势原子提交且不请求 Python,公开转换输入仍保持四个参数。"""
capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))
demo = gradio_app.build_gradio_app(Mock(), capabilities, output_root=tmp_path, max_pages=20, enable_example=False)
- sliders = [block for block in demo.blocks.values() if block.__class__.__name__ == "Slider"]
- assert len(sliders) == 3
- assert sliders[1].elem_classes == ["mineru-page-handle-a"]
- assert sliders[2].elem_classes == ["mineru-page-handle-b"]
- for slider in sliders[1:]:
- assert slider.step == 1 and slider.precision == 0
- events = [event for event in demo.config["dependencies"] if (slider._id, "input") in event["targets"]]
- assert len(events) == 1 and events[0]["backend_fn"] is False and events[0]["queue"] is False
- assert events[0]["trigger_mode"] == "always_last"
- assert len(events[0]["targets"]) == 10
- assert events[0]["outputs"][:2] == [sliders[1]._id, sliders[2]._id]
+ control = next(block for block in demo.blocks.values() if "mineru-page-control" in (block.elem_classes or []))
+ assert control.__class__.__name__ == "HTML"
+ assert control.html_template.count('type="range"') == 2
+ events = [event for event in demo.config["dependencies"] if (control._id, "input") in event["targets"]]
+ assert len(events) == 1 and events[0]["backend_fn"] is False and events[0]["queue"] is False
+ assert events[0]["trigger_mode"] == "always_last"
+ assert len(events[0]["targets"]) == 9
+ assert events[0]["outputs"][0] == control._id
numbers = [block for block in demo.blocks.values() if "mineru-page-number" in (block.elem_classes or [])]
assert len(numbers) == 2
for number in numbers:
@@ -374,3 +371,10 @@ def test_frontend_tier_capsule_interactions() -> None:
node = shutil.which("node")
assert node is not None
subprocess.run([node, str(Path(__file__).with_name("test_kit_gradio_tier.cjs"))], check=True)
+
+
+def test_frontend_page_range_gestures() -> None:
+ """执行真实手势控制器,验证本地预览、原子提交、整段平移和取消竞态。"""
+ node = shutil.which("node")
+ assert node is not None
+ subprocess.run([node, str(Path(__file__).with_name("test_kit_gradio_page_control.cjs"))], check=True)