Модуль:ТранспортнаяСхема: различия между версиями

мНет описания правки
мНет описания правки
Строка 1: Строка 1:
local p = {}
local p = {}


-- Извлечение аргументов вызова
-- Извлечение аргументов
local function getArgs(frame)
local function getArgs(frame)
     local args = {}
     local args = {}
Строка 16: Строка 16:
end
end


-- Умная загрузка JSON с автоматическим перебором вариантов названий
-- Загрузка JSON данных
local function loadData(args)
local function loadData(args)
     local dataParam = args['данные'] or args[1]
     local dataParam = args['данные'] or args[1]
Строка 30: Строка 30:
         table.insert(candidates, 'Шаблон:Интерактивная схема ' .. dataParam .. '/data.json')
         table.insert(candidates, 'Шаблон:Интерактивная схема ' .. dataParam .. '/data.json')
         table.insert(candidates, 'Шаблон:' .. dataParam .. '/data.json')
         table.insert(candidates, 'Шаблон:' .. dataParam .. '/data.json')
        table.insert(candidates, dataParam .. '/data.json')
         table.insert(candidates, dataParam)
         table.insert(candidates, dataParam)
     end
     end
      
      
     for _, dataPageTitle in ipairs(candidates) do
     for _, title in ipairs(candidates) do
        -- Попытка быстрой загрузки встроенным парсером JSON
         local success, jsonData = pcall(mw.loadJsonData, title)
         local success, jsonData = pcall(mw.loadJsonData, dataPageTitle)
         if success and jsonData then return jsonData end
         if success and jsonData then
            return jsonData
        end
          
          
        -- Попытка ручной загрузки текста страницы
         local titleObj = mw.title.new(title)
         local titleObj = mw.title.new(dataPageTitle)
         if titleObj and titleObj.exists then
         if titleObj and titleObj.exists then
             local rawText = titleObj:getContent()
             local raw = titleObj:getContent()
             if rawText and rawText ~= '' then
             if raw and raw ~= '' then
                 rawText = mw.ustring.gsub(rawText, '<noinclude>.-</noinclude>', '')
                 raw = mw.ustring.gsub(raw, '<noinclude>.-</noinclude>', '')
                 rawText = mw.ustring.gsub(rawText, '<!--.-?-->', '')
                 raw = mw.ustring.gsub(raw, '<!--.-?-->', '')
                rawText = mw.text.trim(rawText)
                 local ok, decoded = pcall(mw.text.jsonDecode, mw.text.trim(raw))
               
                 if ok and decoded then return decoded end
                 local decodeSuccess, decodedData = pcall(mw.text.jsonDecode, rawText)
                 if decodeSuccess and decodedData then
                    return decodedData
                else
                    error('Ошибка в синтаксисе JSON на странице [[' .. dataPageTitle .. ']]!')
                end
             end
             end
         end
         end
     end
     end
   
     error('Страница данных не найдена: ' .. dataParam)
     error('Страница данных не найдена. Проверены следующие пути:\n* [[' .. table.concat(candidates, ']]\n* [[') .. ']]')
end
 
-- Функция парсинга координат "X Y"
local function parseCoords(str)
    if not str then return nil, nil end
    local x, y = mw.ustring.match(str, '(%d+%.?%d*)%s+(%d+%.?%d*)')
    return tonumber(x), tonumber(y)
end
end


