1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-01-02 12:47:41 +02:00

Desktop: PDF scroll persistence (#6747)

This commit is contained in:
asrient 2022-08-27 18:02:20 +05:30 committed by GitHub
parent ed2a328616
commit 3ec3a37603
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 494 additions and 234 deletions

View File

@ -1973,6 +1973,15 @@ packages/pdf-viewer/hooks/useIsFocused.js.map
packages/pdf-viewer/hooks/useIsVisible.d.ts packages/pdf-viewer/hooks/useIsVisible.d.ts
packages/pdf-viewer/hooks/useIsVisible.js packages/pdf-viewer/hooks/useIsVisible.js
packages/pdf-viewer/hooks/useIsVisible.js.map packages/pdf-viewer/hooks/useIsVisible.js.map
packages/pdf-viewer/hooks/usePdfData.d.ts
packages/pdf-viewer/hooks/usePdfData.js
packages/pdf-viewer/hooks/usePdfData.js.map
packages/pdf-viewer/hooks/useScaledSize.d.ts
packages/pdf-viewer/hooks/useScaledSize.js
packages/pdf-viewer/hooks/useScaledSize.js.map
packages/pdf-viewer/main.d.ts
packages/pdf-viewer/main.js
packages/pdf-viewer/main.js.map
packages/pdf-viewer/miniViewer.d.ts packages/pdf-viewer/miniViewer.d.ts
packages/pdf-viewer/miniViewer.js packages/pdf-viewer/miniViewer.js
packages/pdf-viewer/miniViewer.js.map packages/pdf-viewer/miniViewer.js.map

9
.gitignore vendored
View File

@ -1962,6 +1962,15 @@ packages/pdf-viewer/hooks/useIsFocused.js.map
packages/pdf-viewer/hooks/useIsVisible.d.ts packages/pdf-viewer/hooks/useIsVisible.d.ts
packages/pdf-viewer/hooks/useIsVisible.js packages/pdf-viewer/hooks/useIsVisible.js
packages/pdf-viewer/hooks/useIsVisible.js.map packages/pdf-viewer/hooks/useIsVisible.js.map
packages/pdf-viewer/hooks/usePdfData.d.ts
packages/pdf-viewer/hooks/usePdfData.js
packages/pdf-viewer/hooks/usePdfData.js.map
packages/pdf-viewer/hooks/useScaledSize.d.ts
packages/pdf-viewer/hooks/useScaledSize.js
packages/pdf-viewer/hooks/useScaledSize.js.map
packages/pdf-viewer/main.d.ts
packages/pdf-viewer/main.js
packages/pdf-viewer/main.js.map
packages/pdf-viewer/miniViewer.d.ts packages/pdf-viewer/miniViewer.d.ts
packages/pdf-viewer/miniViewer.js packages/pdf-viewer/miniViewer.js
packages/pdf-viewer/miniViewer.js.map packages/pdf-viewer/miniViewer.js.map

View File

@ -619,6 +619,8 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
mapsToLine: true, mapsToLine: true,
// Always using useCustomPdfViewer for now, we can add a new setting for it in future if we need to. // Always using useCustomPdfViewer for now, we can add a new setting for it in future if we need to.
useCustomPdfViewer: true, useCustomPdfViewer: true,
noteId: props.noteId,
vendorDir: bridge().vendorDir(),
})); }));
if (cancelled) return; if (cancelled) return;

View File

@ -421,6 +421,9 @@ function NoteEditor(props: NoteEditorProps) {
fontSize: Setting.value('style.editor.fontSize'), fontSize: Setting.value('style.editor.fontSize'),
contentMaxWidth: props.contentMaxWidth, contentMaxWidth: props.contentMaxWidth,
isSafeMode: props.isSafeMode, isSafeMode: props.isSafeMode,
// We need it to identify the context for which media is rendered.
// It is currently used to remember pdf scroll position for each attacments of each note uniquely.
noteId: props.noteId,
}; };
let editor = null; let editor = null;

View File

