glowingbear-mainbox/js/glowingbear.js

945 lines
37 KiB
JavaScript
Raw Normal View History

(function() {
'use strict';
// cordova splash screen
document.addEventListener("deviceready", function () {
if (navigator.splashscreen !== undefined) {
navigator.splashscreen.hide();
}
}, false);
2016-09-06 18:11:05 +02:00
var weechat = angular.module('weechat', ['ngRoute', 'localStorage', 'weechatModels', 'bufferResume', 'plugins', 'IrcUtils', 'ngSanitize', 'ngWebsockets', 'ngTouch'], ['$compileProvider', function($compileProvider) {
// hacky way to be able to find out if we're in debug mode
weechat.compileProvider = $compileProvider;
}]);
weechat.config(['$compileProvider', function ($compileProvider) {
2014-12-30 21:05:40 +01:00
// hack to determine whether we're executing the tests
if (typeof(it) === "undefined" && typeof(describe) === "undefined") {
$compileProvider.debugInfoEnabled(false);
}
}]);
2013-02-18 00:49:42 +01:00
2016-09-06 18:11:05 +02:00
weechat.controller('WeechatCtrl', ['$rootScope', '$scope', '$store', '$timeout', '$log', 'models', 'bufferResume', 'connection', 'notifications', 'utils', 'settings',
function ($rootScope, $scope, $store, $timeout, $log, models, bufferResume, connection, notifications, utils, settings)
{
window.openBuffer = function(channel) {
$scope.openBuffer(channel);
$scope.$apply();
};
$scope.command = '';
2017-06-03 00:05:12 +02:00
$scope.themes = ['dark', 'light', 'black', 'dark-spacious', 'blue', 'base16-default', 'base16-light', 'base16-mocha', 'base16-ocean-dark', 'base16-solarized-dark', 'base16-solarized-light'];
// Current swipe status. Values:
// +1: bufferlist open, nicklist closed
// 0: bufferlist closed, nicklist closed
// -1: bufferlist closed, nicklist open
$scope.swipeStatus = 1;
2014-12-30 20:24:33 +01:00
// Initialise all our settings, this needs to include all settings
// or else they won't be saved to the localStorage.
2014-12-30 20:24:33 +01:00
settings.setDefaults({
'theme': 'dark',
2018-08-01 15:41:49 +02:00
'host': window.location.hostname, // Left here for compat - not sure if necessary
'port': 443, // Left here for compat - not sure if necessary
'ssl': true, // Left here for compat - not sure if necessary
2014-12-30 20:24:33 +01:00
'savepassword': false,
'autoconnect': false,
'nonicklist': utils.isMobileUi(),
'alwaysnicklist': false, // only significant on mobile
'noembed': true,
2014-12-30 20:24:33 +01:00
'onlyUnread': false,
'hotlistsync': true,
'orderbyserver': true,
2017-04-23 14:34:12 +02:00
'useFavico': !utils.isCordova(),
'soundnotification': true,
2014-12-30 20:24:33 +01:00
'fontsize': '14px',
'fontfamily': (utils.isMobileUi() ? 'sans-serif' : 'Inconsolata, Consolas, Monaco, Ubuntu Mono, monospace'),
'readlineBindings': false,
2017-04-23 14:34:12 +02:00
'enableJSEmoji': !utils.isMobileUi(),
'enableMathjax': false,
2017-03-06 15:34:45 +01:00
'enableQuickKeys': true,
2016-01-10 11:37:27 +01:00
'customCSS': '',
2016-09-06 18:11:05 +02:00
"currentlyViewedBuffers":{},
2014-12-30 20:24:33 +01:00
});
2014-12-22 22:17:01 +01:00
$scope.settings = settings;
2013-12-17 21:30:22 +01:00
$rootScope.countWatchers = function () {
$log.debug($rootScope.$$watchersCount);
};
2013-10-06 12:34:41 +02:00
// Detect page visibility attributes
(function() {
// Sadly, the page visibility API still has a lot of vendor prefixes
if (typeof document.hidden !== "undefined") { // Chrome >= 33, Firefox >= 18, Opera >= 12.10, Safari >= 7
$scope.documentHidden = "hidden";
$scope.documentVisibilityChange = "visibilitychange";
} else if (typeof document.webkitHidden !== "undefined") { // 13 <= Chrome < 33
$scope.documentHidden = "webkitHidden";
$scope.documentVisibilityChange = "webkitvisibilitychange";
} else if (typeof document.mozHidden !== "undefined") { // 10 <= Firefox < 18
$scope.documentHidden = "mozHidden";
$scope.documentVisibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") { // IE >= 10
$scope.documentHidden = "msHidden";
$scope.documentVisibilityChange = "msvisibilitychange";
}
})();
// Enable debug mode if "?debug=1" or "?debug=true" is set
(function() {
window.location.search.substring(1).split('&').forEach(function(f) {
var segs = f.split('=');
if (segs[0] === "debug" && ["true", "1"].indexOf(segs[1]) != -1) {
$rootScope.debugMode = true;
}
});
// If we haven't reloaded yet, do an angular reload with debug infos
// store whether this has happened yet in a GET parameter
if ($rootScope.debugMode && !weechat.compileProvider.debugInfoEnabled()) {
angular.reloadWithDebugInfo();
}
})();
2016-11-11 13:09:55 +01:00
// Show a TLS warning if GB was loaded over an unencrypted connection,
2017-04-23 14:34:12 +02:00
// except for local instances (testing, cordova, or electron)
2016-11-11 13:09:55 +01:00
$scope.show_tls_warning = (window.location.protocol !== "https:") &&
(["localhost", "127.0.0.1", "::1"].indexOf(window.location.hostname) === -1) &&
2017-04-23 14:34:12 +02:00
!window.is_electron && !utils.isCordova();
2016-11-11 13:09:55 +01:00
2016-04-02 18:07:12 +02:00
if (window.is_electron) {
// Use packaged emojione sprite in the electron app
emojione.imageType = 'svg';
emojione.sprites = true;
emojione.imagePathSVGSprites = './3rdparty/emojione.sprites.svg';
}
$rootScope.isWindowFocused = function() {
if (typeof $scope.documentHidden === "undefined") {
// Page Visibility API not supported, assume yes
return true;
} else {
var isHidden = document[$scope.documentHidden];
return !isHidden;
}
};
if (typeof $scope.documentVisibilityChange !== "undefined") {
document.addEventListener($scope.documentVisibilityChange, function() {
if (!document[$scope.documentHidden]) {
// We just switched back to the glowing-bear window and unread messages may have
// accumulated in the active buffer while the window was in the background
var buffer = models.getActiveBuffer();
// This can also be triggered before connecting to the relay, check for null (not undefined!)
if (buffer !== null) {
buffer.unread = 0;
buffer.notification = 0;
// Trigger title and favico update
$rootScope.$emit('notificationChanged');
}
// the unread badge in the bufferlist doesn't update if we don't do this
$rootScope.$apply();
}
}, false);
}
$rootScope.$on('activeBufferChanged', function(event, unreadSum) {
var ab = models.getActiveBuffer();
2014-06-26 22:38:04 +02:00
// Discard unread lines above 2 screenfuls. We can click through to get more if needs be
// This is to keep GB responsive when loading buffers which have seen a lot of traffic. See issue #859
var linesToRemove = ab.lines.length - (2 * $scope.lines_per_screen + 10);
if (linesToRemove > 0) {
ab.lines.splice(0, linesToRemove); // remove the lines from the buffer
ab.requestedLines -= linesToRemove; // to ensure that the correct amount of lines is fetched should more be requested
ab.lastSeen -= linesToRemove; // adjust readmarker
ab.allLinesFetched = false; // we just removed lines, so we don't have all of them. re-enable "fetch more lines"
}
2014-06-26 22:38:04 +02:00
$scope.bufferlines = ab.lines;
$scope.nicklist = ab.nicklist;
// Send a request for the nicklist if it hasn't been loaded yet
if (!ab.nicklistRequested()) {
connection.requestNicklist(ab.id, function() {
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
// Scroll after nicklist has been loaded, as it may break long lines
$rootScope.scrollWithBuffer(true);
});
} else {
// Check if we should show nicklist or not
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
}
2014-06-27 04:36:30 +02:00
if (ab.requestedLines < $scope.lines_per_screen) {
2014-02-10 20:32:00 +01:00
// buffer has not been loaded, but some lines may already be present if they arrived after we connected
// try to determine how many lines to fetch
var numLines = $scope.lines_per_screen + 10; // that's (a screenful plus 10 lines) plus 10 lines, just to be safe
if (unreadSum > numLines) {
// request up to 4*(screenful + 10 lines)
numLines = Math.min(4*numLines, unreadSum);
}
$scope.fetchMoreLines(numLines).then(
// Update initial scroll position
// Most relevant when first connecting to properly initalise
function() {
$timeout(function() {
2014-09-23 02:08:27 +02:00
var bl = document.getElementById("bufferlines");
var lastScrollHeight = bl.scrollHeight;
var scrollHeightObserver = function() {
if (bl) {
var newScrollHeight = bl.scrollHeight;
if (newScrollHeight !== lastScrollHeight) {
$rootScope.updateBufferBottom($rootScope.bufferBottom);
lastScrollHeight = newScrollHeight;
}
setTimeout(scrollHeightObserver, 500);
}
};
$rootScope.updateBufferBottom(true);
$rootScope.scrollWithBuffer(true);
2014-09-23 02:08:27 +02:00
bl.onscroll = _.debounce(function() {
$rootScope.updateBufferBottom();
}, 80);
setTimeout(scrollHeightObserver, 500);
});
}
);
}
2014-08-28 18:25:40 +02:00
notifications.updateTitle(ab);
setTimeout(function(){
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
});
2014-09-23 02:08:27 +02:00
$timeout(function() {
$rootScope.scrollWithBuffer(true);
2014-09-23 02:08:27 +02:00
});
// Clear search term on buffer change
$scope.search = '';
$scope.search_placeholder = 'Search';
2013-12-17 21:30:22 +01:00
2014-08-28 18:25:40 +02:00
if (!utils.isMobileUi()) {
// This needs to happen asynchronously to prevent the enter key handler
// of the input bar to be triggered on buffer switch via the search.
// Otherwise its current contents would be sent to the new buffer
setTimeout(function() {
document.getElementById('sendMessage').focus();
}, 0);
}
// Do this part last since it's not important for the UI
if (settings.hotlistsync && ab.fullName) {
connection.sendHotlistClear();
}
});
2014-02-18 19:13:23 +01:00
2017-04-23 14:34:12 +02:00
if (!utils.isCordova()) {
$rootScope.favico = new Favico({animation: 'none'});
}
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
2014-02-18 19:13:23 +01:00
2013-10-15 15:21:13 +02:00
$rootScope.$on('notificationChanged', function() {
2014-08-28 18:25:40 +02:00
notifications.updateTitle();
$scope.notifications = notifications.unreadCount('notification');
$scope.unread = notifications.unreadCount('unread');
2017-04-23 14:34:12 +02:00
if (!utils.isCordova() && settings.useFavico && $rootScope.favico) {
2014-08-28 18:25:40 +02:00
notifications.updateFavico();
2013-10-15 15:21:13 +02:00
}
});
$rootScope.$on('relayDisconnect', function() {
// Reset title
$rootScope.pageTitle = '';
$rootScope.notificationStatus = '';
2017-04-23 14:34:12 +02:00
// cancel outstanding notifications (incl cordova)
notifications.cancelAll();
2017-04-23 14:34:12 +02:00
if (window.plugin !== undefined && window.plugin.notification !== undefined && window.plugin.notification.local !== undefined) {
window.plugin.notification.local.cancelAll();
}
models.reinitialize();
2014-03-05 14:20:48 +01:00
$rootScope.$emit('notificationChanged');
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
bufferResume.reset();
});
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
$scope.getBuffers = models.getBuffers.bind(models);
2014-02-25 21:42:59 +01:00
$scope.bufferlines = {};
$scope.nicklist = {};
2013-12-16 14:09:01 +01:00
$scope.activeBuffer = models.getActiveBuffer;
2013-10-08 15:55:07 +02:00
$rootScope.connected = false;
$rootScope.waseverconnected = false;
$rootScope.userdisconnect = false;
$rootScope.reconnecting = false;
2013-02-16 19:18:14 +01:00
2013-10-08 15:55:07 +02:00
$rootScope.models = models;
$rootScope.iterCandidate = null;
2014-12-22 22:17:01 +01:00
if (settings.savepassword) {
$scope.$watch('password', function() {
settings.password = $scope.password;
});
settings.addCallback('password', function(password) {
$scope.password = password;
});
$scope.password = settings.password;
} else {
settings.password = '';
}
// Check if user decides to save password, and copy it over
settings.addCallback('savepassword', function(newvalue) {
if (settings.savepassword) {
// Init value in settings module
settings.setDefaults({'password': $scope.password});
settings.password = $scope.password;
}
});
$rootScope.wasMobileUi = false;
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
$rootScope.wasMobileUi = true;
}
2014-12-22 22:17:01 +01:00
if (!settings.fontfamily) {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-12-22 22:17:01 +01:00
settings.fontfamily = 'sans-serif';
} else {
2014-12-22 22:17:01 +01:00
settings.fontfamily = "Inconsolata, Consolas, Monaco, Ubuntu Mono, monospace";
}
}
2014-07-08 10:51:17 +02:00
$scope.isSidebarVisible = function() {
return document.getElementById('content').getAttribute('sidebar-state') === 'visible';
2014-07-08 10:51:17 +02:00
};
$scope.swipeRight = function() {
// Depending on swipe state
if ($scope.swipeStatus === 1) {
/* do nothing */
} else if ($scope.swipeStatus === 0) {
$scope.showSidebar(); // updates swipe status to 1
} else if ($scope.swipeStatus === -1) {
// hide nicklist
$scope.swipeStatus = 0;
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
} else {
console.log("Weird swipe status:", $scope.swipeStatus);
$scope.swipeStatus = 0; // restore sanity
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
$scope.hideSidebar();
}
};
$rootScope.swipeLeft = function() {
// Depending on swipe state, ...
if ($scope.swipeStatus === 1) {
$scope.hideSidebar(); // updates swipe status to 0
} else if ($scope.swipeStatus === 0) {
// show nicklist
$scope.swipeStatus = -1;
if (!$scope.updateShowNicklist()) {
$scope.swipeStatus = 0;
}
} else if ($scope.swipeStatus === -1) {
/* do nothing */
} else {
console.log("Weird swipe status:", $scope.swipeStatus);
$scope.swipeStatus = 0; // restore sanity
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
$scope.hideSidebar();
}
};
2014-07-08 10:51:17 +02:00
$scope.showSidebar = function() {
document.getElementById('sidebar').setAttribute('data-state', 'visible');
document.getElementById('content').setAttribute('sidebar-state', 'visible');
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
// de-focus the input bar when opening the sidebar on mobile, so that the keyboard goes down
_.each(document.getElementsByTagName('textarea'), function(elem) {
2014-09-23 23:36:03 +02:00
$timeout(function(){elem.blur();});
});
}
$scope.swipeStatus = 1;
2014-07-08 10:51:17 +02:00
};
$rootScope.hideSidebar = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
// make sure nicklist is hidden
document.getElementById('sidebar').setAttribute('data-state', 'hidden');
document.getElementById('content').setAttribute('sidebar-state', 'hidden');
}
$scope.swipeStatus = 0;
2014-07-08 10:51:17 +02:00
};
2014-12-22 22:17:01 +01:00
settings.addCallback('autoconnect', function(autoconnect) {
if (autoconnect && !$rootScope.connected && !$rootScope.sslError && !$rootScope.securityError && !$rootScope.errorMessage) {
$scope.connect();
}
});
2014-07-08 10:51:17 +02:00
// toggle sidebar (if on mobile)
$scope.toggleSidebar = function() {
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
if ($scope.isSidebarVisible()) {
$scope.hideSidebar();
} else {
$scope.showSidebar();
}
2014-02-23 15:17:59 +01:00
}
2014-02-19 16:15:23 +01:00
};
2014-02-24 11:28:43 +01:00
// Watch model and update channel sorting when it changes
var set_filter_predicate = function(orderbyserver) {
if ($rootScope.showJumpKeys) {
$rootScope.predicate = '$jumpKey';
} else if (orderbyserver) {
$rootScope.predicate = 'serverSortKey';
} else {
$rootScope.predicate = 'number';
}
};
settings.addCallback('orderbyserver', set_filter_predicate);
// convenience wrapper for jump keys
$rootScope.refresh_filter_predicate = function() {
set_filter_predicate(settings.orderbyserver);
};
2014-12-22 22:17:01 +01:00
settings.addCallback('useFavico', function(useFavico) {
// this check is necessary as this is called on page load, too
if (!$rootScope.connected) {
return;
}
2017-03-17 09:45:44 +01:00
2017-04-23 14:34:12 +02:00
if (utils.isCordova()) {
return; // cordova doesn't have a favicon
2017-03-17 09:45:44 +01:00
}
2014-12-22 22:17:01 +01:00
if (useFavico) {
2014-08-28 18:25:40 +02:00
notifications.updateFavico();
} else {
2014-08-28 18:25:40 +02:00
$rootScope.favico.reset();
notifications.updateBadge('');
}
});
// To prevent unnecessary loading times for users who don't
2016-04-03 14:32:17 +02:00
// want LaTeX math, load it only if the setting is enabled.
// This also fires when the page is loaded if enabled.
2016-04-03 14:32:17 +02:00
// Note that this says MathJax but we switched to KaTeX
settings.addCallback('enableMathjax', function(enabled) {
2017-04-23 14:34:12 +02:00
// no latex math support for cordova right now
if (!utils.isCordova() && enabled && !$rootScope.mathjax_init) {
// Load MathJax only once
$rootScope.mathjax_init = true;
2016-04-03 14:32:17 +02:00
utils.inject_css("https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css");
utils.inject_script("https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.js");
utils.inject_script("https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/contrib/auto-render.min.js");
}
});
// Inject theme CSS
settings.addCallback('theme', function(theme) {
// Unload old theme
var oldThemeCSS = document.getElementById("themeCSS");
if (oldThemeCSS) {
oldThemeCSS.parentNode.removeChild(oldThemeCSS);
}
// Load new theme
2016-04-03 14:32:17 +02:00
utils.inject_css("css/themes/" + theme + ".css", "themeCSS");
});
2016-01-10 11:37:27 +01:00
settings.addCallback('customCSS', function(css) {
// We need to delete the old tag and add a new one so that the browser
// notices the change. Thus, first remove old custom CSS.
var old_css = document.getElementById('custom-css-tag');
if (old_css) {
old_css.parentNode.removeChild(old_css);
}
// Create new CSS tag
var new_css = document.createElement("style");
new_css.type = "text/css";
new_css.id = "custom-css-tag";
new_css.appendChild(document.createTextNode(css));
// Append it to the <head> tag
var heads = document.getElementsByTagName("head");
heads[0].appendChild(new_css);
});
// Update font family when changed
2014-12-22 22:17:01 +01:00
settings.addCallback('fontfamily', function(fontfamily) {
utils.changeClassStyle('favorite-font', 'fontFamily', fontfamily);
});
2014-07-07 16:09:25 +02:00
// Update font size when changed
2014-12-22 22:17:01 +01:00
settings.addCallback('fontsize', function(fontsize) {
if (typeof(fontsize) === "number") {
// settings module recognizes a fontsize without unit it as a number
// and converts, we need to convert back
fontsize = fontsize.toString();
}
// If no unit is specified, it should be pixels
if (fontsize.match(/^[0-9]+$/)) {
fontsize += 'px';
}
2014-12-22 22:17:01 +01:00
utils.changeClassStyle('favorite-font', 'fontSize', fontsize);
});
2013-10-02 02:32:18 +02:00
$scope.setActiveBuffer = function(bufferId, key) {
// If we are on mobile we need to collapse the menu on sidebar clicks
// We use 968 px as the cutoff, which should match the value in glowingbear.css
2014-08-28 18:25:40 +02:00
if (utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
$scope.hideSidebar();
}
// Clear the hotlist for this buffer, because presumable you have read
// the messages in this buffer before you switched to the new one
// this is only needed with new type of clearing since in the old
// way WeeChat itself takes care of that part
if (models.version[0] >= 1) {
connection.sendHotlistClear();
}
return models.setActiveBuffer(bufferId, key);
2013-07-30 15:22:37 +02:00
};
$scope.openBuffer = function(bufferName) {
var fullName = models.getActiveBuffer().fullName;
fullName = fullName.substring(0, fullName.lastIndexOf('.') + 1) + bufferName; // substitute the last part
if (!$scope.setActiveBuffer(fullName, 'fullName')) {
// WeeChat 0.4.0+ supports /join -noswitch
// As Glowing Bear requires 0.4.2+, we don't need to check the version
var command = 'join -noswitch';
// Check if it's a query and we need to use /query instead
if (['#', '&', '+', '!'].indexOf(bufferName.charAt(0)) < 0) { // these are the characters a channel name can start with (RFC 2813-2813)
command = 'query';
// WeeChat 1.2+ supports /query -noswitch. See also #577 (different context)
if ((models.version[0] == 1 && models.version[1] >= 2) || models.version[1] > 1) {
command += " -noswitch";
}
}
connection.sendMessage('/' + command + ' ' + bufferName);
}
2013-12-16 14:09:01 +01:00
};
2014-08-28 18:25:40 +02:00
//XXX this does not belong here (or does it?)
// Calculate number of lines to fetch
$scope.calculateNumLines = function() {
var bufferlineElements = document.querySelectorAll(".bufferline");
var lineHeight = 0, idx = 0;
while (lineHeight === 0 && idx < bufferlineElements.length) {
lineHeight = bufferlineElements[idx++].clientHeight;
}
var areaHeight = document.querySelector("#bufferlines").clientHeight;
// Fetch 10 lines more than theoretically needed so that scrolling up will correctly trigger the loading of more lines
// Also, some lines might be hidden, so it's probably better to have a bit of buffer there
var numLines = Math.ceil(areaHeight/lineHeight + 10);
2014-06-27 04:36:30 +02:00
$scope.lines_per_screen = numLines;
};
$scope.calculateNumLines();
2014-09-23 02:08:27 +02:00
// get animationframe method
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
// Recalculate number of lines on resize
window.addEventListener("resize", _.debounce(function() {
// Recalculation fails when not connected
if ($rootScope.connected) {
// Show the sidebar if switching away from mobile view, hide it when switching to mobile
// Wrap in a condition so we save ourselves the $apply if nothing changes (50ms or more)
2014-08-28 18:25:40 +02:00
if ($scope.wasMobileUi && !utils.isMobileUi()) {
2014-07-08 10:51:17 +02:00
$scope.showSidebar();
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
}
2014-08-28 18:25:40 +02:00
$scope.wasMobileUi = utils.isMobileUi();
$scope.calculateNumLines();
// if we're scrolled to the bottom, scroll down to the same position after the resize
// most common use case: opening the keyboard on a mobile device
2014-09-23 02:08:27 +02:00
if ($rootScope.bufferBottom) {
var rescroll = function(){
$rootScope.updateBufferBottom(true);
};
$timeout(rescroll, 500);
window.requestAnimationFrame(rescroll);
}
}
}, 100));
2014-02-10 19:43:52 +01:00
$rootScope.loadingLines = false;
$scope.fetchMoreLines = function(numLines) {
if (!numLines) {
2014-06-27 04:36:30 +02:00
numLines = $scope.lines_per_screen;
}
return connection.fetchMoreLines(numLines);
2014-02-10 20:32:00 +01:00
};
2014-02-10 19:43:52 +01:00
$scope.infiniteScroll = function() {
// Check if we are already fetching
if ($rootScope.loadingLines) {
return;
}
var buffer = models.getActiveBuffer();
if (!buffer.allLinesFetched) {
$scope.fetchMoreLines();
}
};
2014-09-23 02:08:27 +02:00
$rootScope.updateBufferBottom = function(bottom) {
var eob = document.getElementById("end-of-buffer");
var bl = document.getElementById('bufferlines');
if (bottom) {
eob.scrollIntoView();
}
$rootScope.bufferBottom = eob.offsetTop <= bl.scrollTop + bl.clientHeight;
};
$rootScope.scrollWithBuffer = function(scrollToReadmarker, moreLines) {
2013-12-28 16:50:31 +01:00
// First, get scrolling status *before* modification
// This is required to determine where we were in the buffer pre-change
var bl = document.getElementById('bufferlines');
var sVal = bl.scrollHeight - bl.clientHeight;
var scroll = function() {
2013-12-09 11:10:11 +01:00
var sTop = bl.scrollTop;
2013-12-28 16:50:31 +01:00
// Determine if we want to scroll at all
2014-02-05 11:19:54 +01:00
// Give the check 3 pixels of slack so you don't have to hit
// the exact spot. This fixes a bug in some browsers
if (((scrollToReadmarker || moreLines) && sTop < sVal) || (Math.abs(sTop - sVal) < 3)) {
var readmarker = document.querySelector(".readmarker");
if (scrollToReadmarker && readmarker) {
// Switching channels, scroll to read marker
bl.scrollTop = readmarker.offsetTop - readmarker.parentElement.scrollHeight + readmarker.scrollHeight;
} else if (moreLines) {
// We fetched more lines but the read marker is still out of view
// Keep the scroll position constant
bl.scrollTop = bl.scrollHeight - bl.clientHeight - sVal;
2013-12-28 16:50:31 +01:00
} else {
// New message, scroll with buffer (i.e. to bottom)
2014-09-23 02:08:27 +02:00
var eob = document.getElementById("end-of-buffer");
eob.scrollIntoView();
}
2014-09-23 02:08:27 +02:00
$rootScope.updateBufferBottom();
2013-10-11 18:45:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
// Here be scrolling dragons
$timeout(scroll);
2014-09-23 02:08:27 +02:00
window.requestAnimationFrame(scroll);
2013-12-16 14:09:01 +01:00
};
2013-10-07 16:58:41 +02:00
2013-02-16 19:18:14 +01:00
2013-02-18 00:49:42 +01:00
$scope.connect = function() {
2014-08-28 18:25:40 +02:00
notifications.requestNotificationPermission();
2014-04-22 19:03:12 +02:00
$rootScope.sslError = false;
2014-05-06 21:48:40 +02:00
$rootScope.securityError = false;
2014-04-22 19:03:12 +02:00
$rootScope.errorMessage = false;
2014-09-23 02:08:27 +02:00
$rootScope.bufferBottom = true;
$scope.connectbutton = 'Connecting';
$scope.connectbuttonicon = 'glyphicon-refresh glyphicon-spin';
2014-12-22 22:17:01 +01:00
connection.connect(settings.host, settings.port, $scope.password, settings.ssl);
2013-12-16 14:09:01 +01:00
};
2013-10-16 14:44:44 +02:00
$scope.disconnect = function() {
$scope.connectbutton = 'Connect';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
bufferResume.reset();
2013-10-16 14:25:07 +02:00
connection.disconnect();
2013-12-16 14:09:01 +01:00
};
$scope.reconnect = function() {
var bufferId = models.getActiveBuffer().id;
connection.attemptReconnect(bufferId, 3000);
};
2014-08-28 18:25:40 +02:00
2014-07-06 16:05:48 +02:00
$scope.showModal = function(elementId) {
document.getElementById(elementId).setAttribute('data-state', 'visible');
};
$scope.closeModal = function($event) {
function closest(elem, selector) {
var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
while (elem) {
if (matchesSelector.call(elem, selector)) return elem;
else elem = elem.parentElement;
}
}
closest($event.target, '.gb-modal').setAttribute('data-state', 'hidden');
};
$scope.toggleAccordion = function(event) {
event.stopPropagation();
event.preventDefault();
var target = event.target.parentNode.parentNode.parentNode;
target.setAttribute('data-state', target.getAttribute('data-state') === 'active' ? 'collapsed' : 'active');
// Hide all other siblings
var siblings = target.parentNode.children;
for (var childId in siblings) {
var child = siblings[childId];
if (child.nodeType === 1 && child !== target) {
child.setAttribute('data-state', 'collapsed');
}
}
};
2013-10-06 12:34:41 +02:00
2014-08-28 18:25:40 +02:00
//XXX what do we do with this?
$scope.hasUnread = function(buffer) {
2013-12-17 21:30:22 +01:00
// if search is set, return every buffer
if ($scope.search && $scope.search !== "") {
2013-10-11 23:47:47 +02:00
return true;
}
2014-12-22 22:17:01 +01:00
if (settings.onlyUnread) {
// Always show current buffer in list
2014-02-08 14:20:33 +01:00
if (models.getActiveBuffer() === buffer) {
return true;
}
// Always show core buffer in the list (issue #438)
// Also show server buffers in hierarchical view
if (buffer.fullName === "core.weechat" || (settings.orderbyserver && buffer.type === 'server')) {
return true;
}
// Always show pinned buffers
if (buffer.pinned) {
return true;
}
return (buffer.unread > 0 && !buffer.hidden) || buffer.notification > 0;
}
return !buffer.hidden;
};
2013-10-11 15:59:55 +02:00
// filter bufferlist for search or jump key
$rootScope.bufferlistfilter = function(buffer) {
if ($rootScope.showJumpKeys) {
// filter by jump key
if ($rootScope.jumpDecimal === undefined) {
// no digit input yet, show all buffers
return true;
} else {
var min_jumpKey = 10 * $rootScope.jumpDecimal,
max_jumpKey = 10 * ($rootScope.jumpDecimal + 1);
return (min_jumpKey <= buffer.$jumpKey) &&
(buffer.$jumpKey < max_jumpKey);
}
} else {
// filter by buffer name
2017-05-19 06:35:04 +02:00
return buffer.fullName.toLowerCase().indexOf($scope.search.toLowerCase()) !== -1;
}
};
// Watch model and update show setting when it changes
2014-12-22 22:17:01 +01:00
settings.addCallback('nonicklist', function() {
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
2014-09-23 02:08:27 +02:00
// restore bottom view
if ($rootScope.connected && $rootScope.bufferBottom) {
$timeout(function(){
$rootScope.updateBufferBottom(true);
}, 500);
}
});
settings.addCallback('alwaysnicklist', function() {
2017-04-17 18:04:30 +02:00
$scope.updateShowNicklist();
});
$scope.showNicklist = false;
// Utility function that template can use to check if nicklist should be
// displayed for current buffer or not is called on buffer switch and
// certain swipe actions. Sets $scope.showNicklist accordingly and returns
// whether the buffer even has a nicklist to show.
$scope.updateShowNicklist = function() {
2018-03-19 11:03:04 +01:00
var ab = models.getActiveBuffer();
// Check whether buffer exists and nicklist is non-empty
if (!ab || ab.isNicklistEmpty()) {
$scope.showNicklist = false;
return false;
}
// Check if nicklist is disabled in settings (ignored on mobile)
if (!utils.isMobileUi() && settings.nonicklist) {
$scope.showNicklist = false;
return true;
}
// mobile: hide nicklist unless overriden by setting or swipe action
if (utils.isMobileUi() && !settings.alwaysnicklist && $scope.swipeStatus !== -1) {
$scope.showNicklist = false;
return true;
}
$scope.showNicklist = true;
return true;
2013-12-16 14:09:01 +01:00
};
2014-08-28 18:25:40 +02:00
//XXX not sure whether this belongs here
2013-10-11 15:59:55 +02:00
$rootScope.switchToActivityBuffer = function() {
// Find next buffer with activity and switch to it
var sortedBuffers = _.sortBy($scope.getBuffers(), 'number');
var i, buffer;
2014-02-18 19:13:23 +01:00
// Try to find buffer with notification
for (i in sortedBuffers) {
buffer = sortedBuffers[i];
if (buffer.notification > 0) {
2013-10-11 15:59:55 +02:00
$scope.setActiveBuffer(buffer.id);
return; // return instead of break so that the second for loop isn't executed
}
}
2014-02-18 19:13:23 +01:00
// No notifications, find first buffer with unread lines instead
for (i in sortedBuffers) {
buffer = sortedBuffers[i];
if (buffer.unread > 0 && !buffer.hidden) {
2013-10-11 15:59:55 +02:00
$scope.setActiveBuffer(buffer.id);
return;
2013-10-11 15:59:55 +02:00
}
2013-10-11 22:43:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
2014-02-28 00:31:32 +01:00
// Helper function since the keypress handler is in a different scope
$rootScope.toggleNicklist = function() {
2014-12-22 22:17:01 +01:00
settings.nonicklist = !settings.nonicklist;
2014-02-28 03:25:59 +01:00
};
2013-10-11 15:59:55 +02:00
$rootScope.switchToAdjacentBuffer = function(direction) {
// direction is +1 for next buffer, -1 for previous buffer
var sortedBuffers = _.sortBy($scope.getBuffers(), $rootScope.predicate);
var activeBuffer = models.getActiveBuffer();
var index = sortedBuffers.indexOf(activeBuffer) + direction;
var newBuffer;
// look for next non-hidden buffer
while (index >= 0 && index < sortedBuffers.length &&
(!newBuffer || newBuffer.hidden)) {
newBuffer = sortedBuffers[index];
index += direction;
}
if (!!newBuffer) {
$scope.setActiveBuffer(newBuffer.id);
}
};
2013-10-17 13:13:01 +02:00
$scope.handleSearchBoxKey = function($event) {
// Support different browser quirks
var code = $event.keyCode ? $event.keyCode : $event.charCode;
2013-10-17 13:13:01 +02:00
// Handle escape
2014-02-08 14:20:33 +01:00
if (code === 27) {
$event.preventDefault();
$scope.search = '';
2013-10-17 13:13:01 +02:00
} // Handle enter
2014-02-08 14:20:33 +01:00
else if (code === 13) {
var index;
$event.preventDefault();
if ($scope.filteredBuffers.length > 0) {
// Go to highlighted buffer if available
// or first one
if ($scope.search_highlight_key) {
index = $scope.search_highlight_key;
} else {
index = 0;
}
$scope.setActiveBuffer($scope.filteredBuffers[index].id);
}
$scope.search = '';
} // Handle arrow up
else if (code === 38) {
$event.preventDefault();
if ($scope.search_highlight_key && $scope.search_highlight_key > 0) {
$scope.search_highlight_key = $scope.search_highlight_key - 1;
}
} // Handle arrow down and tab
else if (code === 40 || code === 9) {
$event.preventDefault();
$scope.search_highlight_key = $scope.search_highlight_key + 1;
} // Set highlight key to zero on all other keypress
else {
$scope.search_highlight_key = 0;
2013-10-17 13:13:01 +02:00
}
2013-12-16 14:09:01 +01:00
};
2013-10-15 15:21:13 +02:00
$rootScope.supports_formatting_date = (function() {
// function toLocaleDateStringSupportsLocales taken from MDN:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#Checking_for_support_for_locales_and_options_arguments
try {
new Date().toLocaleDateString('i');
} catch (e) {
if (e.name !== 'RangeError') {
$log.info("Browser does not support toLocaleDateString()," +
" falling back to en-US");
}
return e.name === 'RangeError';
}
$log.info("Browser does not support toLocaleDateString()," +
" falling back to en-US");
return false;
})();
// Prevent user from accidentally leaving the page
window.onbeforeunload = function(event) {
if ($scope.command !== null && $scope.command !== '') {
event.preventDefault();
// Chrome requires this
// Firefox does not show the site provides message
event.returnValue = "Any unsent input will be lost. Are you sure that you want to quit?";
} else {
if ($rootScope.connected) {
$scope.disconnect();
}
2017-03-17 09:45:44 +01:00
2017-04-23 14:34:12 +02:00
if (!utils.isCordova()) {
2017-03-17 09:45:44 +01:00
$scope.favico.reset();
}
}
};
$scope.init = function() {
if (window.location.hash) {
var rawStr = atob(window.location.hash.substring(1));
window.location.hash = "";
var spl = rawStr.split(":");
var host = spl[0];
var port = parseInt(spl[1]);
var password = spl[2];
var ssl = spl.length > 3;
notifications.requestNotificationPermission();
$rootScope.sslError = false;
$rootScope.securityError = false;
$rootScope.errorMessage = false;
$rootScope.bufferBottom = true;
$scope.connectbutton = 'Connecting';
$scope.connectbuttonicon = 'glyphicon-chevron-right';
connection.connect(host, port, password, ssl);
}
};
2014-08-28 18:25:40 +02:00
}]);
2013-10-27 20:49:51 +01:00
2013-12-17 21:30:22 +01:00
weechat.config(['$routeProvider',
2013-10-27 20:49:51 +01:00
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'index.html',
controller: 'WeechatCtrl'
2013-10-27 20:49:51 +01:00
});
}
]);
})();