跳转到内容

模組:Bar

本页使用了标题或全文手工转换
被永久保护的模块
维基百科,自由的百科全书

这是本页的一个历史版本,由Shizhao留言 | 贡献2013年5月14日 (二) 12:45 建立内容为“-- https://meta.wikimedia.org/wiki/Module:Bar local p = {} --########## --## Public functions --########## -- the main entry point function p.form...”的新頁面)编辑。这可能和当前版本存在着巨大的差异。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)

-- https://meta.wikimedia.org/wiki/Module:Bar
local p = {}
 
--##########
--## Public functions
--##########
-- the main entry point
function p.format( frame )
    -- extract configuration
    local width = frame.args['width'] or '100%'
    local barCSS = frame.args['barCSS'] or ''
    local zeroWidth = frame.args['zeroWidth'] or '1px'
 
    -- extract bar series from arguments like 'value,color,title'
    local series = {}
    for key, spec in ipairs(frame.args) do
        spec = mw.text.split(spec, ',')
        local data = {value = tonumber(spec[1] or 0), color = spec[2] or '#CCC', title = spec[3] or ''}
        if data['value'] > 0 then
            table.insert(series, data)
        end
    end
 
    -- calculate total
    local total = tonumber(frame.args['total'] or 0)
    local seriesTotal = 0
    for k,v in ipairs(series) do
       seriesTotal = seriesTotal + v['value']
    end
    if total < seriesTotal then
       total = seriesTotal
    end
 
    -- inject empty series for uncharted values
    if(seriesTotal < total) then
        table.insert(series, {value = total - seriesTotal, color = 'transparent', title = ''})
    end
 
    -- inject ratios
    for k,v in ipairs(series) do
       v['total'] = total
       v['ratio'] = getRatio(v['value'], total)
       if v['ratio'] == 0 then
           v['width'] = zeroWidth
      end
    end
 
    return format(series, total, width, barCSS)
end
 
 
--##########
--## Private functions
--##########
-- get the markup for a bar
function format(series, total, width, barCSS)
    result = '<table style="width:' .. width .. ';' .. barCSS .. '" cellspacing="0"><tr>'
    for k, v in pairs(series) do
        result = result .. formatSeries(v)
    end
    result = result .. '</tr></table>'
    return result
end
 
-- get the markup to format a series
function formatSeries(series)
    -- set width
    local width = series.width
    if not(width) then
        width = series.ratio .. '%'
    end
 
    -- format
    local result = mw.ustring.format('<td title="%s" style="width:%s; height:1em; padding:0; background:%s;" data-value="%s"></td>', series.title, width, series.color, series.value)
    return result
end
 
-- get the percentage ratio of two numbers
function getRatio(value, total)
    if(total == 0) then
       error('the total for a series cannot be zero')
    end
    return math.floor(value / total * 10000) / 100
end
 
return p