Jump to content

Module:Random slideshow/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Evad37 (talk | contribs) at 02:46, 7 June 2018 (Create sandbox version of Module:Random slideshow). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
-- Creates a slideshow gallery where the order is randomised. Intended for use on portal pages.
local p = {}

local randomModule = require('Module:Random')

function cleanupArgs(argsTable)
	local cleanArgs = {}
	for key, val in pairs(argsTable) do
		if type(val) == 'string' then
			val = val:match('^%s*(.-)%s*$')
			if val ~= '' then
				cleanArgs[key] = val
			end
		else
			cleanArgs[key] = val
		end
	end
	return cleanArgs
end

function makeOutput(galleryLines, maxWidth)
	local randomiseArgs = {	['t'] = galleryLines }
	local randomisedLines = randomModule.main('array', randomiseArgs)
	local galleryContent = table.concat(randomisedLines, '\n')
	local output = '<div style="max-width:' .. maxWidth .. 'px; margin:-4em auto;">{{#tag:gallery|' .. galleryContent  .. '|mode=slideshow}}</div>'
	return output
end

function makeGalleryLine(file, caption)
	local title = mw.title.new(file, "File" )
	return title.prefixedText .. '{{!}}' .. (caption or '')
end

function makeGalleryLinesTable(args)
	local galleryLinesTable = {}
	local i = 1
	while args[i] do
		table.insert(galleryLinesTable, makeGalleryLine(args[i], args[i+1]))
		i = i + 2
	end
	return galleryLinesTable 
end

p.main = function(frame)
	local parent = frame.getParent(frame)
	local parentArgs = parent.args
	local args = cleanupArgs(parentArgs)
	if not args[1] then
		return error('No files specified', 0)
	end
	local lines = makeGalleryLinesTable(args)
	local output = makeOutput(lines, args.width or '350')
	return frame:preprocess(output)
end

return p