Compare commits

..

2 Commits

Author SHA1 Message Date
Fabian Stamm
0dff9d869d Restructuring 2020-02-09 18:26:22 +01:00
Fabian Stamm
b588693ccf Switching to parcel 2020-02-09 17:36:25 +01:00
51 changed files with 10689 additions and 6245 deletions

View File

@ -1,9 +0,0 @@
https://notes.dev.hibas123.de:443 {
proxy / localhost:1234/
tls D:\Certs\_wildcard.dev.hibas123.de.pem D:\Certs\_wildcard.dev.hibas123.de-key.pem
}
https://sf.dev.hibas123.de:443 {
proxy / localhost:3004/
tls D:\Certs\_wildcard.dev.hibas123.de.pem D:\Certs\_wildcard.dev.hibas123.de-key.pem
}

View File

@ -1,26 +0,0 @@
VERSION 0.7
docker-multi:
BUILD --platform linux/amd64 --platform linux/arm64 +docker
build:
FROM node:lts
WORKDIR /build
COPY . .
RUN npm config set registry https://npm.hibas123.de
RUN npm install
RUN npm run build
SAVE ARTIFACT dist secure_notes_files
docker:
FROM busybox:1.36
WORKDIR /app
COPY --platform=linux/amd64 +build/secure_notes_files /app/
CMD ["busybox", "httpd", "-f", "-v", "-p", "3001", "-h", "/app"]
ARG EARTHLY_TARGET_TAG
ARG TAG=$EARTHLY_TARGET_TAG
SAVE IMAGE --push git.hibas.dev/openserver/secure_notes:$TAG

7
config.json Executable file
View File

@ -0,0 +1,7 @@
{
"secure_file_server": "https://sf.dev.hibas123.de",
"auth_server": "https://auth.stamm.me",
"client_id": "cf699b12-2014-4a61-bb7d-a7e38b197350",
"permission": "5c1ed399dc361731340a49d4",
"callback_url": "https://notes.dev.hibas123.de"
}

8298
package-lock.json generated Executable file

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,8 @@
{ {
"name": "@hibas123/securenotes2", "name": "@hibas123/securenotes2",
"version": "2.0.2", "version": "2.0.0-alpha.1",
"description": "", "description": "",
"main": "index.js",
"scripts": { "scripts": {
"build": "parcel build src/index.html", "build": "parcel build src/index.html",
"dev": "parcel src/index.html" "dev": "parcel src/index.html"
@ -12,33 +13,25 @@
"last 2 Chrome versions" "last 2 Chrome versions"
], ],
"dependencies": { "dependencies": {
"@codemirror/commands": "^6.6.0", "@hibas123/secure-file-wrapper": "^2.5.1",
"@codemirror/lang-markdown": "^6.2.5", "@hibas123/theme": "^1.2.14",
"@hibas123/secure-file-wrapper": "^2.5.3", "@hibas123/utils": "^2.2.3",
"@hibas123/theme": "^2.0.7",
"@hibas123/utils": "^2.2.18",
"aes-js": "^3.1.2", "aes-js": "^3.1.2",
"codemirror": "^6.0.1", "feather-icons": "^4.26.0",
"easymde": "^2.18.0", "idb": "^4.0.3",
"feather-icons": "^4.29.2", "js-sha256": "^0.9.0",
"idb": "^5.0.8",
"js-sha256": "^0.11.0",
"lodash": "^4.17.21",
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"parcel": "^2.12.0", "parcel": "^1.12.4",
"preact": "^10.22.0", "uuid": "^3.4.0"
"preact-feather": "^4.2.1",
"uuid": "^10.0.0"
}, },
"devDependencies": { "devDependencies": {
"@parcel/packager-raw-url": "2.12.0", "@types/lodash.clonedeep": "^4.5.6",
"@parcel/transformer-sass": "^2.12.0", "@types/uikit": "^2.27.7",
"@parcel/transformer-webmanifest": "^2.12.0", "@types/uuid": "^3.4.7",
"@types/codemirror": "5.60.15", "node-sass": "^4.13.1",
"@types/lodash.clonedeep": "^4.5.9", "parcel-bundler": "^1.12.4",
"@types/uuid": "^10.0.0", "preact": "^10.3.1",
"process": "^0.11.10", "ts-loader": "^6.2.1",
"sass": "^1.77.6", "typescript": "^3.7.5"
"typescript": "^5.5.2"
} }
} }

File diff suppressed because it is too large Load Diff

0
src/public/favicon.ico → public/favicon.ico Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

0
src/public/notepad128.png → public/notepad128.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

0
src/public/notepad16.png → public/notepad16.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 562 B

After

Width:  |  Height:  |  Size: 562 B

0
src/public/notepad24.png → public/notepad24.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 554 B

After

Width:  |  Height:  |  Size: 554 B

0
src/public/notepad256.png → public/notepad256.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

0
src/public/notepad32.png → public/notepad32.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 720 B

After

Width:  |  Height:  |  Size: 720 B

0
src/public/notepad512.png → public/notepad512.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

0
src/public/notepad64.png → public/notepad64.png Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 915 B

After

Width:  |  Height:  |  Size: 915 B

View File

@ -0,0 +1,37 @@
import { h } from "preact";
import { Page } from "../../page";
import Theme, { ThemeStates } from "../../theme";
import Navigation from "../../navigation";
import ArrowLeft from "feather-icons/dist/icons/arrow-left.svg";
export default class SettingsPage extends Page<{ state: any }, { vault: string }> {
componentWillMount() {
}
render() {
let active = Theme.active();
return <div>
<header class="header">
<a class="header-icon-button" onClick={() => history.back()}><img src={ArrowLeft} height={undefined} width={undefined} /></a>
<h3 style="display:inline" class="header-title" onClick={() => Navigation.setPage("/")}>Settings</h3>
<span></span>
</header>
<div class="container">
<div className="input-group">
<label>Select Theme: </label>
<select class="inp" onChange={(ev) => Theme.change(Number((ev.target as HTMLSelectElement).value))}>
{Object.keys(ThemeStates)
.filter(e => Number.isNaN(Number(e)))
.map(e => <option selected={ThemeStates[e] === active} value={ThemeStates[e]}>{e.charAt(0).toUpperCase() + e.slice(1).toLowerCase()}</option>)}
{/* <option value={ThemeStates.AUTO}>Auto</option>
<option value={ThemeStates.LIGHT}>Light</option>
<option value={ThemeStates.DARK}>Dark</option> */}
</select>
</div>
{/* <button class="btn" onClick={() => Theme.toggle()}>Toggle Dark Mode</button> */}
<button class="btn" onClick={() => window.navigator.serviceWorker.controller.postMessage("message")}>Clear cache</button>
</div>
</div >;
}
}

View File

