source: Klonkt/src/views/pages/post-edit.ejs@ e9c9ae1

main
Last change on this file since e9c9ae1 was c06816e, checked in by roboburr <roboburr@…>, 2 months ago

feat(audio): sharing openly on the fediverse is one-way + lock the editor choice

Once a track has federated openly the file is out there — re-gating would be false
security. Opening is now permanent: the flag can be set but never cleared, the editor
locks the checkbox once open, and warns before you tick it. Default stays closed
(safe default; self-hosters choose per track).

  • src/routes/posts.js — setAudioFediOpen never writes fedi_open back to 0 (one-way).
  • src/views/pages/post-edit.ejs — locked (checked+disabled) checkbox with an explainer once open; a red permanence warning appears when ticking it on a gated post. Also fixes the poll fields showing while "Add a poll" was unchecked: the conditional style attribute was emitted through an escaping tag, turning it into entity soup — the condition now lives inside the quoted attribute.
  • src/services/i18n.js — pedit.fedi_audio_oneway + pedit.fedi_audio_locked (nl/en/de).
  • CHANGELOG(.nl/.de).md — "Sharing audio openly is now one-way" under Changed.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 104.0 KB
Line 
1<%
2// Post editor — split into card sections for visual hierarchy:
3// - Identity : title, slug, excerpt
4// - Cover : thumbnail + URL + custom upload button
5// - Content : markdown textarea with attached toolbar
6// - Meta : status, type, pin, noindex, tags
7//
8// All behavior (IDs, names, upload endpoints) is preserved — only layout
9// and styling changed.
10const _hasCover = !!post.cover_image_url;
11// In hub mode, save/create/cancel must carry the /user/<slug>/ prefix, otherwise
12// the request falls back to the primary site (siteUrlBase empty) and the post
13// renders headerless (bareChrome) after saving. In solo mode _base is empty.
14const _base = (typeof siteUrlBase !== 'undefined' && siteUrlBase) ? siteUrlBase : '';
15%>
16<div class="container post-edit-page">
17 <h1><%= isNew ? t('pedit.title_new') : t('pedit.title_edit') %></h1>
18
19 <form method="post" action="<%= _base %><%= isNew ? '/posts/create' : '/posts/' + post.slug + '/save' %>" class="post-edit-form">
20
21 <%# ── TYPE (segmented) + type-specific inputs ────────────────
22 Post type lives at the TOP (above the body), and the selected type
23 reveals its own input: Audio → inline upload, Video → embed URL,
24 Foto → cover/insert hint. %>
25 <% var ptype = post.type || 'post'; %>
26 <% var TYPE_ICONS = { post: '📝', foto: '📷', video: '🎬', audio: '🎵' }; %>
27 <section class="pe-card pe-type-card">
28 <div class="pe-section-title"><%= t('pedit.s_type') %></div>
29 <input type="hidden" name="type" id="pe-type-input" value="<%= ptype %>">
30 <div class="pe-typeseg" role="radiogroup" aria-label="<%= t('pedit.s_type') %>">
31 <% ['post','foto','video','audio'].forEach(function (tt) { %>
32 <button type="button" class="pe-typeseg-btn<%= ptype === tt ? ' is-active' : '' %>"
33 data-type="<%= tt %>" role="radio" aria-checked="<%= ptype === tt ? 'true' : 'false' %>">
34 <span class="pe-typeseg-ic" aria-hidden="true"><%= TYPE_ICONS[tt] %></span>
35 <span><%= t('pedit.type_' + tt) %></span>
36 </button>
37 <% }); %>
38 </div>
39
40 <%# Audio: inline upload (transcodes + drops [[track]] into the post) %>
41 <div class="pe-type-panel" data-panel="audio" hidden>
42 <div class="pe-audio-up" id="pe-audio-drop" tabindex="0" role="button" aria-label="<%= t('pedit.audio_up_drop') %>">
43 <input type="file" id="pe-audio-file" accept="audio/*,.mp3,.m4a,.ogg,.opus,.flac,.wav" multiple hidden>
44 <span class="pe-audio-up-ic" aria-hidden="true">🎵</span>
45 <strong><%= t('pedit.audio_up_drop') %></strong>
46 <small><%= t('pedit.audio_up_hint') %></small>
47 </div>
48 <ul class="pe-audio-list" id="pe-audio-list"></ul>
49 </div>
50
51 <%# Video: paste a URL → embed chip %>
52 <div class="pe-type-panel" data-panel="video" hidden>
53 <label class="pe-field">
54 <span><%= t('pedit.video_up_title') %></span>
55 <div class="pe-video-row">
56 <input type="url" id="pe-video-url" inputmode="url" autocapitalize="none" spellcheck="false"
57 placeholder="<%= t('pedit.video_up_ph') %>">
58 <button type="button" class="pe-btn pe-btn-secondary" id="pe-video-insert"><%= t('pedit.video_up_btn') %></button>
59 </div>
60 </label>
61 </div>
62
63 <%# Foto: light hint toward cover + insert-image %>
64 <div class="pe-type-panel" data-panel="foto" hidden>
65 <p class="pe-foto-hint">🖼 <%= t('pedit.foto_up_hint') %></p>
66 </div>
67 </section>
68
69 <%# ── IDENTITY ─────────────────────────────────────────────── %>
70 <section class="pe-card">
71 <label class="pe-field">
72 <span><%= t('pedit.f_title') %></span>
73 <input type="text" name="title" value="<%= post.title %>" required>
74 </label>
75 <div class="pe-row pe-row-2">
76 <label class="pe-field">
77 <span><%= t('pedit.f_slug') %></span>
78 <input type="text" name="slug" value="<%= post.slug %>" placeholder="<%= t('pedit.slug_placeholder') %>">
79 </label>
80 <label class="pe-field">
81 <span><%= t('pedit.f_tags') %> <small><%= t('pedit.tags_hint') %></small></span>
82 <input type="text" name="tags" value="<%= Array.isArray(post.tags) ? post.tags.join(', ') : '' %>">
83 </label>
84 </div>
85 <label class="pe-field">
86 <span><%= t('pedit.f_excerpt') %></span>
87 <textarea name="excerpt" rows="2"><%= post.excerpt %></textarea>
88 <small class="pe-hint" style="opacity:.7"><%- t('pedit.excerpt_hint') %></small>
89 </label>
90 <% var _postLang = (typeof post.language !== 'undefined' && post.language) ? post.language : (typeof lang !== 'undefined' ? lang : 'en'); %>
91 <label class="pe-field">
92 <span><%= t('pedit.f_language') %> <small><%= t('pedit.language_hint') %></small></span>
93 <select name="language" id="pe-language" style="max-width:220px">
94 <% [['en','English'],['nl','Nederlands'],['de','Deutsch'],['fr','Français'],['es','Español'],['it','Italiano'],['pt','Português'],['pl','Polski'],['ru','Русский'],['uk','Українська'],['sv','Svenska'],['da','Dansk'],['nb','Norsk'],['fi','Suomi'],['tr','Türkçe'],['ja','日本語'],['zh','中文'],['ar','العربية']].forEach(function (l) { %>
95 <option value="<%= l[0] %>" <%= l[0] === _postLang ? 'selected' : '' %>><%= l[1] %></option>
96 <% }); %>
97 </select>
98 </label>
99 </section>
100
101 <%# ── COVER ────────────────────────────────────────────────── %>
102 <section class="pe-card">
103 <div class="pe-section-title"><%= t('pedit.s_cover') %></div>
104 <div class="pe-cover-row">
105 <div class="pe-cover-thumb" id="cover-preview-wrap" <%= _hasCover ? '' : 'data-empty' %>>
106 <img src="<%= _hasCover ? post.cover_image_url : '' %>" alt="" id="cover-preview-img" <%= _hasCover ? '' : 'hidden' %>>
107 <% if (!_hasCover) { %><span class="pe-cover-empty">🖼</span><% } %>
108 </div>
109 <div class="pe-cover-actions">
110 <label class="pe-field">
111 <span><%= t('pedit.f_cover_url') %></span>
112 <input type="text" name="cover_image_url" id="cover-url-field"
113 value="<%= post.cover_image_url || '' %>"
114 inputmode="url" autocapitalize="none" spellcheck="false"
115 placeholder="<%= t('pedit.cover_url_placeholder') %>">
116 </label>
117 <label class="pe-field">
118 <span><%= t('pedit.f_cover_alt') %></span>
119 <input type="text" name="cover_alt" id="cover-alt-field" maxlength="1500"
120 value="<%= post.cover_alt || '' %>"
121 placeholder="<%= t('pedit.cover_alt_placeholder') %>">
122 </label>
123 <%# Muted loop MP4 for an animated cover (auto-made from an animated WebP). Hidden — set by the uploader. %>
124 <input type="hidden" name="cover_video_url" id="cover-video-field" value="<%= post.cover_video_url || '' %>">
125 <div class="pe-cover-upload">
126 <button type="button" class="pe-btn pe-btn-secondary" id="cover-upload-trigger">
127 📷 <%= t('pedit.cover_upload_btn') %>
128 </button>
129 <input type="file" id="cover-upload-field" accept="image/jpeg,image/png,image/webp,image/gif" hidden>
130 <small id="cover-upload-status" class="pe-status"></small>
131 </div>
132 </div>
133 </div>
134 </section>
135
136 <%# ── CONTENT ──────────────────────────────────────────────── %>
137 <section class="pe-card pe-card-content">
138 <div class="pe-section-title">
139 <%= t('pedit.s_content') %>
140 <small class="pe-content-hint"><%= t('pedit.content_hint') %></small>
141 </div>
142 <div class="pe-editor-frame">
143 <div class="pe-toolbar" id="pe-toolbar" role="toolbar" aria-label="Format">
144 <button type="button" id="pe-fs-done" class="pe-fs-done" title="<%= t('pedit.tb_done_title') %>">✓ <%= t('pedit.tb_done') %></button>
145 <button type="button" data-cmd="bold" title="<%= t('pedit.tb_bold_title') %>" aria-label="<%= t('pedit.tb_bold') %>">
146 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 4h8a4 4 0 0 1 0 8H6z"/><path d="M6 12h9a4 4 0 0 1 0 8H6z"/></svg>
147 </button>
148 <button type="button" data-cmd="italic" title="<%= t('pedit.tb_italic_title') %>" aria-label="<%= t('pedit.tb_italic') %>">
149 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>
150 </button>
151 <button type="button" data-cmd="underline" title="<%= t('pedit.tb_underline') %>" aria-label="<%= t('pedit.tb_underline') %>">
152 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 4v6a6 6 0 0 0 12 0V4"/><line x1="4" y1="20" x2="20" y2="20"/></svg>
153 </button>
154 <span class="pe-toolbar-sep" aria-hidden="true"></span>
155 <button type="button" class="pe-tb-text" data-cmd="formatBlock" data-arg="h2" title="<%= t('pedit.tb_h2') %>">H2</button>
156 <button type="button" class="pe-tb-text" data-cmd="formatBlock" data-arg="h3" title="<%= t('pedit.tb_h3') %>">H3</button>
157 <button type="button" class="pe-tb-text" data-cmd="formatBlock" data-arg="p" title="<%= t('pedit.tb_p') %>">¶</button>
158 <span class="pe-toolbar-sep" aria-hidden="true"></span>
159 <button type="button" data-cmd="insertUnorderedList" title="<%= t('pedit.tb_ul') %>" aria-label="<%= t('pedit.tb_ul') %>">
160 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1.2"/><circle cx="4.5" cy="12" r="1.2"/><circle cx="4.5" cy="18" r="1.2"/></svg>
161 </button>
162 <button type="button" data-cmd="insertOrderedList" title="<%= t('pedit.tb_ol') %>" aria-label="<%= t('pedit.tb_ol') %>">
163 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><path d="M4 6h1v4"/><path d="M4 10h2"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/></svg>
164 </button>
165 <button type="button" data-cmd="formatBlock" data-arg="blockquote" title="<%= t('pedit.tb_quote') %>" aria-label="<%= t('pedit.tb_quote') %>">
166 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.75-2-2-2H4c-1.25 0-2 .75-2 2v6c0 1.25.75 2 2 2h2.5C6 17.5 4 19 3 19v2z"/><path d="M14 21c3 0 7-1 7-8V5c0-1.25-.75-2-2-2h-4c-1.25 0-2 .75-2 2v6c0 1.25.75 2 2 2h2.5c-.5 4.5-2.5 6-3.5 6v2z"/></svg>
167 </button>
168 <button type="button" data-cmd="link-prompt" title="<%= t('pedit.tb_link_title') %>" aria-label="<%= t('pedit.tb_link') %>">
169 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
170 </button>
171 <button type="button" data-cmd="code-wrap" title="<%= t('pedit.tb_code_title') %>" aria-label="<%= t('pedit.tb_code') %>">
172 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
173 </button>
174 <span class="pe-toolbar-sep" aria-hidden="true"></span>
175 <button type="button" id="insert-image-btn" title="<%= t('pedit.tb_image_title') %>" aria-label="<%= t('pedit.tb_image') %>">
176 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
177 </button>
178 <button type="button" id="insert-track-btn" title="<%= t('pedit.tb_track_title') %>" aria-label="<%= t('pedit.tb_track') %>">
179 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
180 </button>
181 <button type="button" id="insert-playlist-btn" title="<%= t('pedit.tb_playlist_title') %>" aria-label="<%= t('pedit.tb_playlist') %>">
182 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="15" y2="18"/><polygon points="3 5 3 13 9 9"/></svg>
183 </button>
184 <button type="button" id="insert-embed-btn" title="<%= t('pedit.tb_embed_title') %>" aria-label="<%= t('pedit.tb_embed') %>">
185 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="4" width="20" height="16" rx="2"/><polygon points="10 9 15.5 12 10 15"/></svg>
186 </button>
187 <span class="pe-toolbar-spacer"></span>
188 <button type="button" data-cmd="removeFormat" title="<%= t('pedit.tb_clear') %>" aria-label="<%= t('pedit.tb_clear') %>">
189 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M5 5l14 14" stroke-linecap="round"/></svg>
190 </button>
191 <button type="button" id="pe-fullscreen-btn" title="<%= t('pedit.tb_fullscreen') %>" aria-label="<%= t('pedit.tb_fullscreen') %>" aria-pressed="false">
192 <svg class="fs-icon-expand" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
193 <svg class="fs-icon-compress" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/><line x1="14" y1="10" x2="21" y2="3"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
194 </button>
195 </div>
196
197 <div id="content-editor"
198 class="pe-editor"
199 contenteditable="true"
200 role="textbox"
201 aria-multiline="true"
202 aria-label="<%= t('pedit.editor_aria') %>"></div>
203
204 <%# Sticky "tap to edit" hint (only visible on touch + non-fullscreen
205 via CSS). Purely visual (pointer-events:none); tapping the field opens fullscreen. %>
206 <div class="pe-edit-hint" aria-hidden="true">✎ <%= t('pedit.tap_to_edit') %></div>
207
208 <%# Hidden field is what actually submits to the server. The visible
209 contenteditable's serialized HTML is copied here on submit. %>
210 <input type="hidden" name="content" id="content-hidden" value="">
211
212 <%# Initial content is injected as a JSON string in a script tag so we
213 can set innerHTML safely from JS. EJS-escaping HTML directly into
214 the editor would render entity-escaped tags as text. %>
215 <script id="initial-content" type="application/json"><%- JSON.stringify(post.content || '').replace(/</g, '\\u003c') %></script>
216
217 <div class="pe-editor-status">
218 <small id="content-upload-status" class="pe-status"></small>
219 <span class="pe-char-count"><span id="char-count">0</span> <%= t('pedit.chars') %></span>
220 </div>
221
222 <input type="file" id="content-upload-field" accept="image/jpeg,image/png,image/webp,image/gif" hidden>
223 </div>
224 </section>
225
226 <%# ── META ─────────────────────────────────────────────────── %>
227 <section class="pe-card">
228 <div class="pe-section-title"><%= t('pedit.s_publication') %></div>
229 <label class="pe-field">
230 <span><%= t('pedit.f_status') %></span>
231 <% var _st = isNew ? 'published' : (post.status || 'draft'); %>
232 <select name="status">
233 <option value="published" <%= _st === 'published' ? 'selected' : '' %>><%= t('pedit.status_published') %></option>
234 <option value="draft" <%= _st === 'draft' ? 'selected' : '' %>><%= t('pedit.status_draft') %></option>
235 <option value="archived" <%= _st === 'archived' ? 'selected' : '' %>><%= t('pedit.status_archived') %></option>
236 </select>
237 </label>
238 <div class="pe-checkboxes">
239 <div class="pe-pin">
240 <label class="pe-checkbox">
241 <input type="checkbox" id="pin-toggle" <%= (Number(post.pinned) > 0) ? 'checked' : '' %>>
242 <span>📌 <%= t('pedit.pin_label') %></span>
243 </label>
244 <input type="hidden" name="pinned" id="pin-rank" value="<%= post.pinned || 0 %>">
245 <div class="pe-pin-pos" id="pin-pos" <%= (Number(post.pinned) > 0) ? '' : 'hidden' %>>
246 <span class="pe-pin-steps">
247 <button type="button" class="pe-pin-btn" id="pin-up" aria-label="<%= t('pedit.pin_up') %>">▲</button>
248 <button type="button" class="pe-pin-btn" id="pin-down" aria-label="<%= t('pedit.pin_down') %>">▼</button>
249 </span>
250 <span class="pe-pin-label" id="pin-label"></span>
251 </div>
252 </div>
253 <label class="pe-checkbox">
254 <input type="checkbox" name="noindex" value="1" <%= post.noindex ? 'checked' : '' %>>
255 <span>🚫 <%= t('pedit.noindex_label') %></span>
256 </label>
257 <label class="pe-checkbox">
258 <input type="checkbox" name="nsfw" value="1" id="pe-nsfw" <%= post.nsfw ? 'checked' : '' %>>
259 <span>🔞 <%= t('pedit.nsfw_label') %></span>
260 </label>
261 <input type="text" name="content_warning" id="pe-cw" value="<%= post.content_warning || '' %>" maxlength="200"
262 placeholder="<%= t('pedit.nsfw_cw_ph') %>"
263 style="width:100%;box-sizing:border-box;margin:6px 0 2px;font-size:13px;padding:7px 9px">
264 <% var _fediOpen = (typeof fediOpenAudio !== 'undefined' && fediOpenAudio); %>
265 <label class="pe-checkbox">
266 <%# One-way: once opened, the file has federated — re-gating would be false security, so the box locks. %>
267 <input type="checkbox" name="fedi_open_audio" value="1" id="pe-fedi-audio" <%= _fediOpen ? 'checked disabled' : '' %>>
268 <span>🌐 <%= t('pedit.fedi_audio_label') %></span>
269 </label>
270 <% if (_fediOpen) { %>
271 <p style="font-size:12px;opacity:.7;margin:2px 0 0 26px"><%= t('pedit.fedi_audio_locked') %></p>
272 <% } else { %>
273 <p id="pe-fedi-audio-warn" style="font-size:12px;color:#c0392b;margin:2px 0 0 26px" hidden>⚠️ <%= t('pedit.fedi_audio_oneway') %></p>
274 <script>
275 (function () {
276 var cb = document.getElementById('pe-fedi-audio'), w = document.getElementById('pe-fedi-audio-warn');
277 if (cb && w && !cb.__wired) { cb.__wired = true; cb.addEventListener('change', function () { w.hidden = !cb.checked; }); }
278 })();
279 </script>
280 <% } %>
281 <script>
282 (function () {
283 var cw = document.getElementById('pe-cw'), nsfw = document.getElementById('pe-nsfw');
284 // Typing a warning text implies the post is sensitive → auto-tick NSFW.
285 if (cw && nsfw && !cw.__nsfwWired) { cw.__nsfwWired = true;
286 cw.addEventListener('input', function () { if (cw.value.trim()) nsfw.checked = true; });
287 }
288 })();
289 </script>
290 <% // Poll (federates as an AS2 Question). Free feature. A poll with votes is frozen.
291 var _poll = null; try { _poll = post.poll_json ? JSON.parse(post.poll_json) : null; } catch (e) { _poll = null; }
292 var _pollLocked = (typeof pollLocked !== 'undefined' && pollLocked);
293 var _pollOpts = (_poll && Array.isArray(_poll.options) && _poll.options.length) ? _poll.options : [{ name: '' }, { name: '' }]; %>
294 <label class="pe-checkbox" style="margin-top:8px">
295 <input type="checkbox" name="poll_enabled" value="1" id="pe-poll-toggle" <%= _poll ? 'checked' : '' %> <%= _pollLocked ? 'disabled' : '' %>>
296 <span>📊 <%= t('pedit.poll_label') %></span>
297 </label>
298 <style>
299 .pe-poll { margin-top: 6px; }
300 .pe-poll-locked { font-size: 12px; opacity: .7; margin: 0 0 6px; }
301 .pe-poll-row { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
302 .pe-poll-opt { flex: 1; min-width: 0; box-sizing: border-box; font-size: 13px; padding: 7px 9px; border-radius: 7px; border: 1px solid var(--rule, rgba(128,128,128,.35)); background: transparent; color: inherit; }
303 .pe-poll-opt:focus { outline: none; border-color: var(--accent); }
304 .pe-poll-del { flex: 0 0 auto; width: 30px; height: 32px; display: inline-flex; align-items: center; justify-content: center; font-size: 18px; line-height: 1; border: 1px solid var(--rule, rgba(128,128,128,.35)); border-radius: 7px; background: transparent; color: var(--ink-muted, #999); cursor: pointer; transition: color .12s, border-color .12s; }
305 .pe-poll-del:hover { border-color: #c0392b; color: #c0392b; }
306 .pe-poll-del[hidden] { display: none; }
307 .pe-poll-add { display: block; width: fit-content; font-size: 12.5px; padding: 6px 12px; border-radius: 7px; border: 1px dashed var(--rule, rgba(128,128,128,.45)); background: transparent; color: inherit; cursor: pointer; margin: 0 0 10px; transition: color .12s, border-color .12s; }
308 .pe-poll-add:hover { border-color: var(--accent); color: var(--accent); }
309 .pe-poll-add:disabled { opacity: .4; cursor: default; border-style: dashed; }
310 .pe-poll-durlabel { display: block; font-size: 12.5px; opacity: .8; margin: 8px 0 4px; }
311 .pe-poll-dur { padding: 7px 9px; border-radius: 7px; border: 1px solid var(--rule, rgba(128,128,128,.35)); background: transparent; color: inherit; font-size: 13px; }
312 </style>
313 <%# NB: keep the condition INSIDE the quoted attribute — escaped output (equals-tag)
314 turns a whole emitted style attribute into entity soup (fields showed always). %>
315 <div id="pe-poll-fields" class="pe-poll" style="<%= _poll ? '' : 'display:none' %>">
316 <% if (_pollLocked) { %><p class="pe-poll-locked"><%= t('pedit.poll_locked') %></p><% } %>
317 <div id="pe-poll-opts" data-ph="<%= t('pedit.poll_option_ph') %>" data-del="<%= t('pedit.poll_remove') %>">
318 <% _pollOpts.forEach(function (o) { %>
319 <div class="pe-poll-row">
320 <input type="text" name="poll_option" class="pe-poll-opt" maxlength="100" value="<%= (o && o.name) || '' %>" placeholder="<%= t('pedit.poll_option_ph') %>" <%= _pollLocked ? 'disabled' : '' %>>
321 <% if (!_pollLocked) { %><button type="button" class="pe-poll-del" aria-label="<%= t('pedit.poll_remove') %>" title="<%= t('pedit.poll_remove') %>">&times;</button><% } %>
322 </div>
323 <% }); %>
324 </div>
325 <% if (!_pollLocked) { %><button type="button" id="pe-poll-add" class="pe-poll-add">+ <%= t('pedit.poll_add') %></button><% } %>
326 <label class="pe-checkbox">
327 <input type="checkbox" name="poll_multiple" value="1" <%= (_poll && _poll.multiple) ? 'checked' : '' %> <%= _pollLocked ? 'disabled' : '' %>>
328 <span><%= t('pedit.poll_multiple') %></span>
329 </label>
330 <label class="pe-poll-durlabel"><%= t('pedit.poll_duration') %></label>
331 <select name="poll_duration" class="pe-poll-dur" <%= _pollLocked ? 'disabled' : '' %>>
332 <% [['300','5m'],['1800','30m'],['3600','1h'],['21600','6h'],['43200','12h'],['86400','1d'],['259200','3d'],['604800','7d']].forEach(function (d) { %>
333 <option value="<%= d[0] %>" <%= d[0] === '86400' ? 'selected' : '' %>><%= t('pedit.poll_dur_' + d[1]) %></option>
334 <% }); %>
335 </select>
336 </div>
337 <script>
338 (function () {
339 var box = document.getElementById('pe-poll-fields');
340 var tog = document.getElementById('pe-poll-toggle');
341 var opts = document.getElementById('pe-poll-opts');
342 var add = document.getElementById('pe-poll-add');
343 if (!box || !opts) return;
344 if (tog && !tog.__wired) { tog.__wired = true; tog.addEventListener('change', function () { box.style.display = tog.checked ? '' : 'none'; }); }
345 var PH = opts.getAttribute('data-ph') || '', DEL = opts.getAttribute('data-del') || '';
346 function rows() { return opts.querySelectorAll('.pe-poll-row'); }
347 // A poll needs at least 2 options: hide the ✕ at the minimum, and cap adding at 8.
348 function refresh() {
349 var n = rows().length;
350 opts.querySelectorAll('.pe-poll-del').forEach(function (b) { b.hidden = n <= 2; });
351 if (add) add.disabled = n >= 8;
352 }
353 function makeRow() {
354 var row = document.createElement('div'); row.className = 'pe-poll-row';
355 var i = document.createElement('input'); i.type = 'text'; i.name = 'poll_option'; i.className = 'pe-poll-opt'; i.maxLength = 100; i.placeholder = PH;
356 var d = document.createElement('button'); d.type = 'button'; d.className = 'pe-poll-del'; d.setAttribute('aria-label', DEL); d.title = DEL; d.innerHTML = '&times;';
357 row.appendChild(i); row.appendChild(d); return row;
358 }
359 if (add && !add.__wired) { add.__wired = true; add.addEventListener('click', function () { if (rows().length >= 8) return; opts.appendChild(makeRow()); refresh(); }); }
360 if (!opts.__wired) { opts.__wired = true; opts.addEventListener('click', function (e) { var d = e.target.closest('.pe-poll-del'); if (!d || rows().length <= 2) return; d.closest('.pe-poll-row').remove(); refresh(); }); }
361 refresh();
362 })();
363 </script>
364 <% if (typeof premiumUnlocked === 'undefined' || premiumUnlocked) { %>
365 <label class="pe-checkbox">
366 <input type="checkbox" name="fan_only" value="1" <%= post.fan_only ? 'checked' : '' %>>
367 <span>🔒 <%= t('pedit.fan_only_label') %></span>
368 </label>
369 <% var _scheduled = !!(post.publish_at && (post.status === 'scheduled' || Date.parse(String(post.publish_at).replace(' ', 'T')) > Date.now())); %>
370 <label class="pe-checkbox" style="margin-top:8px">
371 <input type="checkbox" name="schedule_enabled" value="1" id="pe-sched-toggle" <%= _scheduled ? 'checked' : '' %>>
372 <span>📅 <%= t('pedit.schedule_label') %></span>
373 </label>
374 <div id="pe-sched-fields" style="margin-top:6px;<%= _scheduled ? '' : 'display:none' %>">
375 <label style="display:block;font-size:12.5px;opacity:.8;margin-bottom:4px"><%= t('pedit.publish_at_label') %></label>
376 <input type="datetime-local" id="pe-publish-at" name="publish_at" <%= _scheduled ? '' : 'disabled' %> data-iso="<%= post.publish_at || '' %>" value="" style="padding:8px 10px;border-radius:8px;border:1px solid var(--rule,rgba(128,128,128,.4));background:transparent;color:inherit">
377 <% if (post.status === 'scheduled' && post.publish_at) { %><div style="font-size:12px;opacity:.7;margin-top:4px"><span id="pe-sched-when" data-iso="<%= post.publish_at %>" data-label="<%= t('pedit.scheduled_prefix') %>">⏳ <%= t('pedit.scheduled_for', { d: post.publish_at }) %></span></div><% } %>
378 <div style="font-size:11.5px;opacity:.65;margin-top:4px"><%= t('pedit.schedule_hint') %></div>
379 </div>
380 <script>
381 (function () {
382 var cb = document.getElementById('pe-sched-toggle');
383 var box = document.getElementById('pe-sched-fields');
384 if (!cb || !box) return;
385 var inp = document.getElementById('pe-publish-at');
386 var SITE_TZ = '<%= timezone || '' %>'; // configured site timezone; empty = browser local
387 var pad = function (n) { return String(n).padStart(2, '0'); };
388 // Offset (ms) between a timezone and UTC at a given moment.
389 function tzOffset(date, tz) {
390 var f = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
391 var p = {}; f.formatToParts(date).forEach(function (x) { p[x.type] = x.value; });
392 return Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second) - date.getTime();
393 }
394 // datetime-local "wall time" (in the site zone) → UTC Date.
395 function wallToUtc(wall) {
396 if (!SITE_TZ) return new Date(wall);
397 var guess = new Date(wall + ':00Z').getTime();
398 return new Date(guess - tzOffset(new Date(guess), SITE_TZ));
399 }
400 // UTC-ISO → "YYYY-MM-DDTHH:MM" wall time in the site zone.
401 function utcToWall(iso) {
402 var d = new Date(iso); if (isNaN(d)) return '';
403 if (!SITE_TZ) return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
404 var f = new Intl.DateTimeFormat('en-CA', { timeZone: SITE_TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
405 var p = {}; f.formatToParts(d).forEach(function (x) { p[x.type] = x.value; });
406 return p.year + '-' + p.month + '-' + p.day + 'T' + p.hour + ':' + p.minute;
407 }
408 // Prefill: stored UTC → wall time in the site zone.
409 if (inp && inp.dataset.iso) inp.value = utcToWall(inp.dataset.iso);
410 // "Scheduled for" in human-readable time in the site zone.
411 var when = document.getElementById('pe-sched-when');
412 if (when && when.dataset.iso) {
413 var dw = new Date(when.dataset.iso);
414 if (!isNaN(dw)) when.textContent = '⏳ ' + when.dataset.label + ' ' + dw.toLocaleString(undefined, SITE_TZ ? { timeZone: SITE_TZ } : undefined);
415 }
416 function sync() { box.style.display = cb.checked ? '' : 'none'; if (inp) inp.disabled = !cb.checked; }
417 cb.addEventListener('change', sync); sync();
418 // On save: wall time in the site zone → UTC-ISO via a hidden field.
419 var form = cb.closest('form');
420 if (form) {
421 form.addEventListener('submit', function () {
422 if (inp) inp.removeAttribute('name');
423 var old = form.querySelector('input[data-pa-utc]');
424 if (old) old.remove();
425 if (cb.checked && inp && inp.value) {
426 var d2 = wallToUtc(inp.value);
427 if (!isNaN(d2)) {
428 var h = document.createElement('input');
429 h.type = 'hidden'; h.name = 'publish_at'; h.setAttribute('data-pa-utc', '');
430 h.value = d2.toISOString();
431 form.appendChild(h);
432 }
433 }
434 });
435 }
436 })();
437 </script>
438 <% } %>
439 </div>
440 </section>
441
442 <%# ── ACTIONS (sticky at bottom) ──────────────────────────── %>
443 <div class="pe-actions">
444 <a href="<%= _base %><%= isNew ? '/' : '/' + post.slug %>" class="pe-btn"><%= t('pedit.cancel') %></a>
445 <div class="pe-actions-spacer"></div>
446 <% if (!isNew && post.status !== 'published') { %>
447 <button type="submit" name="action" value="publish" class="pe-btn pe-btn-success">📤 <%= t('pedit.publish') %></button>
448 <% } %>
449 <button type="submit" class="pe-btn pe-btn-primary">💾 <%= t('pedit.save') %></button>
450 </div>
451 </form>
452</div>
453
454<style>
455/* ─── Page wrapper ──────────────────────────────────────────────── */
456.post-edit-page {
457 max-width: 880px;
458 margin: 1.5rem auto 6rem; /* extra bottom for sticky-actions clearance */
459 padding: 0 1rem;
460}
461.post-edit-page h1 {
462 font-family: var(--font-display, serif);
463 margin: 0 0 1.25rem;
464 font-size: 1.75rem;
465}
466
467.post-edit-form {
468 display: flex; flex-direction: column;
469 gap: 1rem;
470}
471
472/* ─── Card sections ─────────────────────────────────────────────── */
473.pe-card {
474 background: var(--paper);
475 border: 1px solid var(--rule);
476 border-radius: 12px;
477 padding: 1.25rem;
478 display: flex; flex-direction: column;
479 gap: 0.85rem;
480}
481.pe-card-content { padding-bottom: 0; overflow: hidden; } /* editor flush to bottom */
482.pe-section-title {
483 font-size: 0.8rem;
484 font-weight: 600;
485 text-transform: uppercase;
486 letter-spacing: 0.05em;
487 color: var(--ink-soft);
488 display: flex; align-items: baseline; gap: 0.5rem;
489 flex-wrap: wrap;
490}
491.pe-section-title small {
492 font-size: 0.75rem; font-weight: 400;
493 letter-spacing: 0; text-transform: none;
494 color: var(--ink-muted, var(--ink-soft));
495}
496
497/* ─── Field primitives ──────────────────────────────────────────── */
498.pe-field {
499 display: flex; flex-direction: column;
500 gap: 0.35rem;
501 min-width: 0; /* allow grid items to shrink */
502}
503.pe-field > span {
504 font-size: 0.8rem;
505 font-weight: 600;
506 color: var(--ink-soft);
507 display: flex; align-items: baseline; gap: 0.4rem;
508}
509.pe-field > span small {
510 font-weight: 400; color: var(--ink-muted);
511}
512.pe-field input,
513.pe-field textarea,
514.pe-field select {
515 width: 100%;
516 box-sizing: border-box;
517 display: block;
518 padding: 0.6rem 0.75rem;
519 border: 1px solid var(--rule);
520 border-radius: 6px;
521 background: var(--paper-2);
522 color: var(--ink);
523 font-family: var(--font-ui, system-ui), sans-serif;
524 font-size: 0.95rem;
525 -webkit-appearance: none;
526 appearance: none;
527 transition: border-color 120ms;
528}
529.pe-field input:focus,
530.pe-field textarea:focus,
531.pe-field select:focus {
532 outline: 2px solid var(--accent);
533 outline-offset: -1px;
534 border-color: var(--accent);
535}
536.pe-field textarea {
537 font-family: var(--font-mono, monospace);
538 resize: vertical;
539}
540.pe-field select {
541 /* Restore the dropdown arrow we removed with appearance:none */
542 background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>");
543 background-repeat: no-repeat;
544 background-position: right 0.75rem center;
545 padding-right: 2rem;
546}
547
548.pe-row {
549 display: grid;
550 gap: 0.75rem;
551}
552.pe-row-2 { grid-template-columns: 1fr 1fr; }
553@media (max-width: 600px) {
554 .pe-row-2 { grid-template-columns: 1fr; }
555}
556
557/* ─── Cover field ───────────────────────────────────────────────── */
558.pe-cover-row {
559 display: grid;
560 grid-template-columns: 120px 1fr;
561 gap: 1rem;
562 align-items: start;
563}
564.pe-cover-thumb {
565 width: 120px; height: 120px;
566 border-radius: 10px;
567 overflow: hidden;
568 background: var(--paper-2);
569 border: 1px solid var(--rule);
570 display: flex; align-items: center; justify-content: center;
571 position: relative;
572}
573.pe-cover-thumb[data-empty] {
574 border-style: dashed;
575}
576.pe-cover-thumb img {
577 width: 100%; height: 100%;
578 object-fit: cover; display: block;
579}
580/* Honor HTML hidden — our display:block above otherwise renders an empty
581 broken-image icon when no cover is set. */
582.pe-cover-thumb img[hidden] { display: none; }
583.pe-cover-empty {
584 font-size: 2rem;
585 color: var(--ink-muted, var(--ink-soft));
586 opacity: 0.5;
587}
588.pe-cover-actions {
589 display: flex; flex-direction: column;
590 gap: 0.6rem;
591 min-width: 0;
592}
593.pe-cover-upload {
594 display: flex; align-items: center; gap: 0.6rem;
595 flex-wrap: wrap;
596}
597@media (max-width: 600px) {
598 .pe-cover-row { grid-template-columns: 88px 1fr; }
599 .pe-cover-thumb { width: 88px; height: 88px; }
600}
601
602/* ─── Post type: segmented control + type-aware panels ──────────── */
603.pe-typeseg {
604 display: grid;
605 grid-template-columns: repeat(4, 1fr);
606 gap: 0.4rem;
607}
608.pe-typeseg-btn {
609 display: flex; flex-direction: column; align-items: center; gap: 0.25rem;
610 padding: 0.7rem 0.4rem;
611 border: 1px solid var(--rule);
612 border-radius: 9px;
613 background: var(--paper-2);
614 color: var(--ink-soft);
615 font-size: 0.85rem; font-weight: 600;
616 cursor: pointer;
617 transition: border-color 120ms, background 120ms, color 120ms;
618}
619.pe-typeseg-btn:hover { border-color: var(--accent); color: var(--ink); }
620.pe-typeseg-btn .pe-typeseg-ic { font-size: 1.3rem; line-height: 1; }
621.pe-typeseg-btn.is-active {
622 border-color: var(--accent);
623 background: color-mix(in srgb, var(--accent) 14%, var(--paper-2));
624 color: var(--ink);
625}
626.pe-typeseg-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
627@media (max-width: 480px) {
628 .pe-typeseg-btn { font-size: 0.78rem; padding: 0.6rem 0.25rem; }
629 .pe-typeseg-btn .pe-typeseg-ic { font-size: 1.15rem; }
630}
631
632.pe-type-panel { margin-top: 0.2rem; }
633
634/* Audio drop/upload zone */
635.pe-audio-up {
636 display: flex; flex-direction: column; align-items: center; gap: 0.3rem;
637 text-align: center;
638 padding: 1.4rem 1rem;
639 border: 2px dashed var(--rule);
640 border-radius: 10px;
641 background: var(--paper-2);
642 color: var(--ink-soft);
643 cursor: pointer;
644 transition: border-color 120ms, background 120ms;
645}
646.pe-audio-up:hover,
647.pe-audio-up:focus-visible { border-color: var(--accent); outline: none; }
648.pe-audio-up.is-drag {
649 border-color: var(--accent);
650 background: color-mix(in srgb, var(--accent) 12%, var(--paper-2));
651}
652.pe-audio-up .pe-audio-up-ic { font-size: 1.7rem; line-height: 1; }
653.pe-audio-up strong { color: var(--ink); font-size: 0.95rem; }
654.pe-audio-up small { font-size: 0.78rem; color: var(--ink-muted, var(--ink-soft)); max-width: 42ch; }
655
656.pe-audio-list { list-style: none; margin: 0.7rem 0 0; padding: 0; display: flex; flex-direction: column; gap: 0.35rem; }
657.pe-audio-item {
658 display: flex; align-items: center; justify-content: space-between; gap: 0.75rem;
659 padding: 0.5rem 0.7rem;
660 border: 1px solid var(--rule);
661 border-radius: 7px;
662 background: var(--paper-2);
663 font-size: 0.85rem;
664}
665.pe-audio-item-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
666.pe-audio-item-state { flex: none; font-size: 0.8rem; color: var(--ink-soft); }
667.pe-audio-item.is-done { border-color: color-mix(in srgb, var(--accent) 50%, var(--rule)); }
668.pe-audio-item.is-done .pe-audio-item-state { color: var(--accent); }
669.pe-audio-item.is-fail .pe-audio-item-state { color: #d9534f; }
670
671/* Video URL row */
672.pe-video-row { display: flex; gap: 0.5rem; }
673.pe-video-row input { flex: 1 1 auto; min-width: 0; }
674.pe-video-row input {
675 box-sizing: border-box; padding: 0.6rem 0.75rem;
676 border: 1px solid var(--rule); border-radius: 6px;
677 background: var(--paper-2); color: var(--ink); font-size: 0.95rem;
678}
679.pe-video-row input:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: var(--accent); }
680.pe-video-row .pe-btn { flex: none; }
681
682.pe-foto-hint { margin: 0; font-size: 0.88rem; color: var(--ink-soft); }
683
684/* ─── Editor frame (WYSIWYG: top toolbar, contenteditable body, status bar) ─── */
685.pe-editor-frame {
686 margin: 0 -1.25rem -1.25rem; /* break out of card padding for flush edges */
687 border-top: 1px solid var(--rule);
688 background: var(--paper);
689 display: flex; flex-direction: column;
690}
691
692/* Top toolbar — sticks to the top of the viewport while editing */
693.pe-toolbar {
694 display: flex; align-items: center; gap: .15rem;
695 flex-wrap: wrap;
696 padding: .4rem .75rem;
697 background: color-mix(in srgb, var(--paper) 92%, transparent);
698 backdrop-filter: blur(10px);
699 -webkit-backdrop-filter: blur(10px);
700 border-bottom: 1px solid var(--rule);
701 position: sticky;
702 top: 0;
703 z-index: 10;
704}
705.pe-toolbar button {
706 display: inline-flex; align-items: center; justify-content: center;
707 width: 32px; height: 32px;
708 padding: 0;
709 touch-action: manipulation; /* snappy taps on mobile, no double-tap zoom */
710 -webkit-user-select: none; user-select: none;
711 background: transparent;
712 border: 1px solid transparent;
713 border-radius: 6px;
714 color: var(--ink);
715 cursor: pointer;
716 font-family: var(--font-ui, system-ui), sans-serif;
717 font-weight: 600; font-size: .85rem;
718 transition: background var(--transition), color var(--transition), border-color var(--transition);
719 -webkit-tap-highlight-color: transparent;
720}
721/* Hover only on real hover-capable devices — on touch :hover otherwise "sticks"
722 after a tap, making the active/inactive state unreadable. */
723@media (hover: hover) {
724 .pe-toolbar button:hover {
725 background: var(--paper-2);
726 color: var(--accent);
727 }
728}
729.pe-toolbar button:active { transform: scale(.94); }
730/* Active formatting = unmistakably filled with the accent colour. On mobile
731 it's immediately clear when e.g. bold is ON (tap again = off). */
732.pe-toolbar button.is-active {
733 background: var(--accent);
734 color: #fff;
735 border-color: var(--accent);
736}
737.pe-toolbar button.is-active svg { color: #fff; }
738.pe-toolbar button svg { width: 16px; height: 16px; }
739.pe-toolbar button.pe-tb-text { font-family: var(--font-display, serif); font-weight: 700; }
740.pe-toolbar-sep {
741 width: 1px; height: 18px;
742 background: var(--rule);
743 margin: 0 .35rem;
744 flex-shrink: 0;
745}
746.pe-toolbar-spacer { flex: 1; }
747
748/* ─── Full-screen writing mode ─── */
749.fs-icon-compress { display: none; }
750.pe-editor-frame.pe-fs .fs-icon-expand { display: none; }
751.pe-editor-frame.pe-fs .fs-icon-compress { display: inline; }
752.pe-editor-frame.pe-fs {
753 position: fixed; inset: 0; z-index: 1000;
754 margin: 0; border-top: 0;
755 height: 100dvh;
756 background: var(--paper);
757 overflow: hidden; /* only the text field scrolls, not the frame itself */
758}
759/* In fullscreen the writing field fills the remaining space and scrolls itself
760 (max-height: none overrides the mobile box limit below). */
761.pe-editor-frame.pe-fs .pe-editor {
762 flex: 1 1 auto; min-height: 0; height: auto; max-height: none;
763}
764/* iOS: in fullscreen the toolbar sits at the very top → push it below the
765 camera / Dynamic Island with the top safe-area inset. */
766.pe-editor-frame.pe-fs .pe-toolbar { padding-top: calc(.4rem + env(safe-area-inset-top, 0px)); }
767/* NB: deliberately NO overflow:hidden on html/body in fullscreen — that could get
768 stuck (e.g. leaving fullscreen via navigation) and would block scrolling on the
769 whole page. The fullscreen frame (position:fixed, inset:0) already covers the page,
770 and on touch scrollbars are hidden → no double bar needed. */
771
772/* "Done" button: only visible in fullscreen (left side of toolbar), clear
773 accent-pill instead of a square icon. */
774/* Hide rule more specific than ".pe-toolbar button" (otherwise that wins and the
775 Done button also shows inline as a small button). Only shown in fullscreen → large. */
776.pe-toolbar button.pe-fs-done { display: none; }
777.pe-editor-frame.pe-fs .pe-fs-done {
778 display: inline-flex; align-items: center; gap: .35rem;
779 width: auto !important; height: auto !important; min-height: 40px;
780 padding: .55rem 1.3rem !important; margin-right: .5rem;
781 background: var(--accent); color: #fff;
782 font-weight: 700; font-size: 1.05rem; border-radius: 999px;
783}
784.pe-editor-frame.pe-fs .pe-fs-done:hover { background: var(--accent); color: #fff; }
785
786/* Editor body — looks like prose, behaves like a textarea */
787.pe-editor {
788 width: 100%;
789 box-sizing: border-box;
790 min-height: 420px;
791 padding: 1.25rem 1.5rem;
792 border: 0;
793 background: transparent;
794 color: var(--ink);
795 font-family: var(--font-body, system-ui), serif;
796 font-size: 1.0625rem;
797 line-height: 1.65;
798 outline: none;
799 overflow-y: auto;
800}
801.pe-editor:focus { outline: none; }
802/* Inline (non-fullscreen) the writing field simply grows with the content — no
803 internal scroll-box (scroll-within-scroll is confusing). On mobile/tablet typing
804 always goes fullscreen (see JS), where the field fills the page and is the sole
805 scroller. */
806.pe-editor-frame:not(.pe-fs) .pe-editor { overflow: visible; }
807
808/* Touch: the inline content field is not a text field but a tap target → fullscreen
809 editing. A "✎ Tap to edit" pill sticks to the bottom of the container,
810 so the hint is always visible without sitting in the middle of the text. */
811.pe-editor.pe-tap-to-edit { cursor: pointer; }
812.pe-edit-hint { display: none; }
813@media (pointer: coarse) {
814 .pe-editor-frame:not(.pe-fs) .pe-edit-hint {
815 display: block;
816 position: sticky;
817 bottom: 4.5rem; /* above the sticky Save/Cancel bar */
818 width: max-content;
819 max-width: calc(100% - 2rem);
820 margin: .4rem auto;
821 background: var(--accent); color: #fff;
822 font-size: .9rem; font-weight: 700; padding: .5rem 1.1rem; border-radius: 999px;
823 box-shadow: 0 4px 14px rgba(0,0,0,.35);
824 pointer-events: none; text-align: center; white-space: nowrap;
825 }
826 /* Not relevant on touch (drag/select belongs to inline editing on desktop). */
827 .pe-content-hint { display: none; }
828 /* Inline (non-fullscreen) on touch: keep it simple — you don't edit here anyway,
829 so no formatting toolbar and no border. Just the content preview + the
830 "tap to edit" pill. The toolbar only appears in fullscreen. */
831 .pe-editor-frame:not(.pe-fs) .pe-toolbar { display: none; }
832 .pe-editor-frame:not(.pe-fs) { border-top: 0; }
833 .pe-editor-frame:not(.pe-fs) .pe-editor { min-height: 8rem; }
834}
835.pe-editor.is-dragover {
836 outline: 2px dashed var(--accent);
837 outline-offset: -10px;
838}
839/* Inline prose styles inside the editor — match the public post styling so
840 what you see is roughly what you'll get. Margins are tighter than on the
841 live site since this is a confined writing space. */
842.pe-editor h1, .pe-editor h2, .pe-editor h3, .pe-editor h4 {
843 font-family: var(--font-display, serif);
844 line-height: 1.2;
845 margin: 1.1rem 0 .35rem;
846}
847.pe-editor h1 { font-size: 1.85rem; }
848.pe-editor h2 { font-size: 1.45rem; }
849.pe-editor h3 { font-size: 1.2rem; }
850.pe-editor p { margin: 0 0 .85em; }
851.pe-editor ul, .pe-editor ol { margin: 0 0 .85em 1.4em; padding: 0; }
852.pe-editor li { margin: .15em 0; }
853.pe-editor blockquote {
854 margin: 1em 0;
855 padding: .15em 0 .15em 1em;
856 border-left: 3px solid var(--accent);
857 color: var(--ink-soft, var(--ink));
858 font-style: italic;
859}
860.pe-editor code {
861 background: var(--paper-2);
862 border: 1px solid var(--rule);
863 border-radius: 4px;
864 padding: .1em .35em;
865 font-family: var(--font-mono, ui-monospace, monospace);
866 font-size: .92em;
867}
868.pe-editor a { color: var(--accent); text-decoration: underline; text-underline-offset: 3px; }
869.pe-editor img {
870 max-width: 100%; height: auto;
871 border-radius: 6px;
872 display: block;
873 margin: 1em auto;
874}
875
876/* Shortcode chips — visible inline placeholder in the editor for
877 [[track:UUID]] / [[album:Name]] / [[playlist:slug]]. They serialize back
878 to plain shortcode text on submit. */
879.sc-chip {
880 display: inline-flex; align-items: center; gap: .3rem;
881 padding: .15em .5em;
882 margin: 0 .15em;
883 background: color-mix(in srgb, var(--accent) 10%, var(--paper-2));
884 border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--rule));
885 border-radius: 999px;
886 color: var(--accent);
887 font-family: var(--font-ui, system-ui), sans-serif;
888 font-size: .85em;
889 font-weight: 600;
890 font-style: normal;
891 white-space: nowrap;
892 user-select: none;
893 cursor: default;
894 vertical-align: baseline;
895}
896.sc-chip-icon { display: inline-flex; opacity: .8; }
897.sc-chip-icon svg { width: 12px; height: 12px; }
898
899/* Status bar below the editor */
900.pe-editor-status {
901 display: flex; align-items: center; justify-content: space-between;
902 gap: .75rem;
903 padding: .45rem 1rem;
904 border-top: 1px solid var(--rule);
905 background: var(--paper-2);
906 color: var(--ink-muted, var(--ink-soft));
907 font-size: .78rem;
908}
909.pe-char-count { font-variant-numeric: tabular-nums; }
910
911/* ─── Track picker modal (P59) ─────────────────────────────────
912 Mobile-first: full-screen bottom-sheet on phones, centered card
913 on desktop. Lock body scroll while open via .tp-locked on body. */
914.tp-modal {
915 position: fixed; inset: 0;
916 z-index: 1000;
917 display: flex; align-items: stretch; justify-content: center;
918 /* Avoid the iOS home-indicator + the keyboard when search is focused */
919 padding: env(safe-area-inset-top) 0 env(safe-area-inset-bottom);
920}
921.tp-modal[hidden] { display: none; }
922.tp-backdrop {
923 position: absolute; inset: 0;
924 background: color-mix(in srgb, var(--ink) 55%, transparent);
925 backdrop-filter: blur(4px);
926 -webkit-backdrop-filter: blur(4px);
927 animation: tp-bd-in .18s ease-out;
928}
929@keyframes tp-bd-in { from { opacity: 0 } to { opacity: 1 } }
930
931/* Mobile: sheet docks to the bottom and fills viewport almost completely */
932.tp-sheet {
933 position: relative;
934 margin-top: auto;
935 width: 100%;
936 max-height: calc(100dvh - env(safe-area-inset-top) - 1rem);
937 background: var(--paper);
938 border-top: 1px solid var(--rule);
939 border-radius: 16px 16px 0 0;
940 box-shadow:
941 0 -2px 8px color-mix(in srgb, var(--ink) 8%, transparent),
942 0 -16px 48px color-mix(in srgb, var(--ink) 18%, transparent);
943 display: flex; flex-direction: column;
944 animation: tp-sheet-up .22s cubic-bezier(.2, .8, .25, 1);
945 overflow: hidden;
946}
947@keyframes tp-sheet-up {
948 from { transform: translateY(100%); opacity: .8; }
949 to { transform: translateY(0); opacity: 1; }
950}
951
952/* Header — title + close, with a small grab-handle bar on mobile */
953.tp-header {
954 display: flex; align-items: center; justify-content: space-between;
955 gap: .75rem;
956 padding: .85rem 1rem .65rem;
957 border-bottom: 1px solid var(--rule);
958 position: relative;
959}
960.tp-header::before {
961 /* Grab-handle: visible on mobile only */
962 content: '';
963 position: absolute;
964 top: .35rem; left: 50%;
965 transform: translateX(-50%);
966 width: 38px; height: 4px;
967 background: var(--rule-2, var(--rule));
968 border-radius: 2px;
969}
970.tp-h2 {
971 margin: .35rem 0 0;
972 font-family: var(--font-display, serif);
973 font-size: 1.15rem; font-weight: 600;
974 color: var(--ink);
975 line-height: 1.1;
976}
977.tp-close {
978 width: 32px; height: 32px; border-radius: 8px;
979 display: inline-flex; align-items: center; justify-content: center;
980 background: transparent; border: 1px solid transparent;
981 color: var(--ink-muted, var(--ink-soft));
982 cursor: pointer;
983 transition: background var(--transition), color var(--transition), border-color var(--transition);
984 -webkit-tap-highlight-color: transparent;
985 margin-top: .35rem;
986}
987.tp-close:hover, .tp-close:focus-visible {
988 background: var(--paper-2);
989 color: var(--ink);
990 outline: none;
991}
992.tp-close svg { width: 18px; height: 18px; }
993
994/* Search row — sticky just below header so list scrolls underneath */
995.tp-search-row {
996 position: relative;
997 padding: .65rem 1rem;
998 border-bottom: 1px solid var(--rule);
999 background: var(--paper);
1000}
1001.tp-search-icon {
1002 position: absolute;
1003 top: 50%; left: 1.65rem;
1004 transform: translateY(-50%);
1005 color: var(--ink-muted, var(--ink-soft));
1006 pointer-events: none;
1007 display: inline-flex;
1008}
1009.tp-search-icon svg { width: 16px; height: 16px; }
1010.tp-search {
1011 width: 100%; box-sizing: border-box;
1012 padding: .65rem .85rem .65rem 2.4rem;
1013 font-family: var(--font-ui, system-ui), sans-serif;
1014 font-size: 1rem;
1015 background: var(--paper-2);
1016 color: var(--ink);
1017 border: 1px solid var(--rule);
1018 border-radius: 9px;
1019 -webkit-appearance: none;
1020 appearance: none;
1021}
1022.tp-search:focus {
1023 outline: none;
1024 border-color: var(--accent);
1025 box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent);
1026}
1027
1028/* List — vertically scrollable, takes remaining sheet height */
1029.tp-list {
1030 flex: 1 1 auto;
1031 overflow-y: auto;
1032 -webkit-overflow-scrolling: touch;
1033 padding: .35rem .35rem 1rem;
1034}
1035.tp-empty {
1036 padding: 1.5rem 1rem;
1037 text-align: center;
1038 color: var(--ink-muted, var(--ink-soft));
1039 font-size: .9rem;
1040}
1041
1042/* Track row — tap target ≥ 56px for mobile */
1043.tp-row {
1044 display: grid;
1045 grid-template-columns: 44px 1fr auto;
1046 align-items: center;
1047 gap: .75rem;
1048 width: 100%;
1049 padding: .55rem .65rem;
1050 border: 0; background: transparent;
1051 border-radius: 10px;
1052 text-align: left;
1053 cursor: pointer;
1054 color: inherit;
1055 font: inherit;
1056 transition: background var(--transition);
1057 -webkit-tap-highlight-color: transparent;
1058}
1059.tp-row:hover, .tp-row:focus-visible {
1060 background: color-mix(in srgb, var(--accent) 8%, var(--paper-2));
1061 outline: none;
1062}
1063.tp-row:active { transform: scale(.98); }
1064.tp-row[aria-disabled="true"] { opacity: .55; cursor: not-allowed; }
1065
1066.tp-cover {
1067 width: 44px; height: 44px;
1068 border-radius: 6px;
1069 background-size: cover; background-position: center;
1070 background-color: var(--rule);
1071 display: inline-flex; align-items: center; justify-content: center;
1072 flex-shrink: 0;
1073}
1074.tp-cover-empty {
1075 background: linear-gradient(135deg,
1076 color-mix(in srgb, var(--accent) 30%, var(--paper-2)),
1077 color-mix(in srgb, var(--accent) 8%, var(--paper-2)));
1078 color: var(--accent);
1079}
1080.tp-cover-empty svg { width: 18px; height: 18px; opacity: .8; }
1081
1082.tp-meta {
1083 display: flex; flex-direction: column;
1084 min-width: 0;
1085 line-height: 1.25;
1086}
1087.tp-row-title {
1088 font-weight: 600; font-size: .94rem;
1089 color: var(--ink);
1090 white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
1091}
1092.tp-row-artist {
1093 font-size: .8rem;
1094 color: var(--ink-muted, var(--ink-soft));
1095 white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
1096 margin-top: .1rem;
1097}
1098.tp-duration {
1099 font-variant-numeric: tabular-nums;
1100 font-size: .8rem;
1101 color: var(--ink-muted, var(--ink-soft));
1102 flex-shrink: 0;
1103}
1104
1105/* Body lock when modal open */
1106body.tp-locked { overflow: hidden; touch-action: none; }
1107
1108/* Desktop: centered card, max-width ~520px */
1109@media (min-width: 640px) {
1110 .tp-modal {
1111 align-items: center;
1112 padding: 1.5rem;
1113 }
1114 .tp-sheet {
1115 margin-top: 0;
1116 width: 100%;
1117 max-width: 520px;
1118 max-height: 80dvh;
1119 border-radius: 14px;
1120 border: 1px solid var(--rule);
1121 animation: tp-sheet-pop .2s cubic-bezier(.2, .8, .25, 1);
1122 }
1123 .tp-header::before { display: none; } /* hide grab-handle on desktop */
1124 .tp-header { padding: 1rem 1.25rem .75rem; }
1125 .tp-h2 { margin-top: 0; font-size: 1.25rem; }
1126 .tp-close { margin-top: 0; }
1127 @keyframes tp-sheet-pop {
1128 from { transform: translateY(-8px) scale(.97); opacity: 0; }
1129 to { transform: translateY(0) scale(1); opacity: 1; }
1130 }
1131}
1132
1133/* ─── Buttons ───────────────────────────────────────────────────── */
1134.pe-btn {
1135 display: inline-flex; align-items: center; gap: 0.4rem;
1136 padding: 0.55rem 1rem;
1137 border: 1px solid var(--rule);
1138 background: var(--paper-2);
1139 color: var(--ink);
1140 font-family: var(--font-ui, system-ui), sans-serif;
1141 font-size: 0.9rem; font-weight: 500;
1142 text-decoration: none;
1143 border-radius: 6px;
1144 cursor: pointer;
1145 transition: background 120ms, border-color 120ms;
1146 min-height: 40px;
1147 -webkit-tap-highlight-color: transparent;
1148}
1149.pe-btn:hover { border-color: var(--accent); }
1150.pe-btn:active { transform: scale(0.97); }
1151.pe-btn-tiny {
1152 padding: 0.35rem 0.7rem;
1153 font-size: 0.85rem;
1154 min-height: 32px;
1155}
1156.pe-btn-secondary { background: var(--paper-2); }
1157.pe-btn-primary {
1158 background: var(--accent); color: white;
1159 border-color: var(--accent);
1160}
1161.pe-btn-primary:hover { opacity: 0.92; border-color: var(--accent); }
1162.pe-btn-success {
1163 background: #16a34a; color: white;
1164 border-color: #16a34a;
1165}
1166.pe-btn-success:hover { opacity: 0.92; border-color: #16a34a; }
1167
1168.pe-status {
1169 color: var(--ink-muted, var(--ink-soft));
1170 font-size: 0.8rem;
1171}
1172.pe-status.is-error { color: #dc2626; }
1173
1174/* ─── Checkboxes (clean inline row) ─────────────────────────────── */
1175.pe-checkboxes {
1176 display: flex; flex-direction: column;
1177 gap: 0.5rem;
1178 padding-top: 0.25rem;
1179}
1180.pe-checkbox {
1181 display: inline-flex; align-items: center; gap: 0.5rem;
1182 cursor: pointer;
1183 font-size: 0.95rem;
1184 color: var(--ink);
1185 user-select: none;
1186}
1187.pe-checkbox input[type="checkbox"] {
1188 width: 18px; height: 18px;
1189 margin: 0;
1190 cursor: pointer;
1191 accent-color: var(--accent);
1192}
1193
1194/* Pin: checkbox + ▲▼-stepper with description (instead of a raw rank number). */
1195.pe-pin { display: flex; flex-direction: column; gap: 0.45rem; }
1196.pe-pin-pos { display: flex; align-items: center; gap: 0.55rem; padding-left: 1.65rem; }
1197.pe-pin-pos[hidden] { display: none; }
1198.pe-pin-steps { display: inline-flex; border: 1px solid var(--rule); border-radius: 6px; overflow: hidden; }
1199.pe-pin-btn {
1200 width: 30px; height: 28px; padding: 0;
1201 border: none; background: var(--paper-2); color: var(--ink);
1202 cursor: pointer; font-size: 0.68rem; line-height: 1;
1203 display: inline-flex; align-items: center; justify-content: center;
1204}
1205.pe-pin-btn + .pe-pin-btn { border-left: 1px solid var(--rule); }
1206.pe-pin-btn:hover { background: color-mix(in srgb, var(--accent) 14%, var(--paper-2)); color: var(--accent); }
1207.pe-pin-btn:disabled { opacity: 0.35; cursor: default; }
1208.pe-pin-label { font-size: 0.85rem; color: var(--accent); font-weight: 600; }
1209
1210/* ─── Sticky action footer ──────────────────────────────────────── */
1211.pe-actions {
1212 position: sticky;
1213 bottom: 0;
1214 display: flex; align-items: center;
1215 gap: 0.5rem;
1216 padding: 0.85rem 1rem;
1217 margin: 0.5rem -1rem 0; /* extend to viewport edges on a narrow container */
1218 background: color-mix(in srgb, var(--paper) 94%, transparent);
1219 -webkit-backdrop-filter: blur(8px);
1220 backdrop-filter: blur(8px);
1221 border-top: 1px solid var(--rule);
1222 z-index: 10;
1223}
1224.pe-actions-spacer { flex: 1; }
1225
1226/* The editor is a focus screen: hide the mobile site tab bar (Home/Search/…)
1227 so two bars don't stack at the bottom (Save bar + tab bar). The
1228 Save/Cancel bar then becomes the only bottom bar → plain bottom:0,
1229 no tab offset needed. On desktop the tab bar is already hidden. */
1230body:has(.post-edit-page) .bottom-tab { display: none; }
1231/* Audio player (if playing) no longer lifted 56px for the now-hidden
1232 tab bar, otherwise it would float above the action bar. */
1233body:has(.post-edit-page) .audio-player { bottom: 0; }
1234
1235/* ── Image editor (rotate / crop / mirror) ── */
1236.imed-backdrop {
1237 position: fixed; inset: 0; z-index: 9999;
1238 display: flex; align-items: center; justify-content: center;
1239 background: rgba(0,0,0,.62); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
1240 padding: 14px;
1241}
1242.imed-modal {
1243 display: flex; flex-direction: column; gap: 12px;
1244 width: 100%; max-width: 640px; max-height: 92vh;
1245 background: var(--paper, #fff); color: var(--ink, #111);
1246 border: 1px solid var(--rule, rgba(128,128,128,.3)); border-radius: 14px;
1247 padding: 14px; box-sizing: border-box;
1248}
1249.imed-stage {
1250 height: 58vh; flex: 0 0 auto;
1251 background: var(--paper-2, rgba(128,128,128,.08)); border-radius: 10px; overflow: hidden;
1252}
1253.imed-stage img { display: block; max-width: 100%; }
1254/* Cropper's container must fill the full stage height — otherwise it collapses
1255 in a flex column without an explicit height → empty edit window (no image). */
1256.imed-stage .cropper-container { width: 100% !important; height: 100% !important; }
1257.imed-tools {
1258 display: flex; flex-wrap: wrap; gap: 6px; justify-content: center;
1259}
1260.imed-tools button {
1261 width: 42px; height: 42px; font-size: 18px; line-height: 1;
1262 border: 1px solid var(--rule, rgba(128,128,128,.4)); border-radius: 10px;
1263 background: var(--paper-2, transparent); color: inherit; cursor: pointer;
1264}
1265.imed-tools button:hover { border-color: var(--accent); }
1266.imed-actions { display: flex; gap: 8px; justify-content: flex-end; }
1267</style>
1268
1269<script>
1270(function() {
1271
1272 // ── Cover upload ────────────────────────────────────────────────
1273 const coverField = document.getElementById('cover-upload-field');
1274 const coverTrigger = document.getElementById('cover-upload-trigger');
1275 const coverUrl = document.getElementById('cover-url-field');
1276 const coverVideo = document.getElementById('cover-video-field');
1277 const coverStatus = document.getElementById('cover-upload-status');
1278 const coverWrap = document.getElementById('cover-preview-wrap');
1279 const coverImg = document.getElementById('cover-preview-img');
1280
1281 async function uploadImage(file) {
1282 const fd = new FormData();
1283 fd.append('image', file);
1284 const res = await fetch('/posts/upload-image', { method: 'POST', body: fd });
1285 if (!res.ok) {
1286 const j = await res.json().catch(() => ({}));
1287 throw new Error(j.error || ('Upload failed (' + res.status + ')'));
1288 }
1289 return await res.json(); // {url, size, mime}
1290 }
1291
1292 // ── Image editor (rotate / crop / mirror) ──────────
1293 // Lazy-load Cropper.js (locally vendored) on first use.
1294 let _cropperReady = null;
1295 function ensureCropper() {
1296 if (window.Cropper) return Promise.resolve();
1297 if (_cropperReady) return _cropperReady;
1298 _cropperReady = new Promise((resolve, reject) => {
1299 if (!document.querySelector('link[data-cropper-css]')) {
1300 const l = document.createElement('link');
1301 l.rel = 'stylesheet'; l.href = '/assets/vendor/cropper.min.css'; l.setAttribute('data-cropper-css', '');
1302 document.head.appendChild(l);
1303 }
1304 const s = document.createElement('script');
1305 s.src = '/assets/vendor/cropper.min.js';
1306 s.onload = () => resolve();
1307 s.onerror = () => reject(new Error('cropper load failed'));
1308 document.head.appendChild(s);
1309 });
1310 return _cropperReady;
1311 }
1312
1313 // True for an animated WebP (VP8X chunk with the animation flag set) — like a GIF it must skip
1314 // the canvas editor, otherwise it'd be flattened to a single static frame.
1315 async function isAnimatedWebpFile(file) {
1316 if (!file || file.type !== 'image/webp') return false;
1317 try {
1318 const b = new Uint8Array(await file.slice(0, 40).arrayBuffer());
1319 return b.length >= 21 && String.fromCharCode(b[12], b[13], b[14], b[15]) === 'VP8X' && (b[20] & 0x02) !== 0;
1320 } catch (_) { return false; }
1321 }
1322
1323 // Opens the editor for a chosen file; resolves with an edited File,
1324 // or null if the user cancels. Animated images (GIF / animated WebP) are NOT sent through the
1325 // canvas editor (they would become static) — those upload directly.
1326 async function openImageEditor(file) {
1327 if (!file || !file.type || !file.type.startsWith('image/')) return file;
1328 if (file.type === 'image/gif') return file; // preserve animation
1329 if (await isAnimatedWebpFile(file)) return file; // animated WebP → preserve animation
1330 try { await ensureCropper(); } catch (_) { return file; } // editor unavailable → upload directly
1331
1332 return new Promise((resolve) => {
1333 const back = document.createElement('div');
1334 back.className = 'imed-backdrop';
1335 back.innerHTML =
1336 '<div class="imed-modal" role="dialog" aria-modal="true" aria-label="<%= t('imed.title') %>">' +
1337 '<div class="imed-stage"><img alt=""></div>' +
1338 '<div class="imed-tools">' +
1339 '<button type="button" data-act="rl" title="<%= t('imed.rotate_left') %>">⟲</button>' +
1340 '<button type="button" data-act="rr" title="<%= t('imed.rotate_right') %>">⟳</button>' +
1341 '<button type="button" data-act="fh" title="<%= t('imed.flip_h') %>">⇆</button>' +
1342 '<button type="button" data-act="fv" title="<%= t('imed.flip_v') %>">⇅</button>' +
1343 '<button type="button" data-act="zi" title="<%= t('imed.zoom_in') %>">+</button>' +
1344 '<button type="button" data-act="zo" title="<%= t('imed.zoom_out') %>">-</button>' +
1345 '<button type="button" data-act="reset" title="<%= t('imed.reset') %>">↺</button>' +
1346 '</div>' +
1347 '<div class="imed-actions">' +
1348 '<button type="button" data-act="cancel" class="pe-btn pe-btn-secondary"><%= t('imed.cancel') %></button>' +
1349 '<button type="button" data-act="apply" class="pe-btn pe-btn-primary"><%= t('imed.apply') %></button>' +
1350 '</div>' +
1351 '</div>';
1352 document.body.appendChild(back);
1353 const img = back.querySelector('img');
1354 const url = URL.createObjectURL(file);
1355 let cropper = null, sx = 1, sy = 1;
1356
1357 function cleanup() {
1358 try { if (cropper) cropper.destroy(); } catch (_) {}
1359 URL.revokeObjectURL(url);
1360 back.remove();
1361 document.removeEventListener('keydown', onKey);
1362 }
1363 function onKey(e) { if (e.key === 'Escape') { cleanup(); resolve(null); } }
1364 document.addEventListener('keydown', onKey);
1365
1366 img.onload = () => {
1367 cropper = new Cropper(img, { viewMode: 1, autoCropArea: 1, background: false, responsive: true });
1368 };
1369 img.onerror = () => { cleanup(); resolve(file); }; // could not load → upload the original
1370 img.src = url;
1371
1372 back.addEventListener('click', (e) => {
1373 const btn = e.target.closest('[data-act]');
1374 if (e.target === back) { cleanup(); resolve(null); return; }
1375 if (!btn || !cropper) return;
1376 const a = btn.getAttribute('data-act');
1377 if (a === 'rl') cropper.rotate(-90);
1378 else if (a === 'rr') cropper.rotate(90);
1379 else if (a === 'fh') { sx = -sx; cropper.scaleX(sx); }
1380 else if (a === 'fv') { sy = -sy; cropper.scaleY(sy); }
1381 else if (a === 'zi') cropper.zoom(0.1);
1382 else if (a === 'zo') cropper.zoom(-0.1);
1383 else if (a === 'reset') { sx = 1; sy = 1; cropper.reset(); }
1384 else if (a === 'cancel') { cleanup(); resolve(null); }
1385 else if (a === 'apply') {
1386 const canvas = cropper.getCroppedCanvas({ maxWidth: 3000, maxHeight: 3000, imageSmoothingEnabled: true, imageSmoothingQuality: 'high' });
1387 const png = (file.type === 'image/png' || file.type === 'image/webp');
1388 const mime = png ? 'image/png' : 'image/jpeg';
1389 const ext = png ? '.png' : '.jpg';
1390 canvas.toBlob((blob) => {
1391 cleanup();
1392 if (!blob) { resolve(file); return; }
1393 const base = (file.name || 'afbeelding').replace(/\.[^.]+$/, '');
1394 resolve(new File([blob], base + ext, { type: mime }));
1395 }, mime, 0.92);
1396 }
1397 });
1398 });
1399 }
1400
1401 function showCoverPreview(url) {
1402 if (!coverWrap || !coverImg) return;
1403 if (url) {
1404 coverImg.src = url;
1405 coverImg.hidden = false;
1406 coverWrap.removeAttribute('data-empty');
1407 const emptyIcon = coverWrap.querySelector('.pe-cover-empty');
1408 if (emptyIcon) emptyIcon.remove();
1409 } else {
1410 coverImg.hidden = true;
1411 coverImg.src = '';
1412 coverWrap.setAttribute('data-empty', '');
1413 if (!coverWrap.querySelector('.pe-cover-empty')) {
1414 const span = document.createElement('span');
1415 span.className = 'pe-cover-empty';
1416 span.textContent = '🖼';
1417 coverWrap.appendChild(span);
1418 }
1419 }
1420 }
1421
1422 if (coverTrigger && coverField) {
1423 coverTrigger.addEventListener('click', () => coverField.click());
1424 }
1425 if (coverField) {
1426 coverField.addEventListener('change', async () => {
1427 if (!coverField.files[0]) return;
1428 const edited = await openImageEditor(coverField.files[0]);
1429 coverField.value = '';
1430 if (!edited) return; // cancelled
1431 coverStatus.classList.remove('is-error');
1432 coverStatus.textContent = '<%= t('pedit.js_uploading') %>';
1433 try {
1434 const j = await uploadImage(edited);
1435 coverUrl.value = j.url;
1436 if (coverVideo) coverVideo.value = j.video || ''; // muted loop MP4 for an animated cover
1437 showCoverPreview(j.url);
1438 coverStatus.textContent = (j.video ? '🎬 ' : '') + '<%= t('pedit.js_uploaded') %> ✓';
1439 setTimeout(() => { coverStatus.textContent = ''; }, 2000);
1440 } catch (e) {
1441 coverStatus.classList.add('is-error');
1442 coverStatus.textContent = '<%= t('pedit.js_failed') %>: ' + e.message;
1443 }
1444 });
1445 }
1446 // Live-update preview when user pastes a URL manually
1447 if (coverUrl) {
1448 coverUrl.addEventListener('input', () => {
1449 const v = coverUrl.value.trim();
1450 if (v) showCoverPreview(v); else showCoverPreview('');
1451 });
1452 }
1453
1454 // ── WYSIWYG editor (P58) ────────────────────────────────────────
1455 // Architecture:
1456 // - Visible <div contenteditable> (`#content-editor`) is what the user
1457 // types in; it shows real HTML (formatted, not raw markup).
1458 // - Hidden <input name="content"> (`#content-hidden`) is what submits.
1459 // On submit we serialize the editor's HTML into it, with shortcode
1460 // chips reduced back to their [[track:UUID]]/[[album:Name]]/[[playlist:slug]] text.
1461 // - Initial content comes from a <script type="application/json"> tag
1462 // to avoid HTML-escape-into-DOM issues; we set innerHTML once on load
1463 // and walk text nodes to render shortcode tokens as chips.
1464 const contentField = document.getElementById('content-upload-field');
1465 const contentBtn = document.getElementById('insert-image-btn');
1466 const contentStatus = document.getElementById('content-upload-status');
1467 const editor = document.getElementById('content-editor');
1468 const hiddenField = document.getElementById('content-hidden');
1469 const charCountEl = document.getElementById('char-count');
1470 const initialEl = document.getElementById('initial-content');
1471 const toolbar = document.getElementById('pe-toolbar');
1472 const form = editor && editor.closest('form');
1473
1474 if (!editor) return;
1475
1476 // Auto-focus the title only on desktop (mouse/trackpad). On touch this would
1477 // immediately open the keyboard when the editor opens — not desired.
1478 try {
1479 const titleInput = form && form.querySelector('input[name="title"]');
1480 if (titleInput && window.matchMedia && window.matchMedia('(hover: hover) and (pointer: fine)').matches) {
1481 titleInput.focus({ preventScroll: true });
1482 }
1483 } catch (_) {}
1484
1485 // ── Shortcode chip rendering / serialization ────────────────────
1486 // Pattern matches [[track:UUID]] / [[album:any text]] / [[playlist:slug]]
1487 // — but we DON'T want to chipify text the user is mid-typing inside an
1488 // HTML attribute; since chipify only walks text nodes (never attribute
1489 // values) that's already safe.
1490 const SC_RE = /\[\[(track|album|playlist|embed):([^\]]+)\]\]/g;
1491
1492 const SC_ICONS = {
1493 track: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="6 4 20 12 6 20 6 4"/></svg>',
1494 album: '<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="10"/><circle cx="12" cy="12" r="3"/></svg>',
1495 playlist: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="15" y2="18"/><polygon points="3 5 3 13 9 9"/></svg>',
1496 embed: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><polygon points="10 9 15.5 12 10 15"/></svg>',
1497 };
1498
1499 function chipLabel(kind, value) {
1500 if (kind === 'track') {
1501 // UUIDs are noisy — show a 6-char prefix for visual hint
1502 const v = String(value || '');
1503 return '<%= t('pedit.chip_track') %> ' + (v.length > 8 ? v.slice(0, 6) + '…' : v);
1504 }
1505 if (kind === 'album') return '<%= t('pedit.chip_album') %> ' + value;
1506 if (kind === 'playlist') return '<%= t('pedit.chip_playlist') %> ' + value;
1507 if (kind === 'embed') {
1508 const clean = String(value || '').replace(/^https?:\/\/(www\.)?/, '');
1509 return '▶ ' + (clean.length > 36 ? clean.slice(0, 34) + '…' : clean);
1510 }
1511 return value;
1512 }
1513
1514 function makeChip(kind, value) {
1515 const span = document.createElement('span');
1516 span.className = 'sc-chip';
1517 span.contentEditable = 'false';
1518 span.setAttribute('data-sc', kind + ':' + value);
1519 span.innerHTML =
1520 '<span class="sc-chip-icon" aria-hidden="true">' + (SC_ICONS[kind] || '') + '</span>' +
1521 '<span class="sc-chip-label"></span>';
1522 span.querySelector('.sc-chip-label').textContent = chipLabel(kind, value);
1523 return span;
1524 }
1525
1526 // Walk text nodes inside `root` and replace [[type:value]] tokens with chips.
1527 function chipifyShortcodes(root) {
1528 const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
1529 const targets = [];
1530 while (walker.nextNode()) {
1531 const n = walker.currentNode;
1532 // Skip text inside existing chips (their .sc-chip-label is set via .textContent so the [[...]] text never appears)
1533 if (n.parentElement && n.parentElement.closest('.sc-chip')) continue;
1534 if (SC_RE.test(n.nodeValue)) targets.push(n);
1535 SC_RE.lastIndex = 0;
1536 }
1537 for (const node of targets) {
1538 const txt = node.nodeValue;
1539 const frag = document.createDocumentFragment();
1540 let last = 0;
1541 let m;
1542 SC_RE.lastIndex = 0;
1543 while ((m = SC_RE.exec(txt)) !== null) {
1544 if (m.index > last) frag.appendChild(document.createTextNode(txt.slice(last, m.index)));
1545 frag.appendChild(makeChip(m[1], m[2].trim()));
1546 last = m.index + m[0].length;
1547 }
1548 if (last < txt.length) frag.appendChild(document.createTextNode(txt.slice(last)));
1549 node.parentNode.replaceChild(frag, node);
1550 }
1551 }
1552
1553 // Inverse of chipify: clone the editor, replace every chip with its text.
1554 function serializeChips(rootClone) {
1555 const chips = rootClone.querySelectorAll('.sc-chip[data-sc]');
1556 for (const c of chips) {
1557 const txt = '[[' + c.getAttribute('data-sc') + ']]';
1558 c.replaceWith(document.createTextNode(txt));
1559 }
1560 }
1561
1562 // ── Boot: load initial content as HTML, then render shortcodes as chips
1563 try {
1564 const initial = JSON.parse(initialEl.textContent || '""');
1565 editor.innerHTML = initial || '';
1566 chipifyShortcodes(editor);
1567 } catch (e) {
1568 console.error('[editor] could not parse initial content', e);
1569 editor.innerHTML = '';
1570 }
1571
1572 // ── Char counter
1573 function updateCharCount() {
1574 const text = (editor.innerText || '').replace(/\s+/g, ' ').trim();
1575 if (charCountEl) charCountEl.textContent = String(text.length);
1576 }
1577 updateCharCount();
1578 editor.addEventListener('input', updateCharCount);
1579
1580 // ── Toolbar wiring
1581 // Lock the scroll position around an edit command. execCommand/insert scrolls
1582 // the caret into view by default → the view "jumps" when clicking a formatting
1583 // button. We lock ALL scrollable ancestors (editor, frame, #pcms-main, …)
1584 // + the page and restore them — sync and over a few frames, because Chrome
1585 // sometimes scrolls a frame later. The user scrolls themselves.
1586 function scrollableAncestors(el) {
1587 const list = [];
1588 let node = el;
1589 while (node && node !== document.body && node !== document.documentElement) {
1590 const oy = getComputedStyle(node).overflowY;
1591 if (oy === 'auto' || oy === 'scroll' || oy === 'overlay') list.push(node);
1592 node = node.parentElement;
1593 }
1594 return list;
1595 }
1596 function keepScroll(fn) {
1597 // In fullscreen the page is locked (body overflow:hidden) and the field may
1598 // scroll to the caret freely — no page jump possible, so nothing to fix.
1599 const frame = document.querySelector('.pe-editor-frame');
1600 if (frame && frame.classList.contains('pe-fs')) { fn(); return; }
1601 const wx = window.scrollX, wy = window.scrollY;
1602 const anc = scrollableAncestors(editor).map(function (n) { return [n, n.scrollTop, n.scrollLeft]; });
1603 const restore = function () {
1604 window.scrollTo(wx, wy);
1605 anc.forEach(function (e) { e[0].scrollTop = e[1]; e[0].scrollLeft = e[2]; });
1606 };
1607 fn();
1608 restore();
1609 requestAnimationFrame(restore);
1610 }
1611 function execCmd(cmd, arg) {
1612 keepScroll(function () {
1613 editor.focus({ preventScroll: true });
1614 document.execCommand(cmd, false, arg);
1615 });
1616 updateToolbarState();
1617 updateCharCount();
1618 }
1619 function wrapCode() {
1620 const sel = window.getSelection();
1621 if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return;
1622 keepScroll(function () {
1623 const range = sel.getRangeAt(0);
1624 const code = document.createElement('code');
1625 code.textContent = sel.toString();
1626 range.deleteContents();
1627 range.insertNode(code);
1628 // Move caret after the new node
1629 range.setStartAfter(code);
1630 range.collapse(true);
1631 sel.removeAllRanges();
1632 sel.addRange(range);
1633 editor.focus({ preventScroll: true });
1634 });
1635 }
1636 function linkPrompt() {
1637 const url = window.prompt('<%= t('pedit.js_link_prompt') %>');
1638 if (!url) return;
1639 execCmd('createLink', url);
1640 }
1641 // Is the current selection inside a <blockquote> within the editor? Return it.
1642 function blockquoteAncestor() {
1643 const sel = window.getSelection();
1644 if (!sel || sel.rangeCount === 0) return null;
1645 let node = sel.anchorNode;
1646 while (node && node !== editor) {
1647 if (node.nodeType === 1 && node.tagName === 'BLOCKQUOTE') return node;
1648 node = node.parentNode;
1649 }
1650 return null;
1651 }
1652 // Real toggle: execCommand('formatBlock','blockquote') does turn it ON but
1653 // can never turn it OFF (browser quirk). If the caret is already in a quote →
1654 // unwrap it; otherwise apply blockquote.
1655 function toggleBlockquote() {
1656 keepScroll(function () {
1657 editor.focus({ preventScroll: true });
1658 const bq = blockquoteAncestor();
1659 if (bq) {
1660 const parent = bq.parentNode;
1661 // Extract content from the quote in place, then remove the empty wrapper.
1662 const ref = bq;
1663 let firstMoved = null;
1664 while (bq.firstChild) {
1665 const child = bq.firstChild;
1666 if (!firstMoved) firstMoved = child;
1667 parent.insertBefore(child, ref);
1668 }
1669 parent.removeChild(bq);
1670 // Restore the caret inside the unwrapped content.
1671 if (firstMoved) {
1672 const sel = window.getSelection();
1673 const range = document.createRange();
1674 range.selectNodeContents(firstMoved.nodeType === 1 ? firstMoved : parent);
1675 range.collapse(false);
1676 sel.removeAllRanges();
1677 sel.addRange(range);
1678 }
1679 } else {
1680 document.execCommand('formatBlock', false, 'blockquote');
1681 }
1682 });
1683 updateToolbarState();
1684 updateCharCount();
1685 }
1686
1687 if (toolbar) {
1688 // CRUCIAL (mobile + desktop): prevent a toolbar button from stealing focus/selection
1689 // from the editor field. Without this the selection is lost on tap
1690 // → execCommand operates on an empty selection (bold can no longer be toggled OFF)
1691 // and the browser scrolls the caret back into view (the "jump down"). preventDefault
1692 // on mousedown keeps focus in the editor; the click still fires normally.
1693 toolbar.addEventListener('mousedown', (e) => {
1694 if (e.target.closest('button')) e.preventDefault();
1695 });
1696 toolbar.addEventListener('click', (e) => {
1697 const btn = e.target.closest('button[data-cmd]');
1698 if (!btn) return;
1699 e.preventDefault();
1700 const cmd = btn.dataset.cmd;
1701 const arg = btn.dataset.arg || null;
1702 if (cmd === 'link-prompt') linkPrompt();
1703 else if (cmd === 'code-wrap') wrapCode();
1704 else if (cmd === 'formatBlock' && arg === 'blockquote') toggleBlockquote();
1705 else execCmd(cmd, arg);
1706 });
1707 }
1708
1709 // ── Full-screen writing mode: the writing field fills the whole page.
1710 const fsBtn = document.getElementById('pe-fullscreen-btn');
1711 const editorFrame = document.querySelector('.pe-editor-frame');
1712 const isTouch = !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
1713
1714 // On mobile the keyboard pushes the visible (visual) viewport up while
1715 // a position:fixed frame stays pinned to the LAYOUT viewport → the toolbar
1716 // slides out of view. Keep the fullscreen frame aligned to the visual
1717 // viewport (top + height) so the toolbar stays visible at the top.
1718 function syncFsViewport() {
1719 if (!editorFrame || !editorFrame.classList.contains('pe-fs')) return;
1720 const vv = window.visualViewport;
1721 if (!vv) return;
1722 editorFrame.style.top = vv.offsetTop + 'px';
1723 editorFrame.style.height = vv.height + 'px';
1724 }
1725 function clearFsViewport() {
1726 if (!editorFrame) return;
1727 editorFrame.style.top = '';
1728 editorFrame.style.height = '';
1729 }
1730 function isFs() { return !!(editorFrame && editorFrame.classList.contains('pe-fs')); }
1731 function applyFs(on) {
1732 if (!editorFrame) return;
1733 editorFrame.classList.toggle('pe-fs', on);
1734 document.body.classList.toggle('pe-fs-open', on);
1735 document.documentElement.classList.toggle('pe-fs-open', on);
1736 if (fsBtn) {
1737 fsBtn.setAttribute('aria-pressed', on ? 'true' : 'false');
1738 fsBtn.title = on ? '<%= t('pedit.tb_done') %>' : '<%= t('pedit.tb_fullscreen') %>';
1739 }
1740 if (window.visualViewport) {
1741 if (on) {
1742 window.visualViewport.addEventListener('resize', syncFsViewport);
1743 window.visualViewport.addEventListener('scroll', syncFsViewport);
1744 syncFsViewport();
1745 } else {
1746 window.visualViewport.removeEventListener('resize', syncFsViewport);
1747 window.visualViewport.removeEventListener('scroll', syncFsViewport);
1748 clearFsViewport();
1749 }
1750 }
1751 // On touch the field is NOT editable inline; only in fullscreen.
1752 if (isTouch) editor.setAttribute('contenteditable', on ? 'true' : 'false');
1753 if (on) {
1754 editor.focus({ preventScroll: true });
1755 } else {
1756 if (isTouch) editor.blur();
1757 // On close: scroll to the TOP of the content instead of staying
1758 // somewhere at the bottom (footer).
1759 requestAnimationFrame(function () {
1760 try { editorFrame.scrollIntoView({ block: 'start' }); } catch (_) {}
1761 });
1762 }
1763 }
1764 // The fullscreen writing "page": opening pushes a history state so the browser
1765 // back button (and the Done button) closes it and returns you to the form — feels
1766 // like a separate page, but all form fields remain intact (same DOM).
1767 function openFs() {
1768 if (isFs()) return;
1769 try { history.pushState({ peFs: true }, ''); } catch (_) {}
1770 applyFs(true);
1771 }
1772 function closeFs() {
1773 if (!isFs()) return;
1774 if (history.state && history.state.peFs) history.back(); // → popstate closes it
1775 else applyFs(false);
1776 }
1777 function toggleFullscreen() { if (isFs()) closeFs(); else openFs(); }
1778 window.addEventListener('popstate', function () { if (isFs()) applyFs(false); });
1779 if (fsBtn) fsBtn.addEventListener('click', toggleFullscreen);
1780 var fsDoneBtn = document.getElementById('pe-fs-done');
1781 if (fsDoneBtn) fsDoneBtn.addEventListener('click', closeFs);
1782 document.addEventListener('keydown', (e) => {
1783 if (e.key === 'Escape' && isFs()) { e.preventDefault(); closeFs(); }
1784 });
1785
1786 // On mobile/tablet (touch): the content field is NOT editable inline — it is
1787 // not a text field there. One tap → fullscreen, where it becomes editable
1788 // (toggleFullscreen toggles contenteditable). This prevents inline typing.
1789 if (isTouch) {
1790 editor.setAttribute('contenteditable', 'false');
1791 editor.classList.add('pe-tap-to-edit');
1792 editor.addEventListener('click', function () {
1793 if (!isFs()) openFs();
1794 });
1795 }
1796
1797 // Reflect bold/italic/list state on the toolbar buttons
1798 function updateToolbarState() {
1799 if (!toolbar) return;
1800 const cmds = ['bold', 'italic', 'underline', 'insertUnorderedList', 'insertOrderedList'];
1801 for (const cmd of cmds) {
1802 const btn = toolbar.querySelector('button[data-cmd="' + cmd + '"]');
1803 if (!btn) continue;
1804 try { btn.classList.toggle('is-active', document.queryCommandState(cmd)); } catch(_) {}
1805 }
1806 // Quote button: active when the caret is inside a <blockquote> (toggle feedback).
1807 const bqBtn = toolbar.querySelector('button[data-cmd="formatBlock"][data-arg="blockquote"]');
1808 if (bqBtn) bqBtn.classList.toggle('is-active', !!blockquoteAncestor());
1809 }
1810 document.addEventListener('selectionchange', () => {
1811 if (document.activeElement === editor) updateToolbarState();
1812 });
1813
1814 // Keyboard shortcuts: Ctrl/Cmd + B/I/U/K
1815 editor.addEventListener('keydown', (e) => {
1816 const mod = e.ctrlKey || e.metaKey;
1817 if (!mod) return;
1818 const k = e.key.toLowerCase();
1819 if (k === 'b') { e.preventDefault(); execCmd('bold'); }
1820 else if (k === 'i') { e.preventDefault(); execCmd('italic'); }
1821 else if (k === 'u') { e.preventDefault(); execCmd('underline'); }
1822 else if (k === 'k') { e.preventDefault(); linkPrompt(); }
1823 });
1824
1825 // Paste: keep it simple — strip formatting unless user wants it. Default
1826 // execCommand 'paste' includes Word/Google-Docs garbage. We accept inline
1827 // styles from clipboard only when shift is held — otherwise plain text.
1828 editor.addEventListener('paste', (e) => {
1829 if (e.shiftKey) return; // user wants formatted paste
1830 const text = (e.clipboardData || window.clipboardData).getData('text/plain');
1831 if (text == null) return;
1832 e.preventDefault();
1833 document.execCommand('insertText', false, text);
1834 });
1835
1836 // ── Image upload (button + drag-drop into the editor)
1837 async function uploadAndInsertImage(file) {
1838 const edited = await openImageEditor(file);
1839 if (!edited) return; // cancelled
1840 contentStatus.classList.remove('is-error');
1841 contentStatus.textContent = '<%= t('pedit.js_uploading') %>';
1842 try {
1843 const j = await uploadImage(edited);
1844 const img = '<img src="' + j.url + '" alt="">';
1845 editor.focus({ preventScroll: true });
1846 document.execCommand('insertHTML', false, img);
1847 contentStatus.textContent = '<%= t('pedit.js_inserted') %> ✓';
1848 setTimeout(() => { contentStatus.textContent = ''; }, 2000);
1849 updateCharCount();
1850 } catch (e) {
1851 contentStatus.classList.add('is-error');
1852 contentStatus.textContent = '<%= t('pedit.js_failed') %>: ' + e.message;
1853 }
1854 }
1855
1856 if (contentBtn && contentField) {
1857 contentBtn.addEventListener('click', () => contentField.click());
1858 contentField.addEventListener('change', () => {
1859 if (contentField.files[0]) uploadAndInsertImage(contentField.files[0]);
1860 contentField.value = '';
1861 });
1862
1863 editor.addEventListener('dragover', (e) => {
1864 if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
1865 e.preventDefault();
1866 editor.classList.add('is-dragover');
1867 }
1868 });
1869 editor.addEventListener('dragleave', () => editor.classList.remove('is-dragover'));
1870 editor.addEventListener('drop', async (e) => {
1871 editor.classList.remove('is-dragover');
1872 const files = e.dataTransfer && e.dataTransfer.files;
1873 if (!files || !files.length) return;
1874 e.preventDefault();
1875 for (const f of files) {
1876 if (f.type.startsWith('image/')) await uploadAndInsertImage(f);
1877 }
1878 });
1879 }
1880
1881 // ── Insert chip helpers (track / playlist)
1882 function insertChip(kind, value) {
1883 editor.focus({ preventScroll: true });
1884 const chip = makeChip(kind, value);
1885 // Insert at caret using the Selection API (execCommand insertNode)
1886 const sel = window.getSelection();
1887 if (sel && sel.rangeCount > 0) {
1888 const range = sel.getRangeAt(0);
1889 range.deleteContents();
1890 range.insertNode(chip);
1891 // Insert a trailing space so the user can keep typing after the chip
1892 const space = document.createTextNode('\u00A0');
1893 chip.after(space);
1894 range.setStartAfter(space);
1895 range.collapse(true);
1896 sel.removeAllRanges();
1897 sel.addRange(range);
1898 } else {
1899 editor.appendChild(chip);
1900 editor.appendChild(document.createTextNode('\u00A0'));
1901 }
1902 updateCharCount();
1903 }
1904
1905 // ── Embed insert: paste a platform URL -> [[embed:url]]-chip that becomes
1906 // an iframe server-side (YouTube/Spotify/SoundCloud/Vimeo/Apple Music/Bandcamp).
1907 const embedBtn = document.getElementById('insert-embed-btn');
1908 if (embedBtn) {
1909 embedBtn.addEventListener('click', () => {
1910 const raw = window.prompt('<%= t('pedit.js_embed_prompt') %>');
1911 if (!raw) return;
1912 const url = raw.trim();
1913 if (!/^https?:\/\//i.test(url)) { alert('<%= t('pedit.js_embed_invalid') %>'); return; }
1914 insertChip('embed', url);
1915 });
1916 }
1917
1918 // ── Track insert: opens the track-picker modal (P59)
1919 const trackBtn = document.getElementById('insert-track-btn');
1920 const trackPicker = document.getElementById('track-picker');
1921 if (trackBtn && trackPicker) {
1922 const tpList = document.getElementById('tp-list');
1923 const tpEmpty = document.getElementById('tp-empty');
1924 const tpSearch = document.getElementById('tp-search');
1925 let tpCache = null; // cached track list (fetched once per page load)
1926 let tpLastFocus = null; // element to restore focus to on close
1927
1928 const SVG_NOTE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 17V5l12-2v12"/><circle cx="6" cy="17" r="3"/><circle cx="18" cy="15" r="3"/></svg>';
1929
1930 function fmtDur(sec) {
1931 sec = Math.max(0, Math.floor(sec || 0));
1932 const m = Math.floor(sec / 60), s = sec % 60;
1933 return m + ':' + String(s).padStart(2, '0');
1934 }
1935 function escAttr(s) {
1936 return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({
1937 '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
1938 }[c]));
1939 }
1940
1941 function renderList(filter) {
1942 if (!Array.isArray(tpCache)) return;
1943 const q = (filter || '').trim().toLowerCase();
1944 const filtered = q
1945 ? tpCache.filter(t =>
1946 (t.title || '').toLowerCase().includes(q) ||
1947 (t.artist || '').toLowerCase().includes(q))
1948 : tpCache;
1949
1950 if (!filtered.length) {
1951 tpList.innerHTML = '';
1952 tpEmpty.textContent = q ? '<%= t('pedit.js_no_tracks_found') %> ' + q : '<%= t('pedit.js_no_tracks_yet') %>';
1953 tpList.appendChild(tpEmpty);
1954 return;
1955 }
1956
1957 tpList.innerHTML = filtered.map(t => {
1958 const cov = t.cover
1959 ? '<span class="tp-cover" style="background-image:url(\'' + escAttr(t.cover) + '\')"></span>'
1960 : '<span class="tp-cover tp-cover-empty">' + SVG_NOTE + '</span>';
1961 const dis = t.playable ? '' : ' aria-disabled="true"';
1962 const sub = t.artist ? '<span class="tp-row-artist">' + escAttr(t.artist) + '</span>' : '';
1963 return (
1964 '<button type="button" class="tp-row" role="option" data-track-id="' + escAttr(t.id) + '"' + dis + '>' +
1965 cov +
1966 '<span class="tp-meta">' +
1967 '<span class="tp-row-title">' + escAttr(t.title) + '</span>' +
1968 sub +
1969 '</span>' +
1970 '<span class="tp-duration">' + fmtDur(t.duration) + '</span>' +
1971 '</button>'
1972 );
1973 }).join('');
1974 }
1975
1976 async function loadTracks() {
1977 if (Array.isArray(tpCache)) return tpCache;
1978 tpEmpty.textContent = '<%= t('pedit.js_tracks_loading') %>';
1979 try {
1980 const r = await fetch('/admin/playlists/api/tracks', { credentials: 'same-origin' });
1981 const j = await r.json();
1982 tpCache = (j && j.ok && Array.isArray(j.tracks)) ? j.tracks : [];
1983 } catch (e) {
1984 tpCache = [];
1985 tpEmpty.textContent = '<%= t('pedit.js_tracks_load_fail') %>: ' + e.message;
1986 }
1987 return tpCache;
1988 }
1989
1990 function openPicker() {
1991 tpLastFocus = document.activeElement;
1992 trackPicker.hidden = false;
1993 trackPicker.setAttribute('aria-hidden', 'false');
1994 document.body.classList.add('tp-locked');
1995 tpSearch.value = '';
1996 renderList('');
1997 // Defer focus so the open animation doesn't get jumped
1998 setTimeout(() => tpSearch.focus(), 30);
1999 }
2000 function closePicker() {
2001 trackPicker.hidden = true;
2002 trackPicker.setAttribute('aria-hidden', 'true');
2003 document.body.classList.remove('tp-locked');
2004 if (tpLastFocus && typeof tpLastFocus.focus === 'function') {
2005 try { tpLastFocus.focus(); } catch(_) {}
2006 }
2007 }
2008
2009 trackBtn.addEventListener('click', async () => {
2010 openPicker();
2011 await loadTracks();
2012 renderList(tpSearch.value);
2013 });
2014
2015 // Close: backdrop click, [data-tp-close], or Escape
2016 trackPicker.addEventListener('click', (e) => {
2017 if (e.target.closest('[data-tp-close]')) {
2018 closePicker();
2019 return;
2020 }
2021 const row = e.target.closest('.tp-row[data-track-id]');
2022 if (row) {
2023 if (row.getAttribute('aria-disabled') === 'true') return;
2024 const id = row.dataset.trackId;
2025 if (id) {
2026 insertChip('track', id);
2027 closePicker();
2028 }
2029 }
2030 });
2031 document.addEventListener('keydown', (e) => {
2032 if (!trackPicker.hidden && e.key === 'Escape') {
2033 e.preventDefault();
2034 closePicker();
2035 }
2036 });
2037
2038 // Live filter
2039 tpSearch.addEventListener('input', () => renderList(tpSearch.value));
2040 }
2041
2042 // ── Playlist insert (open existing or create new via modal)
2043 const playlistBtn = document.getElementById('insert-playlist-btn');
2044 if (playlistBtn) {
2045 playlistBtn.addEventListener('click', async () => {
2046 if (typeof window.openPlaylistEditor !== 'function') {
2047 alert('<%= t('pedit.js_playlist_editor_missing') %>');
2048 return;
2049 }
2050 try {
2051 const r = await fetch('/admin/playlists/api/list', { credentials: 'same-origin' });
2052 const j = await r.json();
2053 if (j.ok && Array.isArray(j.playlists) && j.playlists.length > 0) {
2054 const choice = prompt(
2055 '<%= t('pedit.js_playlist_existing') %>\n\n' +
2056 j.playlists.map((p, i) => `${i + 1}. ${p.title} (${p.track_count} tracks)`).join('\n') +
2057 '\n\n<%= t('pedit.js_playlist_choose') %>'
2058 );
2059 if (choice && /^\d+$/.test(choice.trim())) {
2060 const idx = parseInt(choice.trim(), 10) - 1;
2061 if (idx >= 0 && idx < j.playlists.length) {
2062 insertChip('playlist', j.playlists[idx].id);
2063 return;
2064 }
2065 }
2066 if (choice === null) return;
2067 }
2068 } catch (_) { /* fall through to create */ }
2069
2070 window.openPlaylistEditor({
2071 mode: 'create',
2072 onSaved: ({ id }) => insertChip('playlist', id),
2073 });
2074 });
2075 }
2076
2077 // ── Post type: segmented control + type-aware panels ──────────
2078 (function () {
2079 const typeInput = document.getElementById('pe-type-input');
2080 const card = document.querySelector('.pe-type-card');
2081 if (!typeInput || !card) return;
2082 const seg = card.querySelector('.pe-typeseg');
2083 const panels = card.querySelectorAll('.pe-type-panel');
2084
2085 function applyType(tt) {
2086 typeInput.value = tt;
2087 seg.querySelectorAll('.pe-typeseg-btn').forEach(b => {
2088 const on = b.dataset.type === tt;
2089 b.classList.toggle('is-active', on);
2090 b.setAttribute('aria-checked', on ? 'true' : 'false');
2091 });
2092 panels.forEach(p => { p.hidden = (p.dataset.panel !== tt); });
2093 }
2094 seg.addEventListener('click', (e) => {
2095 const btn = e.target.closest('.pe-typeseg-btn');
2096 if (btn) applyType(btn.dataset.type);
2097 });
2098 applyType(typeInput.value || 'post');
2099
2100 // Video URL → [[embed:url]] chip
2101 const vBtn = document.getElementById('pe-video-insert');
2102 const vUrl = document.getElementById('pe-video-url');
2103 if (vBtn && vUrl) {
2104 const doInsert = () => {
2105 const url = (vUrl.value || '').trim();
2106 if (!/^https?:\/\//i.test(url)) { alert('<%= t('pedit.js_embed_invalid') %>'); return; }
2107 insertChip('embed', url);
2108 vUrl.value = '';
2109 };
2110 vBtn.addEventListener('click', doInsert);
2111 vUrl.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); doInsert(); } });
2112 }
2113
2114 // Audio: inline upload → transcodes server-side → [[track:id]] chip
2115 const drop = document.getElementById('pe-audio-drop');
2116 const fileInput = document.getElementById('pe-audio-file');
2117 const list = document.getElementById('pe-audio-list');
2118 if (drop && fileInput && list) {
2119 const pick = () => fileInput.click();
2120 drop.addEventListener('click', pick);
2121 drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(); } });
2122 ['dragenter', 'dragover'].forEach(ev => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('is-drag'); }));
2123 ['dragleave', 'drop'].forEach(ev => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('is-drag'); }));
2124 drop.addEventListener('drop', (e) => { if (e.dataTransfer && e.dataTransfer.files) handleFiles(e.dataTransfer.files); });
2125 fileInput.addEventListener('change', () => { handleFiles(fileInput.files); fileInput.value = ''; });
2126
2127 function clientDuration(f) {
2128 return new Promise((resolve) => {
2129 try {
2130 const u = URL.createObjectURL(f);
2131 const a = document.createElement('audio');
2132 a.preload = 'metadata';
2133 a.onloadedmetadata = () => { URL.revokeObjectURL(u); resolve(Number.isFinite(a.duration) ? Math.round(a.duration) : null); };
2134 a.onerror = () => { URL.revokeObjectURL(u); resolve(null); };
2135 a.src = u;
2136 } catch (_) { resolve(null); }
2137 });
2138 }
2139 async function handleFiles(files) {
2140 for (const f of Array.from(files || [])) await uploadOne(f);
2141 }
2142 async function uploadOne(f) {
2143 const li = document.createElement('li');
2144 li.className = 'pe-audio-item';
2145 const nameEl = document.createElement('span');
2146 nameEl.className = 'pe-audio-item-name';
2147 nameEl.textContent = f.name;
2148 const stateEl = document.createElement('span');
2149 stateEl.className = 'pe-audio-item-state';
2150 stateEl.textContent = '⏳ <%= t('pedit.audio_up_busy') %>';
2151 li.appendChild(nameEl); li.appendChild(stateEl);
2152 list.appendChild(li);
2153 try {
2154 const dur = await clientDuration(f);
2155 const fd = new FormData();
2156 fd.append('audio', f);
2157 if (dur) fd.append('duration', String(dur));
2158 const res = await fetch('/admin/audio/upload', {
2159 method: 'POST', body: fd,
2160 headers: { 'Accept': 'application/json' },
2161 credentials: 'same-origin',
2162 });
2163 const j = await res.json().catch(() => ({}));
2164 if (!res.ok || !j.ok || !j.id) throw new Error(j.error || ('HTTP ' + res.status));
2165 insertChip('track', j.id);
2166 stateEl.textContent = '✓ <%= t('pedit.audio_up_done') %>';
2167 li.classList.add('is-done');
2168 } catch (err) {
2169 stateEl.textContent = '✕ <%= t('pedit.audio_up_fail') %>: ' + err.message;
2170 li.classList.add('is-fail');
2171 }
2172 }
2173 }
2174 })();
2175
2176 // ── Submit: serialize editor contents into the hidden field
2177 if (form && hiddenField) {
2178 form.addEventListener('submit', () => {
2179 const clone = editor.cloneNode(true);
2180 serializeChips(clone);
2181 hiddenField.value = clone.innerHTML;
2182 });
2183 }
2184})();
2185</script>
2186
2187<%# ── Track picker modal (P59). Mobile-first: full-screen sheet on small
2188 viewports, centered modal on ≥640px. Populated lazily on first open. %>
2189<% if (typeof user !== 'undefined' && user) { %>
2190<div id="track-picker" class="tp-modal" hidden aria-hidden="true">
2191 <div class="tp-backdrop" data-tp-close></div>
2192 <div class="tp-sheet" role="dialog" aria-modal="true" aria-labelledby="tp-title">
2193 <header class="tp-header">
2194 <h2 id="tp-title" class="tp-h2"><%= t('pedit.tp_title') %></h2>
2195 <button type="button" class="tp-close" data-tp-close aria-label="<%= t('pedit.tp_close') %>">
2196 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
2197 </button>
2198 </header>
2199 <div class="tp-search-row">
2200 <span class="tp-search-icon" aria-hidden="true">
2201 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
2202 </span>
2203 <input type="search" class="tp-search" id="tp-search" placeholder="<%= t('pedit.tp_search_placeholder') %>" autocomplete="off" inputmode="search">
2204 </div>
2205 <div class="tp-list" id="tp-list" role="listbox" aria-label="<%= t('pedit.tp_list_aria') %>">
2206 <div class="tp-empty" id="tp-empty"><%= t('pedit.js_tracks_loading') %></div>
2207 </div>
2208 </div>
2209</div>
2210<% } %>
2211
2212<%# Playlist editor modal — included so its global window.openPlaylistEditor
2213 is available when the toolbar button fires. Only renders if user can post. %>
2214<% if (typeof user !== 'undefined' && user) { %>
2215 <%- include('../partials/playlist-editor', { csrfToken: (typeof csrfToken !== 'undefined' ? csrfToken : '') }) %>
2216<% } %>
2217
2218<script>
2219(function () {
2220 // Pin: checkbox toggles the hidden rank field (0 = not pinned),
2221 // ▲▼ shifts the position, with a readable description instead of a raw number.
2222 var toggle = document.getElementById('pin-toggle');
2223 var rank = document.getElementById('pin-rank');
2224 var pos = document.getElementById('pin-pos');
2225 var label = document.getElementById('pin-label');
2226 var up = document.getElementById('pin-up'); // higher = lower number (towards 1/top)
2227 var down = document.getElementById('pin-down');
2228 if (!toggle || !rank || !pos) return;
2229
2230 function descr(n) {
2231 n = Number(n) || 0;
2232 if (n <= 1) return '<%= t('pedit.pin_top') %>';
2233 return n + '<%= t('pedit.pin_nth_suffix') %>';
2234 }
2235 function render() {
2236 var on = toggle.checked;
2237 pos.hidden = !on;
2238 if (on && Number(rank.value) < 1) rank.value = 1;
2239 if (!on) rank.value = 0;
2240 if (label) label.textContent = on ? descr(rank.value) : '';
2241 if (up) up.disabled = Number(rank.value) <= 1;
2242 }
2243 toggle.addEventListener('change', render);
2244 if (up) up.addEventListener('click', function () { rank.value = Math.max(1, (Number(rank.value) || 1) - 1); render(); });
2245 if (down) down.addEventListener('click', function () { rank.value = (Number(rank.value) || 0) + 1; render(); });
2246 render();
2247})();
2248
2249(function () {
2250 // Keep the Save/Cancel bar (position: sticky; bottom:0) just above two possible
2251 // obstacles by setting a dynamic bottom offset = the greater of:
2252 // 1) the height of the keyboard area NOT covered by the layout viewport
2253 // (on iOS the visual viewport shifts; on Android the layout viewport shrinks
2254 // due to interactive-widget=resizes-content → offset ≈ 0);
2255 // 2) the height of the playing audio player (fixed, z-index 1000).
2256 // We stick with sticky (no fixed/top tricks → no bar floating in the middle).
2257 var bar = document.querySelector('.pe-actions');
2258 if (!bar) return;
2259 var vv = window.visualViewport;
2260 function position() {
2261 var ap = document.querySelector('.audio-player');
2262 var playing = document.body.classList.contains('has-audio-player') &&
2263 ap && getComputedStyle(ap).display !== 'none';
2264 var audioOffset = playing ? Math.round(ap.getBoundingClientRect().height) : 0;
2265 var kbCovered = vv ? Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)) : 0;
2266 var offset = Math.max(audioOffset, kbCovered);
2267 bar.style.bottom = offset ? offset + 'px' : '';
2268 }
2269 position();
2270 window.addEventListener('resize', position);
2271 if (vv) { vv.addEventListener('resize', position); vv.addEventListener('scroll', position); }
2272 // has-audio-player is toggled via a body class → observe it.
2273 try { new MutationObserver(position).observe(document.body, { attributes: true, attributeFilter: ['class'] }); } catch (_) {}
2274})();
2275</script>
Note: See TracBrowser for help on using the repository browser.