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

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-11-07 01:25:33 +08:00
import '@tiptap/extension-text-style'
2020-11-06 22:14:04 +08:00
import { Extension } from '@tiptap/core'
export type FontFamilyOptions = {
2020-11-06 22:14:04 +08:00
types: string[],
}
2021-02-10 16:59:35 +08:00
declare module '@tiptap/core' {
2021-06-05 03:56:29 +08:00
interface Commands<ReturnType> {
2021-02-16 18:27:58 +08:00
fontFamily: {
/**
* Set the font family
*/
2021-06-05 03:56:29 +08:00
setFontFamily: (fontFamily: string) => ReturnType,
2021-02-16 18:27:58 +08:00
/**
* Unset the font family
*/
2021-06-05 03:56:29 +08:00
unsetFontFamily: () => ReturnType,
2021-02-16 18:27:58 +08:00
}
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',
addOptions() {
return {
types: ['textStyle'],
}
2020-11-06 22:14:04 +08:00
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontFamily: {
default: null,
parseHTML: element => element.style.fontFamily?.replace(/['"]+/g, ''),
2020-11-06 23:21:19 +08:00
renderHTML: attributes => {
if (!attributes.fontFamily) {
return {}
}
return {
style: `font-family: ${CSS.escape(attributes.fontFamily)}`,
2020-11-06 23:21:19 +08:00
}
},
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
},
}
},
})