Zum Inhalt springen

Modul:List und Modul:TableTools: Unterschied zwischen den Seiten

(Unterschied zwischen Seiten)
from sandbox: another slight code simplification and a couple comment fixes
(Minerva skin needs whether an hlist is separated to be explicit (see https://en.wikipedia.org/wiki/Wikipedia:Village_pump_(technical)#Hlist_bullets_not_shown_in_mobile))
 
(from sandbox: another slight code simplification and a couple comment fixes)
 
Zeile 1: Zeile 1:
-- This module outputs different kinds of lists. At the moment, bulleted,
--[[
-- unbulleted, horizontal, ordered, and horizontal ordered lists are supported.
------------------------------------------------------------------------------------
--                              TableTools                                      --
--                                                                                --
-- This module includes a number of functions for dealing with Lua tables.       --
-- It is a meta-module, meant to be called from other Lua modules, and should    --
-- not be called directly from #invoke.                                           --
------------------------------------------------------------------------------------
--]]


local libUtil = require('libraryUtil')
local libraryUtil = require('libraryUtil')
local checkType = libUtil.checkType
local mTableTools = require('Module:TableTools')


local p = {}
local p = {}


local listTypes = {
-- Define often-used variables and functions.
['bulleted'] = true,
local floor = math.floor
['unbulleted'] = true,
local infinity = math.huge
['horizontal'] = true,
local checkType = libraryUtil.checkType
['ordered'] = true,
local checkTypeMulti = libraryUtil.checkTypeMulti
['horizontal_ordered'] = true
}


function p.makeListData(listType, args)
--[[
-- Constructs a data table to be passed to p.renderList.
------------------------------------------------------------------------------------
local data = {}
-- isPositiveInteger
--
-- This function returns true if the given value is a positive integer, and false
-- if not. Although it doesn't operate on tables, it is included here as it is
-- useful for determining whether a given table key is in the array part or the
-- hash part of a table.
------------------------------------------------------------------------------------
--]]
function p.isPositiveInteger(v)
return type(v) == 'number' and v >= 1 and floor(v) == v and v < infinity
end


-- Classes
--[[
data.classes = {}
------------------------------------------------------------------------------------
if listType == 'horizontal' or listType == 'horizontal_ordered' then
-- isNan
table.insert(data.classes, 'hlist hlist-separated')
--
elseif listType == 'unbulleted' then
-- This function returns true if the given number is a NaN value, and false
table.insert(data.classes, 'plainlist')
-- if not. Although it doesn't operate on tables, it is included here as it is
-- useful for determining whether a value can be a valid table key. Lua will
-- generate an error if a NaN is used as a table key.
------------------------------------------------------------------------------------
--]]
function p.isNan(v)
return type(v) == 'number' and tostring(v) == '-nan'
end
 
--[[
------------------------------------------------------------------------------------
-- shallowClone
--
-- This returns a clone of a table. The value returned is a new table, but all
-- subtables and functions are shared. Metamethods are respected, but the returned
-- table will have no metatable of its own.
------------------------------------------------------------------------------------
--]]
function p.shallowClone(t)
local ret = {}
for k, v in pairs(t) do
ret[k] = v
end
end
table.insert(data.classes, args.class)
return ret
end


-- Main div style
--[[
data.style = args.style
------------------------------------------------------------------------------------
-- removeDuplicates
--
-- This removes duplicate values from an array. Non-positive-integer keys are
-- ignored. The earliest value is kept, and all subsequent duplicate values are
-- removed, but otherwise the array order is unchanged.
------------------------------------------------------------------------------------
--]]
function p.removeDuplicates(t)
checkType('removeDuplicates', 1, t, 'table')
local isNan = p.isNan
local ret, exists = {}, {}
for i, v in ipairs(t) do
if isNan(v) then
-- NaNs can't be table keys, and they are also unique, so we don't need to check existence.
ret[#ret + 1] = v
else
if not exists[v] then
ret[#ret + 1] = v
exists[v] = true
end
end
end
return ret
end


-- Indent for horizontal lists
--[[
if listType == 'horizontal' or listType == 'horizontal_ordered' then
------------------------------------------------------------------------------------
local indent = tonumber(args.indent)
-- numKeys
indent = indent and indent * 1.6 or 0
--
if indent > 0 then
-- This takes a table and returns an array containing the numbers of any numerical
data.marginLeft = indent .. 'em'
-- keys that have non-nil values, sorted in numerical order.
------------------------------------------------------------------------------------
--]]
function p.numKeys(t)
checkType('numKeys', 1, t, 'table')
local isPositiveInteger = p.isPositiveInteger
local nums = {}
for k, v in pairs(t) do
if isPositiveInteger(k) then
nums[#nums + 1] = k
end
end
end
end
table.sort(nums)
-- List style types for ordered lists
return nums
-- This could be "1, 2, 3", "a, b, c", or a number of others. The list style
end
-- type is either set by the "type" attribute or the "list-style-type" CSS
 
-- property.
--[[
if listType == 'ordered' or listType == 'horizontal_ordered' then
------------------------------------------------------------------------------------
data.listStyleType = args.list_style_type or args['list-style-type']
-- affixNums
data.type = args['type']
--
-- This takes a table and returns an array containing the numbers of keys with the
-- specified prefix and suffix. For example, for the table
-- {a1 = 'foo', a3 = 'bar', a6 = 'baz'} and the prefix "a", affixNums will
-- return {1, 3, 6}.
------------------------------------------------------------------------------------
--]]
function p.affixNums(t, prefix, suffix)
checkType('affixNums', 1, t, 'table')
checkType('affixNums', 2, prefix, 'string', true)
checkType('affixNums', 3, suffix, 'string', true)
 
local function cleanPattern(s)
-- Cleans a pattern so that the magic characters ()%.[]*+-?^$ are interpreted literally.
return s:gsub('([%(%)%%%.%[%]%*%+%-%?%^%$])', '%%%1')
end
 
prefix = prefix or ''
suffix = suffix or ''
prefix = cleanPattern(prefix)
suffix = cleanPattern(suffix)
local pattern = '^' .. prefix .. '([1-9]%d*)' .. suffix .. '$'
 
local nums = {}
for k, v in pairs(t) do
if type(k) == 'string' then
local num = mw.ustring.match(k, pattern)
if num then
nums[#nums + 1] = tonumber(num)
end
end
end
table.sort(nums)
return nums
end


-- Detect invalid type attributes and attempt to convert them to
--[[
-- list-style-type CSS properties.
------------------------------------------------------------------------------------
if data.type
-- numData
and not data.listStyleType
--
and not tostring(data.type):find('^%s*[1AaIi]%s*$')
-- Given a table with keys like ("foo1", "bar1", "foo2", "baz2"), returns a table
then
-- of subtables in the format
data.listStyleType = data.type
-- { [1] = {foo = 'text', bar = 'text'}, [2] = {foo = 'text', baz = 'text'} }
data.type = nil
-- Keys that don't end with an integer are stored in a subtable named "other".
-- The compress option compresses the table so that it can be iterated over with
-- ipairs.
------------------------------------------------------------------------------------
--]]
function p.numData(t, compress)
checkType('numData', 1, t, 'table')
checkType('numData', 2, compress, 'boolean', true)
local ret = {}
for k, v in pairs(t) do
local prefix, num = mw.ustring.match(tostring(k), '^([^0-9]*)([1-9][0-9]*)$')
if num then
num = tonumber(num)
local subtable = ret[num] or {}
if prefix == '' then
-- Positional parameters match the blank string; put them at the start of the subtable instead.
prefix = 1
end
subtable[prefix] = v
ret[num] = subtable
else
local subtable = ret.other or {}
subtable[k] = v
ret.other = subtable
end
end
end
end
if compress then
-- List tag type
local other = ret.other
if listType == 'ordered' or listType == 'horizontal_ordered' then
ret = p.compressSparseArray(ret)
data.listTag = 'ol'
ret.other = other
else
data.listTag = 'ul'
end
end
return ret
end


-- Start number for ordered lists
--[[
data.start = args.start
------------------------------------------------------------------------------------
if listType == 'horizontal_ordered' then
-- compressSparseArray
-- Apply fix to get start numbers working with horizontal ordered lists.
--
local startNum = tonumber(data.start)
-- This takes an array with one or more nil values, and removes the nil values
if startNum then
-- while preserving the order, so that the array can be safely traversed with
data.counterReset = 'listitem ' .. tostring(startNum - 1)
-- ipairs.
------------------------------------------------------------------------------------
--]]
function p.compressSparseArray(t)
checkType('compressSparseArray', 1, t, 'table')
local ret = {}
local nums = p.numKeys(t)
for _, num in ipairs(nums) do
ret[#ret + 1] = t[num]
end
return ret
end
 
--[[
------------------------------------------------------------------------------------
-- sparseIpairs
--
-- This is an iterator for sparse arrays. It can be used like ipairs, but can
-- handle nil values.
------------------------------------------------------------------------------------
--]]
function p.sparseIpairs(t)
checkType('sparseIpairs', 1, t, 'table')
local nums = p.numKeys(t)
local i = 0
local lim = #nums
return function ()
i = i + 1
if i <= lim then
local key = nums[i]
return key, t[key]
else
return nil, nil
end
end
end
end
end


-- List style
--[[
-- ul_style and ol_style are included for backwards compatibility. No
------------------------------------------------------------------------------------
-- distinction is made for ordered or unordered lists.
-- size
data.listStyle = args.list_style
--
-- This returns the size of a key/value pair table. It will also work on arrays,
-- but for arrays it is more efficient to use the # operator.
------------------------------------------------------------------------------------
--]]


-- List items
function p.size(t)
-- li_style is included for backwards compatibility. item_style was included
checkType('size', 1, t, 'table')
-- to be easier to understand for non-coders.
local i = 0
data.itemStyle = args.item_style or args.li_style
for k in pairs(t) do
data.items = {}
i = i + 1
for i, num in ipairs(mTableTools.numKeys(args)) do
end
local item = {}
return i
item.content = args[num]
end
item.style = args['item' .. tostring(num) .. '_style']
 
or args['item_style' .. tostring(num)]
 
item.value = args['item' .. tostring(num) .. '_value']
local function defaultKeySort(item1, item2)
or args['item_value' .. tostring(num)]
-- "number" < "string", so numbers will be sorted before strings.
table.insert(data.items, item)
local type1, type2 = type(item1), type(item2)
if type1 ~= type2 then
return type1 < type2
else -- This will fail with table, boolean, function.
return item1 < item2
end
end
 
--[[
Returns a list of the keys in a table, sorted using either a default
comparison function or a custom keySort function.
]]
function p.keysToList(t, keySort, checked)
if not checked then
checkType('keysToList', 1, t, 'table')
checkTypeMulti('keysToList', 2, keySort, { 'function', 'boolean', 'nil' })
end
local list = {}
local index = 1
for key, value in pairs(t) do
list[index] = key
index = index + 1
end
end
return data
if keySort ~= false then
keySort = type(keySort) == 'function' and keySort or defaultKeySort
table.sort(list, keySort)
end
return list
end
end


function p.renderList(data)
--[[
-- Renders the list HTML.
Iterates through a table, with the keys sorted using the keysToList function.
If there are only numerical keys, sparseIpairs is probably more efficient.
]]
function p.sortedPairs(t, keySort)
checkType('sortedPairs', 1, t, 'table')
checkType('sortedPairs', 2, keySort, 'function', true)
-- Return the blank string if there are no list items.
local list = p.keysToList(t, keySort, true)
if type(data.items) ~= 'table' or #data.items < 1 then
return ''
local i = 0
return function()
i = i + 1
local key = list[i]
if key ~= nil then
return key, t[key]
else
return nil, nil
end
end
end
end
--[[
Returns true if all keys in the table are consecutive integers starting at 1.
--]]
function p.isArray(t)
checkType("isArray", 1, t, "table")
-- Render the main div tag.
local i = 0
local root = mw.html.create('div')
for k, v in pairs(t) do
for i, class in ipairs(data.classes or {}) do
i = i + 1
root:addClass(class)
if t[i] == nil then
return false
end
end
end
root:css{['margin-left'] = data.marginLeft}
return true
if data.style then
end
root:cssText(data.style)
 
-- { "a", "b", "c" } -> { a = 1, b = 2, c = 3 }
function p.invert(array)
checkType("invert", 1, array, "table")
local map = {}
for i, v in ipairs(array) do
map[v] = i
end
end
return map
end


-- Render the list tag.
--[[
local list = root:tag(data.listTag or 'ul')
{ "a", "b", "c" } -> { ["a"] = true, ["b"] = true, ["c"] = true }
list
--]]
:attr{start = data.start, type = data.type}
function p.listToSet(t)
:css{
checkType("listToSet", 1, t, "table")
['counter-reset'] = data.counterReset,
['list-style-type'] = data.listStyleType
local set = {}
}
for _, item in ipairs(t) do
if data.listStyle then
set[item] = true
list:cssText(data.listStyle)
end
end
return set
end


-- Render the list items
--[[
for i, t in ipairs(data.items or {}) do
Recursive deep copy function.
local item = list:tag('li')
Preserves identities of subtables.
if data.itemStyle then
item:cssText(data.itemStyle)
]]
local function _deepCopy(orig, includeMetatable, already_seen)
-- Stores copies of tables indexed by the original table.
already_seen = already_seen or {}
local copy = already_seen[orig]
if copy ~= nil then
return copy
end
if type(orig) == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[deepcopy(orig_key, includeMetatable, already_seen)] = deepcopy(orig_value, includeMetatable, already_seen)
end
end
if t.style then
already_seen[orig] = copy
item:cssText(t.style)
if includeMetatable then
local mt = getmetatable(orig)
if mt ~= nil then
local mt_copy = deepcopy(mt, includeMetatable, already_seen)
setmetatable(copy, mt_copy)
already_seen[mt] = mt_copy
end
end
end
item
else -- number, string, boolean, etc
:attr{value = t.value}
copy = orig
:wikitext(t.content)
end
end
return copy
end


return tostring(root)
function p.deepCopy(orig, noMetatable, already_seen)
checkType("deepCopy", 3, already_seen, "table", true)
return _deepCopy(orig, not noMetatable, already_seen)
end
end


function p.renderTrackingCategories(args)
--[[
local isDeprecated = false -- Tracks deprecated parameters.
Concatenates all values in the table that are indexed by a number, in order.
for k, v in pairs(args) do
sparseConcat{ a, nil, c, d }  =>  "acd"
k = tostring(k)
sparseConcat{ nil, b, c, d }  =>  "bcd"
if k:find('^item_style%d+$') or k:find('^item_value%d+$') then
]]
isDeprecated = true
function p.sparseConcat(t, sep, i, j)
break
local list = {}
end
local list_i = 0
for _, v in p.sparseIpairs(t) do
list_i = list_i + 1
list[list_i] = v
end
end
local ret = ''
if isDeprecated then
return table.concat(list, sep, i, j)
ret = ret .. '[[Category:List templates with deprecated parameters]]'
end
return ret
end
end


function p.makeList(listType, args)
--[[
if not listType or not listTypes[listType] then
-- Finds the length of an array, or of a quasi-array with keys such
error(string.format(
-- as "data1", "data2", etc., using an exponential search algorithm.
"bad argument #1 to 'makeList' ('%s' is not a valid list type)",
-- It is similar to the operator #, but may return
tostring(listType)
-- a different value when there are gaps in the array portion of the table.
), 2)
-- Intended to be used on data loaded with mw.loadData. For other tables, use #.
end
-- Note: #frame.args in frame object always be set to 0, regardless of
checkType('makeList', 2, args, 'table')
-- the number of unnamed template parameters, so use this function for
local data = p.makeListData(listType, args)
-- frame.args.
local list = p.renderList(data)
--]]
local trackingCategories = p.renderTrackingCategories(args)
 
return list .. trackingCategories
function p.length(t, prefix)
-- requiring module inline so that [[Module:Exponential search]]
-- which is only needed by this one function
-- doesn't get millions of transclusions
local expSearch = require("Module:Exponential search")
checkType('length', 1, t, 'table')
checkType('length', 2, prefix, 'string', true)
return expSearch(function(i)
local key
if prefix then
key = prefix .. tostring(i)
else
key = i
end
return t[key] ~= nil
end) or 0
end
end
 
function p.inArray(arr, valueToFind)
for listType in pairs(listTypes) do
checkType("inArray", 1, arr, "table")
p[listType] = function (frame)
local mArguments = require('Module:Arguments')
-- if valueToFind is nil, error?
local origArgs = mArguments.getArgs(frame)
-- Copy all the arguments to a new table, for faster indexing.
for _, v in ipairs(arr) do
local args = {}
if v == valueToFind then
for k, v in pairs(origArgs) do
return true
args[k] = v
end
end
return p.makeList(listType, args)
end
end
return false
end
end


return p
return p
Anonymer Benutzer