34 Commits

Author SHA1 Message Date
Noel Maróti
277bbc14d9 Small changes + cleanup 2026-11-29 18:25:55 +01:00
Noel Maróti
05e24d768a Ported MessagesView to V3 2026-11-29 18:25:33 +01:00
Noel Maróti
eaa355e40e Updated MessageBox to align with schema changes 2026-11-29 18:25:26 +01:00
Noel Maróti
8fc0da520c Updated DmComponent (partially) to V3 2026-11-29 18:25:06 +01:00
Noel Maróti
7149ebad10 Re-implemented DmStore in V3 2026-11-29 18:24:50 +01:00
Noel Maróti
34752b446c Minor changes 2026-11-29 11:50:17 +01:00
Noel Maróti
c18a8c14ca Updated 'chatid' parameter to 'contactId' 2026-11-29 11:50:08 +01:00
Noel Maróti
bc8501d74c Renamed Cache to CacheService to prevent name collisions 2026-11-29 11:49:55 +01:00
Noel Maróti
76d96067d0 Removed old redundant initializers 2026-11-29 11:49:41 +01:00
Noel Maróti
aa3494eac0 Updated DM chat initialization to use V3 API and V2 SDK 2026-11-29 11:49:15 +01:00
Noel Maróti
e386608e59 Updated Chatenium SDK 2026-11-29 11:48:16 +01:00
Noel Maróti
56d6065eef Minor update 2026-11-28 07:14:03 +01:00
Noel Maróti
aa811bff1b Added new variable to help with timing 2026-11-28 07:13:50 +01:00
Noel Maróti
b4ff8356ab Updated Chatenium SDK 2026-11-28 07:13:39 +01:00
Noel Maróti
f836df391b Renamed DmList to ContactList and updated logic to V3 2026-11-28 07:13:31 +01:00
Noel Maróti
1988c0a61e New singleton to hold cache globally in-memory 2026-11-28 07:13:18 +01:00
Noel Maróti
043a97ada5 New component (WIP) to handle avatar image loading, blurHash display and monogram avatar generation for accounts without PFPs (now possible in API/v3) 2026-11-28 07:13:00 +01:00
Noel Maróti
3ef5387b8d Finished implementing sign-in procedure for API/v3. Updated guards to V3 and started rewriting /chat too. UserData updating and multi-user support is TODO 2026-11-27 22:07:32 +01:00
Noel Maróti
086d27c9a4 Added transtitions in sign-in flow and implemented Google OAuth 2026-11-24 20:01:51 +01:00
Noel Maróti
eeee9d5154 Started rewriting SignIn component to use new V3 API. TODO methods: Google, Apple and SMS 2026-11-22 19:36:44 +01:00
aa3e1de412 Merged network view with chat sidenav and updated the look of the category/channel list to a threaded one 2026-10-04 17:42:03 +02:00
f9518a9164 Scrolling bug fix 2026-04-27 18:12:18 +02:00
3ed025ee61 UI Hotfix 2026-04-19 16:12:59 +02:00
5f032c5098 Finished implementing user settings -> security 2026-04-19 12:37:52 +02:00
20e67ecd85 Started implementing user settings -> security -> e-mail management 2026-04-18 19:28:51 +02:00
4eaaacac2c Started implementing user settings -> security -> password management 2026-04-18 15:24:37 +02:00
8afd4a81b0 3.0 Beta 8 2026-04-17 17:55:42 +02:00
a0a6fdaf55 3.0 Beta 7 2026-04-15 17:35:55 +02:00
0dc1e15e59 3.0 Beta 6 2026-04-14 17:51:02 +02:00
931ac91526 3.0 Beta 5 2026-04-13 15:14:24 +02:00
c56b0aab8a Started implementing Chatenium Pictures 2026-04-12 17:40:51 +02:00
62bc82f158 3.0 Beta 4 2026-04-11 17:23:19 +02:00
7e5ea20409 3.0 Beta 3 2026-04-11 13:22:56 +02:00
a01b5347d6 3.0 Beta 2 2026-04-10 21:57:29 +02:00
155 changed files with 9084 additions and 2088 deletions

View File

@@ -1,2 +1,2 @@
# Chatenium On Web
A modern web application for Chatenium compatible with a wide range of devices.
# Chatenium Nexum
The next generation Web application for Chatenium, built on modern standards powered by Chatenium SDK (TypeScript).

View File

