Module:Clean image

From Brighter Shores Wiki
Jump to navigation Jump to search
Module documentation
This documentation is transcluded from Module:Clean image/doc. [edit] [history] [purge]
Module:Clean image's function main is invoked by Template:Clean image.
Module:Clean image requires Module:Paramtest.

Cleans an input image to prevent double linking.

This module is a helper module to be used by other modules; it may not designed to be invoked directly. See Brighter Shores:Lua/Helper modules for a full list and more information. For a full list of modules using this helper click here

FunctionTypeUse
clean{ file = [string|'no'], width = [string|nil], height = [string|nil], link = [string|nil], align = [string|nil] }tableUsed to clean up user input; extracts only the file name of the input and returns its own formatted link.

Input is a table with fields:

  • file - the full wikitext to be cleaned. All processing is skipped if file is empty or is the string no.
  • width - width to resize the file to; no default
  • height - height to resize the file to, can be combined with width; no default
  • link - what page to link the file to; no default (file will link to file page), no to link to nothing
  • align - alignment for the image; left, center, right; no default
Example:
local cleanImage = require( 'Module:Clean image' ).clean
mw.log( cleanImage{ file = '[[File:Basic bacon.png|link=Basic bacon|200px]]' } ) --> '[[File:Basic bacon.png|frameless]]'

-- <nowiki>
-- Removes 'File:' prefix, just in case
-- Replace {{!}} with | instead of preprocessing
-- Turn into a nice wiki file link
local hc = require('Module:Paramtest').has_content
local p = {}
p.main = function(frame)
	local args = frame:getParent().args
	local clean = {
		file = args.file or args[1],
		width = args.width or args[2],
		height = args.height or args[3],
		link = args.link or args[4],
		align = args.align or args[5]
	}
	return p.clean(clean)
end

p.clean = function(args)
	local file = args.file
	if not hc(file) or (file and (file:lower() == 'no' or file == '')) then
		return ''
	end
	
	local height, width = '',''
	if hc(args.height) then
		height = 'x'..args.height
	end
	if hc(args.width) then
		width = args.width
	end
	local size = ''
	if width ~= '' or height ~= '' then
		size = string.format('|%s%spx', width, height)
	end
	
	local link = ''
	if hc(args.link) then
		if args.link == 'no' then
			link = '|link='
		else
			link = '|link='..args.link
		end
	end
	
	local alignment = ''
	local align = args.align
	if align and (align:lower() == 'left' or align:lower() == 'center' or align:lower() == 'right') then
		alignment = string.format('|%s', align)
	end
	
	file = file:gsub('%[',''):gsub('%]',''):gsub('[Ff]ile:',''):gsub('{{!}}','|')

	-- enforce max height and width
	file = mw.text.split(file, '|')

	file = string.format('%s%s%s%s',file[1], size, link, alignment)
	return '[[File:'..file..'|frameless]]'
end

return p
-- </nowiki>