Jump to content
Toggle menu
  • 8 articles
  • 75 files
  • 7 users
  • 37.8K edits
Neodyland Wiki
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Module:Clickable button

From Neodyland Wiki
Revision as of 19:40, 19 September 2025 by commons>Waddie96 (import from module:clickable button/sandbox that'll likely be merged into module:clickable button)
Module documentation[ view · edit · history · purge ]
This documentation is transcluded from Module:Clickable button/doc.

Template:Template rating

Template:Uses templatestyles

Generates wikitext for clickable Codex button. Renders the button component from the Codex design system for Wikimedia. Includes helper functions for URL parsing and cleaning, adding tracking categories. Intended for use in templates and other modules. Implements Template:Clickable button and others. Supports legacy parameters.

  • Options to include an icon or create an icon-only button.
  • Target a URL or a wikilink
  • Set the weight, size and state of the button (enabled or disabled).
  • Dummy button creation can be disabled.

For more information on appropriate usage of UI buttons, see the Codex documentation.

  • Inserts two CSS files. Module:Clickable button/styles.css is required and makes minor tweaks for word-wrapping if the visible label is too long, centering or aligning button left or right, and minimum widths as is needed for icon-only buttons and labels containing two characters or less.
  • The second CSS file, Module:Clickable button/icons.css, is prepended to the button's HTML only if an icon is used.
  • Supports legacy parameters from previous templates.

Usage in wikitext

Some arguments are case-insensitive.

{{#invoke:Clickable button|main
| 1        = <!-- Alias for wikilink -->
| 2        = <!-- Alias for label -->
| label    = <!-- Button visible text label -->
| link     = <!-- Target wikilink -->
| url      = <!-- Target external URL -->
<!-- Inputs action, weight, size, and icon are case-insensitive -->
| action   = <!-- progressive | destructive | default: default. -->
| weight   = <!-- primary | quiet | default: normal. -->
| size     = <!-- small | large | default: medium. Automatically chooses size based on line-height and device. -->
| icon     = <!-- Name of icon, stored in [[Module:Clickable button/icons.css]] e.g., search  -->
| disabled = <!-- `true` or any other true value like `1` or `yes`. -->
| aria-label = <!-- [[w:ARIA]] label for accessibility DOM tree. -->
| nocat      = <!-- `true` to not auto-categorize. -->
<!-- Others -->
| category = <!-- Category name e.g., Category:Name or Name or [[Category:Name]] -->
| class    = <!-- Custom CSS class without quotation marks -->
| style    = <!-- Custom CSS styling without quotation marks -->
<!-- Legacy arguments -->
| color    = <!-- blue | red --> 
}}

Usage in other modules

Ensure you know what to expect from the function you call from another module.

  • function p.main(frame) emits TemplateStyles for the CSS files with the wikitext, and pre-processes the arguments in a frame using Module:Arguments, e.g. ignore blank values'', and trim trailing whitespace.
  • function p._main(arguments) Parses the arguments such as lowercase appropriate arguments, account for use of legacy parameters and decides whether aria-disabled should be true.
  • function p.url(url, [label]) is available, not for button creation, but as an adaption of Module:URL to clean and normalise a URL string and optionally generate a label.
  • The module's other functions, such as makeLinkData() and renderLink(), are localised/local to the module and would need to be made global first to be accessible to other modules.

To call p.main() for example, use:

local createButton = require( 'Module:Clickable button/sandbox' )
buttonWikitext = createButton.main( {
    link = 'South Africa',
    label = 'Go to South Africa',
    action = 'progressive'
    weight = 'default',
    size = 'medium',
    icon = 'link-external',
} ) 
return buttonWikitext

and the value of buttonWikitext would be:

<<templatestyles src="Module:Cdx-button/styles.css" /><templatestyles src="Module:Cdx-button/icons.css" /><span class="cdx-button cdx-button--fake-button cdx-button--action-progressive cdx-button--weight-quiet cdx-button--size-medium" role="button" aria-disabled="false"><span class="cdx-button__icon cdx-demo-css-icon--link-external" aria-hidden="true"></span>Go to South Africa</span>

Function _main would output:

<span class="cdx-button cdx-button--fake-button cdx-button--action-progressive cdx-button--weight-quiet cdx-button--size-medium" role="button" aria-disabled="false"><span class="cdx-button__icon cdx-demo-css-icon--link-external" aria-hidden="true"></span>Go to South Africa</span>

As a result, unless a CSS file is added to give the appropriate class an icon, the icon will not render.

Implementation

Length of visible label

See the Codex button component documentation.


-- [[w:en:Module:Clickable button]]
-- Builds Codex's button component. See [[wmdoc:codex/latest]].
-- Implements [[Template:Clickable button]] and others.
-- Wiki's [[Special:Version]] must have @wikimedia/codex and its dependences.
-- To add icons: [[Template:Clickable button/styles.css]].

local p = {}

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		wrappers = 'Template:Clickable button', 'Template:Clickable button/sandbox',
		'Template:Cdx-button'})

	-- Return empty string if no arguments were supplied
	local hasInput = false
	for k, v in pairs(args) do
		if v and v ~= "" then
			hasInput = true
			break
		end
	end
	if not hasInput then
		return ''
	end

	return frame:extensionTag(
		'templatestyles', '', { src = 'Template:Clickable button/styles.css' }
		) .. p.luaMain(args)
