improve types

This commit is contained in:
Anton Bracke 2022-02-22 12:02:56 +01:00
parent d03544c839
commit 71c8e32b2f
No known key found for this signature in database
GPG Key ID: B1222603899C6B25
16 changed files with 105 additions and 121 deletions

View File

@ -1,23 +1,23 @@
# Desktop app # Desktop app
The desktop component is an electron app. It uses a hybrid setup based of two main components: The desktop component is an electron app inside `./electron/`. It uses a hybrid setup based of two main components:
- A `local-app` bundled into the electron app. It has two main parts: - A `local-app` bundled into the electron app with two main parts:
- A sidebar to show the server list, with the currently selected server - A sidebar to show the server list, with the currently selected server
- A main page which is used to manage servers and to show other "local" pages like the options - A main page which is used to manage servers and to show other "local" pages like the desktop-app settings
- A BrowserView (often called `appView` or `app`) showing the actual frontend of an external WorkAdventure deployment. - A BrowserView (often called `appView` or `app`) showing the actual frontend of an external WorkAdventure deployment.
If a server is selected the BrowserView / `appView` is overlaying the main part right to the sidebar. If a server is selected the BrowserView / `appView` is overlaying the whole main part right to the sidebar.
## Development ## Development
```bash ```bash
# start local-app # start local-app in watch mode
yarn dev:local-app cd local-app && yarn dev
# start electron app # start electron app in watch mode
LOCAL_APP_URL=http://localhost:3000 yarn dev cd electron && LOCAL_APP_URL=http://localhost:3000 yarn dev
# or create an executable by running: # or create an executable by running:
yarn bundle cd electron && yarn bundle
``` ```
## API for front ## API for front

View File

@ -2,8 +2,8 @@ import { ipcMain, app } from "electron";
import electronIsDev from "electron-is-dev"; import electronIsDev from "electron-is-dev";
import { createAndShowNotification } from "./notification"; import { createAndShowNotification } from "./notification";
import { Server } from "./preload-local-app/types"; import { Server } from "./preload-local-app/types";
import settings from "./settings"; import settings, { SettingsData } from "./settings";
import { saveShortcut } from "./shortcuts"; import { loadShortcuts, saveShortcut } from "./shortcuts";
import { getWindow, hideAppView, showAppView } from "./window"; import { getWindow, hideAppView, showAppView } from "./window";
export function emitMuteToggle() { export function emitMuteToggle() {
@ -92,7 +92,10 @@ export default () => {
return true; return true;
}); });
ipcMain.handle("local-app:saveShortcut", (event, shortcut, key) => saveShortcut(shortcut, key)); ipcMain.handle("local-app:reloadShortcuts", (event, shortcut, key) => loadShortcuts());
ipcMain.handle("local-app:getShortcuts", (event) => settings.get("shortcuts") || {}); ipcMain.handle("local-app:getSettings", (event) => settings.get() || {});
ipcMain.handle("local-app:saveSetting", <T extends keyof SettingsData>(event, key: T, value: SettingsData[T]) =>
settings.set(key, value)
);
}; };

View File

@ -1,14 +1,13 @@
import { contextBridge, ipcRenderer, IpcRendererEvent } from "electron"; import { contextBridge, ipcRenderer, IpcRendererEvent } from "electron";
import { SettingsData } from "src/settings";
import type { WorkAdventureDesktopApi } from "./types"; import type { WorkAdventureDesktopApi } from "./types";
const api: WorkAdventureDesktopApi = { const api: WorkAdventureDesktopApi = {
desktop: true, desktop: true,
isDevelopment: () => ipcRenderer.invoke("is-development"), isDevelopment: () => ipcRenderer.invoke("is-development"),
getVersion: () => ipcRenderer.invoke("get-version"), getVersion: () => ipcRenderer.invoke("get-version"),
notify: (txt: string) => ipcRenderer.send("app:notify", txt), notify: (txt) => ipcRenderer.send("app:notify", txt),
onMuteToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-mute-toggle", callback), onMuteToggle: (callback) => ipcRenderer.on("app:on-mute-toggle", callback),
onCameraToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-camera-toggle", callback), onCameraToggle: (callback) => ipcRenderer.on("app:on-camera-toggle", callback),
}; };
contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api); contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api);

View File

