From 11597d5bdafa771fff9188c78ea81b38090da596 Mon Sep 17 00:00:00 2001 From: "David L. Qiu" Date: Fri, 2 Feb 2024 12:20:44 -0800 Subject: [PATCH] refactor JS test clients --- tests/yjs_client_0.js | 20 ++++++++------------ tests/yjs_client_1.js | 34 +++++++++++++++------------------- 2 files changed, 23 insertions(+), 31 deletions(-) diff --git a/tests/yjs_client_0.js b/tests/yjs_client_0.js index 6266a88..63aefff 100644 --- a/tests/yjs_client_0.js +++ b/tests/yjs_client_0.js @@ -16,17 +16,13 @@ wsProvider.on("status", (event) => { console.log(event.status); }); -var clock = -1; - ymap.observe((event) => { - event.changes.keys.forEach((change, key) => { - if (key === "clock") { - const clk = ymap.get("clock"); - if (clk > clock) { - ymap.set("out", ymap.get("in") + 1); - clock = clk + 1; - ymap.set("clock", clock); - } - } - }); + // only do something when another client updates `ymap.clock` + if (event.transaction.local || !event.changes.keys.has("clock")) { + return; + } + + const clock = ymap.get("clock"); + ymap.set("out", ymap.get("in") + 1); + ymap.set("clock", clock + 1); }); diff --git a/tests/yjs_client_1.js b/tests/yjs_client_1.js index 43f790f..6422401 100644 --- a/tests/yjs_client_1.js +++ b/tests/yjs_client_1.js @@ -18,24 +18,20 @@ wsProvider.on("status", (event) => { console.log(event.status); }); -var clock = -1; - ymap.observe((event) => { - event.changes.keys.forEach((change, key) => { - if (key === "clock") { - const clk = ymap.get("clock"); - if (clk > clock) { - const cells = [ - new Y.Map([ - ["source", new Y.Text("1 + 2")], - ["metadata", { foo: "bar" }], - ]), - ]; - ycells.push(cells); - ystate.set("state", { dirty: false }); - clock = clk + 1; - ymap.set("clock", clock); - } - } - }); + // only do something when another client updates `ymap.clock` + if (event.transaction.local || !event.changes.keys.has("clock")) { + return; + } + + const clock = ymap.get("clock"); + const cells = [ + new Y.Map([ + ["source", new Y.Text("1 + 2")], + ["metadata", { foo: "bar" }], + ]), + ]; + ycells.push(cells); + ystate.set("state", { dirty: false }); + ymap.set("clock", clock + 1); });