diff options
Diffstat (limited to 'src/features')
| -rw-r--r-- | src/features/ark.js | 71 | ||||
| -rw-r--r-- | src/features/gifts.js | 2 | ||||
| -rw-r--r-- | src/features/messages.js | 244 | ||||
| -rw-r--r-- | src/features/names.js | 4 | ||||
| -rw-r--r-- | src/features/nostrlogin.js | 143 | ||||
| -rw-r--r-- | src/features/nwc.js | 15 | ||||
| -rw-r--r-- | src/features/pos.js | 30 | ||||
| -rw-r--r-- | src/features/withdraw-links.js | 25 | ||||
| -rw-r--r-- | src/features/zaps.js | 8 |
9 files changed, 471 insertions, 71 deletions
diff --git a/src/features/ark.js b/src/features/ark.js index 1b8c591..2c1a581 100644 --- a/src/features/ark.js +++ b/src/features/ark.js @@ -1,4 +1,4 @@ -import { momentTags } from '../media-timeline.js'; +import { momentTags, momentToggle, mediaClock } from '../media-timeline.js'; // Ark feature — off-chain payments via an ASP (Second's bark/captaind // protocol, spoken natively by ../ark). Receive address + boarding, instant // sends, history entries, refresh/consolidation, server settings. @@ -1516,13 +1516,27 @@ export function arkFeature(ctx) { : m.type === 'ln-send' && m.invoice ? zapNotes()['inv:' + m.invoice] : null; - function arkHistoryItem(m) { + // A move inside one account (on-chain ⇄ Ark): no money in or out, only + // what moving it cost. + function arkInternalMoveItem(m, feeSat, pending) { + const label = m.type === 'board' ? (pending ? t('movingInstant') : t('movedInstant')) : t('movedOnchain'); + return h('div', { class: 'item internal-move', style: m.id ? 'cursor:pointer' : '', onClick: m.id ? () => { ui.arkMoveDetail = m.id; render(); } : undefined }, + h('div', { class: 'ico' }, '\u21c4'), + h('div', { class: 'grow' }, + h('div', {}, label), + h('div', { class: 'small faint' }, (pending ? t('pending') + ' · ' : '') + fmtAmount(m.amountSat || 0) + ' ' + unitLabel() + ' · ' + timeAgo((m.ts || Date.now()) / 1000))), + h('div', { style: 'text-align:right' }, + feeSat > 0 ? h('div', { class: 'amount-neg' }, fmtAmount(feeSat)) : h('div', { class: 'small faint' }, t('arkDepthFree')))); + } + + function arkHistoryItem(m, labelAs) { const failed = m.status === 'failed'; const incoming = !['send', 'offboard', 'exit', 'ln-send', 'refresh'].includes(m.type); - const label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded') + let label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded') : m.type === 'ln-send' ? t('arkLnPaidHistory') : m.type === 'ln-receive' ? t('arkLnReceivedHistory') : m.type === 'offboard' ? t('arkOffboarded') : m.type === 'exit' ? t('arkExited') : m.type === 'refresh' ? t('arkRenewedHistory') : t('sent'); + if (labelAs) label = labelAs; // A spent input proves neither a payment amount nor its date: it can // contain change, an offboard, or a renewal this device has not synced. // Show the missing history explicitly until its records arrive. @@ -1892,7 +1906,8 @@ export function arkFeature(ctx) { // 3. an on-chain address from the BIP-353 record const NAMES_REGISTRAR = 'https://names.coinos.io'; function startNpubPay(pk, npub, eventId = null, autoSat = 0, moment = null) { - const z = { npub, pk, eventId, moment, amount: '', comment: '', status: 'lookup', autoSat }; + // `moment`: where the clip was — offered in the sheet, tied only when ticked + const z = { npub, pk, eventId, momentOffer: moment, moment: null, amount: '', comment: '', status: 'lookup', autoSat }; // A one-tap post zap has no card: it resolves and pays off-screen, so a // second tap — the same post again, or another — never evicts the one // already in the air. Everything else takes the send screen's zap slot. @@ -1974,7 +1989,7 @@ export function arkFeature(ctx) { z.lnOk = true; await connectArk().catch(() => {}); if (!live()) return; - if (ctx.hook('canLnZap')) { if (ui.arkZap === z) ui.arkZap = null; ctx.hook('lnZapNpub', pk, npub, z.eventId, z.autoSat, z.moment); return; } + if (ctx.hook('canLnZap')) { if (ui.arkZap === z) ui.arkZap = null; ctx.hook('lnZapNpub', pk, npub, z.eventId, z.autoSat, z.moment || (z.autoSat ? null : z.momentOffer)); return; } } // 3. on-chain fallback (a one-tap zap can't take the send form) if (onchain && !(z.autoSat && z.eventId)) { @@ -2227,6 +2242,8 @@ export function arkFeature(ctx) { h('div', { style: 'display:flex;align-items:center' }, unitTag())), h('input', { type: 'text', class: 'mono-input', placeholder: t('arkZapCommentPh'), value: z.comment, onInput: (e) => { z.comment = e.target.value; } }), + z.momentOffer ? h('div', { class: 'row' }, momentToggle(h, z.momentOffer, !!z.moment, (on) => { z.moment = on ? z.momentOffer : null; render(); }, + t('mediaTieTo', { time: mediaClock(z.momentOffer.seconds) }))) : null, h('div', { class: 'small faint' }, hint)); return h('div', { class: 'card col', style: 'gap:12px' }, h('h3', {}, '⚡ ' + t('zapTitle')), @@ -2237,7 +2254,7 @@ export function arkFeature(ctx) { // Only someone with a Lightning address gets the Lightning door (the // lookup normally hands such a person straight to the zaps feature). noAddr && z.lnOk && ctx.hook('canLnZap') - ? h('button', { class: 'btn-block', disabled: !!ui.busy, onClick: () => { ctx.hook('lnZapNpub', z.pk, z.npub, z.eventId, 0, z.moment); } }, '⚡ ' + t('lnZapFallback')) + ? h('button', { class: 'btn-block', disabled: !!ui.busy, onClick: () => { ctx.hook('lnZapNpub', z.pk, z.npub, z.eventId, 0, z.moment || z.momentOffer); } }, '⚡ ' + t('lnZapFallback')) : null, payable && spendable < 330 ? h('div', { class: 'notice info' }, t(spendable + renewingSat() >= 330 ? 'spendingRenewingPayment' : 'zapNoBalance')) @@ -4267,7 +4284,11 @@ export function arkFeature(ctx) { } // In a Spending wallet an on-chain address means "exit ark to there": // the offboard happens right in the send flow, no Move money ceremony. - if (ctx.getAccount() === 'spending' && wallet.isOnchainAddress(inv) && arkAvailable()) { + // One balance: an on-chain address is paid from the on-chain coins + // when there are any — one ordinary transaction, nothing to move out + // of Ark first. Only without them does the payment leave Ark. + const onchainFirst = ctx.unifiedBalance && ctx.unifiedBalance() && (wallet.spendable || 0) > 0; + if (ctx.getAccount() === 'spending' && !onchainFirst && wallet.isOnchainAddress(inv) && arkAvailable()) { const b = arkBalance() || {}; if ((b.spendableSat || 0) > 0) { ui.arkOffboardSend = { address: inv, amount: '' }; @@ -4330,10 +4351,11 @@ export function arkFeature(ctx) { render(); } }, t('arkExitInFlightLink', { n: fmtAmount(acts.reduce((s2, a) => s2 + a.amountSat, 0)) })); }, - historyEntries(_txs, sel) { - if (sel && sel !== 'spending') return []; // ark movements are the Spending timeline + historyEntries(txs, sel) { + if (sel && sel !== 'spending' && sel !== 'all') return []; // ark movements are the Spending timeline const s = arkStateNow(); if (!s) return []; + if (sel === 'all') return this._histOne(s, txs || []); // Memoized on the state's REVISION, not a timer. This rebuild sorts and // dedupes every movement, resolves gifts, and touches secp256k1 — ~60ms // cold. A 1.5s TTL used to re-cool it between unhurried flicks, so every @@ -4346,6 +4368,35 @@ export function arkFeature(ctx) { this._histMemo = { key, val }; return val; }, + // One balance's timeline: a board, or an offboard to our own on-chain + // address, moves money between two halves of the same account. Its + // on-chain transaction and its Ark movement were two rows (Sent, then + // Boarded); here they're one, worth what the move cost. + _histOne(s, txs) { + const key = `${s._rev || 0}:${(s.movements || []).length}:${(s.actions || []).length}`; + if (!(this._histMemo && this._histMemo.key === key)) this._histMemo = { key, val: this._histBuild(s) }; + const own = new Map(txs.map((tx) => [tx.txid, tx])); + const rows = this._histMemo.val.map((e) => { + const m = e.m; + // with no Savings to move to, an offboard elsewhere is a payment + if (m && m.type === 'offboard' && !(m.txid && own.has(m.txid))) return { ...e, render: () => arkHistoryItem(m, t('sent')) }; + if (!m || !m.txid || !own.has(m.txid) || (m.type !== 'board' && m.type !== 'offboard')) return e; + const tx = own.get(m.txid); + const feeSat = m.type === 'board' ? Math.max(0, -(tx.net || 0) - (m.amountSat || 0)) : (m.feeSat || 0); + return { ...e, replacesTxid: m.txid, render: () => arkInternalMoveItem(m, feeSat, false) }; + }); + // a board still waiting on its funding transaction's confirmations + const told = new Set(rows.map((e) => e.replacesTxid).filter(Boolean)); + for (const a of s.actions || []) { + if (a.type !== 'board' || !a.fundingTxid || ['done', 'failed'].includes(a.step) || told.has(a.fundingTxid)) continue; + const tx = own.get(a.fundingTxid); + if (!tx) continue; + const m = { id: null, type: 'board', amountSat: (a.amountSat || 0) - (a.feeSat || 0), ts: exitStartedTs(a), txid: a.fundingTxid }; + const feeSat = Math.max(0, -(tx.net || 0) - m.amountSat); + rows.push({ time: m.ts, replacesTxid: a.fundingTxid, render: () => arkInternalMoveItem(m, feeSat, true) }); + } + return rows; + }, _histBuild(s) { // In-flight exits are payments the user made — they belong in history // as pending records, not on a monitoring page nobody thinks to visit. @@ -4429,7 +4480,7 @@ export function arkFeature(ctx) { } } this._histFolded = folded; // a folded row's detail shows the whole payment - return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }))); + return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, m, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }))); }, historyDetail() { if (ui.arkExitDetail) { diff --git a/src/features/gifts.js b/src/features/gifts.js index c6ccbd9..30b8d5e 100644 --- a/src/features/gifts.js +++ b/src/features/gifts.js @@ -1096,7 +1096,7 @@ export function giftsFeature(ctx) { balanceLines() { const locked = wallet.giftLockedValue(); // on-chain reservations: money still in Savings, spoken for - return locked > 0 ? [{ label: t('lockedInGifts'), sat: locked, side: 'savings' }] : []; + return locked > 0 ? [{ label: t('balGifts'), sat: locked, side: 'savings', part: true }] : []; }, historyEntries(txs, sel) { // These are ON-CHAIN gift reservations — Savings timeline. Ark gifts show diff --git a/src/features/messages.js b/src/features/messages.js index 2892153..d5d286a 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -1,4 +1,4 @@ -import { mediaMoment, momentTags, readMoment, mediaClock, mediaTimeline, markAt } from '../media-timeline.js'; +import { mediaMoment, momentTags, readMoment, mediaClock, mediaTimeline, markAt, momentToggle } from '../media-timeline.js'; import { mediaServers } from '../media-servers.js'; // Messages — Concord community chat (CORD-01..05) + NIP-17 private DMs. // @@ -39,7 +39,7 @@ import { createThreadPrefetch } from '../thread-prefetch.js'; import { makeImageThumbnails } from '../image-thumbnails.js'; import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js'; import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js'; -import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache } from '../recipient-search.js'; +import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache, searchRecipients, searchable } from '../recipient-search.js'; import { getNetwork } from '../api.js'; import { decodeBolt11 } from '../ark/lightning.js'; import { hexToBytes, bytesToHex } from '@noble/hashes/utils'; @@ -4360,6 +4360,7 @@ export function messagesFeature(ctx) { } function openProfile(pk) { rememberPlace('p:' + pk); + viewedProfiles.set(pk, Date.now()); ui.liveStream = null; ui.profilePk = pk; // Opened from inside a thread (an author's avatar/name), the profile @@ -4833,7 +4834,9 @@ export function messagesFeature(ctx) { } }, '▶ ' + mediaClock(m.seconds)); } const momentStripped = (ev, text) => (readMoment(ev) ? String(text || '').replace(/^\s*\[\d{1,2}(?::\d{2}){1,2}\]\s*/, '') : text); - const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, mediaMoment: m } : ev; }; + // the moment is only offered: a reaction is about it once the toggle says so + const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, momentOffer: m } : ev; }; + const tieLabel = (m) => t('mediaTieTo', { time: mediaClock(m.seconds) }); function attachMediaTimeline(player, url, explicitEvent) { if (player._timeline) return; player._timeline = true; @@ -5246,7 +5249,13 @@ export function messagesFeature(ctx) { // A word search (def.search) asks NIP-50 relays for notes and replies // whose text holds it: kind 1 only, replies kept as rows of their own. const feedKinds = (def) => (def && def.search ? [1] : def && def.replies ? REPLY_KINDS : FEED_KINDS); - const feedKeeps = (def, e) => (def && def.search ? e.kind === 1 : def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e)); + // A search within someone's posts reads their own relays too (few people + // are in any search index), so it checks the words itself: every word, + // anywhere in the text, case and accents aside. + const foldText = (x) => String(x || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, ''); + const searchWords = (q) => foldText(q).split(/\s+/).map((w) => w.replace(/^#/, '')).filter(Boolean); + const saysWords = (q, e) => { const text = foldText(e.content); return searchWords(q).every((w) => text.includes(w)); }; + const feedKeeps = (def, e) => (def && def.search ? e.kind === 1 && (!(def.authors || []).length || saysWords(def.search, e)) : def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e)); // What a reply answers: the e tag marked 'reply' (NIP-10), else 'root' // (a reply straight to the root), else — the deprecated positional form — // the last e tag; a NIP-22 comment's lowercase e (its parent), else its E. @@ -6541,7 +6550,7 @@ export function messagesFeature(ctx) { c.at = Date.now(); const merge = { newerThan: c.notes.length ? c.notes[0].created_at : Infinity }; if (def.search) { - try { await queryFeed(feedRelaysOr(def, TEXT_SEARCH_RELAYS), { kinds: [1], search: def.search, limit: FEED_PAGE }, merge, c, 5000); } catch {} finally { + try { await searchPass(def, c, merge); } catch {} finally { if (!c.stopped) { c.status = 'ready'; if (c === feed && ui.chatOpen && ui.msgView === 'feed') scheduleRepaint(); } } return; @@ -6583,8 +6592,10 @@ export function messagesFeature(ctx) { const fits = (e) => feedKeeps(def, e) && (((!authors.size || authors.has(e.pubkey)) && (!topics.size || tagged(e, topics))) || (orT.size && tagged(e, orT))); const seen = new Set(), out = []; - for (const o of feedStates.values()) { - for (const e of o.notes) if (!seen.has(e.id) && fits(e) && !hidden(e)) { seen.add(e.id); out.push(e); } + // a search within someone's posts: what their profile already loaded + const pools = [...[...feedStates.values()].map((o) => o.notes), ...(def.search ? [...authors].map((pk) => (notesCache.get(pk) || {}).notes || []) : [])]; + for (const notes of pools) { + for (const e of notes) if (!seen.has(e.id) && fits(e) && !hidden(e)) { seen.add(e.id); out.push(e); } } return out.sort((a, b) => b.created_at - a.created_at).slice(0, FEED_PAGE); } @@ -6695,7 +6706,7 @@ export function messagesFeature(ctx) { const packs = (q.get('pack') || '').split(',').map((x) => parsePackLink(x.trim())).filter(Boolean); const relays = urlRelays(q); const words = (q.get('q') || '').trim(); - if (words) { openTextSearch(words, relays); return true; } + if (words) { openTextSearch(words, relays, authors); return true; } if (!authors.length && !topics.length && !packs.length) { openFirehose(relays); return true; } const sig = JSON.stringify([authors, topics, packs.map(packKey), relays]); let hsh = 5381; for (let i = 0; i < sig.length; i++) hsh = ((hsh * 33) ^ sig.charCodeAt(i)) >>> 0; @@ -6726,7 +6737,7 @@ export function messagesFeature(ctx) { if (def.all) return (def.curated ? '/feed' : '/feed/all') + r; if (def.builtin) return share && mePk() && !def.replies ? '/feed/' + npubOf(mePk()) + r : null; if (def.of) return '/feed/' + npubOf(def.of) + r; - if (def.search) return '/feed?q=' + encodeURIComponent(def.search) + (r ? '&' + r.slice(1) : ''); + if (def.search) return '/feed?q=' + encodeURIComponent(def.search) + ((def.authors || []).length ? '&p=' + def.authors.map(npubOf).join(',') : '') + (r ? '&' + r.slice(1) : ''); const authors = def.authors || [], topics = feedTopics(def), packs = def.packs || []; if (!authors.length && !packs.length && topics.length === 1) return '/feed/t/' + encodeURIComponent(topics[0]) + r; if (!authors.length && !topics.length && packs.length === 1) { @@ -6856,11 +6867,14 @@ export function messagesFeature(ctx) { } // Words typed into search and submitted without picking a suggestion: // the notes and replies that say them, as a feed for this session. - function openTextSearch(q, relays = []) { + // `authors`: only what these people posted ("search Franca's posts"). + function openTextSearch(q, relays = [], authors = []) { q = String(q || '').replace(/\s+/g, ' ').trim().slice(0, 200); if (!q) return; - const id = 'search:' + q.toLowerCase() + (relays.length ? '@' + relays.join(',') : ''); - if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: '\u201c' + q + '\u201d', follows: false, authors: [], packs: [], topics: [], search: q, relays }); + authors = hexList(authors).slice(0, 5); + const id = 'search:' + q.toLowerCase() + (authors.length ? '~' + authors.join(',') : '') + (relays.length ? '@' + relays.join(',') : ''); + const name = '\u201c' + q + '\u201d' + (authors.length ? ' \u00b7 ' + authors.map((pk) => displayName(pk)).join(', ') : ''); + if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name, follows: false, authors, packs: [], topics: [], search: q, relays }); showFeed(id); } // Something above the posts is in use — a post being written, the relay @@ -7903,6 +7917,34 @@ export function messagesFeature(ctx) { for (const e of evs || []) if (e && e.created_at && !(c.seenBack <= e.created_at)) c.seenBack = e.created_at; c.sawAny = (c.sawAny || 0) + ((evs || []).length); } + // A word search: the NIP-50 relays, and for a search within someone's + // posts their own recent posts too, read here a page at a time until a + // few match (most people's posts are in no search index at all). + async function searchPass(def, c, merge, extra = {}, limit = FEED_PAGE, relays = null) { + const authors = def.authors || []; + const indexed = queryFeed(relays || feedRelaysOr(def, TEXT_SEARCH_RELAYS), + { kinds: [1], search: def.search, limit, ...(authors.length ? { authors } : {}), ...extra }, merge, c, 5000).catch(() => false); + if (!authors.length) return indexed; + const read = (async () => { + const from = relays || [...new Set([...NOTE_RELAYS, ...PROFILE_ARCHIVE_RELAYS, + ...(await Promise.all(authors.map((pk) => relaysOf(pk).catch(() => [])))).flat()])]; + let until = extra.until, got = false, hits = 0; + for (let page = 0; page < 4 && !c.stopped; page++) { + let oldest = Infinity, n = 0; + await queryStreamOn(from, { kinds: [1], authors, limit: 400, ...(until ? { until } : {}) }, async (ev) => { + if (c.stopped) return; + n++; + if (ev.created_at < oldest) oldest = ev.created_at; + if (saysWords(def.search, ev) && await mergeFeed([ev], merge, c)) { got = true; hits++; } + }, 6000); + if (hits >= 10 || n < 100 || !isFinite(oldest)) break; + until = oldest - 1; + } + return got; + })().catch(() => false); + const [a, b] = await Promise.all([indexed, read]); + return a || b; + } async function queryFeed(relays, filter, merge, c, maxWait = 5000, qualifies = () => true) { let got = false; await queryStreamOn(relays, filter, async (ev) => { @@ -7923,7 +7965,7 @@ export function messagesFeature(ctx) { const tag = topics.length ? { '#t': topics } : {}; let got = false; if (def.curated) return popularPass(extra, merge, c, def); - if (def.search) return queryFeed(relays || feedRelaysOr(def, TEXT_SEARCH_RELAYS), { kinds: [1], search: def.search, limit, ...extra }, merge, c); + if (def.search) return searchPass(def, c, merge, extra, limit, relays); const orT = orTopicsOf(def); const orPass = orT.length ? queryFeed(relays || feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, limit, ...extra }, merge, c).then((x) => { if (x) got = true; }) @@ -11239,7 +11281,8 @@ export function messagesFeature(ctx) { } else ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev }; const s = ui.noteThread; ui.profOverThread = false; - s.mediaMoment = moment; + s.momentOffer = moment; // offered, not taken: the toggle in the box ties it + s.mediaMoment = null; s.replying = true; // the box appears under this note s.scrollPending = false; // focus the composer, without a competing note scroll s.refocus = true; @@ -12476,6 +12519,8 @@ export function messagesFeature(ctx) { }, h('div', { class: 'card col msg-sheet' }, reactRow(null, (e2) => { close(); reactTo(ev, e2).catch(() => {}).finally(after); setTimeout(after, 50); }), + ev.momentOffer ? h('div', { class: 'row', style: 'justify-content:center' }, + momentToggle(h, ev.momentOffer, !!ev.mediaMoment, (on) => { ev.mediaMoment = on ? ev.momentOffer : null; render(); }, tieLabel(ev.momentOffer))) : null, h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back')))); } @@ -13104,10 +13149,8 @@ export function messagesFeature(ctx) { style: 'gap:8px;margin:0 -8px;padding:' + (joined ? '2px' : '8px') + ' 8px 10px;background:var(--accent-soft,rgba(128,128,128,.08));border-radius:' + (joined ? '0 0 8px 8px' : '8px'), }, // the moment of the clip this reply is about, and a way to make it about the whole post - s.mediaMoment ? h('div', { class: 'row small muted', style: 'gap:6px;align-items:center' }, - t('mediaCommentAt') + ' ' + mediaClock(s.mediaMoment.seconds), - h('button', { type: 'button', class: 'btn-ghost btn-sm', 'aria-label': t('mediaMomentDrop'), title: t('mediaMomentDrop'), - style: 'padding:0 6px;min-height:0', onClick: () => { s.mediaMoment = null; if (s.momentFor) s.momentFor = null; render(); } }, '×')) : null, + s.momentOffer ? h('div', { class: 'row' }, + momentToggle(h, s.momentOffer, !!s.mediaMoment, (on) => { s.mediaMoment = on ? s.momentOffer : null; render(); }, tieLabel(s.momentOffer))) : null, s.preview ? draftPreview(s.draft) : null, mediaBar(), // A textarea that grows with the reply, like the chat composer: Enter @@ -13182,7 +13225,7 @@ export function messagesFeature(ctx) { // morph leaves a focused field's value alone: clear it by hand. onClick: () => { const text = s.draft || ''; - s.draft = ''; s.replying = false; s.preview = false; s.mediaMoment = null; + s.draft = ''; s.replying = false; s.preview = false; s.mediaMoment = null; s.momentOffer = null; ui.postMedia = (ui.postMedia || []).filter((m) => !text.includes(m.url)); const inp = document.querySelector('.thread-reply-input'); if (inp) inp.value = ''; @@ -13203,7 +13246,7 @@ export function messagesFeature(ctx) { // focused field's value — clear it by hand const inp = document.querySelector('.thread-reply-input'); if (inp) inp.value = ''; - s.replying = false; s.preview = false; s.mediaMoment = null; // sent: the box folds away + s.replying = false; s.preview = false; s.mediaMoment = null; s.momentOffer = null; // sent: the box folds away toast(t('threadReplied')); } catch (e) { if (!e.silent) toast(e.message); } s.sending = false; render(); @@ -17156,25 +17199,132 @@ export function messagesFeature(ctx) { const top = (rows || []).filter((r) => r.pk).slice(0, 2); for (const r of top.reverse()) prefetchProfilePage(r.pk, { first: true }); }); + // ---- searching inside someone's posts -------------------------------- + // "i found him by searching franca but then i was wanting some way to + // search his feed for something … i was wanting to search 'franca + // wildwood' but knew it wouldn't work" (Adam, 2026-11-14). Two ways in, + // no new field: a profile on screen puts its person in the search field as + // a chip (× or Backspace takes it out), and words that start or end with + // someone's name ("franca wildwood") are offered as that person's posts. + const viewedProfiles = new Map(); // pk -> when its profile was opened (this session) + // Whose posts the field searches: the open profile's person (unless taken + // out), else whoever the search page was scoped to. + function searchScope() { + if (ui.profilePk) return ui.searchScopeOff === ui.profilePk ? null : ui.profilePk; + return (ui.userSearch && ui.userSearch.scope) || null; + } + function unscopeSearch() { + if (ui.profilePk) ui.searchScopeOff = ui.profilePk; + if (ui.userSearch) ui.userSearch.scope = null; + if (ui.userSearch) guessScope(ui.userSearch.q || ''); + render(); + setTimeout(() => document.querySelector('.header-search-field, .user-search-input.user-search-main')?.focus(), 30); + } + function scopeChip() { + const pk = searchScope(); + if (!pk) return null; + return h('span', { class: 'search-scope-chip', title: t('searchInPosts', { name: displayName(pk) }) }, + avatar(pk, 'chat-avatar mini', false), + h('span', { class: 'search-scope-name' }, displayName(pk)), + h('button', { type: 'button', class: 'search-scope-x', 'aria-label': t('searchScopeRemove'), onMousedown: (e) => e.preventDefault(), onClick: unscopeSearch }, '\u00d7')); + } + // "franca wildwood": the first or last word or two may be a person. Asked + // of the people search; a hit must have the word at the start of a word of + // its name or address. Someone you follow, or whose profile you opened + // this session, is a strong guess (Enter goes there); anyone else is only + // offered as a row ("bitcoin wallet" is not Bitcoin Magazine's posts). + let guessSeq = 0, guessTimer = null; + function guessScope(q) { + clearTimeout(guessTimer); + const my = ++guessSeq; + const s = ui.userSearch; + if (s) s.guess = null; + const words = String(q || '').trim().split(/\s+/).filter(Boolean); + if (!s || s.scope || words.length < 2 || words.length > 8) return; + const splits = [[words.slice(0, 1), words.slice(1)], [words.slice(-1), words.slice(0, -1)]]; + if (words.length >= 3) splits.push([words.slice(0, 2), words.slice(2)], [words.slice(-2), words.slice(0, -2)]); + guessTimer = setTimeout(async () => { + let best = null; + await Promise.all(splits.map(async ([who, what]) => { + const part = who.join(' ').replace(/^@/, ''); + if (part.length < 3 || !searchable(part)) return; + const rows = await searchRecipients(part).catch(() => []); + const needle = ' ' + foldText(part); + rows.slice(0, 6).forEach((r, i) => { + if (!r.pk) return; + const hay = ' ' + foldText([r.name, r.address, r.nip05].filter(Boolean).join(' ')).replace(/[^\p{L}\p{N}]+/gu, ' '); + if (!hay.includes(needle)) return; + const known = isFollowing(r.pk) || viewedProfiles.has(r.pk); + const score = (known ? 100 : 0) + who.length * 5 + (i === 0 ? 3 : 0) - i; + if (!best || score > best.score) best = { pk: r.pk, text: what.join(' '), score, strong: known }; + }); + })); + if (my !== guessSeq || ui.userSearch !== s || s.q !== q) return; + s.guess = best; + render(); + }, 300); + } + // A guess is off when the whole query is someone's name ("jack dorsey"). + function usableGuess(s) { + const g = s && s.guess; + if (!g || s.scope) return null; + const whole = foldText(s.q).trim(); + if ((s.rows || []).some((r) => foldText(r.name).includes(whole))) return null; + return g; + } + // Where Enter goes: the scoped search, a strong guess, else everywhere. + function submitUserSearch(q) { + q = String(q || '').trim(); + if (!q) return; + const scope = searchScope(); + const s = ui.userSearch; + const g = s && s.q.trim() === q ? usableGuess(s) : null; + if (scope) openTextSearch(q, [], [scope]); + else if (g && g.strong) openTextSearch(g.text, [], [g.pk]); + else openTextSearch(q); + render(); + } + function scopedRows(s) { + const q = s.q.trim(); + if (q.length < 2 || /^(npub1|nprofile1|nevent1|note1|naddr1|nostr:)/i.test(q)) return []; + const scope = searchScope(), g = usableGuess(s); + const row = (pk, words, enter) => h('div', { class: 'item chat-thread-row search-scoped-row', onClick: () => { openTextSearch(words, [], [pk]); render(); } }, + avatar(pk, 'chat-avatar', false), + h('div', { class: 'col grow', style: 'min-width:0;gap:1px' }, + h('span', { class: 'chat-name' }, '\u201c' + words + '\u201d'), + h('div', { class: 'muted small' }, t('searchInPosts', { name: displayName(pk) }))), + enter ? h('kbd', { class: 'search-enter-hint' }, '\u21b5') : null); + if (scope) return [row(scope, q, true)]; + if (g) return [row(g.pk, g.text, g.strong)]; + return []; + } + function userSearchScreen() { const s = ui.userSearch; + const scoped = scopedRows(s); return h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(!ui.pubProf && wallet.loaded), h('div', { class: 'card col', style: 'gap:10px' }, h('h3', { class: 'user-search-main', style: 'margin:0' }, t('searchUsers')), - h('input', { - type: 'text', class: 'user-search-input user-search-main', placeholder: t('searchUsersHint'), value: s.q, - autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', - onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); }, - onKeydown: (e) => { if (e.key === 'Enter' && !e.isComposing && s.q.trim()) { e.preventDefault(); openTextSearch(s.q); render(); } }, - }), + h('div', { class: 'row gap6 user-search-main', style: 'align-items:center' }, + scopeChip(), + h('input', { + type: 'text', class: 'user-search-input user-search-main grow', placeholder: searchScope() ? t('searchScopedHint') : t('searchUsersHint'), value: s.q, + autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', + onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); guessScope(s.q); }, + onKeydown: (e) => { + if (e.key === 'Enter' && !e.isComposing && s.q.trim()) { e.preventDefault(); submitUserSearch(s.q); } + else if (e.key === 'Backspace' && !e.target.value && searchScope()) { e.preventDefault(); unscopeSearch(); } + }, + })), + scoped.length ? h('div', { class: 'list' }, ...scoped) : null, // the words themselves: every note and reply that says them s.q.trim().length >= 2 && !/^(npub1|nprofile1|nevent1|note1|naddr1|nostr:)/i.test(s.q.trim()) ? h('div', { class: 'list' }, h('div', { class: 'item chat-thread-row', onClick: () => { openTextSearch(s.q); render(); } }, h('div', { class: 'chat-avatar fallback' }, '\u{1F50D}'), h('div', { class: 'col grow', style: 'min-width:0;gap:1px' }, h('span', { class: 'chat-name' }, '\u201c' + s.q.trim() + '\u201d'), - h('div', { class: 'muted small' }, t('searchPostsRow'))))) + h('div', { class: 'muted small' }, t(scoped.length ? 'searchPostsRowAll' : 'searchPostsRow'))))) : null, // a word is a topic too: posts tagged with it, as a feed (() => { @@ -17954,7 +18104,7 @@ export function messagesFeature(ctx) { // the message's own custom emoji (an edit brings its own set) const em = emojiTagMap((edit && edit.author === m.author ? edit.rumor : m.rumor).tags); return h( - 'div', { class: 'chat-row' + (mine ? ' mine' : '') + (grouped ? ' grouped' : '') }, + 'div', { class: 'chat-row group' + (mine ? ' mine' : '') + (grouped ? ' grouped' : '') }, grouped ? h('div', { class: 'chat-avatar spacer' }) : avatar(m.author), h('div', { class: 'chat-body' }, grouped ? null : h('div', { class: 'chat-meta' }, @@ -17996,8 +18146,7 @@ export function messagesFeature(ctx) { title: t('msgReact'), onClick: (e) => { e.stopPropagation(); sendReaction(room, chId, m, emoji); }, }, reactNode(emoji), n > 1 ? ' ' + n : ''))) - : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null, onHold: () => openZapSettings(m.author, m.rumor.id) }))), - msgZapBtn(m.author, m.rumor.id))) + : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null, onHold: () => openZapSettings(m.author, m.rumor.id) }))))) ); }); } @@ -18617,8 +18766,7 @@ export function messagesFeature(ctx) { ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id; render(); }), - }, dmQuote(m), ...(m.rumor.kind === 15 ? [] : noteBody(m.rumor.content, 0, emojiTagMap(m.rumor.tags))), ...attachmentNodes(m.rumor, m.wn), dmChips(m)), - m.mine ? null : msgZapBtn(m.rumor.pubkey, m.rumor.id)), + }, dmQuote(m), ...(m.rumor.kind === 15 ? [] : noteBody(m.rumor.content, 0, emojiTagMap(m.rumor.tags))), ...attachmentNodes(m.rumor, m.wn), dmChips(m))), h('div', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000))))) : [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgNoDmsYet'))])), dmReplyBar(), @@ -19216,16 +19364,35 @@ export function messagesFeature(ctx) { // The header magnifier: search anyone on nostr, results open profiles. userSearchAvailable() { return true; }, // the desktop header's search field: typing there IS the search page's query - userSearchSubmit(q) { if (String(q || '').trim()) { openTextSearch(q); render(); } }, + userSearchSubmit(q) { submitUserSearch(q); }, + userSearchScopeChip() { return scopeChip(); }, + userSearchScoped() { return !!searchScope(); }, + userSearchUnscope() { unscopeSearch(); }, + // before the header field's first keystroke takes the profile away + userSearchHoldScope() { + if (!ui.profilePk) return; + if (!ui.userSearch) { ui.userSearch = { q: '', rows: null }; warmSearch(); } + ui.userSearch.scope = ui.searchScopeOff === ui.profilePk ? null : ui.profilePk; + }, userSearchQuery(q) { - if (!ui.userSearch) { if (!isVisitor()) ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = { q: '', rows: null }; warmSearch(); } - ui.userSearch.q = q; userSearcher.update(q); render(); + if (!ui.userSearch) { ui.userSearch = { q: '', rows: null }; warmSearch(); } + // typed from a profile: its person is what the field searches, until taken out + if (ui.profilePk) ui.userSearch.scope = ui.searchScopeOff === ui.profilePk ? null : ui.profilePk; + // Typing brings the results forward every time, not only the first: + // the search is kept (Back from a profile lands on it), so a second + // search typed from a profile opened from the first one updated a + // page hidden under that profile ("the search box stops working", + // Adam 2026-11-14). Back still returns to the profile. + if (!isVisitor()) ui.chatOpen = false; + ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; + ui.userSearch.q = q; userSearcher.update(q); guessScope(q); render(); return true; }, - openUserSearch() { + userSearchScopePk() { return searchScope(); }, + openUserSearch(scope = searchScope()) { if (!isVisitor()) ui.chatOpen = false; // a visitor's feed stays underneath, for Back ui.profilePk = null; - ui.userSearch = { q: '', rows: null }; + ui.userSearch = { q: '', rows: null, scope }; warmSearch(); // the field is about to be typed into — open the pipes return true; }, @@ -19351,8 +19518,9 @@ export function messagesFeature(ctx) { visitorSignIn() { toFrontDoor(); return true; }, visitorSearch() { rememberReturn(); + const scope = searchScope(); // from a profile: search inside its person's posts ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.profOverThread = false; - ui.userSearch = { q: '', rows: null }; + ui.userSearch = { q: '', rows: null, scope }; warmSearch(); render(); return true; diff --git a/src/features/names.js b/src/features/names.js index 3f23a0c..e1f23ce 100644 --- a/src/features/names.js +++ b/src/features/names.js @@ -683,6 +683,10 @@ export function namesFeature(ctx) { onClick: () => copy(addr), html: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>', }))), + // ask for a sum: the point of sale's amount pad and invoice, simplified + hook('posAvailable') ? h('button', { class: 'btn-block', id: 'recv-amount', onClick: () => hook('openAmountRequest') }, t('recvAmount')) : null, + // one balance: an on-chain address for the payers who need one + ctx.receiveOnchainBtn ? ctx.receiveOnchainBtn() : null, moreSection()); } diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js index 4a811fc..5ef6fb8 100644 --- a/src/features/nostrlogin.js +++ b/src/features/nostrlogin.js @@ -16,7 +16,7 @@ import { qrSvg } from '../qr.js'; import { extensionSigner, bunkerSigner, keySigner, parseNostrSecret, walletForSigner, publishWalletBackup, fetchWalletBackup, nostrConnect, nostrConnectPending, resumeBunker, - amberAvailable, amberSigner, amberPending, amberDeliver, amberCancel, amberOpen, onAmberChange } from '../nostr-login.js'; + amberSigner, amberPending, amberDeliver, amberCancel, amberOpen, onAmberChange } from '../nostr-login.js'; // The nostr ostrich, in the brand's monochrome. const OSTRICH = '<svg width="23" height="23" style="display:block" viewBox="0 0 2000 2000" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="ng" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#B84FE8"/><stop offset="100%" stop-color="#6D28D9"/></linearGradient></defs><circle cx="1000" cy="1000" r="1000" fill="url(#ng)"/><g transform="translate(1000 1000) scale(0.82) translate(-1000 -1000)"><path d="M1574.29 770.408C1532.04 840.612 1445.92 888.367 1437.96 892.449C1421.84 901.02 1415.92 913.469 1416.94 932.041C1417.96 950.612 1413.47 1042.65 1357.35 1083.27C1328.57 1104.08 1212.45 1131.02 1159.18 1140C1131.84 1144.69 1125.51 1153.06 1110.41 1162.04C1090 1174.69 1017.55 1275.1 1005.31 1297.35C1006.94 1297.14 1233.67 1226.73 1243.88 1225.1C1270.82 1221.02 1291.22 1228.78 1304.49 1248.37C1317.14 1267.14 1329.59 1286.12 1342.04 1305.1C1346.53 1311.84 1350.82 1318.78 1355.1 1325.71L1359.59 1332.86C1361.22 1335.51 1363.47 1338.57 1364.49 1342.65C1365.31 1345.51 1367.14 1355.1 1361.63 1360.82C1356.53 1366.12 1347.76 1366.12 1343.06 1364.9C1338.57 1363.67 1331.84 1361.02 1326.33 1356.53L1318.78 1350.2C1312.86 1345.1 1301.63 1342.65 1292.86 1343.06C1282.65 1343.47 1269.18 1340.2 1262.65 1336.12C1250 1327.96 1246.73 1307.55 1246.73 1307.35C1245.1 1300.61 1240.2 1298.78 1235.71 1298.78C1227.55 1298.57 1221.22 1301.02 1214.69 1302.86C1184.9 1311.84 1155.31 1321.02 1125.51 1330.41L1082.86 1343.67C1061.84 1350.2 1040.82 1356.73 1020 1363.67C1014.29 1365.51 1008.78 1368.37 1002.86 1371.43C1000.41 1372.65 997.959 1373.88 995.51 1375.1C993.061 1376.33 990.408 1377.76 987.959 1379.18C982.449 1382.24 976.531 1385.51 970 1387.35C948.776 1393.67 930.204 1384.49 921.429 1363.27C915.714 1349.59 920.816 1322.45 923.878 1314.49C943.061 1264.69 1005.51 1170.82 1005.51 1170.2C1004.49 1169.8 936.327 1197.14 925.102 1205.71C894.286 1229.18 822.041 1284.69 821.02 1290C816.327 1314.69 801.02 1333.27 777.551 1342.45C760.612 1348.98 750.408 1362.45 740.408 1375.51C740.408 1375.51 559.388 1624.9 547.143 1638.37C543.469 1642.45 509.592 1677.96 500.612 1694.49C498.571 1698.57 490.816 1714.9 488.776 1718.98C487.143 1722.24 483.469 1731.02 469.592 1730.41C455.714 1729.8 455.306 1710.41 454.694 1702.04C453.265 1681.43 457.755 1661.22 468.571 1640C469.592 1637.96 481.837 1619.39 477.347 1604.49C473.265 1591.43 469.388 1571.22 475.51 1561.02C485.102 1544.9 502.041 1544.29 524.694 1540.61C540.408 1537.96 551.837 1530.2 562.857 1514.08C586.122 1480.2 673.674 1355.92 693.469 1327.14C698.776 1319.59 702.857 1309.8 704.694 1300.2C710.408 1271.22 727.959 1251.02 758.571 1238.57C765.102 1235.92 886.939 1134.08 886.939 1121.02C886.939 1111.63 873.674 1106.53 863.469 1103.67C862.041 1103.27 785.51 1083.47 750.612 1067.55C731.633 1058.98 717.347 1051.43 700.408 1039.18C677.347 1022.24 631.225 1030.41 624.49 1031.43C591.837 1036.12 567.551 1050.82 540 1069.39C535.102 1072.86 510 1081.84 497.347 1074.69C472.653 1060.61 418.367 1035.31 398.367 1004.9C389.184 990.816 390.408 967.959 396.939 942.653C417.959 883.878 448.98 857.551 506.327 841.633C547.143 827.551 629.388 824.49 668.98 821.429C671.633 820.612 759.388 818.571 821.02 786.939C862.041 765.918 983.878 684.898 1159.18 690.408C1230 692.653 1363.88 761.837 1415.51 763.878C1468.16 766.122 1494.49 760.204 1524.9 728.776C1533.47 719.796 1570 641.02 1535.51 597.959C1522.65 582.041 1509.39 567.755 1494.08 554.694C1473.47 537.143 1452.04 520.408 1433.47 500.612C1392.45 457.143 1379.8 397.755 1399.18 351.429C1411.63 318.98 1437.76 304.898 1475.51 312.245C1502.04 317.347 1521.43 341.225 1540.41 353.878C1551.02 361.02 1568.78 365.102 1580.41 367.959C1595.1 371.429 1606.12 382.653 1605.51 390.204C1604.9 397.755 1585.51 404.286 1566.94 402.857C1544.9 401.429 1507.14 401.225 1484.49 408.776C1469.39 414.286 1462.65 431.02 1467.14 447.551C1470.82 461.02 1499.59 485.102 1510.41 494.082C1532.04 511.837 1555.1 527.959 1573.06 550.204C1593.27 575.51 1603.88 604.286 1607.14 636.122C1612.04 684.898 1599.18 728.776 1574.29 770.408Z" fill="#fff"/></g></svg>'; @@ -158,6 +158,17 @@ export function nostrLoginFeature(ctx) { // and the payment name too — the Receive pane should open with its QR const nameHintP = ctx.hook('namesLookupByPk', signer.pubkey); const res = await walletForSigner(signer); + // A way back in (added from Settings): the key holds a copy of an + // account's seed, and opens that account as ITSELF — its own name, + // profile and identity. Nothing about the key is adopted or kept. + if (res.mode === 'restored' && res.recovery) { + try { if (signer.kind === 'bunker' && signer.close) signer.close(); } catch {} + ctx.onbNostrLogin(true); + ui.navAnimSkip = true; + await ctx.openMnemonic(res.mnemonic, res.passphrase || '', { spendingHint: !!res.spending, spendingOnly: !!res.spendingOnly }); + busy(false); + return; + } if (res.mode === 'new') { // No wallet on this identity yet — make one and walk straight in. // The interstitial that used to ask first read as an error screen to @@ -472,12 +483,11 @@ export function nostrLoginFeature(ctx) { onClick: () => run(() => extensionSigner()) }, t('nlExtension')) : null, nostrConnectSection(run), - // On Android, the signer app straight through an intent (NIP-55): works - // with Amber offline, no bunker, no relay — one trip through the app - // per signature. - amberAvailable() - ? h('button', { class: 'btn-block', disabled: ui.nostrLoginBusy, onClick: () => run(() => amberSigner()) }, t('nlAmber')) - : null, + // No separate Android-intent (NIP-55) door any more (Adam, 2026-11-15): + // it opened the same Amber as Connect a signer app, but a login made + // that way couldn't read messages. Accounts that already came in by + // intent keep working (resumeLogin), and their pending requests still + // show here. amberWaitCard(), // These are alternatives, not steps: without the divider the field under // the button reads as something you also have to fill in. @@ -681,6 +691,124 @@ export function nostrLoginFeature(ctx) { resumeLogin().then((s) => { if (s) render(); }).catch(() => {}); } + // ---- ways back in ------------------------------------------------------ + // Settings → Wallet: the sign-in methods that can open THIS account on + // another device, added after the fact — a passkey, Google, a nostr key — + // next to the recovery phrase. Each one gets a copy of the seed encrypted + // to its own key (kind 30078, marked `recovery`), so signing in with it + // anywhere opens this account as itself. Unlike linking a login, the + // account's identity doesn't change. + async function addRecovery(makeSigner, via, label = '') { + ui.waysBackError = ''; ui.waysBackBusy = via; ui.nostrLoginBusy = true; render(); + let signer = null; + try { + if (!wallet.mnemonic) throw new Error(t('nlNeedSeed')); + signer = await makeSigner(); + const st = load(); + if (st.pubkey && st.pubkey === signer.pubkey) throw new Error(t('waysBackIsLogin')); + // a key that already opens a DIFFERENT wallet keeps it: never overwrite + const existing = await fetchWalletBackup(signer); + if (existing && existing.mnemonic + && (existing.mnemonic !== wallet.mnemonic || (existing.passphrase || '') !== (wallet.passphrase || ''))) { + throw new Error(t('waysBackTaken')); + } + await publishWalletBackup(signer, { + mnemonic: wallet.mnemonic, passphrase: wallet.passphrase || '', + spending: true, recovery: true, spendingOnly: !!ctx.spendingOnlyAccount(), + }); + ctx.addRecoveryMethod({ via, id: signer.pubkey, label }); + ui.waysBackNostr = false; + toast(t('waysBackAdded')); + } catch (e) { + const msg = String((e && e.message) || e || ''); + // a dismissed passkey or Google dialog is a plain cancel + if (!/NotAllowed|abort/i.test(String((e && e.name) || '') + ' ' + msg)) ui.waysBackError = msg; + } finally { + try { if (signer && signer.kind === 'bunker' && signer.close) signer.close(); } catch {} + ui.waysBackBusy = null; ui.nostrLoginBusy = false; + render(); + } + } + async function passkeyRecovery() { + const pass = await import('../passkey.js'); + const name = ctx.hook('namesAddress') || 'coinos'; + await addRecovery(async () => keySigner(await pass.passkeyCreate({ name, displayName: name })), 'passkey'); + } + async function googleRecovery() { + // opened in the click itself (user activation) — see googleLogin + const popup = window.open('about:blank', 'OAuth', 'width=600,height=600'); + ui.waysBackError = ''; ui.waysBackBusy = 'google'; render(); + try { + const pome = await import('../pomegranate.js'); + const { uri, email } = await pome.loginWithGoogle(popup, {}); + await addRecovery(() => bunkerSigner(uri, { onAuth: (url) => { ui.nostrLoginAuthUrl = url; render(); } }), 'google', email || ''); + } catch (e) { + try { popup && popup.close(); } catch {} + ui.waysBackError = (e && e.message) || String(e); + ui.waysBackBusy = null; + render(); + } + } + // pen over a sheet of paper, in the line style of the passkey mark + const PAPER_MARK = '<svg width="19" height="19" style="display:block" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><path d="M13 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"/><path d="M8 9h4"/><path d="M8 13h3"/><path d="M8 17h6"/><path d="M18.4 2.6a2 2 0 0 1 2.8 2.8L14 12.6l-3.6.9.9-3.6z"/></svg>'; + const fmtDay = (ms) => { try { return new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }); } catch { return ''; } }; + function waysBackCard() { + if (wallet.watchOnly || !wallet.mnemonic) return null; + const methods = ctx.recoveryMethods() || []; + const st = load(); + const busyVia = ui.waysBackBusy; + const hasPasskey = typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials; + const done = (mark, title, detail, key) => h('div', { class: 'row gap6 ways-back-row', 'data-way': key, style: 'align-items:center;padding:8px 2px' }, + h('span', { style: 'display:flex;flex-shrink:0;width:23px;justify-content:center', html: mark }), + h('span', { class: 'col', style: 'flex:1;gap:1px;min-width:0' }, + h('span', { style: 'font-weight:600' }, title), + detail ? h('span', { class: 'small muted break' }, detail) : null), + h('span', { class: 'ways-back-check', 'aria-label': t('waysBackOn') }, '✓')); + const add = (mark, label, via, onClick) => h('button', { + class: 'btn-block ways-back-add', 'data-way': via, disabled: !!busyVia, onClick, + }, markedLabel(mark, label, busyVia === via)); + const rows = []; + // the sign-in this account came through is a way back in already + if (st.pubkey) { + const via = st.via || 'nostr'; + rows.push(done(via === 'google' ? GOOGLE_MARK : via === 'passkey' ? PASSKEY_MARK : OSTRICH, + t('waysBackLogin', { via: via === 'google' ? 'Google' : via === 'passkey' ? t('doorPasskey') : 'Nostr' }), + via === 'google' || via === 'passkey' ? '' : (npubOf(st.pubkey) || '').slice(0, 20) + '…', 'login')); + } + for (const m of methods) { + if (m.via === 'passkey') rows.push(done(PASSKEY_MARK, t('doorPasskey'), t('waysBackAddedOn', { date: fmtDay(m.at) }), 'passkey')); + else if (m.via === 'google') rows.push(done(GOOGLE_MARK, 'Google', m.label || t('waysBackAddedOn', { date: fmtDay(m.at) }), 'google')); + else rows.push(done(OSTRICH, 'Nostr', (npubOf(m.id) || '').slice(0, 20) + '…', 'nostr')); + } + const seen = ctx.seedSeen(); + const have = (via) => methods.some((m) => m.via === via) || (via !== 'nostr' && st.via === via); + const adds = [ + hasPasskey && !have('passkey') ? add(PASSKEY_MARK, t('waysBackAddPasskey'), 'passkey', () => passkeyRecovery()) : null, + !have('google') ? add(GOOGLE_MARK, t('waysBackAddGoogle'), 'google', () => googleRecovery()) : null, + ui.waysBackNostr + ? h('div', { class: 'col', style: 'gap:8px' }, + h('div', { class: 'row between' }, + h('strong', { class: 'small' }, t('waysBackAddNostr')), + h('span', { class: 'linklike small', onClick: () => { ui.waysBackNostr = false; ui.waysBackError = ''; render(); } }, t('cancel'))), + signerButtons((make) => addRecovery(make, 'nostr'), { nostrOnly: true })) + : add(OSTRICH, t('waysBackAddNostr'), 'nostr', () => { ui.waysBackNostr = true; ui.waysBackError = ''; ui.nostrLoginError = ''; render(); }), + // the recovery phrase, as one more button (Adam, 2026-11-15): it opens + // the masked words below, ticked once they've been seen + h('button', { class: 'btn-block ways-back-add', 'data-way': 'phrase', disabled: !!busyVia, onClick: () => ctx.showRecoveryPhrase() }, + h('span', { style: 'display:flex;align-items:center;justify-content:center;gap:8px' }, + h('span', { style: 'display:flex;flex-shrink:0', html: PAPER_MARK }), + t('waysBackPaper'), + seen ? h('span', { class: 'ways-back-check', 'aria-label': t('waysBackOn') }, '✓') : null)), + ].filter(Boolean); + return h('div', { class: 'card col ways-back', style: 'gap:6px' }, + h('h3', {}, t('waysBackTitle')), + h('p', { class: 'small muted', style: 'margin:0 0 4px' }, t('waysBackDesc')), + h('div', { class: 'col', style: 'gap:0' }, ...rows), + adds.length ? h('div', { class: 'col', style: 'gap:8px;margin-top:6px' }, ...adds) : null, + ui.waysBackError ? h('div', { class: 'notice err' }, ui.waysBackError) : null, + h('p', { class: 'small faint', style: 'margin:4px 0 0' }, t('waysBackNote'))); + } + function settingsCard() { if (wallet.watchOnly || !wallet.mnemonic) return null; const st = load(); @@ -879,5 +1007,6 @@ export function nostrLoginFeature(ctx) { ].filter(Boolean); }, nostrSettingsCards() { return [settingsCard()]; }, + waysBackCard() { return waysBackCard(); }, }; } diff --git a/src/features/nwc.js b/src/features/nwc.js index 9768740..741b0a4 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -627,12 +627,23 @@ export function nwcFeature(ctx) { if (!o || !pend.length) return; const moves = hook('arkMovements') || []; const keep = []; + // The pending list rides the synced wallet state, and every device holds + // the offer key: phone and laptop each published the same receipt a + // minute apart (Helen's 88-sat zap, Adam 2026-11-14). A receipt already + // out — sent from here, or found on the relays — isn't sent again. + const done = new Set(st.zapDone || []); + const sent = []; for (const z of pend) { if (Date.now() - z.ts > 86400_000) continue; // expired unpaid + if (done.has(z.invoice)) continue; const paid = moves.find((m) => m.type === 'ln-receive' && m.status === 'complete' && m.invoice === z.invoice); if (!paid) { keep.push(z); continue; } try { const zapReq = JSON.parse(z.zap); + const offerPk = getPublicKey(hex.decode(o.sk)); + const to = (zapReq.tags.find((t2) => t2[0] === 'p') || [])[1]; + const out = await query(NWC_RELAYS, { kinds: [9735], authors: [offerPk], ...(to ? { '#p': [to] } : {}), since: Math.floor(z.ts / 1000) - 120 }, 2500).catch(() => []); + if ((out || []).some((r) => (r.tags || []).some((t2) => t2[0] === 'bolt11' && t2[1] === z.invoice))) { sent.push(z.invoice); continue; } const tags = [ ...zapReq.tags.filter((t2) => t2[0] === 'p' || t2[0] === 'e'), ['P', zapReq.pubkey], @@ -644,10 +655,12 @@ export function nwcFeature(ctx) { const relayTag = zapReq.tags.find((t2) => t2[0] === 'relays'); const relays = [...new Set([...(relayTag ? relayTag.slice(1) : []), ...NWC_RELAYS])].slice(0, 8); await publish(relays, receipt); + sent.push(z.invoice); } catch (e) { console.warn('nwc: zap receipt failed', e.message); } } const st2 = load(); st2.zapPending = keep; + st2.zapDone = [...new Set([...(st2.zapDone || []), ...sent])].slice(-100); save(st2); } @@ -1106,6 +1119,8 @@ export function nwcFeature(ctx) { id: 'nwc', nwcOfferPubkey() { return (hook('arkReady') && !wallet.watchOnly) ? offerKeys().pk : null; }, nwcOfferString() { return hook('arkReady') && !wallet.watchOnly ? offerString() : null; }, + // tests: the receipt pass on demand (normally the watchdog's and the reconcile's) + nwcPublishZapReceipts() { return publishZapReceipts(); }, init() { listen(); startWatchdog(); refreshRegistration(); reconcileBg(); ensureBackground(false); serveWake(); }, stop() { stop(); if (watchdog) { clearInterval(watchdog); watchdog = null; } }, nostrSettingsCards() { return [nwcCard()]; }, diff --git a/src/features/pos.js b/src/features/pos.js index 3727862..eb4b0e9 100644 --- a/src/features/pos.js +++ b/src/features/pos.js @@ -44,8 +44,11 @@ export function posFeature(ctx) { // ---- flow ---------------------------------------------------------------- // ui.pos: { step: 'amount'|'tip'|'invoice'|'paid', amount, note, tipMode, tipCustom, sale, error, busy } - function open() { - ui.pos = { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '' }; + // `request`: Receive → Amount (Adam, 2026-11-15) — the same amount pad + // and invoice for asking someone for a sum, without the till around it: + // no tip prompt, no tip settings or day's sales, and Back is Receive. + function open(opts = {}) { + ui.pos = { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '', request: !!opts.request }; render(); } // Digits on screen, into the same field a keyboard or a paste would fill. @@ -90,7 +93,7 @@ export function posFeature(ctx) { if (!bill) { p.error = t('posEnterAmount'); render(); return; } p.error = ''; if (!hook('arkReady')) { p.error = t('posNeedsSpending'); render(); return; } - if (st().askTip) { p.step = 'tip'; p.tipMode = null; p.tipCustom = ''; render(); return; } + if (st().askTip && !p.request) { p.step = 'tip'; p.tipMode = null; p.tipCustom = ''; render(); return; } makeSale(bill, 0, 0); } function tipSat() { @@ -107,6 +110,7 @@ export function posFeature(ctx) { id: 's' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), at: Date.now(), billSat: bill, tipSat: tip, tipPct, note: (p.note || '').trim().slice(0, 80), status: 'open', fiat: rateNow() ? { code: getCurrency(), rate: rateNow() } : null, + ...(p.request ? { request: true } : {}), }; try { const memo = (sale.note ? sale.note + ' · ' : '') + t('posMemo', { bill: fmtAmount(bill) + ' ' + unitLabel(), tip: tip ? fmtAmount(tip) + ' ' + unitLabel() : '0' }); @@ -145,7 +149,7 @@ export function posFeature(ctx) { function newSale() { const p = ui.pos; if (p.sale && p.sale.status === 'open') voidSale(p.sale); - Object.assign(p, { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '' }); + Object.assign(p, { step: 'amount', amount: '', note: '', tipMode: null, tipCustom: '', sale: null, error: '', request: p.request }); render(); } @@ -194,7 +198,7 @@ export function posFeature(ctx) { return h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(false), h('div', { class: 'card col', style: 'gap:12px' }, - h('h3', { style: 'margin:0' }, t('posTitle')), + h('h3', { style: 'margin:0' }, t(p.request ? 'recvAmountTitle' : 'posTitle')), h('div', { class: 'input-group' }, h('input', { type: 'text', inputmode: 'decimal', class: 'pos-amount', placeholder: '0', value: p.amount, @@ -204,12 +208,12 @@ export function posFeature(ctx) { unitTag()), getUnit() !== 'fiat' && billSat() && fiatLine(billSat()) ? h('div', { class: 'small muted', style: 'text-align:right' }, fiatLine(billSat())) : null, numpad(() => p.amount, (v) => { p.amount = v; }), - h('input', { type: 'text', placeholder: t('posNoteHint'), value: p.note, maxlength: '80', onInput: (e) => { p.note = e.target.value; } }), + h('input', { type: 'text', placeholder: t(p.request ? 'recvAmountNote' : 'posNoteHint'), value: p.note, maxlength: '80', onInput: (e) => { p.note = e.target.value; } }), p.error ? h('div', { class: 'notice error small' }, p.error) : null, - h('button', { class: 'btn-primary btn-block', disabled: !!p.busy, onClick: charge }, p.busy ? h('span', { class: 'spinner sm' }) : t('posCharge')), + h('button', { class: 'btn-primary btn-block', id: 'pos-charge', disabled: !!p.busy, onClick: charge }, p.busy ? h('span', { class: 'spinner sm' }) : t(p.request ? 'recvAmountGo' : 'posCharge')), p.busy ? h('div', { class: 'small muted', style: 'text-align:center' }, t('posMakingInvoice')) : null), - tipSettingsCard(s), - salesCard(s), + p.request ? null : tipSettingsCard(s), + p.request ? null : salesCard(s), back()); } function tipSettingsCard(s) { @@ -231,7 +235,7 @@ export function posFeature(ctx) { } function salesCard(s) { adoptPaid(s); - const sales = [...s.sales].reverse(); + const sales = s.sales.filter((x) => !x.request).reverse(); // Receive → Amount isn't a sale if (!sales.length) return null; const today = dayKey(Date.now()); const paidToday = sales.filter((x) => x.status === 'paid' && dayKey(x.paidAt || x.at) === today); @@ -310,8 +314,8 @@ export function posFeature(ctx) { h('h3', { style: 'margin:0' }, t('posPaid')), money(sale.billSat + sale.tipSat, sale.fiat && sale.fiat.rate), sale.tipSat ? h('div', { class: 'small muted' }, t('posBreakdown', { bill: fmtAmount(sale.billSat), tip: fmtAmount(sale.tipSat), u: unitLabel() })) : null, - h('button', { class: 'btn-primary btn-block', onClick: newSale }, t('posNewSale'))), - back()); + p.request ? null : h('button', { class: 'btn-primary btn-block', onClick: newSale }, t('posNewSale'))), + p.request ? h('button', { class: 'btn-primary btn-block', onClick: close }, t('recvAmountDone')) : back()); } function posScreen() { const p = ui.pos; @@ -346,6 +350,8 @@ export function posFeature(ctx) { h('p', { class: 'small faint', style: 'margin:0' }, t('posLinkHint', { url })))]; }, openPos: open, + openAmountRequest: () => open({ request: true }), + posAvailable: () => !!hook('arkReady'), // The history detail of a till payment says what was the bill and what the tip. arkMoveDetailExtra(m, row) { const sale = saleOfMovement(m); diff --git a/src/features/withdraw-links.js b/src/features/withdraw-links.js index a63d180..38b2d8c 100644 --- a/src/features/withdraw-links.js +++ b/src/features/withdraw-links.js @@ -114,6 +114,18 @@ export function withdrawLinks(ctx) { } finally { s.taking = null; render(); load(); } } + // What became of the latest claim someone made (reclaims aside): on its + // way, or turned back with the sats still here. "I made a transaction for + // 1,000,000 sats using the Withdraw link method, but they never arrived" + // (a user, 2026-11-14): the claim had failed and the link said only + // "1,000,000 sats left". + function lastClaim(l) { + const c = (l.claims || []).filter((x) => !x.reclaim).at(-1); + if (!c || c.status === 'paid') return null; + if (c.status === 'paying') return { kind: 'paying', c }; + return l.status === 'open' && l.remainingSat >= c.sat ? { kind: 'failed', c } : null; + } + function linkCard(l) { const s = st(); const lnurl = lnurlOf(l); @@ -130,6 +142,15 @@ export function withdrawLinks(ctx) { live ? h('div', { class: 'addr-box break mono', style: 'width:100%;font-size:11px' }, lnurl) : h('div', { class: 'notice small' }, l.status === 'closed' ? t('wlClosed') : t('wlUsedUp')), live ? h('div', { class: 'row gap6 wrap', style: 'width:100%' }, copyBtn(lnurl, t('wlCopy'))) : null, live ? h('div', { class: 'small faint', style: 'text-align:center' }, t('wlBearer')) : null, + (() => { + const lc = lastClaim(l); + if (!lc) return null; + // while it's being paid, look again every 10 s so the answer shows up here + if (lc.kind === 'paying' && !s.poll) s.poll = setTimeout(() => { st().poll = null; if (ui.giftMode === 'lnurl') load(); }, 10_000); + return lc.kind === 'paying' + ? h('div', { class: 'notice info small wl-claim-paying', style: 'width:100%' }, t(lc.c.tries > 1 ? 'wlClaimRetrying' : 'wlClaimPaying', { amount: amt(lc.c.sat) })) + : h('div', { class: 'notice err small wl-claim-failed', style: 'width:100%' }, t('wlClaimFailed', { amount: amt(lc.c.sat) })); + })(), s.error && h('div', { class: 'notice err', style: 'width:100%' }, s.error), live || (l.status === 'open' && l.remainingSat > 0) ? (s.taking === l.id @@ -171,7 +192,9 @@ export function withdrawLinks(ctx) { ...s.list.map((l) => h('button', { class: 'row between wl-row', style: 'text-align:left', onClick: () => { s.open = l.id; s.made = null; s.error = ''; render(); } }, h('span', { class: 'small' }, amt(l.sat), l.uses > 1 ? ` × ${l.uses}` : '', l.note ? h('span', { class: 'faint' }, ' · ' + l.note) : null), h('span', { class: 'small faint' }, - l.status === 'closed' ? t('wlClosedTag') : l.remainingSat < 1 || l.used >= l.uses ? t('wlUsedUpTag') : t('wlLeft', { amount: amt(l.remainingSat) }))))); + l.status === 'closed' ? t('wlClosedTag') : l.remainingSat < 1 || l.used >= l.uses ? t('wlUsedUpTag') + : lastClaim(l)?.kind === 'failed' ? t('wlClaimFailedTag', { amount: amt(l.remainingSat) }) + : t('wlLeft', { amount: amt(l.remainingSat) }))))); } function view() { diff --git a/src/features/zaps.js b/src/features/zaps.js index 8e29409..49e457f 100644 --- a/src/features/zaps.js +++ b/src/features/zaps.js @@ -12,6 +12,7 @@ // land here directly. import { t } from '../i18n.js'; +import { momentToggle, mediaClock } from '../media-timeline.js'; import { npubOf } from '../nostr.js'; import { parseZapTarget, zapTargetFromProfile, fetchPayParams, buildZapRequest, requestInvoice, parseLnurlAuth, lnurlAuthKey, lnurlAuthLogin, submitWithdraw } from '../lnurl.js'; import { HDKey } from '@scure/bip32'; @@ -213,7 +214,8 @@ export function zapsFeature(ctx) { const profile = await wallet.nostrProfile(target.pk); const lnTarget = zapTargetFromProfile(profile, target.pk); if (!lnTarget) throw new Error(t('lnZapNoAddress')); - const t2 = { ...lnTarget, eventId: target.eventId || null, moment: target.moment }; + // a one-tap zap has no sheet to tick: never tied to a moment + const t2 = { ...lnTarget, eventId: target.eventId || null, moment: null }; const p = await fetchPayParams(t2.url); const msat = sats * 1000; if (msat < p.minSendable || msat > p.maxSendable) { @@ -286,7 +288,7 @@ export function zapsFeature(ctx) { const sign = await zapSigner(); zapRequest = await buildZapRequest({ amountMsat: msat, relays: wallet.nostrRelays(), lnurlBech32: z.target.lnurlBech32, - recipientPk: z.target.pk, eventId: z.target.eventId || null, moment: z.target.moment, comment: z.comment, + recipientPk: z.target.pk, eventId: z.target.eventId || null, moment: z.momentOn ? z.target.moment : null, comment: z.comment, signFn: sign, }); } @@ -517,6 +519,8 @@ export function zapsFeature(ctx) { maxlength: p.allowsNostr ? '280' : String(p.commentAllowed || 280), onInput: (e) => { z.comment = e.target.value; } }) : null, + p.allowsNostr && z.target && z.target.moment ? h('div', { class: 'row' }, momentToggle(h, z.target.moment, !!z.momentOn, (on) => { z.momentOn = on; render(); }, + t('mediaTieTo', { time: mediaClock(z.target.moment.seconds) }))) : null, z.social ? h('div', { class: 'small faint' }, p.allowsNostr ? t('lnZapHintNostr') : t('lnZapHintPlain')) : null), z.error ? h('div', { class: 'notice err' }, z.error) : null, h('div', { class: 'row gap6' }, |
