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

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

feat(polls): removable options + tidier editor layout

Each poll option is now its own row with a ✕ remove button (hidden at the
2-option minimum, add capped at 8); the "+ Add option" button sits on its own
line above a stacked "multiple choices" checkbox, matching the rest of the
options panel. Inline styles moved to a scoped block.

  • src/views/pages/post-edit.ejs — option rows with remove buttons, .pe-poll-* styles, refresh() enforces min-2/max-8; add button is block-level.
  • src/services/i18n.js — pedit.poll_remove (nl/en/de).

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

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