end

function p.luaMain(args)

	-- Backward compatibility:

	-- @TODO: In future, can format any wikilinks removing underscores,
	--        URL-coding using [[Module:Format link]] and [[Module:Urldecode]]
	--        like in [[Template:Format linkr]]
	-- It's weird that we may make a link a label above, but if we truly only got 1=,
	-- then that would mean it's intentional to make both the link and label the same.
	-- Ensure label is set from priority: label= > 2= > 1=
	args.label = args.label or args[2] or args[1]

	--Disable if link=no or disabled=1
	args.disabled = (args.link == "no") or (args.disabled == "1")

	args.link = args.link or args[1]

	-- Remove positional args after assigning
	args[1] = nil
	args[2] = nil

	--[[ Remove links if disabled
	if args.disabled then
		args.link = nil
		args.url = nil 
	end ]]

	-- Make aria-disabled=true later on if no link
	if args.link and args.link ~= "no" then
		args.ariaDisabled = false
	else
		-- If no link whatsoever, make dummy button.
		-- But for accessibility, ARIA must know it won't do anything.
		args.ariaDisabled = true
		-- Option to forcefully disable dummy buttons.
		-- args.disabled = true
	end
	
	-- Normalize ARIA label keys
    args.aria_label = args.aria_label or args['aria-label'] or args.arialabel

	-- Determine action from old parameters color/class
	local color = type(args.color) == 'string' and args.color:lower()
	local class = type(args.class) == 'string' and args.class:lower()
	if (color == "blue"
		or color == "green"
		or class == 'ui-button-green'
		or class == 'ui-button-blue'
		or class == 'mw-ui-progressive'
		or class == 'progressive') then
		args.action = "progressive"
	elseif (color == "red"
		    or class == 'ui-button-red'
			or class == 'mw-ui-destructive'
			or class == 'destructive') then
		args.action = "destructive"
	end

	local data = p.makeLinkData(args)

	-- Error if ARIA label required and not provided
	if data == 'error-no-aria' then
		return '<strong class="error">Clickable button error: A button without' ..
			' a visible label needs an [[WAI-ARIA|ARIA]] label, please define it using "' ..
			'aria-label".</strong>'
	end

	return p.renderLink(data)
end

-- Constructs attributes for the HTML elements.
function p.makeLinkData(args)
	local data = {}

	-- Decide link vs. url vs. none
	-- URL has priority over link if both provided. Also, clean URL
	if args.url then
		data.isUrl = true
		-- Clean up URL
		local label
		data.url, label = p.url(args.url, args.label)
		-- Make pretty link label using the URL if no label
		data.label = args.label or label
	elseif args.link then
		data.isUrl = false
		data.link = args.link
		data.label = args.label
	elseif not args.url and not args.link then
		-- Dummy button, no link at all
		data.label = args.label
	end
	-- Make sure if icon-only button or no label at all button (i.e. dummy button) it has aria-label else error.
	if (not data.label
		and not args.aria_label
		and not args.disabled
		and not args.ariaDisabled) then
		return 'error-no-aria'
	end

	-- Classes
	local class = type(args.class) == 'string' and args.class:lower()
	data.classes = {'cdx-button', 'cdx-button--fake-button'}
	local action = type(args.action) == 'string' and args.action:lower() or 'default'
	local weight = type(args.weight) == 'string' and args.weight:lower() or 'normal'
	local size   = type(args.size) == 'string' and args.size:lower() or 'medium'

	table.insert(data.classes, 'cdx-button--action-' .. action)
	table.insert(data.classes, 'cdx-button--weight-' .. weight)
	table.insert(data.classes, 'cdx-button--size-' .. size)

	-- Disabled state
	data.disabled = args.disabled
	if data.disabled then
		table.insert(data.classes, 'cdx-button--fake-button--disabled')
	else
		table.insert(data.classes, 'cdx-button--fake-button--enabled')
	end

	-- Icon
	local icon = type(args.icon) == 'string' and args.icon:lower()
	if icon then
		data.iconSpan = mw.html.create('span')
			:addClass('cdx-button__icon cdx-demo-css-icon--' .. icon)
			:attr('aria-hidden', 'true')
	end

	data.aria_label = args.aria_label
	data.ariaDisabled = args.ariaDisabled

	return data
