Commit Graph

127 Commits

Author SHA1 Message Date
Anders Kaseorg 2868b7c3e3 dict: Replace with Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 15:37:37 -08:00
shubhamgupta2956 efda2684ea util: Replace util.get_message_topic().
Replace `util.get_message_topic(message)` with `message.topic`.

Fixes #13931
2020-02-21 09:53:45 -05: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 59d55d1e06 js: Use modern spread arguments syntax.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-11 17:43:35 -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
Steve Howell 58859ab115 unread: Remove topic counts.
We no longer use topic counts from unread.get_counts().
The topic list widget instead calls
unread.num_unread_for_topic().
2020-02-05 13:04:16 -08:00
Anders Kaseorg ea9212a92d babel: Enable loose mode.
Due to try-catch deoptimization, Babel strict mode for…of loops run
about 5× slower in Firefox than Babel loose mode for…of, native
for…of, or forEach (which are all about the same speed).  Chrome
doesn’t seem to care.

For some reason we need to explicitly add the core-js Symbol polyfill
near the beginning of the common bundle.  Otherwise it gets loaded at
the wrong time and the Casper tests fail.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-05 11:52:52 -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
Tim Abbott ceb0879b0d unread: Add a block comment explaining how it works. 2020-02-04 12:39:58 -08:00
Anders Kaseorg 4480963f5a dict: Remove each method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -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 fe54e73c77 dict, lazy_set: Rename del method to delete, for consistency with Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg 5b824702b4 unread: Replace key_to_bucket Map with Dict/FoldDict/IntDict.
This reverts commit d84646f091 (which
incorrectly assumed in unread_topic_counter that the messages were
present in the message store), while fixing the type confusion problem
by using IntDict for stream_id keys.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:21:29 -08:00
Anders Kaseorg 2f91f583fc unread: Replace buckets with Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 5262ff790e unread: Replace unread_message_ids with Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 6a0de3bb74 unread: Replace unread_mentions_counter with Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg a9e28218b2 unread: Replace reverse_lookup Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg d84646f091 unread: Replace key_to_bucket Dict/FoldDict with Map.
Fixes type confusion in unread_topic_counter, which uses stream IDs as
keys.

Since unread_topic_counter calls message_store.get now, update the
mocks so that message_store.get knows about our mocked messages.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Steve Howell 9ba1829243 streams: Use IntDict for stream/topic unread counts.
Note that we haven't fully swept this for Dict,
since some dicts are keyed by strings.  For
example PM counts can have a huddle like
"101,102,103" as a key.
2020-01-05 12:28:34 -08:00
Steve Howell ee3e488e02 js: Extract FoldDict class.
We have ~5 years of proof that we'll probably never
extend Dict with more options.

Breaking the classes into makes both a little faster
(no options to check), and we remove some options
in FoldDict that are never used (from/from_array).

A possible next step is to fine-tune the Dict to use
Map internally.

Note that the TypeScript types for FoldDict are now
more specific (requiring string keys).  Of course,
this isn't really enforced until we convert other
modules to TS.
2020-01-03 17:19:50 -08:00
Anders Kaseorg 28f3dfa284 js: Automatically convert var to let and const in most files.
This commit was originally automatically generated using `tools/lint
--only=eslint --fix`.  It was then modified by tabbott to contain only
changes to a set of files that are unlikely to result in significant
merge conflicts with any open pull request, excluding about 20 files.
His plan is to merge the remaining changes with more precise care,
potentially involving merging parts of conflicting pull requests
before running the `eslint --fix` operation.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-03 12:42:39 -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
Rohitt Vashishtha 4cfb209dc5 unread: Don't count wildcard mentions in muted streams/topics.
Users generally don't expect wildcard mentions in muted streams and
topics to be treated as a mention, either for the purposes of desktop
notifications or the unread mention counts.

This fixes the unread mention counts part of the issue.

Fixes part of #13073.
2019-10-21 22:23:29 -07:00
Kanishk Kakar e4f0d3d79b notifications: Add 'none' to unread count options. 2019-08-25 21:29:10 -07:00
YashRE42 9f5fca5579 notifications: Refactor and test notifiable unreads logic.
In this refactor, we extract two functions in unread.js.  Which one to
use depends on whether res has already been fetched or not.

This also adds node tests to maintain coverage of unread.js.

Tweaked by tabbott for cleaner variable names and tests.
2019-07-21 14:56:42 -07:00
Tim Abbott 500b161aab unread: Enable the load_server_counts setting for everyone.
This change is long overdue.  After implementing this much more robust
system and deploying it on chat.zulip.org, we hesitated to make
load_server_counts the default behavior in master, because of data
anomalies present for many existing users (basically messages far back
in their history that they had never read, on streams they believed
themselves caught up on), which would have been confusing for many
users.

However, because the mobile apps have been using this data set for a
long time, we've likely cleared out the anomalies from active users'
data set.  And for older users, they're going to come back to
approximately infinite unread messages anyway, so the data anomalies
are unlikely to be important.

