Aller au contenu

Module:TreeList

De Wikiquestia
Version datée du 12 juin 2025 à 07:11 par Alakihel (discussion | contributions) (Page créée avec « local p = {} -- Fonction utilitaire pour diviser une chaîne avec un séparateur local function split(text, sep) if not sep then sep = ">" end local result = {} for token in mw.text.gsplit(text, sep, true) do table.insert(result, mw.text.trim(token)) end return result end -- Construction récursive de l'arbre local function insertPath(tree, path) local node = tree for _, part in ipairs(path) do node.children = node.children or {} node.children[part... »)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)

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

local p = {}

-- Fonction utilitaire pour diviser une chaîne avec un séparateur
local function split(text, sep)
	if not sep then sep = ">" end
	local result = {}
	for token in mw.text.gsplit(text, sep, true) do
		table.insert(result, mw.text.trim(token))
	end
	return result
end

-- Construction récursive de l'arbre
local function insertPath(tree, path)
	local node = tree
	for _, part in ipairs(path) do
		node.children = node.children or {}
		node.children[part] = node.children[part] or {}
		node = node.children[part]
	end
end

-- Rendu récursif
local function renderNode(node, prefix, isLast, level, colorByLevel)
	local output = ""
	local keys = {}

	-- Collecter les enfants dans l’ordre
	for k in pairs(node.children or {}) do table.insert(keys, k) end
	table.sort(keys)

	for i, name in ipairs(keys) do
		local child = node.children[name]
		local isLastChild = (i == #keys)

		local line = prefix
		if prefix ~= "" then
			line = line .. (isLast and "    " or "│   ")
		end
		line = line .. (isLastChild and "└── " or "├── ")

		local color = colorByLevel[level] or ""
		local text = name:match("^%[%[.+%]%]$") and name or "[[" .. name .. "]]"
		if color ~= "" then
			line = line .. string.format('<span style="color:%s;">%s</span>\n', color, text)
		else
			line = line .. text .. "\n"
		end

		output = output .. line
		output = output .. renderNode(child, prefix .. (isLast and "    " or "│   "), isLastChild, level + 1, colorByLevel)
	end

	return output
end

-- Point d’entrée principal
function p.render(frame)
	local args = frame:getParent().args
	local paths = {}

	-- Récupérer les chaînes de type : Langue > Sous-langue > ...
	for _, v in ipairs(args) do
		if v and v ~= "" then
			table.insert(paths, split(v))
		end
	end

	-- Définir les couleurs par niveau
	local colorByLevel = {
		[1] = "#993333",
		[2] = "#209a57",
		[3] = "#2080a5",
		[4] = "#5555cc",
		[5] = "#cc3366",
	}

	-- Construire l'arbre
	local root = {}
	for _, path in ipairs(paths) do
		insertPath(root, path)
	end

	-- Rendu final
	local result = '<div style="font-family:monospace; white-space:pre;">\n'
	result = result .. renderNode(root, "", true, 1, colorByLevel)
	result = result .. '</div>'
	return result
end

return p