コンテンツにスキップ

モジュール:サンドボックス/Ef3/ExLink

モジュールの解説[作成]
require('strict')
local yesno = require('Module:Yesno')
local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType

local ExLink = {}

function ExLink:entity(from)
	return mw.wikibase.getEntityObject(from) or error(("(%s) no found in wiki data"):format(tostring(from)), 0)
end
function ExLink:prop(property, from)
	return self:entity(from):formatPropertyValues(property or error("prop:", 0)) or error("prop;", 0)
end
function ExLink:propValue(property, from)
	return mw.text.decode(self:prop(property, from).value)
end
function ExLink:propLabel(property, from)
	return mw.text.decode(self:prop(property, from).label)
end

-- suffix handle
function ExLink.match_suffix(str, suffix)
	return str:match(suffix:gsub("[()]", "%%%1") .. '$')
end

-- like python
function ExLink.timeit(f,...)
	local t = os.clock()
	local r = f(...) -- use xpcall()???
	return os.clock() -t , r
end

function ExLink.new(fargs)
	fargs = fargs or {}
	local args = setmetatable({}, {
		__index = function(t,key)
			if fargs[key] and fargs[key] == '' then
				return nil
			end
			return fargs[key]
		end
	})
	
-- closure for args 
	function ExLink:id()
		return args.id or self:propValue(args.idProp or error("id and idProp no found", 0), args.from)
	end
	function ExLink:formatterURL()
		return mw.text.decode(args.formatter or self:propValue(args.formatterProp or "P1630", args.idProp) or error("ExLink:formatterURL()", 0));
	end
	function ExLink:name()
		return args.name or self:label(args.from) or self:PAGENAME()
	end
	function ExLink:PAGENAMEBASE(name)
		return (name or self:name() or self:PAGENAME() or error("PAGENAMEBASE", 0)):gsub("%s+%b()", "")
	end
	function ExLink:lang(cont)
		local lang = args.lang
		return lang and 
			tostring(mw.html.create('span')
				:attr('xml:lang', lang)
				:attr('lang', lang)
				:wikitext(cont))
			or cont
	end
	function ExLink:label(from)
		return mw.wikibase.label(from)
	end
	function ExLink:url()
		return self:formatterURL():gsub("\$1", self:id())
	end
	function ExLink:PAGENAME()
		return mw.title.getCurrentTitle().text
	end
	function ExLink:getArgs()
		return args
	end
	
	return setmetatable({args = args}, {__index = ExLink})
end

-- type1 - as Twitter, Facebook and Instagram
function ExLink.type1(frame)
	local el = ExLink.new(frame and frame.args or frame or {})
	local args = el.getArgs()
	local links = args.links or true -- 'yes' is default
	return (yesno(links) and "[%s %s]%s - [[%s]]" or  "[%s %s]%s - %s" ):format(
		el:url(),
		el:lang(el:name()),
		args.noAccount and "" or
			(el.match_suffix(el:name(),(" (%s)"):format(el:id())) and
				" " or -- backward compatibility for {{Template:Twitter}}
				(" (%s%s)"):format(args.account_prefix or '',el:id())),
		args.service or "</nowiki>:service:")
end

return ExLink