zulip/static/js/hash_util.js

244 lines
6.8 KiB
JavaScript
Raw Normal View History

import $ from "jquery";
import {$t_html} from "./i18n";
import * as narrow_state from "./narrow_state";
import * as people from "./people";
import * as stream_data from "./stream_data";
import * as ui_report from "./ui_report";
export function get_hash_category(hash) {
// given "#streams/subscribed", returns "streams"
return hash ? hash.replace(/^#/, "").split(/\//)[0] : "";
}
export function get_hash_section(hash) {
// given "#settings/your-account", returns "your-account"
// given '#streams/5/social", returns "5"
if (!hash) {
return "";
}
const parts = hash.replace(/\/$/, "").split(/\//);
return parts[1] || "";
}
export function get_current_hash_category() {
return get_hash_category(window.location.hash);
}
export function get_current_hash_section() {
return get_hash_section(window.location.hash);
}
const hashReplacements = new Map([
["%", "."],
["(", ".28"],
[")", ".29"],
[".", ".2E"],
]);
// Some browsers zealously URI-decode the contents of
// window.location.hash. So we hide our URI-encoding
// by replacing % with . (like MediaWiki).
export function encodeHashComponent(str) {
return encodeURIComponent(str).replace(/[%().]/g, (matched) => hashReplacements.get(matched));
}
export function encode_operand(operator, operand) {
if (operator === "group-pm-with" || operator === "pm-with" || operator === "sender") {
const slug = people.emails_to_slug(operand);
if (slug) {
return slug;
}
}
if (operator === "stream") {
return encode_stream_name(operand);
}
return encodeHashComponent(operand);
}
export function encode_stream_id(stream_id) {
// stream_data appends the stream name, but it does not do the
// URI encoding piece
const slug = stream_data.id_to_slug(stream_id);
return encodeHashComponent(slug);
}
export function encode_stream_name(operand) {
// stream_data prefixes the stream id, but it does not do the
// URI encoding piece
operand = stream_data.name_to_slug(operand);
return encodeHashComponent(operand);
}
export function decodeHashComponent(str) {
try {
// This fails for URLs containing
// foo.foo or foo%foo due to our fault in special handling
// of such characters when encoding. This can also,
// fail independent of our fault, so just tell the user
// that the URL is invalid.
// TODO: Show possible valid URLs to the user.
return decodeURIComponent(str.replace(/\./g, "%"));
} catch {
ui_report.error(
$t_html({defaultMessage: "Invalid URL"}),
undefined,
$("#home-error"),
2000,
);
return "";
}
}
export function decode_operand(operator, operand) {
if (operator === "group-pm-with" || operator === "pm-with" || operator === "sender") {
const emails = people.slug_to_emails(operand);
if (emails) {
return emails;
}
}
operand = decodeHashComponent(operand);
if (operator === "stream") {
return stream_data.slug_to_name(operand);
}
return operand;
}
export function by_stream_uri(stream_id) {
return "#narrow/stream/" + encode_stream_id(stream_id);
}
export function by_stream_topic_uri(stream_id, topic) {
return "#narrow/stream/" + encode_stream_id(stream_id) + "/topic/" + encodeHashComponent(topic);
}
// Encodes an operator list into the
// corresponding hash: the # component
// of the narrow URL
export function operators_to_hash(operators) {
let hash = "#";
if (operators !== undefined) {
hash = "#narrow";
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. 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 { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; 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); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.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; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); 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-06 06:19:47 +01:00
for (const elem of operators) {
// Support legacy tuples.
const operator = elem.operator;
const operand = elem.operand;
const sign = elem.negated ? "-" : "";
hash +=
"/" +
sign +
encodeHashComponent(operator) +
"/" +
encode_operand(operator, operand);
js: Automatically convert _.each to for…of. This commit was automatically generated by the following script, followed by lint --fix and a few small manual lint-related cleanups. 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 { Context } from "ast-types/lib/path-visitor"; import K from "ast-types/gen/kinds"; import { NodePath } from "ast-types/lib/node-path"; import assert from "assert"; 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); const checkStatement = (node: n.Node): node is K.StatementKind => n.Statement.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; let inLoop = false; let replaceReturn = false; const visitLoop = (...args: string[]) => function(this: Context, path: NodePath) { for (const arg of args) { this.visit(path.get(arg)); } const old = { inLoop }; inLoop = true; this.visit(path.get("body")); inLoop = old.inLoop; return false; }; recast.visit(ast, { visitDoWhileStatement: visitLoop("test"), visitExpressionStatement(path) { const { expression, comments } = path.node; let valueOnly; if ( n.CallExpression.check(expression) && n.MemberExpression.check(expression.callee) && !expression.callee.computed && n.Identifier.check(expression.callee.object) && expression.callee.object.name === "_" && n.Identifier.check(expression.callee.property) && ["each", "forEach"].includes(expression.callee.property.name) && [2, 3].includes(expression.arguments.length) && checkExpression(expression.arguments[0]) && (n.FunctionExpression.check(expression.arguments[1]) || n.ArrowFunctionExpression.check(expression.arguments[1])) && [1, 2].includes(expression.arguments[1].params.length) && n.Identifier.check(expression.arguments[1].params[0]) && ((valueOnly = expression.arguments[1].params[1] === undefined) || n.Identifier.check(expression.arguments[1].params[1])) && (expression.arguments[2] === undefined || n.ThisExpression.check(expression.arguments[2])) ) { const old = { inLoop, replaceReturn }; inLoop = false; replaceReturn = true; this.visit( path .get("expression") .get("arguments") .get(1) .get("body") ); inLoop = old.inLoop; replaceReturn = old.replaceReturn; const [right, { body, params }] = expression.arguments; const loop = b.forOfStatement( b.variableDeclaration("let", [ b.variableDeclarator( valueOnly ? params[0] : b.arrayPattern([params[1], params[0]]) ), ]), valueOnly ? right : b.callExpression( b.memberExpression(right, b.identifier("entries")), [] ), checkStatement(body) ? body : b.expressionStatement(body) ); loop.comments = comments; path.replace(loop); changed = true; } this.traverse(path); }, visitForStatement: visitLoop("init", "test", "update"), visitForInStatement: visitLoop("left", "right"), visitForOfStatement: visitLoop("left", "right"), visitFunction(path) { this.visit(path.get("params")); const old = { replaceReturn }; replaceReturn = false; this.visit(path.get("body")); replaceReturn = old.replaceReturn; return false; }, visitReturnStatement(path) { if (replaceReturn) { assert(!inLoop); // could use labeled continue if this ever fires const { argument, comments } = path.node; if (argument === null) { const s = b.continueStatement(); s.comments = comments; path.replace(s); } else { const s = b.expressionStatement(argument); s.comments = comments; path.replace(s, b.continueStatement()); } return false; } this.traverse(path); }, visitWhileStatement: visitLoop("test"), }); 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-06 06:19:47 +01:00
}
}
return hash;
}
export function by_sender_uri(reply_to) {
return operators_to_hash([{operator: "sender", operand: reply_to}]);
}
export function pm_with_uri(reply_to) {
const slug = people.emails_to_slug(reply_to);
return "#narrow/pm-with/" + slug;
}
export function huddle_with_uri(user_ids_string) {
// This method is convenient for callers
// that have already converted emails to a comma-delimited
// list of user_ids. We should be careful to keep this
// consistent with hash_util.decode_operand.
return "#narrow/pm-with/" + user_ids_string + "-group";
}
export function by_conversation_and_time_uri(message) {
const absolute_url =
window.location.protocol +
"//" +
window.location.host +
"/" +
window.location.pathname.split("/")[1];
const suffix = "/near/" + encodeHashComponent(message.id);
if (message.type === "stream") {
return absolute_url + by_stream_topic_uri(message.stream_id, message.topic) + suffix;
}
return absolute_url + people.pm_perma_link(message) + suffix;
}
export function stream_edit_uri(sub) {
const hash = `#streams/${sub.stream_id}/${encodeHashComponent(sub.name)}`;
return hash;
}
export function search_public_streams_notice_url() {
// Computes the URL of the current narrow if streams:public were added.
const operators = narrow_state.filter().operators();
const public_operator = {operator: "streams", operand: "public"};
return operators_to_hash([public_operator].concat(operators));
}
export function parse_narrow(hash) {
let i;
const operators = [];
for (i = 1; i < hash.length; i += 2) {
// We don't construct URLs with an odd number of components,
// but the user might write one.
let operator = decodeHashComponent(hash[i]);
// Do not parse further if empty operator encountered.
if (operator === "") {
break;
}
const raw_operand = hash[i + 1];
if (!raw_operand) {
return undefined;
}
let negated = false;
if (operator[0] === "-") {
negated = true;
operator = operator.slice(1);
}
const operand = decode_operand(operator, raw_operand);
operators.push({negated, operator, operand});
}
return operators;
}
export function is_overlay_hash(hash) {
// Hash changes within this list are overlays and should not unnarrow (etc.)
const overlay_list = [
"streams",
"drafts",
"settings",
"organization",
"invite",
"keyboard-shortcuts",
"message-formatting",
"search-operators",
"about-zulip",
];
const main_hash = get_hash_category(hash);
return overlay_list.includes(main_hash);
}