aboutsummaryrefslogtreecommitdiff
path: root/resources/vue/components/StudipModalLeave.vue
blob: 1e1f4f585eb87e03da60f8ce0e244bd790be9d58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<template>
    <StudipDialog
        v-if="showModal"
        width="600"
        height="200"
        @confirm="confirmLeave"
        @close="cancelLeave"
        :closeClass="false"
        :closeText="$gettext('Auf Seite bleiben')"
        :confirmText="$gettext('Seite verlassen')"
        :title="$gettext('Ungespeicherte Änderungen')"
        :question="$gettext('Es gibt ungespeicherte Änderungen. Möchten Sie die Seite wirklich verlassen?')"
    >
        <template #dialogButtons>
            <button v-if="props.onSave" class="button" @click="saveAndLeave">
                {{ $gettext('Speichern & Verlassen') }}
            </button>
        </template>
    </StudipDialog>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import StudipDialog from './StudipDialog.vue';

const props = defineProps({
    hasUnsavedChanges: {
        type: Boolean,
        required: true,
    },
    onSave: {
        type: Function,
        required: false,
    },
});

const showModal = ref(false);
const pendingHref = ref(null);

function onClick(e) {
    const link = e.target.closest('a[href]');
    if (!link || link.target === '_blank') {
        return;
    }

    const href = link.href;

    if (props.hasUnsavedChanges) {
        e.preventDefault();
        pendingHref.value = href;
        showModal.value = true;
    }
}

function confirmLeave() {
    window.removeEventListener('beforeunload', onBeforeUnload);
    showModal.value = false;
    window.location.href = pendingHref.value;
}

function cancelLeave() {
    showModal.value = false;
    pendingHref.value = null;
}

function onBeforeUnload(e) {
    if (props.hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
        return '';
    }
}
async function saveAndLeave() {
    if (typeof props.onSave === 'function') {
        try {
            await props.onSave();
            window.removeEventListener('beforeunload', onBeforeUnload);
            window.location.href = pendingHref.value;
        } catch (e) {
            console.error('Speichern fehlgeschlagen:', e);
        }
    }
}

onMounted(() => {
    document.addEventListener('click', onClick);
    window.addEventListener('beforeunload', onBeforeUnload);
});

onUnmounted(() => {
    document.removeEventListener('click', onClick);
    window.removeEventListener('beforeunload', onBeforeUnload);
});
</script>