5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-26 16:56:22 +00:00
panel/app/javascript/editor/editor.js

536 lines
15 KiB
JavaScript
Raw Permalink Normal View History

import {
moveChildren,
marks,
blocks,
parentBlocks,
typesWithProperties,
setAuxiliaryToolbar,
tagNameSetFn
} from 'editor/types'
2020-11-13 21:38:02 +00:00
const origin = location.origin
2020-11-03 21:16:59 +00:00
/*
* Guarda una copia local de los cambios para poder recuperarlos
* después.
*
* Usamos la URL completa sin anchors.
*/
const storageKey = (editorEl) => editorEl.querySelector('[data-target="storage-key"]').value
const forgetContent = (storedKey) => window.localStorage.removeItem(storedKey)
const storeContent = (editorEl, contentEl) => {
if (contentEl.innerText.trim().length === 0) return
window.localStorage.setItem(storageKey(editorEl), contentEl.innerHTML)
}
const restoreContent = (editorEl, contentEl) => {
const content = window.localStorage.getItem(storageKey(editorEl))
if (!content) return
if (content.trim().length === 0) return
contentEl.innerHTML = content
}
2021-02-02 17:20:32 +00:00
/* getRangeAt puede fallar si no hay una selección
*/
const safeGetRangeAt = (num) => {
2021-02-02 17:20:32 +00:00
try {
return window.getSelection().getRangeAt(num)
} catch (error) {
console.warn("No hay una selección!")
return null;
}
}
2020-11-03 21:16:59 +00:00
const isDirectChild = (node, supposedChild) => {
2020-11-03 21:16:59 +00:00
for (const child of node.childNodes) {
if (child == supposedChild) return true
}
}
const isChildSelection = (sel, el) => {
2020-11-03 21:16:59 +00:00
return (
(el.contains(sel.anchorNode) || el.contains(sel.focusNode))
&& !(sel.anchorNode == el || sel.focusNode == el)
)
}
const getElementParent = (node) => {
2020-11-03 21:16:59 +00:00
let parentEl = node
while (parentEl.nodeType != Node.ELEMENT_NODE) parentEl = parentEl.parentElement
return parentEl
}
const splitNode = (node, range) => {
2020-11-03 21:16:59 +00:00
const [left, right] = [
{ range: document.createRange(), node: node.cloneNode(false) },
{ range: document.createRange(), node: node.cloneNode(false) },
]
left.range.setStartBefore(node.firstChild)
left.range.setEnd(range.startContainer, range.startOffset)
left.range.surroundContents(left.node)
right.range.setStart(range.endContainer, range.endOffset)
right.range.setEndAfter(node.lastChild)
right.range.surroundContents(right.node)
//left.node.appendChild(left.range.extractContents())
//left.range.insertNode(left.node)
//right.node.appendChild(right.range.extractContents())
//right.range.insertNode(right.node)
moveChildren(node, node.parentNode, node)
node.parentNode.removeChild(node)
return [left, right]
}
/* Configura un botón que hace una acción inline (ej: negrita).
* Parametros:
* * button: el botón
* * mark: un objeto que representa el tipo de acción (ver types.js)
* * contentEl: el elemento de contenido del editor.
*/
const setupMarkButton = (button, mark, contentEl) => {
2020-11-03 21:16:59 +00:00
button.addEventListener("click", event => {
event.preventDefault()
const sel = window.getSelection()
if (!isChildSelection(sel, contentEl)) return
let parentEl = getElementParent(sel.anchorNode)
//if (sel.anchorNode == parentEl) parentEl = parentEl.firstChild
2021-02-02 17:20:32 +00:00
const range = safeGetRangeAt(0)
if (!range) return
2020-11-03 21:16:59 +00:00
if (parentEl.matches(mark.selector)) {
2020-11-03 21:16:59 +00:00
const [left, right] = splitNode(parentEl, range)
right.range.insertNode(range.extractContents())
const selectionRange = document.createRange()
selectionRange.setStartAfter(left.node)
selectionRange.setEndBefore(right.node)
sel.removeAllRanges()
sel.addRange(selectionRange)
} else {
for (const child of parentEl.childNodes) {
if (
(child instanceof Element)
&& child.matches(mark.selector)
&& sel.containsNode(child)
) {
2020-11-03 21:16:59 +00:00
moveChildren(child, parentEl, child)
parentEl.removeChild(child)
// TODO: agregar a selección
return
}
}
const tagEl = mark.createFn()
try {
range.surroundContents(tagEl)
} catch (error) {
// TODO: mostrar error
return console.error("No puedo marcar cosas a través de distintos bloques!")
}
for (const child of tagEl.childNodes) {
if (child instanceof Element && child.matches(mark.selector)) {
2020-11-03 21:16:59 +00:00
moveChildren(child, tagEl, child)
tagEl.removeChild(child)
}
}
range.insertNode(tagEl)
range.selectNode(tagEl)
}
})
}
/* Igual que `setupMarkButton` pero para bloques. */
const setupBlockButton = (button, block, contentEl, editorEl) => {
2020-11-03 21:16:59 +00:00
button.addEventListener("click", event => {
event.preventDefault()
const sel = window.getSelection()
// TODO: mostrar error
if (
!contentEl.contains(sel.anchorNode)
|| !contentEl.contains(sel.focusNode)
|| sel.anchorNode == contentEl
|| sel.focusNode == contentEl
) return
2021-02-02 17:20:32 +00:00
const range = safeGetRangeAt(0)
if (!range) return
2020-11-03 21:16:59 +00:00
let parentEl = sel.anchorNode
while (!isDirectChild(contentEl, parentEl)) parentEl = parentEl.parentElement
if (block.setFn) {
if (parentEl.matches(block.selector)) {
2020-11-03 21:16:59 +00:00
tagNameSetFn("P")(parentEl)
} else {
block.setFn(parentEl)
}
} else if (block.createFn) {
const newEl = block.createFn(editorEl)
parentEl.parentElement.insertBefore(newEl, parentEl.nextSibling)
newEl.click()
2020-11-03 21:16:59 +00:00
}
})
}
/* Igual que `setupBlockButton` pero para bloques parientes. */
const setupParentBlockButton = (button, parentBlock, contentEl) => {
2020-11-03 21:16:59 +00:00
button.addEventListener("click", event => {
event.preventDefault()
const sel = window.getSelection()
if (
!contentEl.contains(sel.anchorNode)
|| !contentEl.contains(sel.focusNode)
|| sel.anchorNode == contentEl
|| sel.focusNode == contentEl
) return
2021-02-02 17:20:32 +00:00
const range = safeGetRangeAt(0)
if (!range) return
2020-11-03 21:16:59 +00:00
let parentEl = sel.anchorNode
while (!isDirectChild(contentEl, parentEl)) parentEl = parentEl.parentElement
if (parentEl.matches(parentBlock.selector)) {
2020-11-03 21:16:59 +00:00
moveChildren(parentEl, parentEl.parentElement, parentEl)
parentEl.parentElement.removeChild(parentEl)
} else if (elementIsParentBlock(parentEl)) {
const el = parentBlock.createFn()
moveChildren(parentEl, el, null)
parentEl.parentElement.insertBefore(el, parentEl)
parentEl.parentElement.removeChild(parentEl)
} else {
const el = parentBlock.createFn()
parentEl.parentElement.insertBefore(el, parentEl)
el.appendChild(parentEl)
}
})
}
const elementIsTypes = types => element => {
for (const type of Object.values(types)) {
if (element.matches(type.selector)) return true
2020-11-03 21:16:59 +00:00
}
return false
}
const elementIsBlock = elementIsTypes(blocks)
const elementIsParentBlock = elementIsTypes(parentBlocks)
const hasContent = (element) => {
2020-11-03 21:16:59 +00:00
if (element.firstElementChild) return true
for (const child of element.childNodes) {
if (child.nodeType === Node.TEXT_NODE && child.data.length > 0) return true
else if (child.hasChildNodes() && hasContent(child)) return true
}
// TODO: verificar que los elementos tiene contenido
if (element.tagName === "IMG"
|| element.tagName === "AUDIO"
|| element.tagName === "VIDEO"
2021-02-02 17:00:42 +00:00
|| element.tagName === "IFRAME"
|| element.tagName === "BR") return true
2020-11-03 21:16:59 +00:00
return false
}
/* Limpia el elemento de contenido del editor
* Por ahora:
* * Cambia el tag de los bloques no reconocidos (ver `elementIsBlock`)
* * Hace lo que hace cleanNode
*/
const cleanContent = (contentEl) => {
2020-11-03 21:16:59 +00:00
const sel = window.getSelection()
2020-11-06 14:48:37 +00:00
cleanNode(contentEl, contentEl)
2020-11-03 21:16:59 +00:00
for (const child of contentEl.childNodes) {
if (child.tagName) {
if (elementIsParentBlock(child)) {
cleanContent(child)
} else if (!elementIsBlock(child)) {
2021-02-02 19:48:47 +00:00
const el = document.createElement("p")
moveChildren(child, el, null)
contentEl.insertBefore(el, child)
child.parentNode.removeChild(child)
2020-11-03 21:16:59 +00:00
}
} else if (child.nodeType === Node.TEXT_NODE) {
const el = document.createElement("p")
contentEl.insertBefore(el, child.nextSibling)
el.appendChild(child)
sel.collapse(el, el.textContent.length)
2020-11-03 21:16:59 +00:00
}
}
}
/* Arregla cosas en el elemento de contendo del editor
* Por ahora:
* * Crea un p y inserta la selección si no hay elementos
* * Wrappea el contenido de un UL o OL en un LI si no lo está
*/
const fixContent = (contentEl) => {
2020-11-03 21:16:59 +00:00
for (const child of contentEl.childNodes) {
if (child.tagName) {
if (elementIsParentBlock(child)) {
fixContent(child)
} else if (child.tagName === "UL" || child.tagName === "OL") {
let notItems = []
for (const item of child.childNodes) {
if (item.tagName !== "LI") notItems.push(item)
}
2020-11-06 14:48:37 +00:00
2020-11-03 21:16:59 +00:00
if (notItems.length) {
const item = document.createElement("li")
item.append(...notItems)
child.appendChild(item)
}
}
}
}
}
/* Recursivamente "limpia" los nodos a partir del llamado.
* Por ahora:
* * Junta nodos de texto que están al lado
* * Junta nodos de la misma "mark" que están al lado
* * Borra elementos sin contenido (ver `hasContent`) y no están seleccionados
2020-11-16 20:06:47 +00:00
* * Borra inline styles no autorizados
* * Borra propiedades de IMG no autorizadas
* * Borra <FONT> y <STYLE>
2020-11-03 21:16:59 +00:00
*/
const cleanNode = (node, contentEl) => {
2020-11-03 21:16:59 +00:00
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
if (child.nextSibling && child.nextSibling.nodeType === Node.TEXT_NODE) {
// Juntar nodos
child.data += child.nextSibling.data
child.parentNode.removeChild(child.nextSibling)
}
} else if (child.nodeType === Node.ELEMENT_NODE) {
2021-02-02 17:20:32 +00:00
const range = safeGetRangeAt(0)
if (!hasContent(child) && (!range || !range.intersectsNode(child)))
2020-11-03 21:16:59 +00:00
child.parentNode.removeChild(child)
for (const mark of Object.values(marks)) {
if (
child.matches(mark.selector)
&& child.nextSibling
&& (child.nextSibling instanceof Element)
&& child.nextSibling.matches(mark.selector)
) {
2020-11-03 21:16:59 +00:00
moveChildren(child.nextSibling, child, null)
child.nextSibling.parentNode.removeChild(child.nextSibling)
}
}
2020-11-06 14:48:37 +00:00
if (child.tagName === "LI") {
let parentEl = child
while (
parentEl
&& !(parentEl.nodeType == Node.ELEMENT_NODE && elementIsBlock(parentEl))
&& contentEl.contains(parentEl)
)
parentEl = parentEl.parentElement
2020-11-16 23:49:23 +00:00
2020-11-06 14:48:37 +00:00
if (
parentEl
&& contentEl.contains(parentEl)
&& parentEl.tagName !== "UL"
&& parentEl.tagName !== "OL"
)
moveChildren(child, parentEl, child.nextSibling)
2020-11-16 20:06:47 +00:00
} else if (child.tagName === "IMG") {
if (child.getAttribute("width")) child.removeAttribute("width")
if (child.getAttribute("height")) child.removeAttribute("height")
if (child.getAttribute("vspace")) child.removeAttribute("vspace")
if (child.getAttribute("hspace")) child.removeAttribute("hspace")
if (child.align.length) child.removeAttribute("align")
if (child.name.length) child.removeAttribute("name")
2020-11-18 16:38:24 +00:00
if (!child.src.length) child.src = "/placeholder.png"
2020-11-16 20:06:47 +00:00
} else if (child.tagName === "FONT") {
moveChildren(child, child.parentElement, child.nextSiling)
child.parentElement.removeChild(child)
return
} else if (child.tagName === "STYLE") {
2020-11-19 01:37:06 +00:00
return child.parentElement.removeChild(child)
} else if (child.tagName === "B") {
const el = document.createElement("STRONG")
moveChildren(child, el)
child.parentElement.insertBefore(el, child)
child.parentElement.removeChild(child)
} else if (child.tagName === "I") {
const el = document.createElement("EM")
moveChildren(child, el)
child.parentElement.insertBefore(el, child)
2020-11-16 20:06:47 +00:00
child.parentElement.removeChild(child)
}
child.style.forEach(prop => {
const value = child.style[prop]
2020-11-16 20:06:47 +00:00
switch (prop) {
2020-11-17 16:01:17 +00:00
case 'background-color':
if (child.tagName === "MARK") return
2020-11-17 16:01:17 +00:00
default:
child.style[prop] = ""
2020-11-16 20:06:47 +00:00
}
})
2020-11-03 21:16:59 +00:00
}
2020-11-06 14:48:37 +00:00
cleanNode(child, contentEl)
2020-11-03 21:16:59 +00:00
}
}
2020-11-16 19:31:05 +00:00
/* Generar el clickListener para este editor.
*/
const generateClickListener = (editorEl, contentEl) => {
2020-11-16 19:31:05 +00:00
/* El event listener para los typesWithProperties.
*/
return (event) => {
2020-11-16 19:31:05 +00:00
// Borrar todas las selecciones
for (const el of contentEl.querySelectorAll(".selected")) {
el.classList.remove("selected")
}
setAuxiliaryToolbar(editorEl)
let selectedType
let selectedEl
for (const [name, type] of Object.entries(typesWithProperties)) {
type.disableInput(editorEl)
let el = event.target
while (el && !el.matches(type.selector)) el = el.parentElement
if (el && contentEl.contains(el)) {
selectedType = type
selectedEl = el
}
}
if (selectedType) {
event.preventDefault()
selectedType.updateInput(selectedEl, editorEl)
selectedEl.classList.add("selected")
2020-11-16 19:31:05 +00:00
return false
}
}
}
const setupEditor = (editorEl) => {
2020-11-09 18:25:06 +00:00
// XXX: ¡Esto afecta a todo el documento! ¿Quizás usar un iframe para el editor?
document.execCommand('defaultParagraphSeparator', false, 'p')
2020-11-03 21:16:59 +00:00
const contentEl = editorEl.querySelector(".editor-content")
2020-11-19 01:51:15 +00:00
contentEl.addEventListener("paste", event => {
editorEl.querySelector(".editor-aviso-word").style.display = "block"
2020-11-19 01:51:15 +00:00
})
document.addEventListener("selectionchange", event => cleanContent(contentEl))
2020-11-03 21:16:59 +00:00
2020-11-16 19:31:05 +00:00
const clickListener = generateClickListener(editorEl, contentEl)
contentEl.addEventListener("click", clickListener, true)
2020-11-03 21:16:59 +00:00
const htmlEl = editorEl.querySelector("textarea")
const observer = new MutationObserver((mutationList, observer) => {
cleanContent(contentEl)
fixContent(contentEl)
storeContent(editorEl, contentEl)
htmlEl.value = contentEl.innerHTML
2020-11-03 21:16:59 +00:00
})
observer.observe(contentEl, {
childList: true,
attributes: true,
subtree: true,
characterData: true,
})
2020-11-03 21:29:47 +00:00
const editorBtn = id => editorEl.querySelector(`*[data-button="${id}"]`)
2020-11-03 21:16:59 +00:00
// == SETUP BUTTONS ==
for (const [name, mark] of Object.entries(marks)) {
setupMarkButton(editorBtn(name), mark, contentEl)
}
for (const [name, block] of Object.entries(blocks)) {
if (block.noButton) continue
setupBlockButton(editorBtn(name), block, contentEl, editorEl)
}
for (const [name, parentBlock] of Object.entries(parentBlocks)) {
if (parentBlock.noButton) continue
setupParentBlockButton(editorBtn(name), parentBlock, contentEl)
}
for (const [name, type] of Object.entries(typesWithProperties)) {
type.setupInput(editorEl, contentEl)
}
2020-11-13 20:35:12 +00:00
document.addEventListener(editorBtn("mark"), () => setAuxiliaryToolbar(editorEl, "mark"))
document.addEventListener(editorBtn("img"), () => setAuxiliaryToolbar(editorEl, "img"))
document.addEventListener(editorBtn("audio"), () => setAuxiliaryToolbar(editorEl, "audio"))
document.addEventListener(editorBtn("video"), () => setAuxiliaryToolbar(editorEl, "video"))
document.addEventListener(editorBtn("pdf"), () => setAuxiliaryToolbar(editorEl, "pdf"))
2020-11-18 16:37:15 +00:00
document.addEventListener(editorBtn("a"), () => setAuxiliaryToolbar(editorEl, "a"))
2020-11-13 20:35:12 +00:00
2020-11-17 20:36:55 +00:00
for (const video of document.querySelectorAll('.editor .editor-content video')) {
video.addEventListener('click', event => event.target.controls = true)
video.addEventListener('focusout', event => event.target.controls = false)
video.controls = false
2020-11-17 20:36:55 +00:00
}
2020-11-03 21:16:59 +00:00
cleanContent(contentEl)
2020-11-16 19:31:05 +00:00
fixContent(contentEl)
// Recuperar el contenido si hay algo guardado, si tuviéramos un campo
// de última edición podríamos saber si el artículo fue editado
// después o la versión local es la última.
//
// TODO: Preguntar si se lo quiere recuperar.
restoreContent(editorEl, contentEl)
htmlEl.value = contentEl.innerHTML
2020-11-03 21:16:59 +00:00
}
// TODO: por ahora confiamos, quizás queremos filtrar estilos?
const stringifyAllowedStyle = (element) => element.style.cssText
2020-11-03 21:16:59 +00:00
2020-11-13 21:38:02 +00:00
document.addEventListener("turbolinks:load", () => {
2020-11-03 21:16:59 +00:00
for (const editorEl of document.querySelectorAll(".editor")) {
if (!editorEl.querySelector('.editor-toolbar')) continue
2020-11-17 22:18:53 +00:00
2020-11-03 21:16:59 +00:00
setupEditor(editorEl)
}
const flash = document.querySelector('.js-flash[data-target="editor"]')
if (!flash) return
switch (flash.dataset.action) {
case 'forget-content':
if (!flash.dataset.keys) break
2020-11-20 20:24:36 +00:00
try { JSON.parse(flash.dataset.keys).forEach(forgetContent) } catch(e) { undefined }
break
default:
}
})