Module:YouTube/sandbox

From Uncyclopedia, the content-free encyclopedia
Jump to navigation Jump to search
local p = {}
local getArgs = require('Module:Arguments').getArgs

local function toNumber(s, default)
	if not s then return default end
	local numStr = tostring(s):match("%d+")
	return tonumber(numStr) or default
end

local function extractVideoID(id)
	id = tostring(id)
	return id:match("v=([%w%-_]+)")
		or id:match("youtu%.be/([%w%-_]+)")
		or id:match("([%w%-_]+)$")
		or "dQw4w9WgXcQ"
end

function p.main(frame)
	local args = getArgs(frame)
	local positional = {}

	-- Collect positional arguments
	for k, v in pairs(args) do
		if type(k) == "number" then
			table.insert(positional, tostring(v))
		end
	end

	-- ID must be first
	local id = args.id or positional[1] or "dQw4w9WgXcQ"
	id = extractVideoID(id)

	local float, width
	local captionParts = {}

	-- Parse ALL remaining positionals after the first
	for i = 2, #positional do
		local v = tostring(positional[i]):match("^%s*(.-)%s*$") -- trim

		-- Float detection (only if not set)
		if not float and (v == "left" or v == "right" or v == "center" or v == "none") then
			float = v

		-- Width detection (only if not set)
		elseif not width then
			local n = v:match("^(%d+)%s*[pP][xX]?$") or v:match("^(%d+)$")
			if n then
				width = tonumber(n)
			else
				table.insert(captionParts, v)
			end

		-- Anything else → caption
		else
			table.insert(captionParts, v)
		end
	end

	-- Fallback to named parameters
	float   = float   or args.float or args.position or "right"
	width   = width   or toNumber(args.width, 330)
	local caption = (#captionParts > 0 and table.concat(captionParts, " ")) or args.caption or ""

	-- Compute height (16:9)
	local height = toNumber(args.height, math.floor(width * 9 / 16 + 0.5))

	-- Map float to thumb class
	local floatMap = { left="left", right="right", center="none", none="none" }
	local floatThumb = floatMap[float] or "right"

	-- Build HTML
	local out = {}
	table.insert(out, frame:extensionTag{ name = 'templatestyles', args = { src = 'YouTube/styles.css' }})

	if floatThumb == "none" then
		table.insert(out, '<div class="center">') 
	end

	table.insert(out, string.format(
		'<div class="thumb t%s"><div class="thumbinner" style="width:min-content">',
		floatThumb
	))

	table.insert(out, frame:extensionTag{
		name = 'YouTube',
		content = id,
		args = { width = width, height = height }
	})

	if caption ~= "" then
		table.insert(out, string.format('<div class="thumbcaption">%s</div>', caption))
	end

	table.insert(out, '</div></div>')

	if floatThumb == "none" then
		table.insert(out, '</div>')
	end

	return table.concat(out)
end

return p