Module:BiographyNav

From HandWiki Test
Revision as of 07:18, 25 May 2026 by WikiHarold (talk | contribs) (Add biography previous-next navigation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:BiographyNav/doc

local p = {}

local DATA_PAGE = 'Template:Biography page/list'

local function trim(s)
    if not s then
        return ''
    end
    return mw.text.trim(s)
end

local function escapeHtml(s)
    return mw.text.encode(s or '')
end

local function displayLabel(title)
    title = title or ''
    title = title:gsub('^Biography:', '')
    title = title:gsub('_', ' ')
    return title
end

local function getList()
    local title = mw.title.new(DATA_PAGE)
    local text = title and title:getContent() or ''
    local pages = {}

    for raw in text:gmatch('%[%[([^%]]+)%]%]') do
        local target = raw:match('^([^|#]+)') or raw
        target = trim(target)

        if target:match('^Biography:') then
            table.insert(pages, target)
        end
    end

    return pages
end

local function renderLink(className, target, prefix, suffix)
    if not target or target == '' then
        return '<div class="quantum-article-nav-empty"></div>'
    end

    return '<div class="' .. className .. '">[[' .. target .. '|' ..
        escapeHtml(prefix .. displayLabel(target) .. suffix) .. ']]</div>'
end

function p.nav(frame)
    local current = mw.title.getCurrentTitle()
    local currentName = current and current.prefixedText or ''
    local pages = getList()
    local previous = ''
    local nextPage = ''

    for i, page in ipairs(pages) do
        if page == currentName then
            if i > 1 then
                previous = pages[i - 1]
            end
            if i < #pages then
                nextPage = pages[i + 1]
            end
            break
        end
    end

    if previous == '' and nextPage == '' then
        return ''
    end

    return '<div class="quantum-article-nav">' ..
        renderLink('quantum-article-nav-previous', previous, '← Previous: ', '') ..
        renderLink('quantum-article-nav-next', nextPage, 'Next: ', ' →') ..
        '</div>'
end

return p