Move methods from mainWindow.webContents (index.js) to WebView (main.js).

This commit is contained in:
Zhongyi Tong
2017-04-27 00:07:22 +08:00
committed by akashnimare
parent 865553fa45
commit de34a22740
8 changed files with 59 additions and 189 deletions

View File

@@ -48,49 +48,7 @@ let mainWindow;
let targetLink; let targetLink;
// Load this url in main window // Load this url in main window
const staticURL = 'file://' + path.join(__dirname, '../renderer', 'index.html'); const mainURL = 'file://' + path.join(__dirname, '../renderer', 'main.html');
const targetURL = function () {
if (data.domain === undefined) {
return staticURL;
}
// TODO: Use new main window
return 'file://' + path.join(__dirname, '../renderer', 'main.html');
return data.domain;
};
function serverError(targetURL) {
// TODO: disabled
return;
if (targetURL.indexOf('localhost:') < 0 && data.domain) {
const req = https.request(targetURL + '/static/audio/zulip.ogg', res => {
console.log('Server StatusCode:', res.statusCode);
console.log('You are connected to:', res.req._headers.host);
if (res.statusCode >= 500 && res.statusCode <= 599) {
return dialog.showErrorBox('SERVER IS DOWN!', 'We are getting a ' + res.statusCode + ' error status from the server ' + res.req._headers.host + '. Please try again after some time or you may switch server.');
}
});
req.on('error', e => {
if (e.toString().indexOf('Error: self signed certificate') >= 0) {
const url = targetURL.replace(/^https?:\/\//, '');
console.log('Server StatusCode:', 200);
console.log('You are connected to:', url);
} else {
console.error(e);
}
});
req.end();
} else if (data.domain) {
const req = http.request(targetURL + '/static/audio/zulip.ogg', res => {
console.log('Server StatusCode:', res.statusCode);
console.log('You are connected to:', res.req._headers.host);
});
req.on('error', e => {
console.error(e);
});
req.end();
}
}
function checkConnectivity() { function checkConnectivity() {
return dialog.showMessageBox({ return dialog.showMessageBox({
@@ -117,6 +75,7 @@ const connectivityERR = [
'ERR_NAME_NOT_RESOLVED' 'ERR_NAME_NOT_RESOLVED'
]; ];
// TODO
function checkConnection() { function checkConnection() {
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => { mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
@@ -142,13 +101,6 @@ if (isAlreadyRunning) {
app.quit(); app.quit();
} }
function checkWindowURL() {
if (data.domain !== undefined) {
return data.domain;
}
return targetLink;
}
function isWindowsOrmacOS() { function isWindowsOrmacOS() {
return process.platform === 'darwin' || process.platform === 'win32'; return process.platform === 'darwin' || process.platform === 'win32';
} }
@@ -201,9 +153,7 @@ function createMainWindow() {
win.show(); win.show();
}); });
serverError(targetURL()); win.loadURL(mainURL, {
win.loadURL(targetURL(), {
userAgent: isUserAgent + ' ' + win.webContents.getUserAgent() userAgent: isUserAgent + ' ' + win.webContents.getUserAgent()
}); });
@@ -314,36 +264,22 @@ app.on('ready', () => {
// TODO - use global shortcut instead // TODO - use global shortcut instead
electronLocalshortcut.register(mainWindow, 'CommandOrControl+R', () => { electronLocalshortcut.register(mainWindow, 'CommandOrControl+R', () => {
mainWindow.reload(); page.send('reload');
mainWindow.webContents.send('destroytray'); // page.send('destroytray');
}); });
electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => { electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => {
if (page.canGoBack()) { page.send('back');
page.goBack();
}
}); });
electronLocalshortcut.register(mainWindow, 'CommandOrControl+]', () => { electronLocalshortcut.register(mainWindow, 'CommandOrControl+]', () => {
if (page.canGoForward()) { page.send('forward');
page.goForward();
}
}); });
page.on('dom-ready', () => { page.on('dom-ready', () => {
page.insertCSS(fs.readFileSync(path.join(__dirname, '../renderer/css/preload.css'), 'utf8'));
mainWindow.show(); mainWindow.show();
}); });
page.on('new-window', (event, url) => {
if (linkIsInternal(checkWindowURL(), url) && url.match(skipImages) === null) {
event.preventDefault();
return mainWindow.loadURL(url);
}
event.preventDefault();
electron.shell.openExternal(url);
});
page.once('did-frame-finish-load', () => { page.once('did-frame-finish-load', () => {
const checkOS = isWindowsOrmacOS(); const checkOS = isWindowsOrmacOS();
if (checkOS && !isDev) { if (checkOS && !isDev) {
@@ -362,21 +298,3 @@ app.on('will-quit', () => {
// Unregister all the shortcuts so that they don't interfare with other apps // Unregister all the shortcuts so that they don't interfare with other apps
electronLocalshortcut.unregisterAll(mainWindow); electronLocalshortcut.unregisterAll(mainWindow);
}); });
ipc.on('new-domain', (e, domain) => {
// MainWindow.loadURL(domain);
if (!mainWindow) {
mainWindow = createMainWindow();
mainWindow.loadURL(domain);
mainWindow.webContents.send('destroytray');
} else if (mainWindow.isMinimized()) {
mainWindow.webContents.send('destroytray');
mainWindow.loadURL(domain);
mainWindow.show();
} else {
mainWindow.webContents.send('destroytray');
mainWindow.loadURL(domain);
serverError(domain);
}
targetLink = domain;
});

View File

@@ -1,74 +0,0 @@
body{
background-color: #6BB6C7;
}
.form {
position: absolute;
top: 35%;
width: 300px;
left: 9%;
}
.close {
background: transparent url('../img/close.png') no-repeat 4px 4px;
background-size: 24px 24px;
cursor: pointer;
display: inline-block;
height: 32px;
position: absolute;
right: 6px;
text-indent: -10000px;
top: 6px;
width: 32px;
z-index: 1;
-webkit-app-region: no-drag;
}
input[type="text"] {
display: block;
margin: 0;
width: 100%;
font-family: sans-serif;
font-size: 18px;
appearance: none;
box-shadow: none;
border-radius: none;
color: #646464;
}
input[type="text"]:focus {
outline: none;
}
.form input[type="text"] {
padding: 10px;
border: solid 1px #dcdcdc;
transition: box-shadow 0.3s, border 0.3s;
}
.form input[type="text"]:focus,
.form input[type="text"].focus {
border: solid 1px #707070;
box-shadow: 0 0 5px 1px #969696;
}
button {
border: none;
color: #fff;
padding: 12px 32px;
text-align: center;
text-decoration: none;
margin-left: 107px;
margin-top: 24px;
display: inline-block;
font-size: 16px;
background: #137b86;
}
button:focus {
outline: 0;
}
#urladded {
font-size: 20px;
position: absolute;
font-family: 'opensans';
top: -61%;
left: 25%;
text-align: center;
}

View File

@@ -1 +0,0 @@
/* We'll be overriding default styling so that app look more native * /

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -2,6 +2,10 @@
const path = require("path"); const path = require("path");
const DomainUtil = require(path.resolve(('app/renderer/js/utils/domain-util.js'))); const DomainUtil = require(path.resolve(('app/renderer/js/utils/domain-util.js')));
const { linkIsInternal, skipImages } = require(path.resolve(('app/main/link-helper')));
const { shell, ipcRenderer } = require('electron');
require(path.resolve(('app/renderer/js/tray.js')));
class ServerManagerView { class ServerManagerView {
constructor() { constructor() {
this.$tabsContainer = document.getElementById('tabs-container'); this.$tabsContainer = document.getElementById('tabs-container');
@@ -20,6 +24,7 @@ class ServerManagerView {
this.domainUtil = new DomainUtil(); this.domainUtil = new DomainUtil();
this.initTabs(); this.initTabs();
this.initActions(); this.initActions();
this.registerIpcs();
} }
initTabs() { initTabs() {
@@ -67,6 +72,7 @@ class ServerManagerView {
this.$content.appendChild($webView); this.$content.appendChild($webView);
this.isLoading = true; this.isLoading = true;
$webView.addEventListener('dom-ready', this.endLoading.bind(this, index)); $webView.addEventListener('dom-ready', this.endLoading.bind(this, index));
this.registerListeners($webView);
} }
startLoading(url, index) { startLoading(url, index) {
@@ -86,7 +92,6 @@ class ServerManagerView {
const $webView = document.getElementById(`webview-${index}`); const $webView = document.getElementById(`webview-${index}`);
this.isLoading = false; this.isLoading = false;
$webView.classList.remove('loading'); $webView.classList.remove('loading');
$webView.openDevTools();
} }
initActions() { initActions() {
@@ -145,6 +150,39 @@ class ServerManagerView {
__get_tab_at(index) { __get_tab_at(index) {
return this.$tabsContainer.childNodes[index]; return this.$tabsContainer.childNodes[index];
} }
registerListeners($webView) {
$webView.addEventListener('new-window', (event) => {
const {url} = event;
const domainPrefix = this.domainUtil.getDomain(this.activeTabIndex).url;
if (linkIsInternal(domainPrefix, url) && url.match(skipImages) === null) {
event.preventDefault();
return $webView.loadURL(url);
}
event.preventDefault();
shell.openExternal(url);
});
}
registerIpcs() {
const activeWebview = document.getElementById(`webview-${this.activeTabIndex}`);
ipcRenderer.on('reload', () => {
activeWebview.reload();
});
ipcRenderer.on('back', () => {
if (activeWebview.canGoBack()) {
activeWebview.goBack();
}
});
ipcRenderer.on('forward', () => {
if (activeWebview.canGoForward()) {
activeWebview.goForward();
}
});
}
} }
window.onload = () => { window.onload = () => {

View File

@@ -11,9 +11,7 @@ process.once('loaded', () => {
}); });
// eslint-disable-next-line import/no-unassigned-import // eslint-disable-next-line import/no-unassigned-import
require('./domain'); // require('./tray.js');
// eslint-disable-next-line import/no-unassigned-import
require('./tray.js');
// Calling Tray.js in renderer process everytime app window loads // Calling Tray.js in renderer process everytime app window loads
// Handle zooming functionality // Handle zooming functionality

View File

@@ -13,6 +13,10 @@ class DomainUtil {
return this.db.getData('/domains'); return this.db.getData('/domains');
} }
getDomain(index) {
return this.db.getData(`/domains[${index}]`);
}
addDomain(server) { addDomain(server) {
server.icon = server.icon || 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png'; server.icon = server.icon || 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png';
this.db.push("/domains[]", server, true); this.db.push("/domains[]", server, true);
@@ -38,6 +42,12 @@ class DomainUtil {
request(checkDomain, (error, response) => { request(checkDomain, (error, response) => {
if (!error && response.statusCode !== 404) { if (!error && response.statusCode !== 404) {
res(domain); res(domain);
} else if (error.toString().indexOf('Error: self signed certificate') >= 0) {
if (window.confirm(`Do you trust certificate from ${domain}?`)) {
res(domain);
} else {
rej('Untrusted Certificate.');
}
} else { } else {
rej('Not a valid Zulip server'); rej('Not a valid Zulip server');
} }

View File

@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/pref.css">
</head>
<body>
<div class="close" id="close-button">Close</div>
<div class="form">
<form onsubmit="prefDomain(); return false">
<input id="url" type="text" placeholder="Server URL">
<button type="submit" id="main" value="Submit">
Switch</button>
</form>
<p id="urladded"><p>
</div>
<script src="js/pref.js"></script>
</body>
</html>