Module:Inventory slot

-- Initially taken from: https://minecraft.gamepedia.com/Module:Inventory_slot

local p = {}

local getArgs = require('Module:Arguments').getArgs local loader = require('Module:Loader')

local string, table, yesno, currency, random, uitext = loader.require('String', 'Table', 'Yesno', 'Currency', 'Random', 'UIText')

local aliasesCache = require('Module:Cache').slotAliasesCache

local pageName = mw.title.getCurrentTitle.text local i18n = { prefixes = { any = 'Any', matching = 'Matching', all = 'All', },	suffixes = { }, } p.i18n = i18n local availableFrameParameters = { 'title', 'num', 'num2', 'text', 'link', 'image', 'image_id' }

--	Structure for main slot creation: --	p.slot --	├── p.parseFrameText --	│	└── p.combineFrames --	│	└── p.makeFrame --	└── p.makeItem

--Merges a list, or inserts a string	or table into a table -- local function mergeList( parentTable, content ) if content[1] then -- Merge list into table for _, v in ipairs( content ) do			parentTable[#parentTable + 1] = v		end else -- Add strings or tables to table parentTable[#parentTable + 1] = content end end

-- Main entry point function p.slot( f ) local args = getArgs(f) if not args.parsed then args[1] = string.trim( args[1] and (args[1]:gsub("(%s)%s+", "%1")) or '' ) end -- Prepare List of "Frames" local frames if args.parsed then frames = args[1] elseif args[1] ~= '' then local randomise = args.class == 'invslot-large' and 'never' or nil frames = p.parseFrameText( args[1], randomise, false ) end -- Now, Prepare Top-level Slot Element local body = mw.html.create( 'span' ):addClass( 'invslot noselect' ):css{ ['vertical-align'] = args.align } local animated = frames and #frames > 1 local imgClass = args.imgclass local numStyle = args.numstyle if animated then body:addClass( 'animated' ) end if args.class then body:addClass( args.class ) end if args.style then body:cssText( args.style ) end if not frames then return tostring(body:tag('span'):addClass('invslot-item'):done) end -- Create Slot Item for Each "Frame" local activeFrame = frames.randomise == true and random.number{ #frames } or 1 for index, frame in ipairs( frames ) do		local item -- If the "frame" is list of frames, handle "subframes" if frame[1] then item = body:tag( 'span' ):addClass( 'animated-subframe' ) local subActiveFrame = frame.randomise and random.number{ #frame } or 1 for subIndex, subFrame in ipairs( frame ) do				local subItem = p.makeItem( subFrame, subIndex, args ) item:node( sItem ) if subIndex == subActiveFrame then subItem:addClass( 'animated-active' ) else -- CUSTOM: "hidden" class is needed to hide it on mobile (since wikia doesn't allow CSS / JS on mobile) subItem:addClass('hidden') end end else item = p.makeItem( frame, index, args ) body:node( item ) end if index == activeFrame and animated then item:addClass( 'animated-active' ) elseif animated then -- CUSTOM: "hidden" class is needed to hide it on mobile (since wikia doesn't allow CSS / JS on mobile) item:addClass('hidden') end end return tostring( body ) end

--Creates the HTML for a single Slot Item -- function p.makeItem( frame, i, args ) -- Initialize Element local item = mw.html.create( 'span' ):addClass( 'invslot-item' ) if args.imgclass then item:addClass( args.imgclass ) end if frame.image_id then item:attr('data-iid', frame.image_id) end if frame.name == '' then return item end local category local title = string.trim( args.title or frame.title or '' ) local name = frame.name or '' local n_1 = tonumber(frame.num) or 1 local n_2 = tonumber(frame.num2) local n_str, n_fs, n_r local image = args.image or frame.image or nil local description = args.text or frame.text or '' local forceNum = yesno(args.forcenum) local img -- Handle Image if frame.image_id then -- has CSS handled image ID: don't display image img = nil elseif image and string.anyMatched(image, '%.gif$', '%.webp$', '%.png', '%.apng', '%.jpg$', '%.jpeg$') then img = image else img = (image or name) .. '.png' end -- Handle Link local link = args.link or frame.link or '' if link == '' then link = name == 'none' and nil or name for _, suffix in pairs( i18n.suffixes ) do link = link:gsub( ' ' .. suffix .. '$', '' ) end elseif ((not args.link) or (args.link or ''):lower == 'none') and link:lower == 'none' then link = nil end -- (Handle Link Redirects) local rtName = mw.title.makeTitle(0, link or ) and mw.title.makeTitle(0, link or ).redirectTarget or false rtName = rtName and rtName.text or false if link == pageName or rtName == pageName or link == 'none' then link = nil end -- Handle Numbers if not (n_1 and n_2 and n_1 ~= n_2) then -- No second number n_2 = nil end if (n_1 or 0) >= 10000 then n_1 = string._formatShortNum(n_1):lower end if (n_2 or 0) >= 10000 then n_2 = string._formatShortNum(n_2):lower end if forceNum or ((not n_2) and n_1 and n_1 ~= 1) or (n_1 and n_2) then -- Entering condition for displaying numbers (else, n_str undefined) local function len(n) return n and tostring(n):len or 0 end if n_1 and n_2 then n_1 = tostring(n_1) .. '-'		end local splitLine = n_2 and (len(n_1) + len(n_2) > 4) -- Deciding font-size (n_fs) and right (n_r) values if (len(n_1) > 7) or (len(n_2) > 7) then n_fs = 5.4; n_r = 1.2 elseif (len(n_1) > 6) or (len(n_2) > 6) then n_fs = 6.1; n_r = 1.3 elseif (len(n_1) > 5) or (len(n_2) > 5) then n_fs = 7.2; n_r = 1.6 elseif (len(n_1) > 3) or (len(n_2) > 3) or splitLine then n_fs = 9; n_r = 1 elseif n_2 or splitLine then n_fs = 12; n_r = 0 else n_fs = 15; n_r = 0 end -- Stringify Numbers n_str = n_2 and (n_1 .. (splitLine and ' ' or '') .. n_2) or n_1 end -- Handle Title local formattedTitle, plainTitle title = uitext.applyReplacements(title) if title == '' then plainTitle = name formattedTitle = name elseif title:lower ~= 'none' then formattedTitle = title plainTitle = title local formatPattern = '&[0-9a-fk-or]' if plainTitle:match( formatPattern ) then plainTitle = plainTitle:gsub( formatPattern, '' ) end if plainTitle == '' then plainTitle = name end elseif link then if img then formattedTitle = '' else plainTitle = '' end end -- Handle Description description = uitext.applyReplacements(description) if description:lower == 'none' then description = '' end -- (Transform newlines into `/`) if description and description:match("\n") then description = description:gsub("\n", "/") end -- Now, Prepare Element -- Insert Title/Text item:attr{ ['data-minetip-title'] = formattedTitle and formattedTitle:gsub('"', '&quot;') or nil,		['data-minetip-text'] = description and description:gsub('"', '&quot;') or nil, }	-- Insert Image if img then -- & is re-escaped because mw.html treats attributes -- as plain text, but MediaWiki doesn't		local escapedTitle = ( plainTitle or '' ):gsub( '&', '&#38;' ) item:addClass( 'invslot-item-image' ) :wikitext( '' ) end -- Insert Numbers if n_str then local stacksizeElm = item:tag( 'span' ) :addClass( 'invslot-stacksize' ) :attr{ title = plainTitle } stacksizeElm:css('font-size', n_fs .. 'px'):css('right', (n_r - 2) .. 'px') if args.numStyle then stacksizeElm:cssText( args.numStyle ) end stacksizeElm:wikitext( n_str ) end return item end

--Parses the frame text into a table of frames and subframes,	expanding aliases (and optionally retaining a reference), and	deciding if the slot can be randomised -- function p.parseFrameText( framesText, randomise, aliasReference ) local frames = { randomise = randomise } local subframes = {} local subframe local expandedAliases framesText = framesText:gsub( '\\;', '%%%%SEMICOLON%%%%' );-- gsub here allows us to escape ; character local splitFrames = string.split( string.trim( framesText ), '%s*;%s*' ) for _, frameText in ipairs( splitFrames ) do		frameText = frameText:gsub('%%%%SEMICOLON%%%%', ';') -- undo-escape now that semicolon regex check is done -- Check Subframe Status frameText = frameText:gsub( '^%s*{%s*', function			subframe = true			return ''		end ) if subframe then frameText = frameText:gsub( '%s*}%s*$', function				subframe = 'last'				return ''			end ) end -- Now, Parse Frame Text local frame = p.makeFrame( frameText ) local newFrame = frame local id = frame.name -- Now, Find Frame Alias and Combine With Frame local alias = aliasesCache:get(id) if alias then newFrame = p.combineFrames( alias, frame ) if aliasReference then local curFrame = #frames + 1 local aliasData = { frame = frame, length = #newFrame } if subframe then if not subframes.aliasReference then subframes.aliasReference = {} end subframes.aliasReference[#subframes + 1] = aliasData else if not expandedAliases then expandedAliases = {} end expandedAliases[curFrame] = aliasData end end end -- Handle Subframes if subframe then mergeList( subframes, newFrame ) -- Randomise starting frame for "Any *" aliases, as long as the alias is the only subframe if frames.randomise ~= 'never' and subframes.randomise == nil and i18n.prefixes.any and frame.name:match( '^' .. i18n.prefixes.any .. ' ' ) then subframes.randomise = true else subframes.randomise = false end if frames.randomise ~= 'never' then frames.randomise = false end if subframe == 'last' then -- No point having a subframe containing a single frame, -- or the subframe being the only frame if #subframes == 1 or #splitFrames == i and #frames == 0 then mergeList( frames, subframes ) else table.insert( frames, subframes ) end subframes = {} subframe = nil end else -- Randomise starting frame for "Any *" aliases, as long as the alias is the only frame if frames.randomise == nil and i18n.prefixes.any and frame.name:match( '^' .. i18n.prefixes.any .. ' ' ) then frames.randomise = true elseif frames.randomise ~= 'never' then frames.randomise = false end mergeList( frames, newFrame ) end end frames.aliasReference = expandedAliases return frames end

--Returns a new table with the parent frame values	added to alias frames (parent frame overrides alias frames) -- function p.combineFrames( aliasFrames, parentFrame ) -- If alias is just a name, return the parent frame with the new name if type( aliasFrames ) == 'string' then local expandedFrame = mw.clone( parentFrame ) expandedFrame.name = aliasFrames return { expandedFrame } end -- Single frame alias, put in list if aliasFrames.name then aliasFrames = { aliasFrames } end -- Prepare new table, combine frames local expandedFrames = {} for i, aliasFrame in ipairs( aliasFrames ) do		local expandedFrame if type( aliasFrame ) == 'string' then expandedFrame = { name = aliasFrame } else expandedFrame = table.deepCopy( aliasFrame, true ) end for _, param in ipairs(availableFrameParameters) do			expandedFrame[param] = parentFrame[param] or expandedFrame[param] end expandedFrames[i] = expandedFrame end return expandedFrames end

--Parses frame text into a table	[] :, [ ] - function p.makeFrame( frameText ) local c = currency._newcurrencySlot( frameText ) if c then return c end local frameTextUntouched = frameText -- Simple frame with no parts if type(frameText) ~= 'string' then error(type(frameText)) end -- [ESC] allow escaping special characters - we'll convert normal character after we parse frameText = frameText:gsub( '\\\\', '%%%%BACKSLASH%%%%' ):gsub( '\\%[', '%%%%SQBRACL%%%%' ):gsub( '\\%]', '%%%%SQBRACR%%%%' ):gsub( '\\:', '%%%%COLON%%%%' ) if not frameText:match( '[%[:,]' ) then return { name = string.trim( frameTextUntouched ), }	end frameText = frameText:gsub( '%s*([%[%]:,;])%s*', '%1' ) local frame = {} frame.title = frameText:match( '^%[([^%]]+)%]' ) frame.image = frameText:match( '([^:%]]+):' ) local nameStart = ( frameText:find( ':' ) or frameText:find( '%]' ) or 0 ) + 1 if nameStart - 1 == #frameText then nameStart = 1 end frame.name = frameText:sub( nameStart, ( frameText:find( '[,%[]', nameStart ) or 0 ) - 1 ) -- Handle m-n syntax frame.num = math.floor( frameText:match( ',%s*(%d+)' ) or 1 ) frame.num2 = math.floor( frameText:match( ',%s*%d+%s*[%-%–]%s*(%d+)%s*' ) or frame.num ) frame.text = frameText:match( '%[([^%]]+)%]$' ) -- [/ESC] un-replace the characters we used for escaped characters earlier if frame.title then frame.title = frame.title:gsub('%%%%BACKSLASH%%%%','\\'):gsub('%%%%SQBRACL%%%%','['):gsub('%%%%SQBRACR%%%%',']'):gsub('%%%%COLON%%%%',':') end if frame.name then frame.name = frame.name:gsub('%%%%BACKSLASH%%%%','\\'):gsub('%%%%SQBRACL%%%%','['):gsub('%%%%SQBRACR%%%%',']'):gsub('%%%%COLON%%%%',':') end if frame.text then frame.text = frame.text:gsub('%%%%BACKSLASH%%%%','\\'):gsub('%%%%SQBRACL%%%%','['):gsub('%%%%SQBRACR%%%%',']'):gsub('%%%%COLON%%%%',':') end -- Transform newlines into `/` if frame.text and frame.text:match("\n") then frame.text = frame.text:gsub("\n", "/") end return frame end

- -- Other Features -

p.getAlias = p.combineFrames function p.expandAlias( parentFrame, alias ) return p.combineFrames( alias, parentFrame ) end

function p.stringifyFrame( frame ) if not frame.name then return '' end return string.format(		'[%s]%s,%s[%s]',		frame.title or ,		frame.name,		frame.num or ,		frame.text or ''	) end

function p.stringifyFrames( frames ) for i, frame in ipairs( frames ) do		frames[i] = p.stringifyFrame( frame ) end return table.concat( frames, ';' ) end

return p