Module:File link

From Wayne County, Ohio Online Resource Center
Jump to navigation Jump to search

This module is used to construct wikitext links to files, using a fluent Lua interface. This is done by creating a fileLink object, which has various methods corresponding to different file link parameters. The module is used from other Lua modules, and cannot be used directly from wiki pages.

Usage

Creating the object

First, you need to import the module.

local fileLink = require('Module:File link')

Then, create the object using the fileLink.new function. The first parameter is the filename, and is optional.

local obj = fileLink.new('Example.png')

Basic usage

You can add parameters to the file link using the fileLink object's methods. (See the Methods section below for the full list.)

obj:width(220)
obj:alt('The alt text')
obj:caption('The caption.')

You can then produce the link wikitext using the object's render method.

obj:render()

This will produce the following wikitext:

[[File:Example.png|220px|alt=The alt text|The caption.]]

Call-chaining

All the object's methods apart from the render method return the object itself, so can be used to call-chain.

obj:width(220):alt('The alt text'):caption('The caption.'):render()

Apart from the name method, all of the object's methods support nil as an input, so call-chaining can be performed with variables whose value is unknown. However, an error will be raised if the input is of an unsupported type for that method. Please see the Methods section for supported input types for each method. Passing nil to a method will overwrite any existing values.

Use with tostring

Instead of using the render method, you can call tostring on the object to create the link wikitext.

obj:width(220):alt('The alt text'):caption('The caption.')
tostring(obj)

Methods

Name

obj:name(s)

Sets the filename. s must be a string. Nil values are not accepted, as every file link requires a filename. The filename can also be set in the first parameter to fileLink.new, although in that case it is optional.

Format

obj:format(s, filename)

Sets the display format. s must either be nil, or one of the strings 'thumb', 'thumbnail', 'frame', 'framed', or 'frameless'. To see the effect of each of these values, see the images help page on mediawiki.org. Note that the border format is not set with this method, but with the border method. (This is because the border option can be set independently of the values that can be set with this method, for example in the code [[File:Example.png|frameless|border|caption]].)

The filename variable is an optional variable that can be used to set the filename for thumbnails. The filename specified will be used instead of the automatically generated thumbnail. This option doesn't have any effect on the other format options.

Border

obj:border(hasBorder)

Sets a border for images. hasBorder must either be nil, or a boolean value. A border will be set if hasBorder is true. To see the effect of this option, see the images help page on mediawiki.org.

Width

obj:width(px)

Sets a width for the file in pixels. px must either be nil or a number value. Width can be used in conjunction with the height method, but will produce an error if used when the upright option has been set by the upright method.

Height

obj:height(px)

Sets a height for the file in pixels. px must either be nil or a number value. Height can be used in conjunction with the width method, but will produce an error if used when the upright option has been set by the upright method.

Upright

obj:upright(isUpright, factor)

Sets the upright option, used for images that are taller than they are wide. isUpright must either be nil, or a boolean value. The upright option will be set if isUpright is true. factor provides an optional conversion factor for the upright option; the factor is the image's width divided by its height. If no factor is specified, the MediaWiki software uses the default of 0.75. factor must be either nil or a number value. If a width or height has been set with the width or height methods, then setting the upright value will result in an error.

ResetSize

obj:resetSize()

This method clears any size-related data the fileLink object is holding. This includes width, height, the upright option, and any upright factor.

Location

obj:location(s)

Sets the location option. This is also known as the horizontal alignment option. s must either be nil, or one of the strings 'right', 'left', 'center', or 'none'. To see the effect of each of these values, see the images help page on mediawiki.org.

Alignment

obj:alignment(s)

Sets the alignment option. This is also known as the vertical alignment option. s must either be nil, or one of the strings 'baseline', 'middle', 'sub', 'super', 'text-top', 'text-bottom', 'top', or 'bottom'. To see the effect of each of these values, see the images help page on mediawiki.org.

Link

obj:link(s)

Sets a link target for the file, instead of the default target of the file description page. s must either be nil or a string value. The link can be a wiki page or a URL, although the exact formatting of the string is not checked by this module. To specify no link, use the blank string: obj:link('').

Alt

obj:alt(s)

Sets alt text for the file. s must either be nil or a string value.

Page

obj:page(num)

Sets a page number for multi-paged files such as PDFs. num must either be nil or a number.

Class

obj:class(s)

Adds a class parameter to image links. The MediaWiki software adds this parameter to the class="..." attribute of the image's <img /> element when the page is rendered into HTML. s must either be nil or a string value.

Lang

obj:lang(s)

Adds a language attribute to specify what language to render the file in. s must either be nil or a string value. This module does not check whether the language tag is valid or not.

StartTime

obj:startTime(time)

Specifies a start time for audio and video files. time must be nil, a number, or a string value. Numbers are interpreted as the number of seconds since the start of the file. Strings can be in the format "mm:ss" to specify the number of minutes and seconds of a file, or "ss" to specify the number of seconds since the start of the file.

EndTime

obj:endTime(time)