@ -1,7 +1,7 @@
import { h } from "preact"; import { h } from "preact";
import { Page } from "../../../page"; import { Page } from "../../page";
import VaultsPage from "../vaults/Vaults"; import VaultsPage from "../Vaults/Vaults";
import Navigation from "../../../navigation"; import Navigation from "../../navigation";
export default class SharePage extends Page<{ state: any }, { vault: string }> { export default class SharePage extends Page<{ state: any }, { vault: string }> {
text: string; text: string;

188
src/Views/Vault/Entry.tsx Executable file
View File

@ -0,0 +1,188 @@
import { h, Component } from "preact"
import { IVault, ViewNote } from "../../notes";
import Trash from "feather-icons/dist/icons/trash-2.svg"
import X from "feather-icons/dist/icons/x.svg"
import Save from "feather-icons/dist/icons/save.svg"
import Navigation from "../../navigation";
import { YesNoModal } from "../../components/modals/YesNoModal";
import Notifications, { MessageType } from "../../notifications";
const minRows = 3;
export default class EntryComponent extends Component<{ vault: Promise<IVault>, id: string | undefined, note: string | undefined }, { title: string, changed: boolean }> {
private text: string = "";
private vault: IVault;
// private lineHeight: number = 24;
private note: ViewNote;
private rows: number = minRows;
private skip_save: boolean = false;
private inputElm: HTMLInputElement;
constructor(props) {
super(props);
this.state = { changed: false, title: "" };
this.textAreaChange = this.textAreaChange.bind(this);
this.textAreaKeyPress = this.textAreaKeyPress.bind(this);
}
private toVault() {
history.back();
}
componentDidMount() {
this.inputElm.focus();
}
async componentWillMount() {
this.text = "";
this.vault = undefined;
this.note = undefined;
this.rows = minRows;
this.skip_save = false;
this.setState({ changed: false, title: "" });
try {
this.skip_save = false;
this.vault = await this.props.vault;
let note: ViewNote;
let changed = false;
if (this.props.id)
note = await this.vault.getNote(this.props.id)
else {
note = this.vault.newNote();
if (this.props.note) {
note.__value = this.props.note;
changed = true;
}
}
if (!note) {
Notifications.sendNotification("Note not found!", MessageType.ERROR);
} else {
this.note = note;
this.text = note.__value;
let rows = this.getRows(this.text);
if (rows !== this.rows) {
this.rows = rows;
}
let [title] = this.text.split("\n", 1);
this.setState({ title, changed })
}
} catch (err) {
Notifications.sendError(err);
}
}
private async save() {
try {
if (this.state.changed) {
this.note.__value = this.text;
await this.vault.saveNote(this.note);
this.setState({ changed: false })
}
} catch (err) {
Notifications.sendError(err);
}
}
componentWillUnmount() {
if (!this.skip_save)
this.save()
}
strToNr(value: string) {
let match = value.match(/\d/g)
return Number(match.join(""))
}
getRows(value: string) {
const lines = (value.match(/\r?\n/g) || '').length + 1
return Math.max(lines + 1, minRows);
}
textAreaChange(evt: KeyboardEvent) {
if (evt.keyCode === 17 || evt.keyCode === 27) return; //No character, so not relevant for this function
if (!this.state.changed && this.textAreaKeyPress(evt)) this.setState({ changed: true })
let target = (evt.target as HTMLTextAreaElement)
let value = target.value;
this.text = value;
let [title] = value.split("\n", 1);
if (title !== this.state.title)
this.setState({ title });
let rows = this.getRows(value);
if (rows !== this.rows) {
target.rows = rows;
this.rows = rows;
}
}
async exitHandler() {
if (this.state.changed) {
let modal = new YesNoModal("Really want to quit?");
let res = await modal.getResult();
if (res === true) {
this.skip_save = true;
this.toVault();
}
} else
this.toVault()
}
textAreaKeyPress(evt: KeyboardEvent) {
console.log(evt);
if ((evt.keyCode === 83 || evt.keyCode === 13) && evt.ctrlKey) {
evt.preventDefault()
this.save();
return false;
}
else if (evt.keyCode === 27) {
evt.preventDefault();
this.exitHandler();
return false;
}
return true;
}
render() {
const save_handler = async () => {
await this.save()
Navigation.setPage("/vault", { id: this.vault.id }, { entry: "false" }, true);
this.toVault()
}
const delete_handler = async () => {
await this.vault.deleteNote(this.props.id);
this.toVault()
}
console.log("Rerender")
return <div>
<header class="header">
<a class="header-icon-button" onClick={() => this.exitHandler()}><img src={X} height={undefined} width={undefined} /></a>
{this.state.changed ? <a class="header-icon-button" style="margin-left: 0.5em;" onClick={() => save_handler()}><img src={Save} height={undefined} width={undefined} /></a> : undefined}
<h3 style="display:inline" class="button header-title">{this.state.title}</h3>
<a class="header-icon-button" onClick={() => delete_handler()}><img src={Trash} height={undefined} width={undefined} /></a>
</header>
<div class="container">
<textarea
value={this.text}
rows={this.rows}
class="inp"
style="width:100%;"
onInput={this.textAreaChange}
onKeyDown={this.textAreaKeyPress}
onChange={this.textAreaChange}
ref={elm => this.inputElm = elm}
/>
</div>
</div>
}
}

297
src/Views/Vault/EntryList.tsx Executable file
View File

@ -0,0 +1,297 @@
import { h, Component, JSX } from "preact"
import Notes, { IVault, BaseNote } from "../../notes";
import AddButton from "../../components/AddButton";
import Navigation from "../../navigation";
import ArrowLeft from "feather-icons/dist/icons/arrow-left.svg"
import Search from "feather-icons/dist/icons/search.svg"
import ContextMenu from "../../components/context";
import Notifications from "../../notifications";
import { Observable, Lock } from "@hibas123/utils";
export default class EntryList extends Component<{ vault: Promise<IVault> }, { notes: BaseNote[], context: JSX.Element | undefined }> {
rawNotes: BaseNote[];
private searchObservableServer = new Observable<void>(1000);
private searchObservable = this.searchObservableServer.getPublicApi();
constructor(props) {
super(props)
console.log("Creating new Instance of EntryList")
this.state = { notes: [], context: undefined }
this.onDragOver = this.onDragOver.bind(this);
this.onDrop = this.onDrop.bind(this);
this.reloadNotes = this.reloadNotes.bind(this);
this.searchChanged = this.searchChanged.bind(this);
}
vault: IVault;
async reloadNotes(s?: boolean) {
if (s)
return;
this.rawNotes = await this.vault.getAllNotes();
await this.applySearch(true);
}
async componentWillMount() {
this.vault = await this.props.vault;
this.reloadNotes();
document.body.addEventListener("dragover", this.onDragOver);
document.body.addEventListener("drop", this.onDrop);
Notes.syncObservable.subscribe(this.reloadNotes);
this.searchObservable.subscribeCollect(() => this.applySearch());
}
componentWillUnmount() {
document.body.removeEventListener("dragover", this.onDragOver);
document.body.removeEventListener("drop", this.onDrop);
Notes.syncObservable.unsubscribe(this.reloadNotes);
}
componentDidMount() {
console.log("ON Component Did mount", this.search);
this.searchInput.value = this.search;
}
onDragOver(evt: DragEvent) {
evt.preventDefault();
}
onContext(evt: MouseEvent, note: BaseNote) {
evt.preventDefault();
evt.stopPropagation();
const close = () => {
document.documentElement.removeEventListener("click", close);
this.setState({ context: undefined });
}
document.documentElement.addEventListener("click", close);
const shareNote = async () => {
let nav = window.navigator as any;
if (nav.share !== undefined) {
let vnote = await this.vault.getNote(note._id);
nav.share({ title: vnote.preview.split("\n")[0], text: vnote.__value })
.then(() => console.log('Successful share'))
.catch(error => {
console.error('Error sharing:', error)
Notifications.sendError(error)
});
} else {
Notifications.sendError("Sharing not possible on this device")
}
}
const deleteNote = async () => {
this.vault.deleteNote(note._id).then(() => {
Notifications.sendSuccess("Deleted")
this.rawNotes = this.rawNotes.filter(e => e._id !== note._id);
this.setState({ notes: this.state.notes.filter(e => e._id !== note._id) });
}).catch(err => {
Notifications.sendError(err);
})
}
const copyNote = async () => {
this.vault.getNote(note._id).then(note => {
const el = document.createElement('textarea');
el.value = note.__value;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
Notifications.sendSuccess("Copied");
})
}
let share;
if ((window.navigator as any).share) {
share = <button class="btn" onClick={shareNote}>
share
</button>
}
let context = <ContextMenu event={evt} >
{share}
<button class="btn" onClick={deleteNote}>delete</button>
<button class="btn" onClick={copyNote}>copy</button>
</ContextMenu>
this.setState({ context });
return false;
}
async onDrop(evt: DragEvent) {
evt.preventDefault();
if (evt.dataTransfer.items) {
for (let i = 0; i < evt.dataTransfer.items.length; i++) {
let item = evt.dataTransfer.items[i];
if (item.kind === "file") {
let file = item.getAsFile();
if (file.type !== "application/json") {
Notifications.sendError("Invalid File Type!!!")
} else {
try {
let data = await new Promise<string>((yes, no) => {
let fr = new FileReader()
fr.onload = (ev) => {
yes((ev.target as any).result);
}
fr.onerror = no;
fr.readAsText(file);
})
let parsed = JSON.parse(data);
let c = new Error("Could not parse!");
let notes: { content: string, time: Date }[] = null;
if (Array.isArray(parsed)) { // Could be from SecureNotes 1
notes = parsed.map(elm => {
if (typeof elm.message !== "string" || typeof elm.time !== "string") {
throw c;
}
return {
content: elm.message,
time: new Date(elm.time)
}
})
} else if (parsed.version) { // Could be from SecureNotes 2
if (parsed.version === 1) { //Could be from SecureNotes 2 version 1
notes = (parsed.notes as any[]).map(elm => {
if (typeof elm.content !== "string" || typeof elm.time !== "string") {
throw c;
}
return {
content: elm.content,
time: new Date(elm.time)
}
})
} else {
throw c;
}
} else
throw c;
await Promise.all(notes.map(n => {
let note = this.vault.newNote();
note.__value = n.content;
return this.vault.saveNote(note, n.time);
}));
await this.reloadNotes();
Notifications.sendSuccess(`Imported ${notes.length} notes!`);
} catch (err) {
Notifications.sendError("Cannot read File!")
console.error(err);
}
}
}
}
}
}
searchLock = new Lock();
oldSearch = "";
async applySearch(force = false) {
const search = this.search.toLowerCase();
if (!force && search === this.oldSearch) {
return;
}
if (this.searchLock.locked)
return;
const lock = await this.searchLock.getLock();
console.time("SearchOP");
let notes: BaseNote[] = [];
if (search === "") {
notes = this.rawNotes;
} else {
const parts = search.split(" ");
const match = (note: BaseNote) => {
return parts.every(function (el) {
return note.preview.toLowerCase().indexOf(el) > -1;
});
}
let elements: BaseNote[];
if (!force && this.oldSearch && search.startsWith(this.oldSearch)) {
elements = [...this.state.notes];
} else {
elements = [...this.rawNotes];
}
await new Promise(yes => {
const idle = () => {
window.requestIdleCallback(deadline => {
let invTR = deadline.timeRemaining() <= 0;
while ((deadline.timeRemaining() > 0 || invTR) && elements.length > 0) {
let element = elements.shift();
if (match(element)) {
notes.push(element);
}
}
if (elements.length > 0)
idle();
else
yes();
}, { timeout: 100 });
}
idle();
})
// notes = elements.filter(note => match(note));
}
await new Promise(yes => this.setState({ notes }, yes));
this.oldSearch = search;
lock.release();
console.timeEnd("SearchOP");
}
search = "";
searchChanged(evt: Event) {
let input = evt.target as HTMLInputElement;
this.search = input.value;
this.searchObservableServer.send();
}
searchInput: HTMLInputElement;
render() {
const open_entry = (id: string | null) => {
Navigation.setPage("/vault", { id: this.vault.id }, { id, entry: "true" })
}
return <div>
{this.state.context}
<header class="header">
<a class="header-icon-button" onClick={() => history.back()}><img src={ArrowLeft} height={undefined} width={undefined} /></a>
<h3 style="display:inline" class="header-title" onClick={() => Navigation.setPage("/")}>{this.vault ? this.vault.name : ""}</h3>
<span></span>
{/* <a class="button header_icon_button"><MoreVertival height={undefined} width={undefined} /></a> */}
</header>
<AddButton onClick={() => open_entry(null)} />
<div class="container">
<div style="display:flex;">
<input class="inp" type="text" style="width: 100%; height: 40px;" onKeyUp={this.searchChanged} ref={elm => this.searchInput = elm} />
<button class="btn btn-primary" style="padding: 5px 10px; margin: 0; height: 40px; width: 40px;">
<img src={Search} />
</button>
</div>
<div class="vault-list" style="margin-top: 1rem;">
{this.state.notes.map(note => {
let [first, second] = note.preview.split("\n", 2);
return <div class="card vault-vault" onContextMenu={evt => this.onContext(evt, note)} onClick={() => {
open_entry(note._id)
}}>
<div>{first}</div>
<div>{second}</div>
</div>
})}
</div>
</div>
</div>;
}
}

47
src/Views/Vault/Vault.tsx Executable file
View File

@ -0,0 +1,47 @@
import { h } from "preact"
import { Page } from "../../page";
import Notes, { IVault, BaseNote } from "../../notes";
import Navigation from "../../navigation";
import EntryComponent from "./Entry";
import EntryList from "./EntryList";
import "./vault.scss"
export interface VaultProps {
state: { id: string };
hidden: { entry: string, id: string, note: string };
}
export default class VaultPage extends Page<VaultProps, { entries: BaseNote[] }> {
vault: Promise<IVault>
constructor(props: VaultProps) {
super(props);
this.state = { entries: [] };
}
async componentWillMount() {
this.vault = Notes.getVault(this.props.state.id, Notes.getVaultKey(this.props.state.id))
this.vault.then(vlt => {
window.debug.activeVault = vlt;
window.debug.createNotes = (cnt = 10) => {
for (let i = 0; i < cnt; i++) {
let nt = vlt.newNote();
nt.__value = `Random Note ${i}\ With some Content ${i}`;
vlt.saveNote(nt);
}
}
})
this.vault.catch(err => {
Navigation.setPage("/")
});
}
render() {
if (this.props.hidden && this.props.hidden.entry === "true") {
return <EntryComponent vault={this.vault} id={this.props.hidden.id} note={this.props.hidden.note} />
} else {
return <EntryList vault={this.vault} />
}
}
}

241
src/Views/Vaults/Vaults.tsx Normal file
View File

@ -0,0 +1,241 @@
import { h, JSX } from "preact"
import { Page } from "../../page";
import Notes, { VaultList } from "../../notes";
import "./vaults.scss"
import Lock from "feather-icons/dist/icons/lock.svg";
import Unlock from "feather-icons/dist/icons/unlock.svg";
import Settings from "feather-icons/dist/icons/settings.svg"
import Navigation from "../../navigation";
import { InputModal } from "../../components/modals/InputModal";
import { YesNoModal } from "../../components/modals/YesNoModal";
import AddButton from "../../components/AddButton";
import ContextMenu from "../../components/context";
import Notifications from "../../notifications";
export interface VaultsProps {
state: any;
selectVault?: boolean;
onSelected?: (vaultid: string) => void;
}
export default class VaultsPage extends Page<VaultsProps, { vaults: VaultList, modal: JSX.Element | undefined, context: JSX.Element | undefined }> {
constructor(props: VaultsProps) {
super(props);
this.state = { vaults: [], modal: undefined, context: undefined };
this.updateVaults = this.updateVaults.bind(this);
}
updateVaults(s?: boolean) {
if (s)
return;
return new Promise(yes => {
Notes.getVaults().then(vaults => this.setState({ vaults }, yes))
})
}
componentWillMount() {
this.updateVaults()
Notes.syncObservable.subscribe(this.updateVaults);
}
componentWillUnmount() {
Notes.syncObservable.unsubscribe(this.updateVaults);
}
async getKey(vault: { name: string, id: string }, permanent = true) {
let inp_mod = new InputModal("Enter password for " + vault.name, "Password", "password");
let key = undefined;
while (true) {
// inp_mod.show();
let value = await inp_mod.getResult(false);
if (value === null) {
console.log("Value is null")
inp_mod.close()
return false;
} else {
key = Notes.passwordToKey(value);
try {
await Notes.getVault(vault.id, key);
break;
} catch (err) {
Notifications.sendError("Invalid password!")
}
}
}
inp_mod.close()
let perm = false;
if (permanent) {
let save_modal = new YesNoModal("Save permanent?");
let res = await save_modal.getResult();
if (res === undefined) {
res = false;
}
perm = res;
}
Notes.saveVaultKey(vault.id, key, perm);
return true;
}
async openVault(vault: { name: string, encrypted: boolean, id: string }) {
const action = () => {
if (this.props.selectVault) {
this.props.onSelected(vault.id);
} else {
Navigation.setPage("/vault", { id: vault.id })
}
}
if (vault.encrypted) {
let key = Notes.getVaultKey(vault.id);
if (key)
action()
else {
if (await this.getKey(vault))
action();
}
} else {
action()
}
}
async addButtonClick() {
let name_modal = new InputModal("Enter new name", "Name", "text");
let name = await name_modal.getResult();
if (name === null) return;
let encrypted_modal = new YesNoModal("Encrypt?");
let encrypted = encrypted_modal.getResult();
if (encrypted === null) return;
let password;
if (encrypted) {
let password_modal = new InputModal("Enter new password", "Password", "password");
password = await password_modal.getResult();
if (password === null) return;
}
let key;
if (password) {
key = Notes.passwordToKey(password)
}
await Notes.createVault(name, key)
this.updateVaults();
}
onContext(evt: MouseEvent, vault: { name: string, encrypted: boolean, id: string }) {
evt.preventDefault();
evt.stopPropagation();
const close = () => {
document.documentElement.removeEventListener("click", close);
this.setState({ context: undefined });
}
document.documentElement.addEventListener("click", close);
let deleteb = <button class="btn" onClick={async () => {
let delete_modal = new YesNoModal("Delete Vault? Cannot be undone!");
let result = await delete_modal.getResult();
if (result) {
Notes.deleteVault(vault.id).then(() => {
this.updateVaults();
}).catch(err => {
Notifications.sendError("Error deleting vault!")
console.error(err);
})
}
}}>
delete
</button>;
let delete_key;
if (Notes.getVaultKey(vault.id)) {
delete_key = <button class="btn" onClick={() => {
Notes.forgetVaultKey(vault.id);
Notifications.sendSuccess("Forgot password!")
}}>
forget password
</button>;
}
let exportb = <button class="btn" onClick={async () => {
let key: Uint8Array;
if (vault.encrypted) {
await this.getKey(vault, false)
key = Notes.getVaultKey(vault.id);
}
let note_vault = await Notes.getVault(vault.id, key);
let base_notes = await note_vault.getAllNotes();
let notes = await Promise.all(base_notes.map(e => {
return note_vault.getNote(e._id);
}));
let result =
{
version: 1,
notes: notes.map(e => {
return {
content: e.__value,
time: e.time
}
})
}
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(result, undefined, 3));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "notes_export_" + vault.name + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}}>
export
</button>;
let context = <ContextMenu event={evt} >
{deleteb}
{delete_key}
{exportb}
</ContextMenu>
this.setState({ context });
return false;
}
render() {
// <Unlock height={undefined} width={undefined} />}
// <Lock height={undefined} width={undefined} />
let elms = this.state.vaults.map(vault => {
return <li class="vaults_vault" onClick={() => this.openVault(vault)} onContextMenu={(evt) => this.onContext(evt, vault)}>
{vault.encrypted ? <img src={Lock} /> : <img src={Unlock} />}
<span>
{vault.name}
</span>
</li>
})
return <div style={{ marginTop: "-12px", paddingTop: "12px" }} >
{/* {this.state.modal} */}
{this.state.context}
<header class="header">
<span></span>
<h3 style="display:inline" onClick={() => Navigation.setPage("/")}>{this.props.selectVault ? "Select Vault for share" : "Your vaults:"}</h3>
<a class="header-icon-button" onClick={() => Navigation.setPage("/settings")}>
<img src={Settings} />
{/* <Settings height={undefined} width={undefined} /> */}
</a>
</header>
<AddButton onClick={() => this.addButtonClick()} />
<div class="container">
<ul class="list list-divider list-clickable">
{elms}
</ul>
</div>
</div>
}
}

View File

@ -1,14 +1,14 @@
import { h } from "preact"; import { h } from "preact";
import "./add_button.scss"; import "./add_button.scss";
import { Plus } from "preact-feather"; import Plus from "feather-icons/dist/icons/plus.svg";
export default function AddButton({ onClick }: { onClick: () => void }) { export default function AddButton({ onClick }: { onClick: () => void }) {
return ( return <button
<button
title="add button" title="add button"
class="fab btn-primary" class="fab btn-primary"
onClick={() => onClick()} onClick={() => onClick()}
> >
<Plus width={undefined} height={undefined} /> <img src={Plus} />
</button> </button>
);
} }
// <Plus width={undefined} height={undefined} />

View File

@ -1,3 +0,0 @@
.CodeMirror {
height: auto;
}

View File

@ -1,62 +0,0 @@
import { h } from "preact";
import { useEffect, useRef } from "preact/hooks";
import { EditorView, basicSetup, } from "codemirror";
import { EditorState, Text } from "@codemirror/state";
import { defaultKeymap } from "@codemirror/commands"
import { markdown } from "@codemirror/lang-markdown"
// import "codemirror/lib/codemirror.css";
// import "codemirror/theme/base16-dark.css";
import "./CodeMirror.scss";
import Theme from "../theme";
interface ICodeMirrorProps {
value: string;
onChange: (value: string) => void;
onSave?: (value: string) => void;
onClose?: () => void;
}
export default function CodeMirror(props: ICodeMirrorProps) {
const ref = useRef<HTMLTextAreaElement>();
useEffect(() => {
const instance = new EditorView({
parent: ref.current,
extensions: [
basicSetup,
markdown(),
],
})
// const instance = CM.(ref.current, {
// value: props.value,
// mode: "markdown",
// lineNumbers: true,
// lineWrapping: true,
// theme: Theme.isDark.value ? "base16-dark" : "default",
// viewportMargin: Infinity,
// // extraKeys: {
// // "Ctrl-S": (cm) => {
// // const val = cm.getValue();
// // props?.onSave(val);
// // },
// // Esc: props.onClose,
// // },
// });
const state = EditorState.create({
doc: Text.of([props.value ?? ""]),
});
instance.setState(state);
instance.focus();
state.
instance.on("change", () => props?.onChange(instance.getValue()));
return () => { };
}, [ref]);
return <textarea ref={ref}></textarea>;
}

View File

@ -1,13 +1,10 @@
import { h, Component } from "preact"; import { h, Component } from "preact";
import Notes from "../notes"; import Notes from "../notes";
import { RefreshCw as Refresh } from "preact-feather"; import Refresh from "feather-icons/dist/icons/refresh-cw.svg";
import "./footer.scss"; import "./footer.scss";
import Notifications from "../notifications"; import Notifications from "../notifications";
export class Footer extends Component< export class Footer extends Component<{}, { synced: boolean, syncing: boolean }> {
{},
{ synced: boolean; syncing: boolean }
> {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { synced: false, syncing: false }; this.state = { synced: false, syncing: false };
@ -18,7 +15,7 @@ export class Footer extends Component<
async componentWillMount() { async componentWillMount() {
Notes.syncedObservable.subscribe(this.onSyncedChange); Notes.syncedObservable.subscribe(this.onSyncedChange);
Notes.syncObservable.subscribe(this.onSyncChange); Notes.syncObservable.subscribe(this.onSyncChange);
this.setState({ synced: await Notes.isSynced() }); this.setState({ synced: await Notes.isSynced() })
} }
componentWillUnmount() { componentWillUnmount() {
@ -28,18 +25,18 @@ export class Footer extends Component<
onSyncChange(state: boolean) { onSyncChange(state: boolean) {
console.log("sync", state); console.log("sync", state);
this.setState({ syncing: state }); this.setState({ syncing: state })
} }
onSyncedChange(state: boolean) { onSyncedChange(state: boolean) {
console.log("synced", state); console.log("synced", state);
this.setState({ synced: state }); this.setState({ synced: state })
} }
onSyncClick() { onSyncClick() {
Notes.sync().then(() => { Notes.sync().then(() => {
Notifications.sendInfo("Finished Synchronisation"); Notifications.sendInfo("Finished Synchronisation");
}); })
} }
render() { render() {
@ -49,7 +46,7 @@ export class Footer extends Component<
if (this.state.syncing) { if (this.state.syncing) {
color = "orange"; color = "orange";
text = "syncing"; text = "syncing";
extrac = "reloading"; extrac = "reloading"
} else { } else {
if (this.state.synced) { if (this.state.synced) {
color = "green"; color = "green";
@ -59,12 +56,12 @@ export class Footer extends Component<
text = "not synced"; text = "not synced";
} }
} }
return ( return <footer class="elv-8">
<footer class="elv-8">
<span> <span>
<span class={extrac}> <span class={extrac} >
<a onClick={() => this.onSyncClick()}> <a onClick={() => this.onSyncClick()} >
<Refresh style="height: 1em; width: 1em;"></Refresh> <img src={Refresh} style="height: 1em; width: 1em;" />
{/* <Refresh style="height: 1em; width: 1em;"></Refresh> */}
</a> </a>
</span> </span>
<span style={"margin-left: 8px; color:" + color}>{text}</span> <span style={"margin-left: 8px; color:" + color}>{text}</span>
@ -72,8 +69,9 @@ export class Footer extends Component<
<span> <span>
Welcome <b>{Notes.name}</b> Welcome <b>{Notes.name}</b>
</span> </span>
<span style="color: lightgrey;">v2.0.2</span> <span style="color: lightgrey;">
v1.4
</span>
</footer> </footer>
);
} }
} }

View File

@ -1,4 +1,4 @@
import { h, Component } from 'preact'; import { h, Component, JSX } from 'preact';
import Navigation from '../navigation'; import Navigation from '../navigation';
import "./routing.scss" import "./routing.scss"

View File

@ -1,4 +1,4 @@
import { h } from "preact"; import { h, JSX } from "preact";
import "./context.scss"; import "./context.scss";
export default function ContextMenu({ children, event }: { children: JSX.Element | JSX.Element[], event: MouseEvent }) { export default function ContextMenu({ children, event }: { children: JSX.Element | JSX.Element[], event: MouseEvent }) {

View File

@ -1,15 +1,13 @@
import { Observable } from "@hibas123/utils"; import { Observable } from "@hibas123/utils";
import { h, Component } from "preact"; import { h, Component, JSX } from "preact";
import { X } from "preact-feather"; import CloseIcon from "feather-icons/dist/icons/x.svg";
export default abstract class Modal<T> { export default abstract class Modal<T> {
// Static // Static
private static modalObservableServer = new Observable<{ private static modalObservableServer = new Observable<{ modal: Modal<any>, close: boolean }>();
modal: Modal<any>;
close: boolean;
}>();
public static modalObservable = Modal.modalObservableServer.getPublicApi(); public static modalObservable = Modal.modalObservableServer.getPublicApi();
protected abstract title: string; protected abstract title: string;
// Private // Private
@ -19,8 +17,10 @@ export default abstract class Modal<T> {
// Protected // Protected
protected result(value: T | null) { protected result(value: T | null) {
if (this.closeOnResult) this.close(); if (this.closeOnResult)
if (this.onResult) this.onResult(value); this.close()
if (this.onResult)
this.onResult(value);
} }
//Public //Public
@ -41,7 +41,7 @@ export default abstract class Modal<T> {
public async getResult(close = true) { public async getResult(close = true) {
this.closeOnResult = close; this.closeOnResult = close;
this.show(false); this.show(false);
return new Promise<T | null>((yes) => (this.onResult = yes)); return new Promise<T | null>((yes) => this.onResult = yes);
} }
public close() { public close() {
@ -50,68 +50,53 @@ export default abstract class Modal<T> {
public abstract getComponent(): JSX.Element; public abstract getComponent(): JSX.Element;
public static BaseModal = class BaseModal<T> extends Component< public static BaseModal = class BaseModal<T> extends Component<{ modal: Modal<T> }, {}> {
{ modal: Modal<T> },
{}
> {
render() { render() {
return ( return <div class="modal-container" onClick={(evt) => {
<div
class="modal-container"
onClick={(evt) => {
let path = evt.composedPath(); let path = evt.composedPath();
if ( if (!path.find(e => {
!path.find((e) => { let s = (e as Element);
let s = e as Element;
return s.id === "ModalContent"; return s.id === "ModalContent";
}) })) {
) { this.props.modal.result(null)
this.props.modal.result(null);
} }
}} }} onKeyDown={evt => {
onKeyDown={(evt) => {
if (evt.keyCode === 27) { if (evt.keyCode === 27) {
this.props.modal.result(null); this.props.modal.result(null)
} }
}} }}>
> <div id="ModalContent" class="modal" >
<div id="ModalContent" class="modal">
<div class="modal-title" style=""> <div class="modal-title" style="">
<h3>{this.props.modal.title}</h3> <h3>{this.props.modal.title}</h3>
{/* <div> */} {/* <div> */}
{!this.props.modal.noClose ? ( {!this.props.modal.noClose ?
<X <img src={CloseIcon} onClick={() => this.props.modal.result(null)} />
onClick={() => this.props.modal.result(null)} // <CloseIcon onClick={() => this.props.modal.result(null)} width={undefined} height={undefined} />
width={undefined} : undefined
height={undefined} }
/>
) : undefined}
{/* </div> */} {/* </div> */}
</div> </div>
{this.props.children} {this.props.children}
</div> </div>
</div> </div>
);
} }
}; }
} }
export class ModalComponent extends Component< export class ModalComponent extends Component<{}, { modal: Modal<any> | undefined, component: JSX.Element | undefined }>{
{},
{ modal: Modal<any> | undefined; component: JSX.Element | undefined }
> {
constructor(props) { constructor(props) {
super(props); super(props);
this.onModal = this.onModal.bind(this); this.onModal = this.onModal.bind(this);
} }
onModal({ modal, close }: { modal: Modal<any>; close: boolean }) { onModal({ modal, close }: { modal: Modal<any>, close: boolean }) {
if (!close && this.state.modal !== modal) { if (!close && this.state.modal !== modal) {
this.setState({ modal: modal, component: modal.getComponent() }); this.setState({ modal: modal, component: modal.getComponent() })
} else { }
if (this.state.modal === modal && close) else {
// Only close if the same if (this.state.modal === modal && close) // Only close if the same
this.setState({ modal: undefined, component: undefined }); this.setState({ modal: undefined, component: undefined })
} }
} }
@ -124,6 +109,8 @@ export class ModalComponent extends Component<
} }
render() { render() {
return <div>{this.state.component}</div>; return <div>
{this.state.component}
</div>
} }
} }

View File

@ -1,66 +0,0 @@
import { h } from "preact";
import { Page } from "../../../page";
import Theme, { ThemeStates } from "../../../theme";
import Navigation from "../../../navigation";
import { ArrowLeft } from "preact-feather";
export default class SettingsPage extends Page<
{ state: any },
{ vault: string }
> {
componentWillMount() {}
render() {
let active = Theme.active();
return (
<div>
<header class="header">
<div class="header-icon-button" onClick={() => history.back()}>
<ArrowLeft height={undefined} width={undefined} />
</div>
<span onClick={() => Navigation.setPage("/")}>Settings</span>
<span></span>
</header>
<div class="container">
<div className="input-group">
<label>Select Theme: </label>
<select
class="inp"
onChange={(ev) =>
Theme.change(
Number((ev.target as HTMLSelectElement).value)
)
}
>
{Object.keys(ThemeStates)
.filter((e) => Number.isNaN(Number(e)))
.map((e) => (
<option
selected={ThemeStates[e] === active}
value={ThemeStates[e]}
>
{e.charAt(0).toUpperCase() +
e.slice(1).toLowerCase()}
</option>
))}
{/* <option value={ThemeStates.AUTO}>Auto</option>
<option value={ThemeStates.LIGHT}>Light</option>
<option value={ThemeStates.DARK}>Dark</option> */}
</select>
</div>
{/* <button class="btn" onClick={() => Theme.toggle()}>Toggle Dark Mode</button> */}
<button
class="btn"
onClick={() =>
window.navigator.serviceWorker.controller.postMessage(
"message"
)
}
>
Clear cache
</button>
</div>
</div>
);
}
}

View File

@ -1,27 +0,0 @@
import { h } from "preact";
import * as EasyMDE from "easymde";
import "easymde/dist/easymde.min.css"
// import "./easymde.scss"
import { useEffect, useRef } from "preact/hooks";
export default function EasyMDEPreact(props: { value: string, onChange: (value: string) => void }) {
const ref = useRef<HTMLTextAreaElement>();
useEffect(() => {
const mde = new EasyMDE({
element: ref.current,
initialValue: props.value
})
mde.codemirror.on("change", () => {
props.onChange(mde.value());
});
return () => {
mde.cleanup();
}
}, [ref])
return <div style="background: white;">
<textarea ref={ref}></textarea>
</div>
}

View File

@ -1,134 +0,0 @@
import { h, Component } from "preact";
import { IVault, ViewNote } from "../../../notes";
import { Trash2 as Trash, X, Save } from "preact-feather";
// import Navigation from "../../../navigation";
import { YesNoModal } from "../../modals/YesNoModal";
import Notifications, { MessageType } from "../../../notifications";
// import CodeMirror from "../../CodeMirror";
import { useEffect, useMemo, useState } from "preact/hooks";
import { usePromise } from "../../../hooks";
import EasyMDEPreact from "./EasyMde";
interface IEntryProps {
vault: IVault;
id?: string;
note?: string;
}
export default function Entry(props: IEntryProps) {
const [changed, setChanged] = useState(false);
const [text, setText] = useState("");
const title = useMemo(() => text?.split("\n", 1)[0], [text]);
const [loading, error, note] = usePromise(async () => {
let note: ViewNote;
if (props.id) {
note = await props.vault.getNote(props.id);
} else {
note = props.vault.newNote();
if (props.note) {
note.__value = props.note;
setChanged(true);
}
}
if (!note) {
Notifications.sendNotification("Note not found!", MessageType.ERROR);
history.back();
} else {
setText(note.__value);
}
return note;
}, [props.vault, props.id]);
if (loading) {
return <div>Loading entry</div>;
} else {
const save = async () => {
try {
if (changed) {
note.__value = text;
await props.vault.saveNote(note);
setChanged(false);
}
} catch (err) {
Notifications.sendError(err);
}
};
const del = async () => {
await props.vault.deleteNote(props.id);
history.back();
};
const close = async () => {
if (changed) {
let modal = new YesNoModal("Really want to quit?");
let res = await modal.getResult();
if (!res) return;
}
history.back();
};
// TODO: Add warning on possibly unwanted exit
useEffect(() => {
const keyevent = (evt: KeyboardEvent) => {
if (evt.key === "s" && evt.ctrlKey) {
evt.preventDefault();
save();
return false;
} else if (evt.key === "Escape") {
evt.preventDefault();
close();
return false;
}
return true;
};
document.addEventListener("keydown", keyevent);
return () => {
document.removeEventListener("keydown", keyevent);
};
});
return (
<div>
<header class="header" style="margin-bottom: 0;">
<div class="header-icon-button" onClick={close}>
<X height={undefined} width={undefined} />
</div>
{changed && (
<div
class="header-icon-button"
style="margin-left: 0.5em;"
onClick={save}
>
<Save height={undefined} width={undefined} />
</div>
)}
<span>{title}</span>
<div class="header-icon-button" onClick={del}>
<Trash height={undefined} width={undefined} />
</div>
</header>
<div class="container" style="padding: 0">
<EasyMDEPreact
value={text}
onChange={(value) => {
setChanged(true);
setText(value);
}}
// onSave={save}
// onClose={close}
/>
</div>
</div>
);
}
}

View File

@ -1,351 +0,0 @@
import { h, Component } from "preact";
import Notes, { IVault, BaseNote } from "../../../notes";
import AddButton from "../../AddButton";
import Navigation from "../../../navigation";
import { ArrowLeft, Search } from "preact-feather";
import ContextMenu from "../../context";
import Notifications from "../../../notifications";
import { Observable, Lock } from "@hibas123/utils";
export default class EntryList extends Component<
{ vault: IVault },
{ notes: BaseNote[]; context: h.JSX.Element | undefined }
> {
rawNotes: BaseNote[];
private searchObservableServer = new Observable<void>(1000);
private searchObservable = this.searchObservableServer.getPublicApi();
constructor(props) {
super(props);
console.log("Creating new Instance of EntryList");
this.state = { notes: [], context: undefined };
this.onDragOver = this.onDragOver.bind(this);
this.onDrop = this.onDrop.bind(this);
this.reloadNotes = this.reloadNotes.bind(this);
this.searchChanged = this.searchChanged.bind(this);
}
vault: IVault;
async reloadNotes(s?: boolean) {
if (s) return;
this.rawNotes = await this.vault.getAllNotes();
await this.applySearch(true);
}
async componentWillMount() {
this.vault = this.props.vault;
this.reloadNotes();
document.body.addEventListener("dragover", this.onDragOver);
document.body.addEventListener("drop", this.onDrop);
Notes.syncObservable.subscribe(this.reloadNotes);
this.searchObservable.subscribeCollect(() => this.applySearch());
}
componentWillUnmount() {
document.body.removeEventListener("dragover", this.onDragOver);
document.body.removeEventListener("drop", this.onDrop);
Notes.syncObservable.unsubscribe(this.reloadNotes);
}
componentDidMount() {
console.log("ON Component Did mount", this.search);
this.searchInput.value = this.search;
}
onDragOver(evt: DragEvent) {
evt.preventDefault();
}
onContext(evt: MouseEvent, note: BaseNote) {
evt.preventDefault();
evt.stopPropagation();
const close = () => {
document.documentElement.removeEventListener("click", close);
this.setState({ context: undefined });
};
document.documentElement.addEventListener("click", close);
const shareNote = async () => {
let nav = window.navigator as any;
if (nav.share !== undefined) {
let vnote = await this.vault.getNote(note._id);
nav.share({
title: vnote.preview.split("\n")[0],
text: vnote.__value,
})
.then(() => console.log("Successful share"))
.catch((error) => {
console.error("Error sharing:", error);
Notifications.sendError(error);
});
} else {
Notifications.sendError("Sharing not possible on this device");
}
};
const deleteNote = async () => {
this.vault
.deleteNote(note._id)
.then(() => {
Notifications.sendSuccess("Deleted");
this.rawNotes = this.rawNotes.filter((e) => e._id !== note._id);
this.setState({
notes: this.state.notes.filter((e) => e._id !== note._id),
});
})
.catch((err) => {
Notifications.sendError(err);
});
};
const copyNote = async () => {
this.vault.getNote(note._id).then((note) => {
const el = document.createElement("textarea");
el.value = note.__value;
document.body.appendChild(el);
el.select();
document.execCommand("copy");
document.body.removeChild(el);
Notifications.sendSuccess("Copied");
});
};
let share;
if ((window.navigator as any).share) {
share = (
<button class="btn" onClick={shareNote}>
share
</button>
);
}
let context = (
<ContextMenu event={evt}>
{share}
<button class="btn" onClick={deleteNote}>
delete
</button>
<button class="btn" onClick={copyNote}>
copy
</button>
</ContextMenu>
);
this.setState({ context });
return false;
}
async onDrop(evt: DragEvent) {
evt.preventDefault();
if (evt.dataTransfer.items) {
for (let i = 0; i < evt.dataTransfer.items.length; i++) {
let item = evt.dataTransfer.items[i];
if (item.kind === "file") {
let file = item.getAsFile();
if (file.type !== "application/json") {
Notifications.sendError("Invalid File Type!!!");
} else {
try {
let data = await new Promise<string>((yes, no) => {
let fr = new FileReader();
fr.onload = (ev) => {
yes((ev.target as any).result);
};
fr.onerror = no;
fr.readAsText(file);
});
let parsed = JSON.parse(data);
let c = new Error("Could not parse!");
let notes: { content: string; time: Date }[] = null;
if (Array.isArray(parsed)) {
// Could be from SecureNotes 1
notes = parsed.map((elm) => {
if (
typeof elm.message !== "string" ||
typeof elm.time !== "string"
) {
throw c;
}
return {
content: elm.message,
time: new Date(elm.time),
};
});
} else if (parsed.version) {
// Could be from SecureNotes 2
if (parsed.version === 1) {
//Could be from SecureNotes 2 version 1
notes = (parsed.notes as any[]).map((elm) => {
if (
typeof elm.content !== "string" ||
typeof elm.time !== "string"
) {
throw c;
}
return {
content: elm.content,
time: new Date(elm.time),
};
});
} else {
throw c;
}
} else throw c;
await Promise.all(
notes.map((n) => {
let note = this.vault.newNote();
note.__value = n.content;
return this.vault.saveNote(note, n.time);
})
);
await this.reloadNotes();
Notifications.sendSuccess(
`Imported ${notes.length} notes!`
);
} catch (err) {
Notifications.sendError("Cannot read File!");
console.error(err);
}
}
}
}
}
}
searchLock = new Lock();
oldSearch = "";
async applySearch(force = false) {
const search = this.search.toLowerCase();
if (!force && search === this.oldSearch) {
return;
}
if (this.searchLock.locked) return;
const lock = await this.searchLock.getLock();
console.time("SearchOP");
let notes: BaseNote[] = [];
if (search === "") {
notes = this.rawNotes;
} else {
const parts = search.split(" ");
const match = (note: BaseNote) => {
return parts.every(function (el) {
return note.preview.toLowerCase().indexOf(el) > -1;
});
};
let elements: BaseNote[];
if (!force && this.oldSearch && search.startsWith(this.oldSearch)) {
elements = [...this.state.notes];
} else {
elements = [...this.rawNotes];
}
await new Promise((yes) => {
const idle = () => {
window.requestIdleCallback(
(deadline) => {
let invTR = deadline.timeRemaining() <= 0;
while (
(deadline.timeRemaining() > 0 || invTR) &&
elements.length > 0
) {
let element = elements.shift();
if (match(element)) {
notes.push(element);
}
}
if (elements.length > 0) idle();
else yes();
},
{ timeout: 100 }
);
};
idle();
});
// notes = elements.filter(note => match(note));
}
await new Promise((yes) => this.setState({ notes }, yes));
this.oldSearch = search;
lock.release();
console.timeEnd("SearchOP");
}
search = "";
searchChanged(evt: Event) {
let input = evt.target as HTMLInputElement;
this.search = input.value;
this.searchObservableServer.send();
}
searchInput: HTMLInputElement;
render() {
const open_entry = (id: string | null) => {
Navigation.setPage(
"/vault",
{ id: this.vault.id },
{ id, entry: "true" }
);
};
return (
<div>
{this.state.context}
<header class="header">
<div class="header-icon-button" onClick={() => history.back()}>
<ArrowLeft height={undefined} width={undefined} />
</div>
<span onClick={() => Navigation.setPage("/")}>
{this.vault ? this.vault.name : ""}
</span>
<span></span>
{/* <a class="button header_icon_button"><MoreVertival height={undefined} width={undefined} /></a> */}
</header>
<AddButton onClick={() => open_entry(null)} />
<div class="container">
<div style="display:flex; margin-top: .5rem;">
<input
class="inp"
type="text"
style="width: 100%; height: 40px;"
onKeyUp={this.searchChanged}
ref={(elm) => (this.searchInput = elm)}
/>
<button
class="btn btn-primary"
style="padding: 5px 10px; margin: 0; height: 40px; width: 40px;"
>
<Search />
</button>
</div>
<div class="vault-list" style="margin-top: 1rem;">
{this.state.notes.map((note) => {
let [first, second] = note.preview.split("\n", 2);
return (
<div
class="card vault-vault"
onContextMenu={(evt) => this.onContext(evt, note)}
onClick={() => {
open_entry(note._id);
}}
>
<div>{first}</div>
<div>{second}</div>
</div>
);
})}
</div>
</div>
</div>
);
}
}

View File

@ -1,55 +0,0 @@
import { h } from "preact";
import { Page } from "../../../page";
import Notes, { IVault, BaseNote } from "../../../notes";
import Navigation from "../../../navigation";
import EntryComponent from "./Entry";
import EntryList from "./EntryList";
import "./vault.scss";
import { useState } from "preact/hooks";
import { usePromise } from "../../../hooks";
export interface VaultProps {
state: { id: string };
hidden: { entry: string; id: string; note: string };
}
export default function VaultPage(props: VaultProps) {
console.log("Vault page");
const [loading, error, vault] = usePromise(
() =>
Notes.getVault(
this.props.state.id,
Notes.getVaultKey(this.props.state.id)
),
[props.state.id]
);
if (vault) {
window.debug.activeVault = vault;
window.debug.createNotes = (cnt = 10) => {
for (let i = 0; i < cnt; i++) {
let nt = vault.newNote();
nt.__value = `Random Note ${i}\ With some Content ${i}`;
vault.saveNote(nt);
}
};
}
if (loading) return <div>Loading Vault</div>;
// Maybe return loading animation or so
else if (error) return <div>{error.message}</div>;
else {
if (props.hidden?.entry) {
return (
<EntryComponent
vault={vault}
id={props.hidden.id}
note={props.hidden.note}
/>
);
} else {
return <EntryList vault={vault} />;
}
}
}

View File

@ -1,294 +0,0 @@
import { h } from "preact";
import { Page } from "../../../page";
import Notes, { VaultList } from "../../../notes";
import "./vaults.scss";
import { Lock, Unlock, Settings } from "preact-feather";
import Navigation from "../../../navigation";
import { InputModal } from "../../modals/InputModal";
import { YesNoModal } from "../../modals/YesNoModal";
import AddButton from "../../AddButton";
import ContextMenu from "../../context";
import Notifications from "../../../notifications";
export interface VaultsProps {
state: any;
selectVault?: boolean;
onSelected?: (vaultid: string) => void;
}
export default class VaultsPage extends Page<
VaultsProps,
{
vaults: VaultList;
modal: h.JSX.Element | undefined;
context: h.JSX.Element | undefined;
}
> {
constructor(props: VaultsProps) {
super(props);
this.state = { vaults: [], modal: undefined, context: undefined };
this.updateVaults = this.updateVaults.bind(this);
}
updateVaults(s?: boolean) {
if (s) return;
return new Promise<void>((yes) => {
Notes.getVaults().then((vaults) => this.setState({ vaults }, yes));
});
}
componentWillMount() {
this.updateVaults();
Notes.syncObservable.subscribe(this.updateVaults);
}
componentWillUnmount() {
Notes.syncObservable.unsubscribe(this.updateVaults);
}
async getKey(vault: { name: string; id: string }, permanent = true) {
let inp_mod = new InputModal(
"Enter password for " + vault.name,
"Password",
"password"
);
let key = undefined;
while (true) {
// inp_mod.show();
let value = await inp_mod.getResult(false);
if (value === null) {
console.log("Value is null");
inp_mod.close();
return false;
} else {
key = Notes.passwordToKey(value);
try {
await Notes.getVault(vault.id, key);
break;
} catch (err) {
Notifications.sendError("Invalid password!");
}
}
}
inp_mod.close();
let perm = false;
if (permanent) {
let save_modal = new YesNoModal("Save permanent?");
let res = await save_modal.getResult();
if (res === undefined) {
res = false;
}
perm = res;
}
Notes.saveVaultKey(vault.id, key, perm);
return true;
}
async openVault(vault: { name: string; encrypted: boolean; id: string }) {
const action = () => {
if (this.props.selectVault) {
this.props.onSelected(vault.id);
} else {
Navigation.setPage("/vault", { id: vault.id });
}
};
if (vault.encrypted) {
let key = Notes.getVaultKey(vault.id);
if (key) action();
else {
if (await this.getKey(vault)) action();
}
} else {
action();
}
}
async addButtonClick() {
let name_modal = new InputModal("Enter new name", "Name", "text");
let name = await name_modal.getResult();
if (name === null) return;
let encrypted_modal = new YesNoModal("Encrypt?");
let encrypted = encrypted_modal.getResult();
if (encrypted === null) return;
let password;
if (encrypted) {
let password_modal = new InputModal(
"Enter new password",
"Password",
"password"
);
password = await password_modal.getResult();
if (password === null) return;
}
let key;
if (password) {
key = Notes.passwordToKey(password);
}
await Notes.createVault(name, key);
this.updateVaults();
}
onContext(
evt: MouseEvent,
vault: { name: string; encrypted: boolean; id: string }
) {
evt.preventDefault();
evt.stopPropagation();
const close = () => {
document.documentElement.removeEventListener("click", close);
this.setState({ context: undefined });
};
document.documentElement.addEventListener("click", close);
let deleteb = (
<button
class="btn"
onClick={async () => {
let delete_modal = new YesNoModal(
"Delete Vault? Cannot be undone!"
);
let result = await delete_modal.getResult();
if (result) {
Notes.deleteVault(vault.id)
.then(() => {
this.updateVaults();
})
.catch((err) => {
Notifications.sendError("Error deleting vault!");
console.error(err);
});
}
}}
>
delete
</button>
);
let delete_key;
if (Notes.getVaultKey(vault.id)) {
delete_key = (
<button
class="btn"
onClick={() => {
Notes.forgetVaultKey(vault.id);
Notifications.sendSuccess("Forgot password!");
}}
>
forget password
</button>
);
}
let exportb = (
<button
class="btn"
onClick={async () => {
let key: Uint8Array;
if (vault.encrypted) {
await this.getKey(vault, false);
key = Notes.getVaultKey(vault.id);
}
let note_vault = await Notes.getVault(vault.id, key);
let base_notes = await note_vault.getAllNotes();
let notes = await Promise.all(
base_notes.map((e) => {
return note_vault.getNote(e._id);
})
);
let result = {
version: 1,
notes: notes.map((e) => {
return {
content: e.__value,
time: e.time,
};
}),
};
var dataStr =
"data:text/json;charset=utf-8," +
encodeURIComponent(JSON.stringify(result, undefined, 3));
var downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute(
"download",
"notes_export_" + vault.name + ".json"
);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}}
>
export
</button>
);
let context = (
<ContextMenu event={evt}>
{deleteb}
{delete_key}
{exportb}
</ContextMenu>
);
this.setState({ context });
return false;
}
render() {
console.log({ vaults: this.state.vaults })
let elms = this.state.vaults.map((vault) => {
return (
<li
class="vaults_vault"
onClick={() => this.openVault(vault)}
onContextMenu={(evt) => this.onContext(evt, vault)}
>
{vault.encrypted ? (
<Lock height={undefined} width={undefined} />
) : (
<Unlock height={undefined} width={undefined} />
)}
<span>{vault.name}</span>
</li>
);
});
return (
<div style={{ marginTop: "-12px", paddingTop: "12px" }}>
{/* {this.state.modal} */}
{this.state.context}
<header class="header">
<span></span>
<span
style="display:inline"
onClick={() => Navigation.setPage("/")}
>
{this.props.selectVault
? "Select Vault for share"
: "Your vaults:"}
</span>
<div
class="header-icon-button"
onClick={() => Navigation.setPage("/settings")}
>
<Settings height={undefined} width={undefined} />
</div>
</header>
<AddButton onClick={() => this.addButtonClick()} />
<div class="container">
<ul class="list list-divider list-clickable">{elms}</ul>
</div>
</div>
);
}
}

View File

@ -5,16 +5,9 @@
* @fileoverview Global |this| required for resolving indexes in node. * @fileoverview Global |this| required for resolving indexes in node.
* @suppress {globalThis} * @suppress {globalThis}
*/ */
(function(global) { (function (global) {
'use strict'; 'use strict';
// If we're in node require encoding-indexes and attach it to the global.
if (typeof module !== "undefined" && module.exports &&
!global["encoding-indexes"]) {
global["encoding-indexes"] =
require("./encoding-indexes.js")["encoding-indexes"];
}
// //
// Utilities // Utilities
// //
@ -202,7 +195,7 @@
/** /**
* @return {boolean} True if end-of-stream has been hit. * @return {boolean} True if end-of-stream has been hit.
*/ */
endOfStream: function() { endOfStream: function () {
return !this.tokens.length; return !this.tokens.length;
}, },
@ -214,7 +207,7 @@
* @return {number} Get the next token from the stream, or * @return {number} Get the next token from the stream, or
* end_of_stream. * end_of_stream.
*/ */
read: function() { read: function () {
if (!this.tokens.length) if (!this.tokens.length)
return end_of_stream; return end_of_stream;
return this.tokens.pop(); return this.tokens.pop();
@ -228,7 +221,7 @@
* @param {(number|!Array.<number>)} token The token(s) to prepend to the * @param {(number|!Array.<number>)} token The token(s) to prepend to the
* stream. * stream.
*/ */
prepend: function(token) { prepend: function (token) {
if (Array.isArray(token)) { if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token); var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length) while (tokens.length)
@ -246,7 +239,7 @@
* @param {(number|!Array.<number>)} token The tokens(s) to push to the * @param {(number|!Array.<number>)} token The tokens(s) to push to the
* stream. * stream.
*/ */
push: function(token) { push: function (token) {
if (Array.isArray(token)) { if (Array.isArray(token)) {
var tokens = /**@type {!Array.<number>}*/(token); var tokens = /**@type {!Array.<number>}*/(token);
while (tokens.length) while (tokens.length)
@ -286,7 +279,7 @@
} }
/** @interface */ /** @interface */
function Decoder() {} function Decoder() { }
Decoder.prototype = { Decoder.prototype = {
/** /**
* @param {Stream} stream The stream of bytes being decoded. * @param {Stream} stream The stream of bytes being decoded.
@ -295,18 +288,18 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point, or |finished|. * stream to decode a complete code point, or |finished|.
*/ */
handler: function(stream, bite) {} handler: function (stream, bite) { }
}; };
/** @interface */ /** @interface */
function Encoder() {} function Encoder() { }
Encoder.prototype = { Encoder.prototype = {
/** /**
* @param {Stream} stream The stream of code points being encoded. * @param {Stream} stream The stream of code points being encoded.
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|. * @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|.
*/ */
handler: function(stream, code_point) {} handler: function (stream, code_point) { }
}; };
// 5.2 Names and labels // 5.2 Names and labels
@ -798,9 +791,9 @@
// Label to encoding registry. // Label to encoding registry.
/** @type {Object.<string,{name:string,labels:Array.<string>}>} */ /** @type {Object.<string,{name:string,labels:Array.<string>}>} */
var label_to_encoding = {}; var label_to_encoding = {};
encodings.forEach(function(category) { encodings.forEach(function (category) {
category.encodings.forEach(function(encoding) { category.encodings.forEach(function (encoding) {
encoding.labels.forEach(function(label) { encoding.labels.forEach(function (label) {
label_to_encoding[label] = encoding; label_to_encoding[label] = encoding;
}); });
}); });
@ -929,7 +922,7 @@
// 1. Let index be index jis0208 excluding all entries whose // 1. Let index be index jis0208 excluding all entries whose
// pointer is in the range 8272 to 8835, inclusive. // pointer is in the range 8272 to 8835, inclusive.
shift_jis_index = shift_jis_index || shift_jis_index = shift_jis_index ||
index('jis0208').map(function(code_point, pointer) { index('jis0208').map(function (code_point, pointer) {
return inRange(pointer, 8272, 8835) ? null : code_point; return inRange(pointer, 8272, 8835) ? null : code_point;
}); });
var index_ = shift_jis_index; var index_ = shift_jis_index;
@ -948,7 +941,7 @@
function indexBig5PointerFor(code_point) { function indexBig5PointerFor(code_point) {
// 1. Let index be index Big5 excluding all entries whose pointer // 1. Let index be index Big5 excluding all entries whose pointer
big5_index_no_hkscs = big5_index_no_hkscs || big5_index_no_hkscs = big5_index_no_hkscs ||
index('big5').map(function(code_point, pointer) { index('big5').map(function (code_point, pointer) {
return (pointer < (0xA1 - 0x81) * 157) ? null : code_point; return (pointer < (0xA1 - 0x81) * 157) ? null : code_point;
}); });
var index_ = big5_index_no_hkscs; var index_ = big5_index_no_hkscs;
@ -1050,21 +1043,21 @@
// The encoding attribute's getter must return encoding's name. // The encoding attribute's getter must return encoding's name.
Object.defineProperty(TextDecoder.prototype, 'encoding', { Object.defineProperty(TextDecoder.prototype, 'encoding', {
/** @this {TextDecoder} */ /** @this {TextDecoder} */
get: function() { return this._encoding.name.toLowerCase(); } get: function () { return this._encoding.name.toLowerCase(); }
}); });
// The fatal attribute's getter must return true if error mode // The fatal attribute's getter must return true if error mode
// is fatal, and false otherwise. // is fatal, and false otherwise.
Object.defineProperty(TextDecoder.prototype, 'fatal', { Object.defineProperty(TextDecoder.prototype, 'fatal', {
/** @this {TextDecoder} */ /** @this {TextDecoder} */
get: function() { return this._error_mode === 'fatal'; } get: function () { return this._error_mode === 'fatal'; }
}); });
// The ignoreBOM attribute's getter must return true if ignore // The ignoreBOM attribute's getter must return true if ignore
// BOM flag is set, and false otherwise. // BOM flag is set, and false otherwise.
Object.defineProperty(TextDecoder.prototype, 'ignoreBOM', { Object.defineProperty(TextDecoder.prototype, 'ignoreBOM', {
/** @this {TextDecoder} */ /** @this {TextDecoder} */
get: function() { return this._ignoreBOM; } get: function () { return this._ignoreBOM; }
}); });
} }
@ -1093,7 +1086,8 @@
// BOM seen flag. // BOM seen flag.
if (!this._do_not_flush) { if (!this._do_not_flush) {
this._decoder = decoders[this._encoding.name]({ this._decoder = decoders[this._encoding.name]({
fatal: this._error_mode === 'fatal'}); fatal: this._error_mode === 'fatal'
});
this._BOMseen = false; this._BOMseen = false;
} }
@ -1259,7 +1253,7 @@
// The encoding attribute's getter must return encoding's name. // The encoding attribute's getter must return encoding's name.
Object.defineProperty(TextEncoder.prototype, 'encoding', { Object.defineProperty(TextEncoder.prototype, 'encoding', {
/** @this {TextEncoder} */ /** @this {TextEncoder} */
get: function() { return this._encoding.name.toLowerCase(); } get: function () { return this._encoding.name.toLowerCase(); }
}); });
} }
@ -1277,7 +1271,8 @@
// the input is a USVString so streaming is not necessary. // the input is a USVString so streaming is not necessary.
if (!this._do_not_flush) if (!this._do_not_flush)
this._encoder = encoders[this._encoding.name]({ this._encoder = encoders[this._encoding.name]({
fatal: this._fatal === 'fatal'}); fatal: this._fatal === 'fatal'
});
this._do_not_flush = Boolean(options['stream']); this._do_not_flush = Boolean(options['stream']);
// 1. Convert input to a stream. // 1. Convert input to a stream.
@ -1356,7 +1351,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and utf-8 bytes needed is not 0, // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
// set utf-8 bytes needed to 0 and return error. // set utf-8 bytes needed to 0 and return error.
if (bite === end_of_stream && utf8_bytes_needed !== 0) { if (bite === end_of_stream && utf8_bytes_needed !== 0) {
@ -1484,7 +1479,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -1538,11 +1533,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['UTF-8'] = function(options) { encoders['UTF-8'] = function (options) {
return new UTF8Encoder(options); return new UTF8Encoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['UTF-8'] = function(options) { decoders['UTF-8'] = function (options) {
return new UTF8Decoder(options); return new UTF8Decoder(options);
}; };
@ -1566,7 +1561,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream, return finished. // 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream) if (bite === end_of_stream)
return finished; return finished;
@ -1603,7 +1598,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -1626,21 +1621,21 @@
}; };
} }
(function() { (function () {
if (!('encoding-indexes' in global)) if (!('encoding-indexes' in global))
return; return;
encodings.forEach(function(category) { encodings.forEach(function (category) {
if (category.heading !== 'Legacy single-byte encodings') if (category.heading !== 'Legacy single-byte encodings')
return; return;
category.encodings.forEach(function(encoding) { category.encodings.forEach(function (encoding) {
var name = encoding.name; var name = encoding.name;
var idx = index(name.toLowerCase()); var idx = index(name.toLowerCase());
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders[name] = function(options) { decoders[name] = function (options) {
return new SingleByteDecoder(idx, options); return new SingleByteDecoder(idx, options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders[name] = function(options) { encoders[name] = function (options) {
return new SingleByteEncoder(idx, options); return new SingleByteEncoder(idx, options);
}; };
}); });
@ -1656,14 +1651,14 @@
// 11.1.1 gbk decoder // 11.1.1 gbk decoder
// gbk's decoder is gb18030's decoder. // gbk's decoder is gb18030's decoder.
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['GBK'] = function(options) { decoders['GBK'] = function (options) {
return new GB18030Decoder(options); return new GB18030Decoder(options);
}; };
// 11.1.2 gbk encoder // 11.1.2 gbk encoder
// gbk's encoder is gb18030's encoder with its gbk flag set. // gbk's encoder is gb18030's encoder with its gbk flag set.
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['GBK'] = function(options) { encoders['GBK'] = function (options) {
return new GB18030Encoder(options, true); return new GB18030Encoder(options, true);
}; };
@ -1689,7 +1684,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and gb18030 first, gb18030 // 1. If byte is end-of-stream and gb18030 first, gb18030
// second, and gb18030 third are 0x00, return finished. // second, and gb18030 third are 0x00, return finished.
if (bite === end_of_stream && gb18030_first === 0x00 && if (bite === end_of_stream && gb18030_first === 0x00 &&
@ -1841,7 +1836,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -1916,11 +1911,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['gb18030'] = function(options) { encoders['gb18030'] = function (options) {
return new GB18030Encoder(options); return new GB18030Encoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['gb18030'] = function(options) { decoders['gb18030'] = function (options) {
return new GB18030Decoder(options); return new GB18030Decoder(options);
}; };
@ -1949,7 +1944,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and Big5 lead is not 0x00, set // 1. If byte is end-of-stream and Big5 lead is not 0x00, set
// Big5 lead to 0x00 and return error. // Big5 lead to 0x00 and return error.
if (bite === end_of_stream && Big5_lead !== 0x00) { if (bite === end_of_stream && Big5_lead !== 0x00) {
@ -2044,7 +2039,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -2081,11 +2076,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['Big5'] = function(options) { encoders['Big5'] = function (options) {
return new Big5Encoder(options); return new Big5Encoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['Big5'] = function(options) { decoders['Big5'] = function (options) {
return new Big5Decoder(options); return new Big5Decoder(options);
}; };
@ -2117,7 +2112,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and euc-jp lead is not 0x00, set // 1. If byte is end-of-stream and euc-jp lead is not 0x00, set
// euc-jp lead to 0x00, and return error. // euc-jp lead to 0x00, and return error.
if (bite === end_of_stream && eucjp_lead !== 0x00) { if (bite === end_of_stream && eucjp_lead !== 0x00) {
@ -2212,7 +2207,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -2260,11 +2255,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['EUC-JP'] = function(options) { encoders['EUC-JP'] = function (options) {
return new EUCJPEncoder(options); return new EUCJPEncoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['EUC-JP'] = function(options) { decoders['EUC-JP'] = function (options) {
return new EUCJPDecoder(options); return new EUCJPDecoder(options);
}; };
@ -2303,7 +2298,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// switching on iso-2022-jp decoder state: // switching on iso-2022-jp decoder state:
switch (iso2022jp_decoder_state) { switch (iso2022jp_decoder_state) {
default: default:
@ -2602,7 +2597,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream and iso-2022-jp encoder // 1. If code point is end-of-stream and iso-2022-jp encoder
// state is not ASCII, prepend code point to stream, set // state is not ASCII, prepend code point to stream, set
// iso-2022-jp encoder state to ASCII, and return three bytes // iso-2022-jp encoder state to ASCII, and return three bytes
@ -2711,11 +2706,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['ISO-2022-JP'] = function(options) { encoders['ISO-2022-JP'] = function (options) {
return new ISO2022JPEncoder(options); return new ISO2022JPEncoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['ISO-2022-JP'] = function(options) { decoders['ISO-2022-JP'] = function (options) {
return new ISO2022JPDecoder(options); return new ISO2022JPDecoder(options);
}; };
@ -2739,7 +2734,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and Shift_JIS lead is not 0x00, // 1. If byte is end-of-stream and Shift_JIS lead is not 0x00,
// set Shift_JIS lead to 0x00 and return error. // set Shift_JIS lead to 0x00 and return error.
if (bite === end_of_stream && Shift_JIS_lead !== 0x00) { if (bite === end_of_stream && Shift_JIS_lead !== 0x00) {
@ -2833,7 +2828,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -2888,11 +2883,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['Shift_JIS'] = function(options) { encoders['Shift_JIS'] = function (options) {
return new ShiftJISEncoder(options); return new ShiftJISEncoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['Shift_JIS'] = function(options) { decoders['Shift_JIS'] = function (options) {
return new ShiftJISDecoder(options); return new ShiftJISDecoder(options);
}; };
@ -2920,7 +2915,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and euc-kr lead is not 0x00, set // 1. If byte is end-of-stream and euc-kr lead is not 0x00, set
// euc-kr lead to 0x00 and return error. // euc-kr lead to 0x00 and return error.
if (bite === end_of_stream && euckr_lead !== 0) { if (bite === end_of_stream && euckr_lead !== 0) {
@ -2994,7 +2989,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -3024,11 +3019,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['EUC-KR'] = function(options) { encoders['EUC-KR'] = function (options) {
return new EUCKREncoder(options); return new EUCKREncoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['EUC-KR'] = function(options) { decoders['EUC-KR'] = function (options) {
return new EUCKRDecoder(options); return new EUCKRDecoder(options);
}; };
@ -3081,7 +3076,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream and either utf-16 lead byte or // 1. If byte is end-of-stream and either utf-16 lead byte or
// utf-16 lead surrogate is not null, set utf-16 lead byte and // utf-16 lead surrogate is not null, set utf-16 lead byte and
// utf-16 lead surrogate to null, and return error. // utf-16 lead surrogate to null, and return error.
@ -3171,7 +3166,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1. If code point is end-of-stream, return finished. // 1. If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -3200,24 +3195,24 @@
// 15.3 utf-16be // 15.3 utf-16be
// 15.3.1 utf-16be decoder // 15.3.1 utf-16be decoder
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['UTF-16BE'] = function(options) { encoders['UTF-16BE'] = function (options) {
return new UTF16Encoder(true, options); return new UTF16Encoder(true, options);
}; };
// 15.3.2 utf-16be encoder // 15.3.2 utf-16be encoder
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['UTF-16BE'] = function(options) { decoders['UTF-16BE'] = function (options) {
return new UTF16Decoder(true, options); return new UTF16Decoder(true, options);
}; };
// 15.4 utf-16le // 15.4 utf-16le
// 15.4.1 utf-16le decoder // 15.4.1 utf-16le decoder
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['UTF-16LE'] = function(options) { encoders['UTF-16LE'] = function (options) {
return new UTF16Encoder(false, options); return new UTF16Encoder(false, options);
}; };
// 15.4.2 utf-16le encoder // 15.4.2 utf-16le encoder
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['UTF-16LE'] = function(options) { decoders['UTF-16LE'] = function (options) {
return new UTF16Decoder(false, options); return new UTF16Decoder(false, options);
}; };
@ -3238,7 +3233,7 @@
* decoded, or null if not enough data exists in the input * decoded, or null if not enough data exists in the input
* stream to decode a complete code point. * stream to decode a complete code point.
*/ */
this.handler = function(stream, bite) { this.handler = function (stream, bite) {
// 1. If byte is end-of-stream, return finished. // 1. If byte is end-of-stream, return finished.
if (bite === end_of_stream) if (bite === end_of_stream)
return finished; return finished;
@ -3266,7 +3261,7 @@
* @param {number} code_point Next code point read from the stream. * @param {number} code_point Next code point read from the stream.
* @return {(number|!Array.<number>)} Byte(s) to emit. * @return {(number|!Array.<number>)} Byte(s) to emit.
*/ */
this.handler = function(stream, code_point) { this.handler = function (stream, code_point) {
// 1.If code point is end-of-stream, return finished. // 1.If code point is end-of-stream, return finished.
if (code_point === end_of_stream) if (code_point === end_of_stream)
return finished; return finished;
@ -3287,11 +3282,11 @@
} }
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
encoders['x-user-defined'] = function(options) { encoders['x-user-defined'] = function (options) {
return new XUserDefinedEncoder(options); return new XUserDefinedEncoder(options);
}; };
/** @param {{fatal: boolean}} options */ /** @param {{fatal: boolean}} options */
decoders['x-user-defined'] = function(options) { decoders['x-user-defined'] = function (options) {
return new XUserDefinedDecoder(options); return new XUserDefinedDecoder(options);
}; };
@ -3308,6 +3303,6 @@
}; };
} }
// For strict environments where `this` inside the global scope // For strict environments where `this` inside the global scope
// is `undefined`, take a pure object instead // is `undefined`, take a pure object instead
}(this || {})); }(this || {}));

View File

@ -1,23 +0,0 @@
import { useEffect, useMemo, useState } from "preact/hooks";
export function usePromise<T>(promiseFnc: () => Promise<T>, params: any[]) {
const promise = useMemo(promiseFnc, params);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(undefined);
const [value, setValue] = useState(undefined);
useEffect(() => {
let canceled = false;
promise
.then((res) => setValue(res))
.catch((err) => setError(err))
.finally(() => setLoading(false));
return () => {
canceled = true;
};
}, [promise]);
return [loading, error, value];
}

View File

@ -4,36 +4,59 @@
<head> <head>
<title>SecureNotes</title> <title>SecureNotes</title>
<meta charset="utf8" /> <meta charset="utf8" />
<meta name="Description" content="Notes app" /> <meta name="Description" content="Notes app">
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="manifest" href="./manifest.webmanifest" /> <link rel="manifest" href="./manifest.json">
<!-- <link rel="shortcut icon" href="/public/icon-72x72.png"> --> <!-- <link rel="shortcut icon" href="/public/icon-72x72.png"> -->
<!-- Add to home screen for Safari on iOS --> <!-- Add to home screen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Secure Notes" /> <meta name="apple-mobile-web-app-title" content="Secure Notes">
<!-- sizes="180x180" -->
<!-- href="/public/apple-touch-icon.png" -->
<link rel="apple-touch-icon" sizes="256x256" href="./public/notepad256.png" /> <!-- <link rel="apple-touch-icon" sizes="180x180" href="../public/apple-touch-icon.png"> -->
<!-- <link <!-- <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#1E88E5"> -->
rel="mask-icon" <script src="./encoding.js"></script>
href="/public/safari-pinned-tab.svg" <meta name="msapplication-TileColor" content="#1E88E5">
color="#1E88E5" <meta name="theme-color" content="#1E88E5">
/> -->
<meta name="msapplication-TileColor" content="#1E88E5" />
<meta name="theme-color" content="#1E88E5" />
</head> </head>
<body> <body>
<noscript> You have to enable JavaScript to use this site! </noscript> <noscript>
You have to enable JavaScript to use this site!
</noscript>
<div id="app"></div> <div id="app"></div>
<script> <script>
window.debug = {} // // Check that service workers are registered
// if ('serviceWorker' in navigator) {
// // Use the window load event to keep the page load performant
// window.addEventListener('load', () => {
// navigator.serviceWorker.register('/public/serviceworker.js');
// });
// }
if (navigator.serviceWorker.controller) {
if (localStorage.getItem("debug")) {
console.warn("Debuggung and service worker found, make shure to clear cache!");
}
console.log('active service worker found, no need to register')
} else {
if (localStorage.getItem("debug")) {
console.warn("Disabling Service Worker in debug mode!")
} else {
// Register the ServiceWorker
navigator.serviceWorker.register('./serviceworker.ts', {
scope: '/'
}).then(function (reg) {
console.log('Service worker has been registered for scope:' + reg.scope);
navigator.serviceWorker.controller.addEventListener("cleared_cache", evt => {
console.log(evt);
})
});
}
}
</script> </script>
<script src="index.tsx" type="module"></script> <script src="./index.tsx"></script>
</body> </body>
</html> </html>

View File

@ -4,14 +4,64 @@ body {
overscroll-behavior-y: contain; overscroll-behavior-y: contain;
} }
// html {
// min-height: 100%;
// display: flex;
// }
$header-margin: .5em;
// $header-icon-size: calc(1.5rem * 1);
// $header-icon-size: 100%;
header { header {
display: flex;
justify-content: space-between; justify-content: space-between;
margin-bottom: $header-margin;
align-content: center;
padding: 0.75em;
border-bottom: solid var(--border-color) 1px;
background-color: var(--primary);
>* {
margin: 0;
color: white;
background: var(--primary);
}
>.header-title {
overflow: hidden;
text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
flex-grow: 1;
margin: 0 1em;
}
.header-icon-button {
display: block;
margin-top: auto;
margin-bottom: auto;
// min-width: $header-icon-size;
// >svg {
// height: $header-icon-size;
// width: $header-icon-size;
// }
}
}
body {
overscroll-behavior-y: contain;
} }
.def-shadow { .def-shadow {
box-shadow: 0px 5px 8px 2px rgba(66, 66, 66, 0.53); box-shadow: 0px 5px 8px 2px rgba(66, 66, 66, 0.53);
} }
.ccontainer { .ccontainer {
margin: 0 1rem; margin: 0 1rem;
max-width: 100%; max-width: 100%;

View File

@ -1,3 +1,36 @@
declare global {
interface Window {
requestIdleCallback: (callback: (deadline: { didTimeout: boolean, timeRemaining: () => number }) => void, options?: { timeout: number }) => number | NodeJS.Timeout;
cancelIdleCallback: (id: number | NodeJS.Timeout) => void;
debug: any;
}
// namespace JSX {
// interface IntrinsicElements {
// "wired-button": HTMLAttributes;
// "wired-card": HTMLAttributes;
// "wired-checkbox": HTMLAttributes;
// "wired-combo": HTMLAttributes;
// "wired-fab": HTMLAttributes;
// "wired-icon-button": HTMLAttributes;
// "wired-input": HTMLAttributes;
// "wired-item": HTMLAttributes;
// "wired-lib": HTMLAttributes;
// "wired-listbox": HTMLAttributes;
// "wired-progress": HTMLAttributes;
// "wired-radio-group": HTMLAttributes;
// "wired-radio": HTMLAttributes;
// "wired-slider": HTMLAttributes;
// "wired-spinner": HTMLAttributes;
// "wired-tabs": HTMLAttributes;
// "wired-textarea": HTMLAttributes;
// "wired-toggle": HTMLAttributes;
// "wired-tooltip": HTMLAttributes;
// }
// }
}
declare const window: Window;
window.requestIdleCallback = window.requestIdleCallback =
window.requestIdleCallback || window.requestIdleCallback ||
@ -9,7 +42,7 @@ window.requestIdleCallback =
didTimeout: false, didTimeout: false,
timeRemaining: function () { timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start)); return Math.max(0, 50 - (Date.now() - start));
}, }
}); });
}, 1); }, 1);
}; };
@ -24,23 +57,34 @@ console.log(window.requestIdleCallback);
window.debug = {}; window.debug = {};
import { h, render } from "preact";
import App from "./components/App";
import "@hibas123/theme/out/base.css";
import "./index.scss";
import Navigation from "./navigation";
import VaultsPage from "./components/routes/vaults/Vaults";
import { Page } from "./page";
import Notes from "./notes";
import DemoPage from "./components/demo";
import VaultPage from "./components/routes/vault/Vault"; import { h, render } from 'preact';
import SharePage from "./components/routes/share/Share"; import App from './components/App';
import Notifications from "./notifications";
import Error404Page from "./components/routes/404";
import SettingsPage from "./components/routes/settings/Settings"; // import "uikit";
// import "uikit/dist/css/uikit.css"
import "@hibas123/theme/out/base.css"
// import "@hibas123/theme/out/light.css"
// import "@hibas123/theme/out/dark.css"
import "./index.scss";
import Navigation from './navigation';
import VaultsPage from './Views/Vaults/Vaults';
import { Page } from './page';
import Notes from "./notes"
import DemoPage from './components/demo';
import VaultPage from './Views/Vault/Vault';
import SharePage from './Views/Share/Share';
import Notifications from './notifications';
import Error404Page from './Views/404';
import SettingsPage from './Views/Settings/Settings';
window.debug.notes = Notes; window.debug.notes = Notes;
import Theme from "./theme"; import Theme from "./theme";
console.log("Dark mode:", Theme.active); console.log("Dark mode:", Theme.active);
@ -48,85 +92,46 @@ console.log("Dark mode:", Theme.active);
(async () => { (async () => {
// Initialize notes provider // Initialize notes provider
if (Notes.loginRequired()) { if (Notes.loginRequired()) {
let url = new URL(location.href); let url = new URL(location.href)
let code = url.searchParams.get("code"); let code = url.searchParams.get("code");
if (code) { if (code) {
let err = await Notes.getToken(code); let err = await Notes.getToken(code)
if (err) { if (err) {
Notifications.sendError("Login failed: " + err); Notifications.sendError("Login failed: " + err)
return Notes.login(); return Notes.login()
} else { } else {
window.history.replaceState( window.history.replaceState(null, document.title, "/" + window.location.hash);
null,
document.title,
"/" + window.location.hash
);
} }
} else { } else {
return Notes.login(); return Notes.login()
} }
} }
await Notes.start(); await Notes.start();
if (window.navigator.storage && navigator.storage.persist) { if (window.navigator.storage && navigator.storage.persist) {
navigator.storage navigator.storage.persisted()
.persisted() .then(has => has ? true : navigator.storage.persist())
.then((has) => (has ? true : navigator.storage.persist())) .then(is => {
.then((is) => {
console.log("Persistant Storage:", is); console.log("Persistant Storage:", is);
}); })
} }
Navigation.default = VaultsPage as typeof Page; Navigation.default = VaultsPage as typeof Page;
Navigation.addPage("/vault", VaultPage as any as typeof Page); Navigation.addPage("/vault", VaultPage as typeof Page)
Navigation.addPage("/demo", DemoPage as typeof Page); Navigation.addPage("/demo", DemoPage as typeof Page)
Navigation.addPage("/share", SharePage as typeof Page); Navigation.addPage("/share", SharePage as typeof Page)
Navigation.addPage("/settings", SettingsPage as typeof Page); Navigation.addPage("/settings", SettingsPage as typeof Page)
Navigation.addPage("/404", Error404Page); Navigation.addPage("/404", Error404Page);
const trad = window.location.pathname; const trad = window.location.pathname;
if (trad && trad !== "/" && trad !== "") { if (trad && trad !== "/" && trad !== "") {
let p: any = {}; let p: any = {};
new URL(window.location.href).searchParams.forEach( new URL(window.location.href).searchParams.forEach((val, key) => p[key] = val);
(val, key) => (p[key] = val)
);
Navigation.setPage(trad, p, undefined, true); Navigation.setPage(trad, p, undefined, true);
// window.location.href = "/#/" + trad; // window.location.href = "/#/" + trad;
} }
Navigation.start(); Navigation.start();
render(<App />, document.body, document.getElementById("app")); render(<App />, document.body, document.getElementById('app'));
})(); })()
if (navigator.serviceWorker.controller) {
if (localStorage.getItem("debug")) {
console.warn(
"Debuggung and service worker found, make shure to clear cache!"
);
}
console.log("active service worker found, no need to register");
} else {
if (localStorage.getItem("debug")) {
console.warn("Disabling Service Worker in debug mode!");
} else {
// Register the ServiceWorker
navigator.serviceWorker
.register(new URL("serviceworker.js", import.meta.url), {
scope: "/",
})
.then(function (reg) {
console.log(
"Service worker has been registered for scope:" +
reg.scope
);
navigator.serviceWorker.controller.addEventListener(
"cleared_cache",
(evt) => {
console.log(evt);
}
);
});
}
}

55
src/manifest.json Executable file
View File

@ -0,0 +1,55 @@
{
"short_name": "Secure Notes",
"name": "Secure Notes",
"decription": "A place to store your notes securly",
"share_target": {
"action": "/share",
"method": "GET",
"enctype": "application/x-www-form-urlencoded",
"params": {
"title": "title",
"text": "text",
"url": "url"
}
},
"icons": [{
"src": "notepad16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "notepad24.png",
"sizes": "24x24",
"type": "image/png"
},
{
"src": "notepad32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "notepad64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "notepad128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "notepad256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "notepad512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#1E88E5",
"background_color": "#ffffff"
}

View File

@ -1,56 +0,0 @@
{
"short_name": "Secure Notes",
"name": "Secure Notes",
"decription": "A place to store your notes securly",
"share_target": {
"action": "/share",
"method": "GET",
"enctype": "application/x-www-form-urlencoded",
"params": {
"title": "title",
"text": "text",
"url": "url"
}
},
"icons": [
{
"src": "public/notepad16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "public/notepad24.png",
"sizes": "24x24",
"type": "image/png"
},
{
"src": "public/notepad32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "public/notepad64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "public/notepad128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "public/notepad256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "public/notepad512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#1E88E5",
"background_color": "#ffffff"
}

View File

@ -1,6 +1,6 @@
import { Observable } from "@hibas123/utils"; import { Observable } from "@hibas123/utils";
import { Page, PageProps } from "./page"; import { Page, PageProps } from "./page";
import { h, VNode } from "preact"; import { h, VNode, JSX } from "preact";
function serializQuery(obj: any) { function serializQuery(obj: any) {
var str = []; var str = [];

View File

@ -3,12 +3,12 @@ import { Lock, Observable } from "@hibas123/utils";
import * as aesjs from "aes-js"; import * as aesjs from "aes-js";
import { IDBPTransaction } from "idb"; import { IDBPTransaction } from "idb";
import { sha256 } from "js-sha256"; import { sha256 } from "js-sha256";
import { v4 as uuidv4 } from "uuid"; import uuidv4 from "uuid/v4";
import * as config from "../config.json"; import * as config from "../config.json";
import * as b64 from "./helper/base64"; import * as b64 from "./helper/base64";
import IDB from "./helper/indexeddb"; import IDB from "./helper/indexeddb";
import Notifications, { MessageType } from "./notifications"; import Notifications, { MessageType } from "./notifications";
import { cloneDeep } from "lodash";
export class HttpError extends Error { export class HttpError extends Error {
constructor(public status: number, public statusText: string) { constructor(public status: number, public statusText: string) {
@ -38,13 +38,16 @@ export interface ViewNote extends BaseNote {
__value: string; __value: string;
} }
import clonedeep = require("lodash.clonedeep");
import uuid = require("uuid");
const Encoder = new TextEncoder(); const Encoder = new TextEncoder();
const Decoder = new TextDecoder(); const Decoder = new TextDecoder();
enum OpLogType { enum OpLogType {
CREATE, CREATE,
CHANGE, CHANGE,
DELETE, DELETE
} }
interface OpLog { interface OpLog {
@ -57,8 +60,8 @@ interface OpLog {
* The value * The value
*/ */
values: { values: {
value: Uint8Array; value: Uint8Array,
preview: Uint8Array; preview: Uint8Array
}; };
/** /**
@ -67,43 +70,42 @@ interface OpLog {
date: Date; date: Date;
} }
export type VaultList = { name: string; encrypted: boolean; id: string }[]; export type VaultList = { name: string, encrypted: boolean, id: string }[];
export interface IVault { export interface IVault {
name: string; name: string;
id: string; id: string;
encrypted: boolean; encrypted: boolean;
getAllNotes(): Promise<BaseNote[]>; getAllNotes(): Promise<BaseNote[]>;
searchNote(term: string): Promise<BaseNote[]>; searchNote(term: string): Promise<BaseNote[]>
newNote(): ViewNote; newNote(): ViewNote;
saveNote(note: ViewNote, date?: Date): Promise<void>; saveNote(note: ViewNote, date?: Date): Promise<void>;
getNote(id: string): Promise<ViewNote>; getNote(id: string): Promise<ViewNote>;
deleteNote(id: string): Promise<void>; deleteNote(id: string): Promise<void>;
// type: string; //Defines type of plugin, that is required to handle this vault
} }
const awaitTimeout = (ms: number) => const awaitTimeout = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
new Promise<void>((resolve) => setTimeout(resolve, ms));
class NotesProvider { class NotesProvider {
private notesObservableServer = new Observable<Note>(); private notesObservableServer = new Observable<Note>()
public notesObservable = this.notesObservableServer.getPublicApi(); public notesObservable = this.notesObservableServer.getPublicApi()
private syncObservableServer = new Observable<boolean>(); private syncObservableServer = new Observable<boolean>()
/** /**
* Will send false once finished and true on start * Will send false once finished and true on start
*/ */
public syncObservable = this.syncObservableServer.getPublicApi(); public syncObservable = this.syncObservableServer.getPublicApi()
private database = new IDB("notes", ["notes", "oplog"]); private database = new IDB("notes", ["notes", "oplog"]);
private noteDB = this.database.getStore<DBNote>("notes"); private noteDB = this.database.getStore<DBNote>("notes");
private oplogDB = this.database.getStore<{ id: string; logs: OpLog[] }>( private oplogDB = this.database.getStore<{ id: string, logs: OpLog[] }>("oplog");
"oplog"
);
private vaultKeys = new Map<string, Uint8Array>(); private vaultKeys = new Map<string, Uint8Array>();
public apiLock = new Lock(); public apiLock = new Lock();
public apiLockRls = this.apiLock.getLock(); public apiLockRls = this.apiLock.getLock()
private syncLock = new Lock(); private syncLock = new Lock();
@ -115,7 +117,7 @@ class NotesProvider {
public syncedObservable = this.syncedObservableServer.getPublicApi(); public syncedObservable = this.syncedObservableServer.getPublicApi();
public async isSynced() { public async isSynced() {
return (await this.oplogDB.getAll()).length <= 0; return (await this.oplogDB.getAll()).length <= 0
} }
private _name; private _name;
@ -128,16 +130,11 @@ class NotesProvider {
} }
login() { login() {
window.location.href = `${config.auth_server}/auth?client_id=${config.client_id window.location.href = `${config.auth_server}/auth?client_id=${config.client_id}&scope=${config.permission}&redirect_uri=${encodeURIComponent(config.callback_url)}&response_type=code`
}&scope=${config.permission}&redirect_uri=${encodeURIComponent(
config.callback_url
)}&response_type=code`;
} }
async getToken(code: string) { async getToken(code: string) {
let req = await fetch( let req = await fetch(`${config.auth_server}/api/oauth/refresh?grant_type=authorization_code&client_id=${config.client_id}&code=${code}`);
`${config.auth_server}/api/oauth/refresh?grant_type=authorization_code&client_id=${config.client_id}&code=${code}`
);
let res = await req.json(); let res = await req.json();
if (!res.error) { if (!res.error) {
localStorage.setItem("refreshtoken", res.token); localStorage.setItem("refreshtoken", res.token);
@ -145,9 +142,9 @@ class NotesProvider {
this._name = res.profile.name; this._name = res.profile.name;
let kb = this.passwordToKey(res.profile.enc_key); let kb = this.passwordToKey(res.profile.enc_key);
localStorage.setItem("enc_key", b64.encode(kb)); localStorage.setItem("enc_key", b64.encode(kb));
this.generalEncryption = kb; this.generalEncryption = kb
} else { } else {
return "Invalid Code"; return "Invalid Code"
} }
} }
@ -160,11 +157,11 @@ class NotesProvider {
} catch (err) { } catch (err) {
callback(err, null); callback(err, null);
} }
}); })
let key = localStorage.getItem("enc_key"); let key = localStorage.getItem("enc_key");
if (key) { if (key) {
this.generalEncryption = b64.decode(key); this.generalEncryption = b64.decode(key)
} }
this._name = localStorage.getItem("name"); this._name = localStorage.getItem("name");
} }
@ -173,42 +170,34 @@ class NotesProvider {
const next = () => { const next = () => {
setTimeout(() => { setTimeout(() => {
this.sync().then(next); this.sync().then(next);
}, 30000); }, 30000)
}; }
this.syncedObservableServer.send( this.syncedObservableServer.send((await this.oplogDB.getAll()).length <= 0);
(await this.oplogDB.getAll()).length <= 0 let prs = this.apiLockRls.then(lock => lock.release());
); prs.then(() => awaitTimeout(2000)).then(() => this.sync()).then(() => next());
let prs = this.apiLockRls.then((lock) => lock.release());
prs.then(() => awaitTimeout(2000))
.then(() => this.sync())
.then(() => next());
return prs; return prs;
} }
private async getJWT() { private async getJWT() {
let lock = await this.apiLock.getLock(); let lock = await this.apiLock.getLock()
try { try {
console.log("Getting JWT"); console.log("Getting JWT");
let req = await fetch( let req = await fetch(config.auth_server + "/api/oauth/jwt?refreshtoken=" + localStorage.getItem("refreshtoken"));
config.auth_server +
"/api/oauth/jwt?refreshtoken=" +
localStorage.getItem("refreshtoken")
);
if (req.status !== 200) { if (req.status !== 200) {
Notifications.sendNotification("offline", MessageType.INFO); Notifications.sendNotification("offline", MessageType.INFO);
throw new Error("Offline"); throw new Error("Offline")
} }
let res = await req.json(); let res = await req.json();
if (res.error) { if (res.error) {
console.log("Refresh token invalid, forward to login"); console.log("Refresh token invalid, forward to login")
localStorage.removeItem("refreshtoken"); localStorage.removeItem("refreshtoken");
this.login(); this.login()
throw new Error("Need login!"); throw new Error("Need login!")
} else { } else {
return res.token; return res.token
} }
} finally { } finally {
lock.release(); lock.release()
} }
} }
@ -218,38 +207,29 @@ class NotesProvider {
} }
async sync() { async sync() {
const lock = await this.syncLock.getLock(); const lock = await this.syncLock.getLock()
const log = (...message: any[]) => { const log = (...message: any[]) => {
console.log("[SYNC]: ", ...message); console.log("[SYNC]: ", ...message)
}; }
this.syncObservableServer.send(true); this.syncObservableServer.send(true);
log("Start"); log("Start")
try { try {
log("Fetching"); log("Fetching");
let [remotes, locals, oplogs] = await Promise.all([ let [remotes, locals, oplogs] = await Promise.all([this._secureFile.list(), this.noteDB.getAll(), this.oplogDB.getAll()]);
this._secureFile.list(),
this.noteDB.getAll(),
this.oplogDB.getAll(),
]);
log("Fetched"); log("Fetched");
// Create sync pairs (remote & local) // Create sync pairs (remote & local)
log("Building pairs"); log("Building pairs");
let pairs: { let pairs: { local: DBNote, remote: IFile, id: string, oplog: OpLog[] }[] = [];
local: DBNote; remotes.map(r => {
remote: IFile; let lIdx = locals.findIndex(e => e._id === r._id);
id: string;
oplog: OpLog[];
}[] = [];
remotes.map((r) => {
let lIdx = locals.findIndex((e) => e._id === r._id);
let l: DBNote = undefined; let l: DBNote = undefined;
if (lIdx >= 0) { if (lIdx >= 0) {
l = locals[lIdx]; l = locals[lIdx];
locals.splice(lIdx, 1); locals.splice(lIdx, 1);
} }
let oIdx = oplogs.findIndex((e) => e.id === r._id); let oIdx = oplogs.findIndex(e => e.id === r._id);
let oplog: OpLog[]; let oplog: OpLog[];
if (oIdx >= 0) { if (oIdx >= 0) {
oplog = oplogs[oIdx].logs; oplog = oplogs[oIdx].logs;
@ -260,12 +240,12 @@ class NotesProvider {
remote: r, remote: r,
local: l, local: l,
oplog, oplog,
id: r._id, id: r._id
}); })
}); })
locals.forEach((l) => { locals.forEach(l => {
let oIdx = oplogs.findIndex((e) => e.id === l._id); let oIdx = oplogs.findIndex(e => e.id === l._id);
let oplog: OpLog[] = undefined; let oplog: OpLog[] = undefined;
if (oIdx >= 0) { if (oIdx >= 0) {
oplog = oplogs[oIdx].logs; oplog = oplogs[oIdx].logs;
@ -277,20 +257,20 @@ class NotesProvider {
remote: undefined, remote: undefined,
local: l, local: l,
oplog, oplog,
id: l._id, id: l._id
}); })
}); })
oplogs.forEach((oplog) => { oplogs.forEach(oplog => {
if (!oplog) return; if (!oplog) return;
if (oplog.logs.length > 0) if (oplog.logs.length > 0)
pairs.push({ pairs.push({
remote: undefined, remote: undefined,
local: undefined, local: undefined,
oplog: oplog.logs, oplog: oplog.logs,
id: oplog.id, id: oplog.id
}); })
}); })
log("Pairs builded"); log("Pairs builded");
@ -301,8 +281,8 @@ class NotesProvider {
local_change: 0, local_change: 0,
local_delete: 0, local_delete: 0,
do_nothing: 0, do_nothing: 0,
error: 0, error: 0
}; }
log("Start inspection"); log("Start inspection");
for (let { local, remote, oplog, id } of pairs) { for (let { local, remote, oplog, id } of pairs) {
@ -313,19 +293,13 @@ class NotesProvider {
case OpLogType.CHANGE: case OpLogType.CHANGE:
log(id, "REMOTE CHANGE"); log(id, "REMOTE CHANGE");
stats.remote_change++; stats.remote_change++;
await this._secureFile.update( await this._secureFile.update(id, op.values.value, b64.encode(op.values.preview), op.date, old);
id,
op.values.value,
b64.encode(op.values.preview),
op.date,
old
);
break; break;
case OpLogType.DELETE: case OpLogType.DELETE:
log(id, "REMOTE DELETE"); log(id, "REMOTE DELETE");
stats.remote_delete++; stats.remote_delete++;
if (old) break; // if the deletion is old, just ignore if (old) break; // if the deletion is old, just ignore
await this._secureFile.delete(id); await this._secureFile.delete(id)
break; break;
case OpLogType.CREATE: case OpLogType.CREATE:
log(id, "REMOTE CREATE"); log(id, "REMOTE CREATE");
@ -342,11 +316,11 @@ class NotesProvider {
break; break;
} }
} }
}; }
const localChange = (id: string) => { const localChange = (id: string) => {
//TODO implement //TODO implement
}; }
const create = async () => { const create = async () => {
log(id, "LOCAL CREATAE/UPDATE"); log(id, "LOCAL CREATAE/UPDATE");
@ -354,64 +328,59 @@ class NotesProvider {
let value = await this._secureFile.get(id); let value = await this._secureFile.get(id);
let note: DBNote = { let note: DBNote = {
_id: remote._id, _id: remote._id,
folder: remote.active.folder, folder: remote.folder,
preview: b64.decode(remote.active.preview || ""), preview: b64.decode(remote.active.preview),
time: remote.active.time, time: remote.active.time,
__value: new Uint8Array(value), __value: new Uint8Array(value)
}; }
await this.noteDB.set(id, note); await this.noteDB.set(id, note);
localChange(id); localChange(id);
}; }
try { try {
// log(id, "LRO: ", !!local, !!remote, !!oplog)
if (remote && !oplog) { if (remote && !oplog) {
if (local) { if (local) {
let old = let old = remote.active.time.valueOf() > local.time.valueOf();
remote.active.time.valueOf() > local.time.valueOf(); if (old)
if (old) await create(); await create()
else { else {
stats.do_nothing++; stats.do_nothing++;
log(id, "DO NOTHING"); log(id, "DO NOTHING");
} }
} else { } else {
await create(); await create()
} }
} else if (!remote && local && !oplog) { } else if (!remote && local && !oplog) { // No local changes, but remote deleted
// No local changes, but remote deleted
log("LOCAL DELETE"); log("LOCAL DELETE");
stats.local_delete++; stats.local_delete++;
await this.noteDB.delete(id); await this.noteDB.delete(id);
localChange(id); localChange(id);
} else if (!remote && oplog) { } else if (!remote && oplog) { // Remote does not exist, but oplog, just apply all changes including possible delete
// Remote does not exist, but oplog, just apply all changes including possible delete await apply()
await apply();
} else if (remote && oplog) { } else if (remote && oplog) {
let last = oplog[oplog.length - 1]; let last = oplog[oplog.length - 1]
let old = remote.active.time.valueOf() > last.date.valueOf(); let old = remote.active.time.valueOf() > last.date.valueOf();
if (old) await create(); // Will recreate local entry if (old)
await apply(old); // Will apply changes to remote await create() // Will recreate local entry
await apply(old) // Will apply changes to remote
} else { } else {
log(id, "DO NOTHING"); log(id, "DO NOTHING");
stats.do_nothing++; stats.do_nothing++;
} }
await this.oplogDB.delete(id);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
stats.error++; stats.error++;
Notifications.sendNotification( Notifications.sendNotification("Error syncing: " + id, MessageType.ERROR);
"Error syncing: " + id,
MessageType.ERROR
);
} }
await this.oplogDB.delete(id);
} }
log("Stats", stats); log("Stats", stats);
this.syncedObservableServer.send( this.syncedObservableServer.send((await this.oplogDB.getAll()).length <= 0)
(await this.oplogDB.getAll()).length <= 0
);
} finally { } finally {
log("Finished"); log("Finished")
lock.release(); lock.release()
this.syncObservableServer.send(false); this.syncObservableServer.send(false);
} }
} }
@ -441,62 +410,53 @@ class NotesProvider {
} }
public getVaults(): Promise<VaultList> { public getVaults(): Promise<VaultList> {
return this.noteDB.getAll().then((notes) => return this.noteDB.getAll()
notes .then(notes => notes
.filter((e) => Decoder.decode(e.preview) === "__VAULT__") .filter(e => Decoder.decode(e.preview) === "__VAULT__")
.map((e) => { .map(e => {
let value = e.__value; let value = e.__value;
let encrypted = false; let encrypted = false;
if (this.decrypt(value) !== "__BASELINE__") encrypted = true; if (this.decrypt(value) !== "__BASELINE__") encrypted = true;
return { name: e.folder, encrypted, id: e._id }; return { name: e.folder, encrypted, id: e._id }
}) }));
);
} }
public async createVault(name: string, key?: Uint8Array) { public async createVault(name: string, key?: Uint8Array) {
// console.log(uuidv4, uuid);
let vault: DBNote = { let vault: DBNote = {
__value: this.encrypt("__BASELINE__", key), __value: this.encrypt("__BASELINE__", key),
_id: uuidv4(), _id: uuidv4(),
folder: name, folder: name,
preview: Encoder.encode("__VAULT__"), preview: Encoder.encode("__VAULT__"),
time: new Date(), time: new Date()
}; }
let tx = this.database.transaction(); let tx = this.database.transaction();
await Promise.all([ await Promise.all([
this.addop( this.addop(vault._id, OpLogType.CREATE, {
vault._id,
OpLogType.CREATE,
{
value: vault.__value, value: vault.__value,
preview: vault.preview, preview: vault.preview
}, }, vault.time, tx),
vault.time, this.noteDB.set(vault._id, vault)
tx
),
this.noteDB.set(vault._id, vault),
]); ]);
} }
public async getVault(vault_id: string, key?: Uint8Array): Promise<IVault> { public async getVault(vault_id: string, key?: Uint8Array): Promise<IVault> {
let vault = await this.noteDB.get(vault_id); let vault = await this.noteDB.get(vault_id);
if (!vault) throw new Error("Vault not found!"); if (!vault) throw new Error("Vault not found!");
if (this.decrypt(vault.__value, key) !== "__BASELINE__") if (this.decrypt(vault.__value, key) !== "__BASELINE__") throw new Error("Invalid password!");
throw new Error("Invalid password!"); return new NotesProvider.Vault(vault, key)
return new NotesProvider.Vault(vault, key);
} }
public async deleteVault(vault_id: string) { public async deleteVault(vault_id: string) {
let vault = await this.noteDB.get(vault_id); let vault = await this.noteDB.get(vault_id);
if (!vault) throw new Error("Vault not found!"); if (!vault) throw new Error("Vault not found!");
let v = new NotesProvider.Vault(vault); let v = new NotesProvider.Vault(vault);
await Promise.all( await Promise.all((await v.getAllNotes()).map(note => this.delete(note._id)));
(await v.getAllNotes()).map((note) => this.delete(note._id))
);
await this.delete(v.id); // This can also delete a vault await this.delete(v.id); // This can also delete a vault
} }
public passwordToKey(password: string) { public passwordToKey(password: string) {
return new Uint8Array(sha256.arrayBuffer(password + config.client_id)); return new Uint8Array(sha256.arrayBuffer(password + config.client_id))
} }
private _encrypt(value: Uint8Array, key?: Uint8Array): Uint8Array { private _encrypt(value: Uint8Array, key?: Uint8Array): Uint8Array {
@ -507,48 +467,42 @@ class NotesProvider {
} }
private encrypt(value: string, key?: Uint8Array): Uint8Array { private encrypt(value: string, key?: Uint8Array): Uint8Array {
let msg = this._encrypt(Encoder.encode(value), key); let msg = this._encrypt(Encoder.encode(value), key)
return new Uint8Array(this._encrypt(msg, this.generalEncryption)); return new Uint8Array(this._encrypt(msg, this.generalEncryption))
} }
private _decrypt(value: ArrayBuffer, key?: Uint8Array): Uint8Array { private _decrypt(value: ArrayBuffer, key?: Uint8Array): Uint8Array {
if (!key) return new Uint8Array(value); if (!key) return new Uint8Array(value);
var aesCtr = new aesjs.ModeOfOperation.ctr(key); var aesCtr = new aesjs.ModeOfOperation.ctr(key);
var decryptedBytes = aesCtr.decrypt(value); var decryptedBytes = aesCtr.decrypt(value);
return new Uint8Array(decryptedBytes); return new Uint8Array(decryptedBytes)
} }
private decrypt(value: ArrayBuffer, key?: Uint8Array): string { private decrypt(value: ArrayBuffer, key?: Uint8Array): string {
let msg = this._decrypt(value, key); let msg = this._decrypt(value, key)
return Decoder.decode(this._decrypt(msg, this.generalEncryption)); return Decoder.decode(this._decrypt(msg, this.generalEncryption))
} }
async addop( async addop(note_id: string, type: OpLogType, values: { value: Uint8Array, preview: Uint8Array }, date: Date, transaction?: IDBPTransaction<unknown, string[]>) {
note_id: string,
type: OpLogType,
values: { value: Uint8Array; preview: Uint8Array },
date: Date,
transaction?: IDBPTransaction<unknown, string[]>
) {
let tx = transaction || this.oplogDB.transaction(); let tx = transaction || this.oplogDB.transaction();
let oplog = await this.oplogDB.get(note_id, tx); let oplog = await this.oplogDB.get(note_id, tx);
if (!oplog) oplog = { logs: [], id: note_id }; if (!oplog) oplog = { logs: [], id: note_id };
oplog.logs.push({ oplog.logs.push({
date: date, date: date,
type, type,
values, values
}); })
this.syncedObservableServer.send(false); this.syncedObservableServer.send(false);
await this.oplogDB.set(note_id, oplog, tx); await this.oplogDB.set(note_id, oplog, tx);
} }
async delete(id: string) { async delete(id: string) {
let lock = await this.syncLock.getLock(); let lock = await this.syncLock.getLock();
let tx = this.database.transaction(this.oplogDB, this.noteDB); let tx = this.database.transaction(this.oplogDB, this.noteDB)
await Promise.all([ await Promise.all([
this.addop(id, OpLogType.DELETE, null, new Date(), tx), this.addop(id, OpLogType.DELETE, null, new Date(), tx),
this.noteDB.delete(id, tx), this.noteDB.delete(id, tx)
]); ])
lock.release(); lock.release();
} }
@ -571,17 +525,15 @@ class NotesProvider {
} }
async getAllNotes() { async getAllNotes() {
return Notes.noteDB.getAll().then((all) => return Notes.noteDB.getAll()
all .then(all => all.filter(e => e.folder === this.vault._id)
.filter((e) => e.folder === this.vault._id)
.sort(this.sort) .sort(this.sort)
.map<BaseNote>((e) => { .map<BaseNote>(e => {
let new_note = cloneDeep(<Note>e) as BaseNote; let new_note = clonedeep(<Note>e) as BaseNote
delete (<any>new_note).__value; delete (<any>new_note).__value
new_note.preview = this.decrypt(e.preview); new_note.preview = this.decrypt(e.preview)
return new_note; return new_note;
}) }));
);
} }
private sort(a: DBNote, b: DBNote) { private sort(a: DBNote, b: DBNote) {
@ -590,7 +542,7 @@ class NotesProvider {
async searchNote(term: string) { async searchNote(term: string) {
let all = await this.getAllNotes(); let all = await this.getAllNotes();
return all.filter((e) => e.preview.indexOf(term) >= 0); return all.filter(e => e.preview.indexOf(term) >= 0)
} }
newNote(): ViewNote { newNote(): ViewNote {
@ -599,8 +551,8 @@ class NotesProvider {
folder: this.vault._id, folder: this.vault._id,
time: new Date(), time: new Date(),
__value: "", __value: "",
preview: "", preview: ""
}; }
} }
async saveNote(note: ViewNote, date = new Date()) { async saveNote(note: ViewNote, date = new Date()) {
@ -608,34 +560,28 @@ class NotesProvider {
const tx = Notes.database.transaction(Notes.noteDB, Notes.oplogDB); const tx = Notes.database.transaction(Notes.noteDB, Notes.oplogDB);
let old_note = await Notes.noteDB.get(note._id, tx); let old_note = await Notes.noteDB.get(note._id, tx);
let new_note = cloneDeep(<Note>note) as DBNote; let new_note = clonedeep(<Note>note) as DBNote;
new_note.__value = this.encrypt(note.__value); new_note.__value = this.encrypt(note.__value)
let [title, preview] = note.__value.split("\n"); let [title, preview] = note.__value.split("\n");
if (preview) preview = "\n" + preview; if (preview) preview = "\n" + preview;
else preview = ""; else preview = ""
new_note.preview = this.encrypt((title + preview).substr(0, 128)); new_note.preview = this.encrypt((title + preview).substr(0, 128))
new_note.time = date; new_note.time = date;
await Promise.all([ await Promise.all([
Notes.addop( Notes.addop(note._id, !old_note ? OpLogType.CREATE : OpLogType.CHANGE, {
note._id,
!old_note ? OpLogType.CREATE : OpLogType.CHANGE,
{
value: new_note.__value, value: new_note.__value,
preview: new_note.preview, preview: new_note.preview
}, }, date, tx),
date, Notes.noteDB.set(note._id, new_note, tx)
tx ])
),
Notes.noteDB.set(note._id, new_note, tx),
]);
lock.release(); lock.release();
} }
async getNote(id: string): Promise<ViewNote> { async getNote(id: string): Promise<ViewNote> {
let note = await Notes.noteDB.get(id); let note = await Notes.noteDB.get(id);
if (!note) return undefined; if (!note) return undefined;
let new_note = cloneDeep(<Note>note) as ViewNote; let new_note = clonedeep(<Note>note) as ViewNote;
new_note.__value = this.decrypt(note.__value); new_note.__value = this.decrypt(note.__value);
return new_note; return new_note;
} }
@ -643,10 +589,10 @@ class NotesProvider {
deleteNote(id: string) { deleteNote(id: string) {
return Notes.delete(id); return Notes.delete(id);
} }
}; }
} }
const Notes = new NotesProvider(); const Notes = new NotesProvider()
export default Notes; export default Notes;
(<any>window).api = Notes; (<any>window).api = Notes

View File

@ -1,130 +0,0 @@
function log(...params) {
console.log.apply(this, [
...["%c[SW]: %c", "color: #f4b942;", "color:unset;"],
...params,
]);
}
const CACHE = "offline";
let precacheFiles = ["/", "/index.html"];
//Install stage sets up the cache-array to configure pre-cache content
self.addEventListener("install", (evt) => {
log("The service worker is being installed.");
evt.waitUntil(
precache()
.then(() => {
log("Skip waiting on install");
})
.catch(log)
.then(() => self.skipWaiting())
);
});
//allow sw to control of current page
self.addEventListener("activate", (event) => {
log("Claiming clients for current page");
return self.clients.claim();
});
self.addEventListener("message", (event) => {
log("Clearing cache");
caches.delete(CACHE);
event.waitUntil(precache());
});
var Types;
(function (Types) {
Types[(Types["CACHE"] = 0)] = "CACHE";
Types[(Types["NOCACHE"] = 1)] = "NOCACHE";
Types[(Types["REFRESH"] = 2)] = "REFRESH";
Types[(Types["INDEX"] = 3)] = "INDEX";
})(Types || (Types = {}));
let rules = [
{
match: (url) => {
return url.indexOf("/api/") >= 0;
},
type: Types.NOCACHE,
},
{
match: (url) => {
return url.indexOf("/share") >= 0;
},
type: Types.INDEX,
},
{
match: () => {
return true;
},
type: Types.REFRESH,
},
];
self.addEventListener("fetch", (evt) => {
if (evt.request.method != "GET") return; // Dont care about POST requests
let rule = rules.find((rule) => rule.match(evt.request.url));
evt.respondWith(
(async () => {
log("Cache:", Types[rule.type]);
switch (rule.type) {
case Types.CACHE:
return fromCache(evt.request);
case Types.REFRESH:
return refresh(evt.request).then((r) => {
evt.waitUntil(r.refresh.catch((_) => {}));
return r.result;
});
case Types.NOCACHE:
return fetch(evt.request);
case Types.INDEX:
return refresh(new Request("/")).then((r) => {
evt.waitUntil(r.refresh.catch((_) => {}));
return r.result;
});
}
})()
);
});
async function fromCache(request) {
let cache = await caches.open(CACHE);
let matching = await cache.match(request);
if (matching) return matching;
let res = await fetch(request.clone());
await cache.put(
request,
{
match: (url) => {
return url.indexOf("/version_hash") >= 0;
},
type: Types.NOCACHE,
},
res
);
return await cache.match(request);
}
async function refresh(request) {
let cache = await caches.open(CACHE);
let web = fetch(request.clone()).then((res) => {
return cache.put(request, res).then(() => {
return cache.match(request);
});
});
let matching = await cache.match(request);
return {
result: matching ? matching : web,
refresh: web,
};
}
function precache() {
return caches.open(CACHE).then(function (cache) {
return cache.addAll(precacheFiles);
});
}

121
src/serviceworker.ts Normal file
View File

@ -0,0 +1,121 @@
function log(...params) {
console.log.apply(this, [...["%c[SW]: %c", "color: #f4b942;", "color:unset;"], ...params])
}
const CACHE = "offline";
let precacheFiles = [
"/",
"/index.html",
"/main.js",
"/main.css",
"/serviceworker.js"
]
//Install stage sets up the cache-array to configure pre-cache content
self.addEventListener('install', (evt) => {
log('The service worker is being installed.');
evt.waitUntil(precache().then(() => {
log('Skip waiting on install');
}).catch(log).then(() => self.skipWaiting()));
});
//allow sw to control of current page
self.addEventListener('activate', (event) => {
log('Claiming clients for current page');
return self.clients.claim();
});
self.addEventListener('message', (event) => {
log("Clearing cache");
caches.delete(CACHE);
event.waitUntil(precache());
});
var Types;
(function (Types) {
Types[Types["CACHE"] = 0] = "CACHE";
Types[Types["NOCACHE"] = 1] = "NOCACHE";
Types[Types["REFRESH"] = 2] = "REFRESH";
Types[Types["INDEX"] = 3] = "INDEX";
})(Types || (Types = {}));
let rules = [{
match: (url) => {
return url.indexOf("/api/") >= 0;
},
type: Types.NOCACHE
}, {
match: (url) => {
return url.indexOf("/share") >= 0;
},
type: Types.INDEX
},
{
match: () => {
return true;
},
type: Types.REFRESH
}
]
self.addEventListener('fetch', (evt) => {
if (evt.request.method != 'GET') return; // Dont care about POST requests
let rule = rules.find(rule => rule.match(evt.request.url));
evt.respondWith((async () => {
log("Cache:", Types[rule.type]);
switch (rule.type) {
case Types.CACHE:
return fromCache(evt.request);
case Types.REFRESH:
return refresh(evt.request).then(r => {
evt.waitUntil(r.refresh.catch(_ => {}));
return r.result;
});
case Types.NOCACHE:
return fetch(evt.request);
case Types.INDEX:
return refresh(new Request("/")).then(r => {
evt.waitUntil(r.refresh.catch(_ => {}));
return r.result;
})
}
})());
});
async function fromCache(request) {
let cache = await caches.open(CACHE);
let matching = await cache.match(request);
if (matching)
return matching
let res = await fetch(request.clone());
await cache.put(request, {
match: (url) => {
return url.indexOf("/version_hash") >= 0;
},
type: Types.NOCACHE
}, res);
return await cache.match(request);
}
async function refresh(request) {
let cache = await caches.open(CACHE);
let web = fetch(request.clone()).then(res => {
return cache.put(request, res).then(() => {
return cache.match(request);
})
})
let matching = await cache.match(request);
return {
result: matching ? matching : web,
refresh: web
}
}
function precache() {
return caches.open(CACHE).then(function (cache) {
return cache.addAll(precacheFiles);
});
}

View File

@ -1,20 +1,17 @@
import { AwaitStore, Observable } from "@hibas123/utils";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
const light = readFileSync( const light = readFileSync("./node_modules/@hibas123/theme/out/light.css", "utf8")
"node_modules/@hibas123/theme/out/light.css", const dark = readFileSync("./node_modules/@hibas123/theme/out/dark.css", "utf8")
"utf-8"
);
const dark = readFileSync("node_modules/@hibas123/theme/out/dark.css", "utf-8");
export enum ThemeStates { export enum ThemeStates {
AUTO, AUTO,
LIGHT, LIGHT,
DARK, DARK
} }
let themeConfig: ThemeStates = Number(localStorage.getItem("theme")); let themeConfig: ThemeStates = Number(localStorage.getItem("theme"));
if (Number.isNaN(themeConfig)) themeConfig = ThemeStates.AUTO; if (Number.isNaN(themeConfig))
themeConfig = ThemeStates.AUTO;
let isDark = false; let isDark = false;
let mediaIsDark = false; let mediaIsDark = false;
@ -22,32 +19,28 @@ let mediaIsDark = false;
if (window.matchMedia) { if (window.matchMedia) {
const mediaq = matchMedia("(prefers-color-scheme: dark)"); const mediaq = matchMedia("(prefers-color-scheme: dark)");
mediaIsDark = mediaq.matches; mediaIsDark = mediaq.matches;
mediaq.onchange = (ev) => { mediaq.onchange = ev => {
mediaIsDark = ev.matches; mediaIsDark = ev.matches;
apply(); apply();
}; }
console.log(mediaq); console.log(mediaq);
} }
const DarkModeStore = new AwaitStore<boolean>(isDark);
let styleElm: HTMLStyleElement; let styleElm: HTMLStyleElement;
function apply(force?: boolean) { function apply(force?: boolean) {
let shouldDark = let shouldDark = themeConfig === ThemeStates.AUTO ? mediaIsDark : themeConfig === ThemeStates.DARK;
themeConfig === ThemeStates.AUTO
? mediaIsDark
: themeConfig === ThemeStates.DARK;
if (force || shouldDark !== isDark) { if (force || shouldDark !== isDark) {
if (styleElm) styleElm.remove(); if (styleElm) styleElm.remove();
styleElm = document.createElement("style"); styleElm = document.createElement("style");
document.head.appendChild(styleElm); document.head.appendChild(styleElm);
styleElm.innerHTML = shouldDark ? dark : light; styleElm.innerHTML = shouldDark ? dark : light;
isDark = shouldDark; isDark = shouldDark;
DarkModeStore.send(isDark);
} }
} }
apply(true); apply(true);
function change(state: ThemeStates) { function change(state: ThemeStates) {
themeConfig = state; themeConfig = state;
localStorage.setItem("theme", String(themeConfig)); localStorage.setItem("theme", String(themeConfig));
@ -56,6 +49,6 @@ function change(state: ThemeStates) {
export default { export default {
active: () => themeConfig, active: () => themeConfig,
change: (state: ThemeStates) => change(state), change: (state: ThemeStates) => change(state)
isDark: DarkModeStore, }
};

15
src/types.d.ts vendored
View File

@ -1,3 +1,18 @@
// declare module "*.svg" {
// const SVG: (props: {
// width?: number | undefined
// height?: number | undefined
// onClick?: (evt: MouseEvent) => void;
// style?: string;
// }) => JSX.Element;
// export default SVG;
// }
declare module "*.svg" {
const SVG: string;
export default SVG;
}
interface Window { interface Window {
debug: any; debug: any;
} }

View File

@ -1,15 +1,24 @@
{ {
"compilerOptions": { "compilerOptions": {
"outDir": "./public", "outDir": "./public",
"target": "ES2022", "target": "es6",
"module": "commonjs", "module": "commonjs",
"noImplicitAny": false, "noImplicitAny": false,
"removeComments": true, "removeComments": true,
"sourceMap": true, "sourceMap": true,
"jsx": "react", "jsx": "react",
"jsxFactory": "h", "jsxFactory": "h",
"lib": ["es2015", "dom", "esnext"], "lib": [
"resolveJsonModule": true "es2015",
"dom",
"esnext"
],
"resolveJsonModule": true,
"esModuleInterop": true
}, },
"include": ["./src/types.d.ts", "./src/**/*.tsx", "./src/**/*.ts"] "include": [
"./src/types.d.ts",
"./src/**/*.tsx",
"./src/**/*.ts"
]
} }

76
webpack.config.js Executable file
View File

@ -0,0 +1,76 @@
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const Visualizer = require('webpack-visualizer-plugin');
const path = require("path");
const fs = require("fs");
const config = require("./config.json");
const url = require("url");
module.exports = {
devServer: {
host: "0.0.0.0", // Defaults to `localhost`
open: false, // Open the page in browser,
contentBase: path.join(__dirname, 'dist'),
disableHostCheck: true,
headers: {
"Access-Control-Allow-Origin": "*"
},
watchOptions: {
aggregateTimeout: 300,
poll: 500
},
public: url.parse(config.callback_url).hostname
},
plugins: [
new CopyWebpackPlugin([{
from: "public"
}]),
new HtmlWebpackPlugin({
title: 'SecureNotes',
template: "./src/index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new BundleAnalyzerPlugin({
analyzerMode: "static",
openAnalyzer: false
}),
new Visualizer(),
],
entry: {
main: "./src/index.tsx"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "eval",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".mjs"]
},
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}, {
test: /\.(png|jpg)$/,
loader: "file-loader",
}, {
test: /\.(scss|css)$/,
use: [
"style-loader", // creates style nodes from JS strings
MiniCssExtractPlugin.loader,
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
{
test: /\.svg$/,
use: ['preact-svg-loader'],
}
]
}
};