模块:CGroupViewer

求闻百科,共笔求闻

本模块用于以Lua语言执行公共转换组中的字词转换规则。

上述文档内容嵌入自Module:CGroupViewer/doc编辑 | 历史
编者可以在本模块的沙盒创建 | 镜像和测试样例创建页面进行实验。
请将模块自身所属的分类添加在文档中。本模块的子页面
local z = {}
local error = require( 'Module:Error' )

local function makeText( frame, v )
	local text = v.text
	if not v.preprocessed then
		text = frame:preprocess( text )
	end
	return mw.text.trim( text ) .. '\n'
end

local function makeItem( frame, v )
	local text = '* '
	if v.original then
		text = text .. '原文:' .. v.original .. ';'
	end
	return text .. '-{D|' .. v.rule .. '}-当前显示为:-{|' .. v.rule .. '}-\n'
end

function z.main( frame )
	local name = frame.args[1]
	if not name or name == '' then
		return ''
	end
	local data = require( 'Module:CGroup/' .. name )
	if type( data ) ~= 'table' or not data.name or data.name == '' then
		return error.error{ '指定模块“' .. name .. '”不是有效的转换组' }
	end
	if data.name ~= name then
		return frame:expandTemplate{ title = 'Template:CGroup redirect', args = { 'Module:CGroup/' .. data.name } }
	end
	local pieces = {
		'<strong>以下是[[Help:公共转换组|公共转换组]]“' .. data.description .. '”。</strong>\n\n',
	}
	for i, v in ipairs( data.content ) do
		if v.type == 'text' then
			table.insert( pieces, makeText( frame, v ) )
		elseif v.type == 'item' then
			table.insert( pieces, makeItem( frame, v ) )
		end
	end
	table.insert( pieces, '[[Category:公共转换组模块|' .. name .. ']]' )
	return table.concat( pieces )
end

function z.dialog( frame )
	local name = frame.args[1]
	if not name or name == '' then
		return ''
	end
	local data = require( 'Module:CGroup/' .. name )
	local pieces = { '<div class="mw-collapsible mw-collapsed"><span class="plainlinks" style="float: right; padding-left: 0.2em; ">&#91;[',
		tostring( mw.uri.fullUrl( 'Module:CGroup/' .. name, { action = 'edit' } ) ),
    	' 编辑]&#93;</span>\n<span class="plainlinks" style="float: right;">&#91;[',
    	tostring( mw.uri.fullUrl( 'Module:CGroup/' .. name ) ),
    	' 查看]&#93;</span>\n',
		'; 本文使用[[Help:公共转换组|公共转换组]]“' .. data.description .. '”。\n',
		'<div class="mw-collapsible-content">\n' }
	for i, v in ipairs( data.content ) do
		if v.type == 'item' then
			table.insert( pieces, makeItem( frame, v ) )
		end
	end
	table.insert( pieces, '</div></div>' )
	return table.concat( pieces )
end

function z.json( frame )
	local name = frame.args[1]
	if not name or name == '' then
		return 'null'
	end
	local data = require( 'Module:CGroup/' .. name )
	local json = require( 'Module:MicroJSON' )
	return json.encode_object( data, {
		name = '',
		description = '',
		content = {
			{ type = '', [true] = '' },
		},
	} )
end

function z.test(frame)
	frame = frame or mw.getCurrentFrame()
	local name = frame.args[1]
	assert(name, "请提供公共转换组名称。")
	if type(name)~='string' then
		error "没有指定有效的公共转换组页面名称。"
	end
	local state, data = pcall(mw.loadData,  'Module:CGroup/' .. name)
	if not state then
		return "无法加载[[" .. name .. "]]的数据,原因:" .. data
	end
	return tostring(require 'Module:CGroup'.test(data, nil, frame))
end

return z