Fandom Developers Wiki
Documentation icon Module documentation

-- <nowiki>
-- This module implements context-link templates.
local p = {}
local getArgs = require('Dev:Arguments').getArgs
local i18n = require('Dev:i18n').loadMessages('Context-link')
local comma = require('Dev:Comma').main

-- Helper functions

local function findNamespace(link)
    local namespace = link:match('^(.-):')

    if namespace then
        local namespaces = mw.site.namespaces[namespace]
        if namespaces then
            return namespaces.id
        end
    end

    return 0
end
 
local function formatLink(link, display)
    local namespace = findNamespace(link, false)
    local colon

    if namespace == 6 or namespace == 14 then
        colon = ':'
    else
        colon = ''
    end
 
    -- Find the display value.
    if not display then
        local page, section = link:match('^(.-)#(.*)$')
        if page then
            display = page .. i18n:msg('section') .. section
        end
    end
 
    -- Assemble the link.
    if display then
        return string.format('[[%s%s|%s]]', colon, link, display)
    else
        return string.format('[[%s%s]]', colon, link)
    end
end

local function build(desc, links, options)
    local linktext
    
    if next(links) == nil then
        linktext = i18n:msg('ellipsis')
    else
        linktext = comma(links)
    end
    
    local outputString = (desc or i18n:msg('desc')) .. (i18n:msg('space') == 'yes' and '&#32;' or '') .. linktext
    
    local container = mw.html.create('div')
        :addClass('context-link')
        :addClass(options.extraclasses)
        :attr('data-nosnippet', 'true')
        :cssText(options.extrastyles)
        :wikitext(outputString)

    return tostring(container)
end

-- Produces standard context-link text.
function p.contextlink(frame)
    local args = getArgs(frame)
    local desc = args.desc
    local links = {}
    for i, link in ipairs(args) do
        local display = args['t' .. i]
        table.insert(links, formatLink(link, display))
    end

    local options = {}
    options.extraclasses = args.class
    options.extrastyles = args.style
    return build(desc, links, options)
end

return p
-- </nowiki>