Module:ChartJs
Appearance
This documentation is transcluded from Module:ChartJs/doc.
Lua interface for building HTML required for Chart.js. Chart.js is loaded through the gadget MediaWiki:Gadget-ChartJs.js.
require( 'strict' )
local p = {}
--- @class ChartJsConfig
--- @field type string
--- @field data table
--- @field options table
--- Encode curly braces to something else so that
--- they don't get interpreted in wikitext. This is then
--- decoded in the MediaWiki:Gadget-ChartJs.js.
---
--- This is needed when we transclude this module multiple times,
--- such as with Module:GameTabs.
---
--- @param str string
--- @return string
local function encodeCurlyBraces( str )
return str:gsub( '{', '😩' ):gsub( '}', '😒' )
end
--- Build the chart html
---
--- @param config ChartJsConfig
--- @return mw.html
local function getChartHtml( config )
local root = mw.html.create( 'div' )
root
:addClass( 'site-chartjs-target' ) -- For attaching Chart.js
:addClass( 'skin-invert' ) -- For dark mode
:attr( 'data-chartjs-type', config.type )
:attr( 'data-chartjs-data', encodeCurlyBraces( mw.text.jsonEncode( config.data ) ) )
:attr( 'data-chartjs-options', encodeCurlyBraces( mw.text.jsonEncode( config.options ) ) )
:tag( 'div' )
:addClass( 'site-chartjs-target-placeholder' )
:wikitext( 'Loading chart...' )
:done()
return root
end
--- Validate the config
---
--- @param config ChartJsConfig
local function validateConfig( config )
if type( config ) ~= 'table' then
error( 'Invalid ChartJs config type: ' .. type( config ) )
end
if type( config.type ) ~= 'string' then
error( 'Invalid ChartJs config.type type: ' .. type( config.type ) )
end
if type( config.data ) ~= 'table' then
error( 'Invalid ChartJs config.data type: ' .. type( config.data ) )
end
if type( config.options ) ~= 'table' then
error( 'Invalid ChartJs config.options type: ' .. type( config.options ) )
end
end
--- Return the wikitext for the chart
---
--- @param config ChartJsConfig
--- @return string
function p.render( config )
validateConfig( config )
return tostring( getChartHtml( config ) )
end
--- Get the mw.html for the chart
---
--- @param config ChartJsConfig
--- @return mw.html
function p.getHtml( config )
validateConfig( config )
return getChartHtml( config )
end
return p