Перейти к содержимому страницы
Переключить меню
Переключить меню настроек
Переключить персональное меню
Вы не представились системе
Ваш IP-адрес будет виден всем, если вы внесёте какие-либо изменения.
Сообщество «Повелителя Тайн»Telegram — новости, дунхуа, игры и мерчDiscord — обсуждение книг и теорий, вопросы по вики

Модуль:Cite

Материал из проекта «Повелитель Тайн Вики»

Data

Format

Usage Template


local helpers = require('Module:Helpers')

local p = {}

-- Tracking category only for real content (not template/module docs that demonstrate errors)
local function errCat()
    local ns = mw.title.getCurrentTitle().namespace
    if ns == 10 or ns == 828 or ns == 2 then return '' end
    return '[[Категория:Страницы с ошибками в сносках]]'
end

p.wechat_colour = "#00EB74"
p.text_clr = "var(--theme-page-text-color)"

local wechat_link_style = string.format("font-variant: small-caps; font-style: italic; color: %s; text-decoration-color: %s;", p.wechat_colour, p.wechat_colour)

function refWrap(frame, name, text)
    if name == nil or name == "" then
        return frame:preprocess(string.format("<ref>%s</ref>", text))
    else
        return frame:preprocess(string.format([[<ref name="%s">%s</ref>]], name, text))
    end
end

function wechatLink(link, title, additional_text)
    return string.format(
        [=[[[%s|<span style="%s">%s</span>%s]]]=], 
        link, 
        wechat_link_style, 
        title,
        additional_text or ""
    )
end

-- function for {{Cite Book}} template
function p.citeBook(frame)
    local books = mw.loadData('Module:Cite/books')

    local text = frame.args[1] or frame.args["text"]
    local chapter = frame.args[2]
    local addChapterName = frame.args[3] == "name" -- Only add chapter name if the third parameter is "name"
    local book_number = tonumber(text) -- Convert to number for easy comparison
    local use_ref = helpers.strToBool(frame.args["ref"])

    if books[text] == nil then
        return '<span style="color:red;">\'\'\'Ошибка: источник не найден\'\'\'</span>' .. errCat()
    end

    local result = '[[' .. books[text]['link'] .. '|<span style="font-variant: small-caps;">' .. books[text]['text'] .. '</span>]]'
    
    -- Skip appending chapter number if text is "year1346", "rebellious", "littlecase", "convince", "fullmoon", or "cordu"
    if chapter and text ~= "year1346" and text ~= "rebellious" and text ~= "littlecase" and text ~= "convince" and text ~= "fullmoon" and text ~= "cordu" then
        result = result .. ', <span>глава ' .. chapter
        
        -- Check if addChapterName is true and book is 1 or 2
        if addChapterName and (book_number == 1 or book_number == 2) then
            -- Load the appropriate module for the book
            local chaptersModule = mw.loadData('Module:ChaptersList/Book' .. book_number).chapters
            
            -- Fetch chapter name by iterating through the chapter list
            local chapterName = 'Неизвестная глава'
            for _, chap in ipairs(chaptersModule) do
                if chap.number == tonumber(chapter) then
                    chapterName = chap.name
                    break
                end
            end
            
            result = result .. ': ' .. chapterName
        end
        
        result = result .. '</span>'
    end

    if use_ref then
        return refWrap(frame, "book-" .. text .. "." .. tonumber(chapter) or "chap", result)
    else
        return result
    end
end

