Модуль:HF/Infobox/Jutsu

Материал из Викимультии — энциклопедии мультипликации
Это старая версия этой страницы, сохранённая Alexandr Efremov (обсуждение | вклад) в 21:34, 13 февраля 2021. Она может серьёзно отличаться от текущей версии.
Перейти к навигации Перейти к поиску


Документация
local Infobox = {}

------------------------------------
-- Libraries and Global functions --
------------------------------------
-- "High Frequency" functions
local HF = require('Module:HF')
-- Parses invocation and template parameters, trims whitespace, and removes blanks.
local getArgs = require('Module:Arguments').getArgs
-- Generates lists
local L = require('Module:List')
-- Language functions
local language = mw.language.new('ru')

-- Helper functions (local to not have to worry about namespaces)
local arraymap = require('Module:HF/Infobox').arraymap
local arrayTable = require('Module:HF/Infobox').arrayTable
local base = require('Module:HF/Infobox').base
local extra1 = require('Module:HF/Infobox').extra1

-- The page title of whatever page is calling the function
local pageTitle = mw.title.getCurrentTitle().text

-- Convenient constants
local stripLinkToTarget = '^%[*([^%[|]*)|?'
local stripPageTitleToBase = "[^(]*"
local basepattern = '^[^~]*'
local extra1pattern = '^[^~]*~([^~]*)'

------------------------------------------------
-- Local functions (used only in this Module) --
------------------------------------------------
-- Replaces {{IsUnnamed}}
local function nameCheck ( target )
	local nq = mw.smw.ask{ HF.Link(target:match(stripLinkToTarget)), '?Обслуживание' }
	if type(nq) == 'table' 
	    and (
	        nq[1]['Обслуживание'] == 'Название'
	        or (type(nq[1]['Обслуживание']) == 'table' and table.concat(nq[1]['Обслуживание']):match('Name'))
	    )
        then
		return true
	else return nil
	end
end

----------------------------------------------------------
-- Public functions (called from a Template or article) --
----------------------------------------------------------
-- Creates the infobox main title
function Infobox.titleJutsu(frame)
	local args = getArgs(frame)
	local out = {}
	if mw.title.getCurrentTitle().isContentPage == true then
		table.insert( out, HF.Category('Jutsu') )
		local _editFormURL = mw.html.create('span')
			:css('float','right'):css('font-size','x-small')
            :wikitext( HF.Link('Special:FormEdit/Jutsu/' .. pageTitle, 'edit') ):allDone()			
		local editFormURL = tostring(_editFormURL)
		if args['название'] then
			mw.smw.set {
				['Название'] = args['название'],
				['Названия'] = args['название']
			}
		end
		if args['кандзи'] then
			mw.smw.set {
				['Кандзи'] = args['кандзи'],
				['Названия'] = args['кандзи']
			}
		else
			mw.smw.set { ['Обслуживание'] = 'Кандзи' }
		end
		if args['киридзи'] then
			mw.smw.set{
				['Киридзи'] = args['киридзи']:match(stripLinkToTarget),
				['Названия'] = args['киридзи']
			}
		end
		if args['команда'] then
			local teams = mw.text.split( args['команда'], ',%s*' )
			for _, v in ipairs(teams) do
				mw.smw.set{ ['Команда'] = mw.text.trim(v) }
			end
		end
		if args['изображение'] then
			local images = mw.text.split( args['изображение'], '\n')
			for _, image in ipairs(images) do
				if type(image) == 'string' then
					mw.smw.set{ ['Изображение'] = 'File:' .. image:match("[^:;]*") }
				end
			end
		else
			mw.smw.set{ ['Обслуживание'] = 'Отсутствующее изображение' }
		end
		if args['безымянное дзюцу'] == 'Да' then
			mw.smw.set{ ['Обслуживание'] = 'Название' }
			table.insert( out, ("''%s''"):format( pageTitle:match("[^(]*") ) )
		else
				table.insert( out, pageTitle:match("[^(]*") )
		end
		local popup = frame:newParserValue(
			"{{#queryformlink:form=Image query|link text=" ..
			"[[File:Camera font awesome.svg|15px|link=]]" ..
			"|query string=Image_query[jutsu]=" .. pageTitle ..
			"&_run|wpRunQuery=true|popup|tooltip=Images of " .. pageTitle .. " }}"
		)
		return table.concat( out ) .. popup:expand() .. ( args['ref'] or '' ) .. editFormURL
	elseif mw.title.getCurrentTitle().namespace == 10
	    and not pageTitle:match('/testcases') then
	    return nil
	else
		if args['безымянное дзюцу'] == 'Да' then
			table.insert( out, ("''%s''"):format( args['название'] or pageTitle:match("[^(]*") ) )
		else
			table.insert( out, args['название'] or pageTitle:match("[^(]*") )
		end
		return table.concat( out ) .. ( args['ref'] or '' )
	end
