Jump to content

Module:LinkParser: Difference between revisions

// via Wikitext Extension for VSCode
// via Wikitext Extension for VSCode
Tag: Reverted
Line 57: Line 57:
-- Construct an external link of the form:
-- Construct an external link of the form:
--  [ rawLink displayText ]
--  [ rawLink displayText ]
return string.format("[%s %s]", rawLink, displayText)
-- Use mw.text.nowiki to prevent the link from being interpreted as wikitext
-- when it's included in HTML contexts
return mw.text.nowiki(string.format("[%s %s]", rawLink, displayText))
end
end


return p
return p

Revision as of 04:00, 19 April 2025

Documentation for this module may be created at Module:LinkParser/doc

-- Module:LinkParser
-- Parses links inserted by editors in templates, strips them of the protocol part, leading "www.", and any trailing "/", while otherwise printing exactly what was entered to minimize spoofing.

local p = {}

-- Cache for previously processed URLs (persists during a single page render)
local stripCache = {}

----------------------------------
-- Remove protocol, leading www., and trailing /
----------------------------------
function p.strip(link)
	-- Input validation
	if not link or link == "" then
		return link
	end
	
	-- Check cache first for previously processed URLs
	if stripCache[link] then
		return stripCache[link]
	end
	
	-- Combine all operations into a single chain to reduce string allocations
	local result = link:gsub("^%a+://", ""):gsub("^www%.", ""):gsub("/$", "")
	
	-- Cache the result before returning
	stripCache[link] = result
	return result
end

----------------------------------
-- Return a MediaWiki link with:
--   [ originalURL  strippedDisplayText ]
----------------------------------
function p.render(frame)
	-- Input validation
	if not frame or not frame.getParent then
		return ""
	end
	
	local parent = frame:getParent()
	if not parent or not parent.args then
		return ""
	end
	
	local args = parent.args
	local rawLink = args["link"] or ""
	
	-- Early return for empty links
	if not rawLink or rawLink == "" then
		return ""
	end

	-- Strip protocol, leading 'www.', and trailing '/'
	local displayText = p.strip(rawLink)

	-- Construct an external link of the form:
	--   [ rawLink displayText ]
	-- Use mw.text.nowiki to prevent the link from being interpreted as wikitext
	-- when it's included in HTML contexts
	return mw.text.nowiki(string.format("[%s %s]", rawLink, displayText))
end

return p