@ -1,6 +1,5 @@
import { contextBridge, ipcRenderer } from "electron"; import { contextBridge, ipcRenderer } from "electron";
import { SettingsData } from "src/settings"; import type { WorkAdventureLocalAppApi } from "./types";
import type { Server, WorkAdventureLocalAppApi } from "./types";
const api: WorkAdventureLocalAppApi = { const api: WorkAdventureLocalAppApi = {
desktop: true, desktop: true,
@ -8,12 +7,12 @@ const api: WorkAdventureLocalAppApi = {
getVersion: () => ipcRenderer.invoke("get-version"), getVersion: () => ipcRenderer.invoke("get-version"),
showLocalApp: () => ipcRenderer.invoke("local-app:showLocalApp"), showLocalApp: () => ipcRenderer.invoke("local-app:showLocalApp"),
getServers: () => ipcRenderer.invoke("local-app:getServers"), getServers: () => ipcRenderer.invoke("local-app:getServers"),
selectServer: (serverId: string) => ipcRenderer.invoke("local-app:selectServer", serverId), selectServer: (serverId) => ipcRenderer.invoke("local-app:selectServer", serverId),
addServer: (server: Omit<Server, "_id">) => ipcRenderer.invoke("local-app:addServer", server), addServer: (server) => ipcRenderer.invoke("local-app:addServer", server),
removeServer: (serverId: Server["_id"]) => ipcRenderer.invoke("local-app:removeServer", serverId), removeServer: (serverId) => ipcRenderer.invoke("local-app:removeServer", serverId),
saveShortcut: (shortcut: keyof SettingsData["shortcuts"], key: string | null) => reloadShortcuts: () => ipcRenderer.invoke("local-app:reloadShortcuts"),
ipcRenderer.invoke("local-app:saveShortcut", shortcut, key), getSettings: () => ipcRenderer.invoke("local-app:getSettings"),
getShortcuts: () => ipcRenderer.invoke("local-app:getShortcuts"), saveSetting: (key, value) => ipcRenderer.invoke("local-app:setSetting", key, value),
}; };
contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api); contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api);

View File

@ -1,4 +1,4 @@
import { SettingsData } from "src/settings"; import { SettingsData } from "../settings";
export type Server = { export type Server = {
_id: string; _id: string;
@ -6,6 +6,8 @@ export type Server = {
url: string; url: string;
}; };
export { SettingsData };
export type WorkAdventureLocalAppApi = { export type WorkAdventureLocalAppApi = {
desktop: boolean; desktop: boolean;
isDevelopment: () => Promise<boolean>; isDevelopment: () => Promise<boolean>;
@ -13,8 +15,9 @@ export type WorkAdventureLocalAppApi = {
showLocalApp: () => Promise<void>; showLocalApp: () => Promise<void>;
getServers: () => Promise<Server[]>; getServers: () => Promise<Server[]>;
selectServer: (serverId: string) => Promise<Error | boolean>; selectServer: (serverId: string) => Promise<Error | boolean>;
addServer: (server: Omit<Server, "_id">) => Promise<Server>; addServer: (server: Omit<Server, "_id">) => Promise<Server | Error>;
removeServer: (serverId: Server["_id"]) => Promise<boolean>; removeServer: (serverId: Server["_id"]) => Promise<boolean>;
saveShortcut: (shortcut: keyof SettingsData["shortcuts"], key: string | null) => Promise<void>; reloadShortcuts: () => Promise<void>;
getShortcuts: () => Promise<SettingsData["shortcuts"]>; getSettings: () => Promise<SettingsData>;
saveSetting: <T extends keyof SettingsData>(key: T, value: SettingsData[T]) => Promise<void>;
}; };

View File

@ -15,20 +15,33 @@ async function init() {
settings = (await Settings.get()) as SettingsData; settings = (await Settings.get()) as SettingsData;
} }
function get<T extends keyof SettingsData>(key: T): SettingsData[T] | undefined { function get(): SettingsData;
function get<T extends keyof SettingsData>(key: T): SettingsData[T] | undefined;
function get<T extends keyof SettingsData>(key?: T): SettingsData | SettingsData[T] | undefined {
if (settings === undefined) { if (settings === undefined) {
throw new Error("Settings not initialized"); throw new Error("Settings not initialized");
} }
if (key === undefined) {
return settings;
}
return settings?.[key]; return settings?.[key];
} }
export function set<T extends keyof SettingsData>(key: T, value: SettingsData[T]) { function set(key: SettingsData): void;
function set<T extends keyof SettingsData>(key: T, value: SettingsData[T]): void;
function set<T extends keyof SettingsData>(key: T | SettingsData, value?: SettingsData[T]) {
if (settings === undefined) { if (settings === undefined) {
throw new Error("Settings not initialized"); throw new Error("Settings not initialized");
} }
if (typeof key === "string") {
settings[key] = value; settings[key] = value;
} else {
Object.assign(settings, key);
}
void Settings.set(settings); void Settings.set(settings);
} }

View File

@ -1,70 +1,21 @@
{ {
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true, "experimentalDecorators": true,
/* Basic Options */ "target": "es5",
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"downlevelIteration": true, "downlevelIteration": true,
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ "module": "commonjs",
// "lib": [], /* Specify library files to be included in the compilation. */ "allowJs": true,
"allowJs": true, /* Allow javascript files to be compiled. */ "sourceMap": true,
// "checkJs": true, /* Report errors in .js files. */ "outDir": "./dist",
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "strict": true,
// "declaration": true, /* Generates corresponding '.d.ts' file. */ "noImplicitThis": false,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "noImplicitReturns": true,
"sourceMap": true, /* Generates corresponding '.map' file. */ "noFallthroughCasesInSwitch": true,
// "outFile": "./", /* Concatenate and emit output to single file. */ "moduleResolution": "node",
"outDir": "./dist", /* Redirect output structure to the directory. */ "baseUrl": ".",
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ "paths": {},
// "composite": true, /* Enable project compilation */ "esModuleInterop": true,
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ "forceConsistentCasingInFileNames": true,
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": false, /* Raise error on 'this' expressions with an implied 'any' type. */ // Disabled because of sifrr server that is monkey patching HttpResponse
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": ".", /* Base directory to resolve non-absolute module names. */
"paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"skipLibCheck": true "skipLibCheck": true
} }
} }

