Module:UnitLinker: Difference between revisions

From Heroes of Might and Magic: Olden Era Official Wiki
Created page with "local p = {} -- Fonction pour déterminer la langue à partir du titre de la page local function getLanguage() local title = mw.title.getCurrentTitle().text local lang = mw.ustring.match(title, "/([a-z_]+)$") if not lang or lang == "en" then return "en" end return lang end -- Fonction pour vérifier si un nom d'unité est valide et obtenir son nom anglais de base local function resolveUnit(name) -- Recherche dans la table Translation pour trouver le..."
 
No edit summary
Line 1: Line 1:
local p = {}
local p = {}


-- Fonction pour déterminer la langue à partir du titre de la page
-- Fonction pour charger toutes les unités en mémoire (Mise en cache interne)
local function getLanguage()
local function getUnitRegistry(lang)
    local title = mw.title.getCurrentTitle().text
     local registry = {}
     local lang = mw.ustring.match(title, "/([a-z_]+)$")
     local cargoQuery = mw.ext.cargo.query("Translation", "target_id, name", {
    if not lang or lang == "en" then return "en" end
         where = "type = 'unit' AND (language = 'en' OR language = '" .. lang .. "')",
    return lang
         orderBy = "target_id"
end
 
-- Fonction pour vérifier si un nom d'unité est valide et obtenir son nom anglais de base
local function resolveUnit(name)
    -- Recherche dans la table Translation pour trouver le nom anglais (target_id)
    -- si le nom fourni est déjà une traduction
     local res = mw.ext.cargo.query("Translation", "target_id", {
         where = "type = 'unit' AND name = '" .. name .. "'",
         limit = 1
     })
     })
      
      
     if res and #res > 0 then return res[1].target_id end
     -- On organise les données pour un accès rapide : registry[nom_traduit] = nom_anglais
      
     for _, row in ipairs(cargoQuery) do
    -- Sinon, vérifier si le nom est déjà un nom anglais valide dans la table Unit
        registry[row.name] = row.target_id
    local unitCheck = mw.ext.cargo.query("Unit", "id", { where = "id = '" .. name .. "'", limit = 1 })
     end
     if unitCheck and #unitCheck > 0 then return name end
     return registry
   
     return nil
end
end


-- Fonction principale appelée par {{#invoke:UnitLinker|link|Ton texte ici}}
-- Fonction principale : replace les noms d'unités dans un texte
function p.link(frame)
function p.link(frame)
     local text = frame.args[1] or ""
     local text = frame.args[1] or ""
     local lang = getLanguage()
    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)
      
      
     -- On utilise une fonction de remplacement globale
     -- Remplacement
     local processedText = mw.ustring.gsub(text, "([%a%s]+)", function(match)
     for _, unitName in ipairs(keys) do
         local unitName = mw.text.trim(match)
         local engName = registry[unitName]
         local baseName = resolveUnit(unitName)
         local link
          
          
         if baseName then
         -- Construction du lien selon la langue
            -- Si anglais, lien simple
        if lang == "en" then
            if lang == "en" then
            link = "[[" .. engName .. "]]"
                return "[[" .. baseName .. "]]"
        else
            else
            link = "[[" .. engName .. "/" .. lang .. "|" .. unitName .. "]]"
                -- Si autre langue, on cherche le nom traduit pour le display
                local trans = mw.ext.cargo.query("Translation", "name", {
                    where = "type = 'unit' AND target_id = '" .. baseName .. "' AND language = '" .. lang .. "'",
                    limit = 1
                })
                local displayName = (trans and #trans > 0) and trans[1].name or unitName
                return "[[" .. baseName .. "/" .. lang .. "|" .. displayName .. "]]"
            end
         end
         end
         return match
          
     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 processedText
     return text
end
end


return p
return p

Revision as of 15:36, 13 June 2026

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