@ -75,6 +75,7 @@ export interface NoteBodyEditorProps {
fontSize: number; fontSize: number;
contentMaxWidth: number; contentMaxWidth: number;
isSafeMode: boolean; isSafeMode: boolean;
noteId: string;
} }
export interface FormNote { export interface FormNote {

View File

@ -21,6 +21,8 @@ export interface MarkupToHtmlOptions {
bodyOnly?: boolean; bodyOnly?: boolean;
mapsToLine?: boolean; mapsToLine?: boolean;
useCustomPdfViewer?: boolean; useCustomPdfViewer?: boolean;
noteId?: string;
vendorDir?: string;
} }
export default function useMarkupToHtml(deps: HookDependencies) { export default function useMarkupToHtml(deps: HookDependencies) {

View File

@ -1,9 +1,38 @@
import React, { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState, MutableRefObject } from 'react';
import * as React from 'react';
import useIsVisible from './hooks/useIsVisible'; import useIsVisible from './hooks/useIsVisible';
import { PdfData, ScaledSize } from './pdfSource'; import { PdfData, ScaledSize } from './pdfSource';
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect'; import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
import styled from 'styled-components';
require('./pages.css'); const PageWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow: hidden;
border: solid thin rgba(120, 120, 120, 0.498);
background: rgb(233, 233, 233);
position: relative;
border-radius: 0px;
`;
const PageInfo = styled.div`
position: absolute;
top: 0.5rem;
left: 0.5rem;
padding: 0.3rem;
background: rgba(203, 203, 203, 0.509);
border-radius: 0.3rem;
font-size: 0.8rem;
color: rgba(91, 91, 91, 0.829);
backdrop-filter: blur(0.5rem);
cursor: default;
user-select: none;
&:hover{
opacity: 0.3;
}
`;
export interface PageProps { export interface PageProps {
pdf: PdfData; pdf: PdfData;
@ -12,21 +41,22 @@ export interface PageProps {
isAnchored: boolean; isAnchored: boolean;
scaledSize: ScaledSize; scaledSize: ScaledSize;
isDarkTheme: boolean; isDarkTheme: boolean;
container: React.MutableRefObject<HTMLElement>; container: MutableRefObject<HTMLElement>;
showPageNumbers?: boolean;
} }
export default function Page(props: PageProps) { export default function Page(props: PageProps) {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [page, setPage] = useState(null); const [page, setPage] = useState(null);
const [scale, setScale] = useState(null); const scaleRef = useRef<number>(null);
const [timestamp, setTimestamp] = useState(null); const timestampRef = useRef<number>(null);
const canvasRef = useRef<HTMLCanvasElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null); const wrapperRef = useRef<HTMLDivElement>(null);
const isVisible = useIsVisible(canvasRef, props.container); const isVisible = useIsVisible(canvasRef, props.container);
useEffect(() => { useEffect(() => {
if (!isVisible || !page || !props.scaledSize || (scale && props.scaledSize.scale === scale)) return; if (!isVisible || !page || !props.scaledSize || (scaleRef.current && props.scaledSize.scale === scaleRef.current)) return;
try { try {
const viewport = page.getViewport({ scale: props.scaledSize.scale || 1.0 }); const viewport = page.getViewport({ scale: props.scaledSize.scale || 1.0 });
const canvas = canvasRef.current; const canvas = canvasRef.current;
@ -34,28 +64,27 @@ export default function Page(props: PageProps) {
canvas.height = viewport.height; canvas.height = viewport.height;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
const pageTimestamp = new Date().getTime(); const pageTimestamp = new Date().getTime();
setTimestamp(pageTimestamp); timestampRef.current = pageTimestamp;
page.render({ page.render({
canvasContext: ctx, canvasContext: ctx,
viewport, viewport,
// Used so that the page rendering is throttled to some extent. // Used so that the page rendering is throttled to some extent.
// https://stackoverflow.com/questions/18069448/halting-pdf-js-page-rendering // https://stackoverflow.com/questions/18069448/halting-pdf-js-page-rendering
continueCallback: function(cont: any) { continueCallback: function(cont: any) {
if (timestamp !== pageTimestamp) { if (timestampRef.current !== pageTimestamp) {
return; return;
} }
cont(); cont();
}, },
}); });
setScale(props.scaledSize.scale); scaleRef.current = props.scaledSize.scale;
} catch (error) { } catch (error) {
error.message = `Error rendering page no. ${props.pageNo}: ${error.message}`; error.message = `Error rendering page no. ${props.pageNo}: ${error.message}`;
setError(error); setError(error);
throw error; throw error;
} }
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied }, [page, props.scaledSize, isVisible, props.pageNo]);
}, [page, props.scaledSize, isVisible]);
useAsyncEffect(async (event: AsyncEffectEvent) => { useAsyncEffect(async (event: AsyncEffectEvent) => {
if (page || !isVisible || !props.pdf) return; if (page || !isVisible || !props.pdf) return;
@ -74,8 +103,7 @@ export default function Page(props: PageProps) {
props.container.current.scrollTop = wrapperRef.current.offsetTop; props.container.current.scrollTop = wrapperRef.current.offsetTop;
// console.warn('setting focus on page', props.pageNo, wrapperRef.current.offsetTop); // console.warn('setting focus on page', props.pageNo, wrapperRef.current.offsetTop);
} }
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied }, [props.container, props.focusOnLoad]);
}, [props.focusOnLoad]);
let style: any = {}; let style: any = {};
if (props.scaledSize) { if (props.scaledSize) {
@ -87,16 +115,14 @@ export default function Page(props: PageProps) {
} }
return ( return (
<div className="page-wrapper" ref={wrapperRef} style={style}> <PageWrapper ref={wrapperRef} style={style}>
<canvas ref={canvasRef} className="page-canvas" style={style}> <canvas ref={canvasRef} className="page-canvas" style={style}>
<div> <div>
{error ? 'ERROR' : 'Loading..'} {error ? 'ERROR' : 'Loading..'}
</div> </div>
Page {props.pageNo} Page {props.pageNo}
</canvas> </canvas>
<div className="page-info"> {props.showPageNumbers && <PageInfo>{props.isAnchored ? '📌' : ''} Page {props.pageNo}</PageInfo>}
{props.isAnchored ? '📌' : ''} Page {props.pageNo} </PageWrapper>
</div>
</div>
); );
} }

View File

@ -1,42 +1,67 @@
import React, { useLayoutEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState, MutableRefObject } from 'react';
import { PdfData, ScaledSize } from './pdfSource'; import * as React from 'react';
import { PdfData } from './pdfSource';
import Page from './Page'; import Page from './Page';
import styled from 'styled-components';
import useScaledSize, { ScaledSizeParams } from './hooks/useScaledSize';
require('./pages.css');
const PagesHolder = styled.div<{ pageGap: number }>`
display: flex;
justify-content: center;
align-items: center;
flex-flow: column;
width: 100%;
min-height: 100%;
row-gap: ${(props)=> props.pageGap || 2}px;
`;
export interface VerticalPagesProps { export interface VerticalPagesProps {
pdf: PdfData; pdf: PdfData;
isDarkTheme: boolean; isDarkTheme: boolean;
anchorPage: number; anchorPage?: number;
container: React.MutableRefObject<HTMLElement>; rememberScroll?: boolean;
pdfId?: string;
container: MutableRefObject<HTMLElement>;
pageGap?: number;
showPageNumbers?: boolean;
} }
export default function VerticalPages(props: VerticalPagesProps) { export default function VerticalPages(props: VerticalPagesProps) {
const [scaledSize, setScaledSize] = useState<ScaledSize>(null); const [containerWidth, setContainerWidth] = useState<number>(null);
const innerContainerEl = useRef<HTMLDivElement>(null); const innerContainerEl = useRef<HTMLDivElement>(null);
useLayoutEffect(() => { const scaledSize = useScaledSize({
pdf: props.pdf,
pdfId: props.pdfId,
containerWidth,
rememberScroll: props.rememberScroll,
anchorPage: props.anchorPage,
container: props.container,
innerContainerEl,
pageGap: props.pageGap,
} as ScaledSizeParams);
useEffect(() => {
let resizeTimer: number = null; let resizeTimer: number = null;
let cancelled = false; let cancelled = false;
const updateSize = async () => {
if (props.pdf) { const updateWidth = () => {
const innerWidth = innerContainerEl.current.clientWidth; if (cancelled) return;
const scaledSize = await props.pdf.getScaledSize(null, innerWidth - 10); setContainerWidth(innerContainerEl.current.clientWidth);
if (cancelled) return;
setScaledSize(scaledSize);
}
}; };
const onResize = () => { const onResize = () => {
if (resizeTimer) { if (resizeTimer) {
clearTimeout(resizeTimer); clearTimeout(resizeTimer);
resizeTimer = null; resizeTimer = null;
} }
resizeTimer = window.setTimeout(updateSize, 200); resizeTimer = window.setTimeout(updateWidth, 200);
}; };
updateWidth();
window.addEventListener('resize', onResize); window.addEventListener('resize', onResize);
updateSize()
.catch(console.error);
return () => { return () => {
cancelled = true; cancelled = true;
window.removeEventListener('resize', onResize); window.removeEventListener('resize', onResize);
@ -47,13 +72,46 @@ export default function VerticalPages(props: VerticalPagesProps) {
}; };
}, [props.pdf]); }, [props.pdf]);
return (<div className='pages-holder' ref={innerContainerEl} > useEffect(() => {
{Array.from(Array(props.pdf.pageCount).keys()).map((i: number) => { let scrollTimer: number = null;
// setting focusOnLoad only after scaledSize is set so that the container height is set correctly
return <Page pdf={props.pdf} pageNo={i + 1} focusOnLoad={scaledSize && props.anchorPage && props.anchorPage === i + 1} const saveScroll = () => {
isAnchored={props.anchorPage && props.anchorPage === i + 1} const scrollTop = props.container.current.scrollTop;
isDarkTheme={props.isDarkTheme} scaledSize={scaledSize} container={props.container} key={i} />; if (props.rememberScroll && props.pdfId) {
sessionStorage.setItem(`pdf.${props.pdfId}.scrollTop`, `${scrollTop}`);
}
};
const onScroll = () => {
if (scrollTimer) {
clearTimeout(scrollTimer);
scrollTimer = null;
}
scrollTimer = window.setTimeout(saveScroll, 200);
};
props.container.current.addEventListener('scroll', onScroll);
return () => {
props.container.current.removeEventListener('scroll', onScroll);
if (scrollTimer) {
clearTimeout(scrollTimer);
scrollTimer = null;
}
};
}, [props.container, props.pdfId, props.rememberScroll]);
return (<PagesHolder pageGap={props.pageGap || 2} ref={innerContainerEl} >
{scaledSize ?
Array.from(Array(props.pdf.pageCount).keys()).map((i: number) => {
// setting focusOnLoad only after scaledSize is set so that the container height is set correctly
return <Page pdf={props.pdf} pageNo={i + 1} focusOnLoad={scaledSize && props.anchorPage && props.anchorPage === i + 1}
isAnchored={props.anchorPage && props.anchorPage === i + 1}
showPageNumbers={props.showPageNumbers}
isDarkTheme={props.isDarkTheme} scaledSize={scaledSize} container={props.container} key={i} />;
}
) : 'Calculating size...'
} }
)} </PagesHolder>);
</div>);
} }

View File

@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'; import { useEffect, useState, MutableRefObject } from 'react';
const useIsVisible = (elementRef: React.MutableRefObject<HTMLElement>, rootRef: React.MutableRefObject<HTMLElement>) => { const useIsVisible = (elementRef: MutableRefObject<HTMLElement>, rootRef: MutableRefObject<HTMLElement>) => {
const [isVisible, setIsVisible] = useState(false); const [isVisible, setIsVisible] = useState(false);
useEffect(() => { useEffect(() => {
let observer: IntersectionObserver = null; let observer: IntersectionObserver = null;
@ -29,8 +29,7 @@ const useIsVisible = (elementRef: React.MutableRefObject<HTMLElement>, rootRef:
observer.disconnect(); observer.disconnect();
} }
}; };
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied }, [elementRef, rootRef]);
}, []);
return isVisible; return isVisible;
}; };

View File

@ -0,0 +1,19 @@
import { useState } from 'react';
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
import { PdfData } from '../pdfSource';
const usePdfData = (pdfPath: string) => {
const [pdf, setPdf] = useState<PdfData>(null);
useAsyncEffect(async (event: AsyncEffectEvent) => {
const pdfData = new PdfData();
await pdfData.loadDoc(pdfPath);
if (event.cancelled) return;
setPdf(pdfData);
}, [pdfPath]);
return pdf;
};
export default usePdfData;

View File

@ -0,0 +1,52 @@
import { useRef, useState, MutableRefObject } from 'react';
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
import { ScaledSize, PdfData } from '../pdfSource';
export interface ScaledSizeParams {
pdf: PdfData;
pdfId: string;
containerWidth: number;
rememberScroll: boolean;
anchorPage: number;
container: MutableRefObject<HTMLElement>;
innerContainerEl: MutableRefObject<HTMLElement>;
pageGap: number;
}
const useScaledSize = ({ pdf, pdfId, containerWidth, rememberScroll, anchorPage, container, innerContainerEl, pageGap }: ScaledSizeParams) => {
const [scaledSize, setScaledSize] = useState<ScaledSize>(null);
const currentScaleSize = useRef(scaledSize);
useAsyncEffect(async (event: AsyncEffectEvent) => {
if (!pdf || !containerWidth) return;
// console.log('scaledSize calculation triggered');
const scaledSize_ = await pdf.getScaledSize(null, containerWidth - 10);
if (event.cancelled) return;
const oldScaleSize = currentScaleSize.current;
const oldScrollTop = container.current.scrollTop;
innerContainerEl.current.style.height = `${(scaledSize_.height + (pageGap || 2)) * pdf.pageCount}px`;
// Adjust scroll position after window resize to keep the same page visible
if (oldScaleSize && container.current) {
container.current.scrollTop = oldScrollTop * (scaledSize_.scale / oldScaleSize.scale);
}
currentScaleSize.current = scaledSize_;
setScaledSize(scaledSize_);
// If loading after note rerender, try to retirive the old scroll position
if (rememberScroll && pdfId && !oldScaleSize && !anchorPage) {
const scrollOffset = parseInt(sessionStorage.getItem(`pdf.${pdfId}.scrollTop`), 10) || null;
if (scrollOffset) {
container.current.scrollTop = scrollOffset;
// console.log('scroll set',container.current.scrollTop);
}
}
}, [pdf, pdfId, rememberScroll, anchorPage, containerWidth]);
return scaledSize;
};
export default useScaledSize;

View File

@ -0,0 +1,31 @@
import React from 'react';
import shim from '@joplin/lib/shim';
shim.setReact(React);
import { render } from 'react-dom';
import * as pdfjsLib from 'pdfjs-dist';
import MiniViewerApp from './miniViewer';
require('./viewer.css');
// Setting worker path to worker bundle.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
const url = window.frameElement.getAttribute('x-url');
const type = window.frameElement.getAttribute('x-type');
const appearance = window.frameElement.getAttribute('x-appearance');
const anchorPage = window.frameElement.getAttribute('x-anchorPage');
const pdfId = window.frameElement.getAttribute('id');
document.documentElement.setAttribute('data-theme', appearance);
function App() {
if (type === 'mini') {
return <MiniViewerApp pdfPath={url} isDarkTheme={appearance === 'dark'} anchorPage={anchorPage ? Number(anchorPage) : null} pdfId={pdfId} />;
}
return <div>Error: Unknown app type "{type}"</div>;
}
render(
<App/>,
document.getElementById('pdf-root')
);

View File

@ -1,31 +1,20 @@
import React, { useRef, useState } from 'react'; import React, { useRef } from 'react';
import shim from '@joplin/lib/shim';
shim.setReact(React);
import { render } from 'react-dom';
import * as pdfjsLib from 'pdfjs-dist';
import useIsFocused from './hooks/useIsFocused'; import useIsFocused from './hooks/useIsFocused';
import { PdfData } from './pdfSource'; import usePdfData from './hooks/usePdfData';
import VerticalPages from './VerticalPages'; import VerticalPages from './VerticalPages';
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
require('./viewer.css'); export interface MiniViewerAppProps {
pdfPath: string;
isDarkTheme: boolean;
anchorPage: number;
pdfId: string;
}
// Setting worker path to worker bundle. export default function MiniViewerApp(props: MiniViewerAppProps) {
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js'; const pdf = usePdfData(props.pdfPath);
function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPage: number }) {
const [pdf, setPdf] = useState<PdfData>(null);
const isFocused = useIsFocused(); const isFocused = useIsFocused();
const containerEl = useRef<HTMLDivElement>(null); const containerEl = useRef<HTMLDivElement>(null);
useAsyncEffect(async (event: AsyncEffectEvent) => {
const pdfData = new PdfData();
await pdfData.loadDoc(props.pdfPath);
if (event.cancelled) return;
setPdf(pdfData);
}, []);
if (!pdf) { if (!pdf) {
return ( return (
<div className="mini-app loading"> <div className="mini-app loading">
@ -36,7 +25,8 @@ function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPag
return ( return (
<div className={`mini-app${isFocused ? ' focused' : ''}`}> <div className={`mini-app${isFocused ? ' focused' : ''}`}>
<div className={`app-pages${isFocused ? ' focused' : ''}`} ref={containerEl}> <div className={`app-pages${isFocused ? ' focused' : ''}`} ref={containerEl}>
<VerticalPages pdf={pdf} isDarkTheme={props.isDarkTheme} anchorPage={props.anchorPage} container={containerEl} /> <VerticalPages pdf={pdf} isDarkTheme={props.isDarkTheme} anchorPage={props.anchorPage} pdfId={props.pdfId} rememberScroll={true}
container={containerEl} showPageNumbers={true} />
</div> </div>
<div className='app-bottom-bar'> <div className='app-bottom-bar'>
<div className='pdf-info'> <div className='pdf-info'>
@ -47,14 +37,3 @@ function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPag
</div> </div>
); );
} }
const url = window.frameElement.getAttribute('url');
const appearance = window.frameElement.getAttribute('appearance');
const anchorPage = window.frameElement.getAttribute('anchorPage');
document.documentElement.setAttribute('data-theme', appearance);
render(
<MiniViewerApp pdfPath={url} isDarkTheme={appearance === 'dark'} anchorPage={anchorPage ? Number(anchorPage) : null} />,
document.getElementById('pdf-root')
);

View File

@ -21,8 +21,9 @@
"devDependencies": { "devDependencies": {
"@types/jest": "^28.1.6", "@types/jest": "^28.1.6",
"@types/pdfjs-dist": "^2.10.378", "@types/pdfjs-dist": "^2.10.378",
"@types/react": "^18.0.14", "@types/react": "16.9.55",
"@types/react-dom": "^16.9.0", "@types/react-dom": "^16.9.0",
"@types/styled-components": "^5.1.25",
"babel-jest": "^28.1.3", "babel-jest": "^28.1.3",
"css-loader": "^6.7.1", "css-loader": "^6.7.1",
"jest": "^28.1.3", "jest": "^28.1.3",
@ -38,6 +39,7 @@
"@joplin/lib": "workspace:^", "@joplin/lib": "workspace:^",
"pdfjs-dist": "^2.14.305", "pdfjs-dist": "^2.14.305",
"react": "16.13.1", "react": "16.13.1",
"react-dom": "16.9.0" "react-dom": "16.9.0",
"styled-components": "^5.3.5"
} }
} }

View File

@ -1,76 +0,0 @@
::-webkit-scrollbar {
width: 7px;
height: 7px;
}
::-webkit-scrollbar-corner {
background: none;
}
::-webkit-scrollbar-track {
border: none;
}
::-webkit-scrollbar-thumb {
background: var(--grey);
border-radius: 5px;
}
.app-pages {
display: flex;
justify-content: center;
align-items: start;
overflow-x: hidden;
width: 100%;
height: 100%;
padding: 0.5rem;
padding-top: 0px;
overflow-y: hidden;
padding-right: 0.25rem;
position: relative;
}
.app-pages.focused {
padding-right: 0px;
overflow-y: auto;
}
.pages-holder {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
flex-flow: column;
width: 100%;
min-height: 100%;
height: auto;
row-gap: 2px;
}
.page-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow: hidden;
border: solid thin rgba(120, 120, 120, 0.498);
background: rgb(233, 233, 233);
position: relative;
}
.page-info {
position: absolute;
top: 0.5rem;
left: 0.5rem;
padding: 0.3rem;
background: rgba(203, 203, 203, 0.509);
border-radius: 0.3rem;
font-size: 0.8rem;
color: rgba(91, 91, 91, 0.829);
backdrop-filter: blur(0.5rem);
cursor: default;
}
.page-info:hover {
opacity: 0.3;
}

View File

@ -1,98 +1,157 @@
*, *,
*::before, *::before,
*::after { *::after {
box-sizing: border-box; box-sizing: border-box;
outline: none; outline: none;
}
::-webkit-scrollbar {
width: 7px;
height: 7px;
}
::-webkit-scrollbar-corner {
background: none;
}
::-webkit-scrollbar-track {
border: none;
}
::-webkit-scrollbar-thumb {
background: var(--grey);
border-radius: 5px;
} }
:root { :root {
--white: rgb(255, 255, 255); --white: rgb(255, 255, 255);
--light: rgb(219, 219, 219); --light: rgb(219, 219, 219);
--grey: rgb(128, 128, 128); --grey: rgb(128, 128, 128);
--dark: rgb(1, 0, 34); --dark: rgb(1, 0, 34);
--black: rgb(24, 24, 24); --black: rgb(24, 24, 24);
--red: #ff000d; --red: #ff000d;
--blue: #00A8FF; --blue: #00A8FF;
--green: rgb(0, 167, 28); --green: rgb(0, 167, 28);
--purple: rgb(132, 0, 255); --purple: rgb(132, 0, 255);
--orange: rgb(255, 164, 27); --orange: rgb(255, 164, 27);
--primary: var(--black); --primary: var(--black);
--secondary: var(--dark); --secondary: var(--dark);
--tertiary: var(--light); --tertiary: var(--light);
--bg: var(--white); --bg: var(--white);
} }
[data-theme="dark"] { [data-theme="dark"] {
--primary: var(--white); --primary: var(--white);
--secondary: var(--light); --secondary: var(--light);
--tertiary: var(--dark); --tertiary: var(--dark);
--bg: var(--black); --bg: var(--black);
} }
html { html {
-webkit-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%; -ms-text-size-adjust: 100%;
-ms-overflow-style: scrollbar; -ms-overflow-style: scrollbar;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0); -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
} }
body { body {
margin: 0px; margin: 0px;
padding: 0px; padding: 0px;
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
scroll-behavior: smooth; scroll-behavior: smooth;
} }
html, html,
body { body {
font-family: 'Segoe UI', sans-serif; font-family: 'Segoe UI', sans-serif;
font-size: var(--s); font-size: var(--s);
font-weight: 300; font-weight: 300;
color: var(--secondary); color: var(--secondary);
} }
hr { hr {
box-sizing: content-box; box-sizing: content-box;
height: 0; height: 0;
overflow: visible; overflow: visible;
} }
.mini-app { .mini-app {
display: grid; display: grid;
grid-template-rows: auto 2rem; grid-template-rows: auto 2rem;
height: 100vh; height: 100vh;
width: 100vw; width: 100vw;
background-color: var(--bg); background-color: var(--bg);
overflow: hidden; overflow: hidden;
border-radius: 0.4rem; border-radius: 0.4rem;
border: solid thin var(--tertiary); border: solid thin var(--tertiary);
padding-top: 0.6rem; padding-top: 0.6rem;
padding-right: 0.25rem; padding-right: 0.25rem;
background-color: rgb(240, 241, 245); background-color: rgb(240, 241, 245);
} }
.mini-app.focused { .mini-app.focused {
border: solid thin var(--grey); border: solid thin var(--grey);
} }
.mini-app.loading { .mini-app.loading {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
} }
[data-theme="dark"] .mini-app { [data-theme="dark"] .mini-app {
background-color: rgb(54, 54, 54); background-color: rgb(54, 54, 54);
} }
.app-bottom-bar { .app-bottom-bar {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
padding: 0.2rem 0.5rem; padding: 0.2rem 0.5rem;
font-size: 0.8rem; font-size: 0.8rem;
color: var(--grey); color: var(--grey);
}
.pdf-info>a {
padding: 0rem 0.4rem;
color: var(--blue);
cursor: pointer;
border: solid thin transparent;
border-radius: 5px;
user-select: none;
}
.pdf-info>a:hover {
border-color: var(--grey);
}
.app-pages {
display: flex;
justify-content: center;
align-items: start;
overflow-x: hidden;
width: 100%;
height: 100%;
padding: 0.5rem;
padding-top: 0px;
padding-bottom: 0px;
overflow-y: hidden;
padding-right: 0.25rem;
position: relative;
}
.app-pages.focused {
padding-right: 0px;
overflow-y: auto;
overflow-x: auto;
}
.pdf-info {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
} }

View File

@ -2,7 +2,7 @@ const path = require('path');
module.exports = { module.exports = {
entry: { entry: {
main: './miniViewer.tsx', main: './main.tsx',
'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry', 'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry',
}, },
module: { module: {

View File

@ -28,6 +28,8 @@ export interface RenderOptions {
plainResourceRendering?: boolean; plainResourceRendering?: boolean;
mapsToLine?: boolean; mapsToLine?: boolean;
useCustomPdfViewer?: boolean; useCustomPdfViewer?: boolean;
noteId?: string;
vendorDir?: string;
} }
interface RendererRule { interface RendererRule {
@ -172,6 +174,8 @@ export interface RuleOptions {
videoPlayerEnabled: boolean; videoPlayerEnabled: boolean;
pdfViewerEnabled: boolean; pdfViewerEnabled: boolean;
useCustomPdfViewer: boolean; useCustomPdfViewer: boolean;
noteId?: string;
vendorDir?: string;
itemIdToUrl?: ItemIdToUrlHandler; itemIdToUrl?: ItemIdToUrlHandler;
} }

View File

@ -1,5 +1,6 @@
import { Link } from '../MdToHtml'; import { Link } from '../MdToHtml';
import { toForwardSlashes } from '../pathUtils'; import { toForwardSlashes } from '../pathUtils';
import { LinkIndexes } from './rules/link_close';
const Entities = require('html-entities').AllHtmlEntities; const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = new Entities().encode; const htmlentities = new Entities().encode;
@ -8,6 +9,8 @@ export interface Options {
videoPlayerEnabled: boolean; videoPlayerEnabled: boolean;
pdfViewerEnabled: boolean; pdfViewerEnabled: boolean;
useCustomPdfViewer: boolean; useCustomPdfViewer: boolean;
noteId: string;
vendorDir: string;
theme: any; theme: any;
} }
@ -16,7 +19,7 @@ function resourceUrl(resourceFullPath: string): string {
return `file://${toForwardSlashes(resourceFullPath)}`; return `file://${toForwardSlashes(resourceFullPath)}`;
} }
export default function(link: Link, options: Options) { export default function(link: Link, options: Options, linkIndexes: LinkIndexes) {
const resource = link.resource; const resource = link.resource;
if (!link.resourceReady || !resource || !resource.mime) return ''; if (!link.resourceReady || !resource || !resource.mime) return '';
@ -44,16 +47,32 @@ export default function(link: Link, options: Options) {
} }
if (options.pdfViewerEnabled && resource.mime === 'application/pdf') { if (options.pdfViewerEnabled && resource.mime === 'application/pdf') {
if (options.useCustomPdfViewer) { if (options.useCustomPdfViewer) {
const resourceId = resource.id;
let anchorPageNo = null; let anchorPageNo = null;
let id = `${options.noteId}.${resourceId}`;
if (linkIndexes && linkIndexes[resourceId]) {
linkIndexes[resourceId]++;
} else {
linkIndexes[resourceId] = 1;
}
id += `.${linkIndexes[resourceId]}`;
if (link.href.indexOf('#') > 0) { if (link.href.indexOf('#') > 0) {
anchorPageNo = Number(link.href.split('#').pop()); anchorPageNo = Number(link.href.split('#').pop());
if (anchorPageNo < 1) anchorPageNo = null; if (anchorPageNo < 1) anchorPageNo = null;
} }
return `<iframe src="../../vendor/lib/@joplin/pdf-viewer/index.html" url="${escapedResourcePath}"
appearance="${options.theme.appearance}" ${anchorPageNo ? `anchorPage="${anchorPageNo}"` : ''} const src = `${options.vendorDir}/lib/@joplin/pdf-viewer/index.html`;
return `<iframe src="${src}" x-url="${escapedResourcePath}"
x-appearance="${options.theme.appearance}" ${anchorPageNo ? `x-anchorPage="${anchorPageNo}"` : ''} id="${id}"
x-type="mini"
class="media-player media-pdf"></iframe>`; class="media-player media-pdf"></iframe>`;
} }
return `<object data="${escapedResourcePath}" class="media-player media-pdf" type="${escapedMime}"></object>`; return `<object data="${escapedResourcePath}" class="media-player media-pdf" type="${escapedMime}"></object>`;
} }

View File

@ -4,18 +4,25 @@
import { RuleOptions } from '../../MdToHtml'; import { RuleOptions } from '../../MdToHtml';
import renderMedia, { Options as RenderMediaOptions } from '../renderMedia'; import renderMedia, { Options as RenderMediaOptions } from '../renderMedia';
export interface LinkIndexes {
[key: string]: number;
}
function plugin(markdownIt: any, ruleOptions: RuleOptions) { function plugin(markdownIt: any, ruleOptions: RuleOptions) {
const defaultRender = markdownIt.renderer.rules.link_close || function(tokens: any, idx: any, options: any, _env: any, self: any) { const defaultRender = markdownIt.renderer.rules.link_close || function(tokens: any, idx: any, options: any, _env: any, self: any) {
return self.renderToken(tokens, idx, options); return self.renderToken(tokens, idx, options);
}; };
const linkIndexes: LinkIndexes = {};
markdownIt.renderer.rules.link_close = function(tokens: any[], idx: number, options: any, env: any, self: any) { markdownIt.renderer.rules.link_close = function(tokens: any[], idx: number, options: any, env: any, self: any) {
const defaultOutput = defaultRender(tokens, idx, options, env, self); const defaultOutput = defaultRender(tokens, idx, options, env, self);
const link = ruleOptions.context.currentLinks.pop(); const link = ruleOptions.context.currentLinks.pop();
if (!link || ruleOptions.linkRenderingType === 2 || ruleOptions.plainResourceRendering) return defaultOutput; if (!link || ruleOptions.linkRenderingType === 2 || ruleOptions.plainResourceRendering) return defaultOutput;
return [defaultOutput, renderMedia(link, ruleOptions as RenderMediaOptions)].join(''); return [defaultOutput, renderMedia(link, ruleOptions as RenderMediaOptions, linkIndexes)].join('');
}; };
} }

View File

@ -2985,6 +2985,15 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@emotion/is-prop-valid@npm:^1.1.0":
version: 1.2.0
resolution: "@emotion/is-prop-valid@npm:1.2.0"
dependencies:
"@emotion/memoize": ^0.8.0
checksum: cc7a19850a4c5b24f1514665289442c8c641709e6f7711067ad550e05df331da0692a16148e85eda6f47e31b3261b64d74c5e25194d053223be16231f969d633
languageName: node
linkType: hard
"@emotion/memoize@npm:0.7.4": "@emotion/memoize@npm:0.7.4":
version: 0.7.4 version: 0.7.4
resolution: "@emotion/memoize@npm:0.7.4" resolution: "@emotion/memoize@npm:0.7.4"
@ -2999,6 +3008,13 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@emotion/memoize@npm:^0.8.0":
version: 0.8.0
resolution: "@emotion/memoize@npm:0.8.0"
checksum: c87bb110b829edd8e1c13b90a6bc37cebc39af29c7599a1e66a48e06f9bec43e8e53495ba86278cc52e7589549492c8dfdc81d19f4fdec0cee6ba13d2ad2c928
languageName: node
linkType: hard
"@emotion/serialize@npm:^0.9.1": "@emotion/serialize@npm:^0.9.1":
version: 0.9.1 version: 0.9.1
resolution: "@emotion/serialize@npm:0.9.1" resolution: "@emotion/serialize@npm:0.9.1"
@ -4268,8 +4284,9 @@ __metadata:
"@joplin/lib": "workspace:^" "@joplin/lib": "workspace:^"
"@types/jest": ^28.1.6 "@types/jest": ^28.1.6
"@types/pdfjs-dist": ^2.10.378 "@types/pdfjs-dist": ^2.10.378
"@types/react": ^18.0.14 "@types/react": 16.9.55
"@types/react-dom": ^16.9.0 "@types/react-dom": ^16.9.0
"@types/styled-components": ^5.1.25
babel-jest: ^28.1.3 babel-jest: ^28.1.3
css-loader: ^6.7.1 css-loader: ^6.7.1
jest: ^28.1.3 jest: ^28.1.3
@ -4278,6 +4295,7 @@ __metadata:
react: 16.13.1 react: 16.13.1
react-dom: 16.9.0 react-dom: 16.9.0
style-loader: ^3.3.1 style-loader: ^3.3.1
styled-components: ^5.3.5
ts-jest: ^28.0.7 ts-jest: ^28.0.7
ts-loader: ^9.3.0 ts-loader: ^9.3.0
typescript: ^4.0.5 typescript: ^4.0.5
@ -6990,17 +7008,6 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@types/react@npm:^18.0.14":
version: 18.0.15
resolution: "@types/react@npm:18.0.15"
dependencies:
"@types/prop-types": "*"
"@types/scheduler": "*"
csstype: ^3.0.2
checksum: e22cc388d1c145aa184787e44dc28db4789976c704cd5db475c170bb76a560eb81def5f346cfe750949bb3d43ad88822b8cbb9f19b1286e3795892a8263e7715
languageName: node
linkType: hard
"@types/responselike@npm:*, @types/responselike@npm:^1.0.0": "@types/responselike@npm:*, @types/responselike@npm:^1.0.0":
version: 1.0.0 version: 1.0.0
resolution: "@types/responselike@npm:1.0.0" resolution: "@types/responselike@npm:1.0.0"
@ -7046,6 +7053,17 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"@types/styled-components@npm:^5.1.25":
version: 5.1.25
resolution: "@types/styled-components@npm:5.1.25"
dependencies:
"@types/hoist-non-react-statics": "*"
"@types/react": "*"
csstype: ^3.0.2
checksum: 60ce64f13283b01da54fd3a4c5703769d8575c979d5ec6b67ad124c2d4df980c9b96bb91af87e03f6447a816a5d2b0270c63eefad60cfa885091b594984525f5
languageName: node
linkType: hard
"@types/testing-library__react-hooks@npm:^3.4.0": "@types/testing-library__react-hooks@npm:^3.4.0":
version: 3.4.1 version: 3.4.1
resolution: "@types/testing-library__react-hooks@npm:3.4.1" resolution: "@types/testing-library__react-hooks@npm:3.4.1"
@ -9087,6 +9105,21 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"babel-plugin-styled-components@npm:>= 1.12.0":
version: 2.0.7
resolution: "babel-plugin-styled-components@npm:2.0.7"
dependencies:
"@babel/helper-annotate-as-pure": ^7.16.0
"@babel/helper-module-imports": ^7.16.0
babel-plugin-syntax-jsx: ^6.18.0
lodash: ^4.17.11
picomatch: ^2.3.0
peerDependencies:
styled-components: ">= 2"
checksum: 80b06b10db02d749432a0ac43a5feedd686f6b648628d7433a39b1844260b2b7c72431f6e705c82636ee025fcfd4f6c32fc05677e44033b8a39ddcd4488b3147
languageName: node
linkType: hard
"babel-plugin-syntax-flow@npm:^6.18.0": "babel-plugin-syntax-flow@npm:^6.18.0":
version: 6.18.0 version: 6.18.0
resolution: "babel-plugin-syntax-flow@npm:6.18.0" resolution: "babel-plugin-syntax-flow@npm:6.18.0"
@ -26785,7 +26818,7 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"picomatch@npm:^2.3.1": "picomatch@npm:^2.3.0, picomatch@npm:^2.3.1":
version: 2.3.1 version: 2.3.1
resolution: "picomatch@npm:2.3.1" resolution: "picomatch@npm:2.3.1"
checksum: 050c865ce81119c4822c45d3c84f1ced46f93a0126febae20737bd05ca20589c564d6e9226977df859ed5e03dc73f02584a2b0faad36e896936238238b0446cf checksum: 050c865ce81119c4822c45d3c84f1ced46f93a0126febae20737bd05ca20589c564d6e9226977df859ed5e03dc73f02584a2b0faad36e896936238238b0446cf
@ -31518,6 +31551,28 @@ __metadata:
languageName: node languageName: node
linkType: hard linkType: hard
"styled-components@npm:^5.3.5":
version: 5.3.5
resolution: "styled-components@npm:5.3.5"
dependencies:
"@babel/helper-module-imports": ^7.0.0
"@babel/traverse": ^7.4.5
"@emotion/is-prop-valid": ^1.1.0
"@emotion/stylis": ^0.8.4
"@emotion/unitless": ^0.7.4
babel-plugin-styled-components: ">= 1.12.0"
css-to-react-native: ^3.0.0
hoist-non-react-statics: ^3.0.0
shallowequal: ^1.1.0
supports-color: ^5.5.0
peerDependencies:
react: ">= 16.8.0"
react-dom: ">= 16.8.0"
react-is: ">= 16.8.0"
checksum: 05a664dfe423c2906959a0f3f47f9b1ad630e493eb2e06deea0dc0906af33ba5ca17277b98948a6c9642e73894d6533391aebf45576489f5afe920c974e9f8eb
languageName: node
linkType: hard
"styled-system@npm:5.1.5": "styled-system@npm:5.1.5":
version: 5.1.5 version: 5.1.5
resolution: "styled-system@npm:5.1.5" resolution: "styled-system@npm:5.1.5"