Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions docs/mobile-pdf-text-selection-fix.md

Large diffs are not rendered by default.

290 changes: 193 additions & 97 deletions packages/app-expo/assets/reader/reader.html

Large diffs are not rendered by default.

118 changes: 100 additions & 18 deletions packages/app-expo/assets/reader/reader.template.html
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@
function postToRN(type, data) {
if (RN) RN.postMessage(JSON.stringify({ type, ...data }));
}
window.__READANY_READER_BUILD_ID = 'android-local-server-cors';
// build-reader.js stamps a deterministic content id into this line; a stale
// committed bundle is detectable via the RN 'debug' message.
window.__READANY_READER_BUILD_ID = 'build-id-placeholder';
postToRN('debug', { message: '[ReaderBuild] ' + window.__READANY_READER_BUILD_ID });
Promise.withResolvers ??= function () {
let resolve;
Expand Down Expand Up @@ -1773,6 +1775,30 @@
}

// ─── Settings ───

// Safe style block for fixed-layout docs (PDF/CBZ). PDF.js TextLayer glyphs
// are transparent spans whose size/position are computed from CSS variables;
// injecting font-size/font-family/line-height or `color: inherit` would
// break glyph sizing and make the text layer visible over the canvas.
function buildFixedLayoutStyles(bg, fg, primary) {
return `
:root {
--readany-font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
}
html, body {
background-color: ${bg} !important;
color: ${fg} !important;
}
.textLayer,
.textLayer :is(span, br) {
color: transparent !important;
}
::selection {
background: rgba(59, 130, 246, 0.3) !important;
}
`;
}

function applySettings(settings) {
if (!view || !view.renderer) return;
const renderer = view.renderer;
Expand Down Expand Up @@ -1836,7 +1862,19 @@
const layoutScale = currentFontSize / BASELINE_FONT_SIZE;
const ps = Math.round(currentParagraphSpacing * layoutScale);

const baseStyles = `
// Fixed layout (PDF/CBZ): never inject font-size/font-family/line-height
// reflow overrides — they would break the pdf.js TextLayer (glyph sizes
// are computed from CSS variables in PDF.js 5.x, not set inline). Only a
// theme-safe block is used, mirroring the desktop FoliateViewer
// fixed-layout guard.
const isFixedLayout = !!(view && view.isFixedLayout);
const baseStyles = isFixedLayout
? buildFixedLayoutStyles(
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
)
: `
:root {
--readany-font-family: ${fontFamily};
}
Expand Down Expand Up @@ -1897,12 +1935,17 @@
${getVerticalWritingCompatibilityStyles()}
`;
lastRendererStyles = baseStyles;
const themedStyles = injectThemeIntoStyles(
baseStyles,
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
);
// For fixed layout baseStyles is already a self-contained safe block;
// re-wrapping it with injectThemeIntoStyles would re-add the
// `color: inherit` rule that makes PDF TextLayer glyphs visible.
const themedStyles = isFixedLayout
? baseStyles
: injectThemeIntoStyles(
baseStyles,
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
);
if (typeof renderer.setStyles === 'function') {
renderer.setStyles(themedStyles);
}
Expand Down Expand Up @@ -2055,8 +2098,15 @@
document.body.style.color = fg;

if (view && view.renderer && view.renderer.setStyles) {
const currentStyles = lastRendererStyles || '';
const themedStyles = injectThemeIntoStyles(currentStyles, bg, fg, primary);
const isFixedLayout = !!(view && view.isFixedLayout);
// For fixed layout, lastRendererStyles carries baked-in theme colors, so
// rebuild the safe block with the new colors; injectThemeIntoStyles
// would re-add the `color: inherit` rule that makes PDF TextLayer glyphs
// visible.
const themedStyles = isFixedLayout
? buildFixedLayoutStyles(bg, fg, primary)
: injectThemeIntoStyles(lastRendererStyles || '', bg, fg, primary);
lastRendererStyles = themedStyles;
view.renderer.setStyles(themedStyles);
syncReaderOverrideStylesForAllDocs(themedStyles);
}
Expand Down Expand Up @@ -2213,6 +2263,15 @@
}

function applyDocStyles(doc) {
const isFixedLayout = !!(view && view.isFixedLayout);
// Fixed layout (PDF/CBZ): the pdf.js TextLayer glyphs are transparent spans
// positioned by CSS variables — `color: inherit` would make them visible and
// reflow overrides would misalign selection. Keep only the safe baseline.
const fixedLayoutStyles = buildFixedLayoutStyles(
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
);
syncCustomFontStylesForDoc(doc, currentCustomFontFaceCSS);
const verticalDoc = isVerticalDoc(doc);
if (!verticalDoc) {
Expand All @@ -2225,7 +2284,18 @@
}
const style = doc.createElement('style');
const { bg, fg, primary } = currentThemeColors;
style.textContent = `
style.textContent = isFixedLayout
? `
* { -webkit-touch-callout: none !important; -webkit-user-select: text !important; user-select: text !important; }
html, body { background-color: ${bg} !important; color: ${fg} !important; }
img, picture, svg, image, canvas {
-webkit-user-drag: none !important;
touch-action: manipulation !important;
}
${fixedLayoutStyles}
${verticalDoc ? getVerticalWritingCompatibilityStyles() : ''}
`
: `
* { -webkit-touch-callout: none !important; -webkit-user-select: text !important; user-select: text !important; }
html, body { background-color: ${bg} !important; color: ${fg} !important; }
img, picture, svg, image, canvas {
Expand All @@ -2239,13 +2309,25 @@
`;
doc.head.appendChild(style);
if (lastRendererStyles) {
const themedStyles = injectThemeIntoStyles(
lastRendererStyles,
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
);
syncReaderOverrideStylesForDoc(doc, themedStyles);
if (isFixedLayout) {
// For PDF/CBZ, sync the freshly computed safe block instead of
// lastRendererStyles: lastRendererStyles is never reset in openBook,
// so after an EPUB→PDF switch in the same WebView it can still hold
// stale reflow styles (font-size/font-family/line-height !important)
// that would break the pdf.js TextLayer. fixedLayoutStyles is derived
// from the current theme colors, so it is always correct. Re-wrapping
// it with injectThemeIntoStyles would re-add `color: inherit`, so
// inject it verbatim.
syncReaderOverrideStylesForDoc(doc, fixedLayoutStyles);
} else {
const themedStyles = injectThemeIntoStyles(
lastRendererStyles,
currentThemeColors.bg,
currentThemeColors.fg,
currentThemeColors.primary,
);
syncReaderOverrideStylesForDoc(doc, themedStyles);
}
}
doc.addEventListener('contextmenu', (e) => { e.preventDefault(); e.stopPropagation(); return false; }, true);
}
Expand Down
19 changes: 18 additions & 1 deletion packages/app-expo/scripts/build-reader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* Run: node scripts/build-reader.js
*/
const esbuild = require("esbuild");
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");

