Module:Message box
外观
-- 这是一个用于生成消息框模板的元模块,包括
-- {{mbox}}, {{ambox}}, {{imbox}}, {{tmbox}}, {{ombox}}, {{cmbox}} 和 {{fmbox}}。
-- 加载必要的模块。
require('strict')
local getArgs
local yesno = require('Module:Yesno')
-- 获取用于formatDate和ucfirst的语言对象。
local lang = mw.language.getContentLanguage()
-- 定义常量
local CONFIG_MODULE = 'Module:Message box/configuration'
local DEMOSPACES = {talk = 'tmbox', image = 'imbox', file = 'imbox', category = 'cmbox', article = 'ambox', main = 'ambox'}
local TEMPLATE_STYLES = 'Module:Message box/%s.css'
--------------------------------------------------------------------------------
-- 辅助函数
--------------------------------------------------------------------------------
local function getTitleObject(...)
-- 获取标题对象,通过pcall传递函数
-- 以防我们超过昂贵的函数计数限制。
local success, title = pcall(mw.title.new, ...)
if success then
return title
end
end
local function union(t1, t2)
-- 返回两个数组的并集。
local vals = {}
for i, v in ipairs(t1) do
vals[v] = true
end
for i, v in ipairs(t2) do
vals[v] = true
end
local ret = {}
for k in pairs(vals) do
table.insert(ret, k)
end
table.sort(ret)
return ret
end
local function getArgNums(args, prefix)
local nums = {}
for k, v in pairs(args) do
local num = mw.ustring.match(tostring(k), '^' .. prefix .. '([1-9]%d*)$')
if num then
table.insert(nums, tonumber(num))
end
end
table.sort(nums)
return nums
end
--------------------------------------------------------------------------------
-- 消息框类定义
--------------------------------------------------------------------------------
local MessageBox = {}
MessageBox.__index = MessageBox
function MessageBox.new(boxType, args, cfg)
args = args or {}
local obj = {}
obj.boxType = boxType
-- 设置标题对象和命名空间。
obj.title = getTitleObject(args.page) or mw.title.getCurrentTitle()
-- 为我们的框类型设置配置。
obj.cfg = cfg[boxType]
if not obj.cfg then
local ns = obj.title.namespace
-- boxType是"mbox"或无效输入
if args.demospace and args.demospace ~= '' then
-- 实现mbox的demospace参数
local demospace = string.lower(args.demospace)
if DEMOSPACES[demospace] then
-- 使用DEMOSPACES中的模板
obj.cfg = cfg[DEMOSPACES[demospace]]
obj.boxType = DEMOSPACES[demospace]
elseif string.find( demospace, 'talk' ) then
-- 作为讨论页演示
obj.cfg = cfg.tmbox
obj.boxType = 'tmbox'
else
-- 默认为ombox
obj.cfg = cfg.ombox
obj.boxType = 'ombox'
end
elseif ns == 0 then
obj.cfg = cfg.ambox -- 主命名空间
obj.boxType = 'ambox'
elseif ns == 6 then
obj.cfg = cfg.imbox -- 文件命名空间
obj.boxType = 'imbox'
elseif ns == 14 then
obj.cfg = cfg.cmbox -- 分类命名空间
obj.boxType = 'cmbox'
else
local nsTable = mw.site.namespaces[ns]
if nsTable and nsTable.isTalk then
obj.cfg = cfg.tmbox -- 任何讨论命名空间
obj.boxType = 'tmbox'
else
obj.cfg = cfg.ombox -- 其他命名空间或无效输入
obj.boxType = 'ombox'
end
end
end
-- 设置参数,并移除所有空白参数,除了
-- 在cfg.allowBlankParams中列出的参数。
do
local newArgs = {}
for k, v in pairs(args) do
if v ~= '' then
newArgs[k] = v
end
end
for i, param in ipairs(obj.cfg.allowBlankParams or {}) do
newArgs[param] = args[param]
end
obj.args = newArgs
end
-- 定义内部数据结构。
obj.categories = {}
obj.classes = {}
-- 用于延迟加载[[Module:Category handler]]。
obj.hasCategories = false
return setmetatable(obj, MessageBox)
end
function MessageBox:addCat(ns, cat, sort)
if not cat then
return nil
end
if sort then
cat = string.format('[[Category:%s|%s]]', cat, sort)
else
cat = string.format('[[Category:%s]]', cat)
end
self.hasCategories = true
self.categories[ns] = self.categories[ns] or {}
table.insert(self.categories[ns], cat)
end
function MessageBox:addClass(class)
if not class then
return nil
end
self.classes[class] = 1
end
function MessageBox:removeClass(class)
if not class then
return nil
end
self.classes[class] = nil
end
function MessageBox:setParameters()
local args = self.args
local cfg = self.cfg
-- 获取类型数据。
self.type = args.type
local typeData = cfg.types[self.type]
self.invalidTypeError = cfg.showInvalidTypeError
and self.type
and not typeData
typeData = typeData or cfg.types[cfg.default]
self.typeClass = typeData.class
self.typeImage = typeData.image
-- 查找框是否被错误地替换。
self.isSubstituted = cfg.substCheck and args.subst == 'SUBST'
-- 查找我们是否使用小型消息框。
self.isSmall = cfg.allowSmall and (
cfg.smallParam and args.small == cfg.smallParam
or not cfg.smallParam and yesno(args.small)
)
-- 添加属性、类和样式。
self.id = args.id
self.name = args.name
for _, class in ipairs(cfg.classes or {}) do
self:addClass(class)
end
if self.name then
self:addClass('box-' .. string.gsub(self.name,' ','_'))
end
local plainlinks = yesno(args.plainlinks)
if plainlinks == true then
self:addClass('plainlinks')
elseif plainlinks == false then
self:removeClass('plainlinks')
end
if self.isSmall then
self:addClass(cfg.smallClass or 'mbox-small')
end
self:addClass(self.typeClass)
self:addClass(args.class)
self.style = args.style
self.attrs = args.attrs
-- 设置文本样式。
self.textstyle = args.textstyle
-- 查找我们是否在模板页面上。此功能仅在
-- useCollapsibleTextFields被设置,或者cfg.templateCategory
-- 和cfg.templateCategoryRequireName都被设置时使用。
self.useCollapsibleTextFields = cfg.useCollapsibleTextFields
if self.useCollapsibleTextFields
or cfg.templateCategory
and cfg.templateCategoryRequireName
then
if self.name then
local templateName = mw.ustring.match(
self.name,
'^[tT][eE][mM][pP][lL][aA][tT][eE][%s_]*:[%s_]*(.*)$'
) or self.name
templateName = 'Template:' .. templateName
self.templateTitle = getTitleObject(templateName)
end
self.isTemplatePage = self.templateTitle
and mw.title.equals(self.title, self.templateTitle)
end
-- 处理可折叠文本字段的数据。目前这些仅
-- 在{{ambox}}中使用。
if self.useCollapsibleTextFields then
-- 获取self.issue值。
if self.isSmall and args.smalltext then
self.issue = args.smalltext
else
local sect
if args.sect == '' then
sect = 'This ' .. (cfg.sectionDefault or 'page')
elseif type(args.sect) == 'string' then
sect = 'This ' .. args.sect
end
local issue = args.issue
issue = type(issue) == 'string' and issue ~= '' and issue or nil
local text = args.text
text = type(text) == 'string' and text or nil
local issues = {}
table.insert(issues, sect)
table.insert(issues, issue)
table.insert(issues, text)
self.issue = table.concat(issues, ' ')
end
-- 获取self.talk值。
local talk = args.talk
-- 如果talk参数为空,则在模板页面或模板子页面上显示讨论链接。
if talk == ''
and self.templateTitle
and (
mw.title.equals(self.templateTitle, self.title)
or self.title:isSubpageOf(self.templateTitle)
)
then
talk = '#'
elseif talk == '' then
talk = nil
end
if talk then
-- 如果talk值是讨论页面,则创建指向该页面的链接。否则
-- 假设它是一个章节标题,并创建指向当前页面讨论页面的链接
-- 以及该章节标题。
local talkTitle = getTitleObject(talk)
local talkArgIsTalkPage = true
if not talkTitle or not talkTitle.isTalkPage then
talkArgIsTalkPage = false
talkTitle = getTitleObject(
self.title.text,
mw.site.namespaces[self.title.namespace].talk.id
)
end
if talkTitle and talkTitle.exists then
local talkText = 'Relevant discussion may be found on'
if talkArgIsTalkPage then
talkText = string.format(
'%s [[%s|%s]].',
talkText,
talk,
talkTitle.prefixedText
)
else
talkText = string.format(
'%s the [[%s#%s|talk page]].',
talkText,
talkTitle.prefixedText,
talk
)
end
self.talk = talkText
end
end
-- 获取其他值。
self.fix = args.fix ~= '' and args.fix or nil
local date
if args.date and args.date ~= '' then
date = args.date
elseif args.date == '' and self.isTemplatePage then
date = lang:formatDate('F Y')
end
if date then
self.date = string.format(" <small class='date-container'>''(<span class='date'>%s</span>)''</small>", date)
end
self.info = args.info
if yesno(args.removalnotice) then
self.removalNotice = cfg.removalNotice
end
end
-- 设置不可折叠的文本字段。目前所有框类型
-- 除了ambox都使用此功能,当small=yes时ambox也使用。
if self.isSmall then
self.text = args.smalltext or args.text
else
self.text = args.text
end
-- 设置下方行。
self.below = cfg.below and args.below
-- 通用图像设置。
self.imageCellDiv = not self.isSmall and cfg.imageCellDiv
self.imageEmptyCell = cfg.imageEmptyCell
if cfg.imageEmptyCellStyle then
self.imageEmptyCellStyle = 'border:none;padding:0px;width:1px'
end
-- 左侧图像设置。
local imageLeft = self.isSmall and args.smallimage or args.image
if cfg.imageCheckBlank and imageLeft ~= 'blank' and imageLeft ~= 'none'
or not cfg.imageCheckBlank and imageLeft ~= 'none'
then
self.imageLeft = imageLeft
if not imageLeft then
local imageSize = self.isSmall
and (cfg.imageSmallSize or '30x30px')
or '40x40px'
self.imageLeft = string.format('[[File:%s|%s|link=|alt=]]', self.typeImage
or 'Information icon4.svg', imageSize)
end
end
-- 右侧图像设置。
local imageRight = self.isSmall and args.smallimageright or args.imageright
if not (cfg.imageRightNone and imageRight == 'none') then
self.imageRight = imageRight
end
end
function MessageBox:setMainspaceCategories()
local args = self.args
local cfg = self.cfg
if not cfg.allowMainspaceCategories then
return nil
end
local nums = {}
for _, prefix in ipairs{'cat', 'category', 'all'} do
args[prefix .. '1'] = args[prefix]
nums = union(nums, getArgNums(args, prefix))
end
-- 以下大致相当于旧的{{Ambox/category}}。
local date = args.date
date = type(date) == 'string' and date
local preposition = 'from'
for _, num in ipairs(nums) do
local mainCat = args['cat' .. tostring(num)]
or args['category' .. tostring(num)]
local allCat = args['all' .. tostring(num)]
mainCat = type(mainCat) == 'string' and mainCat
allCat = type(allCat) == 'string' and allCat
if mainCat and date and date ~= '' then
local catTitle = string.format('%s %s %s', mainCat, preposition, date)
self:addCat(0, catTitle)
catTitle = getTitleObject('Category:' .. catTitle)
if not catTitle or not catTitle.exists then
self:addCat(0, 'Articles with invalid date parameter in template')
end
elseif mainCat and (not date or date == '') then
self:addCat(0, mainCat)
end
if allCat then
self:addCat(0, allCat)
end
end
end
function MessageBox:setTemplateCategories()
local args = self.args
local cfg = self.cfg
-- 添加模板分类。
if cfg.templateCategory then
if cfg.templateCategoryRequireName then
if self.isTemplatePage then
self:addCat(10, cfg.templateCategory)
end
elseif not self.title.isSubpage then
self:addCat(10, cfg.templateCategory)
end
end
-- 添加模板错误分类。
if cfg.templateErrorCategory then
local templateErrorCategory = cfg.templateErrorCategory
local templateCat, templateSort
if not self.name and not self.title.isSubpage then
templateCat = templateErrorCategory
elseif self.isTemplatePage then
local paramsToCheck = cfg.templateErrorParamsToCheck or {}
local count = 0
for i, param in ipairs(paramsToCheck) do
if not args[param] then
count = count + 1
end
end
if count > 0 then
templateCat = templateErrorCategory
templateSort = tostring(count)
end
if self.categoryNums and #self.categoryNums > 0 then
templateCat = templateErrorCategory
templateSort = 'C'
end
end
self:addCat(10, templateCat, templateSort)
end
end
function MessageBox:setAllNamespaceCategories()
-- 为所有命名空间设置分类。
if self.isSubstituted then
self:addCat('all', 'Pages with incorrectly substituted templates')
end
end
function MessageBox:setCategories()
if self.title.namespace == 0 then
self:setMainspaceCategories()
elseif self.title.namespace == 10 then
self:setTemplateCategories()
end
self:setAllNamespaceCategories()
end
function MessageBox:renderCategories()
if not self.hasCategories then
-- 没有添加分类,无需将它们传递给Category handler,
-- 如果被调用,它将返回空字符串。
-- 所以我们直接返回空字符串。
return ""
end
-- 将分类表转换为字符串,并通过
-- [[Module:Category handler]]传递它们。
return require('Module:Category handler')._main{
main = table.concat(self.categories[0] or {}),
template = table.concat(self.categories[10] or {}),
all = table.concat(self.categories.all or {}),
nocat = self.args.nocat,
page = self.args.page
}
end
function MessageBox:export()
local root = mw.html.create()
-- 添加替换检查错误。
if self.isSubstituted and self.name then
root:tag('b')
:addClass('error')
:wikitext(string.format(
'Template <code>%s[[Template:%s|%s]]%s</code> has been incorrectly substituted.',
mw.text.nowiki('{{'), self.name, self.name, mw.text.nowiki('}}')
))
end
-- 添加TemplateStyles
root:wikitext(mw.getCurrentFrame():extensionTag{
name = 'templatestyles',
args = { src = TEMPLATE_STYLES:format(self.boxType) },
})
-- 创建框表。
local boxTable
-- 检查fmbox,因为并非所有界面消息都有mw-parser-output
-- 这是TemplateStyles所必需的。如果是fmbox则添加包装类,
-- 然后开始实际的mbox,否则开始mbox。
if self.boxType == 'fmbox' then
boxTable = root:tag('div')
:addClass('mw-parser-output')
:tag('table')
else
boxTable = root:tag('table')
end
boxTable:attr('id', self.id or nil)
for class, _ in pairs(self.classes or {}) do
boxTable:addClass(class or nil)
end
boxTable
:cssText(self.style or nil)
:attr('role', 'presentation')
if self.attrs then
boxTable:attr(self.attrs)
end
-- 添加左侧图像。
local row = boxTable:tag('tr')
if self.imageLeft then
local imageLeftCell = row:tag('td'):addClass('mbox-image')
if self.imageCellDiv then
-- 如果我们使用div,重新定义imageLeftCell,使图像
-- 位于其中。Div使用style="width: 52px;",这限制了
-- 图像宽度为52px。如果div中的任何图像比这更宽,
-- 它们可能会与文本重叠或导致其他显示问题。
imageLeftCell = imageLeftCell:tag('div'):css('width', '52px')
end
imageLeftCell:wikitext(self.imageLeft or nil)
elseif self.imageEmptyCell then
-- 一些消息框在没有指定图像时定义空单元格,
-- 一些则不定义。在指定空单元格的模板中的旧模板代码
-- 给出以下提示:"无图像。需要一些宽度或填充的单元格
-- 以使文本单元格具有100%宽度。"
row:tag('td')
:addClass('mbox-empty-cell')
:cssText(self.imageEmptyCellStyle or nil)
end
-- 添加文本。
local textCell = row:tag('td'):addClass('mbox-text')
if self.useCollapsibleTextFields then
-- 消息框使用高级文本参数,允许内容
-- 可折叠。目前只有ambox使用此功能。
textCell:cssText(self.textstyle or nil)
local textCellDiv = textCell:tag('div')
textCellDiv
:addClass('mbox-text-span')
:wikitext(self.issue or nil)
if (self.talk or self.fix) and not self.isSmall then
textCellDiv:tag('span')
:addClass('hide-when-compact')
:wikitext(self.talk and (' ' .. self.talk) or nil)
:wikitext(self.fix and (' ' .. self.fix) or nil)
end
textCellDiv:wikitext(self.date and (' ' .. self.date) or nil)
if self.info and not self.isSmall then
textCellDiv
:tag('span')
:addClass('hide-when-compact')
:wikitext(self.info and (' ' .. self.info) or nil)
end
if self.removalNotice then
textCellDiv:tag('small')
:addClass('hide-when-compact')
:tag('i')
:wikitext(string.format(" (%s)", self.removalNotice))
end
else
-- 默认文本格式化 - 任何内容都可以。
textCell
:cssText(self.textstyle or nil)
:wikitext(self.text or nil)
end
-- 添加右侧图像。
if self.imageRight then
local imageRightCell = row:tag('td'):addClass('mbox-imageright')
if self.imageCellDiv then
-- 如果我们使用div,重新定义imageRightCell,使图像
-- 位于其中。
imageRightCell = imageRightCell:tag('div'):css('width', '52px')
end
imageRightCell
:wikitext(self.imageRight or nil)
end
-- 添加下方行。
if self.below then
boxTable:tag('tr')
:tag('td')
:attr('colspan', self.imageRight and '3' or '2')
:addClass('mbox-text')
:cssText(self.textstyle or nil)
:wikitext(self.below or nil)
end
-- 为无效类型参数添加错误消息。
if self.invalidTypeError then
root:tag('div')
:css('text-align', 'center')
:wikitext(string.format(
'This message box is using an invalid "type=%s" parameter and needs fixing.',
self.type or ''
))
end
-- 添加分类。
root:wikitext(self:renderCategories() or nil)
return tostring(root)
end
--------------------------------------------------------------------------------
-- 导出函数
--------------------------------------------------------------------------------
local p, mt = {}, {}
function p._exportClasses()
-- 用于测试。
return {
MessageBox = MessageBox
}
end
function p.main(boxType, args, cfgTables)
local box = MessageBox.new(boxType, args, cfgTables or mw.loadData(CONFIG_MODULE))
box:setParameters()
box:setCategories()
return box:export()
end
function mt.__index(t, k)
return function (frame)
if not getArgs then
getArgs = require('Module:Arguments').getArgs
end
return t.main(k, getArgs(frame, {trim = false, removeBlanks = false}))
end
end
return setmetatable(p, mt)