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

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

fix(editor): animated WebP covers skip the crop editor (were flattened to a static frame)

The post editor's image editor (Cropper.js -> canvas) flattens an animated image to one frame.
Animated GIFs already bypassed it; animated WebP did not, so an animated WebP cover became static.
Detect an animated WebP (VP8X animation flag) client-side and upload it directly, like GIFs —
preserving the animation. Combined with the thumbnail fix, animated covers now move on-site.

  • src/views/pages/post-edit.ejs — isAnimatedWebpFile() + bypass the crop editor for animated WebP

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

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