Модуль:ExtGraph

Материал из Поле цифровой дидактики

Для документации этого модуля может быть создана страница Модуль:ExtGraph/doc

local p = {}

function p.main(frame)
    local args = frame.args
    local csvUrl = args.url or 'YOUR_CSV_URL_HERE'
    local view = args.view or 'table'  -- 'table' или 'graph'

    -- Получаем данные из CSV через ExternalData
    local data, errors = mw.ext.externalData.getWebData {
        url = csvUrl,
        format = 'CSV with header'
    }

    if errors then
        return '<strong>Ошибка загрузки данных:</strong> ' .. table.concat(errors, '<br>')
    end

    if not data or #data == 0 then
        return 'Нет данных для отображения.'
    end

    local output = {}

    -- Таблица (по умолчанию)
    if view == 'table' or view == 'both' then
        local tableHtml = '{| class="wikitable sortable"\n! author_id !! pageid !! page_title !! category\n'
        for i, row in ipairs(data) do
            tableHtml = tableHtml .. string.format('|-\n| %s || %s || %s || %s\n',
                row.author_id or '',
                row.pageid or '',
                row.page_title or '',
                row.category or ''
            )
        end
        tableHtml = tableHtml .. '|}\n'
        table.insert(output, tableHtml)
    end

    -- Граф (второй режим)
    if view == 'graph' or view == 'both' then
        local graphNodes = {}
        local graphEdges = {}
        
        for i, row in ipairs(data) do
            local aid = row.author_id or ''
            local pid = row.pageid or ''
            
            if aid ~= '' and pid ~= '' then
                -- Узлы с shape
                graphNodes[aid] = 'author_' .. aid .. ' [shape=box,label="' .. aid .. '"]'
                graphNodes['page_' .. pid] = 'page_' .. pid .. ' [shape=ellipse,label="' .. pid .. '"]'
                
                -- Ребро
                table.insert(graphEdges, string.format('author_%s -> page_%s', aid, pid))
            end
        end

        local graphContent = 'digraph G {\n  layout = "neato";\n'
        
        -- Узлы
        for _, nodeDef in pairs(graphNodes) do
            graphContent = graphContent .. '  ' .. nodeDef .. ';\n'
        end
        
        -- Рёбра
        for _, edge in ipairs(graphEdges) do
            graphContent = graphContent .. '  ' .. edge .. ';\n'
        end
        
        graphContent = graphContent .. '}\n'
        table.insert(output, '<graphviz>' .. graphContent .. '</graphviz>')
    end

    return table.concat(output, '\n\n')
end

return p