Skip to content

Instantly share code, notes, and snippets.

@sabetAI
Last active August 10, 2021 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabetAI/e7ac09da82ea4e1e01929beb836ffa41 to your computer and use it in GitHub Desktop.
Save sabetAI/e7ac09da82ea4e1e01929beb836ffa41 to your computer and use it in GitHub Desktop.
TipTap Color Extension
import { Extension } from "@tiptap/core";
import "@tiptap/extension-text-style";
type ColorOptions = {
types: string[];
};
declare module "@tiptap/core" {
interface Commands<ReturnType> {
color: {
/**
* Set the font family
*/
setColor: (color: string) => ReturnType;
/**
* Unset the font family
*/
unsetColor: () => ReturnType;
};
}
}
export const Color = Extension.create<ColorOptions>({
name: "color",
defaultOptions: {
types: ["textStyle"],
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
color: {
default: null,
renderHTML: (attributes) => {
if (!attributes.color) {
return {};
}
return {
style: `color:${attributes.color};`,
};
},
parseHTML: (element) => ({
color: element.style.color.replace(/['"]+/g, ""),
}),
},
},
},
];
},
addCommands() {
return {
setColor:
(color) =>
({ chain }) => {
return chain().setMark("textStyle", { color }).run();
},
unsetFontFamily:
() =>
({ chain }) => {
return chain()
.setMark("textStyle", { color: null })
.removeEmptyTextStyle()
.run();
},
};
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment