Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import sfetch from './assets/utils/sfetch';
import { useToast } from './composables/useToast';
import TopBar from './components/layout/topBar.vue';
import useSecurePeer from './composables/useSecurePeer';
import useAppPresence from './composables/useAppPresence';
import CallOverlay from './components/peer/CallOverlay.vue';
import waitFor from './assets/utils/waitfor';
import Popup from './components/Popup.vue';
Expand Down Expand Up @@ -258,6 +259,7 @@ const finishAuthInit = async () => {
await init.run();
await waitFor(() => user.value !== null);
await initPeer();
useAppPresence();
};

const handleTauriLogin = async () => {
Expand Down
17 changes: 12 additions & 5 deletions src/components/common/MentionsList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,34 @@
index === activeIndex ? 'bg-(--primary)/20 text-(--primary)' : 'hover:bg-white/5'
]"
>
<div class="w-6 h-6 rounded-full bg-white/10 flex items-center justify-center font-bold text-xs">
<div
v-if="user.special"
class="w-6 h-6 rounded-full bg-(--primary)/20 text-(--primary) flex items-center justify-center text-xs shrink-0"
>
<i class="bi" :class="user.special === 'everyone' ? 'bi-megaphone-fill' : 'bi-broadcast'" />
</div>
<div v-else class="w-6 h-6 rounded-full bg-white/10 flex items-center justify-center font-bold text-xs shrink-0">
{{ $p(user.name).charAt(0).toUpperCase() }}
</div>
<div class="flex flex-col min-w-0">
<span class="truncate">{{ $p(user.name) }}</span>
<span v-if="user.pseudo" class="text-xs text-(--primary) truncate">@{{ user.pseudo }}</span>
</div>
</button>

</div>

</template>

<script setup lang="ts">

import { computed } from 'vue';
import type { MentionEntry } from '@/composables/useMentions';

const props = defineProps<{
isOpen: boolean;
searchQuery: string;
users: Array<{ id: string; name: string; pseudo?: string }>;
users: MentionEntry[];
activeIndex: number;
}>();

Expand All @@ -47,8 +54,8 @@ defineEmits(['select']);
const filteredUsers = computed(() => {
if (!props.searchQuery) return props.users;
const query = props.searchQuery.toLowerCase();
return props.users.filter(u =>
u.name.toLowerCase().includes(query) ||
return props.users.filter(u =>
u.name.toLowerCase().includes(query) ||
(u.pseudo && u.pseudo.toLowerCase().includes(query))
);
});
Expand Down
265 changes: 231 additions & 34 deletions src/components/windows/UserSettings.vue

Large diffs are not rendered by default.

51 changes: 51 additions & 0 deletions src/composables/useAppPresence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Capacitor } from '@capacitor/core';
import { App } from '@capacitor/app';
import useWSocket from '@/composables/useWSocket';

// How long the mobile app can sit in the background before we tell the
// server to show the user as "Absent" (idle). A quick app-switch (checking
// a notification, answering a call) shouldn't flip the status.
const BACKGROUND_IDLE_DELAY_MS = 60_000;

let started = false;
let backgroundTimer: ReturnType<typeof setTimeout> | null = null;
let wentIdle = false;

const clearBackgroundTimer = () => {
if (backgroundTimer) {
clearTimeout(backgroundTimer);
backgroundTimer = null;
}
};

// Starts listening for the app going to/returning from the background on
// native platforms (Android/iOS). A no-op on web/Tauri, and a no-op if
// called more than once. Only affects the live status when the user's
// manual preference is "online" — a manual dnd/idle/offline is never
// overridden (enforced server-side, see synco_api services/presence.ts).
const useAppPresence = () => {
if (started || !Capacitor.isNativePlatform()) return;
started = true;

App.addListener('appStateChange', async ({ isActive }) => {
if (isActive) {
clearBackgroundTimer();
if (wentIdle) {
wentIdle = false;
const socket = await useWSocket();
socket.value?.emit('presence:foreground');
}
return;
}

clearBackgroundTimer();
backgroundTimer = setTimeout(async () => {
backgroundTimer = null;
wentIdle = true;
const socket = await useWSocket();
socket.value?.emit('presence:background');
}, BACKGROUND_IDLE_DELAY_MS);
});
};

export default useAppPresence;
185 changes: 185 additions & 0 deletions src/composables/useMentions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import type { OrgMember, User } from '@/types/types';

// Matches "@token" where token can contain letters, digits, underscores, hyphens and dots
// (same charset the composer's autocomplete uses when inserting a mention).
export const MENTION_TOKEN_REGEX = /@([a-zA-Z0-9_\-.]+)/g;

export interface MentionEntry {
id: string;
name: string;
pseudo?: string;
special?: 'everyone' | 'here';
}

export type MentionTarget =
| { type: 'everyone' }
| { type: 'here' }
| { type: 'user'; user: User };

export interface MentionLookup {
// token (lowercased pseudo/name, or "everyone"/"here") -> resolved target
byToken: Map<string, MentionTarget>;
// userId -> User, for resolving a click back to a profile
usersById: Map<string, User>;
}

const normalize = (s: string) => s.trim().toLowerCase();

// Special entries always offered first in the autocomplete list, on top of real members.
export const buildMentionableList = (members: OrgMember[] | undefined): MentionEntry[] => {

const everyone: MentionEntry = { id: '__everyone__', name: 'Tout le monde', pseudo: 'everyone', special: 'everyone' };
const here: MentionEntry = { id: '__here__', name: 'Membres en ligne', pseudo: 'here', special: 'here' };

const users: MentionEntry[] = (members || [])
.filter(m => m.user)
.map(m => ({ id: m.user!.id, name: m.user!.name, pseudo: m.user!.pseudo }));

return [everyone, here, ...users];

};

