| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- # Загрузка стилей компонента
- document.head.insertAdjacentHTML('beforeend','<style type="text/tailwindcss" page="Page">'+stylFns['app/pages/Page/index.styl']+'</style>')
- # Подключение markdown парсера
- marked = require 'marked'
- module.exports =
- name: 'Page'
- render: (new Function '_ctx', '_cache', renderFns['app/pages/Page/index.pug'])()
-
- data: ->
- page: null
- loading: true
- error: null
- notFound: false
- pageSettings: {}
-
- computed:
- # Текущий язык из глобального состояния
- currentLanguage: ->
- return _.currentLanguage || 'ru'
-
- # Настройки сайта из глобального состояния
- siteSettings: ->
- return _.appState?.siteSettings || {}
-
- # Обработанный markdown контент
- processedContent: ->
- if not @page?.content
- return ''
-
- # Получаем контент для текущего языка
- content = @getMultilingualText(@page.content, '')
- return @processMarkdown(content)
-
- # Мета-данные для SEO
- pageMeta: ->
- if not @page
- return {}
-
- return {
- title: @getMultilingualText(@page.seo?.title, @getMultilingualText(@page.title, '')),
- description: @getMultilingualText(@page.seo?.description, @getMultilingualText(@page.excerpt, '')),
- keywords: @getMultilingualText(@page.seo?.keywords, []).join(', ')
- }
-
- beforeMount: ->
- @loadPageSettings()
- @loadPageData()
-
- watch:
- '$route.params.slug': ->
- @loadPageData()
-
- 'currentLanguage': ->
- @loadPageData()
-
- methods:
- # Загрузка настроек страниц
- loadPageSettings: ->
- @pageSettings = _.appState?.siteSettings?.pages || {
- urls: {
- about: '/about'
- contacts: '/contacts'
- privacy: '/privacy'
- terms: '/terms'
- }
- components: {
- about: 'AboutPage'
- contacts: 'ContactsPage'
- }
- strings: {
- not_found: ['Страница не найдена', 'Page not found', 'Саҳифа ёфт нашуд']
- back_to_home: ['Вернуться на главную', 'Back to home', 'Бозгашт ба саҳифаи асосӣ']
- loading: ['Загрузка...', 'Loading...', 'Бор шуда истодааст...']
- }
- }
-
- # Загрузка данных страницы
- loadPageData: ->
- @loading = true
- @error = null
- @notFound = false
-
- slug = @$route.params.slug
- if not slug
- @error = "Не указан slug страницы"
- @loading = false
- return
-
- @loadPageBySlug(slug).then (page) =>
- if page
- @.page = page
- @updatePageMeta()
- else
- @.notFound = true
- @loading = false
- .catch (error) =>
- @error = "Ошибка загрузки страницы: "+error
- @loading = false
-
- # Поиск страницы по slug
- loadPageBySlug: (slug) ->
- return new Promise (resolve, reject) =>
- try
- # Ищем в кэше глобального состояния
- cachedPages = _.appState?.pages || []
- cachedPage = cachedPages.find (page) =>
- slugs = @getMultilingualText(page.slug, [])
- return slugs.includes(slug)
-
- if cachedPage
- resolve(cachedPage)
- return
-
- # Если нет в кэше, загружаем из базы
- AppDB.db.query('pages/by_slug_multilingual', {
- key: ['borbad.s5l.ru', @currentLanguage, slug]
- include_docs: true
- }).then (result) =>
- if result.rows.length > 0
- page = AppDB.processMultilingualDocument(result.rows[0].doc)
- # Сохраняем в кэш
- if not _.appState.pages
- _.appState.pages = []
- _.appState.pages.push(page)
- resolve(page)
- else
- resolve(null)
- .catch (error) ->
- reject(error)
-
- catch error
- reject(error)
-
- # Обработка markdown с поддержкой кастомных классов
- processMarkdown: (content) ->
- if not content
- return ''
-
- # Обрабатываем кастомные теги для классов
- processedContent = content.replace(/\[class:([^\]]+)\]/g, '<div class="$1">')
- .replace(/\[\/class\]/g, '</div>')
-
- # Настройка marked
- marked.setOptions({
- breaks: true
- gfm: true
- sanitize: false # Разрешаем HTML для кастомных классов
- })
-
- return marked(processedContent)
-
- # Получение мультиязычного текста
- getMultilingualText: (textArray, fallback = '') ->
- return AppDB.multilingual.getText(textArray, fallback)
-
- # Получение локализованной строки из настроек
- getLocalizedString: (key, fallback = '') ->
- strings = @pageSettings.strings?[key] || []
- return @getMultilingualText(strings, fallback)
-
- # Обновление мета-данных страницы
- updatePageMeta: ->
- if @pageMeta.title
- document.title = @pageMeta.title + ' - Кохи Борбад'
-
- # Обновляем meta теги
- metaDescription = document.querySelector('meta[name="description"]')
- if not metaDescription
- metaDescription = document.createElement('meta')
- metaDescription.name = 'description'
- document.head.appendChild(metaDescription)
- metaDescription.content = @pageMeta.description
-
- metaKeywords = document.querySelector('meta[name="keywords"]')
- if not metaKeywords
- metaKeywords = document.createElement('meta')
- metaKeywords.name = 'keywords'
- document.head.appendChild(metaKeywords)
- metaKeywords.content = @pageMeta.keywords
-
- # Рендер компонента указанного в настройках страницы
- renderCustomComponent: ->
- if not @page?.settings?.component
- return null
-
- componentName = @page.settings.component
- try
- component = require('app/pages/' + componentName)
- return component
- catch error
- debug.log "Компонент "+componentName+" не найден: "+error
- return null
-
- # Обработка клика по внутренним ссылкам в контенте
- handleContentClick: (event) ->
- if event.target.tagName == 'A'
- href = event.target.getAttribute('href')
- if href and href.startsWith('/')
- event.preventDefault()
- _.$router.push(href)
|