Browse Source

eslint-related code cleanup

Andrew Dolgov 5 months ago
parent
commit
489aa4dfad
8 changed files with 119 additions and 159 deletions
  1. 2 2
      .eslintrc.js
  2. 1 1
      include/functions.php
  3. 2 2
      index.php
  4. 19 15
      js/functions.js
  5. 22 16
      js/prefs.js
  6. 67 117
      js/tt-irc.js
  7. 5 5
      prefs.php
  8. 1 1
      users.php

+ 2 - 2
.eslintrc.js

@@ -99,7 +99,7 @@ module.exports = {
         "no-alert": "off",
         "no-array-constructor": "error",
         "no-async-promise-executor": "off",
-        "no-await-in-loop": "error",
+        "no-await-in-loop": "warn",
         "no-bitwise": "off",
         "no-buffer-constructor": "error",
         "no-caller": "error",
@@ -244,7 +244,7 @@ module.exports = {
             "as-needed"
         ],
         "require-atomic-updates": "off",
-        "require-await": "error",
+        "require-await": "warn",
         "require-jsdoc": "off",
         "require-unicode-regexp": "off",
         "rest-spread-spacing": "error",

+ 1 - 1
include/functions.php

@@ -1952,7 +1952,7 @@
 
 						init();
 					} else {
-						update_emoticons();
+						model.updateEmoticons();
 					}
 				});
 			});

+ 2 - 2
index.php

