Jump to content

Module:TemplateStarter: Difference between revisions

// via Wikitext Extension for VSCode
// via Wikitext Extension for VSCode
Line 85: Line 85:
-- Main function to be called from wiki (for testing/preview)
-- Main function to be called from wiki (for testing/preview)
function p.main(frame)
function p.main(frame)
     local errorContext = ErrorHandling.createContext()
    -- Simple validation without complex error handling for this function
     local args = frame.args
    local parent = frame:getParent()
    local pargs = parent and parent.args or {}
   
    -- Get parameters (check both direct and parent args)
    local articleName = args.articleName or pargs.articleName or args[1] or pargs[1]
    local templateType = args.templateType or pargs.templateType or args[2] or pargs[2]
      
      
     -- Protected function to process arguments
     -- Validate inputs
    local function processArgs()
    if not articleName or mw.text.trim(tostring(articleName)) == "" then
        local args = frame.args
        return "Error: Article name is required"
        local parent = frame:getParent()
        local pargs = parent and parent.args or {}
       
        -- Get parameters (check both direct and parent args)
        local articleName = args.articleName or pargs.articleName or args[1] or pargs[1]
        local templateType = args.templateType or pargs.templateType or args[2] or pargs[2]
       
        -- Validate inputs
        if not articleName or mw.text.trim(tostring(articleName)) == "" then
            ErrorHandling.addError(errorContext, 'TemplateStarter.main', "Article name is required")
            return nil
        end
       
        if not templateType or mw.text.trim(tostring(templateType)) == "" then
            ErrorHandling.addError(errorContext, 'TemplateStarter.main', "Template type is required")
            return nil
        end
       
        return {
            articleName = mw.text.trim(tostring(articleName)),
            templateType = mw.text.trim(tostring(templateType))
        }
     end
     end
      
      
     -- Process arguments with error protection
     if not templateType or mw.text.trim(tostring(templateType)) == "" then
    local success, params = ErrorHandling.protect(errorContext, processArgs)
         return "Error: Template type is required"
    if not success or not params then
         return "Error: " .. (ErrorHandling.formatOutput(errorContext) or "Invalid parameters")
     end
     end
      
      
     -- Generate the template content
     -- Generate the template content
     local content = p.generateTemplate(params.templateType)
     local content = p.generateTemplate(mw.text.trim(tostring(templateType)))
      
      
     -- For testing, return the generated content in a pre block
     -- For testing, return the generated content in a pre block
     return string.format('<pre>Page: %s\n\n%s</pre>',  
     return string.format('<pre>Page: %s\n\n%s</pre>',  
         mw.text.nowiki(params.articleName),  
         mw.text.nowiki(mw.text.trim(tostring(articleName))),  
         mw.text.nowiki(content))
         mw.text.nowiki(content))
end
end
Line 150: Line 133:
     end
     end
      
      
     -- Create error context for template list generation
     -- Simple approach without complex error handling
     local errorContext = ErrorHandling.createContext()
     local templates = {}
      
      
     -- Protected function to get templates
     -- Check if ConfigRepository.templates exists
     local function getTemplates()
     if ConfigRepository.templates then
        local templates = {}
       
        if not ConfigRepository.templates then
            ErrorHandling.addError(errorContext, 'TemplateStarter.getAvailableTemplates',
                "ConfigRepository.templates is not available")
            return {}
        end
       
        -- Pre-allocate table for better performance
        local templateCount = 0
        for _ in pairs(ConfigRepository.templates) do
            templateCount = templateCount + 1
        end
       
        local templates = {}
         local index = 1
         local index = 1
         for templateName, _ in pairs(ConfigRepository.templates) do
         for templateName, _ in pairs(ConfigRepository.templates) do
Line 177: Line 145:
             end
             end
         end
         end
       
         table.sort(templates)
         table.sort(templates)
        return templates
     end
     end
      
      
     -- Get templates with error protection
     -- Fallback to basic list if no templates found
     local success, templates = ErrorHandling.protect(errorContext, getTemplates)
     if #templates == 0 then
    if not success then
        -- Fallback to basic list if there's an error
         templates = {"Person", "Organization", "Event", "TLD", "Process", "Norm", "LibraryInterview"}
         templates = {"Person", "Organization", "Event", "TLD", "Process", "Norm", "LibraryInterview"}
     end
     end

Revision as of 02:46, 10 June 2025

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

-- Module:TemplateStarter
-- Generates empty template structures for new pages using ConfigRepository

local p = {}

-- Required modules
local ConfigRepository = require('Module:ConfigRepository')
local ErrorHandling = require('Module:ErrorHandling')

