Claude commited on
Commit
e363538
·
1 Parent(s): 5a2d8c8

editor: Download Markdown — semantic .md export

Browse files

Adds a "Download Markdown" button to the editor toolbar that produces
a single self-contained .md file from the current editor state. Mirrors
"Download final HTML"'s contract: same per-element include toggles,
same description-replaces-alt rule, no server round-trip.

Output is semantic markdown (no raw HTML hacks):
* # for the page title, ## per section, --- between sections
* Eyebrow as *italic*, subtitle as plain paragraph
* Timestamps as *italic* sub-line under each heading
* Image as ![alt](data:image/jpeg;base64,…) — alt is empty when a
scene description is present (matches the published-HTML behaviour)
or when the alt-text include checkbox is off
* Scene description as plain paragraphs (blank-line separated)
* On-screen text as a labelled blockquote (>) when its include
toggle is on
* Transcript as plain paragraphs when its include toggle is on
* Math equations as $…$ (inline) or $$…$$ (block), GitHub-flavoured
Markdown compatible

Audio is intentionally skipped — markdown has no semantic audio
construct, and embedding raw <audio> HTML would either render
inconsistently or be stripped by the renderer. Documented in the
buildMarkdown comment so the omission isn't mistaken for a bug.

Includes a regression test pinning the button's presence in the
rendered editor toolbar.

https://claude.ai/code/session_01EM8jiYxdVFy1w3LeJ9GBJg

Files changed (2) hide show
  1. app/templates/review.html +157 -0
  2. tests/test_html_gen.py +12 -0
app/templates/review.html CHANGED
@@ -303,6 +303,7 @@
303
  aria-hidden="true" tabindex="-1" style="display:none">
304
  <button type="button" data-action="preview-html">Preview</button>
305
  <button type="button" data-action="download-html">Download final HTML</button>
 
306
  {% if zip_url %}
307
  <button type="button" data-action="download-zip">Download ZIP</button>
308
  {% endif %}
@@ -1130,6 +1131,161 @@
1130
  setStatus('Downloaded final HTML.');
1131
  }
1132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1133
  let previewURL = null;
