Ir para o conteúdo

Módulo:Lista de episódio

De Wiki TokuDrive
Revisão de 05h44min de 6 de setembro de 2026 por Tavoraadmin (discussão | contribs) (Importando predefinição/módulo da Wikipédia em português para manter layout)
(dif) ← Edição anterior | Revisão atual (dif) | Versão posterior → (dif)

local p = {}

-- This module requires the use of the following modules: local colorContrastModule = require('Module:Color contrast') local htmlColor = mw.loadData('Module:Color contrast/colors') local langModule = require("Module:Lang") local mathModule = require('Module:Math') local tableEmptyCellModule = require('Module:Table empty cell') local yesNoModule = require('Module:Yesno')

-- mw.html object for the generated row. local row

-- Variable that will decide the colspan= of the Short Summary cell. local nonNilParams = 0

-- Variable that will keep track if a TBA value was entered. local cellValueTBA = false

-- Variable that handles the assigned tracking categories. local trackingCategories = ""

-- List of tracking categories. local trackingCategoryList = {

   ["air_dates"] = "",
   ["alt_air_dates"] = "",
   ["faulty_line_colors"] = "",
   ["non_compliant_line_colors"] = "",
   ["default_line_colors"] = "",
   ["row_deviations"] = "",
   ["invalid_top_colors"] = "",
   ["tba_values"] = "",
   ["nonmatching_numbered_parameters"] = "",
   ["raw_unformatted_storyteleplay"] = ""

}

-- Parameter name variations mapping local parameterVariations = {

   ['NoEpisódio'] = 'NúmeroEpisódio',
   ['NoEpisódio2'] = 'NúmeroEpisódio2',
   ['DataExibição'] = 'DataTransmissãoOriginal',
   ['DataAlt'] = 'DataAlter',
   ['ProdCod'] = 'CódigoProd',
   ['Resumo'] = 'Sinopse'

}

-- List of parameter names in this order. local cellNameList = {

   'NúmeroEpisódio',
   'NúmeroEpisódio2',
   'Título',
   'Aux1',
   'Dirigido',
   'Escrito',
   'Aux2',
   'Aux3',
   'DataTransmissãoOriginal',
   'DataAlter',
   'Convidados',
   'ConvidadosMusicais',
   'CódigoProd',
   'Audiência',
   'Aux4'

}

-- List of pairs which cannot be used together local excludeList = {

   ['Convidados'] = 'Aux1',
   ['ConvidadosMusicais'] = 'Aux2'

}

-- List of cells that have parameter groups local parameterGroupCells = {} local firstParameterGroupCell local parameterGroupCellsAny = false

-- List of title parameter names in this order. local titleList = {

   'Título',
   'RTítulo',
   'TítuloAlter',
   'RTítuloAlter',
   'TítuloNativo',
   'TítuloTranslit',
   'TítuloBR', 
   'RTítuloBR',
   'TítuloPT', 
   'RTítuloPT'

}

-- Function to handle parameter name variations local function getParamValue(args, paramName)

   -- First check for the standard name
   if args[paramName] ~= nil then
       return args[paramName]
   end
   
   -- Check all variations
   for variation, standard in pairs(parameterVariations) do
       if standard == paramName and args[variation] ~= nil then
           return args[variation]
       end
   end
   
   return nil

end

-- Local function which is used to retrieve the episode number or production code number, -- without any additional text. local function idTrim(val, search)

   local valFind = string.find(val, search)
   if (valFind == nil) then
       return val
   else
       return string.sub(val, 0, valFind-1)
   end

end

-- Local function which is used to validate that a parameter has an actual value. local function hasValue(param)

   if (param ~= nil and param ~= "") then
       return true
   else
       return false
   end

end

-- Local function which is used to create a table data cell. local function createTableData(text, rowSpan, textAlign)

   if (rowSpan ~= nil and tonumber(rowSpan) > 1) then
       row:tag('td')
           :attr('rowspan', rowSpan)
           :wikitext(text)
   else
       row:tag('td')
           :css('text-align', textAlign)
           :wikitext(text)
   end

end

-- Local function which is used to add a tracking category to the page. local function addTrackingCategory(category)

   trackingCategories = trackingCategories .. category

end

