DEV/other things

trumbowyg table bug

석봉 2024. 9. 4. 15:15

How to fix a bug where the table width changes randomly.

 

trumbowyg.table.js

// Original code
var setColWidths = function ($table, tableState, isUnitPercent = false) {
    var $colgroup = $('colgroup', $table);
    var $cols = $('col', $colgroup);
    var tableWidth = $table[0].offsetWidth;
    $table.css({
        maxWidth: $table[0].offsetWidth,
    });

    var columnCount = tableState[0].length;
    var colWidths = [];
    for (var columnIndex = 0; columnIndex < columnCount; columnIndex += 1) {
        var cellElement = findFirstCellAtIndex(tableState, columnIndex).element;
        var cellWidth = cellElement.getBoundingClientRect().width;

        if (isUnitPercent) {
            cellWidth = ((cellWidth / tableWidth) * 100) + '%';
        }

        colWidths[columnIndex] = cellWidth;
    }

    for (var colIndex = 0; colIndex < columnCount; colIndex += 1) {
        $($cols[colIndex]).css({
            width: colWidths[colIndex],
        });
    }
};

// fixed code
var setColWidths = function ($table, tableState, isUnitPercent = false) {
    var $colgroup = $('colgroup', $table);
    var $cols = $('col', $colgroup);
    var tableWidth = $table[0].offsetWidth;
    $table.css({
        maxWidth: $table[0].offsetWidth,
    });

    var columnCount = tableState[0].length;
    var colWidths = [];
    for (var columnIndex = 0; columnIndex < columnCount; columnIndex += 1) {
        var cellElement = findFirstCellAtIndex(tableState, columnIndex).element;
        var cellWidth = cellElement.getBoundingClientRect().width;

        if (isUnitPercent) {
            cellWidth = ((cellWidth / tableWidth) * 100) + '%';
        }

        colWidths[columnIndex] = Math.floor(cellWidth);
    }

    for (var colIndex = 0; colIndex < columnCount; colIndex += 1) {
        $($cols[colIndex]).css({
            width: colWidths[colIndex],
        });
    }
};