sync and keep by change timestamp

This commit is contained in:
Julian Krauser 2025-02-28 14:02:06 +01:00
parent 5857c7e0d4
commit a590a4ed30
4 changed files with 128 additions and 45 deletions

View file

@ -4,7 +4,7 @@
"description": "Feuerwehr/Verein Einsatzverwaltung UI", "description": "Feuerwehr/Verein Einsatzverwaltung UI",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite --host",
"build": "run-p type-check \"build-only {@}\" --", "build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview", "preview": "vite preview",
"build-only": "vite build", "build-only": "vite build",

View file

@ -4,50 +4,116 @@ import * as Y from "yjs";
import { Awareness } from "y-protocols/awareness.js"; import { Awareness } from "y-protocols/awareness.js";
import { computed, ref } from "vue"; import { computed, ref } from "vue";
export const useMissionDetailStore = defineStore("missionDetail", () => { export const useMissionDetailStore = defineStore("missionDetail", {
state: () => {
return {
yDoc: new Y.Doc(),
docId: null as null | string,
lastUpdateTimestamp: 0 as number,
connectionStatus: "disconnected", // 'disconnected', 'connecting', 'connected', 'syncing', 'synced'
};
},
actions: {
initialize(docId: string) {
this.docId = docId;
this.lastUpdateTimestamp = this.loadLastUpdateFromLocalStorage();
this.setupSocketHandlers();
this.setupYjsObservers();
},
setupSocketHandlers() {
const connectionStore = useConnectionStore(); const connectionStore = useConnectionStore();
const initialized = ref(false);
const ydoc = ref(new Y.Doc());
const awareness = ref(new Awareness(ydoc.value));
const title = computed({
get() {
return ydoc.value.getMap("form").get("title") ?? "";
},
set(val) {
ydoc.value.getMap("form").set("title", val);
},
});
const editor = ref(ydoc.value.getText("editor"));
function init(missionId: string) {
if (!connectionStore.connection) return; if (!connectionStore.connection) return;
ydoc.value = new Y.Doc(); connectionStore.connection.on("package-sync", (data) => {
awareness.value = new Awareness(ydoc.value); try {
editor.value = ydoc.value.getText("editor"); this.connectionStatus = "syncing";
ydoc.value.on("update", (update) => {
connectionStore.connection?.emit("mission:sync", Array.from(update));
});
connectionStore.connection.on("package-sync", (update) => { Y.applyUpdate(this.yDoc, new Uint8Array(data.update));
Y.applyUpdate(ydoc.value, new Uint8Array(update));
});
connectionStore.connection.on("package-mission", (initial) => { if (data.timestamp > this.lastUpdateTimestamp) {
Y.applyUpdate(ydoc.value, new Uint8Array(initial)); this.lastUpdateTimestamp = data.timestamp;
}); this.saveLastUpdateToLocalStorage();
connectionStore.connection.emit("mission:join", missionId, initialized.value);
initialized.value = true;
} }
function destroy() {
this.connectionStatus = "synced";
} catch (error) {
console.error("Error applying update:", error);
this.requestFullSync();
}
});
connectionStore.connection.on("sync-get-missing-updates", (data) => {
const clientUpdates = Y.encodeStateAsUpdate(this.yDoc, new Uint8Array(data.stateVector));
connectionStore.connection?.emit("mission:sync-client-updates", {
update: clientUpdates,
timestamp: Date.now(),
});
});
this.joinDocument();
},
setupYjsObservers() {
if (!this.yDoc) return;
this.yDoc.on("update", (update) => {
const connectionStore = useConnectionStore();
if (connectionStore.connected) {
connectionStore.connection?.emit("mission:sync-client-updates", {
update: Array.from(update),
timestamp: Date.now(),
});
}
this.lastUpdateTimestamp = Date.now();
this.saveLastUpdateToLocalStorage();
});
},
joinDocument() {
const connectionStore = useConnectionStore();
if (!connectionStore.connection || !this.docId) return;
connectionStore.connection.emit("mission:join", this.docId, {
timestamp: this.lastUpdateTimestamp,
});
},
requestFullSync() {
const connectionStore = useConnectionStore();
if (!connectionStore.connection || !this.docId) return;
connectionStore.connection.emit("mission:join", this.docId, null);
},
loadLastUpdateFromLocalStorage() {
if (!this.docId) return 0;
const stored = localStorage.getItem(`yjsDoc_timestamp`);
return stored ? parseInt(stored, 10) : 0;
},
saveLastUpdateToLocalStorage() {
if (!this.docId) return;
localStorage.setItem(`yjsDoc_timestamp`, this.lastUpdateTimestamp.toString());
},
cleanup() {
if (this.yDoc) {
this.yDoc.destroy();
this.yDoc = new Y.Doc();
}
this.lastUpdateTimestamp = 0;
localStorage.removeItem("yjsDoc_timestamp");
const connectionStore = useConnectionStore();
connectionStore.connection?.emit("mission:leave"); connectionStore.connection?.emit("mission:leave");
connectionStore.connection?.off("package-mission"); this.connectionStatus = "disconnected";
connectionStore.connection?.off("package-sync"); },
} },
return { ydoc, awareness, title, editor, init, destroy };
}); });

