Module:YouTube

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 args.url or positional[1] or "dQw4w9WgXcQ"
	id = extractVideoID(id)
	
	-- Determine where to start detecting remaining parameters
	-- Slide back to 1 if id= is supplied, otherwise start at 2 (legacy behavior)
	local startIndex = args.id and 1 or args.url and 1 or 2
	
	local float, width
	local undecided = {}
	
	-- Parse remaining positionals
	for i = startIndex, #positional do
	    local v = tostring(positional[i]):match("^%s*(.-)%s*$") -- trim
	
	    -- Float detection
	    if not float and (v == "left" or v == "right" or v == "center" or v == "none") then
	        float = v
	
	    -- Width detection
	    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(undecided, v)
	        end
	
	    -- Anything else is undecided (potential caption)
	    else
	        table.insert(undecided, v)
	    end
	end

	-- Fallback to named parameters
	float = float or args.float or args.position or "right"
	width = width or toNumber(args.width, 330)

	-- Caption: exactly ONE positional slot
	local caption = undecided[1] 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