mirror of
https://github.com/laurent22/joplin.git
synced 2025-02-01 19:15:01 +02:00
Desktop: New Embedded Pdf Viewer (#6681)
This commit is contained in:
parent
0191de8bb4
commit
6ea40c9895
@ -69,6 +69,7 @@ packages/tools/node_modules
|
|||||||
packages/tools/PortableAppsLauncher
|
packages/tools/PortableAppsLauncher
|
||||||
packages/turndown-plugin-gfm/
|
packages/turndown-plugin-gfm/
|
||||||
packages/turndown/
|
packages/turndown/
|
||||||
|
packages/pdf-viewer/dist
|
||||||
plugin_types/
|
plugin_types/
|
||||||
readme/
|
readme/
|
||||||
|
|
||||||
@ -1909,6 +1910,27 @@ packages/lib/uuid.js.map
|
|||||||
packages/lib/versionInfo.d.ts
|
packages/lib/versionInfo.d.ts
|
||||||
packages/lib/versionInfo.js
|
packages/lib/versionInfo.js
|
||||||
packages/lib/versionInfo.js.map
|
packages/lib/versionInfo.js.map
|
||||||
|
packages/pdf-viewer/Page.d.ts
|
||||||
|
packages/pdf-viewer/Page.js
|
||||||
|
packages/pdf-viewer/Page.js.map
|
||||||
|
packages/pdf-viewer/VerticalPages.d.ts
|
||||||
|
packages/pdf-viewer/VerticalPages.js
|
||||||
|
packages/pdf-viewer/VerticalPages.js.map
|
||||||
|
packages/pdf-viewer/hooks/useIsFocused.d.ts
|
||||||
|
packages/pdf-viewer/hooks/useIsFocused.js
|
||||||
|
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/miniViewer.d.ts
|
||||||
|
packages/pdf-viewer/miniViewer.js
|
||||||
|
packages/pdf-viewer/miniViewer.js.map
|
||||||
|
packages/pdf-viewer/pdfSource.d.ts
|
||||||
|
packages/pdf-viewer/pdfSource.js
|
||||||
|
packages/pdf-viewer/pdfSource.js.map
|
||||||
|
packages/pdf-viewer/pdfSource.test.d.ts
|
||||||
|
packages/pdf-viewer/pdfSource.test.js
|
||||||
|
packages/pdf-viewer/pdfSource.test.js.map
|
||||||
packages/plugin-repo-cli/commands/updateRelease.d.ts
|
packages/plugin-repo-cli/commands/updateRelease.d.ts
|
||||||
packages/plugin-repo-cli/commands/updateRelease.js
|
packages/plugin-repo-cli/commands/updateRelease.js
|
||||||
packages/plugin-repo-cli/commands/updateRelease.js.map
|
packages/plugin-repo-cli/commands/updateRelease.js.map
|
||||||
|
21
.gitignore
vendored
21
.gitignore
vendored
@ -1899,6 +1899,27 @@ packages/lib/uuid.js.map
|
|||||||
packages/lib/versionInfo.d.ts
|
packages/lib/versionInfo.d.ts
|
||||||
packages/lib/versionInfo.js
|
packages/lib/versionInfo.js
|
||||||
packages/lib/versionInfo.js.map
|
packages/lib/versionInfo.js.map
|
||||||
|
packages/pdf-viewer/Page.d.ts
|
||||||
|
packages/pdf-viewer/Page.js
|
||||||
|
packages/pdf-viewer/Page.js.map
|
||||||
|
packages/pdf-viewer/VerticalPages.d.ts
|
||||||
|
packages/pdf-viewer/VerticalPages.js
|
||||||
|
packages/pdf-viewer/VerticalPages.js.map
|
||||||
|
packages/pdf-viewer/hooks/useIsFocused.d.ts
|
||||||
|
packages/pdf-viewer/hooks/useIsFocused.js
|
||||||
|
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/miniViewer.d.ts
|
||||||
|
packages/pdf-viewer/miniViewer.js
|
||||||
|
packages/pdf-viewer/miniViewer.js.map
|
||||||
|
packages/pdf-viewer/pdfSource.d.ts
|
||||||
|
packages/pdf-viewer/pdfSource.js
|
||||||
|
packages/pdf-viewer/pdfSource.js.map
|
||||||
|
packages/pdf-viewer/pdfSource.test.d.ts
|
||||||
|
packages/pdf-viewer/pdfSource.test.js
|
||||||
|
packages/pdf-viewer/pdfSource.test.js.map
|
||||||
packages/plugin-repo-cli/commands/updateRelease.d.ts
|
packages/plugin-repo-cli/commands/updateRelease.d.ts
|
||||||
packages/plugin-repo-cli/commands/updateRelease.js
|
packages/plugin-repo-cli/commands/updateRelease.js
|
||||||
packages/plugin-repo-cli/commands/updateRelease.js.map
|
packages/plugin-repo-cli/commands/updateRelease.js.map
|
||||||
|
@ -614,6 +614,8 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) {
|
|||||||
resourceInfos: props.resourceInfos,
|
resourceInfos: props.resourceInfos,
|
||||||
contentMaxWidth: props.contentMaxWidth,
|
contentMaxWidth: props.contentMaxWidth,
|
||||||
mapsToLine: true,
|
mapsToLine: true,
|
||||||
|
// Always using useCustomPdfViewer for now, we can add a new setting for it in future if we need to.
|
||||||
|
useCustomPdfViewer: true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
@ -20,6 +20,7 @@ export interface MarkupToHtmlOptions {
|
|||||||
plugins?: Record<string, any>;
|
plugins?: Record<string, any>;
|
||||||
bodyOnly?: boolean;
|
bodyOnly?: boolean;
|
||||||
mapsToLine?: boolean;
|
mapsToLine?: boolean;
|
||||||
|
useCustomPdfViewer?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function useMarkupToHtml(deps: HookDependencies) {
|
export default function useMarkupToHtml(deps: HookDependencies) {
|
||||||
|
@ -653,6 +653,17 @@
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
document.addEventListener('click', webviewLib.logEnabledEventHandler(e => {
|
||||||
|
document.querySelectorAll('.media-pdf').forEach(element => {
|
||||||
|
if(!!element.contentWindow){
|
||||||
|
element.contentWindow.postMessage({
|
||||||
|
type: 'blur'
|
||||||
|
}, '*');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}));
|
||||||
|
|
||||||
let lastClientWidth_ = NaN, lastClientHeight_ = NaN, lastScrollTop_ = NaN;
|
let lastClientWidth_ = NaN, lastClientHeight_ = NaN, lastScrollTop_ = NaN;
|
||||||
|
|
||||||
window.addEventListener('resize', webviewLib.logEnabledEventHandler(() => {
|
window.addEventListener('resize', webviewLib.logEnabledEventHandler(() => {
|
||||||
|
@ -138,6 +138,7 @@
|
|||||||
"@fortawesome/fontawesome-free": "^5.13.0",
|
"@fortawesome/fontawesome-free": "^5.13.0",
|
||||||
"@joeattardi/emoji-button": "^4.6.0",
|
"@joeattardi/emoji-button": "^4.6.0",
|
||||||
"@joplin/lib": "~2.9",
|
"@joplin/lib": "~2.9",
|
||||||
|
"@joplin/pdf-viewer": "~2.9",
|
||||||
"@joplin/renderer": "~2.9",
|
"@joplin/renderer": "~2.9",
|
||||||
"async-mutex": "^0.1.3",
|
"async-mutex": "^0.1.3",
|
||||||
"codemirror": "^5.56.0",
|
"codemirror": "^5.56.0",
|
||||||
|
@ -13,46 +13,65 @@ function fileIsNewerThan(path1, path2) {
|
|||||||
return stat1.mtime > stat2.mtime;
|
return stat1.mtime > stat2.mtime;
|
||||||
}
|
}
|
||||||
|
|
||||||
function convertJsx(path) {
|
function convertJsx(paths) {
|
||||||
chdir(`${__dirname}/..`);
|
chdir(`${__dirname}/..`);
|
||||||
|
|
||||||
fs.readdirSync(path).forEach((filename) => {
|
paths.forEach(path => {
|
||||||
const jsxPath = `${path}/${filename}`;
|
fs.readdirSync(path).forEach((filename) => {
|
||||||
const p = jsxPath.split('.');
|
const jsxPath = `${path}/${filename}`;
|
||||||
if (p.length <= 1) return;
|
const p = jsxPath.split('.');
|
||||||
const ext = p[p.length - 1];
|
if (p.length <= 1) return;
|
||||||
if (ext !== 'jsx') return;
|
const ext = p[p.length - 1];
|
||||||
p.pop();
|
if (ext !== 'jsx') return;
|
||||||
|
p.pop();
|
||||||
|
|
||||||
const basePath = p.join('.');
|
const basePath = p.join('.');
|
||||||
|
|
||||||
const jsPath = `${basePath}.min.js`;
|
const jsPath = `${basePath}.min.js`;
|
||||||
|
|
||||||
if (fileIsNewerThan(jsxPath, jsPath)) {
|
if (fileIsNewerThan(jsxPath, jsPath)) {
|
||||||
console.info(`Compiling ${jsxPath}...`);
|
console.info(`Compiling ${jsxPath}...`);
|
||||||
|
|
||||||
// { shell: true } is needed to get it working on Windows:
|
// { shell: true } is needed to get it working on Windows:
|
||||||
// https://discourse.joplinapp.org/t/attempting-to-build-on-windows/22559/12
|
// https://discourse.joplinapp.org/t/attempting-to-build-on-windows/22559/12
|
||||||
const result = spawnSync('yarn', ['run', 'babel', '--presets', 'react', '--out-file', jsPath, jsxPath], { shell: true });
|
const result = spawnSync('yarn', ['run', 'babel', '--presets', 'react', '--out-file', jsPath, jsxPath], { shell: true });
|
||||||
if (result.status !== 0) {
|
if (result.status !== 0) {
|
||||||
const msg = [];
|
const msg = [];
|
||||||
if (result.stdout) msg.push(result.stdout.toString());
|
if (result.stdout) msg.push(result.stdout.toString());
|
||||||
if (result.stderr) msg.push(result.stderr.toString());
|
if (result.stderr) msg.push(result.stderr.toString());
|
||||||
console.error(msg.join('\n'));
|
console.error(msg.join('\n'));
|
||||||
if (result.error) console.error(result.error);
|
if (result.error) console.error(result.error);
|
||||||
process.exit(result.status);
|
process.exit(result.status);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = function() {
|
function build(path) {
|
||||||
convertJsx(`${__dirname}/../gui`);
|
chdir(path);
|
||||||
convertJsx(`${__dirname}/../gui/MainScreen`);
|
|
||||||
convertJsx(`${__dirname}/../gui/NoteList`);
|
const result = spawnSync('yarn', ['run', 'build'], { shell: true });
|
||||||
convertJsx(`${__dirname}/../plugins`);
|
if (result.status !== 0) {
|
||||||
|
const msg = [];
|
||||||
|
if (result.stdout) msg.push(result.stdout.toString());
|
||||||
|
if (result.stderr) msg.push(result.stderr.toString());
|
||||||
|
console.error(msg.join('\n'));
|
||||||
|
if (result.error) console.error(result.error);
|
||||||
|
process.exit(result.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = function() {
|
||||||
|
convertJsx([
|
||||||
|
`${__dirname}/../gui`,
|
||||||
|
`${__dirname}/../gui/MainScreen`,
|
||||||
|
`${__dirname}/../gui/NoteList`,
|
||||||
|
`${__dirname}/../plugins`,
|
||||||
|
]);
|
||||||
|
|
||||||
|
build(`${__dirname}/../../pdf-viewer`);
|
||||||
|
|
||||||
// TODO: should get from node_modules @joplin/lib
|
|
||||||
const libContent = [
|
const libContent = [
|
||||||
fs.readFileSync(`${basePath}/packages/lib/string-utils-common.js`, 'utf8'),
|
fs.readFileSync(`${basePath}/packages/lib/string-utils-common.js`, 'utf8'),
|
||||||
fs.readFileSync(`${basePath}/packages/lib/markJsUtils.js`, 'utf8'),
|
fs.readFileSync(`${basePath}/packages/lib/markJsUtils.js`, 'utf8'),
|
||||||
|
@ -72,6 +72,10 @@ async function main() {
|
|||||||
src: langSourceDir,
|
src: langSourceDir,
|
||||||
dest: `${buildLibDir}/tinymce/langs`,
|
dest: `${buildLibDir}/tinymce/langs`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
src: resolve(__dirname, '../../pdf-viewer/dist'),
|
||||||
|
dest: `${buildLibDir}/@joplin/pdf-viewer`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const files = [
|
const files = [
|
||||||
@ -87,6 +91,10 @@ async function main() {
|
|||||||
src: resolve(__dirname, '../../lib/services/plugins/sandboxProxy.js'),
|
src: resolve(__dirname, '../../lib/services/plugins/sandboxProxy.js'),
|
||||||
dest: `${buildLibDir}/@joplin/lib/services/plugins/sandboxProxy.js`,
|
dest: `${buildLibDir}/@joplin/lib/services/plugins/sandboxProxy.js`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
src: resolve(__dirname, '../../pdf-viewer/index.html'),
|
||||||
|
dest: `${buildLibDir}/@joplin/pdf-viewer/index.html`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
// First we delete all the destination directories, then we copy the files.
|
// First we delete all the destination directories, then we copy the files.
|
||||||
|
1
packages/pdf-viewer/.gitignore
vendored
Normal file
1
packages/pdf-viewer/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
dist/*
|
100
packages/pdf-viewer/Page.tsx
Normal file
100
packages/pdf-viewer/Page.tsx
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
import useIsVisible from './hooks/useIsVisible';
|
||||||
|
import { PdfData, ScaledSize } from './pdfSource';
|
||||||
|
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
|
||||||
|
|
||||||
|
require('./pages.css');
|
||||||
|
|
||||||
|
export interface PageProps {
|
||||||
|
pdf: PdfData;
|
||||||
|
pageNo: number;
|
||||||
|
focusOnLoad: boolean;
|
||||||
|
isAnchored: boolean;
|
||||||
|
scaledSize: ScaledSize;
|
||||||
|
isDarkTheme: boolean;
|
||||||
|
container: React.MutableRefObject<HTMLElement>;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 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;
|
||||||
|
try {
|
||||||
|
const viewport = page.getViewport({ scale: props.scaledSize.scale || 1.0 });
|
||||||
|
const canvas = canvasRef.current;
|
||||||
|
canvas.width = viewport.width;
|
||||||
|
canvas.height = viewport.height;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
const pageTimestamp = new Date().getTime();
|
||||||
|
setTimestamp(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) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cont();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setScale(props.scaledSize.scale);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
error.message = `Error rendering page no. ${props.pageNo}: ${error.message}`;
|
||||||
|
setError(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}, [page, props.scaledSize, isVisible]);
|
||||||
|
|
||||||
|
useAsyncEffect(async (event: AsyncEffectEvent) => {
|
||||||
|
if (page || !isVisible || !props.pdf) return;
|
||||||
|
try {
|
||||||
|
const _page = await props.pdf.getPage(props.pageNo);
|
||||||
|
if (event.cancelled) return;
|
||||||
|
setPage(_page);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Page load error', props.pageNo, error);
|
||||||
|
setError(error);
|
||||||
|
}
|
||||||
|
}, [page, props.scaledSize, isVisible]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (props.focusOnLoad) {
|
||||||
|
props.container.current.scrollTop = wrapperRef.current.offsetTop;
|
||||||
|
// console.warn('setting focus on page', props.pageNo, wrapperRef.current.offsetTop);
|
||||||
|
}
|
||||||
|
}, [props.focusOnLoad]);
|
||||||
|
|
||||||
|
let style: any = {};
|
||||||
|
if (props.scaledSize) {
|
||||||
|
style = {
|
||||||
|
...style,
|
||||||
|
width: props.scaledSize.width,
|
||||||
|
height: props.scaledSize.height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-wrapper" 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>
|
||||||
|
);
|
||||||
|
}
|
17
packages/pdf-viewer/README.md
Normal file
17
packages/pdf-viewer/README.md
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
# PDF VIEWER
|
||||||
|
|
||||||
|
//Todo
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import viewer from '@joplin/pdf-viewer';
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
//Todo
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
59
packages/pdf-viewer/VerticalPages.tsx
Normal file
59
packages/pdf-viewer/VerticalPages.tsx
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||||
|
import { PdfData, ScaledSize } from './pdfSource';
|
||||||
|
import Page from './Page';
|
||||||
|
|
||||||
|
require('./pages.css');
|
||||||
|
|
||||||
|
|
||||||
|
export interface VerticalPagesProps {
|
||||||
|
pdf: PdfData;
|
||||||
|
isDarkTheme: boolean;
|
||||||
|
anchorPage: number;
|
||||||
|
container: React.MutableRefObject<HTMLElement>;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export default function VerticalPages(props: VerticalPagesProps) {
|
||||||
|
const [scaledSize, setScaledSize] = useState<ScaledSize>(null);
|
||||||
|
const innerContainerEl = useRef<HTMLDivElement>(null);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
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);
|
||||||
|
if (cancelled) return;
|
||||||
|
setScaledSize(scaledSize);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onResize = () => {
|
||||||
|
if (resizeTimer) {
|
||||||
|
clearTimeout(resizeTimer);
|
||||||
|
resizeTimer = null;
|
||||||
|
}
|
||||||
|
resizeTimer = window.setTimeout(updateSize, 200);
|
||||||
|
};
|
||||||
|
window.addEventListener('resize', onResize);
|
||||||
|
updateSize()
|
||||||
|
.catch(console.error);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
window.removeEventListener('resize', onResize);
|
||||||
|
if (resizeTimer) {
|
||||||
|
clearTimeout(resizeTimer);
|
||||||
|
resizeTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [props.pdf]);
|
||||||
|
|
||||||
|
return (<div className='pages-holder' ref={innerContainerEl} >
|
||||||
|
{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}
|
||||||
|
isDarkTheme={props.isDarkTheme} scaledSize={scaledSize} container={props.container} key={i} />;
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
</div>);
|
||||||
|
}
|
14
packages/pdf-viewer/config/cssTransform.js
Normal file
14
packages/pdf-viewer/config/cssTransform.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// This is a custom Jest transformer turning style imports into empty objects.
|
||||||
|
// http://facebook.github.io/jest/docs/en/webpack.html
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
process() {
|
||||||
|
return 'module.exports = {};';
|
||||||
|
},
|
||||||
|
getCacheKey() {
|
||||||
|
// The output is always the same.
|
||||||
|
return 'cssTransform';
|
||||||
|
},
|
||||||
|
};
|
BIN
packages/pdf-viewer/config/welcome.pdf
Normal file
BIN
packages/pdf-viewer/config/welcome.pdf
Normal file
Binary file not shown.
26
packages/pdf-viewer/hooks/useIsFocused.ts
Normal file
26
packages/pdf-viewer/hooks/useIsFocused.ts
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
const useIsFocused = () => {
|
||||||
|
const [isFocused, setIsFocused] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onMessage = (event: MessageEvent) => {
|
||||||
|
if (event.data.type === 'blur') {
|
||||||
|
setIsFocused(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onClick = (_event: MouseEvent) => {
|
||||||
|
setIsFocused(true);
|
||||||
|
};
|
||||||
|
window.addEventListener('message', onMessage);
|
||||||
|
document.addEventListener('click', onClick);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('message', onMessage);
|
||||||
|
document.removeEventListener('click', onClick);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return isFocused;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useIsFocused;
|
37
packages/pdf-viewer/hooks/useIsVisible.ts
Normal file
37
packages/pdf-viewer/hooks/useIsVisible.ts
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
|
||||||
|
const useIsVisible = (elementRef: React.MutableRefObject<HTMLElement>, rootRef: React.MutableRefObject<HTMLElement>) => {
|
||||||
|
const [isVisible, setIsVisible] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
let observer: IntersectionObserver = null;
|
||||||
|
if (elementRef.current) {
|
||||||
|
observer = new IntersectionObserver((entries, _observer) => {
|
||||||
|
let visible = false;
|
||||||
|
entries.forEach((entry) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
visible = true;
|
||||||
|
setIsVisible(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!visible) {
|
||||||
|
setIsVisible(false);
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
root: rootRef.current,
|
||||||
|
rootMargin: '0px 0px 0px 0px',
|
||||||
|
threshold: 0,
|
||||||
|
});
|
||||||
|
observer.observe(elementRef.current);
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
if (observer) {
|
||||||
|
observer.disconnect();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return isVisible;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useIsVisible;
|
19
packages/pdf-viewer/index.html
Normal file
19
packages/pdf-viewer/index.html
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
<div id="pdf-root">
|
||||||
|
<div id="splash-screen">
|
||||||
|
Loading PDF...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<style>
|
||||||
|
#pdf-root {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
#splash-screen{
|
||||||
|
display:flex;
|
||||||
|
justify-content:center;
|
||||||
|
align-items:center;
|
||||||
|
width:100%;
|
||||||
|
height:100%;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script src="./main.js"></script>
|
172
packages/pdf-viewer/jest.config.js
Normal file
172
packages/pdf-viewer/jest.config.js
Normal file
@ -0,0 +1,172 @@
|
|||||||
|
// For a detailed explanation regarding each configuration property, visit:
|
||||||
|
// https://jestjs.io/docs/en/configuration.html
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
// All imported modules in your tests should be mocked automatically
|
||||||
|
// automock: false,
|
||||||
|
|
||||||
|
// Stop running tests after `n` failures
|
||||||
|
// bail: 0,
|
||||||
|
|
||||||
|
// The directory where Jest should store its cached dependency information
|
||||||
|
// cacheDirectory: "/tmp/jest_rs",
|
||||||
|
|
||||||
|
// Automatically clear mock calls and instances between every test
|
||||||
|
// clearMocks: false,
|
||||||
|
|
||||||
|
// Indicates whether the coverage information should be collected while executing the test
|
||||||
|
// collectCoverage: false,
|
||||||
|
|
||||||
|
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
||||||
|
// collectCoverageFrom: undefined,
|
||||||
|
|
||||||
|
// The directory where Jest should output its coverage files
|
||||||
|
// coverageDirectory: undefined,
|
||||||
|
|
||||||
|
// Indicates which provider should be used to instrument code for coverage
|
||||||
|
coverageProvider: 'v8',
|
||||||
|
|
||||||
|
preset: 'ts-jest',
|
||||||
|
|
||||||
|
// A list of reporter names that Jest uses when writing coverage reports
|
||||||
|
// coverageReporters: [
|
||||||
|
// "json",
|
||||||
|
// "text",
|
||||||
|
// "lcov",
|
||||||
|
// "clover"
|
||||||
|
// ],
|
||||||
|
|
||||||
|
// An object that configures minimum threshold enforcement for coverage results
|
||||||
|
// coverageThreshold: undefined,
|
||||||
|
|
||||||
|
// A path to a custom dependency extractor
|
||||||
|
// dependencyExtractor: undefined,
|
||||||
|
|
||||||
|
// Make calling deprecated APIs throw helpful error messages
|
||||||
|
// errorOnDeprecated: false,
|
||||||
|
|
||||||
|
// Force coverage collection from ignored files using an array of glob patterns
|
||||||
|
// forceCoverageMatch: [],
|
||||||
|
|
||||||
|
// A path to a module which exports an async function that is triggered once before all test suites
|
||||||
|
// globalSetup: undefined,
|
||||||
|
|
||||||
|
// A path to a module which exports an async function that is triggered once after all test suites
|
||||||
|
// globalTeardown: undefined,
|
||||||
|
|
||||||
|
// A set of global variables that need to be available in all test environments
|
||||||
|
// globals: {},
|
||||||
|
|
||||||
|
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
||||||
|
// maxWorkers: "50%",
|
||||||
|
|
||||||
|
// An array of file extensions your modules use
|
||||||
|
// moduleFileExtensions: [
|
||||||
|
// "js",
|
||||||
|
// "json",
|
||||||
|
// "jsx",
|
||||||
|
// "ts",
|
||||||
|
// "tsx",
|
||||||
|
// "node"
|
||||||
|
// ],
|
||||||
|
|
||||||
|
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
||||||
|
// moduleNameMapper: {},
|
||||||
|
|
||||||
|
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
||||||
|
// modulePathIgnorePatterns: [],
|
||||||
|
|
||||||
|
// Activates notifications for test results
|
||||||
|
// notify: false,
|
||||||
|
|
||||||
|
// An enum that specifies notification mode. Requires { notify: true }
|
||||||
|
// notifyMode: "failure-change",
|
||||||
|
|
||||||
|
// A preset that is used as a base for Jest's configuration
|
||||||
|
// preset: undefined,
|
||||||
|
|
||||||
|
// Run tests from one or more projects
|
||||||
|
// projects: undefined,
|
||||||
|
|
||||||
|
// Use this configuration option to add custom reporters to Jest
|
||||||
|
// reporters: undefined,
|
||||||
|
|
||||||
|
// Automatically reset mock state between every test
|
||||||
|
// resetMocks: false,
|
||||||
|
|
||||||
|
// Reset the module registry before running each individual test
|
||||||
|
// resetModules: false,
|
||||||
|
|
||||||
|
// A path to a custom resolver
|
||||||
|
// resolver: undefined,
|
||||||
|
|
||||||
|
// Automatically restore mock state between every test
|
||||||
|
// restoreMocks: false,
|
||||||
|
|
||||||
|
// The root directory that Jest should scan for tests and modules within
|
||||||
|
// rootDir: undefined,
|
||||||
|
|
||||||
|
// A list of paths to directories that Jest should use to search for files in
|
||||||
|
roots: [
|
||||||
|
'<rootDir>',
|
||||||
|
],
|
||||||
|
|
||||||
|
// Allows you to use a custom runner instead of Jest's default test runner
|
||||||
|
// runner: "jest-runner",
|
||||||
|
|
||||||
|
// The paths to modules that run some code to configure or set up the testing environment before each test
|
||||||
|
// setupFiles: [],
|
||||||
|
|
||||||
|
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
||||||
|
// setupFilesAfterEnv: [],
|
||||||
|
|
||||||
|
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
||||||
|
// slowTestThreshold: 5,
|
||||||
|
|
||||||
|
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
||||||
|
// snapshotSerializers: [],
|
||||||
|
|
||||||
|
// The test environment that will be used for testing
|
||||||
|
testEnvironment: 'jsdom',
|
||||||
|
|
||||||
|
// Options that will be passed to the testEnvironment
|
||||||
|
// testEnvironmentOptions: {},
|
||||||
|
|
||||||
|
// Adds a location field to test results
|
||||||
|
// testLocationInResults: false,
|
||||||
|
|
||||||
|
// The glob patterns Jest uses to detect test files
|
||||||
|
testMatch: [
|
||||||
|
'**/*.test.ts',
|
||||||
|
],
|
||||||
|
|
||||||
|
// The regexp pattern or array of patterns that Jest uses to detect test files
|
||||||
|
// testRegex: [],
|
||||||
|
|
||||||
|
// This option allows the use of a custom results processor
|
||||||
|
// testResultsProcessor: undefined,
|
||||||
|
|
||||||
|
// This option allows use of a custom test runner
|
||||||
|
// testRunner: "jasmine2",
|
||||||
|
|
||||||
|
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
|
||||||
|
// testURL: "http://localhost",
|
||||||
|
|
||||||
|
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
|
||||||
|
// timers: "real",
|
||||||
|
|
||||||
|
// A map from regular expressions to paths to transformers
|
||||||
|
// transform: undefined,
|
||||||
|
|
||||||
|
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
||||||
|
// unmockedModulePathPatterns: undefined,
|
||||||
|
|
||||||
|
// Indicates whether each individual test should be reported during the run
|
||||||
|
// verbose: undefined,
|
||||||
|
|
||||||
|
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
||||||
|
// watchPathIgnorePatterns: [],
|
||||||
|
|
||||||
|
// Whether to use watchman for file crawling
|
||||||
|
// watchman: true,
|
||||||
|
};
|
60
packages/pdf-viewer/miniViewer.tsx
Normal file
60
packages/pdf-viewer/miniViewer.tsx
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
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 useIsFocused from './hooks/useIsFocused';
|
||||||
|
import { PdfData } from './pdfSource';
|
||||||
|
import VerticalPages from './VerticalPages';
|
||||||
|
import useAsyncEffect, { AsyncEffectEvent } from '@joplin/lib/hooks/useAsyncEffect';
|
||||||
|
|
||||||
|
require('./viewer.css');
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
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">
|
||||||
|
<div>Loading pdf..</div>
|
||||||
|
</div>);
|
||||||
|
}
|
||||||
|
|
||||||
|
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} />
|
||||||
|
</div>
|
||||||
|
<div className='app-bottom-bar'>
|
||||||
|
<div className='pdf-info'>
|
||||||
|
{pdf.pageCount} pages
|
||||||
|
</div>
|
||||||
|
<div>{isFocused ? '' : 'Click to enable scroll'}</div>
|
||||||
|
</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')
|
||||||
|
);
|
52
packages/pdf-viewer/package-lock.json
generated
Normal file
52
packages/pdf-viewer/package-lock.json
generated
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
{
|
||||||
|
"name": "@joplin/pdf-viewer",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 1,
|
||||||
|
"requires": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@types/prop-types": {
|
||||||
|
"version": "15.7.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz",
|
||||||
|
"integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
|
"@types/react": {
|
||||||
|
"version": "18.0.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.0.14.tgz",
|
||||||
|
"integrity": "sha512-x4gGuASSiWmo0xjDLpm5mPb52syZHJx02VKbqUKdLmKtAwIh63XClGsiTI1K6DO5q7ox4xAsQrU+Gl3+gGXF9Q==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"@types/prop-types": "*",
|
||||||
|
"@types/scheduler": "*",
|
||||||
|
"csstype": "^3.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"version": "16.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-16.9.0.tgz",
|
||||||
|
"integrity": "sha512-OL2lk7LYGjxn4b0efW3Pvf2KBVP0y1v3wip1Bp7nA79NkOpElH98q3WdCEdDj93b2b0zaeBG9DvriuKjIK5xDA==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"@types/react": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"@types/scheduler": {
|
||||||
|
"version": "0.16.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.2.tgz",
|
||||||
|
"integrity": "sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
|
"csstype": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-uX1KG+x9h5hIJsaKR9xHUeUraxf8IODOwq9JLNPq6BwB04a/xgpq3rcx47l5BZu5zBPlgD342tdke3Hom/nJRA==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
|
"typescript": {
|
||||||
|
"version": "4.5.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz",
|
||||||
|
"integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==",
|
||||||
|
"dev": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
42
packages/pdf-viewer/package.json
Normal file
42
packages/pdf-viewer/package.json
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"name": "@joplin/pdf-viewer",
|
||||||
|
"version": "2.9.0",
|
||||||
|
"description": "Provides embedded PDF viewers for Joplin",
|
||||||
|
"main": "dist/main.js",
|
||||||
|
"types": "src/main.ts",
|
||||||
|
"private": true,
|
||||||
|
"publishConfig": {
|
||||||
|
"access": "restricted"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"tsc": "tsc --project tsconfig.json",
|
||||||
|
"watch": "tsc --watch --preserveWatchOutput --project tsconfig.json",
|
||||||
|
"build": "webpack --config webpack.config.js",
|
||||||
|
"test": "jest",
|
||||||
|
"test-ci": "yarn test"
|
||||||
|
},
|
||||||
|
"author": "Joplin",
|
||||||
|
"license": "MIT",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/jest": "^28.1.6",
|
||||||
|
"@types/pdfjs-dist": "^2.10.378",
|
||||||
|
"@types/react": "^18.0.14",
|
||||||
|
"@types/react-dom": "^16.9.0",
|
||||||
|
"babel-jest": "^28.1.3",
|
||||||
|
"css-loader": "^6.7.1",
|
||||||
|
"jest": "^28.1.3",
|
||||||
|
"jest-environment-jsdom": "^28.1.3",
|
||||||
|
"style-loader": "^3.3.1",
|
||||||
|
"ts-jest": "^28.0.7",
|
||||||
|
"ts-loader": "^9.3.0",
|
||||||
|
"typescript": "^4.0.5",
|
||||||
|
"webpack": "^5.73.0",
|
||||||
|
"webpack-cli": "^4.10.0"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@joplin/lib": "workspace:^",
|
||||||
|
"pdfjs-dist": "^2.14.305",
|
||||||
|
"react": "16.13.1",
|
||||||
|
"react-dom": "16.9.0"
|
||||||
|
}
|
||||||
|
}
|
76
packages/pdf-viewer/pages.css
Normal file
76
packages/pdf-viewer/pages.css
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
::-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;
|
||||||
|
}
|
56
packages/pdf-viewer/pdfSource.test.ts
Normal file
56
packages/pdf-viewer/pdfSource.test.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import { PdfData } from './pdfSource';
|
||||||
|
import * as pdfjsLib from 'pdfjs-dist';
|
||||||
|
import { readFile } from 'fs';
|
||||||
|
import { resolve } from 'path';
|
||||||
|
|
||||||
|
pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/legacy/build/pdf.worker.entry');
|
||||||
|
|
||||||
|
const pdfFilePath1 = resolve('config/welcome.pdf');
|
||||||
|
|
||||||
|
|
||||||
|
function loadFile(filePath: string) {
|
||||||
|
return new Promise<Uint8Array>((resolve, reject) => {
|
||||||
|
readFile(filePath, (err, data) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
} else {
|
||||||
|
resolve(new Uint8Array((data)));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('pdfData', () => {
|
||||||
|
|
||||||
|
test('Should have correct page count', async () => {
|
||||||
|
const file = await loadFile(pdfFilePath1);
|
||||||
|
const pdf = new PdfData();
|
||||||
|
await pdf.loadDoc(file);
|
||||||
|
expect(pdf.pageCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Should throw error on invalid file', async () => {
|
||||||
|
const pdf = new PdfData();
|
||||||
|
await expect(async () => {
|
||||||
|
await pdf.loadDoc('');
|
||||||
|
}).rejects.toThrowError();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Should get correct page size', async () => {
|
||||||
|
const file = await loadFile(pdfFilePath1);
|
||||||
|
const pdf = new PdfData();
|
||||||
|
await pdf.loadDoc(file);
|
||||||
|
const size = await pdf.getPageSize();
|
||||||
|
expect(size.height).toBeCloseTo(841.91998);
|
||||||
|
expect(size.width).toBeCloseTo(594.95996);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Should calculate scaled size', async () => {
|
||||||
|
const file = await loadFile(pdfFilePath1);
|
||||||
|
const pdf = new PdfData();
|
||||||
|
await pdf.loadDoc(file);
|
||||||
|
const scaledSize = await pdf.getScaledSize(null, 200);
|
||||||
|
expect(scaledSize.scale).toBeCloseTo(0.336157);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
74
packages/pdf-viewer/pdfSource.ts
Normal file
74
packages/pdf-viewer/pdfSource.ts
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import * as pdfjsLib from 'pdfjs-dist';
|
||||||
|
|
||||||
|
|
||||||
|
export interface ScaledSize {
|
||||||
|
height: number;
|
||||||
|
width: number;
|
||||||
|
scale: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PdfData {
|
||||||
|
public url: string | Uint8Array;
|
||||||
|
private doc: any = null;
|
||||||
|
public pageCount: number = null;
|
||||||
|
private pages: any = {};
|
||||||
|
private pageSize: {
|
||||||
|
height: number;
|
||||||
|
width: number;
|
||||||
|
} = null;
|
||||||
|
|
||||||
|
public constructor() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public loadDoc = async (url: string | Uint8Array) => {
|
||||||
|
this.url = url;
|
||||||
|
const loadingTask = pdfjsLib.getDocument(url);
|
||||||
|
try {
|
||||||
|
const pdfDocument: any = await loadingTask.promise;
|
||||||
|
this.doc = pdfDocument;
|
||||||
|
this.pageCount = pdfDocument.numPages;
|
||||||
|
} catch (error) {
|
||||||
|
error.message = `Could not load document: ${error.message}`;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public getPage = async (pageNo: number) => {
|
||||||
|
if (!this.doc) {
|
||||||
|
throw new Error('Document not loaded');
|
||||||
|
}
|
||||||
|
if (!this.pages[pageNo]) {
|
||||||
|
this.pages[pageNo] = await this.doc.getPage(pageNo);
|
||||||
|
}
|
||||||
|
return this.pages[pageNo];
|
||||||
|
};
|
||||||
|
|
||||||
|
public getPageSize = async () => {
|
||||||
|
if (!this.pageSize) {
|
||||||
|
const page = await this.getPage(1);
|
||||||
|
const viewport = page.getViewport({ scale: 1.0 });
|
||||||
|
this.pageSize = {
|
||||||
|
height: viewport.height,
|
||||||
|
width: viewport.width,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return this.pageSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
public getScaledSize = async (height: number = null, width: number = null): Promise<ScaledSize> => {
|
||||||
|
const actualSize = await this.getPageSize();
|
||||||
|
let scale = 1.0;
|
||||||
|
if (height && width) {
|
||||||
|
scale = Math.min(height / actualSize.height, width / actualSize.width);
|
||||||
|
} else if (height) {
|
||||||
|
scale = height / actualSize.height;
|
||||||
|
} else if (width) {
|
||||||
|
scale = width / actualSize.width;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
height: actualSize.height * scale,
|
||||||
|
width: actualSize.width * scale,
|
||||||
|
scale,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
17
packages/pdf-viewer/tsconfig.json
Normal file
17
packages/pdf-viewer/tsconfig.json
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||||
|
"esModuleInterop": true,
|
||||||
|
/* Required since pdf.js does not have a ts binding.*/
|
||||||
|
"allowJs": true,
|
||||||
|
},
|
||||||
|
"rootDir": ".",
|
||||||
|
"include": [
|
||||||
|
"**/*.ts",
|
||||||
|
"**/*.tsx",
|
||||||
|
],
|
||||||
|
"exclude": [
|
||||||
|
"**/node_modules",
|
||||||
|
],
|
||||||
|
}
|
98
packages/pdf-viewer/viewer.css
Normal file
98
packages/pdf-viewer/viewer.css
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
*,
|
||||||
|
*::before,
|
||||||
|
*::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--white: rgb(255, 255, 255);
|
||||||
|
--light: rgb(219, 219, 219);
|
||||||
|
--grey: rgb(128, 128, 128);
|
||||||
|
--dark: rgb(1, 0, 34);
|
||||||
|
--black: rgb(24, 24, 24);
|
||||||
|
|
||||||
|
--red: #ff000d;
|
||||||
|
--blue: #00A8FF;
|
||||||
|
--green: rgb(0, 167, 28);
|
||||||
|
--purple: rgb(132, 0, 255);
|
||||||
|
--orange: rgb(255, 164, 27);
|
||||||
|
|
||||||
|
--primary: var(--black);
|
||||||
|
--secondary: var(--dark);
|
||||||
|
--tertiary: var(--light);
|
||||||
|
--bg: var(--white);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] {
|
||||||
|
--primary: var(--white);
|
||||||
|
--secondary: var(--light);
|
||||||
|
--tertiary: var(--dark);
|
||||||
|
--bg: var(--black);
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
-ms-text-size-adjust: 100%;
|
||||||
|
-ms-overflow-style: scrollbar;
|
||||||
|
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0px;
|
||||||
|
padding: 0px;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', sans-serif;
|
||||||
|
font-size: var(--s);
|
||||||
|
font-weight: 300;
|
||||||
|
color: var(--secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
hr {
|
||||||
|
box-sizing: content-box;
|
||||||
|
height: 0;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mini-app {
|
||||||
|
display: grid;
|
||||||
|
grid-template-rows: auto 2rem;
|
||||||
|
height: 100vh;
|
||||||
|
width: 100vw;
|
||||||
|
background-color: var(--bg);
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
border: solid thin var(--tertiary);
|
||||||
|
padding-top: 0.6rem;
|
||||||
|
padding-right: 0.25rem;
|
||||||
|
background-color: rgb(240, 241, 245);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mini-app.focused {
|
||||||
|
border: solid thin var(--grey);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mini-app.loading {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .mini-app {
|
||||||
|
background-color: rgb(54, 54, 54);
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-bottom-bar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--grey);
|
||||||
|
}
|
29
packages/pdf-viewer/webpack.config.js
Normal file
29
packages/pdf-viewer/webpack.config.js
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
entry: {
|
||||||
|
main: './miniViewer.tsx',
|
||||||
|
'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry',
|
||||||
|
},
|
||||||
|
module: {
|
||||||
|
rules: [
|
||||||
|
{
|
||||||
|
test: /\.tsx?$/,
|
||||||
|
use: 'ts-loader',
|
||||||
|
exclude: /node_modules/,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
test: /\.css$/i,
|
||||||
|
use: ['style-loader', 'css-loader'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
extensions: ['.tsx', '.ts', '.js'],
|
||||||
|
},
|
||||||
|
output: {
|
||||||
|
filename: '[name].js',
|
||||||
|
path: path.resolve(__dirname, 'dist'),
|
||||||
|
clean: true,
|
||||||
|
},
|
||||||
|
};
|
@ -27,6 +27,7 @@ export interface RenderOptions {
|
|||||||
codeHighlightCacheKey?: string;
|
codeHighlightCacheKey?: string;
|
||||||
plainResourceRendering?: boolean;
|
plainResourceRendering?: boolean;
|
||||||
mapsToLine?: boolean;
|
mapsToLine?: boolean;
|
||||||
|
useCustomPdfViewer?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RendererRule {
|
interface RendererRule {
|
||||||
@ -170,7 +171,7 @@ export interface RuleOptions {
|
|||||||
audioPlayerEnabled: boolean;
|
audioPlayerEnabled: boolean;
|
||||||
videoPlayerEnabled: boolean;
|
videoPlayerEnabled: boolean;
|
||||||
pdfViewerEnabled: boolean;
|
pdfViewerEnabled: boolean;
|
||||||
|
useCustomPdfViewer: boolean;
|
||||||
itemIdToUrl?: ItemIdToUrlHandler;
|
itemIdToUrl?: ItemIdToUrlHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,6 +7,8 @@ export interface Options {
|
|||||||
audioPlayerEnabled: boolean;
|
audioPlayerEnabled: boolean;
|
||||||
videoPlayerEnabled: boolean;
|
videoPlayerEnabled: boolean;
|
||||||
pdfViewerEnabled: boolean;
|
pdfViewerEnabled: boolean;
|
||||||
|
useCustomPdfViewer: boolean;
|
||||||
|
theme: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resourceUrl(resourceFullPath: string): string {
|
function resourceUrl(resourceFullPath: string): string {
|
||||||
@ -42,6 +44,16 @@ export default function(link: Link, options: Options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (options.pdfViewerEnabled && resource.mime === 'application/pdf') {
|
if (options.pdfViewerEnabled && resource.mime === 'application/pdf') {
|
||||||
|
if (options.useCustomPdfViewer) {
|
||||||
|
let anchorPageNo = null;
|
||||||
|
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}"` : ''}
|
||||||
|
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>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -375,7 +375,12 @@ export default function(theme: any, options: Options = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.media-player.media-pdf {
|
.media-player.media-pdf {
|
||||||
min-height: 100vh;
|
min-height: 35rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1000px;
|
||||||
|
margin: 0;
|
||||||
|
border: 0;
|
||||||
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Clear the CODE style if the element is within a joplin-editable block */
|
/* Clear the CODE style if the element is within a joplin-editable block */
|
||||||
|
@ -135,6 +135,7 @@ async function main() {
|
|||||||
await updatePackageVersion(`${rootDir}/packages/renderer/package.json`, majorMinorVersion, options);
|
await updatePackageVersion(`${rootDir}/packages/renderer/package.json`, majorMinorVersion, options);
|
||||||
await updatePackageVersion(`${rootDir}/packages/server/package.json`, majorMinorVersion, options);
|
await updatePackageVersion(`${rootDir}/packages/server/package.json`, majorMinorVersion, options);
|
||||||
await updatePackageVersion(`${rootDir}/packages/tools/package.json`, majorMinorVersion, options);
|
await updatePackageVersion(`${rootDir}/packages/tools/package.json`, majorMinorVersion, options);
|
||||||
|
await updatePackageVersion(`${rootDir}/packages/pdf-viewer/package.json`, majorMinorVersion, options);
|
||||||
|
|
||||||
if (options.updateVersion) {
|
if (options.updateVersion) {
|
||||||
await updateGradleVersion(`${rootDir}/packages/app-mobile/android/app/build.gradle`, majorMinorVersion);
|
await updateGradleVersion(`${rootDir}/packages/app-mobile/android/app/build.gradle`, majorMinorVersion);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user