end

function Infobox.jutsuClassification(frame)
	local args = getArgs(frame)
	local classifications =
		type(args['классификация дзюцу']) == 'string'
		and mw.text.split( args['классификация дзюцу'], ',%s*' )
	if type(classifications) == 'table' then
		local out = {}
		local icons = {}
		local kekkei = {
			['kekkei mōra'] = true,
			['kekkei tōta'] = true,
			['kekkei genkai'] = true
		}
		for _,classification in ipairs(classifications) do
			if classification:match(extra1pattern) then
				if classification:match(basepattern):lower() == 'hiden' then
					local options = {
						['SemanticPropertyName'] = 'Клан',
						['PrependText'] = 'Клан ниндзя',
						['PrependTemplate'] = 'Карточка/Значки',
						['Print'] = 'none',
						['Link'] = 'default'
					}
					local clans = arrayTable( classification:match('^[^~]*~(.*)'), '~', options, frame )
					table.insert( icons, table.concat( clans ) )
				elseif kekkei[classification:match(basepattern):lower()] then
					local options = {
						['SemanticPropertyName'] = 'Кэккэй Гэнкай',
						['PrependText'] = 'Кэккэй Гэнкай',
						['PrependTemplate'] = 'Карточка/Значки',
						['Print'] = 'none',
						['Link'] = 'default'
					}
					local clans = arrayTable( classification:match('^[^~]*~(.*)'), '~', options, frame )
					table.insert( icons, table.concat( clans ) )
				end
			end
			if classification:match(basepattern) and #classification > 1 then
				mw.smw.set { ['Классификация дзюцу'] = classification:match(basepattern) }
				table.insert( out, HF.Link(classification:match(basepattern)) )
			end
		end
		return table.concat( icons ) .. table.concat( out, ', ' )
	else return nil
	end
end

function Infobox.jutsuType(frame)
	local args = getArgs(frame)
	local options = {
		['SemanticPropertyName'] = 'Природа чакры',
		['PrependText'] = 'Природа',
		['PrependTemplate'] = 'Карточка/Значки',
		['Link'] = 'default'
	}
	local values = arrayTable ( args['тип дзюцу'], ',%s*', options, frame )
	return L.makeList( 'unbulleted' , values )
end

function Infobox.jutsuRank(frame)
	local args = getArgs(frame)
	local array = mw.text.split( args['ранг дзюцу'], ',' )
	local out = {}
	for _, v in ipairs( array ) do
		table.insert( out , HF.Link('Ранг дзюцу::'..v, v..'-rank') )
	end
	return table.concat( out, ',' )
end

function Infobox.jutsuClass(frame)
	local args = getArgs(frame)
	local options = {
		['SemanticPropertyName'] = 'Тип класса дзюцу',
		['Link'] = 'none'
	}
	local classes = arrayTable ( args['тип класса дзюцу'], ',%s*', options, frame )
	return table.concat( classes, ', ' )
end

