When using the DOMSerializer table does not include colgroup / cols for pixel widths

When using the DOMSerializer table does not include colgroup / cols for pixel width’s, have others hit this issue? How have you worked around it ?

It’s pretty rough and it’s making some assumptions about the initial state of the table, but I wanted to share my proposed solution to this problem…

var fragment = DOMSerializer.fromSchema(this.schema).serializeFragment(this.view.state.doc.content);

domNode.appendChild(fragment);

domNode.querySelectorAll("table").forEach(function(table){

	var colgroup = document.createElement("colgroup"), tbody = table.querySelector("tbody");

	if ( table.rows && table.rows.length > 0 ) {

		for ( var c=0, clen = table.rows[0].cells.length; c < clen; c++ ){

			var cell = table.rows[0].cells[c],
				colwidth = cell.getAttribute('data-colwidth'),
				colwidths = [],
				col;

			if ( colwidth ) {
				colwidths = colwidth.split(",");
				for( var w=0, wlen = colwidths.length; w < wlen; w++ ) {
					col = document.createElement("col");
					col.style.width = colwidths[w] + "px";
					colgroup.appendChild(col);
				}
			} else {
				col = document.createElement("col");
				colgroup.appendChild(col);
			}

		}

		table.insertBefore(colgroup, tbody);

	}

});

In schema I define table like this

  tableNodes({
    tableGroup: 'block',
    cellContent: 'block+',
    cellAttributes: {
      background: {
        default: null,
        getFromDOM (dom) {
          return dom.dataset.colwidth || null
        },
        setDOMAttr (value, attrs) {
          if (value) {
            attrs.style =
              (attrs.style || '') + `width: ${value}px;`
          }
        }
      }
    }
  })

Then use fixed layout for the table tag

table {
  table-layout: fixed;
}

three years have passed and no one seems to nag about this.

this is because prosemirror-tables doesn’t define colgroup node. it adds colgroup element in the TableView (nodeview for the table node). so what’s serialized into html does not contain colgroup, nor cols. but fortunately the col-widths are saved in td[data-colwidth] attribute. so do your best at inserting your own cols with the widths from td data attribute.