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
The desktop component is an electron app. It uses a hybrid setup based of two main components:
- A `local-app` bundled into the electron app. It has two main parts:
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 with two main parts:
- 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.
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
```bash
# start local-app
yarn dev:local-app
# start local-app in watch mode
cd local-app && yarn dev
# start electron app
LOCAL_APP_URL=http://localhost:3000 yarn dev
# start electron app in watch mode
cd electron && LOCAL_APP_URL=http://localhost:3000 yarn dev
# or create an executable by running:
yarn bundle
cd electron && yarn bundle
```
## API for front

View File

@ -2,8 +2,8 @@ import { ipcMain, app } from "electron";
import electronIsDev from "electron-is-dev";
import { createAndShowNotification } from "./notification";
import { Server } from "./preload-local-app/types";
import settings from "./settings";
import { saveShortcut } from "./shortcuts";
import settings, { SettingsData } from "./settings";
import { loadShortcuts, saveShortcut } from "./shortcuts";
import { getWindow, hideAppView, showAppView } from "./window";
export function emitMuteToggle() {
@ -92,7 +92,10 @@ export default () => {
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 { SettingsData } from "src/settings";
import type { WorkAdventureDesktopApi } from "./types";
const api: WorkAdventureDesktopApi = {
desktop: true,
isDevelopment: () => ipcRenderer.invoke("is-development"),
getVersion: () => ipcRenderer.invoke("get-version"),
notify: (txt: string) => ipcRenderer.send("app:notify", txt),
onMuteToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-mute-toggle", callback),
onCameraToggle: (callback: (event: IpcRendererEvent) => void) => ipcRenderer.on("app:on-camera-toggle", callback),
notify: (txt) => ipcRenderer.send("app:notify", txt),
onMuteToggle: (callback) => ipcRenderer.on("app:on-mute-toggle", callback),
onCameraToggle: (callback) => ipcRenderer.on("app:on-camera-toggle", callback),
};
contextBridge.exposeInMainWorld("WorkAdventureDesktopApi", api);

View File

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

View File

@ -1,4 +1,4 @@
import { SettingsData } from "src/settings";
import { SettingsData } from "../settings";
export type Server = {
_id: string;
@ -6,6 +6,8 @@ export type Server = {
url: string;
};
export { SettingsData };
export type WorkAdventureLocalAppApi = {
desktop: boolean;
isDevelopment: () => Promise<boolean>;
@ -13,8 +15,9 @@ export type WorkAdventureLocalAppApi = {
showLocalApp: () => Promise<void>;
getServers: () => Promise<Server[]>;
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>;
saveShortcut: (shortcut: keyof SettingsData["shortcuts"], key: string | null) => Promise<void>;
getShortcuts: () => Promise<SettingsData["shortcuts"]>;
reloadShortcuts: () => Promise<void>;
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;
}
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) {
throw new Error("Settings not initialized");
}
if (key === undefined) {
return settings;
}
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) {
throw new Error("Settings not initialized");
}
settings[key] = value;
if (typeof key === "string") {
settings[key] = value;
} else {
Object.assign(settings, key);
}
void Settings.set(settings);
}

View File

@ -1,70 +1,21 @@
{
"compilerOptions": {
"experimentalDecorators": true,
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"target": "es5",
"downlevelIteration": true,
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "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. */
"module": "commonjs",
"allowJs": true,
"sourceMap": true,
"outDir": "./dist",
"strict": true,
"noImplicitThis": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": ".",
"paths": {},
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true
}
}

View File

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

View File

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

View File

@ -2,8 +2,9 @@
import { onMount } from "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 { api } from "~/lib/ipc";
let isDevelopment = false;
@ -26,7 +27,7 @@
onMount(async () => {
await loadServers();
isDevelopment = await window?.WorkAdventureDesktopApi?.isDevelopment();
isDevelopment = await api.isDevelopment();
});
</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";
export type Server = {
_id: string;
name: string;
url: string;
};
import { api, Server } from "~/lib/ipc";
export const newServer = writable<Omit<Server, "_id">>({
name: "",
@ -14,15 +9,14 @@ export const servers = writable<Server[]>([]);
export const selectedServer = writable<string | undefined>("");
export async function selectServer(server: Server) {
await window.WorkAdventureDesktopApi.selectServer(server._id);
await api.selectServer(server._id);
selectedServer.set(server._id);
}
export async function addServer() {
const addedServer = await window?.WorkAdventureDesktopApi?.addServer(get(newServer));
if (!addedServer?._id) {
console.log(addedServer);
throw new Error(addedServer);
const addedServer = await api.addServer(get(newServer));
if (addedServer instanceof Error) {
throw new Error(addedServer as unknown as string);
}
newServer.set({ name: "", url: "" });
servers.update((s) => [...s, addedServer]);
@ -30,5 +24,5 @@ export async function addServer() {
}
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">
<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">
<TextInput bind:value={$newServer.name} required id="name" />
</InputField>

View File

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

View File

@ -1,19 +1,33 @@
<script lang="ts">
import { onMount } from "svelte";
import { writable } from "svelte/store";
import { writable, get } from "svelte/store";
import ToggleSwitch from "~/lib/ToggleSwitch.svelte";
import InputField from "~/lib/InputField.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 () => {
shortCuts.set(await window?.WorkAdventureDesktopApi?.getShortcuts());
const shortCuts = writable<ShortCuts>({
mute_toggle: "",
camera_toggle: "",
});
async function saveShortcut(key: string, value: string) {
await window?.WorkAdventureDesktopApi?.saveShortcut(key, value);
onMount(async () => {
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>

View File

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