Module:If preview/sandbox

This is an old revision of this page, as edited by Izno (talk | contribs) at 14:47, 30 April 2021 (is this all it takes). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local p = {}

--[[
is_preview

This function returns a boolean indicating whether the page is a preview.

]]
local function is_preview()
	local revision_id = mw.getCurrentFrame():preprocess('{{REVISIONID}}')
	-- {{REVISIONID}} is usually the empty string when previewed.
	-- not (Preview_mode == nil or Preview_mode == '')
	-- return not (revision_id == nil or revision_id == '')
	return revision_id, type(revision_id), tostring(revision_id == nil or revision_id == '')
end

--[[
main

This function returns either the first argument or second argument passed to
this module, depending on whether the page is being previewed.

Usage:
{{#invoke:If preview|main|value_if_preview|value_if_not_preview}}

]]
function p.if_preview(frame)
	if is_preview() then
		return frame.args[1] or ''
	else
		return frame.args[2] or ''
	end
end

--[[
preview_warning

This function returns a "preview warning", which is the first argument marked
up with HTML and some supporting text, depending on whether the page is being previewed.

Usage:
{{#invoke:If preview|warning|preview_warning_text}}

]]
function p.warning(frame)
	-- if not is_preview() then return '' end
	
	local warning = frame.args[1]:match('^%s*(.-)%s*$') or ''
	if warning == '' then
		warning = 'Something is wrong with this template'
	end
	
	local rev_id, rev_id_type, eval = is_preview()
	
	return mw.ustring.format(
		'%s<div class="preview-warning"><strong>Preview warning "%s" %s %s:</strong> %s</div>',
		frame:extensionTag{
			name = 'templatestyles', args = { src = 'Module:Preview warning/styles.css' }
		},
		rev_id,
		rev_id_type,
		eval,
		warning
	)
end

return p