This commit is contained in:
Magnus Åhall 2024-12-02 15:26:35 +01:00
parent 1d6ba99a36
commit 42b66714aa
3 changed files with 62 additions and 52 deletions

View File

@ -2,25 +2,27 @@ import { h, Component, createRef } from 'preact'
import { signal } from 'preact/signals' import { signal } from 'preact/signals'
import htm from 'htm' import htm from 'htm'
import { API } from 'api' import { API } from 'api'
import { Node } from 'node' import { Node, NodeUI } from 'node'
const html = htm.bind(h) const html = htm.bind(h)
export class Notes2 { export class Notes2 {
constructor() {//{{{ constructor() {//{{{
this.startNode = null this.startNode = null
this.tree = createRef() this.tree = createRef()
this.nodeUI = createRef()
this.setStartNode() this.setStartNode()
}//}}} }//}}}
render() {//{{{ render() {//{{{
return html` return html`
<button onclick=${() => API.logout()}>Log out</button> <button onclick=${() => API.logout()}>Log out</button>
<${Tree} ref=${this.tree} app=${this} /> <${Tree} ref=${this.tree} app=${this} />
<${NodeUI} app=${this} ref=${this.nodeUI} />
` `
}//}}} }//}}}
setStartNode() {//{{{ setStartNode() {//{{{
let urlParams = new URLSearchParams(window.location.search) const urlParams = new URLSearchParams(window.location.search)
let nodeID = urlParams.get('node') const nodeID = urlParams.get('node')
this.startNode = new Node(this, nodeID ? parseInt(nodeID) : 0) this.startNode = new Node(this, nodeID ? Number.parseInt(nodeID) : 0)
}//}}} }//}}}
treeGet() {//{{{ treeGet() {//{{{
@ -45,9 +47,9 @@ class Tree extends Component {
this.retrieve() this.retrieve()
}//}}} }//}}}
render({ app }) {//{{{ render({ app }) {//{{{
let renderedTreeTrunk = this.treeTrunk.map(node => { const renderedTreeTrunk = this.treeTrunk.map(node => {
this.treeNodeComponents[node.ID] = createRef() this.treeNodeComponents[node.ID] = createRef()
return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${this} node=${node} ref=${this.treeNodeComponents[node.ID]} selected=${node.ID == app.startNode.ID} />` return html`<${TreeNode} key=${`treenode_${node.ID}`} tree=${this} node=${node} ref=${this.treeNodeComponents[node.ID]} selected=${node.ID === app.startNode.ID} />`
}) })
return html`<div id="tree">${renderedTreeTrunk}</div>` return html`<div id="tree">${renderedTreeTrunk}</div>`
}//}}} }//}}}
@ -64,8 +66,8 @@ class Tree extends Component {
// returned from the server to be sorted in such a way that // returned from the server to be sorted in such a way that
// a parent node always appears before a child node. // a parent node always appears before a child node.
// The server uses a recursive SQL query delivering this. // The server uses a recursive SQL query delivering this.
res.forEach(nodeData => { for (const nodeData of res) {
let node = new Node( const node = new Node(
this, this,
nodeData.ID, nodeData.ID,
) )
@ -80,11 +82,11 @@ class Tree extends Component {
this.treeNodes[node.ID] = node this.treeNodes[node.ID] = node
if (node.ParentID == 0) if (node.ParentID === 0)
this.treeTrunk.push(node) this.treeTrunk.push(node)
else if (this.treeNodes[node.ParentID] !== undefined) else if (this.treeNodes[node.ParentID] !== undefined)
this.treeNodes[node.ParentID].Children.push(node) this.treeNodes[node.ParentID].Children.push(node)
}) }
// When starting with an explicit node value, expanding all nodes // When starting with an explicit node value, expanding all nodes
// on its path gives the user a sense of location. Not necessarily working // on its path gives the user a sense of location. Not necessarily working
// as the start node isn't guaranteed to have returned data yet. // as the start node isn't guaranteed to have returned data yet.
@ -107,17 +109,17 @@ class Tree extends Component {
this.expandToTrunk(node.ID) this.expandToTrunk(node.ID)
}//}}} }//}}}
crumbsUpdateNodes(node) {//{{{ crumbsUpdateNodes(node) {//{{{
this.props.app.startNode.Crumbs.forEach(crumb => { for (const crumb in this.props.app.startNode.Crumbs) {
// Start node is loaded before the tree. // Start node is loaded before the tree.
let node = this.treeNodes[crumb.ID] const node = this.treeNodes[crumb.ID]
if (node) if (node)
node._expanded = true node._expanded = true
// Tree is done before the start node. // Tree is done before the start node.
let component = this.treeNodeComponents[crumb.ID] const component = this.treeNodeComponents[crumb.ID]
if (component && component.current) if (component?.component.current)
component.current.expanded.value = true component.current.expanded.value = true
}) }
// Will be undefined when called from tree initialization // Will be undefined when called from tree initialization
// (as tree nodes aren't rendered yet) // (as tree nodes aren't rendered yet)
@ -145,13 +147,13 @@ class TreeNode extends Component {
}//}}} }//}}}
render({ tree, node }) {//{{{ render({ tree, node }) {//{{{
let children = node.Children.map(node => { const children = node.Children.map(node => {
tree.treeNodeComponents[node.ID] = createRef() tree.treeNodeComponents[node.ID] = createRef()
return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${tree} node=${node} ref=${tree.treeNodeComponents[node.ID]} selected=${node.ID == tree.props.app.startNode.ID} />` return html`<${TreeNode} key=${`treenode_${node.ID}`} tree=${tree} node=${node} ref=${tree.treeNodeComponents[node.ID]} selected=${node.ID === tree.props.app.startNode.ID} />`
}) })
let expandImg = '' let expandImg = ''
if (node.Children.length == 0) if (node.Children.length === 0)
expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />` expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />`
else { else {
if (this.expanded.value) if (this.expanded.value)
@ -161,13 +163,15 @@ class TreeNode extends Component {
} }
let selected = (this.selected.value ? 'selected' : '') const selected = (this.selected.value ? 'selected' : '')
return html` return html`
<div class="node"> <div class="node">
<div class="expand-toggle" onclick=${() => this.expanded.value ^= true}>${expandImg}</div> <div class="expand-toggle" onclick=${() => { this.expanded.value ^= true }}>${expandImg}</div>
<div class="name ${selected}" onclick=${() => window._app.current.nodeUI.current.goToNode(node.ID)}>${node.Name}</div> <div class="name ${selected}" onclick=${() => window._notes2.current.nodeUI.current.goToNode(node.ID)}>${node.Name}</div>
<div class="children ${node.Children.length > 0 && this.expanded.value ? 'expanded' : 'collapsed'}">${children}</div> <div class="children ${node.Children.length > 0 && this.expanded.value ? 'expanded' : 'collapsed'}">${children}</div>
</div>` </div>`
}//}}} }//}}}
} }
// vim: foldmethod=marker

View File

@ -16,7 +16,7 @@ export class NodeUI extends Component {
this.keys = signal([]) this.keys = signal([])
this.page = signal('node') this.page = signal('node')
window.addEventListener('popstate', evt => { window.addEventListener('popstate', evt => {
if (evt.state && evt.state.hasOwnProperty('nodeID')) if (evt.state?.hasOwnProperty('nodeID'))
this.goToNode(evt.state.nodeID, true) this.goToNode(evt.state.nodeID, true)
else else
this.goToNode(0, true) this.goToNode(0, true)
@ -28,7 +28,7 @@ export class NodeUI extends Component {
if (this.node.value === null) if (this.node.value === null)
return return
let node = this.node.value const node = this.node.value
document.title = `N: ${node.Name}` document.title = `N: ${node.Name}`
let crumbs = [ let crumbs = [
@ -39,7 +39,7 @@ export class NodeUI extends Component {
html`<div class="crumb" onclick=${() => this.goToNode(node.ID)}>${node.Name}</div>` html`<div class="crumb" onclick=${() => this.goToNode(node.ID)}>${node.Name}</div>`
).reverse()) ).reverse())
let children = node.Children.sort((a, b) => { const children = node.Children.sort((a, b) => {
if (a.Name.toLowerCase() > b.Name.toLowerCase()) return 1 if (a.Name.toLowerCase() > b.Name.toLowerCase()) return 1
if (a.Name.toLowerCase() < b.Name.toLowerCase()) return -1 if (a.Name.toLowerCase() < b.Name.toLowerCase()) return -1
return 0 return 0
@ -56,9 +56,9 @@ export class NodeUI extends Component {
let page = '' let page = ''
switch (this.page.value) { switch (this.page.value) {
case 'node': case 'node':
if (node.ID == 0) { if (node.ID === 0) {
page = html` page = html`
<div style="cursor: pointer; color: #000; text-align: center;" onclick=${() => this.page.value = 'schedule-events'}>Schedule events</div> <div style="cursor: pointer; color: #000; text-align: center;" onclick=${() => { this.page.value = 'schedule-events' }}>Schedule events</div>
${children.length > 0 ? html`<div class="child-nodes">${children}</div><div id="notes-version">Notes version ${window._VERSION}</div>` : html``} ${children.length > 0 ? html`<div class="child-nodes">${children}</div><div id="notes-version">Notes version ${window._VERSION}</div>` : html``}
` `
} else { } else {
@ -104,8 +104,8 @@ export class NodeUI extends Component {
break break
} }
let menu = () => (this.menu.value ? html`<${Menu} nodeui=${this} />` : null) const menu = () => (this.menu.value ? html`<${Menu} nodeui=${this} />` : null)
let checklist = () => const checklist = () =>
html` html`
<div class="checklist" onclick=${evt => { evt.stopPropagation(); this.toggleChecklist() }}> <div class="checklist" onclick=${evt => { evt.stopPropagation(); this.toggleChecklist() }}>
<img src="/images/${window._VERSION}/${this.showChecklist() ? 'checklist-on.svg' : 'checklist-off.svg'}" /> <img src="/images/${window._VERSION}/${this.showChecklist() ? 'checklist-on.svg' : 'checklist-off.svg'}" />
@ -209,17 +209,19 @@ export class NodeUI extends Component {
}//}}} }//}}}
goToNode(nodeID, dontPush) {//{{{ goToNode(nodeID, dontPush) {//{{{
/* TODO - implement modified values
if (this.props.app.nodeModified.value) { if (this.props.app.nodeModified.value) {
if (!confirm("Changes not saved. Do you want to discard changes?")) if (!confirm("Changes not saved. Do you want to discard changes?"))
return return
} }
*/
if (!dontPush) if (!dontPush)
history.pushState({ nodeID }, '', `/?node=${nodeID}`) history.pushState({ nodeID }, '', `/?node=${nodeID}`)
// New node is fetched in order to retrieve content and files. // New node is fetched in order to retrieve content and files.
// Such data is unnecessary to transfer for tree/navigational purposes. // Such data is unnecessary to transfer for tree/navigational purposes.
let node = new Node(this.props.app, nodeID) const node = new Node(this.props.app, nodeID)
node.retrieve(node => { node.retrieve(node => {
this.props.app.nodeModified.value = false this.props.app.nodeModified.value = false
this.node.value = node this.node.value = node
@ -278,12 +280,14 @@ export class NodeUI extends Component {
async retrieveKeys() {//{{{ async retrieveKeys() {//{{{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
/* TODO - implement keys in IndexedDB
this.props.app.request('/key/retrieve', {}) this.props.app.request('/key/retrieve', {})
.then(res => { .then(res => {
this.keys.value = res.Keys.map(keyData => new Key(keyData, this.keyCounter)) this.keys.value = res.Keys.map(keyData => new Key(keyData, this.keyCounter))
resolve(this.keys.value) resolve(this.keys.value)
}) })
.catch(reject) .catch(reject)
*/
}) })
}//}}} }//}}}
keyCounter() {//{{{ keyCounter() {//{{{

View File

@ -1,24 +1,24 @@
import { API } from 'api' import { API } from 'api'
export class NodeStore { export class NodeStore {
constructor() { constructor() {//{{{
if (!('indexedDB' in window)) { if (!('indexedDB' in window)) {
throw 'Missing IndexedDB' throw 'Missing IndexedDB'
} }
this.db = null this.db = null
} }//}}}
async initializeDB() { async initializeDB() {//{{{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let req = indexedDB.open('notes', 2) const req = indexedDB.open('notes', 2)
// Schema upgrades for IndexedDB. // Schema upgrades for IndexedDB.
// These can start from different points depending on updates to Notes2 since a device was online. // These can start from different points depending on updates to Notes2 since a device was online.
req.onupgradeneeded = (event) => { req.onupgradeneeded = (event) => {
var store let store
let db = event.target.result const db = event.target.result
let trx = event.target.transaction const trx = event.target.transaction
for (let i = event.oldVersion + 1; i <= event.newVersion; i++) { for (let i = event.oldVersion + 1; i <= event.newVersion; i++) {
console.log(`Upgrade to schema ${i}`) console.log(`Upgrade to schema ${i}`)
@ -45,13 +45,13 @@ export class NodeStore {
reject(event.target.error) reject(event.target.error)
} }
}) })
} }//}}}
async add(records) { async add(records) {//{{{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
let t = this.db.transaction('nodes', 'readwrite') const t = this.db.transaction('nodes', 'readwrite')
let nodeStore = t.objectStore('nodes') const nodeStore = t.objectStore('nodes')
t.onerror = (event) => { t.onerror = (event) => {
console.log('transaction error', event.target.error) console.log('transaction error', event.target.error)
reject(event.target.error) reject(event.target.error)
@ -60,22 +60,22 @@ export class NodeStore {
resolve() resolve()
} }
records.forEach(record => { for (const record in records) {
let addReq = nodeStore.put(record) const addReq = nodeStore.put(record)
addReq.onsuccess = (event) => { addReq.onsuccess = () => {
console.log('OK!', record.ID, record.Name) console.log('OK!', record.ID, record.Name)
} }
addReq.onerror = (event) => { addReq.onerror = (event) => {
console.log('Error!', event.target.error, record.ID) console.log('Error!', event.target.error, record.ID)
} }
}) }
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
}) })
} }//}}}
async get(id) { async get(id) {//{{{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// Node is always returned from IndexedDB if existing there. // Node is always returned from IndexedDB if existing there.
// Otherwise an attempt to get it from backend is executed. // Otherwise an attempt to get it from backend is executed.
@ -103,14 +103,16 @@ export class NodeStore {
.catch(e => reject(e)) .catch(e => reject(e))
} }
}) })
} }//}}}
async getTreeNodes() { async getTreeNodes() {//{{{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let trx = this.db.transaction('nodes', 'readonly') const trx = this.db.transaction('nodes', 'readonly')
let nodeStore = trx.objectStore('nodes') const nodeStore = trx.objectStore('nodes')
let req = nodeStore.getAll() const req = nodeStore.getAll()
req.onsuccess = (event) => resolve(event.target.result) req.onsuccess = (event) => resolve(event.target.result)
req.onerror = (event) => reject(event.target.error) req.onerror = (event) => reject(event.target.error)
}) })
} }//}}}
} }
// vim: foldmethod=marker