-- Local function which is used to create a Short Summary row. local function createShortSummaryRow(args, lineColor)

   local shortSummaryText = getParamValue(args, 'Sinopse') or 
   if (shortSummaryText:match('^[*:;#]') or shortSummaryText:match('^{|')) then
       shortSummaryText = '\n' .. shortSummaryText
   end
   if (shortSummaryText:match('\n[*:;#]')) then
       shortSummaryText = shortSummaryText .. '\n'
   end
   
   local shortSummaryDiv = mw.html.create('div')
               :addClass('shortSummaryText')
               :css('max-width', '90vw')
               :css('position', 'sticky')
               :css('left', '0.2em')
               :newline()
               :wikitext(shortSummaryText)
   local shortSummaryCell = mw.html.create('td')
               :addClass('description')
               :css('border-bottom', 'solid 3px ' .. lineColor)
               :attr('colspan', nonNilParams)
               :newline()
               :node(shortSummaryDiv)
   return mw.html.create('tr')
                   :addClass('expand-child')
                   :node(shortSummaryCell)

end

-- Local function which is used to add tracking categories for Top Color issues. local function addTopColorTrackingCategories(args)

   local topColor = getParamValue(args, 'CorTopo')
   if (hasValue(topColor)) then
       addTrackingCategory(trackingCategoryList["row_deviations"])
       local textContrastRatio = colorContrastModule._ratio{topColor, 'black', ['error'] = 0}
       local linkContrastRatio = colorContrastModule._ratio{topColor, '#0B0080', ['error'] = 0}
       local visitedLinkContrastRatio = colorContrastModule._ratio{topColor, '#0645AD', ['error'] = 0}
       if (textContrastRatio < 7 or linkContrastRatio < 7 or visitedLinkContrastRatio < 7) then
           addTrackingCategory(trackingCategoryList["invalid_top_colors"])
       end
   end

end

-- Local function which is used to add tracking categories for Line Color issues. local function addLineColorTrackingCategories(args)

   local lineColor = getParamValue(args, 'CorLinha')
   if (hasValue(lineColor)) then
       local blackContrastRatio = colorContrastModule._ratio{lineColor, 'black', ['error'] = 0}
       local whiteContrastRatio = colorContrastModule._ratio{'white', lineColor, ['error'] = 0}
       if (colorContrastModule._lum(lineColor) == ) then
           addTrackingCategory(trackingCategoryList["faulty_line_colors"])
       elseif (blackContrastRatio < 7 and whiteContrastRatio < 7) then
           addTrackingCategory(trackingCategoryList["non_compliant_line_colors"])
       end
   else
       addTrackingCategory(trackingCategoryList["default_line_colors"])
   end

end

-- Local function which is used to set the text of an empty cell -- with either "TBD" or "N/A". local function setTBDStatus(args, awaitingText, expiredText, weeks)

   local originalDate = getParamValue(args, 'DataTransmissãoOriginal')
   if originalDate == nil or originalDate ==  then
       return tableEmptyCellModule._main({alt_text = awaitingText})
   end
   if string.match(originalDate, '^Não exibido') then
       return tableEmptyCellModule._main({alt_text = "N/A"})
   end    
   local month, day, year = originalDate:gsub(" ", " "):match("(%a+) (%d+), (%d+)")
   if (month == nil) then
       day, month, year = originalDate:gsub(" ", " "):match("(%d+) (%a+) (%d+)")
   end
   if (day == nil) then
       return tableEmptyCellModule._main({alt_text = "ASD"})
   else
       local monthList = {
           ['janeiro'] = 1,
           ['fevereiro'] = 2,
           ['março'] = 3,
           ['abril'] = 4,
           ['maio'] = 5,
           ['junho'] = 6,
           ['julho'] = 7,
           ['agosto'] = 8,
           ['setembro'] = 9,
           ['outubro'] = 10,
           ['novembro'] = 11,
           ['dezembro'] = 12
       }
       
       if not monthList[month] then
           error('Mês invalido ' .. month)
       end
       local seconds = os.time() - os.time({year = year, month = monthList[month], day = day, hour = 0, min = 0, sec = 0})
       if (seconds >= 60 * 60 * 24 * 7 * weeks) then
           return tableEmptyCellModule._main({alt_text = expiredText})
       else
           return tableEmptyCellModule._main({alt_text = awaitingText})
       end
   end

end