1134
  window.addEventListener('pagehide', () => {
1135
  if (previewURL) {
@@ -1218,6 +1374,7 @@
1218
  toolbar.querySelector('[data-action="save-json"]').addEventListener('click', saveJSON);
1219
  toolbar.querySelector('[data-action="preview-html"]').addEventListener('click', previewHTML);
1220
  toolbar.querySelector('[data-action="download-html"]').addEventListener('click', downloadHTML);
 
1221
  const zipBtn = toolbar.querySelector('[data-action="download-zip"]');
1222
  if (zipBtn) zipBtn.addEventListener('click', downloadZIP);
1223
  const loadInput = toolbar.querySelector('[data-action="load-json"]');
 
303
  aria-hidden="true" tabindex="-1" style="display:none">
304
  <button type="button" data-action="preview-html">Preview</button>
305
  <button type="button" data-action="download-html">Download final HTML</button>
306
+ <button type="button" data-action="download-markdown">Download Markdown</button>
307
  {% if zip_url %}
308
  <button type="button" data-action="download-zip">Download ZIP</button>
309
  {% endif %}
 
1131
  setStatus('Downloaded final HTML.');
1132
  }
1133
 
1134
+ function formatTimecode(seconds) {
1135
+ const sec = Math.max(0, Math.floor(seconds || 0));
1136
+ const h = Math.floor(sec / 3600);
1137
+ const m = Math.floor((sec % 3600) / 60);
1138
+ const ss = sec % 60;
1139
+ const pad = (n) => String(n).padStart(2, '0');
1140
+ return h ? `${h}:${pad(m)}:${pad(ss)}` : `${m}:${pad(ss)}`;
1141
+ }
1142
+
1143
+ function mdEscapeAlt(s) {
1144
+ // Inside ![alt](url), backslashes / brackets need escaping; newlines
1145
+ // would break the syntax so flatten them.
1146
+ return String(s || '').replace(/[\\\[\]]/g, '\\$&').replace(/\s+/g, ' ').trim();
1147
+ }
1148
+
1149
+ function buildMarkdown() {
1150
+ // Semantic markdown: headings as #/##, paragraphs as blank-line-
1151
+ // separated text, on-screen text as blockquote, math as $…$ /
1152
+ // $$…$$, images as ![alt](data:…). Per-section include toggles
1153
+ // and the description-replaces-alt rule are honoured exactly as
1154
+ // they are in buildFinalHTML, so the .md and .html outputs stay
1155
+ // consistent for any given editor state. Audio is intentionally
1156
+ // skipped — markdown has no semantic audio construct, and HTML
1157
+ // <audio> tags would either render inconsistently or be stripped.
1158
+ const state = readState();
1159
+ const stateBySegmentId = new Map();
1160
+ state.segments.forEach(s => stateBySegmentId.set(`section-${s.index}`, s));
1161
+ const out = [];
1162
+ const push = (line) => out.push(line == null ? '' : line);
1163
+
1164
+ // Document header.
1165
+ push(`# ${state.title || 'Study Guide'}`);
1166
+ push('');
1167
+ if (state.eyebrow && state.eyebrow.trim()) {
1168
+ push(`*${state.eyebrow.trim()}*`);
1169
+ push('');
1170
+ }
1171
+ if (state.subtitle && state.subtitle.trim()) {
1172
+ push(state.subtitle.trim());
1173
+ push('');
1174
+ }
1175
+ push('---');
1176
+ push('');
1177
+
1178
+ getSegmentEls().forEach(sec => {
1179
+ const segState = stateBySegmentId.get(sec.id);
1180
+ if (!segState) return;
1181
+ if (segState.include === false) return;
1182
+
1183
+ // ## Section title
1184
+ push(`## ${(segState.section_title || 'Untitled section').trim()}`);
1185
+ push('');
1186
+
1187
+ // Timestamps as italic plain text
1188
+ push(`*${formatTimecode(segState.start_seconds)} – ${formatTimecode(segState.end_seconds)}*`);
1189
+ push('');
1190
+
1191
+ // Determine include states from live DOM (matches buildFinalHTML).
1192
+ const descEl = sec.querySelector('[data-element="description"]');
1193
+ const descBody = descEl && descEl.querySelector('[data-bind="description"]');
1194
+ const descIncluded = descEl && descEl.getAttribute('data-include') !== 'false';
1195
+ const descText = descBody && (descBody.textContent || '').trim();
1196
+ const hasDescription = !!(descIncluded && descText);
1197
+ const altInclude = sec.getAttribute('data-include-alt-text') === 'true';
1198
+ const ocrEl = sec.querySelector('[data-element="on_screen_text"]');
1199
+ const ocrIncluded = ocrEl && ocrEl.getAttribute('data-include') !== 'false';
1200
+ const ocrText = ocrEl && (ocrEl.querySelector('[data-bind="ocr_text"]').textContent || '').trim();
1201
+ const transcriptEl = sec.querySelector('[data-element="transcript"]');
1202
+ const transcriptIncluded = transcriptEl && transcriptEl.getAttribute('data-include') !== 'false';
1203
+
1204
+ // Image. When a description carries the meaning, alt = "" to
1205
+ // match the published-HTML decorative pattern. Otherwise emit
1206
+ // the alt-text only when the user opted to include it.
1207
+ const img = sec.querySelector('figure img');
1208
+ if (img && img.getAttribute('src')) {
1209
+ let alt = '';
1210
+ if (!hasDescription && altInclude) {
1211
+ alt = (segState.alt_text || '').trim();
1212
+ }
1213
+ push(`![${mdEscapeAlt(alt)}](${img.getAttribute('src')})`);
1214
+ push('');
1215
+ }
1216
+
1217
+ // Scene description as plain paragraphs.
1218
+ if (hasDescription) {
1219
+ descText.split(/\n\n+/).map(p => p.trim()).filter(Boolean).forEach(p => {
1220
+ push(p.replace(/\n/g, ' '));
1221
+ push('');
1222
+ });
1223
+ }
1224
+
1225
+ // On-screen text as a labelled blockquote.
1226
+ if (ocrIncluded && ocrText) {
1227
+ push('**On-screen text from video**');
1228
+ push('');
1229
+ ocrText.split('\n').forEach(line => push(`> ${line}`));
1230
+ push('');
1231
+ }
1232
+
1233
+ // Transcript as plain paragraphs.
1234
+ if (transcriptIncluded && segState.narration && segState.narration.length) {
1235
+ segState.narration.forEach(p => {
1236
+ const text = (p || '').trim();
1237
+ if (!text) return;
1238
+ push(text);
1239
+ push('');
1240
+ });
1241
+ }
1242
+
1243
+ // Math equations: $…$ for inline, $$…$$ for block.
1244
+ (segState.math_equations || []).forEach(eq => {
1245
+ const latex = (eq.latex || '').trim();
1246
+ if (!latex) return;
1247
+ if (eq.label) {
1248
+ push(`**${eq.label}**`);
1249
+ push('');
1250
+ }
1251
+ if (eq.inline) {
1252
+ push(`$${latex}$`);
1253
+ } else {
1254
+ push(`$$`);
1255
+ push(latex);
1256
+ push(`$$`);
1257
+ }
1258
+ push('');
1259
+ if (eq.caption) {
1260
+ push(`*${eq.caption}*`);
1261
+ push('');
1262
+ }
1263
+ });
1264
+
1265
+ push('---');
1266
+ push('');
1267
+ });
1268
+
1269
+ // Trim trailing blank lines and trailing horizontal rule.
1270
+ while (out.length && out[out.length - 1] === '') out.pop();
1271
+ if (out[out.length - 1] === '---') out.pop();
1272
+ while (out.length && out[out.length - 1] === '') out.pop();
1273
+ return out.join('\n') + '\n';
1274
+ }
1275
+
1276
+ function downloadMarkdown() {
1277
+ setStatus('Building markdown…');
1278
+ const md = buildMarkdown();
1279
+ const blob = new Blob([md], { type: 'text/markdown;charset=utf-8' });
1280
+ const url = URL.createObjectURL(blob);
1281
+ const a = document.createElement('a');
1282
+ a.href = url;
1283
+ a.download = safeName(titleEl.textContent.trim()) + '.md';
1284
+ document.body.appendChild(a); a.click(); a.remove();
1285
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1286
+ setStatus('Downloaded markdown.');
1287
+ }
1288
+
1289
  let previewURL = null;
1290
  window.addEventListener('pagehide', () => {
1291
  if (previewURL) {
 
1374
  toolbar.querySelector('[data-action="save-json"]').addEventListener('click', saveJSON);
1375
  toolbar.querySelector('[data-action="preview-html"]').addEventListener('click', previewHTML);
1376
  toolbar.querySelector('[data-action="download-html"]').addEventListener('click', downloadHTML);
1377
+ toolbar.querySelector('[data-action="download-markdown"]').addEventListener('click', downloadMarkdown);
1378
  const zipBtn = toolbar.querySelector('[data-action="download-zip"]');
1379
  if (zipBtn) zipBtn.addEventListener('click', downloadZIP);
1380
  const loadInput = toolbar.querySelector('[data-action="load-json"]');
tests/test_html_gen.py CHANGED
@@ -401,6 +401,18 @@ def test_render_guide_falls_back_to_alt_when_no_description(tmp_path):
401
  assert "Alt-text needs author review." in html
402
 
403
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  def test_render_review_emits_bulk_toggle_bar(tmp_path):
405
  """Per UX feedback: a 'Apply to all sections' bar exposes a bulk
406
  checkbox per element type so the editor can hide/show alt-text,
 
401
  assert "Alt-text needs author review." in html
402
 
403
 
404
+ def test_render_review_has_markdown_download_button(tmp_path):
405
+ """Editor toolbar exposes a Download Markdown action alongside the
406
+ HTML download. Both produce single self-contained files honouring
407
+ the same per-element include toggles."""
408
+ img = tmp_path / "scene_0000.jpg"
409
+ _make_image(img)
410
+ segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
411
+ html = render_review("Review Me", segments, lang="en")
412
+ assert 'data-action="download-markdown"' in html
413
+ assert '>Download Markdown<' in html
414
+
415
+
416
  def test_render_review_emits_bulk_toggle_bar(tmp_path):
417
  """Per UX feedback: a 'Apply to all sections' bar exposes a bulk
418
  checkbox per element type so the editor can hide/show alt-text,