Commit Graph

61 Commits

Author SHA1 Message Date
Anders Kaseorg 6ec808b8df js: Add "use strict" directive to CommonJS files.
ES and TypeScript modules are strict by default and don’t need this
directive.  ESLint will remind us to add it to new CommonJS files and
remove it from ES and TypeScript modules.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-31 22:09:46 -07:00
Anders Kaseorg 96dcc0ce6e js: Use ES6 object literal shorthand syntax.
Generated by ESLint.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-21 12:42:22 -07:00
Anders Kaseorg b65d2e063d js: Reformat with Prettier.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-17 14:31:25 -07:00
Anders Kaseorg 6924d501bc js: Indent case clauses in switch statements.
Prettier would do this anyway, but it’s separated out for a more
reviewable diff.  Generated by ESLint.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-17 14:31:25 -07:00
Anders Kaseorg f3726db89a js: Normalize strings to double quotes.
Prettier would do this anyway, but it’s separated out for a more
reviewable diff.  Generated by ESLint.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-17 14:31:24 -07:00
Anders Kaseorg e014ea966a eslint: Enable comma-dangle for functions.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-03 16:55:51 -07:00
Anders Kaseorg b0253c5a2e eslint: Enable arrow-parens.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-03 16:53:39 -07:00
YashRE42 b3eb7b11a8 buddy_data: Extract all user list logic.
This is a prep commit for the buddy_list_mode feature.
2020-04-03 14:51:35 -07:00
YashRE42 148cf30931 refactor: Rename filter_text as user_filter_text.
This is a prep-refactor for adding the buddy_list_mode feature.

Tweaked by tabbott to rename the field across the whole file for
better readability.
2020-04-03 14:47:42 -07:00
Tim Abbott 0f238f29fb unread: Remove suppress_unread_counts flag.
This flag was used to delay unread count updates while the bankruptcy
modal was visible.  Now that bankrupcty is no longer a modal, we don't
need this flag at all.
2020-03-31 15:30:52 -07:00
Stefan Weil d2fa058cc1
text: Fix some typos (most of them found and fixed by codespell).
Signed-off-by: Stefan Weil <sw@weilnetz.de>
2020-03-27 17:25:56 -07:00
Steve Howell 58b72a2194 refactor: Make bot owner hovers more robust.
This is code simplification motivated
by a recent bug that we fixed with some
server changes, but which was really
caused in some sense by our client code
using an overly finicky
condition to check falsiness.

For cross-realm bots, the value of
`user.bot_owner_id` may be `null`, or it
may simply be `undefined`, depending
on whether the server passes `None`
or simply omits the field.

We don't want out client code to be
coupled to that rather arbitrary
decision.

We were doing a `!== null` check instead
of checking for falsiness, which led to
blueslip errors in the past.  Because a
bot owner id could be plausibly 0, a falsiness
check would be brittle in a different way.

Now we avoid that ugliness by calling
`get_bot_owner_user`, which either returns
an object or `undefined`.

And then the caller can just do a concise
check for whether `bot_owner` exists.

And we also fix up the crufty code that
was putting `bot_owner_full_name` on to
the object instead of using a local.

We have a bug report for this again, although
it might be on an old branch.

Fixes #13621.
2020-03-24 20:40:19 -07:00
Steve Howell 9ab07d1038 util.js: Remove util from window.
We now treat util like a leaf module and
use "require" to import it everywhere it's used.

An earlier version of this commit moved
util into our "shared" library, but we
decided to wait on that.  Once we're ready
to do that, we should only need to do a
simple search/replace on various
require/zrequire statements plus a small
tweak to one of the custom linter checks.

It turns out we don't really need util.js
for our most immediate code-sharing goal,
which is to reuse our markdown code on
mobile.  There's a little bit of cleanup
still remaining to break the dependency,
but it's minor.

The util module still calls the global
blueslip module in one place, but that
code is about to be removed in the next
few commits.

I am pretty confident that once we start
sharing things like the typeahead code
more aggressively, we'll start having
dependencies on util.  The module is barely
more than 300 lines long, so we'll probably
just move the whole thing into shared
rather than break it apart.  Also, we
can continue to nibble away at the
cruftier parts of the module.
2020-02-15 12:20:20 -08:00
Anders Kaseorg ef50346a29 js: Convert _.reject(a, … => …) to a.filter(… => !…).
And convert the corresponding function expressions to arrow style
while we’re here.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 4948240619 js: Convert _.filter(a, …) to a.filter(…).
And convert the corresponding function expressions to arrow style
while we’re here.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg ac7b09d57e 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-10 14:08:12 -08:00
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
Anders Kaseorg 737efd1fac presence: Convert presence_info from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Steve Howell b8f01f9cda people: Rename method to get_by_user_id().
This name is consistent with:

    get_by_email()
    get_by_name()
