打开/关闭菜单
274
2927
142
1.6万
星露谷物语扩展百科
打开/关闭外观设置菜单
打开/关闭个人菜单
未登录
未登录用户的IP地址会在进行任意编辑后公开展示。

模块:Gifts

来自星露谷物语扩展百科
[ 创建 | 刷新 ]文档页面
当前模块文档缺失,需要扩充。
local p = {}

local okArgs, Arguments = pcall(require, 'Module:Arguments')
local getArgs = (okArgs and type(Arguments) == 'table' and Arguments.getArgs) or nil

local okData, giftData = pcall(mw.loadData, 'Module:Gifts/Data')

local dialogueOk, dialogueData = pcall(mw.loadData, 'Module:Gifts/Dialogue')

local TIERS = {
    { key = 'love',     zh = '最爱',   portrait = ' Happy',     link = '礼物#最爱的礼物',   label = '普遍最爱的礼物' },
    { key = 'like',     zh = '喜欢',   portrait = ' Happy',     link = '礼物#喜欢的礼物',   label = '普遍喜欢的礼物' },
    { key = 'neutral',  zh = '一般',   portrait = '',           link = nil,                 label = '普遍觉得一般的礼物' },
    { key = 'dislike',  zh = '不喜欢', portrait = ' Concerned', link = '礼物#不喜欢的礼物', label = '普遍不喜欢的礼物' },
    { key = 'hate',     zh = '讨厌',   portrait = ' Concerned', link = '礼物#讨厌的礼物',   label = '普遍讨厌的礼物' },
}

local UNIVERSAL_MODES = {
    ['universal'] = true, ['普遍'] = true, ['通用'] = true, ['普遍礼物'] = true,
}

local iconCache = {}
local sourceCache = {}
local ACTIVE_FRAME = nil  -- 入口捕获,供 fileExists 走 #ifexist(零 expensive)

local function trim(s)
    if type(s) ~= 'string' then return nil end
    return (s:gsub('^%s*(.-)%s*$', '%1'))
end

local function err(msg)
    return '<strong class="error">[Gifts] ' .. msg .. '</strong>'
end

local function escapePipe(s)
    return (s:gsub('|', '{{!}}'))
end

local function fileExists(name)
    if iconCache[name] ~= nil then return iconCache[name] end
    local res = false
    if ACTIVE_FRAME and type(ACTIVE_FRAME.callParserFunction) == 'function' then
        local ok, r = pcall(ACTIVE_FRAME.callParserFunction, ACTIVE_FRAME,
            '#ifexist', { 'File:' .. name, '1', '0' })
        res = (ok and r == '1') or false
    else
        local ok, title = pcall(mw.title.new, 'File:' .. name)
        res = ok and type(title) == 'table' and title.exists or false
    end
    iconCache[name] = res
    return res
end

local function iconFile(item, useFallback)
    local en = item.e .. '.png'
    if not useFallback then return en end
    if fileExists(en) then return en end
    if item.n and item.n ~= item.e and fileExists(item.n .. '.png') then
        return item.n .. '.png'
    end
    return 'Blank icon.png'
end

local function portraitFile(npc, tier, enabled)
    if not enabled or not tier.portrait then return nil end
    local en = npc.english or npc.internal
    local mood = en .. tier.portrait .. '.png'
    if fileExists(mood) then return mood end
    if fileExists(en .. '.png') then return en .. '.png' end
    return nil
end

local function queryGiftsTable(frame, key, field)
    if key == '' or key == nil then return '' end
    local cacheKey = key .. '/' .. field
    if sourceCache[cacheKey] ~= nil then return sourceCache[cacheKey] end
    local res = ''
    if frame and type(frame.expandTemplate) == 'function' then
        local ok, val = pcall(frame.expandTemplate, frame,
            { title = 'GiftsTable/data', args = { key, field } })
        if ok and type(val) == 'string' then res = val end
    end
    sourceCache[cacheKey] = res
    return res
end

local function itemKey(item)
    return (item.e or ''):lower():gsub(' ', '_')
end

local function nameCell(item)
    local name = item.n or item.e
    if item.l == 'w' then
        return '[[' .. name .. ']]'
    end
    return '[[s:' .. name .. '|' .. name .. ']]'
end

local function categoryLi(item)

    local cats = giftData.categories
    local target = cats and (cats[item.t] or cats[tostring(item.t)])
    if type(target) == 'string' and target ~= '' then
        local display = target:gsub('^s:', '')
        return '所有[[' .. target .. '|' .. display .. ']]'
    end
    return '所有' .. (item.n or '物品')
end

local function manualGetArgs(frame)

    local args = {}
    local function copyInto(t)
        if type(t) ~= 'table' then return end
        for k, v in pairs(t) do args[k] = v end
    end
    copyInto(frame.args)
    local ok, parent = pcall(frame.getParent, frame)
    if ok and parent then copyInto(parent.args) end
    for k, v in pairs(args) do
        if type(v) == 'string' then v = trim(v) if v ~= '' then args[k] = v else args[k] = nil end end
    end
    return args
end

