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

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


-- Извлечение аргументов вызова
-- Извлечение аргументов
local function getArgs(frame)
local function getArgs(frame)
     local args = {}
     local args = {}
Строка 14: Строка 14:
     end
     end
     return args
     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
end


Строка 19: Строка 28:
local function loadData(args)
local function loadData(args)
     local dataParam = args['данные'] or args[1] or 'Муроморского'
     local dataParam = args['данные'] or args[1] or 'Муроморского'
     local candidates = {
    dataParam = mw.text.trim(dataParam)
         dataParam,
   
         'Шаблон:Интерактивная схема ' .. dataParam .. ' метрополитена/data.json',
    local cleanName = mw.ustring.gsub(dataParam, '^[Шш][Аа][Бб][Лл][Оо][Нн]:', '')
        'Шаблон:Интерактивная схема ' .. dataParam .. '/data.json',
    cleanName = mw.ustring.gsub(cleanName, '^[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]:', '')
        'Шаблон:' .. dataParam .. '/data.json',
    cleanName = mw.ustring.gsub(cleanName, '/data%.json$', '')
        dataParam .. '/data.json'
    cleanName = mw.ustring.gsub(cleanName, '%.json$', '')
     }
    cleanName = mw.ustring.gsub(cleanName, '^[Ии]нтерактивная схема%s*', '')
    cleanName = mw.text.trim(cleanName)
   
     local candidates = {}
    local function addCandidate(title)
         if title and title ~= '' then
            for _, existing in ipairs(candidates) do
                if existing == title then return end
            end
            table.insert(candidates, title)
         end
    end
   
    addCandidate(dataParam)
    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)
 
     local jsonErrors = {}
      
      
     for _, title in ipairs(candidates) do
     for _, pageTitle in ipairs(candidates) do
         local success, jsonData = pcall(mw.loadJsonData, title)
         local ok, data = pcall(mw.loadJsonData, pageTitle)
         if success and jsonData then return jsonData end
         if ok and type(data) == 'table' then
            return data
        end
          
          
         local titleObj = mw.title.new(title)
         local titleObj = mw.title.new(pageTitle)
         if titleObj and titleObj.exists then
         if titleObj then
             local raw = titleObj:getContent()
             local rawText = titleObj:getContent()
             if raw and raw ~= '' then
             if rawText and rawText ~= '' then
                 raw = mw.ustring.gsub(raw, '<noinclude>.-</noinclude>', '')
                 rawText = cleanJsonText(rawText)
                raw = mw.ustring.gsub(raw, '<!--.-?-->', '')
                 local decOk, decoded = pcall(mw.text.jsonDecode, rawText)
                 local ok, decoded = pcall(mw.text.jsonDecode, mw.text.trim(raw))
                 if decOk and type(decoded) == 'table' then
                 if ok and decoded then return decoded end
                    return decoded
                else
                    table.insert(jsonErrors, '[[' .. pageTitle .. ']] (' .. tostring(decoded) .. ')')
                end
             end
             end
         end
         end
     end
     end
     error('Страница данных JSON не найдена: ' .. dataParam)
   
    if #jsonErrors > 0 then
        error('Ошибка в синтаксисе JSON:\n* ' .. table.concat(jsonErrors, '\n* '))
    end
   
     error('Страница данных не найдена ни по одному из путей:\n* [[' .. table.concat(candidates, ']]\n* [[') .. ']]')
end
end


Строка 52: Строка 94:
end
end


