Модуль:FetchData2: відмінності між версіями

Немає опису редагування
Немає опису редагування
Мітка: Ручний відкіт
 
(Не показано 28 проміжних версій цього користувача)
Рядок 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. Details: %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)
local function parse_table_cells(row_text)
     if page_cache[page_name] then
     local cells = {}
        return page_cache[page_name]
    local current_cell = ""
    local in_link = false
    local i = 1
   
    while i <= #row_text do
        local char = row_text:sub(i, i)
        local next_char = row_text:sub(i + 1, i + 1)
       
        -- Відслідковуємо вікі-посилання
        if char == "[" and next_char == "[" then
            in_link = true
            current_cell = current_cell .. "[["
            i = i + 2
        elseif char == "]" and next_char == "]" then
            in_link = false
            current_cell = current_cell .. "]]"
            i = i + 2
        -- Якщо знайшли роздільник комірок
        elseif char == "|" and not in_link then
            if next_char == "|" then
                -- || - роздільник комірок
                table.insert(cells, mw.text.trim(current_cell))
                current_cell = ""
                i = i + 2
            else
                -- | на початку рядка - також роздільник
                if current_cell ~= "" then
                    table.insert(cells, mw.text.trim(current_cell))
                    current_cell = ""
                end
                i = i + 1
            end
        else
            current_cell = current_cell .. char
            i = i + 1
        end
     end
     end
      
      
     -- Додаємо останню комірку
     local title = mw.title.new(page_name)
     if current_cell ~= "" then
     if not title or not title.exists then
         table.insert(cells, mw.text.trim(current_cell))
        page_cache[page_name] = nil
         return nil
     end
     end
      
      
     return cells
    local content = title:getContent()
    page_cache[page_name] = content
     return content
end
end


----------------------------------------------------------------------
-- ================================================
-- ГОЛОВНИЙ ПАРСЕР ДЛЯ ГОРИЗОНТАЛЬНИХ ТАБЛИЦЬ
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
----------------------------------------------------------------------
-- ================================================
local function fetch_from_table(page_title, player_name, column_index)
 
   
function p.section_menu(frame)
    if not player_name or player_name == "" then
     local page_name = frame.args.page or mw.title.getCurrentTitle().text
        return error_output("No Player Name", page_title)  
     local content = get_page_content(page_name)
    end
   
     local title = mw.title.new(page_title)
    if not title or not title.exists then
        return error_output("Page Missing", page_title)
    end
   
     local content = title:getContent()
    if not content then
        return error_output("Content Read Fail", page_title)
    end
      
      
    -- Знаходимо таблицю
     if not content then
    local table_content = mw.ustring.match(content, "{|.-(.-|})")
         return ""
     if not table_content then  
         return error_output("Table Missing", page_title)
     end
     end
      
      
     local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
     local sections = {}
    local player_pattern = "%[%[" .. escaped .. "%]%]"
      
      
    -- Парсимо рядки таблиці
     for line in mw.ustring.gmatch(content, "[^\n]+") do
     for row in mw.ustring.gmatch(table_content, "|\n(.-)\n|-") do
         -- ТІЛЬКИ заголовки рівня 2: == Назва ==
         row = row .. "\n" -- Додаємо перенос для коректної обробки
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
       
             local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
        -- Перевіряємо, чи є ім'я гравця в цьому рядку
        if mw.ustring.find(row, player_pattern) then
             local cells = parse_table_cells(row)
              
              
             if column_index <= #cells and cells[column_index] then
             if section_name and section_name ~= "" then
                 return clean_wikilinks(cells[column_index])
                 -- Виконуємо шаблони щоб отримати реальний текст
                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
     end
      
      
    return nil
     if #sections == 0 then
end
         return ""
 
----------------------------------------------------------------------
-- ФУНКЦІЇ, ЩО ВИКЛИКАЮТЬСЯ З ШАБЛОНУ
----------------------------------------------------------------------
function p.recruiter(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4)
   
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then  
         return raw
     end
     end
      
      
     if raw == "Відсутній" or raw == "-" or not raw then
     -- Будуємо HTML
        return "Не вказано"
     local html_parts = {}
     end
      
      
     return raw
     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
 
function p.date_added(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3)  
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then
     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>')
        return raw
    end
      
      
     return raw or "Невідомо"
     for i, section in ipairs(sections) do
end
        local border = ""
 
        if i < #sections then
function p.prize_pool(frame)
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
    local name = frame.args.player
        end
    local raw = fetch_from_table("Призовий_фонд", name, 3)  
       
   
        table.insert(html_parts, string.format(
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
         return raw
            border, section.anchor, section.display
         ))
     end
     end
      
      
     if raw then
     table.insert(html_parts, '</div>')
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
      
      
     return (raw or "0") .. " ₴"
     return table.concat(html_parts, '\n')
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