@@ -240,9 +240,9 @@
 			if (strpos($email, "@localhost") === FALSE) {
 				$grav_hash = md5(trim($email));
 			?>
-				<img onclick="show_prefs()" class="avatar" title="<?php echo __('Preferences (Alt+P)') ?>" referrerpolicy="no-referrer"  src="https://secure.gravatar.com/avatar/<?php echo $grav_hash ?>?s=96">
+				<img onclick="Prefs.show()" class="avatar" title="<?php echo __('Preferences (Alt+P)') ?>" referrerpolicy="no-referrer"  src="https://secure.gravatar.com/avatar/<?php echo $grav_hash ?>?s=96">
 		<?php } else { ?>
-			<a href="#" onclick="show_prefs()" title="<?php echo __("Preferences (Alt+P)") ?>"><span class="text-muted glyphicon glyphicon-cog"></a>
+			<a href="#" onclick="Prefs.show()" title="<?php echo __("Preferences (Alt+P)") ?>"><span class="text-muted glyphicon glyphicon-cog"></a>
 		<?php } ?>
 
 		<?php if ($_SESSION["access_level"] >= 10) { ?>

+ 19 - 15
js/functions.js

@@ -14,7 +14,11 @@ RegExp.escape = function(str) {
 };
 
 String.prototype.hashCode = function() {
-	return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
+	return this.split("").reduce((a,b) =>
+		{
+			a=((a<<5)-a)+b.charCodeAt(0);
+			return a & a
+		}, 0);
 }
 
 /* add method to remove element from array */
@@ -40,23 +44,23 @@ Array.prototype.last = function(){
 Array.prototype.equals = function (array) {
 	// if the other array is a falsy value, return
 	if (!array)
-		 return false;
+		return false;
 
 	// compare lengths - can save a lot of time
 	if (this.length != array.length)
-		 return false;
-
-	for (var i = 0, l=this.length; i < l; i++) {
-		 // Check if we have nested arrays
-		 if (this[i] instanceof Array && array[i] instanceof Array) {
-			  // recurse into the nested arrays
-			  if (!this[i].equals(array[i]))
-					return false;
-		 }
-		 else if (this[i] != array[i]) {
-			  // Warning - two different object instances will never be equal: {x:20} != {x:20}
-			  return false;
-		 }
+		return false;
+
+	for (let i = 0, l=this.length; i < l; i++) {
+		// Check if we have nested arrays
+		if (this[i] instanceof Array && array[i] instanceof Array) {
+			// recurse into the nested arrays
+			if (!this[i].equals(array[i]))
+				return false;
+		}
+		else if (this[i] != array[i]) {
+			// Warning - two different object instances will never be equal: {x:20} != {x:20}
+			return false;
+		}
 	}
 	return true;
 }

+ 22 - 16
js/prefs.js

@@ -1,6 +1,19 @@
 'use strict';
 
 /* global __ */
+/* global show_spinner, infobox_callback2, hide_spinner, mini_error */
+
+/* TODO: move everything prefs-related here */
+const Prefs = {
+	show: function() {
+		show_spinner();
+
+		$.post("backend.php", {op: 'prefs'}, function(resp) {
+			infobox_callback2(resp);
+			hide_spinner();
+		}, 'html');
+	}
+};
 
 function save_prefs(callback) {
 	const query = $("#prefs_form").serialize();
@@ -35,18 +48,10 @@ function save_prefs(callback) {
 	return false;
 }
 
-function show_prefs() {
-	show_spinner();
-
-	$.post("backend.php", {op: 'prefs'}, function(resp) {
-		infobox_callback2(resp);
-		hide_spinner();
-	}, 'html');
-}
-
+/* exported edit_connection */
 function edit_connection(id) {
 
-	save_prefs(function (obj) {
+	save_prefs(function (/*obj*/) {
 		$.post("backend.php", {op: 'prefs-edit-con', id: id}, function (resp) {
 			infobox_callback2(resp);
 		}, 'html');
@@ -54,11 +59,6 @@ function edit_connection(id) {
 
 }
 
-function select_row(elem) {
-	const row_id = elem.getAttribute("row_id");
-	const checked = elem.checked;
-}
-
 // TODO: what the fuck is this
 function get_selected_rows(elem) {
 	const rv = [];
@@ -77,6 +77,7 @@ function get_selected_rows(elem) {
 	return rv;
 }
 
+/* exported delete_connection */
 function delete_connection() {
 	const rows = get_selected_rows("#connections-list");
 
@@ -106,6 +107,7 @@ function delete_connection() {
 	}
 }
 
+/* exported create_connection */
 function create_connection() {
 	const title = prompt(__("Title for a new connection:"));
 
@@ -121,6 +123,7 @@ function create_connection() {
 	}
 }
 
+/* exported save_conn */
 function save_conn(callback) {
 	const query = $("#prefs_conn_form").serialize();
 
@@ -134,13 +137,14 @@ function save_conn(callback) {
 			callback(obj);
 		} else {
 			//close_infobox();
-			show_prefs();
+			Prefs.show();
 		}
 
 		hide_spinner();
 	});
 }
 
+/* exported delete_server */
 function delete_server() {
 	const rows = get_selected_rows("#servers-list");
 
@@ -173,6 +177,7 @@ function delete_server() {
 	}
 }
 
+/* exported create_server */
 function create_server() {
 	const data = prompt(__("Server:Port (e.g. irc.example.org:6667):"));
 
@@ -202,6 +207,7 @@ function create_server() {
 	}
 }
 
+/* exported customize_css */
 function customize_css() {
 	save_prefs(function (obj) {
 		$.post("backend.php", {op: 'prefs-customize-css'}, function (resp) {

+ 67 - 117
js/tt-irc.js

@@ -396,7 +396,7 @@ const Message = function(data, chan) {
 							<span class="action"> * &nbsp; ${rewrite_emoticons(self.sender(), KIND_MESSAGE)} &nbsp; ${tmp_message}</span>`;
 
 						break;
-				case MSGT_NOTICE:
+				case MSGT_NOTICE: {
 						const sender_class = self.incoming() == true ? 'pvt-sender' : 'pvt-sender-out';
 
 						formatted_message = `<span class="timestamp" title="${self.formatted_ts(true)}">${self.formatted_ts()}</span>
@@ -406,6 +406,7 @@ const Message = function(data, chan) {
 							<span class='gt'>&ndash;</span>
 							<span class="message notice">${tmp_message}</span>`;
 
+						}
 						break;
 				case MSGT_SYSTEM:
 						formatted_message = `<span class="timestamp" title="${self.formatted_ts(true)}">${self.formatted_ts()}</span>
@@ -1119,6 +1120,49 @@ function Model() {
 		}
 	}
 
+	self.updateEmoticons = function(mtime, allow_reload) {
+		localforage.getItem("ttirc.emoticons-cache").then(function(obj) {
+			if (!obj || obj.mtime != mtime) {
+				console.log('updating emoticons...');
+
+				fetch("emoticons/emoticons.json.gz?" + mtime).then(function(resp) {
+					return resp.arrayBuffer();
+				}).then(function(buf) {
+					const gunzip = new Zlib.Gunzip(new Uint8Array(buf));
+					const dec = gunzip.decompress();
+
+					if (dec) {
+						const json = JSON.parse(new TextDecoder("utf-8").decode(dec));
+						let tmp_map = {};
+
+						$.each(Object.keys(json), function(i, k) {
+							tmp_map = $.extend(tmp_map, json[k]);
+						});
+
+						self.emoticons_cache([]);
+						self.emoticons_map(tmp_map);
+						self.emoticons_mtime(mtime);
+
+						console.log('emoticons updated');
+
+						localforage.setItem("ttirc.emoticons-cache",
+								{mtime: mtime, map: self.emoticons_map(), fullmap: json})
+							.then(function() {
+								if (allow_reload) window.location.reload();
+							});
+					}
+				});
+
+			} else {
+				console.log('using cached emoticons');
+
+				self.emoticons_map(obj.map);
+
+				//self.emoticons_mtime(mtime);
+			}
+		});
+	};
+
 	self.backendPing = function() {
 		const ts = new Date().getTime();
 
@@ -1157,49 +1201,6 @@ let colormap_dark = ["#6bc8c8", "#b7edd6", "#9494f5", "#ce7dce", "#a3a3a3",
 	"/op", "/deop", "/voice", "/devoice", "/ping", "/notice", "/away",
 	"/ctcp", "/clear" ];*/
 
-function update_emoticons(mtime, allow_reload) {
-	localforage.getItem("ttirc.emoticons-cache").then(function(obj) {
-		if (!obj || obj.mtime != mtime) {
-			console.log('updating emoticons...');
-
-			fetch("emoticons/emoticons.json.gz?" + mtime).then(function(resp) {
-				return resp.arrayBuffer();
-			}).then(function(buf) {
-				const gunzip = new Zlib.Gunzip(new Uint8Array(buf));
-				const dec = gunzip.decompress();
-
-				if (dec) {
-					const json = JSON.parse(new TextDecoder("utf-8").decode(dec));
-					let tmp_map = {};
-
-					$.each(Object.keys(json), function(i, k) {
-						tmp_map = $.extend(tmp_map, json[k]);
-					});
-
-					model.emoticons_cache([]);
-					model.emoticons_map(tmp_map);
-					model.emoticons_mtime(mtime);
-
-					console.log('emoticons updated');
-
-					localforage.setItem("ttirc.emoticons-cache",
-							{mtime: mtime, map: model.emoticons_map(), fullmap: json})
-						.then(function() {
-							if (allow_reload) window.location.reload();
-						});
-				}
-			});
-
-		} else {
-			console.log('using cached emoticons');
-
-			model.emoticons_map(obj.map);
-
-			//model.emoticons_mtime(mtime);
-		}
-	});
-}
-
 function init_second_stage(params) {
 
 	console.log("init_second_stage");
@@ -1228,7 +1229,7 @@ function init_second_stage(params) {
 	default_buffer_size = params.default_buffer_size;
 
 	if (params.emoticons_mtime)
-		update_emoticons(params.emoticons_mtime, true);
+		model.updateEmoticons(params.emoticons_mtime, true);
 
 	$("#overlay").hide();
 
@@ -1421,30 +1422,6 @@ function init_second_stage(params) {
 		return hotkey_handler(e);
 	});
 
-	/*$("#tabs").on("swiperight", function() {
-		$(this).addClass("active");
-	});
-
-	$("#tabs").on("swipeleft", function() {
-		$(this).removeClass("active");
-	});
-
-	$("#sidebar").on("swipeleft", function() {
-		$(this).addClass("active");
-	});
-
-	$("#sidebar").on("swiperight", function() {
-		$(this).removeClass("active");
-	});
-
-	$("#tabs").click(function() {
-		$(this).addClass("active");
-	});
-
-	$("#sidebar").click(function() {
-		$(this).addClass("active");
-	});*/
-
 	$("#log").on("swiperight", function() {
 		$("#tabs").addClass("active");
 	});
@@ -1493,7 +1470,23 @@ function init_second_stage(params) {
 
 	hide_spinner();
 
-	update_initial();
+	$.post("backend.php",
+		{op: 'update', last_id: last_id, uniqid: uniqid,
+			init: true, bufsize: default_buffer_size}, function(resp) {
+
+			console.log('update', resp);
+
+			return handle_update(resp).then(function() {
+				PluginHost.run(PluginHost.HOOK_INIT_COMPLETE);
+				init_event_source();
+			});
+
+	}).error(function() {
+		PluginHost.run(PluginHost.HOOK_INIT_COMPLETE);
+
+		init_event_source();
+	});
+
 }
 
 function init_dnd_upload() {
@@ -1561,30 +1554,6 @@ function init() {
 		report_error(message, filename, lineno, colno, error);
 	};
 
-	/* element data-bind="logger: name, ..." */
-	ko.bindingHandlers.logger = {
-		update: function(element, valueAccessor, allBindings) {
-			 //store a counter with this element
-			 var count = ko.utils.domData.get(element, "_ko_logger") || 0,
-				  data = ko.toJS(valueAccessor() || allBindings());
-
-			 ko.utils.domData.set(element, "_ko_logger", ++count);
-
-			 if (window.console && console.log) {
-				  console.log(count, element, data);
-			 }
-		}
-  };
-
-  	ko.bindingHandlers.element = {
-		update: function(element, valueAccessor) {
-			var elem = ko.utils.unwrapObservable(valueAccessor());
-
-			$(element).empty();
-			$(element).append(elem);
-		}
-	};
-
 	model = new Model();
 
 	ko.applyBindings(model, $('#html-root')[0]);
@@ -1715,7 +1684,7 @@ async function handle_update(rv) {
 			master_running = params.master_running;
 
 			if (params.emoticons_mtime)
-				update_emoticons(params.emoticons_mtime);
+				model.updateEmoticons(params.emoticons_mtime);
 		}
 	};
 
@@ -1856,26 +1825,6 @@ function init_event_source() {
 	};
 }
 
-function update_initial() {
-
-	$.post("backend.php",
-		{op: 'update', last_id: last_id, uniqid: uniqid,
-			init: true, bufsize: default_buffer_size}, function(resp) {
-
-			console.log('update', resp);
-
-			return handle_update(resp).then(function() {
-				PluginHost.run(PluginHost.HOOK_INIT_COMPLETE);
-				init_event_source();
-			});
-
-	}).error(function() {
-		PluginHost.run(PluginHost.HOOK_INIT_COMPLETE);
-
-		init_event_source();
-	});
-}
-
 function get_selected_tab() {
 	return $("#tabs-list li.selected")[0];
 }
@@ -2376,7 +2325,7 @@ function handle_event(connection_id, line) {
 		line.sender = "---";
 
 		return push_message(connection_id, line.channel, line, MSGT_PRIVMSG);
-	case "SERVER_PONG":
+	case "SERVER_PONG": {
 		const conn = model.getConnection(connection_id);
 
 		if (conn)
@@ -2387,6 +2336,7 @@ function handle_event(connection_id, line) {
 
 		push_message(connection_id, line.channel, line, MSGT_PRIVMSG); */
 
+		}
 		break;
 	case "AUTOAWAY_USER_IDLE":
 		line.message = __("Automatically setting away: no users connected.");
@@ -2897,7 +2847,7 @@ function hotkey_handler(e) {
 	}
 
 	if (keycode == 80 && e.altKey) {
-		show_prefs();
+		Prefs.show();
 		return false;
 	}
 

+ 5 - 5
prefs.php

@@ -29,7 +29,7 @@
 		<button class="btn btn-primary" type="submit" onclick="save_css()">
 			<span class='glyphicon glyphicon-saved'> </span>
 			<?php echo __('Save & reload') ?></button>
-		<button class="btn btn-default" type="submit" onclick="show_prefs()">
+		<button class="btn btn-default" type="submit" onclick="Prefs.show()">
 			<span class='glyphicon glyphicon-remove'> </span>
 			<?php echo __('Go back') ?></button></div>
 	</div>
@@ -64,7 +64,7 @@
 
 			print "<li class='row' id='S-$id' server_id='$id'>";
 			print "<div class='checkbox'><label>";
-			print "<input type='checkbox' onchange='select_row(this)'
+			print "<input type='checkbox'
 				row_id='S-$id'>";
 			print $line['server'] . ":" . $line['port'] . " $connected";
 			print "</label></div>";
@@ -145,7 +145,7 @@
 				<span class='glyphicon glyphicon-saved'> </span>
 				<?php echo __('Save') ?>
 			</button>
-			<button class="btn btn-default" type="submit" onclick="show_prefs()">
+			<button class="btn btn-default" type="submit" onclick="Prefs.show()">
 				<span class='glyphicon glyphicon-remove'> </span>
 				<?php echo __('Go back') ?>
 			</button></div>
@@ -274,7 +274,7 @@
 			<button class="btn btn-danger" onclick="delete_server()"><?php echo __('Delete') ?></button>
 			</div>
 			<button class="btn btn-primary" type="submit" onclick="save_conn()"><?php echo __('Save') ?></button>
-			<button class="btn btn-default" type="submit" onclick="show_prefs()"><?php echo __('Go back') ?></button></div>
+			<button class="btn btn-default" type="submit" onclick="Prefs.show()"><?php echo __('Go back') ?></button></div>
 		</div>
 	</div>
 
@@ -300,7 +300,7 @@
 
 			print "<li class='row' id='C-$id' connection_id='$id'>";
 			print "<div class='checkbox'><label>";
-			print "<input type='checkbox' onchange='select_row(this)'
+			print "<input type='checkbox'
 				row_id='C-$id'>";
 			print "<a href=\"#\" title=\"".__('Click to edit connection')."\"
 				onclick=\"edit_connection($id)\">".

+ 1 - 1
users.php

@@ -16,7 +16,7 @@
 			$id = $line['id'];
 
 			$tmp .= "<li id='U-$id' class='row' user_id='$id'>";
-			$tmp .= "<input type='checkbox' onchange='select_row(this)'
+			$tmp .= "<input type='checkbox'
 				row_id='U-$id'>";
 			$tmp .= "&nbsp;<a href=\"#\" title=\"".__('Click to edit user')."\"
 				onclick=\"edit_user($id)\">".