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

71 lines
1.5 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[],
}
2021-02-10 16:59:35 +08:00
declare module '@tiptap/core' {
2021-02-17 01:39:37 +08:00
interface Commands {
2021-02-16 18:27:58 +08:00
fontFamily: {
/**
* Set the font family
*/
setFontFamily: (fontFamily: string) => Command,
/**
* Unset the font family
*/
unsetFontFamily: () => Command,
}
2021-02-10 16:59:35 +08:00
}
}
2021-02-11 01:25:08 +08:00
export const FontFamily = Extension.create<FontFamilyOptions>({
2020-12-02 16:44:46 +08:00
name: 'fontFamily',
2021-02-11 01:25:08 +08:00
defaultOptions: {
2020-11-06 22:14:04 +08:00
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 {
2021-02-10 16:59:35 +08:00
setFontFamily: fontFamily => ({ chain }) => {
2020-11-06 23:21:19 +08:00
return chain()
2020-11-19 00:36:00 +08:00
.setMark('textStyle', { fontFamily })
2020-11-18 19:09:04 +08:00
.run()
},
2021-02-10 16:59:35 +08:00
unsetFontFamily: () => ({ chain }) => {
2020-11-18 19:09:04 +08:00
return chain()
2020-11-19 00:36:00 +08:00
.setMark('textStyle', { fontFamily: null })
2020-11-06 23:21:19 +08:00
.removeEmptyTextStyle()
.run()
2020-11-06 22:14:04 +08:00
},
}
},
})