Jump to content

Module:Prevnext

From Creopedia

This documentation is transcluded from Module:Prevnext/doc.

Implements Template:Prevnext.


require( 'strict' )

local p = {}

local ICON_MAP = {
	prev = 'cdxIconArrowPrevious.svg',
	next = 'cdxIconArrowNext.svg'
}

--- Returns true if a page exists
---
--- @param page string
--- @return boolean
local function pageExists( page )
	local title = mw.title.new( page )
	return title and title.exists
end

--- Make a link for the previous or next page
---
--- @param args table
--- @param dir string
--- @return mw.html|nil
local function getLinkHtml( args, dir )
	if not args[ dir ] then
		return
	end

	local inner = mw.html.create( 'div' )
	inner:addClass( 't-prevnext__' .. dir )
		:addClass( 't-prevnext__link' )

	if not pageExists( args[ dir ] ) then
		inner:addClass( 't-prevnext__link--new' )
	end

	local icon = mw.html.create( 'div' )

	icon:addClass( 't-prevnext__icon' )
		:wikitext( string.format( '[[File:%s|14px|link=|class=skin-invert-image]]', ICON_MAP[ dir ] ) )
		:done()

	if dir == 'prev' then
		inner:node( icon )
	end

	local content = inner:tag( 'div' )
		:addClass( 't-prevnext__content' )
		:tag( 'div' )
		:addClass( 't-prevnext__title' )
		:wikitext( args[ dir .. 'Title' ] or args[ dir ] )
		:done()

	if args[ dir .. 'Desc' ] then
		content:tag( 'div' )
			:addClass( 't-prevnext__desc' )
			:wikitext( args[ dir .. 'Desc' ] )
			:done()
	end

	if dir == 'next' then
		inner:node( icon )
	end

	inner:tag( 'div' )
		:addClass( 't-prevnext__linkoverlay' )
		:wikitext( string.format( '[[%s]]', args[ dir ] ) )
		:allDone()

	return inner
end

--- Wikitext entry point for the module
---
--- @param frame mw.frame
--- @return string
function p.main( frame )
	local getArgs = require( 'Module:Arguments' ).getArgs
	return p._main( getArgs( frame ) )
end

--- Lua entry point for the module
---
--- @param args table
--- @return string
function p._main( args )
	local root = mw.html.create( 'div' )
	root:addClass( 't-prevnext' )

	local current = mw.html.create( 'div' )
	current:addClass( 't-prevnext__current' )

	local content = current:tag( 'div' )
		:addClass( 't-prevnext__content' )
		:tag( 'div' )
		:addClass( 't-prevnext__title' )
		:wikitext( args.title or mw.title.getCurrentTitle().subpageText )
		:done()

	if args.desc then
		content:tag( 'div' )
			:addClass( 't-prevnext__desc' )
			:wikitext( args.desc )
	end

	current:allDone()

	root
		:node( getLinkHtml( args, 'prev' ) )
		:node( current )
		:node( getLinkHtml( args, 'next' ) )

	return mw.getCurrentFrame():extensionTag {
		name = 'templatestyles', args = { src = 'Module:Prevnext/styles.css' }
	} .. tostring( root:allDone() )
end


return p