@@ -24,6 +24,11 @@
"glob": "**/*",
"input": "public"
},
{
"glob": "**/*",
"input": "node_modules/@taiga-ui/icons/src",
"output": "assets/taiga-ui/icons"
},
{
"glob": "**/*",
"input": "node_modules/@taiga-ui/icons/src",
@@ -42,15 +47,16 @@
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
"maximumError": "100MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
"maximumError": "100MB"
}
],
"outputHashing": "all"
"outputHashing": "all",
"serviceWorker": "ngsw-config.json"
},
"development": {
"optimization": false,

30
ngsw-config.json Normal file
View File

@@ -0,0 +1,30 @@
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.csr.html",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}

4620
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -18,18 +18,28 @@
"@angular/forms": "^21.2.0",
"@angular/platform-browser": "^21.2.0",
"@angular/router": "^21.2.0",
"@chatenium/chatenium-sdk": "^1.1.3",
"@angular/service-worker": "^21.2.0",
"@chatenium/chatenium-sdk": "^1.2.2",
"@fortawesome/angular-fontawesome": "^4.0.0",
"@fortawesome/free-brands-svg-icons": "^7.1.0",
"@fortawesome/free-solid-svg-icons": "^7.1.0",
"@ngx-translate/core": "^17.0.0",
"@ngx-translate/http-loader": "^17.0.0",
"@taiga-ui/addon-charts": "^5.1.0",
"@taiga-ui/addon-mobile": "^5.1.0",
"@taiga-ui/addon-table": "^5.1.0",
"@taiga-ui/cdk": "^5.1.0",
"@taiga-ui/core": "^5.1.0",
"@taiga-ui/icons": "^5.1.0",
"@taiga-ui/kit": "^5.1.0",
"@taiga-ui/layout": "^5.1.0",
"@taiga-ui/addon-charts": "^5.25.0",
"@taiga-ui/addon-commerce": "^5.25.0",
"@taiga-ui/addon-doc": "^5.25.0",
"@taiga-ui/addon-mobile": "^5.25.0",
"@taiga-ui/addon-table": "^5.25.0",
"@taiga-ui/cdk": "^5.25.0",
"@taiga-ui/core": "^5.25.0",
"@taiga-ui/i18n": "^5.2.0",
"@taiga-ui/icons": "^5.25.0",
"@taiga-ui/kit": "^5.25.0",
"@taiga-ui/layout": "^5.25.0",
"chatenium-sdk-preview": "npm:@chatenium/chatenium-sdk@^2.0.0-preview.7",
"libphonenumber-js": "^1.12.41",
"ngx-cookie-service": "^21.3.1",
"ngx-device-detector": "^11.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"uuid": "^13.0.0"
@@ -38,6 +48,7 @@
"@angular/build": "^21.2.6",
"@angular/cli": "^21.2.6",
"@angular/compiler-cli": "^21.2.0",
"@types/google.accounts": "^0.0.18",
"jsdom": "^28.0.0",
"less": "^4.6.4",
"prettier": "^3.8.1",

BIN
public/Kinn-Book.ttf Normal file

Binary file not shown.

BIN
public/Kinn-Heavy.ttf Normal file

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -1,24 +1,277 @@
{
"version": "Chatenium Nexum 3.0 Beta 11 (October 4, 2026)",
"ok": "Ok",
"back": "Back",
"aChatProgram": "A messaging platform that you can trust.",
"fast": "Fast",
"secure": "Secure",
"independent": "Independent",
"scrollDownForMore": "Scroll down for more",
"whatIsChtn": "Chatenium is a chat platform aiming to provide a secure, well integrated fast chatting experience across any devices. You can create a new account for free and start chatting and broadcasting messages.",
"updating": "Updating...",
"home": {
"soon": "Coming soon...",
"chtn": "Chatenium ",
"chtnIs": "Chatenium is ",
"help": "Help",
"blog": "Blog",
"apiSpecs": "API specifications",
"adaptsTo": "Chatenium adapts to ",
"adaptsToYouDesc": "Choose your platform:",
"chtnOnWeb": "Chatenium On Web",
"chtnOnWebDesc": "Built for maximum compatibility. The Web will work on every device you have.",
"chtnOnAndroid": "Chatenium On Android™",
"chtnOnAndroidDesc": "Built to work beautifully with your Android™ device. Blends in beautifully with your Material You theme.",
"chtnOnApple": "Chatenium On Apple®",
"chtnOnAppleDesc": "Built with the latest Liquid Glass design to blend in and work flawlessly across all your Apple® devices.",
"chtnOnWindows": "Chatenium On Windows®",
"chtnOnWindowsDesc": "We are also expanding our native apps to Microsoft Windows®, because using a web app is resource intensive and inferior to a native application. So we built a fully native Windows® application using WinUI3 + C#.",
"chtnOnLinux": "Chatenium On Linux",
"chtnOnLinuxDesc": "Built on the latest GNOME Adwaita design language to beautifully blend into the GNOME desktop environment on Linux.",
"chtnEcho": "Chatenium Echo",
"chtnEchoDesc": "Built on the GNOME GTK design language to beautifully blend into any GTK based desktop environment on Linux.",
"chtnReson": "Chatenium Reson",
"chtnResonDesc": "Built on the KDE Kirigami design language to beautifully blend into KDE or any other Qt based desktop environment on Linux.",
"tba": "To be announced",
"secure": "secure",
"secureDesc": "Chatenium uses the latest algorithms to protect your data from any third-parties.",
"secureCdn": "Encrypted CDN",
"secureCdnDesc": "All uploaded media is encrypted and never accessed by anyone outside your chat. Not even by us. All deleted media are permanently removed from our servers and databases.",
"encryptedText": "Encrypted messages",
"encryptedTextDesc": "Any message that is sent to any DM chat or channel is encrypted and stored securely in our databases. We do not share your messages with any third-parties.",
"zeroDataCollection": "Zero data collection",
"zeroDataCollectionDesc": "Our policies allow zero data collection. We do not collect any data from our clients.",
"secureCalling": "Secure calls",
"secureCallingDesc": "When using Chatenium Call, all audio and video tracks are sent to our servers for secure distribution. No audio or video is ever recorded by our servers under any circumstances.",
"zeroDigitalFootprint": "Zero digital footprint",
"zeroDigitalFootprintDesc": "We make it easy to delete your account from our services and we make sure to remove all data made by you.",
"underDevelopment": "Under development",
"devPreview": "Developer Preview",
"weAreExcitedFor": "We are excited for ",
"you": "you",
"weAreExcitedForYouDesc": "Our community awaits you with love. We are independent, so you can express your true feelings without getting censored.",
"enterChtnOnWeb": "Enter Chatenium On Web",
"enterChtnOnWebDesc": "Register your account here are access the latest experimental features we can offer. The web is mobile-friendly and offers offline mode.",
"downloadChtnOnAndroid": "Get Chatenium On Android",
"downloadChtnOnAndroidDesc": "We are preparing a Google Play release right now. Don't worry, you can get access to .apk releases in the official 'Chatenium' network.",
"downloadChtnOnApple": "Get Chatenium On Apple",
"downloadChtnOnAppleDesc": "We are preparing an App Store release right now. Don't worry, you can get access to .ipa (.dmg soon) releases in the official 'Chatenium' network.",
"storeReleaseSoon": "Store release coming soon...",
"closedAlpha": "Closed alpha",
"openBeta": "Beta",
"openBetaDesc": "Participate in public beta testing to help us create the best app experience!",
"closedAlphaDesc": "Great news! You are eligible to participate in the testing program. All we need is your e-mail address.",
"alphaRequestedSuccessfully": "Request sent successfully! We will get back to you later.",
"alphaRequestAlreadySent": "You already requested an alpha access! We will get back to you later.",
"alphaRequestError": "Something went wrong. Please try again later.",
"cookies": "Cookies",
"cookiesDesc": "Chatenium is using cookies to securely store your session token. No cookies are used for tracking purposes",
"understood": "Understood",
"privacyPolicy": "Privacy policy",
"tos": "Terms of services",
"requestAlphaAccess": "Start beta testing",
"joinGoogleGroup": "Our Google Group",
"joinGoogleGroupWhy": "All you need to do is join our Google Group and you can join the beta testing program via the link provided in the group.",
"testFlight": "Apple TestFlight",
"testFlightDesc": "Start testing the application on your Apple device via TestFlight!",
"downloadOnWindows": "Get Chatenium On Windows",
"microsoftStore": "Microsoft Store",
"microsoftStoreDesc": "Start testing the application on your Windows computer via the Microsoft Store!"
},
"signIn": {
"formTitle": "Sign in",
"mainInput": {
"label": "Username, email or phone number",
"placeholder": "bob, bob@example.com, +36201234567"
"initial": {
"formTitle": "Welcome back!",
"formSubtitle": "Sign in with your Chatenium account.",
"mainInput": {
"label": "Username, email or phone number",
"placeholder": "bob, bob@example.com, +36201234567"
},
"password": {
"label": "Password"
},
"signInButton": "Sign in"
},
"password": {
"label": "Password"
"methodChoose": {
"formTitle": "Choose a verification method",
"formSubtitle": "Based on your security settings, more than 1 verification method may be required.",
"formTitleAlt": "Choose another verification method",
"formSubtitleAlt": "Because of your security settings, multiple verification methods are required",
"methods": {
"password": {
"title": "Password",
"desc": "Use your password to verify your identity"
},
"mail": {
"title": "E-mail",
"desc": "Use a one-time e-mail code to verify your identity"
},
"sms": {
"title": "SMS",
"desc": "Use a one-time SMS code to verify your identity"
},
"google": {
"title": "Google",
"desc": "Use your linked Google account to verify your identity"
},
"apple": {
"title": "Apple",
"desc": "Use your linked Apple account to verify your identity"
}
}
},
"emailButton": "Sign in with email code",
"smsButton": "Sign in with SMS code",
"signInButton": "Sign in",
"errors": {
"unameMailPhoneRequired": "Username, email or phone number is required",
"passwordRequired": "Password is required",
"passwordIncorrect": "Password is incorrect"
"anyAuth": {
"verifyButton": "Verify identity"
},
"passwordAuth": {
"formTitle": "Password authentication",
"formSubtitle": "Enter your password below",
"errors": {
"passwordRequired": "Password is required",
"passwordIncorrect": "Password is incorrect"
}
},
"emailAuth": {
"formTitle": "E-mail authentication",
"formSubtitle": "Enter your one-time e-mail code below",
"errors": {
"passwordRequired": "Code is required",
"passwordIncorrect": "Code is incorrect"
},
"emailCode": {
"label": "E-mail code"
}
}
},
"chat": {
"userSettingsDialog": {
"label": "Settings",
"options": {
"security": "Privacy & Security",
"profile": "Profile",
"themes": "Themes",
"sessions": "Sessions",
"storage": "Data and Storage"
},
"security": {
"changePasswordDialog": {
"label": "Change password",
"labelSet": "Set password",
"labelRemove": "Remove password",
"warn": "After you change your password, you will be logged out of all your sessions.",
"currentPassword": "Current password",
"newPassword": "New password",
"newPasswordRepeat": "Repeat new password"
},
"changeEmailDialog": {
"label": "Change e-mail address",
"labelSet": "Set e-mail address",
"labelRemove": "Remove e-mail address",
"warn": "After you change your e-mail address, you will be logged out of all your sessions.",
"newMail": "New e-mail address",
"currentPassword": "Current password",
"oldCode": "Code sent to the old e-mail address",
"newCode": "Code sent to the new e-mail address"
},
"changePhoneDialog": {
"label": "Change phone number",
"labelSet": "Set phone number",
"labelRemove": "Remove phone number",
"warn": "After you change your phone number, you will be logged out of all your sessions.",
"newPhone": "New phone number",
"currentPassword": "Current password",
"oldCode": "Code sent to the old phone number",
"newCode": "Code sent to the new phone number"
},
"label": "Keep your account safe by using as much sign in methods as possible. Also check your credentials regularly to keep them up to date.",
"password": "Password",
"set": "Set",
"notSet": "Not set",
"changePassword": "Change password",
"phoneNumber": "Phone number",
"email": "E-mail address",
"removePassword": "Remove password",
"changePhone": "Change phone number",
"changeMail": "Change e-mail address",
"removePhone": "Remove phone number",
"removeMail": "Remove e-mail address",
"setPassword": "Set password",
"setPhone": "Set phone number",
"setMail": "Set e-mail address"
}
},
"tabBar": {
"tab1": "Chats",
"tab2": "Networks",
"tab3": "Pictures",
"tab4": "Settings"
},
"network": {
"tabs": {
"channels": "Channels",
"members": "Members",
"settings": "Settings"
},
"settings": {
"options": {
"categories": {
"apps": "Apps",
"moderation": "Moderation",
"community": "Community"
},
"overview": "Overview",
"rank": "Ranks",
"emoji": "Emojis",
"embed": "Embed",
"invite": "Invites",
"webhook": "Webhooks",
"bots": "Bots",
"activityHistory": "Activity history",
"bans": "Bans",
"communityChannels": "Community channels",
"networkIntroducer": "Network introducer",
"members": "Members"
},
"overviewPage": {
"networkPicture": "Network picture",
"networkName": "Network name",
"networkVisibility": "Network visibility",
"uploadNewPicture": "Upload new picture",
"setNewName": "Set new name",
"changeToPrivate": "Change to private",
"changeToPrivateDialog": {
"label": "You are about to make your network private",
"warn": {
"1": "Your network will be delisted from Network Discovery.",
"2": "Users will no longer be able to freely join your network without an invite.",
"3": "Your broadcasts may be unavailable to users outside your network."
}
},
"changeToPublic": "Change to public",
"changeToPublicDialog": {
"label": "You are about to make your network public",
"warn": {
"1": "Your network will be listed in Network Discovery.",
"2": "Users will be able to freely join your network without an invite.",
"3": "Your broadcasts will be available to users outside your network."
}
},
"setNewNameDialog": {
"label": "New name"
}
}
}
},
"changeLogDialog": {
"label": "Chatenium has been updated",
"changeLog": {
"1": "The network UI have been merged with the left side navigation panel.",
"2": "Categories and channels now have a threaded UI to align with recent changes"
}
},
"chatnav": {
"pictureList": {
"myPictures": "My pictures"
},
"dmList": {
"newChat": "Start new chat",
"messageBox": {
@@ -26,10 +279,20 @@
"you": "You: "
}
}
},
"networkList": {
"newNetwork": "Start new network"
}
},
"pictures": {
"albumList": {
"noAlbum": "This user has no albums published"
}
},
"elements": {
"messageBox": {
"editMessageLabel": "Editing message: ",
"attachments": "Attachment(s)",
"placeholder": "Type a message...",
"message": "Message",
"uplDrag": {
@@ -39,6 +302,12 @@
"fileUploadDialog": {
"label": "Upload files"
}
},
"messages": {
"contextMenu": {
"edit": "Edit",
"delete": "Delete"
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 635 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 658 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 769 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 836 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

BIN
public/icons/icon-72x72.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
public/icons/icon-96x96.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 487 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 444 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 391 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

BIN
public/images/logo/logo.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
public/images/logo/logo_beta.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

BIN
public/images/logo/logo_short.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

BIN
public/images/logo/logoold.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -0,0 +1,57 @@
{
"name": "Chatenium",
"short_name": "Chtn",
"display": "standalone",
"scope": "./",
"start_url": "./",
"icons": [
{
"src": "icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
]
}

View File

@@ -1,23 +1,39 @@
import {provideTaiga} from '@taiga-ui/core';
import {ApplicationConfig, provideBrowserGlobalErrorListeners} from '@angular/core';
import {provideRouter} from '@angular/router';
import { provideTaiga } from '@taiga-ui/core';
import { ApplicationConfig, provideBrowserGlobalErrorListeners, isDevMode } from '@angular/core';
import { provideRouter, withRouterConfig } from '@angular/router';
import {routes} from './app.routes';
import {provideTranslateService} from '@ngx-translate/core';
import {provideTranslateHttpLoader} from '@ngx-translate/http-loader';
import { routes } from './app.routes';
import { provideTranslateService } from '@ngx-translate/core';
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
import { provideServiceWorker } from '@angular/service-worker';
import { tuiInputPhoneInternationalOptionsProvider } from '@taiga-ui/kit';
import { defer } from 'rxjs';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideRouter(
routes,
withRouterConfig({
paramsInheritanceStrategy: 'always',
}),
),
provideTaiga(),
provideTranslateService({
fallbackLang: "en",
lang: "hu",
fallbackLang: 'en',
lang: 'en',
loader: provideTranslateHttpLoader({
prefix: "/i18n/",
suffix: ".json"
})
})
prefix: '/i18n/',
suffix: '.json',
}),
}),
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000',
}),
tuiInputPhoneInternationalOptionsProvider({
metadata: defer(async () => import('libphonenumber-js/max/metadata').then((m) => m.default)),
}),
provideTaiga(),
],
};

View File

@@ -1,13 +1,29 @@
import {Routes} from '@angular/router';
import {SignIn} from './signin/signin';
import {Chat} from './chat/chat';
import {Dm} from './chat/dm/dm';
import { Routes } from '@angular/router';
import { SignIn } from './signin/signin';
import { Chat } from './chat/chat';
import { Dm } from './chat/dm/dm';
import { noAuthGuard } from './guards/no-auth-guard';
import { authNeededGuard } from './guards/auth-needed-guard';
import { Homepage } from './homepage/homepage';
import { Privacy } from './privacy/privacy';
import { TOS } from './tos/tos';
import { Network } from './chat/network/network';
import { Text } from './chat/network/channel/text/text';
import { See } from './chat/picture/see/see';
export const routes: Routes = [
{path: 'signin', component: SignIn},
{ path: '', component: Homepage },
{ path: 'privacy', component: Privacy },
{ path: 'tos', component: TOS },
{ path: 'signin', component: SignIn, canActivate: [noAuthGuard] },
{
path: 'chat', component: Chat, children: [
{path: 'dm/:chatid', component: Dm},
]
path: 'chat',
component: Chat,
canActivate: [authNeededGuard],
children: [
{ path: 'dm/:contactId', component: Dm },
{ path: 'picture/:uploaderId', component: See },
{ path: 'network/:networkId/:categoryId/:channelId', component: Text },
],
},
];

View File

@@ -1,18 +1,20 @@
import { TuiRoot } from '@taiga-ui/core';
import {Component, inject, OnInit, signal} from '@angular/core';
import { Component, inject, OnInit, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { environment as env } from '../environments/environment';
import {environment, SDKConfig} from '@chatenium/chatenium-sdk/core/environment';
import {IndexedDB} from './storage/indexed-db';
import { environment, SDKConfig } from '@chatenium/chatenium-sdk/core/environment';
import { IndexedDB } from './storage/indexed-db';
import { SessionManager } from './session-manager';
@Component({
selector: 'app-root',
imports: [RouterOutlet, TuiRoot],
imports: [RouterOutlet, TuiRoot, TuiRoot],
templateUrl: './app.html',
styleUrl: './app.scss',
})
export class App implements OnInit {
indexedDb = inject(IndexedDB)
indexedDb = inject(IndexedDB);
sessionManager = inject(SessionManager);
protected readonly title = signal('Chatenium-On-Web');
@@ -22,5 +24,8 @@ export class App implements OnInit {
apiUrl: env.api_url,
wsUrl: env.ws_url,
});
this.indexedDb.openDatabase().then(() => {
this.sessionManager.loadSessions();
})
}
}

16
src/app/cache.spec.ts Normal file
View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { CacheService } from './cache';
describe('Cache', () => {
let service: CacheService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CacheService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

31
src/app/cache.ts Normal file
View File

@@ -0,0 +1,31 @@
import { Injectable, signal, WritableSignal } from '@angular/core';
import { MessagesViewModel } from './chat/elements/messages/messages-viewmodel';
import { MessageBoxViewModel } from './chat/elements/message-box/message-box-viewmodel';
import {WrappedDMHandler, DirectMessagingApi, Contact, Message} from "chatenium-sdk-preview"
@Injectable({
providedIn: 'root',
})
export class CacheService {
contacts = signal<Contact[]>([]);
contactsState = signal<LoadState>(LoadState.CLEAN_LOADING);
dms = signal<Record<string, DmStorage>>({});
}
export enum LoadState {
CLEAN_LOADING,
CACHE_UPDATING,
LOADED,
ERROR,
}
export interface DmStorage {
handler: WrappedDMHandler<DirectMessagingApi>;
messages: WritableSignal<Message[]>;
messagesState: WritableSignal<LoadState>;
messagesVm: MessagesViewModel;
chatData: WritableSignal<Contact>;
messageBox: MessageBoxViewModel;
wsListener: (action: string, message: string) => void;
}

View File

@@ -1,39 +1,141 @@
@if (serviceManager.currentSession() == null) {
<ng-template [(tuiDialog)]="changeLogOpen"
[tuiDialogOptions]="{closable: false, dismissible: false, label: 'chat.changeLogDialog.label'|translate}">
<h3>{{ "version"|translate }}</h3>
<ul>
<li>{{ "chat.changeLogDialog.changeLog.1"|translate }}</li>
<li>{{ "chat.changeLogDialog.changeLog.2"|translate }}</li>
</ul>
<button tuiButton iconStart="@tui.check"
(click)="localStorage.setItem('changeLogLastRead', environment.version); changeLogOpen.set(false)">{{ "ok"|translate }}
</button>
</ng-template>
<ng-template [(tuiDialog)]="userSettingsOpen" [tuiDialogOptions]="{closable: false, appearance: 'taiga big'}"
class="user-settings">
<user-settings (close)="userSettingsOpen.set(false)" />
</ng-template>
@if (!sessionManager.sessionReady()) {
<main style="width: 100%; height: 100svh; display: flex; justify-content: center; align-items: center;">
<tui-loader size="xl"/>
<tui-loader size="xl" />
</main>
} @else {
<main id="layout" tuiGroup [collapsed]="true">
<aside id="chatnav">
<aside>
<tui-segmented id="mode_switcher">
<button>
<tui-icon icon="@tui.message-circle"/>
</button>
<button>
<tui-icon icon="@tui.network"/>
</button>
<button>
<tui-icon icon="@tui.image"/>
</button>
</tui-segmented>
@if (breakpoint() != "mobile") {
<main id="layout" tuiGroup [collapsed]="true" [class.expanded]="expandedSidenav()">
<aside id="chatnav">
<aside>
<tui-segmented id="mode_switcher" [(activeItemIndex)]="navigationActiveIndex">
<button (click)="expandedSidenav.set(false)">
<tui-icon icon="@tui.message-circle" />
</button>
<button>
<tui-icon icon="@tui.network" />
</button>
<button (click)="expandedSidenav.set(false)">
<tui-icon icon="@tui.image" />
</button>
</tui-segmented>
<button id="bottom_btn" tuiButton appearance="flat">
<tui-icon icon="@tui.cog"/>
</button>
<button id="bottom_btn" tuiButton [appearance]="userSettingsOpen() ? 'primary' : 'flat'"
(click)="userSettingsOpen.set(true)">
<tui-icon icon="@tui.cog" />
</button>
</aside>
<main>
@switch (navigationActiveIndex) {
@case (0) {
<app-contact-list></app-contact-list>
} <!--
@case (1) {
<network-list
[(expandedSidenav)]="expandedSidenav"
[token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></network-list>
}
@case (2) {
<app-picture-list [token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
}-->
}
</main>
</aside>
<main>
<app-dm-list [token]="serviceManager.currentSession()!.token" [userid]="serviceManager.currentSession()!.userData.userid"></app-dm-list>
<main id="content">
<div id="content_tint">
@if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) {
<!-- To ensure data is loaded -->
@defer (when cache.contactsState() != LoadState.CLEAN_LOADING) {
<router-outlet />
}
} @else if (router.url.startsWith("/chat/network")) {
@defer (when serviceManager.networksStatus() != LoadStatus.loading) {
<router-outlet />
}
} @else {
<router-outlet />
}
</div>
</main>
</aside>
<main id="content">
<div id="content_tint">
@defer (when serviceManager.chatsStatus() != LoadStatus.loading) {
<router-outlet/>
}
</div>
</main>
</main>
} @else {
<main id="layout_mobile">
@if (!routerOutletActive()) {
<div id="navigation">
<div id="navigation_content">
<!--
@switch (navigationActiveIndex) {
@case (0) {
<app-contact-list [token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></app-contact-list>
}
@case (1) {
<network-list
[(expandedSidenav)]="expandedSidenav"
[token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></network-list>
}
@case (2) {
<app-picture-list [token]="serviceManager.currentSession()!.token"
[userid]="serviceManager.currentSession()!.userData.userid"></app-picture-list>
}
@case (3) {
<user-settings />
}
}
-->
</div>
<nav tuiTabBar [(activeItemIndex)]="navigationActiveIndex">
@for (item of tabBarItems; track item; let i = $index) {
<button
[disabled]="!item.implemented"
[class.disabled]="!item.implemented"
tuiTabBarItem
type="button"
[icon]="item.icon"
(click)="navigationActiveIndex = i"
>
{{ item.text | translate }}
</button>
}
</nav>
</div>
}
@if (router.url.startsWith("/chat/dm") || router.url.startsWith("/chat/picture")) {
<!-- To ensure data is loaded -->
@defer (when serviceManager.chatsStatus() != LoadStatus.loading) {
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
}
} @else if (router.url.startsWith("/chat/network")) {
@defer (when serviceManager.networksStatus() != LoadStatus.loading) {
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
}
} @else {
<router-outlet (activate)="routerOutletActive.set(true)" (deactivate)="routerOutletActive.set(false)" />
}
</main>
}
}

View File

@@ -1,12 +1,17 @@
#layout {
transition: 0.3s ease;
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
height: 100svh;
overflow: hidden;
&.expanded {
grid-template-columns: 450px minmax(0, 1fr) !important;
}
#chatnav {
display: grid;
grid-template-columns: 70px minmax(0, 1fr);
height: 100svh;
aside {
padding: 15px;
@@ -25,6 +30,12 @@
button {
height: 50px;
tui-icon {
&::before {
color: var(--tui-background-accent-1);
}
}
}
}
@@ -37,6 +48,8 @@
}
main {
overflow-y: scroll;
overflow-x: hidden;
background: var(--tui-background-base-alt);
border-radius: 20px 0 0 20px;
margin: 10px 0 10px 10px;
@@ -46,13 +59,39 @@
#content {
width: 100%;
height: 100svh;
padding: 10px 10px 10px 0;
#content_tint {
border-radius: 0 20px 20px 0;
height: 100%;
background: var(--tui-background-neutral-2);
padding: 15px;
}
}
}
#layout_mobile {
height: 93svh;
#navigation {
height: 100%;
grid-template-rows: 1fr 50px;
button {
&.disabled {
opacity: 0.5;
}
}
#navigation_content {
overflow-y: scroll;
height: 100%;
padding: 20px;
}
}
}
::ng-deep tui-dialog[data-appearance~=big] {
height: 90svh;
width: 90svw !important;
}

View File

@@ -1,13 +1,22 @@
import {Component, inject, OnInit} from '@angular/core';
import {RouterOutlet} from '@angular/router';
import {Component, computed, inject, OnInit, signal} from '@angular/core';
import {isActive, IsActiveMatchOptions, Router, RouterOutlet} from '@angular/router';
import {TuiSegmented} from '@taiga-ui/kit';
import {TuiAppearance, TuiButton, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
import {LoadStatus, ServiceManager} from '../service-manager';
import {IndexedDB} from '../storage/indexed-db';
import {DmList} from './dm-list/dm-list';
import {ContactList} from './contact-list/contact-list';
import {JsonPipe} from '@angular/common';
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
import {TranslatePipe, TranslateService} from '@ngx-translate/core';
import {environment} from '../../environments/environment';
import {TuiTabBarComponent, TuiTabBarItem} from '@taiga-ui/addon-mobile';
import {NetworkList} from './network-list/network-list';
import {PictureList} from './picture-list/picture-list';
import {UserSettings} from './user-settings/user-settings';
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
import {UserService} from '@chatenium/chatenium-sdk/services/userService';
import { SessionManager } from '../session-manager';
import { CacheService, LoadState } from '../cache';
@Component({
selector: 'app-chat',
@@ -17,25 +26,78 @@ import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
TuiIcon,
TuiButton,
TuiLoader,
DmList,
ContactList,
JsonPipe,
TuiAppearance,
TuiGroup
TuiGroup,
TuiDialog,
TranslatePipe,
TuiTabBarComponent,
TuiTabBarItem,
NetworkList,
PictureList,
UserSettings
],
templateUrl: './chat.html',
styleUrl: './chat.scss',
})
export class Chat implements OnInit {
serviceManager = inject(ServiceManager)
indexedDb = inject(IndexedDB)
sessionManager = inject(SessionManager);
serviceManager = inject(ServiceManager);
cache = inject(CacheService);
indexedDb = inject(IndexedDB);
breakpoint = inject(TUI_BREAKPOINT);
router = inject(Router);
expandedSidenav = signal(false)
routerOutletActive = signal(false)
userSettingsOpen = signal(false)
navigationActiveIndex = 0
// Mobile navigation //
protected readonly tabBarItems = [
{
text: "chat.tabBar.tab1",
icon: '@tui.message-circle',
implemented: true,
},
{
text: "chat.tabBar.tab2",
icon: '@tui.network',
implemented: true,
},
{
text: "chat.tabBar.tab3",
icon: '@tui.image',
implemented: true,
},
{
text: "chat.tabBar.tab4",
icon: '@tui.cog',
implemented: true,
}
];
changeLogOpen = signal(false)
async ngOnInit() {
this.indexedDb.openDatabase().then(async () => {
const session = await this.serviceManager.sessionManager.loadPreferredSession()
this.serviceManager.currentSession.set(session)
await WebSocketHandler.getInstance().connect(session.userData.userid, session.token)
})
if (this.router.url.startsWith("/chat/network")) {
this.navigationActiveIndex = 1
} else if (this.router.url.startsWith("/chat/picture")) {
this.navigationActiveIndex = 2
}
setTimeout(() => {
const latestRead = localStorage.getItem("changeLogLastRead")
if (latestRead != environment.version) {
this.changeLogOpen.set(true)
}
}, 50)
}
protected readonly LoadStatus = LoadStatus;
protected readonly localStorage = localStorage;
protected readonly environment = environment;
protected readonly LoadState = LoadState;
}

View File

@@ -0,0 +1,31 @@
<button disabled tuiButton appearance="secondary" iconStart="@tui.mail-plus">
{{ "chat.chatnav.dmList.newChat"|translate }}
</button>
@if (cache.contactsState() == LoadState.CACHE_UPDATING) {
<div id="loader">
<tui-loader/>
{{ "updating"|translate }}
</div>
}
@for (contact of cache.contacts(); track contact.contactId) {
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton
[appearance]="router.url == '/chat/dm/' + contact.contactId ? 'primary' : 'flat'"
[routerLink]="'/chat/dm/' + contact.contactId">
<avatar height="35px" width="35px" [radius]="10" [src]="contact.pfp" [name]="contact.username"></avatar>
<div class="info">
@if (contact.displayName == "") {
<span>{{ '@' + contact.username }}</span>
} @else {
<span>{{ contact.displayName }}</span>
}
@if (contact.latestMessage) {
<span class="latest_message">
@if (contact.latestMessage.isAuthor) {
{{ "chat.chatnav.dmList.messageBox.latestMessage.you"|translate }}
}
{{ contact.latestMessage.message }}
</span>
}
</div>
</button>
}

View File

@@ -0,0 +1,36 @@
:host {
display: flex;
flex-direction: column;
gap: 5px;
#loader {
width: 100%;
display: flex;
justify-content: start;
padding: 5px;
gap: 5px;
}
button {
width: 100%;
display: flex;
justify-content: start;
font-weight: 600;
&.enlarge {
height: 75px;
}
.info {
display: flex;
flex-direction: column;
text-align: start;
.latest_message {
margin-top: -5px;
font-size: 12px;
opacity: 50%;
}
}
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContactList } from './contact-list';
describe('PictureList', () => {
let component: ContactList;
let fixture: ComponentFixture<ContactList>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ContactList],
}).compileComponents();
fixture = TestBed.createComponent(ContactList);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,65 @@
import {Component, inject, input, OnInit} from '@angular/core';
import {ChatService} from '@chatenium/chatenium-sdk/services/chatService';
import {IndexedDB} from '../../storage/indexed-db';
import { TUI_BREAKPOINT, TuiButton, TuiLoader, TuiNotificationService } from '@taiga-ui/core';
import {Oimg} from '../elements/oimg/oimg';
import {Router, RouterLink} from '@angular/router';
import {TranslatePipe} from '@ngx-translate/core';
import {LoadStatus, ServiceManager} from '../../service-manager';
import { Contact } from 'chatenium-sdk-preview';
import { CHATENIUM_SDK } from '../../chatenium.token';
import { CacheService, LoadState } from '../../cache';
import { Avatar } from '../elements/avatar/avatar';
@Component({
selector: 'app-contact-list',
imports: [TuiButton, Oimg, RouterLink, TranslatePipe, TuiLoader, Avatar],
templateUrl: './contact-list.html',
styleUrl: './contact-list.scss',
})
export class ContactList implements OnInit {
SDK = inject(CHATENIUM_SDK);
idb = inject(IndexedDB);
router = inject(Router);
cache = inject(CacheService);
notification = inject(TuiNotificationService);
serviceManager = inject(ServiceManager);
breakpoint = inject(TUI_BREAKPOINT);
async ngOnInit() {
if (this.cache.contactsState() != LoadState.LOADED) {
try {
const contacts = (await this.idb.getAll('contacts')) as Contact[];
if (contacts.length > 0) {
this.cache.contacts.set(contacts);
this.cache.contactsState.set(LoadState.CACHE_UPDATING);
} else {
console.log("Found no contacts in cache")
}
} catch (e) {
console.warn(`Contacts cache load failed: ${e}. Skipping cache load...`);
}
try {
const resp = await this.SDK.contacts.getContacts();
const data = resp.data as Contact[];
if (data == null) {
console.log("No contacts were fetched - user possibly has 0 contacts")
this.cache.contactsState.set(LoadState.LOADED);
return
}
this.cache.contacts.set(data);
console.log(`Successfully fetched ${data.length} contacts`);
this.cache.contactsState.set(LoadState.LOADED);
} catch (e) {
console.error(e);
this.serviceManager.chatsStatus.set(LoadStatus.error);
this.notification
.open(`Loading contacts failed: ${e}`, { appearance: 'negative' })
.subscribe();
}
}
}
protected readonly LoadStatus = LoadStatus;
protected readonly LoadState = LoadState;
}