--  function for {{Cite EP}} template
function p.citeEP(frame)
    local args = frame.args
    local epType = args[1] and mw.text.trim(args[1]) or ""
    local epNum = args[2] and mw.text.trim(args[2]) or ""

    -- Handle {{Cite EP|X}} — if only one parameter, treat it as the episode number
    if epNum == "" or epNum == nil then
        epNum = epType
        epType = ""
    end

    if epNum == "" then
        return "<span style=\"color:red;\">'''Ошибка: не указан номер эпизода'''</span>" .. errCat()
    end

    local seriesText = "<span style=\"font-variant: small-caps;\">[[Donghua|Дунхуа «Повелитель Тайн»]]</span>"
    local episodeTitle

    if epType == "Q" then
        episodeTitle = "Q Theater Episode " .. epNum
    elseif epType == "S" then
        episodeTitle = "Special Episode " .. epNum
    else
        episodeTitle = "Episode " .. epNum
    end

    local episodeLabel = (epType == "Q" and "Театр «Кью», эпизод " .. epNum) or (epType == "S" and "Спецэпизод " .. epNum) or ("Эпизод " .. epNum)
    local main_link = seriesText .. ", [[" .. episodeTitle .. "|" .. episodeLabel .. "]]"
    
    local time_stamp = args["time"]
    if time_stamp ~= "" and time_stamp ~= nil then
        time_stamp = mw.text.trim(time_stamp)
        main_link = main_link .. " " .. time_stamp
    else
        time_stamp = nil
        local hh = tonumber(args["hh"])
        local mm = tonumber(args["mm"])
        local ss = tonumber(args["ss"])
        
        if hh ~= nil and hh > 0 then 
            time_stamp = string.format("%02d:%02d:", hh, mm)
        elseif mm ~= nil then
            time_stamp = string.format("%02d:", mm)
        end
        
        if time_stamp ~= nil then
            -- Seconds can be none-specified and can be replaced with XX.
            if ss == nil or ss < 0 then
                time_stamp = time_stamp .. "XX"
            else
                time_stamp = time_stamp .. string.format("%02d", ss)
            end
            
            main_link = main_link .. " " .. time_stamp
        end
    end

    return main_link
end

--  function for {{Suplink}} template
function p.rubylink(frame)
    -- mw.loadData resuses the same content when called over the same thing, using the same function over the same link is fine.
    local books = mw.loadData('Module:Cite/books')

    local args = frame:getParent().args  -- Fetch arguments passed from the template
    local arg1 = args[1]  -- Book key (e.g., "1", "2", "book1", etc.)
    local arg2 = args[2]  -- Chapter number
    local arg3 = args[3]  -- Optional prefix like "ch"
    local class = args["class"] or "default-class"
    local parens = (args["parens"] == "true" or args["parens"] == "1")

    -- Ensure that books[arg1] exists
    if not books[arg1] then
        return '<span style="color:red;">\'\'\'Ошибка: книга не найдена\'\'\'</span>' .. errCat()
    end

    local popupText = '[[' .. books[arg1].link .. '|' .. books[arg1].text .. ']]'
    if arg2 and arg2 ~= "" then
        popupText = popupText .. ', глава ' .. arg2
    end

    -- Prepare base text (chapter number)
    local baseText = ""
    if arg2 and arg2 ~= "" then
        if arg3 == "ch" then
            baseText = 'гл. ' .. arg2
        else
            baseText = arg2
        end
    end

    -- Determine Book number for label
    local bookLabel = ""
    if arg1 == "1" or arg1 == "book1" then
        bookLabel = "Книга 1"
    elseif arg1 == "2" or arg1 == "book2" then
        bookLabel = "Книга 2"
    else
        bookLabel = books[arg1].text 
    end

    local rubyText = '<ruby><rb>' .. baseText .. '</rb><rt style="font-variant: small-caps;">[[' .. books[arg1].link .. '|' .. bookLabel .. ']]</rt></ruby>'

    -- Wrap everything in styled <span> with class and optional parens
    local spanText
    if parens then
        spanText = '<span style="cursor:help;" class="' .. class .. '">(' .. rubyText .. ')</span>'
    else
        spanText = '<span style="cursor:help;" class="' .. class .. '">' .. rubyText .. '</span>'
    end

    -- Return Popup markup
    return frame:preprocess('{{Popup|text=' .. spanText .. '|popup=' .. popupText .. '|inline=1}}')
end