-- Генерация только ImageMap карты
-- Главная функция отрисовки векторной схемы
function p.map(frame)
function p.vector(frame)
     local args = getArgs(frame)
     local args = getArgs(frame)
     local jsonData = loadData(args)
     local data = loadData(args)
      
      
     local file = args['файл'] or args['изображение'] or jsonData.file or 'Схема_Муроморского_метрополитена.png'
     local width = tonumber(args['ширина_svg'] or 850) or 850
     local width = args['ширина'] or jsonData.width or '850px'
     local height = tonumber(args['высота_svg'] or 620) or 620
     local alt = args['alt'] or args['название'] or jsonData.title or 'Схема скоростного транспорта'
     local viewBox = args['viewbox'] or ('0 0 ' .. width .. ' ' .. height)
    local defaultRadius = args['радиус'] or jsonData.defaultRadius or '16'
      
      
     local mapText = 'Файл:' .. file .. '|' .. width .. '|center|alt=' .. alt .. '\n'
     local svg = {}
    mapText = mapText .. '# Автоматически сформированная разметка станций\n'
    table.insert(svg, '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' .. viewBox .. '" width="100%" height="auto" style="max-width:' .. width .. 'px; background:#ffffff; border-radius:8px; font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif; user-select:none;">')
      
      
     if jsonData.lines then
     -- Стили подсветки и анимации при наведении (CSS)
        for _, line in ipairs(jsonData.lines) do
    table.insert(svg, '<style>')
            -- Зона плашки линии (если задан box)
    table.insert(svg, '.ts-v-line { transition: opacity 0.25s ease, stroke-width 0.2s ease; cursor: pointer; }')
            if line.box and line.article then
    table.insert(svg, '.ts-v-station { transition: transform 0.2s ease, r 0.2s ease; cursor: pointer; }')
                mapText = mapText .. 'rect ' .. line.box .. ' [[' .. line.article .. '|' .. (line.name or line.article) .. ']]\n'
    table.insert(svg, '.ts-v-station:hover circle { r: 6.5px; stroke-width: 3.5px; }')
    table.insert(svg, '.ts-v-label { font-size: 11px; fill: #24292f; font-weight: 500; pointer-events: all; text-shadow: 0 0 3px #ffffff, 0 0 3px #ffffff, 0 0 3px #ffffff; transition: fill 0.2s ease; }')
    table.insert(svg, '.ts-v-label:hover { fill: #0969da; font-weight: bold; }')
    table.insert(svg, 'svg:hover .ts-v-group:not(:hover) { opacity: 0.35; }')
    table.insert(svg, '.ts-v-group { transition: opacity 0.25s ease; }')
    table.insert(svg, '</style>')
 
    -- 1. Слой сетки/фона (декоративный)
    table.insert(svg, '<rect width="100%" height="100%" fill="#fafbfc" rx="8" />')
 
    -- 2. Слой линий и путей
    if data.lines then
        for i, line in ipairs(data.lines) do
            local color = line.color or '#888888'
            local points = {}
            local futurePoints = {}
           
            table.insert(svg, '<g class="ts-v-group ts-v-line-' .. (line.number or i) .. '">')
           
            -- Сбор координат станций
            if line.stations then
                for _, st in ipairs(line.stations) do
                    local x, y = parseCoords(st.coords)
                    if x and y then
                        table.insert(points, x .. ',' .. y)
                    end
                end
             end
             end
              
              
             -- Дополнительные полигоны линии
             -- Отрисовка основной сплошной трассы
             if line.shapes then
             if #points > 1 then
                 for _, shape in ipairs(line.shapes) do
                 table.insert(svg, '<polyline class="ts-v-line" points="' .. table.concat(points, ' ') .. '" fill="none" stroke="' .. color .. '" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round" />')
                    mapText = mapText .. shape .. '\n'
                end
             end
             end
              
              
             -- Станции линии
             -- Отрисовка станций и подписей
             if line.stations then
             if line.stations then
                 for _, st in ipairs(line.stations) do
                 for _, st in ipairs(line.stations) do
                     if st.coords and st.article then
                     local x, y = parseCoords(st.coords)
                         local r = st.radius or defaultRadius
                    if x and y then
                         mapText = mapText .. 'circle ' .. st.coords .. ' ' .. r .. ' [[' .. st.article .. '|' .. (st.name or st.article) .. ']]\n'
                        local stName = st.name or st.article or ''
                         local article = st.article or stName
                        local isFuture = st.future == true
                          
                        table.insert(svg, '<a href="/wiki/' .. mw.uri.encode(article, 'WIKI') .. '" title="' .. mw.text.nowiki(stName) .. '">')
                        table.insert(svg, '<g class="ts-v-station">')
                       
                        -- Кружок станции
                        if isFuture then
                            table.insert(svg, '<circle cx="' .. x .. '" cy="' .. y .. '" r="4.5" fill="#ffffff" stroke="' .. color .. '" stroke-width="2.5" stroke-dasharray="2,2" />')
                        else
                            table.insert(svg, '<circle cx="' .. x .. '" cy="' .. y .. '" r="5" fill="#ffffff" stroke="' .. color .. '" stroke-width="3" />')
                        end
                       
                        -- Текстовая подпись станции (с небольшим смещением)
                        local textOffset = (x > (width / 2)) and (x + 9) or (x - 9)
                        local textAnchor = (x > (width / 2)) and 'start' or 'end'
                        local textColor = isFuture and '#6e7781' or '#24292f'
                       
                        table.insert(svg, '<text class="ts-v-label" x="' .. textOffset .. '" y="' .. (y + 3.5) .. '" text-anchor="' .. textAnchor .. '" fill="' .. textColor .. '">' .. mw.text.nowiki(stName) .. '</text>')
                        table.insert(svg, '</g></a>')
                     end
                     end
                 end
                 end
             end
             end
           
            table.insert(svg, '</g>')
         end
         end
     end
     end
   
 
     -- Дополнительные объекты (вокзалы, ж/д платформы и т.д.)
     table.insert(svg, '</svg>')
    local extras = {'Вокзалы', 'Ж/д станции', 'Терминалы', 'Аэропорты'}
     return table.concat(svg, '\n')
     for _, key in ipairs(extras) do
        if jsonData[key] then
            for _, item in ipairs(jsonData[key]) do
                if item[1] and item[2] then
                    mapText = mapText .. 'circle ' .. item[2] .. ' ' .. defaultRadius .. ' ' .. item[1] .. '\n'
                end
            end
        end
    end
   
    mapText = mapText .. 'desc none\n'
   
    return frame:preprocess('{{#tag:imagemap|' .. mapText .. '}}')
end
end


return p
return p