2020-02-05 12:04:56 -08:00
Anders Kaseorg de3146c137 js: Replace [...x] with Array.from(x).
Babel strict generates more code for [...x] than you’d like, while
Babel loose mode assumes x is an array.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-05 11:52:52 -08:00
Steve Howell 145c17d9d6 presence: Remove obsolete defensive code.
If you look at info_for, it clearly never returns
`undefined`, so this defensive code isn't preventing
any bugs.

Also, we are doing a better job now of filtering
user_ids in upstream code.
2020-02-04 12:24:53 -08:00
Steve Howell ef84d47d88 presence: Add warning for missing user_id.
This is defensive code for the scenario that we
have a user_id in presence but not people.  This is
unlikely to occur by the time that we actually render
the buddy list, which is the context for this code.

We have previously been reporting an error here via
the people code, but we add an additional warning.
Also, we filter the user_id from the result.
2020-02-04 12:24:53 -08:00
Anders Kaseorg 45d3be5449 dict, lazy_set: Return an iterator from keys method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg fd9557aa0c unread: Fix {get_msg_ids,num_unread}_for_person type confusion.
These methods take a comma-separated string of user IDs; don’t pass a
number.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Steve Howell 7630b859c3 js: Use IntDict in people.js.
This required lots of manual testing:

    - search/navigate user presence
    - send PM and mention user
    - pay attention to compose fade
    - send stream msg and mention user
    - open Private Messages in top-left and click
    - test unread counts
    - invite user who already has account
    - search for users in search bar
    - check user settings
        - User Groups
        - Users
        - Deactivated Users
        - Bots
    - create a bot
    - mention user groups
    - send group PM then click on lower right
    - view/edit/create streams

If there are still pieces of code that don't convert
ids to ints, the code should still work but report
blueslip errors.

I try to mostly convert user_ids to ints in the callers,
since often the callers are dealing with small amounts
of data, like user ids from huddles.
2020-01-05 12:27:28 -08:00
Anders Kaseorg 16ea89ad89 js: Automatically convert var to let and const in remaining files.
This commit was automatically generated by `tools/lint --only=eslint
--fix`, except for the `.eslintrc.json` change itself.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-20 23:04:01 -08:00
Vinit Singh 19234f8705 sidebar: Move the buddy list tooltip content logic to JS.
Moved the logic from static/templates/buddy_list_tooltip_content.hbs to
the get_title_data function to simplify the template.

Fixes #13426.
2019-11-20 17:04:31 -08:00
Anders Kaseorg 0a75fdff6d buddy_data: Fix node tests.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-20 15:16:08 -08:00
Anders Kaseorg f9f104a4f8 js: Automatically convert var to let and const in more files.
This commit was automatically generated by `tools/lint --only=eslint
--fix`, after an `.eslintrc.json` change.

A half dozen files were removed from the changes by tabbott pending
further work to ensure we avoid breaking valuable PRs with merge
conflicts.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-20 14:10:47 -08:00
Vinit Singh 329d0126bd user status: Add JS tooltips for Buddy List and PM List.
Hovering over user names (and user circles for PM List) now displays
Name, Status Message and Last online time in a js tooltip.
Hovering over group names displays the names of all group members.
Unavailable users are shown as "Last active: Today".

Hovering on a user circle in the Buddy List results in a js tooltip
with Active/Idle/Offline/Unavailable for
green/orange/white/white-with-line.

Resolves #11607.
2019-11-20 12:49:37 -08:00
Anders Kaseorg d17b577d0c js: Purge useless IIFEs.
With webpack, variables declared in each file are already file-local
(Global variables need to be explicitly exported), so these IIFEs are
no longer needed.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-10-25 13:51:21 -07:00
vinitS101 232f588d4e user status: Change Online now to Active now in full user profile.
Change "Online now" to "Active now" in Last seen field of
full user profile.
2019-08-07 16:20:19 -07:00
vinitS101 ead9598fbe user status: Change Active now to Online now in full user profile.
Change "Active now" to "Online now" in Last seen field of
full user profile.
2019-03-14 15:19:09 -07:00
Casper f3a4d2df58 search_users: Add | as OR-operator.
Adds possibility for users to use | as an OR-operator (besides ,)
when searching for other users.

This is a thing reasonable folks might try, and | in the thing to
search for isn't a realisitic possibility, so there's no real downside
to adding this.

Fixes #4109.
2019-03-08 12:09:49 -08:00
vinitS101 2dddf8d8b9 refactor: Move user_last_seen_time_status() to buddy_data.
This is a pure data function, so it shouldn't be in popovers.js file

