Skip to content

#18 custom script builder #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
"@types/react-helmet": "^6.1.2",
"@types/react-router-dom": "^5.1.6",
"@types/react-test-renderer": "^16.9.3",
"@types/uuid": "^8.3.1",
"@types/webpack-env": "^1.15.2",
"@typescript-eslint/eslint-plugin": "^4.8.1",
"@typescript-eslint/parser": "^4.8.1",
Expand Down Expand Up @@ -280,7 +281,8 @@
"react-router-dom": "^5.2.0",
"regenerator-runtime": "^0.13.5",
"source-map-support": "^0.5.19",
"sql-formatter": "^4.0.2"
"sql-formatter": "^4.0.2",
"uuid": "^8.3.2"
},
"devEngines": {
"node": ">=10.x",
Expand Down
137 changes: 115 additions & 22 deletions src/components/Main.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { ComponentType, ReactElement, useEffect, useState } from 'react';
import { NavLink, Route, useHistory } from 'react-router-dom';
import { NavLink, Route, useHistory, useLocation } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Helmet } from 'react-helmet';

import { ipcRenderer } from 'electron';
import { v4 as uuidv4 } from 'uuid';
import classNames from 'classnames';
import MarkdownToHtml from './markdown/MarkdownToHtml';
import UnixTimestamp from './timestamp/UnixTimestamp';
Expand All @@ -16,6 +16,7 @@ import JsonFormatter from './json/JsonFormatter';
import QRCodeReader from './qrcode/QrCodeReader';
import RegexTester from './regex/RegexTester';
import JwtDebugger from './jwt/JwtDebugger';
import CustomScript from './custom-script/CustomScript';
import Auto from './auto/Auto';
import CronEditor from './cron/Cron';
import JsConsole from './notebook/JavaScript';
Expand Down Expand Up @@ -166,7 +167,10 @@ const Main = () => {
const [routes, setRoutes] = useState<MenuItem[]>([]);
const [search, setSearch] = useState('');
const [editMenu, setEditMenu] = useState(false);
const [activeMenuItemPath, setActiveMenuItemPath] = useState('');
const [activeMenuItemName, setActiveMenuItemName] = useState('');
const history = useHistory();
const location = useLocation();

const handleSearch = (e: { target: { value: string } }) => {
setSearch(e.target.value);
Expand Down Expand Up @@ -196,6 +200,10 @@ const Main = () => {
}
}, [allRoutes]);

useEffect(() => {
setActiveMenuItemPath('');
}, [location]);

useEffect(() => {
const routeMap: Record<string, boolean> = defaultRoutes.reduce(
(a, b) => ({ ...a, [b.path]: b.show }),
Expand Down Expand Up @@ -225,6 +233,38 @@ const Main = () => {
});
}, []);

const handleAddNewMenuItem = () => {
const id = uuidv4();
const routeList = [
...allRoutes,
{
icon: <FontAwesomeIcon icon="slash" transform={{ rotate: 42 }} />,
path: `/custom-script-${id}`,
name: `Custom Script ${id.slice(0, 5)}`,
show: true,
Component: CustomScript,
},
];
setAllRoutes(routeList);
};

const handleDeleteMenuItem = (path: MenuItem['path']) => {
setAllRoutes(allRoutes.filter((r) => r.path !== activeMenuItemPath));
setActiveMenuItemPath('');
setActiveMenuItemName('');
ipcRenderer.invoke('delete-store', path);
};

const handleSaveMenuItemEdit = () => {
setAllRoutes(
allRoutes.map((r) =>
r.path === activeMenuItemPath ? { ...r, name: activeMenuItemName } : r
)
);
setActiveMenuItemPath('');
setActiveMenuItemName('');
};

