Fix and simplify browser history handling in relation to modals

This simplifies the logic to:
- when the last modal gets closed and we're in our history buffer state, go back
- whenever a modal is open, ensure we're in a history buffer state by
  potentially pushing one
pull/1566/head
Claire 2021-07-12 17:55:40 +02:00
parent c5b4e6b708
commit 6e3d5cbca2
2 changed files with 24 additions and 18 deletions

View File

@ -76,10 +76,13 @@ export default class ModalRoot extends React.PureComponent {
this.activeElement = null; this.activeElement = null;
}).catch(console.error); }).catch(console.error);
this.handleModalClose(); this._handleModalClose();
} }
if (this.props.children && !prevProps.children) { if (this.props.children && !prevProps.children) {
this.handleModalOpen(); this._handleModalOpen();
}
if (this.props.children) {
this._ensureHistoryBuffer();
} }
} }
@ -88,22 +91,29 @@ export default class ModalRoot extends React.PureComponent {
window.removeEventListener('keydown', this.handleKeyDown); window.removeEventListener('keydown', this.handleKeyDown);
} }
handleModalClose () { _handleModalOpen () {
this._modalHistoryKey = Date.now();
this.unlistenHistory = this.history.listen((_, action) => {
if (action === 'POP') {
this.props.onClose();
}
});
}
_handleModalClose () {
this.unlistenHistory(); this.unlistenHistory();
const state = this.history.location.state; const { state } = this.history.location;
if (state && state.mastodonModalOpen) { if (state && state.mastodonModalKey === this._modalHistoryKey) {
this.history.goBack(); this.history.goBack();
} }
} }
handleModalOpen () { _ensureHistoryBuffer () {
const history = this.history; const { pathname, state } = this.history.location;
const state = {...history.location.state, mastodonModalOpen: true}; if (!state || state.mastodonModalKey !== this._modalHistoryKey) {
history.push(history.location.pathname, state); this.history.push(pathname, { ...state, mastodonModalKey: this._modalHistoryKey });
this.unlistenHistory = history.listen(() => { }
this.props.onClose();
});
} }
getSiblings = () => { getSiblings = () => {

View File

@ -59,12 +59,8 @@ export default class ModalRoot extends React.PureComponent {
backgroundColor: null, backgroundColor: null,
}; };
getSnapshotBeforeUpdate () { componentDidUpdate () {
return { visible: !!this.props.type }; if (!!this.props.type) {
}
componentDidUpdate (prevProps, prevState, { visible }) {
if (visible) {
document.body.classList.add('with-modals--active'); document.body.classList.add('with-modals--active');
document.documentElement.style.marginRight = `${getScrollbarWidth()}px`; document.documentElement.style.marginRight = `${getScrollbarWidth()}px`;
} else { } else {