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

мНет описания правки
мНет описания правки
Метка: ручная отмена
 
(не показано 17 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Безопасная загрузка JSON из пространства Шаблонов
-- Извлечение аргументов
local function loadData(frame)
local function getArgs(frame)
     local dataParam = frame.args['данные'] or frame.args[1]
     local args = {}
    if not dataParam or dataParam == '' then
    if frame.getParent then
         error('Не указано имя базы данных или страница JSON (параметр 1 или |данные=)')
        local parent = frame:getParent()
        if parent and parent.args then
            for k, v in pairs(parent.args) do args[k] = v end
         end
     end
     end
   
     if frame.args then
    local dataPageTitle = dataParam
         for k, v in pairs(frame.args) do args[k] = v end
     if not mw.ustring.find(dataParam, ':') then
         dataPageTitle = 'Шаблон:Интерактивная схема ' .. dataParam .. '/data.json'
     end
     end
    return args
end
-- Безопасная очистка текста JSON
local function cleanJsonText(rawText)
    rawText = mw.ustring.gsub(rawText, '<noinclude>.-</noinclude>', '')
    rawText = string.gsub(rawText, '<!%-%-.-%-%->', '')
    rawText = string.gsub(rawText, '\194\160', ' ')
    rawText = string.gsub(rawText, '\194\173', '')
    return mw.text.trim(rawText)
end
-- Загрузка данных из data.json
local function loadData(args)
    local dataParam = args['данные'] or args[1] or 'Муроморского'
    dataParam = mw.text.trim(dataParam)
      
      
     -- Способ 1: Стандартная загрузка через mw.loadJsonData (если тип контента страницы = JSON)
     local cleanName = mw.ustring.gsub(dataParam, '^[Шш][Аа][Бб][Лл][Оо][Нн]:', '')
     local success, jsonData = pcall(mw.loadJsonData, dataPageTitle)
    cleanName = mw.ustring.gsub(cleanName, '^[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]:', '')
     if success and jsonData then
    cleanName = mw.ustring.gsub(cleanName, '/data%.json$', '')
        return jsonData
     cleanName = mw.ustring.gsub(cleanName, '%.json$', '')
     end
     cleanName = mw.ustring.gsub(cleanName, '^[Ии]нтерактивная схема%s*', '')
     cleanName = mw.text.trim(cleanName)
      
      
    -- Способ 2: Резервная загрузка текста и декодирование (если страница сохранена как wikitext)
     local candidates = {}
     local titleObj = mw.title.new(dataPageTitle)
     local function addCandidate(title)
     if titleObj and titleObj.exists then
         if title and title ~= '' then
        local rawText = titleObj:getContent()
             for _, existing in ipairs(candidates) do
         if rawText and rawText ~= '' then
                if existing == title then return end
             -- Очистка от возможных noinclude / комментариев
            rawText = mw.ustring.gsub(rawText, '<noinclude>.-</noinclude>', '')
            rawText = mw.ustring.gsub(rawText, '<!--.--->', '')
            rawText = mw.text.trim(rawText)
           
            local decodeSuccess, decodedData = pcall(mw.text.jsonDecode, rawText)
            if decodeSuccess and decodedData then
                return decodedData
            else
                error('Ошибка в синтаксисе JSON на странице [[' .. dataPageTitle .. ']]! Проверьте запятые и кавычки.')
             end
             end
            table.insert(candidates, title)
         end
         end
     end
     end
      
      
     error('Страница данных [[' .. dataPageTitle .. ']] не найдена. Убедитесь, что она создана.')
     addCandidate(dataParam)
end
    addCandidate('Шаблон:Интерактивная схема ' .. cleanName .. '/data.json')
    addCandidate('Шаблон:Интерактивная схема ' .. cleanName .. ' метрополитена/data.json')
    addCandidate('Шаблон:' .. cleanName .. '/data.json')
    addCandidate('Шаблон:' .. cleanName)
    addCandidate('Интерактивная схема ' .. cleanName .. '/data.json')
    addCandidate('Интерактивная схема ' .. cleanName .. ' метрополитена/data.json')
    addCandidate(cleanName .. '/data.json')
    addCandidate(cleanName)


-- Генерация кода <imagemap>
     local jsonErrors = {}
local function buildImageMap(jsonData, imageFile, width, defaultRadius)
     local radius = defaultRadius or '16'
    local mapText = 'Файл:' .. imageFile .. '|' .. width .. '|center|alt=' .. (jsonData.title or 'Схема скоростного транспорта Муроморска') .. '\n'
      
      
     for _, line in ipairs(jsonData.lines or {}) do
     for _, pageTitle in ipairs(candidates) do
         if line.box and line.article then
        local ok, data = pcall(mw.loadJsonData, pageTitle)
            mapText = mapText .. 'rect ' .. line.box .. ' [[' .. line.article .. '|' .. (line.name or line.article) .. ']]\n'
         if ok and type(data) == 'table' then
            return data
         end
         end
          
          
         for _, station in ipairs(line.stations or {}) do
         local titleObj = mw.title.new(pageTitle)
             if station.coords and station.article then
        if titleObj then
                 local stRadius = station.radius or radius
            local rawText = titleObj:getContent()
                 mapText = mapText .. 'circle ' .. station.coords .. ' ' .. stRadius .. ' [[' .. station.article .. '|' .. (station.name or station.article) .. ']]\n'
             if rawText and rawText ~= '' then
                rawText = cleanJsonText(rawText)
                 local decOk, decoded = pcall(mw.text.jsonDecode, rawText)
                 if decOk and type(decoded) == 'table' then
                    return decoded
                else
                    table.insert(jsonErrors, '[[' .. pageTitle .. ']] (' .. tostring(decoded) .. ')')
                end
             end
             end
         end
         end
     end
     end
      
      
     mapText = mapText .. 'desc none\n'
     if #jsonErrors > 0 then
     return mapText
        error('Ошибка в синтаксисе JSON:\n* ' .. table.concat(jsonErrors, '\n* '))
     end
   
    error('Страница данных не найдена ни по одному из путей:\n* [[' .. table.concat(candidates, ']]\n* [[') .. ']]')
end
end


-- Названия категорий транспорта
-- Парсер координат "X Y"
local function getModeLabel(mode)
local function parseCoords(str)
     local modes = {
    if not str then return nil, nil end
        metro = '🚇 Линии Муроморского метрополитена',
     local x, y = mw.ustring.match(str, '(%d+%.?%d*)%s+(%d+%.?%d*)')
        train = '🚆 Направления Мурской железной дороги (МЖД)',
     return tonumber(x), tonumber(y)
        other = '🚍 Прочие линии'
    }
     return modes[mode] or modes.other
end
end


-- Рендеринг схемы
-- Генерация интерактивной Canvas-схемы с панорамированием и управлением
function p.render(frame)
function p.canvas(frame)
     local args = frame:getParent().args
     local args = getArgs(frame)
     if not args['данные'] and not frame.args['данные'] then
    local data = loadData(args)
         args = frame.args
   
    local origW = tonumber(args['ширина_оригинала'] or 850) or 850
    local origH = tonumber(args['высота_оригинала'] or 620) or 620
   
    -- Кадрирование
    local cropX, cropY, cropW, cropH = nil, nil, nil, nil
     if args['кадрирование'] or args['crop'] then
        local c1, c2, c3, c4 = mw.ustring.match(args['кадрирование'] or args['crop'], '(%d+%.?%d*)%s+(%d+%.?%d*)%s+(%d+%.?%d*)%s+(%d+%.?%d*)')
        cropX, cropY, cropW, cropH = tonumber(c1), tonumber(c2), tonumber(c3), tonumber(c4)
    elseif args['фокус'] or args['focus'] then
         local fx, fy = parseCoords(args['фокус'] or args['focus'])
        local fw = tonumber(args['ширина_фокуса'] or 320) or 320
        local fh = tonumber(args['высота_фокуса'] or 240) or 240
        if fx and fy then
            cropX = math.max(0, fx - fw / 2)
            cropY = math.max(0, fy - fh / 2)
            cropW = fw
            cropH = fh
        end
     end
     end
    local jsonData = loadData(frame)
    local imageFile = args['файл'] or jsonData.image or 'Схема_Муроморского_метрополитена.png'
    local width = args['ширина'] or jsonData.width or '850px'
    local caption = args['подпись'] or jsonData.caption or 'Интерактивная схема линий Муроморска'
    local defaultRadius = args['радиус'] or jsonData.defaultRadius or '16'
      
      
     local root = mw.html.create('div')
     local targetW = cropW or origW
         :addClass('ts-transport-scheme')
    local targetH = cropH or origH
   
    local boxW = tonumber(args['ширина_блока'] or args['ширина_карточки'] or args['ширина'])
    local scale = tonumber(args['масштаб'] or args['scale'])
   
    local isScrollMode = (args['прокрутка'] == 'да' or args['скролл'] == 'да' or args['scroll'] == 'yes')
   
    if not isScrollMode and boxW and not scale then
        scale = boxW / targetW
    elseif not scale then
        scale = 1.0
    end
   
    local finalBoxW = boxW or (targetW * scale)
    local finalBoxH = tonumber(args['высота_блока'] or args['высота_карточки'] or args['высота']) or (targetH * scale)
   
    -- Внешний контейнер-вьюпорт с поддержкой перемещения клавиатурой и скролла
    local wrapper = mw.html.create('div')
         :addClass('ts-transport-map-viewport')
        :attr('tabindex', '0')
        :attr('title', 'Кликните для управления стрелками клавиатуры (← ↑ → ↓) или скролла мышью')
         :css({
         :css({
             ['clear'] = 'both',
             ['position'] = 'relative',
             ['margin'] = '1.2em auto',
             ['width'] = string.format('%.1fpx', finalBoxW),
             ['width'] = '100%',
            ['height'] = string.format('%.1fpx', finalBoxH),
             ['text-align'] = 'center'
             ['max-width'] = '100%',
             ['overflow'] = isScrollMode and 'auto' or 'hidden',
            ['scroll-behavior'] = 'smooth',
            ['overscroll-behavior'] = 'contain',
            ['-webkit-overflow-scrolling'] = 'touch',
            ['border-radius'] = '10px',
            ['border'] = args['без_рамки'] and 'none' or '1px solid #d0d7de',
            ['margin'] = (args['прижатие'] == 'лево' and '0 auto 0 0') or (args['прижатие'] == 'право' and '0 0 0 auto') or '0 auto',
            ['background-color'] = '#ffffff',
            ['background-image'] = 'radial-gradient(#e1e4e8 1px, transparent 1px)',
            ['background-size'] = '20px 20px',
            ['box-shadow'] = args['без_тени'] and 'none' or '0 2px 8px rgba(0,0,0,0.06)',
            ['outline'] = 'none',
            ['user-select'] = 'none'
         })
         })
 
       
     -- 1. Карточка карты с imagemap
    local shiftX = cropX or 0
     local mapCard = root:tag('div')
    local shiftY = cropY or 0
         :addClass('ts-transport-map-card')
   
     -- Внутренний холст схемы
     local canvas = wrapper:tag('div')
         :addClass('ts-html-transport-canvas')
         :css({
         :css({
             ['display'] = 'inline-block',
             ['position'] = isScrollMode and 'relative' or 'absolute',
             ['max-width'] = '100%',
             ['left'] = not isScrollMode and string.format('%.1fpx', -shiftX * scale) or '0',
             ['background'] = 'var(--background-color-base, #ffffff)',
             ['top'] = not isScrollMode and string.format('%.1fpx', -shiftY * scale) or '0',
             ['border'] = '1px solid var(--border-color-base, #d0d7de)',
             ['width'] = origW .. 'px',
             ['border-radius'] = '10px',
             ['height'] = origH .. 'px',
             ['padding'] = '10px',
             ['transform'] = (scale ~= 1.0 and not isScrollMode) and string.format('scale(%.4f)', scale) or 'none',
             ['box-shadow'] = '0 3px 12px rgba(0,0,0,0.06)'
             ['transform-origin'] = '0 0',
            ['font-family'] = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
         })
         })


     local mapContainer = mapCard:tag('div')
     -- Шапка/логотип
        :css({ ['overflow-x'] = 'auto', ['max-width'] = '100%' })
    if not (args['шапка'] == 'нет' or cropX ~= nil) then
 
         local header = canvas:tag('div')
    local imageMapContent = buildImageMap(jsonData, imageFile, width, defaultRadius)
    mapContainer:wikitext(frame:preprocess('{{#tag:imagemap|' .. imageMapContent .. '}}'))
 
    if caption ~= '' then
         mapCard:tag('div')
             :css({
             :css({
                 ['font-size'] = '12px',
                 ['position'] = 'absolute',
                 ['color'] = '#57606a',
                ['top'] = '16px',
                 ['margin-top'] = '8px',
                ['left'] = '18px',
                 ['padding-top'] = '6px',
                ['display'] = 'flex',
                 ['border-top'] = '1px dashed var(--border-color-base, #e1e4e8)'
                ['align-items'] = 'center',
                 ['gap'] = '10px',
                 ['z-index'] = '5',
                ['background'] = 'rgba(255,255,255,0.92)',
                 ['padding'] = '6px 12px',
                 ['border-radius'] = '8px',
                ['border'] = '1px solid #e1e4e8',
                ['box-shadow'] = '0 2px 6px rgba(0,0,0,0.04)'
             })
             })
             :wikitext('🗺 ' .. caption)
        header:tag('div')
             :css({
                ['width'] = '24px',
                ['height'] = '24px',
                ['background'] = '#ED1B24',
                ['color'] = '#fff',
                ['font-weight'] = 'bold',
                ['font-size'] = '13px',
                ['display'] = 'flex',
                ['align-items'] = 'center',
                ['justify-content'] = 'center',
                ['border-radius'] = '50%'
            }):wikitext('M')
        header:tag('div')
            :css({['text-align'] = 'left'})
            :tag('div'):css({['font-weight'] = 'bold', ['font-size'] = '13px', ['color'] = '#1f2328'}):wikitext(data.title or 'Скоростной транспорт'):done()
            :tag('div'):css({['font-size'] = '10px', ['color'] = '#57606a', ['text-transform'] = 'uppercase', ['letter-spacing'] = '0.5px'}):wikitext('Интерактивная схема линий'):done()
     end
     end


     -- 2. Легенда линий
     -- Индикатор подсказки управления
     if jsonData.lines and #jsonData.lines > 0 then
     if isScrollMode then
         local legend = root:tag('div')
         wrapper:tag('div')
            :addClass('ts-transport-lines-legend')
             :css({
             :css({
                 ['margin'] = '12px auto',
                 ['position'] = 'sticky',
                 ['max-width'] = '950px',
                 ['top'] = '10px',
                 ['padding'] = '8px 12px',
                ['left'] = 'calc(100% - 130px)',
                 ['background'] = '#f6f8fa',
                ['width'] = '115px',
                 ['z-index'] = '10',
                 ['background'] = 'rgba(255,255,255,0.88)',
                 ['border'] = '1px solid #d0d7de',
                 ['border'] = '1px solid #d0d7de',
                 ['border-radius'] = '8px'
                 ['border-radius'] = '16px',
            })
                 ['padding'] = '3px 8px',
 
                 ['font-size'] = '10px',
        legend:tag('div')
            :css({
                 ['font-size'] = '11px',
                 ['font-weight'] = 'bold',
                 ['color'] = '#57606a',
                 ['color'] = '#57606a',
                ['text-transform'] = 'uppercase',
                ['margin-bottom'] = '6px',
                ['letter-spacing'] = '0.5px'
            })
            :wikitext(jsonData.legendTitle or 'Линии скоростного транспорта')
        local legendBadges = legend:tag('div')
            :css({
                 ['display'] = 'flex',
                 ['display'] = 'flex',
                 ['flex-wrap'] = 'wrap',
                 ['align-items'] = 'center',
                 ['justify-content'] = 'center',
                 ['gap'] = '4px',
                 ['gap'] = '5px'
                ['pointer-events'] = 'none',
                ['box-shadow'] = '0 1px 4px rgba(0,0,0,0.05)',
                 ['backdrop-filter'] = 'blur(2px)'
             })
             })
 
             :wikitext('⌨ ⇄ ⇅ Скролл')
        for _, line in ipairs(jsonData.lines) do
            local badge = legendBadges:tag('span')
                :css({
                    ['display'] = 'inline-flex',
                    ['align-items'] = 'center',
                    ['padding'] = '2px 8px 2px 4px',
                    ['background'] = '#ffffff',
                    ['border'] = '1px solid #d0d7de',
                    ['border-radius'] = '20px',
                    ['font-size'] = '12px'
                })
 
             badge:tag('span')
                :css({
                    ['display'] = 'inline-flex',
                    ['align-items'] = 'center',
                    ['justify-content'] = 'center',
                    ['min-width'] = '16px',
                    ['height'] = '16px',
                    ['padding'] = '0 4px',
                    ['border-radius'] = '999px',
                    ['background-color'] = line.color or '#888888',
                    ['color'] = line.textColor or '#ffffff',
                    ['font-size'] = '9.5px',
                    ['font-weight'] = 'bold',
                    ['margin-right'] = '6px'
                })
                :wikitext(line.symbol or line.number or '•')
 
            badge:tag('span')
                :wikitext('[[' .. (line.article or '') .. '|' .. (line.displayName or line.name or line.article or '') .. ']]')
        end
     end
     end


     -- 3. Каталог станций
     if data.lines then
    if jsonData.lines and #jsonData.lines > 0 then
        -- 1. Слой путей
        local listCard = root:tag('div')
        for _, line in ipairs(data.lines) do
             :addClass('mw-collapsible toccolours')
            local color = line.color or '#888888'
             :css({
             local stations = line.stations or {}
                ['margin'] = '12px auto 0 auto',
              
                 ['max-width'] = '950px',
            for i = 1, #stations - 1 do
                 ['text-align'] = 'left',
                 local st1, st2 = stations[i], stations[i+1]
                 ['background'] = 'var(--background-color-neutral-subtle, #f8f9fa)',
                 local x1, y1 = parseCoords(st1.coords)
                 ['border'] = '1px solid var(--border-color-base, #d0d7de)',
                 local x2, y2 = parseCoords(st2.coords)
                ['border-radius'] = '8px',
                  
                ['overflow'] = 'hidden'
                if x1 and y1 and x2 and y2 then
            })
                    local dx = x2 - x1
 
                    local dy = y2 - y1
        listCard:tag('div')
                    local length = math.sqrt(dx * dx + dy * dy)
            :css({
                    local angle = math.deg(math.atan2(dy, dx))
                ['font-weight'] = 'bold',
                    local isFuture = (st1.future and st2.future)
                ['font-size'] = '13.5px',
                   
                ['background'] = 'linear-gradient(180deg, #f6f8fa 0%, #eaeef2 100%)',
                    canvas:tag('div')
                ['padding'] = '9px 14px',
                        :css({
                ['border-bottom'] = '1px solid var(--border-color-base, #d0d7de)'
                            ['position'] = 'absolute',
            })
                            ['left'] = x1 .. 'px',
            :wikitext(jsonData.listTitle or '📋 Реестр станций метрополитена и МЖД')
                            ['top'] = (y1 - 3) .. 'px',
 
                            ['width'] = length .. 'px',
        local listContent = listCard:tag('div')
                            ['height'] = isFuture and '0px' or '6px',
            :addClass('mw-collapsible-content')
                            ['background-color'] = isFuture and 'transparent' or color,
            :css({
                            ['border-top'] = isFuture and ('5px dashed ' .. color) or 'none',
                ['padding'] = '14px 18px',
                            ['transform-origin'] = '0 50%',
                ['column-width'] = '20em',
                            ['transform'] = 'rotate(' .. angle .. 'deg)',
                ['column-gap'] = '2em',
                            ['border-radius'] = '3px',
                ['column-rule'] = '1px solid #e1e4e8',
                            ['z-index'] = '1',
                ['font-size'] = '13px',
                            ['pointer-events'] = 'none'
                ['line-height'] = '1.7'
                        })
            })
                 end
 
        local currentMode = nil
        local listWikitext = ''
 
        for _, line in ipairs(jsonData.lines) do
            local mode = line.mode or 'other'
            if mode ~= currentMode then
                currentMode = mode
                 listWikitext = listWikitext .. "\n; " .. getModeLabel(mode) .. "\n"
             end
             end
        end


            listWikitext = listWikitext .. "* '''[[" .. (line.article or '') .. '|' .. (line.name or line.article or '') .. "]]'''\n"
        -- 2. Слой станций и подписей
             for _, station in ipairs(line.stations or {}) do
        for _, line in ipairs(data.lines) do
                 local badge = "<span style='display:inline-flex;align-items:center;justify-content:center;min-width:14px;height:14px;padding:0 3px;border-radius:999px;background:" .. (line.color or '#888') .. ";color:" .. (line.textColor or '#fff') .. ";font-size:9px;font-weight:bold;margin-right:4px;'>" .. (line.symbol or line.number or '•') .. "</span>"
            local color = line.color or '#888888'
                listWikitext = listWikitext .. '** ' .. badge .. ' [[' .. station.article .. '|' .. (station.name or station.article) .. ']]'
           
                if station.transfer then
             for _, st in ipairs(line.stations or {}) do
                    listWikitext = listWikitext .. " <small style='color:#57606a;'>(" .. station.transfer .. ")</small>"
                 local x, y = parseCoords(st.coords)
                end
                if x and y then
                if station.future then
                    local name = st.name or st.article or ''
                     listWikitext = listWikitext .. " <small style='color:#8c959f; font-style:italic;'>(строит.)</small>"
                    local article = st.article or name
                    local isFuture = (st.future == true)
                   
                    local node = canvas:tag('div')
                        :css({
                            ['position'] = 'absolute',
                            ['left'] = (x - 7) .. 'px',
                            ['top'] = (y - 7) .. 'px',
                            ['width'] = '14px',
                            ['height'] = '14px',
                            ['border-radius'] = '50%',
                            ['background-color'] = '#ffffff',
                            ['border'] = isFuture and ('2.5px dashed ' .. color) or ('3px solid ' .. color),
                            ['box-sizing'] = 'border-box',
                            ['box-shadow'] = '0 1px 3px rgba(0,0,0,0.25)',
                            ['z-index'] = '3',
                            ['cursor'] = 'pointer'
                        })
                    node:wikitext('[[' .. article .. '|<span style="display:block;width:100%;height:100%;" title="' .. name .. '"></span>]]')
                   
                    local isRightSide = (x >= (origW / 2))
                    local label = canvas:tag('div')
                        :css({
                            ['position'] = 'absolute',
                            ['left'] = isRightSide and ((x + 11) .. 'px') or ((x - 11) .. 'px'),
                            ['top'] = y .. 'px',
                            ['transform'] = isRightSide and 'translateY(-50%)' or 'translate(-100%, -50%)',
                            ['text-align'] = isRightSide and 'left' or 'right',
                            ['white-space'] = 'nowrap',
                            ['font-size'] = '11.5px',
                            ['font-weight'] = '500',
                            ['z-index'] = '4',
                            ['text-shadow'] = '0 0 3px #ffffff, 0 0 3px #ffffff, 0 0 3px #ffffff, 0 0 4px #ffffff'
                        })
                   
                     local labelStyle = isFuture and 'color: #6e7781; font-style: italic; text-decoration: none;' or 'color: #1f2328; text-decoration: none;'
                    label:wikitext('[[' .. article .. '|<span style="' .. labelStyle .. '">' .. name .. '</span>]]')
                 end
                 end
                listWikitext = listWikitext .. '\n'
             end
             end
         end
         end
        listContent:wikitext(listWikitext)
     end
     end


     return tostring(root)
     return tostring(wrapper)
end
end


return p
return p