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

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

feat(fediverse): alt text for images (accessibility → AS2 attachment name)

Media federated to the fediverse now carries a description (AS2 name on the
attachment), which Mastodon shows and screen readers read. The cover gets an alt
field in the editor; inline images keep their own <img alt="…">. Also used as the
cover's on-site alt.

  • src/config/database.js — posts.cover_alt column.
  • src/services/ActivityPubService.js — buildNote carries alt per media URL (cover_alt + inline <img alt>) and emits it as the attachment name (and on the image fallback).
  • src/routes/posts.js — capture/store cover_alt on create/save and pass it to the federation hooks.
  • src/services/Scheduler.js — carry cover_alt when a scheduled post goes live.
  • src/views/pages/post-edit.ejs — "Alt text (description)" field under the cover URL.
  • src/views/pages/post.ejs — the on-page cover <img> uses cover_alt.
  • src/services/i18n.js — pedit.f_cover_alt + pedit.cover_alt_placeholder (nl/en/de).
  • test/media-alt.test.js — cover alt, inline alt, and no-alt = no name.
  • CHANGELOG(.nl/.de).md — "Alt text for images" under Unreleased.

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

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