diff options
| -rw-r--r-- | src/features/messages.js | 28 | ||||
| -rw-r--r-- | src/style.css | 2 | ||||
| -rw-r--r-- | tools/post-markdown-test.js | 43 |
3 files changed, 71 insertions, 2 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index c803d4d..06371cf 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -8016,6 +8016,30 @@ export function messagesFeature(ctx) { // `em` is the event's own ["emoji", code, url] map (NIP-30): a :code: it // names becomes its picture, any other :code: stays text — a message // never borrows pictures from packs the READER happens to hold. + // Inline markdown in a post's plain text, the subset people actually type + // and Amethyst already shows: **bold** / __bold__, *italic* / _italic_, + // ~~struck~~ and `code`. Strict about edges so snake_case, 2*3*4 and a lone + // asterisk stay as typed; markers never reach across a link, mention or + // hashtag (those are split out first). No headings or lists in posts — + // "#" at a line's start is a hashtag here, and articles have their own. + const MD_INLINE = /(`[^`\n]+`)|(\*\*\*(?=\S)[^\n]*?\S\*\*\*)|(\*\*(?=\S)[^\n]*?\S\*\*)|((?<![\p{L}\p{N}_])__(?=\S)[^\n]*?\S__(?![\p{L}\p{N}_]))|(~~(?=\S)[^\n]*?\S~~)|((?<![\p{L}\p{N}*])\*(?=[^\s*])[^*\n]*?[^\s*]\*(?![\p{L}\p{N}*]))|((?<![\p{L}\p{N}_])_(?=[^\s_])[^_\n]*?[^\s_]_(?![\p{L}\p{N}_]))/u; + function mdInline(str) { + const out = []; + let rest = String(str); + for (let guard = 0; rest && guard < 200; guard++) { + const m = MD_INLINE.exec(rest); + if (!m) { out.push(rest); break; } + if (m.index) out.push(rest.slice(0, m.index)); + const tok = m[0]; + if (m[1]) out.push(h('code', { class: 'md-code' }, tok.slice(1, -1))); + else if (m[2]) out.push(h('strong', {}, h('em', {}, ...mdInline(tok.slice(3, -3))))); + else if (m[3] || m[4]) out.push(h('strong', {}, ...mdInline(tok.slice(2, -2)))); + else if (m[5]) out.push(h('s', {}, ...mdInline(tok.slice(2, -2)))); + else out.push(h('em', {}, ...mdInline(tok.slice(1, -1)))); + rest = rest.slice(m.index + tok.length); + } + return out; + } function noteBody(text, depth = 0, em = null) { const out = []; const emojiAt = em && em.size ? (c) => em.get(c) : null; @@ -8062,8 +8086,8 @@ export function messagesFeature(ctx) { onClick: (e) => { e.preventDefault(); e.stopPropagation(); openTopicFeed(part.slice(1)); }, }, part)); } else if (emojiAt && part.includes(':')) { - for (const p of splitEmoji(part, emojiAt)) out.push(typeof p === 'string' ? p : emojiImg(p.code, p.url)); - } else out.push(part); + for (const p of splitEmoji(part, emojiAt)) out.push(...(typeof p === 'string' ? mdInline(p) : [emojiImg(p.code, p.url)])); + } else out.push(...mdInline(part)); } return out; } diff --git a/src/style.css b/src/style.css index 5e3ddd7..8d41124 100644 --- a/src/style.css +++ b/src/style.css @@ -1628,3 +1628,5 @@ body::after { .mention-ac { display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 10px; background: var(--paper); overflow: hidden; max-height: 280px; overflow-y: auto; } .mention-ac:empty { display: none; } .mention-ac .item { cursor: pointer; padding: 6px 10px; } +/* `code` in a post */ +.md-code { font-family: var(--mono, ui-monospace, monospace); font-size: .9em; background: color-mix(in srgb, currentColor 9%, transparent); border-radius: 4px; padding: 0 .3em; } diff --git a/tools/post-markdown-test.js b/tools/post-markdown-test.js new file mode 100644 index 0000000..e4cf27b --- /dev/null +++ b/tools/post-markdown-test.js @@ -0,0 +1,43 @@ +// Posts render the inline markdown people type — **bold**, *italic*, +// ~~struck~~, `code` — and leave snake_case, 2*3*4 and lone stars alone. +// Run: bun tools/post-markdown-test.js +import puppeteer from './puppeteer.js'; +import { finalizeEvent, generateSecretKey } from 'nostr-tools/pure'; +import { buildHtml, buildVerifyWorker } from '../build.js'; +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const sk = generateSecretKey(), now = Math.floor(Date.now() / 1000); +const TEXT = "📰 **In this week's issue:**\n\nWhen the *servers* go ~~dark~~ away, run `git clone` and keep snake_case_names, 2*3*4 and a lone * star as they are. This is plain English prose for the language check."; +const note = finalizeEvent({ kind: 1, created_at: now, tags: [], content: TEXT }, sk); +const profile = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Newsletter' }) }, sk); +const html = await buildHtml({ minify: true, pwa: false }); +const worker = await buildVerifyWorker({ minify: true }); +const server = Bun.serve({ port: 0, fetch(req) { + const path = new URL(req.url).pathname; + if (path === '/api/feed') return Response.json({ version: 1, generatedAt: Date.now(), popUntil: now - 100, notes: [note], profiles: [profile] }); + if (path === '/verify-worker.js') return new Response(worker, { headers: { 'Content-Type': 'text/javascript' } }); + return new Response(html, { headers: { 'Content-Type': 'text/html' } }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +try { + const page = await browser.newPage(); + const errs = []; + page.on('pageerror', (e) => errs.push(String(e))); + await page.evaluateOnNewDocument(() => { + const Real = window.WebSocket; + window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } } catch {} return send(d); }; return ws; }; + window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); + }); + await page.goto(server.url.origin + '/feed'); + await page.waitForFunction(() => document.querySelector('.note-text strong'), { timeout: 15000 }).catch(() => {}); + const r = await page.evaluate(() => { + const t = document.querySelector('.note-text'); + return t ? { strong: [...t.querySelectorAll('strong')].map((x) => x.textContent), em: [...t.querySelectorAll('em')].map((x) => x.textContent), s: [...t.querySelectorAll('s')].map((x) => x.textContent), code: [...t.querySelectorAll('code')].map((x) => x.textContent), text: t.innerText } : null; + }); + check('**bold** is bold, markers gone', r && r.strong[0] === "In this week's issue:" && !r.text.includes('**'), JSON.stringify(r && r.strong)); + check('*italic*, ~~struck~~ and `code`', r && r.em[0] === 'servers' && r.s[0] === 'dark' && r.code[0] === 'git clone', JSON.stringify(r && [r.em, r.s, r.code])); + check('snake_case, 2*3*4 and a lone star stay as typed', r && r.text.includes('snake_case_names, 2*3*4 and a lone * star')); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ posts render inline markdown' : '\n❌ failed'); +process.exit(ok ? 0 : 1); |
