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.js
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.js
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.js
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.js
packages/pdf-viewer/miniViewer.js.map

View File

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

View File

@ -421,6 +421,9 @@ function NoteEditor(props: NoteEditorProps) {
fontSize: Setting.value('style.editor.fontSize'),
contentMaxWidth: props.contentMaxWidth,
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;

View File

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

View File

@ -21,6 +21,8 @@ export interface MarkupToHtmlOptions {
bodyOnly?: boolean;
mapsToLine?: boolean;
useCustomPdfViewer?: boolean;
noteId?: string;
vendorDir?: string;
}
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 { PdfData, ScaledSize } from './pdfSource';
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 {
pdf: PdfData;
@ -12,21 +41,22 @@ export interface PageProps {
isAnchored: boolean;
scaledSize: ScaledSize;
isDarkTheme: boolean;
container: React.MutableRefObject<HTMLElement>;
container: MutableRefObject<HTMLElement>;
showPageNumbers?: boolean;
}
export default function Page(props: PageProps) {
const [error, setError] = useState(null);
const [page, setPage] = useState(null);
const [scale, setScale] = useState(null);
const [timestamp, setTimestamp] = useState(null);
const scaleRef = useRef<number>(null);
const timestampRef = useRef<number>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const isVisible = useIsVisible(canvasRef, props.container);
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 {
const viewport = page.getViewport({ scale: props.scaledSize.scale || 1.0 });
const canvas = canvasRef.current;
@ -34,28 +64,27 @@ export default function Page(props: PageProps) {
canvas.height = viewport.height;
const ctx = canvas.getContext('2d');
const pageTimestamp = new Date().getTime();
setTimestamp(pageTimestamp);
timestampRef.current = pageTimestamp;
page.render({
canvasContext: ctx,
viewport,
// Used so that the page rendering is throttled to some extent.
// https://stackoverflow.com/questions/18069448/halting-pdf-js-page-rendering
continueCallback: function(cont: any) {
if (timestamp !== pageTimestamp) {
if (timestampRef.current !== pageTimestamp) {
return;
}
cont();
},
});
setScale(props.scaledSize.scale);
scaleRef.current = props.scaledSize.scale;
} catch (error) {
error.message = `Error rendering page no. ${props.pageNo}: ${error.message}`;
setError(error);
throw error;
}
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
}, [page, props.scaledSize, isVisible]);
}, [page, props.scaledSize, isVisible, props.pageNo]);
useAsyncEffect(async (event: AsyncEffectEvent) => {
if (page || !isVisible || !props.pdf) return;
@ -74,8 +103,7 @@ export default function Page(props: PageProps) {
props.container.current.scrollTop = 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.focusOnLoad]);
}, [props.container, props.focusOnLoad]);
let style: any = {};
if (props.scaledSize) {
@ -87,16 +115,14 @@ export default function Page(props: PageProps) {
}
return (
<div className="page-wrapper" ref={wrapperRef} style={style}>
<PageWrapper ref={wrapperRef} style={style}>
<canvas ref={canvasRef} className="page-canvas" style={style}>
<div>
{error ? 'ERROR' : 'Loading..'}
</div>
Page {props.pageNo}
</canvas>
<div className="page-info">
{props.isAnchored ? '📌' : ''} Page {props.pageNo}
</div>
</div>
{props.showPageNumbers && <PageInfo>{props.isAnchored ? '📌' : ''} Page {props.pageNo}</PageInfo>}
</PageWrapper>
);
}

View File

