Module:PercentageBar

Documentation for this module may be created at Module:PercentageBar/doc

require( 'strict' )

local PercentageBar = {}

local metatable = {}
local methodtable = {}

local libraryUtil = require( 'libraryUtil' )
local checkType = libraryUtil.checkType

metatable.__index = methodtable

metatable.__tostring = function ( self )
    return tostring( self:renderSwitcher() )
end

--- Wrap the HTML into a PercentageBar
---
--- @param data table {label, value, width, baseColor, fillColor}
--- @param includeStyle boolean include templatestyles or not
--- @return string html PercentageBar html with or without templatestyles
function methodtable.renderPercentageBar( self, data, includeStyle )
    checkType( 'Module:PercentageBar.renderPageButton', 1, self, 'table' )
    checkType( 'Module:PercentageBar.renderPageButton', 2, data, 'table' )
    checkType( 'Module:PercentageBar.renderPageButton', 3, includeStyle, 'boolean' )

    if includeStyle == nil then
        includeStyle = true
    end

    data['width'] = data['width'] or self.config['width']
    data['maxValue'] = data['maxValue'] or self.config['maxValue']
    data['baseColor'] = data['baseColor'] or self.config['baseColor']
    data['fillColor'] = data['fillColor'] or self.config['fillColor']

    data['label'] = data['label'] or ""
    data['value'] = data['value'] or 0

    local html = mw.html.create( 'div' ):css( 'width', data['width'] .. 'px' )

    local textContainer = html:tag( 'div' ):addClass( 'percentage-bar__text-container' )

    textContainer:tag( 'span' ):wikitext( data['label'] )
    textContainer:tag( 'span' ):wikitext( data['value'] )

    local barContainer = html:tag( 'div' )
            :addClass( 'percentage-bar__bar-container' )
            :css( 'background-color', data['baseColor'])

    barContainer:tag( 'div' )
            :addClass( 'percentage-bar__bar-bar' )
            :css( 'width', 100 * (data['value'] / data['maxValue']) .. '%' )
            :css( 'background-color', data['fillColor'])

    local frame = mw.getCurrentFrame()

    if includeStyle then
        return frame:extensionTag {
            name = 'templatestyles', args = { src = "Module:PercentageBar/styles.css" }
        } .. tostring( html )
    else
        return tostring( html )
    end
end

--- New Instance
---
--- @return table PercentageBar
function PercentageBar.new( config )
    local baseConfig = {
        maxValue = 100,
        width = 200,
        baseColor = "#313238",
        fillColor = "#666666"
    }

    for k, v in pairs( config or {} ) do
        baseConfig[k] = v
    end

    local instance = {
        config = baseConfig,
        modules = {}
    }

    setmetatable( instance, metatable )

    return instance
end

return PercentageBar