local function parseLevels(raw)
    if not raw or raw == '' then return nil end

    raw = raw:gsub(',', ','):gsub('、', ','):gsub(';', ','):gsub(';', ',')
    local selected = {}
    for part in raw:gmatch('[^,]+') do
        part = trim(part) or ''
        local lower = part:lower()
        for _, tier in ipairs(TIERS) do
            if part == tier.zh or lower == tier.key then selected[tier.key] = true end
        end
    end
    if next(selected) == nil then return nil end
    return selected
end

local function resolveKey(name)
    name = trim(name or '')
    if name == '' then return nil, nil end
    if UNIVERSAL_MODES[name:lower()] or UNIVERSAL_MODES[name] then
        return 'universal', name
    end
    if not giftData or type(giftData.npcs) ~= 'table' then return nil, name end
    if giftData.npcs[name] then return name, name end
    local alias = giftData.aliases and giftData.aliases[name]
    if alias then return alias, name end
    local lower = name:lower()
    for a, k in pairs(giftData.aliases or {}) do
        if type(a) == 'string' and a:lower() == lower then return k, name end
    end
    for k in pairs(giftData.npcs) do
        if type(k) == 'string' and k:lower() == lower then return k, name end
    end
    return nil, name
end

local function currentPageName()
    local ok, title = pcall(mw.title.getCurrentTitle)
    if ok and type(title) == 'table' then return title.text end
    return nil
end

local function buildItemRow(frame, item, opts)
    local source = queryGiftsTable(frame, itemKey(item), 'source')
    local ingredients = queryGiftsTable(frame, itemKey(item), 'ingredients')
    return table.concat({
        '\n|-',
        '\n|[[File:', iconFile(item, opts.iconFallback), '|center]]',
        '\n|', nameCell(item),
        '\n|{{Description|', item.e or item.n or '', '}}',
        '\n|', source,
        '\n|', ingredients,
    })
end

