# Загрузка стилей компонента document.head.insertAdjacentHTML('beforeend','') # Подключение 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, '
') .replace(/\[\/class\]/g, '
') # Настройка 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)