From dd4750b09f891cbd18c5c3b24d0498f96d250f5c Mon Sep 17 00:00:00 2001 From: rodrigopavezi Date: Tue, 17 Nov 2026 03:23:47 -0300 Subject: [PATCH 1/2] feat: add the varandinha screens, navigation and terms Two shared screens on hosted nodes: Varandinha (own balcony with the consent sheet, queued acts saved in one garden.play, Quem regou, and a neighbour's balcony with Regar under the node's own help rule) and Varandas da rua (the seeder's street list, kept to the viewer's own follow.list). Entries from the Diario, Ajustes and a member's profile after a peek confirms the garden flag. Queued acts make the top bar arrow, Android Back and Escape ask before leaving; nothing is written on leave. The Vitrine answers on the demo clock. Terms and Privacy gain the Varandinha paragraph, and docs/design.md the LGPD design hypothesis. --- apps/app/App.js | 50 +- apps/app/src/garden.js | 33 +- apps/app/src/gardenClock.js | 21 + apps/app/src/legal.js | 10 +- apps/app/src/nav.js | 8 +- apps/app/src/screens/Ajustes.js | 7 +- apps/app/src/screens/Diario.js | 16 +- apps/app/src/screens/Membro.js | 33 +- apps/app/src/screens/Varandinha.js | 727 +++++++++++++++++++++++ apps/app/src/screens/VarandinhaRua.js | 189 ++++++ apps/app/src/tabs.js | 2 +- apps/app/src/vitrine/request.js | 9 +- apps/app/test/composePolish.test.js | 1 + apps/app/test/garden.test.js | 55 ++ apps/app/test/legal.test.js | 32 +- apps/app/test/nav.test.js | 16 +- apps/app/test/tabBar.test.js | 7 + apps/app/test/vitrine.test.js | 10 + apps/app/test/vitrineGuard.test.js | 7 +- apps/site/public/privacidade/index.html | 7 +- apps/site/public/termos/index.html | 7 +- apps/site/test/legal.test.js | 4 +- docs/app.md | 1 + docs/changelog/feat-varandinha-app.md | 4 + docs/design-review.md | 1 + docs/design.md | 2 + docs/verification/feat-varandinha-app.md | 86 +++ packages/core/lib/terms.js | 2 +- packages/core/test/terms.test.js | 2 +- 29 files changed, 1305 insertions(+), 44 deletions(-) create mode 100644 apps/app/src/gardenClock.js create mode 100644 apps/app/src/screens/Varandinha.js create mode 100644 apps/app/src/screens/VarandinhaRua.js create mode 100644 docs/changelog/feat-varandinha-app.md create mode 100644 docs/verification/feat-varandinha-app.md diff --git a/apps/app/App.js b/apps/app/App.js index 11c581ab3..6668f547a 100644 --- a/apps/app/App.js +++ b/apps/app/App.js @@ -200,6 +200,8 @@ import { refreshMomentSeen } from './src/momentSeenStore' import SalvosScreen from './src/screens/Salvos' import EventosScreen from './src/screens/Eventos' import VisitasScreen from './src/screens/Visitas' +import VarandinhaScreen from './src/screens/Varandinha' +import VarandinhaRuaScreen from './src/screens/VarandinhaRua' import MomentosScreen from './src/screens/Momentos' import FeiraScreen from './src/screens/Feira' import AnuncioScreen from './src/screens/Anuncio' @@ -256,6 +258,8 @@ const Assunto = memo(AssuntoScreen) const Recados = memo(RecadosScreen) const Eventos = memo(EventosScreen) const Visitas = memo(VisitasScreen) +const Varandinha = memo(VarandinhaScreen) +const VarandinhaRua = memo(VarandinhaRuaScreen) const Mensagens = memo(MensagensScreen) const Mensagem = memo(MensagemScreen) const Anuncio = memo(AnuncioScreen) @@ -2253,6 +2257,11 @@ function Member () { pushScreen({ screen: 'recados', key: key.toLowerCase(), params: {} }) }, [pushScreen]) const openVisitas = useCallback(() => pushScreen({ screen: 'visitas' }), [pushScreen]) + const openVarandinha = useCallback((key) => { + if (typeof key !== 'string') return + pushScreen({ screen: 'varandinha', key: key.toLowerCase(), params: {} }) + }, [pushScreen]) + const openVarandinhaRua = useCallback(() => pushScreen({ screen: 'varandinha-rua' }), [pushScreen]) const openEventos = useCallback((key) => { if (typeof key !== 'string') return pushScreen({ screen: 'eventos', key: key.toLowerCase(), params: {} }) @@ -2318,11 +2327,13 @@ function Member () { const helpOpen = useHelpOpen() const helpOpenRef = useRef(helpOpen) helpOpenRef.current = helpOpen - const backGuardRef = useRef(null) + // Every registered guard checks at call time that its own screen is on top, + // so at most one of them answers a back press. + const backGuardsRef = useRef(new Set()) const registerBackGuard = useCallback((fn) => { - backGuardRef.current = fn + backGuardsRef.current.add(fn) return () => { - if (backGuardRef.current === fn) backGuardRef.current = null + backGuardsRef.current.delete(fn) } }, []) // Help opened inside Ajustes or Denunciar keeps sheetOpen true, so it stays. @@ -3206,10 +3217,14 @@ function Member () { }) }, [action, node.online, inviteTick]) useEffect(() => { + const guarded = () => { + for (const fn of backGuardsRef.current) if (fn() === true) return true + return false + } if (Platform.OS === 'android') { const sub = BackHandler.addEventListener('hardwareBackPress', () => { if (helpOpenRef.current || sheetOpenRef.current) return false - if (backGuardRef.current?.() === true) return true + if (guarded()) return true if (nav.depth(stackRef.current) === 0) { if (tabRef.current !== 'avisos') return false closeAvisos() @@ -3224,7 +3239,7 @@ function Member () { if (Platform.OS !== 'web' || typeof globalThis.addEventListener !== 'function') return const onKey = (event) => { if (event.key !== 'Escape' || event.defaultPrevented || helpOpenRef.current || sheetOpenRef.current) return - if (backGuardRef.current?.() === true) { + if (guarded()) { event.preventDefault() return } @@ -3853,6 +3868,7 @@ function Member () { handleOpenRecados: node.hosted === true ? openRecados : undefined, handleOpenEventos: node.hosted === true ? openEventos : undefined, handleOpenVisitas: node.hosted === true ? openVisitas : undefined, + handleOpenVarandinha: node.hosted === true ? openVarandinha : undefined, handleOpenAgenda: node.hosted === true ? openAgenda : undefined, handleOpenTop: node.hosted === true ? openTop : undefined, handleComposeSeen: () => setComposeSignal(null), @@ -3880,6 +3896,7 @@ function Member () { onOpenPeople: openPeople, onOpenTestimonials: openTestimonials, onOpenRecados: h.handleOpenRecados, + onOpenVarandinha: h.handleOpenVarandinha, onOpenEventos: h.handleOpenEventos, onOpenListings: h.handleOpenListings } @@ -3935,6 +3952,23 @@ function Member () { ) } + if (entry.screen === 'varandinha') { + // Queued acts make Android Back and Escape ask first, as the top bar + // arrow does; the guard answers only while this entry is on top. + const guardRegistrar = entryHandlers.current.for(i + ':varandinha', { handleRegisterBackGuard: (fn) => registerBackGuard(() => stackRef.current.length - 1 === i && stackRef.current[i].screen === 'varandinha' && fn()) }).handleRegisterBackGuard + return ( + + + + ) + } + if (entry.screen === 'varandinha-rua') { + return ( + + + + ) + } if (entry.screen === 'melhores-amigos') { return ( @@ -4051,8 +4085,7 @@ function Member () { } if (entry.screen === 'anunciar') { // Anunciar registers once per mount, so the guard checks the stack at - // call time. backGuardRef holds one guard and Anunciar is its only - // registrant: a second one would need Anunciar to register again. + // call time and answers only while this entry is on top. const guardRegistrar = entryHandlers.current.for(i + ':anunciar', { handleRegisterBackGuard: (fn) => registerBackGuard(() => stackRef.current.length - 1 === i && stackRef.current[i].screen === 'anunciar' && fn()) }).handleRegisterBackGuard return ( @@ -4348,6 +4381,7 @@ function Member () { onOpenRecados={h.handleOpenRecados} onOpenEventos={h.handleOpenEventos} onOpenVisitas={h.handleOpenVisitas} + onOpenVarandinha={h.handleOpenVarandinha} onOpenTop={h.handleOpenTop} /> )} @@ -4487,7 +4521,7 @@ function Member () { showToast(text) }} /> - setAjustes(null)} onInfo={ajustesInfo} termsInfo={termsInfo} onTermsReset={dropTermsAndSync} scheduledDeletion={scheduledDeletion} onDeletionChanged={refreshAccount} inviteNudge={inviteNudge} onOpenPaginas={!deleteFromAviso && pagesOn({ hosted: node.hosted, accountOrigin: node.accountOrigin }) ? () => pushScreen({ screen: 'paginas' }) : undefined} node={node} member={member} phoneGate={phone.gate} phoneKey={phone.key} phoneChecking={phone.pending} phoneVerified={phone.state === 'verificado' && !phone.error} markVerified={markPhoneVerified} recheckPhone={recheckPhone} termsBeforeCreate={termsBeforeCreate} /> + setAjustes(null)} onInfo={ajustesInfo} termsInfo={termsInfo} onTermsReset={dropTermsAndSync} scheduledDeletion={scheduledDeletion} onDeletionChanged={refreshAccount} inviteNudge={inviteNudge} onOpenVarandinha={!deleteFromAviso && node.hosted === true && ownKey ? () => openVarandinha(ownKey) : undefined} onOpenPaginas={!deleteFromAviso && pagesOn({ hosted: node.hosted, accountOrigin: node.accountOrigin }) ? () => pushScreen({ screen: 'paginas' }) : undefined} node={node} member={member} phoneGate={phone.gate} phoneKey={phone.key} phoneChecking={phone.pending} phoneVerified={phone.state === 'verificado' && !phone.error} markVerified={markPhoneVerified} recheckPhone={recheckPhone} termsBeforeCreate={termsBeforeCreate} /> {/* Mounted after the splash, so it wins: while the boot cover shows it follows the splash, which stays cream on native (Splash.js). */} diff --git a/apps/app/src/garden.js b/apps/app/src/garden.js index dccf7b962..68edd744d 100644 --- a/apps/app/src/garden.js +++ b/apps/app/src/garden.js @@ -108,6 +108,7 @@ function emptyBalcony () { on: false, pots: new Array(rpc.garden.GARDEN_POTS).fill(null), helpers: [], + received: new Array(rpc.garden.GARDEN_POTS).fill(0), isPage: false, stale: false, loading: false, @@ -168,12 +169,42 @@ export function assembleBalcony (args) { helps.push({ author: row.author, seq: row.seq, record, follow }) } const folded = rpc.garden.foldBalcony({ owner, flag, state, helps, given, now }) - return { on: folded.on, pots: folded.pots, helpers: folded.helpers, isPage: false, stale: folded.stale, loading, incomplete, indexing: idx.indexing, refetch } + // Helps counted per pot, as the fold counts them: the helper list keeps + // one row per neighbour, but a neighbour's helps of several days each + // count. + const received = folded.on && state !== null + ? rpc.garden.foldHelps({ owner, pots: state.pots, helps, now }).perPot + : new Array(rpc.garden.GARDEN_POTS).fill(0) + return { on: folded.on, pots: folded.pots, helpers: folded.helpers, received, isPage: false, stale: folded.stale, loading, incomplete, indexing: idx.indexing, refetch } } catch { return emptyBalcony() } } +// Whether a balcony read proves its owner is not playing: an off answer +// counts only when both first blocks and every pointer were read, the index +// was complete and nothing was dated ahead of the reader. +export function provenOff (result, forced) { + return isObject(result) && result.isPage !== true && result.on === false && result.indexing !== true && + result.incomplete !== true && result.stale !== true && forced !== true +} + +// Varandas da rua: the seeder's street page is a claim, so only keys the +// viewer's own follow list holds are offered, once each, in the seeder's +// order. Without a follow set nothing is offered. +export function streetKeys (items, follows) { + if (!Array.isArray(items) || !(follows instanceof Set)) return [] + const out = [] + const seen = new Set() + for (const it of items) { + const key = isObject(it) && typeof it.key === 'string' ? it.key.toLowerCase() : null + if (key === null || !HEX64.test(key) || seen.has(key) || !follows.has(key)) continue + seen.add(key) + out.push(key) + } + return out +} + export function nextLoadStep (args) { const { attempt, result } = isObject(args) ? args : {} if (!isObject(result) || result.refetch !== true) return 'done' diff --git a/apps/app/src/gardenClock.js b/apps/app/src/gardenClock.js new file mode 100644 index 000000000..3d85fb789 --- /dev/null +++ b/apps/app/src/gardenClock.js @@ -0,0 +1,21 @@ +/* global __DEV__ */ + +// The reader clock of the Varandinha screens. Growth, the dry check and the +// 72 h help window are judged on the reader's own clock, so this is +// Date.now(). The Vitrine answers on its demo clock instead (fixtures.now, +// plus a second per write), so a Vitrine bundle reads that clock here too: +// on the real clock every demo plant would read ripe, no demo watering would +// fall inside the window, and nothing could be watered. + +import { vitrineEnabled } from './vitrine/enabled.js' + +const VITRINE = vitrineEnabled({ EXPO_PUBLIC_VARANDA_VITRINE: process.env.EXPO_PUBLIC_VARANDA_VITRINE }, typeof __DEV__ !== 'undefined' && __DEV__) +let offset = 0 +if (typeof __DEV__ !== 'undefined' && __DEV__ && process.env.EXPO_PUBLIC_VARANDA_VITRINE === '1' && VITRINE) { + const { fixtures } = require('./vitrine/fixtures') + offset = Date.parse(fixtures.now) - Date.now() +} + +export function gardenTime (ms = Date.now()) { + return ms + offset +} diff --git a/apps/app/src/legal.js b/apps/app/src/legal.js index 5b00af958..ad91e597a 100644 --- a/apps/app/src/legal.js +++ b/apps/app/src/legal.js @@ -3,9 +3,9 @@ // Sources: docs/design.md (LGPD, moderation, identity), docs/app.md and // SECURITY.md. Planned flows must not read as features already available. -export const LEGAL_VERSION = 76 -export const LEGAL_DATE = '16/11/2026' -export const REVIEW_NOTE = 'Versão 76, sujeita a revisão jurídica. Não é parecer jurídico.' +export const LEGAL_VERSION = 77 +export const LEGAL_DATE = '17/11/2026' +export const REVIEW_NOTE = 'Versão 77, sujeita a revisão jurídica. Não é parecer jurídico.' export const TERMS = { title: 'Termos de Uso', @@ -68,6 +68,7 @@ export const TERMS = { 'Você pode criar uma enquete numa publicação do seu diário, com 2 a 4 opções, e criar tópicos, com ou sem enquete, num grupo público. Votar numa enquete é público: o voto em uma enquete do diário é um registro no seu diário, e o voto numa enquete de um grupo público é um registro no grupo, e em ambos qualquer pessoa que leia o seu diário ou o grupo pode ver em quem ou em qual opção você votou, e a pessoa que criou a enquete pode ver o seu voto. O app avisa disso antes do seu primeiro voto. Retirar o voto grava um novo registro que desfaz o anterior, e os registros anteriores, com as suas datas, continuam públicos; cópias que outras pessoas ou semeadores já buscaram podem continuar existindo. Enquetes e tópicos não têm data de encerramento. Os totais de uma enquete do diário vêm do semeador e podem estar incompletos. Em grupos privados não há tópicos nem enquetes, e não vote se não quiser que todos vejam o seu voto.', 'Você pode publicar um evento no seu diário, com título, início, fim opcional e lugar, e criar um evento num grupo público. Eventos são públicos: a publicação de um evento no seu diário, um evento de um grupo e as respostas de presença, Vou e Talvez, são registros que qualquer pessoa que leia o seu diário ou o grupo pode ver, com quem respondeu e o que respondeu, e a pessoa que criou o evento pode ver a sua resposta. Retirar a resposta grava um novo registro, e os registros anteriores, com as suas datas, continuam públicos. Um evento não pode ser editado: para mudá-lo ou cancelá-lo, apague a publicação ou peça a um administrador que a esconda. Em grupos privados não há eventos. O lembrete de um evento fica só no seu aparelho.', 'Visitas é opcional e começa desligado. Se você ligar, o app mostra os perfis que visitaram o seu e registra as suas visitas aos perfis de quem também está com Visitas ligado: a troca é mútua, você só vê quem visitou enquanto o seu interruptor está ligado e o da outra pessoa estava ligado na visita. A lista de visitantes fica só no seu aparelho, com a precisão de um dia, e é apagada quando você desliga. Desligar para de enviar e de receber visitas, mas não desfaz as que já foram enviadas. Visitas não são mensagens: não acordam ninguém e não geram aviso.', + 'A Varandinha é um jogo opcional e começa desligada: cada pessoa cuida dos vasos da própria varanda, planta, rega e colhe, e as plantas crescem no relógio de quem olha. Você só rega a varanda de quem segue, uma vez por dia por varanda. Participar, o que você planta, as datas de plantio, rega e colheita e de quem é a varanda que você regou são registros públicos no seu diário, e a pessoa cuja planta você regou vê o seu nome. O jogo não tem dinheiro, compra, recompensa sorteada, ranking nem prêmio, e nenhuma notificação pede para alguém voltar. O estado de cada varanda é declarado por quem joga e não é conferido por ninguém. Sair da Varandinha marca os seus registros do jogo como apagados e deixa no seu diário um registro público de que o jogo foi desligado; cópias que outras pessoas já buscaram podem continuar. Sair apaga só os seus próprios registros: as regas que vizinhos fizeram na sua varanda ficam no diário deles, e só quem regou pode apagá-las.', 'Essa autorização não alcança o conteúdo cifrado das mensagens diretas e dos grupos privados, exceto o que alguém enviar numa denúncia. Ela termina quando você apaga o conteúdo ou exclui a conta, respeitados os Limites da exclusão e o que a associação precisa guardar para moderação e pedidos legais.' ] }, @@ -209,7 +210,8 @@ export const PRIVACY = { 'Na versão web hospedada e no app instalado, ser fã de alguém e a lista de melhores amigos são registros públicos no seu diário, visíveis para qualquer pessoa, e valem os mais recentes. Deixar de ser fã grava um novo registro que desfaz o anterior, e os registros anteriores, com as suas datas, continuam públicos no diário; ao publicar uma nova lista de melhores amigos, o app marca como apagadas as listas anteriores, e uma lista vazia limpa a lista. Isso segue os limites da exclusão: cópias que outras pessoas ou semeadores já buscaram podem continuar existindo. O número e a lista de fãs de uma pessoa são montados pelo semeador a partir desses registros públicos, mostrados como o número de seguidores, com o aviso de que podem estar incompletos, e o app confere cada fã no diário dele antes de mostrá-lo. Quando alguém abre um perfil, o app pede ao semeador o número de fãs, a lista de melhores amigos e, para cada amigo, onde está o registro em que ele segue o dono do perfil, e quando alguém abre a lista de fãs de uma pessoa o app pede essa lista ao semeador; como esses pedidos vão pela conexão em que o app já se identificou com a sua conta, o semeador vê qual perfil ou qual lista de fãs foi aberta e pode associar essa leitura à conta de quem abriu. Enquanto o diário de uma pessoa ainda está sendo indexado, o semeador mostra o número de fãs que já conhece, avisa que ele pode estar incompleto e deixa de fora da lista os fãs cujo próprio diário ainda não terminou de ser indexado. O índice fica em memória no semeador e some ao reiniciar.', 'Na versão web hospedada e no app instalado, votar numa enquete é público. Numa enquete de uma publicação, o voto é um registro no seu diário, visível para qualquer pessoa que o leia; numa enquete de um tópico de grupo público, o voto é um registro no grupo, visível para os membros que o leem. Em ambos, mostra em quem ou em qual opção você votou. Retirar o voto grava um novo registro que desfaz o anterior, e os registros anteriores, com as suas datas, continuam públicos, dentro dos limites da exclusão: cópias que outras pessoas ou semeadores já buscaram podem continuar existindo. Os totais de uma enquete de publicação são montados pelo semeador a partir desses registros públicos, mostrados com o aviso de que podem estar incompletos, e o app confere cada votante no diário dele antes de mostrá-lo em Quem votou. Quando alguém abre uma enquete ou a lista de quem votou numa opção, o app pede essas informações ao semeador; como esses pedidos vão pela conexão em que o app já se identificou com a sua conta, o semeador vê qual enquete e qual opção foram abertas e pode associar essa leitura à conta de quem abriu. O índice fica em memória no semeador e some ao reiniciar. Os totais e os votantes de uma enquete de grupo vêm do próprio grupo, sem passar pelo índice.', 'Na versão web hospedada e no app instalado, um evento e as respostas de presença, Vou e Talvez, são públicos. Num evento de uma publicação, o evento e a resposta são registros no diário de quem os publicou, visíveis para qualquer pessoa que o leia; num evento de um grupo público, são registros no grupo, visíveis para os membros que o leem. A resposta mostra quem respondeu e o que respondeu, e retirar a resposta grava um novo registro, e os registros anteriores, com as suas datas, continuam públicos, dentro dos limites da exclusão: cópias que outras pessoas ou semeadores já buscaram podem continuar existindo. Quando alguém abre o perfil de uma pessoa, o app pede ao semeador a lista dos eventos dela; como esse pedido vai pela conexão em que o app já se identificou com a sua conta, o semeador vê qual perfil foi aberto e pode associar essa leitura à conta de quem abriu. Os lembretes de eventos ficam só no aparelho, no armazenamento local do navegador ou num arquivo do app, não são enviados a ninguém e não ficam no seu diário. O arquivo de calendário é gerado no próprio aparelho, na versão web.', - 'No app instalado e na versão web hospedada, Visitas é opcional e começa desligado. Ligado, o app envia um aviso de visita, no máximo 10 por dia, quando você abre o perfil de alguém que também está com Visitas ligado, e busca os avisos que outras pessoas enviaram a você. É mútuo: você só vê quem visitou enquanto o seu interruptor está ligado e o da outra pessoa estava ligado na visita. Ligar ou desligar Visitas grava um registro público e pequeno no seu diário, só com o estado, ligado ou desligado, e a data, e por isso participar é público: qualquer pessoa que leia o seu diário pode ver que Visitas está ligado. A lista de visitantes fica só no seu aparelho, com a precisão de um dia, guardada por até 30 dias, e é apagada quando você desliga. Os avisos viajam selados por semeadores que não conseguem lê-los, num canal à parte das mensagens diretas, e nunca acordam ninguém nem geram notificação; o semeador vê um envelope cifrado sem nome de diário, como nas mensagens diretas, e a conexão pode revelar o endereço de rede. Um semeador que ainda não tem esse canal não recebe avisos, e o app não os envia por outro caminho.' + 'No app instalado e na versão web hospedada, Visitas é opcional e começa desligado. Ligado, o app envia um aviso de visita, no máximo 10 por dia, quando você abre o perfil de alguém que também está com Visitas ligado, e busca os avisos que outras pessoas enviaram a você. É mútuo: você só vê quem visitou enquanto o seu interruptor está ligado e o da outra pessoa estava ligado na visita. Ligar ou desligar Visitas grava um registro público e pequeno no seu diário, só com o estado, ligado ou desligado, e a data, e por isso participar é público: qualquer pessoa que leia o seu diário pode ver que Visitas está ligado. A lista de visitantes fica só no seu aparelho, com a precisão de um dia, guardada por até 30 dias, e é apagada quando você desliga. Os avisos viajam selados por semeadores que não conseguem lê-los, num canal à parte das mensagens diretas, e nunca acordam ninguém nem geram notificação; o semeador vê um envelope cifrado sem nome de diário, como nas mensagens diretas, e a conexão pode revelar o endereço de rede. Um semeador que ainda não tem esse canal não recebe avisos, e o app não os envia por outro caminho.', + 'No app instalado e na versão web hospedada, a Varandinha é opcional e começa desligada. Ligar ou desligar grava no seu diário um registro público que diz só ligado ou desligado, e por isso participar é público. O que você planta em cada vaso, as datas de plantio, rega e colheita e cada rega que você faz, com a varanda regada, a data e o vaso, também são registros públicos no seu diário, visíveis para qualquer pessoa que o leia, sem texto livre. A pessoa cuja planta você regou vê o seu nome. O estado do jogo é declarado por cada pessoa e não é conferido: a assinatura do diário prova quem gravou o registro, não que a planta cresceu pelas regras. O semeador monta, a partir desses registros públicos, apontadores para eles (a chave do diário e o número do registro e, numa rega, a varanda regada, a data e o vaso), sem guardar planta nem nome, e fica sabendo qual varanda o seu aparelho abre, como já sabe qual perfil uma conexão lê; o aparelho confere cada registro apontado antes de mostrá-lo. Não há dinheiro, compra, recompensa sorteada, ranking nem prêmio, os registros do jogo não são usados para traçar perfil nem para publicidade, e nenhuma notificação pede para alguém voltar. O app mantém só o estado mais recente da sua varanda: ao gravar um novo, marca o anterior como apagado. A cada nova rega, o app marca como apagadas até sete das suas regas com mais de cerca de três dias; as que sobrarem continuam públicas até as regas seguintes ou até você sair. Sair da Varandinha marca como apagados os seus registros do jogo, inclusive as regas que você deu, e deixa no diário o registro público de desligado; cópias que outras pessoas já buscaram podem continuar. Sair apaga só os seus próprios registros: as regas que vizinhos fizeram na sua varanda ficam no diário deles, e só quem regou pode apagá-las.' ] }, { diff --git a/apps/app/src/nav.js b/apps/app/src/nav.js index 570b753e8..2a5acc798 100644 --- a/apps/app/src/nav.js +++ b/apps/app/src/nav.js @@ -34,13 +34,15 @@ // ':' and requires params.group (the group's hex64 key). // 'eventos' (a member's events, keyed by the member's hex64; with params.groups, // a list of up to 12 group keys, the Agenda of a community keyed by its root). +// 'varandinha' (one balcony of the pot game) is keyed by the owner's hex64; +// 'varandinha-rua' (Varandas da rua) takes no key. // The stack is an immutable (frozen) array, oldest first. Invalid entries are // refused by returning the stack unchanged (never throws); pushing the // screen that is already on top is a no-op, whatever its params; past // MAX_DEPTH the oldest entry is dropped. export const MAX_DEPTH = 20 -export const SCREENS = Object.freeze(['conversa', 'membro', 'curtidas', 'citacoes', 'grupo', 'comunidade', 'comunidade-info', 'mensagem', 'seguindo', 'seguidores', 'paginas', 'novapagina', 'paginaajustes', 'comunidades', 'pedidos', 'anuncio', 'anunciar', 'editar-anuncio', 'avaliar', 'anuncios', 'depoimentos', 'momentos', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'topico', 'eventos', 'visitas']) +export const SCREENS = Object.freeze(['conversa', 'membro', 'curtidas', 'citacoes', 'grupo', 'comunidade', 'comunidade-info', 'mensagem', 'seguindo', 'seguidores', 'paginas', 'novapagina', 'paginaajustes', 'comunidades', 'pedidos', 'anuncio', 'anunciar', 'editar-anuncio', 'avaliar', 'anuncios', 'depoimentos', 'momentos', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'topico', 'eventos', 'visitas', 'varandinha', 'varandinha-rua']) const HEX32 = /^[0-9a-f]{32}$/ const HEX64 = /^[0-9a-f]{64}$/ @@ -106,7 +108,7 @@ export function validEntry (entry) { return params.oldPage === undefined || isAuthorKey(params.oldPage) } if (entry.screen === 'membro' || entry.screen === 'grupo' || entry.screen === 'comunidade' || entry.screen === 'comunidade-info') return isAuthorKey(entry.key) - if (entry.screen === 'seguindo' || entry.screen === 'seguidores' || entry.screen === 'paginaajustes' || entry.screen === 'anuncios' || entry.screen === 'momentos' || entry.screen === 'recados' || entry.screen === 'fas') return isAuthorKey(entry.key) + if (entry.screen === 'seguindo' || entry.screen === 'seguidores' || entry.screen === 'paginaajustes' || entry.screen === 'anuncios' || entry.screen === 'momentos' || entry.screen === 'recados' || entry.screen === 'fas' || entry.screen === 'varandinha') return isAuthorKey(entry.key) if (entry.screen === 'depoimentos') { const params = entry.params if (!isAuthorKey(entry.key)) return false @@ -114,7 +116,7 @@ export function validEntry (entry) { if (typeof params !== 'object' || Array.isArray(params)) return false return params.section === undefined || params.section === 'sent' } - if (entry.screen === 'paginas' || entry.screen === 'novapagina' || entry.screen === 'comunidades' || entry.screen === 'salvos' || entry.screen === 'melhores-amigos' || entry.screen === 'visitas') return entry.key === undefined || entry.key === null || entry.key === '' + if (entry.screen === 'paginas' || entry.screen === 'novapagina' || entry.screen === 'comunidades' || entry.screen === 'salvos' || entry.screen === 'melhores-amigos' || entry.screen === 'visitas' || entry.screen === 'varandinha-rua') return entry.key === undefined || entry.key === null || entry.key === '' if (entry.screen === 'citacoes') return isRef(entry.key) if (entry.screen === 'assunto') return typeof entry.key === 'string' && TAG.test(entry.key) if (entry.screen === 'curtidas') { diff --git a/apps/app/src/screens/Ajustes.js b/apps/app/src/screens/Ajustes.js index c90a789bd..8e3c785e4 100644 --- a/apps/app/src/screens/Ajustes.js +++ b/apps/app/src/screens/Ajustes.js @@ -195,7 +195,7 @@ function AccountCard ({ ownKey, profile, onPress }) { ) } -export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInfo = null, onTermsReset, scheduledDeletion = null, onDeletionChanged, onOpenPaginas, inviteNudge = 0, node: nodeProp = null, member: gateMember = null, phoneGate = 'off', phoneKey = null, phoneChecking = false, phoneVerified = false, markVerified, recheckPhone, termsBeforeCreate = null }) { +export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInfo = null, onTermsReset, scheduledDeletion = null, onDeletionChanged, onOpenPaginas, onOpenVarandinha, inviteNudge = 0, node: nodeProp = null, member: gateMember = null, phoneGate = 'off', phoneKey = null, phoneChecking = false, phoneVerified = false, markVerified, recheckPhone, termsBeforeCreate = null }) { const styles = useStyles(makeStyles) const { colors, mode, setMode } = useTheme() const node = useNode() @@ -280,6 +280,10 @@ export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInf onClose() onOpenPaginas() } + const openVarandinha = () => { + onClose() + onOpenVarandinha() + } const pushEligible = node.hosted === true && member !== null // Avisos no aparelho, from the store the shell's note shares (null: not // read yet, or this node is not the hosted one for this member any more). @@ -520,6 +524,7 @@ export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInf {hosted ? onNavigate('recados')} /> : null} {devicesOffered ? onNavigate('aparelhos')} /> : null} {visitasOn ? : null} + {node.hosted === true && typeof onOpenVarandinha === 'function' ? : null} onNavigate('termos')} /> {visitasOn diff --git a/apps/app/src/screens/Diario.js b/apps/app/src/screens/Diario.js index 6df2c6541..454ef802c 100644 --- a/apps/app/src/screens/Diario.js +++ b/apps/app/src/screens/Diario.js @@ -297,7 +297,7 @@ export default function Diario (props) { return } -function DiarioList ({ active, refresh, onSettings, onReply, onPublish, onOpenThread, onOpenMember, onOpenMention, onOpenEngagers, onOpenQuotes, onQuote, onToast, onReport, ownKey, scrollToTop, onDeletedPost, onAvisos, avisosNew, onOpenPeople, onOpenCommunity, onOpenTestimonials, onMessage, onOpenMomentos, onOpenSalvos, onOpenRecados, onOpenEventos, onOpenVisitas, onTabChange, onOpenTop }) { +function DiarioList ({ active, refresh, onSettings, onReply, onPublish, onOpenThread, onOpenMember, onOpenMention, onOpenEngagers, onOpenQuotes, onQuote, onToast, onReport, ownKey, scrollToTop, onDeletedPost, onAvisos, avisosNew, onOpenPeople, onOpenCommunity, onOpenTestimonials, onMessage, onOpenMomentos, onOpenSalvos, onOpenRecados, onOpenEventos, onOpenVisitas, onOpenVarandinha, onTabChange, onOpenTop }) { const styles = useStyles(makeStyles) const { colors, scheme } = useTheme() const node = useNode() @@ -839,6 +839,20 @@ function DiarioList ({ active, refresh, onSettings, onReply, onPublish, onOpenTh ) : null} + {node.hosted === true && ownPublicKey && typeof onOpenVarandinha === 'function' + ? ( + onOpenVarandinha(ownPublicKey)} + style={({ pressed }) => [styles.salvos, pressed && styles.salvosPressed]} + > + + Varandinha + + + ) + : null} setSegmentedHeight(e.nativeEvent.layout.height)}> diff --git a/apps/app/src/screens/Membro.js b/apps/app/src/screens/Membro.js index b116921a4..74b29b9a6 100644 --- a/apps/app/src/screens/Membro.js +++ b/apps/app/src/screens/Membro.js @@ -45,6 +45,9 @@ import * as actingAs from '../actingAs' import { TEXTS, pagesFollow, pagesFollows, pagesSuccessor } from '../pages' import { MAX_HOPS, moveOf, pageMoveView, resolveChain, shownUnderCut, successorOf } from '../pageMove' import { rosterRows } from '../pageRoster' +import { flagOn } from '../garden.js' +import { peekBatches } from '../scraps.js' +import { diaryPeekSlots } from '../engagement' import { Soft, errorText, useBottomPad, useVisibleNow } from '../ui' import { FollowPill } from '../ui/FollowPill' import { OfflineNote } from '../ui/OfflineNote' @@ -287,7 +290,7 @@ export default function Membro (props) { return } -function MembroList ({ entry, ownKey, onBack, onFollowsChanged, onMessage, onReply, onQuote, onReport, onOpenThread, onOpenMember, onOpenMention, onOpenEngagers, onOpenQuotes, onOpenPageSettings, onOpenPeople, onOpenCommunity, onOpenListings, onOpenTestimonials, onOpenRecados, onOpenEventos, onToast, onTabChange }) { +function MembroList ({ entry, ownKey, onBack, onFollowsChanged, onMessage, onReply, onQuote, onReport, onOpenThread, onOpenMember, onOpenMention, onOpenEngagers, onOpenQuotes, onOpenPageSettings, onOpenPeople, onOpenCommunity, onOpenListings, onOpenTestimonials, onOpenRecados, onOpenEventos, onOpenVarandinha, onToast, onTabChange }) { const styles = useStyles(makeStyles) const { colors } = useTheme() const node = useNode() @@ -910,6 +913,23 @@ function MembroList ({ entry, ownKey, onBack, onFollowsChanged, onMessage, onRep const rich = useProfileExtra({ author, enabled: node.hosted === true && !isPage && !blockedHere, request }) const extraShown = extraView(rich.held, now) const hostedHere = node.hosted === true && !isPage && !blockedHere + // The seeder's pointer may name a flag that is off, so the row waits for one + // verified peek of that seq. + const gardenSeq = rich.index && Number.isSafeInteger(rich.index.garden) ? rich.index.garden : null + const [gardenOn, setGardenOn] = useState(false) + useEffect(() => { + setGardenOn(false) + if (!hostedHere || gardenSeq === null || typeof author !== 'string') return undefined + let live = true + ;(async () => { + for (const params of peekBatches(author, [gardenSeq])) { + const peek = await diaryPeekSlots.run(() => (live ? request('diary.peek', params) : null), { front: true }) + if (!live) return + if (peek && peek.key === author && flagOn(peek.entries, gardenSeq)) { setGardenOn(true); return } + } + })().catch(() => {}) + return () => { live = false } + }, [hostedHere, gardenSeq, author, request]) const topRead = useTopFriends({ owner: author, ownKey, index: rich.index, request, enabled: hostedHere && !own }) // One visit note per profile view, fire and forget: the node applies every // budget and the switch, a failure is never retried and never shown. @@ -996,6 +1016,15 @@ function MembroList ({ entry, ownKey, onBack, onFollowsChanged, onMessage, onRep ) : null + const varandinhaRow = hostedHere && gardenOn && typeof onOpenVarandinha === 'function' + ? ( + onOpenVarandinha(author)} style={({ pressed }) => [styles.linkRow, pressed && styles.pressed]}> + + Varandinha + + + ) + : null const eventosRow = node.hosted === true && !(isPage && lifecycle.moved) && typeof onOpenEventos === 'function' ? ( onOpenEventos(author)} style={({ pressed }) => [styles.linkRow, pressed && styles.pressed]}> @@ -1151,7 +1180,7 @@ function MembroList ({ entry, ownKey, onBack, onFollowsChanged, onMessage, onRep about={extraShown.about ? : null} fan={hostedHere && !own && typeof ownKey === 'string' ? : null} top={hostedHere && !own && topRead.view && (topRead.view.rows.length > 0 || topRead.view.notice) ? : null} - rows={blockedHere ? null : <>{listingsRow}{recadosRow}{eventosRow}{ratingsRow}} + rows={blockedHere ? null : <>{listingsRow}{recadosRow}{varandinhaRow}{eventosRow}{ratingsRow}} avatar={{ name: who.avatarName, publicKey: author, picture: header.avatar, persist: own || isFollowed }} title={displayText(who.title)} subtitle={who.subtitle ? displayText(who.subtitle) : null} diff --git a/apps/app/src/screens/Varandinha.js b/apps/app/src/screens/Varandinha.js new file mode 100644 index 000000000..c5dae5ebb --- /dev/null +++ b/apps/app/src/screens/Varandinha.js @@ -0,0 +1,727 @@ +// Varandinha (entry { screen: 'varandinha', key: owner hex64 }): one balcony of +// the cozy pot game, the own one or a neighbour's. Hosted nodes only. All +// state is signed records in each member's own diary; the seeder index only +// points at them, so every block shown here was read with diary.peek by the +// node and judged by the pure model in src/garden.js (a forged pointer never +// shows a pot). Growth runs on the reader clock: a 60 s tick redraws and no +// request is made for it. Writes are garden.set, garden.play and garden.help, +// each behind an explicit tap, never repeated by the screen: an uncertain +// answer re-reads garden.state and offers nothing again by itself. No text is +// typed anywhere, and a visitor sees only a count of who watered; the names +// are for the owner's own balcony. + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Pressable, ScrollView, StyleSheet, Text, View, useWindowDimensions } from 'react-native' +import rpc, { FOLLOW_LIMIT_MAX, displayText } from '@varanda/rpc' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { useBlocks } from '../blocksProvider' +import { diaryPeekSlots } from '../engagement' +import { readFollowKeys } from '../follow' +import { assembleBalcony, closeConsent, discard, initialConsent, nextLoadStep, openConsent, pendingCount, pendingStart, planPeeks, provenOff, queue, revalidate, startConsent, toggleConsent } from '../garden' +import { HELP } from '../help' +import { gardenTime } from '../gardenClock' +import { fetchGarden } from '../indexClient' +import { useNames } from '../names' +import { useNode } from '../node' +import { + ACTIONS, CONSENT_LINES, CONSENT_SWITCH_LABEL, NOTICES, SOIL_LABELS, STAGE_LABELS, TITLE, STREET_TITLE, WHO_WATERED, + harvestVerb, pendingLabel, plantLabel, readyIn, refusalNotice, visitorLine, wateredDay +} from '../varandinhaView' +import { whoOf } from '../who' +import { Btn, ConfirmStack, ErrorText, Soft, errorText, useAction, useBottomPad, useNow } from '../ui' +import { Avatar } from '../ui/Avatar' +import { GardenSceneView } from '../ui/GardenSceneView' +import { Icon } from '../ui/Icon' +import { OfflineNote } from '../ui/OfflineNote' +import { Pill } from '../ui/Pill' +import { RefreshableList } from '../ui/RefreshableList' +import { Sheet } from '../ui/Sheet' +import { EmptyState, ErrorState, Skeleton } from '../ui/States' +import { SwitchRow } from '../ui/SwitchRow' +import { TopActions } from '../ui/TopActions' +import { TopBar } from '../ui/TopBar' +import { layout, space, type } from '../ui/theme' +import { useStyles, useTheme } from '../ui/ThemeProvider' + +const HEX64 = /^[0-9a-f]{64}$/ +const { GARDEN_POTS, GARDEN_HELP_PER_POT, GARDEN_SAVES_DAILY_MAX, GARDEN_HELP_ROWS } = rpc.garden + +// Texts the shared module has no place for. +const BEGIN_LABEL = 'Começar' +const LEAVE_LABEL = 'Sair da Varandinha' +const LEAVE_TITLE = 'Sair da Varandinha?' +const UNSAVED_TITLE = 'Sair sem guardar?' +const OWNER_PREFIX = 'Varanda de ' +const UNSAVED_BODY = 'As ações que você ainda não guardou serão descartadas.' +const UNSAVED_CONFIRM = 'Descartar e sair' +const UNSAVED_STAY = 'Continuar na varanda' +const SAVED_TOAST = 'Varanda guardada.' +const WATERED_TOAST = 'Você regou esta varanda.' +const OFFLINE = 'Sem conexão. Tente de novo quando a internet voltar.' +const UNAVAILABLE = 'Não deu para abrir esta varanda agora.' +const POT_WORD = 'Vaso ' +const EMPTY_POT = 'vazio' + +// A failed index read, as the person reads it. +function indexFailure (reason) { + if (reason === 'not-found') return NOTICES.unreachable + if (reason === 'network' || reason === 'timeout') return OFFLINE + return UNAVAILABLE +} + +// A refused or failed write, as the person reads it: an uncertain answer +// says so, a refusal with one of the node's own sentences shows it, anything +// else goes through errorText (never the raw message). +function failureText (err) { + if (err && err.uncertain === true) return NOTICES.uncertain + const known = refusalNotice(err && err.message) + return known !== null ? known : errorText(err) +} + +// The diary.peek reads of a plan, one at a time through the app-wide slots, +// each answer handed to `sink`. A diary the node cannot reach is left unread +// (the balcony then says it may be incomplete); any other failure stops it. +async function peekInto (request, plan, sink, alive) { + for (const params of plan) { + if (!alive()) return + try { + const peek = await diaryPeekSlots.run(() => (alive() ? request('diary.peek', params) : null), { front: true }) + if (!alive() || !peek || typeof peek.key !== 'string') continue + sink(peek) + } catch (err) { + if (err && typeof err.message === 'string' && /di[aá]rio indispon[ií]vel/i.test(err.message)) continue + throw err + } + } +} + +// One balcony, read progressively: the owner's blocks first (the pots show as +// soon as they are judged), then each helper's, one at a time. One index +// refetch at most when a pointer does not resolve (nextLoadStep); a second +// miss only marks the balcony incomplete. `onStage(result, forced)` gets each +// state. Returns { ok: true } or { ok: false, message }; null when stale. +async function readBalcony ({ request, owner, isBlocked, alive, onStage }) { + let attempt = 0 + for (;;) { + const res = await fetchGarden(owner) + if (!alive()) return null + if (!res.ok) return { ok: false, message: indexFailure(res.reason) } + const index = res.value + const plan = planPeeks({ owner, index, isBlocked }) + const ownerReads = [] + await peekInto(request, plan.owner, (p) => ownerReads.push(p), alive) + if (!alive()) return null + const helperReads = new Map() + const assemble = () => assembleBalcony({ owner, index, ownerReads, helperReads, now: gardenTime(), isBlocked }) + const first = assemble() + const step = nextLoadStep({ attempt, result: first }) + if (step === 'refetch') { + attempt += 1 + continue + } + const forced = step === 'incomplete' + onStage(first, forced) + if (first.isPage || !first.on) return { ok: true } + for (const helper of plan.helpers) { + const answers = [] + try { + await peekInto(request, helper.batches, (p) => answers.push(p), alive) + } catch { + // A helper whose blocks cannot be read counts for nothing; the + // balcony reads as incomplete. + } + if (!alive()) return null + helperReads.set(helper.author, answers) + onStage(assemble(), forced) + } + return { ok: true } + } +} + +// The own balcony as the node reads it from the own diary (garden.state). +async function readMine (request) { + const r = await request('garden.state', {}) + const base = r && r.state && Array.isArray(r.state.pots) && r.state.pots.length === GARDEN_POTS ? r.state.pots : null + // An unreadable count reads as every save spent, never as a fresh budget. + const saves = r && Number.isSafeInteger(r.savesToday) && r.savesToday >= 0 ? r.savesToday : GARDEN_SAVES_DAILY_MAX + const given = r && Array.isArray(r.given) ? r.given.filter((g) => !!g && typeof g === 'object').slice(0, GARDEN_HELP_ROWS) : [] + return { on: !!r && r.on === true, base, savesToday: saves, given } +} + +// The counts the reducer judges with: the node's own bound for helps +// received (it cannot see other diaries), the own helps given as foldGiven +// reads them. +function countsOf (owner, base, given, now) { + const rows = given.map((g) => ({ seq: g.seq, record: { type: 'garden-help', to: g.to, pot: g.pot, at: g.at } })) + const perPot = rpc.garden.foldGiven({ self: owner, pots: base, given: rows, now }).perPot + return { received: new Array(GARDEN_POTS).fill(GARDEN_HELP_PER_POT), given: perPot } +} + +// The own pots the node holds under the queued acts: acts that still apply +// stay queued, the others are dropped (revalidate). +function rebased (p, state, owner, now) { + if (pendingCount(p) === 0) return pendingStart(state.base) + const base = state.base === null ? pendingStart(null).base : state.base + return revalidate({ ...p, base }, now, countsOf(owner, state.base, state.given, now)) +} + +// The views of the own pots with the queued acts applied. A pot an act +// touched is drawn without helps (they were counted against the saved pot and +// the saved state decides after Guardar); the others use the helps verified +// in the helpers' diaries, counted per pot as the fold counts them. +function ownViews (pending, received, givenPer, now) { + const touched = new Set(pending.acts.map((a) => a.pot)) + return pending.pots.map((pot, i) => { + const r = Array.isArray(received) && Number.isSafeInteger(received[i]) ? Math.min(Math.max(received[i], 0), GARDEN_HELP_PER_POT) : 0 + return rpc.garden.potView(pot, now, touched.has(i) ? null : { received: r, given: givenPer[i] }) + }) +} + +function potLabel (index, view, occupied) { + const head = POT_WORD + (index + 1) + ', ' + if (view) return head + plantLabel(view.plant) + ', ' + STAGE_LABELS[view.stage] + return head + (occupied ? STAGE_LABELS[0] : EMPTY_POT) +} + +function PotInfo ({ view, now }) { + const { colors } = useTheme() + const styles = useStyles(makeStyles) + if (!view) return null + return ( + + {plantLabel(view.plant)} + {[STAGE_LABELS[view.stage], 'terra ' + SOIL_LABELS[view.dry ? 'dry' : 'wet'], view.ripe ? null : readyIn(view.ripeAt, now)].filter(Boolean).join(' · ')} + + ) +} + +function HelperRow ({ author, at, now, profile }) { + const styles = useStyles(makeStyles) + const who = whoOf(profile) + const title = displayText(who.title) + return ( + + + + {title} + {wateredDay(at, now)} + + + ) +} + +// On someone else's balcony, whose it is. +function OwnerRow ({ owner, profile }) { + const styles = useStyles(makeStyles) + const who = whoOf(profile) + const title = displayText(who.title) + return ( + + + + {title} + {who.subtitle ? {displayText(who.subtitle)} : null} + + + ) +} + +export default function Varandinha ({ entry, ownKey, onBack, onOpenStreet, onToast, registerBackGuard }) { + const styles = useStyles(makeStyles) + const { scheme, colors } = useTheme() + const node = useNode() + const hosted = node.hosted === true + const names = useNames() + const blocks = useBlocks() + const now = gardenTime(useNow(60000)) + const bottomPad = useBottomPad() + const insets = useSafeAreaInsets() + const { width } = useWindowDimensions() + const act = useAction() + const requestRef = useRef(node.request) + requestRef.current = node.request + const namesRef = useRef(names) + namesRef.current = names + const blockedRef = useRef(blocks.has) + blockedRef.current = blocks.has + const blocksKnown = blocks.loadState !== 'pending' + const owner = entry && typeof entry.key === 'string' ? entry.key.toLowerCase() : '' + const self = typeof ownKey === 'string' ? ownKey.toLowerCase() : null + const own = self !== null && owner === self + + const [view, setView] = useState({ phase: 'loading', error: null, mine: null, following: null }) + const [bal, setBal] = useState({ phase: 'idle', result: null, forced: false, error: null }) + const [pending, setPending] = useState(() => pendingStart(null)) + const [consent, setConsent] = useState(initialConsent) + const [potOpen, setPotOpen] = useState(null) + const [leaveOpen, setLeaveOpen] = useState(false) + const [unsaved, setUnsaved] = useState(null) + const [helped, setHelped] = useState(false) + const [notice, setNotice] = useState('') + const [refreshing, setRefreshing] = useState(false) + const seq = useRef(0) + + useEffect(() => { + if (!own && HEX64.test(owner) && namesRef.current) namesRef.current.resolveMany([owner]) + }, [own, owner]) + + const load = useCallback(async () => { + if (!hosted || !blocksKnown || !HEX64.test(owner)) return + const mine = ++seq.current + const alive = () => mine === seq.current + const request = requestRef.current + setView((v) => ({ ...v, phase: v.mine ? v.phase : 'loading', error: null })) + let state + try { + state = await readMine(request) + } catch (err) { + if (alive()) setView((v) => ({ ...v, phase: v.mine ? v.phase : 'error', error: errorText(err) })) + return + } + if (!alive()) return + // A fresh read settles an uncertain watering: garden.state lists it when + // it was written, and the writer rule then hides Regar. + setHelped((h) => (h === 'uncertain' ? false : h)) + // A refresh keeps the queued acts that still hold on the freshly read pots. + if (own) setPending((p) => rebased(p, state, owner, gardenTime())) + if (!state.on) { + setView({ phase: 'ready', error: null, mine: state, following: null }) + setBal({ phase: 'idle', result: null, forced: false, error: null }) + return + } + setView((v) => ({ phase: 'ready', error: null, mine: state, following: own ? null : v.following })) + setBal((b) => ({ ...b, phase: b.result ? 'ready' : 'loading', error: null })) + if (!own) { + readFollowKeys(request, FOLLOW_LIMIT_MAX).then((set) => { + if (alive()) setView((v) => ({ ...v, following: set === null ? null : set.has(owner) })) + }, () => {}) + } + let out + try { + out = await readBalcony({ + request, + owner, + isBlocked: (key) => blockedRef.current(key), + alive, + onStage: (result, forced) => { + if (!alive()) return + if (own && namesRef.current) namesRef.current.resolveMany(result.helpers.map((h) => h.author)) + setBal({ phase: 'ready', result, forced, error: null }) + } + }) + } catch (err) { + if (alive()) setBal((b) => ({ ...b, phase: b.result ? 'ready' : 'error', error: errorText(err) })) + return + } + if (out && !out.ok && alive()) setBal((b) => ({ ...b, phase: b.result ? 'ready' : 'error', error: out.message })) + }, [hosted, blocksKnown, owner, self, own]) + + useEffect(() => { + load() + return () => { seq.current += 1 } + }, [load]) + + const mine = view.mine + const counts = useMemo( + () => (own && mine ? countsOf(owner, mine.base, mine.given, now) : null), + [own, owner, mine, now] + ) + + // Growth moves on the reader clock: queued acts are judged again at every + // tick, and the longest prefix that still holds is kept. + useEffect(() => { + if (counts === null) return + setPending((p) => (pendingCount(p) === 0 ? p : revalidate(p, now, counts))) + }, [now, counts]) + + const toast = (text) => { if (typeof onToast === 'function') onToast(text) } + + // One write at a time. A failure is filed as the notice and rethrown, so + // useAction knows whether it was uncertain; nothing is sent again. + const write = (method, params) => act.run(async () => { + try { + return await requestRef.current(method, params) + } catch (err) { + setNotice(failureText(err)) + throw err + } + }) + + // The own balcony as the node holds it after a write. A failed read keeps + // the write's own notice (an uncertain answer says to check first). + const reread = async () => { + try { + const state = await readMine(requestRef.current) + setView((v) => ({ ...v, mine: state })) + return state + } catch (err) { + setNotice((n) => n || errorText(err)) + return null + } + } + + const begin = async () => { + if (act.pending) return + const next = startConsent(consent) + if (next === consent) return + setConsent(next) + setNotice('') + const r = await write('garden.set', { on: true }) + if (r.ok) { + setConsent(closeConsent()) + setNotice('') + load() + return + } + setConsent((c) => ({ ...c, busy: false })) + if (r.uncertain) { + const state = await reread() + if (state && state.on) { + setConsent(closeConsent()) + load() + } + } + } + + const leave = async () => { + if (act.pending) return + setNotice('') + const r = await write('garden.set', { on: false }) + if (!r.ok && !r.uncertain) return + const state = r.ok ? { on: false, base: null, savesToday: 0, given: [] } : await reread() + if (state === null) return + setLeaveOpen(false) + if (state.on) { + // The node still reads the balcony as on: the leave may have stopped + // halfway. The uncertain notice stays and the balcony is read again, + // with the queued acts that still hold. + load() + return + } + setView((v) => ({ ...v, mine: state })) + setPending(pendingStart(null)) + setBal({ phase: 'idle', result: null, forced: false, error: null }) + } + + const exhausted = mine !== null && mine.savesToday >= GARDEN_SAVES_DAILY_MAX + + const save = async () => { + if (act.pending || pendingCount(pending) === 0 || exhausted) return + setNotice('') + const r = await write('garden.play', { acts: pending.acts }) + if (!r.ok && !r.uncertain) return + // The batch leaves the queue whatever the read below finds, so it is + // never sent twice. A saved batch shows the pots the node answered with. + const saved = r.ok && r.value && r.value.state && Array.isArray(r.value.state.pots) && r.value.state.pots.length === GARDEN_POTS ? r.value.state.pots : null + setPending((p) => pendingStart(saved !== null ? saved : p.base)) + if (r.ok) toast(SAVED_TOAST) + const state = await reread() + if (state !== null) setPending((p) => rebased(p, state, owner, gardenTime())) + } + + const tap = (op, index, plant) => { + if (act.pending) return + const action = plant === undefined ? { op, pot: index } : { op, pot: index, plant } + const next = queue(pending, action, gardenTime(), counts) + setPending(next) + setNotice(next.refused === null ? '' : NOTICES.invalid) + if (next.refused === null) setPotOpen(null) + } + + const water = async (index) => { + if (act.pending || helped) return + setNotice('') + const r = await write('garden.help', { to: owner, pot: index }) + if (r.ok) { + setHelped('ok') + setPotOpen(null) + toast(WATERED_TOAST) + } else if (r.uncertain) { + // The help may have been written: no second button for it. + setHelped('uncertain') + } + } + + // Leaving with queued acts asks first; nothing is written either way. A + // batch already on its way to the node is not unsaved: leaving then asks + // nothing, and the write goes on. + const unsavedActs = () => pendingCount(pending) > 0 && !act.pending + const guard = (go) => { + if (typeof go !== 'function') return + if (unsavedActs()) setUnsaved({ go }) + else go() + } + // Android Back and Escape ask the same way. The native swipe back and the + // browser Back consult no guard, as for Anunciar. + const backRef = useRef(null) + backRef.current = () => { + if (!unsavedActs() || typeof onBack !== 'function') return false + setUnsaved({ go: onBack }) + return true + } + useEffect(() => { + if (typeof registerBackGuard !== 'function') return + return registerBackGuard(() => backRef.current()) + }, [registerBackGuard]) + + const bar = guard(onBack)} right={} /> + if (!hosted) { + return ( + + {bar} + + + ) + } + if (!HEX64.test(owner)) { + return ( + + {bar} + + + ) + } + if (view.phase === 'loading') { + return ( + + {bar} + + + + ) + } + if (view.phase === 'error') { + return ( + + {bar} + + + + ) + } + + const consentSheet = ( + setConsent(closeConsent())} dismissable={!consent.busy && !act.pending} title={TITLE}> + + {CONSENT_LINES.map((line) => {line})} + setConsent(toggleConsent(consent))} disabled={consent.busy} /> + {notice} + + + + ) + + if (!mine || !mine.on) { + return ( + + {bar} + + { setNotice(''); setConsent(openConsent()) }} /> + {consentSheet} + + ) + } + + const result = bal.result + const page = !!result && result.isPage + // A balcony reads as off only when its blocks were read in full: an unread + // or stale block, or an index still being built, proves nothing. + const away = provenOff(result, bal.forced) && bal.phase === 'ready' + const unproven = !!result && !result.isPage && !result.on && !provenOff(result, bal.forced) + if (!own && (page || away)) { + return ( + + {bar} + + + + ) + } + if (!own && unproven) { + return ( + + {bar} + + + + ) + } + + // A neighbour's pots are shown only once the owner's blocks were judged. + if (!own && !result) { + return ( + + {bar} + + {bal.phase === 'error' ? : } + + ) + } + + const pending6 = pendingCount(pending) + const helpers = result && !page ? result.helpers : [] + const givenPer = own && counts ? counts.given : new Array(GARDEN_POTS).fill(0) + const views = own + ? ownViews(pending, result && !page ? result.received : null, givenPer, now) + : (result && !page && result.on ? result.pots : new Array(GARDEN_POTS).fill(null)) + const labels = views.map((v, i) => potLabel(i, v, own ? !!pending.pots[i] : false)) + const notes = [] + if (result && !page) { + if (result.indexing) notes.push(NOTICES.indexing) + else if (!result.loading && (result.incomplete || result.stale || bal.forced)) notes.push(NOTICES.incomplete) + } + if (exhausted && own) notes.push(NOTICES.saves) + + // The node's own writer rule over the waterings garden.state listed: a + // balcony already watered today, or a spent daily budget, offers no Regar. + const allowed = !own && mine && self !== null && view.following === true && + rpc.garden.helpAllowed({ self, to: owner, follows: new Set([owner]), own: mine.given, now }).ok === true + const canHelp = allowed && result !== null && result.on === true && mine.on && !helped + const sheetView = potOpen === null ? null : views[potOpen] + const occupied = potOpen !== null && own ? !!pending.pots[potOpen] : !!sheetView + + const scene = ( + + { setNotice(''); setPotOpen(i) }} /> + + ) + + const header = ( + + {!own ? : null} + {scene} + {notes.map((n) => {n})} + {notice ? {notice} : null} + {!own && result && !result.loading && !page ? {visitorLine(result.helpers.length + (helped === 'ok' && !result.helpers.some((h) => h.author === self) ? 1 : 0))} : null} + {own && typeof onOpenStreet === 'function' + ? ( + guard(onOpenStreet)} + style={({ pressed }) => [styles.streetRow, pressed && styles.pressed]} + > + + {STREET_TITLE} + + + ) + : null} + {own ? {WHO_WATERED} : null} + + ) + + let empty = null + if (own) { + if (bal.phase === 'error') empty = + else if (!result || result.loading) empty = + else empty = {visitorLine(0)} + } + const footer = own + ? { setNotice(''); setLeaveOpen(true) }} /> + : null + + return ( + + {bar} + + h.author + ':' + h.seq} + renderItem={({ item }) => } + extraData={{ now, notice, names }} + ListHeaderComponent={header} + ListEmptyComponent={empty} + ListFooterComponent={footer} + contentContainerStyle={{ paddingBottom: bottomPad }} + onRefresh={async () => { + setRefreshing(true) + try { await load() } finally { setRefreshing(false) } + }} + refreshing={refreshing} + atEnd + /> + {own && pending6 > 0 + ? ( + + {pendingLabel(pending6)} + + { setPending(discard(pending)); setNotice('') }} /> + + + + ) + : null} + setPotOpen(null)} dismissable={!act.pending} title={potOpen === null ? '' : POT_WORD + (potOpen + 1)}> + + + {own && potOpen !== null && !occupied + ? ( + <> + {ACTIONS.plant} + {rpc.garden.GARDEN_PLANTS.map((p) => ( + tap('plant', potOpen, p.id)} /> + ))} + + ) + : null} + {own && potOpen !== null && occupied + ? ( + <> + {sheetView && sheetView.canWater ? tap('water', potOpen)} /> : null} + {sheetView && sheetView.ripe ? tap('harvest', potOpen)} /> : null} + tap('clear', potOpen)} /> + + ) + : null} + {!own && potOpen !== null && canHelp && sheetView && !sheetView.ripe + ? water(potOpen)} /> + : null} + {notice} + + + setLeaveOpen(false)} dismissable={!act.pending} title={LEAVE_TITLE}> + + {CONSENT_LINES[4]} + {notice} + } + cancel={ setLeaveOpen(false)} disabled={act.pending} />} + /> + + + setUnsaved(null)} title={UNSAVED_TITLE}> + + {UNSAVED_BODY} + { const go = unsaved.go; setUnsaved(null); setPending(discard(pending)); go() }} />} + cancel={ setUnsaved(null)} />} + /> + + + {consentSheet} + + ) +} + +const makeStyles = (colors) => StyleSheet.create({ + screen: { flex: 1, backgroundColor: colors.bg }, + scene: { alignItems: 'center' }, + note: { paddingHorizontal: space.lg, paddingVertical: space.sm }, + count: { ...type.rowName }, + more: { paddingHorizontal: space.lg, paddingVertical: space.lg, alignItems: 'flex-start' }, + section: { ...type.section, color: colors.soft, paddingHorizontal: space.lg, paddingTop: space.lg, paddingBottom: space.xs }, + streetRow: { flexDirection: 'row', alignItems: 'center', gap: space.md, minHeight: layout.hit, paddingVertical: space.sm, paddingHorizontal: space.lg }, + streetLabel: { ...type.rowName, color: colors.ink, flex: 1 }, + pressed: { opacity: 0.6 }, + helper: { flexDirection: 'row', alignItems: 'center', gap: space.md, minHeight: layout.hit, paddingVertical: space.sm, paddingHorizontal: space.lg }, + who: { flex: 1, minWidth: 0 }, + name: { ...type.rowName, color: colors.ink }, + when: { ...type.caption, color: colors.soft }, + pendingBar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: space.md, paddingHorizontal: space.lg, paddingVertical: space.sm, borderTopWidth: 1, borderTopColor: colors.line, backgroundColor: colors.card }, + pendingText: { ...type.rowName, flexShrink: 1 }, + pendingActions: { flexDirection: 'row', alignItems: 'center', gap: space.sm }, + potInfo: { gap: space.xs }, + potName: { ...type.postName }, + sheetBody: { gap: space.md, paddingHorizontal: space.lg, paddingBottom: space.lg } +}) diff --git a/apps/app/src/screens/VarandinhaRua.js b/apps/app/src/screens/VarandinhaRua.js new file mode 100644 index 000000000..9e6d1e985 --- /dev/null +++ b/apps/app/src/screens/VarandinhaRua.js @@ -0,0 +1,189 @@ +// Varandas da rua (entry { screen: 'varandinha-rua' }): the balconies of the +// people the viewer follows who play the Varandinha, in the seeder's key +// order, 20 a page. Hosted nodes only. The list is a seeder claim: a key +// shows only when the viewer's own follow.list holds it, and each balcony is +// read and verified when it is opened (Varandinha.js). A next page loads +// only on an explicit tap, never as a chain, and nothing here writes. + +import { useCallback, useEffect, useRef, useState } from 'react' +import { Pressable, StyleSheet, Text, View } from 'react-native' +import { FOLLOW_LIMIT_MAX, displayText } from '@varanda/rpc' +import { useBlocks } from '../blocksProvider' +import { readFollowKeys } from '../follow' +import { streetKeys } from '../garden' +import { fetchGardenStreet } from '../indexClient' +import { useNames } from '../names' +import { useNode } from '../node' +import { NOT_HOSTED } from '../pessoas' +import { whoOf } from '../who' +import { NOTICES, STREET_TITLE } from '../varandinhaView' +import { Soft, useBottomPad } from '../ui' +import { Avatar } from '../ui/Avatar' +import { OfflineNote } from '../ui/OfflineNote' +import { Pill } from '../ui/Pill' +import { RefreshableList } from '../ui/RefreshableList' +import { EmptyState, ErrorState, Skeleton } from '../ui/States' +import { TopBar } from '../ui/TopBar' +import { layout, space, type } from '../ui/theme' +import { useStyles } from '../ui/ThemeProvider' + +const HEX64 = /^[0-9a-f]{64}$/ +const OFFLINE = 'Sem conexão. Tente de novo quando a internet voltar.' +const UNAVAILABLE = 'Não deu para abrir as varandas da rua agora.' +const MORE = 'Carregar mais' +const EMPTY_TITLE = 'Nenhuma varanda por aqui ainda' +const EMPTY_BODY = 'Quando alguém que você segue entrar na Varandinha, a varanda aparece aqui.' +const ROW_HINT = 'ver a varanda de ' + +// A failed index read, as the person reads it. +function failureOf (reason) { + if (reason === 'not-found') return NOTICES.unreachable + if (reason === 'network' || reason === 'timeout') return OFFLINE + return UNAVAILABLE +} + +function StreetRow ({ keyHex, profile, onOpen }) { + const styles = useStyles(makeStyles) + const who = whoOf(profile) + const title = displayText(who.title) + return ( + onOpen(keyHex)} + style={({ pressed }) => [styles.row, pressed && styles.pressed]} + > + + + {title} + {who.subtitle ? {displayText(who.subtitle)} : null} + + + ) +} + +export default function VarandinhaRua ({ ownKey, onBack, onOpenBalcony }) { + const styles = useStyles(makeStyles) + const node = useNode() + const hosted = node.hosted === true + const names = useNames() + // The names cache changes as profiles arrive; the list is not read again + // for that. + const namesRef = useRef(names) + namesRef.current = names + const blocks = useBlocks() + const bottom = useBottomPad() + const blockedRef = useRef(blocks.has) + blockedRef.current = blocks.has + const blocksKnown = blocks.loadState !== 'pending' + const self = typeof ownKey === 'string' && HEX64.test(ownKey.toLowerCase()) ? ownKey.toLowerCase() : null + const [view, setView] = useState({ phase: 'loading', keys: [], next: null, error: null, more: false, indexing: false, complete: true }) + const [refreshing, setRefreshing] = useState(false) + const held = useRef({ next: null, follows: null }) + const seq = useRef(0) + const requestRef = useRef(node.request) + requestRef.current = node.request + + const load = useCallback(async (more) => { + if (!hosted || !blocksKnown || self === null) return + const mine = ++seq.current + const alive = () => mine === seq.current + const cursor = more ? held.current.next : null + setView((v) => ({ ...v, phase: more || v.keys.length > 0 ? v.phase : 'loading', more, error: null })) + // The follow set is read again on every first page and kept for the next + // ones; a failed read shows no unchecked key. + const known = more ? held.current.follows : null + const [res, follows] = await Promise.all([ + fetchGardenStreet(self, cursor), + known || readFollowKeys(requestRef.current, FOLLOW_LIMIT_MAX) + ]) + if (!alive()) return + if (!res.ok || follows === null) { + const error = res.ok ? UNAVAILABLE : failureOf(res.reason) + setView((v) => ({ ...v, phase: v.keys.length > 0 ? 'ready' : 'error', more: false, error })) + return + } + held.current = { next: res.value.next, follows } + const fresh = streetKeys(res.value.items, follows) + if (namesRef.current) namesRef.current.resolveMany(fresh) + setView((v) => { + const seen = new Set(more ? v.keys : []) + const keys = more ? v.keys.slice() : [] + for (const k of fresh) { + if (seen.has(k)) continue + seen.add(k) + keys.push(k) + } + return { phase: 'ready', keys, next: res.value.next, error: null, more: false, indexing: res.value.indexing, complete: res.value.complete } + }) + }, [hosted, blocksKnown, self]) + + useEffect(() => { + load(false) + return () => { seq.current += 1 } + }, [load]) + + const bar = + if (!hosted) { + return ( + + {bar} + + + ) + } + + // The viewer and blocked people never show, whenever the block list changes. + const rows = view.keys.filter((k) => k !== self && !blockedRef.current(k)) + let empty = null + if (self === null) empty = + else if (view.phase === 'loading') empty = + else if (view.phase === 'error') empty = load(false)} /> + // While the index is still built or the answer is partial, the note says so + // instead of an empty street. + else if (view.next === null && !view.indexing && view.complete !== false) empty = + + let note = null + if (view.phase === 'ready') { + if (view.error) note = view.error + else if (view.indexing) note = NOTICES.indexing + else if (view.complete === false) note = NOTICES.incomplete + } + const header = note ? {note} : null + const footer = view.next && view.phase === 'ready' + ? load(true)} /> + : null + + return ( + + {bar} + + k} + renderItem={({ item }) => } + ListHeaderComponent={header} + ListEmptyComponent={empty} + ListFooterComponent={footer} + contentContainerStyle={{ paddingBottom: bottom }} + onRefresh={async () => { + setRefreshing(true) + try { await load(false) } finally { setRefreshing(false) } + }} + refreshing={refreshing} + atEnd + /> + + ) +} + +const makeStyles = (colors) => StyleSheet.create({ + screen: { flex: 1, backgroundColor: colors.bg }, + notice: { paddingHorizontal: space.lg, paddingVertical: space.sm }, + more: { paddingHorizontal: space.lg, paddingVertical: space.md, alignItems: 'flex-start' }, + row: { flexDirection: 'row', alignItems: 'center', gap: space.md, minHeight: layout.hit, paddingVertical: space.sm, paddingHorizontal: space.lg }, + pressed: { opacity: 0.6 }, + who: { flex: 1, minWidth: 0 }, + name: { ...type.rowName, color: colors.ink }, + handle: { ...type.caption, color: colors.soft } +}) diff --git a/apps/app/src/tabs.js b/apps/app/src/tabs.js index 4aa767be2..26c4dd990 100644 --- a/apps/app/src/tabs.js +++ b/apps/app/src/tabs.js @@ -29,7 +29,7 @@ const FEIRA_SCREENS = new Set(['anuncio', 'anunciar', 'editar-anuncio', 'avaliar // Screens with nothing to publish on: the Depoimentos management screen, // the Posts salvos list, an Assunto page, a Recados page, the fan list, the // Melhores amigos editor and the full-screen Momentos viewer. Conversa has its own reply bar. -const NO_POST_SCREENS = new Set(['depoimentos', 'momentos', 'conversa', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'eventos', 'visitas']) +const NO_POST_SCREENS = new Set(['depoimentos', 'momentos', 'conversa', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'eventos', 'visitas', 'varandinha', 'varandinha-rua']) // The floating "publicar" button belongs to posts: it is hidden on the // Conversas and Feira tabs, on their screens and on NO_POST_SCREENS. `screen` diff --git a/apps/app/src/vitrine/request.js b/apps/app/src/vitrine/request.js index ad96cc52f..8e8907744 100644 --- a/apps/app/src/vitrine/request.js +++ b/apps/app/src/vitrine/request.js @@ -344,11 +344,12 @@ export function createVitrineRequest (fixtures, options) { // Varandinha (5.157 to 5.160): the own balcony is read from the own diary // records, so the fixtures, a play, a help and a leave all agree with // diary.peek and the /index/garden answers. The rules are rpc.garden, on - // the demo clock; answered dates move with options.clock like momentos. + // the demo clock. Unlike momentos, answered dates stay on that clock: a + // peeked garden block cannot move, so the app reads the demo clock for the + // whole game in a Vitrine bundle (src/gardenClock.js). const gardenOf = (type) => (logs.get(data.own) || []).filter((e) => e.record.type === type && !deleted.has(`${data.own}:${e.seq}`)).sort((a, b) => b.seq - a.seq) const gardenOn = () => gardenOf('garden')[0]?.record.on === true - const shownPot = (p) => p === null ? null : { ...p, at: shown(p.at), water: shown(p.water) } - const gardenShape = (e) => e ? { seq: e.seq, pots: e.record.pots.map(shownPot), n: e.record.n, at: shown(e.record.at) } : null + const gardenShape = (e) => e ? { seq: e.seq, pots: e.record.pots.map((p) => p === null ? null : { ...p }), n: e.record.n, at: e.record.at } : null const gardenTombstone = (seq) => deleted.set(`${data.own}:${seq}`, append({ type: 'delete', seq, at: stamp() })) // Latest wins, as the node's publishLatest: every earlier live block of the // type is tombstoned before the new one. @@ -945,7 +946,7 @@ export function createVitrineRequest (fixtures, options) { savesToday: state && Date.parse(state.record.at) >= today ? state.record.n : 0, helpsToday: helps.filter((h) => h.atMs >= today).length, given: helps.filter((h) => h.atMs >= now - rpc.garden.GARDEN_HELP_WINDOW_MS && h.atMs <= now + rpc.garden.GARDEN_MAX_FUTURE_MS) - .slice(0, rpc.garden.GARDEN_HELP_ROWS).map(({ seq, to, pot, at }) => ({ seq, to, pot, at: shown(at) })) + .slice(0, rpc.garden.GARDEN_HELP_ROWS).map(({ seq, to, pot, at }) => ({ seq, to, pot, at })) } }, 'garden.play': ({ acts }) => { diff --git a/apps/app/test/composePolish.test.js b/apps/app/test/composePolish.test.js index bfbf888dd..c52aa0828 100644 --- a/apps/app/test/composePolish.test.js +++ b/apps/app/test/composePolish.test.js @@ -29,6 +29,7 @@ test('settings group every row and keep the existing advanced toggle last', (t) ['{WALL_TITLE}', "() => onNavigate('recados')"], ['{DEVICES_TITLE}', "() => onNavigate('aparelhos')"], ['{VISITAS_TITLE}', 'openVisitasSheet'], + ["'Varandinha'", 'openVarandinha'], ['{CONSENT_SWITCH_LABEL}', '() => setConsent(toggleConsent(consent))'], ["'Convidar pessoas'", "() => onNavigate('convites')"], ["'Páginas'", 'openPaginas'], diff --git a/apps/app/test/garden.test.js b/apps/app/test/garden.test.js index 4267efc1b..55bcb06ad 100644 --- a/apps/app/test/garden.test.js +++ b/apps/app/test/garden.test.js @@ -490,3 +490,58 @@ test('assembleBalcony folds nothing while block 1 or 2 is unread', async (t) => const page = assembleBalcony({ owner: OWNER, index: baseIndex(), ownerReads: [peek(OWNER, [e(1, { type: 'page-roster' }), ...body], { missing: [2] })], helperReads: new Map(), now: NOW }) t.is(page.isPage, true) }) + +test('the garden clock is the reader clock outside the Vitrine', async (t) => { + const { gardenTime } = await import('../src/gardenClock.js') + t.is(gardenTime(NOW), NOW) + const before = Date.now() + const read = gardenTime() + t.ok(read >= before && read <= Date.now()) +}) + +test('assembleBalcony counts a neighbour watering one pot on two days twice', async (t) => { + const { assembleBalcony } = await import('../src/garden.js') + const planted = NOW - 30 * H + const ownerReads = [peek(OWNER, [e(1, { type: 'profile' }), e(3, flag()), e(4, state(potsWith(0, pot('espada', planted))))])] + const helps = [helpRow(BOB, 9, 5), helpRow(BOB, 12, 5)] + const reads = new Map([[BOB, peek(BOB, [e(5, follow(OWNER)), e(9, help(OWNER, 0, NOW - 20 * H)), e(12, help(OWNER, 0, NOW - H))])]]) + const r = assembleBalcony({ owner: OWNER, index: baseIndex({ helps }), ownerReads, helperReads: reads, now: NOW }) + t.is(r.helpers.length, 1, 'one row per neighbour') + t.is(r.helpers[0].seq, 12) + t.alike(r.received, [2, 0, 0, 0, 0, 0]) + t.is(r.pots[0].ripeAt, planted + 48 * H - 4 * H, 'both days shorten the wait') + const off = assembleBalcony({ owner: OWNER, index: baseIndex({ helps }), ownerReads: [peek(OWNER, [e(1, { type: 'profile' }), e(3, flag(false)), e(4, state(potsWith(0, pot('espada', planted))))])], helperReads: reads, now: NOW }) + t.alike(off.received, [0, 0, 0, 0, 0, 0]) + t.alike(assembleBalcony({}).received, [0, 0, 0, 0, 0, 0]) +}) + +test('provenOff is true only for an off balcony read in full', async (t) => { + const { assembleBalcony, provenOff } = await import('../src/garden.js') + const offReads = [peek(OWNER, [e(1, { type: 'profile' }), e(3, flag(false)), e(4, state(ownerPots()))])] + const off = assembleBalcony({ owner: OWNER, index: baseIndex(), ownerReads: offReads, helperReads: new Map(), now: NOW }) + t.is(provenOff(off, false), true) + t.is(provenOff(off, true), false, 'a second stale pointer proves nothing') + t.is(provenOff({ ...off, indexing: true }, false), false) + t.is(provenOff({ ...off, stale: true }, false), false) + const unread = assembleBalcony({ owner: OWNER, index: baseIndex(), ownerReads: [peek(OWNER, [e(3, flag())], { missing: [1, 2] })], helperReads: new Map(), now: NOW }) + t.is(unread.on, false) + t.is(provenOff(unread, false), false, 'unread first blocks read as unknown, not off') + const partial = assembleBalcony({ owner: OWNER, index: baseIndex({ complete: false }), ownerReads: offReads, helperReads: new Map(), now: NOW }) + t.is(provenOff(partial, false), false) + const on = assembleBalcony({ owner: OWNER, index: baseIndex(), ownerReads: ownerRead(), helperReads: new Map(), now: NOW }) + t.is(provenOff(on, false), false) + t.is(provenOff(null, false), false) + t.is(provenOff({ ...off, isPage: true }, false), false) +}) + +test('streetKeys offers only followed keys, once each, in the seeder order', async (t) => { + const { streetKeys } = await import('../src/garden.js') + const follows = new Set([BOB, CAROL]) + const items = [{ key: DAVE, on: 1 }, { key: CAROL, on: 2 }, { key: BOB.toUpperCase(), on: 3 }, { key: CAROL, on: 4 }] + t.alike(streetKeys(items, follows), [CAROL, BOB], 'a key the viewer does not follow never shows') + t.alike(streetKeys([{ key: 'b'.repeat(63) }, { key: 7 }, null, 'x', { key: BOB }], follows), [BOB], 'a malformed row is dropped') + t.alike(streetKeys(items, null), [], 'without a follow set nothing is offered') + t.alike(streetKeys(items, [BOB, CAROL]), [], 'a follow array is not a follow set') + t.alike(streetKeys(null, follows), []) + t.alike(streetKeys(items, new Set()), []) +}) diff --git a/apps/app/test/legal.test.js b/apps/app/test/legal.test.js index c3d281d4f..e9873783e 100644 --- a/apps/app/test/legal.test.js +++ b/apps/app/test/legal.test.js @@ -7,9 +7,9 @@ const load = () => import('../src/legal.js') test('legal: version, date and review note', async (t) => { const { LEGAL_VERSION, LEGAL_DATE, REVIEW_NOTE } = await load() - t.is(LEGAL_VERSION, 76) - t.is(LEGAL_DATE, '16/11/2026') - t.is(REVIEW_NOTE, 'Versão 76, sujeita a revisão jurídica. Não é parecer jurídico.') + t.is(LEGAL_VERSION, 77) + t.is(LEGAL_DATE, '17/11/2026') + t.is(REVIEW_NOTE, 'Versão 77, sujeita a revisão jurídica. Não é parecer jurídico.') }) test('legal: this version describes music covers as never stored', async (t) => { @@ -363,7 +363,7 @@ test('legal: privacy identifies unresolved retention and contact', async (t) => test('legal: published text is pinned to its acceptance version', async (t) => { const { LEGAL_VERSION, TERMS, PRIVACY } = await load() const digest = createHash('sha256').update(JSON.stringify({ LEGAL_VERSION, TERMS, PRIVACY })).digest('hex') - t.is(digest, 'ff8c9d0e4077049a6f46fe9873ae5d8661226ed9918ad5b7c5b3822f1194097b', 'o texto mudou: suba LEGAL_VERSION (e TERMS_VERSION em @varanda/core lib/terms.js) e atualize este digest') + t.is(digest, 'c88c22c2cfad70623f259603754153a48f603913f18ee0af745fe0414ba8eced', 'o texto mudou: suba LEGAL_VERSION (e TERMS_VERSION em @varanda/core lib/terms.js) e atualize este digest') }) test('legal: version 41 describes group and conversation reactions and chat formatting', async (t) => { @@ -893,6 +893,30 @@ test('legal: version 76 describes connected devices and the periodic key change' t.ok(text(TERMS).includes('fica trancado até alguém entrar de novo com a passkey'), 'the disconnected device locks') }) +test('legal: version 77 describes Varandinha', async (t) => { + const { TERMS, PRIVACY } = await load() + const text = (doc) => doc.sections.flatMap(({ paragraphs }) => paragraphs).join(' ') + for (const doc of [TERMS, PRIVACY]) { + t.ok(text(doc).includes('a Varandinha é opcional e começa desligada') || text(doc).includes('A Varandinha é um jogo opcional e começa desligada'), 'optional and off by default') + t.ok(text(doc).includes('a pessoa cuja planta você regou vê o seu nome') || text(doc).includes('A pessoa cuja planta você regou vê o seu nome'), 'the watered person sees the name') + t.ok(text(doc).includes('recompensa sorteada, ranking nem prêmio'), 'no random reward, ranking or prize') + t.ok(text(doc).includes('nenhuma notificação pede para alguém voltar'), 'nothing asks anyone to come back') + t.ok(text(doc).includes('cópias que outras pessoas já buscaram podem continuar'), 'fetched copies may remain') + t.ok(text(doc).includes('Sair apaga só os seus próprios registros: as regas que vizinhos fizeram na sua varanda ficam no diário deles, e só quem regou pode apagá-las.'), 'leaving deletes only the own records') + t.absent(text(doc).includes('\u2014'), 'no em dash') + } + t.ok(text(TERMS).includes('O estado de cada varanda é declarado por quem joga e não é conferido por ninguém.'), 'terms: declared, not verified') + t.ok(text(PRIVACY).includes('O estado do jogo é declarado por cada pessoa e não é conferido'), 'privacy: declared, not verified') + t.ok(text(PRIVACY).includes('e fica sabendo qual varanda o seu aparelho abre'), 'privacy: the seeder sees which balcony is opened') + t.ok(text(PRIVACY).includes('sem guardar planta nem nome'), 'privacy: pointers only') + t.ok(text(PRIVACY).includes('A cada nova rega, o app marca como apagadas até sete das suas regas com mais de cerca de três dias; as que sobrarem continuam públicas até as regas seguintes ou até você sair.'), 'privacy: each watering prunes at most seven helps older than about three days') + t.ok(text(TERMS).includes('deixa no seu diário um registro público de que o jogo foi desligado'), 'terms: leaving keeps a public off flag') + t.ok(text(PRIVACY).includes('deixa no diário o registro público de desligado'), 'privacy: leaving keeps a public off flag') + t.ok(text(PRIVACY).includes('inclusive as regas que você deu'), 'privacy: leaving deletes the given helps') + const visitas = text(PRIVACY).indexOf('No app instalado e na versão web hospedada, Visitas é opcional') + t.ok(visitas >= 0 && text(PRIVACY).indexOf('No app instalado e na versão web hospedada, a Varandinha') > visitas, 'privacy: after the Visitas paragraph') +}) + test('legal: version 73 keeps the one-time notes from repeating on another device', async (t) => { const { TERMS, PRIVACY } = await load() const text = (doc) => doc.sections.flatMap(({ paragraphs }) => paragraphs).join(' ') diff --git a/apps/app/test/nav.test.js b/apps/app/test/nav.test.js index 9833a119e..3157b10a0 100644 --- a/apps/app/test/nav.test.js +++ b/apps/app/test/nav.test.js @@ -249,7 +249,7 @@ test('grupo and comunidade are keyed by a lowercase hex64 root key', async (t) = for (const key of [undefined, null, '', 'ceu', A.toUpperCase(), A + ':1']) t.absent(validEntry({ screen: 'fas', key }), String(key)) t.ok(validEntry({ screen: 'melhores-amigos' })) t.absent(validEntry({ screen: 'melhores-amigos', key: A })) - t.alike(SCREENS, ['conversa', 'membro', 'curtidas', 'citacoes', 'grupo', 'comunidade', 'comunidade-info', 'mensagem', 'seguindo', 'seguidores', 'paginas', 'novapagina', 'paginaajustes', 'comunidades', 'pedidos', 'anuncio', 'anunciar', 'editar-anuncio', 'avaliar', 'anuncios', 'depoimentos', 'momentos', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'topico', 'eventos', 'visitas']) + t.alike(SCREENS, ['conversa', 'membro', 'curtidas', 'citacoes', 'grupo', 'comunidade', 'comunidade-info', 'mensagem', 'seguindo', 'seguidores', 'paginas', 'novapagina', 'paginaajustes', 'comunidades', 'pedidos', 'anuncio', 'anunciar', 'editar-anuncio', 'avaliar', 'anuncios', 'depoimentos', 'momentos', 'salvos', 'assunto', 'recados', 'fas', 'melhores-amigos', 'topico', 'eventos', 'visitas', 'varandinha', 'varandinha-rua']) t.absent(validEntry({ screen: 'cadeira', key: A })) t.ok(SCREENS.includes('comunidade')) for (const screen of ['grupo', 'comunidade', 'comunidade-info']) { @@ -386,7 +386,7 @@ test('momentos is keyed by a lowercase hex64 author', async (t) => { test('popTo drops back to an index and refuses bounds outside the stack', async (t) => { const { EMPTY, MAX_DEPTH, SCREENS, push, pop, popTo, top } = await loadNav() t.is(MAX_DEPTH, 20) - t.is(SCREENS.length, 30, 'popTo adds no screen id') + t.is(SCREENS.length, 32, 'popTo adds no screen id') let stack = EMPTY for (let i = 1; i <= 4; i++) stack = push(stack, { screen: 'conversa', key: A + ':' + i }) t.is(popTo(stack, 3), stack, 'the top index is a no-op') @@ -524,6 +524,18 @@ test('visitas takes no key', async (t) => { t.is(top(push(EMPTY, { screen: 'visitas' })).screen, 'visitas') }) +test('varandinha is keyed by the balcony owner hex64 and varandinha-rua takes no key', async (t) => { + const { EMPTY, SCREENS, push, top, validEntry } = await loadNav() + t.ok(SCREENS.includes('varandinha')) + t.ok(SCREENS.includes('varandinha-rua')) + t.ok(validEntry({ screen: 'varandinha', key: A })) + for (const key of [undefined, null, '', 'ceu', A.toUpperCase(), A + ':1', 42]) t.absent(validEntry({ screen: 'varandinha', key }), String(key)) + t.is(push(EMPTY, { screen: 'varandinha', key: 'ceu' }), EMPTY) + t.ok(validEntry({ screen: 'varandinha-rua' })) + t.absent(validEntry({ screen: 'varandinha-rua', key: A })) + t.is(top(push(EMPTY, { screen: 'varandinha-rua' })).screen, 'varandinha-rua') +}) + test('an old key list and thread carry a valid oldPage only', async (t) => { const { EMPTY, push, top, depth, validEntry } = await loadNav() t.ok(validEntry({ screen: 'pedidos' })) diff --git a/apps/app/test/tabBar.test.js b/apps/app/test/tabBar.test.js index 5b2fc3e7c..53d166fd6 100644 --- a/apps/app/test/tabBar.test.js +++ b/apps/app/test/tabBar.test.js @@ -51,6 +51,13 @@ test('showPostButton: no "publicar" on Feira nor on its screens', async (t) => { } }) +test('showPostButton: no "publicar" on the Varandinha screens', async (t) => { + const { showPostButton } = await load() + for (const screen of ['varandinha', 'varandinha-rua']) { + for (const tab of ['rua', 'diario', 'busca']) t.absent(showPostButton({ tab, screen }), screen + ' on ' + tab) + } +}) + test('showPostButton: no "publicar" on an Assunto page', async (t) => { const { showPostButton } = await load() for (const tab of ['rua', 'diario', 'busca']) t.absent(showPostButton({ tab, screen: 'assunto' }), tab) diff --git a/apps/app/test/vitrine.test.js b/apps/app/test/vitrine.test.js index ce4821356..b04dde232 100644 --- a/apps/app/test/vitrine.test.js +++ b/apps/app/test/vitrine.test.js @@ -1905,6 +1905,16 @@ test('garden.state answers the seeded balcony of Lia, with the helps she gave to for (const e of records3) t.ok(f.diaryRecords.some((x) => x.author === e.author && x.record.type === 'follow' && x.record.key === f.own && x.record.on === true), 'the helper follows Lia') }) +test('garden.state answers on the demo clock whatever options.clock says, as diary.peek does', async (t) => { + const { fixtures: f, request, createVitrineRequest } = await load() + const plain = await answer(t, request, 'garden.state', {}) + const moved = await answer(t, createVitrineRequest(f, { clock: () => Date.parse(f.now) + 12 * 86400000 }), 'garden.state', {}) + t.alike(moved, plain, 'the device clock moves no garden date') + const peek = await answer(t, request, 'diary.peek', { author: f.own, seqs: [plain.state.seq], profileSeq: 1, usernameSeq: 2 }) + t.alike(peek.entries[0].record.pots, plain.state.pots, 'the pots match the peeked block') + t.is(peek.entries[0].record.at, plain.state.at) +}) + test('garden.play saves a valid plant act as a new state and refuses an invalid one without change', async (t) => { const { request } = await load() const call = (method, params) => answer(t, request, method, params) diff --git a/apps/app/test/vitrineGuard.test.js b/apps/app/test/vitrineGuard.test.js index e65fedef9..4d22afcca 100644 --- a/apps/app/test/vitrineGuard.test.js +++ b/apps/app/test/vitrineGuard.test.js @@ -1,6 +1,7 @@ // The Vitrine's fixtures stand in for the node only in a development bundle // with the opt-in env var: the provider, the account calls and the terms -// stores, push hook and index client are the only way in, all behind vitrineEnabled. +// stores, push hook, index client and garden clock are the only way in, all +// behind vitrineEnabled. 'use strict' const test = require('brittle') @@ -12,7 +13,7 @@ const SRC = path.join(APP, 'src') const VITRINE_DIR = path.join(SRC, 'vitrine') // src/client/connect.web.js only reads enabled.js, so the Vitrine page skips // the browser node script it would otherwise preload. -const ALLOWED = ['src/node.js', 'src/account.js', 'src/termsStore.web.js', 'src/termsStore.native.js', 'src/usePush.web.js', 'src/indexClient.js', 'src/client/connect.web.js', 'src/media/fetch.js'] +const ALLOWED = ['src/node.js', 'src/account.js', 'src/termsStore.web.js', 'src/termsStore.native.js', 'src/usePush.web.js', 'src/indexClient.js', 'src/client/connect.web.js', 'src/media/fetch.js', 'src/gardenClock.js'] const TERMS_STORES = ['src/termsStore.web.js', 'src/termsStore.native.js'] const IMPORT_RE = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)(['"])([^'"]*vitrine\/[^'"]*)\1/g const GUARD_RE = /const VITRINE = vitrineEnabled\(\{ EXPO_PUBLIC_VARANDA_VITRINE: process\.env\.EXPO_PUBLIC_VARANDA_VITRINE \}, typeof __DEV__ !== 'undefined' && __DEV__\)/ @@ -77,7 +78,7 @@ test('vitrineEnabled needs a development bundle and the exact opt-in', async (t) t.is(vitrineEnabled(undefined, true), false) }) -test('only the node, account, terms stores, push hook and index client import src/vitrine', (t) => { +test('only the node, account, terms stores, push hook, index client and garden clock import src/vitrine', (t) => { const importers = [] for (const file of appSources()) { const code = withoutComments(fs.readFileSync(file, 'utf8')) diff --git a/apps/site/public/privacidade/index.html b/apps/site/public/privacidade/index.html index b21ab2608..acc57d880 100644 --- a/apps/site/public/privacidade/index.html +++ b/apps/site/public/privacidade/index.html @@ -7,7 +7,7 @@ Varanda: Política de Privacidade - + @@ -27,8 +27,8 @@

Política de Privacidade

- - + +