-- Генерация карты на чистом HTML/CSS
-- Генерация интерактивной Canvas-схемы с панорамированием и управлением
function p.canvas(frame)
function p.canvas(frame)
     local args = getArgs(frame)
     local args = getArgs(frame)
     local data = loadData(args)
     local data = loadData(args)
      
      
     local mapWidth = tonumber(args['ширина'] or 850) or 850
     local origW = tonumber(args['ширина_оригинала'] or 850) or 850
     local mapHeight = tonumber(args['высота'] or 620) or 620
     local origH = tonumber(args['высота_оригинала'] or 620) or 620
      
      
     local out = mw.html.create('div')
     -- Кадрирование
         :addClass('ts-html-transport-map')
    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
   
    local targetW = cropW or origW
    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({
             ['position'] = 'relative',
             ['position'] = 'relative',
             ['width'] = mapWidth .. 'px',
             ['width'] = string.format('%.1fpx', finalBoxW),
             ['height'] = mapHeight .. 'px',
             ['height'] = string.format('%.1fpx', finalBoxH),
             ['max-width'] = '100%',
             ['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-color'] = '#ffffff',
             ['background-image'] = 'radial-gradient(#e1e4e8 1px, transparent 1px)',
             ['background-image'] = 'radial-gradient(#e1e4e8 1px, transparent 1px)',
             ['background-size'] = '24px 24px',
             ['background-size'] = '20px 20px',
             ['border'] = '1px solid #d0d7de',
             ['box-shadow'] = args['без_тени'] and 'none' or '0 2px 8px rgba(0,0,0,0.06)',
             ['border-radius'] = '10px',
            ['outline'] = 'none',
             ['overflow'] = 'hidden',
             ['user-select'] = 'none'
             ['margin'] = '0 auto',
        })
             ['user-select'] = 'none',
       
             ['box-shadow'] = '0 3px 10px rgba(0,0,0,0.04)',
    local shiftX = cropX or 0
    local shiftY = cropY or 0
   
    -- Внутренний холст схемы
    local canvas = wrapper:tag('div')
        :addClass('ts-html-transport-canvas')
        :css({
            ['position'] = isScrollMode and 'relative' or 'absolute',
             ['left'] = not isScrollMode and string.format('%.1fpx', -shiftX * scale) or '0',
             ['top'] = not isScrollMode and string.format('%.1fpx', -shiftY * scale) or '0',
             ['width'] = origW .. 'px',
             ['height'] = origH .. 'px',
            ['transform'] = (scale ~= 1.0 and not isScrollMode) and string.format('scale(%.4f)', scale) or 'none',
            ['transform-origin'] = '0 0',
             ['font-family'] = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
             ['font-family'] = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
         })
         })


     -- Плашка логотипа в левом верхнем углу
     -- Шапка/логотип
     local header = out:tag('div')
     if not (args['шапка'] == 'нет' or cropX ~= nil) then
        :css({
        local header = canvas:tag('div')
            ['position'] = 'absolute',
            :css({
            ['top'] = '16px',
                ['position'] = 'absolute',
            ['left'] = '18px',
                ['top'] = '16px',
            ['display'] = 'flex',
                ['left'] = '18px',
            ['align-items'] = 'center',
                ['display'] = 'flex',
            ['gap'] = '10px',
                ['align-items'] = 'center',
            ['z-index'] = '5',
                ['gap'] = '10px',
            ['background'] = 'rgba(255,255,255,0.92)',
                ['z-index'] = '5',
            ['padding'] = '6px 12px',
                ['background'] = 'rgba(255,255,255,0.92)',
            ['border-radius'] = '8px',
                ['padding'] = '6px 12px',
            ['border'] = '1px solid #e1e4e8',
                ['border-radius'] = '8px',
            ['box-shadow'] = '0 2px 6px rgba(0,0,0,0.04)'
                ['border'] = '1px solid #e1e4e8',
        })
                ['box-shadow'] = '0 2px 6px rgba(0,0,0,0.04)'
    header:tag('div')
            })
        :css({
        header:tag('div')
            ['width'] = '24px',
            :css({
            ['height'] = '24px',
                ['width'] = '24px',
            ['background'] = '#ED1B24',
                ['height'] = '24px',
            ['color'] = '#fff',
                ['background'] = '#ED1B24',
            ['font-weight'] = 'bold',
                ['color'] = '#fff',
            ['font-size'] = '13px',
                ['font-weight'] = 'bold',
            ['display'] = 'flex',
                ['font-size'] = '13px',
            ['align-items'] = 'center',
                ['display'] = 'flex',
            ['justify-content'] = 'center',
                ['align-items'] = 'center',
            ['border-radius'] = '50%'
                ['justify-content'] = 'center',
        }):wikitext('M')
                ['border-radius'] = '50%'
    header:tag('div')
            }):wikitext('M')
        :css({['text-align'] = 'left'})
        header:tag('div')
        :tag('div'):css({['font-weight'] = 'bold', ['font-size'] = '13px', ['color'] = '#1f2328'}):wikitext(data.title or 'Муроморский скоростной транспорт'):done()
            :css({['text-align'] = 'left'})
        :tag('div'):css({['font-size'] = '10px', ['color'] = '#57606a', ['text-transform'] = 'uppercase', ['letter-spacing'] = '0.5px'}):wikitext('Интерактивная схема линий'):done()
            :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
 
    -- Индикатор подсказки управления
    if isScrollMode then
        wrapper:tag('div')
            :css({
                ['position'] = 'sticky',
                ['top'] = '10px',
                ['left'] = 'calc(100% - 130px)',
                ['width'] = '115px',
                ['z-index'] = '10',
                ['background'] = 'rgba(255,255,255,0.88)',
                ['border'] = '1px solid #d0d7de',
                ['border-radius'] = '16px',
                ['padding'] = '3px 8px',
                ['font-size'] = '10px',
                ['color'] = '#57606a',
                ['display'] = 'flex',
                ['align-items'] = 'center',
                ['gap'] = '4px',
                ['pointer-events'] = 'none',
                ['box-shadow'] = '0 1px 4px rgba(0,0,0,0.05)',
                ['backdrop-filter'] = 'blur(2px)'
            })
            :wikitext('⌨ ⇄ ⇅ Скролл')
    end


     if data.lines then
     if data.lines then
         -- 1. Слой путей (линий между станциями)
         -- 1. Слой путей
         for _, line in ipairs(data.lines) do
         for _, line in ipairs(data.lines) do
             local color = line.color or '#888888'
             local color = line.color or '#888888'
Строка 131: Строка 257:
                     local isFuture = (st1.future and st2.future)
                     local isFuture = (st1.future and st2.future)
                      
                      
                     local track = out:tag('div')
                     canvas:tag('div')
                         :css({
                         :css({
                             ['position'] = 'absolute',
                             ['position'] = 'absolute',
Строка 161: Строка 287:
                     local isFuture = (st.future == true)
                     local isFuture = (st.future == true)
                      
                      
                    -- Кружок станции
                     local node = canvas:tag('div')
                     local node = out:tag('div')
                         :css({
                         :css({
                             ['position'] = 'absolute',
                             ['position'] = 'absolute',
Строка 179: Строка 304:
                     node:wikitext('[[' .. article .. '|<span style="display:block;width:100%;height:100%;" title="' .. name .. '"></span>]]')
                     node:wikitext('[[' .. article .. '|<span style="display:block;width:100%;height:100%;" title="' .. name .. '"></span>]]')
                      
                      
                    -- Текстовая подпись станции
                     local isRightSide = (x >= (origW / 2))
                     local isRightSide = (x >= 430)
                     local label = canvas:tag('div')
                     local label = out:tag('div')
                         :css({
                         :css({
                             ['position'] = 'absolute',
                             ['position'] = 'absolute',
Строка 202: Строка 326:
     end
     end


     return tostring(out)
     return tostring(wrapper)
end
end


return p
return p