From c046fceb304046d1ed817fc07a7fb45fc4be9838 Mon Sep 17 00:00:00 2001
From: Greg Fodor <gfodor@gmail.com>
Date: Wed, 17 Oct 2018 17:05:16 +0000
Subject: [PATCH] Subscription toggling UI working

---
 src/hub.js                      | 32 ++++++++++++++++----------------
 src/react-components/ui-root.js | 18 ++++++++++++------
 src/subscriptions.js            | 13 ++++++++++---
 3 files changed, 38 insertions(+), 25 deletions(-)

diff --git a/src/hub.js b/src/hub.js
index 82f4bce70..50dcd8aa9 100644
--- a/src/hub.js
+++ b/src/hub.js
@@ -306,12 +306,13 @@ async function runBotMode(scene, entryManager) {
 }
 
 document.addEventListener("DOMContentLoaded", async () => {
-  const subscriptions = new Subscriptions();
+  // Connect to reticulum over phoenix channels to get hub info.
+  const hubId = qs.get("hub_id") || document.location.pathname.substring(1).split("/")[0];
+  console.log(`Hub ID: ${hubId}`);
+
+  const subscriptions = new Subscriptions(hubId);
   navigator.serviceWorker.register("/hub.service.js");
-  navigator.serviceWorker.ready.then(registration => {
-    subscriptions.setRegistration(registration);
-    remountUI({ subscriptions });
-  });
+  navigator.serviceWorker.ready.then(registration => subscriptions.setRegistration(registration));
 
   const scene = document.querySelector("a-scene");
   const hubChannel = new HubChannel(store);
@@ -323,7 +324,14 @@ document.addEventListener("DOMContentLoaded", async () => {
   window.APP.scene = scene;
 
   registerNetworkSchemas();
-  remountUI({ hubChannel, linkChannel, enterScene: entryManager.enterScene, exitScene: entryManager.exitScene });
+  remountUI({
+    hubChannel,
+    linkChannel,
+    subscriptions,
+    enterScene: entryManager.enterScene,
+    exitScene: entryManager.exitScene,
+    initialIsSubscribed: subscriptions.isSubscribed()
+  });
 
   pollForSupportAvailability(isSupportAvailable => remountUI({ isSupportAvailable }));
 
@@ -371,10 +379,6 @@ document.addEventListener("DOMContentLoaded", async () => {
     }
   });
 
-  // Connect to reticulum over phoenix channels to get hub info.
-  const hubId = qs.get("hub_id") || document.location.pathname.substring(1).split("/")[0];
-  console.log(`Hub ID: ${hubId}`);
-
   const socket = connectToReticulum(isDebug);
   remountUI({ sessionId: socket.params().session_id });
 
@@ -391,8 +395,7 @@ document.addEventListener("DOMContentLoaded", async () => {
     .join()
     .receive("ok", async data => {
       hubChannel.setPhoenixChannel(hubPhxChannel);
-      subscriptions.setHubInfo(hubId, hubChannel);
-      remountUI({ subscriptions });
+      subscriptions.setHubChannel(hubChannel);
       await handleHubChannelJoined(entryManager, hubChannel, data);
     })
     .receive("error", res => {
@@ -501,10 +504,7 @@ document.addEventListener("DOMContentLoaded", async () => {
   const retPhxChannel = socket.channel(`ret`, { hub_id: hubId });
   retPhxChannel
     .join()
-    .receive("ok", async data => {
-      subscriptions.setVapidPublicKey(data.vapid_public_key);
-      remountUI({ subscriptions });
-    })
+    .receive("ok", async data => subscriptions.setVapidPublicKey(data.vapid_public_key))
     .receive("error", res => console.error(res));
 
   linkChannel.setSocket(socket);
diff --git a/src/react-components/ui-root.js b/src/react-components/ui-root.js
index 017838b46..51542fdd8 100644
--- a/src/react-components/ui-root.js
+++ b/src/react-components/ui-root.js
@@ -90,7 +90,8 @@ class UIRoot extends Component {
     presenceLogEntries: PropTypes.array,
     presences: PropTypes.object,
     sessionId: PropTypes.string,
-    subscriptions: PropTypes.object
+    subscriptions: PropTypes.object,
+    initialIsSubscribed: PropTypes.bool
   };
 
   state = {
@@ -131,8 +132,7 @@ class UIRoot extends Component {
     exited: false,
 
     showProfileEntry: false,
-    pendingMessage: "",
-    isSubscribed: false
+    pendingMessage: ""
   };
 
   componentDidMount() {
@@ -142,7 +142,6 @@ class UIRoot extends Component {
     this.props.scene.addEventListener("stateadded", this.onAframeStateChanged);
     this.props.scene.addEventListener("stateremoved", this.onAframeStateChanged);
     this.props.scene.addEventListener("exit", this.exit);
-    this.updateSubscribedState();
   }
 
   componentWillUnmount() {
@@ -183,7 +182,7 @@ class UIRoot extends Component {
     this.props.scene.emit("spawn_pen");
   };
 
-  onSubscribeClicked = async () => {
+  onSubscribeChanged = async () => {
     if (!this.props.subscriptions) return;
 
     await this.props.subscriptions.toggle();
@@ -713,7 +712,14 @@ class UIRoot extends Component {
         </div>
 
         <div>
-          <input id="subscribe" type="checkbox" onClick={this.onSubscribeClicked} checked={this.state.isSubscribed} />
+          <input
+            id="subscribe"
+            type="checkbox"
+            onChange={this.onSubscribeChanged}
+            checked={
+              typeof this.state.isSubscribed === "undefined" ? this.props.initialIsSubscribed : this.state.isSubscribed
+            }
+          />
           <label htmlFor="subscribe">
             <FormattedMessage id="entry.notify_me" />
           </label>
diff --git a/src/subscriptions.js b/src/subscriptions.js
index fe9b2ca18..282d7b836 100644
--- a/src/subscriptions.js
+++ b/src/subscriptions.js
@@ -18,8 +18,11 @@ function urlBase64ToUint8Array(base64String) {
 const LOCAL_STORE_KEY = "___hubs_subscriptions";
 
 export default class Subscriptions {
-  setHubInfo = (hubId, hubChannel) => {
+  constructor(hubId) {
     this.hubId = hubId;
+  }
+
+  setHubChannel = hubChannel => {
     this.hubChannel = hubChannel;
   };
 
@@ -40,8 +43,11 @@ export default class Subscriptions {
   };
 
   isSubscribed = () => {
-    console.log("WAT");
-    return this.getSubscriptionsFromStorage()[this.hubId];
+    if (typeof this._isSubscribed === "undefined") {
+      this._isSubscribed = !!this.getSubscriptionsFromStorage()[this.hubId];
+    }
+
+    return this._isSubscribed;
   };
 
   toggle = async () => {
@@ -72,6 +78,7 @@ export default class Subscriptions {
       console.log("Register push subscription with reticulum");
     }
 
+    delete this._isSubscribed;
     this.setSubscriptionsToStorage(subscriptions);
   };
 }
-- 
GitLab