View File

@@ -1,24 +0,0 @@
<button tuiButton appearance="secondary" iconStart="@tui.mail-plus">
{{"chat.chatnav.dmList.newChat"|translate}}
</button>
@for (chat of serviceManager.chats(); track chat.chatid) {
<button tuiButton [appearance]="router.url == '/chat/dm/' + chat.chatid ? 'primary' : 'flat'" [routerLink]="'/chat/dm/' + chat.chatid">
<oimg [src]="chat.pfp" height="35px" width="35px" [radius]="10"></oimg>
<div class="info">
@if (chat.displayName == "") {
<span>{{'@'+chat.username}}</span>
} @else {
<span>{{chat.displayName}}</span>
}
@if (chat.latestMessage) {
<span class="latest_message">
@if (chat.latestMessage.isAuthor) {
{{"chat.chatnav.dmList.messageBox.latestMessage.you"|translate}}
}
{{chat.latestMessage.message}}
</span>
}
</div>
</button>
}

View File

@@ -1,25 +1,30 @@
@defer (when store) {
<navbar>
<div class="items-left">
<oimg [src]="store.chatData().pfp" height="50px" width="50px" [radius]="15"></oimg>
<div class="chat-data">
@if (store.chatData().displayName == "") {
<span class="main-name">{{'@'+store.chatData().username}}</span>
} @else {
<span class="main-name">{{store.chatData().displayName}}</span>
<span class="alt-name">{{'@'+store.chatData().username}}</span>
}
<main [class.mobile]="breakpoint() == 'mobile'">
@defer (when store) {
<navbar backButtonDest="/chat">
<div class="data">
<avatar [src]="this.store.chatData().pfp" height="50px" width="50px" [radius]="15" [name]="this.store.chatData().username"></avatar>
<div class="chat-data">
@if (this.store.chatData().displayName == "") {
<span class="main-name">{{ '@' + this.store.chatData().username }}</span>
} @else {
<span class="main-name">{{ this.store.chatData().displayName }}</span>
<span class="alt-name">{{ '@' + this.store.chatData().username }}</span>
}
</div>
</div>
</div>
<div class="items-right">
<button tuiButton appearance="flat">
<tui-icon icon="@tui.phone"/>
</button>
</div>
</navbar>
<div class="items-right">
<button tuiButton appearance="flat" disabled>
<tui-icon icon="@tui.phone" />
</button>
</div>
</navbar>
<messages [messages]="store.messages()"/>
<messages (scrollend)="handleMessagesScroll($event)" [loading]="store.messagesState() == LoadState.CLEAN_LOADING"
[messageBoxViewModel]="store.messageBox" [messages]="store.messages()" id="scrollContainer"
(onDelete)="deleteMessage($event)" />
<message-box [viewModel]="store.messageBox"/>
}
<message-box [viewModel]="store.messageBox" />
}
</main>

View File

