feat: markdown parser for links and lists

This commit is contained in:
Jannat Patel
2024-12-16 16:41:55 +05:30
parent d88aaedf3f
commit 7f44177986
6 changed files with 131 additions and 119 deletions

View File

@@ -1,143 +1,151 @@
export class MarkdownParser {
constructor({ data, api, readOnly, config }) {
console.log('markdownParser constructor called')
this.api = api
this.data = data || {}
this.config = config || {}
this.text = this.data.text || ''
this.text = data.text || ''
this.readOnly = readOnly
}
static get toolbox() {
const app = createApp({
render: () =>
h(UploadIcon, { size: 18, strokeWidth: 1.5, color: 'black' }),
})
const div = document.createElement('div')
app.mount(div)
return {
title: 'Upload',
icon: div.innerHTML,
}
}
static get isReadOnlySupported() {
return true
}
static get conversionConfig() {
return {
export: 'text',
import: 'text',
}
}
render() {
console.log(' render() called')
const container = document.createElement('div')
container.contentEditable = true // Make the div editable like a textarea
container.classList.add('markdown-parser')
container.textContent = this.text
this.wrapper = document.createElement('div')
this.wrapper.classList.add('cdx-block')
this.wrapper.classList.add('ce-paragraph')
this.wrapper.innerHTML = this.text
container.addEventListener('blur', () => {
this.text = container.textContent.trim()
this.parseMarkdown()
})
if (!this.readOnly) {
this.wrapper.contentEditable = true
this.wrapper.innerHTML = this.text
this.textArea = container
return container
this.wrapper.addEventListener('keydown', (event) => {
const value = event.target.textContent
if (event.keyCode === 32 && value.startsWith('#')) {
this.convertToHeader(event, value)
} else if (event.keyCode === 13) {
this.parseContent(event)
}
})
this.wrapper.addEventListener('paste', (event) =>
this.handlePaste(event)
)
}
return this.wrapper
}
convertToHeader(event, value) {
event.preventDefault()
if (['#', '##', '###', '####', '#####', '######'].includes(value)) {
let level = value.length
event.target.textContent = ''
this.convertBlock('header', {
level: level,
})
}
}
parseContent(event) {
event.preventDefault()
const previousLine = this.wrapper.textContent
if (previousLine && this.hasImage(previousLine)) {
this.wrapper.textContent = ''
this.convertBlock('image')
} else if (previousLine && this.hasLink(previousLine)) {
const { text, url } = this.extractLink(previousLine)
const anchorTag = `<a href="${url}" target="_blank">${text}</a>`
this.convertBlock('paragraph', {
text: previousLine.replace(/\[.+?\]\(.+?\)/, anchorTag),
})
} else if (previousLine && previousLine.startsWith('- ')) {
this.convertBlock('list', {
style: 'unordered',
items: [
{
content: previousLine.replace('- ', ''),
},
],
})
} else if (previousLine && previousLine.startsWith('1. ')) {
this.convertBlock('list', {
style: 'ordered',
items: [
{
content: previousLine.replace('1. ', ''),
},
],
})
} else if (previousLine && this.canBeEmbed(previousLine)) {
this.wrapper.textContent = ''
this.convertBlock('embed', {
source: previousLine,
})
}
}
async convertBlock(type, data, index = null) {
const currentIndex = this.api.blocks.getCurrentBlockIndex()
const currentBlock = this.api.blocks.getBlockByIndex(currentIndex)
await this.api.blocks.convert(currentBlock.id, type, data)
this.api.caret.focus(true)
}
handlePaste(event) {
event.preventDefault()
const clipboardData = event.clipboardData || window.clipboardData
const pastedText = clipboardData.getData('text/plain')
const sanitizedText = this.processPastedContent(pastedText)
document.execCommand('insertText', false, sanitizedText)
}
processPastedContent(text) {
return text.trim()
}
save(blockContent) {
return {
text: this.text,
text: blockContent.innerHTML,
}
}
/**
* Parse Markdown text and render Editor.js blocks.
*/
parseMarkdown() {
console.log(' parseMarkdown() called')
const markdown = this.text
const lines = markdown.split('\n')
const blocks = lines.map((line) => {
if (line.startsWith('# ')) {
return {
type: 'header',
data: { text: line.replace('# ', ''), level: 1 },
}
} else if (line.startsWith('## ')) {
return {
type: 'header',
data: { text: line.replace('## ', ''), level: 2 },
}
} else if (line.startsWith('- ')) {
return {
type: 'list',
data: {
items: [line.replace('- ', '')],
style: 'unordered',
},
}
} else if (this.isImage(line)) {
const { alt, url } = this.extractImage(line)
return {
type: 'image',
data: {
file: { url },
caption: alt,
withBorder: false,
stretched: false,
withBackground: false,
},
}
} else if (this.isLink(line)) {
const { text, url } = this.extractLink(line)
return {
type: 'linkTool',
data: { link: url, meta: { title: text } },
}
} else {
return { type: 'paragraph', data: { text: line } }
}
})
this.api.blocks.render({ blocks })
hasImage(line) {
return /!\[.+?\]\(.+?\)/.test(line)
}
/**
* Check if the line matches the image syntax.
* @param {string} line - The line of text.
* @returns {boolean}
*/
isImage(line) {
return /^!\[.*\]\(.*\)$/.test(line)
}
/**
* Extract alt text and URL from the image syntax.
* @param {string} line - The line of text.
* @returns {Object} { alt, url }
*/
extractImage(line) {
const match = line.match(/^!\[(.*)\]\((.*)\)$/)
return { alt: match[1], url: match[2] }
const match = line.match(/!\[(.+?)\]\((.+?)\)/)
if (match) {
return { alt: match[1], url: match[2] }
}
return { alt: '', url: '' }
}
/**
* Check if the line matches the link syntax.
* @param {string} line - The line of text.
* @returns {boolean}
*/
isLink(line) {
return /^\[.*\]\(.*\)$/.test(line)
hasLink(line) {
return /\[.+?\]\(.+?\)/.test(line)
}
/**
* Extract text and URL from the link syntax.
* @param {string} line - The line of text.
* @returns {Object} { text, url }
*/
extractLink(line) {
const match = line.match(/^\[(.*)\]\((.*)\)$/)
return { text: match[1], url: match[2] }
const match = line.match(/\[(.+?)\]\((.+?)\)/)
if (match) {
return { text: match[1], url: match[2] }
}
return { text: '', url: '' }
}
canBeEmbed(line) {
return /^https?:\/\/.+/.test(line)
}
}