Full document, spreadsheet, slideshow, and diagram tooling
1import { Extension } from '@tiptap/core';
2
3interface FontSizeOptions {
4 types: string[];
5}
6
7/**
8 * FontSize extension — adds fontSize attribute to TextStyle marks.
9 * Usage: editor.chain().focus().setFontSize('16px').run()
10 * editor.chain().focus().unsetFontSize().run()
11 */
12export const FontSize = Extension.create<FontSizeOptions>({
13 name: 'fontSize',
14
15 addOptions() {
16 return {
17 types: ['textStyle'],
18 };
19 },
20
21 addGlobalAttributes() {
22 return [
23 {
24 types: this.options.types,
25 attributes: {
26 fontSize: {
27 default: null,
28 parseHTML: (element: HTMLElement) => element.style.fontSize?.replace(/['"]+/g, '') || null,
29 renderHTML: (attributes: Record<string, string | null>) => {
30 if (!attributes.fontSize) return {};
31 return { style: `font-size: ${attributes.fontSize}` };
32 },
33 },
34 },
35 },
36 ];
37 },
38
39 addCommands() {
40 return {
41 setFontSize: (fontSize: string) => ({ chain }) => {
42 return chain().setMark('textStyle', { fontSize }).run();
43 },
44 unsetFontSize: () => ({ chain }) => {
45 return chain().setMark('textStyle', { fontSize: null }).removeEmptyTextStyle().run();
46 },
47 };
48 },
49});