Module:EmbedItem

From Wikidata
Jump to navigation Jump to search
Lua
CodeDiscussionLinksLink count SubpagesDocumentationTestsResultsSandboxLive code All modules

Documentation for this module may be created at Module:EmbedItem/doc

Code

-- Work in progress :)
-- Intended for the new property proposals (see https://www.wikidata.org/wiki/Wikidata:Requests_for_comment/Create_items_for_property_proposals)
-- See https://doc.wikimedia.org/Wikibase/master/php/docs_topics_lua.html for the documentation of the mw.wikibase API.

local p = {}

-- debug with e.g. =p.main(nil, {'P8262'})
function p.main (frame, debugArgs)
	local args = debugArgs or frame.args
	local id = args[1]
	local ent = mw.wikibase.getEntity(id)
	local lang = args.lang or 'en'
	p.lang = lang
	
	function get_lang(map)
		return (map[lang] or map['en']).value -- fall back to English if it's not defined in the given language
	end
	
	local tbl = mw.html.create('table'):attr('class', 'wikitable')
	tbl:tag('caption'):wikitext(wikilink(id, get_lang(ent.labels)))
	
	local desc_row = tbl:tag('tr')
	desc_row:tag('td'):wikitext('description')
	desc_row:tag('td'):wikitext(mw.text.nowiki(get_lang(ent.descriptions)))
	
	if ent.type == 'property' then
		local tr = tbl:tag('tr')
		tr:tag('td'):wikitext('data type')
		tr:tag('td'):wikitext(mw.text.nowiki(ent.datatype))
	end
	
	for id, snaks in pairs(ent.claims) do
		local tr = tbl:tag('tr')
		tr:tag('td'):wikitext(wikilink(id))
		local value_cell = tr:tag('td')
		local best_stmts = ent:getBestStatements(id)
		if #best_stmts == 1 then
			value_cell:wikitext(format_stmt(best_stmts[1]))
		else -- there are more than one statement for the property
			local ul = value_cell:tag('ul')
			for id, stmt in ipairs(best_stmts) do
				ul:tag('li'):wikitext(format_stmt(stmt))
			end
		end
		
	end
	
	return tostring(tbl)
end

function format_stmt(stmt)
	local out = format_snak(stmt.mainsnak)
	if stmt.qualifiers then
		local ul = mw.html.create('ul')
		for id, snaks in pairs(stmt.qualifiers) do
			local values = {}
			for _, snak in pairs(snaks) do
				table.insert(values, format_snak(snak))
			end
			ul:tag('li'):wikitext(wikilink(id) .. ': ' .. table.concat(values, ', '))
		end
		out = out .. '<br>' .. tostring(ul)
	end
	return out
end

function format_snak(snak)
	if snak.datavalue.type == 'wikibase-entityid' then
		return wikilink(snak.datavalue.value.id)
	elseif snak.datavalue.type == 'string' then
		return mw.text.nowiki(snak.datavalue.value)
	elseif snak.datavalue.type == 'monolingualtext' then
		return mw.text.nowiki(snak.datavalue.value.text)
	else
		return mw.text.nowiki(mw.text.jsonEncode(snak.datavalue))
	end
end

function wikilink(id, label)
	label = label or mw.wikibase.getLabelByLang(id, p.lang) or mw.wikibase.getLabel(id)
	target = id
	if id:sub(1, 1) == 'P' then
		target = 'Property:' .. id
	end
    return '[[' .. target .. '|' .. mw.text.nowiki(label) .. ']]'
end

return p