Files
zulip/static/js/pm_list.js
Anders Kaseorg 02511bff1c 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-07 14:09:47 -08:00

166 lines
4.6 KiB
JavaScript

let prior_dom;
let private_messages_open = false;
// This module manages the "Private Messages" section in the upper
// left corner of the app. This was split out from stream_list.js.
function get_filter_li() {
return $(".top_left_private_messages");
}
function update_count_in_dom(count_span, value_span, count) {
if (count === 0) {
count_span.hide();
value_span.text('');
} else {
count_span.show();
value_span.text(count);
}
}
function set_count(count) {
const count_span = get_filter_li().find('.count');
const value_span = count_span.find('.value');
update_count_in_dom(count_span, value_span, count);
}
function remove_expanded_private_messages() {
stream_popover.hide_topic_popover();
ui.get_content_element($("#private-container")).empty();
resize.resize_stream_filters_container();
}
exports.close = function () {
private_messages_open = false;
prior_dom = undefined;
remove_expanded_private_messages();
};
exports.get_active_user_ids_string = function () {
const filter = narrow_state.filter();
if (!filter) {
return;
}
const emails = filter.operands('pm-with')[0];
if (!emails) {
return;
}
return people.emails_strings_to_user_ids_string(emails);
};
exports._get_convos = function () {
const private_messages = pm_conversations.recent.get();
const display_messages = [];
const active_user_ids_string = exports.get_active_user_ids_string();
for (const private_message_obj of private_messages) {
const user_ids_string = private_message_obj.user_ids_string;
const reply_to = people.user_ids_string_to_emails_string(user_ids_string);
const recipients_string = people.get_recipients(user_ids_string);
const num_unread = unread.num_unread_for_person(user_ids_string);
const is_group = user_ids_string.indexOf(',') >= 0;
const is_active = user_ids_string === active_user_ids_string;
let user_circle_class;
let fraction_present;
if (is_group) {
user_circle_class = 'user_circle_fraction';
fraction_present = buddy_data.huddle_fraction_present(user_ids_string);
} else {
const user_id = parseInt(user_ids_string, 10);
user_circle_class = buddy_data.get_user_circle_class(user_id);
const recipient_user_obj = people.get_by_user_id(user_id);
if (recipient_user_obj.is_bot) {
user_circle_class = 'user_circle_green';
}
}
const display_message = {
recipients: recipients_string,
user_ids_string: user_ids_string,
unread: num_unread,
is_zero: num_unread === 0,
is_active: is_active,
url: hash_util.pm_with_uri(reply_to),
user_circle_class: user_circle_class,
fraction_present: fraction_present,
is_group: is_group,
};
display_messages.push(display_message);
}
return display_messages;
};
exports._build_private_messages_list = function () {
const finish = blueslip.start_timing('render pm list');
const convos = exports._get_convos();
const dom_ast = pm_list_dom.pm_ul(convos);
finish();
return dom_ast;
};
exports.update_private_messages = function () {
if (!narrow_state.active()) {
return;
}
if (private_messages_open) {
const container = ui.get_content_element($("#private-container"));
const new_dom = exports._build_private_messages_list();
function replace_content(html) {
container.html(html);
}
function find() {
return container.find('ul');
}
vdom.update(replace_content, find, new_dom, prior_dom);
prior_dom = new_dom;
}
};
exports.is_all_privates = function () {
const filter = narrow_state.filter();
if (!filter) {
return false;
}
return _.contains(filter.operands('is'), "private");
};
exports.expand = function () {
private_messages_open = true;
stream_popover.hide_topic_popover();
exports.update_private_messages();
resize.resize_stream_filters_container();
if (exports.is_all_privates()) {
$(".top_left_private_messages").addClass('active-filter');
}
};
exports.update_dom_with_unread_counts = function (counts) {
exports.update_private_messages();
set_count(counts.private_message_count);
unread_ui.set_count_toggle_button($("#userlist-toggle-unreadcount"),
counts.private_message_count);
};
exports.initialize = function () {
};
window.pm_list = exports;