Модуль:Wikidata: відмінності між версіями

[перевірена версія][неперевірена версія]
Вилучено вміст Додано вміст
Мітка: Скасування
Немає опису редагування
Рядок 1:
-- settings, may differ from project to project
local fileDefaultSize = '267x400px';
local categoryLinksToEntitiesWithMissingLabel = '[[Категорія:Вікіпедія:Статті з посиланнями на елементи Вікіданих без українського підпису]]';
local categoryLocalValuePresent = '[[Категорія:Вікіпедія:Статті з іншим значенням на Вікіданих]]';
local outputReferences = true;
 
Рядок 676 ⟶ 678:
return ''
else
-- в противном случае формируются параметры для вызова шаблона {{coord}}
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
local globe = options. local globe or= '' -- TODO
local lat = {}
lat['abs'] = math.abs(value['latitude'])
lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
lat['d'] = math.floor(lat['abs'] + eps)
lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
lat['s'] = math.max(0, ((lat['abs'] - lat['d']) * 60 - lat['m']) * 60 + eps)
local lon = {}
lon['abs'] = math.abs(value['longitude'])
lon['ew'] = value['longitude'] >= 0 and 'E' or 'W'
lon['d'] = math.floor(lon['abs'] + eps)
lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
lon['s'] = math.max(0, ((lon['abs'] - lon['d']) * 60 - lon['m']) * 60 + eps)
-- TODO: round seconds with precision
local coord = '{{coord'
if (value['precision'] == nil) or (value['precision'] < 1/60) then -- по умолчанию с точностью до секунды
Рядок 717 ⟶ 718:
end
 
--[[
Функция для оформления объектов-значений с файлами с Викисклада
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatCommonsMedia( value, options )
local image = '[[File:' .. value;
if options[ 'border' ] and options[ 'border' ] ~= '' then
image = image .. ']]|border';
end
 
local captionsize = options['size';]
if options[ 'caption' ] andif options[size 'caption'and ]size ~= '' then
if not string.match( size, 'px$' )
caption = options[ 'caption' ];
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
elseif options[ 'description' ] and options[ 'description' ] ~= '' then
then
caption = options[ 'description' ];
size = size .. 'px'
end
end
if caption ~= '' then
else
caption = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>';
size = fileDefaultSize;
end
end
image = image .. '|' .. size;
 
elseif if options[ 'descriptionalt' ] and options[ 'descriptionalt' ] ~= '' then
if not string.find( value, '[%[%]%{%}]' ) then
image = '[[File:'image .. value'|' .. options['|framelessalt';]
end
if options[ 'border' ] and options[ 'border' ] ~= '' then
image = image .. '|border]]';
end
 
local if sizeoptions['description'] =and options['description'] ~= 'size' ];then
captionimage = image .. '<br>' .. options[ 'description' ];
if size and size ~= '' then
if not string.match( size, 'px$' )
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
then
size = size .. 'px'
end
else
size = fileDefaultSize;
end
image = image .. '|' .. size;
 
if options[ 'alt' ] and options[ 'alt' ] ~= '' then
image = image .. '|' .. options[ 'alt' ];
end
image = image .. ']]';
 
if caption ~= '' then
image = image .. '<br>' .. caption;
end
else
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
end
 
return image
end
 
Рядок 834 ⟶ 819:
 
--[[
Функция для оформления числовых значений
Функція для оформлення числових значень
 
Принимает: объект-значение и таблицу параметров,
Приймає: об'єкт-значення і таблицю параметрів,
Возвращает: строку оформленного текста
Повертає: рядок оформленого тексту
]]
local function formatQuantity( value, options )
-- диапазон значений
-- діапазон значень
local amount = string.gsub( value['amount'], '^%+', '' );
local lang = mw.language.getContentLanguage();
Рядок 857 ⟶ 842:
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
out = out .. '  ±  ' .. formatNum( diff )
end
end
Рядок 931 ⟶ 916:
 
return propertyEntity.datatype;
end
 
local function formatLangRefs( options )
local langRefs = ''
if ( options.qualifiers and options.qualifiers.P407 ) then
for i, qualifier in pairs( options.qualifiers.P407 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'wikibase-entityid' ) then
local langRefEntity = getEntityFromId( qualifier.datavalue.value.id )
if ( langRefEntity and langRefEntity.claims ) then
local langRefCodeClaims = WDS.filter( langRefEntity.claims, 'P218' )
if langRefCodeClaims then
for _, claim in pairs( langRefCodeClaims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'string' ) then
local langRefCode = claim.mainsnak.datavalue.value
langRefs = langRefs .. '&#8203;' .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
end
end
end
end
end
end
end
 
return langRefs
end
 
Рядок 1123 ⟶ 1079:
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="вікідані не мають української назви елемента. Ви можете помогти, вказавши її.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;
end
 
Рядок 1269 ⟶ 1225:
-- обробка за типом значення
local datatype = getPropertyDatatype( propertyId );
if args['value-module']datatype and== args['value-functioncommonsMedia'] and not string.find( value, '[%[%]%{%}]' ) then
local func = getUserFunction( args, 'value' );
value = func( {}, args, value );
elseif datatype == 'commonsMedia' and not string.find( value, '[%[%]%{%}]' ) then
value = formatCommonsMedia( value, args );
elseif datatype == 'math' then
Рядок 1283 ⟶ 1236:
value = moduleUrl.formatUrlSingle( nil, args, value );
end
 
-- если трогать всё-таки можно, добавляем категорию-маркер
if (not args.nocat) and (not frame:callParserFunction( '#property', args.property )=='') then
value = value .. categoryLocalValuePresent;
end
-- оборачиваем в тег для JS-функций
if string.match( propertyId, '^P%d+$' ) then
Рядок 1299 ⟶ 1257:
end
 
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
local callArgs = { propertyId };
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
 
g_frame = frame
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
return formatProperty( args )
end