function Infobox.jutsuRange(frame)
	local args = getArgs(frame)
	local ranges = {
		['Короткий'] = 'Короткий диапазон (0-5м)',
		['Средний'] = 'Средний диапазон (5-10м)',
		['Длинный'] = 'Дальность действия (10 м+)',
		['Короткий, Средний, Длинный'] = 'Все диапазоны',
		['Короткий, Средний'] = 'Короткий и средний диапазон (0-10м)',
		['Средний, Длинный'] = 'Средний и длинный диапазон (5 м+)',
		['Короткий, Длинный'] = 'Короткий или длинный диапазон (0-5м или 10м+)'
	}
	arrayTable ( args['диапазон дзюцу'], ',%s*', { ['SemanticPropertyName'] = 'Диапазон дзюцу' } )
	return ranges[args['диапазон дзюцу']] or args['jutsu range']..'-range'
end

function Infobox.jutsuParent(frame)
	local args = getArgs(frame)
	local options = {
		['SemanticPropertyName'] = 'Родительское дзюцу',
		['Link'] = 'Безымянное',
		['UnnamedFormat'] = true
	}
	local Parents = arrayTable ( args['родительское дзюцу'], ',%s*', options )
	return L.makeList( 'unbulleted', Parents )
end

function Infobox.jutsuMedia(frame)
	local args = getArgs(frame)
	local out = {}
	local mtypes = {
		['Фильм'] = 'Дзюцу/НеКанон',
		['Игра'] = 'Дзюцу/НеКанон',
		['Игра, Фильм'] = 'Дзюцу/НеКанон'
	}
	local mq = mw.smw.ask {
		(HF.Link('Concept:%s')):format( mtypes[args['дзюцу медиа']] or 'Дзюцу/Канон' ),
		(HF.Link('Родительское дзюцу::%s')):format( mw.title.getCurrentTitle().prefixedText ),
		'?Появляется в',
		'?Обслуживание',
		('userparam=%s'):format(args['дзюцу медиа']),
		'mainlabel=main',
		'limit=200'
	}
	local hasNCderivatives = mw.smw.ask {
		(HF.Link('Concept:%s')):format( 'Дзюцу/НеКанон' ),
		(HF.Link('Родительское дзюцу::%s')):format( mw.title.getCurrentTitle().prefixedText )
	}
	if type(mq) == 'table' then
		for _, Parent in ipairs(mq) do
			local mainlink =
				(
				    Parent['Обслуживание'] == 'Название'
				    or (
				        type(Parent['Обслуживание']) == 'table'
				        and table.concat(Parent['Обслуживание']):match('Название')
		            )
			    )
				and ("''%s''"):format(
					HF.Link(
						Parent['main']:match(stripLinkToTarget),
						Parent['main']:match('%[%[:?([^|]*)|?'):match(stripPageTitleToBase)
					)
				)
				or HF.Link(
					Parent['main']:match(stripLinkToTarget),
					Parent['main']:match('%[%[:?([^|]*)|?'):match(stripPageTitleToBase)
				)
			local dq = mw.smw.ask {
				(HF.Link('Concept:%s')):format( mtypes[args['дзюцу медиа']] or 'Дзюцу/Канон' ),
				(HF.Link('Родительское дзюцу::%s')):format( Parent['main']:match(stripLinkToTarget) ),
				('userparam=%s'):format( args['дзюцу медиа'] or 'Аниме, Манга' ),
				'mainlabel=main',
				'named args=yes',
				'limit=20'
			}
			local derivatives = {}
			if type( dq ) == 'table' then
				for _, derived in ipairs(dq) do
					local dlink = (
					    derived['Обслуживание'] == 'Название'
					    or type(derived['Обслуживание']) == 'table'
				        and table.concat(derived['Обслуживание']):match('Название')
					    )
					and ("''%s''"):format(
						HF.Link(
							derived['main']:match(stripLinkToTarget),
							derived['main']:match('%[%[:?([^|]*)|?'):match(stripPageTitleToBase)
						)
					)
					or HF.Link(
						derived['main']:match(stripLinkToTarget),
						derived['main']:match('%[%[:?([^|]*)|?'):match(stripPageTitleToBase)
					)
					table.insert( derivatives, dlink )
				end
				table.insert( out, mainlink .. L.makeList( 'bulleted', derivatives ) )
			else
				table.insert( out, mainlink )
			end
		end
		return L.makeList( 'bulleted', out )
	elseif type(hasNCderivatives) == 'table' then
	    local t = 
	        mw.title.new( 'SearchByProperty', 'Special' ).prefixedText
	    local q = mw.uri.buildQueryString{ 
	        ['property'] = 'Родительское дзюцу',
	        ['value'] = mw.uri.encode(
	            mw.title.getCurrentTitle().prefixedText,
	            'WIKI'
	            )
        }
        local searchlink = HF.ExternalLink(
            tostring(mw.uri.fullUrl(t,q)),
            'Все производные дзюцу'
        )
	    return ('<center class="smwsearch">%s</center>'):format( searchlink )
	end
