Last active
August 10, 2021 22:52
-
-
Save sabetAI/e7ac09da82ea4e1e01929beb836ffa41 to your computer and use it in GitHub Desktop.
TipTap Color Extension
This file contains hidden or 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"; | |
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