Module:CustomCursor

From Uncyclopedia, the content-free encyclopedia
Jump to navigation Jump to search

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

local p = {}

function p.changeCursor(frame)
    local args = frame:getParent().args

    local imageName = args.image
    local selector = args.selector or 'body'
    local offsetX = args.offsetX or ''
    local offsetY = args.offsetY or ''
    local fallback = args.fallback or 'auto'

    -- Validate required image name
    if not imageName or imageName:match('^%s*$') then
        -- Using mw.log for server-side logging, less intrusive than HTML comments for this case.
        mw.log('Module:CustomCursor: Warning: Image name parameter was missing or empty.')
        return '' -- Return empty, no CSS generated
    end

    -- Get the title object for the image
    -- mw.title.new can return nil if imageName is invalid (e.g., contains illegal characters)
    local imageTitle = mw.title.new(imageName, 'File')

    -- CRITICAL CHECK: If imageTitle is nil, mw.title.new failed.
    if not imageTitle then
        -- Log the issue and return an HTML comment for debugging in the page source.
        mw.log('Module:CustomCursor: Error: mw.title.new returned nil for imageName: "' .. tostring(imageName) .. '". The image name might be invalid.')
        return ''
    end

    -- At this point, imageTitle should be a valid title object.
    -- Now attempt to get the file URL. This can return nil if the file doesn't exist.
    local imageUrl = imageTitle:getFileUrl()

    if not imageUrl then
        -- Log the issue and return an HTML comment.
        mw.log('Module:CustomCursor: Error: imageTitle:getFileUrl() returned nil for image: "' .. tostring(imageName) .. '". The file likely does not exist or is not accessible.')
        return ''
    end

    -- Construct the CSS cursor property
    local cursorValue = "url('" .. imageUrl .. "')"

    if offsetX ~= '' and offsetY ~= '' then
        if tonumber(offsetX) and tonumber(offsetY) then
            cursorValue = cursorValue .. " " .. offsetX .. " " .. offsetY
        else
            mw.log('Module:CustomCursor: Warning: Non-numeric offsetX or offsetY provided for image: ' .. imageName)
            -- Proceed without hotspot if values are invalid
        end
    end

    cursorValue = cursorValue .. ", " .. fallback

    -- Sanitize selector minimally
    if selector:match('[<>"%*%[%]={}]') and not (selector:match('^%s*body%s*$') or selector:match('^%s*%#[%w%-]+%s*$') or selector:match('^%s*%.[%w%-]+%s*$')) then
        mw.log('Module:CustomCursor: Warning: Potentially complex or unusual selector used: ' .. selector)
    end

    local cssRule = string.format('%s { cursor: %s; }', selector, cursorValue)

    return mw.html.create('style'):wikitext(cssRule):allDone()
end

return p