local function buildFirstRow(npc, tier, tierItems, args, opts)
    local lis = {}
    if args.universal ~= 'no' then
        local custom = args['universal_' .. tier.key]
        if custom and custom ~= '' then
            lis[#lis + 1] = '<li>' .. custom .. '</li>'
        else
            local text = tier.link
                and ("'''所有[[" .. tier.link .. '|' .. tier.label .. "]]'''")
                or  ("'''所有" .. tier.label .. "'''")
            lis[#lis + 1] = '<li>' .. text .. '</li>'
        end
    end
    for _, item in ipairs(tierItems) do
        if item.l == 'c' then lis[#lis + 1] = '<li>' .. categoryLi(item) .. '</li>' end
    end
    if #lis == 0 and not opts.portraitFile then return nil end

    local cells = {}
    if opts.portraitFile then
        cells[#cells + 1] = '\n|[[File:' .. opts.portraitFile .. '|48px|center]]'
        if #lis > 0 then
            cells[#cells + 1] = '\n| colspan="4" | <ul>' .. table.concat(lis) .. '</ul>'
        else
            cells[#cells + 1] = '\n| colspan="4" | '
        end
    else
        if #lis > 0 then
            cells[#cells + 1] = '\n| colspan="5" | <ul>' .. table.concat(lis) .. '</ul>'
        else
            return nil
        end
    end
    return '\n|- class="gifts-first"' .. table.concat(cells)
end

local function buildTierTable(frame, npc, tier, tierItems, args, opts)
    local portrait = portraitFile(npc, tier, opts.portrait)
    opts.portraitFile = portrait

    local rows, hasCategory = {}, false
    for _, item in ipairs(tierItems) do
        if item.l == 'c' then
            hasCategory = true
        else
            rows[#rows + 1] = buildItemRow(frame, item, opts)
        end
    end

    if #rows == 0 and not hasCategory then return nil end

    local firstRow = buildFirstRow(npc, tier, tierItems, args, opts)
    if firstRow == nil and #rows == 0 then return nil end

    local style = opts.tableStyle
    local parts = {
        '{|class="wikitable roundedborder gifts-table" style="', style, '"',
        '\n!style="width:48px;"|图片',
        '\n!名称',
        '\n!描述',
        '\n!style="min-width:6em;"|来源',
        '\n!材料',
        firstRow or '',
        table.concat(rows),
        '\n|}',
    }

    return table.concat(parts)
end

local function renderNpc(frame, npcKey, args)
    local npc = giftData.npcs[npcKey]
    local levels = parseLevels(args.levels)

    local opts = {
        portrait = (args.portrait ~= 'no'),
        iconFallback = (args.icon_fallback ~= 'no'),
    }
    if args.width and args.width ~= '' then
        opts.tableStyle = 'width:' .. args.width .. ';'
    else
        opts.tableStyle = 'width:65%; min-width:500px; max-width:100%;'
    end

    local headingLevel = tonumber(args.heading_level) or 3
    if headingLevel < 2 then headingLevel = 2 end
    if headingLevel > 6 then headingLevel = 6 end

    local sections = {}
    for _, tier in ipairs(TIERS) do
        if not levels or levels[tier.key] then
            local items = npc[tier.key] or {}

            local dialogue = args['dialogue_' .. tier.key]
            if (dialogue == nil or dialogue == '') and dialogueOk
                and type(dialogueData) == 'table' then
                local npcLines = dialogueData[npcKey]
                if type(npcLines) == 'table' then dialogue = npcLines[tier.key] end
            end
            local above = args['above_' .. tier.key]
            local below = args['below_' .. tier.key]
            local hasExtras = (dialogue and dialogue ~= '')
                or (above and above ~= '') or (below and below ~= '')

            local tableWikitext = buildTierTable(frame, npc, tier, items, args, opts)

            if tableWikitext or hasExtras then
                if args.heading ~= 'no' then
                    local bar = string.rep('=', headingLevel)
                    sections[#sections + 1] = bar .. tier.zh .. bar
                end
                if dialogue and dialogue ~= '' then
                    sections[#sections + 1] = '{{Squote|' .. escapePipe(dialogue) .. '}}'
                end
                if above and above ~= '' then
                    sections[#sections + 1] = above
                end
                if tableWikitext then
                    sections[#sections + 1] = tableWikitext
                end
                if below and below ~= '' then
                    sections[#sections + 1] = below
                end
            end
        end
    end

    if #sections == 0 then
        return err('「' .. (npc.name or npcKey) .. '」没有可渲染的送礼数据。')
    end
    return table.concat(sections, '\n\n')
end

local function renderUniversal(frame, args)
    local levels = parseLevels(args.levels)
    local headingLevel = tonumber(args.heading_level) or 3
    if headingLevel < 2 then headingLevel = 2 end
    if headingLevel > 6 then headingLevel = 6 end

    local opts = { iconFallback = (args.icon_fallback ~= 'no') }
    local style
    if args.width and args.width ~= '' then
        style = 'width:' .. args.width .. ';'
    else
        style = 'width:65%; min-width:500px; max-width:100%;'
    end

    local sections = {}
    for _, tier in ipairs(TIERS) do
        if not levels or levels[tier.key] then
            local items = giftData.universal[tier.key]

            if items and items[1] ~= nil then
                if args.heading ~= 'no' then
                    local bar = string.rep('=', headingLevel)
                    local label = tier.link and tier.link:match('#(.+)$') or (tier.zh .. '礼物')
                    sections[#sections + 1] = bar .. label .. bar
                end
                local rows = {}
                for _, item in ipairs(items) do
                    local source = queryGiftsTable(frame, itemKey(item), 'source')
                    rows[#rows + 1] = table.concat({
                        '\n|-',
                        '\n|[[File:', iconFile(item, opts.iconFallback), '|36px|center]]',
                        '\n|', nameCell(item),
                        '\n|{{Description|', item.e or item.n or '', '}}',
                        '\n|', source,
                    })
                end
                sections[#sections + 1] = table.concat({
                    '{|class="wikitable roundedborder gifts-table" style="', style, '"',
                    '\n!图片\n!名称\n!描述\n!来源',
                    table.concat(rows),
                    '\n|}',
                })
            end
        end
    end

    if #sections == 0 then
        return err('通用送礼偏好数据为空。')
    end
    return table.concat(sections, '\n\n')
end

local function mainImpl(frame)
    if not okData or type(giftData) ~= 'table' or type(giftData.npcs) ~= 'table' then
        return err('Module:Gifts/Data 未正确部署或结构异常。')
    end

    local args
    if getArgs then
        args = getArgs(frame, { trim = true, removeBlanks = false })
    else
        args = manualGetArgs(frame)
    end

    local name = args[1] or args.npc or args.NPC or args['NPC'] or currentPageName()
    name = trim(name or '')
    if name == '' or name == nil then
        return err('未指定 NPC 名称(且无法从页面名推断)。')
    end

    local key = resolveKey(name)
    if key == 'universal' then
        return renderUniversal(frame, args)
    end
    if key == nil then
        return err('未找到 NPC「' .. name ..
            '」。请使用站内中文名(如 索菲娅)、英文名(如 Sophia)或数据模块别名。')
    end
    return renderNpc(frame, key, args)
end

function p.main(frame)
    ACTIVE_FRAME = frame
    local ok, result = pcall(mainImpl, frame)
    if not ok then
        return err('渲染异常:' .. tostring(result))
    end

    if frame and type(frame.preprocess) == 'function' and type(result) == 'string' then
        local ok2, expanded = pcall(frame.preprocess, frame, result)
        if ok2 and type(expanded) == 'string' then
            return expanded
        end
    end
    return result
end

p.npc = p.main

function p.data()
    return giftData
end

function p.list()
    if not giftData or type(giftData.npcs) ~= 'table' then
        return err('数据模块未加载。')
    end
    local names = {}
    for _, tier in ipairs(TIERS) do table.insert(names, tier.zh) end
    table.insert(names, '')
    for key, npc in pairs(giftData.npcs) do
        table.insert(names, string.format('%s(%s)', npc.name or key, key))
    end
    table.sort(names, function(a, b) return a < b end)
    return table.concat(names, ' · ')
end

return p