zulip/static/js/util.js

330 lines
9.1 KiB
JavaScript
Raw Normal View History

// From MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random
exports.random_int = function random_int(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
// Like C++'s std::lower_bound. Returns the first index at which
// `value` could be inserted without changing the ordering. Assumes
// the array is sorted.
//
// `first` and `last` are indices and `less` is an optionally-specified
// function that returns true if
// array[i] < value
// for some i and false otherwise.
//
// Usage: lower_bound(array, value, [less])
// lower_bound(array, first, last, value, [less])
exports.lower_bound = function (array, arg1, arg2, arg3, arg4) {
let first;
let last;
let value;
let less;
if (arg3 === undefined) {
first = 0;
last = array.length;
value = arg1;
less = arg2;
} else {
first = arg1;
last = arg2;
value = arg3;
less = arg4;
}
if (less === undefined) {
less = function (a, b) { return a < b; };
}
let len = last - first;
let middle;
let step;
while (len > 0) {
step = Math.floor(len / 2);
middle = first + step;
if (less(array[middle], value, middle)) {
first = middle;
first += 1;
len = len - step - 1;
} else {
len = step;
}
}
return first;
};
function lower_same(a, b) {
return a.toLowerCase() === b.toLowerCase();
}
exports.same_stream_and_topic = function util_same_stream_and_topic(a, b) {
// Streams and topics are case-insensitive.
return a.stream_id === b.stream_id &&
lower_same(
exports.get_message_topic(a),
exports.get_message_topic(b)
);
};
exports.is_pm_recipient = function (email, message) {
const recipients = message.reply_to.toLowerCase().split(',');
js: Convert a.indexOf(…) !== -1 to a.includes(…). Babel polyfills this for us for Internet Explorer. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import K from "ast-types/gen/kinds"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; recast.visit(ast, { visitBinaryExpression(path) { const { operator, left, right } = path.node; if ( n.CallExpression.check(left) && n.MemberExpression.check(left.callee) && !left.callee.computed && n.Identifier.check(left.callee.property) && left.callee.property.name === "indexOf" && left.arguments.length === 1 && checkExpression(left.arguments[0]) && ((["===", "!==", "==", "!=", ">", "<="].includes(operator) && n.UnaryExpression.check(right) && right.operator == "-" && n.Literal.check(right.argument) && right.argument.value === 1) || ([">=", "<"].includes(operator) && n.Literal.check(right) && right.value === 0)) ) { const test = b.callExpression( b.memberExpression(left.callee.object, b.identifier("includes")), [left.arguments[0]] ); path.replace( ["!==", "!=", ">", ">="].includes(operator) ? test : b.unaryExpression("!", test) ); changed = true; } this.traverse(path); }, }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-08 04:55:06 +01:00
return recipients.includes(email.toLowerCase());
};
exports.extract_pm_recipients = function (recipients) {
return recipients.split(/\s*[,;]\s*/).filter(recipient => recipient.trim() !== "");
};
exports.same_recipient = function util_same_recipient(a, b) {
if (a === undefined || b === undefined) {
return false;
}
if (a.type !== b.type) {
return false;
}
switch (a.type) {
case 'private':
if (a.to_user_ids === undefined) {
return false;
}
return a.to_user_ids === b.to_user_ids;
case 'stream':
return exports.same_stream_and_topic(a, b);
}
// should never get here
return false;
};
exports.same_sender = function util_same_sender(a, b) {
return a !== undefined && b !== undefined &&
a.sender_email.toLowerCase() === b.sender_email.toLowerCase();
};
exports.normalize_recipients = function (recipients) {
// Converts a string listing emails of message recipients
// into a canonical formatting: emails sorted ASCIIbetically
// with exactly one comma and no spaces between each.
js: Convert _.map(a, …) to a.map(…). And convert the corresponding function expressions to arrow style while we’re here. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import K from "ast-types/gen/kinds"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; recast.visit(ast, { visitCallExpression(path) { const { callee, arguments: args } = path.node; if ( n.MemberExpression.check(callee) && !callee.computed && n.Identifier.check(callee.object) && callee.object.name === "_" && n.Identifier.check(callee.property) && callee.property.name === "map" && args.length === 2 && checkExpression(args[0]) && checkExpression(args[1]) ) { const [arr, fn] = args; path.replace( b.callExpression(b.memberExpression(arr, b.identifier("map")), [ n.FunctionExpression.check(fn) || n.ArrowFunctionExpression.check(fn) ? b.arrowFunctionExpression( fn.params, n.BlockStatement.check(fn.body) && fn.body.body.length === 1 && n.ReturnStatement.check(fn.body.body[0]) ? fn.body.body[0].argument || b.identifier("undefined") : fn.body ) : fn, ]) ); changed = true; } this.traverse(path); }, }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-08 02:43:49 +01:00
recipients = recipients.split(',').map(s => s.trim());
recipients = recipients.map(s => s.toLowerCase());
recipients = recipients.filter(s => s.length > 0);
recipients.sort();
return recipients.join(',');
};
// Avoid URI decode errors by removing characters from the end
// one by one until the decode succeeds. This makes sense if
// we are decoding input that the user is in the middle of
// typing.
exports.robust_uri_decode = function (str) {
let end = str.length;
while (end > 0) {
try {
return decodeURIComponent(str.substring(0, end));
} catch (e) {
if (!(e instanceof URIError)) {
throw e;
}
end -= 1;
}
}
return '';
};
exports.rtrim = function (str) {
return str.replace(/\s+$/, '');
};
// If we can, use a locale-aware sorter. However, if the browser
// doesn't support the ECMAScript Internationalization API
// Specification, do a dumb string comparison because
// String.localeCompare is really slow.
exports.make_strcmp = function () {
try {
const collator = new Intl.Collator();
return collator.compare;
} catch (e) {
// continue regardless of error
}
return function util_strcmp(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
};
};
exports.strcmp = exports.make_strcmp();
2020-01-11 13:55:21 +01:00
exports.escape_html = function (html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
};
exports.escape_regexp = function (string) {
// code from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
// Modified to escape the ^ to appease jslint. :/
return string.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, "\\$1");
};
exports.array_compare = function util_array_compare(a, b) {
if (a.length !== b.length) {
return false;
}
let i;
for (i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
/* Represents a value that is expensive to compute and should be
* computed on demand and then cached. The value can be forcefully
* recalculated on the next call to get() by calling reset().
*
* You must supply a option to the constructor called compute_value
* which should be a function that computes the uncached value.
*/
const unassigned_value_sentinel = {};
exports.CachedValue = function (opts) {
this._value = unassigned_value_sentinel;
_.extend(this, opts);
};
exports.CachedValue.prototype = {
get: function CachedValue_get() {
if (this._value === unassigned_value_sentinel) {
this._value = this.compute_value();
}
return this._value;
},
reset: function CachedValue_reset() {
this._value = unassigned_value_sentinel;
},
};
exports.find_wildcard_mentions = function (message_content) {
const mention = message_content.match(/(^|\s)(@\*{2}(all|everyone|stream)\*{2})($|\s)/);
if (mention === null) {
return null;
}
return mention[3];
};
exports.move_array_elements_to_front = function util_move_array_elements_to_front(array, selected) {
let i;
const selected_hash = {};
for (i = 0; i < selected.length; i += 1) {
selected_hash[selected[i]] = true;
}
const selected_elements = [];
const unselected_elements = [];
for (i = 0; i < array.length; i += 1) {
if (selected_hash[array[i]]) {
selected_elements.push(array[i]);
} else {
unselected_elements.push(array[i]);
}
}
// Add the unselected elements after the selected ones
return selected_elements.concat(unselected_elements);
};
// check by the userAgent string if a user's client is likely mobile.
exports.is_mobile = function () {
const regex = "Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini";
return new RegExp(regex, "i").test(window.navigator.userAgent);
};
function to_int(s) {
return parseInt(s, 10);
}
exports.sorted_ids = function (ids) {
// This mapping makes sure we are using ints, and
// it also makes sure we don't mutate the list.
js: Convert _.map(a, …) to a.map(…). And convert the corresponding function expressions to arrow style while we’re here. import * as babelParser from "recast/parsers/babel"; import * as recast from "recast"; import * as tsParser from "recast/parsers/typescript"; import { builders as b, namedTypes as n } from "ast-types"; import K from "ast-types/gen/kinds"; import fs from "fs"; import path from "path"; import process from "process"; const checkExpression = (node: n.Node): node is K.ExpressionKind => n.Expression.check(node); for (const file of process.argv.slice(2)) { console.log("Parsing", file); const ast = recast.parse(fs.readFileSync(file, { encoding: "utf8" }), { parser: path.extname(file) === ".ts" ? tsParser : babelParser, }); let changed = false; recast.visit(ast, { visitCallExpression(path) { const { callee, arguments: args } = path.node; if ( n.MemberExpression.check(callee) && !callee.computed && n.Identifier.check(callee.object) && callee.object.name === "_" && n.Identifier.check(callee.property) && callee.property.name === "map" && args.length === 2 && checkExpression(args[0]) && checkExpression(args[1]) ) { const [arr, fn] = args; path.replace( b.callExpression(b.memberExpression(arr, b.identifier("map")), [ n.FunctionExpression.check(fn) || n.ArrowFunctionExpression.check(fn) ? b.arrowFunctionExpression( fn.params, n.BlockStatement.check(fn.body) && fn.body.body.length === 1 && n.ReturnStatement.check(fn.body.body[0]) ? fn.body.body[0].argument || b.identifier("undefined") : fn.body ) : fn, ]) ); changed = true; } this.traverse(path); }, }); if (changed) { console.log("Writing", file); fs.writeFileSync(file, recast.print(ast).code, { encoding: "utf8" }); } } Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-08 02:43:49 +01:00
let id_list = ids.map(to_int);
id_list.sort(function (a, b) {
return a - b;
});
id_list = _.uniq(id_list, true);
return id_list;
};
exports.set_topic_links = function (obj, topic_links) {
obj.topic_links = topic_links;
};
exports.get_topic_links = function (obj) {
return obj.topic_links;
};
exports.set_match_data = function (target, source) {
target.match_subject = source.match_subject;
target.match_content = source.match_content;
};
exports.get_match_topic = function (obj) {
return obj.match_subject;
};
exports.get_draft_topic = function (obj) {
// We will need to support subject for old drafts.
return obj.topic || obj.subject || '';
};
exports.get_reload_topic = function (obj) {
// When we first upgrade to releases that have
// topic=foo in the code, the user's reload URL
// may still have subject=foo from the prior version.
return obj.topic || obj.subject || '';
};
exports.set_message_topic = function (obj, topic) {
obj.topic = topic;
};
exports.get_message_topic = function (obj) {
if (obj.topic === undefined) {
blueslip.warn('programming error: message has no topic');
return obj.subject;
}
return obj.topic;
};
exports.get_edit_event_topic = function (obj) {
if (obj.topic === undefined) {
return obj.subject;
}
// This code won't be reachable till we fix the
// server, but we use it now in tests.
return obj.topic;
};
exports.get_edit_event_orig_topic = function (obj) {
return obj.orig_subject;
};
exports.get_edit_event_prev_topic = function (obj) {
return obj.prev_subject;
};
exports.is_topic_synonym = function (operator) {
return operator === 'subject';
};
exports.convert_message_topic = function (message) {
if (message.topic === undefined) {
message.topic = message.subject;
}
};
window.util = exports;