Модуль:category tree

Wiktionary дан

Бул модулда категория шаблонго үлгүлөрүн жаратуу үчүн колдонулат. Бул түздөн-түз пайдалануу үчүн арналган эмес. Тескерисинче, ар бир үлгүсү деп Калып өзгөчөлүктөрүн тейлеген өз суб модулу, ээ болот.

Бул документтешитирүү гана категория дарак системасынын генерик камтыйт. Эгер белгилүү бир шаблон тууралуу, же кошуп же категория маалыматтарды өзгөртүү кантип документтерди издеп жаткан болсо, ошол үлгүсү документтерди карагыла.

Параметрлер[түзөтүү]

категория дарак модулу катары кылынса:

{{#invoke:category tree|show|template=name of the template|...other parameters...}}

бул модулду колдонгон ар бир шаблон шаблон= параметр берилген аты Бул модулдан турган субмодулду болушу керек. Бул субмодулу бир параметр ашат деген милдетти экспорттоо керек: адегенде калып кабыл алынган ар кандай параметрлерди камтыйт үстөл деген маалымат. параметрлерин айкалышы (б.а. эч кандай категория бар) туура эмес болсо, бул милдетти бир жаңы категория объект ошол параметрлерин өкүлү, же nil нөлгө барабар болууга тийиш.

Көпчүлүк үлгүлөрүн кабыл алуу жана параметрлерин бул жалпы комплексин өтөт. калыбы боюнча модулду өткөн параметрлери ар бир шаблон сөзсүз Булардын баары колдоно турган эмес, ошондуктан, ал шаблону менен өз-өзүнчө аныкталат. {{famcatboiler}}, мисалы, бир гана модулда code= параметрин өтөт.

code=
калыптык анын мазмунун 'ээлик' көрсөтүлгөн коду. Бул, адатта, Эн сыяктуу тил коду, ал эми ошол эле учурда белгилүү бир шаблон аны ыйык тутпаса, кантип жараша тил үй-Latn сыяктуу же коду бир скрипт коду, болушу мүмкүн.
label=
категорияланган жаткан иш үчүн аты-жөнү. суб модулда белги чечмелеп кантип аныктайт, ошондуктан шаблон колдонулган көз каранды. Көп үлгүлөрүн башка кандайдыр бир тил коду катары чечмеленет мүмкүн, ал эми үстөлдүн маалыматтарды карап үчүн колдонушат.
sc=
буюмдарды скрипт коду бөлүштүрсөк болот. Бул, адатта, бош эмес, ал эми кытай тарабынан колдонулган көптөгөн категориялар алиппесине негизделген Биики ыскылаакка бөлүүгө болот.

Жалпы иштеп чыккан[түзөтүү]

Модулу категориядагы эки негизги түрлөрүнүн негизинде жүзөгө ашырылат:

Basic categories are those for which the code= parameter is not empty. These therefore belong to a specific language (or similar) and are the "regular" categories. Examples are: Category:English nouns, Category:French templates, Category:nl:Linguistics, Category:Япон алынган англисче терминдер, Category:Латын жазуусу белги.

Umbrella categories do not have a code, but contain all basic categories of their label, one for each code. These are the "by language" type categories. Examples are: Category:Nouns by language, Category:Templates by language, Category:Linguistics, Category:Terms derived from Japanese, Category:Characters by script.

Some templates also distinguish a third type of category, the fundamental category. This category is used as the parent category for umbrella categories.

Category objects[түзөтүү]

Бул документтешитирүү эскирген.
Бул баракта же бөлүгү боюнча документтер мындан ары анын учурдагы абалын чагылдырган, ал эми кээ бир маалымат жок же туура эмес болушу мүмкүн. мындан ары колдонулуучу маалыматтарды алып, ал эми маянасы өзгөчөлүктөрү жөнүндө the документтерди бет, жана кошумча маалымат түзөтүп, жардам берчи.

Category objects are returned by each submodule's new function. They represent a single category in the tree. A category object has a variety of methods which may be called on it to ask for information about the category.

getBreadcrumbName[түзөтүү]

getBreadcrumbName()

Returns the name that is used for the category in the "breadcrumbs" at the top of the category page.

getDataModule[түзөтүү]

getDataModule()

Returns the name of the module which contains the data for this category. This is used to create an "edit" link on the category, which allows users to find and edit the information more easily.

getCategoryName[түзөтүү]

getCategoryName()

Returns the name of the category that this category object represents.

getDescription[түзөтүү]

getDescription()

Returns the description text that is shown at the top of the category page. If the category has no description, this returns nil.

getParents[түзөтүү]

getParents()

Returns a table of the parent categories of this category. Each element in the table is a table itself, with two elements:

.name
One of two possibilities: An category object representing the parent category, or a string that directly specifies the name of the parent category.
.sort
The sorting key that should be used when categorizing the current category in the parent.

If the category has no parents, this returns nil.

getChildren[түзөтүү]

getChildren()

Returns a table of the child categories of this category. Each element in the table is a category object representing the child category. If the category has no children, this returns nil.

getUmbrella[түзөтүү]

getUmbrella()

Returns a category object for the current category's corresponding umbrella category. If the current category is already an umbrella category, this returns nil. It also returns nil if the category has no umbrella category.


local export = {}
local m_languages = require('Module:languages')

-- негизги кирүү чекити.
-- Бул калып келген дуба болот бир гана милдети болуп саналат.
function export.show(frame)
	if mw.title.getCurrentTitle().nsText == "Калып" then
		return "(Бул шаблон категориядагы барактар колдонулат: ат.)"
	elseif mw.title.getCurrentTitle().nsText ~= "Категория" then
		error("Бул шаблон / модулу гана категориядагы барактар колдонууга болот: ат.")
	end
	
	local args = frame.args
	
	-- бардык параметрлер жана энбелгиси маалыматтарды алуу
	local info = {}
	
	for key, val in pairs(args) do
		info[key] = val; if info[key] == "" then info[key] = nil end
	end
	
	if not info.template then
		error("Бул \"Калып\" параметр көрсөтүлгөн эмес.")
	end
	
	local template = info.template
	info.template = nil
	local current = require("Module:category tree/" .. template).new(info, true)
	local boxes = {}
	local display = {}
	local categories = {}
	
	-- категория азыр бош болсо, текшерүү
	local isEmpty = mw.site.stats.pagesInCategory(mw.title.getCurrentTitle().text, "all") == 0
	
	-- параметрлери жарактуу болуп саналат?
	if not current then
		table.insert(categories, "[[Category:Жараксыз энбелгиси менен категориялар]]")
		table.insert(categories, isEmpty and "[[Category:Бош категориялар]]" or nil)
		table.insert(display, show_error(
			"этикетка \"" .. (info.label or "") .. "\" берилген " ..
			mw.getCurrentFrame():expandTemplate{title = "temp", args = {template}} ..
			" шаблон жарактуу эмес. Аны джазгъан болурсуз, мүмкүн, же тек гана жаратыла элек. " ..
			"бир жаңы Белги кошуп, үлгүсү документтерди сураныч кайрылышат."))
		
		-- бул жерде наркы өйүзүндөгү жерлердин баарын коду учурдагы Жуллиан болуп саналбаган таянат эле, бул жерде чыгып
		return table.concat(categories, "") .. table.concat(display, "\n\n") .. "<br clear=\"all\"/>"
	end
	
	-- категория туура ысмы барбы?
	if mw.title.getCurrentTitle().text ~= current:getCategoryName() then
		table.insert(categories, "[[Category:Туура эмес аты менен категориялар]]")
		table.insert(display, show_error(
			"Берилген параметрлерге негизделген " ..
			mw.getCurrentFrame():expandTemplate{title = "temp", args = {template}} ..
			" шаблон, бул категория деп аталат керек '''[[:Category:" .. current:getCategoryName() .. "]]'''."))
	end
	
	-- Бош категориялары үчүн тазалоо категория кошуу
	if isEmpty and not current:canBeEmpty() then
		table.insert(categories, "[[Category:Бош категориялар]]")
	end
	
	if current:isHidden() then
		table.insert(categories, "__HIDDENCAT__")
	end
	
	table.insert(boxes, show_editlink(current))
	table.insert(boxes, show_pagelist(info))
	
	-- Көрсөтүлгөн маалыматтарды иштеп чыгуу
	table.insert(display, show_breadcrumbs(current))
	table.insert(display, show_description(current))
	table.insert(display, show_children(current))
	table.insert(display, show_TOC(info))
	
	show_categories(current, categories)
	
	return table.concat(categories, "") .. table.concat(boxes, "\n") .. "\n" .. table.concat(display, "\n\n") .. "<br clear=\"all\"/>"
end

function show_error(text)
	return  mw.getCurrentFrame():expandTemplate{title = "maintenance box", args = {
		"red",
		image = "[[File:Ambox warning pn.svg|50px]]",
		title = "Бул категориянын жазуусу түзүлгөн көрүү каталар бар.",
		text = text,
		}}
end

-- Учурдагы барактын атын текшерип, бул туура эмес, эгер ката кайрылып.
function check_name(current, template, info)
	local errortext = nil
	local category = nil
	
	if not current then
		errortext =
			"The label \"" .. (info.label or "") .. "\" given to the " .. mw.getCurrentFrame():expandTemplate{title = "temp", args = {template}} .. " template is not valid. " ..
			"You may have mistyped it, or it simply has not been created yet. To add a new label, please consult the documentation of the template."
		category = "[[Category:Categories with invalid label]]"
	else
		
	end
	
	if errortext then
		return (category or "") .. show_error(errortext)
	else
		return nil
	end
end

-- Show the parent categories that the current category should be placed in.
function show_categories(current, categories)
	local parents = current:getParents()
	
	if not parents then
		return
	end
	
	for _, parent in ipairs(parents) do
		if type(parent.name) == "string" then
			table.insert(categories, "[[" .. parent.name .. "|" .. parent.sort .. "]]")
		else
			local parent_name = parent.name:getCategoryName()
			table.insert(categories, "[[Category:" .. parent_name .. "|" .. parent.sort .. "]]")
		end
	end
	
	-- Also put the category in its corresponding "umbrella" or "by language" category.
	local umbrella = current:getUmbrella()
	
	if umbrella then
		if type(umbrella) == "string" then
			table.insert(categories, "[[" .. umbrella .. "|" .. current:getCategoryName() .. "]]")
		else
			table.insert(categories, "[[Category:" .. umbrella:getCategoryName() .. "|" .. current:getCategoryName() .. "]]")
		end
	end
end

function show_editlink(current)
	return
		"<div class=\"noprint plainlinks\" style=\"float: right; clear: both; margin: 0 0 .5em 1em; background: #f9f9f9; border: 1px #aaaaaa solid; padding: 5px; font-weight: bold;\">[" ..
		mw.getCurrentFrame():callParserFunction{name = "fullurl", args = {current:getDataModule(), action = "edit"}} ..
		" Edit category data]</div>"
end

function show_pagelist(info)
	local namespace = ""
	
	if info.label == "citations" or info.label == "citations of undefined terms" then
		namespace = "Citations"
	elseif info.code then
		local lang = require("Module:languages").getByCode(info.code)
		
		if lang then
			if lang:getType() == "reconstructed" then
				namespace = "Reconstruction"
			elseif lang:getType() == "appendix-constructed" then
				namespace = "Appendix"
			end
		end
	end
	
	local recent = mw.getCurrentFrame():callParserFunction{
		name = "#tag",
		args = {
			"DynamicPageList",
			"category=" .. mw.title.getCurrentTitle().text .. "\n" ..
			"namespace=" .. namespace .. "\n" ..
			"count=10\n" ..
			"mode=ordered\n" ..
			"ordermethod=categoryadd\n" ..
			"order=descending"
		}
	}
	
	local oldest = mw.getCurrentFrame():callParserFunction{
		name = "#tag",
		args = {
			"DynamicPageList",
			"category=" .. mw.title.getCurrentTitle().text .. "\n" ..
			"namespace=" .. namespace .. "\n" ..
			"count=10\n" ..
			"mode=ordered\n" ..
			"ordermethod=lastedit\n" ..
			"order=ascending"
		}
	}
	
	return [=[
{| class="wikitable" style="float: right; clear: both; margin: 0 0 .5em 1em;"
! Recent additions to the category
|-
| style="font-size:0.9em;" | ]=] .. recent .. [=[

|-
! Oldest pages ordered by last edit
|-
| style="font-size:0.9em;" | ]=] .. oldest .. [=[

|}]=]
end

-- Show navigational "breadcrumbs" at the top of the page.
function show_breadcrumbs(current)
	local steps = {}
	
	-- Start at the current label and move our way up the "chain" from child to parent, until we can't go further.
	while current do
		local category = nil
		local display_name = nil
		
		if type(current) == "string" then
			category = current
			display_name = current:gsub("^Category:", "")
		else
			category = "Category:" .. current:getCategoryName()
			display_name = current:getBreadcrumbName()
		end
		
		display_name = mw.getContentLanguage():ucfirst(display_name)
		table.insert(steps, 1, "» [[:" .. category .. "|" .. display_name .. "]]")
		
		-- Move up the "chain" by one level.
		if type(current) == "string" then
			current = nil
		else
			current = current:getParents()
			
			if current then
				current = current[1].name
			end
		end
	end
	
	return "<small>" .. table.concat(steps, " ") .. "</small>"
end

-- Show a short description text for the category.
function show_description(current)
	return (current:getDescription() or "")
end

-- Show a list of child categories.
function show_children(current)
	local children = current:getChildren()
	
	if not children then
		return nil
	end
	
	table.sort(children, function(first, second) return first.sort < second.sort end)
	
	local children_list = {}
	
	for _, child in ipairs(children) do
		local child_basic = child.name:getCategoryName()
		local child_page = mw.title.new("Category:" .. child_basic)
		
		if child_page.exists then
			local child_description = child.name:getDescription()
			table.insert(children_list, "* [[:Category:" .. child_basic .. "]]: " .. child_description)
		end
	end
	
	return table.concat(children_list, "\n")
end

-- Show a table of contents with links to each letter in the language's script.
function show_TOC(info)
	local code = info.code or "en"
	local num_pages = 300 --mw.site.stats.pagesInCategory(mw.title.getCurrentTitle().text, "pages")
	
	-- No need for a TOC if all entry names can fit on one page.
	if num_pages > 200 then
		-- This category is very large, see if there is an "extended" version of the TOC.
		if num_pages > 2500 then
			local TOC_template_extended = mw.title.new("Template:" .. code .. "-categoryTOC/full")
			
			if TOC_template_extended.exists then
				return mw.getCurrentFrame():expandTemplate{title = TOC_template_extended.text, args = {}}
			end
		end
		
		local TOC_template = mw.title.new("Template:" .. code .. "-categoryTOC")
		
		if TOC_template.exists then
			return mw.getCurrentFrame():expandTemplate{title = TOC_template.text, args = {}}
		end
	end
	
	return nil
end

return export