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

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

fix(post-edit): typing a content-warning auto-ticks the NSFW checkbox

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