Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(app): let people preview a community before joining

Hampus1021371cbd52
diff --git a/fluxer_app/src/features/channel/components/InviteEmbed.tsx b/fluxer_app/src/features/channel/components/InviteEmbed.tsx
index 11bd491ee..f058b7066 100644
--- a/fluxer_app/src/features/channel/components/InviteEmbed.tsx
+++ b/fluxer_app/src/features/channel/components/InviteEmbed.tsx
@@ -29,6 +29,7 @@ import {
getGuildInvitePrimaryAction,
isGuildInviteActionDisabled,
} from '@app/features/invite/utils/GuildInviteActionState';
+import {PREVIEW_COMMUNITY_DESCRIPTOR} from '@app/features/invite/utils/InviteMessageDescriptors';
import {
EmbedCard,
EmbedSkeletonButton,
@@ -159,7 +160,14 @@ const InviteEmbedInner = observer(function InviteEmbedInner({
const isGuildInviteType = invite != null && isGuildInvite(invite);
const guildFromInvite = isGuildInviteType ? invite!.guild : null;
const guild = Guilds.getGuild(guildFromInvite?.id ?? '') || guildFromInvite;
- const embedSplash = guild != null ? ('embedSplash' in guild ? guild.embedSplash : guild.embed_splash) : undefined;
+ let embedSplash: string | null | undefined;
+ if (guild == null) {
+ embedSplash = undefined;
+ } else if ('embedSplash' in guild) {
+ embedSplash = guild.embedSplash;
+ } else {
+ embedSplash = guild.embed_splash;
+ }
const splashURL =
guild != null ? AvatarUtils.getGuildEmbedSplashURL({id: guild.id, embedSplash: embedSplash || null}) : null;
const messageViewContext = useMaybeMessageViewContext();
@@ -290,6 +298,8 @@ const InviteEmbedInner = observer(function InviteEmbedInner({
return i18n._(INVITES_DISABLED_DESCRIPTOR);
case GuildInvitePrimaryAction.GoToCommunity:
return i18n._(GO_TO_COMMUNITY_DESCRIPTOR);
+ case GuildInvitePrimaryAction.OpenVisit:
+ return i18n._(PREVIEW_COMMUNITY_DESCRIPTOR);
default:
return i18n._(JOIN_COMMUNITY_DESCRIPTOR);
}
diff --git a/fluxer_app/src/features/discovery/commands/DiscoveryCommands.ts b/fluxer_app/src/features/discovery/commands/DiscoveryCommands.ts
index 15b98bf27..87d0690f0 100644
--- a/fluxer_app/src/features/discovery/commands/DiscoveryCommands.ts
+++ b/fluxer_app/src/features/discovery/commands/DiscoveryCommands.ts
@@ -19,6 +19,7 @@ export interface DiscoveryGuild {
online_count: number;
features: Array<string>;
verification_level: number;
+ visits_enabled?: boolean;
}
type DiscoveryGuildPayload = Omit<DiscoveryGuild, 'banner'> & {banner?: string | null};
diff --git a/fluxer_app/src/features/guild/commands/GuildVisitCommands.ts b/fluxer_app/src/features/guild/commands/GuildVisitCommands.ts
new file mode 100644
index 000000000..218bb3a07
--- /dev/null
+++ b/fluxer_app/src/features/guild/commands/GuildVisitCommands.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Routes} from '@app/app/Routes';
+import {Endpoints} from '@app/features/app/constants/Endpoints';
+import {promptForAccountTier} from '@app/features/auth/utils/AccountTierPrompt';
+import Guilds from '@app/features/guild/state/Guilds';
+import GuildVisits from '@app/features/guild/state/GuildVisits';
+import {isolateBidi} from '@app/features/i18n/utils/BidiIsolate';
+import * as NavigationCommands from '@app/features/navigation/commands/NavigationCommands';
+import SelectedGuild from '@app/features/navigation/state/SelectedGuild';
+import * as RouterUtils from '@app/features/navigation/utils/RouterUtils';
+import {http} from '@app/features/platform/transport/RestTransport';
+import {failureCode, failureMessage} from '@app/features/platform/utils/ResponseInspection';
+import * as ToastCommands from '@app/features/ui/commands/ToastCommands';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import type {GuildVisitStartResponse} from '@fluxer/schema/src/domains/guild/GuildVisitSchemas';
+import {i18n} from '@lingui/core';
+import {msg} from '@lingui/core/macro';
+import {when} from 'mobx';
+
+const VISIT_ENDED_DESCRIPTOR = msg({
+ message: "You're no longer previewing {community}.",
+ comment:
+ 'Quiet toast when the preview of a community ends without the person ending it. community is its name. Previewing means reading before joining.',
+});
+
+const ADULTS_ONLY_COMMUNITY_DESCRIPTOR = msg({
+ message: 'This community is for adults only.',
+ comment: 'Toast when someone who is not an adult tries to join a community marked 18+.',
+});
+const JOIN_FAILED_DESCRIPTOR = msg({
+ message: "Couldn't join this community. Try again in a moment.",
+ comment: 'Toast when joining a community from its preview fails for an unexpected reason.',
+});
+
+const STOP_PREVIEWING_FAILED_DESCRIPTOR = msg({
+ message: "Couldn't stop previewing. Try again in a moment.",
+ comment:
+ 'Toast when ending the preview of a community fails. Previewing means reading a community before joining it.',
+});
+
+const GUILD_ARRIVAL_TIMEOUT_MS = 15_000;
+
+export async function openGuildWhenAvailable(guildId: string, channelId?: string): Promise<void> {
+ const arrived = await when(() => Guilds.getGuild(guildId) != null, {timeout: GUILD_ARRIVAL_TIMEOUT_MS}).then(
+ () => true,
+ () => false,
+ );
+ if (arrived) NavigationCommands.selectChannel(guildId, channelId);
+}
+
+const discoveryVisitsInFlight = new Set<string>();
+
+export async function visitFromDiscovery(guildId: string, fallback: () => void): Promise<void> {
+ if (discoveryVisitsInFlight.has(guildId)) return;
+ discoveryVisitsInFlight.add(guildId);
+ try {
+ const response = await http.post<GuildVisitStartResponse>(Endpoints.DISCOVERY_VISIT(guildId), {body: {}});
+ await openGuildWhenAvailable(response.body.guild_id);
+ } catch (error) {
+ if (failureCode(error) === APIErrorCodes.GUILD_VISIT_AGE_RESTRICTED) {
+ ToastCommands.error(i18n._(ADULTS_ONLY_COMMUNITY_DESCRIPTOR));
+ return;
+ }
+ fallback();
+ } finally {
+ discoveryVisitsInFlight.delete(guildId);
+ }
+}
+
+export async function joinVisitedGuild(guildId: string): Promise<void> {
+ try {
+ await http.post(Endpoints.USER_GUILD_VISIT_JOIN(guildId), {body: {}});
+ await when(() => Guilds.getGuild(guildId)?.visiting !== true, {timeout: GUILD_ARRIVAL_TIMEOUT_MS}).catch(() => {});
+ } catch (error) {
+ if (promptForAccountTier(error, () => void joinVisitedGuild(guildId))) {
+ return;
+ }
+ const code = failureCode(error);
+ if (code === APIErrorCodes.GUILD_VISIT_NOT_FOUND || code === APIErrorCodes.UNKNOWN_INVITE) {
+ showVisitEndedToast(Guilds.getGuild(guildId)?.name ?? '');
+ return;
+ }
+ if (code === APIErrorCodes.GUILD_VISIT_AGE_RESTRICTED) {
+ ToastCommands.error(i18n._(ADULTS_ONLY_COMMUNITY_DESCRIPTOR));
+ return;
+ }
+ ToastCommands.error(failureMessage(error) ?? i18n._(JOIN_FAILED_DESCRIPTOR));
+ }
+}
+
+export function showVisitEndedToast(community: string): void {
+ ToastCommands.createToast({
+ type: 'info',
+ children: i18n._(VISIT_ENDED_DESCRIPTOR, {community: isolateBidi(community)}),
+ });
+}
+
+export async function leaveVisit(guildId: string): Promise<void> {
+ GuildVisits.markEndedByUser(guildId);
+ try {
+ await http.delete(Endpoints.USER_GUILD_VISIT(guildId));
+ } catch {
+ GuildVisits.consumeEndedByUser(guildId);
+ ToastCommands.error(i18n._(STOP_PREVIEWING_FAILED_DESCRIPTOR));
+ return;
+ }
+ if (SelectedGuild.selectedGuildId === guildId) RouterUtils.transitionTo(Routes.ME);
+}
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/index.tsx b/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/index.tsx
index a2a669cc5..a34b6cc50 100644
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/index.tsx
+++ b/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/index.tsx
@@ -9,6 +9,7 @@ import type {
} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/GuildOverviewTypes';
import {BrandingSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/BrandingSection';
import {DefaultNotificationsSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/DefaultNotificationsSection';
+import {GuildVisitsSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/GuildVisitsSection';
import {IdleSettingsSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/IdleSettingsSection';
import {OwnerCrownSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/OwnerCrownSection';
import {SystemWelcomeSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/SystemWelcomeSection';
@@ -148,6 +149,11 @@ const GuildOverviewTab: React.FC<{guildId: string}> = observer(({guildId}) => {
textChannels={textChannels as Array<ChannelLike>}
data-flx="guild.guild-tabs.guild-overview-tab.system-welcome-section"
/>
+ <GuildVisitsSection
+ guildId={guildId}
+ canManageGuild={canManageGuild}
+ data-flx="guild.guild-tabs.guild-overview-tab.guild-visits-section"
+ />
<DefaultNotificationsSection
form={form}
canManageGuild={canManageGuild}
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/GuildVisitsSection.tsx b/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/GuildVisitsSection.tsx
new file mode 100644
index 000000000..451cc1903
--- /dev/null
+++ b/fluxer_app/src/features/guild/components/modals/guild_tabs/guild_overview_tab/sections/GuildVisitsSection.tsx
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import * as GuildCommands from '@app/features/guild/commands/GuildCommands';
+import {SettingsSection} from '@app/features/guild/components/modals/guild_tabs/guild_overview_tab/components/GuildOverviewTabSettingsSection';
+import Guilds from '@app/features/guild/state/Guilds';
+import GuildVisitsRollout from '@app/features/guild/state/GuildVisitsRollout';
+import {Logger} from '@app/features/platform/utils/AppLogger';
+import * as ToastCommands from '@app/features/ui/commands/ToastCommands';
+import {Switch} from '@app/features/ui/components/form/FormSwitch';
+import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
+import {msg} from '@lingui/core/macro';
+import {useLingui} from '@lingui/react/macro';
+import {observer} from 'mobx-react-lite';
+import {useState} from 'react';
+
+const logger = new Logger('GuildVisitsSection');
+
+const VISITORS_TITLE_DESCRIPTOR = msg({
+ message: 'Previewing',
+ context: 'community-previews',
+ comment:
+ 'Heading of the community setting about people previewing the community before they join. Previewing means reading a community before joining it.',
+});
+const LET_PEOPLE_LOOK_AROUND_DESCRIPTOR = msg({
+ message: 'Allow people to preview this community before joining',
+ comment: 'Switch label in community settings. On by default for new communities, owners can turn it off.',
+});
+const LET_PEOPLE_LOOK_AROUND_HELP_DESCRIPTOR = msg({
+ message:
+ "People with an invite link can read the channels @everyone can see before they join. They can't post, react or see the member list.",
+ comment: 'Help text under the switch that lets people preview a community before joining.',
+});
+const UPDATE_FAILED_DESCRIPTOR = msg({
+ message: "Couldn't update this setting. Try again.",
+ comment: 'Error toast when the previews setting could not be saved.',
+});
+
+export const GuildVisitsSection = observer(function GuildVisitsSection({
+ guildId,
+ canManageGuild,
+}: {
+ guildId: string;
+ canManageGuild: boolean;
+}) {
+ const {i18n} = useLingui();
+ const [saving, setSaving] = useState(false);
+ const guild = Guilds.getGuild(guildId);
+ if (!guild || !GuildVisitsRollout.enabled) return null;
+ const enabled = guild.features.has(GuildFeatures.VISITS_ENABLED);
+ const handleChange = async (next: boolean) => {
+ if (saving || !canManageGuild) return;
+ setSaving(true);
+ try {
+ await GuildCommands.toggleFeature(guildId, GuildFeatures.VISITS_ENABLED, next);
+ } catch (error) {
+ logger.error('Failed to toggle visits', error);
+ ToastCommands.error(i18n._(UPDATE_FAILED_DESCRIPTOR));
+ } finally {
+ setSaving(false);
+ }
+ };
+ return (
+ <SettingsSection
+ title={i18n._(VISITORS_TITLE_DESCRIPTOR)}
+ data-flx="guild.guild-tabs.guild-overview-tab.guild-visits-section.settings-section"
+ >
+ <Switch
+ label={i18n._(LET_PEOPLE_LOOK_AROUND_DESCRIPTOR)}
+ description={i18n._(LET_PEOPLE_LOOK_AROUND_HELP_DESCRIPTOR)}
+ value={enabled}
+ onChange={handleChange}
+ disabled={!canManageGuild || saving}
+ data-flx="guild.guild-tabs.guild-overview-tab.guild-visits-section.switch"
+ />
+ </SettingsSection>
+ );
+});
diff --git a/fluxer_app/src/features/guild/components/visits/GuildPreviewNagbar.tsx b/fluxer_app/src/features/guild/components/visits/GuildPreviewNagbar.tsx
new file mode 100644
index 000000000..38235ed04
--- /dev/null
+++ b/fluxer_app/src/features/guild/components/visits/GuildPreviewNagbar.tsx
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Nagbar} from '@app/features/app/components/layout/Nagbar';
+import {NagbarButton} from '@app/features/app/components/layout/NagbarButton';
+import {NagbarContent} from '@app/features/app/components/layout/NagbarContent';
+import {NAGBAR_TONES, NagbarToneKind} from '@app/features/app/components/layout/NagbarTones';
+import {joinVisitedGuild, leaveVisit} from '@app/features/guild/commands/GuildVisitCommands';
+import type {Guild} from '@app/features/guild/models/Guild';
+import {isolateBidi} from '@app/features/i18n/utils/BidiIsolate';
+import {msg} from '@lingui/core/macro';
+import {useLingui} from '@lingui/react/macro';
+import {observer} from 'mobx-react-lite';
+import {useState} from 'react';
+
+const PREVIEWING_DESCRIPTOR = msg({
+ message: "You're previewing {community}.",
+ comment:
+ 'Bar at the top of a community the person is reading without having joined. community is its name. Previewing means reading before joining.',
+});
+export const JOIN_COMMUNITY_DESCRIPTOR = msg({
+ message: 'Join',
+ comment: 'Button that joins the community the person is previewing.',
+});
+export const STOP_PREVIEWING_DESCRIPTOR = msg({
+ message: 'Stop previewing',
+ comment: 'Button or menu item that ends the preview of a community the person has not joined and leaves it.',
+});
+
+const tone = NAGBAR_TONES[NagbarToneKind.BRAND];
+
+export const GuildPreviewNagbar = observer(function GuildPreviewNagbar({
+ guild,
+ isMobile,
+}: {
+ guild: Guild;
+ isMobile: boolean;
+}) {
+ const {i18n} = useLingui();
+ const [pending, setPending] = useState<'join' | 'stop' | null>(null);
+ const run = async (action: 'join' | 'stop') => {
+ if (pending !== null) return;
+ setPending(action);
+ try {
+ await (action === 'join' ? joinVisitedGuild(guild.id) : leaveVisit(guild.id));
+ } finally {
+ setPending(null);
+ }
+ };
+ return (
+ <Nagbar
+ isMobile={isMobile}
+ backgroundColor={tone.backgroundColor}
+ textColor={tone.textColor}
+ data-flx="guild.visits.preview-nagbar"
+ >
+ <NagbarContent
+ isMobile={isMobile}
+ message={i18n._(PREVIEWING_DESCRIPTOR, {community: isolateBidi(guild.name)})}
+ actions={
+ <>
+ <NagbarButton
+ isMobile={isMobile}
+ variant="inverted-outline"
+ onClick={() => void run('stop')}
+ submitting={pending === 'stop'}
+ disabled={pending === 'join'}
+ data-flx="guild.visits.preview-nagbar.button.stop"
+ >
+ {i18n._(STOP_PREVIEWING_DESCRIPTOR)}
+ </NagbarButton>
+ <NagbarButton
+ isMobile={isMobile}
+ onClick={() => void run('join')}
+ submitting={pending === 'join'}
+ disabled={pending === 'stop'}
+ data-flx="guild.visits.preview-nagbar.button.join"
+ >
+ {i18n._(JOIN_COMMUNITY_DESCRIPTOR)}
+ </NagbarButton>
+ </>
+ }
+ data-flx="guild.visits.preview-nagbar.content"
+ />
+ </Nagbar>
+ );
+});
diff --git a/fluxer_app/src/features/guild/events/GuildDelete.ts b/fluxer_app/src/features/guild/events/GuildDelete.ts
index 42e1b5790..49eab7028 100644
--- a/fluxer_app/src/features/guild/events/GuildDelete.ts
+++ b/fluxer_app/src/features/guild/events/GuildDelete.ts
@@ -4,6 +4,7 @@ import Channels from '@app/features/channel/state/Channels';
import Emoji from '@app/features/emoji/state/Emoji';
import Sticker from '@app/features/emoji/state/EmojiSticker';
import type {GatewayHandlerContext} from '@app/features/gateway/events/EventRouter';
+import {showVisitEndedToast} from '@app/features/guild/commands/GuildVisitCommands';
import ChannelMemberCount from '@app/features/guild/state/ChannelMemberCount';
import GuildAvailability from '@app/features/guild/state/GuildAvailability';
import GuildCount from '@app/features/guild/state/GuildCount';
@@ -11,6 +12,7 @@ import GuildList from '@app/features/guild/state/GuildList';
import GuildReadState from '@app/features/guild/state/GuildReadState';
import Guilds from '@app/features/guild/state/Guilds';
import GuildVerification from '@app/features/guild/state/GuildVerification';
+import GuildVisits from '@app/features/guild/state/GuildVisits';
import Invites from '@app/features/invite/state/Invites';
import GuildMembers from '@app/features/member/state/GuildMembers';
import MemberSearch from '@app/features/member/state/MemberSearch';
@@ -34,6 +36,7 @@ export interface GuildDeletePayload {
}
export function handleGuildDelete(data: GuildDeletePayload, _context: GatewayHandlerContext): void {
+ const endedVisit = data.unavailable ? undefined : Guilds.getGuild(data.id);
GuildAvailability.setGuildDegraded(data.id, false);
GuildAvailability.handleGuildAvailability(data.id, data.unavailable, data.unavailable_hidden);
Guilds.handleGuildDelete({guildId: data.id, unavailable: data.unavailable});
@@ -59,4 +62,7 @@ export function handleGuildDelete(data: GuildDeletePayload, _context: GatewayHan
MentionFeed.handleGuildDelete(data.id);
UserProfile.handleGuildDelete(data.unavailable);
QuickSwitcher.recomputeIfOpen();
+ if (endedVisit?.visiting === true && !GuildVisits.consumeEndedByUser(data.id)) {
+ showVisitEndedToast(endedVisit.name);
+ }
}
diff --git a/fluxer_app/src/features/guild/models/Guild.ts b/fluxer_app/src/features/guild/models/Guild.ts
index cbf47b3c7..4866e9f8c 100644
--- a/fluxer_app/src/features/guild/models/Guild.ts
+++ b/fluxer_app/src/features/guild/models/Guild.ts
@@ -63,6 +63,7 @@ export class Guild {
private readonly _disabledOperations: number;
readonly joinedAt: string | null;
readonly unavailable: boolean;
+ readonly visiting: boolean;
readonly messageHistoryCutoff: string | null;
readonly memberCount: number;
@@ -103,6 +104,7 @@ export class Guild {
this.joinedAt = this.normalizeJoinedAt(guild);
this.messageHistoryCutoff = this.normalizeMessageHistoryCutoff(guild);
this.unavailable = guild.unavailable ?? false;
+ this.visiting = guild.visiting === true;
this.memberCount = this.normalizeMemberCount(guild);
}
@@ -284,8 +286,9 @@ export class Guild {
{
...guildData.properties,
roles,
- joined_at: guildData.joined_at,
+ joined_at: guildData.joined_at ?? undefined,
unavailable: guildData.unavailable,
+ visiting: guildData.visiting === true ? true : undefined,
},
{instanceId},
);
@@ -326,6 +329,7 @@ export class Guild {
message_history_cutoff: this.messageHistoryCutoff,
joined_at: this.joinedAt ?? undefined,
unavailable: this.unavailable,
+ visiting: this.visiting ? true : undefined,
member_count: this.memberCount,
roles: Object.values(this.roles).map((role) => role.toJSON()),
};
diff --git a/fluxer_app/src/features/guild/state/GuildList.ts b/fluxer_app/src/features/guild/state/GuildList.ts
index c5e5c5c96..df17165c8 100644
--- a/fluxer_app/src/features/guild/state/GuildList.ts
+++ b/fluxer_app/src/features/guild/state/GuildList.ts
@@ -92,13 +92,18 @@ class GuildList {
return this.computeOrganizedGuildList();
}
+ get visitingGuilds(): Array<Guild> {
+ return this.guilds.filter((guild) => guild.visiting && !guild.unavailable);
+ }
+
getOrganizedGuildList(): Array<OrganizedItem> {
return this.organizedGuildList;
}
private computeOrganizedGuildList(): Array<OrganizedItem> {
const guildFolders = UserSettings.guildFolders;
- const guildMap = new Map(this.guilds.map((guild) => [guild.id, guild]));
+ const memberGuilds = this.guilds.filter((guild) => !guild.visiting);
+ const guildMap = new Map(memberGuilds.map((guild) => [guild.id, guild]));
const result: Array<OrganizedItem> = [];
const placedGuildIds = new Set<string>();
const emittedFolderIds = new Set<number | null>();
@@ -126,7 +131,7 @@ class GuildList {
result.push({type: 'folder', folder, guilds: folderGuilds});
}
}
- const unplacedGuilds = this.guilds.filter((guild) => !placedGuildIds.has(guild.id) && !guild.unavailable);
+ const unplacedGuilds = memberGuilds.filter((guild) => !placedGuildIds.has(guild.id) && !guild.unavailable);
if (unplacedGuilds.length > 0) {
const prefix: Array<OrganizedItem> = new Array(unplacedGuilds.length);
for (let i = 0; i < unplacedGuilds.length; i++) {
diff --git a/fluxer_app/src/features/guild/state/GuildReadState.ts b/fluxer_app/src/features/guild/state/GuildReadState.ts
index 81040b6db..6452cd6de 100644
--- a/fluxer_app/src/features/guild/state/GuildReadState.ts
+++ b/fluxer_app/src/features/guild/state/GuildReadState.ts
@@ -80,6 +80,10 @@ function getThreadContribution(channelId: string): GuildReadStateContribution {
return contribution;
}
+function isVisitingGuildChannel(channel: ContributeChannel): boolean {
+ return channel.guildId != null && Guilds.getGuild(channel.guildId)?.visiting === true;
+}
+
function getChannelContribution(channel: ContributeChannel, channelId: string): GuildReadStateContribution {
if (THREAD_CHANNEL_TYPES.has(channel.type)) {
return getThreadContribution(channelId);
@@ -88,7 +92,8 @@ function getChannelContribution(channel: ContributeChannel, channelId: string):
const mentionCount = ReadStates.getMentionCount(channelId);
const hasUnread = forum ? hasForumUnread(forum) : ReadStates.hasUnread(channelId);
return resolveGuildReadStateContribution({
- isEligibleTextChannel: GUILD_TEXT_BASED_CHANNEL_TYPES.has(channel.type) || forum != null,
+ isEligibleTextChannel:
+ (GUILD_TEXT_BASED_CHANNEL_TYPES.has(channel.type) || forum != null) && !isVisitingGuildChannel(channel),
isPrivate: channel.isPrivate(),
unreadBadgesLevel: resolveUnreadBadgesLevel(channel),
isMutedForUnread: isChannelMutedForUnread(channel),
diff --git a/fluxer_app/src/features/guild/state/GuildVisits.ts b/fluxer_app/src/features/guild/state/GuildVisits.ts
new file mode 100644
index 000000000..8ab193895
--- /dev/null
+++ b/fluxer_app/src/features/guild/state/GuildVisits.ts
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {ResettableStates} from '@app/features/app/state/ResettableStates';
+import GatewaySessions from '@app/features/gateway/transport/GatewaySessionPool';
+import Guilds from '@app/features/guild/state/Guilds';
+import Messages from '@app/features/messaging/state/MessagingMessages';
+import SelectedChannel from '@app/features/navigation/state/SelectedChannel';
+import SelectedGuild from '@app/features/navigation/state/SelectedGuild';
+import {deferUntilModulesLoaded} from '@app/features/platform/utils/DeferUntilModulesLoaded';
+import {compareStructural, reaction} from 'mobx';
+
+interface VisitFocus {
+ readonly guildId: string;
+ readonly channelId: string;
+ readonly sessionId: string;
+}
+
+function resolveVisitFocus(): VisitFocus | null {
+ const guildId = SelectedGuild.selectedGuildId;
+ const sessionId = GatewaySessions.foregroundConnection.sessionId;
+ if (
+ guildId == null ||
+ sessionId == null ||
+ !GatewaySessions.foregroundConnection.isReady ||
+ !(Guilds.getGuild(guildId)?.visiting === true)
+ ) {
+ return null;
+ }
+ const channelId = SelectedChannel.currentChannelId;
+ return channelId == null ? null : {guildId, channelId, sessionId};
+}
+
+class GuildVisits {
+ private readonly endedByUser = new Set<string>();
+ private focusedVisitChannelId: string | null = null;
+ private focusedVisitGuildId: string | null = null;
+
+ constructor() {
+ deferUntilModulesLoaded(() => {
+ reaction(resolveVisitFocus, (focus) => this.handleFocus(focus), {equals: compareStructural});
+ });
+ }
+
+ private handleFocus(focus: VisitFocus | null): void {
+ const previous = this.focusedVisitChannelId;
+ const previousGuildId = this.focusedVisitGuildId;
+ this.focusedVisitChannelId = focus?.channelId ?? null;
+ this.focusedVisitGuildId = focus?.guildId ?? null;
+ if (previous !== null && previous !== this.focusedVisitChannelId) {
+ Messages.forgetUnfocusedVisitChannel(previous);
+ }
+ if (previousGuildId !== null && previousGuildId !== this.focusedVisitGuildId) {
+ this.sendUnfocus(previousGuildId);
+ }
+ this.sendFocus(focus);
+ }
+
+ markEndedByUser(guildId: string): void {
+ this.endedByUser.add(guildId);
+ }
+
+ consumeEndedByUser(guildId: string): boolean {
+ return this.endedByUser.delete(guildId);
+ }
+
+ private sendUnfocus(guildId: string): void {
+ if (Guilds.getGuild(guildId)?.visiting !== true) return;
+ GatewaySessions.foregroundConnection.socket?.updateGuildSubscriptions({
+ subscriptions: {[guildId]: {focused_channel_id: null}},
+ });
+ }
+
+ private sendFocus(focus: VisitFocus | null): void {
+ if (focus === null) return;
+ GatewaySessions.foregroundConnection.socket?.updateGuildSubscriptions({
+ subscriptions: {[focus.guildId]: {active: true, focused_channel_id: focus.channelId}},
+ });
+ }
+
+ reset(): void {
+ this.endedByUser.clear();
+ }
+}
+
+const guildVisits = new GuildVisits();
+
+ResettableStates.register(guildVisits, () => guildVisits.reset());
+
+export default guildVisits;
diff --git a/fluxer_app/src/features/guild/state/GuildVisitsRollout.ts b/fluxer_app/src/features/guild/state/GuildVisitsRollout.ts
new file mode 100644
index 000000000..3c6f49b92
--- /dev/null
+++ b/fluxer_app/src/features/guild/state/GuildVisitsRollout.ts
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import ExperimentAssignments from '@app/features/experiment/state/ExperimentAssignments';
+import SessionManager from '@app/features/platform/state/AuthSession';
+import {INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
+import {makeAutoObservable} from 'mobx';
+
+class GuildVisitsRolloutSelector {
+ constructor() {
+ makeAutoObservable(this, {}, {autoBind: true});
+ }
+
+ get enabled(): boolean {
+ if (
+ ExperimentAssignments.response === INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE ||
+ ExperimentAssignments.ownerId !== SessionManager.userId
+ ) {
+ return false;
+ }
+ return ExperimentAssignments.response.assignments.guild_visits?.enabled === true;
+ }
+}
+
+const GuildVisitsRollout = new GuildVisitsRolloutSelector();
+
+export default GuildVisitsRollout;
diff --git a/fluxer_app/src/features/guild/state/Guilds.ts b/fluxer_app/src/features/guild/state/Guilds.ts
index a2a077920..4b2b7671c 100644
--- a/fluxer_app/src/features/guild/state/Guilds.ts
+++ b/fluxer_app/src/features/guild/state/Guilds.ts
@@ -75,6 +75,7 @@ class Guilds {
this.guilds[guild.id] = new Guild({
...guild,
joined_at: guild.joined_at ?? existingGuild.joinedAt ?? undefined,
+ visiting: existingGuild.visiting ? true : undefined,
roles: existingGuild.roles,
});
}