Skip to content

Commit

Permalink
feat: insert new node on enter
Browse files Browse the repository at this point in the history
  • Loading branch information
sorax committed Dec 12, 2023
1 parent d6ea02d commit 613a0ab
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
30 changes: 27 additions & 3 deletions assets/js/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
import { createNode } from "./node";
import { createNode, focusNode } from "./node"

export const Hooks = {
outline: {
mounted() {
const container: HTMLElement = this.el

container.addEventListener("keydown", (event) => {
container.addEventListener("keydown", (event: KeyboardEvent) => {
const selection = window.getSelection()
const range = selection?.getRangeAt(0)

switch (event.key) {
case "Enter":
event.preventDefault()

const splitPos = range?.endOffset || 0

const target = <HTMLElement>event.target
const parent = target.parentElement!

const content = target.textContent || ""
const contentBefore = content.substring(0, splitPos)
const contentAfter = content.substring(splitPos)

const node = createNode({ content: contentAfter })
parent.after(node)

target.textContent = contentBefore

focusNode(node)
break
}
})

container.addEventListener("keyup", (event) => {
Expand All @@ -15,7 +39,7 @@ export const Hooks = {
nodes.forEach(node => {
const li = createNode(node)
container.prepend(li)
});
})
})
}
}
Expand Down
7 changes: 6 additions & 1 deletion assets/js/hooks/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ interface Node {

export function createNode({ uuid, content }: Node) {
const input = document.createElement("div")
input.innerText = content || ""
input.textContent = content || ""
input.contentEditable = "plaintext-only"

const node = document.createElement("li")
Expand All @@ -18,3 +18,8 @@ export function createNode({ uuid, content }: Node) {

return node
}

export function focusNode(node: HTMLElement) {
const input = node.firstChild as HTMLElement
input.focus()
}

0 comments on commit 613a0ab

Please sign in to comment.