feat(matrix): add SvelteKit Matrix client (Phase 1)

Implements a minimal self-hosted Matrix chat client with:
- matrix-js-sdk integration with Svelte 5 runes store
- Password login with homeserver discovery
- Room list (DMs and groups) with unread counts
- Message timeline with typing indicators
- Send messages with Enter key
- Responsive chat UI with Tailwind CSS

Project structure:
- apps/matrix/apps/web: SvelteKit client (port 5180)
- apps/matrix/packages/shared: Shared types

Commands: pnpm dev:matrix:web

https://claude.ai/code/session_01RUrt2qN1D3nVh9HcGpwoby
This commit is contained in:
Claude 2026-01-28 20:21:13 +00:00
parent bea066c7f8
commit 4e622a66de
No known key found for this signature in database
36 changed files with 2453 additions and 0 deletions

179
apps/matrix/CLAUDE.md Normal file
View file

@ -0,0 +1,179 @@
# Matrix Client
Self-hosted Matrix chat client built with SvelteKit and matrix-js-sdk.
## Project Overview
A minimal, privacy-focused Matrix client that connects to your self-hosted Synapse server (matrix.mana.how).
### Tech Stack
| Layer | Technology |
|-------|------------|
| Frontend | SvelteKit 2, Svelte 5 (runes), Tailwind CSS 4 |
| Matrix SDK | matrix-js-sdk |
| State Management | Svelte 5 runes ($state, $derived) |
| Icons | lucide-svelte |
| Date Handling | date-fns |
## Project Structure
```
apps/matrix/
├── apps/
│ └── web/ # SvelteKit web client
│ ├── src/
│ │ ├── routes/
│ │ │ ├── (auth)/ # Login flow
│ │ │ ├── (app)/ # Protected chat routes
│ │ │ └── health/ # Health check endpoint
│ │ └── lib/
│ │ ├── matrix/ # Matrix SDK integration
│ │ │ ├── store.svelte.ts # Reactive Matrix store
│ │ │ ├── client.ts # Login/auth functions
│ │ │ ├── types.ts # TypeScript types
│ │ │ └── polyfills.ts # Browser polyfills
│ │ └── components/
│ │ └── chat/ # Chat UI components
│ └── package.json
└── packages/
└── shared/ # Shared types
```
## Development
```bash
# Start the Matrix web client
pnpm dev:matrix:web
# Or from monorepo root
pnpm matrix:dev
```
The client runs on **http://localhost:5180**
## Key Files
### Matrix Store (`src/lib/matrix/store.svelte.ts`)
Central reactive store using Svelte 5 runes:
```typescript
import { matrixStore } from '$lib/matrix';
// State
matrixStore.syncState // 'STOPPED' | 'PREPARED' | 'SYNCING' | etc.
matrixStore.isReady // boolean - client ready for use
matrixStore.rooms // SimpleRoom[] - all rooms
matrixStore.messages // SimpleMessage[] - current room messages
matrixStore.currentRoom // Room | null - selected room
// Actions
await matrixStore.initialize(credentials);
matrixStore.selectRoom(roomId);
await matrixStore.sendMessage('Hello!');
await matrixStore.sendTyping(true);
matrixStore.logout();
```
### Login Client (`src/lib/matrix/client.ts`)
```typescript
import { loginWithPassword, checkHomeserver } from '$lib/matrix';
const result = await loginWithPassword('matrix.mana.how', 'user', 'password');
if (result.success) {
await matrixStore.initialize(result.credentials);
}
```
## Features
### Phase 1 (Current)
- [x] Password login
- [x] Room list (DMs and groups)
- [x] Message timeline
- [x] Send text messages
- [x] Typing indicators
- [x] Read receipts
- [x] Unread counts
- [x] Message pagination (load more)
### Phase 2 (Planned)
- [ ] End-to-end encryption (E2EE)
- [ ] File/image uploads
- [ ] Message editing/deletion
- [ ] Room creation
- [ ] User search/invite
### Phase 3 (Future)
- [ ] VoIP calls (WebRTC)
- [ ] Video calls
- [ ] Screen sharing
## Configuration
### Environment Variables
No environment variables required for basic usage. The client stores credentials in localStorage.
### Default Homeserver
The login page defaults to `matrix.mana.how` but any Matrix homeserver can be used.
## Matrix SDK Notes
### Browser Polyfills
matrix-js-sdk requires polyfills for browser usage. These are automatically loaded in `src/lib/matrix/polyfills.ts`:
- `Buffer` from buffer package
- `global` mapped to `globalThis`
- `process.env` stub
### Vite Configuration
Special Vite config in `vite.config.ts`:
```typescript
define: {
global: 'globalThis',
},
optimizeDeps: {
include: ['buffer', 'events'],
}
```
### Client-Side Only
matrix-js-sdk only works client-side. Always guard with:
```typescript
import { browser } from '$app/environment';
if (browser) {
await matrixStore.initialize();
}
```
## Troubleshooting
### "super.off is not a function"
This is a known issue with typed-event-emitter. Make sure polyfills are loaded before any matrix-js-sdk imports.
### Login fails with network error
1. Check if homeserver is reachable: `curl https://matrix.mana.how/_matrix/client/versions`
2. Verify CORS is configured on Synapse
3. Try without https:// prefix in homeserver field
### Messages not loading
The initial sync can take time depending on room history. Check `matrixStore.syncState` for status.
## Related Documentation
- [Matrix Client-Server API](https://spec.matrix.org/latest/client-server-api/)
- [matrix-js-sdk docs](https://matrix-org.github.io/matrix-js-sdk/)
- [Synapse Admin API](https://element-hq.github.io/synapse/latest/admin_api/)

View file

@ -0,0 +1,48 @@
{
"name": "@matrix/web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"type-check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"format": "prettier --write .",
"lint": "eslint ."
},
"devDependencies": {
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.21.0",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"@tailwindcss/vite": "^4.1.7",
"@types/node": "^22.15.21",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.4.0",
"svelte": "^5.33.0",
"svelte-check": "^4.2.1",
"tailwindcss": "^4.1.7",
"tslib": "^2.8.1",
"typescript": "^5.8.3",
"vite": "^6.3.5"
},
"dependencies": {
"matrix-js-sdk": "^37.1.0",
"buffer": "^6.0.3",
"events": "^3.3.0",
"@manacore/shared-auth": "workspace:*",
"@manacore/shared-theme": "workspace:*",
"@manacore/shared-tailwind": "workspace:*",
"@manacore/shared-i18n": "workspace:*",
"@manacore/shared-icons": "workspace:*",
"lucide-svelte": "^0.509.0",
"date-fns": "^4.1.0",
"svelte-i18n": "^4.0.1"
},
"overrides": {
"@matrix-org/matrix-sdk-crypto-nodejs": "npm:empty-npm-package@1.0.0"
}
}

View file

@ -0,0 +1,39 @@
@import 'tailwindcss';
@import '@manacore/shared-tailwind/themes.css';
/* Scan shared packages for Tailwind classes */
@source '../../../packages/shared/src';
@source '../../../../../packages/shared-ui/src';
@source '../../../../../packages/shared-icons/src';
@layer base {
:root {
--spacing-xs: 0.25rem;
--spacing-sm: 0.5rem;
--spacing-md: 1rem;
--spacing-lg: 1.5rem;
--spacing-xl: 2rem;
}
body {
@apply bg-base-100 text-base-content;
}
}
/* Custom scrollbar for chat */
.chat-scrollbar::-webkit-scrollbar {
width: 6px;
}
.chat-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.chat-scrollbar::-webkit-scrollbar-thumb {
background: oklch(var(--bc) / 0.2);
border-radius: 3px;
}
.chat-scrollbar::-webkit-scrollbar-thumb:hover {
background: oklch(var(--bc) / 0.3);
}

20
apps/matrix/apps/web/src/app.d.ts vendored Normal file
View file

@ -0,0 +1,20 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
// Polyfills for matrix-js-sdk
interface Window {
global: typeof globalThis;
Buffer: typeof import('buffer').Buffer;
process: { env: Record<string, string> };
}
}
export {};

View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Mana Matrix</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View file

@ -0,0 +1,89 @@
<script lang="ts">
import type { SimpleMessage } from '$lib/matrix';
import { format, isToday, isYesterday } from 'date-fns';
import { de } from 'date-fns/locale';
interface Props {
message: SimpleMessage;
showAvatar?: boolean;
showTimestamp?: boolean;
}
let { message, showAvatar = true, showTimestamp = false }: Props = $props();
let formattedTime = $derived(format(message.timestamp, 'HH:mm'));
let formattedDate = $derived(() => {
const date = new Date(message.timestamp);
if (isToday(date)) return 'Heute';
if (isYesterday(date)) return 'Gestern';
return format(date, 'EEEE, d. MMMM', { locale: de });
});
let initials = $derived(
message.senderName
.split(' ')
.map((w) => w[0])
.join('')
.substring(0, 2)
.toUpperCase()
);
</script>
<!-- Date separator -->
{#if showTimestamp}
<div class="my-4 flex items-center gap-4">
<div class="h-px flex-1 bg-base-300"></div>
<span class="text-xs text-base-content/50">{formattedDate()}</span>
<div class="h-px flex-1 bg-base-300"></div>
</div>
{/if}
<!-- Message -->
<div class="group flex gap-3 rounded-lg px-2 py-1 hover:bg-base-200/50" class:mt-2={showAvatar}>
<!-- Avatar Column -->
<div class="w-10 flex-shrink-0">
{#if showAvatar && !message.isOwn}
<div class="avatar placeholder">
<div class="w-10 rounded-full bg-neutral text-neutral-content">
<span class="text-xs">{initials}</span>
</div>
</div>
{/if}
</div>
<!-- Content -->
<div class="min-w-0 flex-1">
{#if showAvatar}
<div class="mb-0.5 flex items-baseline gap-2">
<span class="font-medium" class:text-primary={message.isOwn}>
{message.isOwn ? 'Du' : message.senderName}
</span>
<span class="text-xs text-base-content/40">{formattedTime}</span>
{#if message.edited}
<span class="text-xs text-base-content/40">(bearbeitet)</span>
{/if}
</div>
{/if}
<!-- Message body -->
<div class="relative">
{#if message.type === 'm.emote'}
<p class="italic text-base-content/80">* {message.senderName} {message.body}</p>
{:else if message.type === 'm.notice'}
<p class="text-sm text-base-content/60">{message.body}</p>
{:else}
<p class="whitespace-pre-wrap break-words">{message.body}</p>
{/if}
<!-- Hover timestamp for grouped messages -->
{#if !showAvatar}
<span
class="absolute -left-12 top-0 hidden text-xs text-base-content/40 group-hover:inline"
>
{formattedTime}
</span>
{/if}
</div>
</div>
</div>

View file

@ -0,0 +1,105 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import { Send, Paperclip, Smile } from 'lucide-svelte';
let message = $state('');
let textarea: HTMLTextAreaElement;
let typingTimeout: ReturnType<typeof setTimeout>;
let isTyping = $state(false);
async function handleSend() {
const trimmed = message.trim();
if (!trimmed) return;
const sent = await matrixStore.sendMessage(trimmed);
if (sent) {
message = '';
stopTyping();
adjustTextareaHeight();
}
}
function handleInput() {
adjustTextareaHeight();
// Send typing indicator
if (!isTyping) {
isTyping = true;
matrixStore.sendTyping(true);
}
// Reset typing timeout
clearTimeout(typingTimeout);
typingTimeout = setTimeout(stopTyping, 3000);
}
function stopTyping() {
if (isTyping) {
isTyping = false;
matrixStore.sendTyping(false);
}
clearTimeout(typingTimeout);
}
function handleKeydown(e: KeyboardEvent) {
// Send on Enter (without Shift)
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}
function adjustTextareaHeight() {
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}
</script>
<div class="border-t border-base-300 bg-base-100 p-4">
<div class="flex items-end gap-2">
<!-- Attachment button -->
<button class="btn btn-ghost btn-sm" title="Attach file" disabled>
<Paperclip class="h-5 w-5" />
</button>
<!-- Text input -->
<div class="relative flex-1">
<textarea
bind:this={textarea}
bind:value={message}
oninput={handleInput}
onkeydown={handleKeydown}
onblur={stopTyping}
placeholder="Write a message..."
rows="1"
class="textarea textarea-bordered w-full resize-none pr-10"
style="max-height: 200px; min-height: 48px;"
></textarea>
<!-- Emoji button (inside textarea) -->
<button
class="absolute bottom-2 right-2 text-base-content/50 hover:text-base-content"
title="Add emoji"
disabled
>
<Smile class="h-5 w-5" />
</button>
</div>
<!-- Send button -->
<button
class="btn btn-primary"
onclick={handleSend}
disabled={!message.trim()}
title="Send message"
>
<Send class="h-5 w-5" />
</button>
</div>
<!-- Hint -->
<p class="mt-1 text-xs text-base-content/40">
Press Enter to send, Shift+Enter for new line
</p>
</div>

View file

@ -0,0 +1,65 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import { Menu, Phone, Video, Info, Lock, Users } from 'lucide-svelte';
interface Props {
onMenuClick?: () => void;
}
let { onMenuClick }: Props = $props();
let room = $derived(matrixStore.currentSimpleRoom);
</script>
{#if room}
<header class="flex items-center gap-3 border-b border-base-300 bg-base-100 px-4 py-3">
<!-- Mobile menu button -->
<button class="btn btn-ghost btn-sm lg:hidden" onclick={onMenuClick}>
<Menu class="h-5 w-5" />
</button>
<!-- Room avatar -->
<div class="avatar placeholder">
<div class="w-10 rounded-full bg-neutral text-neutral-content">
{#if room.avatar}
<img src={room.avatar} alt={room.name} />
{:else}
<span class="text-sm">{room.name.charAt(0).toUpperCase()}</span>
{/if}
</div>
</div>
<!-- Room info -->
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<h2 class="truncate font-semibold">{room.name}</h2>
{#if room.isEncrypted}
<Lock class="h-4 w-4 flex-shrink-0 text-success" title="End-to-end encrypted" />
{/if}
</div>
<p class="flex items-center gap-1 text-sm text-base-content/60">
{#if room.topic}
<span class="truncate">{room.topic}</span>
{:else if room.isDirect}
<span>Direct message</span>
{:else}
<Users class="h-3 w-3" />
<span>{room.memberCount} members</span>
{/if}
</p>
</div>
<!-- Actions -->
<div class="flex items-center gap-1">
<button class="btn btn-ghost btn-sm" title="Voice call" disabled>
<Phone class="h-5 w-5" />
</button>
<button class="btn btn-ghost btn-sm" title="Video call" disabled>
<Video class="h-5 w-5" />
</button>
<button class="btn btn-ghost btn-sm" title="Room info">
<Info class="h-5 w-5" />
</button>
</div>
</header>
{/if}

View file

@ -0,0 +1,91 @@
<script lang="ts">
import type { SimpleRoom } from '$lib/matrix';
import { formatDistanceToNow } from 'date-fns';
import { de } from 'date-fns/locale';
import { Lock, Users } from 'lucide-svelte';
interface Props {
room: SimpleRoom;
selected: boolean;
onclick: () => void;
}
let { room, selected, onclick }: Props = $props();
let timeAgo = $derived(
room.lastMessageTime
? formatDistanceToNow(room.lastMessageTime, { addSuffix: false, locale: de })
: ''
);
let initials = $derived(
room.name
.split(' ')
.map((w) => w[0])
.join('')
.substring(0, 2)
.toUpperCase()
);
</script>
<button
class="flex w-full items-center gap-3 px-3 py-2 transition-colors hover:bg-base-300"
class:bg-primary/10={selected}
class:hover:bg-primary/20={selected}
{onclick}
>
<!-- Avatar -->
<div class="avatar placeholder">
<div
class="w-12 rounded-full bg-neutral text-neutral-content"
class:bg-primary={selected}
class:text-primary-content={selected}
>
{#if room.avatar}
<img src={room.avatar} alt={room.name} class="object-cover" />
{:else}
<span class="text-sm font-medium">{initials}</span>
{/if}
</div>
</div>
<!-- Room Info -->
<div class="flex min-w-0 flex-1 flex-col items-start">
<div class="flex w-full items-center gap-1">
<span class="truncate font-medium">{room.name}</span>
{#if room.isEncrypted}
<Lock class="h-3 w-3 flex-shrink-0 text-success" />
{/if}
{#if !room.isDirect && room.memberCount > 2}
<span class="flex items-center text-xs text-base-content/50">
<Users class="mr-0.5 h-3 w-3" />
{room.memberCount}
</span>
{/if}
</div>
{#if room.lastMessage}
<p class="w-full truncate text-left text-sm text-base-content/60">
{#if room.lastMessageSender && !room.isDirect}
<span class="font-medium">{room.lastMessageSender}:</span>
{/if}
{room.lastMessage}
</p>
{/if}
</div>
<!-- Meta -->
<div class="flex flex-shrink-0 flex-col items-end gap-1">
{#if timeAgo}
<span class="text-xs text-base-content/40">{timeAgo}</span>
{/if}
{#if room.unreadCount > 0}
<span
class="badge badge-sm"
class:badge-primary={room.highlightCount === 0}
class:badge-error={room.highlightCount > 0}
>
{room.unreadCount > 99 ? '99+' : room.unreadCount}
</span>
{/if}
</div>
</button>

View file

@ -0,0 +1,76 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import RoomItem from './RoomItem.svelte';
import { Search, Plus, Users, MessageCircle } from 'lucide-svelte';
let search = $state('');
let showDMs = $state(true);
let filteredRooms = $derived(
(showDMs ? matrixStore.directRooms : matrixStore.groupRooms).filter((room) =>
room.name.toLowerCase().includes(search.toLowerCase())
)
);
</script>
<div class="flex h-full flex-col">
<!-- Search -->
<div class="p-3">
<div class="relative">
<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-base-content/50" />
<input
type="text"
bind:value={search}
placeholder="Search rooms..."
class="input input-bordered input-sm w-full pl-10"
/>
</div>
</div>
<!-- Tabs -->
<div class="tabs tabs-boxed mx-3 mb-2">
<button class="tab flex-1" class:tab-active={showDMs} onclick={() => (showDMs = true)}>
<MessageCircle class="mr-1 h-4 w-4" />
Direct
{#if matrixStore.directRooms.length > 0}
<span class="badge badge-sm ml-1">{matrixStore.directRooms.length}</span>
{/if}
</button>
<button class="tab flex-1" class:tab-active={!showDMs} onclick={() => (showDMs = false)}>
<Users class="mr-1 h-4 w-4" />
Rooms
{#if matrixStore.groupRooms.length > 0}
<span class="badge badge-sm ml-1">{matrixStore.groupRooms.length}</span>
{/if}
</button>
</div>
<!-- Room List -->
<div class="chat-scrollbar flex-1 overflow-y-auto">
{#each filteredRooms as room (room.id)}
<RoomItem
{room}
selected={room.id === matrixStore.currentRoomId}
onclick={() => matrixStore.selectRoom(room.id)}
/>
{:else}
<div class="flex flex-col items-center justify-center p-8 text-base-content/50">
{#if search}
<Search class="mb-2 h-8 w-8" />
<p>No rooms match "{search}"</p>
{:else}
<MessageCircle class="mb-2 h-8 w-8" />
<p>No {showDMs ? 'direct messages' : 'rooms'} yet</p>
{/if}
</div>
{/each}
</div>
<!-- New Room Button -->
<div class="border-t border-base-300 p-3">
<button class="btn btn-ghost btn-sm w-full justify-start">
<Plus class="h-4 w-4" />
{showDMs ? 'Start new chat' : 'Join or create room'}
</button>
</div>
</div>

View file

@ -0,0 +1,113 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import Message from './Message.svelte';
import TypingIndicator from './TypingIndicator.svelte';
import { onMount, tick } from 'svelte';
import { Loader2, ArrowDown } from 'lucide-svelte';
let container: HTMLDivElement;
let showScrollButton = $state(false);
let loadingMore = $state(false);
let prevMessageCount = $state(0);
// Auto-scroll to bottom on new messages (if already at bottom)
$effect(() => {
const messageCount = matrixStore.messages.length;
if (messageCount > prevMessageCount && container) {
const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
if (isAtBottom) {
tick().then(() => {
container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
});
}
}
prevMessageCount = messageCount;
});
function handleScroll() {
if (!container) return;
// Show scroll button if not at bottom
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
showScrollButton = distanceFromBottom > 200;
// Load more when scrolled to top
if (container.scrollTop < 100 && !loadingMore) {
loadMore();
}
}
async function loadMore() {
if (loadingMore) return;
loadingMore = true;
const prevScrollHeight = container.scrollHeight;
await matrixStore.loadMoreMessages(50);
// Maintain scroll position after loading
tick().then(() => {
const newScrollHeight = container.scrollHeight;
container.scrollTop = newScrollHeight - prevScrollHeight;
});
loadingMore = false;
}
function scrollToBottom() {
container?.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
}
onMount(() => {
// Scroll to bottom on mount
if (container) {
container.scrollTop = container.scrollHeight;
}
});
</script>
<div class="relative flex-1 overflow-hidden">
<div
bind:this={container}
onscroll={handleScroll}
class="chat-scrollbar h-full overflow-y-auto p-4"
>
<!-- Loading indicator at top -->
{#if loadingMore}
<div class="flex justify-center py-4">
<Loader2 class="h-6 w-6 animate-spin text-base-content/50" />
</div>
{/if}
<!-- Messages -->
<div class="space-y-1">
{#each matrixStore.messages as message, index (message.id)}
{@const prevMessage = matrixStore.messages[index - 1]}
{@const showAvatar = !prevMessage || prevMessage.sender !== message.sender}
{@const showTimestamp =
!prevMessage || message.timestamp - prevMessage.timestamp > 5 * 60 * 1000}
<Message {message} {showAvatar} {showTimestamp} />
{:else}
<div class="flex h-full flex-col items-center justify-center text-base-content/50">
<p>No messages yet</p>
<p class="text-sm">Start the conversation!</p>
</div>
{/each}
</div>
<!-- Typing Indicator -->
{#if matrixStore.currentRoomTyping.length > 0}
<TypingIndicator users={matrixStore.currentRoomTyping} />
{/if}
</div>
<!-- Scroll to bottom button -->
{#if showScrollButton}
<button
onclick={scrollToBottom}
class="absolute bottom-4 right-4 btn btn-circle btn-sm shadow-lg"
>
<ArrowDown class="h-4 w-4" />
</button>
{/if}
</div>

View file

@ -0,0 +1,29 @@
<script lang="ts">
interface Props {
users: string[];
}
let { users }: Props = $props();
let text = $derived(() => {
if (users.length === 0) return '';
if (users.length === 1) return `${users[0]} tippt...`;
if (users.length === 2) return `${users[0]} und ${users[1]} tippen...`;
return `${users[0]} und ${users.length - 1} weitere tippen...`;
});
</script>
{#if users.length > 0}
<div class="flex items-center gap-2 px-4 py-2 text-sm text-base-content/60">
<!-- Animated dots -->
<span class="flex gap-1">
<span class="h-2 w-2 animate-bounce rounded-full bg-base-content/40 [animation-delay:0ms]"
></span>
<span class="h-2 w-2 animate-bounce rounded-full bg-base-content/40 [animation-delay:150ms]"
></span>
<span class="h-2 w-2 animate-bounce rounded-full bg-base-content/40 [animation-delay:300ms]"
></span>
</span>
<span>{text()}</span>
</div>
{/if}

View file

@ -0,0 +1,7 @@
export { default as RoomList } from './RoomList.svelte';
export { default as RoomItem } from './RoomItem.svelte';
export { default as RoomHeader } from './RoomHeader.svelte';
export { default as Timeline } from './Timeline.svelte';
export { default as Message } from './Message.svelte';
export { default as MessageInput } from './MessageInput.svelte';
export { default as TypingIndicator } from './TypingIndicator.svelte';

View file

@ -0,0 +1,198 @@
import type { MatrixCredentials, LoginResult } from './types';
/**
* Login with username and password
*/
export async function loginWithPassword(
homeserver: string,
username: string,
password: string
): Promise<LoginResult> {
// Load polyfills first
await import('./polyfills');
const { createClient } = await import('matrix-js-sdk');
// Normalize homeserver URL
let baseUrl = homeserver.trim();
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
baseUrl = `https://${baseUrl}`;
}
// Remove trailing slash
baseUrl = baseUrl.replace(/\/$/, '');
const tempClient = createClient({ baseUrl });
try {
const response = await tempClient.login('m.login.password', {
user: username,
password: password,
initial_device_display_name: 'Mana Matrix Client',
});
return {
success: true,
credentials: {
homeserver: baseUrl,
accessToken: response.access_token,
userId: response.user_id,
deviceId: response.device_id,
},
};
} catch (err) {
const message = err instanceof Error ? err.message : 'Login failed';
// Provide more helpful error messages
if (message.includes('M_FORBIDDEN')) {
return { success: false, error: 'Invalid username or password' };
}
if (message.includes('M_USER_DEACTIVATED')) {
return { success: false, error: 'This account has been deactivated' };
}
if (message.includes('Failed to fetch') || message.includes('NetworkError')) {
return { success: false, error: 'Could not connect to homeserver' };
}
return { success: false, error: message };
}
}
/**
* Login with an existing access token (for SSO/OAuth flows)
*/
export async function loginWithToken(
homeserver: string,
accessToken: string,
userId: string,
deviceId?: string
): Promise<LoginResult> {
// Normalize homeserver URL
let baseUrl = homeserver.trim();
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
baseUrl = `https://${baseUrl}`;
}
baseUrl = baseUrl.replace(/\/$/, '');
return {
success: true,
credentials: {
homeserver: baseUrl,
accessToken,
userId,
deviceId: deviceId || `MANA_${Date.now()}`,
},
};
}
/**
* Discover homeserver from user ID or domain
* Uses .well-known discovery
*/
export async function discoverHomeserver(userIdOrDomain: string): Promise<string | null> {
// Extract domain from user ID if provided
let domain = userIdOrDomain;
if (userIdOrDomain.startsWith('@')) {
const parts = userIdOrDomain.split(':');
if (parts.length < 2) return null;
domain = parts[1];
}
// Remove any protocol prefix
domain = domain.replace(/^https?:\/\//, '');
try {
// Try .well-known discovery
const wellKnownUrl = `https://${domain}/.well-known/matrix/client`;
const response = await fetch(wellKnownUrl);
if (response.ok) {
const data = await response.json();
const baseUrl = data['m.homeserver']?.base_url;
if (baseUrl) {
return baseUrl.replace(/\/$/, '');
}
}
} catch {
// .well-known not available
}
// Fallback: assume homeserver is at the domain
return `https://${domain}`;
}
/**
* Check if a homeserver is reachable
*/
export async function checkHomeserver(homeserver: string): Promise<{ ok: boolean; error?: string }> {
let baseUrl = homeserver.trim();
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
baseUrl = `https://${baseUrl}`;
}
try {
const response = await fetch(`${baseUrl}/_matrix/client/versions`, {
method: 'GET',
});
if (response.ok) {
return { ok: true };
}
return { ok: false, error: `Server returned ${response.status}` };
} catch (err) {
return {
ok: false,
error: err instanceof Error ? err.message : 'Could not connect to server',
};
}
}
/**
* Register a new account (if registration is open)
*/
export async function register(
homeserver: string,
username: string,
password: string
): Promise<LoginResult> {
await import('./polyfills');
const { createClient } = await import('matrix-js-sdk');
let baseUrl = homeserver.trim();
if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
baseUrl = `https://${baseUrl}`;
}
baseUrl = baseUrl.replace(/\/$/, '');
const tempClient = createClient({ baseUrl });
try {
const response = await tempClient.register(username, password, null, {
initial_device_display_name: 'Mana Matrix Client',
});
return {
success: true,
credentials: {
homeserver: baseUrl,
accessToken: response.access_token!,
userId: response.user_id,
deviceId: response.device_id!,
},
};
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Registration failed';
// Check for common errors
if (message.includes('M_USER_IN_USE')) {
return { success: false, error: 'Username is already taken' };
}
if (message.includes('M_INVALID_USERNAME')) {
return { success: false, error: 'Invalid username format' };
}
if (message.includes('M_FORBIDDEN')) {
return { success: false, error: 'Registration is disabled on this server' };
}
return { success: false, error: message };
}
}

View file

@ -0,0 +1,10 @@
// Matrix client exports
export { matrixStore } from './store.svelte';
export {
loginWithPassword,
loginWithToken,
discoverHomeserver,
checkHomeserver,
register,
} from './client';
export * from './types';

View file

@ -0,0 +1,18 @@
/**
* Polyfills required for matrix-js-sdk to work in browser environment
* Must be imported before any matrix-js-sdk imports
*/
import { Buffer } from 'buffer';
if (typeof window !== 'undefined') {
// Global object polyfill
window.global = window.globalThis;
// Buffer polyfill (used by matrix-js-sdk for binary data)
(window as Window).Buffer = Buffer;
// Process polyfill (some dependencies check process.env)
(window as Window).process = { env: {} };
}
export {};

View file

@ -0,0 +1,484 @@
import { browser } from '$app/environment';
import type { MatrixClient, Room, MatrixEvent, RoomMember as SDKRoomMember } from 'matrix-js-sdk';
import type { SyncState, MatrixCredentials, SimpleRoom, SimpleMessage, RoomMember } from './types';
const STORAGE_KEY = 'matrix_credentials';
/**
* Reactive Matrix store using Svelte 5 runes
*/
class MatrixStore {
// ─────────────────────────────────────────────────────────
// Private State
// ─────────────────────────────────────────────────────────
private _client = $state<MatrixClient | null>(null);
private _syncState = $state<SyncState>('STOPPED');
private _rooms = $state<Room[]>([]);
private _currentRoomId = $state<string | null>(null);
private _timeline = $state<MatrixEvent[]>([]);
private _typingUsers = $state<Map<string, string[]>>(new Map());
private _error = $state<string | null>(null);
private _initialized = $state(false);
// ─────────────────────────────────────────────────────────
// Public Getters
// ─────────────────────────────────────────────────────────
get client() {
return this._client;
}
get syncState() {
return this._syncState;
}
get error() {
return this._error;
}
get initialized() {
return this._initialized;
}
get currentRoomId() {
return this._currentRoomId;
}
// ─────────────────────────────────────────────────────────
// Derived State
// ─────────────────────────────────────────────────────────
/** Is the client ready to use? */
isReady = $derived(this._syncState === 'PREPARED' || this._syncState === 'SYNCING');
/** Is currently syncing? */
isSyncing = $derived(this._syncState === 'SYNCING' || this._syncState === 'CATCHUP');
/** Current user ID */
userId = $derived(this._client?.getUserId() || null);
/** Simplified room list sorted by last activity */
rooms = $derived<SimpleRoom[]>(
this._rooms
.map((room) => this.roomToSimpleRoom(room))
.sort((a, b) => (b.lastMessageTime || 0) - (a.lastMessageTime || 0))
);
/** Direct message rooms */
directRooms = $derived(this.rooms.filter((r) => r.isDirect));
/** Group rooms (non-DM) */
groupRooms = $derived(this.rooms.filter((r) => !r.isDirect));
/** Current selected room */
currentRoom = $derived(
this._currentRoomId ? this._rooms.find((r) => r.roomId === this._currentRoomId) || null : null
);
/** Current room as SimpleRoom */
currentSimpleRoom = $derived(this.currentRoom ? this.roomToSimpleRoom(this.currentRoom) : null);
/** Messages in current room */
messages = $derived<SimpleMessage[]>(
this._timeline
.filter((e) => e.getType() === 'm.room.message')
.map((e) => this.eventToSimpleMessage(e))
);
/** Users currently typing in current room */
currentRoomTyping = $derived(
this._currentRoomId ? this._typingUsers.get(this._currentRoomId) || [] : []
);
/** Total unread count across all rooms */
totalUnreadCount = $derived(this.rooms.reduce((sum, r) => sum + r.unreadCount, 0));
// ─────────────────────────────────────────────────────────
// Initialization
// ─────────────────────────────────────────────────────────
/**
* Initialize the Matrix client
* @param credentials Optional credentials, will load from storage if not provided
*/
async initialize(credentials?: MatrixCredentials): Promise<boolean> {
if (!browser) return false;
if (this._initialized && this._client) return true;
// Load polyfills first
await import('./polyfills');
// Get credentials
const creds = credentials || this.loadCredentials();
if (!creds) {
this._error = 'No credentials available';
return false;
}
try {
const sdk = await import('matrix-js-sdk');
this._client = sdk.createClient({
baseUrl: creds.homeserver,
accessToken: creds.accessToken,
userId: creds.userId,
deviceId: creds.deviceId,
timelineSupport: true,
});
this.setupEventHandlers(sdk);
await this._client.startClient({
initialSyncLimit: 20,
lazyLoadMembers: true,
});
this.saveCredentials(creds);
this._initialized = true;
this._error = null;
return true;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to initialize Matrix client';
console.error('Matrix initialization error:', err);
return false;
}
}
/**
* Setup event handlers for Matrix SDK events
*/
private setupEventHandlers(sdk: typeof import('matrix-js-sdk')) {
if (!this._client) return;
// Sync state changes
this._client.on(sdk.ClientEvent.Sync, (state, prevState) => {
this._syncState = state as SyncState;
if (state === 'PREPARED') {
this._rooms = this._client!.getRooms();
console.log(`Matrix sync prepared, ${this._rooms.length} rooms loaded`);
}
if (state === 'ERROR') {
this._error = 'Sync error occurred';
}
});
// Room timeline updates (new messages)
this._client.on(sdk.RoomEvent.Timeline, (event, room, toStartOfTimeline) => {
// Skip historical events from pagination
if (toStartOfTimeline) return;
// Update rooms list
this._rooms = this._client!.getRooms();
// Update timeline if we're in this room
if (room?.roomId === this._currentRoomId) {
this._timeline = [...(room.getLiveTimeline().getEvents() || [])];
}
});
// Typing indicators
this._client.on(sdk.RoomMemberEvent.Typing, (event, member) => {
const roomId = event.getRoomId();
if (!roomId) return;
const room = this._client!.getRoom(roomId);
const typingMembers =
room
?.getMembersWithMembership('join')
.filter((m) => m.typing && m.userId !== this._client!.getUserId())
.map((m) => m.name || m.userId) || [];
// Trigger reactivity by creating new Map
const newMap = new Map(this._typingUsers);
newMap.set(roomId, typingMembers);
this._typingUsers = newMap;
});
// Room membership changes (invites, joins, leaves)
this._client.on(sdk.RoomEvent.MyMembership, (room, membership, prevMembership) => {
console.log(`Membership changed: ${room.roomId} - ${prevMembership} -> ${membership}`);
this._rooms = this._client!.getRooms();
});
// Room name/state changes
this._client.on(sdk.RoomStateEvent.Events, (event, state, prevEvent) => {
// Trigger reactivity for room updates
this._rooms = this._client!.getRooms();
});
}
// ─────────────────────────────────────────────────────────
// Room Actions
// ─────────────────────────────────────────────────────────
/**
* Select a room to view
*/
selectRoom(roomId: string) {
this._currentRoomId = roomId;
const room = this._client?.getRoom(roomId);
if (room) {
this._timeline = room.getLiveTimeline().getEvents() || [];
// Mark as read
const lastEvent = this._timeline[this._timeline.length - 1];
if (lastEvent) {
this._client?.sendReadReceipt(lastEvent).catch(console.error);
}
} else {
this._timeline = [];
}
}
/**
* Clear current room selection
*/
clearRoom() {
this._currentRoomId = null;
this._timeline = [];
}
/**
* Join a room by ID or alias
*/
async joinRoom(roomIdOrAlias: string): Promise<boolean> {
if (!this._client) return false;
try {
await this._client.joinRoom(roomIdOrAlias);
this._rooms = this._client.getRooms();
return true;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to join room';
return false;
}
}
/**
* Leave a room
*/
async leaveRoom(roomId: string): Promise<boolean> {
if (!this._client) return false;
try {
await this._client.leave(roomId);
if (this._currentRoomId === roomId) {
this.clearRoom();
}
this._rooms = this._client.getRooms();
return true;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to leave room';
return false;
}
}
/**
* Create a new room
*/
async createRoom(options: {
name?: string;
topic?: string;
isDirect?: boolean;
invite?: string[];
}): Promise<string | null> {
if (!this._client) return null;
try {
const result = await this._client.createRoom({
name: options.name,
topic: options.topic,
is_direct: options.isDirect,
invite: options.invite,
preset: options.isDirect ? 'trusted_private_chat' : 'private_chat',
});
this._rooms = this._client.getRooms();
return result.room_id;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to create room';
return null;
}
}
// ─────────────────────────────────────────────────────────
// Message Actions
// ─────────────────────────────────────────────────────────
/**
* Send a text message to current room
*/
async sendMessage(body: string): Promise<boolean> {
if (!this._client || !this._currentRoomId) return false;
try {
await this._client.sendTextMessage(this._currentRoomId, body);
return true;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to send message';
return false;
}
}
/**
* Send typing indicator
*/
async sendTyping(typing: boolean): Promise<void> {
if (!this._client || !this._currentRoomId) return;
try {
await this._client.sendTyping(this._currentRoomId, typing, typing ? 30000 : 0);
} catch (err) {
// Ignore typing errors
}
}
/**
* Load more messages (pagination)
*/
async loadMoreMessages(limit = 50): Promise<boolean> {
if (!this._client || !this._currentRoomId) return false;
const room = this._client.getRoom(this._currentRoomId);
if (!room) return false;
try {
await this._client.scrollback(room, limit);
this._timeline = room.getLiveTimeline().getEvents() || [];
return true;
} catch (err) {
this._error = err instanceof Error ? err.message : 'Failed to load messages';
return false;
}
}
// ─────────────────────────────────────────────────────────
// Cleanup
// ─────────────────────────────────────────────────────────
/**
* Stop the client and clean up
*/
destroy() {
this._client?.stopClient();
this._client = null;
this._syncState = 'STOPPED';
this._rooms = [];
this._timeline = [];
this._currentRoomId = null;
this._typingUsers = new Map();
this._initialized = false;
}
/**
* Logout and clear credentials
*/
logout() {
this.destroy();
if (browser) {
localStorage.removeItem(STORAGE_KEY);
}
}
// ─────────────────────────────────────────────────────────
// Helper Methods
// ─────────────────────────────────────────────────────────
/**
* Convert SDK Room to SimpleRoom
*/
private roomToSimpleRoom(room: Room): SimpleRoom {
const lastEvent = room
.getLiveTimeline()
.getEvents()
.filter((e) => e.getType() === 'm.room.message')
.pop();
return {
id: room.roomId,
name: room.name || 'Unnamed Room',
topic: room.currentState.getStateEvents('m.room.topic', '')?.[0]?.getContent()?.topic,
avatar: room.getAvatarUrl(this._client?.baseUrl || '', 48, 48, 'scale') || undefined,
lastMessage: lastEvent?.getContent()?.body,
lastMessageSender: lastEvent ? this.getSenderName(lastEvent) : undefined,
lastMessageTime: room.getLastActiveTimestamp() || undefined,
unreadCount: room.getUnreadNotificationCount('total') || 0,
highlightCount: room.getUnreadNotificationCount('highlight') || 0,
isDirect: this.isDirectRoom(room),
isEncrypted: room.hasEncryptionStateEvent(),
memberCount: room.getJoinedMemberCount(),
};
}
/**
* Convert SDK MatrixEvent to SimpleMessage
*/
private eventToSimpleMessage(event: MatrixEvent): SimpleMessage {
const content = event.getContent();
const relatesTo = content['m.relates_to'];
return {
id: event.getId() || '',
sender: event.getSender() || '',
senderName: this.getSenderName(event),
body: content.body || '',
formattedBody: content.formatted_body,
timestamp: event.getTs(),
type: content.msgtype || 'm.text',
isOwn: event.getSender() === this._client?.getUserId(),
replyTo: relatesTo?.['m.in_reply_to']?.event_id,
edited: !!event.replacingEvent(),
};
}
/**
* Get display name for message sender
*/
private getSenderName(event: MatrixEvent): string {
const room = this._client?.getRoom(event.getRoomId() || '');
const member = room?.getMember(event.getSender() || '');
return member?.name || event.getSender()?.split(':')[0].substring(1) || 'Unknown';
}
/**
* Check if room is a direct message room
*/
private isDirectRoom(room: Room): boolean {
const dominated = this._client?.getAccountData('m.direct')?.getContent() || {};
return Object.values(dominated).flat().includes(room.roomId);
}
/**
* Load credentials from localStorage
*/
private loadCredentials(): MatrixCredentials | null {
if (!browser) return null;
try {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? JSON.parse(stored) : null;
} catch {
return null;
}
}
/**
* Save credentials to localStorage
*/
private saveCredentials(creds: MatrixCredentials) {
if (browser) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(creds));
}
}
/**
* Check if credentials exist in storage
*/
hasStoredCredentials(): boolean {
return this.loadCredentials() !== null;
}
}
// Export singleton instance
export const matrixStore = new MatrixStore();

View file

@ -0,0 +1,83 @@
import type { Room, MatrixEvent, MatrixClient } from 'matrix-js-sdk';
/**
* Matrix sync states
*/
export type SyncState = 'STOPPED' | 'PREPARED' | 'SYNCING' | 'ERROR' | 'RECONNECTING' | 'CATCHUP';
/**
* Credentials for Matrix authentication
*/
export interface MatrixCredentials {
homeserver: string;
accessToken: string;
userId: string;
deviceId: string;
}
/**
* Simplified message for UI rendering
*/
export interface SimpleMessage {
id: string;
sender: string;
senderName: string;
body: string;
formattedBody?: string;
timestamp: number;
type: MessageType;
isOwn: boolean;
replyTo?: string;
edited?: boolean;
}
export type MessageType = 'm.text' | 'm.image' | 'm.file' | 'm.audio' | 'm.video' | 'm.emote' | 'm.notice';
/**
* Simplified room for UI rendering
*/
export interface SimpleRoom {
id: string;
name: string;
topic?: string;
avatar?: string;
lastMessage?: string;
lastMessageSender?: string;
lastMessageTime?: number;
unreadCount: number;
highlightCount: number;
isDirect: boolean;
isEncrypted: boolean;
memberCount: number;
}
/**
* Room member info
*/
export interface RoomMember {
userId: string;
displayName: string;
avatarUrl?: string;
membership: 'join' | 'invite' | 'leave' | 'ban' | 'knock';
powerLevel: number;
}
/**
* Login result
*/
export interface LoginResult {
success: boolean;
credentials?: MatrixCredentials;
error?: string;
}
/**
* Matrix store state (for debugging)
*/
export interface MatrixStoreState {
syncState: SyncState;
roomCount: number;
currentRoomId: string | null;
messageCount: number;
error: string | null;
}

View file

@ -0,0 +1,105 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import { goto } from '$app/navigation';
import { onMount, onDestroy } from 'svelte';
import type { Snippet } from 'svelte';
import { Loader2, AlertCircle, RefreshCw } from 'lucide-svelte';
interface Props {
children: Snippet;
}
let { children }: Props = $props();
let loading = $state(true);
let initError = $state<string | null>(null);
onMount(async () => {
// Check if already initialized
if (matrixStore.isReady) {
loading = false;
return;
}
// Try to initialize
const success = await matrixStore.initialize();
if (!success) {
// Check if no credentials (should redirect to login)
if (!matrixStore.hasStoredCredentials()) {
goto('/login');
return;
}
// Has credentials but failed to init
initError = matrixStore.error || 'Failed to connect to Matrix server';
}
loading = false;
});
onDestroy(() => {
// Don't destroy on navigation within app routes
// matrixStore.destroy();
});
async function retry() {
loading = true;
initError = null;
const success = await matrixStore.initialize();
if (!success) {
initError = matrixStore.error || 'Failed to connect';
}
loading = false;
}
function logout() {
matrixStore.logout();
goto('/login');
}
</script>
{#if loading}
<!-- Loading State -->
<div class="flex h-screen flex-col items-center justify-center gap-4">
<Loader2 class="h-12 w-12 animate-spin text-primary" />
<div class="text-center">
<p class="font-medium">Connecting to Matrix...</p>
<p class="text-sm text-base-content/60">
{#if matrixStore.syncState === 'PREPARED'}
Preparing sync...
{:else if matrixStore.syncState === 'SYNCING'}
Syncing messages...
{:else if matrixStore.syncState === 'CATCHUP'}
Catching up...
{:else}
Initializing...
{/if}
</p>
</div>
</div>
{:else if initError}
<!-- Error State -->
<div class="flex h-screen flex-col items-center justify-center gap-4 p-4">
<div class="rounded-full bg-error/10 p-4">
<AlertCircle class="h-12 w-12 text-error" />
</div>
<div class="text-center">
<h2 class="text-xl font-semibold">Connection Failed</h2>
<p class="mt-2 max-w-md text-base-content/60">{initError}</p>
</div>
<div class="flex gap-2">
<button class="btn btn-primary" onclick={retry}>
<RefreshCw class="h-4 w-4" />
Retry
</button>
<button class="btn btn-ghost" onclick={logout}> Sign Out </button>
</div>
</div>
{:else if matrixStore.isReady}
<!-- Ready - Render children -->
{@render children()}
{:else}
<!-- Unknown state - redirect to login -->
<div class="flex h-screen items-center justify-center">
<p class="text-base-content/60">Redirecting...</p>
</div>
{/if}

View file

@ -0,0 +1,105 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import { RoomList, RoomHeader, Timeline, MessageInput } from '$lib/components/chat';
import { goto } from '$app/navigation';
import { Settings, LogOut, MessageSquare } from 'lucide-svelte';
let sidebarOpen = $state(true);
function toggleSidebar() {
sidebarOpen = !sidebarOpen;
}
function handleLogout() {
matrixStore.logout();
goto('/login');
}
</script>
<div class="flex h-screen overflow-hidden bg-base-100">
<!-- Sidebar -->
<aside
class="flex w-80 flex-shrink-0 flex-col border-r border-base-300 bg-base-200 transition-all duration-300 ease-in-out"
class:hidden={!sidebarOpen}
class:lg:flex={true}
>
<!-- Sidebar Header -->
<header class="flex items-center justify-between border-b border-base-300 p-4">
<div class="flex items-center gap-2">
<MessageSquare class="h-6 w-6 text-primary" />
<h1 class="text-xl font-bold">Mana Matrix</h1>
</div>
<div class="dropdown dropdown-end">
<button tabindex="0" class="btn btn-ghost btn-sm btn-circle">
<Settings class="h-5 w-5" />
</button>
<ul
tabindex="0"
class="dropdown-content menu rounded-box z-50 w-52 bg-base-100 p-2 shadow-lg"
>
<li>
<a href="/settings">
<Settings class="h-4 w-4" />
Settings
</a>
</li>
<li>
<button onclick={handleLogout} class="text-error">
<LogOut class="h-4 w-4" />
Sign out
</button>
</li>
</ul>
</div>
</header>
<!-- User Info -->
<div class="border-b border-base-300 px-4 py-2">
<p class="truncate text-sm font-medium">{matrixStore.userId}</p>
<p class="flex items-center gap-1 text-xs text-base-content/60">
<span class="h-2 w-2 rounded-full bg-success"></span>
{matrixStore.syncState === 'SYNCING' ? 'Connected' : matrixStore.syncState}
</p>
</div>
<!-- Room List -->
<div class="flex-1 overflow-hidden">
<RoomList />
</div>
</aside>
<!-- Main Chat Area -->
<main class="flex flex-1 flex-col overflow-hidden">
{#if matrixStore.currentRoom}
<!-- Room Header -->
<RoomHeader onMenuClick={toggleSidebar} />
<!-- Timeline -->
<Timeline />
<!-- Message Input -->
<MessageInput />
{:else}
<!-- No Room Selected -->
<div class="flex flex-1 flex-col items-center justify-center gap-4 p-8 text-base-content/50">
<MessageSquare class="h-16 w-16" />
<div class="text-center">
<h2 class="text-xl font-semibold text-base-content">Welcome to Mana Matrix</h2>
<p class="mt-2">Select a conversation from the sidebar to start chatting</p>
</div>
<!-- Stats -->
<div class="mt-8 flex gap-8 text-center">
<div>
<p class="text-3xl font-bold text-base-content">{matrixStore.rooms.length}</p>
<p class="text-sm">Rooms</p>
</div>
<div>
<p class="text-3xl font-bold text-base-content">{matrixStore.totalUnreadCount}</p>
<p class="text-sm">Unread</p>
</div>
</div>
</div>
{/if}
</main>
</div>

View file

@ -0,0 +1,26 @@
<script lang="ts">
import { page } from '$app/stores';
import { matrixStore } from '$lib/matrix';
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
// Get roomId from URL and select that room
onMount(() => {
const roomId = $page.params.roomId;
if (roomId) {
// URL decode the room ID (Matrix room IDs contain special chars)
const decodedRoomId = decodeURIComponent(roomId);
matrixStore.selectRoom(decodedRoomId);
}
});
// Redirect to main chat page - the room selection is handled there
$effect(() => {
goto('/chat');
});
</script>
<!-- This page just handles deep-linking to specific rooms -->
<div class="flex h-screen items-center justify-center">
<p class="text-base-content/60">Loading room...</p>
</div>

View file

@ -0,0 +1,123 @@
<script lang="ts">
import { matrixStore } from '$lib/matrix';
import { goto } from '$app/navigation';
import { ArrowLeft, User, Bell, Palette, Shield, LogOut, Server } from 'lucide-svelte';
function handleLogout() {
matrixStore.logout();
goto('/login');
}
</script>
<div class="flex h-screen flex-col bg-base-100">
<!-- Header -->
<header class="flex items-center gap-4 border-b border-base-300 p-4">
<a href="/chat" class="btn btn-ghost btn-sm btn-circle">
<ArrowLeft class="h-5 w-5" />
</a>
<h1 class="text-xl font-bold">Settings</h1>
</header>
<!-- Content -->
<div class="flex-1 overflow-y-auto p-4">
<div class="mx-auto max-w-2xl space-y-6">
<!-- Profile Section -->
<section class="card bg-base-200">
<div class="card-body">
<h2 class="card-title">
<User class="h-5 w-5" />
Profile
</h2>
<div class="mt-4 flex items-center gap-4">
<div class="avatar placeholder">
<div class="w-16 rounded-full bg-neutral text-neutral-content">
<span class="text-2xl">
{matrixStore.userId?.charAt(1).toUpperCase() || '?'}
</span>
</div>
</div>
<div>
<p class="font-medium">{matrixStore.userId}</p>
<p class="text-sm text-base-content/60">Matrix ID</p>
</div>
</div>
</div>
</section>
<!-- Server Section -->
<section class="card bg-base-200">
<div class="card-body">
<h2 class="card-title">
<Server class="h-5 w-5" />
Server
</h2>
<div class="mt-2 space-y-2 text-sm">
<div class="flex justify-between">
<span class="text-base-content/60">Homeserver</span>
<span class="font-mono">{matrixStore.client?.getHomeserverUrl() || 'Unknown'}</span>
</div>
<div class="flex justify-between">
<span class="text-base-content/60">Sync Status</span>
<span
class="badge"
class:badge-success={matrixStore.isReady}
class:badge-warning={!matrixStore.isReady}
>
{matrixStore.syncState}
</span>
</div>
<div class="flex justify-between">
<span class="text-base-content/60">Rooms</span>
<span>{matrixStore.rooms.length}</span>
</div>
</div>
</div>
</section>
<!-- Appearance Section (Placeholder) -->
<section class="card bg-base-200">
<div class="card-body">
<h2 class="card-title">
<Palette class="h-5 w-5" />
Appearance
</h2>
<p class="text-sm text-base-content/60">Theme and display settings coming soon...</p>
</div>
</section>
<!-- Notifications Section (Placeholder) -->
<section class="card bg-base-200">
<div class="card-body">
<h2 class="card-title">
<Bell class="h-5 w-5" />
Notifications
</h2>
<p class="text-sm text-base-content/60">Notification settings coming soon...</p>
</div>
</section>
<!-- Security Section (Placeholder) -->
<section class="card bg-base-200">
<div class="card-body">
<h2 class="card-title">
<Shield class="h-5 w-5" />
Security
</h2>
<p class="text-sm text-base-content/60">
End-to-end encryption settings coming in Phase 2...
</p>
</div>
</section>
<!-- Logout -->
<section class="card bg-base-200">
<div class="card-body">
<button class="btn btn-error w-full" onclick={handleLogout}>
<LogOut class="h-5 w-5" />
Sign Out
</button>
</div>
</section>
</div>
</div>
</div>

View file

@ -0,0 +1,13 @@
<script lang="ts">
import type { Snippet } from 'svelte';
interface Props {
children: Snippet;
}
let { children }: Props = $props();
</script>
<div class="flex min-h-screen items-center justify-center bg-base-100 p-4">
{@render children()}
</div>

View file

@ -0,0 +1,201 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { loginWithPassword, discoverHomeserver, checkHomeserver, matrixStore } from '$lib/matrix';
import { Eye, EyeOff, Loader2, Server, User, Lock, AlertCircle } from 'lucide-svelte';
// Form state
let homeserver = $state('matrix.mana.how');
let username = $state('');
let password = $state('');
let showPassword = $state(false);
// UI state
let loading = $state(false);
let checkingServer = $state(false);
let error = $state<string | null>(null);
let serverValid = $state<boolean | null>(null);
// Auto-discover homeserver when username looks like a full Matrix ID
let discoverTimeout: ReturnType<typeof setTimeout>;
function handleUsernameInput() {
if (username.includes(':')) {
clearTimeout(discoverTimeout);
discoverTimeout = setTimeout(async () => {
const discovered = await discoverHomeserver(username);
if (discovered) {
homeserver = discovered.replace(/^https?:\/\//, '');
await validateServer();
}
}, 500);
}
}
async function validateServer() {
if (!homeserver.trim()) {
serverValid = null;
return;
}
checkingServer = true;
const result = await checkHomeserver(homeserver);
serverValid = result.ok;
checkingServer = false;
if (!result.ok) {
error = `Server check failed: ${result.error}`;
} else {
error = null;
}
}
async function handleLogin(e: Event) {
e.preventDefault();
if (!username.trim() || !password.trim()) {
error = 'Please enter username and password';
return;
}
loading = true;
error = null;
const result = await loginWithPassword(homeserver, username, password);
if (result.success && result.credentials) {
const initialized = await matrixStore.initialize(result.credentials);
if (initialized) {
goto('/chat');
} else {
error = matrixStore.error || 'Failed to initialize Matrix client';
}
} else {
error = result.error || 'Login failed';
}
loading = false;
}
</script>
<div class="card w-full max-w-md bg-base-200 shadow-xl">
<div class="card-body">
<!-- Header -->
<div class="mb-4 text-center">
<h1 class="text-2xl font-bold">Mana Matrix</h1>
<p class="text-sm text-base-content/60">Sign in to your Matrix account</p>
</div>
<!-- Error Alert -->
{#if error}
<div class="alert alert-error mb-4">
<AlertCircle class="h-5 w-5" />
<span>{error}</span>
</div>
{/if}
<!-- Login Form -->
<form onsubmit={handleLogin} class="space-y-4">
<!-- Homeserver -->
<div class="form-control">
<label class="label" for="homeserver">
<span class="label-text flex items-center gap-2">
<Server class="h-4 w-4" />
Homeserver
</span>
{#if checkingServer}
<span class="label-text-alt">
<Loader2 class="h-4 w-4 animate-spin" />
</span>
{:else if serverValid === true}
<span class="label-text-alt text-success">Connected</span>
{:else if serverValid === false}
<span class="label-text-alt text-error">Unreachable</span>
{/if}
</label>
<input
id="homeserver"
type="text"
bind:value={homeserver}
onblur={validateServer}
class="input input-bordered"
class:input-success={serverValid === true}
class:input-error={serverValid === false}
placeholder="matrix.org"
disabled={loading}
/>
</div>
<!-- Username -->
<div class="form-control">
<label class="label" for="username">
<span class="label-text flex items-center gap-2">
<User class="h-4 w-4" />
Username
</span>
</label>
<input
id="username"
type="text"
bind:value={username}
oninput={handleUsernameInput}
class="input input-bordered"
placeholder="@user:matrix.org or username"
disabled={loading}
autocomplete="username"
/>
</div>
<!-- Password -->
<div class="form-control">
<label class="label" for="password">
<span class="label-text flex items-center gap-2">
<Lock class="h-4 w-4" />
Password
</span>
</label>
<div class="relative">
<input
id="password"
type={showPassword ? 'text' : 'password'}
bind:value={password}
class="input input-bordered w-full pr-12"
placeholder="Your password"
disabled={loading}
autocomplete="current-password"
/>
<button
type="button"
class="absolute right-3 top-1/2 -translate-y-1/2 text-base-content/50 hover:text-base-content"
onclick={() => (showPassword = !showPassword)}
tabindex={-1}
>
{#if showPassword}
<EyeOff class="h-5 w-5" />
{:else}
<Eye class="h-5 w-5" />
{/if}
</button>
</div>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-primary w-full" disabled={loading}>
{#if loading}
<Loader2 class="h-5 w-5 animate-spin" />
Signing in...
{:else}
Sign In
{/if}
</button>
</form>
<!-- Footer -->
<div class="mt-4 text-center text-sm text-base-content/60">
<p>
Don't have an account?
<a href="/register" class="link link-primary">Register</a>
</p>
</div>
</div>
</div>

View file

@ -0,0 +1,17 @@
<script lang="ts">
import '../app.css';
import type { Snippet } from 'svelte';
interface Props {
children: Snippet;
}
let { children }: Props = $props();
</script>
<svelte:head>
<title>Mana Matrix</title>
<meta name="description" content="Self-hosted Matrix chat client" />
</svelte:head>
{@render children()}

View file

@ -0,0 +1,33 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { matrixStore } from '$lib/matrix';
import { Loader2 } from 'lucide-svelte';
let checking = $state(true);
onMount(async () => {
if (!browser) return;
// Check if we have stored credentials
if (matrixStore.hasStoredCredentials()) {
// Try to initialize with stored credentials
const success = await matrixStore.initialize();
if (success) {
goto('/chat');
return;
}
}
// No valid session, go to login
goto('/login');
});
</script>
<div class="flex h-screen items-center justify-center">
<div class="text-center">
<Loader2 class="mx-auto h-8 w-8 animate-spin text-primary" />
<p class="mt-4 text-base-content/60">Loading...</p>
</div>
</div>

View file

@ -0,0 +1,17 @@
import type { RequestHandler } from '@sveltejs/kit';
export const GET: RequestHandler = async () => {
return new Response(
JSON.stringify({
status: 'ok',
timestamp: new Date().toISOString(),
service: 'matrix-web',
}),
{
status: 200,
headers: {
'Content-Type': 'application/json',
},
}
);
};

View file

@ -0,0 +1,14 @@
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
out: 'build',
}),
},
};
export default config;

View file

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ES2022",
"target": "ES2022",
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"types": ["node"]
},
"include": ["src/**/*", "src/**/*.svelte"]
}

View file

@ -0,0 +1,25 @@
import { sveltekit } from '@sveltejs/kit/vite';
import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
server: {
port: 5180,
strictPort: true,
},
define: {
global: 'globalThis',
},
optimizeDeps: {
include: ['buffer', 'events'],
esbuildOptions: {
define: {
global: 'globalThis',
},
},
},
ssr: {
noExternal: ['@manacore/shared-*', '@matrix/shared'],
},
});

8
apps/matrix/package.json Normal file
View file

@ -0,0 +1,8 @@
{
"name": "matrix",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "turbo run dev"
}
}

View file

@ -0,0 +1,18 @@
{
"name": "@matrix/shared",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./types": "./src/types.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
},
"devDependencies": {
"typescript": "^5.8.3"
}
}

View file

@ -0,0 +1,2 @@
// Re-export all types
export * from './types';

View file

@ -0,0 +1,42 @@
/**
* Shared types for Matrix client
*/
export type SyncState = 'STOPPED' | 'PREPARED' | 'SYNCING' | 'ERROR' | 'RECONNECTING' | 'CATCHUP';
export interface MatrixCredentials {
homeserver: string;
accessToken: string;
userId: string;
deviceId: string;
}
export type MessageType = 'm.text' | 'm.image' | 'm.file' | 'm.audio' | 'm.video' | 'm.emote' | 'm.notice';
export interface SimpleMessage {
id: string;
sender: string;
senderName: string;
body: string;
formattedBody?: string;
timestamp: number;
type: MessageType;
isOwn: boolean;
replyTo?: string;
edited?: boolean;
}
export interface SimpleRoom {
id: string;
name: string;
topic?: string;
avatar?: string;
lastMessage?: string;
lastMessageSender?: string;
lastMessageTime?: number;
unreadCount: number;
highlightCount: number;
isDirect: boolean;
isEncrypted: boolean;
memberCount: number;
}

View file

@ -0,0 +1,16 @@
{
"compilerOptions": {
"lib": ["ES2022"],
"module": "ES2022",
"target": "ES2022",
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"]
}

View file

@ -106,6 +106,8 @@
"todo:db:studio": "pnpm --filter @todo/backend db:studio",
"todo:db:seed": "pnpm --filter @todo/backend db:seed",
"dev:tags-test": "./scripts/setup-databases.sh todo && ./scripts/setup-databases.sh calendar && ./scripts/setup-databases.sh contacts && ./scripts/setup-databases.sh auth && concurrently -n auth,todo-be,todo-web,cal-be,cal-web,con-be,con-web -c blue,green,cyan,yellow,magenta,red,white \"pnpm dev:auth\" \"pnpm dev:todo:backend\" \"pnpm dev:todo:web\" \"pnpm dev:calendar:backend\" \"pnpm dev:calendar:web\" \"pnpm dev:contacts:backend\" \"pnpm dev:contacts:web\"",
"matrix:dev": "turbo run dev --filter=matrix...",
"dev:matrix:web": "pnpm --filter @matrix/web dev",
"moodlit:dev": "turbo run dev --filter=moodlit...",
"dev:moodlit:mobile": "pnpm --filter @moodlit/mobile dev",
"dev:moodlit:web": "pnpm --filter @moodlit/web dev",