-- function for {{Cite Wechat}} template
function p.citeWechat(frame)
    local wechat = mw.loadData('Module:Cite/wechat')

    local post_id = frame.args[1]
    local question_num = frame.args[2]
    local additional_qna_text = frame.args[3]
    local qna_ru = { ["Complete Formulas Post"] = "пост с полными формулами", ["Rituals Post"] = "пост о ритуалах", ["Ritual Post"] = "пост о ритуалах" }
    if additional_qna_text then additional_qna_text = qna_ru[mw.text.trim(additional_qna_text)] or additional_qna_text end
    local additional_qna_post_text = frame.args[4]
    local show_id = helpers.strToBool(frame.args["show_id"])

    local post = wechat[post_id]

    -- Invalid ID
    if not post then
        return '<span style="color:red;">\'\'\'Ошибка: источник не найден\'\'\'</span>' .. errCat()
    end

    local has_qna = question_num and question_num ~= ''

    local post_name = post['name'] or tostring(post)
    local post_nick = post['nick'] or post_name
    -- [ru] displayed title (link target stays English)
    local post_nick_ru = post['nick_ru'] or post['name_ru'] or post_nick

    -- These colours directly taken from the WeChat site.
    local colour = "#2AAD67"
    local colour2 = p.wechat_colour

    local pageFull = tostring(mw.title.getCurrentTitle().prefixedText)

    local display_group = "Cuttlefish's WeChat Post"
    local display_group_ru = "Пост Каракатицы в WeChat"
    local link_group = 'Cuttlefish That Loves Diving/Archive'
    local pre_group = ""
    local id_display = string.format(
        [=[ <span class="nomobile" style="color: rgba(140, 140, 140, 0.8);">(id=%s)</span>]=],
        post_id
    )

    -- The do_id_display is necessary, so it doesn't unnecessarily show the id for sample uses.
    local do_id_display = show_id and (pageFull == "Template:Cite Wechat/doc" or pageFull == "Template:Cite Wechat")

    if link_group == pageFull then
        pre_group = string.format('<em><span style="text-decoration: underline; text-decoration-color: %s;">%s</span></em>', colour2, display_group_ru)
    else
        pre_group = wechatLink(link_group, display_group_ru)
    end

    -- No QnA
    if not has_qna then
        return string.format(
            [=[%s: [[Archive:%s: "%s"|«%s»]]]=], 
            pre_group, 
            display_group, 
            post_name, 
            post_nick_ru
        ) .. (do_id_display and id_display or "")
    end

    -- Has QnA
    local str = string.format(
        [=[%s: [[Archive:%s: "%s"#Вопросы и ответы|«%s», вопросы и ответы]]]=], 
        pre_group,
        display_group,
        post_name, 
        post_nick_ru
    )

    str = str .. (do_id_display and id_display or "") .. ", "

    if additional_qna_text and additional_qna_text ~= '' then
        str = str .. additional_qna_text .. ", "
    end

    str = str .. string.format(
        "вопрос %s",
        question_num == "?" and 
            frame:expandTemplate{ title = 'Cite', args = {} } or
            question_num
    )
        
    if additional_qna_post_text and additional_qna_post_text ~= '' then
        str = str ..  ", " .. additional_qna_post_text
    end

    return str
end

-- function for {{Cite DM}} template
function p.citeDm(frame)
    local archivePage  = "Archive:Direct QnA With Cuttflefish"
    local displayTitle = "<i>Прямые вопросы Каракатице</i>"
    local wechatClr   = p.wechat_colour

    local function getQuestionTitle(q_number) 
        local dplRaw = frame:callParserFunction{
            name = "#dpl:",
            args = { title = archivePage, include = "#Question " .. q_number }
        }

        -- I predic that this is super unoptimal. DPL with searching for templates would be better. Once the page does get bigger, then move onto subgages.
        local questionTitle = frame:callParserFunction{
            name = "#invoke",
            args = { "Helpers/WikiText", "getElementByClassInvoker", dplRaw, "title" }
        }

        return questionTitle
    end
 
    local args = frame.args
    local q_number  = args["q"] or args[1]
    local add_text  = args["add"] or args[2]
 
    local after_title = ""
 
    if q_number == "base" then
        after_title = ""
    else
        if q_number == nil or q_number == "" or q_number == "?" then
            after_title = "вопрос " .. frame:preprocess("{{Cite}}")
        else
            questionTitle = getQuestionTitle(q_number)

            if questionTitle == nil or questionTitle == "" then
                after_title = "вопрос " .. q_number
            else
                after_title = string.format([["%s"]], questionTitle)
            end
        end

        after_title = "&#58; " .. after_title
    end

    if add_text ~= nil and add_text ~= "" then
        add_text = ", " .. add_text
    end

    local result = wechatLink(archivePage, displayTitle, after_title) .. add_text
 
    return result
end

return p