Basculer le menu
Changer de menu des préférences
Basculer le menu personnel
Non connecté(e)
Votre adresse IP sera visible au public si vous faites des modifications.

« Module:TableColors » : différence entre les versions

De Nefald
Hiob (discussion | contributions)
Auto détection tableau / texte en ligne
Hiob (discussion | contributions)
amélioration
 
Ligne 47 : Ligne 47 :
end
end


-- Détection automatique du contexte (tableau vs texte)
-- Fonction principale unifiée avec auto-détection AMÉLIORÉE
local function isInTableContext(frame)
    -- Récupère le wikitext parent
    local parent = frame:getParent()
    if not parent then return false end
   
    -- Récupère le titre de la page
    local title = mw.title.getCurrentTitle()
    local content = title:getContent()
   
    if not content then return false end
   
    -- Cherche si le modèle est appelé dans un contexte de tableau
    -- On détecte les patterns typiques : {| ... {{Couleur ... |}
    local pattern = "%{%|.-%{%{[Cc]ouleur%|.-%}%}.-%|%}"
   
    return content:match(pattern) ~= nil
end
 
-- Fonction principale unifiée avec auto-détection
function p.cell(frame)
function p.cell(frame)
     local args = frame:getParent().args
     local args = frame:getParent().args
Ligne 83 : Ligne 64 :
     local color = colors[colorName] or colors.light
     local color = colors[colorName] or colors.light
      
      
     -- DÉTECTION AUTOMATIQUE AMÉLIORÉE
     -- DÉTECTION AUTOMATIQUE STRICTE
     local useTableMode = false
     local useTableMode = false
    local trimmedContent = mw.text.trim(content)
   
    -- Indicateurs de contexte TABLEAU
    local hasTableSyntax = content:match("%|%|") or content:match("!!") or content:match("%|-")
    local startsWithCode = trimmedContent:match("^<code>")
    local isShortLabel = mw.ustring.len(trimmedContent) <= 20 and not trimmedContent:match("%s%s")
   
    -- Indicateurs de contexte TEXTE (badge inline)
    local hasEmoji = trimmedContent:match("[💡⚠️🔥ℹ️✓✗🎯📌❌✅⭐🎨]")
    local hasBoldWithColon = trimmedContent:match("'''[^']+'''%s*:")
    local hasLongText = mw.ustring.len(trimmedContent) > 40
    local hasPunctuation = trimmedContent:match("[%.%,%;%!%?]") and mw.ustring.len(trimmedContent) > 15
      
      
     -- Méthode 1 : Détection par le contenu vide (cellule de tableau)
     -- DÉCISION : MODE TABLEAU si critères stricts
     if mw.text.trim(content) == "" then
     if hasTableSyntax or startsWithCode then
         useTableMode = true
         useTableMode = true
   
     elseif trimmedContent == "" then
    -- Méthode 2 : Détection par balises HTML typiques de tableaux
     elseif content:match("^%s*<code>") or content:match("^%s*'''") then
         useTableMode = true
         useTableMode = true
   
     elseif isShortLabel and not hasEmoji and not hasBoldWithColon then
    -- Méthode 3 : Contenu très court (probablement un en-tête de tableau)
     elseif mw.ustring.len(mw.text.trim(content)) <= 20 and not content:match("%s%s") then
         useTableMode = true
         useTableMode = true
    end
      
      
     -- Méthode 4 : Présence de syntaxe wiki spécifique aux tableaux
     -- FORCER MODE TEXTE si indicateurs clairs
     elseif content:match("||") or content:match("!!") then
     if hasEmoji or hasBoldWithColon or hasLongText or hasPunctuation then
         useTableMode = true
         useTableMode = false
     end
     end
      
      
Ligne 120 : Ligne 110 :
     -- MODE TABLEAU
     -- MODE TABLEAU
     if useTableMode then
     if useTableMode then
         if mw.text.trim(content) == "" then
         if trimmedContent == "" then
             return 'style="' .. cellStyle .. '" | '
             return 'style="' .. cellStyle .. '" | '
         end
         end
Ligne 127 : Ligne 117 :
      
      
     -- MODE TEXTE (badge)
     -- MODE TEXTE (badge)
     if mw.text.trim(content) == "" then
     if trimmedContent == "" then
         return ''
         return ''
     end
     end
Ligne 154 : Ligne 144 :
             color.fg,
             color.fg,
             borderColor,
             borderColor,
            color.label
        )
       
        -- Cellule exemple
        local cell = string.format(
            'style="background-color:%s; color:%s; padding:8px 12px;" | %s',
            color.bg,
            color.fg,
             color.label
             color.label
         )
         )
          
          
         table.insert(rows, string.format(
         table.insert(rows, string.format(
             '|-\n| %s || %s || <code>{{Couleur|%s|Texte}}</code>',
             '|-\n| %s || %s || %s || <code>{{Couleur|%s|...}}</code>',
             color.label,
             color.label,
             badge,
             badge,
            cell,
             name
             name
         ))
         ))
     end
     end
      
      
     local wikitext = '{| class="wikitable sortable"\n! Nom !! Aperçu (badge) !! Code\n'  
     local wikitext = '{| class="wikitable sortable"\n! Nom !! Badge (texte) !! Cellule (tableau) !! Code\n'  
         .. table.concat(rows, '\n')  
         .. table.concat(rows, '\n')  
         .. '\n|}'
         .. '\n|}'

