Refactor synchronization logic

This commit is contained in:
Jon Staab
2025-10-06 11:23:19 -07:00
committed by hodlbod
parent d0491ed202
commit e0099141aa
17 changed files with 357 additions and 375 deletions
+10 -15
View File
@@ -1,7 +1,8 @@
<script lang="ts"> <script lang="ts">
import {onMount} from "svelte" import {onMount} from "svelte"
import {derived} from "svelte/store"
import {displayRelayUrl, getTagValue, EVENT_TIME, ZAP_GOAL, THREAD} from "@welshman/util" import {displayRelayUrl, getTagValue, EVENT_TIME, ZAP_GOAL, THREAD} from "@welshman/util"
import {deriveRelay, repository} from "@welshman/app" import {deriveRelay} from "@welshman/app"
import {fly} from "@lib/transition" import {fly} from "@lib/transition"
import AltArrowDown from "@assets/icons/alt-arrow-down.svg?dataurl" import AltArrowDown from "@assets/icons/alt-arrow-down.svg?dataurl"
import RemoteControllerMinimalistic from "@assets/icons/remote-controller-minimalistic.svg?dataurl" import RemoteControllerMinimalistic from "@assets/icons/remote-controller-minimalistic.svg?dataurl"
@@ -36,12 +37,13 @@
import MenuSpaceRoomItem from "@app/components/MenuSpaceRoomItem.svelte" import MenuSpaceRoomItem from "@app/components/MenuSpaceRoomItem.svelte"
import { import {
ENABLE_ZAPS, ENABLE_ZAPS,
MESSAGE_FILTER,
userRoomsByUrl, userRoomsByUrl,
hasMembershipUrl, hasMembershipUrl,
memberships, memberships,
deriveEventsForUrl,
deriveUserRooms, deriveUserRooms,
deriveOtherRooms, deriveOtherRooms,
trackerStore,
hasNip29, hasNip29,
alerts, alerts,
deriveUserCanCreateRoom, deriveUserCanCreateRoom,
@@ -62,16 +64,9 @@
const owner = $derived($relay?.profile?.pubkey) const owner = $derived($relay?.profile?.pubkey)
const hasAlerts = $derived($alerts.some(a => getTagValue("feed", a.tags)?.includes(url))) const hasAlerts = $derived($alerts.some(a => getTagValue("feed", a.tags)?.includes(url)))
const spaceKinds = $derived( const spaceKinds = derived(
Array.from($trackerStore.getIds(url)).reduce((kinds, id) => { deriveEventsForUrl(url, [MESSAGE_FILTER]),
const event = repository.getEvent(id) $events => new Set($events.map(e => e.kind)),
if (event) {
kinds.add(event.kind)
}
return kinds
}, new Set()),
) )
const openMenu = () => { const openMenu = () => {
@@ -196,7 +191,7 @@
<Icon icon={ChatRound} /> Chat <Icon icon={ChatRound} /> Chat
</SecondaryNavItem> </SecondaryNavItem>
{/if} {/if}
{#if ENABLE_ZAPS && spaceKinds.has(ZAP_GOAL)} {#if ENABLE_ZAPS && $spaceKinds.has(ZAP_GOAL)}
<SecondaryNavItem <SecondaryNavItem
{replaceState} {replaceState}
href={goalsPath} href={goalsPath}
@@ -204,7 +199,7 @@
<Icon icon={StarFallMinimalistic} /> Goals <Icon icon={StarFallMinimalistic} /> Goals
</SecondaryNavItem> </SecondaryNavItem>
{/if} {/if}
{#if spaceKinds.has(THREAD)} {#if $spaceKinds.has(THREAD)}
<SecondaryNavItem <SecondaryNavItem
{replaceState} {replaceState}
href={threadsPath} href={threadsPath}
@@ -212,7 +207,7 @@
<Icon icon={NotesMinimalistic} /> Threads <Icon icon={NotesMinimalistic} /> Threads
</SecondaryNavItem> </SecondaryNavItem>
{/if} {/if}
{#if spaceKinds.has(EVENT_TIME)} {#if $spaceKinds.has(EVENT_TIME)}
<SecondaryNavItem <SecondaryNavItem
{replaceState} {replaceState}
href={calendarPath} href={calendarPath}
+1 -1
View File
@@ -9,7 +9,7 @@
const {url} = $props() const {url} = $props()
const path = makeSpacePath(url) const path = makeSpacePath(url) + ":mobile"
const openMenu = () => pushDrawer(MenuSpace, {url}) const openMenu = () => pushDrawer(MenuSpace, {url})
</script> </script>
@@ -14,11 +14,12 @@
enabled = false enabled = false
} }
}) })
let notificationCount = $state($notifications.size) let notificationCount = $state($notifications.size)
const playSound = () => { const playSound = () => {
if (enabled && $userSettingsValues.play_notification_sound) { if (enabled && $userSettingsValues.play_notification_sound) {
audioElement.play() audioElement?.play()
} }
} }
+3 -3
View File
@@ -5,11 +5,11 @@
import type {Filter} from "@welshman/util" import type {Filter} from "@welshman/util"
import {deriveEvents} from "@welshman/store" import {deriveEvents} from "@welshman/store"
import {formatTimestampRelative} from "@welshman/lib" import {formatTimestampRelative} from "@welshman/lib"
import {NOTE, ROOMS, MESSAGE, THREAD, COMMENT, getRelayTags, getListTags} from "@welshman/util" import {NOTE, ROOMS, COMMENT, getRelayTags, getListTags} from "@welshman/util"
import {repository, loadRelaySelections} from "@welshman/app" import {repository, loadRelaySelections} from "@welshman/app"
import Button from "@lib/components/Button.svelte" import Button from "@lib/components/Button.svelte"
import ProfileSpaces from "@app/components/ProfileSpaces.svelte" import ProfileSpaces from "@app/components/ProfileSpaces.svelte"
import {membershipsByPubkey} from "@app/core/state" import {membershipsByPubkey, MESSAGE_KINDS} from "@app/core/state"
import {goToEvent} from "@app/util/routes" import {goToEvent} from "@app/util/routes"
import {pushModal} from "@app/util/modal" import {pushModal} from "@app/util/modal"
@@ -36,7 +36,7 @@
load({ load({
filters: [ filters: [
{authors: [pubkey], kinds: [ROOMS]}, {authors: [pubkey], kinds: [ROOMS]},
{authors: [pubkey], limit: 1, kinds: [NOTE, MESSAGE, THREAD, COMMENT]}, {authors: [pubkey], limit: 1, kinds: [NOTE, COMMENT, ...MESSAGE_KINDS]},
], ],
relays: Router.get().FromPubkeys([pubkey]).getUrls(), relays: Router.get().FromPubkeys([pubkey]).getUrls(),
}) })
+2 -2
View File
@@ -3,6 +3,7 @@
import type {Snippet} from "svelte" import type {Snippet} from "svelte"
import {groupBy, sum, uniq, uniqBy, batch, displayList} from "@welshman/lib" import {groupBy, sum, uniq, uniqBy, batch, displayList} from "@welshman/lib"
import { import {
REPORT,
REACTION, REACTION,
ZAP_RESPONSE, ZAP_RESPONSE,
getReplyFilters, getReplyFilters,
@@ -10,7 +11,6 @@
getEmojiTag, getEmojiTag,
fromMsats, fromMsats,
getTag, getTag,
REPORT,
DELETE, DELETE,
} from "@welshman/util" } from "@welshman/util"
import type {TrustedEvent, EventContent, Zap} from "@welshman/util" import type {TrustedEvent, EventContent, Zap} from "@welshman/util"
@@ -96,7 +96,7 @@
load({ load({
relays: [url], relays: [url],
signal: controller.signal, signal: controller.signal,
filters: getReplyFilters([event], {kinds: [REPORT, DELETE, ...REACTION_KINDS]}), filters: getReplyFilters([event], {kinds: REACTION_KINDS}),
onEvent: batch(300, (events: TrustedEvent[]) => { onEvent: batch(300, (events: TrustedEvent[]) => {
load({ load({
relays: [url], relays: [url],
+1 -12
View File
@@ -1,8 +1,6 @@
<script module lang="ts"> <script module lang="ts">
import {goto} from "$app/navigation" import {goto} from "$app/navigation"
import {dissoc} from "@welshman/lib" import {dissoc} from "@welshman/lib"
import {ROOM_META} from "@welshman/util"
import {load} from "@welshman/net"
import {pushToast} from "@app/util/toast" import {pushToast} from "@app/util/toast"
import {makeSpacePath} from "@app/util/routes" import {makeSpacePath} from "@app/util/routes"
import {addSpaceMembership, broadcastUserData} from "@app/core/commands" import {addSpaceMembership, broadcastUserData} from "@app/core/commands"
@@ -11,17 +9,8 @@
export const confirmSpaceJoin = async (url: string) => { export const confirmSpaceJoin = async (url: string) => {
await addSpaceMembership(url) await addSpaceMembership(url)
const path = makeSpacePath(url)
if (window.location.pathname === path) {
load({
relays: [url],
filters: [{kinds: [ROOM_META]}],
})
}
broadcastUserData([url]) broadcastUserData([url])
goto(path, {replaceState: true}) goto(makeSpacePath(url), {replaceState: true})
relaysMostlyRestricted.update(dissoc(url)) relaysMostlyRestricted.update(dissoc(url))
pushToast({message: "Welcome to the space!"}) pushToast({message: "Welcome to the space!"})
} }
+45 -124
View File
@@ -1,20 +1,18 @@
import {get, writable} from "svelte/store" import {get, writable} from "svelte/store"
import { import {
partition,
uniq, uniq,
int, int,
YEAR, YEAR,
DAY, DAY,
insertAt, insertAt,
sortBy, sortBy,
assoc,
now, now,
on,
isNotNil, isNotNil,
filterVals, filterVals,
fromPairs, fromPairs,
} from "@welshman/lib" } from "@welshman/lib"
import { import {
DELETE,
EVENT_TIME, EVENT_TIME,
AUTH_INVITE, AUTH_INVITE,
ALERT_EMAIL, ALERT_EMAIL,
@@ -23,7 +21,6 @@ import {
ALERT_ANDROID, ALERT_ANDROID,
ALERT_STATUS, ALERT_STATUS,
matchFilters, matchFilters,
getTagValues,
getTagValue, getTagValue,
getAddress, getAddress,
isShareableRelayUrl, isShareableRelayUrl,
@@ -32,74 +29,37 @@ import {
import type {TrustedEvent, Filter, List} from "@welshman/util" import type {TrustedEvent, Filter, List} from "@welshman/util"
import {feedFromFilters, makeRelayFeed, makeIntersectionFeed} from "@welshman/feeds" import {feedFromFilters, makeRelayFeed, makeIntersectionFeed} from "@welshman/feeds"
import {load, request} from "@welshman/net" import {load, request} from "@welshman/net"
import type {AppSyncOpts, Thunk} from "@welshman/app" import {repository, makeFeedController, loadRelay} from "@welshman/app"
import {
repository,
pull,
hasNegentropy,
thunkQueue,
makeFeedController,
loadRelay,
} from "@welshman/app"
import {createScroller} from "@lib/html" import {createScroller} from "@lib/html"
import {daysBetween} from "@lib/util" import {daysBetween} from "@lib/util"
import {NOTIFIER_RELAY, getUrlsForEvent} from "@app/core/state" import {NOTIFIER_RELAY, getEventsForUrl} from "@app/core/state"
// Utils // Utils
export const pullConservatively = ({relays, filters}: AppSyncOpts) => {
const $getUrlsForEvent = get(getUrlsForEvent)
const [smart, dumb] = partition(hasNegentropy, relays)
const promises = [pull({relays: smart, filters})]
const allEvents = repository.query(filters, {shouldSort: false})
// Since pulling from relays without negentropy is expensive, limit how many
// duplicates we repeatedly download
for (const url of dumb) {
const events = allEvents.filter(e => $getUrlsForEvent(e.id).includes(url))
if (events.length > 100) {
filters = filters.map(assoc("since", events[10]!.created_at))
}
promises.push(pull({relays: [url], filters}))
}
return Promise.all(promises)
}
export const makeFeed = ({ export const makeFeed = ({
relays, url,
feedFilters, filters,
subscriptionFilters,
element, element,
onEvent,
onExhausted, onExhausted,
initialEvents = [],
}: { }: {
relays: string[] url: string
feedFilters: Filter[] filters: Filter[]
subscriptionFilters: Filter[]
element: HTMLElement element: HTMLElement
onEvent?: (event: TrustedEvent) => void
onExhausted?: () => void onExhausted?: () => void
initialEvents?: TrustedEvent[]
}) => { }) => {
const seen = new Set<string>() const initialEvents = getEventsForUrl(url, filters)
const buffer = writable<TrustedEvent[]>([]) const seen = new Set(initialEvents.map(e => e.id))
const events = writable(initialEvents)
const controller = new AbortController() const controller = new AbortController()
const buffer = writable(initialEvents)
const markEvent = (event: TrustedEvent) => { const events = writable<TrustedEvent[]>([])
if (!seen.has(event.id)) {
seen.add(event.id)
onEvent?.(event)
}
}
const insertEvent = (event: TrustedEvent) => { const insertEvent = (event: TrustedEvent) => {
let handled = false let handled = false
if (seen.has(event.id)) {
return
}
events.update($events => { events.update($events => {
for (let i = 0; i < $events.length; i++) { for (let i = 0; i < $events.length; i++) {
if ($events[i].id === event.id) return $events if ($events[i].id === event.id) return $events
@@ -123,47 +83,27 @@ export const makeFeed = ({
}) })
} }
markEvent(event) seen.add(event.id)
} }
const removeEvents = (ids: string[]) => { const unsubscribe = on(repository, "update", ({added, removed}) => {
buffer.update($buffer => $buffer.filter(e => !ids.includes(e.id))) if (removed.size > 0) {
events.update($events => $events.filter(e => !ids.includes(e.id))) buffer.update($buffer => $buffer.filter(e => !removed.has(e.id)))
} events.update($events => $events.filter(e => !removed.has(e.id)))
const handleDelete = (e: TrustedEvent) => removeEvents(getTagValues(["e", "a"], e.tags))
const onThunk = (thunk: Thunk) => {
if (matchFilters(feedFilters, thunk.event)) {
insertEvent(thunk.event)
thunk.controller.signal.addEventListener("abort", () => {
removeEvents([thunk.event.id])
})
} else if (thunk.event.kind === DELETE) {
handleDelete(thunk.event)
} }
}
for (const event of added) {
if (matchFilters(filters, event)) {
insertEvent(event)
}
}
})
const ctrl = makeFeedController({ const ctrl = makeFeedController({
useWindowing: true, useWindowing: true,
feed: makeIntersectionFeed(makeRelayFeed(...relays), feedFromFilters(feedFilters)),
onEvent: insertEvent,
onExhausted,
})
for (const event of initialEvents) {
markEvent(event)
}
request({
relays,
signal: controller.signal, signal: controller.signal,
filters: subscriptionFilters, feed: makeIntersectionFeed(makeRelayFeed(url), feedFromFilters(filters)),
onEvent: (e: TrustedEvent) => { onExhausted,
if (matchFilters(feedFilters, e)) insertEvent(e)
if (e.kind === DELETE) handleDelete(e)
},
}) })
const scroller = createScroller({ const scroller = createScroller({
@@ -173,7 +113,7 @@ export const makeFeed = ({
onScroll: async () => { onScroll: async () => {
const $buffer = get(buffer) const $buffer = get(buffer)
events.update($events => sortBy(e => -e.created_at, [...$events, ...$buffer.splice(0, 100)])) events.update($events => [...$events, ...$buffer.splice(0, 100)])
if ($buffer.length < 100) { if ($buffer.length < 100) {
ctrl.load(100) ctrl.load(100)
@@ -181,8 +121,6 @@ export const makeFeed = ({
}, },
}) })
const unsubscribe = thunkQueue.subscribe(onThunk)
return { return {
events, events,
cleanup: () => { cleanup: () => {
@@ -194,22 +132,19 @@ export const makeFeed = ({
} }
export const makeCalendarFeed = ({ export const makeCalendarFeed = ({
relays, url,
feedFilters, filters,
subscriptionFilters,
element, element,
onExhausted, onExhausted,
initialEvents = [],
}: { }: {
relays: string[] url: string
feedFilters: Filter[] filters: Filter[]
subscriptionFilters: Filter[]
element: HTMLElement element: HTMLElement
onExhausted?: () => void onExhausted?: () => void
initialEvents?: TrustedEvent[]
}) => { }) => {
const interval = int(5, DAY) const interval = int(5, DAY)
const controller = new AbortController() const controller = new AbortController()
const initialEvents = getEventsForUrl(url, filters)
let exhaustedScrollers = 0 let exhaustedScrollers = 0
let backwardWindow = [now() - interval, now()] let backwardWindow = [now() - interval, now()]
@@ -237,38 +172,26 @@ export const makeCalendarFeed = ({
}) })
} }
const removeEvents = (ids: string[]) => { const unsubscribe = on(repository, "update", ({added, removed}) => {
events.update($events => $events.filter(e => !ids.includes(e.id))) if (removed.size > 0) {
} events.update($events => $events.filter(e => !removed.has(e.id)))
const onThunk = (thunk: Thunk) => {
if (matchFilters(feedFilters, thunk.event)) {
insertEvent(thunk.event)
thunk.controller.signal.addEventListener("abort", () => {
removeEvents([thunk.event.id])
})
} }
}
request({ for (const event of added) {
relays, if (matchFilters(filters, event)) {
signal: controller.signal, insertEvent(event)
filters: subscriptionFilters, }
onEvent: (e: TrustedEvent) => { }
if (matchFilters(feedFilters, e)) insertEvent(e)
},
}) })
const loadTimeframe = (since: number, until: number) => { const loadTimeframe = (since: number, until: number) => {
const hashes = daysBetween(since, until).map(String) const hashes = daysBetween(since, until).map(String)
request({ request({
relays, relays: [url],
signal: controller.signal,
autoClose: true, autoClose: true,
signal: controller.signal,
filters: [{kinds: [EVENT_TIME], "#D": hashes}], filters: [{kinds: [EVENT_TIME], "#D": hashes}],
onEvent: insertEvent,
}) })
} }
@@ -311,8 +234,6 @@ export const makeCalendarFeed = ({
}, },
}) })
const unsubscribe = thunkQueue.subscribe(onThunk)
return { return {
events, events,
cleanup: () => { cleanup: () => {
+42 -14
View File
@@ -5,6 +5,7 @@ import * as nip19 from "nostr-tools/nip19"
import { import {
on, on,
call, call,
assoc,
remove, remove,
uniqBy, uniqBy,
sortBy, sortBy,
@@ -38,6 +39,7 @@ import {isKindFeed, findFeed} from "@welshman/feeds"
import { import {
getIdFilters, getIdFilters,
WRAP, WRAP,
DELETE,
CLIENT_AUTH, CLIENT_AUTH,
AUTH_JOIN, AUTH_JOIN,
REACTION, REACTION,
@@ -50,6 +52,7 @@ import {
ROOMS, ROOMS,
THREAD, THREAD,
COMMENT, COMMENT,
REPORT,
ROOM_JOIN, ROOM_JOIN,
ROOM_ADD_USER, ROOM_ADD_USER,
ROOM_REMOVE_USER, ROOM_REMOVE_USER,
@@ -60,6 +63,8 @@ import {
ALERT_ANDROID, ALERT_ANDROID,
ALERT_STATUS, ALERT_STATUS,
APP_DATA, APP_DATA,
ZAP_GOAL,
EVENT_TIME,
getGroupTags, getGroupTags,
getRelayTagValues, getRelayTagValues,
getPubkeyTagValues, getPubkeyTagValues,
@@ -114,8 +119,6 @@ export const PROTECTED = ["-"]
export const ENABLE_ZAPS = Capacitor.getPlatform() != "ios" export const ENABLE_ZAPS = Capacitor.getPlatform() != "ios"
export const REACTION_KINDS = ENABLE_ZAPS ? [REACTION, ZAP_RESPONSE] : [REACTION]
export const NOTIFIER_PUBKEY = import.meta.env.VITE_NOTIFIER_PUBKEY export const NOTIFIER_PUBKEY = import.meta.env.VITE_NOTIFIER_PUBKEY
export const NOTIFIER_RELAY = import.meta.env.VITE_NOTIFIER_RELAY export const NOTIFIER_RELAY = import.meta.env.VITE_NOTIFIER_RELAY
@@ -280,22 +283,27 @@ export const getUrlsForEvent = derived([trackerStore, thunks], ([$tracker, $thun
}) })
export const getEventsForUrl = (url: string, filters: Filter[]) => { export const getEventsForUrl = (url: string, filters: Filter[]) => {
const $getUrlsForEvent = get(getUrlsForEvent) const ids = uniq([
const $events = repository.query(filters) ...tracker.getIds(url),
...Array.from(flattenThunks(Object.values(get(thunks))))
.filter(t => t.options.relays.includes(url))
.map(t => t.event.id),
])
return sortBy( return repository.query(filters.map(assoc("ids", ids)))
e => -e.created_at,
$events.filter(e => $getUrlsForEvent(e.id).includes(url)),
)
} }
export const deriveEventsForUrl = (url: string, filters: Filter[]) => export const deriveEventsForUrl = (url: string, filters: Filter[]) =>
derived([deriveEvents(repository, {filters}), getUrlsForEvent], ([$events, $getUrlsForEvent]) => derived([trackerStore, thunks], ([$tracker, $thunks]) => {
sortBy( const ids = uniq([
e => -e.created_at, ...$tracker.getIds(url),
$events.filter(e => $getUrlsForEvent(e.id).includes(url)), ...Array.from(flattenThunks(Object.values($thunks)))
), .filter(t => t.options.relays.includes(url))
) .map(t => t.event.id),
])
return repository.query(filters.map(assoc("ids", ids)))
})
// Context // Context
@@ -306,6 +314,26 @@ routerContext.getIndexerRelays = always(INDEXER_RELAYS)
netContext.isEventValid = (event: TrustedEvent, url: string) => netContext.isEventValid = (event: TrustedEvent, url: string) =>
getSetting<string[]>("trusted_relays").includes(url) || verifyEvent(event) getSetting<string[]>("trusted_relays").includes(url) || verifyEvent(event)
// Filters
export const makeCommentFilter = (kinds: number[], extra: Filter = {}) => ({
kinds: [COMMENT],
"#K": kinds.map(String),
...extra,
})
export const REACTION_KINDS = [REPORT, DELETE, REACTION]
if (ENABLE_ZAPS) {
REACTION_KINDS.push(ZAP_RESPONSE)
}
export const MESSAGE_KINDS = [ZAP_GOAL, EVENT_TIME, THREAD, MESSAGE]
export const MESSAGE_FILTER = {kinds: MESSAGE_KINDS}
export const COMMENT_FILTER = makeCommentFilter(MESSAGE_KINDS)
// Settings // Settings
export const canDecrypt = synced({ export const canDecrypt = synced({
+163 -31
View File
@@ -1,19 +1,31 @@
import {page} from "$app/stores" import {page} from "$app/stores"
import type {Unsubscriber} from "svelte/store" import type {Unsubscriber} from "svelte/store"
import {derived, get} from "svelte/store" import {derived, get} from "svelte/store"
import {call, chunk, sleep, now, identity, WEEK, ago} from "@welshman/lib" import {
partition,
call,
sortBy,
assoc,
chunk,
sleep,
now,
identity,
WEEK,
MONTH,
ago,
} from "@welshman/lib"
import { import {
getListTags, getListTags,
getRelayTagValues, getRelayTagValues,
WRAP, WRAP,
MESSAGE, ROOM_META,
ZAP_GOAL, ROOM_ADD_USER,
THREAD, ROOM_REMOVE_USER,
EVENT_TIME,
COMMENT,
isSignedEvent, isSignedEvent,
normalizeRelayUrl,
} from "@welshman/util" } from "@welshman/util"
import {request, pull} from "@welshman/net" import type {Filter, TrustedEvent} from "@welshman/util"
import {request, load, pull} from "@welshman/net"
import { import {
pubkey, pubkey,
loadRelay, loadRelay,
@@ -27,17 +39,54 @@ import {
loadMutes, loadMutes,
loadProfile, loadProfile,
repository, repository,
hasNegentropy,
} from "@welshman/app" } from "@welshman/app"
import { import {
MESSAGE_FILTER,
COMMENT_FILTER,
INDEXER_RELAYS, INDEXER_RELAYS,
REACTION_KINDS,
canDecrypt, canDecrypt,
loadSettings, loadSettings,
userMembership, userMembership,
defaultPubkeys, defaultPubkeys,
decodeRelay, decodeRelay,
loadMembership, loadMembership,
getUrlsForEvent,
} from "@app/core/state" } from "@app/core/state"
import {loadAlerts, loadAlertStatuses} from "@app/core/requests" import {loadAlerts, loadAlertStatuses} from "@app/core/requests"
import {hasBlossomSupport} from "@app/core/commands"
// Utils
type PullOpts = {
relays: string[]
filters: Filter[]
signal: AbortSignal
}
const pullConservatively = ({relays, filters, signal}: PullOpts) => {
const $getUrlsForEvent = get(getUrlsForEvent)
const [smart, dumb] = partition(hasNegentropy, relays)
const events = repository.query(filters, {shouldSort: false}).filter(isSignedEvent)
const promises: Promise<TrustedEvent[]>[] = [pull({relays: smart, filters, signal, events})]
// Since pulling from relays without negentropy is expensive, limit how many
// duplicates we repeatedly download
for (const url of dumb) {
const urlEvents = events.filter(e => $getUrlsForEvent(e.id).includes(url))
if (urlEvents.length >= 100) {
filters = filters.map(assoc("since", sortBy(e => -e.created_at, urlEvents)[10]!.created_at))
}
promises.push(load({relays: [url], filters, signal}))
}
return Promise.all(promises)
}
// Relays
const syncRelays = () => { const syncRelays = () => {
for (const url of INDEXER_RELAYS) { for (const url of INDEXER_RELAYS) {
@@ -46,7 +95,10 @@ const syncRelays = () => {
const unsubscribePage = page.subscribe($page => { const unsubscribePage = page.subscribe($page => {
if ($page.params.relay) { if ($page.params.relay) {
loadRelay(decodeRelay($page.params.relay)) const url = decodeRelay($page.params.relay)
loadRelay(url)
hasBlossomSupport(url)
} }
}) })
@@ -62,6 +114,8 @@ const syncRelays = () => {
} }
} }
// User data
const syncUserData = () => { const syncUserData = () => {
const unsubscribePubkey = pubkey.subscribe($pubkey => { const unsubscribePubkey = pubkey.subscribe($pubkey => {
if ($pubkey) { if ($pubkey) {
@@ -107,40 +161,40 @@ const syncUserData = () => {
} }
} }
const syncSpace = (url: string) => { // Memberships
const syncMembership = (url: string) => {
const controller = new AbortController() const controller = new AbortController()
// Load historical data // Load group metadata
pull({ pullConservatively({
relays: [url], relays: [url],
signal: controller.signal, signal: controller.signal,
filters: [{kinds: [ZAP_GOAL, EVENT_TIME, THREAD, MESSAGE, COMMENT]}], filters: [{kinds: [ROOM_META]}],
events: repository
.query([{kinds: [ZAP_GOAL, EVENT_TIME, THREAD, MESSAGE, COMMENT]}])
.filter(isSignedEvent),
}) })
// Load new events // Load historical data from up to a month ago for quick page loading
pullConservatively({
relays: [url],
signal: controller.signal,
filters: [MESSAGE_FILTER, COMMENT_FILTER].map(assoc("since", ago(MONTH))),
})
// Listen for new events
request({ request({
relays: [url], relays: [url],
signal: controller.signal, signal: controller.signal,
filters: [{kinds: [ZAP_GOAL, EVENT_TIME, THREAD, MESSAGE, COMMENT], since: now()}], filters: [MESSAGE_FILTER, COMMENT_FILTER].map(assoc("since", now())),
}) })
return () => controller.abort() return () => controller.abort()
} }
const syncSpaces = () => { const syncMemberships = () => {
const unsubscribersByUrl = new Map<string, Unsubscriber>() const unsubscribersByUrl = new Map<string, Unsubscriber>()
const unsubscribeMembership = userMembership.subscribe($l => {
const urls = getRelayTagValues(getListTags($l))
// Start syncing newly added spaces const unsubscribeMembership = userMembership.subscribe($l => {
for (const url of urls) { const urls = getRelayTagValues(getListTags($l)).map(normalizeRelayUrl)
if (!unsubscribersByUrl.has(url)) {
unsubscribersByUrl.set(url, syncSpace(url))
}
}
// stop syncing removed spaces // stop syncing removed spaces
for (const [url, unsubscribe] of unsubscribersByUrl.entries()) { for (const [url, unsubscribe] of unsubscribersByUrl.entries()) {
@@ -149,6 +203,13 @@ const syncSpaces = () => {
unsubscribe() unsubscribe()
} }
} }
// Start syncing newly added spaces
for (const url of urls) {
if (!unsubscribersByUrl.has(url)) {
unsubscribersByUrl.set(url, syncMembership(url))
}
}
}) })
return () => { return () => {
@@ -157,17 +218,80 @@ const syncSpaces = () => {
} }
} }
// Sync extra stuff for the current space
const syncSpace = (url: string) => {
const $pubkey = pubkey.get()
const controller = new AbortController()
// Load all membership changes for the current user
if ($pubkey) {
pullConservatively({
relays: [url],
signal: controller.signal,
filters: [
{
kinds: [ROOM_ADD_USER, ROOM_REMOVE_USER],
"#p": [$pubkey],
},
],
})
}
// Listen actively for all current membership changes, reports, reactions, zaps, etc
request({
relays: [url],
signal: controller.signal,
filters: [
{
kinds: [ROOM_ADD_USER, ROOM_REMOVE_USER, ...REACTION_KINDS],
since: now(),
},
],
})
return () => controller.abort()
}
const syncCurrentSpace = () => {
const unsubscribersByUrl = new Map<string, Unsubscriber>()
// Sync the space the user is currently visiting
const unsubscribePage = page.subscribe($page => {
if ($page.params.relay) {
const url = decodeRelay($page.params.relay)
if (!unsubscribersByUrl.has(url)) {
unsubscribersByUrl.set(url, syncSpace(url))
}
for (const [oldUrl, unsubscribe] of unsubscribersByUrl.entries()) {
if (url !== oldUrl) {
unsubscribersByUrl.delete(oldUrl)
unsubscribe()
}
}
} else {
Array.from(unsubscribersByUrl.values()).forEach(call)
}
})
return () => {
Array.from(unsubscribersByUrl.values()).forEach(call)
unsubscribePage()
}
}
// DMs
const syncDMRelay = (url: string, pubkey: string) => { const syncDMRelay = (url: string, pubkey: string) => {
const controller = new AbortController() const controller = new AbortController()
// Load historical data // Load historical data
pull({ pullConservatively({
relays: [url], relays: [url],
signal: controller.signal, signal: controller.signal,
filters: [{kinds: [WRAP], "#p": [pubkey], until: ago(WEEK, 2)}], filters: [{kinds: [WRAP], "#p": [pubkey], until: ago(WEEK, 2)}],
events: repository
.query([{kinds: [ZAP_GOAL, EVENT_TIME, THREAD, MESSAGE, COMMENT]}])
.filter(isSignedEvent),
}) })
// Load new events // Load new events
@@ -243,8 +367,16 @@ const syncDMs = () => {
} }
} }
// Merge all synchronization functions
export const syncApplicationData = () => { export const syncApplicationData = () => {
const unsubscribers = [syncRelays(), syncUserData(), syncSpaces(), syncDMs()] const unsubscribers = [
syncRelays(),
syncUserData(),
syncMemberships(),
syncCurrentSpace(),
syncDMs(),
]
return () => unsubscribers.forEach(call) return () => unsubscribers.forEach(call)
} }
+17
View File
@@ -87,6 +87,7 @@ export const notifications = derived(
for (const [url, rooms] of $userRoomsByUrl.entries()) { for (const [url, rooms] of $userRoomsByUrl.entries()) {
const spacePath = makeSpacePath(url) const spacePath = makeSpacePath(url)
const spacePathMobile = spacePath + ":mobile"
const goalPath = makeGoalPath(url) const goalPath = makeGoalPath(url)
const threadPath = makeThreadPath(url) const threadPath = makeThreadPath(url)
const calendarPath = makeCalendarPath(url) const calendarPath = makeCalendarPath(url)
@@ -104,9 +105,14 @@ export const notifications = derived(
for (const [goalId, [comment]] of commentsByGoalId.entries()) { for (const [goalId, [comment]] of commentsByGoalId.entries()) {
const goalItemPath = makeGoalPath(url, goalId) const goalItemPath = makeGoalPath(url, goalId)
if (hasNotification(spacePathMobile, comment)) {
paths.add(spacePathMobile)
}
if (hasNotification(goalPath, comment)) { if (hasNotification(goalPath, comment)) {
paths.add(goalPath) paths.add(goalPath)
} }
if (hasNotification(goalItemPath, comment)) { if (hasNotification(goalItemPath, comment)) {
paths.add(goalItemPath) paths.add(goalItemPath)
} }
@@ -120,9 +126,14 @@ export const notifications = derived(
for (const [threadId, [comment]] of commentsByThreadId.entries()) { for (const [threadId, [comment]] of commentsByThreadId.entries()) {
const threadItemPath = makeThreadPath(url, threadId) const threadItemPath = makeThreadPath(url, threadId)
if (hasNotification(spacePathMobile, comment)) {
paths.add(spacePathMobile)
}
if (hasNotification(threadPath, comment)) { if (hasNotification(threadPath, comment)) {
paths.add(threadPath) paths.add(threadPath)
} }
if (hasNotification(threadItemPath, comment)) { if (hasNotification(threadItemPath, comment)) {
paths.add(threadItemPath) paths.add(threadItemPath)
} }
@@ -136,6 +147,10 @@ export const notifications = derived(
for (const [eventId, [comment]] of commentsByEventId.entries()) { for (const [eventId, [comment]] of commentsByEventId.entries()) {
const calendarItemPath = makeCalendarPath(url, eventId) const calendarItemPath = makeCalendarPath(url, eventId)
if (hasNotification(spacePathMobile, comment)) {
paths.add(spacePathMobile)
}
if (hasNotification(calendarPath, comment)) { if (hasNotification(calendarPath, comment)) {
paths.add(calendarPath) paths.add(calendarPath)
} }
@@ -153,12 +168,14 @@ export const notifications = derived(
) )
if (hasNotification(roomPath, latestEvent)) { if (hasNotification(roomPath, latestEvent)) {
paths.add(spacePathMobile)
paths.add(spacePath) paths.add(spacePath)
paths.add(roomPath) paths.add(roomPath)
} }
} }
} else { } else {
if (hasNotification(messagesPath, messages[0])) { if (hasNotification(messagesPath, messages[0])) {
paths.add(spacePathMobile)
paths.add(spacePath) paths.add(spacePath)
paths.add(messagesPath) paths.add(messagesPath)
} }
+3 -9
View File
@@ -1,9 +1,7 @@
<script lang="ts"> <script lang="ts">
import type {Snippet} from "svelte" import type {Snippet} from "svelte"
import {page} from "$app/stores" import {page} from "$app/stores"
import {WRAP} from "@welshman/util" import {sleep} from "@welshman/lib"
import {Router} from "@welshman/router"
import {pubkey} from "@welshman/app"
import MenuDots from "@assets/icons/menu-dots.svg?dataurl" import MenuDots from "@assets/icons/menu-dots.svg?dataurl"
import Magnifier from "@assets/icons/magnifier.svg?dataurl" import Magnifier from "@assets/icons/magnifier.svg?dataurl"
import Icon from "@lib/components/Icon.svelte" import Icon from "@lib/components/Icon.svelte"
@@ -16,7 +14,6 @@
import ChatMenu from "@app/components/ChatMenu.svelte" import ChatMenu from "@app/components/ChatMenu.svelte"
import ChatItem from "@app/components/ChatItem.svelte" import ChatItem from "@app/components/ChatItem.svelte"
import {chatSearch} from "@app/core/state" import {chatSearch} from "@app/core/state"
import {pullConservatively} from "@app/core/requests"
import {pushModal} from "@app/util/modal" import {pushModal} from "@app/util/modal"
type Props = { type Props = {
@@ -27,14 +24,11 @@
const openMenu = () => pushModal(ChatMenu) const openMenu = () => pushModal(ChatMenu)
const promise = pullConservatively({
filters: [{kinds: [WRAP], "#p": [$pubkey!]}],
relays: Router.get().UserInbox().getUrls(),
})
let term = $state("") let term = $state("")
const chats = $derived($chatSearch.searchOptions(term)) const chats = $derived($chatSearch.searchOptions(term))
const promise = sleep(10000)
</script> </script>
<SecondaryNav> <SecondaryNav>
+2 -24
View File
@@ -2,8 +2,8 @@
import type {Snippet} from "svelte" import type {Snippet} from "svelte"
import {onMount} from "svelte" import {onMount} from "svelte"
import {page} from "$app/stores" import {page} from "$app/stores"
import {ago, sleep, once, MONTH} from "@welshman/lib" import {sleep, once} from "@welshman/lib"
import {ROOM_META, EVENT_TIME, THREAD, COMMENT, MESSAGE, displayRelayUrl} from "@welshman/util" import {displayRelayUrl} from "@welshman/util"
import {SocketStatus} from "@welshman/net" import {SocketStatus} from "@welshman/net"
import Page from "@lib/components/Page.svelte" import Page from "@lib/components/Page.svelte"
import Dialog from "@lib/components/Dialog.svelte" import Dialog from "@lib/components/Dialog.svelte"
@@ -19,10 +19,7 @@
deriveRelayAuthError, deriveRelayAuthError,
relaysPendingTrust, relaysPendingTrust,
deriveSocket, deriveSocket,
userRoomsByUrl,
} from "@app/core/state" } from "@app/core/state"
import {pullConservatively} from "@app/core/requests"
import {hasBlossomSupport} from "@app/core/commands"
import {notifications} from "@app/util/notifications" import {notifications} from "@app/util/notifications"
type Props = { type Props = {
@@ -33,8 +30,6 @@
const url = decodeRelay($page.params.relay!) const url = decodeRelay($page.params.relay!)
const rooms = Array.from($userRoomsByUrl.get(url) || [])
const socket = deriveSocket(url) const socket = deriveSocket(url)
const authError = deriveRelayAuthError(url) const authError = deriveRelayAuthError(url)
@@ -56,8 +51,6 @@
}) })
onMount(() => { onMount(() => {
const since = ago(MONTH)
sleep(2000).then(() => { sleep(2000).then(() => {
if ($socket.status !== SocketStatus.Open) { if ($socket.status !== SocketStatus.Open) {
pushToast({ pushToast({
@@ -66,21 +59,6 @@
}) })
} }
}) })
// Prime our cache so we can upload images quicker
hasBlossomSupport(url)
// Load group meta, threads, calendar events, comments, and recent messages
// for user rooms to help with a quick page transition
pullConservatively({
relays: [url],
filters: [
{kinds: [ROOM_META]},
{kinds: [THREAD, EVENT_TIME, MESSAGE], since},
{kinds: [COMMENT], "#K": [String(THREAD), String(EVENT_TIME)], since},
...rooms.map(room => ({kinds: [MESSAGE], "#h": [room], since})),
],
})
}) })
</script> </script>
+5 -38
View File
@@ -6,19 +6,8 @@
import type {Readable} from "svelte/store" import type {Readable} from "svelte/store"
import type {MakeNonOptional} from "@welshman/lib" import type {MakeNonOptional} from "@welshman/lib"
import {now, formatTimestampAsDate, ago, MINUTE} from "@welshman/lib" import {now, formatTimestampAsDate, ago, MINUTE} from "@welshman/lib"
import {request} from "@welshman/net"
import type {TrustedEvent, EventContent} from "@welshman/util" import type {TrustedEvent, EventContent} from "@welshman/util"
import { import {makeEvent, makeRoomMeta, MESSAGE} from "@welshman/util"
makeEvent,
makeRoomMeta,
MESSAGE,
DELETE,
THREAD,
EVENT_TIME,
ZAP_GOAL,
ROOM_ADD_USER,
ROOM_REMOVE_USER,
} from "@welshman/util"
import {pubkey, publishThunk, waitForThunkError, joinRoom, leaveRoom} from "@welshman/app" import {pubkey, publishThunk, waitForThunkError, joinRoom, leaveRoom} from "@welshman/app"
import {slide, fade, fly} from "@lib/transition" import {slide, fade, fly} from "@lib/transition"
import Hashtag from "@assets/icons/hashtag.svg?dataurl" import Hashtag from "@assets/icons/hashtag.svg?dataurl"
@@ -43,11 +32,11 @@
userRoomsByUrl, userRoomsByUrl,
userSettingsValues, userSettingsValues,
decodeRelay, decodeRelay,
getEventsForUrl,
deriveUserMembershipStatus, deriveUserMembershipStatus,
deriveChannel, deriveChannel,
MembershipStatus, MembershipStatus,
REACTION_KINDS, PROTECTED,
MESSAGE_KINDS,
} from "@app/core/state" } from "@app/core/state"
import {setChecked, checked} from "@app/util/notifications" import {setChecked, checked} from "@app/util/notifications"
import { import {
@@ -57,7 +46,6 @@
prependParent, prependParent,
publishDelete, publishDelete,
} from "@app/core/commands" } from "@app/core/commands"
import {PROTECTED} from "@app/core/state"
import {makeFeed} from "@app/core/requests" import {makeFeed} from "@app/core/requests"
import {popKey} from "@lib/implicit" import {popKey} from "@lib/implicit"
import {pushToast} from "@app/util/toast" import {pushToast} from "@app/util/toast"
@@ -68,7 +56,6 @@
const lastChecked = $checked[$page.url.pathname] const lastChecked = $checked[$page.url.pathname]
const url = decodeRelay(relay) const url = decodeRelay(relay)
const channel = deriveChannel(url, room) const channel = deriveChannel(url, room)
const filter = {kinds: [MESSAGE, THREAD, EVENT_TIME, ZAP_GOAL], "#h": [room]}
const isFavorite = $derived($userRoomsByUrl.get(url)?.has(room)) const isFavorite = $derived($userRoomsByUrl.get(url)?.has(room))
const shouldProtect = canEnforceNip70(url) const shouldProtect = canEnforceNip70(url)
const membershipStatus = deriveUserMembershipStatus(url, room) const membershipStatus = deriveUserMembershipStatus(url, room)
@@ -267,13 +254,9 @@
cleanup?.() cleanup?.()
const feed = makeFeed({ const feed = makeFeed({
url,
element: element!, element: element!,
relays: [url], filters: [{kinds: MESSAGE_KINDS, "#h": [room]}],
feedFilters: [filter],
subscriptionFilters: [
{kinds: [DELETE, MESSAGE, ...REACTION_KINDS], "#h": [room], since: now()},
],
initialEvents: getEventsForUrl(url, [{...filter, limit: 20}]),
onExhausted: () => { onExhausted: () => {
loadingEvents = false loadingEvents = false
}, },
@@ -301,21 +284,6 @@
} }
onMount(() => { onMount(() => {
const controller = new AbortController()
request({
signal: controller.signal,
relays: [url],
filters: [
{
kinds: [ROOM_ADD_USER, ROOM_REMOVE_USER],
"#p": [$pubkey!],
"#h": [room],
limit: 10,
},
],
})
const observer = new ResizeObserver(() => { const observer = new ResizeObserver(() => {
if (dynamicPadding && chatCompose) { if (dynamicPadding && chatCompose) {
dynamicPadding!.style.minHeight = `${chatCompose!.offsetHeight}px` dynamicPadding!.style.minHeight = `${chatCompose!.offsetHeight}px`
@@ -327,7 +295,6 @@
start() start()
return () => { return () => {
controller.abort()
observer.unobserve(chatCompose!) observer.unobserve(chatCompose!)
observer.unobserve(dynamicPadding!) observer.unobserve(dynamicPadding!)
} }
@@ -5,7 +5,7 @@
import {page} from "$app/stores" import {page} from "$app/stores"
import {now, last, formatTimestampAsDate} from "@welshman/lib" import {now, last, formatTimestampAsDate} from "@welshman/lib"
import type {TrustedEvent} from "@welshman/util" import type {TrustedEvent} from "@welshman/util"
import {DELETE, EVENT_TIME, getTagValue} from "@welshman/util" import {EVENT_TIME, getTagValue} from "@welshman/util"
import {fly} from "@lib/transition" import {fly} from "@lib/transition"
import CalendarMinimalistic from "@assets/icons/calendar-minimalistic.svg?dataurl" import CalendarMinimalistic from "@assets/icons/calendar-minimalistic.svg?dataurl"
import CalendarAdd from "@assets/icons/calendar-add.svg?dataurl" import CalendarAdd from "@assets/icons/calendar-add.svg?dataurl"
@@ -19,7 +19,7 @@
import CalendarEventItem from "@app/components/CalendarEventItem.svelte" import CalendarEventItem from "@app/components/CalendarEventItem.svelte"
import CalendarEventCreate from "@app/components/CalendarEventCreate.svelte" import CalendarEventCreate from "@app/components/CalendarEventCreate.svelte"
import {pushModal} from "@app/util/modal" import {pushModal} from "@app/util/modal"
import {getEventsForUrl, decodeRelay, REACTION_KINDS} from "@app/core/state" import {decodeRelay, makeCommentFilter} from "@app/core/state"
import {makeCalendarFeed} from "@app/core/requests" import {makeCalendarFeed} from "@app/core/requests"
import {setChecked} from "@app/util/notifications" import {setChecked} from "@app/util/notifications"
@@ -31,7 +31,6 @@
let element: HTMLElement | undefined = $state() let element: HTMLElement | undefined = $state()
let loading = $state(true) let loading = $state(true)
let cleanup: () => void
let events: Readable<TrustedEvent[]> = $state(readable([])) let events: Readable<TrustedEvent[]> = $state(readable([]))
type Item = { type Item = {
@@ -96,23 +95,20 @@
}) })
onMount(() => { onMount(() => {
const feedFilters = [{kinds: [EVENT_TIME]}] const feed = makeCalendarFeed({
const subscriptionFilters = [{kinds: [DELETE, EVENT_TIME, ...REACTION_KINDS], since: now()}] url,
;({events, cleanup} = makeCalendarFeed({
element: element!, element: element!,
relays: [url], filters: [{kinds: [EVENT_TIME]}, makeCommentFilter([EVENT_TIME])],
feedFilters,
subscriptionFilters,
initialEvents: getEventsForUrl(url, feedFilters),
onExhausted: () => { onExhausted: () => {
loading = false loading = false
}, },
})) })
events = feed.events
return () => { return () => {
feed.cleanup()
setChecked($page.url.pathname) setChecked($page.url.pathname)
cleanup?.()
} }
}) })
</script> </script>
+11 -23
View File
@@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import {onMount, onDestroy} from "svelte" import {onMount} from "svelte"
import {page} from "$app/stores" import {page} from "$app/stores"
import type {Readable} from "svelte/store" import type {Readable} from "svelte/store"
import {readable} from "svelte/store" import {readable} from "svelte/store"
import {now, formatTimestampAsDate, MINUTE, ago} from "@welshman/lib" import {now, formatTimestampAsDate, MINUTE, ago} from "@welshman/lib"
import type {TrustedEvent, EventContent} from "@welshman/util" import type {TrustedEvent, EventContent} from "@welshman/util"
import {makeEvent, MESSAGE, DELETE, THREAD, EVENT_TIME, ZAP_GOAL} from "@welshman/util" import {makeEvent, MESSAGE} from "@welshman/util"
import {pubkey, publishThunk} from "@welshman/app" import {pubkey, publishThunk} from "@welshman/app"
import {slide, fade, fly} from "@lib/transition" import {slide, fade, fly} from "@lib/transition"
import ChatRound from "@assets/icons/chat-round.svg?dataurl" import ChatRound from "@assets/icons/chat-round.svg?dataurl"
@@ -21,13 +21,7 @@
import ChannelItem from "@app/components/ChannelItem.svelte" import ChannelItem from "@app/components/ChannelItem.svelte"
import ChannelCompose from "@app/components/ChannelCompose.svelte" import ChannelCompose from "@app/components/ChannelCompose.svelte"
import ChannelComposeParent from "@app/components/ChannelComposeParent.svelte" import ChannelComposeParent from "@app/components/ChannelComposeParent.svelte"
import { import {userSettingsValues, decodeRelay, MESSAGE_FILTER, PROTECTED} from "@app/core/state"
userSettingsValues,
decodeRelay,
getEventsForUrl,
PROTECTED,
REACTION_KINDS,
} from "@app/core/state"
import {prependParent, canEnforceNip70, publishDelete} from "@app/core/commands" import {prependParent, canEnforceNip70, publishDelete} from "@app/core/commands"
import {setChecked, checked} from "@app/util/notifications" import {setChecked, checked} from "@app/util/notifications"
import {pushToast} from "@app/util/toast" import {pushToast} from "@app/util/toast"
@@ -38,7 +32,6 @@
const mounted = now() const mounted = now()
const lastChecked = $checked[$page.url.pathname] const lastChecked = $checked[$page.url.pathname]
const url = decodeRelay($page.params.relay!) const url = decodeRelay($page.params.relay!)
const filter = {kinds: [MESSAGE, THREAD, EVENT_TIME, ZAP_GOAL]}
const shouldProtect = canEnforceNip70(url) const shouldProtect = canEnforceNip70(url)
const replyTo = (event: TrustedEvent) => { const replyTo = (event: TrustedEvent) => {
@@ -223,11 +216,9 @@
observer.observe(dynamicPadding!) observer.observe(dynamicPadding!)
const feed = makeFeed({ const feed = makeFeed({
url,
element: element!, element: element!,
relays: [url], filters: [MESSAGE_FILTER],
feedFilters: [filter],
subscriptionFilters: [{kinds: [DELETE, MESSAGE, ...REACTION_KINDS], since: now()}],
initialEvents: getEventsForUrl(url, [{...filter, limit: 20}]),
onExhausted: () => { onExhausted: () => {
loadingEvents = false loadingEvents = false
}, },
@@ -237,20 +228,17 @@
cleanup = feed.cleanup cleanup = feed.cleanup
return () => { return () => {
cleanup()
controller.abort() controller.abort()
observer.unobserve(chatCompose!) observer.unobserve(chatCompose!)
observer.unobserve(dynamicPadding!) observer.unobserve(dynamicPadding!)
// Sveltekit calls onDestroy at the beginning of the page load for some reason
setTimeout(() => {
setChecked($page.url.pathname)
}, 800)
} }
}) })
onDestroy(() => {
cleanup?.()
// Sveltekit calls onDestroy at the beginning of the page load for some reason
setTimeout(() => {
setChecked($page.url.pathname)
}, 800)
})
</script> </script>
<PageBar> <PageBar>
+20 -32
View File
@@ -1,10 +1,11 @@
<script lang="ts"> <script lang="ts">
import {onMount} from "svelte" import {onMount} from "svelte"
import {readable} from "svelte/store"
import type {Readable} from "svelte/store"
import {page} from "$app/stores" import {page} from "$app/stores"
import {sortBy, max, nthEq} from "@welshman/lib" import {sortBy, partition, spec, pushToMapKey, max} from "@welshman/lib"
import type {TrustedEvent} from "@welshman/util" import type {TrustedEvent} from "@welshman/util"
import {ZAP_GOAL, DELETE, COMMENT, getListTags, getPubkeyTagValues} from "@welshman/util" import {ZAP_GOAL, getTagValue} from "@welshman/util"
import {userMutes} from "@welshman/app"
import {fly} from "@lib/transition" import {fly} from "@lib/transition"
import NotesMinimalistic from "@assets/icons/notes-minimalistic.svg?dataurl" import NotesMinimalistic from "@assets/icons/notes-minimalistic.svg?dataurl"
import Icon from "@lib/components/Icon.svelte" import Icon from "@lib/components/Icon.svelte"
@@ -15,61 +16,48 @@
import MenuSpaceButton from "@app/components/MenuSpaceButton.svelte" import MenuSpaceButton from "@app/components/MenuSpaceButton.svelte"
import GoalItem from "@app/components/GoalItem.svelte" import GoalItem from "@app/components/GoalItem.svelte"
import GoalCreate from "@app/components/GoalCreate.svelte" import GoalCreate from "@app/components/GoalCreate.svelte"
import {decodeRelay, getEventsForUrl, REACTION_KINDS} from "@app/core/state" import {decodeRelay, makeCommentFilter} from "@app/core/state"
import {setChecked} from "@app/util/notifications" import {setChecked} from "@app/util/notifications"
import {makeFeed} from "@app/core/requests" import {makeFeed} from "@app/core/requests"
import {pushModal} from "@app/util/modal" import {pushModal} from "@app/util/modal"
const url = decodeRelay($page.params.relay!) const url = decodeRelay($page.params.relay!)
const mutedPubkeys = getPubkeyTagValues(getListTags($userMutes))
const goals: TrustedEvent[] = $state([])
const comments: TrustedEvent[] = $state([])
let loading = $state(true) let loading = $state(true)
let element: HTMLElement | undefined = $state() let element: HTMLElement | undefined = $state()
let events: Readable<TrustedEvent[]> = $state(readable([]))
const createGoal = () => pushModal(GoalCreate, {url}) const createGoal = () => pushModal(GoalCreate, {url})
const events = $derived.by(() => { const items = $derived.by(() => {
const scores = new Map<string, number>() const scores = new Map<string, number[]>()
const [goals, comments] = partition(spec({kind: ZAP_GOAL}), $events)
for (const comment of comments) { for (const comment of comments) {
const id = comment.tags.find(nthEq(0, "E"))?.[1] const id = getTagValue("E", comment.tags)
if (id) { if (id) {
scores.set(id, max([scores.get(id), comment.created_at])) pushToMapKey(scores, id, comment.created_at)
} }
} }
return sortBy(e => -max([scores.get(e.id), e.created_at]), goals) return sortBy(e => -max([...(scores.get(e.id) || []), e.created_at]), goals)
}) })
onMount(() => { onMount(() => {
const {cleanup} = makeFeed({ const feed = makeFeed({
url,
element: element!, element: element!,
relays: [url], filters: [{kinds: [ZAP_GOAL]}, makeCommentFilter([ZAP_GOAL])],
feedFilters: [{kinds: [ZAP_GOAL, COMMENT]}],
subscriptionFilters: [
{kinds: [ZAP_GOAL, DELETE, ...REACTION_KINDS]},
{kinds: [COMMENT], "#K": [String(ZAP_GOAL)]},
],
initialEvents: getEventsForUrl(url, [{kinds: [ZAP_GOAL, COMMENT], limit: 10}]),
onEvent: event => {
if (event.kind === ZAP_GOAL && !mutedPubkeys.includes(event.pubkey)) {
goals.push(event)
}
if (event.kind === COMMENT) {
comments.push(event)
}
},
onExhausted: () => { onExhausted: () => {
loading = false loading = false
}, },
}) })
events = feed.events
return () => { return () => {
cleanup?.() feed.cleanup()
setChecked($page.url.pathname) setChecked($page.url.pathname)
} }
}) })
@@ -96,7 +84,7 @@
</PageBar> </PageBar>
<PageContent bind:element class="flex flex-col gap-2 p-2 pt-4"> <PageContent bind:element class="flex flex-col gap-2 p-2 pt-4">
{#each events as event (event.id)} {#each items as event (event.id)}
<div in:fly> <div in:fly>
<GoalItem {url} event={$state.snapshot(event)} /> <GoalItem {url} event={$state.snapshot(event)} />
</div> </div>
@@ -105,7 +93,7 @@
<Spinner {loading}> <Spinner {loading}>
{#if loading} {#if loading}
Looking for goals... Looking for goals...
{:else if events.length === 0} {:else if items.length === 0}
No goals found. No goals found.
{:else} {:else}
That's all! That's all!
+21 -33
View File
@@ -1,10 +1,11 @@
<script lang="ts"> <script lang="ts">
import {onMount} from "svelte" import {onMount} from "svelte"
import {readable} from "svelte/store"
import type {Readable} from "svelte/store"
import {page} from "$app/stores" import {page} from "$app/stores"
import {sortBy, max, nthEq} from "@welshman/lib" import {sortBy, partition, spec, max, pushToMapKey} from "@welshman/lib"
import type {TrustedEvent} from "@welshman/util" import type {TrustedEvent} from "@welshman/util"
import {THREAD, DELETE, COMMENT, getListTags, getPubkeyTagValues} from "@welshman/util" import {THREAD, getTagValue} from "@welshman/util"
import {userMutes} from "@welshman/app"
import {fly} from "@lib/transition" import {fly} from "@lib/transition"
import NotesMinimalistic from "@assets/icons/notes-minimalistic.svg?dataurl" import NotesMinimalistic from "@assets/icons/notes-minimalistic.svg?dataurl"
import Icon from "@lib/components/Icon.svelte" import Icon from "@lib/components/Icon.svelte"
@@ -15,62 +16,49 @@
import MenuSpaceButton from "@app/components/MenuSpaceButton.svelte" import MenuSpaceButton from "@app/components/MenuSpaceButton.svelte"
import ThreadItem from "@app/components/ThreadItem.svelte" import ThreadItem from "@app/components/ThreadItem.svelte"
import ThreadCreate from "@app/components/ThreadCreate.svelte" import ThreadCreate from "@app/components/ThreadCreate.svelte"
import {decodeRelay, getEventsForUrl} from "@app/core/state" import {decodeRelay} from "@app/core/state"
import {setChecked} from "@app/util/notifications" import {setChecked} from "@app/util/notifications"
import {REACTION_KINDS} from "@app/core/state" import {makeCommentFilter} from "@app/core/state"
import {makeFeed} from "@app/core/requests" import {makeFeed} from "@app/core/requests"
import {pushModal} from "@app/util/modal" import {pushModal} from "@app/util/modal"
const url = decodeRelay($page.params.relay!) const url = decodeRelay($page.params.relay!)
const mutedPubkeys = getPubkeyTagValues(getListTags($userMutes))
const threads: TrustedEvent[] = $state([])
const comments: TrustedEvent[] = $state([])
let loading = $state(true) let loading = $state(true)
let element: HTMLElement | undefined = $state() let element: HTMLElement | undefined = $state()
let events: Readable<TrustedEvent[]> = $state(readable([]))
const createThread = () => pushModal(ThreadCreate, {url}) const createThread = () => pushModal(ThreadCreate, {url})
const events = $derived.by(() => { const items = $derived.by(() => {
const scores = new Map<string, number>() const scores = new Map<string, number[]>()
const [goals, comments] = partition(spec({kind: THREAD}), $events)
for (const comment of comments) { for (const comment of comments) {
const id = comment.tags.find(nthEq(0, "E"))?.[1] const id = getTagValue("E", comment.tags)
if (id) { if (id) {
scores.set(id, max([scores.get(id), comment.created_at])) pushToMapKey(scores, id, comment.created_at)
} }
} }
return sortBy(e => -max([scores.get(e.id), e.created_at]), threads) return sortBy(e => -max([...(scores.get(e.id) || []), e.created_at]), goals)
}) })
onMount(() => { onMount(() => {
const {cleanup} = makeFeed({ const feed = makeFeed({
url,
element: element!, element: element!,
relays: [url], filters: [{kinds: [THREAD]}, makeCommentFilter([THREAD])],
feedFilters: [{kinds: [THREAD, COMMENT]}],
subscriptionFilters: [
{kinds: [THREAD, DELETE, ...REACTION_KINDS]},
{kinds: [COMMENT], "#K": [String(THREAD)]},
],
initialEvents: getEventsForUrl(url, [{kinds: [THREAD, COMMENT], limit: 10}]),
onEvent: event => {
if (event.kind === THREAD && !mutedPubkeys.includes(event.pubkey)) {
threads.push(event)
}
if (event.kind === COMMENT) {
comments.push(event)
}
},
onExhausted: () => { onExhausted: () => {
loading = false loading = false
}, },
}) })
events = feed.events
return () => { return () => {
cleanup?.() feed.cleanup()
setChecked($page.url.pathname) setChecked($page.url.pathname)
} }
}) })
@@ -97,7 +85,7 @@
</PageBar> </PageBar>
<PageContent bind:element class="flex flex-col gap-2 p-2 pt-4"> <PageContent bind:element class="flex flex-col gap-2 p-2 pt-4">
{#each events as event (event.id)} {#each items as event (event.id)}
<div in:fly> <div in:fly>
<ThreadItem {url} event={$state.snapshot(event)} /> <ThreadItem {url} event={$state.snapshot(event)} />
</div> </div>
@@ -106,7 +94,7 @@
<Spinner {loading}> <Spinner {loading}>
{#if loading} {#if loading}
Looking for threads... Looking for threads...
{:else if events.length === 0} {:else if items.length === 0}
No threads found. No threads found.
{:else} {:else}
That's all! That's all!