Skip to content

Commit

Permalink
feat(editor) Use beforeunload event to catch unintended navigation in…
Browse files Browse the repository at this point in the history
… live mode (#4739)
  • Loading branch information
Rheeseyb authored Jan 15, 2024
1 parent 15cd213 commit 046cd91
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 19 deletions.
22 changes: 14 additions & 8 deletions editor/src/components/editor/editor-component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,17 @@ export const EditorComponentInner = React.memo((props: EditorProps) => {
}, 0)
}, [mode.type, dispatch])

const onBeforeUnload = React.useCallback(
(event: BeforeUnloadEvent) => {
if (mode.type === 'live') {
// Catch and check unintended navigation when the user is in live mode
event.preventDefault()
event.returnValue = ''
}
},
[mode.type],
)

const onWindowKeyDown = React.useCallback(
(event: KeyboardEvent) => {
let actions: Array<EditorAction> = []
Expand Down Expand Up @@ -273,18 +284,13 @@ export const EditorComponentInner = React.memo((props: EditorProps) => {
React.useEffect(() => {
window.addEventListener('contextmenu', preventDefault)
window.addEventListener('mousedown', inputBlurForce, true)
window.addEventListener('beforeunload', onBeforeUnload)
return function cleanup() {
window.removeEventListener('contextmenu', preventDefault)
window.removeEventListener('mousedown', inputBlurForce, true)
window.addEventListener('beforeunload', onBeforeUnload)
}
}, [
onWindowMouseDown,
onWindowMouseUp,
onWindowKeyDown,
onWindowKeyUp,
preventDefault,
inputBlurForce,
])
}, [onBeforeUnload, preventDefault, inputBlurForce])

const projectName = useEditorState(
Substores.restOfEditor,
Expand Down
11 changes: 0 additions & 11 deletions editor/src/core/shared/javascript-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,6 @@ function resolveDefinedElsewhere(
continue
}

if (elsewhere === 'window') {
// By spreading the `window.location` we can prevent redirection via e.g. `window.location.href = '...'`
definedElsewhereInfo[elsewhere] = {
...window,
location: {
...window.location,
},
}
continue
}

if ((global as any).hasOwnProperty(elsewhere) as boolean) {
definedElsewhereInfo[elsewhere] = (global as any)[elsewhere]
continue
Expand Down

0 comments on commit 046cd91

Please sign in to comment.