-- Local function which is used to create an empty cell. local function createEmptyCell(args, v, unsetParameterGroup)

   local result
   if (unsetParameterGroup) then
       result = tableEmptyCellModule._main({alt_text = "N/A"}) or "N/A"
   elseif (v == 'Audiência' and hasValue(getParamValue(args, 'DataTransmissãoOriginal'))) then
       result = setTBDStatus(args, "ASD", "N/A", 4) or "ASD"
   elseif (v == 'Dirigido' or v == 'Escrito') then
       result = setTBDStatus(args, "ASA", "Desconhecido", 4) or "ASA"
   else
       result = tableEmptyCellModule._main({}) or ""
   end
   args[v] = result
   return result

end

-- Helper function to convert English templates to Portuguese local function convertEnglishDates(dateStr)

   if dateStr and string.find(dateStr, 'Start date') then
       local y, m, d = dateStr:match('Start date.-(%d%d%d%d).-(%d%d?).-(%d%d?)')
       if y then
           return 'Erro de expressão: Caractere de pontuação “'” não reconhecido. de O primeiro parâmetro é necessário, mas foi fornecido incorretamente! de '..y..' ('..y..'-'..(m or )..'-'..(d or )..')'
       end
   end
   return dateStr

end

-- Updated date checking function local function checkUsageOfDateTemplates(args, v, onInitialPage, title)

   if v == 'DataTransmissãoOriginal' then
       local dateValue = getParamValue(args, v)
       dateValue = convertEnglishDates(dateValue)
       args[v] = dateValue
       
       if dateValue ~=  
          and string.match(dateValue, '%d%d%d%d')
          and not string.match(dateValue, '^Não exibido')
          and onInitialPage
          and title.namespace == 0 then
           
           if not string.find(dateValue, 'data de início') and
              not string.find(dateValue, 'Start date') then
               
               if string.match(dateValue, '^%d%d?/%d%d?/%d%d%d%d$') or
                  string.match(dateValue, '^%d+ de [jJ]aneiro|[fF]evereiro|[mM]arço|[aA]bril|[mM]aio|[jJ]unho|[jJ]ulho|[aA]gosto|[sS]etembro|[oO]utubro|[nN]ovembro|[dD]ezembro de %d%d%d%d$') then
                   addTrackingCategory(trackingCategoryList["air_dates"])
               end
           end
       end
   end
   if v == 'DataAlter' then
       local altDateValue = getParamValue(args, v)
       if altDateValue ~=  then
           altDateValue = convertEnglishDates(altDateValue)
           args[v] = altDateValue
           if string.find(altDateValue, 'dtstart') and onInitialPage and title.namespace == 0 then
               addTrackingCategory(trackingCategoryList["alt_air_dates"])
           end
       end
   end

end

-- Local function which is used to create a Production Code cell. local function createProductionCodeCell(args, v, numberOfParameterGroups)

   local thisRowspan
   if (not parameterGroupCells[v] and parameterGroupCellsAny) then
       thisRowspan = numberOfParameterGroups
   else
       thisRowspan = 1
   end
   
   local prodCode = getParamValue(args, 'CódigoProd')
   if (hasValue(prodCode) and string.find(prodCode, 'ASA') == nil) then
       row:tag('td')
           :attr('id', 'pc' .. idTrim(idTrim(prodCode, ' ----'), '<'))
           :attr('rowspan', thisRowspan)
           :css('text-align', 'center')
           :wikitext(prodCode)
   elseif (prodCode ==  or string.find(prodCode or , 'ASA') ~= nil) then
       createEmptyCell(args, v, false)
       createTableData(prodCode, thisRowspan, "center")
   end
   nonNilParams = nonNilParams + 1

end

local function extractDataFromNumberedSerialArgs(args, i, numberOfParameterGroups, title)

   for _, v in ipairs(cellNameList) do
       local parameter = v
       local numberedParameter = v .. "_" .. i
       local excludeParameter = excludeList[parameter] or 'NULL' .. parameter
       local excludeNumberParameter = (excludeList[numberedParameter] or 'NULL' .. parameter) .. "_" .. i
       if (not hasValue(args[numberedParameter]) and not hasValue(args[excludeNumberParameter])
           and hasValue(parameterGroupCells[parameter]) and not hasValue(args[excludeParameter])) then
           if (v ~= 'CódigoProd') then
               createEmptyCell(args, parameter, true)
           else
               args[parameter] = 
           end
           if (title.namespace == 0) then
               addTrackingCategory(trackingCategoryList["nonmatching_numbered_parameters"])
           end
       elseif (hasValue(args[numberedParameter]) and not  hasValue(args[excludeNumberParameter])) then
           args[parameter] = args[numberedParameter]
       end
   end
   for _, v in ipairs(titleList) do
       local numberedParameter = v .. "_" .. i
       if hasValue(args[numberedParameter]) then
           args[v] = args[numberedParameter]
       end
   end
   return args

