Tiencut - KiotViet SPA Filter Input Under Name Column

Thêm ô nhập tìm kiếm ngay dưới tiêu đề "Tên sản phẩm"

// ==UserScript==
// @name         Tiencut - KiotViet SPA Filter Input Under Name Column
// @namespace    http://tampermonkey.net/
// @version      3
// @description  Thêm ô nhập tìm kiếm ngay dưới tiêu đề "Tên sản phẩm"
// @author       You
// @match        https://0867071703.kiotviet.vn/man/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function insertSearchInputInCell() {
        // Tìm bảng và lấy dòng đầu tiên (hoặc lấy header)
        const table = document.querySelector('.k-grid-content.k-auto-scrollable table');
        if (!table) return;
        // Nếu bảng rỗng
        const tbody = table.querySelector('tbody');
        if (!tbody || !tbody.firstElementChild) return;

        // Xác định dòng đầu tiên (hoặc cuối header)
        const firstRow = tbody.firstElementChild;
        if (!firstRow) return;

        // Tìm ô có class cell-auto
        const tds = firstRow.querySelectorAll('td');
        let cell = null;
        for (let td of tds) {
            if (td.classList && td.classList.contains('cell-auto')) {
                cell = td;
                break;
            }
        }
        if (!cell) return;

        // Đã có input chưa?
        if (cell.querySelector('#spa-search-input')) return;

        // Chèn ô input vào đầu ô này
        const input = document.createElement('input');
        input.type = 'text';
        input.id = 'spa-search-input';
        input.style = 'width:96%;padding:2px;font-size:1em;margin-bottom:2px;';
        input.placeholder = 'Lọc tên sản phẩm...';
        cell.prepend(input);

        // Xử lý filter
        input.addEventListener('input', function() {
            const keyword = input.value.trim().toLowerCase();
            const rows = Array.from(tbody.querySelectorAll('tr'));
            rows.forEach(tr => {
                if (tr.contains(input)) return; // không ẩn dòng chứa input
                const nameTd = tr.querySelector('td.cell-auto');
                const text = nameTd ? nameTd.textContent.trim().toLowerCase() : '';
                tr.style.display = !keyword || text.includes(keyword) ? '' : 'none';
            });
        });
        input.addEventListener('keydown', e => {
            if (e.key === "Escape") {
                input.value = "";
                const rows = Array.from(tbody.querySelectorAll('tr'));
                rows.forEach(tr => { tr.style.display = ''; });
            }
        });
    }

    // Dính lại khi bảng thay đổi qua SPA
    setInterval(insertSearchInputInCell, 100);

})();