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

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

feat(fediverse): host your own polls (federate as AS2 Question)

A post can carry a poll that federates as an AS2 Question so remote (Mastodon)
followers vote from their own app; votes are tallied server-side and the fresh
counts are pushed back as Update(Question). Voting is fediverse-only; the site
shows live, read-only results. Complements the existing inbound poll support.

  • src/config/database.js — posts.poll_json (our poll definition) + poll_votes table (post_id, actor_uri, choice; UNIQUE) backing the tally + per-actor dedupe.
  • src/services/ActivityPubService.js — parseOwnPoll/pollTally/ownPollView helpers; buildNote emits a Question (oneOf/anyOf + replies.totalItems + endTime/closed + votersCount) for a poll post; handleInbox records a ballot (Note with name + inReplyTo our poll) before the reply path, deduped per actor; a debounced Update(Question) pushes fresh counts to followers; votersCount added to AP_CONTEXT.
  • src/services/Scheduler.js — closeExpiredPolls() marks a poll closed once its endTime passes and pushes the final tally; runs on the existing 60s tick.
  • src/routes/posts.js — parsePollForm() turns the editor fields into poll_json on create/save (a poll with votes is frozen), passes poll_json to the federation hooks, and hands the post page a render-ready ownPollView.
  • src/views/pages/post-edit.ejs — poll section (options, multiple-choice, duration); disabled once the poll has votes.
  • src/views/pages/post.ejs — display-only poll with result bars + voter/close meta.
  • src/services/i18n.js — poll.* + pedit.poll_* strings (nl/en/de).
  • test/polls.test.js — Question shape, tally, percentages, closed state, AS2 term.
  • CHANGELOG(.nl/.de).md — "Create your own polls" under Unreleased.

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

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