end

local function createTitleText(args)

   local titleString = 
   local isCellPresent = false
   local useSecondLine = false
   local lineBreakUsed = false
   -- Safely get title with nil check
   local title = getParamValue(args, 'Título') or ""
   
   local hasRTitle = args['RTítulo'] and args['RTítulo'] ~= ""
   
   if title ~= "" then
       titleString = '"' .. title .. '"'
       useSecondLine = true
       isCellPresent = true
   elseif not hasRTitle then
       -- If empty, shows "TBA"
       titleString = tableEmptyCellModule._main({alt_text = "ASA"}) or "ASA"
       useSecondLine = true
       isCellPresent = true
   end
   -- Safely handle RTítulo with nil check
   if args['RTítulo'] and args['RTítulo'] ~= "" then
       titleString = titleString .. (args['RTítulo'] or "")
       useSecondLine = true
       isCellPresent = true
   end
   -- Safely handle alternate titles
   local altTitle = args['TítuloAlter'] or args['TítuloTranslit'] or ""
   if altTitle ~= "" then
       isCellPresent = true
       if useSecondLine then
           titleString = titleString .. "
" lineBreakUsed = true end
       if args['TítuloAlter'] and args['TítuloAlter'] ~= "" then
           titleString = titleString .. '"' .. args['TítuloAlter'] .. '"'
       elseif args['TítuloTranslit'] and args['TítuloTranslit'] ~= "" then
           titleString = titleString .. 'Transliteração: "' .. (args['TítuloTranslit'] or "") .. '"'
       end
   end
   -- Safely handle native title
   if args['TítuloNativo'] and args['TítuloNativo'] ~= "" then
       isCellPresent = true
       if useSecondLine and not lineBreakUsed then
           titleString = titleString .. "
" end
       if args['CodLangTítuloNativo'] and args['CodLangTítuloNativo'] ~= "" then
           local frame = mw.getCurrentFrame()
           titleString = titleString .. ' (' .. (frame:expandTemplate{title='langx', args={ args['CodLangTítuloNativo'] or "" }} or "") ..
                        ''..(args['TítuloNativo'] or "").. ')'
       else
           titleString = titleString .. " (" .. (args['TítuloNativo'] or "") .. ")"
       end
   end
   -- Safely handle alternate title reference
   if args['RTítuloAlter'] and args['RTítuloAlter'] ~= "" then
       isCellPresent = true
       if useSecondLine and not lineBreakUsed then
           titleString = titleString .. "
" end titleString = titleString .. (args['RTítuloAlter'] or "") end
   -- Safely handle Portuguese variants
   local titleBR = args['TítuloBR'] or ""
   local titlePT = args['TítuloPT'] or ""
   if titleBR ~= "" or titlePT ~= "" then
       titleString = titleString .. "
" if titleBR ~= "" and titlePT ~= "" and titleBR == titlePT then titleString = titleString .. '"' .. titleBR .. '"' if args['RTítuloBR'] and args['RTítuloBR'] ~= "" then titleString = titleString .. args['RTítuloBR'] end if args['RTítuloPT'] and args['RTítuloPT'] ~= "" then titleString = titleString .. args['RTítuloPT'] end titleString = titleString .. ' (BR/PT)' else if titleBR ~= "" then titleString = titleString .. '"' .. titleBR .. '"' if args['RTítuloBR'] and args['RTítuloBR'] ~= "" then titleString = titleString .. args['RTítuloBR'] end titleString = titleString .. ' (BR)' end if titlePT ~= "" and titlePT ~= titleBR then if titleBR ~= "" then titleString = titleString .. "
" end titleString = titleString .. '"' .. titlePT .. '"' if args['RTítuloPT'] and args['RTítuloPT'] ~= "" then titleString = titleString .. args['RTítuloPT'] end titleString = titleString .. ' (PT)' end end end
   return titleString ~= "" and titleString or nil, isCellPresent

end