Dernière version du 9 octobre 2025 à 07:40

La documentation pour ce module peut être créée à Module:TableColors/doc

local p = {}

-- Palette inspirée de Bootstrap 5 + Citizen
local colors = {
    -- Variantes de succès (vert)
    success = { bg = "#d1e7dd", fg = "#0f5132", label = "Succès" },
    ["success-light"] = { bg = "#e8f5e9", fg = "#1b5e20", label = "Succès clair" },
    
    -- Variantes de danger (rouge)
    danger = { bg = "#f8d7da", fg = "#842029", label = "Danger" },
    ["danger-light"] = { bg = "#ffebee", fg = "#c62828", label = "Danger clair" },
    
    -- Variantes d'avertissement (jaune/orange)
    warning = { bg = "#fff3cd", fg = "#664d03", label = "Avertissement" },
    ["warning-light"] = { bg = "#fffde7", fg = "#f57f17", label = "Avertissement clair" },
    
    -- Variantes d'information (bleu)
    info = { bg = "#cfe2ff", fg = "#084298", label = "Info" },
    ["info-light"] = { bg = "#e3f2fd", fg = "#01579b", label = "Info clair" },
    
    -- Variantes neutres
    primary = { bg = "#cfe2ff", fg = "#052c65", label = "Primaire" },
    secondary = { bg = "#e2e3e5", fg = "#41464b", label = "Secondaire" },
    light = { bg = "#f8f9fa", fg = "#495057", label = "Clair" },
    dark = { bg = "#ced4da", fg = "#212529", label = "Foncé" },
    
    -- Compatibilité anciens noms
    vert = { bg = "#d1e7dd", fg = "#0f5132", label = "Vert" },
    rouge = { bg = "#f8d7da", fg = "#842029", label = "Rouge" },
    jaune = { bg = "#fff3cd", fg = "#664d03", label = "Jaune" },
    rose = { bg = "#f8d7da", fg = "#842029", label = "Rose" },
    gris = { bg = "#e2e3e5", fg = "#41464b", label = "Gris" },
    bleu = { bg = "#cfe2ff", fg = "#084298", label = "Bleu" },
}

-- Fonction pour assombrir une couleur (pour la bordure)
local function darkenColor(hex)
    local r = tonumber(hex:sub(2, 3), 16)
    local g = tonumber(hex:sub(4, 5), 16)
    local b = tonumber(hex:sub(6, 7), 16)
    
    r = math.floor(r * 0.7)
    g = math.floor(g * 0.7)
    b = math.floor(b * 0.7)
    
    return string.format("#%02x%02x%02x", r, g, b)
end