@@ -1,7 +1,17 @@
:host {
height: 95svh;
main {
height: 98svh;
display: grid;
grid-template-rows: 70px minmax(0, 1fr) auto;
padding: 15px;
&.mobile {
height: 100svh;
padding: 15px;
}
.mobile {
height: 5px;
}
navbar {
.chat-data {

View File

@@ -1,51 +1,88 @@
import {Component, inject, OnInit, signal} from '@angular/core';
import {DmStorage, ServiceManager} from '../../service-manager';
import {ActivatedRoute} from '@angular/router';
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
import {IndexedDB} from '../../storage/indexed-db';
import {Navbar} from '../elements/navbar/navbar';
import {Oimg} from '../elements/oimg/oimg';
import {TuiButton, TuiIcon} from '@taiga-ui/core';
import {FileDataWithPreview, MessageBox} from '../elements/message-box/message-box';
import {Messages} from '../elements/messages/messages';
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
import {FileData, FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
import { Component, inject, OnInit, signal } from '@angular/core';
import { LoadStatus, ServiceManager } from '../../service-manager';
import { ActivatedRoute } from '@angular/router';
import { IndexedDB } from '../../storage/indexed-db';
import { Navbar } from '../elements/navbar/navbar';
import { TUI_BREAKPOINT, TuiButton, TuiIcon, TuiNotificationService } from '@taiga-ui/core';
import { FileDataWithPreview, MessageBox } from '../elements/message-box/message-box';
import { CHATENIUM_SDK } from '../../chatenium.token';
import {
Contact,
createDMWrapper,
DirectMessagingApi,
Message,
WrappedDMHandler,
} from 'chatenium-sdk-preview';
import { CacheService, DmStorage, LoadState } from '../../cache';
import { Avatar } from '../elements/avatar/avatar';
import { MessageBoxViewModel } from '../elements/message-box/message-box-viewmodel';
import { MessagesViewModel } from '../elements/messages/messages-viewmodel';
import { Messages } from '../elements/messages/messages';
@Component({
selector: 'app-dm',
imports: [
Navbar,
Oimg,
TuiButton,
TuiIcon,
MessageBox,
Messages
],
imports: [Navbar, TuiButton, TuiIcon, MessageBox, Avatar, Messages],
templateUrl: './dm.html',
styleUrl: './dm.scss',
})
export class Dm implements OnInit {
serviceManager = inject(ServiceManager)
route = inject(ActivatedRoute)
indexedDb = inject(IndexedDB)
SDK = inject(CHATENIUM_SDK);
cache = inject(CacheService);
serviceManager = inject(ServiceManager);
route = inject(ActivatedRoute);
notification = inject(TuiNotificationService);
indexedDb = inject(IndexedDB);
breakpoint = inject(TUI_BREAKPOINT);
chatid = ""
contactId = '';
get store(): DmStorage {
return this.serviceManager.dmServices()[this.chatid]
return this.cache.dms()[this.contactId];
}
async sendMessage(message: string, files: FileDataWithPreview[] | null) {
console.log('sendMessage', message, files);
try {
const resp = await this.store.handler.sendMessage({
content: message,
});
const data = resp.data as Message;
console.log(data);
} catch (e) {
this.notification.open(`Failed sending DM: ${e}`, { appearance: 'negative' }).subscribe();
console.error(e);
}
/*
if (!files && message.trim() == '') return;
const session = this.serviceManager.currentSession();
if (session != null) {
let attachments: Attachment[] = []
files?.forEach(file => {
const extraMetaData: Record<string, string> = {}
extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""
const editedMessage = this.store.messageBox.editingMessage();
if (editedMessage) {
const storedMsg = this.store.messages().find((m) => m.msgid == editedMessage.messageId);
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg));
if (storedMsg) {
storedMsg.message = message;
}
try {
await this.store.service.editMessage(editedMessage.messageId, message);
} catch (e) {
if (storedMsg) {
storedMsg.message = originalMessage.message;
}
}
return;
}
let attachments: Attachment[] = [];
files?.forEach((file) => {
const extraMetaData: Record<string, any> = {};
extraMetaData['thumbnailMetaData'] = file.videoThumbnail ?? '';
extraMetaData['progressShown'] = true;
extraMetaData['totalChunks'] = 0;
extraMetaData['uploadedChunks'] = 0;
attachments.push({
fileName: file.name,
@@ -55,89 +92,222 @@ export class Dm implements OnInit {
path: file.blob,
height: file.height,
width: file.width,
extraMetaData: extraMetaData
})
})
extraMetaData: extraMetaData,
});
});
this.store.messages.update(value => [...value, {
message: message,
chatid: this.chatid,
files: attachments,
replyTo: "",
author: session.userData.userid,
seen: false,
msgid: "",
forwardedFrom: "",
isEdited: false,
sent_at: {T: 0, I: 0},
replyToId: "",
forwardedFromName: ""
}])
const tempMsgId = uuidv4();
this.store.messages.update((value) => [
...value,
{
message: message,
chatid: this.chatid,
files: attachments,
replyTo: '',
author: session.userData.userid,
seen: false,
msgid: tempMsgId,
forwardedFrom: '',
isEdited: false,
sent_at: { T: 0, I: 0 },
replyToId: '',
forwardedFromName: '',
},
]);
await this.store.service.sendMessage("", message, null, null, files, <FileUploadProgressListener>{
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
}
})
const respMessage = await this.store.service.sendMessage(
tempMsgId,
message,
null,
null,
files,
<FileUploadProgressListener>{
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone);
},
},
);
this.updateTempMessage(tempMsgId, respMessage);
this.scrollToBottom('smooth');
}*/
}
async deleteMessage(messageId: string) {
/*const i = this.store.messages().findIndex((m) => m.msgid == messageId);
if (i != -1) {
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]));
this.store.messages().splice(i, 1);
try {
await this.store.service.deleteMessages([messageId]);
} catch (e) {
this.store.messages().splice(i, 0, originalMessage);
}
}*/
}
async loadMessages() {
try {
const resp = await this.store.handler.getMessages(0);
const data = resp.data as Message[];
console.log(
`Successfully fetched ${data.length} message(s) in DM ${this.store.chatData().contactId}`,
);
console.log(data);
this.store.messages.set(data);
this.store.messagesState.set(LoadState.LOADED);
} catch (e) {
this.notification
.open('Loading direct messages failed.', { appearance: 'negative' })
.subscribe();
}
}
restoreScrollState(): void {
setTimeout(() => {
const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
scrollContainer.scroll({
top:
this.store.messagesVm.scrollBarStatus() == -1
? scrollContainer.scrollHeight
: this.store.messagesVm.scrollBarStatus(),
left: 0,
behavior: 'instant',
});
if (this.store.messagesVm.scrollBarStatus() == -1) {
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight);
}
}, 0);
}
scrollToBottom(anim: 'instant' | 'smooth'): void {
setTimeout(() => {
const scrollContainer = <HTMLDivElement>document.querySelector('#scrollContainer');
scrollContainer.scroll({
top: scrollContainer.scrollHeight,
left: 0,
behavior: anim,
});
}, 0);
}
handleMessagesScroll(e: any) {
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop);
}
uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
console.log(fileId, allChunks, chunksDone)
/*
console.log(tempMsgId, fileId, allChunks, chunksDone);
this.store.messages.update((messages) =>
messages.map((m) => {
if (m.msgid !== tempMsgId) return m;
return {
...m,
files: m.files.map((f) => {
if (f.fileId !== fileId) return f;
return {
...f,
extraMetaData: {
...f.extraMetaData,
totalChunks: allChunks,
uploadedChunks: chunksDone,
},
};
}),
};
}),
);*/
}
updateTempMessage(tempMsgId: string, message: Message) {
/*
this.store.messages.update((messages) =>
messages.map((m) => {
if (m.msgid !== tempMsgId) return m;
return {
...m,
msgid: message.msgid,
sent_at: message.sent_at,
files: m.files.map((f) => {
f.extraMetaData['progressShown'] = false;
return f;
}),
};
}),
);*/
}
// The chatid parameter ensures isolation
onWsListen(action: string, message: string, chatid: string) {
/*
const data = JSON.parse(message);
if (data.chatid === chatid) {
const targetStore = this.serviceManager.dmServices()[chatid];
if (targetStore) {
switch (action) {
case "newMessage":
targetStore.messages.update(messages => [...messages, data]);
case 'newMessage':
targetStore.messages.update((messages) => [...messages, data]);
this.scrollToBottom('smooth');
break;
}
}
}
}*/
}
ngOnInit() {
this.route.params.subscribe(async params => {
const chatid = params['chatid'];
this.chatid = chatid;
this.route.params.subscribe(async (params) => {
const contactId = params['contactId'];
this.contactId = contactId;
console.log(`Loading DM chat ${contactId}...`);
const session = this.serviceManager.currentSession();
const chatData = this.serviceManager.chats().find(c => c.chatid === chatid);
const chatData = this.cache.contacts().find((c) => c.contactId === contactId);
if (!session || !chatData) {
console.warn(`Initialization deferred for ${chatid}: Session or ChatData missing.`);
if (!chatData) {
console.warn(
`Unable to find chat data with the provided contactId: ${contactId}, skipping load.`,
);
return;
}
if (!this.serviceManager.dmServices()[chatid]) {
const newStore = {
chatData: signal<Chat>(chatData),
if (!this.cache.dms()[contactId]) {
console.log(`No store yet, creating service store for DM: ${contactId}`);
this.cache.dms()[contactId] = {
handler: createDMWrapper(this.SDK.directMessaging, chatData.contactId),
chatData: signal<Contact>(chatData),
messages: signal<Message[]>([]),
messagesState: signal<LoadState>(LoadState.CLEAN_LOADING),
messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
wsListener: (action, data) => this.onWsListen(action, data, chatid),
messagesVm: new MessagesViewModel(),
wsListener: (action, data) => this.onWsListen(action, data, contactId),
} as DmStorage;
newStore.service = new DMService(
session.userData.userid,
session.token,
chatid,
this.indexedDb.getApi(),
(action, data) => newStore.wsListener(action, data)
);
this.serviceManager.dmServices()[chatid] = newStore;
const currentStore = this.serviceManager.dmServices()[chatid];
const history = await currentStore.service.get();
currentStore.messages.set(history);
await this.loadMessages();
/*
const currentStore = this.serviceManager.dmServices()[contactId];
try {
const messagesCache = await currentStore.service.getQuick();
currentStore.messages.set(messagesCache);
this.store.messagesStatus.set(LoadStatus.updating)
this.restoreScrollState()
} catch (e) {
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
}
const messages = await currentStore.service.get();
currentStore.messages.set(messages);
this.store.messagesStatus.set(LoadStatus.loaded)
this.restoreScrollState()
await currentStore.service.joinWebSocketRoom();
} else {
this.restoreScrollState()
}*/
}
console.log(`Finished initializing chat: ${contactId}`);
});
}
protected readonly LoadStatus = LoadStatus;
protected readonly LoadState = LoadState;
}

View File

@@ -0,0 +1,3 @@
<div class="avatar" [style]="'width: '+width()+'; height: '+height()+'; background-color: '+stringToHexColor(name())+'; border-radius: '+radius()+'px;'">
<span>{{name()[0]}}</span>
</div>

View File

@@ -0,0 +1,6 @@
.avatar {
display: flex;
align-items: center;
justify-content: center;
color: white;
}

View File

@@ -1,17 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DmList } from './dm-list';
import { Avatar } from './avatar';
describe('DmList', () => {
let component: DmList;
let fixture: ComponentFixture<DmList>;
describe('Avatar', () => {
let component: Avatar;
let fixture: ComponentFixture<Avatar>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DmList],
imports: [Avatar],
}).compileComponents();
fixture = TestBed.createComponent(DmList);
fixture = TestBed.createComponent(Avatar);
component = fixture.componentInstance;
await fixture.whenStable();
});

View File

@@ -0,0 +1,29 @@
import { Component, input } from '@angular/core';
@Component({
selector: 'avatar',
imports: [],
templateUrl: './avatar.html',
styleUrl: './avatar.scss',
})
export class Avatar {
height = input.required<string>();
width = input.required<string>();
src = input<string>();
name = input.required<string>();
radius = input.required<number>();
PALETTE = ['#ff6b6b', '#ffd166', '#06d6a0', '#4cc9f0', '#b56576', '#f78c6b'];
/**
* Picks 1 color from a few for avatar background
* @param str
*/
stringToHexColor(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return this.PALETTE[Math.abs(hash) % this.PALETTE.length];
}
}

View File

@@ -1,9 +1,8 @@
:host {
display: grid;
gap: 4px;
height: 100%;
img {
::ng-deep img {
display: block;
height: 100%;
width: 100%;

View File

@@ -12,4 +12,5 @@ export class MessageBoxViewModel {
message = signal<string>("")
files = signal<FileDataWithPreview[]>([])
dialogOpen = signal<boolean>(false)
editingMessage = signal<{messageId: string, content: string|undefined} | null >(null)
}

View File

@@ -5,7 +5,7 @@
</div>
<span>{{ "chat.elements.messageBox.uplDrag.upload"|translate }}</span>
</div>
<div class="method">
<div class="method" style="opacity: 0.5">
<div class="icon-holder">
<tui-icon icon="@tui.cloud-sync"/>
</div>
@@ -14,13 +14,25 @@
</div>
<ng-template [(tuiDialog)]="viewModel().dialogOpen" [tuiDialogOptions]="{label: 'chat.elements.messageBox.fileUploadDialog.label'|translate}">
<masonry [maxColSize]="2" style="overflow-y: scroll; height: 500px">
@if (filterPictureVideo(viewModel().files()).length != 0) {
<masonry [maxColSize]="2" style="overflow-y: scroll; height: 200px">
@for (file of viewModel().files(); track file) {
@if (file.type == "image") {
<img [src]="file.blob" style="width: 100%; height: 100%; object-fit: fill;"/>
}
}
</masonry>
}
<div tuiGroup orientation="vertical" style="width: 100%">
@for (file of viewModel().files(); track file) {
@if (file.type == "image") {
<img [src]="file.blob" style="width: 100%; height: 100%; object-fit: fill;"/>
@if (file.type != "image") {
<div style="background: var(--tui-background-neutral-1); height: 50px; display: flex; align-items: center; padding: 0 10px">
<span>{{ file.name }}</span>
</div>
}
}
</masonry>
</div>
<div style="margin-top: 10px; display: flex; gap: 10px; width: 100%">
<tui-textfield style="width: 100%">
@@ -37,25 +49,45 @@
</div>
</ng-template>
<div id="message-box" [style]="'border-radius:'+messageBoxRadius+'px;'">
<div class="items-left">
<button tuiButton appearance="flat" (click)="uplInput.click()">
<tui-icon icon="@tui.file-up"/>
<input #uplInput type="file" (change)="handleFileInput($event)" multiple hidden/>
</button>
<main>
<div id="message-box-extension" tuiAppearance="floating" [class.shown]="viewModel().editingMessage()" [class.fullWidth]="breakpoint() != 'desktopLarge'">
<div id="content">
@if (viewModel().editingMessage()) {
<tui-icon icon="@tui.pencil"></tui-icon>
<span>{{"chat.elements.messageBox.editMessageLabel"|translate}}</span>
@if (viewModel().editingMessage()!.content == "") {
<tui-icon icon="@tui.paperclip"></tui-icon>
<span>{{"chat.elements.messageBox.attachments"|translate}}</span>
} @else {
<span style="width: 300px" tuiScrollable tuiFade>{{viewModel().editingMessage()!.content}}</span>
}
}
</div>
<button tuiButton appearance="flat">
<tui-icon icon="@tui.cloud-sync"/>
<button id="close" tuiButton appearance="flat" (click)="viewModel().editingMessage.set(null); viewModel().message.set('');">
<tui-icon icon="@tui.x"/>
</button>
</div>
<div class="items-middle">
<textarea [style]="'height:'+textareaHeight+'px;'" #message (input)="onTextAreaInput(message)" [(ngModel)]="viewModel().message"></textarea>
<span class="placeholder"
[class.hidden]="message.value != ''">{{ "chat.elements.messageBox.placeholder"|translate }}</span>
<div id="message-box" [style]="'border-radius:'+messageBoxRadius+'px;'" [class.fullWidth]="breakpoint() != 'desktopLarge'">
<div class="items-left">
<button tuiButton appearance="flat" (click)="uplInput.click()">
<tui-icon icon="@tui.file-up"/>
<input #uplInput type="file" (change)="handleFileInput($event)" multiple hidden/>
</button>
<button tuiButton appearance="flat" disabled>
<tui-icon icon="@tui.cloud-sync"/>
</button>
</div>
<div class="items-middle">
<textarea (keydown.enter)="viewModel().onMessageSend(message.value, null); viewModel().message.set(''); viewModel().editingMessage.set(null); handleEnterKeydown($event)" [style]="'height:'+textareaHeight+'px;'" #message (input)="onTextAreaInput(message)" [(ngModel)]="viewModel().message"></textarea>
<span class="placeholder"
[class.hidden]="message.value != ''">{{ "chat.elements.messageBox.placeholder"|translate }}</span>
</div>
<div class="items-right">
<button [disabled]="message.value.trim() == ''" tuiButton appearance="flat" (click)="viewModel().onMessageSend(message.value, null); viewModel().message.set(''); viewModel().editingMessage.set(null);">
<tui-icon icon="@tui.send"/>
</button>
</div>
</div>
<div class="items-right">
<button tuiButton appearance="flat" (click)="viewModel().onMessageSend(message.value, null)">
<tui-icon icon="@tui.send"/>
</button>
</div>
</div>
</main>

View File

@@ -48,72 +48,123 @@
}
}
#message-box {
transition: all 0.2s ease-in-out;
width: 60%;
background: var(--tui-background-base-alt);
min-height: 75px;
max-height: 200px;
border: 2px solid var(--tui-border-normal);
display: grid;
grid-template-columns: 85px 1fr 100px;
main {
width: 100%;
display: flex;
align-items: center;
padding: 0 10px;
flex-direction: column;
gap: 5px;
.items-left, .items-middle, .items-right {
display: flex;
align-items: center;
}
#message-box-extension {
transition: all 0.2s ease-in-out;
width: 50%;
border-radius: 20px;
background: var(--tui-background-base-alt);
border: 2px solid var(--tui-border-normal);
transform: translateY(50px);
display: grid;
grid-template-columns: 1fr 40px;
justify-content: center;
height: 0;
.items-left, .items-right {
button {
height: 30px;
width: 30px;
tui-icon {
font-size: 20px;
}
}
}
.items-middle {
::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 10px;
}
position: relative;
textarea {
&.fullWidth {
width: 100%;
background: transparent;
border: none;
outline: none;
resize: none;
color: var(--tui-text-01);
font-size: 16px;
z-index: 1;
}
.placeholder {
position: absolute;
font-size: 16px;
height: 25px;
top: 2px;
left: 2px;
color: gray;
transition: all 0.2s ease-in-out;
#content {
padding-left: 10px;
display: flex;
gap: 5px;
align-items: center;
}
&.hidden {
margin-left: 10px;
opacity: 0;
}
tui-icon {
font-size: 13px;
}
button {
height: 26px;
width: 30px;
}
&.shown {
transform: translateY(0);
height: 30px;
}
}
.items-right {
display: flex;
justify-content: end;
#message-box {
z-index: 5;
transition: all 0.2s ease-in-out;
width: 60%;
background: var(--tui-background-base-alt);
min-height: 75px;
max-height: 200px;
border: 2px solid var(--tui-border-normal);
display: grid;
grid-template-columns: 85px 1fr 100px;
align-items: center;
padding: 0 10px;
&.fullWidth {
width: 100%;
}
.items-left, .items-middle, .items-right {
display: flex;
align-items: center;
}
.items-left, .items-right {
button {
height: 30px;
width: 30px;
tui-icon {
font-size: 20px;
}
}
}
.items-middle {
::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 10px;
}
position: relative;
textarea {
width: 100%;
background: transparent;
border: none;
outline: none;
resize: none;
color: var(--tui-text-01);
font-size: 16px;
z-index: 1;
}
.placeholder {
position: absolute;
font-size: 16px;
height: 25px;
top: 2px;
left: 2px;
color: gray;
transition: all 0.2s ease-in-out;
&.hidden {
margin-left: 10px;
opacity: 0;
}
}
}
.items-right {
display: flex;
justify-content: end;
}
}
}
}

View File

@@ -1,10 +1,11 @@
import {ChangeDetectorRef, Component, HostListener, inject, input} from '@angular/core';
import {
TUI_BREAKPOINT,
TuiAppearance,
TuiButton,
TuiDialog,
TuiGroup,
TuiIcon,
TuiIcon, TuiScrollable,
TuiScrollbarDirective,
TuiTextfield
} from '@taiga-ui/core';
@@ -16,7 +17,7 @@ import {v4 as uuidv4} from 'uuid';
import {Masonry} from '../masonry/masonry';
import {Oimg} from '../oimg/oimg';
import {FileData} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
import {TuiTextarea, TuiTextareaComponent} from '@taiga-ui/kit';
import {TuiFade, TuiTextarea, TuiTextareaComponent} from '@taiga-ui/kit';
@Component({
selector: 'message-box',
@@ -32,7 +33,9 @@ import {TuiTextarea, TuiTextareaComponent} from '@taiga-ui/kit';
Oimg,
Masonry,
TuiTextfield,
TuiTextarea
TuiTextarea,
TuiScrollable,
TuiFade
],
templateUrl: './message-box.html',
styleUrl: './message-box.scss',
@@ -40,6 +43,7 @@ import {TuiTextarea, TuiTextareaComponent} from '@taiga-ui/kit';
export class MessageBox {
viewModel = input.required<MessageBoxViewModel>()
breakpoint = inject(TUI_BREAKPOINT)
cdr = inject(ChangeDetectorRef)
textareaHeight = 25
@@ -99,8 +103,19 @@ export class MessageBox {
sendMessageWithCaption() {
this.viewModel().onMessageSend(this.viewModel().message(), this.viewModel().files())
this.viewModel().message.set("")
this.viewModel().files.set([])
this.viewModel().dialogOpen.set(false)
this.viewModel().editingMessage.set(null)
}
handleEnterKeydown(e: any) {
e.preventDefault()
return false
}
filterPictureVideo(files: FileDataWithPreview[]) {
return files.filter(f => f.type == "image")
}
async processFiles(fileList: FileList) {

View File

@@ -0,0 +1,6 @@
import {signal} from '@angular/core';
export class MessagesViewModel {
// Saves scrolling state. First value initialized when scrolling to bottom on the message load
scrollBarStatus = signal<number>(-1)
}

View File

@@ -1,32 +1,108 @@
@if (serviceManager.currentSession != null) {
@for (message of messages(); track message.msgid; let i = $index) {
<div
class="message"
[class.author]="message.author == serviceManager.currentSession()!.userData.userid"
[class.chained_start]="isMessageStartOfChain(i)"
[class.chained_middle]="isMessageMiddleInChain(i)"
[class.chained_end]="isMessageEndOfChain(i)"
@if (loading()) {
@for (_ of [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]; track _; let i = $index) {
<div class="message"
[class.chained_start]="i == 0 || i == 3 || i == 6"
[class.chained_end]="i == 2 || i == 5 || i == 9"
[class.chained_middle]="i != 0 && i != 3 && i != 6 && i != 2 && i != 5 && i != 9"
[class.author]="i == 3 || i == 4 || i == 5"
>
<div class="above">
<span>{{message.sent_at.T * 1000 | date: 'HH:mm'}}</span>
<div class="bubble" [tuiSkeleton]="true">
{{i}}
</div>
<div class="bubble">
<span class="message-text">{{message.message}}</span>
<masonry style="max-height: 300px">
@for (file of message.files; track file) {
@if (file.type == "image") {
<img [src]="file.path" style="width: 100%; height: 100%; max-height: 300px; object-fit: cover; border-radius: 25px"/>
} @else if (file.type == "video") {
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
<video-player maxHeight="250px" maxWidth="250px" [src]="file.path" [thumbnailOverwrite]="file.extraMetaData['thumbnailMetaData']"></video-player>
} @else {
<video-player maxHeight="250px" maxWidth="250px" [src]="file.path"></video-player>
}
}
}
</masonry>
</div>
<div class="below"></div>
</div>
}
} @else {
@if (serviceManager.currentSession != null) {
@for (message of messages(); track message.messageId; let i = $index) {
<div
class="message"
[class.author]="
messageAsDm(message).author.userId == sessionManager.userData()?.userId ||
messageAsNetwork(message).author.userId == sessionManager.userData()?.userId
"
[class.chained_start]="isMessageStartOfChain(i)"
[class.chained_middle]="isMessageMiddleInChain(i)"
[class.chained_end]="isMessageEndOfChain(i)"
>
<div class="above">
<span>{{ message.sentAt | date: 'HH:mm' }}</span>
</div>
<div class="bubble" tuiDropdownContext [tuiDropdown]="messageContextMenu">
<span class="message-text">{{ message.content }}</span>
<!-- <masonry style="max-height: 300px">
@for (file of filterExpressedMedia(message.attachments); track file) {
<div style="position:relative;">
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
@if (file.extraMetaData['progressShown']) {
<tui-progress-circle
style="position: absolute; top: 0; right: 0; z-index: 10; transform: translate(-50%, -50%)"
[max]="file.extraMetaData['totalChunks']"
[value]="file.extraMetaData['uploadedChunks']"
/>
}
}
@if (file.type == "image") {
<img [src]="file.path"
style="width: 100%; height: 100%; max-height: 300px; object-fit: cover; border-radius: 25px"/>
} @else if (file.type == "video") {
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
<video-player maxHeight="300px" maxWidth="300px" [src]="file.path"
[thumbnailOverwrite]="file.extraMetaData['thumbnailMetaData']"></video-player>
} @else {
<video-player maxHeight="300px" maxWidth="300px" [src]="file.path"></video-player>
}
}
</div>
}
</masonry>
<div tuiGroup orientation="vertical" style="width: 100%">
@for (file of filterNonExpressedMedia(message.files); track file) {
<div style="width: 100%; height: 50px; display: flex; align-items: center; padding: 0 10px; background: var(--tui-background-base-alt); gap: 5px">
@if (file.extraMetaData && Object.keys(file.extraMetaData).length > 0) {
@if (file.extraMetaData['progressShown']) {
<tui-progress-circle
size="xs"
[max]="file.extraMetaData['totalChunks']"
[value]="file.extraMetaData['uploadedChunks']"
/>
} @else {
<tui-icon icon="@tui.file"/>
}
} @else {
<tui-icon icon="@tui.file"/>
}
<span>{{ file.fileName }}</span>
</div>
}
</div>-->
</div>
<div class="below"></div>
<ng-template #messageContextMenu>
<tui-data-list>
<button
tuiOption
type="button"
iconEnd="@tui.pencil"
(click)="messageBoxViewModel().editingMessage.set({content: message.content, messageId: message.messageId}); messageBoxViewModel().message.set(message.content??'');"
>
{{ "chat.elements.messages.contextMenu.edit" | translate }}
</button>
<button
style="color: var(--tui-text-negative)"
tuiOption
type="button"
iconEnd="@tui.trash"
(click)="onDelete.emit(message.messageId)"
>
{{ "chat.elements.messages.contextMenu.delete" | translate }}
</button>
</tui-data-list>
</ng-template>
</div>
}
}
}

View File

@@ -4,10 +4,12 @@
flex-direction: column;
gap: 2px;
overflow-y: scroll;
overflow-x: hidden;
.message {
display: flex;
flex-direction: column;
align-items: start;
&.author {
align-items: end;
@@ -15,6 +17,24 @@
.bubble {
background: var(--tui-background-accent-1-hover);
}
&.chained_start {
.bubble {
border-radius: 10px 25px 10px 10px !important;
}
}
&.chained_middle {
.bubble {
border-radius: 10px !important;
}
}
&.chained_end {
.bubble {
border-radius: 10px 10px 25px 10px !important;
}
}
}
&.chained_start {
@@ -56,13 +76,14 @@
max-width: 50%;
min-width: 250px;
min-height: 40px;
max-height: 400px;
display: flex;
flex-direction: column;
justify-content: center;
padding: 10px;
.message-text {
white-space: none;
white-space: break-spaces;
overflow-wrap: anywhere;
}
}

View File

@@ -1,33 +1,60 @@
import {Component, inject, input} from '@angular/core';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {Message as NetworkMessage} from '@chatenium/chatenium-sdk/domain/textChannelService.schema'
import {ServiceManager} from '../../../service-manager';
import {DatePipe} from '@angular/common';
import {Masonry} from '../masonry/masonry';
import {VideoPlayer} from '../video-player/video-player';
import { Component, EventEmitter, inject, input, Output } from '@angular/core';
import { Message, ThreadMessage, Attachment, ThreadMessageAttachment } from 'chatenium-sdk-preview';
import { ServiceManager } from '../../../service-manager';
import { DatePipe } from '@angular/common';
import { Masonry } from '../masonry/masonry';
import { VideoPlayer } from '../video-player/video-player';
import {
TuiButton,
TuiDataListComponent,
TuiDropdown,
TuiDropdownContext,
TuiGroup,
TuiIcon,
TuiOption,
} from '@taiga-ui/core';
import { TranslatePipe } from '@ngx-translate/core';
import { MessageBoxViewModel } from '../message-box/message-box-viewmodel';
import { TuiProgressCircle, TuiSkeleton } from '@taiga-ui/kit';
import { SessionManager } from '../../../session-manager';
@Component({
selector: 'messages',
imports: [
DatePipe,
Masonry,
VideoPlayer
VideoPlayer,
TuiDropdownContext,
TuiDropdown,
TuiButton,
TuiOption,
TranslatePipe,
TuiDataListComponent,
TuiGroup,
TuiIcon,
TuiProgressCircle,
TuiSkeleton,
],
templateUrl: './messages.html',
styleUrl: './messages.scss',
})
export class Messages {
serviceManager = inject(ServiceManager)
serviceManager = inject(ServiceManager);
sessionManager = inject(SessionManager);
messages = input<Message[] | NetworkMessage[]>([])
messages = input.required<Message[] | ThreadMessage[]>();
messageBoxViewModel = input.required<MessageBoxViewModel>();
loading = input(false);
@Output() onDelete = new EventEmitter<string>();
/**
* Helps code readability by specifying what type of messages are being processed.
* Example: messageAsDm(message).author == userid -- We are specifying that we are handling dm messages
* @param message
*/
messageAsDm(message: Message | NetworkMessage) {
return message == undefined ? <Message>{author: "no"} : message as Message
messageAsDm(message: Message | ThreadMessage) {
return message as Message;
}
/**
@@ -35,8 +62,8 @@ export class Messages {
Example: messageAsNetwork(message).author.userid == userid -- We are specifying that we are handling network messages
* @param message
*/
messageAsNetwork(message: Message | NetworkMessage) {
return message == undefined ? <NetworkMessage>{author: {userid: "no"}} : message as NetworkMessage
messageAsNetwork(message: Message | ThreadMessage) {
return message as ThreadMessage;
}
isMessageStartOfChain(i: number) {
@@ -48,16 +75,17 @@ export class Messages {
// is author == last msg's author
if (prev) {
if (
(typeof message.author === 'string' && this.messageAsDm(prev).author !== this.messageAsDm(message).author) &&
this.messageAsNetwork(prev).author.userid !== this.messageAsNetwork(message).author.userid
typeof message.author === 'string' &&
this.messageAsDm(prev).author.userId !== this.messageAsDm(message).author.userId &&
this.messageAsNetwork(prev).author.userId !== this.messageAsNetwork(message).author.userId
) {
return true;
}
// same author but time gap between this and prev msg
if (
Math.abs(message.sent_at.T - prev.sent_at.T) >= 60
) {
const currMsgDate = new Date(message.sentAt);
const prevMsgDate = new Date(prev.sentAt);
if (Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) >= 60_000) {
return true;
}
}
@@ -72,12 +100,14 @@ export class Messages {
const prev = this.messages()[i - 1];
// message must be from the same author and have little time gap between
const currMsgDate = new Date(message.sentAt);
const prevMsgDate = new Date(prev.sentAt);
return (
(
(typeof message.author === 'string' && this.messageAsDm(prev).author == this.messageAsDm(message).author) ||
this.messageAsNetwork(prev).author.userid == this.messageAsNetwork(message).author.userid
) &&
Math.abs(message.sent_at.T - prev.sent_at.T) <= 60
((typeof message.author === 'string' &&
this.messageAsDm(prev).author == this.messageAsDm(message).author) ||
this.messageAsNetwork(prev).author.userId ==
this.messageAsNetwork(message).author.userId) &&
Math.abs(currMsgDate.getDate() - prevMsgDate.getDate()) <= 60_000
);
}
@@ -90,19 +120,20 @@ export class Messages {
const next = this.messages()[i + 1];
const currMsgDate = new Date(message.sentAt);
const nextMsgDate = new Date(next.sentAt);
// First condition: next author is different
if (next) {
if (
(typeof message.author === 'string' && this.messageAsDm(next).author != this.messageAsDm(message).author) ||
this.messageAsNetwork(next).author.userid != this.messageAsNetwork(message).author.userid
(typeof message.author === 'string' &&
this.messageAsDm(next).author != this.messageAsDm(message).author) ||
this.messageAsNetwork(next).author.userId != this.messageAsNetwork(message).author.userId
) {
return true;
}
// same author but time gap between this and next msg
if (
Math.abs(message.sent_at.T - next.sent_at.T) >= 60
) {
if (Math.abs(currMsgDate.getDate() - nextMsgDate.getDate()) >= 60) {
return true;
}
}
@@ -111,5 +142,17 @@ export class Messages {
return i + 1 === this.messages().length;
}
filterExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
return files
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
: [];
}
filterNonExpressedMedia(files: Attachment[] | ThreadMessageAttachment[] | undefined) {
return files
? files.filter((f) => f.mimeType.startsWith('image') || f.mimeType.startsWith('video'))
: [];
}
protected readonly Object = Object;
}

View File

@@ -1,3 +1,13 @@
<nav>
<nav [class.includeBackButton]="breakpoint() == showBackButtonAt()" [class.mobile]="breakpoint() == 'mobile'" [class.alignCenter]="dataAlignment() == 'center'">
@if (breakpoint() == showBackButtonAt()) {
<div>
<button (click)="router.navigate([backButtonDest()])" tuiButton appearance="flat" iconStart="@tui.chevron-left">
{{"back"|translate}}
</button>
</div>
}
@if (dataAlignment() == "center" && breakpoint() != showBackButtonAt()) {
<div></div> <!-- filler to align data to center -->
}
<ng-content></ng-content>
</nav>

View File

@@ -2,7 +2,31 @@ nav {
display: grid;
grid-template-columns: 1fr 1fr;
::ng-deep .items-right, ::ng-deep .items-left {
&.includeBackButton {
grid-template-columns: 1fr 1fr 1fr;
::ng-deep .data {
display: flex;
justify-content: center;
align-items: center;
}
}
&.mobile {
zoom: 0.85;
}
&.alignCenter {
grid-template-columns: 1fr 1fr 1fr;
::ng-deep .data {
display: flex;
justify-content: center;
align-items: center;
}
}
::ng-deep .items-right, ::ng-deep .data {
display: flex;
gap: 10px;
align-items: center;

View File

@@ -1,9 +1,27 @@
import { Component } from '@angular/core';
import {Component, inject, input} from '@angular/core';
import {TUI_BREAKPOINT, TuiButton} from '@taiga-ui/core';
import {TuiAppBarComponent} from '@taiga-ui/layout';
import {TuiPlatform} from '@taiga-ui/cdk';
import {NgTemplateOutlet} from '@angular/common';
import {TranslatePipe} from '@ngx-translate/core';
import {Router} from '@angular/router';
@Component({
selector: 'navbar',
imports: [],
imports: [
TuiAppBarComponent,
TuiPlatform,
NgTemplateOutlet,
TuiButton,
TranslatePipe
],
templateUrl: './navbar.html',
styleUrl: './navbar.scss',
})
export class Navbar {}
export class Navbar {
breakpoint = inject(TUI_BREAKPOINT)
router = inject(Router)
backButtonDest = input.required<string>()
showBackButtonAt = input<"desktopSmall"|"mobile">("mobile")
dataAlignment = input<"left"|"center">("left")
}

View File

@@ -1 +1 @@
<img [src]="src()" [style]="'width:'+width()+';height:'+height()+'; border-radius: '+radius()+'px;'" class="">
<img [src]="src()" [style]="'width:'+width()+';height:'+height()+'; border-radius: '+radius()+'px; object-fit:'+objectFit()" class="">

View File

@@ -0,0 +1,3 @@
img {
display: block;
}

View File

@@ -15,4 +15,5 @@ export class Oimg {
width = input("")
src = input("")
radius = input(15)
objectFit = input("cover")
}

View File

@@ -1,7 +1,7 @@
@if (playerActive) {
<div id="player" [style]="'max-width:'+maxWidth+';max-height:'+maxHeight" (mouseover)="controlShowed = true"
(mouseleave)="controlShowed = false" #player>
<video (mouseout)="showVolRange = false" [class.upScale]="videoFullscreen"
<video (mouseout)="showVolRange = false" (mouseover)="showVolRange = false" [class.upScale]="videoFullscreen"
[style]="'max-width:'+maxWidth+';height:'+maxHeight+';border-radius: 15px'" (pause)="videoPlaying = false"
(play)="videoPlaying = true" #video (timeupdate)="watched = videoHMSFormat(video.currentTime)"
(loadedmetadata)="videoPlayer = video; video.style.display = 'block'; videoLoaded = true"
@@ -15,28 +15,21 @@
<div id="controlsHolder">
<div id="controls">
<button tuiButton appearance="icon"
(click)="videoPlaying ? video.pause() : video.play();">
@if (videoPlaying) {
<tui-icon icon="@tui.pause"></tui-icon>
} @else {
<tui-icon icon="@tui.play"></tui-icon>
}
</button>
<span>{{ watched }}</span>
<progress class="timeProgress" (click)="jump($event)" [max]="video.duration" [value]="video.currentTime"
tuiProgressBar size="xs"></progress>
<div>
<!-- @if (showVolRange) { -->
<!-- } -->
<div class="volumeSetter" (mouseover)="showVolRange = true">
<div id="buttons">
<button tuiButton appearance="icon"
(mouseover)="showVolRange = false"
(click)="videoPlaying ? video.pause() : video.play();" id="left">
@if (videoPlaying) {
<tui-icon icon="@tui.pause"></tui-icon>
} @else {
<tui-icon icon="@tui.play"></tui-icon>
}
</button>
<div id="right">
<button
type="button"
tuiButton appearance="icon"
tuiDropdown
tuiDropdownAppearance="neutral"
tuiDropdownAuto
tuiDropdownDirection="top"
tuiDropdownLimitWidth="fixed"
tuiIconButton
@@ -50,26 +43,30 @@
} @else {
<tui-icon icon="@tui.volume"></tui-icon>
}
<input
*tuiDropdown
tuiSlider
type="range"
value="100"
(input)="setVolume(volume)"
[(ngModel)]="volume"
/>
</button>
<input
tuiSlider
type="range"
value="100"
(input)="setVolume(volume)"
[(ngModel)]="volume"
/>
<button tuiButton appearance="icon"
(mouseover)="showVolRange = false"
(click)="videoFullscreen ? exitFullScreen() : player.requestFullscreen(); videoFullscreen = !videoFullscreen">
@if (videoFullscreen) {
<tui-icon icon="@tui.minimize"></tui-icon>
} @else {
<tui-icon icon="@tui.maximize"></tui-icon>
}
</button>
</div>
</div>
<button tuiButton appearance="icon"
(click)="videoFullscreen ? exitFullScreen() : player.requestFullscreen(); videoFullscreen = !videoFullscreen">
@if (videoFullscreen) {
<tui-icon icon="@tui.minimize"></tui-icon>
} @else {
<tui-icon icon="@tui.maximize"></tui-icon>
}
</button>
<div id="info">
<span>{{ watched }}</span>
<progress class="timeProgress" (click)="jump($event)" [max]="video.duration" [value]="video.currentTime"
tuiProgressBar size="xs"></progress>
</div>
</div>
</div>
</div>
@@ -77,9 +74,10 @@
} @else {
<div class="player_preview">
@if (thumbnailOverwrite) {
<img [style]="'max-width:'+maxWidth+';max-height:'+maxHeight+';border-radius: 15px'" [src]="thumbnailOverwrite" />
<img [style]="'max-width:'+maxWidth+';max-height:'+maxHeight+';border-radius: 15px'" [src]="thumbnailOverwrite"/>
} @else {
<oimg [height]="maxHeight" [width]="maxWidth" style="border-radius: 15px" [src]="src+'_thumbnail.png'"></oimg>
<oimg [height]="maxHeight" [width]="maxWidth" style="border-radius: 15px; object-fit: cover"
[src]="src+'_thumbnail.png'"></oimg>
}
<button tuiButton (click)="playVideo()">
<tui-icon icon="@tui.play"></tui-icon>

View File

@@ -36,33 +36,49 @@
#controls {
width: 95%;
height: 50px;
height: 60px;
background: var(--tui-background-base-alt);
border: 2px solid var(--tui-border-normal);
padding: 10px;
border-radius: 20px;
gap: 5px;
display: grid;
grid-template-columns: 50px 50px 1fr 50px 50px;
align-items: center;
display: flex;
flex-direction: column;
button {
height: 25px;
width: 50px;
}
.time {
font-size: 15px;
display: flex;
flex-direction: column;
gap: 0;
}
.volumeSetter {
display: flex;
gap: 5px;
#info {
display: grid;
grid-template-columns: 50px 1fr;
align-items: center;
}
#buttons {
display: grid;
grid-template-columns: 50px 1fr;
align-items: center;
#right {
display: flex;
align-items: center;
justify-content: end;
}
button {
height: 25px;
width: 50px;
}
.time {
font-size: 15px;
display: flex;
flex-direction: column;
gap: 0;
}
.volumeSetter {
display: flex;
gap: 5px;
align-items: center;
}
}
}
}
}
@@ -92,6 +108,7 @@ tui-dropdown[data-appearance] {
box-shadow: none;
border: none;
backdrop-filter: blur(1rem);
position: fixed;
[tuiSlider] {
position: absolute;

View File

@@ -1,7 +1,7 @@
import {Component, Input, ViewEncapsulation} from '@angular/core';
import {
TuiButton,
TuiDropdownDirective,
TuiDropdown,
TuiDropdownOpen,
TuiDropdownOptionsDirective,
TuiIcon,
@@ -21,7 +21,7 @@ import {TuiInputDateRange, TuiProgressBar} from '@taiga-ui/kit';
TuiSlider,
TuiProgressBar,
TuiDropdownOptionsDirective,
TuiDropdownDirective,
TuiDropdown,
TuiDropdownOpen,
TuiInputDateRange
],

View File

@@ -0,0 +1,35 @@
<div id="holder" [class.networkActive]="selectedNetwork() != null">
<div id="networks">
<button disabled tuiButton appearance="secondary" iconStart="@tui.plus">
{{ "chat.chatnav.networkList.newNetwork"|translate }}
</button>
@if (serviceManager.networksStatus() == LoadStatus.updating) {
<div id="loader">
<tui-loader />
{{"updating"|translate}}
</div>
}
@for (network of serviceManager.networks(); track network.networkId) {
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton
appearance="flat"
(click)="selectNetwork(network)">
<oimg [src]="network.picture" height="35px" width="35px" [radius]="10"></oimg>
<div class="info">
<span>{{ network.name }}</span>
</div>
</button>
}
</div>
<div id="network">
<div style="display: flex; align-items: center; gap: 1rem;">
<button tuiButton appearance="secondary" iconStart="@tui.arrow-left" (click)="selectNetwork(null)"></button>
@if (selectedNetwork() != null) {
<oimg [src]="selectedNetwork()!.picture" height="35px" width="35px" [radius]="15"></oimg>
<h3>{{ selectedNetwork()!.name }}</h3>
}
</div>
<network [network]="selectedNetwork()!"></network>
</div>
</div>

View File

@@ -0,0 +1,68 @@
#holder {
position: relative;
&.networkActive {
#networks {
transform: translateX(100px);
opacity: 0;
pointer-events: none;
}
#network {
pointer-events: all;
transform: translateX(0);
opacity: 1;
network {
display: block;
}
}
}
#networks {
transition: 0.3s;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
gap: 5px;
button {
width: 100%;
display: flex;
justify-content: start;
font-weight: 600;
&.enlarge {
height: 75px;
}
.info {
display: flex;
flex-direction: column;
text-align: start;
.latest_message {
margin-top: -5px;
font-size: 12px;
opacity: 50%;
}
}
}
}
#network {
pointer-events: none;
transform: translateX(-100px);
opacity: 0;
transition: 0.2s;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NetworkList } from './network-list';
describe('NetworkList', () => {
let component: NetworkList;
let fixture: ComponentFixture<NetworkList>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NetworkList],
}).compileComponents();
fixture = TestBed.createComponent(NetworkList);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,61 @@
import { Component, inject, input, model, OnInit, signal } from '@angular/core';
import {IndexedDB} from '../../storage/indexed-db';
import {Router, RouterLink} from '@angular/router';
import {LoadStatus, ServiceManager} from '../../service-manager';
import {TUI_BREAKPOINT, TuiButton, TuiLoader} from '@taiga-ui/core';
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';
import {Oimg} from '../elements/oimg/oimg';
import {TranslatePipe} from '@ngx-translate/core';
import { Network as NetworkData } from '@chatenium/chatenium-sdk/domain/networkService.schema';
import { Network } from '../network/network';
@Component({
selector: 'network-list',
imports: [Oimg, TranslatePipe, TuiButton, TuiLoader, Network],
templateUrl: './network-list.html',
styleUrl: './network-list.scss',
})
export class NetworkList implements OnInit {
userid = input<string>('');
token = input<string>('');
expandedSidenav = model.required<boolean>();
selectedNetwork = signal<NetworkData | null>(null);
indexedDb = inject(IndexedDB);
router = inject(Router);
serviceManager = inject(ServiceManager);
breakpoint = inject(TUI_BREAKPOINT);
selectNetwork(network: NetworkData | null) {
this.selectedNetwork.set(network);
this.expandedSidenav.set(network !== null);
}
async ngOnInit() {
this.serviceManager.networkService = new NetworkService(
this.userid(),
this.token(),
'',
this.indexedDb.getApi(),
() => {},
);
if (this.serviceManager.networksStatus() != LoadStatus.loaded) {
try {
this.serviceManager.networks.set(await this.serviceManager.networkService.getQuick());
this.serviceManager.networksStatus.set(LoadStatus.updating);
} catch (e) {
console.warn(`Cache load failed: ${e}. Skipping cache load...`);
}
try {
this.serviceManager.networks.set(await this.serviceManager.networkService.get());
this.serviceManager.networksStatus.set(LoadStatus.loaded);
} catch (e) {
console.error(e);
this.serviceManager.networksStatus.set(LoadStatus.error);
}
}
}
protected readonly LoadStatus = LoadStatus;
}

View File

@@ -0,0 +1,34 @@
<main [class.mobile]="breakpoint() == 'mobile'">
@defer (when store) {
<navbar backButtonDest="/chat/network/{{networkId}}" showBackButtonAt="desktopSmall">
<div class="data">
<div class="chat-data">
@switch (store!.channelData().type) {
@case ("message") {
<tui-icon icon="@tui.hash"></tui-icon>
}
@case ("broadcast") {
<tui-icon icon="@tui.radio"></tui-icon>
}
@case ("voice") {
<tui-icon icon="@tui.audio-lines"></tui-icon>
}
}
<span class="main-name">{{ store!.channelData().name }}</span>
</div>
</div>
<div class="items-right">
<button tuiButton appearance="flat" disabled>
<tui-icon icon="@tui.phone"/>
</button>
</div>
</navbar>
<messages [loading]="store!.messagesStatus() == LoadStatus.loading" (scrollend)="handleMessagesScroll($event)" [messageBoxViewModel]="store!.messageBox" [messages]="store!.messages()" id="scrollContainer"
(onDelete)="deleteMessage($event)"/>
<message-box [viewModel]="store!.messageBox"/>
}
</main>

View File

@@ -0,0 +1,43 @@
main {
height: 98svh;
display: grid;
grid-template-rows: 70px minmax(0, 1fr) auto;
padding: 15px;
&.mobile {
height: 100svh;
padding: 15px;
}
.mobile {
height: 5px;
}
navbar {
.chat-data {
display: flex;
justify-content: center;
gap: 5px;
.main-name {
font-size: 18px;
font-weight: bold;
}
.alt-name {
margin-top: -5px;
color: gray;
font-size: 12px;
}
}
.items-right {
margin-top: -10px;
button {
width: 35px;
height: 35px;
}
}
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Text } from './text';
describe('Text', () => {
let component: Text;
let fixture: ComponentFixture<Text>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Text],
}).compileComponents();
fixture = TestBed.createComponent(Text);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,313 @@
import {Component, inject, signal} from '@angular/core';
import {LoadStatus, ServiceManager, TextChannelStorage} from '../../../../service-manager';
import {ActivatedRoute} from '@angular/router';
import {IndexedDB} from '../../../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
import {FileDataWithPreview, MessageBox} from '../../../elements/message-box/message-box';
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
import {MessageBoxViewModel} from '../../../elements/message-box/message-box-viewmodel';
import {TextChannelServiceService} from '@chatenium/chatenium-sdk/services/textChannelService';
import {Message} from '@chatenium/chatenium-sdk/domain/textChannelService.schema';
import {Messages} from '../../../elements/messages/messages';
import {Navbar} from '../../../elements/navbar/navbar';
import {Oimg} from '../../../elements/oimg/oimg';
import {MessagesViewModel} from '../../../elements/messages/messages-viewmodel';
import {v4 as uuidv4} from 'uuid';
@Component({
selector: 'app-text',
imports: [
MessageBox,
Messages,
Navbar,
Oimg,
TuiButton,
TuiIcon
],
templateUrl: './text.html',
styleUrl: './text.scss',
})
export class Text {
serviceManager = inject(ServiceManager)
route = inject(ActivatedRoute)
indexedDb = inject(IndexedDB)
breakpoint = inject(TUI_BREAKPOINT)
networkId = ""
channelId = ""
categoryId = ""
get store(): TextChannelStorage | null {
if (!this.serviceManager.networkServices()[this.networkId]) {
return null
}
return this.serviceManager.networkServices()[this.networkId].textChannels()[this.channelId]
}
async sendMessage(message: string, files: FileDataWithPreview[] | null) {
if (!this.store) return
if (!files && message.trim() == "") return
const session = this.serviceManager.currentSession();
if (session != null) {
const editedMessage = this.store.messageBox.editingMessage()
if (editedMessage) {
const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId)
const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg))
if (storedMsg) {
storedMsg.message = message
}
try {
await this.store.service.editMessage(editedMessage.messageId, message)
} catch (e) {
if (storedMsg) {
storedMsg.message = originalMessage.message
}
}
return
}
let attachments: Attachment[] = []
files?.forEach(file => {
const extraMetaData: Record<string, any> = {}
extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""
extraMetaData["progressShown"] = true
extraMetaData["totalChunks"] = 0
extraMetaData["uploadedChunks"] = 0
attachments.push({
fileName: file.name,
fileId: file.fileId,
type: file.type,
format: file.extension,
path: file.blob,
height: file.height,
width: file.width,
extraMetaData: extraMetaData
})
})
const tempMsgId = uuidv4()
this.store.messages.update(value => [...value, {
author: {
userid: session.userData.userid,
pfp: session.userData.pfp,
username: session.userData.username,
displayName: session.userData.displayName
},
msgid: tempMsgId,
message: message,
sent_at: {
T: 0,
I: 0
},
isEdited: false,
channelId: "",
networkId: "",
categoryId: "",
files: attachments,
seen: false,
replyTo: "",
replyToId: "",
forwardedFrom: "",
forwardedFromName: ""
}])
const respMessage = await this.store.service.sendMessage(tempMsgId, message, null, null, files, <FileUploadProgressListener>{
fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
}
})
this.updateTempMessage(tempMsgId, respMessage)
this.scrollToBottom("smooth")
}
}
async deleteMessage(messageId: string) {
if (!this.store) return
const i = this.store.messages().findIndex(m => m.msgid == messageId)
if (i != -1) {
const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]))
this.store.messages().splice(i, 1)
try {
await this.store.service.deleteMessages([messageId])
} catch (e) {
this.store.messages().splice(i, 0, originalMessage)
}
}
}
restoreScrollState() {
setTimeout(() => {
if (!this.store) {
return
}
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
scrollContainer.scroll({
top: this.store.messagesVm.scrollBarStatus() == -1 ? scrollContainer.scrollHeight : this.store.messagesVm.scrollBarStatus(),
left: 0,
behavior: "instant"
});
if (this.store.messagesVm.scrollBarStatus() == -1) {
this.store.messagesVm.scrollBarStatus.set(scrollContainer.scrollHeight)
}
}, 0)
}
scrollToBottom(anim: 'instant' | 'smooth'): void {
setTimeout(() => {
const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
scrollContainer.scroll({
top: scrollContainer.scrollHeight,
left: 0,
behavior: anim
});
}, 0)
}
handleMessagesScroll(e: any) {
if (!this.store) return
this.store.messagesVm.scrollBarStatus.set(e.target.scrollTop)
}
uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
if (!this.store) return
this.store.messages.update(messages =>
messages.map(m => {
if (m.msgid !== tempMsgId) return m;
return {
...m,
files: m.files.map(f => {
if (f.fileId !== fileId) return f;
return {
...f,
extraMetaData: {
...f.extraMetaData,
totalChunks: allChunks,
uploadedChunks: chunksDone
}
};
})
};
})
);
}
updateTempMessage(tempMsgId: string, message: Message) {
if (!this.store) return
this.store.messages.update(messages =>
messages.map(m => {
if (m.msgid !== tempMsgId) return m;
return {
...m,
msgid: message.msgid,
sent_at: message.sent_at,
files: m.files.map(f => {
f.extraMetaData["progressShown"] = false
return f
})
};
})
);
}
// The chatid parameter ensures isolation
onWsListen(action: string, message: string, networkId: string, channelId: string) {
const data = JSON.parse(message);
if (data.channelId === channelId) {
const targetStore = this.serviceManager.networkServices()[networkId].textChannels()[channelId];
if (targetStore) {
switch (action) {
case "newMessage":
targetStore.messages.update(messages => [...messages, data]);
this.scrollToBottom("smooth")
break;
}
}
}
}
ngOnInit() {
this.route.params.subscribe(async params => {
const networkId = params['networkId'];
const categoryId = params['categoryId'];
const channelId = params['channelId'];
this.networkId = networkId;
this.categoryId = categoryId;
this.channelId = channelId;
const session = this.serviceManager.currentSession();
const networkData = this.serviceManager.networks().find(c => c.networkId === networkId);
if (!session || !networkData) {
console.warn("No network data")
return
}
const categoryData = networkData.categories.find(c => c.categoryId === categoryId);
if (!categoryData) {
console.warn("No category data")
return
}
const channelData = categoryData.channels.find(c => c.channelId === channelId);
if (!channelData) {
console.warn("No channel data")
return
}
if (!this.serviceManager.networkServices()[networkId]) {
console.warn("No networkService")
return
}
console.log(this.serviceManager.networkServices())
console.log(this.serviceManager.networkServices()[networkId])
if (!this.serviceManager.networkServices()[networkId].textChannels()[channelId]) {
const newStore = {
categoryData: signal(categoryData),
channelData: signal(channelData),
messages: signal<Message[]>([]),
messagesVm: new MessagesViewModel(),
messagesStatus: signal<LoadStatus>(LoadStatus.loading),
messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
wsListener: (action, data) => this.onWsListen(action, data, networkId, categoryId),
} as TextChannelStorage;
newStore.service = new TextChannelServiceService(
session.userData.userid,
session.token,
networkId,
categoryId,
channelId,
this.indexedDb.getApi(),
(action, data) => newStore.wsListener(action, data)
);
this.serviceManager.networkServices()[networkId].textChannels()[channelId] = newStore;
const currentStore = this.serviceManager.networkServices()[networkId].textChannels()[channelId]
try {
const messagesCache = await currentStore.service.getQuick();
currentStore.messages.set(messagesCache);
this.restoreScrollState()
currentStore.messagesStatus.set(LoadStatus.updating)
} catch (e) {
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
}
const messages = await currentStore.service.get();
currentStore.messages.set(messages);
currentStore.messagesStatus.set(LoadStatus.loaded)
this.restoreScrollState()
await currentStore.service.joinWebSocketRoom();
} else {
this.restoreScrollState()
}
});
}
protected readonly LoadStatus = LoadStatus;
}

View File

@@ -0,0 +1,43 @@
@defer (when store) {
<div id="layout" [class.routerOutletActive]="routerOutletActive()"
[class.hideNetworkNav]="routerOutletActive() && breakpoint() == 'desktopSmall'">
<div id="network-data">
<main tuiGroup orientation="vertical" style="width: 100%; height: 80svh">
@for (category of store.networkData().categories; track category) {
<div class="category">
<h2>{{ category.name }}</h2>
<div class="channels">
@for (channel of category.channels; track channel) {
<div class="channel">
<button tuiButton
[appearance]="router.url.endsWith(channel.channelId) ? 'secondary' : 'flat'"
[disabled]="channel.type != 'message'"
[routerLink]="'/chat/network/'+store.networkData().networkId+'/'+category.categoryId+'/'+channel.channelId">
@switch (channel.type) {
@case ("message") {
<tui-icon icon="@tui.hash"></tui-icon>
}
@case ("broadcast") {
<tui-icon icon="@tui.radio"></tui-icon>
}
@case ("voice") {
<tui-icon icon="@tui.audio-lines"></tui-icon>
}
}
<span>{{ channel.name }}</span>
</button>
</div>
}
</div>
</div>
}
</main>
<!-- @case (2) {
<main id="settings">
<network-settings [networkStore]="this.store"></network-settings>
</main>
}-->
</div>
</div>
}

View File

@@ -0,0 +1,65 @@
#layout {
overflow-y: scroll;
width: 100%;
height: 100%;
overflow-x: hidden;
padding: 15px;
transition: 0.2s;
#network-data {
display: flex;
flex-direction: column;
}
&.hideNetworkNav {
grid-template-columns: 1fr;
#network-data {
&.hidden {
display: none;
}
}
}
.category {
width: 100%;
padding: 15px;
.channel {
display: flex;
justify-content: start;
}
.channels {
position: relative;
padding-left: 24px; /* Space for the line and spacing */
border-left: 2px solid var(--tui-background-neutral-1-hover); /* Main vertical track */
margin-left: 8px; /* Shifts child tracks slightly right */
.channel {
height: 50px;
position: relative;
}
.channel::before {
content: "";
position: absolute;
left: -26px; /* Reaches backward to snap to the parent track */
top: 10px; /* Aligns horizontally with the center of the user header */
width: 22px; /* Defines width of the horizontal curve */
height: 14px; /* Defines height of the vertical curve drop */
border-left: 2px solid var(--tui-background-neutral-1-hover);
border-bottom: 2px solid var(--tui-background-neutral-1-hover);
border-bottom-left-radius: 8px; /* Creates the smooth curved bend */
}
}
}
#settings {
width: 100%;
height: 100%;
background: var(--tui-background-base-alt);
border-radius: 20px;
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Network } from './network';
describe('Network', () => {
let component: Network;
let fixture: ComponentFixture<Network>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Network],
}).compileComponents();
fixture = TestBed.createComponent(Network);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,92 @@
import { Component, effect, inject, input, OnInit, signal } from '@angular/core';
import {ActivatedRoute, Router, RouterLink, RouterOutlet} from '@angular/router';
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
import {NetworkStorage, ServiceManager} from '../../service-manager';
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
import {Network as NetworkData} from "@chatenium/chatenium-sdk/domain/networkService.schema"
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';
import {IndexedDB} from '../../storage/indexed-db';
import {Navbar} from '../elements/navbar/navbar';
import {Oimg} from '../elements/oimg/oimg';
import {TUI_BREAKPOINT, TuiButton, TuiGroup, TuiIcon} from '@taiga-ui/core';
import {TuiTab, TuiTabsHorizontal, TuiTabsWithMore} from '@taiga-ui/kit';
import {TuiItem} from '@taiga-ui/cdk';
import {TranslatePipe} from '@ngx-translate/core';
import {Settings} from './settings/settings';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'network',
imports: [
RouterOutlet,
Navbar,
Oimg,
TuiGroup,
TuiButton,
TuiIcon,
RouterLink,
TuiTabsWithMore,
TuiItem,
TuiTab,
TranslatePipe,
TuiTabsHorizontal,
Settings,
],
templateUrl: './network.html',
styleUrl: './network.scss',
})
export class Network {
serviceManager = inject(ServiceManager);
route = inject(ActivatedRoute);
indexedDb = inject(IndexedDB);
breakpoint = inject(TUI_BREAKPOINT);
router = inject(Router);
constructor() {
effect(() => {
if (this.network()) {
this.setupNetwork();
}
});
}
network = input.required<NetworkData>();
routerOutletActive = signal(false);
get store() {
return this.serviceManager.networkServices()[this.network().networkId];
}
setupNetwork() {
console.log(`Setting up NetworkView for ${this.network().networkId}`);
const session = this.serviceManager.currentSession();
if (!session) {
console.warn(
`Initialization deferred for ${this.network().networkId}: Session or NetworkData missing.`,
);
return;
}
if (!this.serviceManager.networkServices()[this.network().networkId]) {
const newStore = {
networkData: signal<NetworkData>(this.network()),
textChannels: signal({}),
wsListener: (action, data) => {},
} as NetworkStorage;
newStore.service = new NetworkService(
session.userData.userid,
session.token,
this.network().networkId,
this.indexedDb.getApi(),
(action, data) => newStore.wsListener(action, data),
);
this.serviceManager.networkServices()[this.network().networkId] = newStore;
}
}
}

