530 lines
32 KiB
HTML
530 lines
32 KiB
HTML
{% extends "base.html" %}
|
||
{% block title %}Пост{% endblock %}
|
||
{% block content %}
|
||
{%- set art_for = {'product': 'product', 'lifestyle': 'portrait', 'food': 'product', 'business': 'mockup', 'abstract': 'abstract',
|
||
'portrait': 'portrait', 'infographic': 'announce', 'banner': 'cover', 'nature': 'landscape', 'minimal': 'minimal',
|
||
'story': 'collage', 'before_after': 'collage'} -%}
|
||
{%- set limits = {'telegram': 4096, 'instagram': 2200, 'linkedin': 3000, 'twitter': 280} -%}
|
||
{%- set limit = limits.get(post.platform, 4096) -%}
|
||
<div class="ps-main-head">
|
||
<div>
|
||
<a href="/history" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Мои посты</span></a>
|
||
<h1 class="ps-h1">Пост</h1>
|
||
<p class="ps-lead">{{ platform_label(post.platform) }}{% if post.style %} · {{ post.style }}{% endif %} · {{ post.created_at|local_dt }}</p>
|
||
</div>
|
||
<div class="app-head-actions">
|
||
<form method="post" action="/posts/{{ post.id }}/delete" class="inline-form" data-confirm="Удалить пост?" data-confirm-body="Его версии и картинки тоже удалятся.">
|
||
<button type="submit" class="ps-iconbtn" aria-label="Удалить пост">{{ ui.icon('trash', 22) }}</button>
|
||
</form>
|
||
<a class="ps-btn ps-btn--primary" href="/posts/{{ post.id }}/publish">{{ ui.icon('send', 20) }}<span class="ps-btn-label">Опубликовать</span></a>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="ps-split" style="--ps-aside: 360px">
|
||
<div class="app-stack-lg">
|
||
<!-- Текущий текст поста -->
|
||
<article class="ps-post" id="postCard">
|
||
<header class="ps-post-head">
|
||
<span class="ps-post-platform">{{ ui.icon('send' if post.platform == 'telegram' else 'news', 16) }}{{ platform_label(post.platform) }}</span>
|
||
{% if post.style %}<span class="ps-post-tag">{{ post.style }}</span>{% endif %}
|
||
<span class="ps-post-tag" id="postVersion"{% if not revisions %} hidden{% endif %}>Версия {{ revisions|length }}</span>
|
||
{% if post.published %}
|
||
<span class="ps-badge ps-badge--success">{{ ui.icon('megaphone', 14) }}<span>Опубликован{% if post.published_to %} в «{{ post.published_to }}»{% endif %}</span></span>
|
||
{% endif %}
|
||
</header>
|
||
{% if images %}
|
||
<div class="ps-post-image"><img src="/media/{{ images[0].filename }}" alt="" style="object-fit:cover"></div>
|
||
{% endif %}
|
||
<div class="ps-post-text"><p id="postContent">{{ post.content }}</p></div>
|
||
<footer class="ps-post-foot">
|
||
<span class="ps-post-count{% if post.content|length > limit %} is-over{% endif %}" id="postCount" data-limit="{{ limit }}">{{ post.content|length|num }} / {{ limit|num }} зн.</span>
|
||
<span class="ps-post-note is-danger" id="postOver"{% if post.content|length <= limit %} hidden{% endif %}>{{ ui.icon('alert', 14) }}Длиннее лимита платформы — сократите текст</span>
|
||
{% if post.platform == 'telegram' and images and post.content|length > 1024 %}
|
||
<span class="ps-post-note">{{ ui.icon('info', 14) }}Длиннее 1 024 знаков: фото уйдёт без подписи, текст — следующим сообщением</span>
|
||
{% endif %}
|
||
<div class="ps-post-actions">
|
||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" onclick="copyPostText()">{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/posts/{{ post.id }}/edit">{{ ui.icon('edit', 16) }}<span class="ps-btn-label">Изменить вручную</span></a>
|
||
</div>
|
||
</footer>
|
||
</article>
|
||
{% if post.wishes %}
|
||
<p class="form-hint" style="margin-top: calc(var(--space-4) * -1)">Пожелания: {{ post.wishes }}</p>
|
||
{% endif %}
|
||
|
||
<!-- Чат правок с ИИ -->
|
||
<section class="app-stack" aria-labelledby="chat-title">
|
||
<h2 class="ps-h2" id="chat-title">Правки с ИИ</h2>
|
||
<div class="app-stack" id="aiChat" style="gap: var(--space-6)">
|
||
<div class="ps-msg ps-msg--ai">
|
||
<span class="ps-msg-avatar" aria-hidden="true">{{ ui.mark('chatav0', 'color', 32) }}</span>
|
||
<div class="ps-msg-body">
|
||
<div class="ps-msg-meta"><span class="ps-msg-author">Пресс-секретарь</span><span class="ps-ai-tag">ИИ</span></div>
|
||
<div class="ps-msg-bubble"><p>Пост готов. Напишите, что изменить, или выберите готовую команду ниже.</p></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="aiChatLoader" style="display:none"><div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Переписываю…</span></div></div>
|
||
<div id="aiChatError" class="task-error" role="alert"></div>
|
||
|
||
<div class="ps-composer">
|
||
<div class="ps-composer-suggest" id="aiSuggest">
|
||
{% for s in ['Сократи вдвое', 'Сделай официальнее', 'Добавь призыв к действию', 'Перепиши в стиле эксперта'] %}
|
||
<button type="button" class="ps-chip ps-chip--sm" data-suggest="{{ s }}">{{ ui.icon('sparkle', 16) }}<span>{{ s }}</span></button>
|
||
{% endfor %}
|
||
</div>
|
||
<div class="ps-composer-row">
|
||
<textarea id="aiChatInput" class="ps-composer-input" rows="1" aria-label="Что изменить в посте"
|
||
placeholder="Что изменить? Например: «сократи вдвое»"
|
||
onkeydown="if(event.key==='Enter' && !event.shiftKey){event.preventDefault(); sendAiInstruction();}"></textarea>
|
||
<button type="button" class="ps-iconbtn ps-iconbtn--filled" id="aiChatSendBtn" aria-label="Отправить" onclick="sendAiInstruction()" disabled>{{ ui.icon('send', 22) }}</button>
|
||
</div>
|
||
<p class="ps-composer-note">Пресс-секретарь пишет черновик. В канал пост уходит только по вашей команде.</p>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
|
||
<aside class="app-stack-lg">
|
||
<!-- История версий -->
|
||
<section class="ps-panel" aria-labelledby="ver-title">
|
||
<h2 class="ps-h2" id="ver-title">История изменений</h2>
|
||
{% if revisions %}
|
||
<ol class="ps-history" aria-label="История изменений" id="versionList">
|
||
{% for r in revisions %}
|
||
<li class="ps-history-item{% if loop.first %} is-active{% endif %}" data-rev="{{ r.id }}">
|
||
<span class="ps-history-dot" aria-hidden="true"></span>
|
||
<span class="ps-history-text">
|
||
<span class="ps-history-title">Версия {{ loop.revindex }}</span>
|
||
<span class="ps-history-meta">{{ r.created_at|local_dt('%H:%M · %d.%m.%Y') }} · {{ r.content|length|num }} зн.</span>
|
||
</span>
|
||
{% if loop.first %}
|
||
<span class="ps-history-current">Текущая</span>
|
||
{% else %}
|
||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-restore="{{ r.id }}">{{ ui.icon('history', 16) }}<span class="ps-btn-label">Вернуть</span></button>
|
||
{% endif %}
|
||
<template data-content>{{ r.content }}</template>
|
||
</li>
|
||
{% endfor %}
|
||
</ol>
|
||
{% else %}
|
||
<p class="form-hint" id="versionEmpty">Каждая правка в чате и вручную станет версией — любую можно будет вернуть.</p>
|
||
{% endif %}
|
||
</section>
|
||
|
||
<!-- Картинки поста -->
|
||
<section class="ps-panel" aria-labelledby="img-title">
|
||
<h2 class="ps-h2" id="img-title">Картинки</h2>
|
||
{% if images %}
|
||
<div class="app-gallery" style="grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-3)">
|
||
{% for img in images %}
|
||
<figure class="app-gallery-item" style="margin:0">
|
||
<a href="/media/{{ img.filename }}" target="_blank" rel="noopener" aria-label="Открыть картинку"><img src="/media/{{ img.filename }}" alt=""></a>
|
||
<figcaption class="app-actions" style="padding: 4px; justify-content: space-between">
|
||
<span class="app-caption" style="padding-left: 8px">{{ 'ИИ' if img.source == 'generated' else 'Загружена' }}</span>
|
||
<form action="/posts/{{ post.id }}/images/{{ img.id }}/delete" method="post" class="inline-form" data-confirm="Удалить картинку?">
|
||
<button type="submit" class="ps-iconbtn" aria-label="Удалить картинку">{{ ui.icon('trash', 18) }}</button>
|
||
</form>
|
||
</figcaption>
|
||
</figure>
|
||
{% endfor %}
|
||
</div>
|
||
{% endif %}
|
||
|
||
<form method="post" action="/posts/{{ post.id }}/images/upload" enctype="multipart/form-data" id="uploadForm">
|
||
<label class="ps-drop" id="uploadDrop">
|
||
<input type="file" name="files" accept="image/*" multiple required class="ps-drop-input" id="uploadInput">
|
||
<span class="ps-drop-icon" aria-hidden="true">{{ ui.icon('upload', 24) }}</span>
|
||
<span class="ps-drop-title">Перетащите фото или выберите</span>
|
||
<span class="ps-drop-hint">Можно несколько файлов</span>
|
||
</label>
|
||
</form>
|
||
|
||
<div id="postImgError" class="task-error" role="alert"></div>
|
||
<div id="postImgAnalyzeLoader" class="task-loader">
|
||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Подбираю 4 концепции…</span></div>
|
||
</div>
|
||
<div id="postImgGenLoader" class="task-loader">
|
||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Рисую картинку…</span></div>
|
||
<span class="task-loader-sub">Обычно 15–60 секунд</span>
|
||
</div>
|
||
<div id="postImgResult" class="task-result"></div>
|
||
|
||
<div id="postImgConceptsSection" class="app-stack">
|
||
<button type="button" class="ps-btn ps-btn--secondary ps-btn--block" id="postImgAnalyzeBtn" onclick="startAnalyzeConcepts()">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Подобрать концепцию</span></button>
|
||
<details>
|
||
<summary>Сгенерировать по шаблону</summary>
|
||
<div class="ps-presets" id="postImgGrid" style="margin-top: var(--space-3); grid-template-columns: repeat(auto-fill, minmax(96px, 1fr))">
|
||
{% for t in templates %}
|
||
<button type="button" class="ps-preset" data-key="{{ t.key }}" title="{{ t.hint }}">
|
||
<span class="ps-preset-art" aria-hidden="true"><svg viewBox="0 0 64 48" preserveAspectRatio="xMidYMid slice">{{ ui.PRESET_ART[art_for.get(t.key, 'minimal')] | safe }}</svg></span>
|
||
<span class="ps-preset-label">{{ t.name }}</span>
|
||
</button>
|
||
{% endfor %}
|
||
</div>
|
||
</details>
|
||
</div>
|
||
|
||
<div id="postImgConceptsList" class="app-stack" style="display:none;">
|
||
<div class="ps-choices-grid" id="postImgConcepts" style="grid-template-columns: 1fr"></div>
|
||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" onclick="resetConcepts()">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">К шаблонам</span></button>
|
||
</div>
|
||
|
||
<form method="post" action="/posts/{{ post.id }}/images/generate" id="postImgForm" style="display:none;">
|
||
<input type="hidden" name="task_type" id="postImgTaskType" value="generate_post_image">
|
||
<input type="hidden" name="post_id" value="{{ post.id }}">
|
||
<input type="hidden" name="template_key" id="postImgTemplateKey" value="">
|
||
<input type="hidden" name="concept_prompt" id="postImgConceptPrompt" value="">
|
||
<input type="hidden" name="concept_style" id="postImgConceptStyle" value="">
|
||
<input type="hidden" name="concept_size" id="postImgConceptSize" value="">
|
||
</form>
|
||
</section>
|
||
</aside>
|
||
</div>
|
||
|
||
<template id="tpl-icon-history">{{ ui.icon('history', 16) }}</template>
|
||
<template id="tpl-msg-ai">
|
||
<div class="ps-msg ps-msg--ai">
|
||
<span class="ps-msg-avatar" aria-hidden="true">{{ ui.mark('chatav1', 'color', 32) }}</span>
|
||
<div class="ps-msg-body">
|
||
<div class="ps-msg-meta"><span class="ps-msg-author">Пресс-секретарь</span><span class="ps-ai-tag">ИИ</span><time></time></div>
|
||
<div class="ps-msg-bubble"><p data-text></p></div>
|
||
<div class="ps-msg-actions">
|
||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-act="copy">{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-act="again">{{ ui.icon('refresh', 16) }}<span class="ps-btn-label">Другой вариант</span></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
<template id="tpl-msg-user">
|
||
<div class="ps-msg ps-msg--user">
|
||
<div class="ps-msg-body">
|
||
<div class="ps-msg-meta"><time></time></div>
|
||
<div class="ps-msg-bubble"><p data-text></p></div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
{% endblock %}
|
||
|
||
{% block scripts %}
|
||
<script>
|
||
var _currentPostContent = {{ post.content | tojson }};
|
||
var _lastInstruction = '';
|
||
var POST_ID = {{ post.id }};
|
||
|
||
function copyPostText() { copyText(document.getElementById('postContent').textContent); }
|
||
|
||
function setPostContent(text) {
|
||
_currentPostContent = text;
|
||
document.getElementById('postContent').textContent = text;
|
||
var c = document.getElementById('postCount'), limit = +c.getAttribute('data-limit');
|
||
c.textContent = text.length.toLocaleString('ru-RU') + ' / ' + limit.toLocaleString('ru-RU') + ' зн.';
|
||
c.classList.toggle('is-over', text.length > limit);
|
||
document.getElementById('postOver').hidden = text.length <= limit;
|
||
}
|
||
|
||
/* --- Композер --- */
|
||
(function () {
|
||
var input = document.getElementById('aiChatInput'), send = document.getElementById('aiChatSendBtn');
|
||
function grow() { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 200) + 'px'; send.disabled = !input.value.trim() || input.disabled; }
|
||
input.addEventListener('input', grow);
|
||
document.getElementById('aiSuggest').addEventListener('click', function (e) {
|
||
var b = e.target.closest('[data-suggest]'); if (!b) return;
|
||
input.value = b.getAttribute('data-suggest'); grow(); input.focus();
|
||
});
|
||
window._growComposer = grow;
|
||
grow();
|
||
})();
|
||
|
||
var _aiBusy = false;
|
||
|
||
/* Пока ИИ отвечает — композер и кнопки «Другой вариант» выключены: параллельных правок не бывает */
|
||
function setAiBusy(on) {
|
||
_aiBusy = on;
|
||
var input = document.getElementById('aiChatInput');
|
||
input.disabled = on;
|
||
document.getElementById('aiChatLoader').style.display = on ? 'block' : 'none';
|
||
document.getElementById('aiSuggest').hidden = on;
|
||
document.querySelectorAll('[data-act="again"]').forEach(function (b) { b.disabled = on; });
|
||
window._growComposer();
|
||
if (!on) input.focus();
|
||
}
|
||
|
||
/* base — текст, к которому применяется правка: для «Другого варианта» это текст до первой попытки */
|
||
function sendAiInstruction(forced, base) {
|
||
if (_aiBusy) return;
|
||
var input = document.getElementById('aiChatInput');
|
||
var instruction = (forced || input.value).trim();
|
||
if (!instruction) return;
|
||
var errEl = document.getElementById('aiChatError');
|
||
errEl.style.display = 'none';
|
||
addChatMsg('user', base !== undefined ? 'Другой вариант: ' + instruction : instruction);
|
||
input.value = '';
|
||
setAiBusy(true);
|
||
var prev = _currentPostContent;
|
||
|
||
function run() {
|
||
var fd = new FormData();
|
||
fd.append('task_type', 'modify_post');
|
||
fd.append('post_id', POST_ID);
|
||
fd.append('instruction', instruction);
|
||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||
.then(function (data) {
|
||
if (!data.task_id) { aiFail(data.error || 'Не удалось запустить правку. Повторите.'); return; }
|
||
Press.pollTask(data.task_id, {
|
||
done: function (result) {
|
||
setAiBusy(false);
|
||
var basis = base !== undefined ? base : prev;
|
||
setPostContent(result.content);
|
||
addChatMsg('ai', 'Готово: ' + result.content.length.toLocaleString('ru-RU') + ' зн. вместо ' + basis.length.toLocaleString('ru-RU') + '. Прошлая версия — в истории.', { instruction: instruction, base: basis });
|
||
addVersion(result.content, prev);
|
||
},
|
||
fail: aiFail
|
||
});
|
||
})
|
||
.catch(function (err) { if (err.message !== Press.SESSION) aiFail(err.message); });
|
||
}
|
||
/* Другой вариант: сначала возвращаем текст до правки, затем повторяем команду — получается альтернатива, а не правка правки */
|
||
if (base !== undefined && base !== _currentPostContent) {
|
||
var fd = new FormData(); fd.append('content', base);
|
||
Press.fetchJSON('/api/posts/' + POST_ID + '/edit-text', { method: 'POST', body: fd })
|
||
.then(function (d) {
|
||
if (!d.ok) { aiFail(d.error || 'Не удалось подготовить другой вариант. Повторите.'); return; }
|
||
addVersion(d.content, prev); setPostContent(d.content); prev = d.content; run();
|
||
})
|
||
.catch(function (err) { if (err.message !== Press.SESSION) aiFail(err.message); });
|
||
} else {
|
||
run();
|
||
}
|
||
}
|
||
|
||
function aiFail(msg) {
|
||
setAiBusy(false);
|
||
var el = document.getElementById('aiChatError');
|
||
el.textContent = Press.humanError(msg); el.title = msg || '';
|
||
el.style.display = 'flex';
|
||
}
|
||
|
||
function addChatMsg(role, text, ctx) {
|
||
var tpl = document.getElementById(role === 'user' ? 'tpl-msg-user' : 'tpl-msg-ai').content.firstElementChild.cloneNode(true);
|
||
tpl.querySelector('[data-text]').textContent = text;
|
||
tpl.querySelector('time').textContent = new Date().toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'});
|
||
var copy = tpl.querySelector('[data-act="copy"]');
|
||
if (copy) copy.addEventListener('click', function () { copyText(_currentPostContent); });
|
||
var again = tpl.querySelector('[data-act="again"]');
|
||
if (again) {
|
||
if (ctx) again.addEventListener('click', function () { sendAiInstruction(ctx.instruction, ctx.base); });
|
||
else again.remove();
|
||
}
|
||
var chat = document.getElementById('aiChat');
|
||
chat.appendChild(tpl);
|
||
tpl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||
}
|
||
|
||
/* --- История версий --- */
|
||
function versionItem(title, meta, content, current) {
|
||
var li = document.createElement('li');
|
||
li.className = 'ps-history-item' + (current ? ' is-active' : '');
|
||
li.innerHTML = '<span class="ps-history-dot" aria-hidden="true"></span><span class="ps-history-text"><span class="ps-history-title"></span><span class="ps-history-meta"></span></span>' +
|
||
(current ? '<span class="ps-history-current">Текущая</span>' : restoreBtnHtml()) + '<template data-content></template>';
|
||
li.querySelector('.ps-history-title').textContent = title;
|
||
li.querySelector('.ps-history-meta').textContent = meta;
|
||
li.querySelector('template').innerHTML = escHtml(content);
|
||
return li;
|
||
}
|
||
function restoreBtnHtml() {
|
||
return '<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-restore>' + document.getElementById('tpl-icon-history').innerHTML + '<span class="ps-btn-label">Вернуть</span></button>';
|
||
}
|
||
function escHtml(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
|
||
function addVersion(content, prevContent) {
|
||
var list = document.getElementById('versionList');
|
||
var now = new Date().toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'});
|
||
if (!list) {
|
||
// Первая правка: показываем исходный текст как версию 1
|
||
list = document.createElement('ol');
|
||
list.className = 'ps-history'; list.id = 'versionList'; list.setAttribute('aria-label', 'История изменений');
|
||
var empty = document.getElementById('versionEmpty');
|
||
empty.parentNode.replaceChild(list, empty);
|
||
list.appendChild(versionItem('Исходная версия', prevContent.length.toLocaleString('ru-RU') + ' зн.', prevContent, false));
|
||
}
|
||
var cur = list.querySelector('.is-active');
|
||
if (cur) {
|
||
cur.classList.remove('is-active');
|
||
var badge = cur.querySelector('.ps-history-current');
|
||
if (badge) badge.outerHTML = restoreBtnHtml();
|
||
}
|
||
var n = (+list.getAttribute('data-total') || list.children.length) + 1;
|
||
list.setAttribute('data-total', n);
|
||
list.insertBefore(versionItem('Версия ' + n, now + ' · ' + content.length.toLocaleString('ru-RU') + ' зн.', content, true), list.firstChild);
|
||
var tag = document.getElementById('postVersion');
|
||
tag.hidden = false; tag.textContent = 'Версия ' + n;
|
||
}
|
||
document.addEventListener('click', function (e) {
|
||
var b = e.target.closest('[data-restore]'); if (!b || _aiBusy) return;
|
||
var li = b.closest('.ps-history-item');
|
||
var content = li.querySelector('template[data-content]').content.textContent;
|
||
var prev = _currentPostContent;
|
||
b.disabled = true;
|
||
var fd = new FormData(); fd.append('content', content);
|
||
Press.fetchJSON('/api/posts/' + POST_ID + '/edit-text', { method: 'POST', body: fd })
|
||
.then(function (d) {
|
||
b.disabled = false;
|
||
if (d.ok) {
|
||
setPostContent(d.content);
|
||
addVersion(d.content, prev);
|
||
Press.toast('Версия возвращена', 'success', 'Она стала новой текущей версией.');
|
||
} else { Press.toast('Не удалось вернуть версию', 'danger', Press.humanError(d.error)); }
|
||
})
|
||
.catch(function (err) { b.disabled = false; if (err.message !== Press.SESSION) Press.toast('Не удалось вернуть версию', 'danger', err.message); });
|
||
});
|
||
|
||
/* --- Загрузка фото: только картинки, отправляем сразу после выбора --- */
|
||
(function () {
|
||
var drop = document.getElementById('uploadDrop'), input = document.getElementById('uploadInput'), form = document.getElementById('uploadForm');
|
||
function sendIfImages(files) {
|
||
var imgs = Array.prototype.filter.call(files, function (f) { return /^image\//.test(f.type); });
|
||
if (!imgs.length) { Press.toast('Это не картинка', 'warning', 'Загрузите JPG, PNG или WebP.'); input.value = ''; return; }
|
||
if (imgs.length < files.length) Press.toast('Часть файлов пропущена', 'warning', 'Загружаю только картинки: ' + imgs.length + ' из ' + files.length + '.');
|
||
var dt = new DataTransfer(); imgs.forEach(function (f) { dt.items.add(f); });
|
||
input.files = dt.files;
|
||
form.submit();
|
||
}
|
||
input.addEventListener('change', function () { if (input.files.length) sendIfImages(input.files); });
|
||
drop.addEventListener('dragover', function (e) { e.preventDefault(); drop.classList.add('is-over'); });
|
||
drop.addEventListener('dragleave', function () { drop.classList.remove('is-over'); });
|
||
drop.addEventListener('drop', function (e) { e.preventDefault(); drop.classList.remove('is-over'); if (e.dataTransfer.files.length) sendIfImages(e.dataTransfer.files); });
|
||
})();
|
||
|
||
/* --- Генерация картинки к посту --- */
|
||
(function() {
|
||
var grid = document.getElementById('postImgGrid');
|
||
if (!grid) return;
|
||
grid.addEventListener('click', function(e) {
|
||
var card = e.target.closest('.ps-preset');
|
||
if (!card) return;
|
||
grid.querySelectorAll('.ps-preset').forEach(function(c) { c.classList.toggle('is-selected', c === card); });
|
||
document.getElementById('postImgTaskType').value = 'generate_post_image';
|
||
document.getElementById('postImgTemplateKey').value = card.dataset.key || '';
|
||
document.getElementById('postImgConceptPrompt').value = '';
|
||
document.getElementById('postImgConceptStyle').value = '';
|
||
document.getElementById('postImgConceptSize').value = '';
|
||
runPostImgGeneration('postImgConceptsSection');
|
||
});
|
||
})();
|
||
|
||
function startAnalyzeConcepts() {
|
||
var errEl = document.getElementById('postImgError');
|
||
var loader = document.getElementById('postImgAnalyzeLoader');
|
||
var section = document.getElementById('postImgConceptsSection');
|
||
var conceptsList = document.getElementById('postImgConceptsList');
|
||
if (loader.style.display === 'flex') return;
|
||
|
||
errEl.style.display = 'none';
|
||
section.style.display = 'none';
|
||
conceptsList.style.display = 'none';
|
||
loader.style.display = 'flex';
|
||
|
||
var fd = new FormData();
|
||
fd.append('task_type', 'analyze_post_image');
|
||
fd.append('post_id', POST_ID);
|
||
|
||
function fail(msg) { showError(errEl, msg, section, loader); }
|
||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||
.then(function(data) {
|
||
if (!data.task_id) { fail(data.error || 'Не удалось начать подбор. Повторите.'); return; }
|
||
Press.pollTask(data.task_id, {
|
||
done: function (result) {
|
||
loader.style.display = 'none';
|
||
/* Без концепций — возвращаем кнопки, а не оставляем пустую панель */
|
||
if (Array.isArray(result.concepts) && result.concepts.length) showConcepts(result.concepts);
|
||
else fail('ИИ не предложил концепций. Попробуйте ещё раз или выберите шаблон.');
|
||
},
|
||
fail: fail
|
||
});
|
||
})
|
||
.catch(function(err) { if (err.message !== Press.SESSION) fail(err.message); });
|
||
}
|
||
|
||
function showConcepts(concepts) {
|
||
var styleLabels = {photo: 'Фото', illustration: 'Иллюстрация', minimal: 'Минимализм', '3d': '3D', flat: 'Плоская графика'};
|
||
var sizeLabels = {square: 'Квадрат', wide: 'Широкий', tall: 'Вертикальный'};
|
||
var box = document.getElementById('postImgConcepts');
|
||
box.innerHTML = '';
|
||
box.setAttribute('role', 'list');
|
||
concepts.forEach(function(c, i) {
|
||
var b = document.createElement('button');
|
||
b.type = 'button'; b.className = 'ps-choice'; b.setAttribute('role', 'listitem');
|
||
b.innerHTML = '<span class="ps-choice-body no-icon"><span class="ps-choice-text">' +
|
||
'<span class="ps-choice-kicker"></span><span class="ps-choice-title"></span><span class="ps-choice-desc"></span>' +
|
||
'<span class="app-legend" style="margin-top:var(--space-2)"></span></span></span>';
|
||
b.querySelector('.ps-choice-kicker').textContent = 'Концепция ' + (i + 1);
|
||
b.querySelector('.ps-choice-title').textContent = c.title || '';
|
||
b.querySelector('.ps-choice-desc').textContent = c.description || '';
|
||
var tags = b.querySelector('.app-legend');
|
||
[styleLabels[c.style] || c.style, sizeLabels[c.size] || c.size].forEach(function (t) {
|
||
if (!t) return; var s = document.createElement('span'); s.className = 'ps-post-tag'; s.textContent = t; tags.appendChild(s);
|
||
});
|
||
b.addEventListener('click', function () { selectConcept(i); });
|
||
box.appendChild(b);
|
||
});
|
||
document.getElementById('postImgConceptsList').style.display = '';
|
||
window._postImgConcepts = concepts;
|
||
}
|
||
|
||
function selectConcept(idx) {
|
||
var c = window._postImgConcepts[idx];
|
||
if (!c) return;
|
||
document.getElementById('postImgTaskType').value = 'generate_post_image_with_concept';
|
||
document.getElementById('postImgTemplateKey').value = '';
|
||
document.getElementById('postImgConceptPrompt').value = c.description;
|
||
document.getElementById('postImgConceptStyle').value = c.style || 'none';
|
||
document.getElementById('postImgConceptSize').value = c.size || 'wide';
|
||
runPostImgGeneration('postImgConceptsList');
|
||
}
|
||
|
||
function runPostImgGeneration(hideSectionId) {
|
||
var form = document.getElementById('postImgForm');
|
||
var hideSection = document.getElementById(hideSectionId);
|
||
var genLoader = document.getElementById('postImgGenLoader');
|
||
var errEl = document.getElementById('postImgError');
|
||
if (genLoader.style.display === 'flex') return;
|
||
|
||
errEl.style.display = 'none';
|
||
if (hideSection) hideSection.style.display = 'none';
|
||
genLoader.style.display = 'flex';
|
||
|
||
/* При ошибке возвращаем панель с кнопками — шаблоны и «Подобрать концепцию» */
|
||
function fail(msg) { showError(errEl, msg, document.getElementById('postImgConceptsSection'), genLoader); }
|
||
var fd = new FormData(form);
|
||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||
.then(function(data) {
|
||
if (!data.task_id) { fail(data.error || 'Не удалось начать генерацию. Повторите.'); return; }
|
||
Press.pollTask(data.task_id, {
|
||
done: function () {
|
||
genLoader.style.display = 'none';
|
||
Press.toast('Картинка готова', 'success', 'Обновляю пост…');
|
||
setTimeout(function () { location.reload(); }, 900);
|
||
},
|
||
fail: fail
|
||
});
|
||
})
|
||
.catch(function(err) { if (err.message !== Press.SESSION) fail(err.message); });
|
||
}
|
||
|
||
function resetConcepts() {
|
||
document.getElementById('postImgResult').style.display = 'none';
|
||
document.getElementById('postImgConceptsList').style.display = 'none';
|
||
document.getElementById('postImgConceptsSection').style.display = '';
|
||
document.getElementById('postImgError').style.display = 'none';
|
||
document.getElementById('postImgGenLoader').style.display = 'none';
|
||
document.getElementById('postImgAnalyzeLoader').style.display = 'none';
|
||
}
|
||
|
||
function showError(el, msg, showSection, hideLoader) {
|
||
if (hideLoader) hideLoader.style.display = 'none';
|
||
if (showSection) showSection.style.display = '';
|
||
el.textContent = Press.humanError(msg); el.title = msg || '';
|
||
el.style.display = 'flex';
|
||
}
|
||
</script>
|
||
{% endblock %}
|