Commit Graph

6524 Commits

Author SHA1 Message Date
Anders Kaseorg 4f748fb627 markdown: Stop setting target="_blank".
This setting is being overridden by the frontend since the last
commit, and the security model is clearer and more robust if we don't
make it appear as though the markdown processor is handling this
issue.

Co-authored-by: Tim Abbott <tabbott@zulipchat.com>
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-01 14:01:45 -07:00
Anders Kaseorg 68cfcd6446 CVE-2020-9444: Prevent reverse tabnabbing attacks.
While we could fix this issue by changing the markdown processor,
doing so is not a robust solution, because even a momentary bug in the
markdown processor could allow cached messages that do not follow our
security policy.

This change ensures that even if our markdown processor has bugs that
result in rendered content that does not properly follow our policy of
using rel="noopener noreferrer" on links, we'll still do something
reasonable.

Co-authored-by: Tim Abbott <tabbott@zulipchat.com>
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-01 14:01:45 -07:00
Tim Abbott f572bf50f5 message_list_view: Suppress exceptions for missing mention users.
If we can't find data on a mentioned user to update its full_name to
the current value, we'll have to go with the value in the message
itself.

This can happen if e.g. we hard-deleted the originally mentioned user
from the database (which can sometimes happen after a "delete my
account completely" request).
2020-03-31 17:56:12 -07:00
Ryan Rehman 9cb2475b53 notification_settings: Display streams that differ.
The user has an option for setting global
notification settings as well as the same settings
for individual streams. Currently the user has to
keep track of each unmatched stream and then visit
each individual stream whose settings he wants to
update.

Thus this adds a dedicated UI table allowing the user
to view and update the notifications of the specific
streams which differs from the global settings.
It is located on the same page where the user defined
global notification settings can be modified.

Fixes #9228.
2020-03-31 15:57:47 -07:00
Ryan Rehman e845b2364f refactor: Remove redundant block in `stream_edit.stream_setting_clicked`.
Currently we are updating the checkbox UI as soon as the user clicks.
This block is removed to match with the pattern of rest of the
properties in the stream edit page where `stream_events.update_property`
is responsible for updating the UI after a successful server response.
2020-03-31 15:36:59 -07:00
Ryan Rehman c759083cb8 notification settings: Add helper function for stream notifications.
This function returns a list of objects to create a
list_render object, and each item contains the streams
whose atleast one notification setting differs from the
default set by the user.

This is done by comparing the global settings in the
`#settings/notifications` page with those settings
present in the subscribed streams.

Work towards #9228.
2020-03-31 15:36:59 -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
majordwarf e85e598e56 bankruptcy: Migrate from modal view to top-of-page panel.
Switched to top-of-page prompt to make it natural to fit in with other
notifications. As we switch to panel-based prompt, templates for the
bankruptcy modal are moved along with its usage in application's
homepage.

We include a bit of delay before reloading to make it easy for the
user to read the "Marking all messages as read" banner before it is
covered by the "Reloading..." notice in environments where the reload
is fast.

Fixes #3347.
2020-03-31 15:30:37 -07:00
sahil839 3cea9ce1c4 stream_edit: Fix closing settings overlay after closing modals.
When stream_post_policy modal is closed either after saving or using
cancel button or cross button, the pointer-events is set to none which
does not allow to close the stream settings overlay on one click.

Added overlay.close_modal on saving such that pointer-events:none is
removed.

Added line which removes pointer-events:none again on clicking cancel
button or close icon.
2020-03-31 15:15:11 -07:00
sahil839 e43614debd overlays: Extract methods for disabling and enabling mouse events.
This is a prep commit which extracts the part of the code in open_modal
and close_modal to separate methods which adds inline style of
pointer-events to enable/disable the background mouse events.

Block comments are added for easy understanding of reader.
2020-03-31 15:12:44 -07:00
vaibhavrajsingh2001 51a8873579 widgets: Hide edit question icon in poll widget for non-author users.
If a non-author user clicked on view source in a poll and then close it,
the edit question icon would incorrectly get visible. This made changing
the question in local echo possible for non-author users.

Fixes: #14299
2020-03-28 15:04:36 -04: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
Tim Abbott 737a36a9f8 portico: Use a backend variable to determine desktop version.
This makes it possible to change this parameter without rebuilding all
the server's static assets.
2020-03-27 01:37:56 -07:00
sahil839 a2efe3ab64 narrow: Show starred messages from muted topics in starred message view.
Starred messages from muted topics were not shown in the starred
messages view. Condition for muting_enabled is modified accordingly
such that the starred messages from muted topics is shown in the
starred messages narrowed view.

Node tests are updated accordingly.

Fixes #13548
2020-03-27 00:17:26 -07:00
Anders Kaseorg 7ff9b22500 docs: Convert many http URLs to https.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-03-26 21:35:32 -07:00
Tim Abbott a97d19c8aa server_events_dispatch: Clean up can_create_streams logic.
The previous logic avoided updating the setting for
non-administrators, because their value was always true, but removing
those if statements results in better test coverage and is more likely
correct if we ever try to support live-update for whether the user is
an administrator.
2020-03-26 14:16:41 -07:00
Jagan 5a1df798bc banner: Notify organization admins to change default description.
We've noticed that many production organizations don't set either an
organization description or profile picture, even large open source
organizations that could definitely take advantage of this feature.

This adds a top-of-page banner that bugs organization administrators
to add an organization description and profile picture, generally
starting on the second login (as we only do it on page load after
notifications are configured).

Significantly tweaked by tabbott to get the right user experience.

Fixes #14019.
2020-03-26 13:10:37 -07:00
Tim Abbott 900aea88a4 panels: Restructure to actually make sense.
The original implementation of panels.js was just for notifications,
and ended up running a bunch of notifications-specific code, including
registration click handlers and some localstorage-related
notifications logic, every time a panel was supposed to be opened.

This refactoring makes the panels library make sense -- we now
initialize all click handlers in the initialize() method, and do the
notifications check in a single, coherent place scoped to notifications.
2020-03-26 12:49:55 -07:00
Vaibhav Raj Singh ee9678a2bd stream settings: Fix issues with viewing/editing long stream names.
In continuation to #13250

CHANGES:
-the stream name edit button is now visible for long names too.
-ellipsis are removed when you click on edit name option.
-added border while editing name to give a text-box feel.

REASONS:
-added border while editing the name to give a textbox-esque feel.
-text overflow was changed from ellipsis to clip (while editing) as
ellipsis prevented editing the entire name (clip provides better
functionality).

The last two changes are reverted back to original (i.e. ellipsis and
no border) once you finish editing the stream name.

P.S.- clicking on anywhere else updates the new name perfectly
2020-03-25 17:56:32 -07:00
Pragati Agrawal dd13136371 settings: Migrate notification checkboxes to table format.
Here we have migrated checkboxes of all general notifications to the table.
By general notifications we mean, Mobile, Email, Desktop audio, and visual
notifications.

This is a part of a bigger migration to simply our notifications setting
changing infrastructure for all streams and individual streams. Later we
will add more row to this for different categories of notifications in
addition to the current ones ("Streams" and "PMs, mentions, alerts").

Fixes: #12182.
2020-03-25 17:45:59 -07:00
Steve Howell 1826bac1b1 default streams: Fix overly aggressive typeahead.
When you select a typeahead, it shouldn't
immediately do the action for you; you should
have to hit enter first.  Even though 99% of
the time you're gonna confirm the typeahead,
it's jarring when you don't expect it.

You can still add a bunch of default streams
quickly, using only the keyboard, because
we have always had support for the enter
key saving.  (and tab and enter also works)
2020-03-25 17:11:25 -07:00
Steve Howell 697b00dd6e default streams: Change remove api to use stream_id.
This is a full-stack change:

    - server
    - JS code
    - templates

It's all pretty simple--just use stream_id instead
of stream_name.

I am 99% sure we don't document this API nor use it
in mobile, so it should be a safe change.
2020-03-25 17:11:25 -07:00
Steve Howell 2cd9c77979 refactor: Stop using page_params.realm_default_streams.
We now only use `page_params.realm_default_streams` during
initialization, and then after that we use `stream_data`
APIs to get default stream ids and related info.  (And
for the event that replace the data, we just update our
internal data structures as well.)

Long term we should have the server just send us ids here,
since we are now hydrating info from stream data in all places.
2020-03-25 17:11:25 -07:00
Steve Howell ba495e57eb refactor: Simplify get_invite_stream_data().
This code is a bit simpler.

The previous code was concatenating two lists
and then removing duplicates by calling filter().

Now we just have two loops that append to a single
list, and the second loop detects duplicates
before inserting into the list.

We also now use `default_stream_ids` instead of
`page_params` data, which is convenient for two
reasons:

    - working with sets of ids is convenient
    - we don't need to maintain `page_params`
      data any more
2020-03-25 17:11:25 -07:00
Steve Howell 6313917143 stream_data: Remove invite_streams().
This function was made obsolete in
b4e2313cbc.

It was replaced by get_invite_stream_data(),
which has plenty of coverage.
2020-03-25 17:11:25 -07:00
Steve Howell 4610ef3169 refactor: Remove stream_data.get_default_status().
There was no reason to have this when it's more
robust to look up streams by id than name.
2020-03-25 17:11:25 -07:00
Steve Howell abc0c4d48c default streams: Make filters case-insensitive. 2020-03-25 17:11:25 -07:00
Steve Howell a81fd786f5 refactor: Use get_default_stream_ids() in settings.
We now use the up-to-date info from stream_data
to hydrate the default stream ids.  All we need
here in the template is `invite_only` and `name`.

Since we are no longer using data from `page_params`,
we can remove `maybe_update_realm_default_stream_name`.
(If you are wondering if we still get live updates,
we get that via a more upstream call to
update_default_streams_table in the event
dispatching codepath.)
2020-03-25 17:11:25 -07:00
Steve Howell 8d8226117c refactor: Extract get_default_stream_ids().
We only used get_default_stream_names() in a
test, so now it's being replaced with a function
that just gets ids.

We'll have use for get_default_streams_ids()
in an upcoming commit.
2020-03-25 17:11:25 -07:00
Steve Howell f8913dc321 default streams: Remove complicated remove logic.
Now if a default stream gets deleted, we just
redraw the table.  We always have a small number
of default streams, and the way that we were removing
rows without the actual consent of `list_render` was
really janky (and just a vestige of pre-list-render
code that never got fully ported).

This also makes us consistent with how we handle
added streams (i.e. just call
`update_default_streams_table`).

ASIDE:

Ideally we will update `list_render` at some point to
have an API for adding and removing elements.  It does
allow you now to call `data()` to reset its data, but
for now we just build a new `list_render` object every
time.
2020-03-25 17:11:25 -07:00
Anders Kaseorg 77ce5841b9 info_overlay: Fix keyboard accessibility of keyboard shortcuts modal.
Commit 03393631bd (#14142) regressed the
keyboard accessibility of the keyboard shortcuts modal.  Fix it by
moving tabindex="0" to the scrolling element of the SimpleBar.

Fixes #14320.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-03-24 20:41:24 -07:00
Steve Howell 6d03b82dcb bot_data: Remove set_can_admin.
We stopped needing this with
0329b67048
(Dec 2016).

The function sets `bot.can_admin`,
which was only used in `bot_data.get_editable`.

We removed two tests (and then put back
some test setup that needed to leak down
to the last test).
2020-03-24 20:40:19 -07:00
Steve Howell 4a78b54c53 bot settings: Simplify code for bot owners. 2020-03-24 20:40:19 -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 d916cbbb70 cosmetic: Remove ugly bot_data__* names. 2020-03-24 20:40:19 -07:00
Pragati Agrawal 6fb438277e settings_notifications: Use single `.on()` instead of multiple `.click()`.
By this change we don't need to loop over each input element to attach the
handler, instead, we can use single `.on()` which takes care of changes.
2020-03-24 16:06:45 -07:00
Pragati Agrawal 0080499b08 settings_notifications: Use get_input_element_value for input values.
settings_org.get_input_element_value function returns values of input
elements in proper format based on their data-setting-widget-type.
2020-03-24 16:06:45 -07:00
Pragati Agrawal 83933034a4 settings: Simplify logic to show push notification tooltip in templates.
Instead of having logical expressions in templates, it's always preferred
to calculating them in javascript and pass the results as a context. It
also enhances the readability of templates and testing of such logic is
easier in js over templates.
2020-03-24 16:06:45 -07:00
Pragati Agrawal 1871443d10 settings_notifications: Rename variable to all_notification_settings.
`all_notification_settings_labels` is misleading that this variable is a
list of notifications setting labels so changed it to
`all_notification_settings`.
2020-03-24 16:06:45 -07:00
Pragati Agrawal b8945bafb4 settings_org: Extract get_input_element_value function.
The reason for extracting this function is that getting the text, integer,
boolean value from the input elements (like checkboxes, dropdowns) is a
common task, and later we can use this function to get the input element
value in `settings_notifications` in the upcoming commit.
2020-03-24 16:06:45 -07:00
Ryan Rehman f439bd7c36 list_render: Reset Data for sorted tables.
This is a bug fix where, if a list_render
object with the given name exists and it's items
have been sorted, then the filtered_list's data
does not get updated on re-rendering.

This line was present in the original commit
9576d5caef.
2020-03-24 16:06:45 -07:00
Ryan Rehman 1c605366ed list_render: Remove requirement of filter in opts.
The use case for this are small or fixed tables, which do not need
filtering support. Thus we are able to not include the unnecessary
search input inside the html parent container.
It is not used at present, but will be required when we refactor
the settings pages.

We also split out exports.validate_filter function for
unit testing the above condition.
2020-03-24 16:06:45 -07:00
shubhamgupta2956 6ab1908214 settings: Reword setting name in settings menu.
Rewords "User list on left sidebar in narrow windows" in settings menu
to "Show user list on left sidebar in narrow windows".
2020-03-24 10:47:00 -07:00
Siddharth Varshney 328961a4fc settings: Reorganize options/sections in `Organization Permissions`.
As a consequence of too many options in the bottom `Other permissions`
subsection, the `Save` button could end up too far up from the bottom,
such that it might appear offscreen on low-height laptops.

We fix this by reorganizing the settings in a way that is both more
intuitive and also ensures that none of the subsections are too tall.

Fixes: #14274.
2020-03-24 10:36:40 -07:00
Steve Howell 3e199ed559 reactions: Remove name from local_id.
Adding the emoji name, which can have multiple aliases,
to the `local_id` key seemed to needlessly complicate
the code here.
2020-03-23 17:30:18 -04:00
Steve Howell f59cca2dcd reactions: Rewrite code to use clean reactions.
Before this commit, the reactions code would
take the `message.reactions` structure from
the server and try to "collapse" all the reactions
for the same users into the same reactions,
but with each reaction having a list of user_ids.
It was a strangely denormalized structure that
was awkward to work with, and it made it really
hard to reason about whether the data was in
the original structure that the server sent or
the modified structure.

Now we use a cleaner, normalized Map to keep
each reaction (i.e. one per emoji), and we
write that to `message.clean_reactions`.

The `clean_reactions` structure is now the
authoritatize source for all reaction-related
operations.  As soon as you try to do anything
with reactions, we build the `clean_reactions`
data on the fly from the server data.

In particular, when we process events, we just
directly manipulate the `clean_reactions` data,
which is much easier to work with, since it's
a Map and doesn't duplicate any data.

This rewrite should avoid some obscure bugs.

I use `r` as shorthand for the clean reaction
structures, so as not to confuse it with
data from the server's message.reactions.

It also avoids some confusion where we use
`reaction` as a var name for the reaction
elements.
2020-03-23 17:30:18 -04:00
Steve Howell 9c027e76bb search/hash_util: Parse negated searches properly.
Fixes #14254

You can test this on dev:

    * do "-stream:Verona" in the search bar (the minus
      sign negates the search here)
    * reload the browser

You should see the same search (all streams besides Verona).
2020-03-22 11:29:02 -07:00
Steve Howell 778d457bf7 Avoid blueslip error for empty streams.
We simplify the code for deciding whether
we show a subscribe button or not, and in
doing so avoid a blueslip error where we
were passing `undefined` into `get_sub()`.
2020-03-22 11:29:02 -07:00
Steve Howell f0c99b42ec Rename people.add_in_realm to people.add().
We had this API:

    people.add_in_realm = full-fledged user
    people.add = not necessarily in realm

Now the API is this:

    people.add = full-fledged user
    people._add_user = internal API for cross-realm bots
        and deactivated users

I think in most of our tests the distinction between
people.add() and people.add_in_realm() was just an
accident of history and didn't reflect any real intention.

And if I had to guess the intention in 99% of the cases,
folks probably thought they were just creating ordinary,
active users in the current realm.

In places where the distinction was obviously important
(because a test failed), I deactivated the user via
`people.deactivate`.

For the 'basics' test in the people test suite, I clean
up the test setup for Isaac.  Before this commit I was
adding him first as a non-realm user then as a full-fledged
user, but this was contrived and confusing, and we
didn't really need it for test coverage purposes.
2020-03-22 10:55:11 -07:00
Steve Howell 25d2e2e122 Rename get_realm_persons() to get_realm_users().
The function's name was misleading, since it includes
any bots in your realm.
2020-03-22 10:55:11 -07:00
Steve Howell 7ac5d0602b minor: Rename function to get_active_humans().
Saying `human_persons` is a bit redundant (although
kind of an artifact of our legacy use of `person`
when we really mean `user`.)
2020-03-22 10:55:11 -07:00
Steve Howell 26daeeb358 minor: Optimize get_active_human_persons().
This is used in a few settings panels.  We
optimize it by avoiding creating an intermediate
list of all users.
2020-03-22 10:55:11 -07:00
Steve Howell 156ff33d22 stream edit: Extract stream_data.potential_subscribers().
We want to move more logic to stream_data to facilitate
testing.

Both before and after this commit, we essentially build a
new list of users for typeahead, but now the new list
excludes subscribed users.  We can do even better than
this in a follow-up commit.
2020-03-22 10:55:11 -07:00
Steve Howell 7088d09094 presence/people: Use people.get_active_human_count().
Before this commit, presence used get_realm_count()
to determine whether a realm was "small" (and thus
should show all human users in the buddy list, even
humans that had not been active in a while).

The `get_realm_count` function--despite a very wrong,
misleading comment--was including bots in its count.

The new function truly counts only active humans
(and no bots).

Because we were overcounting users before this change,
we should technically adjust `BIG_REALM_COUNT` down
by some amount to reflect our original intention there
on the parameter.  I'm leaving it alone for now, though,
since we've improved the performance of the buddy list
over time, and it's probably fine if a few "big" realms
get re-classified as small realms (and show more users)
by virtue of this change.

(Also note that this cutoff value only affects the
"normal" view of the buddy list; both small realms
and large realms will show long-inactive users if you
do searches.)

Fixes #14215
2020-03-22 10:55:11 -07:00
YashRE42 96cd8d3677 filter: Cache value of can_mark_messages_read.
Given that can_mark_messages_read is called whenever the blue box
cursor stops on a message and that it is calculated purely on the
basis of sorted_term_types, it makes sense to cache the result.
2020-03-17 12:27:08 -07:00
YashRE42 4d972e1d10 filter: Cache/store sorted_term_types.
Given that the sorted term types depends only on the filter, it makes
sense to only build them once and cache the results.
2020-03-17 12:27:08 -07:00
Pranav 83ad56aa64 ui: Fix list_render sorting breaking after re-creation/update.
Previously, when list_render.create was called, if a list_render
object with the given name existed, it returned the existing
list_render object with the previous properties, without the property
to sort the lists added.  The root cause of the bug was that when we
added the sorting click handlers, we put them just in the constructor,
not in __set_events, the function we call from appropriate code paths
to add the other necessary click handlers.

Fix this by moving the code to add the sorting properties into
__set_events().

Fixes #14175.
2020-03-17 12:08:02 -07:00
Steve Howell 327831df1e hotkeys: Fix "n" key behavior in some narrows.
If you were in the "Starred messages" narrow and
your pointer was on a message with the stream/topic
of "social/lunch", we wouldn't move you to the unread
messages for that topic.

I fixed this by removing the code that looked at
the current message's topic.  Instead, we only look
at the active narrow to figure out the "next" topic
to go to.

Fixes #14120.
2020-03-17 05:41:47 -07:00
majordwarf 68dcdcd28e todo_list: Add task description and index numbers.
The user can pass description along with the task name by splitting the input string with hyphen.

Eg: Task Title - Task Description
todo_list: Add index numbers to task.
2020-03-12 08:02:06 -04:00
Tim Abbott 68274cae74 apps: Fix broken desktop download links.
This was introduced by my failing to properly test the recent bundle
of changes to this logic.
2020-03-10 14:38:23 -07:00
BIraj 60385366f0 js: Cleanup debug.js example to use ES syntax. 2020-03-09 14:07:13 -07:00
sahil839 6a791e1939 subscriber list: Fix display of email addresses in subscribers list.
Original email address is shown to admin users in subscriber list when
email_address_visibilty is set to "Admins only" by passing delivery_email
at required places.  Email address are not shown to non-admin users when
visibility is set to "Admins only".

Tweaked by tabbott to fix a few bugs and dead code.

Fixes a part of #13541.
2020-03-08 12:42:08 -07:00
Tim Abbott d0927d38fc streams: Use user IDs in membership list to track subscribers.
User IDs are more robust than email addresses as they don't change
with time, and also don't have complications with
different email_address_visibility settings.
2020-03-08 12:37:48 -07:00
Divyanshu Agrawal 043b55b5af user status: Save status on enter keypress.
This is a common UX pattern for forms - a user would expect the
input to be submitted on hitting enter.

So, create a 'keypress' event listener on the input field for the
new status, which calls 'submit_new_status' on enter key press.
2020-03-06 17:13:50 -08:00
Wbert Adrian Castro Vera 40a6602b09 filters: Refactor filter_with_new_topic to expand its functionality.
This intent is that we'll be able to reuse this when editing streams
as well.

* Rename method: filter_with_new_topic to filter_with_new_param.
* Fix tests and method calls.
2020-03-06 17:10:26 -08:00
Tim Abbott 9230213bde settings: Add EMAIL_ADDRESS_VISIBILITY_NOBODY.
This extends our email address visibility settings to deny access to
user email addresses even to organization administrators.

At the moment, they can of course change the setting (which leaves an
audit trail), but in the future only organization owners will be able
to change that setting.

While we're at this, we rewrite the settings_data.js test to cover all
the cases in a more consistent way.

Fixes #14111.
2020-03-06 16:34:08 -08:00
Siddharth Varshney 2a3038797b portico: Update google play and app store badges.
This updates update the download android and ios app button on
/apps/android and /apps/ios routes respectively to use the official
badges provided by the google and apple.

We also clean up some of the JavaScript implementing the page.

Fixes #14061.
2020-03-06 12:12:02 -08:00
Tim Abbott 56591890b0
org settings: Fix bot owner profile display.
Clicking on the 'Owner' value for a row in the list of bots does
nothing, and causes a blueslip error.

This is because the map object in which we store the users have
integer keys, while we pass the owner id as string.

This is fixed by parsing the owner id to integer before passing it
on.

Fixes #14107.
2020-03-05 11:02:54 -08:00
Anders Kaseorg eee784312d stats: Fix Other calculation.
In commit 2248d4d9a4 (#13883) I
incorrectly migrated a loop.  Fixes #14052.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-03-02 17:45:44 -08:00
Steve Howell d1d0b415f1 i18n: Rename translations.js to i18n.js.
The file populates `windows.i18n`, so now
the file name matches our convention.

Note that the module really just initializes
`i18next` and then does this:

    window.i18n = i18next;

It doesn't really add any functionality to
third party library.
2020-02-29 12:19:51 -08:00
Steve Howell 1abd00eac2 i18n: Remove code to sweep local storage.
Before 2018, we used a feature of i18next where
we would cache translations in local storage
for up to two weeks:

    var cacheOptions = {
        // ...
        prefix: 'i18next:' + page_params.server_generation + ':',
        expirationTime: 2*7*24*60*60*1000,  // 2 weeks
    };

    i18next.init({
        /// ...
        cache: cacheOptions
    }

Because `server_generation` would change each time you
upgraded a server, a frequently upgraded server like
chat.zulip.org would cause its active users to start
to accumulate lots of obsolete key/value pairs in local
storage over the two weeks.

See #4443 for more details.

We eventually reduced the cache life to 2 days.  And then
on top of that, newer versions of the server would start
to clean up after themselves using this commit from
April 2017:

    e3f1d025ae

We then removed the caching option altogether a year
later in May 2018:

    cff40c557b

We kept around the code to remove all the old keys, though.
This was particularly important for users who may have
been hitting servers that did an upgrade to the new
version from some older version that didn't have the
key-fixing code.

But mostly the problem takes care of itself after
either two days or two weeks, even on really out-of-date
servers.

The original problem was most likely to affect server
admins that did a lot of upgrades (and possibly only really
affected chat.zulip.org), so as long as those server
admins continued their patterns, it's highly likely that
they've done several upgrades since May 2018 that would
have cleaned these keys out for good.

And, again, even if there is some strange straggler here,
they probably only have one set of keys that will expire
either two days or two weeks after an upgrade, depending
on how long ago the prior upgrade was.  (All of their
keys based on older versions of `server_generation` would
have long since expired.)

Finally, any upgrade certainly won't make the problem
worse for any users under this hypothetical situation,
since the new server won't be writing new keys.

So I am removing the cleanup code.
2020-02-29 12:19:51 -08:00
Steve Howell 979dcfe85b refactor: Extract settings_data.py.
This extracts a new module with three
functions, which we will test with 100%
line coverage:

    - show_email
    - email_for_user_settings
    - get_time_preferences

The first two break several dependencies
in the codebase on `settings_org.js`.  The
`get_time_preferences` breaks an annoying
dependency on `page_params` within people.

The module is pretty cohesive, in terms that
all three functions are just light wrappers
around `page_params` and/or `settings_config`.

Now all the modules that want to call show_email()
only have to require `settings_data`, instead of
having a dependency on the much heavier
`settings_org.js` module.

I also make some of the unit tests here be more
full-stack, where instead of stubbing show_email,
I basically just toggle `page_params.is_admin`.
2020-02-28 17:11:24 -08:00
Akash Nimare 97947bc381 desktop: Update desktop app to v4.0.3. 2020-02-28 12:04:18 -08:00
Tim Abbott d79a7a8c35 panels: Show a banner for users with legacy desktop apps.
Users who are using ZulipDesktop or haven't managed to auto-update to
ZulipElectron should be strongly encouraged to upgrade.

We'll likely want to move to something even stricter that blocks
loading the app at all, but this is a good start.
2020-02-28 01:54:46 -08:00
Tim Abbott 82fa72f08a emoji_picker: Improve logging for invalid emoji names.
This should help us properly investigate a bug likely involving users
clicking on emoji reactions whose name->codepoint mapping has changed.
2020-02-27 17:41:45 -08:00
Tim Abbott 9810327aad channel: Ignore error responses when reloading too. 2020-02-27 17:41:45 -08:00
Tim Abbott 9b8240c436 server_events: Only rerender stream settings if open.
This follows the convention of other code calling into
add_sub_to_table of checking whether the stream settings overlay is
open (and thus in the DOM) before trying to rerender it.
2020-02-27 17:41:44 -08:00
Tim Abbott 8779fad281 popovers: Fix missing string-to-integer conversion.
Found looking at browser exceptions.
2020-02-27 17:40:40 -08:00
Anders Kaseorg 71dd495214 js: Convert _.pluck(a, "key") to item => item.key.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-27 17:20:34 -08:00
Steve Howell 8804c63f5d feature_flags: Remove clicking_notification_causes_narrow.
This is another one that's been set to true
since 2013.
2020-02-27 11:19:13 -08:00
Steve Howell 12ae53f11a feature_flags: Remove propagate_topic_edits.
This flag has been set to true since 2013.
2020-02-27 11:19:13 -08:00
Anders Kaseorg 7e5c82291f hashchange: Update state.old_hash before returning early.
This fixes a bug where you can’t open the same overlay twice in a row
in IE 11, which doesn’t support HashChangeEvent.oldURL; it was exposed
by commit 05be16e051 (late 2018).

While here, parse the hash from oldURL in a less ad-hoc way.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-27 11:14:02 -08:00
Steve Howell 1f156230b0 refactor: Clean up alert_words API.
We add these two functions to the API,
so that we no longer have `alert_words_ui`
using private data from `alert_word`:

    alert_words.has_alert_word()
    alert_words.get_word_list()

And to initialize the data, we have a proper
`initialize` method that is passed in only
the parameters that it needs from `ui_init`.

(We also move the step of deleting `alert_words`
from `page_params` to the `ui_init` module.)

Because it's a bit less cumbersome to initialize
`alert_words`, we now just it directly in the
node tests for `alert_words_ui`.
2020-02-27 11:10:13 -08:00
Steve Howell c32b4d098f ui_init: Pass params to pm_conversations.recent.
This is follow up to da79fd206a

I accidentally skipped over pm_conversations.  Same
ideas as the bigger previous commit--we pass in params
to the initialize function and do the delete cleanup
within ui_init.
2020-02-27 11:10:13 -08:00
Anders Kaseorg 56c03e1311 unread: Convert ids.push(...a) to a loop.
Calling a function with hundreds of thousands to millions of
arguments, depending on the browser, can throw a RangeError.  This was
true of both ids.push(...a) and the [].concat.apply construction that
it replaced in commit 59d55d1e06,
although the old one was less likely to overflow due to bucketing.
Use a loop instead.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-27 11:06:49 -08:00
Steve Howell da79fd206a ui_init: Handle page_params more cleanly.
This cleans up the handoff of page_params
data between ui_init and modules that
take over ownership of page_params-derived
data.

Read the long comment in ui_init for a bit
more context.

Most of this diff is actually test cleanup.
And a lot of the diff to "real" code is
just glorified `s/page_params/params/`
in the `initialize` functions.

One little oddity is that we don't actually
surrender ownership of `page_params.user_id`
to `people.js`.  We could plausibly sweep
the rest of the codebase to just use
`people.my_user_id()` consistently, but it's
not a super high priority thing to fix,
since the value never changes.

The stream_data situation is a bit messy,
since we consume `page_params` data in the
initialize() function in addition to the
`params` data we "own".  I added a comment
there and intend to follow up.  I tried
to mostly avoid the "word soup" by extracting
three locals at the top.

Finally, I don't touch `alert_words` yet,
despite it also doing the delete-page-params-data
dance.  The problem is that `alert_words`
doesn't have a proper `initialize()`.  We
should clean that up and have it use a
`Map` internally, too.
2020-02-26 13:14:09 -08:00
Anders Kaseorg 5ba593f124 int_dict: Replace with Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 15:37:37 -08:00
Anders Kaseorg 2868b7c3e3 dict: Replace with Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 15:37:37 -08:00
Anders Kaseorg 7cc16757aa int_dict: Remove filter_values method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 15:35:42 -08:00
Anders Kaseorg 1cdab5ae61 emoji: Resolve emoji sprite sheets and stylesheets through Webpack.
This gives them cache-compatible URLs, and also avoids some extra
copies of the sprite sheet images.

Comments on the Octopus emoji added by tabbott.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:43:46 -08:00
Anders Kaseorg 4baedcf0b7 js: Convert _.omit to delete.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:26:06 -08:00
Anders Kaseorg 1087fbebfe js: Convert _.clone(a) to { ...a } or a.slice().
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:26:06 -08:00
Anders Kaseorg c9dbd13189 js: Convert _.has to Object.prototype.hasOwnProperty.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:09:39 -08:00
Anders Kaseorg fe082248cc js: Convert _.defaults to spread syntax.
This is not always a behavior-preserving translation: _.defaults
mutates its first argument.  However, the code does not always appear
to have been written to expect that.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:09:39 -08:00
Anders Kaseorg dbffb2a614 js: Convert _.extend to spread syntax or Object.assign.
This is not always a behavior-preserving translation: _.extend mutates
its first argument.  However, the code does not always appear to have
been written to expect that.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:09:39 -08:00
Anders Kaseorg 6f32ef749f js: Convert $.extend to spread syntax.
This is not always a behavior-preserving translation: $.extend mutates
its first argument.  However, the code does not always appear to have
been written to expect that.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:09:39 -08:00
Anders Kaseorg 1cd1b5d198 settings_org: Convert time_limit_dropdown_values from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:09:39 -08:00
Anders Kaseorg b474fa0e37 webpack: Generalize debug-require-webpack-plugin interface.
Now the caller simply imports the debug ‘require’ function as a
module, deciding for itself how to expose it and with what name (in
our case, we expose it as ‘require’ with expose-loader).  Also, remove
a stray console.log.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-25 14:01:06 -08:00
Tim Abbott 324b5052c6 stream_edit: Fix error handling for unchanged stream name.
We were incorrectly passing a string version of an integer ID,
e.g. "10", to a function expecting an integer, e.g. 10.  Fix this by
using the common get_stream_id function intended for the purpose
rather than hand-written parsing.

This was likely broken in the recent Dict -> IntDict/Map migrations.
2020-02-24 23:49:07 -08:00
Pragati Agrawal f68e91e6e1 settings_account: Fix real-time sync of text on the "Full name" button.
The issue was the wrong selector.

Fixes: #13820.
2020-02-24 17:30:05 -08:00
Steve Howell 531cafb501 rows.js: Add error handling to rows.id().
We get random blueslip errors from code that
calls rows.id(), and the error messages are
rarely helpful.
2020-02-24 12:19:10 -08:00
Steve Howell 184f51ee0c message view: Remove `id_of_last_message_sent_by_us`.
We were computing id_of_last_message_sent_by_us
for a valid reason before
fa44d2ea69
was committed in December 2017 to remove the
autoscroll_forever setting.

Since then the only thing that the
conditional for `id_of_last_message_sent_by_us`
short-circuits is a buggy computation of
`id_of_last_message_sent_by_us` itself.

Removing this dead code obviously makes the code
more clear, plus it does save some needless and
possibly bug-prone computation.

In particular, I am trying to lock down `rows.id` to
be more strict about receiving bogus elements, and
removing this code will help with that.
2020-02-24 12:19:10 -08:00
Steve Howell 99eb75e558 minor: Remove awesome comment about C++ iterators.
See cff1714209
from 2013. :)
2020-02-24 12:19:10 -08:00
Steve Howell 16fccd77b7 minor: Fix blueslip error to use zid.
There is no point calling rows.id twice
here.
2020-02-24 12:19:10 -08:00
Steve Howell 8abff20ce8 settings: Move time limit properties.
We have to extract a local `config` due to line
length restrictions.  (Or do something else ugly.)
2020-02-24 11:59:05 -08:00
Steve Howell 720e9728db settings_config: Move private_message_policy_values. 2020-02-24 11:53:33 -08:00
Steve Howell 3dd9638f01 settings_config: Move user_group_edit_policy_values. 2020-02-24 11:53:33 -08:00
Steve Howell b4304721a8 settings_config: Move *_stream_policy_values. 2020-02-24 11:53:33 -08:00
Steve Howell 591d8b6105 settings_config: Move email_address_visibility_values. 2020-02-24 11:53:33 -08:00
Tim Abbott af188205cb echo: Add a block comment explaining found_newest=False case.
This is just clarifing some details for postering from the previous
commit.
2020-02-24 11:50:50 -08:00
Steve Howell 6dba3f2420 local echo: Avoid echo until "newest" are found.
We now no longer do local echo if a user has logged in or visited a
narrow so recently that we are still fetching new messages for them in
their current message list.

Since we want any message list we're displaying to show only
contiguous sequences of messages within that view, it's not correct to
append messages that were just sent at the end unless
fetch_status.has_found_newest shows that we are up to date with the
latest messages from the server.

While we have some logic aimed at correcting our-of-order message IDs
in Zulip, even a brief (few seconds) temporary display of that is a
bug that we should avoid.

This means that we should disable local echo when the user's current
narrow is not up to date.  We can be sure that we'll get the message
the user sent from the server either during the catch-up process or
when we receive it back from th server via the events system.

That particular race window can be several seconds in situations where
somebody is in a narrow where their pointer (or equivalent) is far
behind the latest messages.

This commit only fixes the local echo race condition.  There's a
related bug where new messages sent by (potentially other) users
delivered to the client via server_events might race with our fetching
until we get the latest messages in a given narrow, which we'll need
to deal with separately.

See https://github.com/zulip/zulip/issues/8989 for more details.  It's
possible that we'll close the issue after this fix, since any
additional fixes would add a lot of complexity, and I'm not sure how
much of a problem this will really be in practice after this fix.

Note that we don't have great automated testing for
`try_deliver_locally` (or really `echo.js` in general).  For
`try_deliver_locally` the node tests would probably be 8x more complex
than the code itself, since that function is basically "glue" code
touching several external dependencies.  It's also kind of hard to
screw up this code without getting pretty obvious failures early in
the QA process.

Fixes #8989.
2020-02-24 11:45:00 -08:00
Steve Howell ea14dff7de tictactoe: Fix type confusion.
With the new Map, we want to make sure we
convert the square number into an int.

The symptom here was you'd click on the
square, and the data would get passed
around via the event system, but when
we went to draw the board, the idx value
was a string.
2020-02-21 20:01:21 -05:00
Steve Howell 5e8279c2fb refactor: Extract settings_config.
This moves some code from settings_display.js
into the new module settings_config.js.

Extracting this module breaks some dependencies
on settings_display.js (which has some annoying
transitive dependencies, including jQuery).

In particular this isolates stream_data from
from settings_display.js.

Two of the three structures that we moved here
weren't even directly used by settings_display.js,
since we do a lot of rendering in the modules
admin.js and setting.js.

We make get_all_display_settings() a function
to avoid a require-time dependency on page_params.

Breaking the dependencies simplifies a few
node tests.

Most of the node test complexity came from the
following commit in March 2019:

5a130097bf

The commit itself seems harmless enough, but
dependencies can have a somewhat "viral" nature,
where making stream_data depend on settings_display
caused us to modify four different node tests.
2020-02-21 12:06:31 -08:00
shubhamgupta2956 a05f633fc1 util: Replace util.set_message_topic().
Replace `util.set_message_topic(message, topic)` with `message.topic =
topic`.

Fixes #13931
2020-02-21 09:53:45 -05: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 b55d2bc256 markdown: Add helper configuration for mobile.
This refactoring is the first step toward sharing
our markdown code with mobile.  This focuses on
the Zulip layer, not the underlying third party `marked`
library.

In this commit we do a one-time initialization to
wire up the markdown functions, but after further
discussions with Greg, it might make more sense
to just pass in helpers on every use of markdown
(which is generally only once per sent message).
I'll address that in follow-up commits.

Even though it looks like a pretty invasive change,
you will note that we barely needed to modify the
node tests to make this pass.  And we have pretty
decent test coverage here.

All of the places where we used to depend on
other Zulip modules now use helper functions that
any client (e.g. mobile) can configure themselves.
Or course, in the webapp, we configure these from
modules like people/stream_data/hash_util/etc.

Even in places where markdown used to deal directly with
data structures from other modules, we now use functions.
We may revisit this in a future commit, and we might
just pass data directly for certain things.

I decided to keep the helpers data structure completely flat,
so we don't have ugly nested names like
`helpers.emoji.get_emoji_codepoint`.  Because of this,
some of the names aren't 1:1, which I think is fine.

For example, we map `user_groups.is_member_of` to
`is_member_of_user_group`.

It's likely that mobile already has different names
for their versions of these functions, so trying for
fake consistency would only help the webapp.  In some
cases, I think the webapp functions have names that
could be improved, but we can clean that up in future
commits, and since the names aren't coupled to markdown
itself (i.e. only the config), we will be less
constrained.

It's worth noting that `marked` has an `options`
data structure that it uses for configuration, but
I didn't piggyback onto it, since the `marked`
options are more at the lexing/parsing layer vs.
the app-data layer stuff that our helpers mostly
help with.

Hopefully it's obvious why I just put helpers in
the top-level namespace for the module rather than
passing it around through multiple layers of the
parser.

There were a couple places in markdown where we
were doing awkward `hasOwnProperty` checks for
emoji-related stuff.  Now we use the Python
principle of ask-forgiveness-not-permission and
just handle the getters returning falsy data.  (It
should be `undefined`, but any falsy value is
unworkable in the places I changed, so I use
the simpler, less brittle form.)

We also break our direct dependency on
`emoji_codes.json` (with some help from the
prior commit).

In one place I rename streamName to stream_name,
fixing up an ancient naming violation that goes
way back to before this code was even extracted
away from echo.js.  I didn't bother to split this
out into a separate commit, since 2 of the 4
lines would be immediately re-modified in the
subsequent commit.

Note that we still depend on `fenced_code`
via the global namespace, instead of simply
requiring it directly or injecting it.  The
reason I'm postponing any action there is that
we'll have to change things once we move
markdown into a shared library.  (The most
likely outcome is that we'll rename/move both files
at the same time and fix the namespace/require
details as part of that commit.)

Also the markdown code still relies on `_` being
available in the global namespace.  We aren't
quite ready to share code with mobile yet, but the
underscore dependency should not be problematic,
since mobile already uses underscore to use the
webapp's shared typing_status module.
2020-02-18 16:13:38 -08:00
Steve Howell e8de4abb0e markdown: Clean up userMentionHandler().
This mostly moves logic into people.js.
The people functions added here are glorified
two-liners.

One thing that changes here is that we
are a bit more rigorous about duplicate
names.

The code is slightly awkward, because this
commit preserves the strange behavior
that if 'alice|42' doesn't match on
the user with the name "alice" and user_id
"42", we instead look for a user whose
name is "alice|42".  That seems like a
misfeature to me, but there's a test for
it, so I want to check with Tim that it's not
intentional behavior before I simplify
the code.
2020-02-18 16:04:12 -08:00
Steve Howell be45809253 markdown: Extract emoji helpers.
We add this API to emoji.js, so that markdown
doesn't need to look at internal data structures
(or even need to understand any kind of record
format for results).

Here are the functions:

    get_realm_emoji_url()
    get_emoji_name()
    get_emoji_codepoint()

We use the API now in markdown, which eliminates
the need for the markdown parser to require
the emoji JSON file.

Each function has a simple docstring:

    get_emoji_name('1f384') === 'holiday_tree'
    get_emoji_codepoint('avocado') === '1f951'
    get_realm_emoji_url('shrug') === '/user_avatars/2/emoji/images/31.png'

Also we have simple test coverage for the API
(including tests that verify the docstrings).
2020-02-18 16:04:04 -08:00
Steve Howell f603710cd1 markdown: Pass in page_params.realm_filters to initialize(). 2020-02-18 15:52:34 -08:00
Steve Howell d55510b57d refactor: Rename set_realm_filters().
This name was misleading, because we weren't
actually setting realm_filters (that's what
`page_params.realm_filters = realm_filters`
is for); we were instead updating our
realm filter rules.
2020-02-18 15:52:34 -08:00
Pragati Agrawal 479d07c264 org settings: Convert for…of loop to .some.
This is a minor refactor to make the code cleaner, by replacing manual
looping with the Array.prototype.some() function.
2020-02-18 14:28:19 -08:00
Pragati Agrawal bbc25ab88b org settings: Fix usage of forEach method on jQuery object.
Commit 612b237cec introduced a
regression that broke the “Discard” button, because
get_subsection_property_elements returns a jQuery object rather than
array, and jQuery objects don’t have a forEach method.  Change it to
return an array.

[anders@zulipchat.com: Use Array.from instead of .toArray to avoid the
need for extra mocking.]
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-18 13:40:54 -08:00
Ryan Rehman 0d32defe7b refactor: Inline ajaxSubscribeForCreation.
This is done to simplify the flow of `create_stream`.

Tweaked by tabbott to actually inline the full function.
2020-02-18 11:02:14 -08:00
Steve Howell a3af0e8caa markdown: Remove obsolete dependency on util.js.
We are gonna phase out util.get_message_topic()
in our entire codebase eventually, but we
certainly don't need it here, since the local
echo codepath is using brand new objects that
we construct inside the compose code, and
there's no danger of legacy "subject" data.

My goal for the markdown code is to keep it
free of any accidental dependencies that we
can easily avoid, as I think there's some
possible future where we split out the code
as its own library for people who want to
render Zulip markdown in non-core projects.
2020-02-15 21:18:25 +00:00
Steve Howell cb91b7f312 util: Kill off set_topic_links/get_topic_links.
These functions were just shims that were
used in the somewhat painful migration from
subject_* to topic_*.

The commit 4572be8c27
fixed it so that the client never needs to
deal with "subject_links".

So now we just go back to simpler code:

    message.topic_links = links
    links = message.topic_links
2020-02-15 21:15:48 +00:00
Steve Howell 39405fccdc util: Prepare to remove get_message_topic().
I am not quite ready to declare victory on
the subject/topic migration, but we are super
close.  In this commit I bump a blueslip
warning to a blueslip error, so that we'll
be notified of any codepath that is still
using the janky fall-back-to-subject defensive
code here.

If we go a couple days without any errors, then
we can remove the blueslip warning and the
defensive code immediately and then inline
the callers at our leisure.  I wouldn't be
wildly against keeping these wrappers in some
parts of the code, but that debate is out of
the scope of this immediate fix, and I haven't
thought hard about it yet.

We can basically sweep set_message_topic() now,
if we wanted to, since it's truly just a one-liner.
(At one point it was encapsulating something
like `message.subject = foo`).

This required a tiny change to compose_fade
test setup.
2020-02-15 21:14:00 +00:00
Steve Howell 8deac44a54 markdown: Use early-exit code style for mentions. 2020-02-15 12:30:13 -08:00
Steve Howell 4c5b60d700 markdown: Clean up code for broadcast mentions.
We now handle the all/everyone/stream case at
the top of userMentionHandler.

Previously the code would do strange things
in the case that some user had the name "all"
or "everyone" or "stream".  It would only
affect local echo, and maybe we prevent users
from having those names, so I doubt there
were any real user-facing issues here.

But the new code is clearly more simple and
more correct.
2020-02-15 12:30:13 -08:00
Steve Howell 808c262055 minor: Replace `my_current_user_id` with `===` check. 2020-02-15 12:30:13 -08:00
Steve Howell 5e9df7a0a6 markdown: Move translate_emoticons_to_names().
Most of this logic is specific to markdown
message processing, so we move the code to
markdown.js.

The only responsibility that we leave with
`emoji.js` is to provide us with a list
of translations (regex and replacement text).

But now `markdown.js` actually (directly) executes
those translations against Zulip messages
as part of its preprocessing.

This should simplify the upcoming mobile conversion.
Instead of mobile needing to duplicate this fairly
complex function, they will just need to pass
us in a list similar to `emoji_translations` inside
of `emoji.js`.  That code has a comment that shows
what the data structure looks like.
2020-02-15 12:29:16 -08:00
Steve Howell 6050a5bdd6 markdown: Build the emoticon regexes up front.
There are six emoticon regexes that allow us
make translations such as ":)" to ":slight_smile".

We now build these as soon as we read in the
JSON data, instead of rebuilding them every time
we convert a message to markdown.

It's possible that we should just hardcode this
data:

    [
        { regex: /(\:\))/g, replacement_text: ':slight_smile:' },
        { regex: /(\(\:)/g, replacement_text: ':slight_smile:' },
        { regex: /(\:\/)/g, replacement_text: '😕' },
        { regex: /(<3)/g, replacement_text: '❤️' },
        { regex: /(\:\()/g, replacement_text: ':frown:' },
        { regex: /(\:\|)/g, replacement_text: '😑' }
    ]

OTOH I suppose it's possible that some server
admins will want to modify emoji_codes.json to
have custom emoticons.
2020-02-15 12:26:26 -08:00
Steve Howell c9a52411ae util: Kill off rtrim() helper.
I am 99% sure we can rely on trimRight() and
trim() being available in all browsers that
we support.  I verified in FF.

This removes the util dependency from both
modules touched here.
2020-02-15 12:20:20 -08: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 207a734d46 util: Remove unused escape_html function.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-13 17:50:59 -08:00
Anders Kaseorg e5b70920e5 vdom: Use _.escape for correct HTML escaping.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-13 17:50:59 -08:00
Anders Kaseorg 8e356368f7 markdown: Fix HTML escaping of &.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-13 17:50:59 -08:00
Anders Kaseorg b3caa79f35 ui_report: Fix HTML escaping of &.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-13 17:50:59 -08:00
Vishnu KS 5bab2a3762 upload: Replace jQuery filedrop with Uppy. 2020-02-13 16:43:19 -08:00
Anders Kaseorg 11bec3e6b5 common: Account for string.match returning null.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-13 16:37:52 -08:00
Tim Abbott c2f132b8d5 channel: Don't send outgoing HTTP requests during a reload.
This generalizes existing code for the presence code path that is
generically useful for avoiding useless work that will be discarded.

We make an exception for the one type of request that needs to happen
while reloading, namely the one to clean up our event queue.
2020-02-13 15:45:39 -08:00
Tim Abbott e2892a88c1 channel: Discard all HTTP responses while reloading.
We used to have a block of code doing this just in the presence
endpoint because that's where we'd had error-handling problems with it
not being present, but it seems more correct for it to run
unconditionally on all HTTP requests.

This requires adding a dependency of channel on reload_state, which we
record in the webpack configuration for now.
2020-02-13 15:45:39 -08:00
Tim Abbott e20656e02a activity: Move check_for_unsuspend check to right place.
The actual goal we have is that suspect_offline is correct so that we
can rely on that field when determining how to do error handling in
the presence system.
2020-02-13 15:45:39 -08:00
Tim Abbott 906160f1a3 presence: Re-introduce data filtering when offline.
This should return us to a situation where we won't get blueslip
browser error reporting for users created while a device was offline
just before it reloads.
2020-02-13 15:45:39 -08:00
Tim Abbott 3f76124c6c activity: Ignore presence responses when trying to reload.
This avoids risk of logging blueslip errors for user IDs seen in the
presence response that we haven't heard about from the server_events
system because we're offline and in the process of reloading.

The issue only affected large realms; see
02bc630881 and `git log
-Ssuspect_offline` for details.
2020-02-13 11:47:51 -08:00
Anders Kaseorg a889a830dc lightbox: Convert asset_map from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg b15e72e56a list_render: Remove unused listRenders object.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg c4e08a99d7 list_render: Convert generic_sorting_functions from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 4f39199f6d list_render: Convert sorting_functions from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg e5c577aad4 list_render: Convert instances from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 146f5cd600 util: Convert selected_hash from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 9d27407731 tictactoe_widget: Convert square_values from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 5383f019be subs: Convert hidden_ids from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 055bcfd6e6 subs: Convert widgets from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg fd89f3a695 stream_data: Convert is_included from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 2248d4d9a4 stats: Convert data from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 0e3acb5ce6 settings_account: Convert all_field_template_types from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 7844be6d3a sent_messages: Convert messages from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg bf0a3d9d14 search_suggestion: Convert prev from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg e848bc2a21 search_suggestion: Convert huddle_dict from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 7c6ec51e5d search_suggestions: Convert lookup_table from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg d4434a54e0 integrations_dev_panel: Convert loaded_fixtures from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 9b1f55c020 integrations: Convert CATEGORIES from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 230b701acc integrations: Convert INTEGRATIONS from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 50b54563fe help: Convert html_map from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 0ce06d45a1 message_list_view: Convert message_containers from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 86dd98d481 message_list_view: Convert _rows from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg a6a19c6ace message_list_data: Convert id_set from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 9fa9f37521 message_list_data: Convert msg_ids_to_remove from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg dde035faf3 message_list_data: Convert _local_only from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 2d18424da0 message_list_data: Convert _hash from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg bf32dfcb9f markdown: Convert realm_filter_map from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 0d6d36ae16 local_message: Convert already_used from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg ec1ebc936b gear_menu: Convert scroll_positions from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 02fb1d4dd1 emoji_picker: Convert intermediate complete_emoji_catalog to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 0936381cfd echo: Convert waiting_for_ack from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg c42aca3cfb echo: Convert waiting_for_id from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 278420f908 debug: Convert sections from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 99bcd78273 debug: Convert ids from object to Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 265cca4756 blueslip: Convert reported_errors, last_report_attempt from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 2ddd3d046a echo: Further reduce local_id string vs. number confusion.
New rule: local_id is always a string, local_id_float is always a
number.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg 2834b051d2 js: Read zid with rows.id.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:39:01 -08:00
Anders Kaseorg d7d8632525 pygments_data: Replace JS module with JSON module.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:09:12 -08:00
Anders Kaseorg e257253e64 emoji_codes: Replace JS module with JSON module.
webpack optimizes JSON modules using JSON.parse("{…}"), which is
faster than the normal JavaScript parser.

Update the backend to use emoji_codes.json too instead of the three
separate JSON files.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 10:09:12 -08:00
Anders Kaseorg 72dddb7af6 zjsunit: Use assert in strict mode.
This makes assert.equal and assert.deepEqual compare using === rather
than ==, to catch more bugs.

https://nodejs.org/api/assert.html#assert_strict_mode

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-12 08:16:26 -05:00
Steve Howell 483f1d153d minor: Remove "spread operator" todo comment.
This comment was addressed in
59d55d1e06
2020-02-12 06:10:32 -05: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
Hashir Sarwar 6e14c39468 top_left_corner: Don't export `should_expand_pm_list()`.
We don't need to export `should_expand_pm_list` function
since we are not using it anywhere else.
2020-02-11 14:14:59 -08:00
Anders Kaseorg e66c4ea474 settings_invites: Convert invited_as_values from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Anders Kaseorg ed032817c7 hotspots: Convert HOTSPOT_LOCATIONS from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Anders Kaseorg ee68ef516d js: Convert _.isString to typeof.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Anders Kaseorg a3e5fef663 js: Convert _.isObject to typeof.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Anders Kaseorg 9f07cf6b0e js: Convert _.values to Object.values.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Anders Kaseorg 7ca52f1e80 js: Convert _.keys to Object.keys.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 15:57:20 -08:00
Steve Howell 14396c3e32 presence: Prep for upcoming changes to server data.
In the next commit we're going to change what the
server sends for the following:

    - page_params
    - server responses to /json/users/me/presence

We will **not** yet be changing the format of the data
that we get in events when users update their presence.

It's also just a bit in flux what our final formats
will be for various presence payloads, and different
optimizations may lead us to use different data
structures in different payloads.

So for now we decouple these two things:

    raw_info: this is intended to represent a
        snapshot of the latest data from the
        server, including some data like
        timestamps that are only used
        in downstream calculations and not
        user-facing

    exports.presence_info: this is calculated
        info for modules like buddy_data that
        just need to know active vs. idle and
        last_active_date

Another change that happens here is we rename
set_info_for_user to update_info_for_event,
which just makes it clear that the function
expects data in the "event" format (as opposed
to the format for page_params or server
responses).

As of now keeping the intermediate raw_info data
around feels slightly awkward, because we just
immediately calculate presence_info for any kind
of update.  This may be sorta surprising if you
just skim the code and see the various timeout
constants.  You would think we might be automatically
expiring "active" statuses in the client due to
the simple passage of time, but in fact the precise
places we do this are all triggered by new data
from the server and we re-calculate statuses
immediately.

(There are indirect ways that clients
have timing logic, since they ask the
server for new data at various intervals, but a
smarter client could simply expire users on its
own, or at least with a more efficient transfer
of info between it and the server. One of
the thing that complicates client-side logic
is that server and client clocks may be out
of sync.  Also, it's not inherently super expensive
to get updates from the server.)
2020-02-10 14:37:44 -08:00
Steve Howell 75dbc4a2b1 presence: Extract presence.initialize(). 2020-02-10 14:37:44 -08:00
Anders Kaseorg bafdf5229a js: Convert _.flatten(a, true) to [].concat(...a).
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 62ad436c64 js: Convert _.compact(a) to a.filter(Boolean).
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg d0b0a64af3 js: Convert _.isEmpty(a) to a.length !== 0.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 8abf5da717 js: Convert _.isArray to Array.isArray.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg e1cf5e4630 js: Convert _.reduce to less convoluted code.
reduce is almost never a better solution than the alternatives.  Avoid
it.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 612b237cec js: Convert remaining _.each(a, …) to a.forEach(…).
The _.each calls with an inline function expression have already been
converted to for…of loops.  We could do that here, but using .forEach
when we’re just reusing an existing function seems like a good
guideline.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg b566d11d69 js: Convert _.findIndex(a, …) to a.findIndex(…).
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 336a279005 js: Convert _.find(a, …) to a.find(…).
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 cdd774b790 js: Convert _.all(a, …), _.every(a, …) to a.every(…).
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 70ff164f89 js: Convert _.any(a, …), _.some(a, …) to a.some(…).
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 2285ee922e js: Convert _.contains(a, …) to a.includes(…).
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -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 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 788c5afbcf js: Convert _.indexOf(a, …) to a.indexOf(…).
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 29dbf8ec77 schema: Convert _.find used as loop to for…of.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 13b8bf830f message_viewport: Convert _.every used as loop to for…of.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 4fbee73d1a emoji_picker: Convert _.any used as loop to for…of.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 2f314a0854 js: Convert _.map on jQuery collections to Array.from.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 7b0dea0351 js: Convert jQuery.each to for…of.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 22f3ec44bc blueslip: Use modern spread arguments syntax.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg b5bf677717 submessage: Move submessages === undefined check up.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 4fa1075840 popovers: Check for undefined message.edit_history.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg d671d00cbd settings_profile_fields: Iterate over field_types with Object.values.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Anders Kaseorg 56ab5b4cf4 schema: Iterate over fields with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-10 14:08:12 -08:00
Chris Heald 86faebc2e5 lightbox: Don't blow up for messages not in the message store.
This should somewhat reduce the gravity of the failure mode for cases
where the message the user clicked cannot be found (which would be a
significant bug on its own merit in any case).
2020-02-10 14:00:40 -08:00
Chris Heald c802a1393f lightbox: Cast zid to an int before looking it up in message_store.
The keys for message_store are since the recent Map migration intended
to be integer message IDs, not strings (and likely were always
intended to be integers; the failure mode may simply have shifted).

This may just be a new bug, but this max also fix #9549; certainly
we'll want to redo any investigation with this fix in place.

Fixes #9549.
2020-02-10 13:56:49 -08:00
Steve Howell fa1059aa2e stream_data: Remove stream_name param from add_sub().
We just get the stream_name from the sub struct now.

This mostly affects node tests.

The only place in real code where we called add_sub()
was when we initialized data from the server.
2020-02-09 22:08:50 -08:00
Vishnu KS 4572be8c27 api: Rename subject_links to topic_links.
Fixes #13588
2020-02-07 14:35:22 -08:00
Steve Howell e9c6653852 node tests: Always enforce blueslip warn/error/fatal.
We now require all of our unit tests to handle
blueslip errors for warn/error/fatal.  This
simplifies the zblueslip code to not have any
options passed in.

Most of the places changed here fell into two
categories:

    - We were just missing a random piece of
      setup data in a happy path test.

    - We were testing error handling in just
      a lazy way to ensure 100% coverage.  Often
      these error codepaths were fairly
      contrived.

The one place where we especially lazy was
the stream_data tests, and those are now
more thorough.
2020-02-07 14:15:44 -08:00
Steve Howell 996d054fe9 messages: Send stream_id for stream messages.
This saves a tiny bit of bandwidth, but more
importantly, it protects us against races for
stream name changes.  There's some argument that
if the user is thinking they're sending to
old_stream_name, and unbeknownst to them, the
stream has changed to new_stream_name, then we
should fail.  But I think 99% of the time the
user just wants the message to go that stream
despite any renames.

In order to verify the blueslip error, we
had to turn on error checking, which required
a tiny fix to a place where we left out
a stream_id for add_sub.
2020-02-07 14:15:44 -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 b3f63262af lint: Delegate console.log check to ESLint.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg c48eb3d827 extract_people_from_message: Add missing default case.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg f912572887 settings_profile_fields: Iterate over field_data with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg dd10108c24 user_status: Iterate over page_params.user_status with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 91d3d5d9df settings_org: Iterate over auth_methods with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg a9f5730270 drafts: Iterate over drafts with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 0d05decbe4 presence: Iterate over presence info with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 10edd2d0a1 server_events_dispatch: Iterate over event data with Object.entries.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 8bb515dbd9 emoji: Iterate over emoji_codes data with Object.{entries,values}.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 5de013b11e emoji: Iterate over realm_emoji with Object.values.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-07 14:09:47 -08:00
Anders Kaseorg 07602c4aac message_edit: Convert currently_echoing_messages from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg b8c8ba544d message_edit: Convert currently_editing_messages from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 52a8449a0e widgetize: Convert widget_contents from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 56436188a4 widgetize: Convert widgets from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 88c73602e0 vdom: Convert new_dict, old_dict from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -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
Anders Kaseorg cbe476721c message_store: Convert stored_messages from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 442ff64836 notifications: Convert notice_memory from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 44b3b7cf4a emoji: Convert default_emoji_aliases from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 362ab8838b emoji: Convert active_realm_emojis from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg 419666fc31 emoji: Convert all_realm_emojis from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -08:00
Anders Kaseorg ab93385106 emoji: Convert emojis_by_name from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-06 17:24:43 -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
Steve Howell f0e18b3b3e topic list: Use vdom techniques.
We avoid complicated code to update unread counts
by just using vdom.js.

One small change here is that if click on "more
topics", we replace it with the spinner instead
of putting the spinner after it.  This saves us
a redraw under the new scheme.
2020-02-05 13:04:16 -08:00
Steve Howell 3a533dbe8f vdom: Add replace_content/find parameters.
This will give us a bit more flexibility for
updating DOM when we have widgets that
get appended to other containers.
2020-02-05 13:04:16 -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 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
Steve Howell 437961fba3 presence: Eliminate unused mobile-related code.
We had a plan at some point to use this to display a phone icon or
something for users who would receive push notifications if you
messaged them.  IT's not clear that feature was a good idea in any
case, but it certainly shouldn't be synced as presence data; it would
change >100x less often than the rest of presence and so should likely
be synced differently, maybe as a property on user. So it's best to
delete this prototype.
2020-02-05 11:50:10 -08:00
Anders Kaseorg 91b57be02e dependencies: Upgrade stacktrace-gps from 3.0.3 to 3.0.4.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 22:13:33 -08:00
Anders Kaseorg e88fac499f dependencies: Upgrade emoji-datasource from 4.0.4 to 5.0.1.
The “Smileys & People” category has been split into “Smilys & Emotion”
and “People & Body”.

Also, fix generate_sha1sum_emoji to read the emoji-datasource-google
version from yarn.lock, since package.json only gives a version range.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 21:30:51 -08:00
Rohitt Vashishtha f4b02ce31e compose: Add fences of unused length in quote-and-reply.
When quoting a message with fenced code blocks without a language,
we used to have ambiguity in which '```' fence terminates the quote.

This commit adds explicitly non-interfering fences, which fixes the
above issue as well as makes the raw message easier to quickly read.

Fixes #12446.
2020-02-04 18:17:47 -08:00
Rohitt Vashishtha f5990ccbff compose: Add message info with quote-and-reply.
This adds the original message's sender name along with a
link to narrow to that message when using quote-and-reply.

Fixes #11568.
2020-02-04 18:17:47 -08:00
Ryan Rehman 174b2abcfd settings: Migrate to stream_post_policy structure.
This commit includes a new `stream_post_policy` setting,
by replacing the `is_announcement_only` field from the Stream model,
which is done by mirroring the structure of the existing
`create_stream_policy`.

It includes the necessary schema and database migrations to migrate
the is_announcement_only boolean field to stream_post_policy,
a smallPositiveInteger field similar to many other settings.

This change is done to allow organization administrators to restrict
new members from creating and posting to a stream. However, this does
not affect admins who are new members.

With many tweaks by tabbott to documentation under /help, etc.

Fixes #13616.
2020-02-04 17:08:08 -08:00
Pragati Agrawal b975d693bd stream_edit: Fix realm time sync of notifications setting checkbox.
This fixes the buggy behavior for streams which inherits the notification
setting from UserProfile, and are actively opened in "Streams > Stream
settings", if a user has opened two browser windows, and changes the
notification setting from "Settings > Notifications", then the changes
don't reflect such "Streams > Stream settings" notification setting
checkboxes for such stream.

Partially fixes: #12304.
2020-02-04 13:53:27 -08:00
Pragati Agrawal e79c28e13c stream_edit: Use e.currentTarget instead of e.target.
Here we have attached our handler to `.sub_setting_checkbox` so
`e.currentTarget` will return element with class `.sub_setting_checkbox`
but `e.target` will return exactly which element we have clicked, which
could be a child of `.sub_setting_checkbox`. So instead of,

```
$(e.target).closest(".sub_setting_checkbox")
```

we can use

```
$(e.currentTarget)
```

which is more clean and intuitive.

- `e.currentTarget` is less popular which could be the reason behind using
  two step hack to get the targetted element.
2020-02-04 13:53:27 -08:00
Pragati Agrawal 16abd7ec96 subs: Use single jquery-handlers for multiple events.
Rather than defining two different jquery event-handlers for two different
events, we can use a single jquery handler as the function is the same for
both handlers.
2020-02-04 13:53:27 -08:00
Pragati Agrawal 84fd0b0974 stream_edit: Remove separate click handlers from notifications checkboxes.
Rather than looping on each setting checkbox (except "Mute stream"), we can
attach single click handler to `.sub_setting_checkbox` class.
2020-02-04 13:53:27 -08:00
Tim Abbott ceb0879b0d unread: Add a block comment explaining how it works. 2020-02-04 12:39:58 -08:00
Tim Abbott 02bc630881 presence: Document why we no longer need suspect_offline.
Since it took a lot of effort to debug the original issue that caused
us to introduce suspect_offline, it seems worth writing a comment
explaining why we won't see that issue here.
2020-02-04 12:35:51 -08:00
Steve Howell a672a00677 presence: Add user_id to presence event.
In a later commit, we will eliminate email for
clients who have set slim_presence as their
preference.
2020-02-04 12:30:36 -08:00
Steve Howell 36aee9e69c presence: Remove suspect_offline flag.
We now use user_ids for presence, so we don't need
to worry about races related to unknown emails
being sent to us.  Now we just update the data
structure based on user_id, and
it will be there when we render the presence
widget for that user_id, or else it will
simply be ignored.

It's not clear to me whether we still need
dont_block here, so I didn't touch that code.

Here is the commit that added the suspect_offline
flag, for easy reference:

f207450cdb
2020-02-04 12:30:36 -08:00
Steve Howell bf9144ff69 presence: Add slim_presence flag.
This flag affects page_params and the
payload you get back from POSTs to this
url:

    users/me/presence

The flag does not yet affect the
presence events that get sent to a
client.
2020-02-04 12:30:34 -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 4480963f5a dict: Remove each method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg fac2c71776 dict: Replace items method with @@iterator method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg 9e1343ff8a dict, lazy_set: Return an iterator from values 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 61de2e8192 dict: Remove is_empty method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg 60fac80c8e dict, lazy_set: Replace num_items method with size property.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg da633e953e lazy_set: Convert LazySet to a real class.
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 0e657756f1 dict: Make set method return value consistent with Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:03 -08:00
Anders Kaseorg ab61222dd5 dict: Reimplement Dict using Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:02 -08:00
Anders Kaseorg b16222a38b dict: Remove setdefault method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:02 -08:00
Anders Kaseorg 8872aca907 dict: Remove clone method.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:02 -08:00
Anders Kaseorg 22555f53ad dict: Remove Dict.from_array.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:02 -08:00
Anders Kaseorg 52765796c2 dict: Remove Dict.from.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-04 12:22:02 -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 252910202b poll_widget: Convert votes from object to Map.
Fixes implicity stringification of the user ID keys.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-03 15:59:26 -08:00
Anders Kaseorg 85620df34e poll_widget: Convert key_to_option from object to Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-03 15:59:26 -08:00
Anders Kaseorg 849c7f83a0 blueslip_stacktrace: Handle promises in sourceCache.
Fixes “TypeError: sourceContent.split is not a function” at
blueslip_stacktrace.ts:60 when there’s another error during page load.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-03 15:58:57 -08:00
shubhamgupta2956 aaa30df94c Hotkeys: Change hotkeys behaviour on dropdown open.
Disables message_view_only hotkeys when dropdown menu is opened.

Fixes: #11990
2020-02-03 13:45:07 -08:00
shubhamgupta2956 23c5123a55 hotkeys: Change 'q' and 'w' to message_view_only
Add message_view_only property to 'q' and 'w' hotkeys
2020-02-03 13:40:48 -08:00
Pragati Agrawal 8e733fb513 settings_org: Extract the function to hide or show the element block.
This change leads to some de-duplication of repeated code.
2020-02-03 11:37:40 -08:00
Pragati Agrawal dd6e616c9b settings_org: De-duplicate code to set value of normal dropdowns.
In the future, any property which doesn't have any dependent setting can be
added to `simple_dropdown_properties` list, which automates setting the
value of dropdowns on saving.
2020-02-03 11:37:40 -08:00
Anders Kaseorg e4259d48a5 dict: Assert that Dict is only used with string keys.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg b41968c4a7 topic_list: Replace active_widgets Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg a7bed2c8a3 stream_list: Replace rows Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg b5cd8dcedd starred_messages: Replace ids Dict with Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 1189747d4c settings_streams: Replace row_dict Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 90ebaa86e9 settings_sections: Replace is_loaded Dict with loaded_groups Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 21b13e656d recent_senders: Replace topic_senders and stream_senders with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg c4e1357e19 pm_conversations: Replace partners Dict with Set.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg 052497de1c muting: Replace muted_topics Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -08:00
Anders Kaseorg e10da9c85f condense: Replace _message_content_height_cache Dict with IntDict.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-02-02 20:37:41 -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
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
Tim Abbott df6b90db3c settings: Fix copy-from-clipboard behavior for bot tokens.
We do this by cleaning up the API for generate_zuliprc_content,
allowing us to deduplicate the previously incorrect code.
2020-01-31 15:11:20 -08:00
Tim Abbott 992b15b86c echo: Support senders other than ourself in display_recipient logic.
we don't have a current use case for this feature, but it better
matches what we mean and thus makes the function more readable.
2020-01-31 12:46:19 -08:00
Vishnu KS d7107f47cd echo: Include sender in display_recipient during PM local insert.
Previously the sender was not included in display_recipient when
a private message was locally echoed. This broke the copy conversation
link functionality, if the user try to copy the link immedeatly after
sending the message. This issue is present only during local echo.
This was fixed by including the recipient of the user during
local echo.

Fixes #13547.
2020-01-31 12:45:14 -08:00
Tim Abbott 8ba48d0e4f echo: Add comment explaining zephyr mirroring details. 2020-01-31 12:45:14 -08:00
Tim Abbott 0a6e3b41d3 echo: Simplify return flow in build_display_recipient. 2020-01-31 12:45:14 -08:00
Vishnu Ks dde5d1cd4d echo: Extract emails_to_display_recipient function. 2020-01-31 12:45:14 -08:00
Vishnu KS fbd697ee70 tests: Add test for insert_local_message in echo.js. 2020-01-31 12:45:14 -08:00
Vaibhav Raj Singh 1fa46b1963 compose: Improved warning for wildcard mentions.
Edited the warning to clearly state that most members/most stream members
will be notified on using wildcard mentions, along with the specific
mention (e.g. @ALL, @everyone and @stream).

Did a separate check for all wildcard mentions in util.js and stored the
corresponding mention in wildcard_mention inside compose.js.

Fixes: #13636
2020-01-31 12:24:35 -08:00
Anders Kaseorg 23a5cf41dc fold_dict: Reimplement FoldDict using Map.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-01-31 12:15:55 -08:00
Pragati Agrawal 91a32fecbe settings_org: Use the actual value for private message policy options value.
This change is in series of de-duplication of code in "Other permission"
section for various dropdowns.

Here rather than using "by_anyone" and "disabled" for the `value` attribute
of options, we use actual numeric values. As a result, we don't need to
manually handle to extract the data to be sent to the backend on saving.
2020-01-31 12:42:26 +05:30
Pragati Agrawal 97e24e6e8a settings_org: Use actual value for user group edit policy dropdown options.
This change is in series of de-duplication of code in "Other permission"
section for various dropdowns.

Here rather than using "by_admins_only" and "by_admins_only" for `value`
attribute of options, we use actual numeric values. This helps in
de-duplicating lot of code which is vulnerable to bugs.
2020-01-31 12:42:26 +05:30
Pragati Agrawal ffc8042b59 settings_org: Use actual value for value attribute of invite stream policy.
This change is in series of de-duplication of code in "Other permission"
section for various dropdowns.
2020-01-31 12:42:26 +05:30
Pragati Agrawal 1420922705 settings_org: Use actual value for value attribute of create-stream-policy.
For few settings like `waiting_period_threshold` it makes sense to have the
"value" attribute of option to have a value other than the actual setting
value because multiple settings are depending upon this dropdown, so
handling them in JS code makes more sense. But for many settings (which has
integer values), we have followed a wrong trend over the time of
representing every new dropdown with human-readable values and manually
handling them in JS Code, where it makes more sense to use actual setting
value. The result of which is code has become less concise, sensible and
less likely to be mistaken.
2020-01-31 12:42:26 +05:30
Steve Howell 391e08f629 vdom: Support attribute updates.
We don't really need these yet, but we'll want them if we
carry this over to other widgets.  (The PM list never
changes attributes for its `ul`.)
2020-01-30 13:11:32 -08:00
Steve Howell eeee6edf41 pm_list: Simplify redraws for Private Messages.
We now use vdom-ish techniques to track the
list items for the pm list.  When we go to update
the list, we only re-render nodes whose data
has changed, with two exceptions:

    - Obviously, the first time we do a full render.
    - If the keys for the items have changed (i.e.
      a new node has come in or the order has changed),
      we just re-render the whole list.

If the keys are the same since the last re-render, we
only re-render individual items if their data has
changed.

Most of the new code is in these two modules:

    - pm_list_dom.js
    - vdom.js

We remove all of the code in pm_list.js that is
related to updating DOM with unread counts.

For presence updates, we are now *never*
re-rendering the whole list, since presence
updates only change individual line items and
don't affect the keys.  Instead, we just update
any changed elements in place.

The main thing that makes this all work is the
`update` method in `vdom`, which is totally generic
and essentially does a few simple jobs:

    - detect if keys are different
    - just render the whole ul as needed
    - for items that change, do the appropriate
      jQuery to update the item in place

Note that this code seems to play nice with simplebar.

Also, this code continues to use templates to render
the individual list items.

FWIW this code isn't radically different than list_render,
but it's got some key differences:

    - There are fewer bells and whistles in this code.
      Some of the stuff that list_render does is overkill
      for the PM list.

    - This code detects data changes.

Note that the vdom scheme is agnostic about templates;
it simply requires the child nodes to provide a render
method.  (This is similar to list_render, which is also
technically agnostic about rendering, but which also
does use templates in most cases.)

These fixes are somewhat related to #13605, but we
haven't gotten a solid repro on that issue, and
the scrolling issues there may be orthogonal to the
redraws.  But having fewer moving parts here should
help, and we won't get the rug pulled out from under
us on every presence update.

There are two possible extensions to this that are
somewhat overlapping in nature, but can be done
one a time.

    * We can do a deeper vdom approach here that
      gets us away from templates, and just have
      nodes write to an AST.  I have this on another
      branch, but it might be overkill.

    * We can avoid some redraws by detecting where
      keys are moving up and down.  I'm not completely
      sure we need it for the PM list.

If this gets merged, we may want to try similar
things for the stream list, which also does a fairly
complicated mixture of big-hammer re-renders and
surgical updates-in-place (with custom code).

BTW we have 100% line coverage for vdom.js.
2020-01-30 13:11:32 -08:00
Steve Howell 8c0b0092a9 Extract util.escape_html. 2020-01-30 13:11:32 -08:00
Steve Howell 7cc344e554 topic list: Split out spinner template.
This is another prep step for making topic
list work via vdom.
2020-01-30 12:15:40 -08:00
Steve Howell 1f477da7c8 minor: Move some code higher in function.
This is just a prep step to keep a future
diff a bit cleaner.
2020-01-30 12:15:40 -08:00
Steve Howell a0712ab798 minor: Consolidate vars for max topics.
The two vars here got split apart for temporary
logistical reasons during a recent refactoring.

Now they're just both at the top of
topic_list_data.
2020-01-30 12:15:40 -08:00
Steve Howell ca79648dd7 admin user: Remove obsolete data-email markup.
We mostly needed this for Casper tests, and that
usage was eliminated in the prior commit.

There was also some strange defensive code from
ecc42bc9f8 that
is really ancient and which I am eliminating:

    const email = row.attr("data-email");

    if ($("#deactivation_user_modal .email").html() !== email) {
        blueslip.error("User deactivation canceled due to non-matching fields.");
        ui_report.message(i18n.t("Deactivation encountered an error. Please reload and try again."),
                          $("#home-error"), 'alert-error');
    }

If the code was there to protect against live
updates for email changes, then we no longer
have to worry about that, since we use user_ids
now as keys.

Or it might have to do with some ancient bug
where you could pop open two modals at once
or something.  You can actually change users while
the modal is open (which is kinda strange, but ok),
and it works fine.

When testing this, I ran into the glitch that we
don't open redraw the Deactivated Users panel after
going into the User panel and deactivating a user.
2020-01-29 17:01:19 -08:00
Tim Abbott 7479a9b448 narrow: Use "newest" anchor rather than a huge ID when narrowing.
This causes the Zulip frontend to take advantage of the new
server-side support for passing a string-format anchor that's clear
about what it means.
2020-01-29 12:17:21 -08:00
Tim Abbott b25fea24e7 messages: Simplify API for use_first_unread_anchor.
Now that we have the type situation of having anchor support passing a
string, this is a much more natural way to implement
use_first_unread_anchor.

We still support the old interface to avoid breaking compatibility
with legacy versions of the mobile apps.
2020-01-29 12:17:03 -08:00
Tim Abbott bf2f36e6b4 message_fetch: Fix load_messages_for_narrow anchor parameter.
This makes the code more readable, by just passing the anchor through
without changing its field name back and forth.

There's no reason for this parameter to involve parsing and integer --
it should be a number in all incoming code paths.
2020-01-29 11:24:58 -08:00
Tim Abbott 6b79448e01 hotkey: Rename confusingly named is_editing_stream_name.
The feature is used for editing stream descriptions as well, and in
any case, what's important is that it's a content-editable widget (aka
a form of input box).
2020-01-29 11:24:58 -08:00
Steve Howell c103cf69ff Fix pill-container piece of recent hotkey fix.
This fix recently went on master, although it
hasn't actually been deployed yet (not even to czo),
so user impact should be zero:

0fa67c84d8

The fix mostly improved things, but it broke the
logic for pill containers.  The symptom was that
if you tried to autocomplete "Cordelia" in the
pill box we'd instead invoke the "c" hotkey and
try to compose to a stream.
2020-01-29 07:48:26 -05:00
Tim Abbott 7af6be9aaf subs: Fix reloading the browser to "manage streams" UI.
I'm not sure when this regressed, but the bug is one of those subtle
"8" != 8 issues.

Fixes #13756.
2020-01-28 14:17:29 -08:00
Pragati Agrawal b2c71b7cd8 stream edit: Move realm_setting_disabled in settings context.
Basic intention for this change is just to make code clean and intuitive.
2020-01-28 14:09:07 -08:00
Pragati Agrawal ada37a10f4 stream edit: Move logic for disabled checkboxes from template to js.
In templates we determine checkboxes are disabled by using the following
`if` clause,
```
{{#if (or (and is_muted notification_setting) realm_setting_disabled)}}
disabled="disabled"
{{/if}}
```
and it is more intuitive to do such calculation in javascript code, so we
added an `if_disabled` attribute in `settings` context which replaces
logical operations from `if` statement.

So for non-notification settings, it is
```
is_disabled: check_realm_setting[setting]
```
where check_realm_setting[setting] is same as realm_setting_disabled.

and for notifiaction settings it is,

```
ret.is_disabled = check_realm_setting[setting] || sub.is_muted;
```
2020-01-28 14:09:07 -08:00
Pragati Agrawal b862184d23 stream edit: Move is_checked calculation of stream settings in js.
It is more intuitive to do logical operations in js code instead of
templates and it is also cleaner.
2020-01-28 14:09:07 -08:00
Pragati Agrawal fd09111d8d stream_edit: Minor refactoring of stream_edit.stream_settings function.
The primary reason for this refactor is `.map` is more suitable in this
context instead of `_.each`.
2020-01-28 14:09:07 -08:00
Tim Abbott 0fa67c84d8 hotkey: Optimize processing_text.
Profiles of typing in the Zulip webapp's compose box after opening the
stream creation widget showed that hotkey.processing_text was a
significant expense.  There's no good reason for this -- the function
just needs to inspect the focused element; it just was written with a
sloppy selector.

While there's a secondary issue that, there's no good reason for this
extremely latency-sensitive code path (typing an additional character)
to be doing something extremely inefficient.
2020-01-28 16:47:56 -05:00
Steve Howell 345fcd3a69 mobile sharing: Move sort_emojis into typeahead. 2020-01-28 12:48:02 -08:00
Steve Howell 011d52470c refactor: Move popular_emojis to typeahead library.
I removed a slightly confusing code comment, which I
will address in a follow up commit.  Basically,
"slight smile" still doesn't win over "small airplane"
when you search for "sm", which kind of defeats the
purpose of having popular_emojis for the typeahead
use case.  This is a problem with sort_emojis, though,
so when the comment was next to the list of popular
emojis, it wasn't really actionable.
2020-01-28 12:48:02 -08:00
Steve Howell 16ae53890b refactor: Move util.prefix_sort to typeahead.triage. 2020-01-28 12:48:02 -08:00
Steve Howell d0453dc8f4 performance: Use startsWith in many places.
Using startsWith is faster than indexOf, especially for long strings
and short prefixes.  It's also a lot more readable.  The only reason
we weren't using it was when a lot of the code was originally written,
it wasn't available.
2020-01-28 12:47:37 -08:00
Steve Howell d3e961e179 performance: Improve prefix_sort.
We only convert the query to lowercase outside the
loop for an Nx speedup, where N = number of items.

And then we use startsWith instead of indexOf, which
means we don't senselessly search entire strings
for matches.

(We've had startsWith polyfills for a while now.)

Unfortunately, unless a string start with the
exact casing of the query, we still create an
entire lowercase copy of the string for the case
insensitive match.  For the English use case
(and many other languages), we could further
optimize this by slicing the string before
converting it to lowercase.

Unfortunately, you have languages like German
with the straße/STRASSE problem.  It's not clear
to me how we handle them with the current code,
but I don't want to break that yet.
2020-01-28 13:49:03 +00:00
Steve Howell 10e75e6df5 refactor: Clean up prefix_sort get_item usage.
We use the nice es6 syntax to create the get_item
helpers (in the callers and for the default
value in the function).

Also we use better es6 style for the looping.
2020-01-28 13:07:25 +00:00
Steve Howell 162cb27690 emoji sort: Inline helper function. 2020-01-28 12:04:11 +00:00
Steve Howell 4125eb28fd mobile sharing: Extract shared/js/typeahead.js.
This extracts get_emoji_matcher and all the
functions it depended on, most of which were
in composebox_typeahead.js.

We also move remove_diacritics out of the people
module.

This is the first major step for #13728.
2020-01-27 16:32:11 -08:00