View File

@@ -0,0 +1,114 @@
<div tuiGroup id="options" orientation="vertical">
<div>
<header>
<tui-icon icon="@tui.image"></tui-icon>
{{ "chat.network.settings.overviewPage.networkPicture"|translate }}
<oimg [src]="networkStore().networkData().picture" height="25px" width="25px" [radius]="6"/>
</header>
<main>
<button tuiButton appearance="outline" disabled iconEnd="@tui.file-up">
{{ "chat.network.settings.overviewPage.uploadNewPicture"|translate }}
</button>
</main>
</div>
<div>
<ng-template [(tuiDialog)]="setNewNameDialogOpen"
[tuiDialogOptions]="{label: 'chat.network.settings.overviewPage.setNewName'|translate}">
<tui-textfield #newName iconStart="@tui.signature">
<label tuiLabel>{{"chat.network.settings.overviewPage.setNewNameDialog.label"|translate}}</label>
<input type="text" tuiInput>
</tui-textfield>
@if (setNewNameError() != "") {
<tui-error [error]="setNewNameError()"></tui-error>
}
<footer>
<button tuiButton iconStart="@tui.check" [loading]="setNewNamePending()" [disabled]="setNewNamePending()" (click)="setNewName(newName.value())">
{{'chat.network.settings.overviewPage.setNewName'|translate}}
</button>
</footer>
</ng-template>
<header>
<tui-icon icon="@tui.network"></tui-icon>
{{ "chat.network.settings.overviewPage.networkName"|translate }}
<b style="color: gray">{{ networkStore().networkData().name }}</b>
</header>
<main>
<button (click)="setNewNameDialogOpen.set(true)" tuiButton appearance="outline" iconEnd="@tui.pencil">
{{ "chat.network.settings.overviewPage.setNewName"|translate }}
</button>
</main>
</div>
<div>
<ng-template [(tuiDialog)]="makeNetworkPrivateWarnDialogOpen"
[tuiDialogOptions]="{label: 'chat.network.settings.overviewPage.changeToPrivateDialog.label'|translate}">
<ul>
<li>
<tui-icon icon="@tui.eye-off"/>
{{ "chat.network.settings.overviewPage.changeToPrivateDialog.warn.1"|translate }}
</li>
<li>
<tui-icon icon="@tui.ticket"/>
{{ "chat.network.settings.overviewPage.changeToPrivateDialog.warn.2"|translate }}
</li>
<li>
<tui-icon icon="@tui.radio"/>
{{ "chat.network.settings.overviewPage.changeToPrivateDialog.warn.3"|translate }}
</li>
</ul>
<footer>
<button tuiButton iconStart="@tui.eye-off" [loading]="networkVisChangePending()" [disabled]="networkVisChangePending()" (click)="changeVisibility('private')">
{{'chat.network.settings.overviewPage.changeToPrivate'|translate}}
</button>
</footer>
</ng-template>
<ng-template [(tuiDialog)]="makeNetworkPublicWarnDialogOpen"
[tuiDialogOptions]="{label: 'chat.network.settings.overviewPage.changeToPublicDialog.label'|translate}">
<ul>
<li>
<tui-icon icon="@tui.eye"/>
{{ "chat.network.settings.overviewPage.changeToPublicDialog.warn.1"|translate }}
</li>
<li>
<tui-icon icon="@tui.ticket"/>
{{ "chat.network.settings.overviewPage.changeToPublicDialog.warn.2"|translate }}
</li>
<li>
<tui-icon icon="@tui.radio"/>
{{ "chat.network.settings.overviewPage.changeToPublicDialog.warn.3"|translate }}
</li>
</ul>
<footer>
<button tuiButton iconStart="@tui.eye" [loading]="networkVisChangePending()" [disabled]="networkVisChangePending()" (click)="changeVisibility('public')">
{{'chat.network.settings.overviewPage.changeToPublic'|translate}}
</button>
</footer>
</ng-template>
<header>
@if (networkStore().networkData().visibility == "public") {
<tui-icon icon="@tui.eye"></tui-icon>
} @else {
<tui-icon icon="@tui.eye-off"></tui-icon>
}
{{ "chat.network.settings.overviewPage.networkVisibility"|translate }}
</header>
<main>
@if (networkStore().networkData().visibility == "public") {
<button tuiButton appearance="outline" iconEnd="@tui.eye-off" (click)="makeNetworkPrivateWarnDialogOpen.set(true)">
{{ "chat.network.settings.overviewPage.changeToPrivate"|translate }}
</button>
} @else {
<button tuiButton appearance="outline" iconEnd="@tui.eye" (click)="makeNetworkPublicWarnDialogOpen.set(true)">
{{ "chat.network.settings.overviewPage.changeToPublic"|translate }}
</button>
}
</main>
</div>
</div>

