跳转到内容

模組:ZyPy

local p = {}

local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
	local args = getArgs(frame, { wrappers = 'Template:Zy' })
	return p._main(args)
end

function p.nocat(frame)
	local args = getArgs(frame, { wrappers = 'Template:ZyPy' })
	args.nocat = true
	return p._main(args)
end

function p._main(args)
	local pinyin   = args[2] and mw.text.tag{ name = 'span', attrs = { lang = 'zh-Latn-pinyin' }, content = args[2] }
	local zhuyin   = args[3] and mw.text.tag{ name = 'span', attrs = { lang = 'zh-Bopo' }, content = args[3] }
	local jyutping = args[4] and mw.text.tag{ name = 'span', attrs = { lang = 'yue-Latn-jyutping' }, content = args[4] }

	if not pinyin and not zhuyin then
		return args[1]
	end

	local ruby = mw.html.create('ruby'):addClass('zy')
	ruby:wikitext(args[1])
	ruby:tag('rp'):wikitext('(')
	ruby:tag('rt'):wikitext(string.format(
		'-{zh-hans:%s;zh-hant:%s;zh-tw:%s;zh-hk:%s;}-',
		pinyin or zhuyin,            -- zh-hans (zh-cn, zh-my, zh-sg, zh)
		pinyin or zhuyin,            -- zh-hant
		zhuyin or pinyin,            -- zh-tw
		jyutping or pinyin or zhuyin -- zh-hk (zh-mo)
	))
	ruby:tag('rp'):wikitext(')')

	local rubyText = tostring(ruby)

	-- 僅在部分變體下注音
	local v = args.v
	local t = {
		hans = 'tw',
		hant = 'cn'
	}
	if v and t[v] then
		rubyText = string.format(
			'-{zh-%s:-{zh;zh-hans;zh-hant|%s}-;zh-%s:%s;}-',
			v,
			rubyText,
			t[v],
			args[1]
		)
	end

	if args.nocat then
		return rubyText
	end

	-- 維護分類
	local getCategoryName = require('Module:Lang')._category_from_tag
	local result = { rubyText }
	if mw.title.getCurrentTitle().namespace == 0 then
		if pinyin then
			table.insert(result, '[[')
			table.insert(result, getCategoryName({ 'zh-Latn-pinyin' }))
			table.insert(result, ']]')
		end
		if zhuyin then
			table.insert(result, '[[')
			table.insert(result, getCategoryName({ 'zh-Bopo' }))
			table.insert(result, ']]')
		end
		-- 目前沒有粵拼分類
		-- if jyutping then
		-- 	table.insert(categories, '[[')
		-- 	table.insert(categories, getCategoryName({' yue-Latn-jyutping '}))
		-- 	table.insert(categories, ']]')
		-- end
	end
	local count = (pinyin and 1 or 0) + (zhuyin and 1 or 0) + (jyutping and 1 or 0)
	if count == 3 then
		table.insert(result, '[[Category:使用了三种注音方式的页面]]')
	elseif count == 2 then
		table.insert(result, '[[Category:使用了两种注音方式的页面]]')
	else
		table.insert(result, '[[Category:使用了一种注音方式的页面]]')
	end

	return table.concat(result)
end

return p