end

function Infobox.jutsuRelated(frame)
	local args = getArgs(frame)
	return arraymap( args['родственные дзюцу'], ',%s*', HF.Link('%s'), ', ' )
end

function Infobox.jutsuUsers(frame)
  local args = getArgs(frame)
  local out = {}
  -- Valid media types
  local mtypes = {
    anime = true, manga = true, novel = true,
    game = true, movie = true, ['фильм канон'] = true
  }
  -- Divides users into actionable items (even if there's only one)
  local users = args['пользователи'] and mw.text.split( args['пользователи'], ',%s*' )
  -- Checks if any user entries exist, and if they don't, return nil
  if type(users) ~= 'table' then return nil end
  -- For each user
  for _, user in ipairs( users ) do
    -- checks if the entry is real or empty
    if type(user) == 'string' and #user < 1 then break end
    -- separates user name from media
    local prime, media = user:match('([^%~]*)%~?([^%~]*)')
    local link = HF.Link(
      base( prime ):match(stripLinkToTarget),
      base( prime ):match(stripLinkToTarget):match(stripPageTitleToBase)
    )
    link = nameCheck( prime ) == true
      and ("''%s''"):format( link )
      or link

    --- AdditionalInfo
    -- Puppetry handling
    local puppetry = user:match('~~puppet~(.*)$')
    if puppetry then
      puppetry = (' ([[Марионетка]] использует %s)')
        :format(mw.text.listToText(mw.text.split(puppetry, '~')))
    end
    -- "with" handling
    local with = user:match('~~with~([^%~]*)')
      and (' (with %s)'):format(user:match('~~with~([^%~]*)'))
    local AdditionalInfo = puppetry or with or ''

    --- Media
    local Media = ''
    if media
      and mtypes[media:lower()]
      and media:lower() ~= 'movie canon'
    then
      Media = ('<sup> (%s only)</sup>')
        :format( language:ucfirst( media ) )
    elseif media
      and media:lower() == 'movie canon'
      then
        Media = '<sup> (Movie only)</sup>'
    end

    --- Summons
    local cq = mw.smw.ask {
      (HF.Link('Contract::%s')):format( prime:match(stripLinkToTarget) ),
      'mainlabel=main'
    }
    local sl = {}
    if type(cq) == 'table' then
      for _, v in ipairs( cq ) do
        table.insert( sl, v['main'] )
      end
    end
    local Summons = ((#sl > 0)
        and ( pageTitle == 'Summoning Technique' or pageTitle == 'Destruction Bug Host Technique' ))
      and ( ' (%s)' ):format( table.concat( sl, ", " ) )
      or ''

    -- SMW set
    local setmtype = ( media and mtypes[ media:lower() ] )
      and language:ucfirst( media:lower() )
      or 'null'
    mw.smw.set {
      ['User tech'] = prime .. ';' .. setmtype
    }

    table.insert( out, link .. AdditionalInfo .. Summons .. Media )
  end
  return L.makeList( 'bulleted', out )
end
---------------------------------------------------------
-- Exported functions (used in this and other Modules) --
---------------------------------------------------------
-- None.
-------------------------------------------------
-- Output (send it back to whatever called it) --
-------------------------------------------------
return Infobox