-
-
Save lucianovalenca/19a6e43727dbc5fb5159a587c9db783e to your computer and use it in GitHub Desktop.
line-heights for tiptap 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Extension } from "@tiptap/core"; | |
export interface LineHeightOptions { | |
types: string[]; | |
heights: string[]; | |
defaultHeight: string; | |
} | |
declare module "@tiptap/core" { | |
interface Commands<ReturnType> { | |
lineHeight: { | |
/** | |
* Set the line height attribute | |
*/ | |
setLineHeight: (height: string) => ReturnType; | |
/** | |
* Unset the text align attribute | |
*/ | |
unsetLineHeight: () => ReturnType; | |
}; | |
} | |
} | |
export const LineHeight = Extension.create<LineHeightOptions>({ | |
name: "lineHeight", | |
addOptions() { | |
return { | |
types: ["heading", "paragraph"], | |
heights: ["100%", "115%", "150%", "200%", "250%", "300%"], | |
defaultHeight: "100%", | |
}; | |
}, | |
addGlobalAttributes() { | |
return [ | |
{ | |
types: this.options.types, | |
attributes: { | |
lineHeight: { | |
default: this.options.defaultHeight, | |
parseHTML: (element) => | |
element.style.lineHeight || this.options.defaultHeight, | |
renderHTML: (attributes) => { | |
if (attributes.lineHeight === this.options.defaultHeight) { | |
return {}; | |
} | |
return { style: `line-height: ${attributes.lineHeight}` }; | |
}, | |
}, | |
}, | |
}, | |
]; | |
}, | |
addCommands() { | |
return { | |
setLineHeight: | |
(height: string) => | |
({ commands }) => { | |
if (!this.options.heights.includes(height)) { | |
return false; | |
} | |
return this.options.types.every((type) => | |
commands.updateAttributes(type, { lineHeight: height }) | |
); | |
}, | |
unsetLineHeight: | |
() => | |
({ commands }) => { | |
return this.options.types.every((type) => | |
commands.resetAttributes(type, "lineHeight") | |
); | |
}, | |
}; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an extension for setting the line-height attribut of a paragraph or header in a tiptap 2 editor.
The original code for this was taken from tiptap's textAlign extension.
The docs for using the extension are exactly the same as the textAlign docs.
Unlike TextAlign, I have specified a set of default values for types. This defaults to what the TextAlign docs suggest: ["heading", "paragraph"].
I also provide a set of default hieghts specified as a %. If you want to specify a different set of line-heights, then just configure them when adding the extension to the editor:
LineHeight..configure({
heights: ['1.5rem', '1.8rem', '2rem']
})
The other option is defaultHeight. It should be one of the elements of the heights array and is a string.