add inline doc

This commit is contained in:
Araxeus
2021-04-06 01:30:47 +03:00
parent 724c213af1
commit 0e9b15722a
6 changed files with 148 additions and 105 deletions

View File

@ -110,8 +110,8 @@ function createMainWindow() {
titleBarStyle: useInlineMenu titleBarStyle: useInlineMenu
? "hidden" ? "hidden"
: is.macOS() : is.macOS()
? "hiddenInset" ? "hiddenInset"
: "default", : "default",
autoHideMenuBar: config.get("options.hideMenu"), autoHideMenuBar: config.get("options.hideMenu"),
}); });
if (windowPosition) { if (windowPosition) {
@ -156,7 +156,7 @@ function createMainWindow() {
let createdWindow = false; let createdWindow = false;
app.on("browser-window-created", (event, win) => { app.on("browser-window-created", (event, win) => {
//Ensure listeners aren't registered when creating input dialog //Ensures listeners are registered only once
if (createdWindow) { if (createdWindow) {
return; return;
} }
@ -172,7 +172,7 @@ app.on("browser-window-created", (event, win) => {
frameProcessId, frameProcessId,
frameRoutingId, frameRoutingId,
) => { ) => {
let log = { const log = {
error: "did-fail-load", error: "did-fail-load",
event, event,
errorCode, errorCode,
@ -183,7 +183,7 @@ app.on("browser-window-created", (event, win) => {
frameRoutingId, frameRoutingId,
}; };
if (is.dev()) { if (is.dev()) {
console.log(log); console.log(log.toString());
} }
win.webContents.send("log", log); win.webContents.send("log", log);
win.webContents.loadFile(path.join(__dirname, "error.html")); win.webContents.loadFile(path.join(__dirname, "error.html"));
@ -306,13 +306,11 @@ app.on("ready", () => {
} }
// Optimized for Mac OS X // Optimized for Mac OS X
if (is.macOS()) { if (is.macOS() && !config.get("options.appVisible")) {
if (!config.get("options.appVisible")) { app.dock.hide();
app.dock.hide();
}
} }
var forceQuit = false; let forceQuit = false;
app.on("before-quit", () => { app.on("before-quit", () => {
forceQuit = true; forceQuit = true;
}); });

View File

@ -12,6 +12,7 @@ const pluginEnabledMenu = (win, plugin, label = "", hasSubmenu = false) => ({
label: label || plugin, label: label || plugin,
type: "checkbox", type: "checkbox",
checked: config.plugins.isEnabled(plugin), checked: config.plugins.isEnabled(plugin),
//Submenu check used in in-app-menu
hasSubmenu: hasSubmenu || undefined, hasSubmenu: hasSubmenu || undefined,
click: (item) => { click: (item) => {
if (item.checked) { if (item.checked) {

View File

@ -1,11 +1,15 @@
const { ipcRenderer } = require("electron"); const { ipcRenderer } = require("electron");
function logToString(log) {
let string = (typeof log === "string") ? log : log.toString();
if (!string || string.includes("[object Object]")) {
string = JSON.stringify(log);
}
return string;
}
module.exports = () => { module.exports = () => {
ipcRenderer.on("log", (event, log) => { ipcRenderer.on("log", (event, log) => {
let string = log || log.toString(); console.log(logToString(log));
if (!string || string === "[object Object]") { });
string = JSON.stringify(log);
}
console.log(string);
})
}; };

View File

@ -10,8 +10,10 @@ const DEFAULT_HEIGHT = 160;
function electronPrompt(options, parentWindow) { function electronPrompt(options, parentWindow) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//id used to ensure unique listeners per window
const id = `${Date.now()}-${Math.random()}`; const id = `${Date.now()}-${Math.random()}`;
//custom options override default
const options_ = Object.assign( const options_ = Object.assign(
{ {
width: DEFAULT_WIDTH, width: DEFAULT_WIDTH,
@ -19,12 +21,12 @@ function electronPrompt(options, parentWindow) {
minWidth: DEFAULT_WIDTH, minWidth: DEFAULT_WIDTH,
minHeight: DEFAULT_HEIGHT, minHeight: DEFAULT_HEIGHT,
resizable: false, resizable: false,
title: 'Prompt', title: "Prompt",
label: 'Please input a value:', label: "Please input a value:",
buttonLabels: null, buttonLabels: null,
alwaysOnTop: false, alwaysOnTop: false,
value: null, value: null,
type: 'input', type: "input",
selectOptions: null, selectOptions: null,
icon: null, icon: null,
useHtmlLabel: false, useHtmlLabel: false,
@ -70,10 +72,7 @@ function electronPrompt(options, parentWindow) {
promptWindow.setMenu(null); promptWindow.setMenu(null);
promptWindow.setMenuBarVisibility(options_.menuBarVisible); promptWindow.setMenuBarVisibility(options_.menuBarVisible);
const getOptionsListener = event => { //called on exit
event.returnValue = JSON.stringify(options_);
};
const cleanup = () => { const cleanup = () => {
ipcMain.removeListener("prompt-get-options:" + id, getOptionsListener); ipcMain.removeListener("prompt-get-options:" + id, getOptionsListener);
ipcMain.removeListener("prompt-post-data:" + id, postDataListener); ipcMain.removeListener("prompt-post-data:" + id, postDataListener);
@ -85,6 +84,12 @@ function electronPrompt(options, parentWindow) {
} }
}; };
///transfer options to front
const getOptionsListener = event => {
event.returnValue = JSON.stringify(options_);
};
//get input from front
const postDataListener = (event, value) => { const postDataListener = (event, value) => {
resolve(value); resolve(value);
event.returnValue = null; event.returnValue = null;
@ -96,12 +101,14 @@ function electronPrompt(options, parentWindow) {
cleanup(); cleanup();
}; };
//get error from front
const errorListener = (event, message) => { const errorListener = (event, message) => {
reject(new Error(message)); reject(new Error(message));
event.returnValue = null; event.returnValue = null;
cleanup(); cleanup();
}; };
//attach listeners
ipcMain.on("prompt-get-options:" + id, getOptionsListener); ipcMain.on("prompt-get-options:" + id, getOptionsListener);
ipcMain.on("prompt-post-data:" + id, postDataListener); ipcMain.on("prompt-post-data:" + id, postDataListener);
ipcMain.on("prompt-error:" + id, errorListener); ipcMain.on("prompt-error:" + id, errorListener);
@ -113,13 +120,23 @@ function electronPrompt(options, parentWindow) {
resolve(null); resolve(null);
}); });
const promptUrl = url.format({ //should never happen
protocol: "file", promptWindow.webContents.on("did-fail-load", (
slashes: true, event,
pathname: path.join(__dirname, "page", "prompt.html"), errorCode,
hash: id errorDescription,
validatedURL,
) => {
const log = {
error: "did-fail-load",
errorCode,
errorDescription,
validatedURL,
};
reject(new Error("prompt.html did-fail-load, log:\n", + log.toString()));
}); });
//Finally, load prompt
promptWindow.loadURL(promptUrl); promptWindow.loadURL(promptUrl);
}); });
} }

View File

@ -5,6 +5,93 @@ const docReady = require("doc-ready");
let promptId = null; let promptId = null;
let promptOptions = null; let promptOptions = null;
docReady(promptRegister);
//start here
function promptRegister() {
//get custom session id
promptId = document.location.hash.replace("#", "");
//get options from back
try {
promptOptions = JSON.parse(ipcRenderer.sendSync("prompt-get-options:" + promptId));
} catch (error) {
return promptError(error);
}
//set label
if (promptOptions.useHtmlLabel) {
document.querySelector("#label").innerHTML = promptOptions.label;
} else {
document.querySelector("#label").textContent = promptOptions.label;
}
//set button label
if (promptOptions.buttonLabels && promptOptions.buttonLabels.ok) {
document.querySelector("#ok").textContent = promptOptions.buttonLabels.ok;
}
if (promptOptions.buttonLabels && promptOptions.buttonLabels.cancel) {
document.querySelector("#cancel").textContent = promptOptions.buttonLabels.cancel;
}
//inject custom stylesheet from options
if (promptOptions.customStylesheet) {
try {
const customStyleContent = fs.readFileSync(promptOptions.customStylesheet);
if (customStyleContent) {
const customStyle = document.createElement("style");
customStyle.setAttribute("rel", "stylesheet");
customStyle.append(document.createTextNode(customStyleContent));
document.head.append(customStyle);
}
} catch (error) {
return promptError(error);
}
}
//add button listeners
document.querySelector("#form").addEventListener("submit", promptSubmit);
document.querySelector("#cancel").addEventListener("click", promptCancel);
//create input/select
const dataContainerElement = document.querySelector("#data-container");
let dataElement;
if (promptOptions.type === "input") {
dataElement = promptCreateInput();
} else if (promptOptions.type === "select") {
dataElement = promptCreateSelect();
} else {
return promptError(`Unhandled input type '${promptOptions.type}'`);
}
dataContainerElement.append(dataElement);
dataElement.setAttribute("id", "data");
dataElement.focus();
if (promptOptions.type === "input") {
dataElement.select();
}
//load custom script from options
if (promptOptions.customScript) {
try {
const customScript = require(promptOptions.customScript);
customScript();
} catch (error) {
return promptError(error);
}
}
}
window.addEventListener("error", error => {
if (promptId) {
promptError("An error has occured on the prompt window: \n" + error);
}
});
//send error to back
function promptError(error) { function promptError(error) {
if (error instanceof Error) { if (error instanceof Error) {
error = error.message; error = error.message;
@ -13,10 +100,12 @@ function promptError(error) {
ipcRenderer.sendSync("prompt-error:" + promptId, error); ipcRenderer.sendSync("prompt-error:" + promptId, error);
} }
//send to back: input=null
function promptCancel() { function promptCancel() {
ipcRenderer.sendSync("prompt-post-data:" + promptId, null); ipcRenderer.sendSync("prompt-post-data:" + promptId, null);
} }
//transfer input data to back
function promptSubmit() { function promptSubmit() {
const dataElement = document.querySelector("#data"); const dataElement = document.querySelector("#data");
let data = null; let data = null;
@ -32,6 +121,7 @@ function promptSubmit() {
ipcRenderer.sendSync("prompt-post-data:" + promptId, data); ipcRenderer.sendSync("prompt-post-data:" + promptId, data);
} }
//creates input box
function promptCreateInput() { function promptCreateInput() {
const dataElement = document.createElement("input"); const dataElement = document.createElement("input");
dataElement.setAttribute("type", "text"); dataElement.setAttribute("type", "text");
@ -42,6 +132,7 @@ function promptCreateInput() {
dataElement.value = ""; dataElement.value = "";
} }
//insert custom input attributes if in options
if (promptOptions.inputAttrs && typeof (promptOptions.inputAttrs) === "object") { if (promptOptions.inputAttrs && typeof (promptOptions.inputAttrs) === "object") {
for (const k in promptOptions.inputAttrs) { for (const k in promptOptions.inputAttrs) {
if (!Object.prototype.hasOwnProperty.call(promptOptions.inputAttrs, k)) { if (!Object.prototype.hasOwnProperty.call(promptOptions.inputAttrs, k)) {
@ -52,12 +143,14 @@ function promptCreateInput() {
} }
} }
//Cancel/Exit on 'Escape'
dataElement.addEventListener("keyup", event => { dataElement.addEventListener("keyup", event => {
if (event.key === "Escape") { if (event.key === "Escape") {
promptCancel(); promptCancel();
} }
}); });
//Confrim on 'Enter'
dataElement.addEventListener("keypress", event => { dataElement.addEventListener("keypress", event => {
if (event.key === "Enter") { if (event.key === "Enter") {
event.preventDefault(); event.preventDefault();
@ -68,6 +161,7 @@ function promptCreateInput() {
return dataElement; return dataElement;
} }
//create multiple select
function promptCreateSelect() { function promptCreateSelect() {
const dataElement = document.createElement("select"); const dataElement = document.createElement("select");
let optionElement; let optionElement;
@ -90,79 +184,5 @@ function promptCreateSelect() {
return dataElement; return dataElement;
} }
function promptRegister() {
promptId = document.location.hash.replace("#", "");
try {
promptOptions = JSON.parse(ipcRenderer.sendSync("prompt-get-options:" + promptId));
} catch (error) {
return promptError(error);
}
if (promptOptions.useHtmlLabel) {
document.querySelector("#label").innerHTML = promptOptions.label;
} else {
document.querySelector("#label").textContent = promptOptions.label;
}
if (promptOptions.buttonLabels && promptOptions.buttonLabels.ok) {
document.querySelector("#ok").textContent = promptOptions.buttonLabels.ok;
}
if (promptOptions.buttonLabels && promptOptions.buttonLabels.cancel) {
document.querySelector("#cancel").textContent = promptOptions.buttonLabels.cancel;
}
if (promptOptions.customStylesheet) {
try {
const customStyleContent = fs.readFileSync(promptOptions.customStylesheet);
if (customStyleContent) {
const customStyle = document.createElement("style");
customStyle.setAttribute("rel", "stylesheet");
customStyle.append(document.createTextNode(customStyleContent));
document.head.append(customStyle);
}
} catch (error) {
return promptError(error);
}
}
document.querySelector("#form").addEventListener("submit", promptSubmit);
document.querySelector("#cancel").addEventListener("click", promptCancel);
const dataContainerElement = document.querySelector("#data-container");
let dataElement;
if (promptOptions.type === "input") {
dataElement = promptCreateInput();
} else if (promptOptions.type === "select") {
dataElement = promptCreateSelect();
} else {
return promptError(`Unhandled input type '${promptOptions.type}'`);
}
dataContainerElement.append(dataElement);
dataElement.setAttribute("id", "data");
dataElement.focus();
if (promptOptions.type === "input") {
dataElement.select();
}
if (promptOptions.customScript) {
try {
const customScript = require(promptOptions.customScript);
customScript();
} catch (error) {
return promptError(error);
}
}
}
window.addEventListener("error", error => {
if (promptId) {
promptError("An error has occured on the prompt window: \n" + error);
}
});
docReady(promptRegister);

View File

@ -3,11 +3,14 @@
<p align="center"><img width="482" alt="prompt-preview" src="https://user-images.githubusercontent.com/17620180/111753337-09c0c680-8897-11eb-8ce8-43de29c143bd.png"></p> <p align="center"><img width="482" alt="prompt-preview" src="https://user-images.githubusercontent.com/17620180/111753337-09c0c680-8897-11eb-8ce8-43de29c143bd.png"></p>
## Usage ## Usage
```js ```js
prompt([options, parentBrowserWindow]).then(...).catch(...) prompt([options, parentBrowserWindow]).then(...).catch(...)
``` ```
Promise resolve returns input
If user presses cancel/exit window, input = null;
On error, Prompise reject returns custom error message
## Example ## Example
```js ```js