Skip to content

Commit 1b09aa9

Browse files
committed
feat: warn loosing content before reload and switching syntax
1 parent 7f1c6e0 commit 1b09aa9

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

app/components/Editor.vue

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
</div>
1313

1414
<textarea
15+
ref="textarea"
1516
v-model="previewStore.files[props.filename]"
1617
class="textarea w-full min-h-full font-mono focus:outline-0 text-slate-700 dark:text-slate-300"
1718
placeholder="Every journey begins with a first step"
@@ -31,4 +32,23 @@ function loadSample() {
3132
previewStore.files[props.filename] =
3233
previewStore.syntax == Syntax.RST ? sampleRst : sampleMd;
3334
}
35+
36+
// *** Warn dialog before reload ******************************************************
37+
38+
onMounted(() => {
39+
window.addEventListener("beforeunload", handleBeforeUnload);
40+
});
41+
42+
onBeforeUnmount(() => {
43+
window.removeEventListener("beforeunload", handleBeforeUnload);
44+
});
45+
46+
const textarea = useTemplateRef("textarea");
47+
48+
function handleBeforeUnload(e: BeforeUnloadEvent) {
49+
if (textarea && textarea.value!.value.trim() !== "") {
50+
// this will show generic browser dialog, it cannot be customized
51+
e.preventDefault();
52+
}
53+
}
3454
</script>

app/components/Topbar.vue

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
<div class="tooltip tooltip-left" data-tip="Switch syntax">
88
<select
9-
v-model="previewStore.syntax"
9+
:value="previewStore.syntax"
1010
class="select select-ghost text-base"
11+
@change="onSyntaxChange"
1112
>
1213
<option :value="Syntax.RST" selected>reStructuredText</option>
1314
<option :value="Syntax.MD">Markdown</option>
@@ -54,4 +55,24 @@
5455

5556
<script setup lang="ts">
5657
const previewStore = usePreviewStore();
58+
59+
// *** Warn/prevent before syntax switching ********************************************
60+
61+
let previousSyntax = previewStore.syntax;
62+
63+
function onSyntaxChange(event: Event) {
64+
const selectElement = event.target as HTMLSelectElement;
65+
const confirmed = window.confirm(
66+
"Switching a syntax will clear your content. Do you want to continue?"
67+
);
68+
if (confirmed) {
69+
// Switch syntax
70+
const newSyntax = Syntax[selectElement.value as keyof typeof Syntax];
71+
previewStore.syntax = newSyntax;
72+
previousSyntax = newSyntax;
73+
} else {
74+
// Prevent the change by resetting the value
75+
selectElement.value = previousSyntax;
76+
}
77+
}
5778
</script>

0 commit comments

Comments
 (0)