// A mention only "counts" (gets highlighted, becomes clickable, can tag the reader) if its
// token resolves to a real member or one of the two special tokens — typing "@anything" that
// doesn't match anyone must render as plain text, not as a fake mention.
export const buildMentionLookup = (members: OrgMember[] | undefined): MentionLookup => {

const byToken = new Map<string, MentionTarget>();
const usersById = new Map<string, User>();

byToken.set('everyone', { type: 'everyone' });
byToken.set('here', { type: 'here' });

for (const m of members || []) {

if (!m.user) continue;

usersById.set(m.user.id, m.user);
const target: MentionTarget = { type: 'user', user: m.user };

if (m.user.pseudo) byToken.set(normalize(m.user.pseudo), target);
if (m.user.name) byToken.set(normalize(m.user.name.replace(/\s+/g, '')), target);

}

return { byToken, usersById };

};

export const extractMentionTokens = (content: string | undefined | null): string[] => {

if (!content) return [];

const tokens: string[] = [];
for (const match of content.matchAll(MENTION_TOKEN_REGEX)) {
if (match[1]) tokens.push(normalize(match[1]));
}

return tokens;

};

// Is `currentUser` targeted by a mention in `content`? Covers @everyone, @here (only while
// online) and a direct @pseudo/@name mention.
export const isUserMentioned = (
content: string | undefined | null,
currentUser: User | null | undefined,
lookup: MentionLookup
): boolean => {

if (!content || !currentUser) return false;

for (const token of extractMentionTokens(content)) {

const target = lookup.byToken.get(token);
if (!target) continue;

if (target.type === 'everyone') return true;
if (target.type === 'here' && currentUser.data?.status === 'online') return true;
if (target.type === 'user' && target.user.id === currentUser.id) return true;

}

return false;

};

const escapeHtml = (s: string): string =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

// Walks the text nodes under `root` and wraps only the tokens that resolve through `lookup`
// in a clickable ".mention-tag" span. Anything else stays as plain text.
//
// The text is HTML-escaped before being written back via innerHTML — none of the mention
// token characters (a-zA-Z0-9_-.) are affected by escaping, so match positions are unchanged,
// but a literal "<"/"&" typed in the message can no longer be reinterpreted as markup.
export const renderMentions = (root: HTMLElement, lookup: MentionLookup) => {

const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
if (node.parentElement?.classList.contains('mention-tag')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);

let node: Node | null;
const nodesToReplace: { oldNode: ChildNode; newNode: HTMLElement }[] = [];

while ((node = walker.nextNode())) {

const text = node.textContent || '';
if (!text.includes('@')) continue;

let hasMatch = false;

const html = escapeHtml(text).replace(MENTION_TOKEN_REGEX, (full, rawToken: string) => {

const target = lookup.byToken.get(normalize(rawToken));
if (!target) return full;

hasMatch = true;
const id = target.type === 'user' ? target.user.id : target.type;

return `<span class="mention-tag" data-mention-kind="${target.type}" data-mention-id="${id}">@${rawToken}</span>`;

});

if (hasMatch) {
const span = document.createElement('span');
span.innerHTML = html;
nodesToReplace.push({ oldNode: node as ChildNode, newNode: span });
}

}

nodesToReplace.forEach(({ oldNode, newNode }) => {
oldNode.parentNode?.replaceChild(newNode, oldNode);
});

};

// Delegated click handler: pass the click event from anywhere inside the rendered message,
// resolves it to the concrete user (if any) and hands it to `onUser`.
export const handleMentionClick = (
event: MouseEvent,
lookup: MentionLookup,
onUser: (user: User, event: MouseEvent) => void
) => {

const el = (event.target as HTMLElement)?.closest?.('.mention-tag') as HTMLElement | null;
if (!el) return;

const kind = el.dataset.mentionKind;
const id = el.dataset.mentionId;
if (kind !== 'user' || !id) return;

const user = lookup.usersById.get(id);
if (user) onUser(user, event);

};
2 changes: 2 additions & 0 deletions src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export interface User {
id: string;
email: string;
name: string;
firstName?: string;
lastName?: string;
pseudo?: string;
avatarUrl?: string;
job?: string;
Expand Down
26 changes: 23 additions & 3 deletions src/views/OrgSpace/OrgLayout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -592,10 +592,30 @@ onMounted(async () => {
});

onBeforeUnmount(async () => {
// The socket is an app-wide singleton (see useWSocket.ts) shared with
// other features (DMs, notifications, calls) — it must stay connected
// across ordinary in-app navigation. Only the listeners registered by
// this component in initSocketListener() are torn down here; the
// connection itself is only ever closed on logout or app close.
const socket = await useWSocket();
socket.value?.off('user-status-changed');
socket.value?.disconnect();
socket.value = null;
[
'member:new',
'member:kicked',
'user-status-changed',
'user-data-updated',
'key-requested',
'todo-added',
'space:updated',
'org-data-updated',
'category-updated',
'categories-updated',
'notif:new-message',
'notif:dm:new-message',
'privateMeet:incomingCall',
'thread:created',
'thread:updated',
'thread:deleted',
].forEach(event => socket.value?.off(event));
})

</script>
Expand Down
Loading
Loading