Модуль:Television ratings graph/пісочниця
Зовнішній вигляд
![]() | Ця сторінка — пісочниця для модуля Модуль:Television ratings graph (різн.). |

![]() | Зараз цей модуль не має відповідної документації. Якщо вам відомі призначення та засади використання цього модуля, будь ласка, напишіть хоча б коротеньку документацію. |
Документація вище включена з Модуль:Television ratings graph/документація. (ред. | історія) Дописувачі можуть експериментувати на підсторінках пісочниці (ред. | різн.) та тести (створити) цього модуля. Підсторінки цієї сторінки. |
-- This module implements {{Television ratings graph}}.
--------------------------------------------------------------------------------
-- TVRG class
-- The main class.
--------------------------------------------------------------------------------
local TVRG = {}
--Огортає назву серіалу відповідно до письма
function TVRG.formatTitle(text)
local is_Latin = require("Модуль:Unicode data").is_Latin --завантажуємо функцію перевірки на наявність латинського тексту з модуля Unicode data
local formated_text
if is_Latin(text) then --якщо текст латинський
formated_text = "''" .. text .."''" --то огортаємо текст в '' для створення курсиву
else
formated_text = "«" .. text .. "»" --якщо ні, то огортаємо в лапки-ялинки
end
return formated_text --повертаємо відформатований текст
end
-- Convert HEX codes to RGB values
function TVRG.hex2rgb(hex)
hex = hex:gsub('#', '')
if #hex == 3 then
-- #000 format
return tonumber("0x"..hex:sub(1,1)..hex:sub(1,1))/256, tonumber("0x"..hex:sub(2,2)..hex:sub(2,2))/256,
tonumber("0x"..hex:sub(3,3)..hex:sub(3,3))/256
else
-- #000000 format
return tonumber("0x"..hex:sub(1,2))/256, tonumber("0x"..hex:sub(3,4))/256, tonumber("0x"..hex:sub(5,6))/256
end
end
-- Allow usages of {{N/A}} cells
function TVRG.NACell(frame,text)
local cell = mw.html.create('td')
local attrMatch = '([%a-]*)="([^"]*)"'
infoParam = frame:expandTemplate{title='N/A',args={text}}
-- Gather styles of {{N/A}} and assign to node variable
while true do
local a,b = string.match(infoParam,attrMatch)
if a == nil or b == nil then break end
cell:attr(a,b)
infoParam = string.gsub(infoParam,attrMatch,'',1)
end
infoParam = string.gsub(infoParam,'%s*|%s*','',1)
cell:wikitext(infoParam)
return cell
end
-- Create the graph and table
function TVRG.new(frame,args)
args = args or {}
-- Variables
local timeline = ''
local longestseason = -1
local average = args.average and 1 or 0
local season_title = args.season_title or 'Сезон'
local root = mw.html.create('div')
:attr('align', 'center')
-- Create the timeline
-- Number of actual viewer numbers
local numberargs = 0
for k,v in pairs(args) do
if not string.match(k,'[^%d]+') and not string.match(v,'[^%d%.]+') then numberargs = numberargs + 1 end
end
-- Bar width
local barwidth
if numberargs < 20 then barwidth = 8
elseif numberargs >= 20 and numberargs < 50 then barwidth = 7
elseif numberargs >= 50 and numberargs < 80 then barwidth = 6
elseif numberargs >= 80 then barwidth = 5
end
-- Basis parameters
timeline = timeline .. "ImageSize = width:" .. (args.width or 1000) .. " height:" .. (args.height or 300) .. "\n"
timeline = timeline .. "PlotArea = left:50 bottom:70 top:20 right:50\n"
timeline = timeline .. "AlignBars = justify\n"
timeline = timeline .. "Colors =\n"
timeline = timeline .. " id:a value:gray(0.7)\n"
-- Determine number of seasons
local num_seasons = -1
for k,v in pairs(args) do
local thisseason = tonumber(string.sub(k,6))
if string.sub(k,1,5) == 'color' and thisseason > num_seasons then
num_seasons = thisseason
end
end
if num_seasons < 1 then
num_seasons = 1
end
-- Colour and legend variables
local season = 1
for season = 1,num_seasons do
args['color' .. season] = args['color' .. season] or '#006600' -- реалізація як в англ. вікі, щоб коли кольор не задано виводився стандартний колір в графіку і таблиці
local r,g,b = TVRG.hex2rgb(args['color' .. season])
timeline = timeline .. " id:season" .. season .. " value:rgb("..r..","..g..","..b..") legend:" ..
string.gsub(string.gsub((args["legend" .. season] or season_title .. " " .. season), ' ', '_'), "''(.-)''", '%1') .. "\n"
season = season + 1
end
-- Determine maximum viewer figure
local maxviewers = -1
local multiple = 'у мільйонах'
for k,v in pairs(args) do
local num = tonumber(v)
if tonumber(k) ~= nil and num ~= nil and num > maxviewers then
maxviewers = num
end
end
if maxviewers <= 1.5 then
multiple = 'тисячі'
maxviewers = maxviewers*1000
for k, v in pairs(args) do
local num = tonumber(v)
if tonumber(k) ~= nil and num ~= nil then args[k] = tostring(num*1000) end
end
end
-- Further parameters, with rounded-up viewer figures as maximum period
timeline = timeline .. "DateFormat = x.y\n"
timeline = timeline .. "Period = from:0 till:" .. math.ceil(maxviewers) .. "\n"
timeline = timeline .. "TimeAxis = orientation:vertical\n"
timeline = timeline .. "ScaleMajor = gridcolor:a increment:" .. 10^math.ceil(math.log10(maxviewers)-math.log10(15)) .. " start:0\n"
timeline = timeline .. "Legend = orientation:horizontal\n"
-- Interval parameter set to prevent overlapping bars
local bar = 1
if args.intervals then
timeline = timeline .. "BarData =\n"
for k,v in pairs(args) do
if string.lower(v) == 'n/a' or mw.ustring.lower(v) == 'н/д' then v = '' end
if tonumber(k) ~= nil and (tonumber(v) ~= nil or v == '') and (average == 0 or (average == 1 and args[k+1] ~= '-' and args[k+1] ~= nil)) then
timeline = timeline .. " bar:"..bar.." text:"..((bar == 1 or bar % args.intervals == 0) and bar or ' ').."\n"
bar = bar + 1
end
end
end
-- Plot data
timeline = timeline .. "PlotData =\n"
timeline = timeline .. " width:" .. (args.bar_width or barwidth) .. "\n"
timeline = timeline .. " mark:(line,black)\n"
-- Add bars to timeline, one per viewer figure
local bar = 1
local season = 0
local thisseason = 0
for k,v in pairs(args) do
if string.lower(v) == 'n/a' or mw.ustring.lower(v) == 'н/д' then v = '' end
if tonumber(k) ~= nil then
if v == '-' then
-- Hyphen means new season, so change season colour
season = season + 1
-- Determine highest number of episodes in a season
if thisseason > longestseason then
longestseason = thisseason
end
thisseason = 0
elseif average == 0 or (average == 1 and args[k+1] ~= '-' and args[k+1] ~= nil) then
-- Include black bar to act as border
timeline = timeline .. " color:black\n"
timeline = timeline .. " bar:" .. bar .. " width:" .. ((args.bar_width or barwidth)+2) .. " from:start till:" .. (v ~= '' and v or 'start') .. "\n"
-- Include bar for viewer figure, do not include if averages are included and the next parameter is a new season marker
timeline = timeline .. " color:season" .. season .. "\n"
timeline = timeline .. " bar:" .. bar .. " from:start till:" .. (v ~= '' and v or 'start') .. "\n"
-- Increment tracking variables
thisseason = thisseason + 1
bar = bar + 1
end
end
end
-- Determine highest number of episodes in a season after final season's bars
if thisseason > longestseason then
longestseason = thisseason
end
-- Axis labels
local countryDisplayUS, countryDisplayUK, countryDisplayOther
if args.country ~= nil and args.country ~= '' then
if args.country == "U.S." or args.country == "США" then countryDisplayUS = 'США'
elseif args.country == "U.K." or args.country == "Велика Британія" then countryDisplayUK = 'Велика Британія'
else countryDisplayOther = args.country
end
end
timeline = timeline .. "TextData =\n"
timeline = timeline .. " pos:(" .. ((args.width or 1000)/2-18) .. ",45) textcolor:black fontsize:S text:Серія\n"
timeline = timeline .. " pos:(10," .. ((args.height or 300)-10) .. ") textcolor:black fontsize:S text:" .. "Глядачів" .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) and " у " or "") .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) or "") .. " (" .. multiple .. ")\n"
-- If there's a title, add it with the viewers caption, else just display the viewers caption by itself
if args.title ~= nil and args.title ~= '' then
root:wikitext("'''" .. TVRG.formatTitle(args.title) .. ": Глядачів " .. (((countryDisplayUS or countryDisplayUK or countryDisplayOther) and ("у " .. (countryDisplayUS or countryDisplayUK or countryDisplayOther) .. " ")) or "") .. "(" .. multiple .. ")'''"):css('margin-top', '1em')
else
root:wikitext("'''Глядачів за серію (" .. multiple .. ")'''"):css('margin-top', '1em')
end
-- Add timeline to div
if args.nograph == nil then
root:node(frame:extensionTag('timeline', timeline))
end
-- Create ratings table
if args.tabla_no == nil then
local rtable = mw.html.create('table')
:addClass('wikitable')
:css('text-align', 'center')
-- Create headers rows
local row = rtable:tag('tr')
row:tag('th'):wikitext(season_title)
:attr('colspan','2')
:attr('rowspan','2')
:css('padding-left', '.8em')
:css('padding-right', '.8em')
row:tag('th')
:attr('colspan',longestseason)
:wikitext("Номер серії")
:css('padding-left', '.8em')
:css('padding-right', '.8em')
-- Average column
if average == 1 then
row:tag('th')
:attr('scope','col')
:attr('rowspan','2')
:wikitext("Середнє значення")
:css('padding-left', '.8em')
:css('padding-right', '.8em')
end
local row = rtable:tag('tr')
for i = 1,longestseason do
row:tag('th')
:attr('scope','col')
:wikitext(i)
end
local season = 1
local thisseason = 0
-- Create table rows and cells
for k,v in pairs(args) do
if tonumber(k) ~= nil then
-- New season marker, or final episode rating
if v == '-' or (average == 1 and args[k+1] == nil) then
if season > 1 then
-- Spanning empty cells with {{N/A}}
if thisseason < longestseason then
row:node(TVRG.NACell(frame,"Н/Д"):attr('colspan',longestseason-thisseason))
end
if average == 1 then
-- If averages included, then set the averages cell with value or TBD
if v ~= '' then
local lang = mw.getContentLanguage();
local converted;
local onezero = '';
local twozeros = '';
converted = lang.formatNum(lang,tonumber(args[k+1] ~= nil and args[k-1] or v))
if string.match(args[k+1] ~= nil and args[k-1] or v,'%.00$') then twozeros = ',00'
elseif string.match(args[k+1] ~= nil and args[k-1] or v,'%.0$') then onezero = ',0'
elseif string.match(args[k+1] ~= nil and args[k-1] or v,'%.%d0$') then onezero = '0' end
row:tag('td'):wikitext(converted .. twozeros .. onezero)
else
row:node(TVRG.NACell(frame,"<span title='англ. To Be Determined — „буде визначено”'>TBD</span>"))
end
thisseason = thisseason + 1
end
end
-- New season marker
if v == '-' then
-- New row with default or preset caption
row = rtable:tag('tr')
row:tag('th')
:css('background-color', args['color' .. season])
:css('width','10px')
row:tag('th')
:attr('scope','row')
:wikitext(args["legend" .. season] and args["legend" .. season] or season)
thisseason = 0
season = season + 1
end
elseif average == 0 or (average == 1 and args[k+1] ~= '-' and args[k+1] ~= nil) then
-- Viewer figures, either as a number or TBD
if string.lower(v) == 'n/a' or mw.ustring.lower(v) == 'н/д' then
row:node(TVRG.NACell(frame,"Н/Д"))
elseif v ~= '' then
local lang = mw.getContentLanguage();
local converted;
local onezero = '';
local twozeros = '';
converted = lang.formatNum(lang,tonumber(v))
if string.match(v,'%.00$') then twozeros = ',00'
elseif string.match(v,'%.0$') then onezero = ',0'
elseif string.match(v,'%.%d0$') then onezero = '0' end
row:tag('td'):wikitext(converted .. twozeros .. onezero)
else
row:node(TVRG.NACell(frame,"<span title='енгл. To Be Determined — „буде визначено”'>TBD</span>"))
end
thisseason = thisseason + 1
end
end
end
-- Finish by checking if final row needs {{N/A}} cells
if average == 0 and thisseason < longestseason then
row:node(TVRG.NACell(frame,"Н/Д"):attr('colspan',longestseason-thisseason))
end
-- Add table to div root and return
root:node(rtable)
end
local span = mw.html.create( 'span' )
:wikitext(frame:expandTemplate{ title='dummy reference', args={ 'посилання?', txtcol = 'red', txtital = 'y' } })
if countryDisplayUS then
root:wikitext("<small>Джерело: [[Рейтинг Нільсена|Nielsen Media Research]]</small>" .. (args.refs or tostring(span)))
else
root:wikitext("<small>Джерело: </small>" .. (args.refs or tostring(span)))
end
return tostring(root)
end
--------------------------------------------------------------------------------
-- Exports
--------------------------------------------------------------------------------
local p = {}
function p.main(frame)
local args = require('Модуль:Arguments').getArgs(frame, {
removeBlanks = false,
wrappers = 'Шаблон:Television ratings graph/пісочниця'
})
return TVRG.new(frame,args)
end
return p