end

function p.renderLink(data)
	-- Build span tag
	local span = mw.html.create('span')
	for _, class in ipairs(data.classes or {}) do
		span:addClass(class)
	end
	span:attr('role', 'button')
	if data.aria_label then
		span:attr('aria-label', data.aria_label)
	end
	-- ARIA disabled attribute for disabled/no-link/dummy buttons
	if data.disabled or data.ariaDisabled then
		span:attr('aria-disabled', 'true')
	elseif data.disabled == false then
		span:attr('aria-disabled', 'false')
	end
	if data.iconSpan then
		span:node(data.iconSpan)
	end
	if data.label then
		span:wikitext(data.label)
	end

	local display = tostring(span)

	if data.disabled then
		return display
	end
	if data.isUrl then
		-- mw.logObject(data)
		return string.format('<span class="plainlinks">[%s %s]</span>', data.url, display)
	elseif data.isUrl == false then
		return string.format('[[%s|%s]]', data.link, display)
	else
		-- No url/link provided
		return display
	end
end

-- Cleans up and validates a URL.
-- Copied from [[en:Module:URL]] with minor modifications.

local function safeUri(s)
	local success, uri = pcall(function()
		return mw.uri.new(s)
	end)
	if success then
		return uri
	end
end

local function extractUrl(extract)
	local url = extract
		url = mw.ustring.gsub(url, '^[Hh][Tt][Tt][Pp]([Ss]?):(/?)([^/])',
			  'http%1://%3')
		local uri = safeUri(url);
		if uri and uri.host then
			return url
		end
end

function p._url(url, text)
	url = mw.text.trim(url or '')
	text = mw.text.trim(text or '')

	if url == '' then
		return text
	end

	-- If the URL contains any unencoded spaces, encode them, because MediaWiki will otherwise interpret a space as the end of the URL.
	url = mw.ustring.gsub(url, '%s', function(s) return mw.uri.encode(s,
		  	'PATH')
		  end)

	-- If there is an empty query string or fragment id, remove it as it will cause mw.uri.new to throw an error
	url = mw.ustring.gsub(url, '#$', '')
	url = mw.ustring.gsub(url, '%?$', '')

	-- If it's an HTTP[S] URL without the double slash, fix it.
	url = mw.ustring.gsub(url, '^[Hh][Tt][Tt][Pp]([Ss]?):(/?)([^/])', 'http%1://%3')

	local uri = safeUri(url)

	-- Handle URL's without a protocol and URL's that are protocol-relative,
	-- e.g. www.example.com/foo or www.example.com:8080/foo, and //www.example.com/foo
	if uri and (not uri.protocol or (uri.protocol and not uri.host)) and url:sub(1, 2) ~= '//' then
		url = 'http://' .. url
		uri = safeUri(url)
	end

	if text == '' then
		if uri then
			if uri.path == '/' then uri.path = '' end

			local port = ''
			if uri.port then port = ':' .. uri.port end

			text = mw.ustring.lower(uri.host or '') .. port .. (uri.relativePath or '')

			-- Add <wbr> before _/.-# sequences
			text = mw.ustring.gsub(text, "(/+)", "<wbr/>%1") -- This entry MUST be the first. "<wbr/>" has a "/" in it, you know.
			text = mw.ustring.gsub(text, "(%.+)", "<wbr/>%1")
			-- text = mw.ustring.gsub(text,"(%-+)","<wbr/>%1") 	-- DISABLED for now
			text = mw.ustring.gsub(text, "(%#+)", "<wbr/>%1")
			text = mw.ustring.gsub(text, "(_+)", "<wbr/>%1")
		else -- URL is badly-formed, so just display whatever was passed in
			text = url
		end
	end

	return url, text
end

function p.url(URL, TEXT)
	local url = URL or ''
	local text = TEXT or ''
	url = url or extractUrl(url) or extractUrl(text) or ''
	-- Strip out HTML tags and [ ] from URL
	url = (url or ''):gsub("<[^>]*>", ""):gsub("[%[%]]", "")
	-- Truncate anything after a space
	url = url:gsub("%%20", " "):gsub(" .*", "")
	return p._url(url, text)
end

return p
Cookies help us deliver our services. By using our services, you agree to our use of cookies.