Files
zulip/static/js/stream_color.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

162 lines
5.7 KiB
JavaScript

exports.default_color = "#c2c2c2";
// Classes which could be returned by get_color_class.
exports.color_classes = 'dark_background';
function update_table_stream_color(table, stream_name, color) {
// This is ugly, but temporary, as the new design will make it
// so that we only have color in the headers.
const style = color;
const color_class = exports.get_color_class(color);
const stream_labels = $("#floating_recipient_bar").add(table).find(".stream_label");
for (const label of stream_labels) {
const $label = $(label);
if ($.trim($label.text()) === stream_name) {
const messages = $label.closest(".recipient_row").children(".message_row");
messages.children(".messagebox").css("box-shadow", "inset 2px 0px 0px 0px " + style + ", -1px 0px 0px 0px " + style);
$label.css({background: style,
"border-left-color": style});
$label.removeClass(exports.color_classes);
$label.addClass(color_class);
}
}
}
function update_stream_sidebar_swatch_color(id, color) {
$("#stream_sidebar_swatch_" + id).css('background-color', color);
$("#stream_sidebar_privacy_swatch_" + id).css('color', color);
}
function update_historical_message_color(stream_name, color) {
update_table_stream_color($(".focused_table"), stream_name, color);
if ($(".focused_table").attr("id") !== "#zhome") {
update_table_stream_color($("#zhome"), stream_name, color);
}
}
const stream_color_palette = [
['a47462', 'c2726a', 'e4523d', 'e7664d', 'ee7e4a', 'f4ae55'],
['76ce90', '53a063', '94c849', 'bfd56f', 'fae589', 'f5ce6e'],
['a6dcbf', 'addfe5', 'a6c7e5', '4f8de4', '95a5fd', 'b0a5fd'],
['c2c2c2', 'c8bebf', 'c6a8ad', 'e79ab5', 'bd86e5', '9987e1'],
];
const subscriptions_table_colorpicker_options = {
clickoutFiresChange: true,
showPalette: true,
showInput: true,
palette: stream_color_palette,
};
exports.set_colorpicker_color = function (colorpicker, color) {
colorpicker.spectrum(_.extend(subscriptions_table_colorpicker_options,
{color: color,
container: "#subscription_overlay .subscription_settings.show"}));
};
exports.update_stream_color = function (sub, color, opts) {
opts = _.defaults({}, opts, {update_historical: false});
sub.color = color;
const stream_id = sub.stream_id;
// The swatch in the subscription row header.
$(".stream-row[data-stream-id='" + stream_id + "'] .icon").css('background-color', color);
// The swatch in the color picker.
exports.set_colorpicker_color($("#subscription_overlay .subscription_settings[data-stream-id='" + stream_id + "'] .colorpicker"), color);
$("#subscription_overlay .subscription_settings[data-stream-id='" + stream_id + "'] .large-icon").css("color", color);
if (opts.update_historical) {
update_historical_message_color(sub.name, color);
}
update_stream_sidebar_swatch_color(stream_id, color);
if (!page_params.search_pills_enabled) {
tab_bar.colorize_tab_bar();
}
};
function picker_do_change_color(color) {
const stream_id = parseInt($(this).attr('stream_id'), 10);
const hex_color = color.toHexString();
subs.set_color(stream_id, hex_color);
}
subscriptions_table_colorpicker_options.change = picker_do_change_color;
exports.sidebar_popover_colorpicker_options = {
clickoutFiresChange: true,
showPaletteOnly: true,
showPalette: true,
showInput: true,
flat: true,
palette: stream_color_palette,
change: picker_do_change_color,
};
exports.sidebar_popover_colorpicker_options_full = {
clickoutFiresChange: true,
showPalette: true,
showInput: true,
flat: true,
cancelText: "",
chooseText: "choose",
palette: stream_color_palette,
change: picker_do_change_color,
};
let lightness_threshold;
exports.initialize = function () {
// sRGB color component for dark label text.
// 0x33 to match the color #333333 set by Bootstrap.
const label_color = 0x33;
const lightness = colorspace.luminance_to_lightness(
colorspace.sRGB_to_linear(label_color));
// Compute midpoint lightness between that and white (100).
lightness_threshold = (lightness + 100) / 2;
};
// From a background color (in format "#fff" or "#ffffff")
// pick a CSS class (or empty string) to determine the
// text label color etc.
//
// It would be better to work with an actual data structure
// rather than a hex string, but we have to deal with values
// already saved on the server, etc.
//
// This gets called on every message, so cache the results.
exports.get_color_class = _.memoize(function (color) {
let match;
let i;
const channel = [0, 0, 0];
let mult = 1;
match = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/.exec(color);
if (!match) {
// 3-digit shorthand; Spectrum gives this e.g. for pure black.
// Multiply each digit by 16+1.
mult = 17;
match = /^#([\da-fA-F])([\da-fA-F])([\da-fA-F])$/.exec(color);
if (!match) {
// Can't understand color.
return '';
}
}
// CSS colors are specified in the sRGB color space.
// Convert to linear intensity values.
for (i = 0; i < 3; i += 1) {
channel[i] = colorspace.sRGB_to_linear(mult * parseInt(match[i + 1], 16));
}
// Compute perceived lightness as CIE L*.
const lightness = colorspace.luminance_to_lightness(
colorspace.rgb_luminance(channel));
// Determine if we're past the midpoint between the
// dark and light label lightness.
return lightness < lightness_threshold ? 'dark_background' : '';
});
window.stream_color = exports;