-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
text-align.ts
112 lines (99 loc) · 2.85 KB
/
text-align.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { Extension } from '@tiptap/core'
export interface TextAlignOptions {
/**
* The types where the text align attribute can be applied.
* @default []
* @example ['heading', 'paragraph']
*/
types: string[],
/**
* The alignments which are allowed.
* @default ['left', 'center', 'right', 'justify']
* @example ['left', 'right']
*/
alignments: string[],
/**
* The default alignment.
* @default 'left'
* @example 'center'
*/
defaultAlignment: string,
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
textAlign: {
/**
* Set the text align attribute
* @param alignment The alignment
* @example editor.commands.setTextAlign('left')
*/
setTextAlign: (alignment: string) => ReturnType,
/**
* Unset the text align attribute
* @example editor.commands.unsetTextAlign()
*/
unsetTextAlign: () => ReturnType,
}
}
}
/**
* This extension allows you to align text.
* @see https://www.tiptap.dev/api/extensions/text-align
*/
export const TextAlign = Extension.create<TextAlignOptions>({
name: 'textAlign',
addOptions() {
return {
types: [],
alignments: ['left', 'center', 'right', 'justify'],
defaultAlignment: 'left',
}
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
textAlign: {
default: this.options.defaultAlignment,
parseHTML: element => {
const alignment = element.style.textAlign || this.options.defaultAlignment
return this.options.alignments.includes(alignment) ? alignment : this.options.defaultAlignment
},
renderHTML: attributes => {
if (attributes.textAlign === this.options.defaultAlignment) {
return {}
}
return { style: `text-align: ${attributes.textAlign}` }
},
},
},
},
]
},
addCommands() {
return {
setTextAlign: (alignment: string) => ({ commands }) => {
if (!this.options.alignments.includes(alignment)) {
return false
}
return this.options.types
.map(type => commands.updateAttributes(type, { textAlign: alignment }))
.every(response => response)
},
unsetTextAlign: () => ({ commands }) => {
return this.options.types
.map(type => commands.resetAttributes(type, 'textAlign'))
.every(response => response)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-Shift-l': () => this.editor.commands.setTextAlign('left'),
'Mod-Shift-e': () => this.editor.commands.setTextAlign('center'),
'Mod-Shift-r': () => this.editor.commands.setTextAlign('right'),
'Mod-Shift-j': () => this.editor.commands.setTextAlign('justify'),
}
},
})