-- Cache for template lists to improve performance
local templateListCache = nil
local templateListCacheTime = 0
local CACHE_DURATION = 300 -- 5 minutes in seconds

-- Generate empty template wikitext from template type
function p.generateTemplate(templateType)
    -- Input validation and sanitization
    if not templateType or templateType == "" then
        return "Error: Template type is required"
    end
    
    -- Sanitize input - remove any potentially harmful characters
    templateType = mw.text.trim(tostring(templateType))
    if not templateType:match("^[%w_%-]+$") then
        return "Error: Invalid template type format"
    end
    
    -- Create error context for better error handling
    local errorContext = ErrorHandling.createContext("TemplateStarter")
    
    -- Protected function to get configuration
    local function getTemplateConfig()
        local config = ConfigRepository.getConfig(templateType)
        
        if not config then
            return nil, string.format("Template type '%s' not found in ConfigRepository", templateType)
        end
        
        if not config.fields then
            return nil, string.format("Template type '%s' has no fields configuration", templateType)
        end
        
        return config
    end
    
    -- Get configuration with error protection
    local config = ErrorHandling.protect(errorContext, 'getTemplateConfig', getTemplateConfig, nil)
    if not config then
        return "Error: Failed to load template configuration"
    end
    
    -- Pre-allocate lines table for better performance
    local lines = {}
    lines[1] = "{{" .. templateType
    local lineCount = 1
    
    -- Process each field with error protection
    local function processFields()
        for _, field in ipairs(config.fields) do
            -- Skip hidden fields
            if not field.hidden then
                -- Handle fields with multiple keys (prefer single key, fallback to first of multiple)
                local fieldKey = field.key or (field.keys and field.keys[1])
                
                if fieldKey and fieldKey ~= "" then
                    lineCount = lineCount + 1
                    lines[lineCount] = string.format("|%s = ", fieldKey)
                end
            end
        end
        return true
    end
    
    -- Process fields with error protection
    ErrorHandling.protect(errorContext, 'processFields', processFields, false)
    
    -- Close the template
    lineCount = lineCount + 1
    lines[lineCount] = "}}"
    
    -- Join with newlines (more efficient than multiple concatenations)
    return table.concat(lines, "\n")
end

-- Main function to be called from wiki (for testing/preview)
function p.main(frame)
    -- Simple validation without complex error handling for this function
    local args = frame.args
    local parent = frame:getParent()
    local pargs = parent and parent.args or {}
    
    -- Get parameters (check both direct and parent args)
    local articleName = args.articleName or pargs.articleName or args[1] or pargs[1]
    local templateType = args.templateType or pargs.templateType or args[2] or pargs[2]
    
    -- Validate inputs
    if not articleName or mw.text.trim(tostring(articleName)) == "" then
        return "Error: Article name is required"
    end
    
    if not templateType or mw.text.trim(tostring(templateType)) == "" then
        return "Error: Template type is required"
    end
    
    -- Generate the template content
    local content = p.generateTemplate(mw.text.trim(tostring(templateType)))
    
    -- For testing, return the generated content in a pre block
    return string.format('<pre>Page: %s\n\n%s</pre>', 
        mw.text.nowiki(mw.text.trim(tostring(articleName))), 
        mw.text.nowiki(content))
end

-- Generate a dynamic preload template (main function used by JavaScript)
function p.preload(frame)
    local args = frame.args
    local templateType = args.templateType or args[1]
    
    if not templateType or mw.text.trim(tostring(templateType)) == "" then
        return "<!-- No template type specified -->"
    end
    
    return p.generateTemplate(mw.text.trim(tostring(templateType)))
end

-- Get list of available templates with caching
function p.getAvailableTemplates()
    local currentTime = os.time()
    
    -- Check if cache is valid
    if templateListCache and (currentTime - templateListCacheTime) < CACHE_DURATION then
        return templateListCache
    end
    
    -- Simple approach without complex error handling
    local templates = {}
    
    -- Check if ConfigRepository.templates exists
    if ConfigRepository.templates then
        local index = 1
        for templateName, _ in pairs(ConfigRepository.templates) do
            if templateName and templateName ~= "" then
                templates[index] = templateName
                index = index + 1
            end
        end
        table.sort(templates)
    end
    
    -- Fallback to basic list if no templates found
    if #templates == 0 then
        templates = {"Person", "Organization", "Event", "TLD", "Process", "Norm", "LibraryInterview"}
    end
    
    -- Update cache
    templateListCache = templates
    templateListCacheTime = currentTime
    
    return templates
end

-- Test function to list available templates
function p.listTemplates(frame)
    local templates = p.getAvailableTemplates()
    if #templates == 0 then
        return "No templates available"
    end
    return "Available templates: " .. table.concat(templates, ", ")
end

return p