Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean cancel #843

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/Document.jsx
Expand Up @@ -85,8 +85,13 @@ export default class Document extends PureComponent {
// If rendering is in progress, let's cancel it
cancelRunningTask(this.runningTask);

// If loading is in progress, let's destroy it
// If pdfjs loading is in progress, let's destroy it
if (this.loadingTask) this.loadingTask.destroy();

// If FileReader loading is in progress, let's abort it
if (this.loadFromFileTask) {
this.loadFromFileTask.abort();
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a fan of this formatting inconsistency, but honestly, that should have been linter's job.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed it

}

loadDocument = () => {
Expand Down Expand Up @@ -263,7 +268,14 @@ export default class Document extends PureComponent {
if (isBrowser) {
// File is a Blob
if (isBlob(file) || isFile(file)) {
loadFromFile(file).then((data) => {
// abort previous FileReader, if there is one
if (this.loadFromFileTask) {
this.loadFromFileTask.abort();
}

this.loadFromFileTask = loadFromFile(file);
this.loadFromFileTask.promise.then((data) => {
this.loadFromFileTask = null;
resolve({ data });
});
return;
Expand Down
7 changes: 7 additions & 0 deletions src/Page.jsx
Expand Up @@ -246,6 +246,13 @@ export class PageInternal extends PureComponent {
return { page: null };
});

// eslint-disable-next-line no-underscore-dangle
if (pdf && pdf._transport && pdf._transport.destroyed) {
this.setState({ page: false });
this.onLoadError('Attempted to load a page, but the document was destroyed');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onLoadError expects Error.

Suggested change
this.onLoadError('Attempted to load a page, but the document was destroyed');
this.onLoadError(new Error('Attempted to load a page, but the document was destroyed'));

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed it

return;
}

const cancellable = makeCancellable(pdf.getPage(pageNumber));
this.runningTask = cancellable;

Expand Down
12 changes: 9 additions & 3 deletions src/shared/utils.js
Expand Up @@ -141,9 +141,8 @@ export function isCancelException(error) {
}

export function loadFromFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();

const reader = new FileReader();
const promise = new Promise((resolve, reject) => {
reader.onload = () => resolve(new Uint8Array(reader.result));
reader.onerror = (event) => {
switch (event.target.error.code) {
Expand All @@ -163,4 +162,11 @@ export function loadFromFile(file) {

return null;
});

return {
promise,
abort: () => {
reader.abort();
},
};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering, if perhaps making the API consistent with make-cancelable-promise by changing abort to cancel wouldn't be a bettter choice.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both ok for me. I am thinking: 'cancel' is something like "I did the request, but I don't want it anymore, don't send what ever you have, no matter if finished or not" (which is what cancelable-promise does). "Abort" on the other hand is "Stop what you are doing right now". But from our perspective I guess what we want indeed is the same in both cases: don't call any callbacks. So 'cancel' would make sense.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed it in an extra commit

}
16 changes: 16 additions & 0 deletions test/LoadingOptions.jsx
Expand Up @@ -8,6 +8,8 @@ import { isFile } from './shared/propTypes';
export default function LoadingOptions({
file,
setFile,
useExternPage,
setUseExternPage,
setRender,
}) {
function onFileChange(event) {
Expand Down Expand Up @@ -122,6 +124,18 @@ export default function LoadingOptions({
Unload file
</button>
</div>

<div>
<input
id="pageOutsideOfDocument"
type="checkbox"
checked={useExternPage}
onChange={(event) => { setUseExternPage(event.target.checked); }}
/>
<label htmlFor="pageOutsideOfDocument">
Page outside of Document
</label>
</div>
</fieldset>
);
}
Expand All @@ -130,4 +144,6 @@ LoadingOptions.propTypes = {
file: isFile,
setFile: PropTypes.func.isRequired,
setRender: PropTypes.func.isRequired,
setUseExternPage: PropTypes.func.isRequired,
useExternPage: PropTypes.bool.isRequired,
};
108 changes: 106 additions & 2 deletions test/Test.jsx
Expand Up @@ -12,6 +12,8 @@ import {
loadFromFile,
} from 'react-pdf/src/shared/utils';

import { isFile as propTypeIsFile } from './shared/propTypes';

import './Test.less';

import AnnotationOptions from './AnnotationOptions';
Expand Down Expand Up @@ -54,6 +56,7 @@ export const readAsDataURL = (file) => new Promise((resolve, reject) => {

export default function Test() {
const [displayAll, setDisplayAll] = useState(false);
const [useExternPage, setUseExternPage] = useState(false);
const [externalLinkTarget, setExternalLinkTarget] = useState(null);
const [file, setFile] = useState(null);
const [fileForProps, setFileForProps] = useState(null);
Expand Down Expand Up @@ -146,7 +149,7 @@ export default function Test() {
if (isBrowser) {
// File is a Blob
if (isBlob(file) || isFile(file)) {
return { data: await loadFromFile(file) };
return { data: await loadFromFile(file).promise };
}
}
return file;
Expand Down Expand Up @@ -219,6 +222,8 @@ export default function Test() {
<LoadingOptions
file={file}
setFile={setFile}
useExternPage={useExternPage}
setUseExternPage={setUseExternPage}
setRender={setRender}
/>
<PassingOptions
Expand Down Expand Up @@ -254,7 +259,8 @@ export default function Test() {
/>
</aside>
<main className="Test__container__content">
<Document
{/* eslint-disable-next-line */}
{ !useExternPage ? <Document
{...documentProps}
className="custom-classname-document"
onClick={(event, pdf) => console.log('Clicked a document', { event, pdf })}
Expand Down Expand Up @@ -319,9 +325,107 @@ export default function Test() {
</button>
</div>
)}
{/* eslint-disable-next-line */}
</Document>
// eslint-disable-next-line indent
: <TestSeparateDocumentAndPage file={fileForProps} /> }
</main>
</div>
</div>
);
}

// test <Page> element outside of <Document> element
const TestSeparateDocumentAndPage = function (props) {
const { file } = props;
const [display, setDisplay] = useState(true);
const [displayPage, setDisplayPage] = useState(true);
const [document, setDocument] = useState(null);
const [numPages, setNumPages] = useState(0);
const [pageNumber, setPageNumber] = useState(1);
const [unountOnFile, setUnountOnFile] = useState(false);

// unmount Document as soon as file starts loading
useEffect(() => {
if (file && unountOnFile) {
setDisplay(false);
}
}, [file]);

const onDocumentLoadSuccess = (pdf) => {
console.log('Loaded a document', pdf);
if (pdf && pdf.numPages) {
setNumPages(pdf.numPages);
}
setDocument(pdf);
};

const onPageLoadSuccess = (page) => {
console.log('Loaded a page', page);
};

const onPageLoadError = (error) => {
console.log('error loading a page:', error);
};

const toggleDocument = () => {
setDisplay(!display);
};

const pageNumberDec = () => {
if (pageNumber > 1) {
setPageNumber(pageNumber - 1);
}
};

const pageNumberInc = () => {
if (pageNumber < numPages) {
setPageNumber(pageNumber + 1);
}
};

const togglePage = () => {
setDisplayPage(!displayPage);
};

return (
<div style={{ border: 'solid 1px' }}>
<button type="button" onClick={toggleDocument}>{ display ? 'remove Document' : 're-mount Document' }</button>
<button type="button" onClick={togglePage}>{ displayPage ? 'remove Page' : 're-mount Page' }</button>
<button type="button" onClick={pageNumberDec}>prev</button>
<button type="button" onClick={pageNumberInc}>next</button>
<input
id="unmountOnFileLoad"
type="checkbox"
checked={unountOnFile}
onChange={(event) => { setUnountOnFile(event.target.checked); }}
/>
<label htmlFor="unmountOnFileLoad">
unmount Document on file load
</label>

<span style={{ marginLeft: '1em' }}>
Page:
{ pageNumber }
</span>

<div style={{ border: 'solid 1px' }}>
{ !display ? null : <Document file={file} onLoadSuccess={onDocumentLoadSuccess} /> }
{ !displayPage || !document
? null
: (
<Page
pdf={document}
pageNumber={pageNumber}
onLoadSuccess={onPageLoadSuccess}
onLoadError={onPageLoadError}
/>
) }
</div>
</div>
);
};

TestSeparateDocumentAndPage.propTypes = {
file: propTypeIsFile,
};