Module:NoteTransclude

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

local sectionExtractor = require('Module:ExtractSection')

local p = {}

local function findEndOfNoteContent(content)
    local endPos = mw.ustring.find(content, "}}%s*$")
    if endPos then
        return endPos + 2
    else
        return #content
    end
end

local function getNoteContent(content, section, field)
    local sectionContent = sectionExtractor.extractSection(content, section)
    if not sectionContent then
        return "Error: Section not found"
    end

    local noteStart, noteEnd = mw.ustring.find(sectionContent, "{{Note")
    if not noteStart then
        return "Error: Note template not found"
    end
    noteEnd = findEndOfNoteContent(sectionContent)

    if field == "Transcript" then
        local transcriptPattern = "|%s*Transcript%s*=%s*(.-)%s*|%s*Translation"
        local transcriptContent = mw.ustring.match(sectionContent, transcriptPattern)
        return transcriptContent or "Error: Transcript not found"
    elseif field == "Translation" then
        local translationStart = mw.ustring.find(sectionContent, "|%s*Translation%s*=%s*")
        if translationStart then
            local translationEnd = noteEnd
            local translationContent = mw.ustring.sub(sectionContent, translationStart, translationEnd)
            if translationContent then
                -- Remove leading "|Translation = "
                translationContent = mw.ustring.gsub(translationContent, "^%s*|%s*Translation%s*=%s*", "")
                -- Remove trailing "}}" if it's at the end of the string
                translationContent = mw.ustring.gsub(translationContent, "%s*}}$", "")
            end
            return translationContent or "Error: Translation not found"
        else
            return "Error: Translation field not found"
        end
    else
        return "Error: Invalid field. Use 'Transcript' or 'Translation'."
    end
end

function p.transclude(frame)
    local args = frame:getParent().args
    local page = args[1]
    local section = args[2]
    local field = args[3]

    if not (page and section and field) then
        return "Error: Missing parameters. Usage: {{NoteTransclude|Page|Section|Field}}"
    end

    local content = mw.title.new(page):getContent()
    if not content then
        return "Error: Page not found"
    end

    return frame:preprocess(getNoteContent(content, section, field))
end

return p