View file

@ -75,7 +75,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { defineComponent } from "vue"; import { defineComponent, type PropType } from "vue";
import { mapActions, mapState, mapWritableState } from "pinia"; import { mapActions, mapState, mapWritableState } from "pinia";
import { useAbilityStore } from "@/stores/ability"; import { useAbilityStore } from "@/stores/ability";
import { Quill, QuillEditor } from "@vueup/vue-quill"; import { Quill, QuillEditor } from "@vueup/vue-quill";
@ -85,11 +85,17 @@ import { QuillBinding } from "y-quill";
import { moduleOptions } from "@/helpers/quillConfig"; import { moduleOptions } from "@/helpers/quillConfig";
import ForceSelect from "@/components/admin/ForceSelect.vue"; import ForceSelect from "@/components/admin/ForceSelect.vue";
import { useForceStore } from "@/stores/admin/configuration/force"; import { useForceStore } from "@/stores/admin/configuration/force";
import { useMissionDetailStore } from "@/stores/admin/operation/missionDetail"; import * as Y from "yjs";
</script> </script>
<script lang="ts"> <script lang="ts">
export default defineComponent({ export default defineComponent({
props: {
document: {
type: Object as PropType<Y.Doc>,
required: true,
},
},
data() { data() {
return { return {
binding: undefined as undefined | QuillBinding, binding: undefined as undefined | QuillBinding,
@ -99,7 +105,17 @@ export default defineComponent({
computed: { computed: {
...mapState(useAbilityStore, ["can"]), ...mapState(useAbilityStore, ["can"]),
...mapState(useForceStore, ["availableForces"]), ...mapState(useForceStore, ["availableForces"]),
...mapWritableState(useMissionDetailStore, ["editor", "title"]), title: {
get() {
return this.document.getMap("form").get("title");
},
set(val: string) {
this.document.getMap("form").set("title", val);
},
},
editor() {
return this.document.getText("editor");
},
}, },
methods: { methods: {
initEditor(quill: Quill) { initEditor(quill: Quill) {

View file

@ -27,7 +27,7 @@
</RouterLink> </RouterLink>
</div> </div>
<MissionDetail v-show="routeHash == '#edit'" /> <MissionDetail v-show="routeHash == '#edit'" :document="yDoc" />
<MissionPresence v-show="routeHash == '#presence'" /> <MissionPresence v-show="routeHash == '#presence'" />
</div> </div>
</div> </div>
@ -37,7 +37,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { defineComponent } from "vue"; import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia"; import { mapActions, mapState, mapWritableState } from "pinia";
import MainTemplate from "@/templates/Main.vue"; import MainTemplate from "@/templates/Main.vue";
import { useConnectionStore } from "@/stores/admin/operation/connection"; import { useConnectionStore } from "@/stores/admin/operation/connection";
import MissionDetail from "./MissionDetail.vue"; import MissionDetail from "./MissionDetail.vue";
@ -71,12 +71,13 @@ export default defineComponent({
}, },
connectionStatus() { connectionStatus() {
if (this.connectionStatus) { if (this.connectionStatus) {
this.init(this.id); this.setupSocketHandlers();
} }
}, },
}, },
computed: { computed: {
...mapState(useConnectionStore, ["connectionStatus"]), ...mapState(useConnectionStore, ["connectionStatus"]),
...mapWritableState(useMissionDetailStore, ["yDoc"]),
routeHash() { routeHash() {
return this.$route.hash; return this.$route.hash;
}, },
@ -84,15 +85,15 @@ export default defineComponent({
mounted() { mounted() {
this.manageHash(); this.manageHash();
this.connectClient(); this.connectClient();
this.init(this.id); this.initialize(this.id);
this.getAvailableForces(); this.getAvailableForces();
}, },
beforeUnmount() { beforeUnmount() {
this.destroy(); this.cleanup();
}, },
methods: { methods: {
...mapActions(useConnectionStore, ["connectClient"]), ...mapActions(useConnectionStore, ["connectClient"]),
...mapActions(useMissionDetailStore, ["init", "destroy"]), ...mapActions(useMissionDetailStore, ["initialize", "setupSocketHandlers", "cleanup"]),
...mapActions(useForceStore, ["getAvailableForces"]), ...mapActions(useForceStore, ["getAvailableForces"]),
manageHash() { manageHash() {
if (!this.$route.hash || !this.tabs.map((t) => t.hash).includes(this.$route.hash)) { if (!this.$route.hash || !this.tabs.map((t) => t.hash).includes(this.$route.hash)) {