Module:LinkParser

Revision as of 00:10, 23 April 2025 by MarkWD (talk | contribs) (// via Wikitext Extension for VSCode)

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

-- Module:LinkParser
-- Handles link processing for both external links and wiki links
-- 
-- This module contains the following sections:
-- * External Link Processing - For handling URLs and external links
-- * Wiki Link Processing - For handling internal wiki links
-- * Caching and Utilities - Shared functionality for link handling

local p = {}

--------------------------------------------------------------------------------
-- Caching and Utilities
--------------------------------------------------------------------------------

-- Cache for previously processed URLs and wiki links (no persistence)
local stripCache = {}
local wikiLinkCache = {}

--------------------------------------------------------------------------------
-- External Link Processing
--------------------------------------------------------------------------------

-- 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 ]
	return string.format("[%s %s]", rawLink, displayText)
end

--------------------------------------------------------------------------------
-- Wiki Link Processing
--------------------------------------------------------------------------------

-- Process wiki links with different modes: extract, strip, or check
-- @param value The wiki link to process
-- @param mode The processing mode: "extract", "strip", or "check"
-- @return Processed value or boolean depending on mode
function p.processWikiLink(value, mode)
    -- Default mode is "extract"
    mode = mode or "extract"
    
    -- Early return for nil or empty values
    if not value or value == "" then
        return mode == "check" and false or value
    end
    
    -- Create cache key combining value and mode
    local cacheKey = value .. ":" .. mode
    
    -- Check cache first
    if wikiLinkCache[cacheKey] ~= nil then
        return wikiLinkCache[cacheKey]
    end
    
    -- Check if the value is a wiki link
    local isWikiLink = value:match("^%[%[.-%]%]$") ~= nil
    
    -- For check mode, just return whether it's a wiki link
    if mode == "check" then
        wikiLinkCache[cacheKey] = isWikiLink
        return isWikiLink
    end
    
    -- If it's not a wiki link, return the original value
    if not isWikiLink then
        wikiLinkCache[cacheKey] = value
        return value
    end
    
    -- Extract components from the wiki link
    local pageName, displayText
    
    -- Try to match [[PageName|DisplayText]] format
    pageName, displayText = value:match("^%[%[([^%|%]]+)%|([^%]]+)%]%]$")
    
    if not pageName then
        -- Try to match [[PageName]] format
        pageName = value:match("^%[%[([^%|%]]+)%]%]$")
        displayText = pageName -- In this case, display text is the same as page name
    end
    
    -- Determine result based on mode
    local result
    if mode == "extract" then
        result = pageName or value
    elseif mode == "strip" then
        result = displayText or value
    else
        -- Default to extract mode for unknown modes
        result = pageName or value
    end
    
    -- Store result in cache
    wikiLinkCache[cacheKey] = result
    
    return result
end

-- Extract page name from wiki link [[Name]] or [[Name|Text]]
-- @param value The wiki link to extract from
-- @return The extracted page name
function p.extractFromWikiLink(value)
    return p.processWikiLink(value, "extract")
end

-- Adds wiki links to a value if needed based on field configuration
-- @param value The value to process
-- @param field The field configuration
-- @return The processed value with wiki links added if needed
function p.applyWikiLinkHandling(value, field)
    -- Skip if value is not a string or is nil/empty
    if not value or type(value) ~= "string" or value == "" then
        return value
    end
    
    -- Add wiki links at the very end of processing if autoWikiLink is true
    -- This ensures they won't be stripped by any subsequent processing
    if field.autoWikiLink and not value:match("%[%[.-%]%]") then
        return "[[" .. value .. "]]"
    end
    
    return value
end

-- Helper function to preserve wiki links in processed values
-- If the original value had wiki links but the processed value doesn't,
-- returns the original value to preserve the wiki links
-- @param originalValue The original value before processing
-- @param processedValue The value after processing
-- @param preserveWikiLinks Whether to preserve wiki links
-- @return The value with wiki links preserved if needed
function p.preserveWikiLinks(originalValue, processedValue, preserveWikiLinks)
    -- Skip if any value is not a string
    if type(originalValue) ~= "string" or type(processedValue) ~= "string" then
        return processedValue
    end
    
    -- If preserveWikiLinks is true and the processor stripped wiki links,
    -- use the original value with wiki links
    if preserveWikiLinks and 
       originalValue:match("%[%[.-%]%]") and 
       not processedValue:match("%[%[.-%]%]") then
        return originalValue
    end
    
    return processedValue
end

return p