stormid / components

UI components
https://stormid.github.io/components/
MIT License
2 stars 2 forks source link

Textarea > simplify implementation #251

Closed mjbp closed 1 year ago

mjbp commented 1 year ago

Instead of setting the height with an inline style which can have some fiddly interplay with line-height and overflow, set the rows attribute by finding the number of rows by the counting the \n's.

Something like

const update = ({ target, initial = 3 }) => {
    target.setAttribute('rows', Math.max(initial, target.value.split('\n').length));
};

const initObserver = el => {
    const observer = new MutationObserver(mutationsList => {
        update({ target: el });
    });
    observer.observe(el.parentNode, { attributes: true, attributeOldValue: true, attributeFilter: ['class', 'hidden']  });
};

export default (selector, options) => {
    const nodes = getSelection(selector);

    return nodes.map(node => {
        node.addEventListener('input', update);
        if (isHidden(node)) initObserver(node);
        update({ target: node, initial: node.getAttribute('rows') });

        window.addEventListener('resize', () => update({ target: node }));

        return {
            node,
            resize() {
                update({ target: node });
            }
        };
    });
};