Skip to content

Instantly share code, notes, and snippets.

@BastianBlokland
Last active August 31, 2023 12:19
Show Gist options
  • Save BastianBlokland/1f2b2d9dfe75258274588ed53bcb8d90 to your computer and use it in GitHub Desktop.
Save BastianBlokland/1f2b2d9dfe75258274588ed53bcb8d90 to your computer and use it in GitHub Desktop.
Tiny electron wrapper for the TypedTree-Editor
const { app, dialog, BrowserWindow, Menu } = require("electron")
const fs = require("fs")
// Opt-in to new behaviour: https://github.com/electron/electron/issues/18397.
app.allowRendererProcessReuse = true
function getFilePath(window, argPos, extensions, title, message) {
if (process.argv.length >= argPos + 1) {
return process.argv[argPos]
}
const result = dialog.showOpenDialogSync(window, {
title,
message,
properties: ["openFile"],
filters: [{ name: extensions[0], extensions }, { name: "json", extensions: ["json"] }]
})
return result === undefined ? undefined : result[0]
}
function loadJson(path) {
try {
return fs.readFileSync(path, "utf8")
} catch (e) {
console.error(`Failed to load json from path: ${path}, error: ${e}`)
return undefined
}
}
app.on("ready", async () => {
// Create window.
const window = new BrowserWindow({ width: 1280, height: 1024 })
// Create function to load the editor.
const loadEditor = async () => {
console.log("Loading editor")
await window.loadURL("https://www.bastian.tech/tree/?mode=integration")
}
// Create function to load a scheme into the editor.
const loadScheme = async path => {
console.log(`Loading scheme from path: ${path}`)
const schemeJson = loadJson(path)
if (schemeJson === undefined) {
app.quit()
return
}
await window.webContents.executeJavaScript(
`window.enqueueLoadScheme(decodeURIComponent(\`${encodeURIComponent(schemeJson)}\`))`)
}
// Create function to load a tree into the editor.
const loadTree = async (path, focusTree) => {
console.log(`Loading tree from path: ${path}`)
const treeJson = loadJson(path)
if (treeJson === undefined) {
app.quit()
return
}
const name = ''
await window.webContents.executeJavaScript(
`window.enqueueLoadTree(decodeURIComponent(\`${encodeURIComponent(treeJson)}\`), name, ${focusTree})`)
}
// Create function to save the tree json.
const saveTree = async path => {
const treeJson = await window.webContents.executeJavaScript("window.getCurrentTreeJson()")
fs.writeFile(path, treeJson, "utf8", () => {
console.log(`Saved tree-json to path: ${path}`)
})
}
// Create menu.
const menu = Menu.buildFromTemplate([{
label: "Tree",
submenu: [
{
label: "Save",
accelerator: "CmdOrCtrl+S",
click: () => {
// Expects treeJson path being defined as soon as its known.
if (treeJsonPath === undefined) {
console.warn("Failed to save: No 'treeJsonPath' known yet")
} else {
saveTree(treeJsonPath)
}
}
},
{
label: "Quit",
accelerator: "CmdOrCtrl+Q",
click: app.quit
}
]
}])
Menu.setApplicationMenu(menu)
// Load editor.
loadEditor()
// Load scheme file into editor.
const schemeJsonPath = getFilePath(window, 2, ["btscheme","btschema"], "scheme", "Select the scheme json file to use")
if (schemeJsonPath === undefined) {
app.quit()
return
}
await loadScheme(schemeJsonPath)
// Automatically reload scheme if it changes in the background.
fs.watchFile(schemeJsonPath, { persistent: false, interval: 1000 }, () => {
console.log("Scheme changed, reloading file")
loadScheme(schemeJsonPath)
})
// Load tree file into editor.
const treeJsonPath = getFilePath(window, 3, ["bt"], "tree", "Select the tree json file to edit")
if (treeJsonPath === undefined) {
app.quit()
return
}
await loadTree(treeJsonPath, true)
// Automatically reload tree if it changes in the background.
fs.watchFile(treeJsonPath, { persistent: false, interval: 1000 }, () => {
console.log("Tree changed, reloading file")
loadTree(treeJsonPath, false)
})
})
app.on("window-all-closed", () => {
console.log("Shutting down app")
app.quit()
})
{
"name": "typedtree-editor-launcher",
"version": "1.0.0",
"author": "Bastian Blokland",
"license": "MIT",
"bugs": {
"url": "https://github.com/BastianBlokland/typedtree-editor/issues"
},
"scripts": {
"start": "electron ."
},
"main": "main.js",
"devDependencies": {
"electron": "^24.4.0"
}
}
#!/bin/bash
set -e
info ()
{
echo "INFO: $1"
}
warn ()
{
echo "WARN: $1"
}
fail ()
{
echo "$1" >&2
exit 1
}
getScriptDirectory() {
realpath "$(dirname -- "${0}")"
}
verifyCommand ()
{
if [ ! -x "$(command -v "$1")" ]
then
fail "Dependency '$1' is missing, we cannot continue without it"
fi
}
# Verify if dependencies are installed.
verifyCommand npm
ELECTRON_PATH="$(getScriptDirectory)/node_modules/.bin/electron"
# Verify that election has been restored.
if [ ! -f "$ELECTRON_PATH" ]
then
warn "Electron missing: running 'npm install'"
( cd "$(getScriptDirectory)"; npm install )
info "Npm install completed"
fi
# Start app with electron.
( cd "$(getScriptDirectory)"; $ELECTRON_PATH 'main.js' "${@:1}" )

TypedTree-Editor electron wrapper

Tiny electron wrapper around the typedtree-editor (repo).

Advantage is that it allows local filesystem access so it can write changes back to the original file. Atleast untill native-file-system api has become mainstream in browsers.

Usage

On unix systems execute run.sh, on others run npm install and npm start.

Args

  • Path to the scheme json file is taken as arg 1.
  • Path to the tree json file is taken as arg 2.

If the paths are not provided as args then dialog's are shown.

Preview image

MIT License

Copyright (c) 2018 Bastian Blokland

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@BastianBlokland
Copy link
Author

Updated to Electron 24

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment