Aller au contenu

Module:Bacasable

Une page de Wikipédia, l'encyclopédie libre.
Ceci est une version archivée de cette page, en date du 18 mai 2018 à 23:20 et modifiée en dernier par Hlm Z. (discuter | contributions). Elle peut contenir des erreurs, des inexactitudes ou des contenus vandalisés non présents dans la version actuelle.

 Documentation[créer] [purger]
local data = {
	cfg = {
		albumData = 'Module:Classement musical/Données/Album',
		singleData = 'Module:Classement musical/Données/Single',

		albumDetectCat = 'Catégorie:Albumchart utilisé avec des paramètres manquants',
		singleDetectCat = 'Catégorie:Singlechart utilisé avec des paramètres manquants',

		rowHeader = 'rowheader',
		publishDate = 'en ligne le',
		accessDate = 'consulté le',
		accessDatePrefix = 'Consulté le',

		errorPrefix = 'Erreur :',
		noChartError = 'Classement « %s » introuvable',
		noParamsError = 'Paramètre(s) « %s » manquant(s)',
	},
	formats = {
		-- http://www.lescharts.com/showitem.asp?interpret=(artiste)&titel=(chanson)&cat=s
		-- Lescharts.com – (artiste) – (chanson)
		-- order is relevant
		hungMedienSong = { 'artiste', 'chanson', encoder = ansiPercentEncoder },
		hungMedienAlbum = { 'artiste', 'album', encoder = ansiPercentEncoder },
		chartTrack = { 'année', 'année', 'semaine' }
	}
}
local chartData = {
	france = {
		format = 'hungMedienSong',
		flag = 'France',
		chart = "[[Syndicat national de l'édition phonographique|SNEP]]",
		link = 'http://www.lescharts.com/showitem.asp?interpret=%s&titel=%s&cat=s',
		title = 'Lescharts.com – %s – %s',
		publisher = 'Hung Medien'
	},
	irlande = {
		format = 'chartTrack',
		flag = 'Irlande',
		chart = '[[Irish Singles Chart|IRMA]]',
		lang = 'en',
		link = 'www.chart-track.co.uk/index.jsp?c=p%%2Fmusicvideo%%2Fmusic%%2Farchive%%2Findex_test.jsp&ct=240001&arch=t&lyr=%s&year=%s&week=%s',
		title = 'GfK Chart-Track',
		chartNote = '[[Irish Singles Chart]]',
		publisher = '[[Irish Recorded Music Association]]'
	}
}


-- Convert string to a percent ANSI encoding rather than UTF-8 encoding.
-- Function adapted from [[en:Module:WLink.ansiPercent]].
function ansiPercentEncoder(text)
	local k, s
    local r = text:gsub(" ", "+"):gsub("%%", "%%26")
    for i = mw.ustring.len(r), 1, -1 do
        k = mw.ustring.codepoint(r, i, i)
        if k <= 32 or k > 126 then
            if k > 255 then
                s = mw.ustring.sub(r, i, i)
                if k > 2047 then
                    s = string.format("%%%2X%%%2X%%%2X",
                                      s:byte(1, 1),
                                      s:byte(2, 2),
                                      s:byte(3, 3))
                else
                    s = string.format("%%%2X%%%2X",
                                      s:byte(1, 1),
                                      s:byte(2, 2))
                end
            else
                s = string.format("%%%2X", k)
            end
            r = string.format("%s%s%s",
                              mw.ustring.sub(r,  1,  i - 1),
                              s,
                              mw.ustring.sub(r,  i + 1))
        end
    end
    r = mw.ustring.gsub(r, '^%*', '%%2A')
    return r
end

-- Ce module implémente les modèles {{Albumchart}} et {{Singlechart}}.

local p = {}

-- Useful definitions.
local format = mw.ustring.format
local insert = table.insert
local isTrue = require('Module:Yesno')

local Chart = {}
Chart.__index = Chart

function Chart.new(args, cfg, chartType)
	local cfg = data.cfg
	
	local args = args or {}
	local isAlbumChart = chartType == 'album'
	local chartName = mw.ustring.lower(args[1] or '')
	
	-- Loading the data module.
	local data = data--mw.loadData('Module:Classement musical/Données')
	local moduleName = isAlbumChart and cfg.albumData or cfg.singleData
	local chartData = chartData[chartName] or {}--mw.loadData(moduleName)[chartName] or {}

	local root = mw.html.create()
	-- To reproduce the behavior of the wikicode, the HTML code is deliberately
	-- raw and does not use mw.html.
	if isTrue(args[cfg.rowHeader]) then
		root:wikitext('! scope="row" style="font-weight:normal;"')
	end
	root:wikitext('|')

	local fields = {
		args = args,
		cfg = data.cfg,
		isAlbumChart = isAlbumChart,
		chartName = chartName,
		chartData = chartData,
		requiredParams = data.formats[chartData.format] or {},
		errorDetect = false,
		root = root
	}

	return setmetatable(fields, Chart)
end

function Chart:__tostring()
	return tostring(self.root)
end

function Chart:formattingError(textError)
	self.errorDetect = true
	local catName = self.isAlbumChart
		and self.cfg.albumDetectCat
		or self.cfg.singleDetectCat
	self.root
		:tag('span')
		:addClass('error')
		:css('font-size', '100%')
		:wikitext(format(
			'%s %s[[%s]]',
			self.cfg.errorPrefix, textError, catName))
end

function Chart:checkFormat()
	-- Non matching chart type error.
	if not next(self.requiredParams) then
		self:formattingError(format(self.cfg.noChartError, self.chartName))
		return self
	end
	-- Missing parameters type error.
	local missingParams = {}
	for _, requiredParam in ipairs(self.requiredParams) do
		if not self.args[requiredParam] and not missingParams[requiredParam] then
			-- Put the values as the table's keys to not insert a duplicate.
			missingParams[requiredParam] = true
			insert(missingParams, '<code>' .. requiredParam .. '</code>')
		end
	end
	if next(missingParams) then
		self:formattingError(format(
			self.cfg.noParamsError,
			table.concat(missingParams, ', ')))
	end
	return self
end

-- Produces a URL in the format "[link title]" by applying in the order the
-- required parameters.
function Chart:buildRefLink()
	local requiredArgs = {}
	local requiredParams = self.requiredParams
	for _, param in ipairs(requiredParams) do
		insert(requiredArgs, self.args[param])
	end
	local link = format(self.chartData.link, unpack(requiredArgs))
	local title = format(self.chartData.title, unpack(requiredArgs))
	local refLink = format('[%s %s]', link, title)

	return requiredParams.encoder and requiredParams:encoder(refLink) or refLink
end

function Chart:buildRef()
	local res = mw.html.create()
	local frame = mw.getCurrentFrame()
	local args = self.args
	local cfg = self.cfg

	if chartData.lang then
		local lang = frame:expandTemplate{title = chartData.lang}
		res:wikitext(format('%s ', lang))
	end

	res:wikitext(format('%s. %s. %s.',
		self:buildRefLink(),
		self.chartData.chartNote or self.chartData.chart,
		self.chartData.publisher))

	if args[cfg.publishDate] then
		res:wikitext(format(' %s. ', args[cfg.publishDate]))
	end

	if args[cfg.accessDate] then
		res:wikitext(format(' %s %s.',
			cfg.accessDatePrefix,
			args[cfg.accessDate]))
	end

	return mw.html.create():wikitext(frame:extensionTag('ref', tostring(res), {
		name = args.refname
			or (isAlbumChart and 'a' or 's') .. 'c_' .. self.chartName,
		group = args.refgroup
	}))
end

function Chart:buildChartRow()
	if self.errorDetect then
		return self
	end

	self.root
		:wikitext(mw.getCurrentFrame():expandTemplate{title = self.chartData.flag})
		:wikitext(format(' (%s)', self.chartData.chart))
		:node(self:buildRef())

	if self.args[self.cfg.note] then
		self.root
			:tag('br')
			:done()
			:tag('span')
				:css('font-style', 'italic')
				:css('font-size', '89%')
				:wikitext(self.args.note)
	end

	return self
end

function Chart:buildPositionRow()
	self.root
		:newline()
		:wikitext('| style="text-align:center;"|')
		:wikitext(self.args[2] or '{{{2}}}')

	return self
end

-- Access in the module space.
function p._main(args, chartType)
	local chart = Chart.new(args, cfg, chartType)
	return tostring(chart:checkFormat():buildChartRow():buildPositionRow())
end

-- Access outside the module space.
function p.main(frame)
	local argsParent = frame:getParent().args
	local cleanArgs = {}
	for k, v in pairs(argsParent) do
		if type(k) == 'string' and v ~= '' then
			cleanArgs[k] = mw.text.trim(v)
		end
	end

	return p._main(cleanArgs, frame.args[1])
end

return p