sync: import server reference version

This commit is contained in:
apuc committed 2026-11-18 19:51:13 +03:00
1 parent 01e86f330b
commit 054789049f
46 files changed
+5199 -3390

No files matched your search

+422 -227
View File
@@ -1,261 +1,456 @@
{%- set path = request.url.path -%}
{%- set nav = [
('/dashboard', 'Главная', 'home', ['/dashboard']),
('/generate', 'Создать пост', 'sparkle', ['/generate']),
('/plan', 'Контент-план', 'calendar', ['/plan']),
('/history', 'Мои посты', 'news', ['/history', '/posts']),
('/images', 'Картинки', 'image', ['/images']),
('/channels', 'Каналы', 'megaphone', ['/channels']),
('/surveys', 'Медиа-образы', 'persona', ['/surveys', '/survey']),
('/stats', 'Статистика', 'chart', ['/stats']),
('/provider', 'ИИ-провайдеры', 'cpu', ['/provider', '/tenchat']),
('/profile/edit', 'Профиль', 'user', ['/profile', '/delete-account']),
] -%}
{%- set nav_groups = [
('', [nav[0]]),
('Контент', [nav[1], nav[2], nav[3], nav[4]]),
('Бренд и каналы', [nav[6], nav[5], nav[7]]),
('Настройки', [nav[8], nav[9]]),
] -%}
{%- macro is_active(prefixes) -%}{% for p in prefixes %}{% if path == p or path.startswith(p ~ '/') %}1{% endif %}{% endfor %}{%- endmacro -%}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Личный кабинет{% endblock %}</title>
<link rel="stylesheet" href="/static/style.css?v=3">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>{% block title %}Личный кабинет{% endblock %} · ИИ Пресс-секретарь</title>
<link rel="icon" type="image/svg+xml" href="/static/press/app-icon.svg">
<link rel="stylesheet" href="/static/press/tokens.css?v=2">
<link rel="stylesheet" href="/static/press/components.css?v=4">
<link rel="stylesheet" href="/static/style.css?v=20">
<script>
(function () {
function isDark() {
return document.documentElement.getAttribute('data-theme') === 'dark';
}
function setIcon(btn) {
if (btn) btn.textContent = isDark() ? '\u2600\uFE0F' : '\uD83C\uDF19';
}
try {
var saved = localStorage.getItem('theme');
if (saved !== 'light') {
document.documentElement.setAttribute('data-theme', 'dark');
}
if (saved === 'light' || saved === 'dark') document.documentElement.setAttribute('data-theme', saved);
} catch (e) {}
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-theme-toggle]');
if (!btn) return;
if (isDark()) {
document.documentElement.removeAttribute('data-theme');
try { localStorage.setItem('theme', 'light'); } catch (e) {}
} else {
document.documentElement.setAttribute('data-theme', 'dark');
try { localStorage.setItem('theme', 'dark'); } catch (e) {}
}
setIcon(btn);
});
document.addEventListener('DOMContentLoaded', function () {
setIcon(document.querySelector('[data-theme-toggle]'));
});
})();
</script>
<script src="/static/press/glass.js?v=4" defer></script>
<script type="speculationrules">
{"prefetch": [{"where": {"and": [{"href_matches": "/*"}, {"not": {"href_matches": "/media/*"}}, {"not": {"href_matches": "/surveys/*/export"}}, {"not": {"href_matches": "/delete-account"}}]}, "eagerness": "moderate"}]}
</script>
{% block head %}{% endblock %}
</head>
<body>
<aside class="sidebar" id="sidebar">
<a class="sidebar-brand" href="{{ '/dashboard' if user else '/login' }}">
<svg class="sidebar-brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
<span>ИИ Пресс-секретарь</span>
</a>
{% if user %}
<nav class="sidebar-nav">
<a href="/dashboard" class="sidebar-link {% if request.path == '/dashboard' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
<span>Главная</span>
</a>
<a href="/generate" class="sidebar-link {% if request.path == '/generate' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
<span>Создать пост</span>
</a>
<a href="/plan" class="sidebar-link {% if request.path == '/plan' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
<span>План</span>
</a>
<a href="/history" class="sidebar-link {% if request.path == '/history' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
<span>Мои посты</span>
</a>
<a href="/images" class="sidebar-link {% if request.path == '/images' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
<span>Картинки</span>
</a>
<a href="/channels" class="sidebar-link {% if request.path == '/channels' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"/></svg>
<span>Каналы</span>
</a>
<a href="/surveys" class="sidebar-link {% if '/surveys' in request.path %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><path d="M9 14l2 2 4-4"/></svg>
<span>Медиа-образы</span>
</a>
<a href="/stats" class="sidebar-link {% if request.path == '/stats' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
<span>Статистика</span>
</a>
<div class="sidebar-divider"></div>
<a href="/provider" class="sidebar-link {% if request.path == '/provider' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2" ry="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="1" x2="9" y2="4"/><line x1="15" y1="1" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="23"/><line x1="15" y1="20" x2="15" y2="23"/><line x1="20" y1="9" x2="23" y2="9"/><line x1="20" y1="14" x2="23" y2="14"/><line x1="1" y1="9" x2="4" y2="9"/><line x1="1" y1="14" x2="4" y2="14"/></svg>
<span>ИИ</span>
</a>
<a href="/profile/edit" class="sidebar-link {% if request.path == '/profile/edit' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
<span>Профиль</span>
</a>
</nav>
<div class="sidebar-footer">
<button type="button" class="sidebar-link" data-theme-toggle aria-label="Переключить тему">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
<span>Тема</span>
</button>
<form action="/logout" method="post" class="sidebar-form">
<button type="submit" class="sidebar-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
<span>Выйти</span>
</button>
</form>
<body class="{% if user %}is-cabinet{% else %}is-auth{% endif %}">
{% if user %}
<div class="ps-shell app-shell">
<nav class="ps-sidenav app-sidenav app-glass" aria-label="Разделы кабинета">
<a class="ps-sidenav-logo app-logo-link" href="/dashboard">{{ ui.logo('navlogo', 'color', 32) }}</a>
<div class="app-nav" data-nav>
<span class="app-nav-indicator" aria-hidden="true"></span>
{% for caption, items in nav_groups %}
<div class="app-nav-section">
{% if caption %}<div class="app-nav-caption" id="navg{{ loop.index }}">{{ caption }}</div>{% endif %}
<ul class="app-nav-group"{% if caption %} aria-labelledby="navg{{ loop.index }}"{% endif %}>
{% for href, label, icon, prefixes in items %}
{% set active = is_active(prefixes) %}
<li><a href="{{ href }}" data-prefixes="{{ prefixes | join(' ') }}" class="ps-sidenav-item{% if active %} is-active{% endif %}"{% if active %} aria-current="page"{% endif %}>{{ ui.icon(icon, 20) }}<span>{{ label }}</span></a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
{% else %}
<nav class="sidebar-nav">
<a href="/login" class="sidebar-link {% if request.path == '/login' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
<span>Вход</span>
<div class="app-sidenav-foot">
<ul class="ps-sidenav-list">
<li><button type="button" class="ps-sidenav-item" data-theme-toggle>{{ ui.icon('theme', 20) }}<span data-theme-label>Тема</span></button></li>
<li><form action="/logout" method="post" class="inline-form">
<button type="submit" class="ps-sidenav-item">{{ ui.icon('logout', 20) }}<span>Выйти</span></button>
</form></li>
</ul>
{% if active_persona %}
<a class="ps-sidenav-persona" href="/surveys/{{ active_persona.id }}">
<span class="ps-sidenav-persona-icon" aria-hidden="true">{{ ui.icon('persona', 18) }}</span>
<span class="ps-sidenav-persona-text">
<span class="ps-sidenav-persona-cap">Активный медиа-образ</span>
<span class="ps-sidenav-persona-name">{{ active_persona.title }}</span>
</span>
{{ ui.icon('chevron-right', 16) }}
</a>
<a href="/register" class="sidebar-link {% if request.path == '/register' %}active{% endif %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg>
<span>Регистрация</span>
{% else %}
<a class="ps-sidenav-persona" href="/survey">
<span class="ps-sidenav-persona-icon" aria-hidden="true">{{ ui.icon('plus', 18) }}</span>
<span class="ps-sidenav-persona-text">
<span class="ps-sidenav-persona-cap">Медиа-образа пока нет</span>
<span class="ps-sidenav-persona-name">Создать медиа-образ</span>
</span>
{{ ui.icon('chevron-right', 16) }}
</a>
</nav>
<div class="sidebar-footer">
<button type="button" class="sidebar-link" data-theme-toggle aria-label="Переключить тему">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
<span>Тема</span>
</button>
{% endif %}
</div>
{% endif %}
</aside>
</nav>
<button class="sidebar-toggle" id="sidebarToggle" aria-label="Меню">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="app-body">
<header class="app-topbar app-glass">
<a href="/dashboard" class="app-logo-link">{{ ui.logo('toplogo', 'color', 28) }}</a>
<button type="button" class="ps-iconbtn" data-theme-toggle aria-label="Сменить тему">{{ ui.icon('theme', 22) }}</button>
</header>
<main class="main-content">
{% if flash_message %}
<div class="flash">{{ flash_message }}</div>
{% endif %}
{% if errors %}
<div class="errors">
<ul>
{% for error in errors %}
<li>{{ error }}</li>
<div class="app-compactbar" data-compactbar aria-hidden="true"><span class="app-compactbar-title">{{ self.title() }}</span></div>
<main class="ps-main app-main" id="main">
{% if errors %}
<div class="app-alert" role="alert">
<span class="app-alert-icon">{{ ui.icon('alert', 18) }}</span>
<ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>
</div>
{% endif %}
{% block content %}{% endblock %}
</main>
</div>
{%- set tab_more_active = not (is_active(['/dashboard']) or is_active(['/generate']) or is_active(['/plan']) or is_active(['/history', '/posts'])) %}
<nav class="ps-tabbar app-tabbar app-glass" aria-label="Разделы" data-tabs>
<span class="app-tab-indicator" aria-hidden="true"></span>
<a href="/dashboard" data-prefixes="/dashboard" class="ps-tab{% if is_active(['/dashboard']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('home', 24) }}</span><span class="ps-tab-label">Главная</span></a>
<a href="/generate" data-prefixes="/generate" class="ps-tab{% if is_active(['/generate']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('sparkle', 24) }}</span><span class="ps-tab-label">Создать</span></a>
<a href="/plan" data-prefixes="/plan" class="ps-tab{% if is_active(['/plan']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('calendar', 24) }}</span><span class="ps-tab-label">План</span></a>
<a href="/history" data-prefixes="/history /posts" class="ps-tab{% if is_active(['/history', '/posts']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('news', 24) }}</span><span class="ps-tab-label">Посты</span></a>
<button type="button" class="ps-tab{% if tab_more_active %} is-active{% endif %}" data-sheet-open="moreSheet" aria-haspopup="dialog" aria-expanded="false" aria-controls="moreSheet"><span class="ps-tab-icon">{{ ui.icon('grid', 24) }}</span><span class="ps-tab-label">Ещё</span></button>
</nav>
<div class="app-sheet" id="moreSheet" role="dialog" aria-modal="true" aria-label="Все разделы" hidden>
<div class="app-sheet-scrim" data-sheet-close></div>
<div class="app-sheet-panel app-glass">
<div class="app-sheet-head">
<h2 class="ps-h2">Разделы</h2>
<button type="button" class="ps-iconbtn" data-sheet-close aria-label="Закрыть">{{ ui.icon('close', 22) }}</button>
</div>
<ul class="ps-sidenav-list">
{% for href, label, icon, prefixes in nav[4:] %}
<li><a href="{{ href }}" class="ps-sidenav-item{% if is_active(prefixes) %} is-active" aria-current="page{% endif %}">{{ ui.icon(icon, 20) }}<span>{{ label }}</span></a></li>
{% endfor %}
<li><form action="/logout" method="post" class="inline-form">
<button type="submit" class="ps-sidenav-item">{{ ui.icon('logout', 20) }}<span>Выйти</span></button>
</form></li>
</ul>
</div>
</div>
</div>
{% else %}
<div class="app-auth">
<a href="/" class="app-auth-logo">{{ ui.logo('authlogo', 'white', 44) }}</a>
<main class="app-auth-card" id="main">
{% if errors %}
<div class="app-alert" role="alert">
<span class="app-alert-icon">{{ ui.icon('alert', 18) }}</span>
<ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>
</div>
{% endif %}
{% block content %}{% endblock %}
{{ self.content() }}
</main>
<button type="button" class="ps-btn ps-btn--glass ps-btn--sm app-auth-theme" data-theme-toggle>{{ ui.icon('theme', 16) }}<span data-theme-label>Тема</span></button>
</div>
{% endif %}
<script>
(function () {
var toggle = document.getElementById('sidebarToggle');
var sidebar = document.getElementById('sidebar');
if (toggle && sidebar) {
toggle.addEventListener('click', function () {
sidebar.classList.toggle('open');
{%- set flash_text = (flash_message or '') | replace('❌', '') | replace('✅', '') | replace('⚠️', '') | trim -%}
{%- set flash_low = flash_text | lower -%}
{%- set flash_bad = flash_text and ('ошибк' in flash_low or 'не удалось' in flash_low or 'недопустим' in flash_low or 'не подключ' in flash_low or 'не найден' in flash_low) -%}
<div class="app-toasts" id="toasts" aria-live="polite">
{% if flash_text %}
<div class="ps-toast app-glass ps-toast--{{ 'danger' if flash_bad else 'success' }}" role="{{ 'alert' if flash_bad else 'status' }}" data-autoclose{% if flash_bad %} data-humanize{% endif %}>
<span class="ps-toast-icon" aria-hidden="true">{{ ui.icon('alert' if flash_bad else 'check', 18) }}</span>
<div class="ps-toast-text"><p class="ps-toast-title">{{ flash_text }}</p></div>
<button type="button" class="ps-iconbtn" data-toast-close aria-label="Закрыть уведомление">{{ ui.icon('close', 18) }}</button>
</div>
{% endif %}
</div>
{# Подтверждение удаления — лист, а не системное окно. Текст берётся из data-confirm формы. #}
<div class="app-sheet" id="confirmSheet" role="alertdialog" aria-modal="true" aria-labelledby="confirmTitle" aria-describedby="confirmBody" hidden>
<div class="app-sheet-scrim" data-sheet-close></div>
<div class="app-sheet-panel app-glass app-confirm">
<span class="ps-empty-icon app-confirm-icon" aria-hidden="true">{{ ui.icon('trash', 28) }}</span>
<h2 class="ps-h2" id="confirmTitle"></h2>
<p class="app-muted" id="confirmBody"></p>
<div class="app-actions app-confirm-actions">
<button type="button" class="ps-btn ps-btn--danger" data-confirm-ok>{{ ui.icon('trash', 20) }}<span class="ps-btn-label">Удалить</span></button>
<button type="button" class="ps-btn ps-btn--quiet" data-sheet-close><span class="ps-btn-label">Оставить</span></button>
</div>
</div>
</div>
<template id="tpl-thinking"><div class="ps-thinking" role="status" aria-live="polite"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span data-label></span></div></template>
<template id="tpl-icon-check">{{ ui.icon('check', 18) }}</template>
<template id="tpl-icon-alert">{{ ui.icon('alert', 18) }}</template>
<template id="tpl-icon-close">{{ ui.icon('close', 18) }}</template>
<template id="tpl-icon-sparkle">{{ ui.icon('sparkle', 18) }}</template>
<script>
window.Press = window.Press || {};
/* === Склонение по числу: Press.plural(3, ['идея', 'идеи', 'идей']) === */
Press.plural = function (n, forms) {
var a = Math.abs(n) % 100, b = a % 10;
if (a > 10 && a < 20) return forms[2];
if (b > 1 && b < 5) return forms[1];
if (b === 1) return forms[0];
return forms[2];
};
/* === Тосты: цвет по смыслу, пауза на наведении и фокусе === */
function armToast(el) {
var left = 5000, started = Date.now(), timer = null;
function run() { started = Date.now(); timer = setTimeout(function () { el.remove(); }, left); }
function pause() { if (timer) { clearTimeout(timer); timer = null; left -= Date.now() - started; } }
el.addEventListener('mouseenter', pause); el.addEventListener('focusin', pause);
el.addEventListener('mouseleave', function () { if (!el.contains(document.activeElement)) run(); });
el.addEventListener('focusout', function (e) { if (!el.contains(e.relatedTarget)) run(); });
run();
}
Press.toast = function (title, tone, body) {
tone = tone || 'success';
var wrap = document.getElementById('toasts');
var el = document.createElement('div');
el.className = 'ps-toast app-glass ps-toast--' + tone;
el.setAttribute('role', tone === 'danger' ? 'alert' : 'status');
var iconId = tone === 'danger' || tone === 'warning' ? 'tpl-icon-alert' : tone === 'ai' ? 'tpl-icon-sparkle' : 'tpl-icon-check';
el.innerHTML = '<span class="ps-toast-icon" aria-hidden="true">' + document.getElementById(iconId).innerHTML + '</span>' +
'<div class="ps-toast-text"><p class="ps-toast-title"></p>' + (body ? '<p class="ps-toast-body"></p>' : '') + '</div>' +
'<button type="button" class="ps-iconbtn" data-toast-close aria-label="Закрыть уведомление">' + document.getElementById('tpl-icon-close').innerHTML + '</button>';
el.querySelector('.ps-toast-title').textContent = title;
if (body) el.querySelector('.ps-toast-body').textContent = body;
wrap.appendChild(el);
armToast(el);
};
/* === Технические ошибки → «что случилось и что сделать» === */
Press.humanError = function (msg) {
msg = String(msg || '');
if (/\b(401|403)\b|Unauthorized|Forbidden|invalid.*key|api key/i.test(msg))
return 'Провайдер ИИ не принял ключ. Проверьте ключ в разделе «ИИ-провайдеры».';
if (/\b429\b|rate limit|too many/i.test(msg))
return 'Слишком много запросов к провайдеру ИИ. Подождите минуту и повторите.';
if (/timed? ?out|timeout/i.test(msg))
return 'Провайдер ИИ не ответил вовремя. Попробуйте ещё раз через минуту.';
if (/\b(500|502|503|504)\b|Bad Gateway|Service Unavailable/i.test(msg))
return 'Сервис сейчас недоступен. Повторите через минуту.';
if (/ProxyError|Max retries|ConnectionError|Failed to establish|Failed to fetch|NetworkError|Load failed/i.test(msg))
return 'Нет связи с сервером. Проверьте интернет и повторите.';
return msg || 'Не получилось выполнить действие. Повторите через минуту — если не поможет, проверьте раздел «ИИ-провайдеры».';
};
document.querySelectorAll('[data-humanize] .ps-toast-title').forEach(function (t) { t.textContent = Press.humanError(t.textContent); });
document.querySelectorAll('[data-autoclose]').forEach(armToast);
/* === Запросы к API: истёкшая сессия и не-JSON — понятной ошибкой === */
Press.SESSION = 'session-expired';
Press.sessionExpired = function () {
if (Press._sessionShown) return; Press._sessionShown = true;
Press.toast('Сессия истекла', 'warning', 'Войдите заново — открываю страницу входа.');
setTimeout(function () { location.href = '/login'; }, 2500);
};
Press.fetchJSON = function (url, opts) {
return fetch(url, Object.assign({ credentials: 'same-origin', headers: { 'Accept': 'application/json' } }, opts || {}))
.then(function (r) {
if (r.redirected && /\/login(\?|$)/.test(r.url)) { Press.sessionExpired(); throw new Error(Press.SESSION); }
var ct = r.headers.get('content-type') || '';
if (ct.indexOf('json') < 0) throw new Error('Сервер ответил не так, как ожидалось (' + r.status + '). Обновите страницу и повторите.');
return r.json().then(function (d) {
if (!r.ok && d && !d.error) d.error = d.detail || ('Ошибка ' + r.status);
return d;
});
document.addEventListener('click', function (e) {
if (sidebar.classList.contains('open') && !sidebar.contains(e.target) && e.target !== toggle) {
sidebar.classList.remove('open');
}
});
}
})();
function copyText(text, btn) {
function done(ok) {
if (!btn) return;
var old = btn.textContent;
btn.textContent = ok ? '\u2705 \u0421\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u043e' : '\u274c \u041e\u0448\u0438\u0431\u043a\u0430';
setTimeout(function () { btn.textContent = old; }, 1500);
}
function fallback() {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
var ok = false;
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
document.body.removeChild(ta);
done(ok);
}
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text).then(function () { done(true); }, fallback);
} else {
fallback();
})
.catch(function (err) {
if (err.message === Press.SESSION) throw err;
if (err instanceof TypeError) throw new Error('Нет связи с сервером. Проверьте интернет и повторите.');
throw err;
});
};
/* Опрос фоновой задачи: не дольше 5 минут; всё, кроме «в работе» и «готово с результатом», — ошибка */
Press.pollTask = function (taskId, cb, startedAt) {
startedAt = startedAt || Date.now();
if (Date.now() - startedAt > 5 * 60 * 1000) {
cb.fail('Ответ не пришёл за 5 минут. Повторите — возможно, провайдер ИИ перегружен.');
return;
}
Press.fetchJSON('/api/tasks/' + taskId)
.then(function (data) {
if (data.status === 'running' || data.status === 'pending') {
setTimeout(function () { Press.pollTask(taskId, cb, startedAt); }, 1500);
} else if (data.status === 'done' && data.result) {
cb.done(data.result);
} else if (data.status === 'error') {
cb.fail(data.error || 'Не получилось. Проверьте настройки в разделе «ИИ-провайдеры».');
} else {
cb.fail(data.error || 'Задача не найдена или завершилась без результата. Повторите.');
}
})
.catch(function (err) { if (err.message !== Press.SESSION) cb.fail(err.message); });
};
/* === Листы: фокус внутрь, Tab не выходит наружу, после закрытия — обратно на кнопку === */
var sheetOpener = null;
function focusables(root) {
return Array.prototype.slice.call(root.querySelectorAll('a[href], button:not(:disabled), input:not(:disabled), select, textarea, [tabindex]:not([tabindex="-1"])'))
.filter(function (el) { return el.offsetParent !== null; });
}
Press.openSheet = function (sheet, opener) {
sheetOpener = opener || document.activeElement;
sheet.hidden = false;
if (opener) opener.setAttribute('aria-expanded', 'true');
var f = focusables(sheet.querySelector('.app-sheet-panel'));
if (f.length) f[0].focus();
};
Press.closeSheet = function (sheet) {
sheet.hidden = true;
if (sheetOpener) { sheetOpener.setAttribute('aria-expanded', 'false'); if (document.contains(sheetOpener)) sheetOpener.focus(); }
sheetOpener = null;
};
/* === Подтверждение удаления: форма с data-confirm открывает лист === */
var pendingForm = null;
document.addEventListener('submit', function (e) {
var form = e.target;
if (!form.hasAttribute('data-confirm') || form.dataset.confirmed === '1') return;
e.preventDefault();
pendingForm = form;
var sheet = document.getElementById('confirmSheet');
document.getElementById('confirmTitle').textContent = form.getAttribute('data-confirm');
document.getElementById('confirmBody').textContent = form.getAttribute('data-confirm-body') || 'Вернуть будет нельзя.';
sheet.querySelector('[data-confirm-ok] .ps-btn-label').textContent = form.getAttribute('data-confirm-ok') || 'Удалить';
Press.openSheet(sheet, form.querySelector('button[type="submit"]') || e.submitter);
/* Фокус — на безопасное «Оставить»: случайный Enter ничего не удаляет */
sheet.querySelector('.app-confirm-actions [data-sheet-close]').focus();
sheet.querySelector('[data-confirm-ok]').disabled = false;
}, true);
document.addEventListener('click', function (e) {
var c = e.target.closest('[data-toast-close]');
if (c) { c.closest('.ps-toast').remove(); return; }
var ok = e.target.closest('[data-confirm-ok]');
if (ok && pendingForm) {
var form = pendingForm; pendingForm = null;
form.dataset.confirmed = '1';
ok.disabled = true;
HTMLFormElement.prototype.submit.call(form);
return;
}
var o = e.target.closest('[data-sheet-open]');
if (o) { var s = document.getElementById(o.getAttribute('data-sheet-open')); if (s) Press.openSheet(s, o); return; }
var x = e.target.closest('[data-sheet-close]');
if (x) { pendingForm = null; Press.closeSheet(x.closest('.app-sheet')); return; }
/* Карточки выбора (ChoiceGroup) поверх обычного radio */
var ch = e.target.closest('.ps-choice[data-value]');
if (ch && !ch.disabled) {
var grid = ch.closest('[role="radiogroup"]');
grid.querySelectorAll('.ps-choice').forEach(function (b) {
var on = b === ch;
b.classList.toggle('is-selected', on);
b.setAttribute('aria-checked', on ? 'true' : 'false');
b.tabIndex = on ? 0 : -1;
});
var input = document.getElementById(grid.getAttribute('data-input'));
if (input) { input.value = ch.getAttribute('data-value'); input.dispatchEvent(new Event('change', { bubbles: true })); }
}
});
document.addEventListener('keydown', function (e) {
var open = document.querySelector('.app-sheet:not([hidden])');
if (open) {
if (e.key === 'Escape') { pendingForm = null; Press.closeSheet(open); return; }
if (e.key === 'Tab') {
var f = focusables(open.querySelector('.app-sheet-panel'));
if (!f.length) return;
var first = f[0], last = f[f.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
else if (!open.contains(document.activeElement)) { e.preventDefault(); first.focus(); }
return;
}
}
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-copy-target]');
if (!btn) return;
var el = document.getElementById(btn.getAttribute('data-copy-target'));
if (el) copyText(el.textContent, btn);
});
/* Стрелки в группах выбора: карточки выбора и шаблоны картинок */
var grid = e.target.closest && e.target.closest('[role="radiogroup"].ps-choices-grid, [role="radiogroup"].ps-presets');
if (!grid) return;
var d = (e.key === 'ArrowRight' || e.key === 'ArrowDown') ? 1 : (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 0;
if (!d) return;
e.preventDefault();
var items = Array.prototype.slice.call(grid.querySelectorAll('.ps-choice:not(:disabled), .ps-preset:not(:disabled)'));
var i = items.indexOf(e.target.closest('.ps-choice, .ps-preset'));
var next = items[(i + d + items.length) % items.length];
next.click(); next.focus();
});
/* === Background Task Engine === */
window.TaskEngine = {
start: function(formEl, opts) {
var fd = new FormData(formEl);
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
var resultEl = document.getElementById(opts.resultId || 'taskResult');
var formContainer = document.getElementById(opts.formId || 'taskForm');
var btn = formEl.querySelector('button[type="submit"]');
var errEl = document.getElementById(opts.errorId || 'taskError');
function copyText(text, btn) {
function done(ok) {
Press.toast(ok ? 'Скопировано' : 'Не удалось скопировать', ok ? 'success' : 'danger', ok ? '' : 'Выделите текст и скопируйте вручную (Ctrl+C).');
}
function fallback() {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
var ok = false;
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
document.body.removeChild(ta);
done(ok);
}
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text).then(function () { done(true); }, fallback);
} else {
fallback();
}
}
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-copy-target]');
if (!btn) return;
var el = document.getElementById(btn.getAttribute('data-copy-target'));
if (el) copyText(el.textContent, btn);
});
// Hide form, show loader
if (formContainer) formContainer.style.display = 'none';
if (resultEl) resultEl.style.display = 'none';
if (errEl) { errEl.style.display = 'none'; errEl.textContent = ''; }
if (loaderEl) loaderEl.style.display = 'flex';
/* === Фоновые задачи страниц: создать пост, план, картинка === */
window.TaskEngine = {
start: function(formEl, opts) {
if (opts._busy) return;
opts._busy = true;
var fd = new FormData(formEl);
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
var resultEl = document.getElementById(opts.resultId || 'taskResult');
var formContainer = document.getElementById(opts.formId || 'taskForm');
var errEl = document.getElementById(opts.errorId || 'taskError');
fetch('/api/tasks', { method: 'POST', body: fd })
.then(function(r) { return r.json(); })
.then(function(data) {
if (data.status === 'error' || data.error) {
if (formContainer && !opts.keepForm) formContainer.style.display = 'none';
if (resultEl) resultEl.style.display = 'none';
if (errEl) { errEl.style.display = 'none'; errEl.textContent = ''; }
if (loaderEl) loaderEl.style.display = 'flex';
if (opts.onStart) opts.onStart();
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
.then(function(data) {
if (!data.task_id) { TaskEngine.fail(opts, data.error || 'Не удалось запустить задачу. Повторите.'); return; }
Press.pollTask(data.task_id, {
done: function (result) {
opts._busy = false;
if (loaderEl) loaderEl.style.display = 'none';
if (formContainer) formContainer.style.display = '';
if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || 'Ошибка запуска задачи'; }
return;
}
TaskEngine.poll(data.task_id, opts);
})
.catch(function(err) {
if (loaderEl) loaderEl.style.display = 'none';
if (formContainer) formContainer.style.display = '';
if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Ошибка сети: ' + err.message; }
if (opts.onEnd) opts.onEnd(true);
if (opts.onDone) opts.onDone(result);
},
fail: function (msg) { TaskEngine.fail(opts, msg); }
});
},
poll: function(taskId, opts) {
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
var resultEl = document.getElementById(opts.resultId || 'taskResult');
var formContainer = document.getElementById(opts.formId || 'taskForm');
var errEl = document.getElementById(opts.errorId || 'taskError');
fetch('/api/tasks/' + taskId)
.then(function(r) { return r.json(); })
.then(function(data) {
if (data.status === 'running' || data.status === 'pending') {
setTimeout(function() { TaskEngine.poll(taskId, opts); }, 1500);
return;
}
if (loaderEl) loaderEl.style.display = 'none';
if (data.status === 'error') {
if (formContainer) formContainer.style.display = '';
if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || 'Ошибка генерации'; }
return;
}
if (data.status === 'done' && opts.onDone) {
opts.onDone(data.result || {});
}
})
.catch(function(err) {
if (loaderEl) loaderEl.style.display = 'none';
if (formContainer) formContainer.style.display = '';
if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Ошибка сети: ' + err.message; }
});
}
};
</script>
})
.catch(function(err) { if (err.message !== Press.SESSION) TaskEngine.fail(opts, err.message); else opts._busy = false; });
},
fail: function(opts, message) {
opts._busy = false;
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
var formContainer = document.getElementById(opts.formId || 'taskForm');
var errEl = document.getElementById(opts.errorId || 'taskError');
if (loaderEl) loaderEl.style.display = 'none';
if (formContainer) formContainer.style.display = '';
if (errEl) { errEl.style.display = 'flex'; errEl.textContent = Press.humanError(message); errEl.title = message; }
if (opts.onEnd) opts.onEnd(false);
}
};
</script>
{% block scripts %}{% endblock %}
</body>
</html>