@ -1,42 +1,67 @@
import React, { useLayoutEffect, useRef, useState } from 'react';
import { PdfData, ScaledSize } from './pdfSource';
import { useEffect, useRef, useState, MutableRefObject } from 'react';
import * as React from 'react';
import { PdfData } from './pdfSource';
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 {
pdf: PdfData;
isDarkTheme: boolean;
anchorPage: number;
container: React.MutableRefObject<HTMLElement>;
anchorPage?: number;
rememberScroll?: boolean;
pdfId?: string;
container: MutableRefObject<HTMLElement>;
pageGap?: number;
showPageNumbers?: boolean;
}
export default function VerticalPages(props: VerticalPagesProps) {
const [scaledSize, setScaledSize] = useState<ScaledSize>(null);
const [containerWidth, setContainerWidth] = useState<number>(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 cancelled = false;
const updateSize = async () => {
if (props.pdf) {
const innerWidth = innerContainerEl.current.clientWidth;
const scaledSize = await props.pdf.getScaledSize(null, innerWidth - 10);
const updateWidth = () => {
if (cancelled) return;
setScaledSize(scaledSize);
}
setContainerWidth(innerContainerEl.current.clientWidth);
};
const onResize = () => {
if (resizeTimer) {
clearTimeout(resizeTimer);
resizeTimer = null;
}
resizeTimer = window.setTimeout(updateSize, 200);
resizeTimer = window.setTimeout(updateWidth, 200);
};
updateWidth();
window.addEventListener('resize', onResize);
updateSize()
.catch(console.error);
return () => {
cancelled = true;
window.removeEventListener('resize', onResize);
@ -47,13 +72,46 @@ export default function VerticalPages(props: VerticalPagesProps) {
};
}, [props.pdf]);
return (<div className='pages-holder' ref={innerContainerEl} >
{Array.from(Array(props.pdf.pageCount).keys()).map((i: number) => {
useEffect(() => {
let scrollTimer: number = null;
const saveScroll = () => {
const scrollTop = props.container.current.scrollTop;
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} />;
}
)}
</div>);
) : 'Calculating size...'
}
</PagesHolder>);
}

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);
useEffect(() => {
let observer: IntersectionObserver = null;
@ -29,8 +29,7 @@ const useIsVisible = (elementRef: React.MutableRefObject<HTMLElement>, rootRef:
observer.disconnect();
}
};
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
}, []);
}, [elementRef, rootRef]);
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 shim from '@joplin/lib/shim';
shim.setReact(React);
import { render } from 'react-dom';
import * as pdfjsLib from 'pdfjs-dist';
import React, { useRef } from 'react';
import useIsFocused from './hooks/useIsFocused';
import { PdfData } from './pdfSource';
import usePdfData from './hooks/usePdfData';
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.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPage: number }) {
const [pdf, setPdf] = useState<PdfData>(null);
export default function MiniViewerApp(props: MiniViewerAppProps) {
const pdf = usePdfData(props.pdfPath);
const isFocused = useIsFocused();
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) {
return (
<div className="mini-app loading">
@ -36,7 +25,8 @@ function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPag
return (
<div className={`mini-app${isFocused ? ' focused' : ''}`}>
<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 className='app-bottom-bar'>
<div className='pdf-info'>
@ -47,14 +37,3 @@ function MiniViewerApp(props: { pdfPath: string; isDarkTheme: boolean; anchorPag
</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": {
"@types/jest": "^28.1.6",
"@types/pdfjs-dist": "^2.10.378",
"@types/react": "^18.0.14",
"@types/react": "16.9.55",
"@types/react-dom": "^16.9.0",
"@types/styled-components": "^5.1.25",
"babel-jest": "^28.1.3",
"css-loader": "^6.7.1",
"jest": "^28.1.3",
@ -38,6 +39,7 @@
"@joplin/lib": "workspace:^",
"pdfjs-dist": "^2.14.305",
"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

@ -5,6 +5,24 @@
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 {
--white: rgb(255, 255, 255);
--light: rgb(219, 219, 219);
@ -96,3 +114,44 @@ hr {
font-size: 0.8rem;
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 = {
entry: {
main: './miniViewer.tsx',
main: './main.tsx',
'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry',
},
module: {

View File

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

View File

@ -1,5 +1,6 @@
import { Link } from '../MdToHtml';
import { toForwardSlashes } from '../pathUtils';
import { LinkIndexes } from './rules/link_close';
const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = new Entities().encode;
@ -8,6 +9,8 @@ export interface Options {
videoPlayerEnabled: boolean;
pdfViewerEnabled: boolean;
useCustomPdfViewer: boolean;
noteId: string;
vendorDir: string;
theme: any;
}
@ -16,7 +19,7 @@ function resourceUrl(resourceFullPath: string): string {
return `file://${toForwardSlashes(resourceFullPath)}`;
}
export default function(link: Link, options: Options) {
export default function(link: Link, options: Options, linkIndexes: LinkIndexes) {
const resource = link.resource;
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.useCustomPdfViewer) {
const resourceId = resource.id;
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) {
anchorPageNo = Number(link.href.split('#').pop());
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>`;
}
return `<object data="${escapedResourcePath}" class="media-player media-pdf" type="${escapedMime}"></object>`;
}

View File

@ -4,18 +4,25 @@
import { RuleOptions } from '../../MdToHtml';
import renderMedia, { Options as RenderMediaOptions } from '../renderMedia';
export interface LinkIndexes {
[key: string]: number;
}
function plugin(markdownIt: any, ruleOptions: RuleOptions) {
const defaultRender = markdownIt.renderer.rules.link_close || function(tokens: any, idx: any, options: any, _env: any, self: any) {
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) {
const defaultOutput = defaultRender(tokens, idx, options, env, self);
const link = ruleOptions.context.currentLinks.pop();
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
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":
version: 0.7.4
resolution: "@emotion/memoize@npm:0.7.4"
@ -2999,6 +3008,13 @@ __metadata:
languageName: node
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":
version: 0.9.1
resolution: "@emotion/serialize@npm:0.9.1"
@ -4268,8 +4284,9 @@ __metadata:
"@joplin/lib": "workspace:^"
"@types/jest": ^28.1.6
"@types/pdfjs-dist": ^2.10.378
"@types/react": ^18.0.14
"@types/react": 16.9.55
"@types/react-dom": ^16.9.0
"@types/styled-components": ^5.1.25
babel-jest: ^28.1.3
css-loader: ^6.7.1
jest: ^28.1.3
@ -4278,6 +4295,7 @@ __metadata:
react: 16.13.1
react-dom: 16.9.0
style-loader: ^3.3.1
styled-components: ^5.3.5
ts-jest: ^28.0.7
ts-loader: ^9.3.0
typescript: ^4.0.5
@ -6990,17 +7008,6 @@ __metadata:
languageName: node
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":
version: 1.0.0
resolution: "@types/responselike@npm:1.0.0"
@ -7046,6 +7053,17 @@ __metadata:
languageName: node
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":
version: 3.4.1
resolution: "@types/testing-library__react-hooks@npm:3.4.1"
@ -9087,6 +9105,21 @@ __metadata:
languageName: node
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":
version: 6.18.0
resolution: "babel-plugin-syntax-flow@npm:6.18.0"
@ -26785,7 +26818,7 @@ __metadata:
languageName: node
linkType: hard
"picomatch@npm:^2.3.1":
"picomatch@npm:^2.3.0, picomatch@npm:^2.3.1":
version: 2.3.1
resolution: "picomatch@npm:2.3.1"
checksum: 050c865ce81119c4822c45d3c84f1ced46f93a0126febae20737bd05ca20589c564d6e9226977df859ed5e03dc73f02584a2b0faad36e896936238238b0446cf
@ -31518,6 +31551,28 @@ __metadata:
languageName: node
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":
version: 5.1.5
resolution: "styled-system@npm:5.1.5"