Skip to content

Commit

Permalink
Fix preserving scroll-position in preview (sulu#6395)
Browse files Browse the repository at this point in the history
  • Loading branch information
mavuio authored Apr 29, 2024
1 parent cbe8873 commit 66f66d7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,18 @@ class Preview extends React.Component<Props> {

setContent = (previewContent: string) => {
const previewDocument = this.getPreviewDocument();

if (!previewDocument) {
return;
}

const preservedScrollPosition = this.getPreviewScrollPosition();
previewDocument.open(); // This will lose in Firefox the and safari previewDocument.location
previewDocument.write(previewContent);
previewDocument.close();

if (preservedScrollPosition) {
setTimeout(() => this.setPreviewScrollPosition(preservedScrollPosition), 0);
}
};

componentWillUnmount() {
Expand Down Expand Up @@ -251,6 +255,34 @@ class Preview extends React.Component<Props> {
return this.iframeRef.contentDocument;
};

getPreviewWindow = (): ?any => {
if (this.previewWindow) {
return this.previewWindow;
}

if (!(this.iframeRef instanceof HTMLIFrameElement)) {
return;
}

return this.iframeRef.contentWindow;
};

getPreviewScrollPosition = (): ?number => {
const previewWindow = this.getPreviewWindow();
if (previewWindow) {
return previewWindow.document?.documentElement?.scrollTop
|| previewWindow.pageYOffset
|| previewWindow.document?.body?.scrollTop;
}
};

setPreviewScrollPosition = (pos) => {
const previewWindow = this.getPreviewWindow();
if (previewWindow) {
previewWindow.scrollTo({top: pos});
}
};

@action setIframe = (iframeRef: ?Object) => {
this.iframeRef = iframeRef;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,11 @@ test('React and update preview in external window when data is changed', () => {
close: jest.fn(),
open: jest.fn(),
write: jest.fn(),
document: {
body: {
scrollTop: 10,
},
},
},
};
window.open.mockReturnValue(previewWindow);
Expand Down

0 comments on commit 66f66d7

Please sign in to comment.