Resize element to fit text

by Roman Bruckner

HTML

<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.7.5/joint.css" />
</head>
<body>
      <!-- content -->
      <div id="paper"></div>
        <button id="resize">
            resize
        </button>
      <!-- dependencies -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.0/backbone.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.7.5/joint.js"></script>
    
    </body>
</html>

CSS

button { position: absolute; top: 10px; left: 10px; }

JavaScript

const graph = new joint.dia.Graph({}, {
    cellNamespace: joint.shapes
});

const paper = new joint.dia.Paper({
    el: document.getElementById('paper'),
    width: 800,
    height: 900,
    model: graph,
    cellViewNamespace: joint.shapes,
    gridSize: 10,
    async: true,
    sorting: joint.dia.Paper.sorting.APPROX,
});

const rect1 = new joint.shapes.standard.Rectangle({
    attrs: {
        label: {
            text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam in dui mauris.',
            fontSize: 14,
            lineHeight: 18,
            fontFamily: 'sans-serif',
            textWrap: {
                width: 'calc(w - 10)',
                height: 'calc(h - 10)',
                ellipsis: true,
            }
        }
    }
});

rect1.position(100, 50);
rect1.resize(100, 50);

graph.addCells([rect1]);

document.getElementById('resize').addEventListener('click', () => {

    resizeElementToFitText(rect1, paper);


}, false);

function resizeElementToFitText(el, paper, opt = {}) {
    const { selector = 'label', margin = 10, lineHeightExtra = 18 - 14 } = opt;
    const wrapHeightPath = `${selector}/textWrap/height`;
    const textWrapHeight = el.attr(wrapHeightPath);
    el.startBatch('resize-text');
    el.attr(wrapHeightPath, null, { async: false });
    const elView = el.findView(paper);
    const [labelEl] = elView.findBySelector(selector);
    const bbox = elView.getNodeBoundingRect(labelEl);
    el.resize(bbox.width + margin, bbox.height + margin + lineHeightExtra);
    el.attr(wrapHeightPath, textWrapHeight);
    el.stopBatch('resize-text');
}