tiptap/packages/extension-font-family/src/index.ts

68 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-11-16 06:25:25 +08:00
import { Command, Extension } from '@tiptap/core'
2020-11-07 01:25:33 +08:00
import '@tiptap/extension-text-style'
2020-11-06 22:14:04 +08:00
type FontFamilyOptions = {
types: string[],
}
2020-11-16 06:25:25 +08:00
const FontFamily = Extension.create({
2020-11-06 22:14:04 +08:00
defaultOptions: <FontFamilyOptions>{
types: ['textStyle'],
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontFamily: {
default: null,
2020-11-06 23:21:19 +08:00
renderHTML: attributes => {
if (!attributes.fontFamily) {
return {}
}
return {
style: `font-family: ${attributes.fontFamily}`,
}
},
2020-11-06 22:14:04 +08:00
parseHTML: element => ({
2020-11-06 23:21:19 +08:00
fontFamily: element.style.fontFamily.replace(/['"]+/g, ''),
2020-11-06 22:14:04 +08:00
}),
},
},
},
]
},
addCommands() {
return {
2020-11-13 22:08:30 +08:00
/**
2020-11-18 19:09:04 +08:00
* Set the font family
2020-11-13 22:08:30 +08:00
*/
2020-11-18 19:09:04 +08:00
setFontFamily: (fontFamily: string): Command => ({ chain }) => {
2020-11-06 23:21:19 +08:00
return chain()
2020-11-18 18:05:19 +08:00
.addMark('textStyle', { fontFamily })
2020-11-18 19:09:04 +08:00
.run()
},
/**
* Unset the font family
*/
unsetFontFamily: (): Command => ({ chain }) => {
return chain()
.addMark('textStyle', { fontFamily: null })
2020-11-06 23:21:19 +08:00
.removeEmptyTextStyle()
.run()
2020-11-06 22:14:04 +08:00
},
}
},
})
export default FontFamily
declare module '@tiptap/core' {
interface AllExtensions {
FontFamily: typeof FontFamily,
2020-11-06 22:14:04 +08:00
}
}