Commit Graph

335 Commits

Author SHA1 Message Date
Anders Kaseorg 719546641f js: Convert a.indexOf(…) !== -1 to a.includes(…).
Babel polyfills this for us for Internet Explorer.

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, {
    visitBinaryExpression(path) {
      const { operator, left, right } = path.node;
      if (
        n.CallExpression.check(left) &&
        n.MemberExpression.check(left.callee) &&
        !left.callee.computed &&
        n.Identifier.check(left.callee.property) &&
        left.callee.property.name === "indexOf" &&
        left.arguments.length === 1 &&
        checkExpression(left.arguments[0]) &&
        ((["===", "!==", "==", "!=", ">", "<="].includes(operator) &&
          n.UnaryExpression.check(right) &&
          right.operator == "-" &&
          n.Literal.check(right.argument) &&
          right.argument.value === 1) ||
          ([">=", "<"].includes(operator) &&
            n.Literal.check(right) &&
            right.value === 0))
      ) {
        const test = b.callExpression(
          b.memberExpression(left.callee.object, b.identifier("includes")),
          [left.arguments[0]]
        );
        path.replace(
          ["!==", "!=", ">", ">="].includes(operator)
            ? test
            : b.unaryExpression("!", test)
        );
        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 2c4101dbc5 dependencies: Upgrade simplebar from 4.2.3 to 5.0.7.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-13 12:46:29 -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
Anders Kaseorg f0e0fe1c15 ui.get_scroll_element: Set up SimpleBar if it’s expected but missing.
Although SimpleBar automatically sets itself up on elements with a
`data-simplebar` attribute, sometimes we try to set event listeners
before that happens.  Create the SimpleBar early in that case.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-07-25 16:18:54 -07:00
Yashashvi Dave 371343709b static/js/common: Extract function `has_mac_keyboard`. 2019-06-24 14:04:42 -07:00
Anders Kaseorg 01613e71fb ui: Replace set_up_scrollbar with data-simplebar attribute.
With perfectScrollbar, we needed to call a function from JavaScript to
enable a scrollbar on a new element, but simplebar has a much simpler
default API one can do by using data-simplebar attributes in the HTML.

So we can delete all the scrollbar creation/deletion code.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-05-19 18:06:38 -07:00
Anders Kaseorg 141088586b Completely replace perfect-scrollbar with SimpleBar.
perfect-scrollbar replaces both the appearance and the behavior of the
scrollbar, and its emulated behavior will never feel native on most
platforms.  SimpleBar customizes the appearance while preserving the
native behavior.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-05-17 12:06:51 -07:00
Steve Howell 82e453d9fe ui: Fix scrollbar regressions.
In between releases, the following commit introduced
a bug where we agressively scroll to the top every
place we call `ui.update_scrollbar`:

    092b73d0b7

The main symptoms were that the left and right sidebars
would go to the top for things like selecting a topic,
getting activity updates from the server, and resizing
the window.  It was very jarring.

The recent commit looked innocuous--the root of the problem
was the original API expressed an intent to scroll to the
top, but didn't actually do it, so it was a bug in hiding.

There are **some** occasions where it's actually appropriate
to scroll to the top, mostly around search filtering, and
in those places we now call the new `ui.reset_scrollbar`
function.

This is a bit of an emergency fix, so particularly with
the settings stuff, we may get more reports of glitches here.

The important thing here is that you almost never want to
reset the scrollTop for sidebars.
2019-01-09 09:15:45 -08:00
Steve Howell 995a26f4e5 ui: Explicity initialize night mode. 2019-01-04 10:54:10 -08:00
Shubham Dhama 092b73d0b7 ui: Fix wrong usage of scrolling to top in ui.updateScrollbar.
This was a bug introduced in 2363c9955a.

Fixes: #11141.
2019-01-02 11:00:01 -08:00
Akash Nimare dbb2d28ad6 hotkey: Update deprecation notice for '*' hotkey.
This PR updates the shortcut of the deprecation notice
for '*' hotkey. On macOS, it should be 'Cmd + s' instead
of 'Ctrl'.
2018-09-21 10:59:55 -07:00
Joshua Pan 2fcc54ac14 ui: Rename update_starred to update_starred_view. 2018-08-01 11:07:44 -07:00
Joshua Pan 47aaa73f96 events: Fix buggy update starred event.
Fixes #10111.
2018-07-31 14:47:36 -07:00
Marco Burstein bb09bea0b6 ui: Simplify hotkey deprecation notices.
To reduce code duplication when creating hotkey deprecation notices,
create the `get_hotkey_deprecation_notice` function. Also, create a
`ui` testing file with a test for the new function.

Fix #10004.
2018-07-23 22:41:59 -07:00
Aditya Bansal 66096e9509 single_message.handlebars: Upgrade to font-awesome 4.7 icon prefixes. 2018-07-11 20:31:17 +05:30
Steve Howell b88206a637 Remove code for full-width feature.
The full-width feature has been turned off for
about four years.
2018-07-07 10:19:15 +02: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
Shubham Dhama dcb6254a4e eslint: Enable `no-extra-parens` rule.
Following sub-configuration is disabled:
                "nestedBinaryExpressions": false,
2018-06-11 07:51:24 -04:00
Shubham Dhama 8852ed588a style: Remove redundant brackets from typeof operator. 2018-06-05 09:22:26 -07:00
Shubham Dhama c6738889a9 eslint: Add and enable `space-unary-ops` rule.
Info about rule at https://eslint.org/docs/rules/space-unary-ops.
2018-06-05 00:47:35 +05:30
Anupam Dagar c8024cec5c hotkey: Close deprecation notice on Enter keypress. 2018-06-03 09:33:16 -07:00
Anupam Dagar 0e8081093b hotkey: Add deprecation notice for '*' hotkey. 2018-06-02 08:59:42 -07:00
Tim Abbott 785d615921 ui: Remove do_stuff_for_desktop_app call.
Apparently I missed this when removing the code for the old desktop
app.
2018-05-15 16:22:44 -07:00
Tim Abbott 1188f4a3e3 notifications: Remove remaining basic window.bridge logic. 2018-05-15 16:00:30 -07:00
Tim Abbott 954fd8178f desktop: Remove logic for legacy QT/webkit desktop app.
We leave around a few comments that may help the new electron desktop
app do similar things in the future.
2018-05-15 16:00:14 -07:00
Steve Howell c7731a7ebb Move functions into ui.initialize().
We had three different initialization entry points
for ui.js, which seems a bit excessive. :)
2018-05-15 15:43:55 -07:00
guaca 83f4c0a723 ui.js: Add minimum scrollbar length. 2018-04-02 10:48:28 -07:00
Tim Abbott 3cfc760506 deprecation: Add fallback for if local storage is not available.
This falls back to a persistent variable for situations where local
storage is not enabled on the system.
2018-04-01 16:19:47 -07:00
Anurag Sharma 1227857de6 hotkeys: Replace C with x for composing PM.
Pressing the 'x' key can now be used to compose a PM.
Pressing the 'C' key displays a modal that shows a deprecation notice.

Fixes #6548.
2018-04-01 16:13:05 -07:00
Steve Howell 9ce9c2f9db Extract info_overlay.js.
There are several ways we open help for keyboard shortcuts,
markdown help, and search operators.

    - from the gear menu
    - from the compose box
    - from the search box
    - hitting ? for keyboard help
    - arrowing/clicking through the tabs

This just moves the relevant code into a module and changes a
bunch of one-line calls in various places.
2018-03-30 09:07:23 -07:00
Gooca 2363c9955a ui scrollbar: Update perfect-scrollbar to 1.3.0.
Update perfect-scrollbar to fix stutter space-scrolling in #8544. Also
reworked deprecated `element.perfectScrollbar` to `new
PerfectScrollbar(element)`.  Lastly, updated provision version and
changed node module path to new path.

This also refactors perfect-scrollbar in help.js to work with updated
version of perfect-scrollbar. Because the update also changed
perfect-scrollbar's css selectors for all scrollbars in zulip, we
update those too.

Fixes #8544.
2018-03-20 21:59:11 -07:00
gooca ba05ac5c77 Refactor perfect-scrollbar: Call ui methods in emoji_picker.js. 2018-03-16 12:47:44 -07:00
Steve Howell 8063f73f6d Extract message_scroll.js.
This mostly moves code from ui.js.

We change the arguments to `message_fetch.load_more_messages()`
to be `opts` with callbacks for `show_loading` and `hide_loading`.

We also defer starting the scroll handler until `message_fetch.js`
has been initialized.
2018-03-08 15:03:47 -08:00
Brock Whittaker 709ffe6361 informational-overlays: Fix category duplication bug, change map to array.
There is a bug on MacOS on Zulip where the categories are all
duplicated due to faulty looping logic, while also changing the Map to
an Array since maps have less cross-browser support.
2018-01-27 15:20:49 -08:00
Cynthia Lin 7d8cd37035 modals: Dynamically replace keyboard shortcuts for Mac OS.
Fixes #3577.
2018-01-22 19:41:17 -05:00
Steve Howell d52552dcc3 Simplify/unify starring messages from the frontend.
We now do all of the main logic for starring/unstarring
a message in `message_flags.toggle_starred`:

    * mark the message as read (just in case)
    * update the UI (i.e. the green star in the message)
    * update the server

The calling code in both the click handler and the hotkey
handler remains simple--they just handle minor details like
finding the message and clearing popovers.

For updating the server, we now call the new
`send_flag_update` helper.

And we continue to delegate some of the logic to
`ui.update_starred`, but we remove some code there that's
now pushed up to `message_flags.toggle_starred`.

This change should be mostly transparent to users, but it
does remove some inconsistent behaviors between the click
handler and the hotkey handler.  Before this change, the
click handler was more aggressive about updating the UI
and marking the message as read.  For people using the "*"
key to star/unstar, they probably would only have noticed
different behavior on a slow connection or in an edge
case scenario where only half of the message was onscreen.

More importantly, by simplifying how we talk to the server,
this eliminated up to a one-second lag due to the debounce
logic in the batch_updater code.  The complicated debounce
logic is only really needed for batch-updating "read"
messages, and it was overkill and sluggish for starring
messages.

Last but not least, we add defensive code for the local
echo case.  (Users have to wait till the message gets acked
to star it.)
2017-12-26 09:01:21 -05:00
Brock Whittaker e0236646bf night-mode: Add custom CSS through JS.
This adds custom CSS through JavaScript for things that do not
scope well and will override other inherited styles.

This should ONLY be used for problematic CSS that has no obvious
or easy CSS-only solution.

(Specifically, we need this for the "default link" styling, which is
hard to override because we don't want to start winning ties due to
specificity that we would not have won in the light theme).
2017-11-29 23:06:11 -08:00
Tommy Ip 6e22847548 refactor: new message content -> compose textarea. 2017-11-28 12:53:40 -08:00
Harshit Bansal 9234abbd59 notifications: Fix realm emojis not appearing in desktop notifications. 2017-10-17 22:03:33 -07:00
Steve Howell c5b7e3f1ab Eliminate have_scrolled_away_from_top boolean.
The `have_scrolled_away_from_top` logic goes way back
to November 2012.

Now we unconditionally load older messages when we scroll
to the top of the feed.  Before this bug, you could get
"stuck."  It was a bit difficult to reproduce, but with
the right combination of render window sizes and batch
sizes, you would hit the home key quickly and hit the top
of the feed in a way that the flag got in the way of
going back in history.

Fixes #6628
2017-10-03 11:29:47 -07:00
Harshit Bansal 5b5bcce098 emoji: Migrate bugdown emoji to use sprite sheets.
This commit switches to use sprite sheets for rendering emojis
in all the remaining places, i.e., message bodies and composebox
typeahead. This commit also includes some changes to notifications.py
file so that the spans used for rendering emojis can be converted
to corresponding image tags so that we don't break the emoji rendering
in missed message emails since we can't use sprite sheets there.

As part of switching the bugdown system to use sprite sheets, we need
to switch the name_to_codepoint mappings to match the new sprite
sheets.  This has the side effect of fixing a bunch of emoji like
numbers and flag emoji in the emoji pickers.

Fixes: #3895.
Fixes: #3972.
2017-09-29 11:14:34 -07:00
Steve Howell b32c3273dc Always re-render locally echoed messages.
Our old optimizations to prevent re-rendering of locally echoed
messages created a lot of code complexity.  This commit is an
experiment to simplify the code, which it clearly does.  The
danger of re-rendering messages is flicker, but our message
view has changed since the original local echo code was written.
2017-09-26 12:50:01 -07:00
akashnimare ab11b7213b js: Replace ZulipDesktop useragent check for old desktop app.
Checking for window.bridge !== undefined is how the old desktop app
had always been tested for in the JS codebase.

Also, "Zulip Desktop" is how this should have been spelled in the first place.

Tweaked by tabbott to provide a proper commit message.

Fixes #6580.
2017-09-20 05:22:24 -07:00
Brock Whittaker 32af99cd4d Display an error for the ZulipDesktop unsupported platform.
This displays an error at the top of the screen on page load that
will inform any user with the userAgent string "ZulipDesktop" that
they should upgrade to our newer electron app

Fixes: #6551.
2017-09-16 03:01:51 -07:00
Vaida Plankyte 971dc71ed6 ui.js: Create perfectScrollbar functions. 2017-08-16 08:07:28 -07:00
Greg Price ee3ead2744 ui: Wait for i18n setup before rendering hotkeys help.
Much like 038a2c769, but for the three tabs at the top of the
`?` help overlay for keyboard shortcuts.
2017-08-07 18:22:51 -07:00
Greg Price 4b765ae304 i18n: Fix a smattering of strings that weren't getting translated.
These are some strings I spotted in English when playing around a bit
with the UI set to German, where our translations are near complete.

It'd be great to have a more systematic way of spotting this kind of
omission.  Probably a fairly simple linter could catch a lot of cases.
2017-07-07 16:59:23 -07:00
Umair Khan d44c62e894 update_starred: Make the status translatable. 2017-06-29 07:39:20 -04:00