View File

@ -2,14 +2,14 @@
import { Router, Route } from "svelte-navigator"; import { Router, Route } from "svelte-navigator";
import Sidebar from "~/lib/Sidebar.svelte"; import Sidebar from "~/lib/Sidebar.svelte";
import LazyRoute from "~/lib/LazyRoute.svelte"; import LazyRoute from "~/lib/LazyRoute.svelte";
import { api } from "~/lib/ipc";
const Home = () => import("~/views/Home.svelte"); const Home = () => import("~/views/Home.svelte");
const AddServer = () => import("~/views/AddServer.svelte"); const AddServer = () => import("~/views/AddServer.svelte");
const Settings = () => import("~/views/Settings.svelte"); const Settings = () => import("~/views/Settings.svelte");
let insideElectron = window?.WorkAdventureDesktopApi?.desktop; let insideElectron = api.desktop;
</script> </script>
{#if insideElectron} {#if insideElectron}

View File

@ -1,5 +1,6 @@
<script> <script>
import { navigate } from "svelte-navigator"; import { navigate } from "svelte-navigator";
import { api } from "~/lib/ipc";
let to = "/"; let to = "/";
let clazz = ""; let clazz = "";
@ -7,7 +8,7 @@
export { clazz as class, to }; export { clazz as class, to };
async function click() { async function click() {
await window?.WorkAdventureDesktopApi?.showLocalApp(); await api.showLocalApp();
navigate(to); navigate(to);
} }
</script> </script>

View File

@ -2,8 +2,9 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import Link from "~/lib/Link.svelte"; import Link from "~/lib/Link.svelte";
import { servers, selectedServer, selectServer, loadServers, Server } from "../store"; import { servers, selectedServer, selectServer, loadServers } from "~/store";
import CogIcon from "~/assets/nes.icons/cog.svg"; import CogIcon from "~/assets/nes.icons/cog.svg";
import { api } from "~/lib/ipc";
let isDevelopment = false; let isDevelopment = false;
@ -26,7 +27,7 @@
onMount(async () => { onMount(async () => {
await loadServers(); await loadServers();
isDevelopment = await window?.WorkAdventureDesktopApi?.isDevelopment(); isDevelopment = await api.isDevelopment();
}); });
</script> </script>

View File

@ -0,0 +1,5 @@
import type { WorkAdventureLocalAppApi, SettingsData, Server } from "@wa-preload-local-app";
export { WorkAdventureLocalAppApi, SettingsData, Server };
// TODO fix type
export const api = (window as any)?.WorkAdventureDesktopApi as WorkAdventureLocalAppApi;

View File

@ -1,10 +1,5 @@
import { writable, get } from "svelte/store"; import { writable, get } from "svelte/store";
import { api, Server } from "~/lib/ipc";
export type Server = {
_id: string;
name: string;
url: string;
};
export const newServer = writable<Omit<Server, "_id">>({ export const newServer = writable<Omit<Server, "_id">>({
name: "", name: "",
@ -14,15 +9,14 @@ export const servers = writable<Server[]>([]);
export const selectedServer = writable<string | undefined>(""); export const selectedServer = writable<string | undefined>("");
export async function selectServer(server: Server) { export async function selectServer(server: Server) {
await window.WorkAdventureDesktopApi.selectServer(server._id); await api.selectServer(server._id);
selectedServer.set(server._id); selectedServer.set(server._id);
} }
export async function addServer() { export async function addServer() {
const addedServer = await window?.WorkAdventureDesktopApi?.addServer(get(newServer)); const addedServer = await api.addServer(get(newServer));
if (!addedServer?._id) { if (addedServer instanceof Error) {
console.log(addedServer); throw new Error(addedServer as unknown as string);
throw new Error(addedServer);
} }
newServer.set({ name: "", url: "" }); newServer.set({ name: "", url: "" });
servers.update((s) => [...s, addedServer]); servers.update((s) => [...s, addedServer]);
@ -30,5 +24,5 @@ export async function addServer() {
} }
export async function loadServers() { export async function loadServers() {
servers.set(await window.WorkAdventureDesktopApi.getServers()); servers.set(await api.getServers());
} }

View File

@ -17,7 +17,6 @@
<div class="flex w-full h-full justify-center items-center"> <div class="flex w-full h-full justify-center items-center">
<form class="flex flex-col justify-center" on:submit|preventDefault={_addServer}> <form class="flex flex-col justify-center" on:submit|preventDefault={_addServer}>
<!-- <input type="text" class="w-full h-12 px-4 py-2 bg-gray-200 rounded-lg" placeholder="Url" required > -->
<InputField title="Name" id="name"> <InputField title="Name" id="name">
<TextInput bind:value={$newServer.name} required id="name" /> <TextInput bind:value={$newServer.name} required id="name" />
</InputField> </InputField>

View File

@ -2,11 +2,12 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import Logo from "~/../../electron/assets/icons/logo.svg"; import Logo from "~/../../electron/assets/icons/logo.svg";
import { api } from "~/lib/ipc";
let version = ""; let version = "";
onMount(async () => { onMount(async () => {
version = await window?.WorkAdventureDesktopApi?.getVersion(); version = await api.getVersion();
}); });
</script> </script>

View File

@ -1,19 +1,33 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { writable } from "svelte/store"; import { writable, get } from "svelte/store";
import ToggleSwitch from "~/lib/ToggleSwitch.svelte"; import ToggleSwitch from "~/lib/ToggleSwitch.svelte";
import InputField from "~/lib/InputField.svelte"; import InputField from "~/lib/InputField.svelte";
import KeyRecord from "~/lib/KeyRecord.svelte"; import KeyRecord from "~/lib/KeyRecord.svelte";
import { api, SettingsData } from "../lib/ipc";
const shortCuts = writable<Record<string, string> | undefined>({}); type ShortCuts = Record<"mute_toggle" | "camera_toggle", string>;
onMount(async () => { const shortCuts = writable<ShortCuts>({
shortCuts.set(await window?.WorkAdventureDesktopApi?.getShortcuts()); mute_toggle: "",
camera_toggle: "",
}); });
async function saveShortcut(key: string, value: string) { onMount(async () => {
await window?.WorkAdventureDesktopApi?.saveShortcut(key, value); const newShortCuts = await api.getSettings()?.["shortcuts"];
shortCuts.set({
...get(shortCuts),
...newShortCuts,
});
});
async function saveShortcut(key: keyof SettingsData['shortcuts'], value: string) {
shortCuts.update((shortCuts) => ({
...shortCuts,
[key]: value,
}));
await api.saveSetting('shortcuts', get(shortCuts));
} }
</script> </script>

View File

@ -15,7 +15,8 @@
"allowJs": true, "allowJs": true,
"checkJs": true, "checkJs": true,
"paths": { "paths": {
"~/*": ["./*"] "~/*": ["./src/*"],
"@wa-preload-local-app": ["../electron/src/preload-local-app/types.ts"],
} }
}, },
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"], "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],