feat: proof of concept v0.1 web extension companion

feat/type-attributes
Tomáš Mládek 2023-05-20 18:17:13 +02:00
parent db26a4ed32
commit 5b96a9409c
18 changed files with 4917 additions and 46 deletions

View File

@ -394,6 +394,7 @@ fn main() -> Result<()> {
.allowed_origin_fn(|origin, _req_head| {
origin.as_bytes().starts_with(b"http://localhost:")
|| origin.as_bytes().starts_with(b"http://127.0.0.1:")
|| origin.as_bytes().starts_with(b"moz-extension://")
})
.allowed_origin_fn(move |origin, _req_head| {
allowed_origins.iter().any(|allowed_origin| {
@ -431,6 +432,8 @@ fn main() -> Result<()> {
actix_files::Files::new("/", ui_path).index_file("index.html"),
);
}
} else {
// TODO - 503 error
}
app

3
webext/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
dist
web-ext-artifacts

48
webext/README.md Normal file
View File

@ -0,0 +1,48 @@
# Svelte + Vite
This template should help get you started developing with Svelte in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
## Need an official Svelte framework?
Check out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
## Technical considerations
**Why use this over SvelteKit?**
- It brings its own routing solution which might not be preferable for some users.
- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.
`vite dev` and `vite build` wouldn't work in a SvelteKit environment, for example.
This template contains as little as possible to get started with Vite + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.
Should you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.
**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**
Setting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.
**Why include `.vscode/extensions.json`?**
Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
**Why enable `checkJs` in the JS template?**
It is likely that most cases of changing variable types in runtime are likely to be accidental, rather than deliberate. This provides advanced typechecking out of the box. Should you like to take advantage of the dynamically-typed nature of JavaScript, it is trivial to change the configuration.
**Why is HMR not preserving my local component state?**
HMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/rixo/svelte-hmr#svelte-hmr).
If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
```js
// store.js
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)
```

12
webext/index.html Normal file
View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

34
webext/jsconfig.json Normal file
View File

@ -0,0 +1,34 @@
{
"compilerOptions": {
"moduleResolution": "node",
"target": "esnext",
"module": "esnext",
/**
* svelte-preprocess cannot figure out whether you have
* a value or a type, so tell TypeScript to enforce using
* `import type` instead of `import` for Types.
*/
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"resolveJsonModule": true,
/**
* To have warnings / errors of the Svelte compiler at the
* correct position, enable source maps by default.
*/
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable this if you'd like to use dynamic types.
*/
"checkJs": true
},
/**
* Use global.d.ts instead of compilerOptions.types
* to avoid limiting type declarations.
*/
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}

21
webext/manifest.json Normal file
View File

@ -0,0 +1,21 @@
{
"manifest_version": 2,
"name": "UpEnd Companion",
"version": "0.1",
"description": "A database for the complex, the changing, and the indeterminate.",
"permissions": ["activeTab", "storage"],
"icons": {
"64": "public/icon.png"
},
"browser_action": {
"browser_style": true,
"default_icon": "public/icon.png",
"default_title": "Open in UpEnd",
"default_popup": "dist/index.html"
},
"browser_specific_settings": {
"gecko": {
"id": "upend-companion@upend.dev"
}
}
}

32
webext/package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "webext",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"build": "npm-run-all build:vite build:web-ext",
"build:vite": "vite build",
"build:web-ext": "web-ext build --overwrite-dest",
"dev": "npm-run-all -p dev:vite dev:web-ext",
"dev:vite": "vite build --watch",
"dev:web-ext": "web-ext run --devtools"
},
"dependencies": {
"@ibm/plex": "^6.3.0",
"@sveltejs/vite-plugin-svelte": "^1.0.1",
"boxicons": "^2.1.4",
"sass": "^1.62.1",
"svelte": "^3.55.0",
"svelte-preprocess": "^5.0.3",
"typescript": "^4.9.4",
"upend": "../tools/upend_js/",
"vite": "^4.0.3",
"vite-plugin-static-copy": "^0.15.0",
"web-ext": "^7.6.2"
},
"devDependencies": {
"@types/webextension-polyfill": "^0.10.0",
"npm-run-all": "^4.1.5",
"webextension-polyfill": "^0.10.0"
}
}

BIN
webext/public/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

227
webext/src/App.svelte Normal file
View File

@ -0,0 +1,227 @@
<script lang="ts">
import browser from "webextension-polyfill";
import type { VaultInfo } from "upend/types";
import { cleanInstanceUrl, instanceUrlStore } from "./common";
import { onMount } from "svelte";
import "./main.scss";
let opening = false;
let openError: string | undefined;
let instanceUrl: string;
$: instanceUrl = $instanceUrlStore;
let instanceUrlModified = false;
$: instanceUrlModified = $instanceUrlStore !== instanceUrl;
let instanceVersion: string;
let instanceVersionError: string;
$: Boolean($instanceUrlStore) && updateVersion();
async function updateVersion() {
instanceVersion = undefined;
instanceVersionError = undefined;
try {
const vaultInfo = (await (
await fetch(`${$cleanInstanceUrl}/api/info`)
).json()) as VaultInfo;
instanceVersion = vaultInfo.version;
} catch (err: unknown) {
instanceVersionError = processError(err);
}
}
let currentUrl: string | undefined;
let contentType: string | undefined;
onMount(async () => {
const currentTab = (
await browser.tabs.query({
active: true,
currentWindow: true,
})
)[0];
currentUrl = currentTab.url;
contentType = (await browser.tabs.executeScript(currentTab.id, {
code: "document.contentType",
})) as unknown as string | undefined;
});
function visit(address: string) {
browser.tabs.create({ url: `${$cleanInstanceUrl}/#/browse/${address}` });
window.close();
}
async function openAsUrl() {
opening = true;
try {
const address = (await (
await fetch(`${$cleanInstanceUrl}/api/address?url=${currentUrl}`)
).json()) as string;
visit(address);
} catch (err) {
openError = processError(err);
}
}
async function openContent() {
opening = true;
try {
const address = (await (
await fetch(
`${$cleanInstanceUrl}/api/address?url_content=${currentUrl}`
)
).json()) as string;
visit(address);
} catch (err) {
openError = processError(err);
}
}
let primaryAction: [string, () => void] | undefined;
$: primaryAction =
contentType &&
(contentType == "text/html"
? ["Open as URL", openAsUrl]
: ["Open Content", openContent]);
$: primaryActionLabel = primaryAction ? primaryAction[0] : "...";
function performPrimaryAction() {
console.log({ primaryAction });
primaryAction[1]();
}
function processError(err: unknown): string {
if (err instanceof Error) {
if (err.message.includes("NetworkError")) {
return "Network Error. Is UpEnd running?";
} else {
return err.message;
}
} else {
return String(err);
}
}
</script>
<main>
<div class="primary-controls">
<button
class="button"
disabled={!Boolean(primaryAction)}
on:click={performPrimaryAction}
>
{primaryActionLabel}
</button>
<div class="label">Content type: {contentType || "???"}</div>
</div>
<div class="controls row">
<button class="button" on:click={openAsUrl}>Open as URL</button>
<button class="button" on:click={openContent}>Open Content</button>
</div>
{#if opening && !openError}
<div class="status-label">Opening, please wait...</div>
{/if}
{#if openError}
<div class="status-label error">{openError}</div>
{/if}
<hr />
<div class="row">
<label>
Instance URL
<input
class="instance-input"
type="url"
bind:value={instanceUrl}
class:modified={instanceUrlModified}
/>
</label>
<button class="button" on:click={() => ($instanceUrlStore = instanceUrl)}>
Save
</button>
</div>
<div class="version">
Status: {#if !instanceVersionError}
{`OK, v.${instanceVersion}` || "???"}
{:else}
<div class="error">{instanceVersionError}</div>
{/if}
</div>
</main>
<style lang="scss">
@use "../../webui/src/styles/colors";
main {
padding: 1em;
}
input {
background: var(--background);
color: var(--foreground);
border: 1px solid var(--foreground);
border-radius: 2px;
}
input[type="url"] {
font-family: var(--monospace-font);
&:focus-visible {
outline: 1px solid var(--primary-lighter);
}
&:invalid {
color: colors.$red;
outline: 2px solid colors.$red;
}
}
.instance-input.modified {
color: colors.$yellow;
}
hr {
margin: 1rem 0;
}
.controls {
display: flex;
justify-content: space-evenly;
}
.primary-controls {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.25rem;
margin-bottom: 1rem;
.button {
font-size: 1.5rem;
}
.label {
font-size: 0.75rem;
}
}
.row {
display: flex;
align-items: center;
gap: 1rem;
}
.status-label {
margin-top: 1rem;
text-align: center;
}
.error {
color: colors.$red;
}
.version .error {
display: inline;
}
</style>

21
webext/src/common.ts Normal file
View File

@ -0,0 +1,21 @@
import browser from "webextension-polyfill";
import { derived, writable } from "svelte/store";
export const instanceUrlStore = writable<string | undefined>(
undefined,
(set) => {
browser.storage.local.get("instanceUrl").then((result) => {
set(result["instanceUrl"] || "http://localhost:8093");
});
}
);
instanceUrlStore.subscribe((instanceUrl) => {
browser.storage.local.set({ instanceUrl });
});
export const cleanInstanceUrl = derived(instanceUrlStore, (url) => {
if (url) {
return url.replace(/\/+$/g, "");
}
});

7
webext/src/main.js Normal file
View File

@ -0,0 +1,7 @@
import App from './App.svelte'
const app = new App({
target: document.getElementById('app')
})
export default app

3
webext/src/main.scss Normal file
View File

@ -0,0 +1,3 @@
@use "../webui/src/styles/common";
@use "../webui/src/styles/colors-app";
@use "../webui/src/styles/fonts";

2
webext/src/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />

7
webext/svelte.config.js Normal file
View File

@ -0,0 +1,7 @@
import sveltePreprocess from 'svelte-preprocess'
export default {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: sveltePreprocess()
}

24
webext/vite.config.ts Normal file
View File

@ -0,0 +1,24 @@
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { viteStaticCopy } from "vite-plugin-static-copy";
import * as path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
svelte(),
viteStaticCopy({
targets: [
{
src: path.join(__dirname, "node_modules/boxicons", "fonts"),
dest: path.resolve(__dirname, "dist/vendor/boxicons"),
},
{
src: path.join(__dirname, "node_modules/boxicons", "css"),
dest: path.resolve(__dirname, "dist/vendor/boxicons"),
},
],
}),
],
base: "./",
});

4427
webext/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
html {
box-sizing: border-box;
}
* {
box-sizing: inherit;
}
select {
background: var(--background-lighter);
color: var(--foreground);
font-family: var(--default-font);
border: 1px solid var(--foreground-lighter);
border-radius: 4px;
}
.spinner {
font-size: 2em;
}
.button {
border: 1px solid var(--foreground);
border-radius: 4px;
background: var(--background-lighter);
color: var(--foreground);
padding: 0.25em 1em;
line-height: 1;
display: block;
text-align: center;
cursor: pointer;
input {
display: none;
}
&.disabled, &:disabled {
pointer-events: none;
opacity: 0.7;
}
}

View File

@ -1,14 +1,7 @@
@use "normalize.css/normalize.css";
@use "colors-app";
@use "fonts";
html {
box-sizing: border-box;
}
* {
box-sizing: inherit;
}
@use "common";
body {
height: calc(100vh - 2rem);
@ -19,41 +12,3 @@ body {
main {
flex-grow: 1;
}
select {
background: var(--background-lighter);
color: var(--foreground);
font-family: var(--default-font);
border: 1px solid var(--foreground-lighter);
border-radius: 4px;
}
.spinner {
font-size: 2em;
}
.button {
border: 1px solid var(--foreground);
border-radius: 4px;
background: var(--background-lighter);
color: var(--foreground);
padding: 0.25em 1em;
line-height: 1;
display: block;
text-align: center;
cursor: pointer;
input {
display: none;
}
&.disabled {
pointer-events: none;
opacity: 0.7;
}
}