From daa54aaf3e5df380e5c72a531f2e19b3f13f0eb2 Mon Sep 17 00:00:00 2001
From: Moritz Langenstein <ml5717@ic.ac.uk>
Date: Fri, 22 Nov 2019 21:50:32 +0000
Subject: [PATCH] (ml5717) Moved undo disabling to room.canUndo check

---
 src/app.js  | 30 ++++++++++++++++++++----------
 src/room.js | 10 +++-------
 2 files changed, 23 insertions(+), 17 deletions(-)

diff --git a/src/app.js b/src/app.js
index 10ab8c2..9f70615 100644
--- a/src/app.js
+++ b/src/app.js
@@ -163,11 +163,6 @@ const onRoomConnect = (room_) => {
     HTML.fastUndoButton.classList.remove("disabled")
     HTML.undoButton.classList.remove("disabled")
   })
-
-  room.addEventListener("undoDisabled", () => {
-    HTML.fastUndoButton.classList.add("disabled")
-    HTML.undoButton.classList.add("disabled")
-  })
 }
 
 const tryRoomConnect = async (roomID) => {
@@ -208,11 +203,26 @@ const onRoomJoinEnter = () => {
 
 HTML.roomConnectButton.addEventListener("click", onRoomJoinEnter)
 
-HTML.fastUndoButton.addEventListener(
-  "click",
-  () => room != null && room.fastUndo(),
-)
-HTML.undoButton.addEventListener("click", () => room != null && room.undo())
+HTML.fastUndoButton.addEventListener("click", () => {
+  if (room == null) return
+
+  room.fastUndo()
+
+  if (!room.canUndo) {
+    HTML.fastUndoButton.classList.add("disabled")
+    HTML.undoButton.classList.add("disabled")
+  }
+})
+HTML.undoButton.addEventListener("click", () => {
+  if (room == null) return
+
+  room.undo()
+
+  if (!room.canUndo) {
+    HTML.fastUndoButton.classList.add("disabled")
+    HTML.undoButton.classList.add("disabled")
+  }
+})
 
 HTML.roomIDElem.addEventListener("keydown", (event) => {
   if (event.key == "Enter") {
diff --git a/src/room.js b/src/room.js
index c0325bb..c8422ab 100644
--- a/src/room.js
+++ b/src/room.js
@@ -72,10 +72,6 @@ class Room extends EventTarget {
     const [id, ...interval] = operation
 
     this.shared.eraseIntervals.get(id).merge([interval])
-
-    if (this.undoStack.length <= 0) {
-      this.dispatchEvent(new CustomEvent("undoDisabled"))
-    }
   }
 
   fastUndo() {
@@ -96,10 +92,10 @@ class Room extends EventTarget {
     this.undoStack = this.undoStack.slice(0, Math.max(0, from))
 
     this.shared.eraseIntervals.get(id).merge([[0, end]])
+  }
 
-    if (this.undoStack.length <= 0) {
-      this.dispatchEvent(new CustomEvent("undoDisabled"))
-    }
+  get canUndo() {
+    return this.undoStack.length > 0
   }
 
   getPaths() {
-- 
GitLab