Notes/static/js/app.mjs

331 lines
8.9 KiB
JavaScript
Raw Permalink Normal View History

2023-06-15 07:24:23 +02:00
import 'preact/devtools'
2023-06-17 09:11:14 +02:00
import { signal } from 'preact/signals'
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'
2023-06-15 07:24:23 +02:00
const html = htm.bind(h)
class App extends Component {
constructor() {//{{{
super()
this.websocket_uri = `ws://localhost:1371/ws`
2023-06-15 07:24:23 +02:00
this.websocket = null
this.websocket_int_ping = null
this.websocket_int_reconnect = null
this.wsConnect()
this.wsLoop()
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
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')
2023-06-16 07:11:27 +02:00
if(!this.session.initialized) {
2023-06-17 09:11:14 +02:00
return html`<div>Validating session</div>`
2023-06-16 07:11:27 +02:00
}
2023-07-18 07:09:03 +02:00
2023-06-16 07:11:27 +02: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
}//}}}
wsLoop() {//{{{
setInterval(()=>{
if(this.websocket === null) {
console.log("wsLoop connect")
this.wsConnect()
}
}, 1000)
}//}}}
wsConnect() {//{{{
2023-06-18 20:13:35 +02:00
this.websocket = new WebSocket(this.websocket_uri)
2023-06-15 07:24:23 +02:00
this.websocket.onopen = evt=>this.wsOpen(evt)
this.websocket.onmessage = evt=>this.wsMessage(evt)
this.websocket.onerror = evt=>this.wsError(evt)
this.websocket.onclose = evt=>this.wsClose(evt)
}//}}}
wsOpen() {//{{{
this.setState({ wsConnected: true })
// A ping interval to implement a rudimentary keep-alive.
}//}}}
wsClose() {//{{{
console.log("Lost connection to Notes server")
this.websocket = null
}//}}}
wsError(evt) {//{{{
console.log("websocket error", evt)
this.websocket = null;
}//}}}
wsMessage(evt) {//{{{
let msg = JSON.parse(evt.data)
// Broadcast message
if(msg.ID == '') {
this.broadcastHandler(msg)
} else {
this.msgHandler(msg)
}
}//}}}
2023-06-21 23:52:21 +02:00
responseError({comm, app, upload}) {//{{{
2023-06-15 14:12:35 +02:00
if(comm !== undefined) {
comm.text().then(body=>alert(body))
return
}
2023-06-17 09:11:14 +02:00
if(app !== undefined && app.hasOwnProperty('Error')) {
alert(app.Error)
2023-06-15 14:12:35 +02:00
return
}
if(app !== undefined) {
alert(JSON.stringify(app))
}
2023-06-21 23:52:21 +02:00
if(upload !== undefined) {
alert(upload)
return
}
2023-06-15 14:12:35 +02:00
}//}}}
async request(url, params) {//{{{
return new Promise((resolve, reject)=>{
let headers = {
'Content-Type': 'application/json',
}
2023-06-16 07:11:27 +02:00
if(this.session.UUID !== '')
headers['X-Session-Id'] = this.session.UUID
2023-06-15 14:12:35 +02:00
fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(params),
})
.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
2023-06-17 09:11:14 +02:00
if(!json.OK) {
2023-06-15 14:12:35 +02:00
return reject({app: json})
2023-06-17 09:11:14 +02:00
}
2023-06-15 14:12:35 +02:00
return resolve(json)
})
.catch(err=>reject({comm: err}))
})
}//}}}
2023-06-15 07:24:23 +02:00
broadcastHandler(msg) {//{{{
switch(msg.Op) {
case 'css_reload':
refreshCSS()
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: '',
}
}//}}}
render({}, { username, password }) {//{{{
let authentication_failed = html``;
if(this.authentication_failed.value)
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">
<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>
${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
this.props.app.request('/node/tree', { StartNodeID: 0 })
.then(res=>{
// 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()
})
.catch(this.responseError)
}//}}}
render({ app }) {//{{{
let renderedTreeTrunk = this.treeTrunk.map(node=>{
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`<div id="tree">${renderedTreeTrunk}</div>`
}//}}}
setSelected(node) {//{{{
if(this.selectedTreeNode)
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) {//{{{
this.props.app.startNode.Crumbs.forEach(crumb=>{
// Start node is loaded before the tree.
let node = this.treeNodes[crumb.ID]
if(node)
node._expanded = true
// Tree is done before the start node.
let component = this.treeNodeComponents[crumb.ID]
if(component && component.current)
component.current.expanded.value = true
})
// Will be undefined when called from tree initialization
// (as tree nodes aren't rendered yet)
if(node !== undefined)
this.setSelected(node)
}//}}}
2023-07-22 09:31:26 +02:00
expandToTrunk(nodeID) {//{{{
let node = this.treeNodes[nodeID]
if(node === undefined)
return
node = this.treeNodes[node.ParentID]
while(node !== undefined) {
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 }) {//{{{
let children = node.Children.map(node=>{
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} />`
})
let expandImg = ''
if(node.Children.length == 0)
expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />`
else {
if(this.expanded.value)
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">
<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="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