Skip to content

Instantly share code, notes, and snippets.

@lucianovalenca
Forked from gregveres/font-size.ts
Created September 16, 2023 19:56
Show Gist options
  • Save lucianovalenca/28d2109cca9ac5914f895f317a881ed7 to your computer and use it in GitHub Desktop.
Save lucianovalenca/28d2109cca9ac5914f895f317a881ed7 to your computer and use it in GitHub Desktop.
font-size for tiptap 2
import { Extension } from "@tiptap/core";
import "@tiptap/extension-text-style";
export type FontSizeOptions = {
types: string[];
};
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fontSize: {
/**
* Set the font size
*/
setFontSize: (fontSize: string) => ReturnType;
/**
* Unset the font size
*/
unsetFontSize: () => ReturnType;
};
}
}
export const FontSize = Extension.create<FontSizeOptions>({
name: "fontSize",
addOptions() {
return {
types: ["textStyle"],
};
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontSize: {
default: null,
parseHTML: (element) =>
element.style.fontSize.replace(/['"]+/g, ""),
renderHTML: (attributes) => {
if (!attributes.fontSize) {
return {};
}
return {
style: `font-size: ${attributes.fontSize}`,
};
},
},
},
},
];
},
addCommands() {
return {
setFontSize:
(fontSize) =>
({ chain }) => {
return chain().setMark("textStyle", { fontSize }).run();
},
unsetFontSize:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { fontSize: null })
.removeEmptyTextStyle()
.run();
},
};
},
});
@lucianovalenca
Copy link
Author

This is an extension for setting the font size in a tiptap 2 editor.
The original code for this was taken from tiptap's fontFamily
The docs for using the extension are exactly the same as the font family docs, just change "fontFamily" to "fontSize" everywhere (match the case of the original).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment