Skip to content

Commit

Permalink
feat(srcDoc): updtaed handleHashChange logic
Browse files Browse the repository at this point in the history
  • Loading branch information
makhnatkin committed Oct 4, 2024
1 parent 113f842 commit 0e76f51
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/runtime/SrcDocIFrameController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {DEFAULT_IFRAME_HEIGHT_PADDING} from '../constants';

import {IEmbeddedContentController} from './IEmbeddedContentController';

const PARENT_LOADED_AND_RESIZED_TIMEOUT = 500;

const validateHostElement: (el: HTMLElement) => asserts el is HTMLIFrameElement = (el) => {
if (!(el instanceof HTMLIFrameElement && el.dataset.yfmSandboxMode === 'srcdoc')) {
throw new Error('Host element for `srcdoc` embedding mode was not configured properly');
Expand Down Expand Up @@ -96,36 +98,39 @@ export class SrcDocIFrameController extends Disposable implements IEmbeddedConte
}
}

setRootClassNames(classNames: string[] | undefined) {
return this.executeOnController((controller) => controller.setClassNames(classNames));
}

setRootStyles(styles: Record<string, string> | undefined) {
return this.executeOnController((controller) => controller.setStyles(styles));
}

private scrollToHash() {
const hash = window.location.hash.substring(1);

if (hash) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const document = this.host.contentWindow!.document;
const element = document.getElementById(hash);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
element.scrollIntoView({behavior: 'smooth'});
}
}
}

private async handleHashChange() {
await ensureIframeLoaded(this.host);

this.scrollToHash();
// цait until all iframes managed by the parent controller are fully loaded,
// and parent containers have heights properly adjusted.
setTimeout(() => {
this.scrollToHash();
}, PARENT_LOADED_AND_RESIZED_TIMEOUT);

const handleHashChange = () => this.scrollToHash();
window.addEventListener('hashchange', handleHashChange);
this.dispose.add(() => window.removeEventListener('hashchange', handleHashChange));
}

setRootClassNames(classNames: string[] | undefined) {
return this.executeOnController((controller) => controller.setClassNames(classNames));
}

setRootStyles(styles: Record<string, string> | undefined) {
return this.executeOnController((controller) => controller.setStyles(styles));
}

private async instantiateController() {
await ensureIframeLoaded(this.host);

Expand Down

0 comments on commit 0e76f51

Please sign in to comment.