"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.appendChild = appendChild;
exports.insertBefore = insertBefore;
exports.insertBeforeAt = insertBeforeAt;
exports.removeChild = removeChild;
exports.prepend = prepend;
exports.removeChildren = removeChildren;
exports.insertAt = insertAt;
exports.elementToJson = elementToJson;
exports.isElementFocusable = isElementFocusable;
const isTextField_1 = require("../client/isTextField");
function appendChild(node, newChild) {
    return node.appendChild(newChild);
}
function insertBefore(node, newChild, refChild) {
    return node.insertBefore(newChild, refChild);
}
function insertBeforeAt(node, newChild, at) {
    const nextChild = node.childNodes.item(at);
    return insertBefore(node, newChild, nextChild);
}
function removeChild(node, oldChild) {
    return node.removeChild(oldChild);
}
function prepend(node, newChild) {
    if (node instanceof Text) {
        return;
    }
    return node.prepend(newChild);
}
function removeChildren(element) {
    while (element.firstChild) {
        element.removeChild(element.lastChild);
    }
}
function insertAt(node, newChild, at) {
    const currentChild = node.childNodes.item(at);
    if (currentChild) {
        return insertBefore(node, newChild, currentChild);
    }
    else {
        return appendChild(node, newChild);
    }
}
function elementToJson(element) {
    if (element instanceof Text) {
        return {
            name: '_text',
            attr: {
                value: element.textContent,
            },
            children: [],
        };
    }
    let i = 0;
    const attr = {};
    while (i < element.attributes.length) {
        const attribute = element.attributes.item(i);
        attr[attribute.name] = attribute.value;
        i++;
    }
    const children = [...element.childNodes]
        .filter((node) => !(node instanceof Text) || !!node.textContent.trim())
        .map(elementToJson);
    const name = element.tagName.toLowerCase();
    return {
        name,
        attr,
        children,
    };
}
function isElementFocusable(system, element) {
    const { api: { window: { HTMLElement, getComputedStyle }, }, } = system;
    if (!(element instanceof HTMLElement)) {
        return false;
    }
    const tabIndex = element.getAttribute('tabindex');
    const hasTabIndex = tabIndex !== null;
    const style = getComputedStyle(element);
    if (style.visibility === 'hidden' || style.display === 'none') {
        return false;
    }
    if ('disabled' in element && element.disabled) {
        return false;
    }
    if ((0, isTextField_1.isTextField)(element)) {
        return true;
    }
    if (hasTabIndex && parseInt(tabIndex, 10) >= 0) {
        return true;
    }
    return false;
}
//# sourceMappingURL=element.js.map