View File

@@ -0,0 +1,31 @@
#options {
display: flex;
flex-direction: column;
div {
width: 100%;
height: 60px;
background: var(--tui-background-base-alt);
padding: 15px;
display: grid;
grid-template-columns: 1fr 1fr;
align-items: center;
gap: 10px;
header {
display: flex;
gap: 5px;
align-items: center;
}
main {
display: flex;
align-items: center;
justify-content: end;
button {
height: 35px;
}
}
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Overview } from './overview';
describe('Overview', () => {
let component: Overview;
let fixture: ComponentFixture<Overview>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Overview],
}).compileComponents();
fixture = TestBed.createComponent(Overview);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,79 @@
import {Component, inject, input, signal} from '@angular/core';
import {NetworkStorage} from '../../../../service-manager';
import {
TuiAlertService,
TuiButton,
TuiDialog,
TuiErrorComponent,
TuiGroup,
TuiIcon,
TuiInputDirective
} from '@taiga-ui/core';
import {TranslatePipe} from '@ngx-translate/core';
import {Oimg} from '../../../elements/oimg/oimg';
import {environment} from '../../../../../environments/environment';
import {TuiButtonLoading, TuiComboBox} from '@taiga-ui/kit';
@Component({
selector: 'network-settings-overview',
imports: [
TuiGroup,
TranslatePipe,
TuiIcon,
Oimg,
TuiButton,
TuiDialog,
TuiComboBox,
TuiInputDirective,
TuiButtonLoading,
TuiErrorComponent
],
templateUrl: './overview.html',
styleUrl: './overview.scss',
})
export class Overview {
networkStore = input.required<NetworkStorage>()
protected readonly environment = environment;
protected readonly localStorage = localStorage;
setNewNameDialogOpen = signal(false)
setNewNamePending = signal(false)
setNewNameError = signal("")
makeNetworkPrivateWarnDialogOpen = signal(false)
makeNetworkPublicWarnDialogOpen = signal(false)
networkVisChangePending = signal(false)
async setNewName(name: string) {
this.setNewNameError.set("")
this.setNewNamePending.set(true)
try {
await this.networkStore().service.editName(name)
this.setNewNamePending.set(false)
this.setNewNameDialogOpen.set(false)
this.networkStore().networkData.update(
value => {
value.name = name
return value
}
)
} catch (e) {
this.setNewNamePending.set(false)
this.setNewNameError.set(e as string)
}
}
async changeVisibility(newVisibility: "public" | "private") {
this.networkVisChangePending.set(true)
await this.networkStore().service.changeVisibility(newVisibility)
this.networkStore().networkData.update(
value => {
value.visibility = newVisibility
return value
}
)
this.networkVisChangePending.set(false)
this.makeNetworkPrivateWarnDialogOpen.set(false)
this.makeNetworkPublicWarnDialogOpen.set(false)
}
}

