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


--- Функція для виведення помилки на сторінку
-- ================================================
local function error_output(context, error_details)
-- КЕШУВАННЯ
    local safe_details = error_details or "N/A"
-- ================================================
    return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Page: %s]</span>", context or "Unknown Context", safe_details)
end


--- Видаляє вікі-посилання [[link|text]] і [[link]]
local page_cache = {}
local function clean_wikilinks(text)
    if not text then return nil end
    -- [[link|text]] -> text
    text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
    -- [[link]] -> link
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
    return mw.text.trim(text)
end


----------------------------------------------------------------------
local function get_page_content(page_name)
-- ГОЛОВНИЙ ПОШУК (Виправлено парсинг, використовує ім'я гравця)
    if page_cache[page_name] then
----------------------------------------------------------------------
        return page_cache[page_name]
 
    end
local function fetch_from_table(page_title, player_name, column_index)
      
      
     if not player_name or player_name == "" then
    local title = mw.title.new(page_name)
         -- Повертаємо помилку, якщо ім'я гравця не передано
     if not title or not title.exists then
         return error_output("No Player Name", page_title)
         page_cache[page_name] = nil
         return nil
     end
     end
      
      
     local title = mw.title.new(page_title)
     local content = title:getContent()
     if not title or not title.exists then
     page_cache[page_name] = content
        return error_output("Page Missing", page_title)
    return content
    end
end


    local content = title:getContent()
-- ================================================
    if not content then return error_output("Content Read Fail", page_title) end
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================


    -- Шукаємо вміст таблиці
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  
    local content = get_page_content(page_name)
         return error_output("Table Missing", page_title)
   
     if not content then
         return ""
     end
     end
    local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    -- Шукаємо гравця у форматі [[Player]]
    local player_pattern = "%[%[" .. escaped .. "%]%]"
    local result = nil
      
      
     -- Ітерація по всіх рядках, що починаються з `|-`
     local sections = {}
     for row in mw.ustring.gmatch(table_content, "\n%s*|-[^%s]*\n(.-)") do
   
       
     for line in mw.ustring.gmatch(content, "[^\n]+") do
         -- Перевіряємо, чи містить рядок ім'я гравця
         -- ТІЛЬКИ заголовки рівня 2: == Назва ==
         if mw.ustring.find(row, player_pattern, 1, true) then
         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 cell_data = {}
                -- Виконуємо шаблони щоб отримати реальний текст
           
                local processed = frame:preprocess(section_name)
            -- 1. Видаляємо маркер початку рядка (пробіли та перший '|')
                 processed = mw.text.trim(processed)
            local cleaned_row = mw.ustring.gsub(row, "^%s*[|]%s*", "")
               
           
                -- Anchor
            -- 2. Розділяємо рядок за '||'. Це надійно захоплює всі комірки.
                local anchor = mw.ustring.gsub(processed, " ", "_")
            local cell_parts = mw.text.split(cleaned_row, '||')
           
            -- 3. Обрізаємо пробіли для кожної частини і заповнюємо cell_data
            for _, cell in ipairs(cell_parts) do
                 table.insert(cell_data, mw.text.trim(cell))
            end
            -- --- КІНЕЦЬ ПОКРАЩЕНОЇ ЛОГІКИ ---
           
            -- Перевіряємо, що ми знайшли [[Player]] саме в Колонці 2
            if #cell_data >= 2 and mw.ustring.find(cell_data[2], player_pattern) then
                  
                  
                -- Перевірка, чи існує потрібна колонка
                 if processed ~= "" then
                 if column_index <= #cell_data and cell_data[column_index] then
                     table.insert(sections, {
                     result = clean_wikilinks(cell_data[column_index])
                        display = processed,
                     break -- Знайшли, виходимо
                        anchor = anchor
                     })
                 end
                 end
             end
             end
         end
         end
     end
     end
    return result
end
----------------------------------------------------------------------
-- ФУНКЦІЇ ДЛЯ {{MCC Player New}} (використовують fetch_from_table)
----------------------------------------------------------------------
function p.recruiter(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4) -- Колонка 4
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     if #sections == 0 then
        return ""
    end
      
      
     if raw == "Відсутній" or raw == "-" then return "Не вказано" end
     -- Будуємо HTML
    return raw or "Не вказано"
     local html_parts = {}
end
 
function p.date_added(frame)
    local name = frame.args.player
     local raw = fetch_from_table("Гравці", name, 3) -- Колонка 3
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     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;">')
      
      
     return raw or "Невідомо"
     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>')
end
 
function p.prize_pool(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Призовий_фонд", name, 3)  
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     for i, section in ipairs(sections) do
   
        local border = ""
    if raw then
        if i < #sections then
         raw = mw.ustring.gsub(raw, "[^%d%s]", "")
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
        raw = mw.text.trim(raw)
        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
     end
    return (raw or "0") .. " ₴"
end
function p.foundation(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фундація", name, 3)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
    return (raw or "0") .. " ₴"
end
function p.final(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фіналіст", name, 3)
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     table.insert(html_parts, '</div>')
      
      
     local count = raw and mw.ustring.match(raw, "(%d+)")
     return table.concat(html_parts, '\n')
   
    if count then
        return count
    else
        return "0"
    end
end
 
-- Ця функція залишається порожньою, як ви просили на початку, щоб не чіпати сезони
function p.season_result(frame)
    return nil
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