Module:UnitLinker

From Heroes of Might and Magic: Olden Era Official Wiki

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

local p = {}

-- Fonction pour charger toutes les unités en mémoire (Mise en cache interne)
local function getUnitRegistry(lang)
    local registry = {}
    local cargoQuery = mw.ext.cargo.query("Translation", "target_id, name", {
        where = "type = 'unit' AND (language = 'en' OR language = '" .. lang .. "')",
        orderBy = "target_id"
    })
    
    -- On organise les données pour un accès rapide : registry[nom_traduit] = nom_anglais
    for _, row in ipairs(cargoQuery) do
        registry[row.name] = row.target_id
    end
    return registry
end

-- Fonction principale : replace les noms d'unités dans un texte
function p.link(frame)
    local text = frame.args[1] or ""
    local title = mw.title.getCurrentTitle().text
    local lang = mw.ustring.match(title, "/([a-z_]+)$") or "en"
    
    -- Si la langue est "en", on ne traite que les noms anglais, sinon on charge les deux
    local registry = getUnitRegistry(lang)
    
    -- On trie les clés par longueur décroissante pour éviter de remplacer "Swordsman" 
    -- dans "Temple Swordsman" avant de traiter le nom complet.
    local keys = {}
    for k in pairs(registry) do table.insert(keys, k) end
    table.sort(keys, function(a, b) return #a > #b end)
    
    -- Remplacement
    for _, unitName in ipairs(keys) do
        local engName = registry[unitName]
        local link
        
        -- Construction du lien selon la langue
        if lang == "en" then
            link = "[[" .. engName .. "]]"
        else
            link = "[[" .. engName .. "/" .. lang .. "|" .. unitName .. "]]"
        end
        
        -- Échappement des caractères spéciaux pour le pattern (si nécessaire)
        -- On utilise une frontière de mot (%f[%a]) pour éviter de couper des mots.
        local pattern = "%f[%a]" .. mw.ustring.gsub(unitName, "([%(%)%.%%%+%-%*%?%[%^%$])", "%%%1") .. "%f[%A]"
        text = mw.ustring.gsub(text, pattern, link)
    end
    
    return text
end

return p