View File

@@ -0,0 +1,29 @@
<aside>
@for (category of networkSettingsOptions; track category) {
<header>
<tui-icon [icon]="'@tui.'+category.icon"></tui-icon>
@if (category.name == "networkName") {
{{networkStore().networkData().name}}
} @else {
{{'chat.network.settings.options.categories.'+category.name|translate}}
}
</header>
<div class="optionList">
@for (option of category.options; track option;) {
<button (click)="selectedOption = option.name" [appearance]="selectedOption == option.name ? 'primary' : 'flat'" tuiButton [disabled]="!option.implemented || !optionRequiredPermissionsGranted(networkStore().networkData().permissions, option.requiredAtLeastOneOf ?? [])">
<tui-icon [icon]="'@tui.'+option.icon"></tui-icon>
{{'chat.network.settings.options.'+option.name|translate}}
</button>
}
</div>
}
</aside>
<main>
@switch (selectedOption) {
@case ("overview") {
<network-settings-overview [networkStore]="networkStore()"/>
}
}
</main>

View File

@@ -0,0 +1,37 @@
:host {
height: 100%;
width: 100%;
display: grid;
grid-template-columns: 300px 1fr;
aside {
height: 100%;
width: 100%;
border-radius: 20px 0 0 20px;
padding: 15px;
header {
display: flex;
gap: 5px;
align-items: center;
}
div {
display: flex;
flex-direction: column;
gap: 1px;
padding: 5px;
button {
height: 40px;
display: flex;
justify-content: start;
}
}
}
main {
background: var(--tui-background-neutral-2);
border-radius: 0 20px 20px 0;
padding: 15px;
}
}

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Settings } from './settings';
describe('Settings', () => {
let component: Settings;
let fixture: ComponentFixture<Settings>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Settings],
}).compileComponents();
fixture = TestBed.createComponent(Settings);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,150 @@
import {Component, inject, input} from '@angular/core';
import {TuiButton, TuiGroup, TuiIcon} from '@taiga-ui/core';
import {permissionGranted, permissions} from '@chatenium/chatenium-sdk/core/permissions';
import {NetworkStorage, ServiceManager} from '../../../service-manager';
import {Session} from '@chatenium/chatenium-sdk/domain/sessionManager.schema';
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
import {TranslatePipe} from '@ngx-translate/core';
import {Overview} from './overview/overview';
@Component({
selector: 'network-settings',
imports: [
TuiGroup,
TuiIcon,
TranslatePipe,
TuiButton,
Overview
],
templateUrl: './settings.html',
styleUrl: './settings.scss',
})
export class Settings {
serviceManager = inject(ServiceManager)
networkStore = input.required<NetworkStorage>()
selectedOption = "overview"
optionRequiredPermissionsGranted(permissions: number, required: number[]) {
if (!this.serviceManager.currentSession) {
return false
}
let granted = false;
if (this.networkStore().networkData().createdBy == this.serviceManager.currentSession()!.userData.userid) {
return true
}
required.forEach((permission) => {
if (permissionGranted(permissions, permission)) {
granted = true
}
})
return granted
}
networkSettingsOptions: {
name: string,
icon: string,
options: {
name: string, // ? channel.settings.[name]
icon: string // ? Class name
requiredAtLeastOneOf?: number[],
implemented: boolean
}[]
}[] = [
{
name: "networkName", // ? UI Will show network name
icon: "network",
options: [
{
icon: "eye",
name: "overview",
implemented: true,
requiredAtLeastOneOf: [permissions.changeNetworkNamePictureAndVisibility]
},
{
name: "rank",
icon: "book",
requiredAtLeastOneOf: [permissions.createAndEditRanks, permissions.deleteRanks],
implemented: false,
},
{
name: "emoji",
icon: "smile",
implemented: false,
requiredAtLeastOneOf: [permissions.createEmojis]
},
{
name: "embed",
icon: "code",
implemented: false,
requiredAtLeastOneOf: [permissions.manageEmbed]
},
{
name: "invite",
icon: "ticket",
implemented: false,
requiredAtLeastOneOf: [permissions.createInvites, permissions.deleteInvites]
}
]
},
{
name: "apps",
icon: "layout-panel-left",
options: [
{
name: "webhook",
icon: "globe",
implemented: false,
requiredAtLeastOneOf: [permissions.deleteWebhooks, permissions.createWebhooks]
},
{
name: "bots",
icon: "bot",
implemented: false,
}
]
},
{
name: "moderation",
icon: "shield-half",
options: [
{
name: "activityHistory",
icon: "scroll-text",
implemented: false,
},
{
name: "bans",
icon: "gavel",
implemented: false,
requiredAtLeastOneOf: [permissions.banMembers]
}
]
},
{
name: "community",
icon: "users",
options: [
{
name: "communityChannels",
icon: "hash",
implemented: false,
},
{
name: "networkIntroducer",
icon: "network",
implemented: false,
},
{
name: "members",
icon: "users",
implemented: false,
}
]
}
]
}

