Compare commits

...

143 Commits

Author SHA1 Message Date
Kanishk Kakar
7338f802e1 docs: Add release notes for v3.1.0-beta. 2019-07-22 20:09:04 +05:30
Akash Nimare
6860f6d836 release: New release v3.1.0-beta. 2019-07-19 00:37:12 +05:30
Kanishk Kakar
088ddf9c62 dev: Use .env file for Sentry DSN.
Reads .env file in root folder of repo to get Sentry DSN for builds.
2019-07-19 00:23:10 +05:30
Priyank Patel
95da6c0d58 dependencies: Remove @types/node.
Electron already depends on the @types/node and extends
it in electron.d.ts.
2019-07-17 00:22:17 +05:30
Akash Nimare
1a3d3fc5ff system-util: Fix user-agent. 2019-07-17 00:22:17 +05:30
Priyank Patel
535039216b package.json: Add clean-ts-files script. 2019-07-17 00:22:17 +05:30
Priyank Patel
f449db1dc1 package.json: Run tsc before running electron-builder. 2019-07-17 00:22:17 +05:30
vsvipul
73e0e81abd gulp: Add tasks for compile and run from src. 2019-07-17 00:22:17 +05:30
Priyank Patel
dd4f3047c3 tools: Add tools for running typescript compiler and electron app.
This tool handles edge cases where all the typescript files might not
be compiled when the electron process starts this defer that; it runs
tsc compiler first.

Next, we want to only run the compiler if the files are not
compiled.
2019-07-17 00:22:17 +05:30
vsvipul
e4ef0e195a typescript: Do final cleanup of issues.
Using `import * as` import syntax causes some problem if the
module exports a class or function. Because the whole point of
star import is to import every property the module exports. It turns
out we have been using it incorrectly in many places which this commit
fixes.

Then we fix a linting error by adding a eslint disable rule to solve
it along with a TODO because the way we currently do it is wrong.

Finally, to conclude this cleanup, we merge all the .gitignore paths
into once now that we can.
2019-07-17 00:22:17 +05:30
Priyank Patel
00a925e39e typscript: Fix electron-debug not found error in app.
The import in question is electron-is-dev one, others we are
just fixing while we are at it. The problem with this way of importing
`import * as` is that the isDev would be { default: true | false } not
true | false as we like it to be. This causes and error in production app
because electron-debug isn't installed.

Next, we fix the electron-connect import in main.js.
2019-07-17 00:22:17 +05:30
Priyank Patel
c34b4f9151 tsconfig: Remove declare module * declaration and normalize imports.
The change in this commits are pretty involved but cannot be split
into small commits. The main changes in this commits are:
    * Remove declare module * now that we don't need it
    * Normalize import paths so typescript is happy

Previously, we were using wrong import paths and so typescript couldn't
really provide full types information for imports. The wrong paths isn't
a bug because it was done to make sure it work when it was imported via a
script tag; we fix this by using require inside the script tag in main.html.

Also, did audit to make sure we correctly use __dirname not that it's
value will be diffrent, it won't be js/ but will be respective to the file
path of the module.
2019-07-17 00:22:17 +05:30
Priyank Patel
8a13f7914c typescript: Fix incorrect types for feedback.ts.
Not that the previous types were incorrect but they were wrong.
SendFeedback extends the HTMLElement and is a class so it has it's
own properties so extended the properties accordingly.
2019-07-17 00:22:17 +05:30
vsvipul
b13c86e2db typescript: Migrate main.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
4fb4773a2b typescript: Migrate tray.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
deda98b9d4 typescript: Migrate preload.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
f98457a0cb typescript: Add typings for window and page_params. 2019-07-17 00:22:17 +05:30
vsvipul
3436fb3e68 domain-util: Change object to any in domain-util. 2019-07-17 00:22:17 +05:30
vsvipul
448822a5fb typescript: Migrate messages.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
6e07945d7c typescript: Migrate spellchecker.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
54a8e33b01 typescript: Migrate feedback.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
93c22ca89d gitignore: Add js and resources dir to gitignore. 2019-07-17 00:22:17 +05:30
vsvipul
a2fca89551 typescript: Migrate electron-bridge.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
1516452a8c tsconfig: Turn off noUnusedParamaters rule.
We want to turn off this rule because this requires us to add _
in front of parameter that are unused which we have lot of, for example,
the ipc listeners.
2019-07-17 00:22:17 +05:30
vsvipul
700e73105e typescript: Migrate network.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
c41bbf9dfd typescript: Migrate shortcuts-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
347de5981a typescript: Migrate servers-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
d932a2b2c4 typescript: Migrate server-info-form.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
34e403d0d2 typescript: Migrate preference.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
77c5b8af30 typescript: Migrate new-server-form.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
b2bc268c09 typescript: Migrate network-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
8c52b563bf typescript: Migrate nav.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
a8109c5106 typescript: Migrate general-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
76818b7def typescript: Migrate find-accounts.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
a5ea3d475f typescript: Migrate connected-org-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
2f9205b0c4 typescript: Migrate base-section.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
3f00beb291 typescript: Migrate badge-settings.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
72f356de9c typescript: Migrate add-certificate.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
482264d878 gitignore: Add pages/ dir to gitignore. 2019-07-17 00:22:17 +05:30
Priyank Patel
d7725c121c typescript: Migrate default-notification to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
2b19cdecf2 typescript: Migrate index.js to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
1182af23e4 typescript: Migrate darwin-notification to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
6192801083 typescript: Migrate helper.js to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
63a913487c .gitignore: Ignore typescript compiled files in notifications directory. 2019-07-17 00:22:17 +05:30
vsvipul
77899f9f48 typescript: Migrate webview.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
2b1e594286 tabs: Fix constructors in webview tabs.
template() property used earlier in tab.ts was a
property of its child classes, which causes problems
in compiler, which this PR fixes.
2019-07-17 00:22:17 +05:30
vsvipul
312dc1daaf typescript: Migrate functional-tab.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
744d056e26 typescript: Migrate server-tab.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
433f11ebd1 typescript: Migrate tab.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
506982b4c6 typescript: Migrate handle-external-link.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
4adda8b8ae typescript: Migrate base.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
fbef3e4d7b utils: Change export statement in domain util. 2019-07-17 00:22:17 +05:30
vsvipul
f076343068 gitignore: Ignore typescript compiled file in js/components. 2019-07-17 00:22:17 +05:30
Priyank Patel
d5c9e638ca typescript: Migrate preventdrag to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
d5a343d549 typescript: Add needed type annotations after rebasing to master. 2019-07-17 00:22:17 +05:30
Priyank Patel
4412f60435 typescript: Add types to node-json-db variables.
This adds JsonDB type to db variables we use, which were
previously any due to issue with node-json-db not specifying
the types field in package.json.
2019-07-17 00:22:17 +05:30
Priyank Patel
cec2b3136d dependencies: Upgrade node-json-db to v0.9.2.
This version was released just for the fact that the
bundles typescript declaration file was not defined
in package.json hence typescript couldn't detect it.
2019-07-17 00:22:17 +05:30
Priyank Patel
9ba2e0ad1e .editconfig: Set the indent_size to 4.
This will make GitHub show 4 spaces for a tab instead of 8; makes
PR diffs more readable.
2019-07-17 00:22:17 +05:30
vsvipul
eb30f48a82 typescript: Migrate index.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
edc5b92ab4 typescript: Migrate linuxupdater to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
29753b1a46 typescript: Migrate autoupdater to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
f490efb2df .gitignore: Ignore .js files in app dir. 2019-07-17 00:22:17 +05:30
vsvipul
bb7426a789 utils: Change export statement in linux-update-util. 2019-07-17 00:22:17 +05:30
vsvipul
e7edfffa89 config: Linting changes to package.json and tsconfig.json 2019-07-17 00:22:17 +05:30
Priyank Patel
fb700350f9 typescript: Fix some issues with recent changes.
In domain-util, we were using `import * as ` syntax which
compiled down to `__importStar(require('...'))` which were
not giving the same result as before and causing errors. This
fixes that.

In logger-util, we were missing the call to .apply function
so it should have been `this._log.apply(...)`, but then when we
use apply typescript still complains about merging string with any[]
so we decided to go with bind.
2019-07-17 00:22:17 +05:30
Priyank Patel
79d0688bcd .gitignore: Ignore typescript compiled files. 2019-07-17 00:22:17 +05:30
Priyank Patel
c6c36b698d typescript: Migrate domain-util to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
8ef39553b8 typescript: Migrate linux-update-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
7374fcbe78 typescript: Migrate config-util to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
aa2c55538f typescript: Migrate params-util.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
4d679acb0c typescript: Migrate logger-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
795b9fdc17 xo: Upgrade xo to v0.24.0.
This version also includes new rule we want to ignore.
2019-07-17 00:22:17 +05:30
Priyank Patel
82d9f795c2 xo: Disable some of the typescript-eslint rule.
One rule requires use to move all the functions which is
unnessacary churn.
2019-07-17 00:22:17 +05:30
vsvipul
ec91d46f7b typescript: Migrate menu.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
728418742d typescript: Migrate proxy-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
8b0e9b55fb typescript: Migrate reconnect-util to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
b40be8d891 xo: Disable lines-between-class-members rule.
Apparently this doesn't work well with typescript files.
For example this will throw this linting error:
class Test {
  a: boolean;
  b: string; // needs a new line before this one to fix this linting error
}
2019-07-17 00:22:17 +05:30
Priyank Patel
e12d69720d typing.d.ts: Add comment for why we use declare module. 2019-07-17 00:22:17 +05:30
vsvipul
8353c4de16 typescript: Migrate dnd-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
8c3a2a80c7 typescript: Migrate link-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
5c4221fc31 typescript: Migrate default-util to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
a57c269935 typescript: Migrate common-util to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
ce81a1b367 typescript: Fix wrong import syntax in request-util.ts.
Using the previous syntax was wrong because the file export
the class For example we would use previous syntax if the class
was export by `module.export = { ProxyUtil }`.
2019-07-17 00:22:17 +05:30
vsvipul
26e97c8746 typescript: Migrate certificate-util to typescript. 2019-07-17 00:22:17 +05:30
Priyank Patel
393a0fc2be request-util: Fix linting error. 2019-07-17 00:22:17 +05:30
vsvipul
b0348d6bca typescript: Migrate system-util.js to typescript.
We use to check for a case where os.platform() == win64
which is not possible so removed the condition.
2019-07-17 00:22:17 +05:30
vsvipul
9c68fcdda8 typescript: Migrate request-util to typescript.
We use newer javascript method for string that linting enforces like
startsWith, includes.
2019-07-17 00:22:17 +05:30
vsvipul
543ead4da3 typescript: Migrate sentry-util.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
b5f8d54aea typescript: Migrate startup.js to typescript. 2019-07-17 00:22:17 +05:30
vsvipul
7b07a20c04 typescript: Setup typescript project.
This adds all the dependencies and tsconfig.json and setup
for working on the typescript migration.
2019-07-17 00:22:17 +05:30
Akash Nimare
6b1a55c7e4 macOS: Support dark mode on macOS.
Fixes: #792.
2019-07-16 21:14:05 +05:30
Akash Nimare
d46bdba8ce asar: Unpack node binding files.
We have noticed that on Windows, Zulip app is creating a temp file at %appdata%/Local/Temp
as <guid>.tmp.node on each run. Adding *.node files to asarUnpack fixes this issue.
More info - https://github.com/brave/browser-laptop/issues/12534

Improves: #789.
2019-07-15 18:45:27 +05:30
Tyler Thrailkill
d3bc765e59 Add missing transitive dependencies.
zulip was using a dependency on fs-extra that was resolving transitively
through electron. This adds the dependency explicitly. This is safer and
allows tools like pnpm to function.
2019-07-02 15:27:46 +05:30
Priyank Patel
613e44ef8d reconnect-util: Gracefully reload current webview. (#783)
Before we were destroying, removing the webview elements when we
need to reload webviews which cause unwanted side-effect for example
drafts not saving because no beforeunload event handler isn't run.

Fixes: #767.
2019-07-01 23:35:50 +05:30
ViPuL
f0e4a3bc53 menu: Disable menu items on non-server pages.
Disables 'Copy Zulip URL' and 'Back' and 'Forward'
when user is on non-server pages, like Settings page.
Also, simplifies the logic for setting enable state
for 'Switch to Next Organization' and 'Switch to
Previous Organization'.
2019-06-29 01:46:14 +05:30
Kanishk Kakar
427c86afaf spellchecker: Improve auto detection of spellchecker language.
*Enabling spellchecker forces app to auto-detect the language the user
is typing in.

*Provide context of the server language when initialising spellchecker.

Fixes: #542.
2019-06-25 22:29:13 +05:30
vsvipul
0e89880cfb proxy-util: Fix syntax error.
Fixes a wrongly-placed bracket.
2019-06-25 21:05:41 +05:30
vsvipul
b1f1b49982 preference: Remove unused defaultId parameter.
defaultId is not a property of OpenDialogOptions.
2019-06-25 21:05:41 +05:30
Priyank Patel
390bf907e5 components: Remove unused isLoading function from Tab. 2019-06-23 00:46:38 +05:30
Akash Nimare
02c8a27567 menu: Open help page of current active server.
* menu: Open help page of the currently active server.

Fixes: #758.
2019-06-21 01:02:48 +05:30
Kanishk Kakar
db4e8e5129 db: Fix JSON db errors on tab switch. 2019-06-20 20:54:30 +05:30
Kanishk Kakar
88b764dcc9 sidebar: Add loading indicator.
* Browser-like loading indicator added to the sidebar.
Shows when the app is loading a page. Inactive once the user starts
navigating on the webpage, and in settings.

* Add tooltip saying "Loading" to indicator.

Fixes #430.
2019-06-15 16:03:50 +05:30
Kanishk Kakar
9fe72c0d21 mennu: Add option to hide menu bar to View menu.
* Add View menu shortcut to hide menu bar
The hide menu bar setting available in General Preferences has been added to the View menu.

* settings: Add method to coordinate menu & settings
Use autoHideMenuBar setting with said method.
2019-06-15 04:29:06 +05:30
Kanishk Kakar
31b00ee6a6 Update server validation logic.
This PR removes .ogg file check (supported only by very old servers). Other enhancements in server validation logic -
* Reject domains with no organizations. 
* Convert validation methods to async await
* Add messages.js for returning error message strings.

Fixes: #596, #573.
2019-06-13 00:26:32 +05:30
ViPuL
ecec7f8b89 docs: Improve development guide.
Minifies the current development guide by
a significant amount. Also, removes system requirements
as no credible source for them. Removes dependency
specific instructions and adds links to instructions
to install them.

Fixes #341.
2019-06-11 22:44:06 +05:30
Kanishk Kakar
139496b716 settings: Add field to find accounts by email.
Takes in an organization URL for taking the user to /accounts/find the page.
2019-06-04 21:29:33 +05:30
Akash Nimare
f6239132c1 electron: Update electron to v3.1.10. 2019-05-30 00:59:01 +05:30
Kanishk Kakar
6451373ff6 changelog: Add release notes for v3.0.0. 2019-05-22 01:20:21 +05:30
Akash Nimare
6f74fea0f3 release: New release v3.0.0. 2019-05-21 02:58:23 +05:30
Akash Nimare
405d938223 Update docs and code to point to new repo url.
This is because we have changed the repo name to zulip-desktop.
2019-05-21 02:33:13 +05:30
ViPuL
c6b7e9a9ee settings: Add option to toggle Error Reporting.
Adds an option to enable or disable sentry error
reporting under Advanced section in General Settings. 
Handles both main and renderer processes.

Also, changes the domain used to resolve proxy
in proxy-util from google.com to example.com.

Fixes #702.
2019-05-15 15:00:22 +05:30
Akash Nimare
b4073ba7ac Update package.json 2019-05-12 03:24:23 +05:30
Akash Nimare
b504f31c26 config: Remove unused icon file. 2019-05-12 03:20:22 +05:30
Akash Nimare
f71660b3f0 builder: Update electron-builder to v20.40.2. 2019-05-12 03:16:38 +05:30
Akash Nimare
5d0516887d windows: Add a config for installer name.
There is a bug with electron-builder where it doesn't name the installer properly. 
Without this config, it always names the installer with spaces in between 
i.e. "Zulip Web Setup.exe".
2019-05-12 03:14:41 +05:30
ViPuL
0dd86f0814 nsis: Allow installing app without admin previliges.
Allow the nsis installer to install the app to
AppData for a single user so that administrator
previliges are not required while installing.

Fixes #720.
2019-05-12 02:46:19 +05:30
Rhythm Sharma
eaecc92055 spellchecker: Use server language for spellchecker for all platforms.
This is an experimental fix for spellchecker. Previously, we were only using this on macOS since on other platforms, the spellcheck-module claimed to auto-detect + switch language on the fly but looks like it's not working as expected.
2019-05-10 03:43:49 +05:30
ViPuL
4f65c36a72 menu: Remove minimize and close from File menu.
Remove duplicate entries of minimize and close from
File menu as they are already present in Window menu.
2019-05-04 14:57:58 +05:30
ViPuL
2380b650c9 focus: Fix focus after clicking back button.
Addresses the issue of the webview not being in focus
after the Back button is clicked. Now, the webview is focused
explicitly by calling focus() on click.
2019-05-03 22:03:03 +05:30
ViPuL
1d713f1df2 logs: Limit the number of lines in log files.
Limits the numbers of lines in log files to 500.

Fixes a part of #727.
2019-05-03 14:57:00 +05:30
ViPuL
7fa9c291cb lint: Implement HTML Linting with htmlhint and fix indent.
* lint: Implement HTML Linting with htmlhint and fix indent.

Implements HTML linting using htmlhint and uses
indentation rules of zulip webapp - 4 spaces.
Creates a separate file .htmlhintrc for the rules, most
of which are defaults. Also, fixes indentation in html
files and adds a missing title in about.html.

* deps: Change versioning of various dependencies to exact versions.

As we prefer to use exact working version
for dependencies, changed the versions to
exact versions.

Fixes #676.
2019-04-24 00:44:01 +05:30
ViPuL
8a40e36a63 lint: Update css lint config to match zulip config.
Updated .stylelintrc to match zulip webapp's
.stylelintrc file. Also, made the required changes
to all CSS files.

Fixes remaining CSS part of #676.
2019-04-21 17:10:26 +05:30
Kanishk Kakar
3456720135 Unify case across menus and settings.
* menu: Convert to title case.

Also, change corresponding shortcuts to title case.

* settings: Convert options to sentence case.
2019-04-18 19:38:01 +05:30
Abhigyan Khaund
43840a5245 webview: Add "role" key to webview property. 2019-04-18 19:35:21 +05:30
ViPuL
d99c29301e lint: Implement CSS linting with stylelint.
* lint: Implement CSS linting with stylelint.
* lint: Format CSS files according to lintconfig.

Adds CSS linting following the rules of zulip webapp.
Some rules have been ommitted because they required
significant changes in code. Also, creates a separate
.stylelintrc for storing css config.

Fixes CSS part of #676.
2019-04-15 16:54:02 +05:30
ViPuL
6e760973ff shortcut: Allow zoom options from numpad.
Numpad keys by default aren't supported by electron
for using in menu accelarators. Uses a workaround to
make zoom options work with Numpad keys.

Fixes: #344.
2019-04-12 17:16:04 +05:30
Rhythm Sharma
88c64e9dd6 docs: improve development guide.
Update development instructions for all the systems.
2019-04-12 17:11:08 +05:30
Rhythm Sharma
e9db11c156 shortcuts-section: Fix tip's place for Windows & Linux. 2019-04-12 17:03:15 +05:30
ViPuL
8e8de212d8 menu: Reorder file menu and add option to Add Organization.
Reorder the File Menu. Also, adds a new option to
add a new organization to the file menu.
2019-04-10 22:03:43 +05:30
Puneeth Chaganti
0e0d7e7c4a webview: Work around buggy focus switching in Electron 3.0.10.
This commit works around a couple of bugs, which seem to be upstream bugs in the
current version of Electron.

First, `webContents.isFocused()` seems to be true even if we just switched to
a tab, and are trying to set it as the focused element. To work around this, we
check if the `webview` element is the same as `document.activeElement`.

Also, as per https://github.com/electron/electron/issues/15718, it looks like
`blur` needs to be called on the currently active element, before switching
focus on another element i.e., calling `focus` on it.

Fixes: #634.
2019-04-05 15:34:39 +05:30
ViPuL
6b98a49245 webview: fix focus after soft reload.
Fixes: #697.
2019-04-04 20:35:31 +05:30
ViPuL
8e5c326d74 context-menu: Add option to copy zulip url.
Added, "copy Zulip URL" in 
* Context menu in left sidebar 
* Application menu item

Fixes: #649.
2019-04-04 00:35:23 +05:30
Rhythm Sharma
862e9e2c8c DND: Fix text for Toggle DND in sidebar on hover. 2019-04-04 00:21:59 +05:30
Akash Nimare
8a0b047d8f snap: Update snap config.
Updating the config as suggested by the snap community here - 
https://forum.snapcraft.io/t/snap-fails-to-load-error-minidump-segmentation-fault/8691/5

Should improve #593.
2019-04-03 16:37:33 +05:30
Akash Nimare
4a833ef603 docs: Fix typo error in issue template. 2019-04-02 16:13:44 +05:30
ViPuL
fefb7247d8 domain-util: add requestOptions to replace request instances.
This simplifies the request instances.

Fixes #603.
2019-04-02 16:11:23 +05:30
ViPuL
54a6903236 sidebar: Fix organization cycling using Ctrl+Tab.
This fixes two issues -
a) While on the first server, Ctrl+Shift+Tab doesn't work. This fixes that and now cycles to the last active webview.
b) Disable org cycling for non-server pages likes settings.

Fixes #691.
2019-04-01 17:34:08 +05:30
Rhythm Sharma
92ef1bd532 settings: Modify reset app data button. 2019-03-23 16:20:34 +05:30
Kanishk Kakar
bf2e04b3bb sidebar: Switch to next server on Ctrl+Tab.
* Adds a new option to the Window menu that allows users to change to the
next organization cyclically. Activated by Ctrl + Tab.
* Switch to the previous server on Ctrl + Shift + Tab.
2019-03-20 22:15:25 +05:30
ViPuL
3e389ea5db requests: Allow insecure requests on user request.
In certain requests like for fetching realm icons, request tries to verify server certificate and fails when the user has chosen to ignore cert warnings and has not uploaded the cert.
In those cases, we should mark that this server verification is ignored and ask request to ignore the cert verification bypassing that parameter.

Fixes #684.
2019-03-18 23:18:06 +05:30
SankalpSh
8edff28daa changelog: Fix grammatical errors. 2019-03-13 14:04:44 +05:30
Kanishk Kakar
ef6abbf49e settings: Default to starting app on login.
Acts on an observation that it is easier to turn off auto-start on login
than it is to turn on.
2019-03-12 20:35:20 +05:30
Ján Hrnko
0f638dd4b5 docs: Fix broken link.
Fix broken link http://jlord.us/essential-electron/ to https://jlord.dev/blog/essential-electron
2019-03-02 23:33:54 +05:30
89 changed files with 7259 additions and 3129 deletions

View File

@@ -2,6 +2,7 @@ root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true

View File

@@ -2,7 +2,7 @@
<!-- Please Include: -->
- **Operating System**:
- [ ] Windows
- [ ] Linux/Ubutnu
- [ ] Linux/Ubuntu
- [ ] macOS
- **Clear steps to reproduce the issue**:
- **Relevant error messages and/or screenshots**:

3
.gitignore vendored
View File

@@ -36,3 +36,6 @@ config.gypi
# tests/package.json
.python-version
# Ignore all the typescript compiled files
app/**/*.js

25
.htmlhintrc Normal file
View File

@@ -0,0 +1,25 @@
{
"tagname-lowercase": true,
"attr-lowercase": true,
"attr-value-double-quotes": true,
"attr-value-not-empty": false,
"attr-no-duplication": true,
"doctype-first": true,
"tag-pair": true,
"empty-tag-not-self-closed": true,
"spec-char-escape": true,
"id-unique": true,
"src-not-empty": true,
"title-require": true,
"alt-require": false,
"doctype-html5": true,
"id-class-value": "dash",
"style-disabled": false,
"inline-style-disabled": false,
"inline-script-disabled": false,
"space-tab-mixed-disabled": "space4",
"id-class-ad-disabled": false,
"href-abs-or-rel": false,
"attr-unsafe-chars": true,
"head-script-disabled": true
}

67
.stylelintrc Normal file
View File

@@ -0,0 +1,67 @@
{
"rules": {
# Stylistic rules for CSS.
"function-comma-space-after": "always",
"function-comma-space-before": "never",
"function-max-empty-lines": 0,
"function-whitespace-after": "always",
"value-keyword-case": "lower",
"value-list-comma-newline-after": "always-multi-line",
"value-list-comma-space-after": "always-single-line",
"value-list-comma-space-before": "never",
"value-list-max-empty-lines": 0,
"unit-case": "lower",
"property-case": "lower",
"color-hex-case": "lower",
"declaration-bang-space-before": "always",
"declaration-colon-newline-after": "always-multi-line",
"declaration-colon-space-after": "always-single-line",
"declaration-colon-space-before": "never",
"declaration-block-semicolon-newline-after": "always",
"declaration-block-semicolon-space-before": "never",
"declaration-block-trailing-semicolon": "always",
"block-closing-brace-empty-line-before": "never",
"block-closing-brace-newline-after": "always",
"block-closing-brace-newline-before": "always",
"block-opening-brace-newline-after": "always",
"block-opening-brace-space-before": "always",
"selector-attribute-brackets-space-inside": "never",
"selector-attribute-operator-space-after": "never",
"selector-attribute-operator-space-before": "never",
"selector-combinator-space-after": "always",
"selector-combinator-space-before": "always",
"selector-descendant-combinator-no-non-space": true,
"selector-pseudo-class-parentheses-space-inside": "never",
"selector-pseudo-element-case": "lower",
"selector-pseudo-element-colon-notation": "double",
"selector-type-case": "lower",
"selector-list-comma-newline-after": "always",
"selector-list-comma-space-before": "never",
"media-feature-colon-space-after": "always",
"media-feature-colon-space-before": "never",
"media-feature-name-case": "lower",
"media-feature-parentheses-space-inside": "never",
"media-feature-range-operator-space-after": "always",
"media-feature-range-operator-space-before": "always",
"media-query-list-comma-newline-after": "always",
"media-query-list-comma-space-before": "never",
"at-rule-name-case": "lower",
"at-rule-name-space-after": "always",
"at-rule-semicolon-newline-after": "always",
"at-rule-semicolon-space-before": "never",
"comment-whitespace-inside": "always",
"indentation": 4,
# Limit language features
"color-no-hex": true,
"color-named": "never",
}
}

View File

