I am trying to add class to selected element (table in this case) when clicking button on element toolbar.
const dropdownView = createDropdown(locale); const model = editor.model; dropdownView.buttonView.set({ label: "Table Style", icon: icon, tooltip: false }); const items = new Collection(); items.add({ type: "button", model: new Model({ id: "type1", withText: true, label: "Type 1" }) }); items.add({ type: "button", model: new Model({ id: "type2", withText: true, label: "Type 2" }) }); addListToDropdown(dropdownView, items); dropdownView.on("execute", function (eventInfo) { const type = eventInfo.source.id; model.enqueueChange("default", (writer) => { const selection = model.document.selection; const table = selection.getFirstPosition().findAncestor("table"); // this not working. It works with keys like: height, width, but not with class writer.setAttribute("class", type, table); }); });
Can not add custom attributes. How can I add class or dataset attribute?
Advertisement
Answer
The solution I found:
const editor = this.editor; const comid = "tableClassAttribute"; editor.model.schema.extend("table", { allowAttributes: comid }); editor.ui.componentFactory.add("tableClass", (locale) => { const dropdownView = createDropdown(locale); const model = editor.model; dropdownView.buttonView.set({ label: "Table Style", icon, tooltip: false }); const items = new Collection(); tableClasses.forEach((tableClass) => { items.add({ type: "button", model: new Model({ id: tableClass.id, withText: true, label: tableClass.label }) }); }); addListToDropdown(dropdownView, items); editor.conversion.attributeToAttribute({ model: { name: "table", key: comid }, view: { name: "figure", key: "class" } }); dropdownView.on("execute", function (eventInfo) { model.enqueueChange("default", (writer) => { const type = eventInfo.source.id; const selection = model.document.selection; const table = selection.getFirstPosition().findAncestor("table"); writer.setAttribute(comid, "table-" + type, table); }); }); return dropdownView; });