View File

@@ -0,0 +1,16 @@
<button (click)="router.navigate(['/chat/picture/'+serviceManager.currentSession()!.userData.userid])" tuiButton [appearance]="router.url == '/chat/picture/' + serviceManager.currentSession()!.userData.userid ? 'primary' : 'secondary'" iconStart="@tui.user">
{{"chat.chatnav.pictureList.myPictures"|translate}}
</button>
@for (chat of serviceManager.chats(); track chat.chatid) {
<button [class.enlarge]="breakpoint() == 'mobile'" tuiButton [appearance]="router.url == '/chat/picture/' + chat.userid ? 'primary' : 'flat'" [routerLink]="'/chat/picture/' + chat.userid">
<oimg [src]="chat.pfp" height="35px" width="35px" [radius]="10"></oimg>
<div class="info">
@if (chat.displayName == "") {
<span>{{'@'+chat.username}}</span>
} @else {
<span>{{chat.displayName}}</span>
}
</div>
</button>
}

View File

@@ -9,6 +9,10 @@
justify-content: start;
font-weight: 600;
&.enlarge {
height: 75px;
}
.info {
display: flex;
flex-direction: column;

View File

@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PictureList } from './picture-list';
describe('PictureList', () => {
let component: PictureList;
let fixture: ComponentFixture<PictureList>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [PictureList],
}).compileComponents();
fixture = TestBed.createComponent(PictureList);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -2,39 +2,48 @@ import {Component, inject, input, OnInit, signal} from '@angular/core';
import {ChatService} from '@chatenium/chatenium-sdk/services/chatService';
import {IndexedDB} from '../../storage/indexed-db';
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {TuiButton} from '@taiga-ui/core';
import {TUI_BREAKPOINT, TuiButton} from '@taiga-ui/core';
import {Oimg} from '../elements/oimg/oimg';
import {Router, RouterLink} from '@angular/router';
import {TranslatePipe} from '@ngx-translate/core';
import {LoadStatus, ServiceManager} from '../../service-manager';
@Component({
selector: 'app-dm-list',
selector: 'app-picture-list',
imports: [
TuiButton,
Oimg,
RouterLink,
TranslatePipe
],
templateUrl: './dm-list.html',
styleUrl: './dm-list.scss',
templateUrl: './picture-list.html',
styleUrl: './picture-list.scss',
})
export class DmList implements OnInit {
export class PictureList implements OnInit {
userid = input<string>("")
token = input<string>("")
indexedDb = inject(IndexedDB)
router = inject(Router)
serviceManager = inject(ServiceManager)
breakpoint = inject(TUI_BREAKPOINT)
async ngOnInit() {
this.serviceManager.chatService = new ChatService(this.userid(), this.token(), this.indexedDb.getApi(), () => {})
try {
this.serviceManager.chats.set(await this.serviceManager.chatService.get())
this.serviceManager.chatsStatus.set(LoadStatus.loaded)
} catch (e) {
console.error(e)
this.serviceManager.chatsStatus.set(LoadStatus.error)
if (this.serviceManager.chatsStatus() != LoadStatus.loaded) {
try {
this.serviceManager.chats.set(await this.serviceManager.chatService.getQuick())
this.serviceManager.chatsStatus.set(LoadStatus.updating)
} catch (e) {
console.warn(`Cache load failed: ${e}. Skipping cache load...`)
}
try {
this.serviceManager.chats.set(await this.serviceManager.chatService.get())
this.serviceManager.chatsStatus.set(LoadStatus.loaded)
} catch (e) {
console.error(e)
this.serviceManager.chatsStatus.set(LoadStatus.error)
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More