@@ -2,20 +2,20 @@
Thanks for taking the time to contribute!
The following is a set of guidelines for contributing to Zulip Electron Desktop Client. These are just guidelines, not rules, so use your best judgement and feel free to propose changes to this document in a pull request.
The following is a set of guidelines for contributing to Zulip's desktop Client. These are just guidelines, not rules, so use your best judgement and feel free to propose changes to this document in a pull request.
## Getting Started
Zulip-Desktop app is built on top of [Electron](http://electron.atom.io/). If you are new to Electron, please head over to [this](http://jlord.us/essential-electron/) great article.
Zulip-Desktop app is built on top of [Electron](http://electron.atom.io/). If you are new to Electron, please head over to [this](https://jlord.dev/blog/essential-electron) great article.
## Community
* The whole Zulip documentation, such as setting up a development environment, setting up with the Zulip webapp project, and testing, can be read [here](https://zulip.readthedocs.io).
* If you have any questions regarding zulip-electron, open an [issue](https://github.com/zulip/zulip-electron/issues/new/) or ask it on [chat.zulip.org](https://chat.zulip.org/#narrow/stream/16-desktop).
* If you have any questions regarding zulip-desktop, open an [issue](https://github.com/zulip/zulip-desktop/issues/new/) or ask it on [chat.zulip.org](https://chat.zulip.org/#narrow/stream/16-desktop).
## Issue
Ensure the bug was not already reported by searching on GitHub under [issues](https://github.com/zulip/zulip-electron/issues). If you're unable to find an open issue addressing the bug, open a [new issue](https://github.com/zulip/zulip-electron/issues/new).
Ensure the bug was not already reported by searching on GitHub under [issues](https://github.com/zulip/zulip-desktop/issues). If you're unable to find an open issue addressing the bug, open a [new issue](https://github.com/zulip/zulip-desktop/issues/new).
The [zulipbot](https://github.com/zulip/zulipbot) helps to claim an issue by commenting the following in the comment section: "**@zulipbot** claim". **@zulipbot** will assign you to the issue and label the issue as **in progress**. For more details, check out [**@zulipbot**](https://github.com/zulip/zulipbot).
@@ -38,7 +38,7 @@ For example:
## Pull Requests
Pull Requests are always welcome.
Pull Requests are always welcome.
1. When you edit the code, please run `npm run test` to check the formatting of your code before you `git commit`.
2. Ensure the PR description clearly describes the problem and solution. It should include:

View File

@@ -1,6 +1,6 @@
# Zulip Desktop Client
[![Build Status](https://travis-ci.org/zulip/zulip-electron.svg?branch=master)](https://travis-ci.org/zulip/zulip-electron)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/zulip/zulip-electron?branch=master&svg=true)](https://ci.appveyor.com/project/akashnimare/zulip-electron/branch/master)
[![Build Status](https://travis-ci.org/zulip/zulip-desktop.svg?branch=master)](https://travis-ci.org/zulip/zulip-desktop)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/zulip/zulip-desktop?branch=master&svg=true)](https://ci.appveyor.com/project/zulip/zulip-desktop/branch/master)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
[![project chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://chat.zulip.org)
@@ -20,7 +20,7 @@ Please see the [installation guide](https://zulipchat.com/help/desktop-app-insta
# Contribute
First, join us on the [Zulip community server](https://zulip.readthedocs.io/en/latest/contributing/chat-zulip-org.html)!
First, join us on the [Zulip community server](https://zulip.readthedocs.io/en/latest/contributing/chat-zulip-org.html)!
Also see our [contribution guidelines](./CONTRIBUTING.md) and our [development guide](./development.md).
# License

View File

@@ -1,18 +1,19 @@
'use strict';
const { app, dialog, shell } = require('electron');
const { autoUpdater } = require('electron-updater');
const isDev = require('electron-is-dev');
import { app, dialog, shell } from 'electron';
import { autoUpdater } from 'electron-updater';
import { linuxUpdateNotification } from './linuxupdater'; // Required only in case of linux
const ConfigUtil = require('./../renderer/js/utils/config-util.js');
import log = require('electron-log');
import isDev = require('electron-is-dev');
import ConfigUtil = require('../renderer/js/utils/config-util');
function appUpdater(updateFromMenu = false) {
export function appUpdater(updateFromMenu = false): void {
// Don't initiate auto-updates in development
if (isDev) {
return;
}
if (process.platform === 'linux' && !process.env.APPIMAGE) {
const { linuxUpdateNotification } = require('./linuxupdater');
linuxUpdateNotification();
return;
}
@@ -23,8 +24,6 @@ function appUpdater(updateFromMenu = false) {
const LogsDir = `${app.getPath('userData')}/Logs`;
// Log whats happening
const log = require('electron-log');
log.transports.file.file = `${LogsDir}/updates.log`;
log.transports.file.level = 'info';
autoUpdater.logger = log;
@@ -84,7 +83,6 @@ Current Version: ${app.getVersion()}`
});
// Ask the user if update is available
// eslint-disable-next-line no-unused-vars
autoUpdater.on('update-downloaded', event => {
// Ask user to update the app
dialog.showMessageBox({
@@ -106,7 +104,3 @@ Current Version: ${app.getVersion()}`
// Init for updates
autoUpdater.checkForUpdates();
}
module.exports = {
appUpdater
};

View File

@@ -1,21 +1,25 @@
'use strict';
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const windowStateKeeper = require('electron-window-state');
const isDev = require('electron-is-dev');
const appMenu = require('./menu');
const { appUpdater } = require('./autoupdater');
const { setAutoLaunch } = require('./startup');
import { sentryInit } from '../renderer/js/utils/sentry-util';
import { appUpdater } from './autoupdater';
import { setAutoLaunch } from './startup';
import windowStateKeeper = require('electron-window-state');
import path = require('path');
import fs = require('fs');
import isDev = require('electron-is-dev');
import electron = require('electron');
const { app, ipcMain } = electron;
const BadgeSettings = require('./../renderer/js/pages/preference/badge-settings.js');
const ConfigUtil = require('./../renderer/js/utils/config-util.js');
const ProxyUtil = require('./../renderer/js/utils/proxy-util.js');
const { sentryInit } = require('./../renderer/js/utils/sentry-util.js');
import AppMenu = require('./menu');
import BadgeSettings = require('../renderer/js/pages/preference/badge-settings');
import ConfigUtil = require('../renderer/js/utils/config-util');
import ProxyUtil = require('../renderer/js/utils/proxy-util');
interface PatchedGlobal extends NodeJS.Global {
mainWindowState: windowStateKeeper.State;
}
const globalPatched = global as PatchedGlobal;
// Adds debug features like hotkeys for triggering dev tools and reload
// in development mode
@@ -24,8 +28,8 @@ if (isDev) {
}
// Prevent window being garbage collected
let mainWindow;
let badgeCount;
let mainWindow: Electron.BrowserWindow;
let badgeCount: number;
let isQuitting = false;
@@ -49,20 +53,20 @@ if (singleInstanceLock) {
const APP_ICON = path.join(__dirname, '../resources', 'Icon');
const iconPath = () => {
const iconPath = (): string => {
return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
};
function createMainWindow() {
function createMainWindow(): Electron.BrowserWindow {
// Load the previous state with fallback to defaults
const mainWindowState = windowStateKeeper({
const mainWindowState: windowStateKeeper.State = windowStateKeeper({
defaultWidth: 1100,
defaultHeight: 720,
path: `${app.getPath('userData')}/config`
});
// Let's keep the window position global so that we can access it in other process
global.mainWindowState = mainWindowState;
globalPatched.mainWindowState = mainWindowState;
const win = new electron.BrowserWindow({
// This settings needs to be saved in config
@@ -134,7 +138,7 @@ app.disableHardwareAcceleration();
app.commandLine.appendSwitch('force-color-profile', 'srgb');
// eslint-disable-next-line max-params
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
app.on('certificate-error', (event: Event, _webContents: Electron.WebContents, _url: string, _error: string, _certificate: any, callback) => {
event.preventDefault();
callback(true);
});
@@ -146,7 +150,7 @@ app.on('activate', () => {
});
app.on('ready', () => {
appMenu.setMenu({
AppMenu.setMenu({
tabs: []
});
mainWindow = createMainWindow();
@@ -159,7 +163,10 @@ app.on('ready', () => {
}
// Initialize sentry for main process
sentryInit();
const errorReporting = ConfigUtil.getConfigItem('errorReporting');
if (errorReporting) {
sentryInit();
}
const isSystemProxy = ConfigUtil.getConfigItem('useSystemProxy');
@@ -231,7 +238,7 @@ app.on('ready', () => {
});
ipcMain.on('clear-app-settings', () => {
global.mainWindowState.unmanage(mainWindow);
globalPatched.mainWindowState.unmanage();
app.relaunch();
app.exit();
});
@@ -248,48 +255,49 @@ app.on('ready', () => {
BadgeSettings.updateBadge(badgeCount, mainWindow);
});
ipcMain.on('toggle-menubar', (event, showMenubar) => {
ipcMain.on('toggle-menubar', (_event: Electron.IpcMessageEvent, showMenubar: boolean) => {
mainWindow.setAutoHideMenuBar(showMenubar);
mainWindow.setMenuBarVisibility(!showMenubar);
page.send('toggle-autohide-menubar', showMenubar, true);
});
ipcMain.on('update-badge', (event, messageCount) => {
ipcMain.on('update-badge', (_event: Electron.IpcMessageEvent, messageCount: number) => {
badgeCount = messageCount;
BadgeSettings.updateBadge(badgeCount, mainWindow);
page.send('tray', messageCount);
});
ipcMain.on('update-taskbar-icon', (event, data, text) => {
ipcMain.on('update-taskbar-icon', (_event: Electron.IpcMessageEvent, data: any, text: string) => {
BadgeSettings.updateTaskbarIcon(data, text, mainWindow);
});
ipcMain.on('forward-message', (event, listener, ...params) => {
ipcMain.on('forward-message', (_event: Electron.IpcMessageEvent, listener: any, ...params: any[]) => {
page.send(listener, ...params);
});
ipcMain.on('update-menu', (event, props) => {
appMenu.setMenu(props);
ipcMain.on('update-menu', (_event: Electron.IpcMessageEvent, props: any) => {
AppMenu.setMenu(props);
const activeTab = props.tabs[props.activeTabIndex];
if (activeTab) {
mainWindow.setTitle(`Zulip - ${activeTab.webview.props.name}`);
}
});
ipcMain.on('toggleAutoLauncher', (event, AutoLaunchValue) => {
ipcMain.on('toggleAutoLauncher', (_event: Electron.IpcMessageEvent, AutoLaunchValue: boolean) => {
setAutoLaunch(AutoLaunchValue);
});
ipcMain.on('downloadFile', (event, url, downloadPath) => {
ipcMain.on('downloadFile', (_event: Electron.IpcMessageEvent, url: string, downloadPath: string) => {
page.downloadURL(url);
page.session.once('will-download', (event, item) => {
page.session.once('will-download', (_event: Event, item) => {
const filePath = path.join(downloadPath, item.getFilename());
const getTimeStamp = () => {
const getTimeStamp = (): any => {
const date = new Date();
return date.getTime();
};
const formatFile = filePath => {
const formatFile = (filePath: string): string => {
const fileExtension = path.extname(filePath);
const baseName = path.basename(filePath, fileExtension);
return `${baseName}-${getTimeStamp()}${fileExtension}`;
@@ -303,7 +311,7 @@ app.on('ready', () => {
item.setSavePath(setFilePath);
item.on('updated', (event, state) => {
item.on('updated', (_event: Event, state) => {
switch (state) {
case 'interrupted': {
// Can interrupted to due to network error, cancel download then
@@ -323,7 +331,7 @@ app.on('ready', () => {
}
}
});
item.once('done', (event, state) => {
item.once('done', (_event: Event, state) => {
const getFileName = fs.existsSync(filePath) ? formatFile(filePath) : item.getFilename();
if (state === 'completed') {
page.send('downloadFileCompleted', item.getSavePath(), getFileName);
@@ -337,13 +345,23 @@ app.on('ready', () => {
});
});
ipcMain.on('realm-name-changed', (event, serverURL, realmName) => {
ipcMain.on('realm-name-changed', (_event: Electron.IpcMessageEvent, serverURL: string, realmName: string) => {
page.send('update-realm-name', serverURL, realmName);
});
ipcMain.on('realm-icon-changed', (event, serverURL, iconURL) => {
ipcMain.on('realm-icon-changed', (_event: Electron.IpcMessageEvent, serverURL: string, iconURL: string) => {
page.send('update-realm-icon', serverURL, iconURL);
});
// Using event.sender.send instead of page.send here to
// make sure the value of errorReporting is sent only once on load.
ipcMain.on('error-reporting', (event: Electron.IpcMessageEvent) => {
event.sender.send('error-reporting-val', errorReporting);
});
ipcMain.on('save-last-tab', (_event: Electron.IpcMessageEvent, index: number) => {
ConfigUtil.setConfigItem('lastActiveTab', index);
});
});
app.on('before-quit', () => {

View File

@@ -1,20 +1,19 @@
const { app } = require('electron');
const { Notification } = require('electron');
import { app, Notification } from 'electron';
const request = require('request');
const semver = require('semver');
const ConfigUtil = require('../renderer/js/utils/config-util');
const ProxyUtil = require('../renderer/js/utils/proxy-util');
const LinuxUpdateUtil = require('../renderer/js/utils/linux-update-util');
const Logger = require('../renderer/js/utils/logger-util');
import request = require('request');
import semver = require('semver');
import ConfigUtil = require('../renderer/js/utils/config-util');
import ProxyUtil = require('../renderer/js/utils/proxy-util');
import LinuxUpdateUtil = require('../renderer/js/utils/linux-update-util');
import Logger = require('../renderer/js/utils/logger-util');
const logger = new Logger({
file: 'linux-update-util.log',
timestamp: true
});
function linuxUpdateNotification() {
let url = 'https://api.github.com/repos/zulip/zulip-electron/releases';
export function linuxUpdateNotification(): void {
let url = 'https://api.github.com/repos/zulip/zulip-desktop/releases';
url = ConfigUtil.getConfigItem('betaUpdate') ? url : url + '/latest';
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
@@ -25,7 +24,7 @@ function linuxUpdateNotification() {
ecdhCurve: 'auto'
};
request(options, (error, response, body) => {
request(options, (error: any, response: any, body: any) => {
if (error) {
logger.error('Linux update error.');
logger.error(error);
@@ -47,7 +46,3 @@ function linuxUpdateNotification() {
}
});
}
module.exports = {
linuxUpdateNotification
};

View File

@@ -1,15 +1,13 @@
'use strict';
const path = require('path');
import { app, shell, BrowserWindow, Menu, dialog } from 'electron';
import { appUpdater } from './autoupdater';
const { app, shell, BrowserWindow, Menu, dialog } = require('electron');
const fs = require('fs-extra');
const AdmZip = require('adm-zip');
const { appUpdater } = require('./autoupdater');
const ConfigUtil = require(__dirname + '/../renderer/js/utils/config-util.js');
const DNDUtil = require(__dirname + '/../renderer/js/utils/dnd-util.js');
const Logger = require(__dirname + '/../renderer/js/utils/logger-util.js');
import AdmZip = require('adm-zip');
import fs = require('fs-extra');
import path = require('path');
import DNDUtil = require('../renderer/js/utils/dnd-util');
import Logger = require('../renderer/js/utils/logger-util');
import ConfigUtil = require('../renderer/js/utils/config-util');
const appName = app.getName();
@@ -19,11 +17,12 @@ const logger = new Logger({
});
class AppMenu {
getHistorySubmenu() {
getHistorySubmenu(enableMenu: boolean): Electron.MenuItemConstructorOptions[] {
return [{
label: 'Back',
accelerator: process.platform === 'darwin' ? 'Command+Left' : 'Alt+Left',
click(item, focusedWindow) {
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('back');
}
@@ -31,7 +30,8 @@ class AppMenu {
}, {
label: 'Forward',
accelerator: process.platform === 'darwin' ? 'Command+Right' : 'Alt+Right',
click(item, focusedWindow) {
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('forward');
}
@@ -39,58 +39,64 @@ class AppMenu {
}];
}
getToolsSubmenu() {
getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
return [{
label: `Check for Updates`,
label: 'Check for Updates',
click() {
AppMenu.checkForUpdate();
}
},
{
label: `Release Notes`,
label: 'Release Notes',
click() {
shell.openExternal(`https://github.com/zulip/zulip-electron/releases/tag/v${app.getVersion()}`);
shell.openExternal(`https://github.com/zulip/zulip-desktop/releases/tag/v${app.getVersion()}`);
}
}, {
},
{
type: 'separator'
}, {
},
{
label: 'Factory Reset',
accelerator: process.platform === 'darwin' ? 'Command+Shift+D' : 'Ctrl+Shift+D',
click() {
AppMenu.resetAppSettings();
}
}, {
},
{
label: 'Download App Logs',
click() {
const zip = new AdmZip();
let date = new Date();
date = date.toLocaleDateString().replace(/\//g, '-');
const date = new Date();
const dateString = date.toLocaleDateString().replace(/\//g, '-');
// Create a zip file of all the logs and config data
zip.addLocalFolder(`${app.getPath('appData')}/${appName}/Logs`);
zip.addLocalFolder(`${app.getPath('appData')}/${appName}/config`);
// Put the log file in downloads folder
const logFilePath = `${app.getPath('downloads')}/Zulip-logs-${date}.zip`;
const logFilePath = `${app.getPath('downloads')}/Zulip-logs-${dateString}.zip`;
zip.writeZip(logFilePath);
// Open and select the log file
shell.showItemInFolder(logFilePath);
}
}, {
},
{
type: 'separator'
}, {
},
{
label: 'Toggle DevTools for Zulip App',
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
focusedWindow.webContents.toggleDevTools();
}
}
}, {
},
{
label: 'Toggle DevTools for Active Tab',
accelerator: process.platform === 'darwin' ? 'Alt+Command+U' : 'Ctrl+Shift+U',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('tab-devtools');
}
@@ -98,11 +104,11 @@ class AppMenu {
}];
}
getViewSubmenu() {
getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
return [{
label: 'Reload',
accelerator: 'CommandOrControl+R',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('reload-current-viewer');
}
@@ -110,7 +116,7 @@ class AppMenu {
}, {
label: 'Hard Reload',
accelerator: 'CommandOrControl+Shift+R',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('hard-reload');
}
@@ -122,7 +128,7 @@ class AppMenu {
}, {
label: 'Zoom In',
accelerator: process.platform === 'darwin' ? 'Command+Plus' : 'Control+=',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('zoomIn');
}
@@ -130,7 +136,7 @@ class AppMenu {
}, {
label: 'Zoom Out',
accelerator: 'CommandOrControl+-',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('zoomOut');
}
@@ -138,7 +144,7 @@ class AppMenu {
}, {
label: 'Actual Size',
accelerator: 'CommandOrControl+0',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('zoomActualSize');
}
@@ -147,7 +153,7 @@ class AppMenu {
type: 'separator'
}, {
label: 'Toggle Tray Icon',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
focusedWindow.webContents.send('toggletray');
}
@@ -155,17 +161,31 @@ class AppMenu {
}, {
label: 'Toggle Sidebar',
accelerator: 'CommandOrControl+Shift+S',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
const newValue = !ConfigUtil.getConfigItem('showSidebar');
focusedWindow.webContents.send('toggle-sidebar', newValue);
ConfigUtil.setConfigItem('showSidebar', newValue);
}
}
}, {
label: 'Auto hide Menu bar',
checked: ConfigUtil.getConfigItem('autoHideMenubar', false),
visible: process.platform !== 'darwin',
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
const newValue = !ConfigUtil.getConfigItem('autoHideMenubar');
focusedWindow.setAutoHideMenuBar(newValue);
focusedWindow.setMenuBarVisibility(!newValue);
focusedWindow.webContents.send('toggle-autohide-menubar', newValue);
ConfigUtil.setConfigItem('autoHideMenubar', newValue);
}
},
type: 'checkbox'
}];
}
getHelpSubmenu() {
getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
return [
{
label: `${appName + ' Desktop'} v${app.getVersion()}`,
@@ -173,7 +193,7 @@ class AppMenu {
},
{
label: 'About Zulip',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('open-about');
}
@@ -181,10 +201,13 @@ class AppMenu {
},
{
label: `Help Center`,
click() {
shell.openExternal('https://zulipchat.com/help/');
click(focusedWindow) {
if (focusedWindow) {
AppMenu.sendAction('open-help');
}
}
}, {
},
{
label: 'Report an Issue',
click() {
// the goal is to notify the main.html BrowserWindow
@@ -193,11 +216,12 @@ class AppMenu {
window.webContents.send('open-feedback-modal');
});
}
}];
}
];
}
getWindowSubmenu(tabs, activeTabIndex) {
const initialSubmenu = [{
getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boolean): Electron.MenuItemConstructorOptions[] {
const initialSubmenu: any[] = [{
role: 'minimize'
}, {
role: 'close'
@@ -208,38 +232,75 @@ class AppMenu {
initialSubmenu.push({
type: 'separator'
});
for (let i = 0; i < tabs.length; i++) {
tabs.forEach(tab => {
// Do not add functional tab settings to list of windows in menu bar
if (tabs[i].props.role === 'function' && tabs[i].webview.props.name === 'Settings') {
continue;
if (tab.props.role === 'function' && tab.webview.props.name === 'Settings') {
return;
}
initialSubmenu.push({
label: tabs[i].webview.props.name,
accelerator: tabs[i].props.role === 'function' ? '' : `${ShortcutKey} + ${tabs[i].props.index + 1}`,
checked: tabs[i].props.index === activeTabIndex,
click(item, focusedWindow) {
label: tab.webview.props.name,
accelerator: tab.props.role === 'function' ? '' : `${ShortcutKey} + ${tab.props.index + 1}`,
checked: tab.props.index === activeTabIndex,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('switch-server-tab', tabs[i].props.index);
AppMenu.sendAction('switch-server-tab', tab.props.index);
}
},
type: 'checkbox'
});
}
});
initialSubmenu.push({
type: 'separator'
});
initialSubmenu.push({
label: 'Switch to Next Organization',
accelerator: `Ctrl+Tab`,
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('switch-server-tab', AppMenu.getNextServer(tabs, activeTabIndex));
}
}
}, {
label: 'Switch to Previous Organization',
accelerator: `Ctrl+Shift+Tab`,
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('switch-server-tab', AppMenu.getPreviousServer(tabs, activeTabIndex));
}
}
});
}
return initialSubmenu;
}
getDarwinTpl(props) {
getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
const { tabs, activeTabIndex, enableMenu } = props;
return [{
label: `${app.getName()}`,
submenu: [{
label: 'Add Organization',
accelerator: 'Cmd+Shift+N',
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('new-server');
}
}
}, {
label: 'Toggle Do Not Disturb',
accelerator: 'Cmd+Shift+M',
click() {
const dndUtil = DNDUtil.toggle();
AppMenu.sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
}
}, {
label: 'Desktop Settings',
accelerator: 'Cmd+,',
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('open-settings');
}
@@ -248,7 +309,7 @@ class AppMenu {
label: 'Keyboard Shortcuts',
accelerator: 'Cmd+Shift+K',
enabled: enableMenu,
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('shortcut');
}
@@ -256,17 +317,19 @@ class AppMenu {
}, {
type: 'separator'
}, {
label: 'Toggle Do Not Disturb',
accelerator: 'Command+Shift+M',
click() {
const dndUtil = DNDUtil.toggle();
AppMenu.sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
label: 'Copy Zulip URL',
accelerator: 'Cmd+Shift+C',
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('copy-zulip-url');
}
}
}, {
label: 'Log Out',
label: 'Log Out of Organization',
accelerator: 'Cmd+L',
enabled: enableMenu,
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('log-out');
}
@@ -313,10 +376,10 @@ class AppMenu {
submenu: this.getViewSubmenu()
}, {
label: 'History',
submenu: this.getHistorySubmenu()
submenu: this.getHistorySubmenu(enableMenu)
}, {
label: 'Window',
submenu: this.getWindowSubmenu(tabs, activeTabIndex)
submenu: this.getWindowSubmenu(tabs, activeTabIndex, enableMenu)
}, {
label: 'Tools',
submenu: this.getToolsSubmenu()
@@ -326,28 +389,17 @@ class AppMenu {
}];
}
getOtherTpl(props) {
getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
const { tabs, activeTabIndex, enableMenu } = props;
return [{
label: '&File',
submenu: [{
label: 'Desktop Settings',
accelerator: 'Ctrl+,',
click(item, focusedWindow) {
label: 'Add Organization',
accelerator: 'Ctrl+Shift+N',
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('open-settings');
}
}
}, {
type: 'separator'
}, {
label: 'Keyboard Shortcuts',
accelerator: 'Ctrl+Shift+K',
enabled: enableMenu,
click(item, focusedWindow) {
if (focusedWindow) {
AppMenu.sendAction('shortcut');
AppMenu.sendAction('new-server');
}
}
}, {
@@ -360,10 +412,38 @@ class AppMenu {
AppMenu.sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
}
}, {
label: 'Log Out',
label: 'Desktop Settings',
accelerator: 'Ctrl+,',
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('open-settings');
}
}
}, {
label: 'Keyboard Shortcuts',
accelerator: 'Ctrl+Shift+K',
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('shortcut');
}
}
}, {
type: 'separator'
}, {
label: 'Copy Zulip URL',
accelerator: 'Ctrl+Shift+C',
enabled: enableMenu,
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('copy-zulip-url');
}
}
}, {
label: 'Log Out of Organization',
accelerator: 'Ctrl+L',
enabled: enableMenu,
click(item, focusedWindow) {
click(_item: any, focusedWindow: any) {
if (focusedWindow) {
AppMenu.sendAction('log-out');
}
@@ -400,10 +480,10 @@ class AppMenu {
submenu: this.getViewSubmenu()
}, {
label: '&History',
submenu: this.getHistorySubmenu()
submenu: this.getHistorySubmenu(enableMenu)
}, {
label: '&Window',
submenu: this.getWindowSubmenu(tabs, activeTabIndex)
submenu: this.getWindowSubmenu(tabs, activeTabIndex, enableMenu)
}, {
label: '&Tools',
submenu: this.getToolsSubmenu()
@@ -414,7 +494,7 @@ class AppMenu {
}];
}
static sendAction(action, ...params) {
static sendAction(action: any, ...params: any[]): void {
const win = BrowserWindow.getAllWindows()[0];
if (process.platform === 'darwin') {
@@ -424,10 +504,27 @@ class AppMenu {
win.webContents.send(action, ...params);
}
static checkForUpdate() {
static checkForUpdate(): void {
appUpdater(true);
}
static resetAppSettings() {
static getNextServer(tabs: any[], activeTabIndex: number): number {
do {
activeTabIndex = (activeTabIndex + 1) % tabs.length;
}
while (tabs[activeTabIndex].props.role !== 'server');
return activeTabIndex;
}
static getPreviousServer(tabs: any[], activeTabIndex: number): number {
do {
activeTabIndex = (activeTabIndex - 1 + tabs.length) % tabs.length;
}
while (tabs[activeTabIndex].props.role !== 'server');
return activeTabIndex;
}
static resetAppSettings(): void {
const resetAppSettingsMessage = 'By proceeding you will be removing all connected organizations and preferences from Zulip.';
// We save App's settings/configurations in following files
@@ -443,7 +540,7 @@ class AppMenu {
if (response === 0) {
settingFiles.forEach(settingFileName => {
const getSettingFilesPath = path.join(app.getPath('appData'), appName, settingFileName);
fs.access(getSettingFilesPath, error => {
fs.access(getSettingFilesPath, (error: any) => {
if (error) {
logger.error('Error while resetting app settings.');
logger.error(error);
@@ -458,11 +555,11 @@ class AppMenu {
});
}
setMenu(props) {
setMenu(props: any): void {
const tpl = process.platform === 'darwin' ? this.getDarwinTpl(props) : this.getOtherTpl(props);
const menu = Menu.buildFromTemplate(tpl);
Menu.setApplicationMenu(menu);
}
}
module.exports = new AppMenu();
export = new AppMenu();

View File

@@ -1,10 +1,11 @@
'use strict';
const { app } = require('electron');
const AutoLaunch = require('auto-launch');
const isDev = require('electron-is-dev');
const ConfigUtil = require('./../renderer/js/utils/config-util.js');
import { app } from 'electron';
const setAutoLaunch = AutoLaunchValue => {
import AutoLaunch = require('auto-launch');
import isDev = require('electron-is-dev');
import ConfigUtil = require('../renderer/js/utils/config-util');
export const setAutoLaunch = (AutoLaunchValue: boolean): void => {
// Don't run this in development
if (isDev) {
return;
@@ -28,7 +29,3 @@ const setAutoLaunch = AutoLaunchValue => {
ZulipAutoLauncher.disable();
}
};
module.exports = {
setAutoLaunch
};

21
app/package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "zulip",
"version": "2.5.0",
"version": "3.1.0-beta",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -260,7 +260,7 @@
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha1-PH/L9SnYcibz0vUrlm/1Jx60Qd0=",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"requires": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
@@ -464,6 +464,11 @@
"dns-packet": "^1.1.0"
}
},
"dotenv": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.0.0.tgz",
"integrity": "sha512-30xVGqjLjiUOArT4+M5q9sYdvuR4riM6yK9wMcas9Vbp6zZa+ocC9dp6QoftuhTPhFAiLK/0C5Ni2nou/Bk8lg=="
},
"duplexer3": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz",
@@ -775,7 +780,7 @@
"hashids": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/hashids/-/hashids-1.1.4.tgz",
"integrity": "sha1-5P+SrWa2hKO9aqznwX1mYY7l+iE="
"integrity": "sha512-U/fnTE3edW0AV92ZI/BfEluMZuVcu3MDOopsN7jS+HqDYcarQo8rXQiWlsBlm0uX48/taYSdxRsfzh2HRg5Z6w=="
},
"hawk": {
"version": "6.0.2",
@@ -1094,7 +1099,7 @@
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
"integrity": "sha1-UWbihkV/AzBgZL5Ul+jbsMPTIIM=",
"integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
"requires": {
"brace-expansion": "^1.1.7"
}
@@ -1123,9 +1128,9 @@
"integrity": "sha1-ltDNYQ69WNS03pzAxoKM2pnHVI8="
},
"node-json-db": {
"version": "0.9.1",
"resolved": "https://registry.npmjs.org/node-json-db/-/node-json-db-0.9.1.tgz",
"integrity": "sha512-4BydUI7a10W8QBdHq/J3UBswU1i8WhCgTS4BZU0MjlUKrSU7cuUti71eojistgqe5hIrb4adj/wvAT5dw63NPg==",
"version": "0.9.2",
"resolved": "https://registry.npmjs.org/node-json-db/-/node-json-db-0.9.2.tgz",
"integrity": "sha512-vd8A6wznm3hi82IKlVKdomZvsEnASYWl0n4iwLkI7ukbIQkXTtFdJG8aZg0BNbEN+Vr/VktDFSqwWx/iSdf31Q==",
"requires": {
"mkdirp": "0.5.x"
}
@@ -1497,7 +1502,7 @@
"spawn-rx": {
"version": "2.0.12",
"resolved": "https://registry.npmjs.org/spawn-rx/-/spawn-rx-2.0.12.tgz",
"integrity": "sha1-tihSlEmUJgib7qDDwewy1/xXo3Y=",
"integrity": "sha512-gOPXiQQFQ9lTOLuys0iMn3jfxxv9c7zzwhbYLOEbQGvEShHVJ5sSR1oD3Daj88os7jKArDYT7rbOKdvNhe7iEg==",
"requires": {
"debug": "^2.5.1",
"lodash.assign": "^4.2.0",

View File

@@ -1,7 +1,7 @@
{
"name": "zulip",
"productName": "Zulip",
"version": "2.5.0-beta",
"version": "3.1.0-beta",
"description": "Zulip Desktop App",
"license": "Apache-2.0",
"copyright": "Kandra Labs, Inc.",
@@ -11,10 +11,10 @@
},
"repository": {
"type": "git",
"url": "https://github.com/zulip/zulip-electron.git"
"url": "https://github.com/zulip/zulip-desktop.git"
},
"bugs": {
"url": "https://github.com/zulip/zulip-electron/issues"
"url": "https://github.com/zulip/zulip-desktop/issues"
},
"main": "main/index.js",
"keywords": [
@@ -30,6 +30,7 @@
"@sentry/electron": "0.14.0",
"adm-zip": "0.4.11",
"auto-launch": "5.0.5",
"dotenv": "8.0.0",
"electron-is-dev": "0.3.0",
"electron-log": "2.2.14",
"electron-spellchecker": "1.1.2",
@@ -37,7 +38,7 @@
"electron-window-state": "5.0.3",
"escape-html": "1.0.3",
"is-online": "7.0.0",
"node-json-db": "0.9.1",
"node-json-db": "0.9.2",
"request": "2.85.0",
"semver": "5.4.1",
"wurl": "2.5.0"

View File

@@ -1,46 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/about.css">
</head>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/about.css">
<title>Zulip - About</title>
</head>
<body>
<div class="about">
<img class="logo" src="../resources/zulip.png" />
<p class="detail" id="version">v?.?.?</p>
<div class="maintenance-info">
<p class="detail maintainer">
Maintained by
<a onclick="linkInBrowser('website')">Zulip</a>
</p>
<p class="detail license">
Available under the
<a onclick="linkInBrowser('license')">Apache 2.0 License</a>
</p>
</div>
</div>
<script>
<body>
<div class="about">
<img class="logo" src="../resources/zulip.png" />
<p class="detail" id="version">v?.?.?</p>
<div class="maintenance-info">
<p class="detail maintainer">
Maintained by
<a onclick="linkInBrowser('website')">Zulip</a>
</p>
<p class="detail license">
Available under the
<a onclick="linkInBrowser('license')">Apache 2.0 License</a>
</p>
</div>
</div>
<script>
const { app } = require('electron').remote;
const { shell } = require('electron');
const version_tag = document.querySelector('#version');
version_tag.innerHTML = 'v' + app.getVersion();
const { app } = require('electron').remote;
const { shell } = require('electron');
const version_tag = document.querySelector('#version');
version_tag.innerHTML = 'v' + app.getVersion();
function linkInBrowser(type) {
let url;
switch (type) {
case 'website':
url = "https://zulipchat.com";
break;
case 'license':
url = "https://github.com/zulip/zulip-electron/blob/master/LICENSE";
break;
}
shell.openExternal(url);
}
</script>
<script>require('./js/shared/preventdrag.js')</script>
</body>
function linkInBrowser(type) {
let url;
switch (type) {
case 'website':
url = "https://zulipchat.com";
break;
case 'license':
url = "https://github.com/zulip/zulip-desktop/blob/master/LICENSE";
break;
}
shell.openExternal(url);
}
</script>
<script>require('./js/shared/preventdrag.js')</script>
</body>
</html>

View File

@@ -1,66 +1,66 @@
body {
background: #fafafa;
font-family: menu, "Helvetica Neue", sans-serif;
-webkit-font-smoothing: subpixel-antialiased;
background: rgba(250, 250, 250, 1.000);
font-family: menu, "Helvetica Neue", sans-serif;
-webkit-font-smoothing: subpixel-antialiased;
}
.logo {
display: block;
margin: -40px auto;
display: block;
margin: -40px auto;
}
#version {
color: #444343;
font-size: 1.3em;
padding-top: 40px;
color: rgba(68, 67, 67, 1.000);
font-size: 1.3em;
padding-top: 40px;
}
.about {
margin: 25vh auto;
height: 25vh;
text-align: center;
margin: 25vh auto;
height: 25vh;
text-align: center;
}
.about p {
font-size: 20px;
color: rgba(0, 0, 0, 0.62);
font-size: 20px;
color: rgba(0, 0, 0, 0.62);
}
.about img {
width: 150px;
width: 150px;
}
.detail {
text-align: center;
text-align: center;
}
.detail.maintainer {
font-size: 1.2em;
font-weight: 500;
font-size: 1.2em;
font-weight: 500;
}
.detail.license {
font-size: 0.8em;
font-size: 0.8em;
}
.maintenance-info {
cursor: pointer;
position: absolute;
width: 100%;
left: 0px;
color: #444;
cursor: pointer;
position: absolute;
width: 100%;
left: 0px;
color: rgba(68, 68, 68, 1.000);
}
.maintenance-info p {
margin: 0;
font-size: 1em;
width: 100%;
margin: 0;
font-size: 1em;
width: 100%;
}
p.detail a {
color: #355f4c;
color: rgba(53, 95, 76, 1.000);
}
p.detail a:hover {
text-decoration: underline;
text-decoration: underline;
}

View File

@@ -16,7 +16,7 @@ body {
}
.toggle-sidebar {
background: #222c31;
background: rgba(34, 44, 49, 1.000);
width: 54px;
padding: 27px 0 20px 0;
justify-content: space-between;
@@ -43,25 +43,25 @@ body {
}
#view-controls-container {
height: calc(100% - 208px);
overflow-y: hidden;
height: calc(100% - 208px);
overflow-y: hidden;
}
#view-controls-container:hover {
overflow-y: overlay;
overflow-y: overlay;
}
#view-controls-container::-webkit-scrollbar {
width: 4px;
width: 4px;
}
#view-controls-container::-webkit-scrollbar-track {
box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
#view-controls-container::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
background-color: rgba(169, 169, 169, 1.000);
outline: 1px solid rgba(169, 169, 169, 1.000);
}
@font-face {
@@ -119,12 +119,12 @@ body {
}
.action-button i {
color: #6c8592;
color: rgba(108, 133, 146, 1.000);
font-size: 28px;
}
.action-button:hover i {
color: #98a9b3;
color: rgba(152, 169, 179, 1.000);
}
.action-button.disable {
@@ -136,18 +136,18 @@ body {
}
.action-button.disable:hover i {
color: #6c8592;
color: rgba(108, 133, 146, 1.000);
}
.action-button.active {
/* background-color: rgba(255, 255, 255, 0.25); */
background-color: #efefef;
background-color: rgba(239, 239, 239, 1.000);
opacity: 0.9;
padding-right: 14px;
}
.action-button.active i {
color: #1c262b;
color: rgba(28, 38, 43, 1.000);
}
.tab:first-child {
@@ -177,7 +177,7 @@ body {
margin-top: 5px;
z-index: 11;
line-height: 31px;
color: #eee;
color: rgba(238, 238, 238, 1.000);
text-align: center;
overflow: hidden;
opacity: 0.6;
@@ -188,7 +188,7 @@ body {
font-family: Verdana;
font-weight: 600;
font-size: 22px;
border: 2px solid #222c31;
border: 2px solid rgba(34, 44, 49, 1.000);
margin-left: 17%;
width: 35px;
border-radius: 4px;
@@ -216,7 +216,7 @@ body {
.tab.active .server-tab {
opacity: 1;
background-color: #648478;
background-color: rgba(100, 132, 120, 1.000);
}
.tab .server-tab-badge.active {
@@ -224,7 +224,7 @@ body {
min-width: 11px;
padding: 0 3px;
height: 17px;
background-color: #f44336;
background-color: rgba(244, 67, 54, 1.000);
font-size: 10px;
font-family: sans-serif;
position: absolute;
@@ -232,7 +232,7 @@ body {
z-index: 15;
top: 6px;
float: right;
color: #fff;
color: rgba(255, 255, 255, 1.000);
text-align: center;
line-height: 17px;
display: block;
@@ -260,13 +260,25 @@ body {
}
.tab .server-tab-shortcut {
color: #648478;
color: rgba(100, 132, 120, 1.000);
font-size: 12px;
text-align: center;
font-family: sans-serif;
margin-bottom: 5px;
}
.refresh {
animation: rotate-loader 1s linear infinite;
}
@keyframes rotate-loader {
from {
transform: rotate(0);
}
to {
transform: rotate(-360deg);
}
}
/*******************
* Webview Area *
@@ -278,19 +290,19 @@ body {
width: 100%;
}
/*Pseudo element for loading indicator*/
/* Pseudo element for loading indicator */
#webviews-container::before {
content: "";
position: absolute;
z-index: 1;
background: #fff url(../img/ic_loading.gif) no-repeat;
background: rgba(255, 255, 255, 1.000) url(../img/ic_loading.gif) no-repeat;
background-size: 60px 60px;
background-position: center;
width: 100%;
height: 100%;
}
/*When the active webview is loaded*/
/* When the active webview is loaded */
#webviews-container.loaded::before {
opacity: 0;
z-index: -1;
@@ -328,32 +340,34 @@ webview.focus {
/* Tooltip styling */
#loading-tooltip,
#dnd-tooltip,
#back-tooltip,
#reload-tooltip,
#setting-tooltip {
font-family: sans-serif;
background: #222c31;
background: rgba(34, 44, 49, 1.000);
margin-left: 48px;
padding: 6px 8px;
position: absolute;
margin-top: 0px;
z-index: 1000;
color: white;
color: rgba(255, 255, 255, 1.000);
border-radius: 4px;
text-align: center;
width: 55px;
font-size: 14px;
}
#dnd-tooltip:after,
#back-tooltip:after,
#reload-tooltip:after,
#setting-tooltip:after {
#loading-tooltip::after,
#dnd-tooltip::after,
#back-tooltip::after,
#reload-tooltip::after,
#setting-tooltip::after {
content: " ";
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-right: 8px solid #222c31;
border-right: 8px solid rgba(34, 44, 49, 1.000);
position: absolute;
top: 7px;
right: 68px;
@@ -362,25 +376,25 @@ webview.focus {
#add-server-tooltip,
.server-tooltip {
font-family: 'arial';
background: #222c31;
background: rgba(34, 44, 49, 1.000);
left: 56px;
padding: 10px 20px;
position: fixed;
margin-top: 11px;
z-index: 5000 !important;
color: #fff;
color: rgba(255, 255, 255, 1.000);
border-radius: 4px;
text-align: center;
width: max-content;
font-size: 14px;
}
#add-server-tooltip:after,
.server-tooltip:after {
#add-server-tooltip::after,
.server-tooltip::after {
content: " ";
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
border-right: 8px solid #222c31;
border-right: 8px solid rgba(34, 44, 49, 1.000);
position: absolute;
top: 10px;
left: -5px;
@@ -392,14 +406,14 @@ webview.focus {
position: absolute;
width: 24px;
height: 24px;
background: #222c31;
background: rgba(34, 44, 49, 1.000);
border-radius: 20px;
cursor: pointer;
box-shadow: #999 1px 1px;
box-shadow: rgba(153, 153, 153, 1.000) 1px 1px;
}
#collapse-button i {
color: #efefef;
color: rgba(239, 239, 239, 1.000);
}
#main-container {
@@ -420,8 +434,8 @@ webview.focus {
.popup .popuptext {
visibility: hidden;
background-color: #555;
color: #fff;
background-color: rgba(85, 85, 85, 1.000);
color: rgba(255, 255, 255, 1.000);
text-align: center;
border-radius: 6px;
padding: 9px 0;
@@ -453,24 +467,24 @@ webview.focus {
}
send-feedback {
width: 60%;
height: 85%;
width: 60%;
height: 85%;
}
#feedback-modal {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(68, 67, 67, 0.81);
align-items: center;
justify-content: center;
z-index: 2;
transition: all 1s ease-out;
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(68, 67, 67, 0.81);
align-items: center;
justify-content: center;
z-index: 2;
transition: all 1s ease-out;
}
#feedback-modal.show {
display: flex;
display: flex;
}

View File

@@ -1,10 +1,11 @@
html, body {
html,
body {
margin: 0;
cursor: default;
font-size: 14px;
color: #333;
background: #fff;
user-select:none;
color: rgba(51, 51, 51, 1.000);
background: rgba(255, 255, 255, 1.000);
user-select: none;
}
#content {
@@ -27,8 +28,8 @@ html, body {
#reconnect {
font-size: 16px;
background: #009688;
color: #fff;
background: rgba(0, 150, 136, 1.000);
color: rgba(255, 255, 255, 1.000);
width: 84px;
height: 32px;
border-radius: 5px;

View File

@@ -7,25 +7,25 @@ body {
font-family: menu, "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
background: #efefef;
background: rgba(239, 239, 239, 1.000);
letter-spacing: -.08px;
line-height: 18px;
color: #8b8e8f;
color: rgba(139, 142, 143, 1.000);
}
kbd {
display: inline-block;
border: 1px solid #ccc;
border: 1px solid rgba(204, 204, 204, 1.000);
border-radius: 4px;
font-size: 15px;
font-family: Courier New, Courier, monospace;
font-weight: bold;
white-space: nowrap;
background-color: #f7f7f7;
color: #333;
background-color: rgba(247, 247, 247, 1.000);
color: rgba(51, 51, 51, 1.000);
margin: 0 0.1em;
padding: 0.3em 0.8em;
text-shadow: 0 1px 0 #fff;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1.000);
line-height: 1.4;
}
@@ -33,7 +33,7 @@ table,
th,
td {
border-collapse: collapse;
color: #383430;
color: rgba(56, 52, 48, 1.000);
}
table {
@@ -43,11 +43,11 @@ table {
}
table tr:nth-child(even) {
background-color: #fafafa;
background-color: rgba(250, 250, 250, 1.000);
}
table tr:nth-child(odd) {
background-color: #fff;
background-color: rgba(255, 255, 255, 1.000);
}
td {
@@ -103,7 +103,7 @@ td:nth-child(odd) {
display: flex;
flex-direction: column;
font-size: 16px;
background: #f2f2f2;
background: rgba(242, 242, 242, 1.000);
}
#nav-container {
@@ -112,18 +112,18 @@ td:nth-child(odd) {
.nav {
padding: 7px 0;
color: #999;
color: rgba(153, 153, 153, 1.000);
cursor: pointer;
}
.nav.active {
color: #4ebfac;
color: rgba(78, 191, 172, 1.000);
cursor: default;
position: relative;
}
.nav.active::before {
background: #464e5a;
background: rgba(70, 78, 90, 1.000);
width: 3px;
height: 18px;
position: absolute;
@@ -139,7 +139,7 @@ td:nth-child(odd) {
#settings-header {
font-size: 22px;
color: #222c31;
color: rgba(34, 44, 49, 1.000);
font-weight: bold;
text-transform: uppercase;
}
@@ -159,11 +159,11 @@ td:nth-child(odd) {
.title {
font-weight: 500;
color: #222c31;
color: rgba(34, 44, 49, 1.000);
}
.page-title {
color: #222c31;
color: rgba(34, 44, 49, 1.000);
font-size: 15px;
font-weight: bold;
padding: 4px 0 6px 0;
@@ -182,7 +182,7 @@ td:nth-child(odd) {
.sub-title {
padding: 4px 0 6px 0;
font-weight: bold;
color: #616161;
color: rgba(97, 97, 97, 1.000);
}
img.server-info-icon {
@@ -249,14 +249,18 @@ img.server-info-icon {
font-size: 14px;
border-radius: 4px;
padding: 13px;
border: #ededed 2px solid;
border: rgba(237, 237, 237, 1.000) 2px solid;
outline-width: 0;
background: transparent;
max-width: 450px;
}
.setting-input-value:focus {
border: #4EBFAC 2px solid;
border: rgba(78, 191, 172, 1.000) 2px solid;
}
.invalid-input-value:focus {
border: rgba(239, 83, 80, 1) 2px solid;
}
.manual-proxy-block {
@@ -266,7 +270,7 @@ img.server-info-icon {
.actions-container {
display: flex;
font-size: 14px;
color: #235d3a;
color: rgba(35, 93, 58, 1.000);
vertical-align: middle;
margin: 10px 0;
flex-wrap: wrap;
@@ -287,7 +291,7 @@ img.server-info-icon {
.settings-pane {
flex-grow: 1;
min-width: 550px;
min-width: 550px;
}
.action:hover {
@@ -299,7 +303,7 @@ img.server-info-icon {
}
.action.disabled {
color: #999;
color: rgba(153, 153, 153, 1.000);
}
.settings-card {
@@ -307,7 +311,7 @@ img.server-info-icon {
flex-wrap: wrap;
padding: 12px 30px;
margin: 10px 0 20px 0;
background: #fff;
background: rgba(255, 255, 255, 1.000);
width: 80%;
transition: all 0.2s;
}
@@ -322,21 +326,29 @@ img.server-info-icon {
}
.red {
color: #ef5350;
padding: 8px;
border: rgba(239, 83, 80, 0.5) solid 1px;
color: rgb(240, 148, 148);
background: rgba(255, 255, 255, 1.000);
border-radius: 4px;
border-color: #fff;
display: inline-block;
border: 2px solid rgb(240, 148, 148);
padding: 10px;
width: 100px;
cursor: pointer;
font-size: 1rem;
font-weight: bold;
transition: background-color 0.2s ease;
text-decoration: none;
text-align: center;
}
.red:hover {
background-color: rgba(230, 52, 49, 0.5);
color: #fff;
background-color: rgb(240, 148, 148);
color: rgba(255, 255, 255, 1.000);
}
.green {
color: #fff;
background: #4EBFAC;
color: rgba(255, 255, 255, 1.000);
background: rgba(78, 191, 172, 1.000);
border-radius: 4px;
display: inline-block;
border: none;
@@ -351,8 +363,8 @@ img.server-info-icon {
}
.green:hover {
background-color: #3c9f8d;
color: #fff;
background-color: rgba(60, 159, 141, 1.000);
color: rgba(255, 255, 255, 1.000);
}
.w-150 {
@@ -364,9 +376,9 @@ img.server-info-icon {
}
.grey {
color: #9E9E9E;
background: #FAFAFA;
border: 1px solid #9E9E9E;
color: rgba(158, 158, 158, 1.000);
background: rgba(250, 250, 250, 1.000);
border: 1px solid rgba(158, 158, 158, 1.000);
}
.setting-row {
@@ -393,7 +405,7 @@ i.open-tab-button {
.selected-css-path,
.download-folder-path {
background: #eeeeee;
background: rgba(238, 238, 238, 1.000);
padding: 5px 10px;
margin-right: 10px;
display: flex;
@@ -433,7 +445,7 @@ i.open-tab-button {
visibility: hidden;
}
.toggle+label {
.toggle + label {
display: block;
position: relative;
cursor: pointer;
@@ -441,16 +453,16 @@ i.open-tab-button {
user-select: none;
}
input.toggle-round+label {
input.toggle-round + label {
padding: 2px;
width: 50px;
height: 25px;
background-color: #dddddd;
background-color: rgba(221, 221, 221, 1.000);
border-radius: 25px;
}
input.toggle-round+label:before,
input.toggle-round+label:after {
input.toggle-round + label::before,
input.toggle-round + label::after {
display: block;
position: absolute;
top: 2px;
@@ -459,8 +471,8 @@ input.toggle-round+label:after {
content: "";
}
input.toggle-round+label:before {
background-color: #f1f1f1;
input.toggle-round + label::before {
background-color: rgba(241, 241, 241, 1.000);
border-radius: 25px;
top: 0;
right: 0px;
@@ -468,22 +480,22 @@ input.toggle-round+label:before {
bottom: 0px;
}
input.toggle-round+label:after {
input.toggle-round + label::after {
width: 25px;
height: 25px;
background-color: #fff;
background-color: rgba(255, 255, 255, 1.000);
border-radius: 100%;
}
input.toggle-round:checked+label:before {
background-color: #4EBFAC;
input.toggle-round:checked + label::before {
background-color: rgba(78, 191, 172, 1.000);
top: 0;
right: 0px;
left: 0px;
bottom: 0px;
}
input.toggle-round:checked+label:after {
input.toggle-round:checked + label::after {
margin-left: 25px;
}
@@ -500,17 +512,17 @@ input.toggle-round:checked+label:after {
width: 100%;
height: 100%;
/* background: rgba(61, 64, 67, 15); */
background: linear-gradient(35deg, #003b52, #45b59b);
background: linear-gradient(35deg, rgba(0, 59, 82, 1.000), rgba(69, 181, 155, 1.000));
overflow: auto;
}
/* Modal Content */
.modal-container {
background-color: #f4f7f8;
background-color: rgba(244, 247, 248, 1.000);
margin: auto;
padding: 57px;
border: #dae1e3 1px solid;
border: rgba(218, 225, 227, 1.000) 1px solid;
width: 550px;
height: 370px;
border-radius: 4px;
@@ -524,7 +536,7 @@ input.toggle-round:checked+label:after {
.divider {
margin-bottom: 30px;
margin-top: 30px;
color: #7d878a;
color: rgba(125, 135, 138, 1.000);
}
.divider hr {
@@ -555,8 +567,8 @@ input.toggle-round:checked+label:after {
margin: auto;
align-items: center;
text-align: center;
color: #fff;
background: #4EBFAC;
color: rgba(255, 255, 255, 1.000);
background: rgba(78, 191, 172, 1.000);
border-color: none;
border: none;
width: 98%;
@@ -566,15 +578,15 @@ input.toggle-round:checked+label:after {
}
.server-center button:hover {
background: #329588;
background: rgba(50, 149, 136, 1.000);
}
.server-center button:focus {
background: #329588;
background: rgba(50, 149, 136, 1.000);
}
.certificates-card {
width: 80%
width: 80%;
}
.certificate-input {
@@ -601,8 +613,8 @@ input.toggle-round:checked+label:after {
padding: 0;
}
.tip:hover{
box-shadow: none;
.tip:hover {
box-shadow: none;
}
.md-14 {

View File

@@ -1,9 +1,9 @@
/* Override css rules */
.portico-wrap>.header {
.portico-wrap > .header {
display: none;
}
.portico-container>.footer {
.portico-container > .footer {
display: none;
}

View File

@@ -1,11 +1,11 @@
'use strict';
class BaseComponent {
generateNodeFromTemplate(template) {
generateNodeFromTemplate(template: string): Element | null {
const wrapper = document.createElement('div');
wrapper.innerHTML = template;
return wrapper.firstElementChild;
}
}
module.exports = BaseComponent;
export = BaseComponent;

View File

@@ -1,9 +1,10 @@
'use strict';
const Tab = require(__dirname + '/../components/tab.js');
import Tab = require('./tab');
class FunctionalTab extends Tab {
template() {
$closeButton: Element;
template(): string {
return `<div class="tab functional-tab" data-tab-id="${this.props.tabIndex}">
<div class="server-tab-badge close-button">
<i class="material-icons">close</i>
@@ -14,16 +15,22 @@ class FunctionalTab extends Tab {
</div>`;
}
init() {
// TODO: Typescript - This type for props should be TabProps
constructor(props: any) {
super(props);
this.init();
}
init(): void {
this.$el = this.generateNodeFromTemplate(this.template());
if (this.props.name !== 'Settings') {
this.props.$root.appendChild(this.$el);
this.$closeButton = this.$el.getElementsByClassName('server-tab-badge')[0];
this.props.$root.append(this.$el);
this.$closeButton = this.$el.querySelectorAll('.server-tab-badge')[0];
this.registerListeners();
}
}
registerListeners() {
registerListeners(): void {
super.registerListeners();
this.$el.addEventListener('mouseover', () => {
@@ -34,11 +41,11 @@ class FunctionalTab extends Tab {
this.$closeButton.classList.remove('active');
});
this.$closeButton.addEventListener('click', e => {
this.$closeButton.addEventListener('click', (e: Event) => {
this.props.onDestroy();
e.stopPropagation();
});
}
}
module.exports = FunctionalTab;
export = FunctionalTab;

View File

@@ -1,12 +1,15 @@
const { ipcRenderer } = require('electron');
const { shell, app } = require('electron').remote;
const LinkUtil = require('../utils/link-util');
const DomainUtil = require('../utils/domain-util');
const ConfigUtil = require('../utils/config-util');
import { ipcRenderer, remote } from 'electron';
import LinkUtil = require('../utils/link-util');
import DomainUtil = require('../utils/domain-util');
import ConfigUtil = require('../utils/config-util');
const { shell, app } = remote;
const dingSound = new Audio('../resources/sounds/ding.ogg');
function handleExternalLink(event) {
// TODO: TypeScript - Figure out a way to pass correct type here.
function handleExternalLink(this: any, event: any): void {
const { url } = event;
const domainPrefix = DomainUtil.getDomain(this.props.index).url;
const downloadPath = ConfigUtil.getConfigItem('downloadsPath', `${app.getPath('downloads')}`);
@@ -33,11 +36,11 @@ function handleExternalLink(event) {
// and not trigger webview reload while image in webview will
// do nothing and will not save it
// Code to show pdf in a new BrowserWindow (currently commented out due to bug-upstream)
// Code to show pdf in a new BrowserWindow (currently commented out due to bug-upstream)
// if (!LinkUtil.isImage(url) && !LinkUtil.isPDF(url) && isUploadsURL) {
if (!LinkUtil.isImage(url) && isUploadsURL) {
ipcRenderer.send('downloadFile', url, downloadPath);
ipcRenderer.once('downloadFileCompleted', (event, filePath, fileName) => {
ipcRenderer.once('downloadFileCompleted', (_event: Event, filePath: string, fileName: string) => {
const downloadNotification = new Notification('Download Complete', {
body: shouldShowInFolder ? `Click to show ${fileName} in folder` : `Click to open ${fileName}`,
silent: true // We'll play our own sound - ding.ogg
@@ -48,7 +51,7 @@ function handleExternalLink(event) {
dingSound.play();
}
downloadNotification.onclick = () => {
downloadNotification.addEventListener('click', () => {
if (shouldShowInFolder) {
// Reveal file in download folder
shell.showItemInFolder(filePath);
@@ -56,7 +59,7 @@ function handleExternalLink(event) {
// Open file in the default native app
shell.openItem(filePath);
}
};
});
ipcRenderer.removeAllListeners('downloadFileFailed');
});
@@ -77,4 +80,4 @@ function handleExternalLink(event) {
}
}
module.exports = handleExternalLink;
export = handleExternalLink;

View File

@@ -1,12 +1,14 @@
'use strict';
const Tab = require(__dirname + '/../components/tab.js');
const SystemUtil = require(__dirname + '/../utils/system-util.js');
import { ipcRenderer } from 'electron';
const {ipcRenderer} = require('electron');
import Tab = require('./tab');
import SystemUtil = require('../utils/system-util');
class ServerTab extends Tab {
template() {
$badge: Element;
template(): string {
return `<div class="tab" data-tab-id="${this.props.tabIndex}">
<div class="server-tooltip" style="display:none">${this.props.name}</div>
<div class="server-tab-badge"></div>
@@ -17,16 +19,22 @@ class ServerTab extends Tab {
</div>`;
}
init() {
super.init();
this.$badge = this.$el.getElementsByClassName('server-tab-badge')[0];
// TODO: Typescript - This type for props should be TabProps
constructor(props: any) {
super(props);
this.init();
}
updateBadge(count) {
if (count > 0) {
const formattedCount = count > 999 ? '1K+' : count;
init(): void {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.append(this.$el);
this.registerListeners();
this.$badge = this.$el.querySelectorAll('.server-tab-badge')[0];
}
updateBadge(count: number): void {
if (count > 0) {
const formattedCount = count > 999 ? '1K+' : count.toString();
this.$badge.innerHTML = formattedCount;
this.$badge.classList.add('active');
} else {
@@ -34,7 +42,7 @@ class ServerTab extends Tab {
}
}
generateShortcutText() {
generateShortcutText(): string {
// Only provide shortcuts for server [0..10]
if (this.props.index >= 10) {
return '';
@@ -57,4 +65,4 @@ class ServerTab extends Tab {
}
}
module.exports = ServerTab;
export = ServerTab;

View File

@@ -1,48 +1,44 @@
'use strict';
const BaseComponent = require(__dirname + '/../components/base.js');
import WebView = require('./webview');
import BaseComponent = require('./base');
// TODO: TypeScript - Type annotate props
interface TabProps {
[key: string]: any;
}
class Tab extends BaseComponent {
constructor(props) {
props: TabProps;
webview: WebView;
$el: Element;
constructor(props: TabProps) {
super();
this.props = props;
this.webview = this.props.webview;
this.init();
}
init() {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$el);
this.registerListeners();
}
registerListeners() {
registerListeners(): void {
this.$el.addEventListener('click', this.props.onClick);
this.$el.addEventListener('mouseover', this.props.onHover);
this.$el.addEventListener('mouseout', this.props.onHoverOut);
}
isLoading() {
return this.webview.isLoading;
}
activate() {
activate(): void {
this.$el.classList.add('active');
this.webview.load();
}
deactivate() {
deactivate(): void {
this.$el.classList.remove('active');
this.webview.hide();
}
destroy() {
destroy(): void {
this.$el.parentNode.removeChild(this.$el);
this.webview.$el.parentNode.removeChild(this.webview.$el);
}
}
module.exports = Tab;
export = Tab;

View File

@@ -1,22 +1,39 @@
'use strict';
import { remote } from 'electron';
const path = require('path');
const fs = require('fs');
import path = require('path');
import fs = require('fs');
import ConfigUtil = require('../utils/config-util');
import SystemUtil = require('../utils/system-util');
import BaseComponent = require('../components/base');
import handleExternalLink = require('../components/handle-external-link');
const ConfigUtil = require(__dirname + '/../utils/config-util.js');
const SystemUtil = require(__dirname + '/../utils/system-util.js');
const { app, dialog } = require('electron').remote;
const BaseComponent = require(__dirname + '/../components/base.js');
const handleExternalLink = require(__dirname + '/../components/handle-external-link.js');
const { app, dialog } = remote;
const shouldSilentWebview = ConfigUtil.getConfigItem('silent');
// TODO: TypeScript - Type annotate WebViewProps.
interface WebViewProps {
[key: string]: any;
}
class WebView extends BaseComponent {
constructor(props) {
props: any;
zoomFactor: number;
badgeCount: number;
loading: boolean;
customCSS: string;
$webviewsContainer: DOMTokenList;
$el: Electron.WebviewTag;
// This is required because in main.js we access WebView.method as
// webview[method].
[key: string]: any;
constructor(props: WebViewProps) {
super();
this.props = props;
this.zoomFactor = 1.0;
this.loading = true;
this.badgeCount = 0;
@@ -24,7 +41,7 @@ class WebView extends BaseComponent {
this.$webviewsContainer = document.querySelector('#webviews-container').classList;
}
template() {
template(): string {
return `<webview
class="disabled"
data-tab-id="${this.props.tabIndex}"
@@ -38,14 +55,14 @@ class WebView extends BaseComponent {
</webview>`;
}
init() {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$el);
init(): void {
this.$el = this.generateNodeFromTemplate(this.template()) as Electron.WebviewTag;
this.props.$root.append(this.$el);
this.registerListeners();
}
registerListeners() {
registerListeners(): void {
this.$el.addEventListener('new-window', event => {
handleExternalLink.call(this, event);
});
@@ -94,12 +111,18 @@ class WebView extends BaseComponent {
this.$el.classList.add('onload');
}
this.loading = false;
this.props.switchLoading(false, this.props.url);
this.show();
// Refocus text boxes after reload
// Remove when upstream issue https://github.com/electron/electron/issues/14474 is fixed
this.$el.blur();
this.$el.focus();
});
this.$el.addEventListener('did-fail-load', event => {
const { errorDescription } = event;
const hasConnectivityErr = (SystemUtil.connectivityERR.indexOf(errorDescription) >= 0);
const hasConnectivityErr = SystemUtil.connectivityERR.includes(errorDescription);
if (hasConnectivityErr) {
console.error('error', errorDescription);
this.props.onNetworkError();
@@ -107,6 +130,10 @@ class WebView extends BaseComponent {
});
this.$el.addEventListener('did-start-loading', () => {
const isSettingPage = this.props.url.includes('renderer/preference.html');
if (!isSettingPage) {
this.props.switchLoading(true, this.props.url);
}
let userAgent = SystemUtil.getUserAgent();
if (!userAgent) {
SystemUtil.setUserAgent(this.$el.getUserAgent());
@@ -114,14 +141,18 @@ class WebView extends BaseComponent {
}
this.$el.setUserAgent(userAgent);
});
this.$el.addEventListener('did-stop-loading', () => {
this.props.switchLoading(false, this.props.url);
});
}
getBadgeCount(title) {
const messageCountInTitle = (/\(([0-9]+)\)/).exec(title);
getBadgeCount(title: string): number {
const messageCountInTitle = (/\((\d+)\)/).exec(title);
return messageCountInTitle ? Number(messageCountInTitle[1]) : 0;
}
show() {
show(): void {
// Do not show WebView if another tab was selected and this tab should be in background.
if (!this.props.isActive()) {
return;
@@ -162,21 +193,27 @@ class WebView extends BaseComponent {
}
}
focus() {
focus(): void {
// focus Webview and it's contents when Window regain focus.
const webContents = this.$el.getWebContents();
if (webContents && !webContents.isFocused()) {
// HACK: webContents.isFocused() seems to be true even without the element
// being in focus. So, we check against `document.activeElement`.
if (webContents && this.$el !== document.activeElement) {
// HACK: Looks like blur needs to be called on the previously focused
// element to transfer focus correctly, in Electron v3.0.10
// See https://github.com/electron/electron/issues/15718
(document.activeElement as HTMLElement).blur();
this.$el.focus();
webContents.focus();
}
}
hide() {
hide(): void {
this.$el.classList.add('disabled');
this.$el.classList.remove('active');
}
load() {
load(): void {
if (this.$el) {
this.show();
} else {
@@ -184,40 +221,41 @@ class WebView extends BaseComponent {
}
}
zoomIn() {
zoomIn(): void {
this.zoomFactor += 0.1;
this.$el.setZoomFactor(this.zoomFactor);
}
zoomOut() {
zoomOut(): void {
this.zoomFactor -= 0.1;
this.$el.setZoomFactor(this.zoomFactor);
}
zoomActualSize() {
zoomActualSize(): void {
this.zoomFactor = 1.0;
this.$el.setZoomFactor(this.zoomFactor);
}
logOut() {
logOut(): void {
this.$el.executeJavaScript('logout()');
}
showShortcut() {
showShortcut(): void {
this.$el.executeJavaScript('shortcut()');
}
openDevTools() {
openDevTools(): void {
this.$el.openDevTools();
}
back() {
back(): void {
if (this.$el.canGoBack()) {
this.$el.goBack();
this.focus();
}
}
canGoBackButton() {
canGoBackButton(): void {
const $backButton = document.querySelector('#actions-container #back-action');
if (this.$el.canGoBack()) {
$backButton.classList.remove('disable');
@@ -226,13 +264,13 @@ class WebView extends BaseComponent {
}
}
forward() {
forward(): void {
if (this.$el.canGoForward()) {
this.$el.goForward();
}
}
reload() {
reload(): void {
this.hide();
// Shows the loading indicator till the webview is reloaded
this.$webviewsContainer.remove('loaded');
@@ -240,9 +278,9 @@ class WebView extends BaseComponent {
this.$el.reload();
}
send(...param) {
this.$el.send(...param);
send(channel: string, ...param: any[]): void {
this.$el.send(channel, ...param);
}
}
module.exports = WebView;
export = WebView;

View File

@@ -1,17 +1,20 @@
const events = require('events');
const { ipcRenderer } = require('electron');
import { ipcRenderer } from 'electron';
import events = require('events');
type ListenerType = ((...args: any[]) => void);
// we have and will have some non camelcase stuff
// while working with zulip so just turning the rule off
// for the whole file.
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
class ElectronBridge extends events {
send_event(...args) {
this.emit(...args);
send_event(eventName: string | symbol, ...args: any[]): void {
this.emit(eventName, ...args);
}
on_event(...args) {
this.on(...args);
on_event(eventName: string, listener: ListenerType): void {
this.on(eventName, listener);
}
}
@@ -37,4 +40,6 @@ electron_bridge.on('realm_icon_url', iconURL => {
// functions zulip side will emit event using ElectronBrigde.send_event
// which is alias of .emit and on this side we can handle the data by adding
// a listener for the event.
module.exports = electron_bridge;
export = electron_bridge;
/* eslint-enable @typescript-eslint/camelcase */

View File

@@ -1,7 +1,16 @@
const { app } = require('electron').remote;
const path = require('path');
const fs = require('fs');
const SendFeedback = require('@electron-elements/send-feedback');
import { remote } from 'electron';
import SendFeedback from '@electron-elements/send-feedback';
import path = require('path');
import fs = require('fs');
const { app } = remote;
interface SendFeedback extends HTMLElement {
[key: string]: any;
}
type SendFeedbackType = SendFeedback;
// make the button color match zulip app's theme
SendFeedback.customStyles = `
@@ -22,8 +31,8 @@ button {
`;
customElements.define('send-feedback', SendFeedback);
const sendFeedback = document.querySelector('send-feedback');
const feedbackHolder = sendFeedback.parentElement;
export const sendFeedback: SendFeedbackType = document.querySelector('send-feedback');
export const feedbackHolder = sendFeedback.parentElement;
// customize the fields of custom elements
sendFeedback.title = 'Report Issue';
@@ -38,9 +47,9 @@ sendFeedback.useReporter('emailReporter', {
email: 'akash@zulipchat.com'
});
feedbackHolder.addEventListener('click', e => {
// only remove the class if the grey out faded
// part is clicked and not the feedback element itself
feedbackHolder.addEventListener('click', (e: Event) => {
// only remove the class if the grey out faded
// part is clicked and not the feedback element itself
if (e.target === e.currentTarget) {
feedbackHolder.classList.remove('show');
}
@@ -55,8 +64,3 @@ sendFeedback.addEventListener('feedback-submitted', () => {
const dataDir = app.getPath('userData');
const logsDir = path.join(dataDir, '/Logs');
sendFeedback.logs.push(...fs.readdirSync(logsDir).map(file => path.join(logsDir, file)));
module.exports = {
feedbackHolder,
sendFeedback
};

View File

@@ -1,61 +1,138 @@
'use strict';
const { ipcRenderer, remote } = require('electron');
const isDev = require('electron-is-dev');
import { ipcRenderer, remote, clipboard, shell } from 'electron';
import { feedbackHolder } from './feedback';
import path = require('path');
import escape = require('escape-html');
import isDev = require('electron-is-dev');
const { session, app, Menu, dialog } = remote;
const escape = require('escape-html');
require(__dirname + '/js/tray.js');
const DomainUtil = require(__dirname + '/js/utils/domain-util.js');
const WebView = require(__dirname + '/js/components/webview.js');
const ServerTab = require(__dirname + '/js/components/server-tab.js');
const FunctionalTab = require(__dirname + '/js/components/functional-tab.js');
const ConfigUtil = require(__dirname + '/js/utils/config-util.js');
const DNDUtil = require(__dirname + '/js/utils/dnd-util.js');
const ReconnectUtil = require(__dirname + '/js/utils/reconnect-util.js');
const Logger = require(__dirname + '/js/utils/logger-util.js');
const CommonUtil = require(__dirname + '/js/utils/common-util.js');
// eslint-disable-next-line import/no-unassigned-import
require('./tray');
const { feedbackHolder } = require(__dirname + '/js/feedback.js');
import DomainUtil = require('./utils/domain-util');
import WebView = require('./components/webview');
import ServerTab = require('./components/server-tab');
import FunctionalTab = require('./components/functional-tab');
import ConfigUtil = require('./utils/config-util');
import DNDUtil = require('./utils/dnd-util');
import ReconnectUtil = require('./utils/reconnect-util');
import Logger = require('./utils/logger-util');
import CommonUtil = require('./utils/common-util');
const logger = new Logger({
file: 'errors.log',
timestamp: true
});
class ServerManagerView {
constructor() {
this.$addServerButton = document.getElementById('add-tab');
this.$tabsContainer = document.getElementById('tabs-container');
interface FunctionalTabProps {
name: string;
materialIcon: string;
url: string;
}
const $actionsContainer = document.getElementById('actions-container');
interface AnyObject {
[key: string]: any;
}
interface SettingsOptions {
autoHideMenubar: boolean;
trayIcon: boolean;
useManualProxy: boolean;
useSystemProxy: boolean;
showSidebar: boolean;
badgeOption: boolean;
startAtLogin: boolean;
startMinimized: boolean;
enableSpellchecker: boolean;
showNotification: boolean;
autoUpdate: boolean;
betaUpdate: boolean;
errorReporting: boolean;
customCSS: boolean;
silent: boolean;
lastActiveTab: number;
dnd: boolean;
dndPreviousSettings: {
showNotification: boolean;
silent: boolean;
flashTaskbarOnMessage?: boolean;
};
downloadsPath: string;
showDownloadFolder: boolean;
flashTaskbarOnMessage?: boolean;
dockBouncing?: boolean;
loading?: AnyObject;
}
const rendererDirectory = path.resolve(__dirname, '..');
type ServerOrFunctionalTab = ServerTab | FunctionalTab;
class ServerManagerView {
$addServerButton: HTMLButtonElement;
$tabsContainer: Element;
$reloadButton: HTMLButtonElement;
$loadingIndicator: HTMLButtonElement;
$settingsButton: HTMLButtonElement;
$webviewsContainer: Element;
$backButton: HTMLButtonElement;
$dndButton: HTMLButtonElement;
$addServerTooltip: HTMLElement;
$reloadTooltip: HTMLElement;
$loadingTooltip: HTMLElement;
$settingsTooltip: HTMLElement;
$serverIconTooltip: HTMLCollectionOf<HTMLElement>;
$backTooltip: HTMLElement;
$dndTooltip: HTMLElement;
$sidebar: Element;
$fullscreenPopup: Element;
$fullscreenEscapeKey: string;
loading: AnyObject;
activeTabIndex: number;
tabs: ServerOrFunctionalTab[];
functionalTabs: AnyObject;
tabIndex: number;
constructor() {
this.$addServerButton = document.querySelector('#add-tab');
this.$tabsContainer = document.querySelector('#tabs-container');
const $actionsContainer = document.querySelector('#actions-container');
this.$reloadButton = $actionsContainer.querySelector('#reload-action');
this.$loadingIndicator = $actionsContainer.querySelector('#loading-action');
this.$settingsButton = $actionsContainer.querySelector('#settings-action');
this.$webviewsContainer = document.getElementById('webviews-container');
this.$webviewsContainer = document.querySelector('#webviews-container');
this.$backButton = $actionsContainer.querySelector('#back-action');
this.$dndButton = $actionsContainer.querySelector('#dnd-action');
this.$addServerTooltip = document.getElementById('add-server-tooltip');
this.$addServerTooltip = document.querySelector('#add-server-tooltip');
this.$reloadTooltip = $actionsContainer.querySelector('#reload-tooltip');
this.$loadingTooltip = $actionsContainer.querySelector('#loading-tooltip');
this.$settingsTooltip = $actionsContainer.querySelector('#setting-tooltip');
this.$serverIconTooltip = document.getElementsByClassName('server-tooltip');
// TODO: This should have been querySelector but the problem is that
// querySelector doesn't return elements not present in dom whereas somehow
// getElementsByClassName does. To fix this we need to call this after this.initTabs
// is called in this.init.
// eslint-disable-next-line unicorn/prefer-query-selector
this.$serverIconTooltip = document.getElementsByClassName('server-tooltip') as HTMLCollectionOf<HTMLElement>;
this.$backTooltip = $actionsContainer.querySelector('#back-tooltip');
this.$dndTooltip = $actionsContainer.querySelector('#dnd-tooltip');
this.$sidebar = document.getElementById('sidebar');
this.$sidebar = document.querySelector('#sidebar');
this.$fullscreenPopup = document.getElementById('fullscreen-popup');
this.$fullscreenPopup = document.querySelector('#fullscreen-popup');
this.$fullscreenEscapeKey = process.platform === 'darwin' ? '^⌘F' : 'F11';
this.$fullscreenPopup.innerHTML = `Press ${this.$fullscreenEscapeKey} to exit full screen`;
this.loading = {};
this.activeTabIndex = -1;
this.tabs = [];
this.functionalTabs = {};
this.tabIndex = 0;
}
init() {
init(): void {
this.loadProxy().then(() => {
this.initSidebar();
this.initTabs();
@@ -65,7 +142,7 @@ class ServerManagerView {
});
}
loadProxy() {
loadProxy(): Promise<boolean> {
return new Promise(resolve => {
// To change proxyEnable to useManualProxy in older versions
const proxyEnabledOld = ConfigUtil.isConfigItemExists('useProxy');
@@ -97,20 +174,22 @@ class ServerManagerView {
// Settings are initialized only when user clicks on General/Server/Network section settings
// In case, user doesn't visit these section, those values set to be null automatically
// This will make sure the default settings are correctly set to either true or false
initDefaultSettings() {
initDefaultSettings(): void {
// Default settings which should be respected
const settingOptions = {
const settingOptions: SettingsOptions = {
autoHideMenubar: false,
trayIcon: true,
useManualProxy: false,
useSystemProxy: false,
showSidebar: true,
badgeOption: true,
startAtLogin: false,
startAtLogin: true,
startMinimized: false,
enableSpellchecker: true,
showNotification: true,
autoUpdate: true,
betaUpdate: false,
errorReporting: true,
customCSS: false,
silent: false,
lastActiveTab: 0,
@@ -141,18 +220,19 @@ class ServerManagerView {
}
for (const i in settingOptions) {
const setting = i as keyof SettingsOptions;
if (ConfigUtil.getConfigItem(i) === null) {
ConfigUtil.setConfigItem(i, settingOptions[i]);
ConfigUtil.setConfigItem(i, settingOptions[setting]);
}
}
}
initSidebar() {
initSidebar(): void {
const showSidebar = ConfigUtil.getConfigItem('showSidebar', true);
this.toggleSidebar(showSidebar);
}
initTabs() {
initTabs(): void {
const servers = DomainUtil.getDomains();
if (servers.length > 0) {
for (let i = 0; i < servers.length; i++) {
@@ -169,7 +249,7 @@ class ServerManagerView {
}
}
initServer(server, index) {
initServer(server: any, index: number): void {
const tabIndex = this.getTabIndex();
this.tabs.push(new ServerTab({
role: 'server',
@@ -186,26 +266,36 @@ class ServerManagerView {
index,
tabIndex,
url: server.url,
role: 'server',
name: CommonUtil.decodeString(server.alias),
isActive: () => {
return index === this.activeTabIndex;
},
switchLoading: (loading: boolean, url: string) => {
if (!loading && this.loading[url]) {
this.loading[url] = false;
} else if (loading && !this.loading[url]) {
this.loading[url] = true;
}
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
},
onNetworkError: this.openNetworkTroubleshooting.bind(this),
onTitleChange: this.updateBadge.bind(this),
nodeIntegration: false,
preload: true
})
}));
this.loading[server.url] = true;
}
initActions() {
initActions(): void {
this.initDNDButton();
this.initServerActions();
this.initLeftSidebarEvents();
}
initServerActions() {
const $serverImgs = document.querySelectorAll('.server-icons');
initServerActions(): void {
const $serverImgs: NodeListOf<HTMLImageElement> = document.querySelectorAll('.server-icons');
$serverImgs.forEach(($serverImg, index) => {
this.addContextMenu($serverImg, index);
if ($serverImg.src.includes('img/icon.png')) {
@@ -217,7 +307,7 @@ class ServerManagerView {
});
}
initLeftSidebarEvents() {
initLeftSidebarEvents(): void {
this.$dndButton.addEventListener('click', () => {
const dndUtil = DNDUtil.toggle();
ipcRenderer.send('forward-message', 'toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
@@ -236,24 +326,29 @@ class ServerManagerView {
});
this.sidebarHoverEvent(this.$addServerButton, this.$addServerTooltip, true);
this.sidebarHoverEvent(this.$loadingIndicator, this.$loadingTooltip);
this.sidebarHoverEvent(this.$settingsButton, this.$settingsTooltip);
this.sidebarHoverEvent(this.$reloadButton, this.$reloadTooltip);
this.sidebarHoverEvent(this.$backButton, this.$backTooltip);
this.sidebarHoverEvent(this.$dndButton, this.$dndTooltip);
}
initDNDButton() {
initDNDButton(): void {
const dnd = ConfigUtil.getConfigItem('dnd', false);
this.toggleDNDButton(dnd);
}
getTabIndex() {
getTabIndex(): number {
const currentIndex = this.tabIndex;
this.tabIndex++;
return currentIndex;
}
displayInitialCharLogo($img, index) {
getCurrentActiveServer(): string {
return this.tabs[this.activeTabIndex].webview.props.url;
}
displayInitialCharLogo($img: HTMLImageElement, index: number): void {
/*
index parameter needed because webview[data-tab-id] can increment
beyond size of sidebar org array and throw error
@@ -276,12 +371,12 @@ class ServerManagerView {
$altIcon.classList.add('alt-icon');
$parent.removeChild($img);
$parent.appendChild($altIcon);
$parent.append($altIcon);
this.addContextMenu($altIcon, index);
this.addContextMenu($altIcon as HTMLImageElement, index);
}
sidebarHoverEvent(SidebarButton, SidebarTooltip, addServer = false) {
sidebarHoverEvent(SidebarButton: HTMLButtonElement, SidebarTooltip: HTMLElement, addServer = false): void {
SidebarButton.addEventListener('mouseover', () => {
SidebarTooltip.removeAttribute('style');
// To handle position of add server tooltip due to scrolling of list of organizations
@@ -298,7 +393,7 @@ class ServerManagerView {
});
}
onHover(index) {
onHover(index: number): void {
// this.$serverIconTooltip[index].innerHTML already has realm name, so we are just
// removing the style.
this.$serverIconTooltip[index].removeAttribute('style');
@@ -309,11 +404,11 @@ class ServerManagerView {
this.$serverIconTooltip[index].style.top = top + 'px';
}
onHoverOut(index) {
onHoverOut(index: number): void {
this.$serverIconTooltip[index].style.display = 'none';
}
openFunctionalTab(tabProps) {
openFunctionalTab(tabProps: FunctionalTabProps): void {
if (this.functionalTabs[tabProps.name] !== undefined) {
this.activateTab(this.functionalTabs[tabProps.name]);
return;
@@ -337,10 +432,19 @@ class ServerManagerView {
index: this.functionalTabs[tabProps.name],
tabIndex,
url: tabProps.url,
role: 'function',
name: tabProps.name,
isActive: () => {
return this.functionalTabs[tabProps.name] === this.activeTabIndex;
},
switchLoading: (loading: AnyObject, url: string) => {
if (!loading && this.loading[url]) {
this.loading[url] = false;
} else if (loading && !this.loading[url]) {
this.loading[url] = true;
}
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
},
onNetworkError: this.openNetworkTroubleshooting.bind(this),
onTitleChange: this.updateBadge.bind(this),
nodeIntegration: true,
@@ -355,46 +459,46 @@ class ServerManagerView {
this.activateTab(this.functionalTabs[tabProps.name]);
}
openSettings(nav = 'General') {
openSettings(nav = 'General'): void {
this.openFunctionalTab({
name: 'Settings',
materialIcon: 'settings',
url: `file://${__dirname}/preference.html#${nav}`
url: `file://${rendererDirectory}/preference.html#${nav}`
});
this.$settingsButton.classList.add('active');
this.tabs[this.functionalTabs.Settings].webview.send('switch-settings-nav', nav);
}
openAbout() {
openAbout(): void {
this.openFunctionalTab({
name: 'About',
materialIcon: 'sentiment_very_satisfied',
url: `file://${__dirname}/about.html`
url: `file://${rendererDirectory}/about.html`
});
}
openNetworkTroubleshooting() {
openNetworkTroubleshooting(): void {
this.openFunctionalTab({
name: 'Network Troubleshooting',
materialIcon: 'network_check',
url: `file://${__dirname}/network.html`
url: `file://${rendererDirectory}/network.html`
});
}
activateLastTab(index) {
activateLastTab(index: number): void {
// Open all the tabs in background, also activate the tab based on the index
this.activateTab(index);
// Save last active tab
ConfigUtil.setConfigItem('lastActiveTab', index);
// Save last active tab via main process to avoid JSON DB errors
ipcRenderer.send('save-last-tab', index);
}
// returns this.tabs in an way that does
// not crash app when this.tabs is passed into
// ipcRenderer. Something about webview, and props.webview
// properties in ServerTab causes the app to crash.
get tabsForIpc() {
const tabs = [];
this.tabs.forEach(tab => {
get tabsForIpc(): ServerOrFunctionalTab[] {
const tabs: ServerOrFunctionalTab[] = [];
this.tabs.forEach((tab: ServerOrFunctionalTab) => {
const proto = Object.create(Object.getPrototypeOf(tab));
const tabClone = Object.assign(proto, tab);
@@ -407,7 +511,7 @@ class ServerManagerView {
return tabs;
}
activateTab(index, hideOldTab = true) {
activateTab(index: number, hideOldTab = true): void {
if (!this.tabs[index]) {
return;
}
@@ -432,6 +536,8 @@ class ServerManagerView {
this.activeTabIndex = index;
this.tabs[index].activate();
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
ipcRenderer.send('update-menu', {
// JSON stringify this.tabs to avoid a crash
// util.inspect is being used to handle circular references
@@ -442,7 +548,17 @@ class ServerManagerView {
});
}
destroyTab(name, index) {
showLoading(loading: boolean): void {
if (!loading) {
this.$reloadButton.removeAttribute('style');
this.$loadingIndicator.style.display = 'none';
} else if (loading) {
this.$reloadButton.style.display = 'none';
this.$loadingIndicator.removeAttribute('style');
}
}
destroyTab(name: string, index: number): void {
if (this.tabs[index].webview.loading) {
return;
}
@@ -458,7 +574,7 @@ class ServerManagerView {
}
}
destroyView() {
destroyView(): void {
// Show loading indicator
this.$webviewsContainer.classList.remove('loaded');
@@ -472,7 +588,7 @@ class ServerManagerView {
this.$webviewsContainer.innerHTML = '';
}
reloadView() {
reloadView(): void {
// Save and remember the index of last active tab so that we can use it later
const lastActiveTab = this.tabs[this.activeTabIndex].props.index;
ConfigUtil.setConfigItem('lastActiveTab', lastActiveTab);
@@ -485,24 +601,33 @@ class ServerManagerView {
// This will trigger when pressed CTRL/CMD + R [WIP]
// It won't reload the current view properly when you add/delete a server.
reloadCurrentView() {
reloadCurrentView(): void {
this.$reloadButton.click();
}
updateBadge() {
updateBadge(): void {
let messageCountAll = 0;
for (let i = 0; i < this.tabs.length; i++) {
if (this.tabs[i] && this.tabs[i].updateBadge) {
const count = this.tabs[i].webview.badgeCount;
for (const tab of this.tabs) {
if (tab && tab instanceof ServerTab && tab.updateBadge) {
const count = tab.webview.badgeCount;
messageCountAll += count;
this.tabs[i].updateBadge(count);
tab.updateBadge(count);
}
}
ipcRenderer.send('update-badge', messageCountAll);
}
toggleSidebar(show) {
updateGeneralSettings(setting: string, value: any): void {
const selector = 'webview:not([class*=disabled])';
const webview: Electron.WebviewTag = document.querySelector(selector);
if (webview) {
const webContents = webview.getWebContents();
webContents.send(setting, value);
}
}
toggleSidebar(show: boolean): void {
if (show) {
this.$sidebar.classList.remove('sidebar-hide');
} else {
@@ -511,12 +636,12 @@ class ServerManagerView {
}
// Toggles the dnd button icon.
toggleDNDButton(alert) {
this.$dndTooltip.textContent = (alert ? 'Turn Off' : 'Enable') + ' Do Not Disturb';
toggleDNDButton(alert: boolean): void {
this.$dndTooltip.textContent = (alert ? 'Disable' : 'Enable') + ' Do Not Disturb';
this.$dndButton.querySelector('i').textContent = alert ? 'notifications_off' : 'notifications';
}
addContextMenu($serverImg, index) {
addContextMenu($serverImg: HTMLImageElement, index: number): void {
$serverImg.addEventListener('contextmenu', e => {
e.preventDefault();
const template = [
@@ -535,6 +660,12 @@ class ServerManagerView {
}
});
}
},
{
label: 'Copy Zulip URL',
click: () => {
clipboard.writeText(DomainUtil.getDomain(index).url);
}
}
];
const contextMenu = Menu.buildFromTemplate(template);
@@ -542,8 +673,8 @@ class ServerManagerView {
});
}
registerIpcs() {
const webviewListeners = {
registerIpcs(): void {
const webviewListeners: AnyObject = {
'webview-reload': 'reload',
back: 'back',
focus: 'focus',
@@ -560,17 +691,23 @@ class ServerManagerView {
ipcRenderer.on(key, () => {
const activeWebview = this.tabs[this.activeTabIndex].webview;
if (activeWebview) {
activeWebview[webviewListeners[key]]();
activeWebview[webviewListeners[key] as string]();
}
});
}
ipcRenderer.on('open-settings', (event, settingNav) => {
ipcRenderer.on('open-settings', (event: Event, settingNav: string) => {
this.openSettings(settingNav);
});
ipcRenderer.on('open-about', this.openAbout.bind(this));
ipcRenderer.on('open-help', () => {
// Open help page of current active server
const helpPage = this.getCurrentActiveServer() + '/help';
shell.openExternal(helpPage);
});
ipcRenderer.on('reload-viewer', this.reloadView.bind(this, this.tabs[this.activeTabIndex].props.index));
ipcRenderer.on('reload-current-viewer', this.reloadCurrentView.bind(this));
@@ -583,7 +720,7 @@ class ServerManagerView {
ipcRenderer.send('clear-app-settings');
});
ipcRenderer.on('switch-server-tab', (event, index) => {
ipcRenderer.on('switch-server-tab', (event: Event, index: number) => {
this.activateLastTab(index);
});
@@ -591,7 +728,7 @@ class ServerManagerView {
this.openSettings('AddServer');
});
ipcRenderer.on('reload-proxy', (event, showAlert) => {
ipcRenderer.on('reload-proxy', (event: Event, showAlert: boolean) => {
this.loadProxy().then(() => {
if (showAlert) {
alert('Proxy settings saved!');
@@ -600,19 +737,16 @@ class ServerManagerView {
});
});
ipcRenderer.on('toggle-sidebar', (event, show) => {
ipcRenderer.on('toggle-sidebar', (event: Event, show: boolean) => {
// Toggle the left sidebar
this.toggleSidebar(show);
// Toggle sidebar switch in the general settings
const selector = 'webview:not([class*=disabled])';
const webview = document.querySelector(selector);
const webContents = webview.getWebContents();
webContents.send('toggle-sidebar-setting', show);
this.updateGeneralSettings('toggle-sidebar-setting', show);
});
ipcRenderer.on('toggle-silent', (event, state) => {
const webviews = document.querySelectorAll('webview');
ipcRenderer.on('toggle-silent', (event: Event, state: boolean) => {
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
webviews.forEach(webview => {
try {
webview.setAudioMuted(state);
@@ -625,17 +759,29 @@ class ServerManagerView {
});
});
ipcRenderer.on('toggle-dnd', (event, state, newSettings) => {
ipcRenderer.on('toggle-autohide-menubar', (event: Event, autoHideMenubar: boolean, updateMenu: boolean) => {
if (updateMenu) {
ipcRenderer.send('update-menu', {
tabs: this.tabsForIpc,
activeTabIndex: this.activeTabIndex
});
return;
}
this.updateGeneralSettings('toggle-menubar-setting', autoHideMenubar);
});
ipcRenderer.on('toggle-dnd', (event: Event, state: boolean, newSettings: SettingsOptions) => {
this.toggleDNDButton(state);
ipcRenderer.send('forward-message', 'toggle-silent', newSettings.silent);
const selector = 'webview:not([class*=disabled])';
const webview = document.querySelector(selector);
const webview: Electron.WebviewTag = document.querySelector(selector);
const webContents = webview.getWebContents();
webContents.send('toggle-dnd', state, newSettings);
});
ipcRenderer.on('update-realm-name', (event, serverURL, realmName) => {
DomainUtil.getDomains().forEach((domain, index) => {
ipcRenderer.on('update-realm-name', (event: Event, serverURL: string, realmName: string) => {
// TODO: TypeScript - Type annotate getDomains() or this domain paramter.
DomainUtil.getDomains().forEach((domain: any, index: number) => {
if (domain.url.includes(serverURL)) {
const serverTooltipSelector = `.tab .server-tooltip`;
const serverTooltips = document.querySelectorAll(serverTooltipSelector);
@@ -655,12 +801,13 @@ class ServerManagerView {
});
});
ipcRenderer.on('update-realm-icon', (event, serverURL, iconURL) => {
DomainUtil.getDomains().forEach((domain, index) => {
ipcRenderer.on('update-realm-icon', (event: Event, serverURL: string, iconURL: string) => {
// TODO: TypeScript - Type annotate getDomains() or this domain paramter.
DomainUtil.getDomains().forEach((domain: any, index: number) => {
if (domain.url.includes(serverURL)) {
DomainUtil.saveServerIcon(iconURL).then(localIconUrl => {
DomainUtil.saveServerIcon(iconURL).then((localIconUrl: string) => {
const serverImgsSelector = `.tab .server-icons`;
const serverImgs = document.querySelectorAll(serverImgsSelector);
const serverImgs: NodeListOf<HTMLImageElement> = document.querySelectorAll(serverImgsSelector);
serverImgs[index].src = localIconUrl;
domain.icon = localIconUrl;
@@ -680,21 +827,21 @@ class ServerManagerView {
this.$fullscreenPopup.classList.remove('show');
});
ipcRenderer.on('focus-webview-with-id', (event, webviewId) => {
const webviews = document.querySelectorAll('webview');
ipcRenderer.on('focus-webview-with-id', (event: Event, webviewId: number) => {
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
webviews.forEach(webview => {
const currentId = webview.getWebContents().id;
const tabId = webview.getAttribute('data-tab-id');
const concurrentTab = document.querySelector(`div[data-tab-id="${tabId}"]`);
const concurrentTab: HTMLButtonElement = document.querySelector(`div[data-tab-id="${tabId}"]`);
if (currentId === webviewId) {
concurrentTab.click();
}
});
});
ipcRenderer.on('render-taskbar-icon', (event, messageCount) => {
ipcRenderer.on('render-taskbar-icon', (event: Event, messageCount: number) => {
// Create a canvas from unread messagecounts
function createOverlayIcon(messageCount) {
function createOverlayIcon(messageCount: number): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.height = 128;
canvas.width = 128;
@@ -724,10 +871,18 @@ class ServerManagerView {
ipcRenderer.on('open-feedback-modal', () => {
feedbackHolder.classList.add('show');
});
ipcRenderer.on('copy-zulip-url', () => {
clipboard.writeText(this.getCurrentActiveServer());
});
ipcRenderer.on('new-server', () => {
this.openSettings('AddServer');
});
}
}
window.onload = () => {
window.addEventListener('load', () => {
const serverManagerView = new ServerManagerView();
const reconnectUtil = new ReconnectUtil(serverManagerView);
serverManagerView.init();
@@ -746,7 +901,8 @@ window.onload = () => {
// `--no-electron-connect`
const mainProcessArgv = remote.getGlobal('process').argv;
if (isDev && !mainProcessArgv.includes('--no-electron-connect')) {
const electronConnect = require('electron-connect');
electronConnect.client.create();
require('electron-connect').client.create();
}
};
});
export = new ServerManagerView();

View File

@@ -1,18 +1,27 @@
'use strict';
const { ipcRenderer } = require('electron');
const url = require('url');
const MacNotifier = require('node-mac-notifier');
const ConfigUtil = require('../utils/config-util');
const {
import { ipcRenderer } from 'electron';
import {
appId, customReply, focusCurrentServer, parseReply, setupReply
} = require('./helpers');
} from './helpers';
import url = require('url');
import MacNotifier = require('node-mac-notifier');
import ConfigUtil = require('../utils/config-util');
type ReplyHandler = (response: string) => void;
type ClickHandler = () => void;
let replyHandler: ReplyHandler;
let clickHandler: ClickHandler;
interface NotificationHandlerArgs {
response: string;
}
let replyHandler;
let clickHandler;
class DarwinNotification {
constructor(title, opts) {
const silent = ConfigUtil.getConfigItem('silent') || false;
tag: string;
constructor(title: string, opts: NotificationOptions) {
const silent: boolean = ConfigUtil.getConfigItem('silent') || false;
const { host, protocol } = location;
const { icon } = opts;
const profilePic = url.resolve(`${protocol}//${host}`, icon);
@@ -39,45 +48,45 @@ class DarwinNotification {
notification.addEventListener('reply', this.notificationHandler);
}
static requestPermission() {
static requestPermission(): void {
return; // eslint-disable-line no-useless-return
}
// Override default Notification permission
static get permission() {
static get permission(): NotificationPermission {
return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied';
}
set onreply(handler) {
set onreply(handler: ReplyHandler) {
replyHandler = handler;
}
get onreply() {
get onreply(): ReplyHandler {
return replyHandler;
}
set onclick(handler) {
set onclick(handler: ClickHandler) {
clickHandler = handler;
}
get onclick() {
get onclick(): ClickHandler {
return clickHandler;
}
// not something that is common or
// used by zulip server but added to be
// future proff.
addEventListener(event, handler) {
addEventListener(event: string, handler: ClickHandler | ReplyHandler): void {
if (event === 'click') {
clickHandler = handler;
clickHandler = handler as ClickHandler;
}
if (event === 'reply') {
replyHandler = handler;
replyHandler = handler as ReplyHandler;
}
}
notificationHandler({ response }) {
notificationHandler({ response }: NotificationHandlerArgs): void {
response = parseReply(response);
focusCurrentServer();
setupReply(this.tag);
@@ -92,7 +101,7 @@ class DarwinNotification {
// method specific to notification api
// used by zulip
close() {
close(): void {
return; // eslint-disable-line no-useless-return
}
}

View File

@@ -1,12 +1,13 @@
'use strict';
const { ipcRenderer } = require('electron');
const ConfigUtil = require('../utils/config-util');
const { focusCurrentServer } = require('./helpers');
import { ipcRenderer } from 'electron';
import { focusCurrentServer } from './helpers';
import ConfigUtil = require('../utils/config-util');
const NativeNotification = window.Notification;
class BaseNotification extends NativeNotification {
constructor(title, opts) {
constructor(title: string, opts: NotificationOptions) {
opts.silent = true;
super(title, opts);
@@ -18,14 +19,14 @@ class BaseNotification extends NativeNotification {
});
}
static requestPermission() {
static requestPermission(): void {
return; // eslint-disable-line no-useless-return
}
// Override default Notification permission
static get permission() {
static get permission(): NotificationPermission {
return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied';
}
}
module.exports = BaseNotification;
export = BaseNotification;

View File

@@ -1,5 +1,6 @@
const { remote } = require('electron');
const Logger = require('../utils/logger-util.js');
import { remote } from 'electron';
import Logger = require('../utils/logger-util');
const logger = new Logger({
file: 'errors.log',
@@ -7,24 +8,25 @@ const logger = new Logger({
});
// Do not change this
const appId = 'org.zulip.zulip-electron';
export const appId = 'org.zulip.zulip-electron';
const botsList = [];
export type BotListItem = [string, string];
const botsList: BotListItem[] = [];
let botsListLoaded = false;
// this function load list of bots from the server
// sync=True for a synchronous getJSON request
// in case botsList isn't already completely loaded when required in parseRely
function loadBots(sync = false) {
export function loadBots(sync = false): void {
const { $ } = window;
botsList.length = 0;
if (sync) {
$.ajaxSetup({async: false});
}
$.getJSON('/json/users')
.done(data => {
const members = data.members;
members.forEach(membersRow => {
.done((data: any) => {
const { members } = data;
members.forEach((membersRow: any) => {
if (membersRow.is_bot) {
const bot = `@${membersRow.full_name}`;
const mention = `@**${bot.replace(/^@/, '')}**`;
@@ -33,7 +35,7 @@ function loadBots(sync = false) {
});
botsListLoaded = true;
})
.fail(error => {
.fail((error: any) => {
logger.log('Load bots request failed: ', error.responseText);
logger.log('Load bots request status: ', error.statusText);
});
@@ -42,7 +44,7 @@ function loadBots(sync = false) {
}
}
function checkElements(...elements) {
export function checkElements(...elements: any[]): boolean {
let status = true;
elements.forEach(element => {
if (element === null || element === undefined) {
@@ -52,13 +54,13 @@ function checkElements(...elements) {
return status;
}
function customReply(reply) {
export function customReply(reply: string): void {
// server does not support notification reply yet.
const buttonSelector = '.messagebox #send_controls button[type=submit]';
const messageboxSelector = '.selected_message .messagebox .messagebox-border .messagebox-content';
const textarea = document.querySelector('#compose-textarea');
const messagebox = document.querySelector(messageboxSelector);
const sendButton = document.querySelector(buttonSelector);
const textarea: HTMLInputElement = document.querySelector('#compose-textarea');
const messagebox: HTMLButtonElement = document.querySelector(messageboxSelector);
const sendButton: HTMLButtonElement = document.querySelector(buttonSelector);
// sanity check for old server versions
const elementsExists = checkElements(textarea, messagebox, sendButton);
@@ -77,19 +79,24 @@ const webContentsId = webContents.id;
// this function will focus the server that sent
// the notification. Main function implemented in main.js
function focusCurrentServer() {
currentWindow.send('focus-webview-with-id', webContentsId);
export function focusCurrentServer(): void {
// TODO: TypeScript: currentWindow of type BrowserWindow doesn't
// have a .send() property per typescript.
(currentWindow as any).send('focus-webview-with-id', webContentsId);
}
// this function parses the reply from to notification
// making it easier to reply from notification eg
// @username in reply will be converted to @**username**
// #stream in reply will be converted to #**stream**
// bot mentions are not yet supported
function parseReply(reply) {
export function parseReply(reply: string): string {
const usersDiv = document.querySelectorAll('#user_presences li');
const streamHolder = document.querySelectorAll('#stream_filters li');
const users = [];
const streams = [];
type UsersItem = BotListItem;
type StreamsItem = BotListItem;
const users: UsersItem[] = [];
const streams: StreamsItem[] = [];
usersDiv.forEach(userRow => {
const anchor = userRow.querySelector('span a');
@@ -139,18 +146,8 @@ function parseReply(reply) {
return reply;
}
function setupReply(id) {
export function setupReply(id: string): void {
const { narrow } = window;
const narrowByTopic = narrow.by_topic || narrow.by_subject;
narrowByTopic(id, { trigger: 'notification' });
}
module.exports = {
appId,
checkElements,
customReply,
parseReply,
setupReply,
focusCurrentServer,
loadBots
};

View File

@@ -1,12 +1,11 @@
'use strict';
const {
remote: { app }
} = require('electron');
import { remote } from 'electron';
import * as params from '../utils/params-util';
import { appId, loadBots } from './helpers';
const params = require('../utils/params-util.js');
const DefaultNotification = require('./default-notification');
const { appId, loadBots } = require('./helpers');
import DefaultNotification = require('./default-notification');
const { app } = remote;
// From https://github.com/felixrieseberg/electron-windows-notifications#appusermodelid
// On windows 8 we have to explicitly set the appUserModelId otherwise notification won't work.
@@ -15,12 +14,11 @@ app.setAppUserModelId(appId);
window.Notification = DefaultNotification;
if (process.platform === 'darwin') {
const DarwinNotification = require('./darwin-notifications');
window.Notification = DarwinNotification;
window.Notification = require('./darwin-notifications');
}
window.addEventListener('load', () => {
// eslint-disable-next-line no-undef, camelcase
// eslint-disable-next-line no-undef, @typescript-eslint/camelcase
if (params.isPageParams() && page_params.realm_uri) {
loadBots();
}

View File

@@ -1,20 +1,21 @@
'use strict';
const {ipcRenderer} = require('electron');
import { ipcRenderer } from 'electron';
class NetworkTroubleshootingView {
$reconnectButton: Element;
constructor() {
this.$reconnectButton = document.getElementById('reconnect');
this.$reconnectButton = document.querySelector('#reconnect');
}
init() {
init(): void {
this.$reconnectButton.addEventListener('click', () => {
ipcRenderer.send('forward-message', 'reload-viewer');
});
}
}
window.onload = () => {
window.addEventListener('load', () => {
const networkTroubleshootingView = new NetworkTroubleshootingView();
networkTroubleshootingView.init();
};
});

View File

@@ -1,20 +1,28 @@
'use-strict';
const { dialog } = require('electron').remote;
const path = require('path');
import { remote, OpenDialogOptions } from 'electron';
const BaseComponent = require(__dirname + '/../../components/base.js');
const CertificateUtil = require(__dirname + '/../../utils/certificate-util.js');
const DomainUtil = require(__dirname + '/../../utils/domain-util.js');
import path = require('path');
import BaseComponent = require('../../components/base');
import CertificateUtil = require('../../utils/certificate-util');
import DomainUtil = require('../../utils/domain-util');
const { dialog } = remote;
class AddCertificate extends BaseComponent {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
_certFile: string;
$addCertificate: Element | null;
addCertificateButton: Element | null;
serverUrl: HTMLInputElement | null;
constructor(props: any) {
super();
this.props = props;
this._certFile = '';
}
template() {
template(): string {
return `
<div class="settings-card certificates-card">
<div class="certificate-input">
@@ -29,15 +37,15 @@ class AddCertificate extends BaseComponent {
`;
}
init() {
init(): void {
this.$addCertificate = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$addCertificate);
this.props.$root.append(this.$addCertificate);
this.addCertificateButton = this.$addCertificate.querySelector('#add-certificate-button');
this.serverUrl = this.$addCertificate.querySelectorAll('input.setting-input-value')[0];
this.serverUrl = this.$addCertificate.querySelectorAll('input.setting-input-value')[0] as HTMLInputElement;
this.initListeners();
}
validateAndAdd() {
validateAndAdd(): void {
const certificate = this._certFile;
const serverUrl = this.serverUrl.value;
if (certificate !== '' && serverUrl !== '') {
@@ -55,14 +63,13 @@ class AddCertificate extends BaseComponent {
this.serverUrl.value = '';
} else {
dialog.showErrorBox('Error', `Please, ${serverUrl === '' ?
'Enter an Organization URL' : 'Choose certificate file'}`);
'Enter an Organization URL' : 'Choose certificate file'}`);
}
}
addHandler() {
const showDialogOptions = {
addHandler(): void {
const showDialogOptions: OpenDialogOptions = {
title: 'Select file',
defaultId: 1,
properties: ['openFile'],
filters: [{ name: 'crt, pem', extensions: ['crt', 'pem'] }]
};
@@ -74,7 +81,7 @@ class AddCertificate extends BaseComponent {
});
}
initListeners() {
initListeners(): void {
this.addCertificateButton.addEventListener('click', () => {
this.addHandler();
});
@@ -89,4 +96,4 @@ class AddCertificate extends BaseComponent {
}
}
module.exports = AddCertificate;
export = AddCertificate;

View File

@@ -1,10 +1,10 @@
'use strict';
const electron = require('electron');
const { app } = require('electron');
import { app } from 'electron';
const ConfigUtil = require(__dirname + '/../../utils/config-util.js');
import electron = require('electron');
import ConfigUtil = require('../../utils/config-util');
let instance = null;
let instance: BadgeSettings | any = null;
class BadgeSettings {
constructor() {
@@ -17,7 +17,7 @@ class BadgeSettings {
return instance;
}
showBadgeCount(messageCount, mainWindow) {
showBadgeCount(messageCount: number, mainWindow: electron.BrowserWindow): void {
if (process.platform === 'darwin') {
app.setBadgeCount(messageCount);
}
@@ -26,7 +26,7 @@ class BadgeSettings {
}
}
hideBadgeCount(mainWindow) {
hideBadgeCount(mainWindow: electron.BrowserWindow): void {
if (process.platform === 'darwin') {
app.setBadgeCount(0);
}
@@ -35,7 +35,7 @@ class BadgeSettings {
}
}
updateBadge(badgeCount, mainWindow) {
updateBadge(badgeCount: number, mainWindow: electron.BrowserWindow): void {
if (ConfigUtil.getConfigItem('badgeOption', true)) {
this.showBadgeCount(badgeCount, mainWindow);
} else {
@@ -43,7 +43,7 @@ class BadgeSettings {
}
}
updateOverlayIcon(messageCount, mainWindow) {
updateOverlayIcon(messageCount: number, mainWindow: electron.BrowserWindow): void {
if (!mainWindow.isFocused()) {
mainWindow.flashFrame(ConfigUtil.getConfigItem('flashTaskbarOnMessage'));
}
@@ -54,10 +54,10 @@ class BadgeSettings {
}
}
updateTaskbarIcon(data, text, mainWindow) {
updateTaskbarIcon(data: string, text: string, mainWindow: electron.BrowserWindow): void {
const img = electron.nativeImage.createFromDataURL(data);
mainWindow.setOverlayIcon(img, text);
}
}
module.exports = new BadgeSettings();
export = new BadgeSettings();

View File

@@ -1,22 +1,23 @@
'use strict';
const {ipcRenderer} = require('electron');
import { ipcRenderer } from 'electron';
const BaseComponent = require(__dirname + '/../../components/base.js');
import BaseComponent = require('../../components/base');
class BaseSection extends BaseComponent {
generateSettingOption(props) {
// TODO: TypeScript - Here props should be object type
generateSettingOption(props: any): void {
const {$element, value, clickHandler} = props;
$element.innerHTML = '';
const $optionControl = this.generateNodeFromTemplate(this.generateOptionTemplate(value));
$element.appendChild($optionControl);
$element.append($optionControl);
$optionControl.addEventListener('click', clickHandler);
}
generateOptionTemplate(settingOption) {
generateOptionTemplate(settingOption: boolean): string {
if (settingOption) {
return `
<div class="action">
@@ -38,9 +39,9 @@ class BaseSection extends BaseComponent {
}
}
reloadApp() {
reloadApp(): void {
ipcRenderer.send('forward-message', 'reload-viewer');
}
}
module.exports = BaseSection;
export = BaseSection;

View File

@@ -1,17 +1,27 @@
'use strict';
const BaseSection = require(__dirname + '/base-section.js');
const DomainUtil = require(__dirname + '/../../utils/domain-util.js');
const ServerInfoForm = require(__dirname + '/server-info-form.js');
const AddCertificate = require(__dirname + '/add-certificate.js');
import { ipcRenderer } from 'electron';
import BaseSection = require('./base-section');
import DomainUtil = require('../../utils/domain-util');
import ServerInfoForm = require('./server-info-form');
import AddCertificate = require('./add-certificate');
import FindAccounts = require('./find-accounts');
class ConnectedOrgSection extends BaseSection {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
$serverInfoContainer: Element | null;
$existingServers: Element | null;
$newOrgButton: HTMLButtonElement | null;
$addCertificateContainer: Element | null;
$findAccountsContainer: Element | null;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="settings-pane" id="server-settings-pane">
<div class="page-title">Connected organizations</div>
@@ -20,24 +30,27 @@ class ConnectedOrgSection extends BaseSection {
<div id="new-org-button"><button class="green sea w-250">Connect to another organization</button></div>
<div class="page-title">Add Custom Certificates</div>
<div id="add-certificate-container"></div>
<div class="page-title">Find accounts by email</div>
<div id="find-accounts-container"></div>
</div>
`;
}
init() {
init(): void {
this.initServers();
}
initServers() {
initServers(): void {
this.props.$root.innerHTML = '';
const servers = DomainUtil.getDomains();
this.props.$root.innerHTML = this.template();
this.$serverInfoContainer = document.getElementById('server-info-container');
this.$existingServers = document.getElementById('existing-servers');
this.$newOrgButton = document.getElementById('new-org-button');
this.$addCertificateContainer = document.getElementById('add-certificate-container');
this.$serverInfoContainer = document.querySelector('#server-info-container');
this.$existingServers = document.querySelector('#existing-servers');
this.$newOrgButton = document.querySelector('#new-org-button');
this.$addCertificateContainer = document.querySelector('#add-certificate-container');
this.$findAccountsContainer = document.querySelector('#find-accounts-container');
const noServerText = 'All the connected orgnizations will appear here';
// Show noServerText if no servers are there otherwise hide it
@@ -53,20 +66,24 @@ class ConnectedOrgSection extends BaseSection {
}
this.$newOrgButton.addEventListener('click', () => {
// We don't need to import this since it's already imported in other files
// eslint-disable-next-line no-undef
ipcRenderer.send('forward-message', 'open-org-tab');
});
this.initAddCertificate();
this.initFindAccounts();
}
initAddCertificate() {
initAddCertificate(): void {
new AddCertificate({
$root: this.$addCertificateContainer
}).init();
}
initFindAccounts(): void {
new FindAccounts({
$root: this.$findAccountsContainer
}).init();
}
}
module.exports = ConnectedOrgSection;
export = ConnectedOrgSection;

View File

@@ -0,0 +1,77 @@
'use-strict';
import { shell } from 'electron';
import BaseComponent = require('../../components/base');
class FindAccounts extends BaseComponent {
// TODO: TypeScript - Here props should be object type
props: any;
$findAccounts: Element | null;
$findAccountsButton: Element | null;
$serverUrlField: HTMLInputElement | null;
constructor(props: any) {
super();
this.props = props;
}
template(): string {
return `
<div class="settings-card certificate-card">
<div class="certificate-input">
<div>Organization URL</div>
<input class="setting-input-value" value="zulipchat.com"/>
</div>
<div class="certificate-input">
<button class="green w-150" id="find-accounts-button">Find accounts</button>
</div>
</div>
`;
}
init(): void {
this.$findAccounts = this.generateNodeFromTemplate(this.template());
this.props.$root.append(this.$findAccounts);
this.$findAccountsButton = this.$findAccounts.querySelector('#find-accounts-button');
this.$serverUrlField = this.$findAccounts.querySelectorAll('input.setting-input-value')[0] as HTMLInputElement;
this.initListeners();
}
findAccounts(url: string): void {
if (!url) {
return;
}
if (!url.startsWith('http')) {
url = 'https://' + url;
}
shell.openExternal(url + '/accounts/find');
}
initListeners(): void {
this.$findAccountsButton.addEventListener('click', () => {
this.findAccounts(this.$serverUrlField.value);
});
this.$serverUrlField.addEventListener('click', () => {
if (this.$serverUrlField.value === 'zulipchat.com') {
this.$serverUrlField.setSelectionRange(0, 0);
}
});
this.$serverUrlField.addEventListener('keypress', event => {
if (event.keyCode === 13) {
this.findAccounts(this.$serverUrlField.value);
}
});
this.$serverUrlField.addEventListener('input', () => {
if (this.$serverUrlField.value) {
this.$serverUrlField.classList.remove('invalid-input-value');
} else {
this.$serverUrlField.classList.add('invalid-input-value');
}
});
}
}
export = FindAccounts;

View File

@@ -1,20 +1,24 @@
'use strict';
const path = require('path');
const { ipcRenderer, remote } = require('electron');
const fs = require('fs-extra');
import { ipcRenderer, remote, OpenDialogOptions } from 'electron';
import path = require('path');
import fs = require('fs-extra');
const { app, dialog } = remote;
const currentBrowserWindow = remote.getCurrentWindow();
const BaseSection = require(__dirname + '/base-section.js');
const ConfigUtil = require(__dirname + '/../../utils/config-util.js');
import BaseSection = require('./base-section');
import ConfigUtil = require('../../utils/config-util');
class GeneralSection extends BaseSection {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="settings-pane">
<div class="title">Appearance</div>
@@ -24,7 +28,7 @@ class GeneralSection extends BaseSection {
<div class="setting-control"></div>
</div>
<div class="setting-row" id="menubar-option" style= "display:${process.platform === 'darwin' ? 'none' : ''}">
<div class="setting-description">Auto hide Menubar (Press Alt key to display)</div>
<div class="setting-description">Auto hide menu bar (Press Alt key to display)</div>
<div class="setting-control"></div>
</div>
<div class="setting-row" id="sidebar-option">
@@ -47,7 +51,7 @@ class GeneralSection extends BaseSection {
<div class="title">Desktop Notifications</div>
<div class="settings-card">
<div class="setting-row" id="show-notification-option">
<div class="setting-description">Show Desktop Notifications</div>
<div class="setting-description">Show desktop notifications</div>
<div class="setting-control"></div>
</div>
<div class="setting-row" id="silent-option">
@@ -83,6 +87,10 @@ class GeneralSection extends BaseSection {
</div>
<div class="title">Advanced</div>
<div class="settings-card">
<div class="setting-row" id="enable-error-reporting">
<div class="setting-description">Enable error reporting (requires restart)</div>
<div class="setting-control"></div>
</div>
<div class="setting-row" id="show-download-folder">
<div class="setting-description">Show downloaded files in file manager</div>
<div class="setting-control"></div>
@@ -120,14 +128,14 @@ class GeneralSection extends BaseSection {
<div class="setting-row" id="resetdata-option">
<div class="setting-description">This will delete all application data including all added accounts and preferences
</div>
<button class="reset-data-button green w-150">Reset App Data</button>
<button class="reset-data-button red w-150">Reset App Data</button>
</div>
</div>
</div>
`;
}
init() {
init(): void {
this.props.$root.innerHTML = this.template();
this.updateTrayOption();
this.updateBadgeOption();
@@ -145,6 +153,7 @@ class GeneralSection extends BaseSection {
this.removeCustomCSS();
this.downloadFolder();
this.showDownloadFolder();
this.enableErrorReporting();
// Platform specific settings
@@ -163,7 +172,7 @@ class GeneralSection extends BaseSection {
}
}
updateTrayOption() {
updateTrayOption(): void {
this.generateSettingOption({
$element: document.querySelector('#tray-option .setting-control'),
value: ConfigUtil.getConfigItem('trayIcon', true),
@@ -176,7 +185,7 @@ class GeneralSection extends BaseSection {
});
}
updateMenubarOption() {
updateMenubarOption(): void {
this.generateSettingOption({
$element: document.querySelector('#menubar-option .setting-control'),
value: ConfigUtil.getConfigItem('autoHideMenubar', false),
@@ -189,7 +198,7 @@ class GeneralSection extends BaseSection {
});
}
updateBadgeOption() {
updateBadgeOption(): void {
this.generateSettingOption({
$element: document.querySelector('#badge-option .setting-control'),
value: ConfigUtil.getConfigItem('badgeOption', true),
@@ -202,7 +211,7 @@ class GeneralSection extends BaseSection {
});
}
updateDockBouncing() {
updateDockBouncing(): void {
this.generateSettingOption({
$element: document.querySelector('#dock-bounce-option .setting-control'),
value: ConfigUtil.getConfigItem('dockBouncing', true),
@@ -214,7 +223,7 @@ class GeneralSection extends BaseSection {
});
}
updateFlashTaskbar() {
updateFlashTaskbar(): void {
this.generateSettingOption({
$element: document.querySelector('#flash-taskbar-option .setting-control'),
value: ConfigUtil.getConfigItem('flashTaskbarOnMessage', true),
@@ -226,7 +235,7 @@ class GeneralSection extends BaseSection {
});
}
autoUpdateOption() {
autoUpdateOption(): void {
this.generateSettingOption({
$element: document.querySelector('#autoupdate-option .setting-control'),
value: ConfigUtil.getConfigItem('autoUpdate', true),
@@ -242,7 +251,7 @@ class GeneralSection extends BaseSection {
});
}
betaUpdateOption() {
betaUpdateOption(): void {
this.generateSettingOption({
$element: document.querySelector('#betaupdate-option .setting-control'),
value: ConfigUtil.getConfigItem('betaUpdate', false),
@@ -256,7 +265,7 @@ class GeneralSection extends BaseSection {
});
}
updateSilentOption() {
updateSilentOption(): void {
this.generateSettingOption({
$element: document.querySelector('#silent-option .setting-control'),
value: ConfigUtil.getConfigItem('silent', false),
@@ -264,12 +273,14 @@ class GeneralSection extends BaseSection {
const newValue = !ConfigUtil.getConfigItem('silent', true);
ConfigUtil.setConfigItem('silent', newValue);
this.updateSilentOption();
currentBrowserWindow.send('toggle-silent', newValue);
// TODO: TypeScript: currentWindow of type BrowserWindow doesn't
// have a .send() property per typescript.
(currentBrowserWindow as any).send('toggle-silent', newValue);
}
});
}
showDesktopNotification() {
showDesktopNotification(): void {
this.generateSettingOption({
$element: document.querySelector('#show-notification-option .setting-control'),
value: ConfigUtil.getConfigItem('showNotification', true),
@@ -281,7 +292,7 @@ class GeneralSection extends BaseSection {
});
}
updateSidebarOption() {
updateSidebarOption(): void {
this.generateSettingOption({
$element: document.querySelector('#sidebar-option .setting-control'),
value: ConfigUtil.getConfigItem('showSidebar', true),
@@ -294,7 +305,7 @@ class GeneralSection extends BaseSection {
});
}
updateStartAtLoginOption() {
updateStartAtLoginOption(): void {
this.generateSettingOption({
$element: document.querySelector('#startAtLogin-option .setting-control'),
value: ConfigUtil.getConfigItem('startAtLogin', false),
@@ -307,7 +318,7 @@ class GeneralSection extends BaseSection {
});
}
enableSpellchecker() {
enableSpellchecker(): void {
this.generateSettingOption({
$element: document.querySelector('#enable-spellchecker-option .setting-control'),
value: ConfigUtil.getConfigItem('enableSpellchecker', true),
@@ -319,7 +330,19 @@ class GeneralSection extends BaseSection {
});
}
clearAppDataDialog() {
enableErrorReporting(): void {
this.generateSettingOption({
$element: document.querySelector('#enable-error-reporting .setting-control'),
value: ConfigUtil.getConfigItem('errorReporting', true),
clickHandler: () => {
const newValue = !ConfigUtil.getConfigItem('errorReporting');
ConfigUtil.setConfigItem('errorReporting', newValue);
this.enableErrorReporting();
}
});
}
clearAppDataDialog(): void {
const clearAppDataMessage = 'By clicking proceed you will be removing all added accounts and preferences from Zulip. When the application restarts, it will be as if you are starting Zulip for the first time.';
const getAppPath = path.join(app.getPath('appData'), app.getName());
@@ -337,10 +360,9 @@ class GeneralSection extends BaseSection {
});
}
customCssDialog() {
const showDialogOptions = {
customCssDialog(): void {
const showDialogOptions: OpenDialogOptions = {
title: 'Select file',
defaultId: 1,
properties: ['openFile'],
filters: [{ name: 'CSS file', extensions: ['css'] }]
};
@@ -353,14 +375,14 @@ class GeneralSection extends BaseSection {
});
}
updateResetDataOption() {
updateResetDataOption(): void {
const resetDataButton = document.querySelector('#resetdata-option .reset-data-button');
resetDataButton.addEventListener('click', () => {
this.clearAppDataDialog();
});
}
minimizeOnStart() {
minimizeOnStart(): void {
this.generateSettingOption({
$element: document.querySelector('#start-minimize-option .setting-control'),
value: ConfigUtil.getConfigItem('startMinimized', false),
@@ -372,51 +394,50 @@ class GeneralSection extends BaseSection {
});
}
addCustomCSS() {
addCustomCSS(): void {
const customCSSButton = document.querySelector('#add-custom-css .custom-css-button');
customCSSButton.addEventListener('click', () => {
this.customCssDialog();
});
}
showCustomCSSPath() {
showCustomCSSPath(): void {
if (!ConfigUtil.getConfigItem('customCSS')) {
const cssPATH = document.getElementById('remove-custom-css');
const cssPATH: HTMLElement = document.querySelector('#remove-custom-css');
cssPATH.style.display = 'none';
}
}
removeCustomCSS() {
const removeCSSButton = document.getElementById('css-delete-action');
removeCustomCSS(): void {
const removeCSSButton = document.querySelector('#css-delete-action');
removeCSSButton.addEventListener('click', () => {
ConfigUtil.setConfigItem('customCSS');
ConfigUtil.setConfigItem('customCSS', "");
ipcRenderer.send('forward-message', 'hard-reload');
});
}
downloadFolderDialog() {
const showDialogOptions = {
downloadFolderDialog(): void {
const showDialogOptions: OpenDialogOptions = {
title: 'Select Download Location',
defaultId: 1,
properties: ['openDirectory']
};
dialog.showOpenDialog(showDialogOptions, selectedFolder => {
if (selectedFolder) {
ConfigUtil.setConfigItem('downloadsPath', selectedFolder[0]);
const downloadFolderPath = document.querySelector('.download-folder-path');
const downloadFolderPath: HTMLElement = document.querySelector('.download-folder-path');
downloadFolderPath.innerText = selectedFolder[0];
}
});
}
downloadFolder() {
downloadFolder(): void {
const downloadFolder = document.querySelector('#download-folder .download-folder-button');
downloadFolder.addEventListener('click', () => {
this.downloadFolderDialog();
});
}
showDownloadFolder() {
showDownloadFolder(): void {
this.generateSettingOption({
$element: document.querySelector('#show-download-folder .setting-control'),
value: ConfigUtil.getConfigItem('showDownloadFolder', false),
@@ -427,7 +448,6 @@ class GeneralSection extends BaseSection {
}
});
}
}
module.exports = GeneralSection;
export = GeneralSection;

View File

@@ -1,19 +1,20 @@
'use strict';
const BaseComponent = require(__dirname + '/../../components/base.js');
import BaseComponent = require('../../components/base');
class PreferenceNav extends BaseComponent {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
navItems: string[];
$el: Element;
constructor(props: any) {
super();
this.props = props;
this.navItems = ['General', 'Network', 'AddServer', 'Organizations', 'Shortcuts'];
this.init();
}
template() {
template(): string {
let navItemsTemplate = '';
for (const navItem of this.navItems) {
navItemsTemplate += `<div class="nav" id="nav-${navItem}">${navItem}</div>`;
@@ -27,23 +28,22 @@ class PreferenceNav extends BaseComponent {
`;
}
init() {
init(): void {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$el);
this.props.$root.append(this.$el);
this.registerListeners();
}
registerListeners() {
registerListeners(): void {
for (const navItem of this.navItems) {
const $item = document.getElementById(`nav-${navItem}`);
const $item = document.querySelector(`#nav-${navItem}`);
$item.addEventListener('click', () => {
this.props.onItemSelected(navItem);
});
}
}
select(navItemToSelect) {
select(navItemToSelect: string): void {
for (const navItem of this.navItems) {
if (navItem === navItemToSelect) {
this.activate(navItem);
@@ -53,15 +53,15 @@ class PreferenceNav extends BaseComponent {
}
}
activate(navItem) {
const $item = document.getElementById(`nav-${navItem}`);
activate(navItem: string): void {
const $item = document.querySelector(`#nav-${navItem}`);
$item.classList.add('active');
}
deactivate(navItem) {
const $item = document.getElementById(`nav-${navItem}`);
deactivate(navItem: string): void {
const $item = document.querySelector(`#nav-${navItem}`);
$item.classList.remove('active');
}
}
module.exports = PreferenceNav;
export = PreferenceNav;

View File

@@ -1,17 +1,24 @@
'use strict';
const {ipcRenderer} = require('electron');
import { ipcRenderer } from 'electron';
const BaseSection = require(__dirname + '/base-section.js');
const ConfigUtil = require(__dirname + '/../../utils/config-util.js');
import BaseSection = require('./base-section');
import ConfigUtil = require('../../utils/config-util');
class NetworkSection extends BaseSection {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
$proxyPAC: HTMLInputElement;
$proxyRules: HTMLInputElement;
$proxyBypass: HTMLInputElement;
$proxySaveAction: Element;
$manualProxyBlock: Element;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="settings-pane">
<div class="title">Proxy</div>
@@ -48,12 +55,12 @@ class NetworkSection extends BaseSection {
`;
}
init() {
init(): void {
this.props.$root.innerHTML = this.template();
this.$proxyPAC = document.querySelector('#proxy-pac-option .setting-input-value');
this.$proxyRules = document.querySelector('#proxy-rules-option .setting-input-value');
this.$proxyBypass = document.querySelector('#proxy-bypass-option .setting-input-value');
this.$proxySaveAction = document.getElementById('proxy-save-action');
this.$proxySaveAction = document.querySelector('#proxy-save-action');
this.$manualProxyBlock = this.props.$root.querySelector('.manual-proxy-block');
this.initProxyOption();
@@ -70,14 +77,14 @@ class NetworkSection extends BaseSection {
});
}
initProxyOption() {
initProxyOption(): void {
const manualProxyEnabled = ConfigUtil.getConfigItem('useManualProxy', false);
this.toggleManualProxySettings(manualProxyEnabled);
this.updateProxyOption();
}
toggleManualProxySettings(option) {
toggleManualProxySettings(option: boolean): void {
if (option) {
this.$manualProxyBlock.classList.remove('hidden');
} else {
@@ -85,7 +92,7 @@ class NetworkSection extends BaseSection {
}
}
updateProxyOption() {
updateProxyOption(): void {
this.generateSettingOption({
$element: document.querySelector('#use-system-settings .setting-control'),
value: ConfigUtil.getConfigItem('useSystemProxy', false),
@@ -125,4 +132,4 @@ class NetworkSection extends BaseSection {
}
}
module.exports = NetworkSection;
export = NetworkSection;

View File

@@ -1,16 +1,22 @@
'use strict';
const BaseComponent = require(__dirname + '/../../components/base.js');
const DomainUtil = require(__dirname + '/../../utils/domain-util.js');
const shell = require('electron').shell;
import { shell } from 'electron';
import BaseComponent = require('../../components/base');
import DomainUtil = require('../../utils/domain-util');
class NewServerForm extends BaseComponent {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
$newServerForm: Element;
$saveServerButton: HTMLButtonElement;
$newServerUrl: HTMLInputElement;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="server-input-container">
<div class="title">Organization URL</div>
@@ -36,21 +42,20 @@ class NewServerForm extends BaseComponent {
`;
}
init() {
init(): void {
this.initForm();
this.initActions();
}
initForm() {
initForm(): void {
this.$newServerForm = this.generateNodeFromTemplate(this.template());
this.$saveServerButton = this.$newServerForm.getElementsByClassName('server-save-action')[0];
this.$saveServerButton = this.$newServerForm.querySelectorAll('.server-save-action')[0] as HTMLButtonElement;
this.props.$root.innerHTML = '';
this.props.$root.appendChild(this.$newServerForm);
this.$newServerUrl = this.$newServerForm.querySelectorAll('input.setting-input-value')[0];
this.props.$root.append(this.$newServerForm);
this.$newServerUrl = this.$newServerForm.querySelectorAll('input.setting-input-value')[0] as HTMLInputElement;
}
submitFormHandler() {
submitFormHandler(): void {
this.$saveServerButton.children[0].innerHTML = 'Connecting...';
DomainUtil.checkDomain(this.$newServerUrl.value).then(serverConf => {
DomainUtil.addDomain(serverConf).then(() => {
@@ -62,15 +67,15 @@ class NewServerForm extends BaseComponent {
});
}
openCreateNewOrgExternalLink() {
openCreateNewOrgExternalLink(): void {
const link = 'https://zulipchat.com/new/';
const externalCreateNewOrgEl = document.getElementById('open-create-org-link');
const externalCreateNewOrgEl = document.querySelector('#open-create-org-link');
externalCreateNewOrgEl.addEventListener('click', () => {
shell.openExternal(link);
});
}
initActions() {
initActions(): void {
this.$saveServerButton.addEventListener('click', () => {
this.submitFormHandler();
});
@@ -86,4 +91,4 @@ class NewServerForm extends BaseComponent {
}
}
module.exports = NewServerForm;
export = NewServerForm;

View File

@@ -1,24 +1,29 @@
'use strict';
const BaseComponent = require(__dirname + '/js/components/base.js');
const { ipcRenderer } = require('electron');
import { ipcRenderer } from 'electron';
const Nav = require(__dirname + '/js/pages/preference/nav.js');
const ServersSection = require(__dirname + '/js/pages/preference/servers-section.js');
const GeneralSection = require(__dirname + '/js/pages/preference/general-section.js');
const NetworkSection = require(__dirname + '/js/pages/preference/network-section.js');
const ConnectedOrgSection = require(__dirname + '/js/pages/preference/connected-org-section.js');
const ShortcutsSection = require(__dirname + '/js/pages/preference/shortcuts-section.js');
import BaseComponent = require('../../components/base');
import Nav = require('./nav');
import ServersSection = require('./servers-section');
import GeneralSection = require('./general-section');
import NetworkSection = require('./network-section');
import ConnectedOrgSection = require('./connected-org-section');
import ShortcutsSection = require('./shortcuts-section');
type Section = ServersSection | GeneralSection | NetworkSection | ConnectedOrgSection | ShortcutsSection;
class PreferenceView extends BaseComponent {
$sidebarContainer: Element;
$settingsContainer: Element;
nav: Nav;
section: Section;
constructor() {
super();
this.$sidebarContainer = document.getElementById('sidebar');
this.$settingsContainer = document.getElementById('settings-container');
this.$sidebarContainer = document.querySelector('#sidebar');
this.$settingsContainer = document.querySelector('#settings-container');
}
init() {
init(): void {
this.nav = new Nav({
$root: this.$sidebarContainer,
onItemSelected: this.handleNavigation.bind(this)
@@ -28,7 +33,7 @@ class PreferenceView extends BaseComponent {
this.registerIpcs();
}
setDefaultView() {
setDefaultView(): void {
let nav = 'General';
const hasTag = window.location.hash;
if (hasTag) {
@@ -37,7 +42,7 @@ class PreferenceView extends BaseComponent {
this.handleNavigation(nav);
}
handleNavigation(navItem) {
handleNavigation(navItem: string): void {
this.nav.select(navItem);
switch (navItem) {
case 'AddServer': {
@@ -77,28 +82,32 @@ class PreferenceView extends BaseComponent {
}
// Handle toggling and reflect changes in preference page
handleToggle(elementName, state) {
handleToggle(elementName: string, state: boolean): void {
const inputSelector = `#${elementName} .action .switch input`;
const input = document.querySelector(inputSelector);
const input: HTMLInputElement = document.querySelector(inputSelector);
if (input) {
input.checked = state;
}
}
registerIpcs() {
ipcRenderer.on('switch-settings-nav', (event, navItem) => {
registerIpcs(): void {
ipcRenderer.on('switch-settings-nav', (_event: Event, navItem: string) => {
this.handleNavigation(navItem);
});
ipcRenderer.on('toggle-sidebar-setting', (event, state) => {
ipcRenderer.on('toggle-sidebar-setting', (_event: Event, state: boolean) => {
this.handleToggle('sidebar-option', state);
});
ipcRenderer.on('toggletray', (event, state) => {
ipcRenderer.on('toggle-menubar-setting', (_event: Event, state: boolean) => {
this.handleToggle('menubar-option', state);
});
ipcRenderer.on('toggletray', (_event: Event, state: boolean) => {
this.handleToggle('tray-option', state);
});
ipcRenderer.on('toggle-dnd', (event, state, newSettings) => {
ipcRenderer.on('toggle-dnd', (_event: Event, _state: boolean, newSettings: any) => {
this.handleToggle('show-notification-option', newSettings.showNotification);
this.handleToggle('silent-option', newSettings.silent);
@@ -109,7 +118,9 @@ class PreferenceView extends BaseComponent {
}
}
window.onload = () => {
window.addEventListener('load', () => {
const preferenceView = new PreferenceView();
preferenceView.init();
};
});
export = PreferenceView;

View File

@@ -1,17 +1,26 @@
'use strict';
const { dialog } = require('electron').remote;
const { ipcRenderer } = require('electron');
const BaseComponent = require(__dirname + '/../../components/base.js');
const DomainUtil = require(__dirname + '/../../utils/domain-util.js');
import { remote, ipcRenderer } from 'electron';
import BaseComponent = require('../../components/base');
import DomainUtil = require('../../utils/domain-util');
const { dialog } = remote;
class ServerInfoForm extends BaseComponent {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
$serverInfoForm: Element;
$serverInfoAlias: Element;
$serverIcon: Element;
$deleteServerButton: Element;
$openServerButton: Element;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="settings-card">
<div class="server-info-left">
@@ -35,21 +44,21 @@ class ServerInfoForm extends BaseComponent {
`;
}
init() {
init(): void {
this.initForm();
this.initActions();
}
initForm() {
initForm(): void {
this.$serverInfoForm = this.generateNodeFromTemplate(this.template());
this.$serverInfoAlias = this.$serverInfoForm.getElementsByClassName('server-info-alias')[0];
this.$serverIcon = this.$serverInfoForm.getElementsByClassName('server-info-icon')[0];
this.$deleteServerButton = this.$serverInfoForm.getElementsByClassName('server-delete-action')[0];
this.$openServerButton = this.$serverInfoForm.getElementsByClassName('open-tab-button')[0];
this.props.$root.appendChild(this.$serverInfoForm);
this.$serverInfoAlias = this.$serverInfoForm.querySelectorAll('.server-info-alias')[0];
this.$serverIcon = this.$serverInfoForm.querySelectorAll('.server-info-icon')[0];
this.$deleteServerButton = this.$serverInfoForm.querySelectorAll('.server-delete-action')[0];
this.$openServerButton = this.$serverInfoForm.querySelectorAll('.open-tab-button')[0];
this.props.$root.append(this.$serverInfoForm);
}
initActions() {
initActions(): void {
this.$deleteServerButton.addEventListener('click', () => {
dialog.showMessageBox({
type: 'warning',
@@ -76,7 +85,6 @@ class ServerInfoForm extends BaseComponent {
ipcRenderer.send('forward-message', 'switch-server-tab', this.props.index);
});
}
}
module.exports = ServerInfoForm;
export = ServerInfoForm;

View File

@@ -1,15 +1,18 @@
'use strict';
const BaseSection = require(__dirname + '/base-section.js');
const NewServerForm = require(__dirname + '/new-server-form.js');
import BaseSection = require('./base-section');
import NewServerForm = require('./new-server-form');
class ServersSection extends BaseSection {
constructor(props) {
// TODO: TypeScript - Here props should be object type
props: any;
$newServerContainer: Element;
constructor(props: any) {
super();
this.props = props;
}
template() {
template(): string {
return `
<div class="add-server-modal">
<div class="modal-container">
@@ -22,20 +25,20 @@ class ServersSection extends BaseSection {
`;
}
init() {
init(): void {
this.initServers();
}
initServers() {
initServers(): void {
this.props.$root.innerHTML = '';
this.props.$root.innerHTML = this.template();
this.$newServerContainer = document.getElementById('new-server-container');
this.$newServerContainer = document.querySelector('#new-server-container');
this.initNewServerForm();
}
initNewServerForm() {
initNewServerForm(): void {
new NewServerForm({
$root: this.$newServerContainer,
onChange: this.reloadApp
@@ -43,4 +46,4 @@ class ServersSection extends BaseSection {
}
}
module.exports = ServersSection;
export = ServersSection;

View File

@@ -1,322 +0,0 @@
'use strict';
const BaseSection = require(__dirname + '/base-section.js');
const shell = require('electron').shell;
class ShortcutsSection extends BaseSection {
constructor(props) {
super();
this.props = props;
}
templateMac() {
const userOSKey = '⌘';
return `
<div class="settings-pane">
<div class="settings-card tip"><p><b><i class="material-icons md-14">settings</i>Tip: </b>These desktop app shortcuts extend the Zulip webapp's <span id="open-hotkeys-link"> keyboard shortcuts</span>.</p></div>
<div class="title">Application Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>,</kbd></td>
<td>Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>K</kbd></td>
<td>Keyboard Shortcuts</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd></td>
<td>Toggle Do Not Disturb</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>D</kbd></td>
<td>Reset App Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>L</kbd></td>
<td>Log Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>H</kbd></td>
<td>Hide Zulip</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>H</kbd></td>
<td>Hide Others</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>Q</kbd></td>
<td>Quit Zulip</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Edit Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>Z</kbd></td>
<td>Undo</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>Z</kbd></td>
<td>Redo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>X</kbd></td>
<td>Cut</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>C</kbd></td>
<td>Copy</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>V</kbd></td>
<td>Paste</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>V</kbd></td>
<td>Paste and Match Style</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>A</kbd></td>
<td>Select All</td>
</tr>
<tr>
<td><kbd>Control</kbd><kbd>${userOSKey}</kbd><kbd>Space</kbd></td>
<td>Emoji & Symbols</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">View Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>R</kbd></td>
<td>Reload</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>R</kbd></td>
<td>Hard Reload</td>
</tr>
<tr>
<td><kbd>Control</kbd><kbd>${userOSKey}</kbd><kbd>F</kbd></td>
<td>Enter Full Screen</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>+</kbd></td>
<td>Zoom In</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>-</kbd></td>
<td>Zoom Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>0</kbd></td>
<td>Actual Size</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd></td>
<td>Toggle Sidebar</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>I</kbd></td>
<td>Toggle DevTools for Zulip App</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>U</kbd></td>
<td>Toggle DevTools for Active Tab</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">History Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>←</kbd></td>
<td>Back</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>→</kbd></td>
<td>Forward</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Window Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>M</kbd></td>
<td>Minimize</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>W</kbd></td>
<td>Close</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
</div>
`;
}
templateWinLin() {
const userOSKey = 'Ctrl';
return `
<div class="settings-pane">
<div class="title">Application Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>,</kbd></td>
<td>Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>K</kbd></td>
<td>Keyboard Shortcuts</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd></td>
<td>Toggle Do Not Disturb</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>L</kbd></td>
<td>Log Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Q</kbd></td>
<td>Quit Zulip</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Edit Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Z</kbd></td>
<td>Undo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Y</kbd></td>
<td>Redo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>X</kbd></td>
<td>Cut</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>C</kbd></td>
<td>Copy</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>V</kbd></td>
<td>Paste</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>V</kbd></td>
<td>Paste and Match Style</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>A</kbd></td>
<td>Select All</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">View Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>R</kbd></td>
<td>Reload</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd></td>
<td>Hard Reload</td>
</tr>
<tr>
<td><kbd>F11</kbd></td>
<td>Toggle Full Screen</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>=</kbd></td>
<td>Zoom In</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>-</kbd></td>
<td>Zoom Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>0</kbd></td>
<td>Actual Size</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd></td>
<td>Toggle Sidebar</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd></td>
<td>Toggle DevTools for Zulip App</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>U</kbd></td>
<td>Toggle DevTools for Active Tab</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">History Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>Alt</kbd> + <kbd>←</kbd></td>
<td>Back</td>
</tr>
<tr>
<td><kbd>Alt</kbd> + <kbd>→</kbd></td>
<td>Forward</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Window Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>M</kbd></td>
<td>Minimize</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>W</kbd></td>
<td>Close</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="tip"><b><i class="material-icons md-14">lightbulb_outline</i>Tip: </b>These desktop app shortcuts extend the Zulip webapp's <span id="open-hotkeys-link">keyboard shortcuts</span>.</div>
</div>
`;
}
openHotkeysExternalLink() {
const link = 'https://zulipchat.com/help/keyboard-shortcuts';
const externalCreateNewOrgEl = document.getElementById('open-hotkeys-link');
externalCreateNewOrgEl.addEventListener('click', () => {
shell.openExternal(link);
});
}
init() {
this.props.$root.innerHTML = (process.platform === 'darwin') ?
this.templateMac() : this.templateWinLin();
this.openHotkeysExternalLink();
}
}
module.exports = ShortcutsSection;

View File

@@ -0,0 +1,344 @@
'use strict';
import { shell } from 'electron';
import BaseSection = require('./base-section');
class ShortcutsSection extends BaseSection {
// TODO: TypeScript - Here props should be object type
props: any;
constructor(props: any) {
super();
this.props = props;
}
// TODO - Deduplicate templateMac and templateWinLin functions. In theory
// they both should be the same the only thing different should be the userOSKey
// variable but there seems to be inconsistences between both function, one has more
// lines though one may just be using more new lines and other thing is the use of +.
templateMac(): string {
const userOSKey = '⌘';
return `
<div class="settings-pane">
<div class="settings-card tip"><p><b><i class="material-icons md-14">settings</i>Tip: </b>These desktop app shortcuts extend the Zulip webapp's <span id="open-hotkeys-link"> keyboard shortcuts</span>.</p></div>
<div class="title">Application Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>,</kbd></td>
<td>Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>K</kbd></td>
<td>Keyboard Shortcuts</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd></td>
<td>Toggle Do Not Disturb</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>D</kbd></td>
<td>Reset App Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>L</kbd></td>
<td>Log Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>H</kbd></td>
<td>Hide Zulip</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>H</kbd></td>
<td>Hide Others</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>Q</kbd></td>
<td>Quit Zulip</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Edit Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>Z</kbd></td>
<td>Undo</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>Z</kbd></td>
<td>Redo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>X</kbd></td>
<td>Cut</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>C</kbd></td>
<td>Copy</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>V</kbd></td>
<td>Paste</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>V</kbd></td>
<td>Paste and Match Style</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>A</kbd></td>
<td>Select All</td>
</tr>
<tr>
<td><kbd>Control</kbd><kbd>${userOSKey}</kbd><kbd>Space</kbd></td>
<td>Emoji & Symbols</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">View Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>R</kbd></td>
<td>Reload</td>
</tr>
<tr>
<td><kbd>Shift</kbd><kbd>${userOSKey}</kbd><kbd>R</kbd></td>
<td>Hard Reload</td>
</tr>
<tr>
<td><kbd>Control</kbd><kbd>${userOSKey}</kbd><kbd>F</kbd></td>
<td>Enter Full Screen</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>+</kbd></td>
<td>Zoom In</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>-</kbd></td>
<td>Zoom Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>0</kbd></td>
<td>Actual Size</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd></td>
<td>Toggle Sidebar</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>I</kbd></td>
<td>Toggle DevTools for Zulip App</td>
</tr>
<tr>
<td><kbd>Option</kbd><kbd>${userOSKey}</kbd><kbd>U</kbd></td>
<td>Toggle DevTools for Active Tab</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd> + <kbd>Tab</kbd></td>
<td>Switch to Next Organization</td>
</tr>
<tr>
<td><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Tab</kbd></td>
<td>Switch to Previous Organization</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">History Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>←</kbd></td>
<td>Back</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>→</kbd></td>
<td>Forward</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Window Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>M</kbd></td>
<td>Minimize</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd><kbd>W</kbd></td>
<td>Close</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
</div>
`;
}
templateWinLin(): string {
const userOSKey = 'Ctrl';
return `
<div class="settings-pane">
<div class="settings-card tip"><p><b><i class="material-icons md-14">settings</i>Tip: </b>These desktop app shortcuts extend the Zulip webapp's <span id="open-hotkeys-link"> keyboard shortcuts</span>.</p></div>
<div class="title">Application Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>,</kbd></td>
<td>Settings</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>K</kbd></td>
<td>Keyboard Shortcuts</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd></td>
<td>Toggle Do Not Disturb</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>L</kbd></td>
<td>Log Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Q</kbd></td>
<td>Quit Zulip</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Edit Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Z</kbd></td>
<td>Undo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Y</kbd></td>
<td>Redo</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>X</kbd></td>
<td>Cut</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>C</kbd></td>
<td>Copy</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>V</kbd></td>
<td>Paste</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>V</kbd></td>
<td>Paste and Match Style</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>A</kbd></td>
<td>Select All</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">View Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>R</kbd></td>
<td>Reload</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd></td>
<td>Hard Reload</td>
</tr>
<tr>
<td><kbd>F11</kbd></td>
<td>Toggle Full Screen</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>=</kbd></td>
<td>Zoom In</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>-</kbd></td>
<td>Zoom Out</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>0</kbd></td>
<td>Actual Size</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd></td>
<td>Toggle Sidebar</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd></td>
<td>Toggle DevTools for Zulip App</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>U</kbd></td>
<td>Toggle DevTools for Active Tab</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Tab</kbd></td>
<td>Switch to Next Organization</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>Shift</kbd> + <kbd>Tab</kbd></td>
<td>Switch to Previous Organization</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">History Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>Alt</kbd> + <kbd>←</kbd></td>
<td>Back</td>
</tr>
<tr>
<td><kbd>Alt</kbd> + <kbd>→</kbd></td>
<td>Forward</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
<div class="title">Window Shortcuts</div>
<div class="settings-card">
<table>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>M</kbd></td>
<td>Minimize</td>
</tr>
<tr>
<td><kbd>${userOSKey}</kbd> + <kbd>W</kbd></td>
<td>Close</td>
</tr>
</table>
<div class="setting-control"></div>
</div>
</div>
`;
}
openHotkeysExternalLink(): void {
const link = 'https://zulipchat.com/help/keyboard-shortcuts';
const externalCreateNewOrgEl = document.querySelector('#open-hotkeys-link');
externalCreateNewOrgEl.addEventListener('click', () => {
shell.openExternal(link);
});
}
init(): void {
this.props.$root.innerHTML = (process.platform === 'darwin') ?
this.templateMac() : this.templateWinLin();
this.openHotkeysExternalLink();
}
}
export = ShortcutsSection;

View File

@@ -1,11 +1,17 @@
'use strict';
const { ipcRenderer, shell } = require('electron');
const SetupSpellChecker = require('./spellchecker');
import { ipcRenderer, shell } from 'electron';
import SetupSpellChecker from './spellchecker';
const ConfigUtil = require(__dirname + '/utils/config-util.js');
const LinkUtil = require(__dirname + '/utils/link-util.js');
const params = require(__dirname + '/utils/params-util.js');
import LinkUtil = require('./utils/link-util');
import params = require('./utils/params-util');
interface PatchedGlobal extends NodeJS.Global {
logout: () => void;
shortcut: () => void;
}
const globalPatched = global as PatchedGlobal;
// eslint-disable-next-line import/no-unassigned-import
require('./notification');
@@ -13,44 +19,46 @@ require('./notification');
// Prevent drag and drop event in main process which prevents remote code executaion
require(__dirname + '/shared/preventdrag.js');
// eslint-disable-next-line camelcase
declare let window: ZulipWebWindow;
// eslint-disable-next-line @typescript-eslint/camelcase
window.electron_bridge = require('./electron-bridge');
const logout = () => {
const logout = (): void => {
// Create the menu for the below
document.querySelector('.dropdown-toggle').click();
const dropdown: HTMLElement = document.querySelector('.dropdown-toggle');
dropdown.click();
const nodes = document.querySelectorAll('.dropdown-menu li:last-child a');
const nodes: NodeListOf<HTMLElement> = document.querySelectorAll('.dropdown-menu li:last-child a');
nodes[nodes.length - 1].click();
};
const shortcut = () => {
const shortcut = (): void => {
// Create the menu for the below
const node = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]');
const node: HTMLElement = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]');
// Additional check
if (node.text.trim().toLowerCase() === 'keyboard shortcuts (?)') {
if (node.textContent.trim().toLowerCase() === 'keyboard shortcuts (?)') {
node.click();
} else {
// Atleast click the dropdown
document.querySelector('.dropdown-toggle').click();
const dropdown: HTMLElement = document.querySelector('.dropdown-toggle');
dropdown.click();
}
};
process.once('loaded', () => {
global.logout = logout;
global.shortcut = shortcut;
process.once('loaded', (): void => {
globalPatched.logout = logout;
globalPatched.shortcut = shortcut;
});
// To prevent failing this script on linux we need to load it after the document loaded
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', (): void => {
if (params.isPageParams()) {
// Get the default language of the server
const serverLanguage = page_params.default_language; // eslint-disable-line no-undef, camelcase
const serverLanguage = page_params.default_language; // eslint-disable-line no-undef, @typescript-eslint/camelcase
if (serverLanguage) {
// Set spellcheker language
ConfigUtil.setConfigItem('spellcheckerLanguage', serverLanguage);
// Init spellchecker
SetupSpellChecker.init();
SetupSpellChecker.init(serverLanguage);
}
// redirect users to network troubleshooting page
const getRestartButton = document.querySelector('.restart_get_events_button');
@@ -61,7 +69,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
// Open image attachment link in the lightbox instead of opening in the default browser
const { $, lightbox } = window;
$('#main_div').on('click', '.message_content p a', function (e) {
$('#main_div').on('click', '.message_content p a', function (this: HTMLElement, e: Event) {
const url = $(this).attr('href');
if (LinkUtil.isImage(url)) {
@@ -85,14 +93,21 @@ document.addEventListener('DOMContentLoaded', () => {
// Clean up spellchecker events after you navigate away from this page;
// otherwise, you may experience errors
window.addEventListener('beforeunload', () => {
window.addEventListener('beforeunload', (): void => {
SetupSpellChecker.unsubscribeSpellChecker();
});
// electron's globalShortcut can cause unexpected results
// so adding the reload shortcut in the old-school way
// Zoom from numpad keys is not supported by electron, so adding it through listeners.
document.addEventListener('keydown', event => {
if (event.code === 'F5') {
ipcRenderer.send('forward-message', 'hard-reload');
} else if (event.ctrlKey && event.code === 'NumpadAdd') {
ipcRenderer.send('forward-message', 'zoomIn');
} else if (event.ctrlKey && event.code === 'NumpadSubtract') {
ipcRenderer.send('forward-message', 'zoomOut');
} else if (event.ctrlKey && event.code === 'Numpad0') {
ipcRenderer.send('forward-message', 'zoomActualSize');
}
});

View File

@@ -5,7 +5,7 @@
// It doesn't affect the compose box so that users can still
// use drag and drop event to share files etc
const preventDragAndDrop = () => {
const preventDragAndDrop = (): void => {
const preventEvents = ['dragover', 'drop'];
preventEvents.forEach(dragEvents => {
document.addEventListener(dragEvents, event => {

View File

@@ -1,62 +0,0 @@
'use strict';
const { SpellCheckHandler, ContextMenuListener, ContextMenuBuilder } = require('electron-spellchecker');
const ConfigUtil = require(__dirname + '/utils/config-util.js');
const Logger = require(__dirname + '/utils/logger-util.js');
const logger = new Logger({
file: 'errors.log',
timestamp: true
});
class SetupSpellChecker {
init() {
if (ConfigUtil.getConfigItem('enableSpellchecker')) {
this.enableSpellChecker();
}
this.enableContextMenu();
}
enableSpellChecker() {
try {
this.SpellCheckHandler = new SpellCheckHandler();
} catch (err) {
logger.error(err);
}
}
enableContextMenu() {
if (this.SpellCheckHandler) {
this.SpellCheckHandler.attachToInput();
const userLanguage = ConfigUtil.getConfigItem('spellcheckerLanguage');
// eslint-disable-next-line no-unused-expressions
process.platform === 'darwin' ?
// On macOS, spellchecker fails to auto-detect the lanugage user is typing in
// that's why we need to mention it explicitly
this.SpellCheckHandler.switchLanguage(userLanguage) :
// On Linux and Windows, spellchecker can automatically detects the language the user is typing in
// and silently switches on the fly; thus we can start off as US English
this.SpellCheckHandler.switchLanguage('en-US');
}
const contextMenuBuilder = new ContextMenuBuilder(this.SpellCheckHandler);
this.contextMenuListener = new ContextMenuListener(info => {
contextMenuBuilder.showPopupMenu(info);
});
}
unsubscribeSpellChecker() {
// eslint-disable-next-line no-undef
if (this.SpellCheckHandler) {
this.SpellCheckHandler.unsubscribe();
}
if (this.contextMenuListener) {
this.contextMenuListener.unsubscribe();
}
}
}
module.exports = new SetupSpellChecker();

View File

@@ -0,0 +1,56 @@
'use strict';
import { SpellCheckHandler, ContextMenuListener, ContextMenuBuilder } from 'electron-spellchecker';
import ConfigUtil = require('./utils/config-util');
import Logger = require('./utils/logger-util');
const logger = new Logger({
file: 'errors.log',
timestamp: true
});
class SetupSpellChecker {
SpellCheckHandler: typeof SpellCheckHandler;
contextMenuListener: typeof ContextMenuListener;
init(serverLanguage: string): void {
if (ConfigUtil.getConfigItem('enableSpellchecker')) {
this.enableSpellChecker();
}
this.enableContextMenu(serverLanguage);
}
enableSpellChecker(): void {
try {
this.SpellCheckHandler = new SpellCheckHandler();
} catch (err) {
logger.error(err);
}
}
enableContextMenu(serverLanguage: string): void {
if (this.SpellCheckHandler) {
this.SpellCheckHandler.attachToInput();
this.SpellCheckHandler.switchLanguage(serverLanguage);
this.SpellCheckHandler.currentSpellcheckerChanged.subscribe(() => {
this.SpellCheckHandler.switchLanguage(this.SpellCheckHandler.currentSpellcheckerLanguage);
});
}
const contextMenuBuilder = new ContextMenuBuilder(this.SpellCheckHandler);
this.contextMenuListener = new ContextMenuListener((info: object) => {
contextMenuBuilder.showPopupMenu(info);
});
}
unsubscribeSpellChecker(): void {
if (this.SpellCheckHandler) {
this.SpellCheckHandler.unsubscribe();
}
if (this.contextMenuListener) {
this.contextMenuListener.unsubscribe();
}
}
}
export = new SetupSpellChecker();

View File

@@ -1,17 +1,15 @@
'use strict';
const path = require('path');
const electron = require('electron');
const { ipcRenderer, remote } = electron;
import { ipcRenderer, remote, WebviewTag, NativeImage } from 'electron';
import path = require('path');
import ConfigUtil = require('./utils/config-util.js');
const { Tray, Menu, nativeImage, BrowserWindow } = remote;
const APP_ICON = path.join(__dirname, '../../resources/tray', 'tray');
const ConfigUtil = require(__dirname + '/utils/config-util.js');
declare let window: ZulipWebWindow;
const iconPath = () => {
const iconPath = (): string => {
if (process.platform === 'linux') {
return APP_ICON + 'linux.png';
}
@@ -20,7 +18,7 @@ const iconPath = () => {
let unread = 0;
const trayIconSize = () => {
const trayIconSize = (): number => {
switch (process.platform) {
case 'darwin':
return 20;
@@ -45,7 +43,7 @@ const config = {
thick: process.platform === 'win32'
};
const renderCanvas = function (arg) {
const renderCanvas = function (arg: number): Promise<HTMLCanvasElement> {
config.unreadCount = arg;
return new Promise(resolve => {
@@ -79,10 +77,10 @@ const renderCanvas = function (arg) {
ctx.fillText('99+', CENTER, CENTER + (SIZE * 0.15));
} else if (config.unreadCount < 10) {
ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`;
ctx.fillText(config.unreadCount, CENTER, CENTER + (SIZE * 0.20));
ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.20));
} else {
ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`;
ctx.fillText(config.unreadCount, CENTER, CENTER + (SIZE * 0.15));
ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.15));
}
resolve(canvas);
@@ -94,18 +92,23 @@ const renderCanvas = function (arg) {
* @param arg: Unread count
* @return the native image
*/
const renderNativeImage = function (arg) {
const renderNativeImage = function (arg: number): Promise<NativeImage> {
return Promise.resolve()
.then(() => renderCanvas(arg))
.then(canvas => {
const pngData = nativeImage.createFromDataURL(canvas.toDataURL('image/png')).toPNG();
// TODO: Fix the function to correctly use Promise correctly.
// the Promise.resolve().then(...) above is useless we should
// start with renderCanvas(arg).then
// eslint-disable-next-line promise/no-return-wrap
return Promise.resolve(nativeImage.createFromBuffer(pngData, {
scaleFactor: config.pixelRatio
}));
});
};
function sendAction(action) {
function sendAction(action: string): void {
const win = BrowserWindow.getAllWindows()[0];
if (process.platform === 'darwin') {
@@ -115,7 +118,7 @@ function sendAction(action) {
win.webContents.send(action);
}
const createTray = function () {
const createTray = function (): void {
window.tray = new Tray(iconPath());
const contextMenu = Menu.buildFromTemplate([
{
@@ -149,9 +152,9 @@ const createTray = function () {
}
};
ipcRenderer.on('destroytray', event => {
ipcRenderer.on('destroytray', (event: Event): Event => {
if (!window.tray) {
return;
return undefined;
}
window.tray.destroy();
@@ -164,7 +167,7 @@ ipcRenderer.on('destroytray', event => {
return event;
});
ipcRenderer.on('tray', (event, arg) => {
ipcRenderer.on('tray', (_event: Event, arg: number): void => {
if (!window.tray) {
return;
}
@@ -184,7 +187,7 @@ ipcRenderer.on('tray', (event, arg) => {
}
});
function toggleTray() {
function toggleTray(): void {
let state;
if (window.tray) {
state = false;
@@ -205,7 +208,7 @@ function toggleTray() {
ConfigUtil.setConfigItem('trayIcon', true);
}
const selector = 'webview:not([class*=disabled])';
const webview = document.querySelector(selector);
const webview: WebviewTag = document.querySelector(selector);
const webContents = webview.getWebContents();
webContents.send('toggletray', state);
}

View File

@@ -1,11 +1,14 @@
'use strict';
const { app, dialog } = require('electron').remote;
const fs = require('fs');
const path = require('path');
const JsonDB = require('node-json-db');
const Logger = require('./logger-util');
const { initSetUp } = require('./default-util');
import { remote } from 'electron';
import JsonDB from 'node-json-db';
import { initSetUp } from './default-util';
import fs = require('fs');
import path = require('path');
import Logger = require('./logger-util');
const { app, dialog } = remote;
initSetUp();
@@ -14,10 +17,12 @@ const logger = new Logger({
timestamp: true
});
let instance = null;
let instance: null | CertificateUtil = null;
const certificatesDir = `${app.getPath('userData')}/certificates`;
class CertificateUtil {
db: JsonDB;
constructor() {
if (instance) {
return instance;
@@ -28,7 +33,8 @@ class CertificateUtil {
this.reloadDB();
return instance;
}
getCertificate(server, defaultValue = null) {
getCertificate(server: string, defaultValue: any = null): any {
this.reloadDB();
const value = this.db.getData('/')[server];
if (value === undefined) {
@@ -37,8 +43,9 @@ class CertificateUtil {
return value;
}
}
// Function to copy the certificate to userData folder
copyCertificate(server, location, fileName) {
copyCertificate(_server: string, location: string, fileName: string): boolean {
let copied = false;
const filePath = `${certificatesDir}/${fileName}`;
try {
@@ -54,16 +61,19 @@ class CertificateUtil {
}
return copied;
}
setCertificate(server, fileName) {
setCertificate(server: string, fileName: string): void {
const filePath = `${certificatesDir}/${fileName}`;
this.db.push(`/${server}`, filePath, true);
this.reloadDB();
}
removeCertificate(server) {
removeCertificate(server: string): void {
this.db.delete(`/${server}`);
this.reloadDB();
}
reloadDB() {
reloadDB(): void {
const settingsJsonPath = path.join(app.getPath('userData'), '/config/certificates.json');
try {
const file = fs.readFileSync(settingsJsonPath, 'utf8');
@@ -83,4 +93,4 @@ class CertificateUtil {
}
}
module.exports = new CertificateUtil();
export = new CertificateUtil();

View File

@@ -1,6 +1,6 @@
'use strict';
let instance = null;
let instance: null | CommonUtil = null;
class CommonUtil {
constructor() {
@@ -13,13 +13,13 @@ class CommonUtil {
}
// unescape already encoded/escaped strings
decodeString(string) {
decodeString(stringInput: string): string {
const parser = new DOMParser();
const dom = parser.parseFromString(
'<!doctype html><body>' + string,
'<!doctype html><body>' + stringInput,
'text/html');
return dom.body.textContent;
}
}
module.exports = new CommonUtil();
export = new CommonUtil();

View File

@@ -1,32 +1,33 @@
'use strict';
import JsonDB from 'node-json-db';
const fs = require('fs');
const path = require('path');
const process = require('process');
const JsonDB = require('node-json-db');
const Logger = require('./logger-util');
import fs = require('fs');
import path = require('path');
import electron = require('electron');
import Logger = require('./logger-util');
const logger = new Logger({
file: 'config-util.log',
timestamp: true
});
let instance = null;
let dialog = null;
let app = null;
let instance: null | ConfigUtil = null;
let dialog: Electron.Dialog = null;
let app: Electron.App = null;
/* To make the util runnable in both main and renderer process */
if (process.type === 'renderer') {
const remote = require('electron').remote;
const { remote } = electron;
dialog = remote.dialog;
app = remote.app;
} else {
const electron = require('electron');
dialog = electron.dialog;
app = electron.app;
}
class ConfigUtil {
db: JsonDB;
constructor() {
if (instance) {
return instance;
@@ -38,7 +39,7 @@ class ConfigUtil {
return instance;
}
getConfigItem(key, defaultValue = null) {
getConfigItem(key: string, defaultValue: any = null): any {
try {
this.db.reload();
} catch (err) {
@@ -53,8 +54,9 @@ class ConfigUtil {
return value;
}
}
// This function returns whether a key exists in the configuration file (settings.json)
isConfigItemExists(key) {
isConfigItemExists(key: string): boolean {
try {
this.db.reload();
} catch (err) {
@@ -65,17 +67,17 @@ class ConfigUtil {
return (value !== undefined);
}
setConfigItem(key, value) {
setConfigItem(key: string, value: any): void {
this.db.push(`/${key}`, value, true);
this.db.save();
}
removeConfigItem(key) {
removeConfigItem(key: string): void {
this.db.delete(`/${key}`);
this.db.save();
}
reloadDB() {
reloadDB(): void {
const settingsJsonPath = path.join(app.getPath('userData'), '/config/settings.json');
try {
const file = fs.readFileSync(settingsJsonPath, 'utf8');
@@ -96,4 +98,4 @@ class ConfigUtil {
}
}
module.exports = new ConfigUtil();
export = new ConfigUtil();

View File

@@ -1,6 +1,6 @@
const fs = require('fs');
import fs = require('fs');
let app = null;
let app: Electron.App = null;
let setupCompleted = false;
if (process.type === 'renderer') {
app = require('electron').remote.app;
@@ -12,7 +12,7 @@ const zulipDir = app.getPath('userData');
const logDir = `${zulipDir}/Logs/`;
const certificatesDir = `${zulipDir}/certificates/`;
const configDir = `${zulipDir}/config/`;
const initSetUp = () => {
export const initSetUp = (): void => {
// if it is the first time the app is running
// create zulip dir in userData folder to
// avoid errors
@@ -72,7 +72,3 @@ const initSetUp = () => {
setupCompleted = true;
}
};
module.exports = {
initSetUp
};

View File

@@ -1,17 +1,30 @@
'use strict';
const ConfigUtil = require(__dirname + '/config-util.js');
import ConfigUtil = require('./config-util');
function toggle() {
// TODO: TypeScript - add to Setting interface
// the list of settings since we have fixed amount of them
// We want to do this by creating a new module that exports
// this interface
interface Setting {
[key: string]: any;
}
interface Toggle {
dnd: boolean;
newSettings: Setting;
}
export function toggle(): Toggle {
const dnd = !ConfigUtil.getConfigItem('dnd', false);
const dndSettingList = ['showNotification', 'silent'];
if (process.platform === 'win32') {
dndSettingList.push('flashTaskbarOnMessage');
}
let newSettings;
let newSettings: Setting;
if (dnd) {
const oldSettings = {};
const oldSettings: Setting = {};
newSettings = {};
// Iterate through the dndSettingList.
@@ -35,7 +48,3 @@ function toggle() {
ConfigUtil.setConfigItem('dnd', dnd);
return {dnd, newSettings};
}
module.exports = {
toggle
};

View File

@@ -1,367 +0,0 @@
'use strict';
const { app, dialog } = require('electron').remote;
const fs = require('fs');
const path = require('path');
const JsonDB = require('node-json-db');
const request = require('request');
const escape = require('escape-html');
const Logger = require('./logger-util');
const CertificateUtil = require(__dirname + '/certificate-util.js');
const ProxyUtil = require(__dirname + '/proxy-util.js');
const ConfigUtil = require(__dirname + '/config-util.js');
const SystemUtil = require(__dirname + '/../utils/system-util.js');
const logger = new Logger({
file: `domain-util.log`,
timestamp: true
});
let instance = null;
const defaultIconUrl = '../renderer/img/icon.png';
class DomainUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.reloadDB();
// Migrate from old schema
if (this.db.getData('/').domain) {
this.addDomain({
alias: 'Zulip',
url: this.db.getData('/domain')
});
this.db.delete('/domain');
}
return instance;
}
getDomains() {
this.reloadDB();
if (this.db.getData('/').domains === undefined) {
return [];
} else {
return this.db.getData('/domains');
}
}
getDomain(index) {
this.reloadDB();
return this.db.getData(`/domains[${index}]`);
}
updateDomain(index, server) {
this.reloadDB();
this.db.push(`/domains[${index}]`, server, true);
}
addDomain(server) {
return new Promise(resolve => {
if (server.icon) {
this.saveServerIcon(server).then(localIconUrl => {
server.icon = localIconUrl;
this.db.push('/domains[]', server, true);
this.reloadDB();
resolve();
});
} else {
server.icon = defaultIconUrl;
this.db.push('/domains[]', server, true);
this.reloadDB();
resolve();
}
});
}
removeDomains() {
this.db.delete('/domains');
this.reloadDB();
}
removeDomain(index) {
this.db.delete(`/domains[${index}]`);
this.reloadDB();
}
// Check if domain is already added
duplicateDomain(domain) {
domain = this.formatUrl(domain);
const servers = this.getDomains();
for (const i in servers) {
if (servers[i].url === domain) {
return true;
}
}
return false;
}
checkDomain(domain, silent = false) {
if (!silent && this.duplicateDomain(domain)) {
// Do not check duplicate in silent mode
return Promise.reject('This server has been added.');
}
domain = this.formatUrl(domain);
const certificate = CertificateUtil.getCertificate(encodeURIComponent(domain));
let certificateLocation = '';
if (certificate) {
// To handle case where certificate has been moved from the location in certificates.json
try {
certificateLocation = fs.readFileSync(certificate);
} catch (err) {
logger.warn('Error while trying to get certificate: ' + err);
}
}
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
// If certificate for the domain exists add it as a ca key in the request's parameter else consider only domain as the parameter for request
// Add proxy as a parameter if it sbeing used.
const checkDomain = {
url: domain + '/static/audio/zulip.ogg',
ca: (certificateLocation) ? certificateLocation : '',
proxy: proxyEnabled ? ProxyUtil.getProxy(domain) : '',
ecdhCurve: 'auto',
headers: { 'User-Agent': SystemUtil.getUserAgent() }
};
const serverConf = {
icon: defaultIconUrl,
url: domain,
alias: domain
};
return new Promise((resolve, reject) => {
request(checkDomain, (error, response) => {
// If the domain contains following strings we just bypass the server
const whitelistDomains = [
'zulipdev.org'
];
// make sure that error is an error or string not undefined
// so validation does not throw error.
error = error || '';
const certsError = error.toString().includes('certificate');
if (!error && response.statusCode < 400) {
// Correct
this.getServerSettings(domain).then(serverSettings => {
resolve(serverSettings);
}, () => {
resolve(serverConf);
});
} else if (domain.indexOf(whitelistDomains) >= 0 || certsError) {
if (silent) {
this.getServerSettings(domain).then(serverSettings => {
resolve(serverSettings);
}, () => {
resolve(serverConf);
});
} else {
// Report error to sentry to get idea of possible certificate errors
// users get when adding the servers
logger.reportSentry(new Error(error));
const certErrorMessage = `Do you trust certificate from ${domain}? \n ${error}`;
const certErrorDetail = `The organization you're connecting to is either someone impersonating the Zulip server you entered, or the server you're trying to connect to is configured in an insecure way.
\nIf you have a valid certificate please add it from Settings>Organizations and try to add the organization again.
\nUnless you have a good reason to believe otherwise, you should not proceed.
\nYou can click here if you'd like to proceed with the connection.`;
dialog.showMessageBox({
type: 'warning',
buttons: ['Yes', 'No'],
defaultId: 1,
message: certErrorMessage,
detail: certErrorDetail
}, response => {
if (response === 0) {
this.getServerSettings(domain).then(serverSettings => {
resolve(serverSettings);
}, () => {
resolve(serverConf);
});
} else {
reject('Untrusted Certificate.');
}
});
}
} else {
const invalidZulipServerError = `${domain} does not appear to be a valid Zulip server. Make sure that \
\n (1) you can connect to that URL in a web browser and \n (2) if you need a proxy to connect to the Internet, that you've configured your proxy in the Network settings \n (3) its a zulip server \
\n (4) the server has a valid certificate, you can add custom certificates in Settings>Organizations`;
reject(invalidZulipServerError);
}
});
});
}
getServerSettings(domain) {
const certificate = CertificateUtil.getCertificate(encodeURIComponent(domain));
let certificateLocation = '';
if (certificate) {
// To handle case where certificate has been moved from the location in certificates.json
try {
certificateLocation = fs.readFileSync(certificate);
} catch (err) {
logger.warn('Error while trying to get certificate: ' + err);
}
}
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
const serverSettingsOptions = {
url: domain + '/api/v1/server_settings',
ca: (certificateLocation) ? certificateLocation : '',
proxy: proxyEnabled ? ProxyUtil.getProxy(domain) : '',
ecdhCurve: 'auto',
headers: { 'User-Agent': SystemUtil.getUserAgent() }
};
return new Promise((resolve, reject) => {
request(serverSettingsOptions, (error, response) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(response.body);
if (data.hasOwnProperty('realm_icon') && data.realm_icon) {
resolve({
// Some Zulip Servers use absolute URL for server icon whereas others use relative URL
// Following check handles both the cases
icon: data.realm_icon.startsWith('/') ? data.realm_uri + data.realm_icon : data.realm_icon,
url: data.realm_uri,
alias: escape(data.realm_name)
});
}
} else {
reject('Zulip server version < 1.6.');
}
});
});
}
saveServerIcon(server) {
const url = server.icon;
const domain = server.url;
const certificate = CertificateUtil.getCertificate(encodeURIComponent(domain));
let certificateLocation = '';
if (certificate) {
// To handle case where certificate has been moved from the location in certificates.json
try {
certificateLocation = fs.readFileSync(certificate);
} catch (err) {
logger.warn('Error while trying to get certificate: ' + err);
}
}
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
// Add proxy and certificate as a parameter if its being used.
const serverIconOptions = {
url,
ca: (certificateLocation) ? certificateLocation : '',
proxy: proxyEnabled ? ProxyUtil.getProxy(url) : '',
ecdhCurve: 'auto',
headers: { 'User-Agent': SystemUtil.getUserAgent() }
};
// The save will always succeed. If url is invalid, downgrade to default icon.
return new Promise(resolve => {
const filePath = this.generateFilePath(url);
const file = fs.createWriteStream(filePath);
try {
request(serverIconOptions).on('response', response => {
response.on('error', err => {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
});
response.pipe(file).on('finish', () => {
resolve(filePath);
});
}).on('error', err => {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
});
} catch (err) {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
}
});
}
updateSavedServer(url, index) {
// Does not promise successful update
this.checkDomain(url, true).then(newServerConf => {
this.saveServerIcon(newServerConf).then(localIconUrl => {
newServerConf.icon = localIconUrl;
this.updateDomain(index, newServerConf);
this.reloadDB();
});
});
}
reloadDB() {
const domainJsonPath = path.join(app.getPath('userData'), 'config/domain.json');
try {
const file = fs.readFileSync(domainJsonPath, 'utf8');
JSON.parse(file);
} catch (err) {
if (fs.existsSync(domainJsonPath)) {
fs.unlinkSync(domainJsonPath);
dialog.showErrorBox(
'Error saving new organization',
'There seems to be error while saving new organization, ' +
'you may have to re-add your previous organizations back.'
);
logger.error('Error while JSON parsing domain.json: ');
logger.error(err);
logger.reportSentry(err);
}
}
this.db = new JsonDB(domainJsonPath, true, true);
}
generateFilePath(url) {
const dir = `${app.getPath('userData')}/server-icons`;
const extension = path.extname(url).split('?')[0];
let hash = 5381;
let len = url.length;
while (len) {
hash = (hash * 33) ^ url.charCodeAt(--len);
}
// Create 'server-icons' directory if not existed
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
return `${dir}/${hash >>> 0}${extension}`;
}
formatUrl(domain) {
const hasPrefix = (domain.indexOf('http') === 0);
if (hasPrefix) {
return domain;
} else {
return (domain.indexOf('localhost:') >= 0) ? `http://${domain}` : `https://${domain}`;
}
}
}
module.exports = new DomainUtil();

View File

@@ -0,0 +1,310 @@
'use strict';
import JsonDB from 'node-json-db';
import escape = require('escape-html');
import request = require('request');
import fs = require('fs');
import path = require('path');
import Logger = require('./logger-util');
import electron = require('electron');
import RequestUtil = require('./request-util');
import Messages = require('../../../resources/messages');
const { app, dialog } = electron.remote;
const logger = new Logger({
file: `domain-util.log`,
timestamp: true
});
let instance: null | DomainUtil = null;
const defaultIconUrl = '../renderer/img/icon.png';
class DomainUtil {
db: JsonDB;
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.reloadDB();
// Migrate from old schema
if (this.db.getData('/').domain) {
this.addDomain({
alias: 'Zulip',
url: this.db.getData('/domain')
});
this.db.delete('/domain');
}
return instance;
}
getDomains(): any {
this.reloadDB();
if (this.db.getData('/').domains === undefined) {
return [];
} else {
return this.db.getData('/domains');
}
}
getDomain(index: number): any {
this.reloadDB();
return this.db.getData(`/domains[${index}]`);
}
updateDomain(index: number, server: object): void {
this.reloadDB();
this.db.push(`/domains[${index}]`, server, true);
}
addDomain(server: any): Promise<void> {
const { ignoreCerts } = server;
return new Promise(resolve => {
if (server.icon) {
this.saveServerIcon(server, ignoreCerts).then(localIconUrl => {
server.icon = localIconUrl;
this.db.push('/domains[]', server, true);
this.reloadDB();
resolve();
});
} else {
server.icon = defaultIconUrl;
this.db.push('/domains[]', server, true);
this.reloadDB();
resolve();
}
});
}
removeDomains(): void {
this.db.delete('/domains');
this.reloadDB();
}
removeDomain(index: number): void {
this.db.delete(`/domains[${index}]`);
this.reloadDB();
}
// Check if domain is already added
duplicateDomain(domain: any): boolean {
domain = this.formatUrl(domain);
const servers = this.getDomains();
for (const i in servers) {
if (servers[i].url === domain) {
return true;
}
}
return false;
}
async checkCertError(domain: any, serverConf: any, error: string, silent: boolean): Promise<string | object> {
if (silent) {
// since getting server settings has already failed
return serverConf;
} else {
// Report error to sentry to get idea of possible certificate errors
// users get when adding the servers
logger.reportSentry(new Error(error).toString());
const certErrorMessage = Messages.certErrorMessage(domain, error);
const certErrorDetail = Messages.certErrorDetail();
const response = await (dialog.showMessageBox({
type: 'warning',
buttons: ['Yes', 'No'],
defaultId: 1,
message: certErrorMessage,
detail: certErrorDetail
}) as any); // TODO: TypeScript - Figure this out
if (response === 0) {
// set ignoreCerts parameter to true in case user responds with yes
serverConf.ignoreCerts = true;
try {
return await this.getServerSettings(domain, serverConf.ignoreCerts);
} catch (_) {
if (error === Messages.noOrgsError(domain)) {
throw new Error(error);
}
return serverConf;
}
} else {
throw new Error('Untrusted certificate.');
}
}
}
// ignoreCerts parameter helps in fetching server icon and
// other server details when user chooses to ignore certificate warnings
async checkDomain(domain: any, ignoreCerts = false, silent = false): Promise<any> {
if (!silent && this.duplicateDomain(domain)) {
// Do not check duplicate in silent mode
throw new Error('This server has been added.');
}
domain = this.formatUrl(domain);
const serverConf = {
icon: defaultIconUrl,
url: domain,
alias: domain,
ignoreCerts
};
try {
return await this.getServerSettings(domain, serverConf.ignoreCerts);
} catch (err) {
// If the domain contains following strings we just bypass the server
const whitelistDomains = [
'zulipdev.org'
];
// make sure that error is an error or string not undefined
// so validation does not throw error.
const error = err || '';
const certsError = error.toString().includes('certificate');
if (domain.indexOf(whitelistDomains) >= 0 || certsError) {
return this.checkCertError(domain, serverConf, error, silent);
} else {
throw Messages.invalidZulipServerError(domain);
}
}
}
getServerSettings(domain: any, ignoreCerts = false): Promise<object | string> {
const serverSettingsOptions = {
url: domain + '/api/v1/server_settings',
...RequestUtil.requestOptions(domain, ignoreCerts)
};
return new Promise((resolve, reject) => {
request(serverSettingsOptions, (error: string, response: any) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(response.body);
if (data.hasOwnProperty('realm_icon') && data.realm_icon) {
resolve({
// Some Zulip Servers use absolute URL for server icon whereas others use relative URL
// Following check handles both the cases
icon: data.realm_icon.startsWith('/') ? data.realm_uri + data.realm_icon : data.realm_icon,
url: data.realm_uri,
alias: escape(data.realm_name),
ignoreCerts
});
} else {
reject(Messages.noOrgsError(domain));
}
} else {
reject(response);
}
});
});
}
saveServerIcon(server: any, ignoreCerts = false): Promise<string> {
const url = server.icon;
const domain = server.url;
const serverIconOptions = {
url,
...RequestUtil.requestOptions(domain, ignoreCerts)
};
// The save will always succeed. If url is invalid, downgrade to default icon.
return new Promise(resolve => {
const filePath = this.generateFilePath(url);
const file = fs.createWriteStream(filePath);
try {
request(serverIconOptions).on('response', (response: any) => {
response.on('error', (err: string) => {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
});
response.pipe(file).on('finish', () => {
resolve(filePath);
});
}).on('error', (err: string) => {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
});
} catch (err) {
logger.log('Could not get server icon.');
logger.log(err);
logger.reportSentry(err);
resolve(defaultIconUrl);
}
});
}
updateSavedServer(url: string, index: number): void {
// Does not promise successful update
const { ignoreCerts } = this.getDomain(index);
this.checkDomain(url, ignoreCerts, true).then(newServerConf => {
this.saveServerIcon(newServerConf, ignoreCerts).then(localIconUrl => {
newServerConf.icon = localIconUrl;
this.updateDomain(index, newServerConf);
this.reloadDB();
});
});
}
reloadDB(): void {
const domainJsonPath = path.join(app.getPath('userData'), 'config/domain.json');
try {
const file = fs.readFileSync(domainJsonPath, 'utf8');
JSON.parse(file);
} catch (err) {
if (fs.existsSync(domainJsonPath)) {
fs.unlinkSync(domainJsonPath);
dialog.showErrorBox(
'Error saving new organization',
'There seems to be error while saving new organization, ' +
'you may have to re-add your previous organizations back.'
);
logger.error('Error while JSON parsing domain.json: ');
logger.error(err);
logger.reportSentry(err);
}
}
this.db = new JsonDB(domainJsonPath, true, true);
}
generateFilePath(url: string): string {
const dir = `${app.getPath('userData')}/server-icons`;
const extension = path.extname(url).split('?')[0];
let hash = 5381;
let len = url.length;
while (len) {
hash = (hash * 33) ^ url.charCodeAt(--len);
}
// Create 'server-icons' directory if not existed
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
return `${dir}/${hash >>> 0}${extension}`;
}
formatUrl(domain: any): string {
const hasPrefix = (domain.indexOf('http') === 0);
if (hasPrefix) {
return domain;
} else {
return (domain.indexOf('localhost:') >= 0) ? `http://${domain}` : `https://${domain}`;
}
}
}
export = new DomainUtil();

View File

@@ -1,8 +1,14 @@
'use strict';
const wurl = require('wurl');
// TODO: TypeScript - Add @types/
import wurl = require('wurl');
let instance = null;
let instance: null | LinkUtil = null;
interface IsInternalResponse {
isInternalUrl: boolean;
isUploadsUrl: boolean;
}
class LinkUtil {
constructor() {
@@ -15,7 +21,7 @@ class LinkUtil {
return instance;
}
isInternal(currentUrl, newUrl) {
isInternal(currentUrl: string, newUrl: string): IsInternalResponse {
const currentDomain = wurl('hostname', currentUrl);
const newDomain = wurl('hostname', newUrl);
@@ -29,17 +35,17 @@ class LinkUtil {
};
}
isImage(url) {
isImage(url: string): boolean {
// test for images extension as well as urls like .png?s=100
const isImageUrl = /\.(bmp|gif|jpg|jpeg|png|webp)\?*.*$/i;
return isImageUrl.test(url);
}
isPDF(url) {
isPDF(url: string): boolean {
// test for pdf extension
const isPDFUrl = /\.(pdf)\?*.*$/i;
return isPDFUrl.test(url);
}
}
module.exports = new LinkUtil();
export = new LinkUtil();

View File

@@ -1,12 +1,13 @@
'use strict';
import JsonDB from 'node-json-db';
import fs = require('fs');
import path = require('path');
import electron = require('electron');
import Logger = require('./logger-util');
const fs = require('fs');
const path = require('path');
const process = require('process');
const remote =
process.type === 'renderer' ? require('electron').remote : require('electron');
const JsonDB = require('node-json-db');
const Logger = require('./logger-util');
process.type === 'renderer' ? electron.remote : electron;
const logger = new Logger({
file: 'linux-update-util.log',
@@ -15,10 +16,11 @@ const logger = new Logger({
/* To make the util runnable in both main and renderer process */
const { dialog, app } = remote;
let instance = null;
let instance: null | LinuxUpdateUtil = null;
class LinuxUpdateUtil {
db: JsonDB;
constructor() {
if (instance) {
return instance;
@@ -30,7 +32,7 @@ class LinuxUpdateUtil {
return instance;
}
getUpdateItem(key, defaultValue = null) {
getUpdateItem(key: string, defaultValue: any = null): any {
this.reloadDB();
const value = this.db.getData('/')[key];
if (value === undefined) {
@@ -41,17 +43,17 @@ class LinuxUpdateUtil {
}
}
setUpdateItem(key, value) {
setUpdateItem(key: string, value: any): void {
this.db.push(`/${key}`, value, true);
this.reloadDB();
}
removeUpdateItem(key) {
removeUpdateItem(key: string): void {
this.db.delete(`/${key}`);
this.reloadDB();
}
reloadDB() {
reloadDB(): void {
const linuxUpdateJsonPath = path.join(app.getPath('userData'), '/config/updates.json');
try {
const file = fs.readFileSync(linuxUpdateJsonPath, 'utf8');
@@ -71,4 +73,4 @@ class LinuxUpdateUtil {
}
}
module.exports = new LinuxUpdateUtil();
export = new LinuxUpdateUtil();

View File

@@ -1,93 +0,0 @@
const NodeConsole = require('console').Console;
const fs = require('fs');
const isDev = require('electron-is-dev');
const { initSetUp } = require('./default-util');
const { sentryInit, captureException } = require('./sentry-util');
initSetUp();
sentryInit();
let app = null;
if (process.type === 'renderer') {
app = require('electron').remote.app;
} else {
app = require('electron').app;
}
const browserConsole = console;
const logDir = `${app.getPath('userData')}/Logs`;
class Logger {
constructor(opts = {}) {
let {
timestamp = true,
file = 'console.log',
level = true,
logInDevMode = false
} = opts;
file = `${logDir}/${file}`;
if (timestamp === true) {
timestamp = this.getTimestamp;
}
const fileStream = fs.createWriteStream(file, { flags: 'a' });
const nodeConsole = new NodeConsole(fileStream);
this.nodeConsole = nodeConsole;
this.timestamp = timestamp;
this.level = level;
this.logInDevMode = logInDevMode;
this.setUpConsole();
}
_log(type, ...args) {
const {
nodeConsole, timestamp, level, logInDevMode
} = this;
let nodeConsoleLog;
/* eslint-disable no-fallthrough */
switch (true) {
case typeof timestamp === 'function':
args.unshift(timestamp() + ' |\t');
case (level !== false):
args.unshift(type.toUpperCase() + ' |');
case isDev || logInDevMode:
nodeConsoleLog = nodeConsole[type] || nodeConsole.log;
nodeConsoleLog.apply(null, args);
default: break;
}
/* eslint-enable no-fallthrough */
browserConsole[type].apply(null, args);
}
setUpConsole() {
for (const type in browserConsole) {
this.setupConsoleMethod(type);
}
}
setupConsoleMethod(type) {
this[type] = (...args) => {
this._log(type, ...args);
};
}
getTimestamp() {
const date = new Date();
const timestamp =
`${date.getMonth()}/${date.getDate()} ` +
`${date.getMinutes()}:${date.getSeconds()}`;
return timestamp;
}
reportSentry(err) {
captureException(err);
}
}
module.exports = Logger;

View File

@@ -0,0 +1,155 @@
import { Console as NodeConsole } from 'console'; // eslint-disable-line node/prefer-global/console
import { initSetUp } from './default-util';
import { sentryInit, captureException } from './sentry-util';
import fs = require('fs');
import os = require('os');
import isDev = require('electron-is-dev');
import electron = require('electron');
// this interface adds [key: string]: any so
// we can do console[type] later on in the code
interface PatchedConsole extends Console {
[key: string]: any;
}
interface LoggerOptions {
timestamp?: any;
file?: string;
level?: boolean;
logInDevMode?: boolean;
}
initSetUp();
let app: Electron.App = null;
let reportErrors = true;
if (process.type === 'renderer') {
app = electron.remote.app;
// Report Errors to Sentry only if it is enabled in settings
// Gets the value of reportErrors from config-util for renderer process
// For main process, sentryInit() is handled in index.js
const { ipcRenderer } = electron;
ipcRenderer.send('error-reporting');
ipcRenderer.on('error-reporting-val', (_event: any, errorReporting: boolean) => {
reportErrors = errorReporting;
if (reportErrors) {
sentryInit();
}
});
} else {
app = electron.app;
}
const browserConsole: PatchedConsole = console;
const logDir = `${app.getPath('userData')}/Logs`;
class Logger {
nodeConsole: PatchedConsole;
timestamp: any; // TODO: TypeScript - Figure out how to make this work with string | Function.
level: boolean;
logInDevMode: boolean;
[key: string]: any;
constructor(opts: LoggerOptions = {}) {
let {
timestamp = true,
file = 'console.log',
level = true,
logInDevMode = false
} = opts;
file = `${logDir}/${file}`;
if (timestamp === true) {
timestamp = this.getTimestamp;
}
// Trim log according to type of process
if (process.type === 'renderer') {
requestIdleCallback(() => this.trimLog(file));
} else {
process.nextTick(() => this.trimLog(file));
}
const fileStream = fs.createWriteStream(file, { flags: 'a' });
const nodeConsole = new NodeConsole(fileStream);
this.nodeConsole = nodeConsole;
this.timestamp = timestamp;
this.level = level;
this.logInDevMode = logInDevMode;
this.setUpConsole();
}
_log(type: string, ...args: any[]): void {
const {
nodeConsole, timestamp, level, logInDevMode
} = this;
let nodeConsoleLog;
/* eslint-disable no-fallthrough */
switch (true) {
case typeof timestamp === 'function':
args.unshift(timestamp() + ' |\t');
case (level !== false):
args.unshift(type.toUpperCase() + ' |');
case isDev || logInDevMode:
nodeConsoleLog = nodeConsole[type] || nodeConsole.log;
nodeConsoleLog.apply(null, args); // eslint-disable-line prefer-spread
default: break;
}
/* eslint-enable no-fallthrough */
browserConsole[type].apply(null, args);
}
setUpConsole(): void {
for (const type in browserConsole) {
this.setupConsoleMethod(type);
}
}
setupConsoleMethod(type: string): void {
this[type] = (...args: any[]) => {
const log = this._log.bind(this, type, ...args);
log();
};
}
getTimestamp(): string {
const date = new Date();
const timestamp =
`${date.getMonth()}/${date.getDate()} ` +
`${date.getMinutes()}:${date.getSeconds()}`;
return timestamp;
}
reportSentry(err: string): void {
if (reportErrors) {
captureException(err);
}
}
trimLog(file: string): void{
fs.readFile(file, 'utf8', (err, data) => {
if (err) {
throw err;
}
const MAX_LOG_FILE_LINES = 500;
const logs = data.split(os.EOL);
const logLength = logs.length - 1;
// Keep bottom MAX_LOG_FILE_LINES of each log instance
if (logLength > MAX_LOG_FILE_LINES) {
const trimmedLogs = logs.slice(logLength - MAX_LOG_FILE_LINES);
const toWrite = trimmedLogs.join(os.EOL);
fs.writeFileSync(file, toWrite);
}
});
}
}
export = Logger;

View File

@@ -1,15 +1,11 @@
// This util function returns the page params if they're present else returns null
function isPageParams() {
export function isPageParams(): null | object {
let webpageParams = null;
try {
// eslint-disable-next-line no-undef, camelcase
// eslint-disable-next-line no-undef, @typescript-eslint/camelcase
webpageParams = page_params;
} catch (err) {
} catch (_) {
webpageParams = null;
}
return webpageParams;
}
module.exports = {
isPageParams
};

View File

@@ -1,9 +1,15 @@
'use strict';
const url = require('url');
const ConfigUtil = require('./config-util.js');
import url = require('url');
let instance = null;
import ConfigUtil = require('./config-util');
let instance: null | ProxyUtil = null;
interface ProxyRule {
hostname?: string;
port?: number;
}
class ProxyUtil {
constructor() {
@@ -17,8 +23,13 @@ class ProxyUtil {
}
// Return proxy to be used for a particular uri, to be used for request
getProxy(uri) {
uri = url.parse(uri);
getProxy(_uri: string): ProxyRule | void {
const parsedUri = url.parse(_uri);
if (parsedUri === null) {
return;
}
const uri = parsedUri;
const proxyRules = ConfigUtil.getConfigItem('proxyRules', '').split(';');
// If SPS is on and system uses no proxy then request should not try to use proxy from
// environment. NO_PROXY = '*' makes request ignore all environment proxy variables.
@@ -27,9 +38,9 @@ class ProxyUtil {
return;
}
const proxyRule = {};
const proxyRule: any = {};
if (uri.protocol === 'http:') {
proxyRules.forEach(proxy => {
proxyRules.forEach((proxy: string) => {
if (proxy.includes('http=')) {
proxyRule.hostname = proxy.split('http=')[1].trim().split(':')[0];
proxyRule.port = proxy.split('http=')[1].trim().split(':')[1];
@@ -39,7 +50,7 @@ class ProxyUtil {
}
if (uri.protocol === 'https:') {
proxyRules.forEach(proxy => {
proxyRules.forEach((proxy: string) => {
if (proxy.includes('https=')) {
proxyRule.hostname = proxy.split('https=')[1].trim().split(':')[0];
proxyRule.port = proxy.split('https=')[1].trim().split(':')[1];
@@ -49,14 +60,15 @@ class ProxyUtil {
}
}
resolveSystemProxy(mainWindow) {
// TODO: Refactor to async function
resolveSystemProxy(mainWindow: Electron.BrowserWindow): void {
const page = mainWindow.webContents;
const ses = page.session;
const resolveProxyUrl = 'www.google.com';
const resolveProxyUrl = 'www.example.com';
// Check HTTP Proxy
const httpProxy = new Promise(resolve => {
ses.resolveProxy('http://' + resolveProxyUrl, proxy => {
ses.resolveProxy('http://' + resolveProxyUrl, (proxy: string) => {
let httpString = '';
if (proxy !== 'DIRECT') {
// in case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
@@ -70,12 +82,12 @@ class ProxyUtil {
});
// Check HTTPS Proxy
const httpsProxy = new Promise(resolve => {
ses.resolveProxy('https://' + resolveProxyUrl, proxy => {
ses.resolveProxy('https://' + resolveProxyUrl, (proxy: string) => {
let httpsString = '';
if (proxy !== 'DIRECT' || proxy.includes('HTTPS')) {
// in case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
// for all other HTTP or direct url:port both uses PROXY
if (proxy.includes('PROXY' || proxy.includes('HTTPS'))) {
if (proxy.includes('PROXY') || proxy.includes('HTTPS')) {
httpsString += 'https=' + proxy.split('PROXY')[1] + ';';
}
}
@@ -85,7 +97,7 @@ class ProxyUtil {
// Check FTP Proxy
const ftpProxy = new Promise(resolve => {
ses.resolveProxy('ftp://' + resolveProxyUrl, proxy => {
ses.resolveProxy('ftp://' + resolveProxyUrl, (proxy: string) => {
let ftpString = '';
if (proxy !== 'DIRECT') {
if (proxy.includes('PROXY')) {
@@ -98,7 +110,7 @@ class ProxyUtil {
// Check SOCKS Proxy
const socksProxy = new Promise(resolve => {
ses.resolveProxy('socks4://' + resolveProxyUrl, proxy => {
ses.resolveProxy('socks4://' + resolveProxyUrl, (proxy: string) => {
let socksString = '';
if (proxy !== 'DIRECT') {
if (proxy.includes('SOCKS5')) {
@@ -127,4 +139,4 @@ class ProxyUtil {
}
}
module.exports = new ProxyUtil();
export = new ProxyUtil();

View File

@@ -1,5 +1,5 @@
const isOnline = require('is-online');
const Logger = require('./logger-util');
import isOnline = require('is-online');
import Logger = require('./logger-util');
const logger = new Logger({
file: `domain-util.log`,
@@ -7,16 +7,22 @@ const logger = new Logger({
});
class ReconnectUtil {
constructor(serverManagerView) {
// TODO: TypeScript - Figure out how to annotate serverManagerView
// it should be ServerManagerView; maybe make it a generic so we can
// pass the class from main.js
serverManagerView: any;
alreadyReloaded: boolean;
constructor(serverManagerView: any) {
this.serverManagerView = serverManagerView;
this.alreadyReloaded = false;
}
clearState() {
clearState(): void {
this.alreadyReloaded = false;
}
pollInternetAndReload() {
pollInternetAndReload(): void {
const pollInterval = setInterval(() => {
this._checkAndReload()
.then(status => {
@@ -28,14 +34,15 @@ class ReconnectUtil {
}, 1500);
}
_checkAndReload() {
// TODO: Make this a async function
_checkAndReload(): Promise<boolean> {
return new Promise(resolve => {
if (!this.alreadyReloaded) { // eslint-disable-line no-negated-condition
isOnline()
.then(online => {
.then((online: boolean) => {
if (online) {
if (!this.alreadyReloaded) {
this.serverManagerView.reloadView();
this.serverManagerView.reloadCurrentView();
}
logger.log('You\'re back online.');
return resolve(true);
@@ -57,4 +64,4 @@ class ReconnectUtil {
}
}
module.exports = ReconnectUtil;
export = ReconnectUtil;

View File

@@ -0,0 +1,73 @@
import fs = require('fs');
import ConfigUtil = require('./config-util');
import Logger = require('./logger-util');
import ProxyUtil = require('./proxy-util');
import CertificateUtil = require('./certificate-util');
import SystemUtil = require('./system-util');
const logger = new Logger({
file: `request-util.log`,
timestamp: true
});
let instance: null | RequestUtil = null;
// TODO: TypeScript - Use ProxyRule for the proxy property
// we can do this now since we use export = ProxyUtil syntax
interface RequestUtilResponse {
ca: string;
proxy: string | void | object;
ecdhCurve: 'auto';
headers: { 'User-Agent': string };
rejectUnauthorized: boolean;
}
class RequestUtil {
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
// ignoreCerts parameter helps in fetching server icon and
// other server details when user chooses to ignore certificate warnings
requestOptions(domain: string, ignoreCerts: boolean): RequestUtilResponse {
domain = this.formatUrl(domain);
const certificate = CertificateUtil.getCertificate(
encodeURIComponent(domain)
);
let certificateLocation = '';
if (certificate) {
// To handle case where certificate has been moved from the location in certificates.json
try {
certificateLocation = fs.readFileSync(certificate, 'utf8');
} catch (err) {
logger.warn(`Error while trying to get certificate: ${err}`);
}
}
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
// If certificate for the domain exists add it as a ca key in the request's parameter else consider only domain as the parameter for request
// Add proxy as a parameter if it is being used.
return {
ca: certificateLocation ? certificateLocation : '',
proxy: proxyEnabled ? ProxyUtil.getProxy(domain) : '',
ecdhCurve: 'auto',
headers: { 'User-Agent': SystemUtil.getUserAgent() },
rejectUnauthorized: !ignoreCerts
};
}
formatUrl(domain: string): string {
const hasPrefix = domain.startsWith('http', 0);
if (hasPrefix) {
return domain;
} else {
return domain.includes('localhost:') ? `http://${domain}` : `https://${domain}`;
}
}
}
const requestUtil = new RequestUtil();
export = requestUtil;

View File

@@ -1,20 +0,0 @@
const { init, captureException } = require('@sentry/electron');
const isDev = require('electron-is-dev');
const sentryInit = () => {
if (!isDev) {
init({
dsn: 'SENTRY_DSN',
// We should ignore this error since it's harmless and we know the reason behind this
// This error mainly comes from the console logs.
// This is a temp solution until Sentry supports disabling the console logs
ignoreErrors: ['does not appear to be a valid Zulip server'],
sendTimeout: 30 // wait 30 seconds before considering the sending capture to have failed, default is 1 second
});
}
};
module.exports = {
sentryInit,
captureException
};

View File

@@ -0,0 +1,21 @@
import { init } from '@sentry/electron';
import isDev = require('electron-is-dev');
import path = require('path');
import dotenv = require('dotenv');
dotenv.config({ path: path.resolve(__dirname, '/../../../../.env') });
export const sentryInit = (): void => {
if (!isDev) {
init({
dsn: process.env.SENTRY_DSN,
// We should ignore this error since it's harmless and we know the reason behind this
// This error mainly comes from the console logs.
// This is a temp solution until Sentry supports disabling the console logs
ignoreErrors: ['does not appear to be a valid Zulip server']
// sendTimeout: 30 // wait 30 seconds before considering the sending capture to have failed, default is 1 second
});
}
};
export { captureException } from '@sentry/electron';

View File

@@ -1,12 +1,16 @@
'use strict';
import { remote } from 'electron';
const {app} = require('electron').remote;
import os = require('os');
const os = require('os');
let instance = null;
const { app } = remote;
let instance: null | SystemUtil = null;
class SystemUtil {
connectivityERR: string[];
userAgent: string | null;
constructor() {
if (instance) {
return instance;
@@ -27,29 +31,30 @@ class SystemUtil {
return instance;
}
getOS() {
if (os.platform() === 'darwin') {
getOS(): string {
const platform = os.platform();
if (platform === 'darwin') {
return 'Mac';
}
if (os.platform() === 'linux') {
} else if (platform === 'linux') {
return 'Linux';
}
if (os.platform() === 'win32' || os.platform() === 'win64') {
} else if (platform === 'win32') {
if (parseFloat(os.release()) < 6.2) {
return 'Windows 7';
} else {
return 'Windows 10';
}
} else {
return '';
}
}
setUserAgent(webViewUserAgent) {
this.userAgent = 'ZulipElectron/' + app.getVersion() + ' ' + webViewUserAgent;
setUserAgent(webViewUserAgent: string): void {
this.userAgent = `ZulipElectron/${app.getVersion()} ${webViewUserAgent}`;
}
getUserAgent() {
getUserAgent(): string | null {
return this.userAgent;
}
}
module.exports = new SystemUtil();
export = new SystemUtil();

View File

@@ -1,56 +1,65 @@
<!DOCTYPE html>
<html lang="en" class="responsive desktop">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip</title>
<link rel="stylesheet" href="css/main.css" type="text/css" media="screen">
</head>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip</title>
<link rel="stylesheet" href="css/main.css" type="text/css" media="screen">
</head>
<body>
<div id="content">
<div class="popup">
<span class="popuptext hidden" id="fullscreen-popup"></span>
</div>
<div id="sidebar" class="toggle-sidebar">
<div id="view-controls-container">
<div id="tabs-container"></div>
<div id="add-tab" class="tab functional-tab">
<div class="server-tab" id="add-action">
<i class="material-icons">add</i>
<body>
<div id="content">
<div class="popup">
<span class="popuptext hidden" id="fullscreen-popup"></span>
</div>
<div id="sidebar" class="toggle-sidebar">
<div id="view-controls-container">
<div id="tabs-container"></div>
<div id="add-tab" class="tab functional-tab">
<div class="server-tab" id="add-action">
<i class="material-icons">add</i>
</div>
<span id="add-server-tooltip" style="display:none">Add organization</span>
</div>
</div>
<div id="actions-container">
<div class="action-button" id="dnd-action">
<i class="material-icons md-48">notifications</i>
<span id="dnd-tooltip" style="display:none">Do Not Disturb</span>
</div>
<div class="action-button" id="reload-action">
<i class="material-icons md-48">refresh</i>
<span id="reload-tooltip" style="display:none">Reload</span>
</div>
<div class="action-button" id="loading-action">
<i class="refresh material-icons md-48">loop</i>
<span id="loading-tooltip" style="display:none">Loading</span>
</div>
<div class="action-button disable" id="back-action">
<i class="material-icons md-48">arrow_back</i>
<span id="back-tooltip" style="display:none">Go Back</span>
</div>
<div class="action-button" id="settings-action">
<i class="material-icons md-48">settings</i>
<span id="setting-tooltip" style="display:none">Settings</span>
</div>
</div>
</div>
<div id="main-container">
<div id="webviews-container"></div>
</div>
</div>
<span id="add-server-tooltip" style="display:none">Add organization</span>
</div>
</div>
<div id="actions-container">
<div class="action-button" id="dnd-action">
<i class="material-icons md-48">notifications</i>
<span id="dnd-tooltip" style="display:none">Do Not Disturb</span>
</div>
<div class="action-button" id="reload-action">
<i class="material-icons md-48">refresh</i>
<span id="reload-tooltip" style="display:none">Reload</span>
</div>
<div class="action-button disable" id="back-action">
<i class="material-icons md-48">arrow_back</i>
<span id="back-tooltip" style="display:none">Go Back</span>
</div>
<div class="action-button" id="settings-action">
<i class="material-icons md-48">settings</i>
<span id="setting-tooltip" style="display:none">Settings</span>
</div>
</div>
</div>
<div id="main-container">
<div id="webviews-container"></div>
</div>
</div>
<div id="feedback-modal">
<send-feedback></send-feedback>
</div>
</body>
<script src="js/main.js"></script>
<script>require('./js/shared/preventdrag.js')</script>
</html>
<div id="feedback-modal">
<send-feedback></send-feedback>
</div>
</body>
<script>
// we don't use src='./js/main' in the script tag because
// it messes up require module path resolution
require('./js/main');
</script>
<script>require('./js/shared/preventdrag.js')</script>
</html>

View File

@@ -1,22 +1,22 @@
<!DOCTYPE html>
<html lang="en" class="responsive desktop">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip - Network Troubleshooting</title>
<link rel="stylesheet" href="css/network.css" type="text/css" media="screen">
</head>
<body>
<div id="content">
<div id="picture"><img src="img/zulip_network.png"></div>
<div id="title">Zulip can't connect</div>
<div id="description">
<div>Your computer seems to be offline.</div>
<div>We will keep trying to reconnect, or you can try now.</div>
</div>
<div id="reconnect">Try now</div>
</div>
</body>
<script src="js/pages/network.js"></script>
<script>require('./js/shared/preventdrag.js')</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip - Network Troubleshooting</title>
<link rel="stylesheet" href="css/network.css" type="text/css" media="screen">
</head>
<body>
<div id="content">
<div id="picture"><img src="img/zulip_network.png"></div>
<div id="title">Zulip can't connect</div>
<div id="description">
<div>Your computer seems to be offline.</div>
<div>We will keep trying to reconnect, or you can try now.</div>
</div>
<div id="reconnect">Try now</div>
</div>
</body>
<script src="js/pages/network.js"></script>
<script>require('./js/shared/preventdrag.js')</script>
</html>

View File

@@ -1,17 +1,19 @@
<!DOCTYPE html>
<html lang="en" class="responsive desktop">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip - Settings</title>
<link rel="stylesheet" href="css/preference.css" type="text/css" media="screen">
</head>
<body>
<div id="content">
<div id="sidebar"></div>
<div id="settings-container"></div>
</div>
</body>
<script src="js/pages/preference/preference.js"></script>
<script>require('./js/shared/preventdrag.js')</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>Zulip - Settings</title>
<link rel="stylesheet" href="css/preference.css" type="text/css" media="screen">
</head>
<body>
<div id="content">
<div id="sidebar"></div>
<div id="settings-container"></div>
</div>
</body>
<script>
require('./js/pages/preference/preference.js');
require('./js/shared/preventdrag.js')
</script>
</html>

27
app/resources/messages.ts Normal file
View File

@@ -0,0 +1,27 @@
class Messages {
invalidZulipServerError(domain: string): string {
return `${domain} does not appear to be a valid Zulip server. Make sure that
\n • You can connect to that URL in a web browser.\
\n • If you need a proxy to connect to the Internet, that you've configured your proxy in the Network settings.\
\n • It's a Zulip server. (The oldest supported version is 1.6).\
\n • The server has a valid certificate. (You can add custom certificates in Settings > Organizations).`;
}
noOrgsError(domain: string): string {
return `${domain} does not have any organizations added.\
\nPlease contact your server administrator.`;
}
certErrorMessage(domain: string, error: string): string {
return `Do you trust certificate from ${domain}? \n ${error}`;
}
certErrorDetail(): string {
return `The organization you're connecting to is either someone impersonating the Zulip server you entered, or the server you're trying to connect to is configured in an insecure way.
\nIf you have a valid certificate please add it from Settings>Organizations and try to add the organization again.
\nUnless you have a good reason to believe otherwise, you should not proceed.
\nYou can click here if you'd like to proceed with the connection.`;
}
}
export = new Messages();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -2,6 +2,111 @@
All notable changes to the Zulip desktop app are documented in this file.
### v3.1.0-beta --2019-07-19
**New features**:
* Add option to find accounts by email.
* Add option to hide Menu bar to View menu.
* Show a loading indicator in the sidebar.
* Update Help Center to open help page of the currently active server.
* Improve auto-detection of spellchecker language.
* Disable menu items on non-server pages.
* Support dark mode on macOS.
**Fixes**:
* Updated, more robust server validation logic.
* Fix JSON DB errors observed when switching tabs.
* Remove unused `isLoading` function from `Tab`.
* Remove unused `defaultId` parameter.
* Fix syntax error in `proxy-util.js`.
* Fix issue with creation of large `.node` files in the `Temp` folder on Windows machines.
* Fix issue where drafts were not saved properly.
**Development**:
* Migrate codebase to TypeScript.
* Set the indent_size in `.editconfig` to 4.
* Use `.env` file for reading Sentry DSN.
**Documentation**:
* Improve development guide.
**Module updates**:
* Upgrade xo to v0.24.0.
* Upgrade node-json-db to v0.9.2.
* Upgrade electron to v3.1.10.
* Add missing transitive dependencies.
### v3.0.0 --2019-05-20
**New features**:
* Add context menu in left sidebar.
* Enable per-user installation on Windows.
* Switch to next server on Ctrl+Tab.
* Add option to copy zulip URL.
* Allow zoom options from numpad.
* Use server language for spellchecker for all platforms.
* Allow installing app without admin privileges.
* Allow insecure requests on user request.
* Unify case across menus and settings.
**Enhancements**:
* Remove Found bug button.
* Set custom css to false by default.
* Disable beta updates if auto updates disabled
* Update menu items on setting page.
* Include certificates in all requests for icon.
* Document show sidebar shortcut properly.
* Improve organization page.
* Improve wording of adding a new org button.
* Increase width of add a new org button.
* Add eol for linebreaks on windows.
* Teach git to ignore unnecessary binary files.
* Send user-agent with request.
* Minimize to tray on startup.
* Update test config files.
* Ensure backward compatibility when using narrow.by_topic.
* Use path.sep for path separator to support Windows.
* Change the window title to contain active Realm's name.
* Use path.basename to get certificate file name.
* Disable pdf-viewer window.
* Default to starting app on login.
* Modify reset app data button.
* Add requestOptions to replace request instances.
* Workaround buggy focus switching in Electron 3.0.10.
* Reorder file menu and add option to Add Organization.
* Improve development guide.
* Implement CSS linting with stylelint.
* Add "role" key to webview property.
* Implement HTML Linting with htmlhint and fix indent.
* Limit the number of lines in log files.
* Fix focus after clicking back button.
* Remove minimize and close from File menu.
* Add config for installer name.
**Fixes**:
* Fix `request` ecdhCurve mismatch errors
* Fix typo in network error message.
* Fix context menu not working on adding new org.
* Fix reply from notification.
* Fix shorcut section horizontal alignment.
* Fix broken link in docs.
* Fix grammatical errors.
* Fix typo error in issue template.
* Fix text for Toggle DND in sidebar on hover.
* Fix focus after soft reload.
* Fix tip's place for Windows & Linux.
**Module updates**:
* Update node-json-db to v0.9.1.
* Update sentry to v0.12.1.
* Update electron-window-state to v5.0.3.
* Update electron to v3.0.10.
* Update electron-builder to v20.40.2.
* Update electron-sentry to v0.14.0.
* Update dependencies to fix minor dev security alerts.
* Update snap config.
### v2.3.82 --2018-09-25
**New features**:
@@ -292,7 +397,7 @@ electron-updater - `v2.21.8`
* Setting page and left-sidebar UI improvements
* Other minor improvments
* Other minor improvements
@@ -419,7 +524,7 @@ electron-updater - `v2.21.8`
* Fixed a bug which was caused by app's shortcuts. From now on our shortcuts won't hijack other apps shortcuts
* Removed [electron-localshortcut](https://github.com/parro-it/electron-localshortcut) completely. Now we only depends on menu accelerators for keyboard shortcuts
* Removed [electron-localshortcut](https://github.com/parro-it/electron-localshortcut) completely. Now we only depend on menu accelerators for keyboard shortcuts
* Handle certificate issue properly
@@ -620,7 +725,7 @@ electron-updater - `v2.21.8`
* Properly signed app for macOS
* Toggle tray icon
* Better error handling when no internet connenction
* Better error handling when no internet connection
@@ -634,7 +739,7 @@ electron-updater - `v2.21.8`
### v0.5.8 --2017-02-13
**Enhacements**:
**Enhancements**:
Smaller Windows installer size
<hr>
@@ -650,7 +755,7 @@ Minor improvements
### v0.5.6 --2017-02-07
**Enhacements**:
**Enhancement**:
- Using NSIS instead of [Squirrel.Windows](https://github.com/Squirrel/Squirrel.Windows) on Windows
@@ -672,9 +777,9 @@ Minor improvements
**Fixes**:
- Fixed :
- Auto-updates
- Spellchecker
- Zooming functionality
- Auto-updates
- Spellchecker
- Zooming functionality
- Removed unused node modules
- Using stable version for node modules
@@ -718,7 +823,7 @@ Minor improvements
### v0.5.1 --2016-11-23
**Enhacements**:
**Enhancement**:
- Added Spellchecker support with correct spell suggestions
@@ -759,6 +864,6 @@ Minor improvements
### v0.0.1-alpha -- 2016-08-31
**Enhacements**:
**Enhancement**:
* Added DMG installer for macOS

View File

@@ -1,6 +1,6 @@
# Development setup
# Development Setup
This is a guide to running the Zulip desktop app from a source tree,
This is a guide to running the Zulip desktop app from source,
in order to contribute to developing it.
## Prerequisites
@@ -8,6 +8,7 @@ in order to contribute to developing it.
To build and run the app from source, you'll need the following:
* [Git](http://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* Use our [Git Guide](https://zulip.readthedocs.io/en/latest/git/setup.html) to get started with Git and GitHub.
* [Node.js](https://nodejs.org) >= v6.9.0
* [NPM](https://www.npmjs.com/get-npm) and
[node-gyp](https://github.com/nodejs/node-gyp#installation),
@@ -15,35 +16,50 @@ To build and run the app from source, you'll need the following:
* [Python](https://www.python.org/downloads/release/python-2713/)
(v2.7.x recommended)
* A C++ compiler compatible with C++11
* Linux users also need [Snapcraft](https://snapcraft.io/)
* Development headers for the libXext, libXtst, and libxkbfile libraries
* Development headers for the libXext, libXtst, and libxkbfile libraries, which can be installed using apt on Ubuntu using
```sh
$ sudo apt install libxext-dev libxtst-dev libxkbfile-dev libgconf-2-4
```
### Debian/Ubuntu and friends
### Ubuntu/Linux and other Debian-based distributions
On a system running Debian, Ubuntu, or another Debian-based Linux
distribution, you can install all dependencies through the package
manager (see [here][nodesource-install] for more on the first command):
manager (see [here][node-debian] for more on the first command):
```sh
$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt install git nodejs python build-essential snapcraft libxext-dev libxtst-dev libxkbfile-dev libgconf-2-4
```
[nodesource-install]: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions
[node-debian]: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions
### Other OSes
### MacOS
Other developers run the app on Windows, macOS, and possibly other OSes.
PRs to add specific instructions to this doc are welcome!
On a system running MacOS, you can refer to [official nodejs docs][node-mac] to
install nodejs. To ensure Node.js has been installed, run ```node -v``` in terminal to know your node version.
On Windows, your C++ compiler should be Visual Studio 2015 or later.
[node-mac]: https://nodejs.org/en/download/package-manager/#macos
If [NPM](https://www.npmjs.com/get-npm) and [node-gyp](https://github.com/nodejs/node-gyp#installation) don't come bundled with your Node.js installation, you will need to install them manually.
### Windows
- Download Node.js for Windows and install it. You can refer to the official docs [here][node-windows] to do so. To ensure Node.js has been installed, run ```node -v``` in Git Bash to know your node version.
[node-windows]: https://nodejs.org/en/download/package-manager/#windows
- Also, install install Windows-Build-Tools to compile native node modules by using
```sh
$ npm install --global windows-build-tools
```
## Download, build, and run
Clone the source locally:
```sh
$ git clone https://github.com/zulip/zulip-electron
$ cd zulip-electron
$ git clone https://github.com/zulip/zulip-desktop
$ cd zulip-desktop
```
Install project dependencies:
@@ -61,6 +77,18 @@ Start and watch changes:
$ npm run dev
```
Run tests:
```sh
$ npm test
```
## How to contribute?
Feel free to fork this repository, test it locally and then report any bugs
you find in the [issue tracker](https://github.com/zulip/zulip-desktop/issues).
You can read more about making contributions in our [Contributing Guide](./CONTRIBUTING.md).
## Troubleshooting
If you have any problems running the app, see the [most common
@@ -75,11 +103,12 @@ npm run dist
This command will produce distributable packages or installers for the
operating system you're running on:
* on Windows, a Windows installer file
* on Windows, a .7z nsis file and a .exe WebSetup file
* on macOS, a `.dmg` file
* on Linux, a plain `.zip` file as well as a `.deb` file, `.snap` file and an
`AppImage` file.
To generate all three types, you will need all three operating
To generate all three types of files, you will need all three operating
systems.
The output files appear in the `dist/` directory.
The output distributable packages appear in the `dist/` directory.

View File

@@ -21,8 +21,8 @@ C:\Windows\system32> npm install --global --production windows-build-tools
Clone the source locally:
```sh
$ git clone https://github.com/zulip/zulip-electron
$ cd zulip-electron
$ git clone https://github.com/zulip/zulip-desktop
$ cd zulip-desktop
```
Install project dependencies:

View File

@@ -1,3 +1,3 @@
### Want to contribute to this Wiki?
[Edit `/docs` files and send a pull request.](https://github.com/zulip/zulip-electron/tree/master/docs)
[Edit `/docs` files and send a pull request.](https://github.com/zulip/zulip-desktop/tree/master/docs)

View File

@@ -5,16 +5,37 @@ const electron = require('electron-connect').server.create({
});
const tape = require('gulp-tape');
const tapColorize = require('tap-colorize');
const ts = require("gulp-typescript");
const tsProject = ts.createProject("tsconfig.json");
const glob = require('glob');
const { execSync } = require('child_process');
const baseFilePattern = 'app/+(main|renderer)/**/*';
const globOptions = { cwd: __dirname };
const jsFiles = glob.sync(baseFilePattern + '.js', globOptions);
const tsFiles = glob.sync(baseFilePattern + '.ts', globOptions);
if (jsFiles.length !== tsFiles.length) {
const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';
console.log('Compiling typescript files...');
execSync(`${npx} tsc`);
}
gulp.task("compile", function () {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest("app"));
});
gulp.task('dev', () => {
// Start browser process
electron.start();
// Restart browser process
gulp.watch('app/main/*.js', gulp.series('restart:browser'));
gulp.watch('app/main/*.ts', gulp.series('compile', 'restart:browser'));
// Reload renderer process
gulp.watch('app/renderer/css/*.css', gulp.series('reload:renderer'));
gulp.watch('app/renderer/*.html', gulp.series('reload:renderer'));
gulp.watch('app/renderer/js/**/*.js', gulp.series('reload:renderer'));
gulp.watch('app/renderer/js/**/*.ts', gulp.series('compile', 'reload:renderer'));
});
gulp.task('restart:browser', done => {

View File

@@ -1,10 +1,10 @@
# How to install
**Note:** If you download from the [releases page](https://github.com/zulip/zulip-electron/releases), be careful what version you pick. Releases that end with `-beta` are beta releases and the rest are stable.
**Note:** If you download from the [releases page](https://github.com/zulip/zulip-desktop/releases), be careful what version you pick. Releases that end with `-beta` are beta releases and the rest are stable.
- **beta:** these releases are the right balance between getting new features early while staying away from nasty bugs.
- **stable:** these releases are more thoroughly tested; they receive new features later, but there's a lower chance that things will go wrong.
[LR]: https://github.com/zulip/zulip-electron/releases
[LR]: https://github.com/zulip/zulip-desktop/releases
## OS X

5179
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{
"name": "zulip",
"productName": "Zulip",
"version": "2.5.0-beta",
"version": "3.1.0-beta",
"main": "./app/main",
"description": "Zulip Desktop App",
"license": "Apache-2.0",
@@ -12,24 +12,30 @@
},
"repository": {
"type": "git",
"url": "https://github.com/zulip/zulip-electron.git"
"url": "https://github.com/zulip/zulip-desktop.git"
},
"bugs": {
"url": "https://github.com/zulip/zulip-electron/issues"
"url": "https://github.com/zulip/zulip-desktop/issues"
},
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"start": "electron app --disable-http-cache --no-electron-connect",
"start": "node tools/run-dev",
"clean-ts-files": "git clean app/*.js -xf",
"watch-ts": "tsc -w",
"reinstall": "node ./tools/reinstall-node-modules.js",
"postinstall": "electron-builder install-app-deps",
"test": "xo",
"lint-css": "stylelint app/renderer/css/*.css",
"lint-html": "./node_modules/.bin/htmlhint \"app/renderer/*.html\" ",
"lint-js": "xo",
"test": "npm run lint-html && npm run lint-css && npm run lint-js",
"test-e2e": "gulp test-e2e",
"dev": "gulp dev & nodemon --watch app/main --watch app/renderer --exec 'npm test' -e html,css,js",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"mas": "electron-builder --mac mas",
"compile": "gulp compile",
"dev": "gulp dev && npm test",
"pack": "tsc && electron-builder --dir",
"dist": "tsc && electron-builder",
"mas": "tsc && electron-builder --mac mas",
"travis": "cd ./scripts && ./travis-build-test.sh",
"build-locales": "node tools/locale-helper"
},
@@ -39,14 +45,18 @@
"build": {
"appId": "org.zulip.zulip-electron",
"asar": true,
"asarUnpack": [
"**/*.node"
],
"files": [
"**/*",
"!docs${/*}",
"!node_modules/@paulcbetts/cld/deps/cld${/*}"
],
"copyright": "©2017 Kandra Labs, Inc.",
"copyright": "©2019 Kandra Labs, Inc.",
"mac": {
"category": "public.app-category.productivity",
"darkModeSupport": true,
"artifactName": "${productName}-${version}-${arch}.${ext}"
},
"linux": {
@@ -59,7 +69,7 @@
"AppImage",
"snap"
],
"maintainer": "Akash Nimare <svnitakash@gmail.com>",
"maintainer": "Akash Nimare <akash@zulipchat.com>",
"artifactName": "${productName}-${version}-${arch}.${ext}"
},
"deb": {
@@ -103,10 +113,13 @@
}
],
"icon": "build/icon.ico",
"artifactName": "${productName}-Web-Setup-${version}.${ext}",
"publisherName": "Kandra Labs, Inc."
},
"nsis": {
"allowToChangeInstallationDirectory": true
"allowToChangeInstallationDirectory": true,
"oneClick": false,
"perMachine": false
}
},
"keywords": [
@@ -118,40 +131,56 @@
"InstantMessaging"
],
"devDependencies": {
"@types/adm-zip": "^0.4.32",
"@types/dotenv": "6.1.1",
"@typescript-eslint/eslint-plugin": "1.10.2",
"@typescript-eslint/parser": "1.10.2",
"assert": "1.4.1",
"cp-file": "^5.0.0",
"cp-file": "5.0.0",
"devtron": "1.4.0",
"electron": "3.0.10",
"electron-builder": "20.38.4",
"electron": "3.1.10",
"electron-builder": "20.40.2",
"electron-connect": "0.6.2",
"electron-debug": "1.4.0",
"eslint-config-xo-typescript": "0.14.0",
"fs-extra": "8.1.0",
"google-translate-api": "2.3.0",
"gulp": "^4.0.0",
"gulp": "4.0.0",
"gulp-tape": "0.0.9",
"is-ci": "^1.0.10",
"nodemon": "^1.14.11",
"gulp-typescript": "5.0.1",
"htmlhint": "0.11.0",
"is-ci": "1.0.10",
"nodemon": "1.14.11",
"pre-commit": "1.2.2",
"spectron": "^5.0.0",
"tap-colorize": "^1.2.0",
"tape": "^4.8.0",
"xo": "0.18.2"
"spectron": "5.0.0",
"stylelint": "9.10.1",
"tap-colorize": "1.2.0",
"tape": "4.8.0",
"typescript": "3.5.2",
"xo": "0.24.0"
},
"xo": {
"extends": "xo-typescript",
"extensions": [
"ts"
],
"parserOptions": {
"sourceType": "script",
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"globalReturn": true
"globalReturn": true,
"modules": true
}
},
"esnext": true,
"overrides": [
{
"files": "app*/**/*.js",
"files": "app/**/*.ts",
"rules": {
"max-lines": [
"warn",
{
"max": 600,
"max": 800,
"skipBlankLines": true,
"skipComments": true
}
@@ -166,13 +195,26 @@
"prefer-promise-reject-errors": 0,
"import/no-unresolved": 0,
"import/no-extraneous-dependencies": 0,
"no-prototype-builtins": 0
"no-prototype-builtins": 0,
"lines-between-class-members": 0,
"padding-line-between-statements": 0,
"quotes": 0,
"unicorn/catch-error-name": 0,
"unicorn/no-console-spaces": 0,
"node/no-deprecated-api": 0,
"@typescript-eslint/member-ordering": "never",
"@typescript-eslint/restrict-plus-operands": "never",
"import/default": 0,
"@typescript-eslint/no-unused-vars": 0
}
}
],
"ignore": [
"tests/*.js",
"tools/locale-helper/*.js"
"tools/locale-helper/*.js",
"*/**/*.js",
"*.js",
"typings.d.ts"
],
"envs": [
"node",

View File

@@ -1,5 +1,5 @@
name: zulip
version: 2.0.0
version: 2.3.82
summary: Zulip Desktop Client for Linux
description: Zulip combines the immediacy of Slack with an email threading model. With Zulip, you can catch up on important conversations while ignoring irrelevant ones.
confinement: strict
@@ -34,4 +34,4 @@ parts:
- libxtst6
source: dist/linux-unpacked
after:
- desktop-gtk2
- desktop-gtk3

89
tools/run-dev Normal file
View File

@@ -0,0 +1,89 @@
#!/usr/bin/env node
const path = require('path');
const glob = require('glob');
const chalk = require('chalk');
const { spawn } = require('child_process');
async function run(task, commandToRun, opts = {}) {
const args = commandToRun.split(' ');
let cmd = args[0];
args.splice(0, 1);
if (process.platform === 'win32' && /np(m|x)/.test(cmd)) {
cmd = cmd + '.cmd';
}
const defaults = {
cwd: path.resolve(__dirname, '..'),
env: process.env,
stdio: 'pipe'
};
opts = { ...defaults, ...opts };
task = ' ' + task + ' ';
const colors = [
{ bg: 'bold.bgGreen', color: 'bold.green' },
{ bg: 'bold.bgMagenta', color: 'bold.magenta' },
{ bg: 'bold.bgBlue', color: 'bold.blue' },
{ bg: 'bold.bgYellow', color: 'bold.yellow' },
{ bg: 'bold.bgCyan', color: 'bold.cyan' },
{ bg: 'bold.bgKeyword("rebeccapurple")', color: 'bold.keyword("rebeccapurple")' },
{ bg: 'bold.bgKeyword("darkslategray")', color: 'bold.keyword("darkslategray")' },
];
const randomColorIndex = Math.floor((Math.random() * (colors.length * 1000)) / 1000);
const randomColor = colors[randomColorIndex];
console.log(chalk`{${randomColor.bg} ${ task }} {${randomColor.color} ${commandToRun}}`);
const proc = spawn(cmd, args, opts);
proc.stderr.on('data', data => console.log(data.toString()));
proc.stdout.on('data', data => console.log(data.toString()));
return new Promise((resolve, reject) => {
function check(code) {
if (code !== 0) {
reject(chalk`{bgRed ERROR!} Running {red ${commandToRun}} failed with exit code: ${code}`);
} else {
resolve();
}
// we don't want to exit after compiling typescript files
// but instead want to do it if the tsc -w or electron app died.
if (commandToRun !== 'npx tsc') {
process.exit(0);
}
}
proc.on('exit', check);
proc.on('close', check);
proc.on('error', () => {
reject();
process.exit(0);
});
});
}
async function main() {
const baseFilePattern = 'app/+(main|renderer)/**/*';
const globOptions = { cwd: path.resolve(__dirname, '..') };
const jsFiles = glob.sync(baseFilePattern + '.js', globOptions);
const tsFiles = glob.sync(baseFilePattern + '.ts', globOptions);
// if the are missing compiled js file for typescript files
// run the typescript compiler before starting the app
if (jsFiles.length !== tsFiles.length) {
console.log('Compiling typescript files...');
await run('TypeScript', 'npx tsc');
}
await Promise.all([
run('Electron app', 'npx electron app --disable-http-cache --no-electron-connect'),
run('TypeScript watch mode', 'npx tsc --watch --pretty')
]);
}
main()
.catch(err => console.error(err));

29
tsconfig.json Normal file
View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"module": "commonjs",
"esModuleInterop": true,
"skipLibCheck": true,
/* Strict type-checking */
"strict": true,
"noImplicitAny": true,
"strictNullChecks": false,
"noImplicitThis": true,
"alwaysStrict": true,
/* Additional checks */
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitReturns": true
},
"include":[
"app/**/*",
"typings.d.ts"
],
"exclude":[
"node_modules",
"app/node_modules"
]
}

54
typings.d.ts vendored Normal file
View File

@@ -0,0 +1,54 @@
declare module 'adm-zip';
declare module 'auto-launch';
declare module 'is-online';
declare module 'request';
declare module 'semver';
declare module '@electron-elements/send-feedback';
declare module 'node-mac-notifier';
declare module 'electron-connect';
declare module 'electron-is-dev';
declare module 'electron-spellchecker';
declare module 'escape-html';
declare module 'fs-extra';
declare module 'wurl';
interface PageParamsObject {
realm_uri: string;
default_language: string;
}
declare var page_params: PageParamsObject;
// since requestIdleCallback didn't make it into lib.dom.d.ts yet
declare function requestIdleCallback(callback: Function, options?: object): void;
// Patch Notification object so we can implement our side
// of Notification classes which we export into zulip side through
// preload.js; if we don't do his extending Notification will throw error.
// Relevant code is in app/renderer/js/notification/default-notification.ts
// and the relevant function is requestPermission.
declare var PatchedNotification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
readonly maxActions: number;
readonly permission: NotificationPermission;
requestPermission(): void;
}
// This is mostly zulip side of code we access from window
interface Window {
$: any;
narrow: any
Notification: typeof PatchedNotification;
}
// typescript doesn't have up to date NotificationOptions yet
interface NotificationOptions {
silent?: boolean;
}
interface ZulipWebWindow extends Window {
electron_bridge: any;
tray: any;
$: any;
lightbox: any;
}

View File

@@ -48,10 +48,10 @@ envSetup()
# Set name of upstreamRemote
cd $workingDir
git remote -v | grep "github\.com.zulip.zulip-electron.git (fetch)" > /dev/null 2>&1
git remote -v | grep "github\.com.zulip.zulip-desktop.git (fetch)" > /dev/null 2>&1
if [ $? -eq 0 ]
then
upstreamRemote=`git remote -v | grep "github\.com.zulip.zulip-electron.git (fetch)" | awk '{ print $1 }'`
upstreamRemote=`git remote -v | grep "github\.com.zulip.zulip-desktop.git (fetch)" | awk '{ print $1 }'`
else
upstreamRemote="origin"
fi