improve text style extension
This commit is contained in:
@@ -16,11 +16,17 @@ const FontFamily = createExtension({
|
||||
attributes: {
|
||||
fontFamily: {
|
||||
default: null,
|
||||
renderHTML: attributes => ({
|
||||
style: `font-family: ${attributes.fontFamily}`,
|
||||
}),
|
||||
renderHTML: attributes => {
|
||||
if (!attributes.fontFamily) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return {
|
||||
style: `font-family: ${attributes.fontFamily}`,
|
||||
}
|
||||
},
|
||||
parseHTML: element => ({
|
||||
fontFamily: element.style.fontFamily,
|
||||
fontFamily: element.style.fontFamily.replace(/['"]+/g, ''),
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -30,8 +36,11 @@ const FontFamily = createExtension({
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
fontFamily: (fontFamily: string): Command => ({ commands }) => {
|
||||
return commands.updateMarkAttributes('textStyle', { fontFamily })
|
||||
fontFamily: (fontFamily: string | null = null): Command => ({ chain }) => {
|
||||
return chain()
|
||||
.updateMarkAttributes('textStyle', { fontFamily })
|
||||
.removeEmptyTextStyle()
|
||||
.run()
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createMark } from '@tiptap/core'
|
||||
import { Command, createMark, getMarkAttrs } from '@tiptap/core'
|
||||
|
||||
const TextStyle = createMark({
|
||||
name: 'textStyle',
|
||||
@@ -7,6 +7,15 @@ const TextStyle = createMark({
|
||||
return [
|
||||
{
|
||||
tag: 'span',
|
||||
getAttrs: element => {
|
||||
const hasStyles = (element as HTMLElement).hasAttribute('style')
|
||||
|
||||
if (!hasStyles) {
|
||||
return false
|
||||
}
|
||||
|
||||
return {}
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
@@ -14,6 +23,22 @@ const TextStyle = createMark({
|
||||
renderHTML({ attributes }) {
|
||||
return ['span', attributes, 0]
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
removeEmptyTextStyle: (): Command => ({ state, commands }) => {
|
||||
const attributes = getMarkAttrs(state, this.type)
|
||||
const hasStyles = Object.entries(attributes).every(([, value]) => !!value)
|
||||
|
||||
if (hasStyles) {
|
||||
return true
|
||||
}
|
||||
|
||||
return commands.removeMark('textStyle')
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
})
|
||||
|
||||
export default TextStyle
|
||||
|
||||
Reference in New Issue
Block a user