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)
amélioration
Hiob (discussion | contributions)
Aucun résumé des modifications
 
(Une version intermédiaire par le même utilisateur non affichée)
Ligne 1 : Ligne 1 :
local p = {}
local p = {}


-- Palette inspirée de Bootstrap 5 + Citizen
-- =============================================================================
-- Palette : uniquement les noms → classe CSS + variables --nefald-*
-- Pas de couleurs en dur : tout est géré par Citizen.css
-- =============================================================================
 
local colors = {
local colors = {
    -- Variantes de succès (vert)
     success = { class = "table-color-success",   label = "Succès",       var = "nefald-success" },
     success = { bg = "#d1e7dd", fg = "#0f5132", label = "Succès" },
     danger  = { class = "table-color-danger",   label = "Danger",       var = "nefald-danger"   },
     ["success-light"] = { bg = "#e8f5e9", fg = "#1b5e20", label = "Succès clair" },
     warning  = { class = "table-color-warning",   label = "Avertissement", var = "nefald-warning" },
   
     info    = { class = "table-color-info",     label = "Info",         var = "nefald-info"    },
    -- Variantes de danger (rouge)
     secondary = { class = "table-color-secondary", label = "Neutre",       var = "nefald-neutral" },
    danger = { bg = "#f8d7da", fg = "#842029", label = "Danger" },
}
     ["danger-light"] = { bg = "#ffebee", fg = "#c62828", label = "Danger clair" },
 
   
-- Aliases → entrée canonique
    -- Variantes d'avertissement (jaune/orange)
local aliases = {
    warning = { bg = "#fff3cd", fg = "#664d03", label = "Avertissement" },
     vert   = "success",
     ["warning-light"] = { bg = "#fffde7", fg = "#f57f17", label = "Avertissement clair" },
     rouge   = "danger",
   
     jaune   = "warning",
    -- Variantes d'information (bleu)
     bleu    = "info",
    info = { bg = "#cfe2ff", fg = "#084298", label = "Info" },
     gris   = "secondary",
    ["info-light"] = { bg = "#e3f2fd", fg = "#01579b", label = "Info clair" },
    neutre  = "secondary",
   
    neutral = "secondary",
     -- Variantes neutres
     primary = "info",
    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)
-- Ordre d'affichage stable
local function darkenColor(hex)
local order = { "success", "danger", "warning", "info", "secondary" }
    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ésolution d'un nom (gère alias + trim + lowercase)
   
-- =============================================================================
    r = math.floor(r * 0.7)
 
     g = math.floor(g * 0.7)
local function resolve(name)
    b = math.floor(b * 0.7)
     name = mw.text.trim(name or ""):lower()
      
     name = aliases[name] or name
     return string.format("#%02x%02x%02x", r, g, b)
     return colors[name], name
end
end


-- Fonction principale unifiée avec auto-détection AMÉLIORÉE
-- =============================================================================
-- p.cell — génère une cellule de tableau OU un badge inline
--
-- Usage tableau  : {{Couleur|success|Texte}}  → style="..." | Texte
-- Usage texte    : {{Couleur|danger|Texte}}  → <span class="...">Texte</span>
-- =============================================================================
 
function p.cell(frame)
function p.cell(frame)
     local args = frame:getParent().args
     local args = frame:getParent().args
     local colorName = mw.text.trim(args[1] or ""):lower()
     local colorName = mw.text.trim(args[1] or ""):lower()
    colorName = aliases[colorName] or colorName
     local content = args[2] or ""
     local content = args[2] or ""
   
     local trimmed = mw.text.trim(content)
    -- Gestion des alias
 
     local aliases = {
     local color = colors[colorName]
        ["gris-"] = "info-light",
     if not color then
        ["gris+"] = "secondary",
        return content
        ["vert-clair"] = "success-light",
     end
        ["rouge-clair"] = "danger-light",
 
    }
     -- Détection du contexte : tableau si le contenu est court et sans ponctuation lourde
   
     local isTableMode = frame:getParent():getTitle() == "" or
    colorName = aliases[colorName] or colorName
        (trimmed:len() < 60 and not trimmed:match("[%.%!%?]") and not trimmed:match("\n"))
     local color = colors[colorName] or colors.light
 
      
     -- Forcer texte si le parent est un wikitable en cours de parsing
    -- DÉTECTION AUTOMATIQUE STRICTE
     -- On se fie au premier argument vide = cellule de tableau
    local useTableMode = false
     if trimmed == "" then
     local trimmedContent = mw.text.trim(content)
         return string.format('class="%s" | ', color.class)
   
     -- 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
     end
   
 
     -- FORCER MODE TEXTE si indicateurs clairs
     -- Heuristique simple : contenu court sans ponctuation → mode tableau
     if hasEmoji or hasBoldWithColon or hasLongText or hasPunctuation then
    local hasLong      = trimmed:len() > 80
         useTableMode = false
    local hasPunct    = trimmed:match("[%.!%?;]") ~= nil
    local hasNewline  = trimmed:match("\n") ~= nil
 
     if hasLong or hasPunct or hasNewline then
         -- Badge inline
        return string.format('<span class="%s" style="padding:4px 10px;border-radius:6px;display:inline-block;font-weight:500;border-left:none;border:1.5px solid var(--%s-border)">%s</span>',
            color.class, color.var, content)
    else
        -- Cellule wikitable
        return string.format('class="%s" | %s', color.class, content)
     end
     end
      
end
     -- Construction des styles
 
     local cellStyle = string.format(
-- =============================================================================
         'background-color:%s; color:%s; padding:8px 12px;',
-- p.badge — badge inline explicite (pas d'ambiguïté)
         color.bg,
-- Usage : {{#invoke:TableColors|badge|success|Texte}}
        color.fg
-- =============================================================================
 
function p.badge(frame)
     local args = frame.args
     local color, _ = resolve(args[1] or "")
     local content = args[2] or ""
    if not color then return content end
 
    return string.format(
         '<span class="%s" style="padding:4px 10px;border-radius:6px;display:inline-block;font-weight:500;border-left:none;border:1.5px solid var(--%s-border)">%s</span>',
         color.class, color.var, content
     )
     )
   
    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
end


-- Fonction pour lister les couleurs disponibles
-- =============================================================================
-- p.list — tableau de référence de toutes les couleurs
-- Usage : {{#invoke:TableColors|list}}
-- =============================================================================
 
function p.list(frame)
function p.list(frame)
     local rows = {}
     local rows = {}
   
 
    local sorted = {}
     for _, name in ipairs(order) do
    for name, _ in pairs(colors) do
        table.insert(sorted, name)
    end
    table.sort(sorted)
   
     for _, name in ipairs(sorted) do
         local color = colors[name]
         local color = colors[name]
       
 
        -- Badge exemple
        local borderColor = darkenColor(color.bg)
         local badge = string.format(
         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>',
             '<span class="%s" style="padding:4px 10px;border-radius:6px;display:inline-block;font-weight:500;border-left:none;border:1.5px solid var(--%s-border)">%s</span>',
             color.bg,
             color.class, color.var, color.label
            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(
         table.insert(rows, string.format(
             '|-\n| %s || %s || %s || <code>{{Couleur|%s|...}}</code>',
             '|-\n| %s || %s || class="%s" | %s || <code>{{Couleur|%s|...}}</code>',
             color.label,
             color.label,
             badge,
             badge,
             cell,
             color.class,
            color.label,
             name
             name
         ))
         ))
     end
     end
   
 
     local wikitext = '{| class="wikitable sortable"\n! Nom !! Badge (texte) !! Cellule (tableau) !! Code\n'  
     local wikitext = '{| class="wikitable"\n! Nom !! Badge !! Cellule !! Syntaxe\n'
         .. table.concat(rows, '\n')  
         .. table.concat(rows, '\n')
         .. '\n|}'
         .. '\n|}'
   
 
     return frame:preprocess(wikitext)
     return frame:preprocess(wikitext)
end
-- =============================================================================
-- p.palette — grille de cards pour Aide:Charte graphique
-- Usage : {{#invoke:TableColors|palette}}
-- =============================================================================
function p.palette(frame)
    local cards = {}
    for _, name in ipairs(order) do
        local color = colors[name]
        local card = string.format(
            '{{Card|title=%s|subtitle=var(--%s-bg)|bgcolor=var(--%s-bg)|colorheight=80|text=<code>%s</code>}}',
            color.label,
            color.var,
            color.var,
            color.class
        )
        table.insert(cards, card)
    end
    local output = '<div class="ds-swatch-grid">\n'
        .. table.concat(cards, '\n')
        .. '\n</div>'
    return frame:preprocess(output)
end
end


return p
return p
Les témoins (''cookies'') nous aident à fournir nos services. En utilisant nos services, vous acceptez notre utilisation de témoins.