thelounge/client/js/utils.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-05-18 22:08:54 +02:00
"use strict";
const $ = require("jquery");
const escape = require("css.escape");
const {vueApp} = require("./vue");
2017-05-18 22:08:54 +02:00
2018-01-11 12:33:36 +01:00
var serverHash = -1; // eslint-disable-line no-var
2017-05-18 22:08:54 +02:00
module.exports = {
findCurrentNetworkChan,
serverHash,
2017-05-18 22:08:54 +02:00
confirmExit,
scrollIntoViewNicely,
hasRoleInChannel,
2017-05-18 22:08:54 +02:00
move,
requestIdleCallback,
2017-05-18 22:08:54 +02:00
};
function findCurrentNetworkChan(name) {
name = name.toLowerCase();
2018-07-09 19:31:48 +02:00
return vueApp.activeChannel.network.channels.find((c) => c.name.toLowerCase() === name);
}
// Given a channel element will determine if the lounge user or a given nick is one of the supplied roles.
function hasRoleInChannel(channel, roles, nick) {
if (!channel || !roles) {
return false;
}
2018-07-19 12:46:30 +02:00
const channelID = channel.attr("data-id");
const network = $("#sidebar .network").has(`.chan[data-id="${channelID}"]`);
const target = nick || network.attr("data-nick");
2019-01-22 15:33:20 +01:00
const user = channel.find(`.names .user[data-name="${escape(target)}"]`).first();
return user.parent().is("." + roles.join(", ."));
}
// Reusable scrollIntoView parameters for channel list / user list
function scrollIntoViewNicely(el) {
// Ideally this would use behavior: "smooth", but that does not consistently work in e.g. Chrome
// https://github.com/iamdustan/smoothscroll/issues/28#issuecomment-364061459
el.scrollIntoView({block: "center", inline: "nearest"});
}
2017-05-18 22:08:54 +02:00
function confirmExit() {
if ($(document.body).hasClass("public")) {
2017-05-18 22:08:54 +02:00
window.onbeforeunload = function() {
return "Are you sure you want to navigate away from this page?";
};
}
}
function move(array, old_index, new_index) {
if (new_index >= array.length) {
let k = new_index - array.length;
2019-07-17 11:33:59 +02:00
while (k-- + 1) {
2017-05-18 22:08:54 +02:00
this.push(undefined);
}
}
2017-05-18 22:08:54 +02:00
array.splice(new_index, 0, array.splice(old_index, 1)[0]);
return array;
}
function requestIdleCallback(callback, timeout) {
if (window.requestIdleCallback) {
// During an idle period the user agent will run idle callbacks in FIFO order
// until either the idle period ends or there are no more idle callbacks eligible to be run.
window.requestIdleCallback(callback, {timeout});
} else {
callback();
}
}