diff options
Diffstat (limited to 'js/main.js')
| -rwxr-xr-x[-rw-r--r--] | js/main.js | 289 |
1 files changed, 178 insertions, 111 deletions
diff --git a/js/main.js b/js/main.js index d85a655..fbee768 100644..100755 --- a/js/main.js +++ b/js/main.js @@ -1,111 +1,178 @@ -//environment variables will be fetched from server -let env = {'thing': 123}; // Default value until loaded - -//the application config. default values here which can be overridden by user's local storage -let cfg = { - -}; - -//some placeholder values here. some ideas for placeholder values here. might all be useful -let dom = { - input: {}, - label: {}, - box: {}, //an info-containing box - icon: {}, - info: {} -}; - - -//APP START HERE -$(document).ready(async function() { - console.log(window.env); - // 1. setup relationship with DOM and grab references to its elements - log('init DOM'); - await initDOM(); - - // 2. grab any local user config - log('init cfg'); - await initCfg(); - - // 3. communicate with any external services if needed, like REST API or websocket - log('init services'); - await initServices(); -}); - -//gets user config from local storage if there is any -function initCfg(){ - let localCfg = localStorage.getItem('config'); - if (localCfg) { - try { - cfg = JSON.parse(localCfg); - } catch (e) { - cfg = {}; - } - } else { - - } -} - - -function initServices(){ - //connect to websocket server - - //grab data from REST API - - // Load environment variables from a server - return fetch('/api/env') - .then(response => { - if (response.status == 200){ - return response.json() - } else { - return null; - } - }) - .then(data => { - env = data; - console.log('Environment loaded:', env); - updateServerStatus('connected'); - return data; - }) - .catch(error => { - console.error('Error loading environment:', error); - updateServerStatus('error'); - return env; // Return default - }); -} - -// Update server status indicator -function updateServerStatus(status) { - const serverStatus = document.getElementById('server-status'); - if (!serverStatus) return; - - switch(status) { - case 'connecting': - serverStatus.innerHTML = 'Server status: Connecting...'; - serverStatus.style.color = 'orange'; - break; - case 'connected': - serverStatus.innerHTML = 'Server status: Connected (Environment loaded successfully)'; - serverStatus.style.color = 'green'; - break; - case 'error': - serverStatus.innerHTML = 'Server status: Error (Could not load environment)'; - serverStatus.style.color = 'red'; - break; - } -} - -function initDOM(){ - dom.body = $('body')[0]; - dom.serverStatus = document.getElementById('server-status'); - if (dom.serverStatus) { - updateServerStatus('connecting'); - } -} - -function log(msg, lvl=1){ - if (dom.debugInfo){ - dom.debugInfo.innerHTML = msg; //TODO running log + timestamp - } - console.log(msg); -} +//environment variables will be fetched from server
+let env = {'thing': 123}; // Default value until loaded
+
+//the application config. default values here which can be overridden by user's local storage
+let cfgDefault = {};
+let cfg = cfgDefault;
+
+//some placeholder values here. some ideas for placeholder values here. might all be useful
+let dom = {
+ input: {},
+ label: {},
+ box: {}, //an info-containing box
+ icon: {},
+ info: {}
+};
+
+// application state
+let ws = null; // WebSocket connection
+
+
+//APP START HERE
+$(document).ready(async function() {
+ console.log(window.env);
+ // 1. setup relationship with DOM and grab references to its elements
+ log('init DOM');
+ await initDOM();
+
+ // 2. grab any local user config
+ log('init cfg');
+ await initCfg();
+
+ // 3. communicate with any external services if needed, like REST API or websocket
+ log('init services');
+ await initServices();
+
+ // 4. now that we have the proper env/config, the DOM is prepared, and we've setup connection to services,
+ // we can initialize the app models and start the app
+ initApp();
+});
+
+//gets user config from local storage if there is any
+function initCfg(){
+ let localCfg = localStorage.getItem('config');
+ if (localCfg) {
+ try {
+ cfg = JSON.parse(localCfg);
+ } catch (e) {
+ console.warn('local config is malformed. using default application config');
+ }
+ } else {
+ console.log('No local config. using default.');
+ }
+}
+
+
+function initServices(){
+ //connect to websocket server
+ connectWebSocket();
+
+ //grab data from REST API
+
+ // Load environment variables from a server
+ return fetch('/api/env')
+ .then(response => {
+ if (response.status == 200){
+ return response.json()
+ } else {
+ return null;
+ }
+ })
+ .then(data => {
+ env = data;
+ console.log('Environment loaded:', env);
+ updateServerStatus('connected');
+ return data;
+ })
+ .catch(error => {
+ console.error('Error loading environment:', error);
+ updateServerStatus('error');
+ return env; // Return default
+ });
+}
+
+// Update server status indicator
+function updateServerStatus(status) {
+ if (!dom.serverStatus) return;
+
+ switch(status) {
+ case 'connecting':
+ dom.serverStatus.innerHTML = 'Server status: Connecting...';
+ dom.serverStatus.style.color = 'orange';
+ break;
+ case 'connected':
+ dom.serverStatus.innerHTML = 'Server status: Connected';
+ dom.serverStatus.style.color = 'green';
+ break;
+ case 'error':
+ dom.serverStatus.innerHTML = 'Server status: Error';
+ dom.serverStatus.style.color = 'red';
+ break;
+ }
+}
+
+function initDOM(){
+ dom.body = $('body')[0];
+ dom.serverStatus = document.getElementById('server-status');
+ if (dom.serverStatus) {
+ updateServerStatus('connecting');
+ }
+}
+
+function initApp(){
+ log('App initialized');
+}
+
+function log(msg, lvl=1){
+ if (dom.debugInfo){
+ dom.debugInfo.innerHTML = msg; //TODO running log + timestamp
+ }
+ console.log(msg);
+}
+
+// Connect to WebSocket server for collaborative editing
+function connectWebSocket() {
+ // Check if WebSocket is supported
+ if (!window.WebSocket) {
+ console.error("WebSocket not supported by browser");
+ return;
+ }
+
+ // Create WebSocket connection
+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
+ const wsUrl = `${protocol}//${window.location.host}/ws`;
+
+ try {
+ ws = new WebSocket(wsUrl);
+
+ // WebSocket event handlers
+ ws.onopen = function(e) {
+ console.log("WebSocket connection established");
+ updateServerStatus("connected");
+ };
+
+ ws.onmessage = function(e) {
+ try {
+ const data = JSON.parse(e.data);
+ handleWebSocketMessage(data);
+ } catch (err) {
+ console.error("Error processing WebSocket message:", err);
+ }
+ };
+
+ ws.onclose = function(e) {
+ console.log("WebSocket connection closed");
+ // Try to reconnect after delay
+ setTimeout(connectWebSocket, 5000);
+ };
+
+ ws.onerror = function(e) {
+ console.error("WebSocket error:", e);
+ updateServerStatus("error");
+ };
+ } catch (err) {
+ console.error("Failed to create WebSocket connection:", err);
+ }
+}
+
+// Handle incoming WebSocket messages (to be extended for graph operations)
+function handleWebSocketMessage(data) {
+ switch (data.type) {
+ case 'graphUpdate':
+ // TODO: Handle graph updates from other clients
+ console.log('Received graph update:', data);
+ break;
+ default:
+ console.log('Unknown message type:', data.type);
+ }
+}
|
