I am trying to add class to selected element (table in this case) when clicking button on element toolbar.
JavaScript
x
39
39
1
const dropdownView = createDropdown(locale);
2
const model = editor.model;
3
4
dropdownView.buttonView.set({
5
label: "Table Style",
6
icon: icon,
7
tooltip: false
8
});
9
10
const items = new Collection();
11
items.add({
12
type: "button",
13
model: new Model({
14
id: "type1",
15
withText: true,
16
label: "Type 1"
17
})
18
});
19
items.add({
20
type: "button",
21
model: new Model({
22
id: "type2",
23
withText: true,
24
label: "Type 2"
25
})
26
});
27
addListToDropdown(dropdownView, items);
28
29
dropdownView.on("execute", function (eventInfo) {
30
const type = eventInfo.source.id;
31
model.enqueueChange("default", (writer) => {
32
const selection = model.document.selection;
33
const table = selection.getFirstPosition().findAncestor("table");
34
35
// this not working. It works with keys like: height, width, but not with class
36
writer.setAttribute("class", type, table);
37
});
38
});
39
Can not add custom attributes. How can I add class or dataset attribute?
Advertisement
Answer
The solution I found:
JavaScript
1
54
54
1
const editor = this.editor;
2
3
const comid = "tableClassAttribute";
4
5
editor.model.schema.extend("table", { allowAttributes: comid });
6
7
editor.ui.componentFactory.add("tableClass", (locale) => {
8
const dropdownView = createDropdown(locale);
9
const model = editor.model;
10
11
dropdownView.buttonView.set({
12
label: "Table Style",
13
icon,
14
tooltip: false
15
});
16
17
const items = new Collection();
18
19
tableClasses.forEach((tableClass) => {
20
items.add({
21
type: "button",
22
model: new Model({
23
id: tableClass.id,
24
withText: true,
25
label: tableClass.label
26
})
27
});
28
});
29
30
addListToDropdown(dropdownView, items);
31
32
editor.conversion.attributeToAttribute({
33
model: {
34
name: "table",
35
key: comid
36
},
37
view: {
38
name: "figure",
39
key: "class"
40
}
41
});
42
43
dropdownView.on("execute", function (eventInfo) {
44
model.enqueueChange("default", (writer) => {
45
const type = eventInfo.source.id;
46
const selection = model.document.selection;
47
const table = selection.getFirstPosition().findAncestor("table");
48
writer.setAttribute(comid, "table-" + type, table);
49
});
50
});
51
52
return dropdownView;
53
});
54