모듈:Message box/연습장

require('strict')
local getArgs
local yesno = require('Module:Yesno')
local lang = mw.language.getContentLanguage()
local CONFIG_MODULE = 'Module:Message box/configuration'
local localize = mw.loadData('Module:Message box/localize')
local DEMOSPACES = {talk = 'tmbox', image = 'imbox', file = 'imbox', category = 'cmbox', article = 'ambox', main = 'ambox'}
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
local function getTitleObject(...)
	-- Get the title object, passing the function through pcall
	-- in case we are over the expensive function count limit.
	local success, title = pcall(mw.title.new, ...)
	if success then
		return title
	end
end
local function union(t1, t2)
	-- Returns the union of two arrays.
	local vals = {}
	for i, v in ipairs(t1) do
		valsv = true
	end
	for i, v in ipairs(t2) do
		valsv = 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
-- kowiki-specific start
local function getDate(date)
	-- convert yyyy-mm or yyyy-mm-dd to 'yyyy년 m월'
	local pattern1 = '^(%d%d%d%d)-(%d%d?)$'
	local pattern2 = '^(%d%d%d%d)-(%d%d?)-(%d%d?)$'
	if date then
		local y, m, _
		
		y, m = date:match(pattern1)
		if not y then
			y, m, _ = date:match(pattern2)
		end
		
		local yy, mm = tonumber(y), tonumber(m)
		
		if yy and mm and yy > 2000 and yy  0 and mm (%s)", date)
		end
		self.info = args.info
		if yesno(args.removalnotice) then
			self.removalNotice = cfg.removalNotice
		end
	end
	-- Set the non-collapsible text field. At the moment this is used by all box
	-- types other than ambox, and also by ambox when small=yes.
	if self.isSmall then
		self.text = args.smalltext or args.text
	else
		self.text = args.text
	end
	-- Set the below row.
	self.below = cfg.below and args.below
	-- General image settings.
	self.imageCellDiv = not self.isSmall and cfg.imageCellDiv
	self.imageEmptyCell = cfg.imageEmptyCell
	-- Left image settings.
	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('alt=', self.typeImage
				or 'Information icon4.svg', imageSize, self.typeImageNeedsLink and "" or "|link=" )
		end
	end
	-- Right image settings.
	local imageRight = self.isSmall and args.smallimageright or args.imageright
	if not (cfg.imageRightNone and imageRight == 'none') then
		self.imageRight = imageRight
	end
	
	-- set templatestyles
	self.base_templatestyles = cfg.templatestyles
	self.templatestyles = args.templatestyles
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
		argsprefix .. '1' = argsprefix
		nums = union(nums, getArgNums(args, prefix))
	end
	-- The following is roughly equivalent to the old .
	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', mainCat, date)
			self:addCat(0, catTitle)
			catTitle = getTitleObject('분류:' .. catTitle)
			if not catTitle or not catTitle.exists then
				self:addCat(0, '지정 날짜가 올바르지 않은 틀이 있는 문서')
			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
	-- Add template categories.
	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
	-- Add template error categories.
	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 argsparam 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()
	-- Set categories for all namespaces.
	if self.invalidTypeError then
		local allSort = (self.title.namespace == 0 and 'Main:' or ) .. self.title.prefixedText
		self:addCat('all', '잘못된 위키백과 알림 상자', allSort)
	end
	if self.isSubstituted then
		self:addCat('all', '잘못 치환된 틀을 사용한 문서')
	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
		-- No categories added, no need to pass them to Category handler so,
		-- if it was invoked, it would return the empty string.
		-- So we shortcut and return the empty string.
		return ""
	end
	-- Convert category tables to strings and pass them through
	-- Module:Category handler.
	return require('Module:Category handler')._main{
		main = table.concat(self.categories0 or {}),
		template = table.concat(self.categories10 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()
	-- Add the subst check error.
	if self.isSubstituted and self.name then
		root:tag('b')
			:addClass('error')
			:wikitext(string.format(
				'%s%s%s 틀이 잘못 치환되었습니다.',
				mw.text.nowiki()
			))
	end
	local frame = mw.getCurrentFrame()
	root:wikitext(frame:extensionTag{
		name = 'templatestyles',
		args = { src = self.base_templatestyles },
	})
	-- Add support for a single custom templatestyles sheet. Undocumented as
	-- need should be limited and many templates using mbox are substed; we
	-- don't want to spread templatestyles sheets around to arbitrary places
	if self.templatestyles then
		root:wikitext(frame:extensionTag{
			name = 'templatestyles',
			args = { src = self.templatestyles },
		})
	end
	-- Create the box table.
	local boxTable = root:tag('table')
	boxTable:attr('id', self.id or nil)
	for i, class in ipairs(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
	-- Add the left-hand image.
	local row = boxTable:tag('tr')
	if self.imageLeft then
		local imageLeftCell = row:tag('td'):addClass('mbox-image')
		if self.imageCellDiv then
			-- If we are using a div, redefine imageLeftCell so that the image
			-- is inside it. Divs use style="width: 52px;", which limits the
			-- image width to 52px. If any images in a div are wider than that,
			-- they may overlap with the text or cause other display problems.
			imageLeftCell = imageLeftCell:tag('div'):addClass('mbox-image-div')
		end
		imageLeftCell:wikitext(self.imageLeft or nil)
	elseif self.imageEmptyCell then
		-- Some message boxes define an empty cell if no image is specified, and
		-- some don't. The old template code in templates where empty cells are
		-- specified gives the following hint: "No image. Cell with some width
		-- or padding necessary for text cell to have 100% width."
		row:tag('td')
			:addClass('mbox-empty-cell')
	end
	-- Add the text.
	local textCell = row:tag('td'):addClass('mbox-text')
	if self.useCollapsibleTextFields then
		-- The message box uses advanced text parameters that allow things to be
		-- collapsible. At the moment, only ambox uses this.
		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) 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('span')
				:addClass('hide-when-compact')
					:wikitext(string.format(" (%s)", self.removalNotice))
		end
	else
		-- Default text formatting - anything goes.
		textCell
			:cssText(self.textstyle or nil)
			:wikitext(self.text or nil)
	end
	-- Add the right-hand image.
	if self.imageRight then
		local imageRightCell = row:tag('td'):addClass('mbox-imageright')
		if self.imageCellDiv then
			-- If we are using a div, redefine imageRightCell so that the image
			-- is inside it.
			imageRightCell = imageRightCell:tag('div'):addClass('mbox-image-div')
		end
		imageRightCell
			:wikitext(self.imageRight or nil)
	end
	-- Add the below row.
	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
	-- Add error message for invalid type parameters.
	if self.invalidTypeError then
		root:tag('div')
			:addClass('mbox-invalid-type')
			:wikitext(string.format(
				'이 메시지 상자는 유효하지 않은 "type=%s" 변수를 사용하고 있으므로 수정이 필요합니다.',
				self.type or 
			))
	end
	-- Add categories.
	root:wikitext(self:renderCategories() or nil)
	return tostring(root)
end
--------------------------------------------------------------------------------
-- Exports
--------------------------------------------------------------------------------
local p, mt = {}, {}
function p._exportClasses()
	-- For testing.
	return {
		MessageBox = MessageBox
	}
end
function p.main(boxType, args, cfgTables)
	-- ko-specific start
	local newargs = {}
	for k, v in pairs(args) do
		newargslocalize.arg_mapk or k = v
	end
	if newargs.type ~= nil then
		newargs.type = localize.type_mapnewargs.type or newargs.type
	end
	if newargs.small ~= nil then
		newargs.small = localize.small_mapnewargs.small or newargs.small
	end
	
	if newargs.image == '없음' then newargs.image = 'none' end
	if newargs.imageright == '없음' then newargs.imageright = 'none' end
	if newargs.smallimage == '없음' then newargs.smallimage = 'none' end
	if newargs.smallimageright == '없음' then newargs.smallimageright = 'none' end
	if newargs.date then newargs.date = getDate(newargs.date) end
	-- ko-specific end
	local box = MessageBox.new(boxType, newargs, 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)