Fixes #7096.
2019-07-18 13:34:55 -07:00
Anders Kaseorg 9368c33098 unread.js: Add setter for suppress_unread_counts.
After migration to an ES6 module, `suppress_unread_counts` would no
longer be mutable from outside the module.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-07-08 21:22:54 -07:00
Anders Kaseorg e24ec31823 unread.js: Add setter for messages_read_in_narrow.
After migration to an ES6 module, `messages_read_in_narrow` would no
longer be mutable from outside the module.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-07-08 21:22:54 -07:00
Yashashvi Dave 784d02bf60 static/js/stream_data: Rename `in_home_view` functions. 2019-05-30 21:39:06 -07:00
Thomas Ip a2872c107e typescript: Move TS files into JS directory.
This is just a code reorganization to avoid making it difficult to
find things as we migrate more file to TypeScript.
2019-03-25 12:11:37 -07:00
Thomas Ip 7d050ab0cf typescript: Migrate dict.js to typescript. 2019-03-21 10:48:44 -07:00
Steve Howell 1ad30c6858 subject -> topic: Sweep "message.subject" in frontend.
These were the last remaining files.  After this, only
util.js has a non-email-related use of "subject".
2019-01-01 20:49:38 -08:00
Steve Howell dc5321fed3 message_edit: Add util.get_edit_event_topic(). 2018-12-29 14:14:43 -08:00
Steve Howell 76a73e00f4 unread: Use topic_name as var. 2018-12-29 11:38:39 -08:00
Steve Howell a8718c9051 muting: Use stream_id for internal data structures.
This fixes the most core data structures inside of
muting.js.  We still use stream names for incoming
data to set_muted_topics and outgoing data from
get_muted_topics.

This will make us more resilient to stream name changes.
Before, if you were logged on when a stream rename
occured, topics that were muted under that stream would
appear to be unmuted.  (You could fix it with a reload,
but it can be jarring to have a bunch of unread messages
appear in your feed suddenly.)

Fixes #11033
2018-12-14 15:58:35 -08:00
Armaan Ahluwalia 6d255efe4c app: Prepare JS files for consumption by webpack.
This commit prepares the frontend code to be consumed by webpack.

It is a hack: In theory, modules should be declaring and importing the
modules they depend on and the globals they expose directly.

However, that requires significant per-module work, which we don't
really want to block moving our toolchain to webpack on.

So we expose the modules by setting window.varName = varName; as
needed in the js files.
2018-07-05 10:53:36 +02:00
Steve Howell 9b4a4d09ea Add unread.get_missing_topics().
We will need this for cases where the topic names in
unread.js are a superset of the names we got from messages.

It's important to pass in a dict of existing dicts to avoid
expensive max() calls to get the max ids of topics (otherwise
the plan would have been to merge the lists in the caller).
2018-05-15 14:25:21 -07:00
Steve Howell b5904b264d minor: Pull statements out of loops in unread.js.
We were recalculating the same sub for every iteration
in these two loops.  It's a pretty fast operation
but still nice to do only one time.
2018-05-13 08:47:55 -07:00
Steve Howell 6ca145b2ed Add unread.get_all_msg_ids(). 2018-05-13 08:47:55 -07:00
Steve Howell a68fa980d3 Add starred messages to our new API for unread ids.
Even though starred messages are never unread, it's useful
for us to have helper functions for them.

This change makes it so that clicking on "Starred Messages"
takes you to the last read message immediately, without a
server delay.
2018-05-03 14:36:34 -07:00
Steve Howell 7bc95efb41 Add unread.get_msg_ids_for_mentions(). 2018-05-02 11:23:58 -07:00
Steve Howell 9987ea525f Add unread.get_msg_ids_for_private(). 2018-05-02 11:23:58 -07:00
Steve Howell 0150c01027 Add unread.get_msg_ids_for_person(). 2018-05-02 09:16:24 -07:00
Steve Howell 2b35f26b88 Add unread.get_msg_ids_for_stream(). 2018-05-02 09:16:24 -07:00
Steve Howell c432acb436 Add unread.get_msg_ids_for_topic().
This will be useful for some narrowing related changes.
2018-05-02 09:16:24 -07:00
Tim Abbott 3d5b6539d1 unread: Fix confusing aliasing of variable names. 2018-03-28 12:21:36 -07:00
Steve Howell 199650d5c7 refactor: Stop using flags array for unread counts.
In the JS code, we now use `message.unread` universally as
the indicator of whether a message is unread, rather than
the `message.flags` array that gets passed down to us
from the server.

In particular, we use the unread flag for filtering when
you search.

A lot of this commit is just removing logic to add/remove
"read" from `message.flags` and updating tests.

We also explicitly set `message.unread` to `false` inside of
`unread.mark_as_read()` and no longer have `unread.set_flag()`.

(Some of the callers to `unread.set_flag` were also calling
`unread.mark_as_read`, which was updating the `message`
object, so now we just have `unread.mark_as_read` update
the `message` object.  And then unread_ops.mark_all_as_read()
was already calling unread.declare_bankruptcy().)
2017-12-26 09:01:21 -05:00