local function extractDataFromNumberedTitleArgs(args, i)

   local nextGroupValid = false
   for _, v in ipairs(titleList) do
       local parameter = v
       local numberedParameter = v .. "_" .. i
       args[parameter] = args[numberedParameter]
       if (nextGroupValid == false and hasValue(args[numberedParameter])) then
           nextGroupValid = true
       end
   end
   return args, nextGroupValid

end

local function createTitleCell(args, numberOfParameterGroups, currentRow, isSerial)

   if (isSerial and getParamValue(args, 'Título') and currentRow > 1) then
       return nil
   end
   
   local titleText, isCellPresent = createTitleText(args)
   if not isCellPresent then
       return nil
   end
   -- Ensure we always have valid text to display
   titleText = titleText or tableEmptyCellModule._main({}) or ""
   local textAlign = "left"
   if (nonNilParams == 0) then
       if (isSerial) then
           row:tag('th')
               :addClass('summary')
               :attr('scope', 'row')
               :attr('rowspan', numberOfParameterGroups)
               :css('text-align', textAlign)
               :wikitext(titleText)
       else
           row:tag('th')
               :addClass('summary')
               :attr('scope', 'row')
               :css('text-align', textAlign)
               :wikitext(titleText)
       end
   else
       if (isSerial) then
           row:tag('td')
               :addClass('summary')
               :attr('rowspan', numberOfParameterGroups)
               :css('text-align', textAlign)
               :wikitext(titleText)
       else
           row:tag('td')
               :addClass('summary')
               :css('text-align', textAlign)
               :wikitext(titleText)
       end
   end
   nonNilParams = nonNilParams + 1

end

local function createCells(args, isSerial, currentRow, onInitialPage, title, numberOfParameterGroups)

   for k, v in ipairs(cellNameList) do
       -- Get value using parameter-safe method
       local paramValue = getParamValue(args, v) or args[v]
       
       if v == 'DataTransmissãoOriginal' or v == 'DataAlter' then
           -- Special handling for dates
           paramValue = getParamValue(args, v)
           if paramValue then
               checkUsageOfDateTemplates(args, v, onInitialPage, title)
           end
       end
       if (v == 'CódigoProd') then
           if (currentRow == 1 or (currentRow > 1 and parameterGroupCells[v])) then
               createProductionCodeCell(args, v, numberOfParameterGroups)
           end
       elseif (v == 'Título') then
           if (currentRow == 1 or (currentRow > 1 and parameterGroupCells[v])) then
               local isSerial = not args['Título_2'] and true or false
               createTitleCell(args, numberOfParameterGroups, currentRow, isSerial)
           end
       elseif excludeList[v] and args[excludeList[v]] then
           -- Ignore this parameter set as multiple conflicting parameters were used
       elseif (args[v] and (v ~= 'NúmeroEpisódio' and v ~= 'NúmeroEpisódio2')) then
           if (args[v] == ) then
               createEmptyCell(args, v, false)
           elseif (v == 'Escrito' and title.namespace == 0) then
               if ((string.find(args[v], "História") ~= nil or string.find(args[v], "Teleplay") ~= nil or string.find(args[v], "Roteiro") ~= nil) and string.find(args[v], "8202") == nil) then
                   addTrackingCategory(trackingCategoryList["raw_unformatted_storyteleplay"])
               end
           end
           local textAlign = "center"
           if (v == 'Aux1' and isSerial) then
               textAlign = "left"
           end
           local thisRowspan
           if (not parameterGroupCells[v] and parameterGroupCellsAny) then
               thisRowspan = numberOfParameterGroups
           else
               thisRowspan = 1
           end
           if (currentRow == 1 or (currentRow > 1 and parameterGroupCells[v])) then
               createTableData(args[v], thisRowspan, textAlign)
           end
           nonNilParams = nonNilParams + 1
           checkUsageOfDateTemplates(args, v, onInitialPage, title)
       end
       
       if args[v] and (args[v] == "ASA" or string.find(args[v], "tv%-ASA")) then
           cellValueTBA = true
       end
   end

end

local function createTableRowEpisodeNumberHeader(episodeNumber, numberOfParameterGroups, episodeText, separateEpisodeNumbers)

       local epID = string.match(episodeNumber, "^%w+")
       row:tag('th')
           :attr('scope', 'row')
           :attr('rowspan', not separateEpisodeNumbers and numberOfParameterGroups or 1)
           :attr('id', epID and 'ep' .. epID or )
           :css('text-align', 'center')
           :wikitext(episodeText)

