This commit is contained in:
Philipp Kühn
2021-06-01 17:44:42 +02:00
6 changed files with 211 additions and 31 deletions

View File

@@ -0,0 +1,104 @@
import {
Command,
Node,
nodeInputRule,
} from '@tiptap/core'
export interface FigureOptions {
HTMLAttributes: Record<string, any>,
}
declare module '@tiptap/core' {
interface Commands {
figure: {
/**
* Add a figure element
*/
setFigure: (options: { src: string, alt?: string, title?: string }) => Command,
}
}
}
export const inputRegex = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/
export const Figure = Node.create<FigureOptions>({
name: 'figure',
defaultOptions: {
// inline: false,
HTMLAttributes: {},
},
group: 'block',
content: 'inline*',
draggable: true,
addAttributes() {
return {
src: {
default: null,
parseHTML: element => {
return {
src: element.querySelector('img')?.getAttribute('src'),
}
},
},
alt: {
default: null,
parseHTML: element => {
return {
alt: element.querySelector('img')?.getAttribute('alt'),
}
},
},
title: {
default: null,
parseHTML: element => {
return {
title: element.querySelector('img')?.getAttribute('title'),
}
},
},
}
},
parseHTML() {
return [
{
tag: 'figure',
contentELement: 'figcaption',
},
]
},
renderHTML({ HTMLAttributes }) {
return [
'figure', this.options.HTMLAttributes,
['img', HTMLAttributes],
['figcaption', 0],
]
},
addCommands() {
return {
setFigure: options => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: options,
})
},
}
},
addInputRules() {
return [
nodeInputRule(inputRegex, this.type, match => {
const [, alt, src, title] = match
return { src, alt, title }
}),
]
},
})

View File

@@ -0,0 +1,81 @@
<template>
<div v-if="editor">
<editor-content :editor="editor" />
<h2>HTML</h2>
{{ editor.getHTML() }}
</div>
</template>
<script>
import { Editor, EditorContent } from '@tiptap/vue-2'
import StarterKit from '@tiptap/starter-kit'
import { Figure } from './figure'
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
}
},
mounted() {
this.editor = new Editor({
extensions: [
StarterKit,
Figure,
],
content: `
<p>Figure + Figcaption</p>
<figure>
<img src="https://source.unsplash.com/8xznAGy4HcY/800x400" alt="Random photo of something" title="Whos dat?">
<figcaption>
<p>Amazing caption</p>
</figcaption>
</figure>
<p>Thats it.</p>
`,
})
},
beforeDestroy() {
this.editor.destroy()
},
}
</script>
<style lang="scss" scoped>
::v-deep {
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
figure {
max-width: 25rem;
border: 3px solid #0D0D0D;
border-radius: 0.5rem;
margin: 1rem 0;
padding: 0.5rem;
}
figcaption {
margin-top: 0.25rem;
text-align: center;
padding: 0.5rem;
border: 2px dashed #0D0D0D20;
border-radius: 0.5rem;
}
img {
max-width: 100%;
height: auto;
border-radius: 0.5rem;
}
}
}
</style>