Created
May 3, 2022 23:26
-
-
Save gregveres/973e8d545ab40dc375b47ebc63f92846 to your computer and use it in GitHub Desktop.
background-color for tiptap 2
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"; | |
export type ColorOptions = { | |
types: string[]; | |
}; | |
declare module "@tiptap/core" { | |
interface Commands<ReturnType> { | |
backColor: { | |
/** | |
* Set the text color | |
*/ | |
setBackColor: (color: string) => ReturnType; | |
/** | |
* Unset the text color | |
*/ | |
unsetBackColor: () => ReturnType; | |
}; | |
} | |
} | |
export const BackColor = Extension.create<ColorOptions>({ | |
name: "backColor", | |
addOptions() { | |
return { | |
types: ["textStyle"], | |
}; | |
}, | |
addGlobalAttributes() { | |
return [ | |
{ | |
types: this.options.types, | |
attributes: { | |
backgroundColor: { | |
default: null, | |
parseHTML: (element) => | |
element.style.backgroundColor.replace(/['"]+/g, ""), | |
renderHTML: (attributes) => { | |
if (!attributes.backgroundColor) { | |
return {}; | |
} | |
return { | |
style: `background-color: ${attributes.backgroundColor}`, | |
}; | |
}, | |
}, | |
}, | |
}, | |
]; | |
}, | |
addCommands() { | |
return { | |
setBackColor: | |
(color) => | |
({ chain }) => { | |
return chain().setMark("textStyle", { backgroundColor: color }).run(); | |
}, | |
unsetBackColor: | |
() => | |
({ chain }) => { | |
return chain() | |
.setMark("textStyle", { backgroundColor: null }) | |
.removeEmptyTextStyle() | |
.run(); | |
}, | |
}; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very good code! But be aware that need to import
@tiptap/extension-text-style
, otherwise you will get an errorremoveEmptyTextStyle
not found!