-- Fonction principale unifiée avec auto-détection AMÉLIORÉE
function p.cell(frame)
    local args = frame:getParent().args
    local colorName = mw.text.trim(args[1] or ""):lower()
    local content = args[2] or ""
    
    -- Gestion des alias
    local aliases = {
        ["gris-"] = "info-light",
        ["gris+"] = "secondary",
        ["vert-clair"] = "success-light",
        ["rouge-clair"] = "danger-light",
    }
    
    colorName = aliases[colorName] or colorName
    local color = colors[colorName] or colors.light
    
    -- DÉTECTION AUTOMATIQUE STRICTE
    local useTableMode = false
    local trimmedContent = mw.text.trim(content)
    
    -- Indicateurs de contexte TABLEAU
    local hasTableSyntax = content:match("%|%|") or content:match("!!") or content:match("%|-")
    local startsWithCode = trimmedContent:match("^<code>")
    local isShortLabel = mw.ustring.len(trimmedContent) <= 20 and not trimmedContent:match("%s%s")
    
    -- Indicateurs de contexte TEXTE (badge inline)
    local hasEmoji = trimmedContent:match("[💡⚠️🔥ℹ️✓✗🎯📌❌✅⭐🎨]")
    local hasBoldWithColon = trimmedContent:match("'''[^']+'''%s*:")
    local hasLongText = mw.ustring.len(trimmedContent) > 40
    local hasPunctuation = trimmedContent:match("[%.%,%;%!%?]") and mw.ustring.len(trimmedContent) > 15
    
    -- DÉCISION : MODE TABLEAU si critères stricts
    if hasTableSyntax or startsWithCode then
        useTableMode = true
    elseif trimmedContent == "" then
        useTableMode = true
    elseif isShortLabel and not hasEmoji and not hasBoldWithColon then
        useTableMode = true
    end
    
    -- FORCER MODE TEXTE si indicateurs clairs
    if hasEmoji or hasBoldWithColon or hasLongText or hasPunctuation then
        useTableMode = false
    end
    
    -- Construction des styles
    local cellStyle = string.format(
        'background-color:%s; color:%s; padding:8px 12px;',
        color.bg,
        color.fg
    )
    
    local borderColor = darkenColor(color.bg)
    local spanStyle = string.format(
        'background-color:%s; color:%s; padding:6px 12px; border-radius:6px; border:1.5px solid %s; display:inline-block; font-weight:500;',
        color.bg,
        color.fg,
        borderColor
    )
    
    -- MODE TABLEAU
    if useTableMode then
        if trimmedContent == "" then
            return 'style="' .. cellStyle .. '" | '
        end
        return 'style="' .. cellStyle .. '" | ' .. content
    end
    
    -- MODE TEXTE (badge)
    if trimmedContent == "" then
        return ''
    end
    
    return string.format('<span style="%s">%s</span>', spanStyle, content)
end

-- Fonction pour lister les couleurs disponibles
function p.list(frame)
    local rows = {}
    
    local sorted = {}
    for name, _ in pairs(colors) do
        table.insert(sorted, name)
    end
    table.sort(sorted)
    
    for _, name in ipairs(sorted) do
        local color = colors[name]
        
        -- Badge exemple
        local borderColor = darkenColor(color.bg)
        local badge = string.format(
            '<span style="background-color:%s; color:%s; padding:6px 12px; border-radius:6px; border:1.5px solid %s; display:inline-block; font-weight:500;">%s</span>',
            color.bg,
            color.fg,
            borderColor,
            color.label
        )
        
        -- Cellule exemple
        local cell = string.format(
            'style="background-color:%s; color:%s; padding:8px 12px;" | %s',
            color.bg,
            color.fg,
            color.label
        )
        
        table.insert(rows, string.format(
            '|-\n| %s || %s || %s || <code>{{Couleur|%s|...}}</code>',
            color.label,
            badge,
            cell,
            name
        ))
    end
    
    local wikitext = '{| class="wikitable sortable"\n! Nom !! Badge (texte) !! Cellule (tableau) !! Code\n' 
        .. table.concat(rows, '\n') 
        .. '\n|}'
    
    return frame:preprocess(wikitext)
end

return p