Specifies an end time for audio and video files. time must be nil, a number, or a string value. Numbers are interpreted as the number of seconds since the start of the file. Strings can be in the format "mm:ss" to specify the number of minutes and seconds of a file, or "ss" to specify the number of seconds since the start of the file.

ThumbTime

obj:thumbTime(time)

Specifies the time to use to generate the thumbnail image for video files. time must be nil, a number, or a string value. Numbers are interpreted as the number of seconds since the start of the file. Strings can be in the format "mm:ss" to specify the number of minutes and seconds of a file, or "ss" to specify the number of seconds since the start of the file.

Caption

obj:caption(s)

Sets a caption for the file. s must either be nil or a string value.

Render

obj:render()

Renders the link wikitext.



-- This module provides a library for formatting file wikilinks.

local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType

local fileLink = {}

function fileLink.new(filename)
	checkType('fileLink.new', 1, filename, 'string', true)
	local obj, data = {}, {}
	
	local checkSelf = libraryUtil.makeCheckSelfFunction(
		'fileLink',
		'fileLink',
		obj,
		'fileLink object'
	)
	
	-- Set the filename if we were passed it as an input to fileLink.new.
	if filename then
		data.theName = filename
	end
	
	function data:name(s)
		checkSelf(self, 'name')
		checkType('fileLink:name', 1, s, 'string')
		data.theName = s
		return self
	end
	
	function data:format(s, filename)
		checkSelf(self, 'format')
		checkType('fileLink:format', 1, s, 'string', true)
		checkType('fileLink:format', 2, format, 'string', true)
		local validFormats = {
			thumb = true,
			thumbnail = true,
			frame = true,
			framed = true,
			frameless = true
		}
		if s == nil or validFormats[s] then
			data.theFormat = s
			data.theFormatFilename = filename
		else
			error(string.format(
				"bad argument #1 to 'fileLink:format' ('%s' is not a valid format)",
				s
			), 2)
		end
		return self
	end

	local function sizeError(methodName)
		-- Used for formatting duplication errors in size-related methods.
		error(string.format(
			"duplicate size argument detected in '%s'"
			.. " ('upright' cannot be used in conjunction with height or width)",
			methodName
		), 3)
	end
	
	function data:width(px)
		checkSelf(self, 'width')
		checkType('fileLink:width', 1, px, 'number', true)
		if px and data.isUpright then
			sizeError('fileLink:width')
		end
		data.theWidth = px
		return self
	end
	
	function data:height(px)
		checkSelf(self, 'height')
		checkType('fileLink:height', 1, px, 'number', true)
		if px and data.isUpright then
			sizeError('fileLink:height')
		end
		data.theHeight = px
		return self
	end
	
	function data:upright(isUpright, factor)
		checkSelf(self, 'upright')
		checkType('fileLink:upright', 1, isUpright, 'boolean', true)
		checkType('fileLink:upright', 2, factor, 'number', true)
		if isUpright and (data.theWidth or data.theHeight) then
			sizeError('fileLink:upright')
		end
		data.isUpright = isUpright
		data.uprightFactor = factor
		return self
	end
	
	function data:resetSize()
		checkSelf(self, 'resetSize')
		for i, field in ipairs{'theWidth', 'theHeight', 'isUpright', 'uprightFactor'} do
			data[field] = nil
		end
		return self
	end
	
	function data:location(s)
		checkSelf(self, 'location')
		checkType('fileLink:location', 1, s, 'string', true)
		local validLocations = {
			right = true,
			left = true,
			center = true,
			none = true
		}
		if s == nil or validLocations[s] then
			data.theLocation = s
		else
			error(string.format(
				"bad argument #1 to 'fileLink:location' ('%s' is not a valid location)",
				s
			), 2)
		end
		return self
	end
	
	function data:alignment(s)
		checkSelf(self, 'alignment')
		checkType('fileLink:alignment', 1, s, 'string', true)
		local validAlignments = {
			baseline = true,
			middle = true,
			sub = true,
			super = true,
			['text-top'] = true,
			['text-bottom'] = true,
			top = true,
			bottom = true
		}
		if s == nil or validAlignments[s] then
			data.theAlignment = s
		else
			error(string.format(
				"bad argument #1 to 'fileLink:alignment' ('%s' is not a valid alignment)",
				s
			), 2)
		end
		return self
	end
	
	function data:border(hasBorder)
		checkSelf(self, 'border')
		checkType('fileLink:border', 1, hasBorder, 'boolean', true)
		data.hasBorder = hasBorder
		return self
	end
	
	function data:link(s)
		checkSelf(self, 'link')
		checkType('fileLink:link', 1, s, 'string', true)
		data.theLink = s
		return self
	end
	
	function data:alt(s)
		checkSelf(self, 'alt')
		checkType('fileLink:alt', 1, s, 'string', true)
		data.theAlt = s
		return self
	end
	
	function data:page(num)
		checkSelf(self, 'page')
		checkType('fileLink:page', 1, num, 'number', true)
		data.thePage = s
		return self
	end
	
	function data:class(s)
		checkSelf(self, 'class')
		checkType('fileLink:class', 1, s, 'string', true)
		data.theClass = s
		return self
	end
	
	function data:lang(s)
		checkSelf(self, 'lang')
		checkType('fileLink:lang', 1, s, 'string', true)
		data.theLang = s
		return self
	end

	local function checkTypeStringOrNum(funcName, pos, arg)
		local argType = type(arg)
		if argType ~= 'nil' and argType ~= 'string' and argType ~= 'number' then
			error(string.format(
				"bad argument #%d to '%s' (string or number expected, got %s)",
				pos,
				funcName,
				argType
			), 3)
		end
	end
	
	function data:startTime(time)
		checkSelf(self, 'startTime')
		checkTypeStringOrNum('fileLink:startTime', 1, time)
		data.theStartTime = time
		return self
	end
	
	function data:endTime(time)
		checkSelf(self, 'endTime')
		checkTypeStringOrNum('fileLink:endTime', 1, time)
		data.theEndTime = time
		return self
	end
	
	function data:thumbTime(time)
		checkSelf(self, 'thumbTime')
		checkTypeStringOrNum('fileLink:thumbTime', 1, time)
		data.theThumbTime = time
		return self
	end
	
	function data:caption(s)
		checkSelf(self, 'caption')
		checkType('fileLink:caption', 1, s, 'string', true)
		data.theCaption = s
		return self
	end
	
	function data:render()
		checkSelf(self, 'render')
		local ret = {}
		
		-- Filename
		if not data.theName then
			error('fileLink:render: no filename was found')
		end
		ret[#ret + 1] = 'File:' .. data.theName
		
		-- Format
		if data.theFormat and data.theFormatFilename then
			ret[#ret + 1] = data.theFormat .. '=' .. data.theFormatFilename
		elseif data.theFormat then
			ret[#ret + 1] = data.theFormat
		end
		
		-- Border
		if data.hasBorder then
			ret[#ret + 1] = 'border'
		end
		
		-- Location
		ret[#ret + 1] = data.theLocation

		-- Alignment
		ret[#ret + 1] = data.theAlignment
		
		-- Size
		if data.isUpright and data.uprightFactor then
			ret[#ret + 1] = 'upright=' .. tostring(data.uprightFactor)
		elseif data.isUpright then
			ret[#ret + 1] = 'upright'
		elseif data.theWidth and data.theHeight then
			ret[#ret + 1] = string.format('%dx%dpx', data.theWidth, data.theHeight)
		elseif data.theWidth then
			ret[#ret + 1] = tostring(data.theWidth) .. 'px'
		elseif data.theHeight then
			ret[#ret + 1] = string.format('x%dpx', data.theHeight)
		end
		
		-- Render named parameters.
		-- That includes link, alt, page, class, lang, start, end, and thumbtime.
		do
			local namedParameters = {
				{'link', 'theLink'},
				{'alt', 'theAlt'},
				{'page', 'thePage'},
				{'class', 'theClass'},
				{'lang', 'theLang'},
				{'start', 'theStartTime'},
				{'end', 'theEndTime'},
				{'thumbtime', 'theThumbTime'}
			}
			for i, t in ipairs(namedParameters) do
				local parameter = t[1]
				local value = data[t[2]]
				if value then
					ret[#ret + 1] = parameter .. '=' .. tostring(value)
				end
			end
		end

		-- Caption
		ret[#ret + 1] = data.theCaption
		
		return string.format('[[%s]]', table.concat(ret, '|'))
	end
	
	local privateFields = {
		theName = true,
		theFormat = true,
		theFormatFilename = true,
		theWidth = true,
		theHeight = true,
		isUpright = true,
		uprightFactor = true,
		theLocation = true,
		theAlignment = true,
		hasBorder = true,
		theLink = true,
		theAlt = true,
		thePage = true,
		theClass = true,
		theLang = true,
		theCaption = true
	}
	
	local readOnlyFields = {}
	for field in pairs(data) do
		readOnlyFields[field] = true
	end
	readOnlyFields.theName = nil -- This is set if a filename is given to fileLink.new, so remove it.
	
	local function restrictedFieldError(key, restriction)
		error(string.format(
			"fileLink object field '%s' is %s",
			tostring(key),
			restriction
		), 3)
	end
	
	setmetatable(obj, {
		__index = function (t, key)
			if privateFields[key] then
				restrictedFieldError(key, 'private')
			else
				return data[key]
			end
		end,
		__newindex = function (t, key, value)
			if privateFields[key] then
				restrictedFieldError(key, 'private')
			elseif readOnlyFields[key] then
				restrictedFieldError(key, 'read-only')
			else
				data[key] = value
			end
		end,
		__tostring = function (t)
			return t:render()
		end,
		__pairs = function ()
			local temp = {}
			for k, v in pairs(data) do
				if not privateFields[k] then
					temp[k] = v
				end
			end
			return pairs(temp)
		end
	})
	
	return obj
end

return fileLink