end

local function getEpisodeText(episodeNumber)

   if (episodeNumber == ) then
       return tableEmptyCellModule._main({})
   else
       local episodeNumber1
       local episodeNumber2
       local divider

episodeNumber = episodeNumber:gsub('%s*<br%s*/?%s*>%s*', '


') if (episodeNumber:match('^(%w+)%s*


%s*(%w+)$')) then episodeNumber1, episodeNumber2 = episodeNumber:match('^(%w+)%s*


%s*(%w+)$') divider = "


" elseif (episodeNumber:match('^(%w+)%s*


.-


%s*(%w+)$')) then episodeNumber1, episodeNumber2 = episodeNumber:match('^(%w+)%s*


.-


%s*(%w+)$') divider = "


"

       elseif (mw.ustring.match(episodeNumber, '^(%w+)%s*[%s%-–/&]%s*(%w+)$')) then
           episodeNumber1, episodeNumber2 = mw.ustring.match(episodeNumber, '^(%w+)%s*[%s%-–/&]%s*(%w+)$')
           divider = "–"
       else
           episodeNumber1, episodeNumber2 = mw.ustring.match(episodeNumber, '^(%w+)%s*[%s%-–/&].-[%s%-–/&]%s*(%w+)$')
           divider = "–"
       end
       if (not episodeNumber1) then
           return episodeNumber
       elseif (not episodeNumber2) then
           return string.match(episodeNumber, '%w+')
       else
           return episodeNumber1 .. divider .. episodeNumber2
       end
   end

end

local function _createEpisodeNumberCellSecondary(episodeValue, numberOfParameterGroups, separateEpisodeNumbers)

   if (episodeValue) then
       local episodeText = getEpisodeText(episodeValue)
       if (nonNilParams == 0) then
           createTableRowEpisodeNumberHeader(episodeValue, numberOfParameterGroups, episodeText, separateEpisodeNumbers)
       else
           createTableData(episodeText, not separateEpisodeNumbers and numberOfParameterGroups or 1, "center")
       end
       nonNilParams = nonNilParams + 1
   end

end

-- Local function which is used to create EpisodeNumber2 and EpisodeNumber3 cells. local function _createEpisodeNumberCellSecondary(episodeValue, numberOfParameterGroups, separateEpisodeNumbers) if (episodeValue) then local episodeText = getEpisodeText(episodeValue)

if (nonNilParams == 0) then createTableRowEpisodeNumberHeader(episodeValue, numberOfParameterGroups, episodeText, separateEpisodeNumbers) else createTableData(episodeText, not separateEpisodeNumbers and numberOfParameterGroups or 1, "center") end

nonNilParams = nonNilParams + 1 end end

-- Local function which is used to create secondary episode number cells. local function createEpisodeNumberCellSecondary(args, numberOfParameterGroups, separateEpisodeNumbers) _createEpisodeNumberCellSecondary(args['NúmeroEpisódio2'], numberOfParameterGroups, separateEpisodeNumbers) _createEpisodeNumberCellSecondary(args['NúmeroEpisódio3'], numberOfParameterGroups, separateEpisodeNumbers) end

-- Local function which is used to create an EpisodeNumber cell. local function createEpisodeNumberCell(args, numberOfParameterGroups, separateEpisodeNumbers) if (args['NúmeroEpisódio']) then local episodeText = getEpisodeText(args['NúmeroEpisódio']) createTableRowEpisodeNumberHeader(args['NúmeroEpisódio'], numberOfParameterGroups, episodeText, separateEpisodeNumbers) nonNilParams = nonNilParams + 1 end end

-- Local function which is used to create a single row of cells. -- This is the standard function called. local function createSingleRowCells(args, numberOfParameterGroups, multiTitleListEnabled, onInitialPage, title) createEpisodeNumberCell(args, 1, false) createEpisodeNumberCellSecondary(args, 1, false) createCells(args, false, 1, onInitialPage, title, numberOfParameterGroups) end

-- Local function which is used to create a multiple row of cells. -- This function is called when part of the row is rowspaned. local function createMultiRowCells(args, numberOfParameterGroups, onInitialPage, title, topColor) local EpisodeNumberSplit = (args['NúmeroEpisódio_1'] and true or false)

for i = 1, numberOfParameterGroups do args = extractDataFromNumberedSerialArgs(args, i, numberOfParameterGroups, title)

if (EpisodeNumberSplit or (not EpisodeNumberSplit and i == 1)) then createEpisodeNumberCell(args, numberOfParameterGroups, EpisodeNumberSplit) createEpisodeNumberCellSecondary(args, numberOfParameterGroups, EpisodeNumberSplit) end

createCells(args, true, i, onInitialPage, title, numberOfParameterGroups) if (i ~= numberOfParameterGroups) then local textColor = '#333' if topColor == 'inherit' then textColor = 'inherit' end

row = row:done() :tag('tr') :addClass('vevent') :addClass('module-episode-list-row') :css('text-align', 'center') :css('background', topColor) :css('color', textColor) end end end

local function getnumberOfParameterGroups(args)

   for k, v in ipairs(cellNameList) do
       local numberedParameter = v .. "_" .. 1
       if (args[numberedParameter]) then
           parameterGroupCells[v] = true
           parameterGroupCellsAny = true
           if not firstParameterGroupCell then
               firstParameterGroupCell = k
           end
       end
   end
   if (hasValue(args.NumPartes)) then
       return args.NumPartes, true
   else
       return 1, false
   end

end

local function getTopColor(args, rowColorEnabled, onInitialPage)

   local episodeNumber = mathModule._cleanNumber(getParamValue(args, 'NúmeroEpisódio')) or 1
   local topColor = getParamValue(args, 'CorTopo')
   if (topColor) then
       if (string.find(topColor, "#")) then
           return topColor
       else
           return '#' .. topColor
       end
   else
       return 'inherit'
   end

end

local function isRowColorEnabled(args)

   local rowColorEnabled = yesNoModule(getParamValue(args, 'CorNaLinha'), false)
   if (args.CorNaLinha and string.lower(args.CorNaLinha) == 'sim') then
       rowColorEnabled = true
   end
   return rowColorEnabled

end

local function getLineColor(args)

   local lineColor = getParamValue(args, 'CorLinha') or 'CCCCFF'
   if (htmlColor[lineColor] == nil) then
       lineColor = '#' .. (mw.ustring.match(lineColor, '^[%s#]*([a-fA-F0-9]*)[%s]*$') or )
       if (lineColor == '#') then
           lineColor = '#CCCCFF'
       end
   end
   return lineColor

end

local function isOnTargetPage(args, sublist, pageTitle, initiallistTitle)

   if not sublist or initiallistTitle ==  then
       return false
   end
   
   local normalize = function(title)
       return mw.ustring.lower(mw.text.trim(title or ))
   end
   
   return normalize(pageTitle) == normalize(initiallistTitle)

end

local function _main(args, sublist)

   local title = mw.title.getCurrentTitle()
   local pageTitle = title.text
   local initiallistTitle = args['1'] or 
   local onTargetPage = isOnTargetPage(args, sublist, pageTitle, initiallistTitle)
   local sinopseValue = getParamValue(args, 'Sinopse')
   if onTargetPage or not hasValue(sinopseValue) then
       args.Sinopse = nil
   else
       args.Sinopse = sinopseValue
   end
   local lineColor = getLineColor(args)
   local rowColorEnabled = isRowColorEnabled(args)
   local topColor = getTopColor(args, rowColorEnabled, not onTargetPage)
   local root = mw.html.create()
   local textColor = '#333'
   if topColor == 'inherit' then
       textColor = 'inherit'
   end
   row = root:tag('tr')
               :addClass('vevent')
               :addClass('module-episode-list-row')
               :css('text-align', 'center')
               :css('background', topColor)
               :css('color', textColor)
   local numberOfParameterGroups, multiTitleListEnabled = getnumberOfParameterGroups(args)
   if multiTitleListEnabled then
       createMultiRowCells(args, numberOfParameterGroups, not onTargetPage, title, topColor)
   else
       createSingleRowCells(args, numberOfParameterGroups, multiTitleListEnabled, not onTargetPage, title)
   end
   if not onTargetPage and title.namespace == 0 then
       addLineColorTrackingCategories(args)
       addTopColorTrackingCategories(args)
       
       if cellValueTBA == true then
           addTrackingCategory(trackingCategoryList["tba_values"])
       end
   end
   if not onTargetPage and args.Sinopse then
       local bottomWrapper = createShortSummaryRow(args, lineColor)
       return tostring(root) .. tostring(bottomWrapper) .. trackingCategories
   else
       return tostring(root) .. trackingCategories
   end

end

local function main(frame, sublist)

   local getArgs = require('Module:Arguments').getArgs
   local args
   if (sublist) then
       args = getArgs(frame, {removeBlanks = false, wrappers = 'Predefinição:Lista de episódio/sublista'})
   else
       args = getArgs(frame, {removeBlanks = false, wrappers = 'Predefinição:Lista de episódio'})
   end
   return _main(args, sublist, frame)

end

--[[ Public function which is used to create an Episode row for an Episode Table used for lists of episodes where each table is on a different page, usually placed on individual season articles.

For tables which are all on the same page see p.list().

Parameters: -- |1= — required; The title of the list of episodes article where the Episode Table is transcluded. -- |NúmeroEpisódio= — suggested; The overall episode number in the series. -- |NúmeroEpisódio2= — suggested; The episode number in the season. -- |Título= — suggested; The English title of the episode. -- |RTítulo= — optional; Unformatted parameter that can be used to add a reference after "Título", or can be used as a "raw title" to replace "Título" completely. -- |TítuloAlter= — optional; An alternative title, such as the title of a foreign show's episode in its native language, or a title that was originally changed. -- |TítuloTranslit= — optional; The title of the episode transliteration (Romanization) to Latin characters. -- |RTítuloAlter= — optional; Unformatted parameter that can be used to add a reference after "TítuloAlter", or can be used as a "raw title" to replace "TítuloAlter" completely. -- |TítuloNativo= — optional; The title of the episode in the native language. -- |CodLangTítuloNativo — optional; The language code of the native title language. -- |TítuloBR= — optional; Brazilian Portuguese title.

   -- |RTítuloBR=  		—  optional; Unformatted parameter that can be used to add a reference after "TítuloBR".
   -- |TítuloPT=   		—  optional; European Portuguese title.

-- |RTítuloPT= — optional; Unformatted parameter that can be used to add a reference after "TítuloPT". -- |Aux1= — optional; General purpose parameter. The meaning is specified by the column header. This parameter is also used for Serial episode titles, such as those used in Doctor Who. -- |Dirigido= — optional; Name of the episode's director. May contain links. -- |Escrito= — optional; Primary writer(s) of the episode. May include links. -- |Aux2= — optional; General purpose parameter. The meaning is specified by the column header. -- |Aux3= — optional; General purpose parameter. The meaning is specified by the column header. -- |DataTransmissãoOriginal= — optional; This is the date the episode first aired on TV, or is scheduled to air. -- |DataAlter= — optional; The next notable air date, such as the first air date of an anime in English. -- |Convidados= — optional; List of Guests for talk shows. Cannot be used simultaneously with Aux1. -- |ConvidadosMusicais= — optional; List of MusicalGuests for talk shows. Cannot be used simultaneously with Aux2. -- |CódigoProd= — optional; The production code in the series. When defined, this parameter also creates a link anchor, prefixed by "pc"; for example, List of episodes#pc01. -- |Audiência= — optional; Number of viewers who watched the episode. Should include a reference. -- |Aux4= — optional; General purpose parameter. The meaning is specified by the column header. -- |Sinopse= — optional; A short 100–200 word plot summary of the episode. -- |CorLinha= — optional; Colors the separator line between episode entries. If not defined the color defaults to "#CCCCFF" and the article is placed in Category:Episode list using the default LineColor. Use of "#", or anything but a valid hex code will result in an invalid syntax. -- |CorTopo= — discouraged; Colors the main row of information (that is, not the ShortSummary row). Articles using this parameter are placed in Category:Episode lists with row deviations. -- |CorNaLinha= — optional; Switch parameter that must only be defined when the NúmeroEpisódio= entry is not a regular number (e.g. "12–13" for two episodes described in one table entry). If the first episode number is even, define pass "on". If the first episode number is odd, pass "off". --]] function p.sublista(frame) return main(frame, true) end

--[[ Public function which is used to create an Episode row for an Episode Table used for lists of episodes where all tables are on the same page.

For tables which are on different pages see p.sublista().

For complete parameter documentation, see the documentation at p.sublista(). --]] function p.lista(frame) return main(frame, false) end

return p