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

main
Last change on this file since bf4596d was bf4596d, checked in by Robin Genis <roboburr@…>, 3 months ago

feat(editor): post type on top (segmented) + type-aware inputs

Bart's UX feedback: the post-type selector moved from the bottom Meta
section to a prominent segmented control at the top of the editor, above
the body. The selected type now reveals its own input:

  • Audio -> inline upload (drag/drop), transcodes server-side and drops

the track straight into the post (no more /admin/audio detour)

  • Video -> paste a URL -> embed chip
  • Foto -> hint toward cover + insert-image

Reuses the existing /admin/audio/upload endpoint (returns {ok,id}) and the
editor's insertChip(). Adds pedit.* i18n keys (nl/en/de).

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

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