(Steve Howell added test coverage here, and tabbott removed an
accidental functional change.)
2019-03-01 15:32:14 -08:00
Boris Yankov 31536a48ef user status: Add icon for "unavailable".
Fixes #11589.

Adds SCSS style for the "unavailable" user status and enables its
usage in `buddy_data.js`.

The style is a red circle with a horizontal line. The values might
look a bit 'magic' but they were considered carefully ` height` of
1px was too thin, 2px was too thick, thus 1.5px was chosen.
2019-03-01 09:56:09 -08:00
Steve Howell a6fdac128f refactor: Move huddle_fraction_present() to buddy_data.
This is a pure data function, so there's no sense having
future callers go through activity.js.
2019-02-18 14:22:37 -08:00
Steve Howell 1adcaad04a refactor: Simplify logic for circles.
We now have a function get_user_circle_class
that returns one of these values:

    "user_circle_green"
    "user_circle_orange"
    "user_circle_empty"

And we put that in the templates.

And then CSS renders the circle of the appropriate
color.

The unit tests now explicitly capture whether
we are rendering the correct kind of circle.
2019-02-18 14:22:37 -08:00
Rishi Gupta b856d9c0f9 user status: Change away to unavailable. 2019-02-16 09:28:58 -08:00
Steve Howell 17c906d6bb user status: Surface status in the buddy list.
When you hover over a user that has set a user
status, we now show something like "out to lunch."

You can test this in the console by doing:

    user_status.server_update({status_text: 'out to lunch'})

And then hover over your name in the buddy list.
2019-01-25 16:53:51 -08:00
Steve Howell 7b5f282aee status: Show "(away)" next to yourself if you're away. 2019-01-02 09:27:16 -08:00
Steve Howell 6507804637 status: buddy list: Add basic UI to show away status.
Right now we do very simple things:

    you: make the green circle empty

    them: make the circle empty and demote to last group
2019-01-02 09:23:19 -08:00
Steve Howell bb8750c22b refactor: Export buddy_data.level().
This is mostly for testing purposes.  The code
structure here is pretty stable--we will probably
always use level() here to either sort or
group users, and being able to test it directly
is nice, rather than bringing in all the other
machinery.
2019-01-02 09:16:31 -08:00
Steve Howell 2c719bdb3f buddy list: Exclude current user from searches.
The current user gets excluded from all non-empty
searches, even ones that match the user, since
it can look funny when the user's at the top of a
search, and you'd never need to search for yourself
(again, since the current user is at the top of
the buddy list).
2018-12-18 11:01:06 -08:00
Steve Howell bf152b94b5 presence: Put current user back at the top of the buddy list.
We tried this out, reverted it, and then put it back.
2018-12-18 11:01:01 -08:00
Tim Abbott bdb3da4504 eslint: Add key-spacing linter rule.
Apparently, we didn't have one of these, and thus had a moderate
number of generally very old violations in the codebase.  Fix this and
clear the ones that exist..
2018-12-18 10:41:06 -08:00
Tim Abbott d5f2eb3790 Revert "buddy list: Put "me" at the top of the list."
This reverts commit 1890c30ee1.
2018-12-04 16:08:18 -08:00
Tim Abbott bddf23894d buddy list: Add marker for which user is yourself.
This helps make clear what's going on with the potentially confusing
"you" user.
2018-11-27 15:07:58 -08:00
Steve Howell 1890c30ee1 buddy list: Put "me" at the top of the list.
I think people will want this, particularly folks
with names toward the back of the alphabet.
2018-11-27 14:52:19 -08:00
Steve Howell 3aa490edbe Add current user back to the buddy list.
For many years we have been excluding the current user
from the buddy list, since their presence is kind
of implicit, and it saves a line of real estate.

This commit removes various user-is-me checks
and puts the user back for the following reasons:

    * explicit is better
    * newbies will be less confused when they
      can see they're actually online
    * even long-time users like myself will
      feel more comfortable if it's just there
    * having yourself in the buddy list facilitates
      things like checking your presence or sending
      yourself a message
    * showing "me" reinforces the meaning of the
      green circle (if my circle is green and I'm
      active, then others with green circles must
      be active too)
    * If you're literally the first user in the
      realm, you can now see what the buddy list
      looks like and try out the chevron menu.

The biggest tradeoff here is the opportunity cost.
For an org with more people than fit on the screen,
we put the Nth person below the fold to show "me".
I think that's fine--users can still scroll or
search.

This commit doesn't do anything special with the
current user in terms of sorting them higher in the
list or giving specific styling.

Fixes #10476
2018-11-27 14:52:19 -08:00