Module:Show Path Items

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

Documentation for this module may be created at Module:Show Path Items/doc

Code

local path = require "Module:PropertyPath"
local p = {}

p.format_list_path_items = function(start, path_str , frame, max, format)

	
	max = tonumber(max) or 10
	
	format=format or "list"
	
	local elem_separator_before="* "
	local elem_separator_between="\n*"
	local elem_separator_end="\n"
	
	if format=="inline" then
		elem_separator_before=""
		elem_separator_between=" • "
		elem_separator_end=""
	end
	
	local path_obj = path.PropertyPath:new(path_str)
	local res = ""
	local i = 0
	
	if path_obj.node then
		local it = path_obj:iterate(start)
		local first=false
		for elem in it do
			i = i + 1
			if i > max then
				break
			end
			local template = nil
			if elem:has_an_item() then
				template = "Q'"
			elseif elem:has_a_property() then
				template = "P'"
			end
			res = (res and res .. elem_separator_between) or elem_separator_before
			if template then
				res = res .. frame:expandTemplate{
					title = template, 
					args = { 
						[1] = elem:entity_value() 
					} 
				}
			else
				res = res .. mw.wikibase.formatValue(elem:snak())
			end
		end
		if i == max + 1 then
			res = res .. elem_separator_between .. "...(?)"
		end
		res = res .. elem_separator_end
	else
		res =  "parse error !!!!"
		error("parse path error : «" .. path_str .."»")
	end
	return res
end

function table.slice(tbl, first, last, step)
  local sliced = {}
  
  for i = first or 1, last or #tbl, step or 1 do
    sliced[#sliced+1] = tbl[i]
  end

  return sliced
end

p.slice = table.slice

local function count_args(table)
	local nargs = 0
	for num, _ in ipairs(table) do
		nargs = num
	end
	return nargs
end

p.show_path_items = function(frame)
	frame = frame:getParent()
	
	local start = frame.args[1]
	local bound
	-- inline
	local format = frame.args.format
	
	-- concanetating numerical arguments with a pipe, to avoid to have to quote the "|" characters in the paths string
	local nargs = count_args(frame.args)
	
	if tonumber(frame.args[nargs]) then
		max = tonumber(frame.args[nargs])
		bound = nargs - 1
	else
		bound = nargs
	end
	
	local slice = table.slice(frame.args, 2, bound)
	local path_str = table.concat(slice, "|")
	----------------------------------------------------------------------------------------------
	
	return p.format_list_path_items(start, path_str, frame, max, format)
	
end

return p