Expand All @@ -13,6 +14,14 @@ const ASSETS_DIR = path.resolve(__dirname, "../assets/reader");
const TEMPLATE = path.resolve(ASSETS_DIR, "reader.template.html");
const OUTPUT = path.resolve(ASSETS_DIR, "reader.html");

// Build id: content hash of the complete output with its deterministic
// placeholder still present. It changes for either template or bundled-source
// changes, so rebuilding makes a stale committed reader.html easy to diagnose
// without depending on a commit SHA that cannot include the generated artifact.
function getBuildId(html) {
return `sha256-${crypto.createHash("sha256").update(html).digest("hex")}`;
}

async function buildReader() {
// Create a temporary entry point
const entryContent = `
Expand Down Expand Up @@ -65,7 +74,15 @@ async function buildReader() {
// Use split/join instead of replace to avoid $ replacement patterns in JS bundle
const MARKER = "<!-- __READANY_FOLIATE_BUNDLE_INSERT_POINT_7f3a9b2e__ -->";
const parts = template.split(MARKER);
const html = `${parts[0]}<script>\n${bundledJS}\n</script>${parts.slice(1).join(MARKER)}`;
let html = `${parts[0]}<script>\n${bundledJS}\n</script>${parts.slice(1).join(MARKER)}`;

// Stamp a deterministic content id so stale bundles are detectable while
// identical source and dependencies produce byte-identical output.
// The template keeps a placeholder value that gets replaced here.
html = html.replace(
"__READANY_READER_BUILD_ID = 'build-id-placeholder'",
`__READANY_READER_BUILD_ID = ${JSON.stringify(getBuildId(html))}`,
);

// Write to output file (separate from template)
fs.writeFileSync(OUTPUT, html);
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/components/reader/FoliateViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ function getRangeTextWithoutRuby(range: Range, fallback = ""): string {
for (const node of fragment.querySelectorAll("rt, rp")) {
node.remove();
}
for (const node of fragment.querySelectorAll("br")) {
node.replaceWith(fragment.ownerDocument.createTextNode("\n"));
}
const text = fragment.textContent?.trim();
if (text) return text;
} catch {
Expand Down
6 changes: 0 additions & 6 deletions packages/app/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,9 @@ export default defineConfig(async () => ({
"@": path.resolve(__dirname, "./src"),
"pdfjs-dist/build/pdf.worker.mjs": path.join(pdfjsDist, "build/pdf.worker.mjs"),
"pdfjs-dist": pdfjsDist,
// Map @pdfjs/* to foliate-js vendored pdfjs (v4.7, compatible with foliate-js)
"@pdfjs": path.resolve(__dirname, "../../foliate-js/vendor/pdfjs"),
},
dedupe: ["i18next", "react-i18next", "react", "react-dom"],
},
optimizeDeps: {
// Exclude foliate-js pdf.js from pre-bundling so that @pdfjs alias works
exclude: ["foliate-js/pdf.js"],
},
clearScreen: false,
server: {
port: 1420,
Expand Down
Loading