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

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

feat(nsfw): custom content-warning text + blur in the Cirkel

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