return (
<div className="absolute inset-0 flex flex-col overflow-hidden">
<main className="relative flex flex-1 min-h-0">
Expand All @@ -249,7 +289,10 @@ const Main = () => {
)}
<FontAwesomeIcon
icon={editMenu ? 'check' : 'sliders-h'}
onClick={() => setEditMenu(!editMenu)}
onClick={() => {
setEditMenu(!editMenu);
if (editMenu) handleSaveMenuItemEdit();
}}
className={classNames({
'text-gray-400 cursor-pointer hover:text-gray-600': true,
'text-blue-500 hover:text-blue-600': editMenu,
Expand All @@ -268,30 +311,80 @@ const Main = () => {
key={path}
className="flex items-center justify-between space-x-2"
>
<NavLink
to={path}
className="flex items-center justify-start flex-1 px-3 py-1 mb-1 space-x-1 rounded-lg"
activeClassName="bg-blue-400 text-white"
>
<span className="w-6">{icon}</span>
{name}
</NavLink>
{editMenu && (
{(activeMenuItemPath === path && (
<input
type="checkbox"
checked={show}
onChange={() =>
setAllRoutes(
allRoutes.map((r) =>
r.path === path ? { ...r, show: !show } : r
)
)
}
className="w-4 h-4 rounded cursor-pointer"
className="flex items-center justify-start flex-1 px-3 py-1 mb-1 space-x-1 rounded-lg"
value={activeMenuItemName}
onChange={(evt) => {
setActiveMenuItemName(evt.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSaveMenuItemEdit();
}
}}
/>
)) || (
<NavLink
to={path}
className="flex items-center justify-start flex-1 px-3 py-1 mb-1 space-x-1 rounded-lg"
activeClassName="bg-blue-400 text-white"
>
<span className="w-6">{icon}</span>
{name}
</NavLink>
)}
{editMenu && (
<>
{location.pathname === path && path.startsWith('/custom-') && (
<>
{(!activeMenuItemPath && (
<button
type="button"
onClick={() => {
setActiveMenuItemPath(path);
setActiveMenuItemName(name);
}}
className="w-10 btn"
>
edit
</button>
)) || (
<button
type="button"
onClick={() => handleDeleteMenuItem(path)}
className="w-12 btn text-white bg-red-500"
>
x
</button>
)}
</>
)}
<input
type="checkbox"
checked={show}
onChange={() =>
setAllRoutes(
allRoutes.map((r) =>
r.path === path ? { ...r, show: !show } : r
)
)
}
className="w-4 h-4 rounded cursor-pointer"
/>
</>
)}
</section>
))}
{editMenu && (
<button
type="button"
className="btn"
onClick={handleAddNewMenuItem}
>
+ Add your script
</button>
)}
</div>
</nav>

Expand Down
150 changes: 150 additions & 0 deletions src/components/custom-script/CustomScript.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/* eslint-disable no-eval */
import React, { useState, useEffect, useCallback } from 'react';
import { ipcRenderer, clipboard } from 'electron';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import { useLocation } from 'react-router-dom';

require('codemirror/mode/javascript/javascript');

const defaultFunc = `function(x) {
return x;
}`;

const CustomScript = () => {
const [customFunc, setCustomFunc] = useState(defaultFunc);
const [output, setOutput] = useState();
const [input, setInput] = useState("'your argument'");

const [opening, setOpening] = useState(false);
const [running, setRunning] = useState(false);
const location = useLocation();

useEffect(() => {
(async () => {
try {
const {
customFunction,
defaultInput,
} = await ipcRenderer.invoke('get-store', { key: location.pathname });
setCustomFunc(customFunction);
setInput(defaultInput);
} catch (e) {
// do nothing
}
})();
}, []);

const handleOpen = async () => {
setOpening(true);
const filters = [{ name: 'JavaScript Files', extensions: ['js'] }];
const c = await ipcRenderer.invoke('open-file', filters);
setCustomFunc(Buffer.from(c).toString());
setOpening(false);
};

const handleClipboard = () => {
setCustomFunc(clipboard.readText());
};

const getOutPut = () => {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
return new Function(`return (${customFunc})(${input})`)();
};

const handleRun = () => {
setRunning(true);
try {
setOutput(getOutPut());
} catch (e) {
setOutput(e.message);
}
setRunning(false);
};

const handleSave = useCallback(async () => {
try {
await ipcRenderer.invoke('set-store', {
key: location.pathname,
value: {
customFunction: customFunc,
defaultInput: input,
},
});
} catch (e) {
// eslint-disable-next-line no-alert
alert(e.message);
}
}, [customFunc, input, location.pathname]);

useEffect(() => {
handleSave();
}, [handleSave]);

return (
<div className="flex flex-col flex-shrink-0 h-full min-h-full">
<div className="flex justify-between mb-1">
<span className="flex space-x-4">
<span className="flex space-x-2">
<button type="button" className="btn" onClick={handleClipboard}>
Clipboard
</button>
<button
type="button"
className="btn"
onClick={handleOpen}
disabled={opening}
>
Open...
</button>
</span>
</span>
<span className="flex space-x-2">
<button
type="button"
onClick={handleRun}
className="w-16 btn"
disabled={running}
>
{running ? 'Running' : 'Run'}
</button>
</span>
</div>
<div className="flex flex-col flex-1 h-full space-y-2 overflow-auto">
<CodeMirror
autoCursor={false}
className="h-1/2 overflow-auto text-base resize-y"
value={customFunc}
options={{
theme: 'elegant',
mode: 'javascript',
lineNumbers: true,
}}
onChange={(_editor, _data, value) => {
setCustomFunc(value);
}}
/>
<CodeMirror
autoCursor={false}
className="h-1/4 overflow-auto text-base resize-y"
value={input}
options={{
theme: 'elegant',
mode: 'javascript',
lineNumbers: true,
}}
onChange={(_editor, _data, value) => {
setInput(value);
}}
/>
<textarea
className="h-1/4 p-2 bg-gray-100 rounded-md"
placeholder="Hit Run to view output"
value={output}
readOnly
/>
</div>
</div>
);
};

export default CustomScript;
4 changes: 4 additions & 0 deletions src/main.dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,10 @@ ipcMain.handle('set-store', async (_event, { key, value }) => {
return store.set(key, value);
});

ipcMain.handle('delete-store', async (_event, { key }) => {
return store.delete(key);
});

/**
* Add event listeners...
*/
Expand Down
13 changes: 9 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1880,6 +1880,11 @@
dependencies:
"@types/jest" "*"

"@types/uuid@^8.3.1":
version "8.3.1"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.1.tgz#1a32969cf8f0364b3d8c8af9cc3555b7805df14f"
integrity sha512-Y2mHTRAbqfFkpjldbkHGY8JIzRN6XqYRliG8/24FcHm2D2PwW24fl5xMRTVGdrb7iMrwCaIEbLWerGIkXuFWVg==

"@types/verror@^1.10.3":
version "1.10.4"
resolved "https://registry.yarnpkg.com/@types/verror/-/verror-1.10.4.tgz#805c0612b3a0c124cf99f517364142946b74ba3b"
Expand Down Expand Up @@ -12407,10 +12412,10 @@ uuid@^3.3.2, uuid@^3.4.0:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==

uuid@^8.3.0:
version "8.3.1"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.1.tgz#2ba2e6ca000da60fce5a196954ab241131e05a31"
integrity sha512-FOmRr+FmWEIG8uhZv6C2bTgEVXsHk08kE7mPlrBbEe+c3r9pjceVPgupIfNIhc4yx55H69OXANrUaSuu9eInKg==
uuid@^8.3.0, uuid@^8.3.2:
version "8.3.2"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==

v8-compile-cache@^2.0.3, v8-compile-cache@^2.2.0:
version "2.2.0"
Expand Down