diff options
Diffstat (limited to 'src/features')
| -rw-r--r-- | src/features/messages.js | 153 |
1 files changed, 138 insertions, 15 deletions
diff --git a/src/features/messages.js b/src/features/messages.js index 76d8c4f..cdb9aea 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -12356,12 +12356,24 @@ export function messagesFeature(ctx) { // at the top of the feed before any signing or relay round-trip (a remote // signer alone can take seconds), swapped for the signed event on success // and withdrawn on failure. + // the hashtags in the text as t tags (NIP-24), so topic feeds and other + // clients' searches find the post — up to the count past which a post + // reads as hashtag spam + const postHashtags = (text) => [...new Set([...String(text || '').matchAll(/(^|[^\w#/&])#([\p{L}\p{N}_]{2,64})(?![\w])/gu)].map((m) => normTopic(m[2])))].slice(0, HASHTAG_MAX); + function postTags(text, media, me) { + // NIP-92: what we uploaded, described, so clients needn't sniff the URL + const imeta = media.filter((m) => m && m.url).map(mediaImeta); + // NIP-18 quote: the reference is already in the text; the tags let a + // client render the quoted post inline and tell its author + const q = ui.quoteOf && text.includes(ui.quoteOf.id.slice(0, 8)) + ? [] : ui.quoteOf ? [['q', ui.quoteOf.id], ['p', ui.quoteOf.pubkey]] : []; + // the people it mentions are told (NIP-27 p tags) + const mentions = mentionedPks(text).filter((pk) => pk !== me && !q.some((x) => x[0] === 'p' && x[1] === pk)).map((pk) => ['p', pk]); + return [...imeta, ...q, ...mentions, ...postHashtags(text).map((x) => ['t', x]), CLIENT_TAG]; + } async function publishPost(text, media = []) { const id = await requireIdentity(); - // the hashtags in the text as t tags (NIP-24), so topic feeds and other - // clients' searches find the post — up to the count past which a post - // reads as hashtag spam - const hashtags = [...new Set([...String(text || '').matchAll(/(^|[^\w#/&])#([\p{L}\p{N}_]{2,64})(?![\w])/gu)].map((m) => normTopic(m[2])))].slice(0, HASHTAG_MAX); + const hashtags = postHashtags(text); const temp = { id: 'pending:' + Math.random().toString(36).slice(2), pubkey: id.pubkey, content: text, created_at: Math.floor(Date.now() / 1000), @@ -12380,15 +12392,7 @@ export function messagesFeature(ctx) { for (const c of feeds) c.notes = [temp, ...c.notes]; render(); try { - // NIP-92: what we uploaded, described, so clients needn't sniff the URL - const imeta = media.filter((m) => m && m.url).map(mediaImeta); - // NIP-18 quote: the reference is already in the text; the tags let a - // client render the quoted post inline and tell its author - const q = ui.quoteOf && text.includes(ui.quoteOf.id.slice(0, 8)) - ? [] : ui.quoteOf ? [['q', ui.quoteOf.id], ['p', ui.quoteOf.pubkey]] : []; - // the people it mentions are told (NIP-27 p tags) - const mentions = mentionedPks(text).filter((pk) => pk !== id.pubkey && !q.some((x) => x[0] === 'p' && x[1] === pk)).map((pk) => ['p', pk]); - const partial = { kind: 1, content: text, created_at: temp.created_at, tags: [...imeta, ...q, ...mentions, ...temp.tags, CLIENT_TAG] }; + const partial = { kind: 1, content: text, created_at: temp.created_at, tags: postTags(text, media, id.pubkey) }; const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); const relays = [...new Set([...(await notesRelays(id.pubkey)), ...wallet.nostrRelays()])]; const ok = await publishOn(relays, evt); @@ -12404,6 +12408,93 @@ export function messagesFeature(ctx) { } } + // ---- scheduled posts ----------------------------------------------------- + // Signed now, with created_at = when it should appear, and handed to the + // notifier, which holds it and publishes it then (relays refuse notes from + // the future). Signing now means a remote signer is asked while you're + // here, and the note that goes out is exactly the one you wrote. This + // device remembers what it scheduled, to show and cancel; the post itself + // turns up in the feeds once it's out. + const SCHED_MIN_AHEAD = 120; + async function schedulePost(text, media, at) { + const id = await requireIdentity(); + if (!(at > Math.floor(Date.now() / 1000) + SCHED_MIN_AHEAD)) throw new Error(t('schedTooSoon')); + const partial = { kind: 1, content: text, created_at: at, tags: postTags(text, media, id.pubkey) }; + const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); + const relays = [...new Set([...(await notesRelays(id.pubkey)), ...wallet.nostrRelays()])]; + const res = await fetch(`${NOTIFIER}/schedule`, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ event: evt, relays }), + }).then((r) => r.json()).catch(() => ({ error: t('msgSendFailed') })); + if (!res.ok) throw new Error(res.error || t('msgSendFailed')); + ui.quoteOf = null; + const s = st(); + s.scheduled ||= {}; + s.scheduled[evt.id] = { at, text, pubkey: id.pubkey }; + save(s); + render(); + return evt; + } + // what this account has waiting, soonest first; anything past its time + // has gone out (or the notifier gave up) and leaves the list + function scheduledPosts() { + const s = st(), me = mePk(), now = Math.floor(Date.now() / 1000); + let dropped = false; + for (const [k, v] of Object.entries(s.scheduled || {})) if (v.at < now - 60) { delete s.scheduled[k]; dropped = true; } + if (dropped) save(s); + return Object.entries(s.scheduled || {}).filter(([, v]) => v.pubkey === me) + .map(([id, v]) => ({ id, ...v })).sort((a, b) => a.at - b.at); + } + // once a session, ask which are still held: one cancelled on another + // device is gone from the notifier, so it goes from here too + let schedChecked = false; + function checkScheduled(list) { + if (schedChecked || !list.length) return; + schedChecked = true; + fetch(`${NOTIFIER}/schedule/status?ids=${list.map((x) => x.id).join(',')}`).then((r) => r.json()).then((st_) => { + const s = st(); + let n = 0; + for (const [k, v] of Object.entries(st_ || {})) if (v === 'gone' && s.scheduled?.[k]) { delete s.scheduled[k]; n++; } + if (n) { save(s); render(); } + }).catch(() => {}); + } + async function cancelScheduled(item) { + const id = await requireIdentity(); + const partial = { kind: 5, content: '', created_at: Math.floor(Date.now() / 1000), tags: [['e', item.id]] }; + const del = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); + const res = await fetch(`${NOTIFIER}/schedule/cancel`, { + method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ event: del }), + }).then((r) => r.json()).catch(() => ({})); + if (!res.ok) throw new Error(res.error || t('msgSendFailed')); + const s = st(); + delete s.scheduled?.[item.id]; + save(s); + render(); + } + const schedWhen = (at) => new Date(at * 1000).toLocaleString(undefined, { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + // <input type=datetime-local> speaks local wall-clock time + const localInput = (ms) => { const d = new Date(ms); d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); return d.toISOString().slice(0, 16); }; + function scheduledList() { + const list = scheduledPosts(); + checkScheduled(list); + if (!list.length) return null; + return h('div', { class: 'card col sched-list', 'data-key': 'sched-list', style: 'gap:8px' }, + h('div', { class: 'small muted' }, t('schedListTitle', { n: list.length })), + ...list.map((x) => h('div', { class: 'row gap6 sched-item', 'data-key': 'sched:' + x.id, style: 'align-items:flex-start' }, + h('div', { class: 'col grow', style: 'min-width:0;gap:2px' }, + h('div', { class: 'small', style: 'font-weight:600' }, '\u{1F552} ' + schedWhen(x.at)), + h('div', { class: 'small muted', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, x.text)), + h('button', { + class: 'btn-ghost btn-sm', disabled: ui.schedCancelling === x.id, + onClick: async () => { + ui.schedCancelling = x.id; render(); + try { await cancelScheduled(x); toast(t('schedCancelled')); } + catch (e) { if (!e.silent) toast(e.message || String(e)); } + ui.schedCancelling = null; render(); + }, + }, ui.schedCancelling === x.id ? h('span', { class: 'spinner sm' }) : t('cancel'))))); + } + async function publishReply(c, s, text) { const id = await requireIdentity(); const target = c.replies.find((e) => e.id === s.focusId) || c.root || s.seed; @@ -13153,6 +13244,7 @@ export function messagesFeature(ctx) { // the half-written post back, composer open. Posting clears // it; Cancel just closes the composer and keeps the text. postComposer(), + ui.profCompose == null ? scheduledList() : null, // the non-destructive way out: add another identity (Nostr, // passkey, Google) next to this one and switch between them // on the Accounts screen — logout stays for actually leaving @@ -13333,6 +13425,7 @@ export function messagesFeature(ctx) { ui.profCompose = null; ui.postMedia = []; ui.postPreview = false; + ui.postSchedule = null; discardDraft(POST_DRAFT); render(); } @@ -13428,11 +13521,34 @@ export function messagesFeature(ctx) { mentionList('.post-input'), ui.postPreview ? draftPreview(text) : null, mediaBar(), + ui.postSchedule != null ? h('label', { class: 'row gap6 sched-pick', style: 'align-items:center' }, + h('span', { class: 'small muted' }, t('schedAt')), + h('input', { + type: 'datetime-local', class: 'grow', value: ui.postSchedule, + min: localInput(Date.now() + SCHED_MIN_AHEAD * 1000), max: localInput(Date.now() + 90 * 86400_000), + onInput: (ev) => { ui.postSchedule = ev.target.value; }, + })) : null, h('div', { class: 'row gap6 wrap post-actions' }, - h('button', { class: 'btn-primary grow', disabled: !!ui.postUploading, onClick: async () => { + h('button', { class: 'btn-primary grow', disabled: !!ui.postUploading || !!ui.postScheduling, onClick: async () => { const body = composeText().trim(); if (!body) return; const media = (ui.postMedia || []).filter((m) => body.includes(m.url)); + if (ui.postSchedule != null) { + // nothing goes on screen yet, so the composer stays open until + // the notifier has it (a signer may ask first) + const at = Math.floor(new Date(ui.postSchedule).getTime() / 1000); + ui.postScheduling = true; render(); + try { + await schedulePost(body, media, at); + ui.profCompose = null; ui.postMedia = []; ui.postSchedule = null; + setDraft(POST_DRAFT, ''); + const inp = document.querySelector('.post-input'); + if (inp) inp.value = ''; + toast(t('schedDone', { when: schedWhen(at) })); + } catch (e) { if (!e.silent) toast(e.message || String(e)); } + ui.postScheduling = false; render(); + return; + } // the post is on screen instantly (publishPost is optimistic) — // close the composer now; a failure reopens it with the text intact ui.profCompose = null; @@ -13446,14 +13562,21 @@ export function messagesFeature(ctx) { if (!e.silent) toast(e.message || String(e)); render(); } - } }, t('profPostBtn')), + } }, ui.postScheduling ? h('span', { class: 'spinner sm' }) : t(ui.postSchedule != null ? 'schedBtn' : 'profPostBtn')), h('input', { type: 'file', id: 'post-file', accept: 'image/*,video/*', style: 'display:none', onChange: async (e) => { const f = e.target.files && e.target.files[0]; e.target.value = ''; await attachMedia(f); }, }), h('div', { class: 'row gap6 composer-options' }, previewBtn(!!ui.postPreview, () => { ui.postPreview = !ui.postPreview; render(); }), + h('button', { + type: 'button', class: 'btn-ghost btn-sm', title: t('schedToggle'), 'aria-label': t('schedToggle'), + 'aria-pressed': String(ui.postSchedule != null), + // an hour from now, on the next quarter hour + onClick: () => { ui.postSchedule = ui.postSchedule != null ? null : localInput(Math.ceil((Date.now() + 3600_000) / 900_000) * 900_000); render(); }, + }, '\u{1F552}'), h('button', { class: 'btn-ghost btn-sm', onClick: requestCancelPost }, t('cancel')))), + scheduledList(), postCancelWarning(), gifs.sheet('post', (g) => { const cur = composeText().replace(/\s+$/, ''); |
