Module:Sprite

Revision as of 16:51, 8 November 2018 by Kroppeb (talk | contribs) (Removed bug that resulted in using the wrong sprite if the name was unkown and setPosition calculating the right position and changing the css accordingly but storing it wrong internaly (of by 1))
-- Based on work by the MC wiki: https://minecraft.gamepedia.com/ and https://minecraft.gamepedia.com/Module:Sprite

local Sprite = {}

local types = {
	inventory = [[Module:InvSprite]],
}

local defaultSettings = {
	scale = 1,
	sheetsize = 256,
	size = 16,
	pos = 1,
	align = 'text-top'
}

function Sprite:new (type)
	source = types[type]
	if not(source) then
		error("Unknown type: " .. tostring(type))
	end
	o = {
		__source = require(source),
		}
	setmetatable(o, {__index = self})
	o:load()
	return o
end

function Sprite:load()
	local settings = self.__source.settings
	self.__settings = {
		size = settings.size,
		sheetWidth = settings.sheetsize,
		tiles = settings.sheetsize / settings.size,
		scale = settings.scale,
		autoScale = settings.autoscale,
	}
	local lSet = self.__settings

	setmetatable(lSet, {__index=defaultSettings})


	styles = {}
	--[[styles["background-image"] = (settings.url and "url(" .. settings.url .. ")") or mw.getCurrentFrame():expandTemplate{
			title = 'FileUrl',
			args = { settings.image}
		} ]]
	styles["background-size"] = lSet.sheetWidth * lSet.scale .. 'px auto'

	local t = lSet.size * lSet.scale .. 'px'

	styles.height = t
	styles.width = t
	styles["vertical-align"] = lSet.align
	self.__styles = styles
end

function Sprite:setItem(item)
	if self.__source.ids[item] then
		self:setPosition(self.__source.ids[item].pos)
	else
		self:setPosition(nil) --will use default
	end
	return self
end

function Sprite:Item(item)
	local sprite = {}
	setmetatable(sprite, {__index = self})
	local settings = {}
	setmetatable(settings, {__index = self.__settings})
	sprite.__settings = settings
	return sprite:setItem(item)
end

function Sprite:setPosition(pos)
	local settings = self.__settings

	local pos = (pos or settings.pos) - 1

	local left = pos % settings.tiles * settings.size * settings.scale
	local top = math.floor( pos / settings.tiles ) * settings.size * settings.scale
	self.__styles["background-position"] = '-' .. left .. 'px -' .. top .. 'px'

	settings.pos = pos + 1
	return self
end

function Sprite:GenerateHTML (html)
	local sprite
	if html then
		sprite = html:tag("div")
	else
		sprite = mw.html.create("div")
	end

	sprite:addClass("sprite")

	local source = self.__source
	sprite:addClass(source.settings.classname)

	local styles = {}
	for k,v in pairs(self.__styles) do
		styles[#styles + 1] = k .. ":" .. v
	end

	sprite:cssText( table.concat( styles, "; " ) )

	return sprite
end

return Sprite