Notes/static/js/app.mjs

321 lines
8.8 KiB
JavaScript
Raw Permalink Normal View History

import 'preact/debug'
2023-06-15 07:24:23 +02:00
import 'preact/devtools'
2023-06-15 07:24:23 +02:00
import { h, Component, render, createRef } from 'preact'
import htm from 'htm'
2023-06-16 07:11:27 +02:00
import { Session } from 'session'
2023-06-27 14:44:36 +02:00
import { Node, NodeUI } from 'node'
2024-01-07 16:20:21 +01:00
import { Websocket } from 'ws'
import { signal } from 'preact/signals'
2023-06-15 07:24:23 +02:00
const html = htm.bind(h)
class App extends Component {
constructor() {//{{{
super()
2023-06-16 07:11:27 +02:00
this.session = new Session(this)
this.session.initialize()
2023-06-17 09:11:14 +02:00
this.login = createRef()
2023-06-27 14:44:36 +02:00
this.tree = null
2023-06-17 09:11:14 +02:00
this.nodeUI = createRef()
2023-06-18 20:13:35 +02:00
this.nodeModified = signal(false)
2023-06-27 14:44:36 +02:00
this.startNode = null
2024-01-07 16:20:21 +01:00
this.websocketInit()
2024-01-05 21:14:55 +01:00
this.setStartNode()
2023-06-15 07:24:23 +02:00
}//}}}
render() {//{{{
2023-07-18 07:09:03 +02:00
let app_el = document.getElementById('app')
2024-01-06 11:40:58 +01:00
if (!this.session.initialized) {
return
2023-06-16 07:11:27 +02:00
}
2023-07-18 07:09:03 +02:00
2024-01-06 11:40:58 +01:00
if (!this.session.authenticated()) {
2023-07-18 07:09:03 +02:00
app_el.classList.remove('node')
app_el.classList.add('login')
2023-06-17 09:11:14 +02:00
return html`<${Login} ref=${this.login} />`
2023-06-15 07:24:23 +02:00
}
2023-07-18 07:09:03 +02:00
app_el.classList.remove('login')
app_el.classList.add('node')
2023-06-27 14:44:36 +02:00
return html`
<${Tree} app=${this} ref=${this.tree} />
<${NodeUI} app=${this} ref=${this.nodeUI} />
`
2023-06-15 07:24:23 +02:00
}//}}}
2024-01-06 11:40:58 +01:00
responseError({ comm, app, upload }) {//{{{
if (comm !== undefined) {
2024-01-10 23:28:00 +01:00
if (typeof comm.text === 'function')
comm.text().then(body => alert(body))
else
alert(comm)
2023-06-15 14:12:35 +02:00
return
}
2024-01-06 11:40:58 +01:00
if (app !== undefined && app.hasOwnProperty('Error')) {
2023-06-17 09:11:14 +02:00
alert(app.Error)
2023-06-15 14:12:35 +02:00
return
}
2024-01-06 11:40:58 +01:00
if (app !== undefined) {
2023-06-15 14:12:35 +02:00
alert(JSON.stringify(app))
}
2023-06-21 23:52:21 +02:00
2024-01-06 11:40:58 +01:00
if (upload !== undefined) {
2023-06-21 23:52:21 +02:00
alert(upload)
return
}
2023-06-15 14:12:35 +02:00
}//}}}
async request(url, params) {//{{{
2024-01-06 11:40:58 +01:00
return new Promise((resolve, reject) => {
2023-06-15 14:12:35 +02:00
let headers = {
'Content-Type': 'application/json',
}
2024-01-06 11:40:58 +01:00
if (this.session.UUID !== '')
2024-01-05 20:00:02 +01:00
headers['X-Session-ID'] = this.session.UUID
2023-06-15 14:12:35 +02:00
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(params),
})
2024-01-06 11:40:58 +01:00
.then(response => {
// A HTTP communication level error occured
if (!response.ok || response.status != 200)
return reject({ comm: response })
return response.json()
})
.then(json => {
// An application level error occured
if (!json.OK) {
switch (json.Code) {
case '001-0001': // Session not found
this.session.reset()
location.href = '/'
break
default:
return reject({ app: json })
}
}
return resolve(json)
})
.catch(err => reject({ comm: err }))
2023-06-15 14:12:35 +02:00
})
}//}}}
2024-01-07 16:20:21 +01:00
websocketInit() {//{{{
this.websocket = new Websocket()
this.websocket.register('open', ()=>console.log('websocket connected'))
this.websocket.register('close', ()=>console.log('websocket disconnected'))
this.websocket.register('error', msg=>console.log(msg))
2024-04-05 09:27:47 +02:00
this.websocket.register('message', msg=>this.websocketMessage(msg))
2024-01-07 16:20:21 +01:00
this.websocket.start()
}//}}}
websocketMessage(data) {//{{{
const msg = JSON.parse(data)
2024-01-06 11:40:58 +01:00
switch (msg.Op) {
2023-06-15 07:24:23 +02:00
case 'css_reload':
2024-04-05 09:27:47 +02:00
this.websocket.refreshCSS()
2023-06-15 07:24:23 +02:00
break;
}
}//}}}
2023-06-27 14:44:36 +02:00
setStartNode() {//{{{
let urlParams = new URLSearchParams(window.location.search)
let nodeID = urlParams.get('node')
this.startNode = new Node(this, nodeID ? parseInt(nodeID) : 0)
}//}}}
2023-06-15 07:24:23 +02:00
}
class Login extends Component {
2023-06-17 09:11:14 +02:00
constructor() {//{{{
super()
this.authentication_failed = signal(false)
this.state = {
username: '',
password: '',
}
}//}}}
2024-01-06 11:40:58 +01:00
render({ }, { username, password }) {//{{{
2023-06-17 09:11:14 +02:00
let authentication_failed = html``;
2024-01-06 11:40:58 +01:00
if (this.authentication_failed.value)
2023-06-17 09:11:14 +02:00
authentication_failed = html`<div class="auth-failed">Authentication failed</div>`;
2023-06-15 07:24:23 +02:00
return html`
<div id="login">
2023-07-18 07:09:03 +02:00
<div class="header">
<h1>Notes</h1>
</div>
<div class="fields">
2024-01-06 11:40:58 +01:00
<input id="username" type="text" placeholder="Username" value=${username} oninput=${evt => this.setState({ username: evt.target.value })} onkeydown=${evt => { if (evt.code == 'Enter') this.login() }} />
<input id="password" type="password" placeholder="Password" value=${password} oninput=${evt => this.setState({ password: evt.target.value })} onkeydown=${evt => { if (evt.code == 'Enter') this.login() }} />
<button onclick=${() => this.login()}>Login</button>
2023-07-18 07:09:03 +02:00
${authentication_failed}
</div>
2023-06-15 07:24:23 +02:00
</div>
`
2023-06-15 14:12:35 +02:00
}//}}}
componentDidMount() {//{{{
document.getElementById('username').focus()
}//}}}
login() {//{{{
let username = document.getElementById('username').value
let password = document.getElementById('password').value
2023-06-16 07:11:27 +02:00
window._app.current.session.authenticate(username, password)
2023-06-15 14:12:35 +02:00
}//}}}
2023-06-15 07:24:23 +02:00
}
2023-06-27 14:44:36 +02:00
class Tree extends Component {
constructor(props) {//{{{
super(props)
this.treeNodes = {}
this.treeNodeComponents = {}
this.treeTrunk = []
this.selectedTreeNode = null
this.props.app.tree = this
2024-01-05 20:00:02 +01:00
this.retrieve()
}//}}}
render({ app }) {//{{{
2024-01-06 11:40:58 +01:00
let renderedTreeTrunk = this.treeTrunk.map(node => {
2024-01-05 20:00:02 +01:00
this.treeNodeComponents[node.ID] = createRef()
2024-01-06 11:40:58 +01:00
return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${this} node=${node} ref=${this.treeNodeComponents[node.ID]} selected=${node.ID == app.startNode.ID} />`
2024-01-05 20:00:02 +01:00
})
return html`<div id="tree">${renderedTreeTrunk}</div>`
}//}}}
2023-06-27 14:44:36 +02:00
2024-01-05 20:00:02 +01:00
retrieve(callback = null) {//{{{
2023-06-27 14:44:36 +02:00
this.props.app.request('/node/tree', { StartNodeID: 0 })
2024-01-06 11:40:58 +01:00
.then(res => {
this.treeNodes = {}
this.treeNodeComponents = {}
this.treeTrunk = []
this.selectedTreeNode = null
// A tree of nodes is built. This requires the list of nodes
// returned from the server to be sorted in such a way that
// a parent node always appears before a child node.
// The server uses a recursive SQL query delivering this.
res.Nodes.forEach(nodeData => {
let node = new Node(
this,
nodeData.ID,
)
node.Children = []
node.Crumbs = []
node.Files = []
node.Level = nodeData.Level
node.Name = nodeData.Name
node.ParentID = nodeData.ParentID
node.Updated = nodeData.Updated
node.UserID = nodeData.UserID
this.treeNodes[node.ID] = node
if (node.ParentID == 0)
this.treeTrunk.push(node)
else if (this.treeNodes[node.ParentID] !== undefined)
this.treeNodes[node.ParentID].Children.push(node)
})
// When starting with an explicit node value, expanding all nodes
// 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.
this.crumbsUpdateNodes()
this.forceUpdate()
if (callback)
callback()
2023-06-27 14:44:36 +02:00
2024-01-06 11:40:58 +01:00
})
.catch(this.responseError)
2023-06-27 14:44:36 +02:00
}//}}}
setSelected(node) {//{{{
2024-01-06 11:40:58 +01:00
if (this.selectedTreeNode)
2023-06-27 14:44:36 +02:00
this.selectedTreeNode.selected.value = false
this.selectedTreeNode = this.treeNodeComponents[node.ID].current
this.selectedTreeNode.selected.value = true
this.selectedTreeNode.expanded.value = true
2023-07-22 09:31:26 +02:00
this.expandToTrunk(node.ID)
2023-06-27 14:44:36 +02:00
}//}}}
crumbsUpdateNodes(node) {//{{{
2024-01-06 11:40:58 +01:00
this.props.app.startNode.Crumbs.forEach(crumb => {
2023-06-27 14:44:36 +02:00
// Start node is loaded before the tree.
let node = this.treeNodes[crumb.ID]
2024-01-06 11:40:58 +01:00
if (node)
2023-06-27 14:44:36 +02:00
node._expanded = true
// Tree is done before the start node.
let component = this.treeNodeComponents[crumb.ID]
2024-01-06 11:40:58 +01:00
if (component && component.current)
2023-06-27 14:44:36 +02:00
component.current.expanded.value = true
})
// Will be undefined when called from tree initialization
// (as tree nodes aren't rendered yet)
2024-01-06 11:40:58 +01:00
if (node !== undefined)
2023-06-27 14:44:36 +02:00
this.setSelected(node)
}//}}}
2023-07-22 09:31:26 +02:00
expandToTrunk(nodeID) {//{{{
let node = this.treeNodes[nodeID]
2024-01-06 11:40:58 +01:00
if (node === undefined)
2023-07-22 09:31:26 +02:00
return
node = this.treeNodes[node.ParentID]
2024-01-06 11:40:58 +01:00
while (node !== undefined) {
2023-07-22 09:31:26 +02:00
this.treeNodeComponents[node.ID].current.expanded.value = true
node = this.treeNodes[node.ParentID]
}
}//}}}
2023-06-27 14:44:36 +02:00
}
class TreeNode extends Component {
constructor(props) {//{{{
super(props)
this.selected = signal(props.selected)
this.expanded = signal(this.props.node._expanded)
}//}}}
render({ tree, node }) {//{{{
2024-01-06 11:40:58 +01:00
let children = node.Children.map(node => {
2023-06-27 14:44:36 +02:00
tree.treeNodeComponents[node.ID] = createRef()
2024-01-06 11:40:58 +01:00
return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${tree} node=${node} ref=${tree.treeNodeComponents[node.ID]} selected=${node.ID == tree.props.app.startNode.ID} />`
2023-06-27 14:44:36 +02:00
})
let expandImg = ''
2024-01-06 11:40:58 +01:00
if (node.Children.length == 0)
2023-06-27 14:44:36 +02:00
expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />`
else {
2024-01-06 11:40:58 +01:00
if (this.expanded.value)
2023-06-27 14:44:36 +02:00
expandImg = html`<img src="/images/${window._VERSION}/expanded.svg" />`
else
expandImg = html`<img src="/images/${window._VERSION}/collapsed.svg" />`
}
let selected = (this.selected.value ? 'selected' : '')
return html`
<div class="node">
2024-01-06 11:40:58 +01:00
<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>
2023-06-27 14:44:36 +02:00
<div class="children ${node.Children.length > 0 && this.expanded.value ? 'expanded' : 'collapsed'}">${children}</div>
</div>`
}//}}}
}
2023-06-15 07:24:23 +02:00
// Init{{{
window._app = createRef()
window._resourceModels = []
render(html`<${App} ref=${window._app} />`, document.getElementById('app'))
//}}}
// vim: foldmethod=marker