tiptap/packages/extension-text-align/index.ts

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-10-23 23:50:28 +08:00
import { Command, createExtension } from '@tiptap/core'
2020-10-23 21:23:40 +08:00
2020-10-23 23:19:12 +08:00
type TextAlignOptions = {
types: string[],
2020-10-23 23:50:28 +08:00
alignments: string[],
defaultAlignment: string,
2020-10-23 23:19:12 +08:00
}
2020-10-23 21:23:40 +08:00
const TextAlign = createExtension({
2020-10-23 23:19:12 +08:00
defaultOptions: <TextAlignOptions>{
types: ['heading', 'paragraph'],
2020-11-03 23:13:13 +08:00
alignments: ['left', 'center', 'right', 'justify'],
defaultAlignment: 'left',
2020-10-23 23:19:12 +08:00
},
2020-10-23 21:23:40 +08:00
addGlobalAttributes() {
return [
{
2020-10-23 23:19:12 +08:00
types: this.options.types,
2020-10-23 21:23:40 +08:00
attributes: {
2020-10-23 23:19:12 +08:00
textAlign: {
default: this.options.defaultAlignment,
2020-10-23 21:23:40 +08:00
renderHTML: attributes => ({
2020-10-23 23:19:12 +08:00
style: `text-align: ${attributes.textAlign}`,
2020-10-23 21:23:40 +08:00
}),
parseHTML: element => ({
textAlign: element.style.textAlign || this.options.defaultAlignment,
}),
2020-10-23 21:23:40 +08:00
},
},
},
]
},
2020-10-23 23:50:28 +08:00
addCommands() {
return {
textAlign: (alignment: string): Command => ({ commands }) => {
if (!this.options.alignments.includes(alignment)) {
return false
}
return commands.setNodeAttributes({ textAlign: alignment })
},
}
},
addKeyboardShortcuts() {
return {
2020-10-27 19:38:07 +08:00
// TODO: re-use only 'textAlign' attribute
// TODO: use custom splitBlock only for `this.options.types`
// TODO: use complete default enter handler (chainCommand) with custom splitBlock
Enter: () => this.editor.splitBlock({
withAttributes: true,
}),
2020-11-05 21:39:28 +08:00
'Ctrl-Shift-l': () => this.editor.textAlign('left'),
'Ctrl-Shift-e': () => this.editor.textAlign('center'),
'Ctrl-Shift-r': () => this.editor.textAlign('right'),
'Ctrl-Shift-j': () => this.editor.textAlign('justify'),
}
},
2020-10-23 21:23:40 +08:00
})
export default TextAlign
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
TextAlign: typeof TextAlign,
}
}