Немає опису редагування
Немає опису редагування
Мітка: Ручний відкіт
 
(Не показано 40 проміжних версій цього користувача)
Рядок 1: Рядок 1:
local p = {}
local p = {}


----------------------------------------------------------------------
-- ================================================
-- ГОЛОВНИЙ ПОШУК
-- КЕШУВАННЯ
-- Шукає у таблиці рядок, де друга колонка = player_name
-- ================================================
-- Повертає значення з column_index того ж самого рядка
-- Індексація: 1=№, 2=Ім'я, 3=Значення, 4=Додатково
----------------------------------------------------------------------


local function fetch_from_table(page_title, player_name, column_index)
local page_cache = {}
    local title = mw.title.new(page_title)
    if not title then return nil end


local function get_page_content(page_name)
    if page_cache[page_name] then
        return page_cache[page_name]
    end
   
    local title = mw.title.new(page_name)
    if not title or not title.exists then
        page_cache[page_name] = nil
        return nil
    end
   
     local content = title:getContent()
     local content = title:getContent()
     if not content then return nil end
     page_cache[page_name] = content
    return content
end


    -- Escape для імен з дужками/крапками
-- ================================================
    local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
    local player_pattern = "%[%[" .. escaped .. "%]%]"
-- ================================================


    -- 1. Вилучаємо вміст таблиці wikitable (все між {| і |})
function p.section_menu(frame)
     local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
     local page_name = frame.args.page or mw.title.getCurrentTitle().text
     if not table_content then return nil end
    local content = get_page_content(page_name)
 
   
    -- 2. Знаходимо весь блок даних гравця (4 комірки)
     if not content then
    -- Патерн, що захоплює послідовність 4 комірок, де друга містить ім'я гравця.
        return ""
    local full_row_pattern = "([|]%s*.-%s*[|]%s*" .. player_pattern .. "%s*[|]%s*.-%s*[|]%s*.-%s*)"
     end
     local full_row_match = mw.ustring.match(table_content, full_row_pattern)
      
      
    if not full_row_match then return nil end
     local sections = {}
 
    -- 3. Розділяємо захоплений блок на комірки
     local cells = {}
      
      
     -- Розділяємо блок по символу |
     for line in mw.ustring.gmatch(content, "[^\n]+") do
    for cell in mw.ustring.gmatch(full_row_match, "[|](.-)") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        local trimmed_cell = mw.text.trim(cell)
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
        if trimmed_cell ~= "" then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
            table.insert(cells, trimmed_cell)
           
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
               
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
               
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
         end
         end
     end
     end
    -- cells[1] = №, cells[2] = [[Гравець]], cells[3] = Дата/Сума, cells[4] = Провідник/Рахунок
      
      
     local result = cells[column_index]
     if #sections == 0 then
     if not result then return nil end
        return ""
 
     end
     -- 4. Прибираємо [[link|text]] і [[link]]
   
     result = mw.ustring.gsub(result, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2") -- [[link|text]] -> text
     -- Будуємо HTML
     result = mw.ustring.gsub(result, "%[%[([^%]]+)%]%]", "%1")          -- [[link]] -> link
     local html_parts = {}
 
   
    return mw.text.trim(result)
     table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
end
      
 
     table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
 
----------------------------------------------------------------------
-- Рахує різницю в днях між датою та 25.10.2024
----------------------------------------------------------------------
 
local function date_with_days(dateString)
     if not dateString then return "" end
 
     local d, m, y = dateString:match("(%d%d)%.(%d%d)%.(%d%d%d%d)")
    if not d then return dateString end
 
    -- Цільова дата: 25.10.2024
    local start = os.time({day = tonumber(d), month = tonumber(m), year = tonumber(y), hour = 0, min = 0, sec = 0})
    local finish = os.time({day = 25, month = 10, year = 2024, hour = 0, min = 0, sec = 0})
      
      
     local diff = math.floor((finish - start) / 86400)
     for i, section in ipairs(sections) do
    if diff < 0 then diff = 0 end
        local border = ""
 
        if i < #sections then
    return string.format("%s (%d д)", dateString, diff)
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
end
        end
 
       
 
        table.insert(html_parts, string.format(
----------------------------------------------------------------------
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
-- ПОЛЯ
            border, section.anchor, section.display
----------------------------------------------------------------------
        ))
 
-- ТАБЛИЦЯ "ГРАВЦІ" (Індекс 3 та 4)
function p.recruiter(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Гравці", name, 4)
    if raw == "Відсутній" then return "Не вказано" end
    return raw or "Не вказано"
end
 
function p.date_added(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Гравці", name, 3)
    return raw and date_with_days(raw) or "Невідомо"
end
 
-- ТАБЛИЦЯ "ФУНДАЦІЯ" (Індекс 3)
function p.foundation(frame)
    local name = mw.title.getCurrentTitle().text
    -- Колонка 3 для суми
    local raw = fetch_from_table("Фундація", name, 3)
    -- Очищення від символів валют та пробілів (на випадок, якщо там 1000 ₴)
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
     end
     end
    return (raw or "0") .. " ₴"
end
-- ТАБЛИЦЯ "ПРИЗОВИЙ_ФОНД" (Індекс 3)
function p.prize_pool(frame)
    local name = mw.title.getCurrentTitle().text
    -- Колонка 3 для суми
    local raw = fetch_from_table("Призовий_фонд", name, 3)
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
    return (raw or "0") .. " ₴"
end
-- ТАБЛИЦЯ "ФІНАЛІСТ" (Індекс 3)
function p.final(frame)
    local name = mw.title.getCurrentTitle().text
    -- Колонка 3 для рахунку (наприклад, 3)
    local raw = fetch_from_table("Фіналіст", name, 3)
      
      
     -- Вилучаємо лише число (на випадок, якщо там написано "3/9")
     table.insert(html_parts, '</div>')
    local count = raw and mw.ustring.match(raw, "(%d+)")
      
      
     if count then
     return table.concat(html_parts, '\n')
        return count .. "/9"
    else
        return "0/9"
    end
end
end


return p
return p

Поточна версія на 10:24, 8 грудня 2025

Документацію для цього модуля можна створити у Модуль:FetchData2/документація

local p = {}

-- ================================================
-- КЕШУВАННЯ
-- ================================================

local page_cache = {}

local function get_page_content(page_name)
    if page_cache[page_name] then
        return page_cache[page_name]
    end
    
    local title = mw.title.new(page_name)
    if not title or not title.exists then
        page_cache[page_name] = nil
        return nil
    end
    
    local content = title:getContent()
    page_cache[page_name] = content
    return content
end

-- ================================================
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================

function p.section_menu(frame)
    local page_name = frame.args.page or mw.title.getCurrentTitle().text
    local content = get_page_content(page_name)
    
    if not content then
        return ""
    end
    
    local sections = {}
    
    for line in mw.ustring.gmatch(content, "[^\n]+") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
            
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
                
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
                
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
        end
    end
    
    if #sections == 0 then
        return ""
    end
    
    -- Будуємо HTML
    local html_parts = {}
    
    table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
    
    table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    
    for i, section in ipairs(sections) do
        local border = ""
        if i < #sections then
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
        end
        
        table.insert(html_parts, string.format(
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
            border, section.anchor, section.display
        ))
    end
    
    table.insert(html_parts, '</div>')
    
    return table.concat(html_parts, '\n')
end

return p