`
+ return ``
+ (token.escaped ? code : escapeHtmlEntities(code, true))
+ '
\n'
}
- return `'
+ (token.escaped ? code : escapeHtmlEntities(code, true))
@@ -260,7 +285,7 @@ export class MarkedPosition {
},
codespan(token) {
- return `${escapeHtmlEntities(token.text, true)}`
+ return `${escapeHtmlEntities(token.text, true)}`
},
br(token) {
diff --git a/static/js/node_store.mjs b/static/js/node_store.mjs
index f31a4b6..6be8f82 100644
--- a/static/js/node_store.mjs
+++ b/static/js/node_store.mjs
@@ -1,6 +1,8 @@
import { Node } from 'node'
export const ROOT_NODE = '00000000-0000-0000-0000-000000000000'
+export const ORPHANED_NODE = '00000000-0000-0000-0000-000000000001'
+export const DELETED_NODE = '00000000-0000-0000-0000-000000000002'
export class NodeStore {
constructor() {//{{{
@@ -13,6 +15,8 @@ export class NodeStore {
this.sendQueue = null
this.nodesHistory = null
this.files = null
+
+ this.initializeSpecialNodes()
}//}}}
initializeDB() {//{{{
return new Promise((resolve, reject) => {
@@ -76,8 +80,7 @@ export class NodeStore {
this.sendQueue = new SimpleNodeStore(this.db, 'send_queue')
this.nodesHistory = new NodeHistoryStore(this.db, 'nodes_history')
this.files = new SimpleNodeStore(this.db, 'files')
- this.initializeRootNode()
- .then(() => resolve())
+ resolve()
}
req.onerror = (event) => {
@@ -85,40 +88,11 @@ export class NodeStore {
}
})
}//}}}
- initializeRootNode() {//{{{
- return new Promise((resolve, reject) => {
- // The root node is a magical node which displays as the first node if none is specified.
- // If not already existing, it will be created.
- const trx = this.db.transaction('nodes', 'readwrite')
- const nodes = trx.objectStore('nodes')
- const getRequest = nodes.get(ROOT_NODE)
- getRequest.onsuccess = (event) => {
- // Root node exists - nice!
- if (event.target.result !== undefined) {
- resolve(event.target.result)
- return
- }
-
- const putRequest = nodes.put({
- UUID: ROOT_NODE,
- Name: 'Notes2',
- Content: 'Hello, World!',
- Updated: new Date().toISOString(),
- ParentUUID: '',
- })
- putRequest.onsuccess = (event) => {
- resolve(event.target.result)
- }
- putRequest.onerror = (event) => {
- reject(event.target.error)
- }
- }
- getRequest.onerror = (event) => reject(event.target.error)
- })
- }//}}}
- purgeCache() {//{{{
- this.nodes = {}
- }//}}}
+ initializeSpecialNodes() {// {{{
+ this.nodes[ROOT_NODE] = new Node({ UUID: ROOT_NODE, Name: 'Start', Special: true }, -1)
+ this.nodes[DELETED_NODE] = new Node({ UUID: DELETED_NODE, Name: 'Deleted nodes', Special: true }, -1)
+ this.nodes[ORPHANED_NODE] = new Node({ UUID: ORPHANED_NODE, Name: 'Orphaned nodes', Special: true }, -1)
+ }// }}}
node(uuid, dataIfUndefined, newLevel) {//{{{
let n = this.nodes[uuid]
@@ -247,6 +221,7 @@ export class NodeStore {
nodeStore = t.objectStore('nodes')
t.oncomplete = (_event) => {
+ console.log('complete')
resolve()
}
@@ -271,6 +246,14 @@ export class NodeStore {
}//}}}
get(uuid, suppliedNodestore) {//{{{
return new Promise((resolve, reject) => {
+ switch (uuid) {
+ case ROOT_NODE:
+ case DELETED_NODE:
+ case ORPHANED_NODE:
+ resolve(this.nodes[uuid])
+ return
+ }
+
// A nodestore can be provided in order to
// avoid creating new transactions.
let trx
@@ -308,6 +291,16 @@ export class NodeStore {
return
}
+ if (node.UUID === DELETED_NODE || node.ParentUUID === DELETED_NODE) {
+ resolve(accumulated)
+ return
+ }
+
+ if (node.UUID === ORPHANED_NODE || node.ParentUUID === ORPHANED_NODE) {
+ resolve(accumulated)
+ return
+ }
+
const getRequest = nodeParentIndex.get(node.ParentUUID)
getRequest.onsuccess = (event) => {
// Node not found in IndexedDB.
@@ -358,6 +351,7 @@ class SimpleNodeStore {
// Node to be moved is first stored in the new queue.
const req = store.put(node.data)
req.onsuccess = () => {
+ console.log('here')
resolve()
}
req.onerror = (event) => {
diff --git a/static/js/page_node.mjs b/static/js/page_node.mjs
index 834e22f..2106ada 100644
--- a/static/js/page_node.mjs
+++ b/static/js/page_node.mjs
@@ -2,14 +2,70 @@ import { ROOT_NODE, uuidv7 } from 'node_store'
import { CustomHTMLElement } from './lib/custom_html_element.mjs'
import { MarkedPosition } from './marked_position.mjs'
+class N2NodeMenu extends CustomHTMLElement {
+ static {// {{{
+ this.tmpl = document.createElement('template')
+ this.tmpl.innerHTML = `
+
+
+ `
+ }// }}}
+ constructor() {// {{{
+ super()
+ }// }}}
+}
+customElements.define('n2-nodemenu', N2NodeMenu)
+
export class N2PageNodeUI extends CustomHTMLElement {
static {// {{{
this.tmpl = document.createElement('template')
this.tmpl.innerHTML = `
@@ -28,10 +92,13 @@ export class N2PageNodeUI extends CustomHTMLElement {
+
`
}// }}}
@@ -40,12 +107,14 @@ export class N2PageNodeUI extends CustomHTMLElement {
this.node = null
this.style.display = 'contents'
- this.classList.add('show-markdown') // TODO Should probably be moved to settings.
this.marked = new MarkedPosition()
_mbus.subscribe('NODE_UI_OPEN', event => {
this.node = event.detail.data
- this.showMarkdown(true)
+
+
+ if (!this.node.isSpecial())
+ this.showMarkdown(true)
this.render()
})
@@ -66,11 +135,27 @@ export class N2PageNodeUI extends CustomHTMLElement {
_mbus.subscribe('MARKDOWN_EDIT', ({ detail }) => this.editMarkdown(detail.data))
_mbus.subscribe('MARKDOWN_CHANGE_CHECKBOX', ({ detail }) => this.checkboxUpdated(detail.data))
+ // Binding the node rename handler.
this.elName.addEventListener('click', async () => this.renameNode())
+
+ // Bind handlers for content keyboard input and paste.
this.elNodeContent.addEventListener('input', event => this.contentChanged(event))
this.elNodeContent.addEventListener('paste', async (event) => this.pasteHandler(event))
+
+ // Bind node icon handlers.
+ this.elIconSave.addEventListener('click', () => this.saveNode())
this.elIconMarkdown.addEventListener('click', () => this.showMarkdown(!this.showMarkdown()))
- this.elIconTableFormat.addEventListener('click', event => {
+ this.elIconNewDocument.addEventListener('click', event => {
+ if (event.shiftKey)
+ _app.createNode(this.node.ParentUUID)
+ else
+ _app.createNode()
+ })
+
+ // Bind node menu items to handlers.
+ this.elNodeMenu.elFormatTables.addEventListener('click', event => {
+ this.elNodeMenu.hidePopover()
+
if (!event.shiftKey)
this.elNodeContent.value = this.formatAllTables(this.elNodeContent.value)
else {
@@ -84,15 +169,12 @@ export class N2PageNodeUI extends CustomHTMLElement {
this.node.setContent(this.elNodeContent.value)
})
- this.elIconHistory.addEventListener('click', () => _mbus.dispatch('SHOW_PAGE', { page: 'history' }))
- this.elIconSave.addEventListener('click', () => this.saveNode())
- this.elIconNewDocument.addEventListener('click', event => {
- if (event.shiftKey)
- _app.createNode(this.node.ParentUUID)
- else
- _app.createNode()
+ this.elNodeMenu.elHistory.addEventListener('click', () => {
+ _mbus.dispatch('SHOW_PAGE', { page: 'history' })
})
+ // Default is to always show markdown.
+ this.classList.add('show-markdown') // TODO Should probably be moved to settings.
this.showMarkdown(true)
}// }}}
renderName() {// {{{
@@ -305,7 +387,7 @@ export class N2PageNodeUI extends CustomHTMLElement {
// Node is modified with the new value. User has to save manually, otherwise other changes could be saved
// when a save wasn't expected.
- const newValue =`[${checkbox.checked ? 'x' : ' '}] `
+ const newValue = `[${checkbox.checked ? 'x' : ' '}] `
const modifiedContent = this.node.content().slice(0, pos.start) + newValue + this.node.content().slice(pos.end)
this.node.setContent(modifiedContent)
@@ -422,12 +504,23 @@ export class Node {
getParent() {//{{{
return this._parent
}//}}}
+ moveToParent(newParentUUID) {// {{{
+ if (this.UUID === newParentUUID)
+ throw new Error("New parent UUID is the same as node UUID. Can't be your own parent.")
+
+ this.ParentUUID = newParentUUID
+ this.data.ParentUUID = newParentUUID
+ this._modified = true
+ }// }}}
isLastSibling() {//{{{
return this._sibling_after === null
}//}}}
isFirstSibling() {//{{{
return this._sibling_before === null
}//}}}
+ isSpecial() {// {{{
+ return this.data.Special
+ }// }}}
content() {//{{{
/* TODO - implement crypto
if (this.CryptoKeyID != 0 && !this._decrypted)
@@ -463,9 +556,10 @@ export class Node {
// When stored into database and ancestry was changed,
// the ancestry path could be interesting.
+ /*
const ancestors = await nodeStore.getNodeAncestry(this)
this.data.Ancestors = ancestors.map(a => a.get('Name')).reverse()
-
+ */
/* The node history is a local store for node history.
* This could be provisioned from the server or cleared if
* deemed unnecessary.
@@ -481,13 +575,19 @@ export class Node {
const history = nodeStore.nodesHistory.add(this)
// Updated node is added to the send queue to be stored on server.
+
const sendQueue = nodeStore.sendQueue.add(this)
// Updated node is saved to the primary node store.
const nodeStoreAdding = nodeStore.add([this])
- return Promise.all([history, sendQueue, nodeStoreAdding])
+ console.log('waiting')
+ await Promise.all([history, sendQueue, nodeStoreAdding])
+ console.log('waiting done')
+
+ return
}//}}}
}
+
// vim: foldmethod=marker
diff --git a/static/js/page_preferences.mjs b/static/js/page_preferences.mjs
new file mode 100644
index 0000000..9655278
--- /dev/null
+++ b/static/js/page_preferences.mjs
@@ -0,0 +1,283 @@
+import { CustomHTMLElement } from "./lib/custom_html_element.mjs"
+import { API } from './api.mjs'
+
+export class N2PagePreferences extends CustomHTMLElement {
+ static {// {{{
+ this.tmpl = document.createElement('template')
+ this.tmpl.innerHTML = `
+
+ Preferences
+
+ Changes preferences to not download images or files on the device doesn't remove the already downloaded data.
+
+
+
Device preference set
+
+
+
+
+
+
+
+ `
+ }// }}}
+ constructor() {// {{{
+ super(true)
+ this.sets = []
+
+ this.elNewSet.addEventListener('click', () => this.newSet())
+ this.elSave.addEventListener('click', () => this.save())
+ this.elDevPreferenceSet.addEventListener('change', event=>this.changePreferenceSet(event))
+
+ window._mbus.subscribe('SHOW_PAGE', async event => {
+ if (event.detail.data?.page == 'preferences') {
+ this.sets = await this.getPreferenceSets()
+ this.render()
+ }
+ })
+
+ window._mbus.subscribe('PREFERENCE_SET_MODIFIED', () => this.preferencesModified())
+ window._mbus.subscribe('PREFERENCE_SET_DELETE', event => this.preferencesDelete(event.detail.data.set))
+ }// }}}
+ sortSets(a, b) {// {{{
+ if (a.name == 'default') return -1
+ if (b.name == 'default') return 1
+
+ if (a.name.toLowerCase() < b.name.toLowerCase()) return -1
+ if (a.name.toLowerCase() > b.name.toLowerCase()) return 1
+
+ return 0
+ }// }}}
+ async render() {// {{{
+ try {
+ this.sets.sort(this.sortSets)
+ this.elSets.replaceChildren(...this.sets)
+
+ const setNames = this.sets.entries().map(([i, set]) => {
+ const optn = document.createElement('option')
+ optn.innerText = set.name
+ return optn
+ })
+ this.elDevPreferenceSet.replaceChildren(...setNames)
+ } catch (e) {
+ console.error(e)
+ alert(e.message)
+ }
+ }// }}}
+ async getPreferenceSets() {// {{{
+ const userData = localStorage.getItem('user')
+ if (userData === null)
+ throw new Error('Could not find user in localStorage')
+
+ const user = JSON.parse(userData)
+ const prefsData = user.Preferences
+
+ if (prefsData === undefined)
+ throw new Error('User object is missing preferences')
+
+ if (!prefsData.hasOwnProperty('default'))
+ throw new Error('The "default" preferences set is missing')
+
+ return Object.keys(prefsData).map(name => new N2PreferenceSet(name, prefsData[name]))
+ }// }}}
+ async retrieveServerPreferences() {// {{{
+ try {
+ API.query('GET', '/user/preferences')
+ } catch (e) {
+ console.error(e)
+ alert(`Error retrieving preferences: ${e.message}`)
+ }
+ }// }}}
+ changePreferenceSet(event) {// {{{
+ this.preferencesModified()
+ }// }}}
+ newSet() {// {{{
+ let name = prompt("Name for new preference set")
+ if (!name)
+ return
+
+ name = name.trim()
+ if (name === '')
+ return
+
+ if (name == 'default') {
+ alert(`Name can't be "default".`)
+ return
+ }
+
+ const exists = this.sets.some(s => s.name.toLowerCase() == name.toLowerCase())
+ if (exists) {
+ alert(`Set with name "${name}" already exist.`)
+ return
+ }
+
+ this.sets.push(new N2PreferenceSet(name, {}))
+ this.preferencesModified()
+ this.render()
+ }// }}}
+ preferencesModified() {// {{{
+ this.elSave.removeAttribute('disabled')
+ }// }}}
+ preferencesDelete(deleteSet) {// {{{
+ if (deleteSet.name == 'default') {
+ alert("Can't delete the default set.")
+ return
+ }
+
+ if (!confirm(`Confirm deleting "${deleteSet.name}"`))
+ return
+
+ this.sets = this.sets.filter(set => {
+ return !(set.name === deleteSet.name)
+ })
+
+ this.preferencesModified()
+ this.render()
+ }// }}}
+ async save() {// {{{
+ try {
+ let newPrefs = {}
+ this.sets.forEach(s => {
+ const setState = s.getState()
+ newPrefs[setState.name] = setState.state
+ })
+
+ // Throws exception on both HTTP and application errors.
+ await API.query('POST', '/user/preferences', newPrefs)
+
+ const userData = localStorage.getItem('user')
+ const user = JSON.parse(userData)
+ user.Preferences = newPrefs
+ localStorage.setItem('user', JSON.stringify(user))
+ localStorage.setItem('device_preference_set', this.elDevPreferenceSet.value)
+ _mbus.dispatch('DEVICE_PREFERENCE_SET_UPDATED')
+ } catch (e) {
+ console.error(e)
+ alert(e.message)
+ } finally {
+ this.elSave.setAttribute('disabled', true)
+ }
+
+ }// }}}
+}
+customElements.define('n2-pagepreferences', N2PagePreferences)
+
+// Preferences is a set of preferences, of which there can be many named.
+export class N2PreferenceSet extends CustomHTMLElement {
+ static {// {{{
+ this.tmpl = document.createElement('template')
+ this.tmpl.innerHTML = `
+
+
+
+
+
+
+
+
+
+ `
+ }// }}}
+ constructor(name, data) {// {{{
+ super(true)
+ this.name = name
+ this.data = data
+ this.render()
+
+ // Enable the save button when settings are modified.
+ this.allFields().forEach(f =>
+ f.addEventListener('input', () => _mbus.dispatch('PREFERENCE_SET_MODIFIED'))
+ )
+
+ this.elName.addEventListener('click', () => this.updateName())
+ this.elDelete.addEventListener('click', () => this.deleteSet())
+ }// }}}
+ updateName() {// {{{
+ if (this.name == 'default') {
+ alert('Can not change name of the default profile.')
+ return
+ }
+
+ const name = prompt("Change name", this.name)
+ if (!name)
+ return
+
+ this.name = name
+ this.render()
+ _mbus.dispatch('PREFERENCE_SET_MODIFIED')
+ }// }}}
+ deleteSet() {// {{{
+ _mbus.dispatch('PREFERENCE_SET_DELETE', { set: this })
+ }// }}}
+ render() {// {{{
+ this.elName.innerText = this.name
+
+ this.fieldDownloadImages.checked = this.data.DownloadImages
+ this.fieldDownloadFiles.checked = this.data.DownloadFiles
+ }// }}}
+ getState() {// {{{
+ const name = this.name.trim()
+ if (name === '')
+ throw new Error('Name can not be empty.')
+
+ return {
+ name: this.name.trim(),
+ state: this.fieldValues(),
+ }
+ }// }}}
+}
+customElements.define('n2-preferenceset', N2PreferenceSet)
diff --git a/static/js/page_storage.mjs b/static/js/page_storage.mjs
index 931a718..a007130 100644
--- a/static/js/page_storage.mjs
+++ b/static/js/page_storage.mjs
@@ -13,7 +13,10 @@ export class N2PageStorage extends CustomHTMLElement {
constructor() {
super()
- window._mbus.subscribe('SHOW_PAGE', () => this.render())
+ window._mbus.subscribe('SHOW_PAGE', event => {
+ if (event.detail.data?.page == 'storage')
+ this.render()
+ })
}
async render() {
const countNodes = await globalThis.nodeStore.nodeCount()
diff --git a/static/js/sidebar.mjs b/static/js/sidebar.mjs
index 7d73d6a..6cd5814 100644
--- a/static/js/sidebar.mjs
+++ b/static/js/sidebar.mjs
@@ -1,4 +1,5 @@
-import { ROOT_NODE } from 'node_store'
+import { ROOT_NODE, ORPHANED_NODE, DELETED_NODE } from 'node_store'
+import { Node } from 'node'
import { CustomHTMLElement } from './lib/custom_html_element.mjs'
import { Color, Solver } from './lib/css_colorize.mjs'
@@ -127,6 +128,7 @@ export class N2Sidebar extends CustomHTMLElement {
this.elSearch.addEventListener('click', () => _mbus.dispatch('op-search'))
this.elSync.addEventListener('click', () => _sync.run())
this.elLogo.addEventListener('click', () => _app.goToNode(ROOT_NODE, false, false))
+ this.elSettings.addEventListener('click', ()=> _mbus.dispatch('SHOW_PAGE', { page: 'preferences' }))
this.elHideTree.addEventListener('click', event => {
event.stopPropagation()
_mbus.dispatch('TREE_EXPANSION', { expand: false })
@@ -156,8 +158,26 @@ export class N2Sidebar extends CustomHTMLElement {
this.expandedNodes[ROOT_NODE] = true
const startnode = await nodeStore.get(ROOT_NODE)
const starttreenode = new N2TreeNode(this, startnode, null)
+
+ const deletednode = await nodeStore.get(DELETED_NODE)
+ const deletedtreenode = new SpecialNodeDeleted(this, deletednode, null)
+
+ const orphanednode = await nodeStore.get(ORPHANED_NODE)
+ const orphanedtreenode = new SpecialNodeOrphaned(this, orphanednode, null)
+
+ startnode._sibling_after = deletednode
+ deletednode._sibling_before = startnode
+
+ deletednode._sibling_after = orphanednode
+ orphanednode._sibling_before = deletednode
+
this.treeNodeComponents[startnode.UUID] = starttreenode
+ this.treeNodeComponents[deletednode.UUID] = deletedtreenode
+ this.treeNodeComponents[orphanednode.UUID] = orphanedtreenode
+
this.elTreenodes.appendChild(await starttreenode.render())
+ this.elTreenodes.appendChild(await deletedtreenode.render())
+ this.elTreenodes.appendChild(await orphanedtreenode.render())
// Notify the application that the initial tree is rendered (with children)
// and that initial node selection can take place. App will check URL to
@@ -178,9 +198,8 @@ export class N2Sidebar extends CustomHTMLElement {
this.expandedNodes[UUID] = false
return this.expandedNodes[UUID]
}//}}}
- setNodeExpanded(node, value) {//{{{
+ async setNodeExpanded(node, value) {//{{{
let expanded = this.expandedNodes[node.UUID]
-
if (expanded === undefined) {
this.expandedNodes[node.UUID] = false
expanded = false
@@ -230,8 +249,6 @@ export class N2Sidebar extends CustomHTMLElement {
// Holding shift down does it recursively.
case Space:
case 'Enter':
- if (n.UUID === ROOT_NODE)
- return
const expanded = this.getNodeExpanded(n.UUID)
if (event.shiftKey) {
this.recursiveExpand(n, !expanded)
@@ -240,38 +257,31 @@ export class N2Sidebar extends CustomHTMLElement {
}
break
- case 'g':
case 'Home':
this.navigateTop()
break
- case 'G':
case 'End':
this.navigateBottom()
break
- case 'j':
case 'ArrowDown':
await this.navigateDown(this.selectedNode)
break
- case 'k':
case 'ArrowUp':
await this.navigateUp(this.selectedNode)
break
- case 'h':
case 'ArrowLeft':
await this.navigateLeft(this.selectedNode)
break
- case 'l':
case 'ArrowRight':
await this.navigateRight(this.selectedNode)
break
default:
- // nonsole.log(event.key)
handled = false
}
@@ -393,23 +403,26 @@ export class N2Sidebar extends CustomHTMLElement {
}//}}}
async navigateTop() {//{{{
const root = await nodeStore.get(ROOT_NODE)
- if (root.Children.length === 0)
- return
- _mbus.dispatch("GO_TO_NODE", { nodeUUID: root.Children[0]?.UUID, dontPush: false, dontExpand: true })
+ _mbus.dispatch("GO_TO_NODE", { nodeUUID: root.UUID, dontPush: false, dontExpand: true })
}//}}}
async navigateBottom() {//{{{
- const root = await nodeStore.get(ROOT_NODE)
- if (root.Children.length === 0)
- return
+ const orphaned = await nodeStore.get(ORPHANED_NODE)
- const toplevel = root.Children[root.Children.length - 1]
+ if (!orphaned.hasChildren() || this.getNodeExpanded(orphaned.UUID)) {
+ _mbus.dispatch("GO_TO_NODE", { nodeUUID: orphaned.UUID, dontPush: false, dontExpand: true })
+ return
+ }
+
+ /* TODO - fix this when orphaned nodes are implemented.
+ const toplevel = orphaned.Children[orphaned.Children.length - 1]
const toplevelExpanded = this.getNodeExpanded(toplevel?.UUID)
if (toplevelExpanded) {
const lastnode = this.getLastExpandedNode(toplevel)
_mbus.dispatch("GO_TO_NODE", { nodeUUID: lastnode?.UUID, dontPush: false, dontExpand: true })
} else
- _mbus.dispatch("GO_TO_NODE", { nodeUUID: root.Children[root.Children.length - 1]?.UUID, dontPush: false, dontExpand: true })
+ _mbus.dispatch("GO_TO_NODE", { nodeUUID: orphaned.Children[orphaned.Children.length - 1]?.UUID, dontPush: false, dontExpand: true })
+ */
}//}}}
getParentWithNextSibling(node) {//{{{
@@ -430,6 +443,10 @@ export class N2Sidebar extends CustomHTMLElement {
if (state)
await this.setNodeExpanded(node, true)
+ // An expanded node needs to have its children fetched.
+ if (!node.hasFetchedChildren())
+ await node.fetchChildren()
+
for (const child of node.Children)
await this.recursiveExpand(child, state)
@@ -449,15 +466,22 @@ export class N2Sidebar extends CustomHTMLElement {
treenode?.scrollIntoView({ block: 'nearest' })
}// }}}
}
-customElements.define('n2-sidebar', N2Sidebar)
export class N2TreeNode extends CustomHTMLElement {
+ static DRAG_ICON = new Image()
+ static DRAG_ICON_OK = new Image()
+
static {// {{{
+ N2TreeNode.DRAG_ICON.src = `/images/${_VERSION}/leaf.svg`
+ N2TreeNode.DRAG_ICON_OK.src = `/images/${_VERSION}/expanded.svg`
+
this.tmpl = document.createElement('template')
this.tmpl.innerHTML = `
-
![]()
+
@@ -490,6 +564,7 @@ export class N2TreeNode extends CustomHTMLElement {
constructor(sidebar, node, parent) {//{{{
super()
+ this.setAttribute('draggable', 'true')
this.classList.add('node')
this.sidebar = sidebar
@@ -498,13 +573,100 @@ export class N2TreeNode extends CustomHTMLElement {
this.children_populated = false
this.rendered = false
+ this.dragNode = null
- this.elExpandToggle.addEventListener('click', () => this.sidebar.setNodeExpanded(this.node, !this.sidebar.getNodeExpanded(this.node.UUID)))
+ this.elExpandToggle.addEventListener('click', event => {
+ if (this.node.hasChildren())
+ this.expandNode(event)
+ else
+ _mbus.dispatch('TREE_NODE_SELECTED', this.node)
+ })
this.elName.addEventListener('click', () => _mbus.dispatch('TREE_NODE_SELECTED', this.node))
_mbus.subscribe(`NODE_EXPAND_${node.UUID}`, _state => {
this.render(true)
})
+
+ // Drag-and-dropping of nodes
+ this.addEventListener('dragstart', event => this.dragStart(event))
+ this.addEventListener('dragend', event => this.dragEnd(event))
+ this.addEventListener('dragover', event => this.dragOver(event))
+ this.addEventListener('drop', event => this.dragDrop(event))
+ this.elName.addEventListener('dragenter', event => this.dragEnter(event))
+ this.elName.addEventListener('dragleave', event => this.dragLeave(event))
+ }// }}}
+
+ dragStart(e) {// {{{
+ if (this.node.isModified()) {
+ alert('Save note before moving it.')
+ e.stopPropagation()
+ e.preventDefault()
+ return
+ }
+
+ this.classList.add('drag-source')
+ const blankPixel = new Image()
+ blankPixel.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
+ e.dataTransfer.setDragImage(blankPixel, 0, 0)
+ e.dataTransfer.allowedEffects = 'none'
+ e.stopPropagation()
+ _app.dragIcon.setSource(this)
+ _app.dragIcon.start()
+ }// }}}
+ dragEnd(e) {// {{{
+ this.classList.remove('drag-source')
+ _app.dragIcon.end()
+ e.stopPropagation()
+ }// }}}
+ dragOver(e) {// {{{
+ e.dataTransfer.dropEffect = 'move'
+ e.preventDefault()
+ }// }}}
+ async dragDrop(e) {// {{{
+ try {
+ e.stopPropagation()
+ const sourceNode = _app.dragIcon.getSource()
+
+ // Abort if user drops the node back on itself.
+ if (sourceNode.node.UUID === this.node.UUID)
+ return
+
+ await _app.moveNode(sourceNode.node, this.node.UUID)
+
+ _app.sidebar.setNodeExpanded(this, true)
+ await this.render(true, true)
+ await sourceNode.render(true, true)
+ } catch (e) {
+ console.error(e)
+ alert(e)
+ } finally {
+ this.dragLeave(e)
+ }
+ }// }}}
+ dragEnter(e) {// {{{
+ const targetNode = e.target.closest('n2-treenode')
+ if (targetNode.classList.contains('drag-source'))
+ return
+ e.stopPropagation()
+ _app.dragIcon.icon('ok')
+ this.classList.add('drag-target')
+ }// }}}
+ dragLeave(e) {// {{{
+ e.stopPropagation()
+ e.dataTransfer.dropEffect = 'none'
+ e.dataTransfer.setDragImage(N2TreeNode.DRAG_ICON, -16, 8)
+ _app.dragIcon.icon('')
+ this.classList.remove('drag-target')
+ }// }}}
+
+ async expandNode(event) {// {{{
+ const expanded = _app.sidebar.getNodeExpanded(this.node.UUID)
+
+ if (event.shiftKey) {
+ _app.sidebar.recursiveExpand(this.node, !expanded)
+ } else {
+ _app.sidebar.setNodeExpanded(this.node, !expanded)
+ }
}// }}}
async fetchChildren(force_fetch) {//{{{
if (this.children_populated && !force_fetch)
@@ -541,6 +703,17 @@ export class N2TreeNode extends CustomHTMLElement {
// The expand icon
is only changed to not get a flickering when re-rendering.
if (this.node.UUID === ROOT_NODE)
this.setImgSrc(this.elExpand, `/images/${window._VERSION}/icon_home.svg`)
+
+ else if (this.node.UUID === DELETED_NODE) {
+ this.setImgSrc(this.elExpand, `/images/${window._VERSION}/leaf_deleted.svg`)
+ this.elExpand.classList.add('deleted')
+ }
+
+ else if (this.node.UUID === ORPHANED_NODE) {
+ this.setImgSrc(this.elExpand, `/images/${window._VERSION}/leaf_orphaned.svg`)
+ this.elExpand.classList.add('deleted')
+ }
+
else if (!this.node.hasChildren())
this.setImgSrc(this.elExpand, `/images/${window._VERSION}/leaf.svg`)
else if (this.sidebar.getNodeExpanded(this.node.UUID))
@@ -575,6 +748,24 @@ export class N2TreeNode extends CustomHTMLElement {
img.setAttribute('src', newSrc)
}// }}}
}
+
+class SpecialNodeDeleted extends N2TreeNode {
+ constructor(sidebar, node, parent) {//{{{
+ super(sidebar, node, parent)
+ this.removeAttribute('draggable')
+ }//}}}
+}
+
+class SpecialNodeOrphaned extends N2TreeNode {
+ constructor(sidebar, node, parent) {//{{{
+ super(sidebar, node, parent)
+ this.removeAttribute('draggable')
+ }//}}}
+}
+
+customElements.define('n2-sidebar', N2Sidebar)
customElements.define('n2-treenode', N2TreeNode)
+customElements.define('n2-specialnodedeleted', SpecialNodeDeleted)
+customElements.define('n2-specialnodeorphaned', SpecialNodeOrphaned)
// vim: foldmethod=marker
diff --git a/static/js/sync.mjs b/static/js/sync.mjs
index fe72c3f..daa603f 100644
--- a/static/js/sync.mjs
+++ b/static/js/sync.mjs
@@ -90,6 +90,7 @@ export class Sync {
nodeStore.setAppState('latest_sync_node', currMax)
} catch (e) {
console.error('sync node tree', e)
+ alert(e.message)
} finally {
syncEnd = Date.now()
const duration = (syncEnd - syncStart) / 1000
@@ -157,8 +158,8 @@ export class Sync {
_mbus.dispatch('SYNC_UPLOADED', { count: nodesToSend.length })
} catch (e) {
- console.trace(e)
- alert(e.error)
+ console.error(e)
+ alert(e.message)
return
}
}
diff --git a/user.go b/user.go
deleted file mode 100644
index b1c2abf..0000000
--- a/user.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package main
-
-import (
- // External
- "github.com/golang-jwt/jwt/v5"
-)
-
-type UserSession struct {
- UserID int
- Username string
- Password string
- Name string
- ClientUUID string
-}
-
-func NewUser(claims jwt.MapClaims) (u UserSession) {
- uid, _ := claims["uid"].(float64)
- name, _ := claims["name"].(string)
- username, _ := claims["login"].(string)
- clientUUID, _ := claims["cid"].(string)
-
- u.UserID = int(uid)
- u.Username = username
- u.Name = name
- u.ClientUUID = clientUUID
- return
-}
diff --git a/user/pkg.go b/user/pkg.go
new file mode 100644
index 0000000..bcdfac8
--- /dev/null
+++ b/user/pkg.go
@@ -0,0 +1,63 @@
+package user
+
+import (
+ // External
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/jmoiron/sqlx"
+
+ // Standard
+ "encoding/json"
+)
+
+type User struct {
+ ID int
+ Username string
+ Name string
+ Preferences map[string]UserPreferences
+}
+
+type UserSession struct {
+ UserID int
+ Username string
+ Password string
+ Name string
+ ClientUUID string
+ Db *sqlx.DB
+}
+
+type UserPreferences struct {
+ DownloadImages bool
+ DownloadFiles bool
+}
+
+func NewUser(claims jwt.MapClaims) (u UserSession) {
+ uid, _ := claims["uid"].(float64)
+ name, _ := claims["name"].(string)
+ username, _ := claims["login"].(string)
+ clientUUID, _ := claims["cid"].(string)
+
+ u.UserID = int(uid)
+ u.Username = username
+ u.Name = name
+ u.ClientUUID = clientUUID
+ return
+}
+
+func (u UserSession) Preferences() (prefs map[string]UserPreferences, err error) {
+ row := u.Db.QueryRow(`SELECT preferences FROM public.user WHERE id=$1`, u.UserID)
+
+ var data []byte
+ err = row.Scan(&data)
+ if err != nil {
+ return
+ }
+
+ err = json.Unmarshal(data, &prefs)
+ return
+}
+
+func (u UserSession) SetPreferences(prefs map[string]UserPreferences) (err error) {
+ j, _ := json.Marshal(prefs)
+ _, err = u.Db.Exec(`UPDATE public.user SET preferences=$2 WHERE id=$1`, u.UserID, j)
+ return
+}
diff --git a/views/pages/notes2.gotmpl b/views/pages/notes2.gotmpl
index abec2b0..2755aea 100644
--- a/views/pages/notes2.gotmpl
+++ b/views/pages/notes2.gotmpl
@@ -1,6 +1,12 @@
{{ define "page" }}
+
+
+
+
+
+
-
-
-
-