Compare commits

..

20 Commits

Author SHA1 Message Date
sercan
4ccce1b423 Increased the version number
(changelog) Updated the changelog
2021-05-06 17:11:12 +03:00
sercan
f6b4ca0880 (apps/notes) Responsive adjustments 2021-05-06 17:05:56 +03:00
sercan
77014174e8 (apps/notes) New version of the Notes app 2021-05-06 17:01:14 +03:00
sercan
5ac7002a98 (fuse/masonry) Fixed: Masonry doesn't work with the data that comes from async pipe 2021-05-06 12:07:07 +03:00
sercan
b0f1e1de95 (apps/mailbox) App title font size adjustment for better consistency 2021-05-05 17:52:10 +03:00
sercan
cf01383358 (apps/mailbox) Use shadow on threads for better consistency 2021-05-05 17:27:39 +03:00
sercan
e4442d683b (apps/tasks) Tweaked the hover color on task list for better consistency 2021-05-05 17:27:12 +03:00
sercan
623b43a94c (fuse/styles) Fixed: fuse-highlight doesn't have a margin around in Docs 2021-05-03 18:49:00 +03:00
sercan
e7a1d386a6 (fuse/masonry) Added a new component (and its docs) for creating Masonry layouts 2021-05-03 18:47:57 +03:00
sercan
b05763135e (apps/chat) Adjustments and optimizations for smaller devices 2021-04-30 19:55:37 +03:00
sercan
5dd60c816c (apps/chat) Small adjustments and tweaks for Dark mode 2021-04-30 19:39:02 +03:00
sercan
0ac967a945 Removed optional chaining operators to support Node v12
Set the version on .nvmrc to 12
2021-04-30 19:27:40 +03:00
sercan
e3821da077 (apps/chat) New and improved Chat app 2021-04-30 19:18:09 +03:00
sercan
ee48e11548 Increased the version number
(dependencies) Updated Angular, Angular Material and various other packages
(changelog) Updated the changelog
2021-04-30 19:07:53 +03:00
sercan
215546cc31 (apps/academy) Removed a misplaced import 2021-04-29 19:57:58 +03:00
sercan
072dbce6d4 (fuse/fullscreen) Added Fullscreen toggle component 2021-04-28 10:55:32 +03:00
sercan
5ffe0d0efa (pages/pricing) Improved the spacing of the CTA section on all pricing pages 2021-04-26 23:42:16 +03:00
sercan
e90fb9e618 (apps/academy) Added missing trackBy functions to '*ngFor's 2021-04-26 16:41:21 +03:00
sercan
88e98d002d (apps/mailbox) Removed unused methods 2021-04-26 16:08:19 +03:00
sercan
deeef323f9 (apps/academy) Better error handling on courses that are not exist 2021-04-26 15:59:44 +03:00
730 changed files with 71847 additions and 1918 deletions

2
.nvmrc
View File

@@ -1 +1 @@
14
12

2599
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@fuse/demo",
"version": "12.1.0",
"version": "12.3.0",
"license": "https://themeforest.net/licenses/standard",
"private": true,
"scripts": {
@@ -12,17 +12,17 @@
"e2e": "ng e2e"
},
"dependencies": {
"@angular/animations": "11.2.11",
"@angular/cdk": "11.2.10",
"@angular/common": "11.2.11",
"@angular/compiler": "11.2.11",
"@angular/core": "11.2.11",
"@angular/forms": "11.2.11",
"@angular/material": "11.2.10",
"@angular/material-moment-adapter": "11.2.10",
"@angular/platform-browser": "11.2.11",
"@angular/platform-browser-dynamic": "11.2.11",
"@angular/router": "11.2.11",
"@angular/animations": "11.2.12",
"@angular/cdk": "11.2.11",
"@angular/common": "11.2.12",
"@angular/compiler": "11.2.12",
"@angular/core": "11.2.12",
"@angular/forms": "11.2.12",
"@angular/material": "11.2.11",
"@angular/material-moment-adapter": "11.2.11",
"@angular/platform-browser": "11.2.12",
"@angular/platform-browser-dynamic": "11.2.12",
"@angular/router": "11.2.12",
"@fullcalendar/angular": "4.4.5-beta",
"@fullcalendar/core": "4.4.2",
"@fullcalendar/daygrid": "4.4.2",
@@ -38,7 +38,7 @@
"moment": "2.29.1",
"ng-apexcharts": "1.5.9",
"ngx-markdown": "11.1.3",
"ngx-quill": "13.2.0",
"ngx-quill": "13.3.1",
"perfect-scrollbar": "1.5.0",
"quill": "1.3.7",
"rrule": "2.6.8",
@@ -48,10 +48,10 @@
"zone.js": "0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "0.1102.10",
"@angular/cli": "11.2.10",
"@angular/compiler-cli": "11.2.11",
"@angular/language-service": "11.2.11",
"@angular-devkit/build-angular": "0.1102.11",
"@angular/cli": "11.2.11",
"@angular/compiler-cli": "11.2.12",
"@angular/language-service": "11.2.12",
"@tailwindcss/aspect-ratio": "0.2.0",
"@tailwindcss/line-clamp": "0.2.0",
"@tailwindcss/typography": "0.4.0",
@@ -73,7 +73,7 @@
"karma-jasmine": "4.0.1",
"karma-jasmine-html-reporter": "1.5.4",
"lodash": "4.17.21",
"postcss": "8.2.12",
"postcss": "8.2.13",
"protractor": "7.0.0",
"tailwindcss": "2.1.2",
"ts-node": "8.3.0",

View File

@@ -0,0 +1,7 @@
<!-- Button -->
<button
mat-icon-button
[matTooltip]="'Toggle Fullscreen'"
(click)="toggleFullscreen()">
<mat-icon [svgIcon]="'heroicons_outline:arrows-expand'"></mat-icon>
</button>

View File

@@ -0,0 +1,164 @@
import { ChangeDetectionStrategy, Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { FSDocument, FSDocumentElement } from '@fuse/components/fullscreen/fullscreen.types';
@Component({
selector : 'fuse-fullscreen',
templateUrl : './fullscreen.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs : 'fuseFullscreen'
})
export class FuseFullscreenComponent implements OnInit
{
private _fsDoc: FSDocument;
private _fsDocEl: FSDocumentElement;
private _isFullscreen: boolean = false;
/**
* Constructor
*/
constructor(@Inject(DOCUMENT) private _document: Document)
{
this._fsDoc = _document as FSDocument;
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
this._fsDocEl = document.documentElement as FSDocumentElement;
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Toggle the fullscreen mode
*/
toggleFullscreen(): void
{
// Check if the fullscreen is open
this._isFullscreen = this._getBrowserFullscreenElement() !== null;
// Toggle the fullscreen
if ( this._isFullscreen )
{
this._closeFullscreen();
}
else
{
this._openFullscreen();
}
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Get browser's fullscreen element
*
* @private
*/
private _getBrowserFullscreenElement(): Element
{
if ( typeof this._fsDoc.fullscreenElement !== 'undefined' )
{
return this._fsDoc.fullscreenElement;
}
if ( typeof this._fsDoc.mozFullScreenElement !== 'undefined' )
{
return this._fsDoc.mozFullScreenElement;
}
if ( typeof this._fsDoc.msFullscreenElement !== 'undefined' )
{
return this._fsDoc.msFullscreenElement;
}
if ( typeof this._fsDoc.webkitFullscreenElement !== 'undefined' )
{
return this._fsDoc.webkitFullscreenElement;
}
throw new Error('Fullscreen mode is not supported by this browser');
}
/**
* Open the fullscreen
*
* @private
*/
private _openFullscreen(): void
{
if ( this._fsDocEl.requestFullscreen )
{
this._fsDocEl.requestFullscreen();
return;
}
// Firefox
if ( this._fsDocEl.mozRequestFullScreen )
{
this._fsDocEl.mozRequestFullScreen();
return;
}
// Chrome, Safari and Opera
if ( this._fsDocEl.webkitRequestFullscreen )
{
this._fsDocEl.webkitRequestFullscreen();
return;
}
// IE/Edge
if ( this._fsDocEl.msRequestFullscreen )
{
this._fsDocEl.msRequestFullscreen();
return;
}
}
/**
* Close the fullscreen
*
* @private
*/
private _closeFullscreen(): void
{
if ( this._fsDoc.exitFullscreen )
{
this._fsDoc.exitFullscreen();
return;
}
// Firefox
if ( this._fsDoc.mozCancelFullScreen )
{
this._fsDoc.mozCancelFullScreen();
return;
}
// Chrome, Safari and Opera
if ( this._fsDoc.webkitExitFullscreen )
{
this._fsDoc.webkitExitFullscreen();
return;
}
// IE/Edge
else if ( this._fsDoc.msExitFullscreen )
{
this._fsDoc.msExitFullscreen();
return;
}
}
}

View File

@@ -0,0 +1,22 @@
import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FuseFullscreenComponent } from '@fuse/components/fullscreen/fullscreen.component';
@NgModule({
declarations: [
FuseFullscreenComponent
],
imports : [
MatButtonModule,
MatIconModule,
MatTooltipModule
],
exports : [
FuseFullscreenComponent
]
})
export class FuseFullscreenModule
{
}

View File

@@ -0,0 +1,16 @@
export interface FSDocument extends HTMLDocument
{
mozFullScreenElement?: Element;
mozCancelFullScreen?: () => void;
msFullscreenElement?: Element;
msExitFullscreen?: () => void;
webkitFullscreenElement?: Element;
webkitExitFullscreen?: () => void;
}
export interface FSDocumentElement extends HTMLElement
{
mozRequestFullScreen?: () => void;
msRequestFullscreen?: () => void;
webkitRequestFullscreen?: () => void;
}

View File

@@ -0,0 +1 @@
export * from '@fuse/components/fullscreen/public-api';

View File

@@ -0,0 +1,3 @@
export * from '@fuse/components/fullscreen/fullscreen.component';
export * from '@fuse/components/fullscreen/fullscreen.module';
export * from '@fuse/components/fullscreen/fullscreen.types';

View File

@@ -0,0 +1 @@
export * from '@fuse/components/card/public-api';

View File

@@ -0,0 +1,3 @@
<div class="flex">
<ng-container *ngTemplateOutlet="columnsTemplate; context: { $implicit: distributedColumns }"></ng-container>
</div>

View File

@@ -0,0 +1,87 @@
import { AfterViewInit, Component, Input, OnChanges, SimpleChanges, TemplateRef, ViewEncapsulation } from '@angular/core';
import { FuseAnimations } from '@fuse/animations';
import { FuseMediaWatcherService } from '@fuse/services/media-watcher';
@Component({
selector : 'fuse-masonry',
templateUrl : './masonry.component.html',
styleUrls : ['./masonry.component.scss'],
encapsulation: ViewEncapsulation.None,
animations : FuseAnimations,
exportAs : 'fuseMasonry'
})
export class FuseMasonryComponent implements OnChanges, AfterViewInit
{
@Input() columnsTemplate: TemplateRef<any>;
@Input() columns: number;
@Input() items: any[] = [];
distributedColumns: any[] = [];
/**
* Constructor
*/
constructor(private _fuseMediaWatcherService: FuseMediaWatcherService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On changes
*
* @param changes
*/
ngOnChanges(changes: SimpleChanges): void
{
// Columns
if ( 'columns' in changes )
{
// Distribute the items
this._distributeItems();
}
// Items
if ( 'items' in changes )
{
// Distribute the items
this._distributeItems();
}
}
/**
* After view init
*/
ngAfterViewInit(): void
{
// Distribute the items for the first time
this._distributeItems();
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Distribute items into columns
*/
private _distributeItems(): void
{
// Return an empty array if there are no items
if ( this.items.length === 0 )
{
this.distributedColumns = [];
return;
}
// Prepare the distributed columns array
this.distributedColumns = Array.from(Array(this.columns), item => ({items: []}));
// Distribute the items to columns
for ( let i = 0; i < this.items.length; i++ )
{
this.distributedColumns[i % this.columns].items.push(this.items[i]);
}
}
}

View File

@@ -0,0 +1,18 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FuseMasonryComponent } from '@fuse/components/masonry/masonry.component';
@NgModule({
declarations: [
FuseMasonryComponent
],
imports : [
CommonModule
],
exports : [
FuseMasonryComponent
]
})
export class FuseMasonryModule
{
}

View File

@@ -0,0 +1,2 @@
export * from '@fuse/components/masonry/masonry.component';
export * from '@fuse/components/masonry/masonry.module';

View File

@@ -36,7 +36,6 @@
.mat-tab-body-content {
.fuse-highlight {
margin: -24px;
pre {
margin: 0;

View File

@@ -72,13 +72,17 @@ function generateThemesObject(themes)
return _.map(_.cloneDeep(themes), (value, key) =>
{
const theme = normalizeTheme(value);
const primary = (theme && theme.primary && theme.primary.DEFAULT) ? theme.primary.DEFAULT : normalizedDefaultTheme.primary.DEFAULT;
const accent = (theme && theme.accent && theme.accent.DEFAULT) ? theme.accent.DEFAULT : normalizedDefaultTheme.accent.DEFAULT;
const warn = (theme && theme.warn && theme.warn.DEFAULT) ? theme.warn.DEFAULT : normalizedDefaultTheme.warn.DEFAULT;
return _.fromPairs([
[
key,
{
primary: theme?.primary?.DEFAULT ?? normalizedDefaultTheme.primary.DEFAULT,
accent : theme?.accent?.DEFAULT ?? normalizedDefaultTheme.accent.DEFAULT,
warn : theme?.warn?.DEFAULT ?? normalizedDefaultTheme.warn.DEFAULT
primary,
accent,
warn
}
]
]);

View File

@@ -1,4 +1,4 @@
import { Version } from '@fuse/version/version';
const __FUSE_VERSION__ = '12.1.0';
const __FUSE_VERSION__ = '12.3.0';
export const FUSE_VERSION = new Version(__FUSE_VERSION__).full;

View File

@@ -8,15 +8,15 @@ import { InitialDataResolver } from 'app/app.resolvers';
// tslint:disable:max-line-length
export const appRoutes: Route[] = [
// Redirect empty path to '/example'
{path: '', pathMatch : 'full', redirectTo: 'example'},
// Redirect empty path to '/dashboards/project'
{path: '', pathMatch : 'full', redirectTo: 'dashboards/project'},
// Redirect signed in user to the '/example'
// Redirect signed in user to the '/dashboards/project'
//
// After the user signs in, the sign in page will redirect the user to the 'signed-in-redirect'
// path. Below is another redirection for that path to redirect the user to the desired
// location. This is a small convenience to keep all main routes together here on this file.
{path: 'signed-in-redirect', pathMatch : 'full', redirectTo: 'example'},
{path: 'signed-in-redirect', pathMatch : 'full', redirectTo: 'dashboards/project'},
// Auth routes for guests
{
@@ -73,7 +73,122 @@ export const appRoutes: Route[] = [
initialData: InitialDataResolver,
},
children : [
{path: 'example', loadChildren: () => import('app/modules/admin/example/example.module').then(m => m.ExampleModule)},
// Dashboards
{path: 'dashboards', children: [
{path: 'project', loadChildren: () => import('app/modules/admin/dashboards/project/project.module').then(m => m.ProjectModule)},
{path: 'analytics', loadChildren: () => import('app/modules/admin/dashboards/analytics/analytics.module').then(m => m.AnalyticsModule)},
]},
// Apps
{path: 'apps', children: [
{path: 'academy', loadChildren: () => import('app/modules/admin/apps/academy/academy.module').then(m => m.AcademyModule)},
{path: 'calendar', loadChildren: () => import('app/modules/admin/apps/calendar/calendar.module').then(m => m.CalendarModule)},
{path: 'chat', loadChildren: () => import('app/modules/admin/apps/chat/chat.module').then(m => m.ChatModule)},
{path: 'contacts', loadChildren: () => import('app/modules/admin/apps/contacts/contacts.module').then(m => m.ContactsModule)},
{path: 'ecommerce', loadChildren: () => import('app/modules/admin/apps/ecommerce/ecommerce.module').then(m => m.ECommerceModule)},
{path: 'file-manager', loadChildren: () => import('app/modules/admin/apps/file-manager/file-manager.module').then(m => m.FileManagerModule)},
{path: 'help-center', loadChildren: () => import('app/modules/admin/apps/help-center/help-center.module').then(m => m.HelpCenterModule)},
{path: 'mailbox', loadChildren: () => import('app/modules/admin/apps/mailbox/mailbox.module').then(m => m.MailboxModule)},
{path: 'notes', loadChildren: () => import('app/modules/admin/apps/notes/notes.module').then(m => m.NotesModule)},
{path: 'tasks', loadChildren: () => import('app/modules/admin/apps/tasks/tasks.module').then(m => m.TasksModule)},
]},
// Pages
{path: 'pages', children: [
// Authentication
{path: 'authentication', loadChildren: () => import('app/modules/admin/pages/authentication/authentication.module').then(m => m.AuthenticationModule)},
// Coming soon
{path: 'coming-soon', loadChildren: () => import('app/modules/admin/pages/coming-soon/coming-soon.module').then(m => m.ComingSoonModule)},
// Error
{path: 'error', children: [
{path: '404', loadChildren: () => import('app/modules/admin/pages/error/error-404/error-404.module').then(m => m.Error404Module)},
{path: '500', loadChildren: () => import('app/modules/admin/pages/error/error-500/error-500.module').then(m => m.Error500Module)}
]},
// Invoice
{path: 'invoice', children: [
{path: 'printable', children: [
{path: 'compact', loadChildren: () => import('app/modules/admin/pages/invoice/printable/compact/compact.module').then(m => m.CompactModule)},
{path: 'modern', loadChildren: () => import('app/modules/admin/pages/invoice/printable/modern/modern.module').then(m => m.ModernModule)}
]}
]},
// Maintenance
{path: 'maintenance', loadChildren: () => import('app/modules/admin/pages/maintenance/maintenance.module').then(m => m.MaintenanceModule)},
// Pricing
{path: 'pricing', children: [
{path: 'modern', loadChildren: () => import('app/modules/admin/pages/pricing/modern/modern.module').then(m => m.PricingModernModule)},
{path: 'simple', loadChildren: () => import('app/modules/admin/pages/pricing/simple/simple.module').then(m => m.PricingSimpleModule)},
{path: 'single', loadChildren: () => import('app/modules/admin/pages/pricing/single/single.module').then(m => m.PricingSingleModule)},
{path: 'table', loadChildren: () => import('app/modules/admin/pages/pricing/table/table.module').then(m => m.PricingTableModule)}
]},
// Profile
{path: 'profile', loadChildren: () => import('app/modules/admin/pages/profile/profile.module').then(m => m.ProfileModule)},
]},
// User interface
{path: 'ui', children: [
// Angular Material
{path: 'angular-material', loadChildren: () => import('app/modules/admin/ui/angular-material/angular-material.module').then(m => m.AngularMaterialModule)},
// TailwindCSS
{path: 'tailwindcss', loadChildren: () => import('app/modules/admin/ui/tailwindcss/tailwindcss.module').then(m => m.TailwindCSSModule)},
// Animations
{path: 'animations', loadChildren: () => import('app/modules/admin/ui/animations/animations.module').then(m => m.AnimationsModule)},
// Cards
{path: 'cards', loadChildren: () => import('app/modules/admin/ui/cards/cards.module').then(m => m.CardsModule)},
// Colors
{path: 'colors', loadChildren: () => import('app/modules/admin/ui/colors/colors.module').then(m => m.ColorsModule)},
// Datatable
{path: 'datatable', loadChildren: () => import('app/modules/admin/ui/datatable/datatable.module').then(m => m.DatatableModule)},
// Forms
{path: 'forms', children: [
{path: 'fields', loadChildren: () => import('app/modules/admin/ui/forms/fields/fields.module').then(m => m.FormsFieldsModule)},
{path: 'layouts', loadChildren: () => import('app/modules/admin/ui/forms/layouts/layouts.module').then(m => m.FormsLayoutsModule)},
{path: 'wizards', loadChildren: () => import('app/modules/admin/ui/forms/wizards/wizards.module').then(m => m.FormsWizardsModule)}
]},
// Icons
{path: 'icons', loadChildren: () => import('app/modules/admin/ui/icons/icons.module').then(m => m.IconsModule)},
// Page layouts
{path: 'page-layouts', loadChildren: () => import('app/modules/admin/ui/page-layouts/page-layouts.module').then(m => m.PageLayoutsModule)},
// Typography
{path: 'typography', loadChildren: () => import('app/modules/admin/ui/typography/typography.module').then(m => m.TypographyModule)}
]},
// Documentation
{path: 'docs', children: [
// Changelog
{path: 'changelog', loadChildren: () => import('app/modules/admin/docs/changelog/changelog.module').then(m => m.ChangelogModule)},
// Guides
{path: 'guides', loadChildren: () => import('app/modules/admin/docs/guides/guides.module').then(m => m.GuidesModule)},
// Core features
{path: 'core-features', loadChildren: () => import('app/modules/admin/docs/core-features/core-features.module').then(m => m.CoreFeaturesModule)},
// Other components
{path: 'other-components', loadChildren: () => import('app/modules/admin/docs/other-components/other-components.module').then(m => m.OtherComponentsModule)},
]},
// 404 & Catch all
{path: '404-not-found', pathMatch: 'full', loadChildren: () => import('app/modules/admin/pages/error/error-404/error-404.module').then(m => m.Error404Module)},
{path: '**', redirectTo: '404-not-found'}
]
}
];

View File

@@ -63,6 +63,7 @@
</ng-container>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { CenteredLayoutComponent } from 'app/layout/layouts/horizontal/centered/
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -46,6 +46,7 @@
</ng-container>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { EnterpriseLayoutComponent } from 'app/layout/layouts/horizontal/enterpr
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -52,6 +52,7 @@
</ng-container>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { MaterialLayoutComponent } from 'app/layout/layouts/horizontal/material/
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -55,6 +55,7 @@
</ng-container>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { ModernLayoutComponent } from 'app/layout/layouts/horizontal/modern/mode
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -36,6 +36,7 @@
</button>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { ClassicLayoutComponent } from 'app/layout/layouts/vertical/classic/clas
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -66,6 +66,7 @@
</button>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -6,6 +6,7 @@ import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { FuseFullscreenModule } from '@fuse/components/fullscreen/fullscreen.module';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
import { SearchModule } from 'app/layout/common/search/search.module';
@@ -25,6 +26,7 @@ import { ClassyLayoutComponent } from 'app/layout/layouts/vertical/classy/classy
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -31,6 +31,7 @@
</button>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { CompactLayoutComponent } from 'app/layout/layouts/vertical/compact/comp
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -40,6 +40,7 @@
</div>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { DenseLayoutComponent } from 'app/layout/layouts/vertical/dense/dense.co
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -45,6 +45,7 @@
</button>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { FuturisticLayoutComponent } from 'app/layout/layouts/vertical/futuristi
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -32,6 +32,7 @@
</button>
<!-- Components -->
<div class="flex items-center pl-2 ml-auto space-x-2">
<fuse-fullscreen></fuse-fullscreen>
<search [appearance]="'bar'"></search>
<shortcuts [shortcuts]="data.shortcuts"></shortcuts>
<messages [messages]="data.messages"></messages>

View File

@@ -5,6 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { FuseFullscreenModule } from '@fuse/components/fullscreen';
import { FuseNavigationModule } from '@fuse/components/navigation';
import { MessagesModule } from 'app/layout/common/messages/messages.module';
import { NotificationsModule } from 'app/layout/common/notifications/notifications.module';
@@ -25,6 +26,7 @@ import { ThinLayoutComponent } from 'app/layout/layouts/vertical/thin/thin.compo
MatDividerModule,
MatIconModule,
MatMenuModule,
FuseFullscreenModule,
FuseNavigationModule,
MessagesModule,
NotificationsModule,

View File

@@ -75,7 +75,10 @@ export class AcademyMockApi
// Find the course and attach steps to it
const course = courses.find((item) => item.id === id);
course.steps = steps;
if ( course )
{
course.steps = steps;
}
return [
200,

View File

@@ -0,0 +1,167 @@
import { Injectable } from '@angular/core';
import { assign, cloneDeep, omit } from 'lodash-es';
import { FuseMockApiService } from '@fuse/lib/mock-api';
import { chats as chatsData, contacts as contactsData, messages as messagesData, profile as profileData } from 'app/mock-api/apps/chat/data';
@Injectable({
providedIn: 'root'
})
export class ChatMockApi
{
private _chats: any[] = chatsData;
private _contacts: any[] = contactsData;
private _messages: any[] = messagesData;
private _profile: any = profileData;
/**
* Constructor
*/
constructor(private _fuseMockApiService: FuseMockApiService)
{
// Register Mock API handlers
this.registerHandlers();
// Modify the chats array to attach certain data to it
this._chats = this._chats.map((chat) => ({
...chat,
// Get the actual contact object from the id and attach it to the chat
contact: this._contacts.find((contact) => contact.id === chat.contactId),
// Since we use same set of messages on all chats, we assign them here.
messages: this._messages.map((message) => ({
...message,
chatId : chat.id,
contactId: message.contactId === 'me' ? this._profile.id : chat.contactId,
isMine : message.contactId === 'me'
}))
}));
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Register Mock API handlers
*/
registerHandlers(): void
{
// -----------------------------------------------------------------------------------------------------
// @ Chats - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/chat/chats')
.reply(() => {
// Clone the chats
const chats = cloneDeep(this._chats);
// Return the response
return [200, chats];
});
// -----------------------------------------------------------------------------------------------------
// @ Chat - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/chat/chat')
.reply(({request}) => {
// Get the chat id
const id = request.params.get('id');
// Clone the chats
const chats = cloneDeep(this._chats);
// Find the chat we need
const chat = chats.find((item) => item.id === id);
// Return the response
return [200, chat];
});
// -----------------------------------------------------------------------------------------------------
// @ Chat - PATCH
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPatch('api/apps/chat/chat')
.reply(({request}) => {
// Get the id and chat
const id = request.body.id;
const chat = cloneDeep(request.body.chat);
// Prepare the updated chat
let updatedChat = null;
// Find the chat and update it
this._chats.forEach((item, index, chats) => {
if ( item.id === id )
{
// Update the chat
chats[index] = assign({}, chats[index], chat);
// Store the updated chat
updatedChat = chats[index];
}
});
// Return the response
return [200, updatedChat];
});
// -----------------------------------------------------------------------------------------------------
// @ Contacts - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/chat/contacts')
.reply(() => {
// Clone the contacts
let contacts = cloneDeep(this._contacts);
// Sort the contacts by the name field by default
contacts.sort((a, b) => a.name.localeCompare(b.name));
// Omit details and attachments from contacts
contacts = contacts.map((contact) => omit(contact, ['details', 'attachments']));
// Return the response
return [200, contacts];
});
// -----------------------------------------------------------------------------------------------------
// @ Contact Details - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/chat/contact')
.reply(({request}) => {
// Get the contact id
const id = request.params.get('id');
// Clone the contacts
const contacts = cloneDeep(this._contacts);
// Find the contact
const contact = contacts.find((item) => item.id === id);
// Return the response
return [200, contact];
});
// -----------------------------------------------------------------------------------------------------
// @ Profile - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/chat/profile')
.reply(() => {
// Clone the profile
const profile = cloneDeep(this._profile);
// Return the response
return [200, profile];
});
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,264 @@
import { Injectable } from '@angular/core';
import { cloneDeep } from 'lodash-es';
import { FuseMockApiService } from '@fuse/lib/mock-api/mock-api.service';
import { labels as labelsData, notes as notesData } from 'app/mock-api/apps/notes/data';
import { FuseMockApiUtils } from '@fuse/lib/mock-api';
@Injectable({
providedIn: 'root'
})
export class NotesMockApi
{
private _labels: any[] = labelsData;
private _notes: any[] = notesData;
/**
* Constructor
*/
constructor(private _fuseMockApiService: FuseMockApiService)
{
// Register Mock API handlers
this.registerHandlers();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Register Mock API handlers
*/
registerHandlers(): void
{
// -----------------------------------------------------------------------------------------------------
// @ Labels - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/notes/labels')
.reply(() => {
return [
200,
cloneDeep(this._labels)
];
});
// -----------------------------------------------------------------------------------------------------
// @ Labels - POST
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPost('api/apps/notes/labels')
.reply(({request}) => {
// Create a new label
const label = {
id : FuseMockApiUtils.guid(),
title: request.body.title
};
// Update the labels
this._labels.push(label);
return [
200,
cloneDeep(this._labels)
];
});
// -----------------------------------------------------------------------------------------------------
// @ Labels - PATCH
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPatch('api/apps/notes/labels')
.reply(({request}) => {
// Get label
const updatedLabel = request.body.label;
// Update the label
this._labels = this._labels.map((label) => {
if ( label.id === updatedLabel.id )
{
return {
...label,
title: updatedLabel.title
};
}
return label;
});
return [
200,
cloneDeep(this._labels)
];
});
// -----------------------------------------------------------------------------------------------------
// @ Labels - DELETE
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onDelete('api/apps/notes/labels')
.reply(({request}) => {
// Get label id
const id = request.params.get('id');
// Delete the label
this._labels = this._labels.filter((label) => label.id !== id);
// Go through notes and delete the label
this._notes = this._notes.map((note) => ({
...note,
labels: note.labels.filter((item) => item !== id)
}));
return [
200,
cloneDeep(this._labels)
];
});
// -----------------------------------------------------------------------------------------------------
// @ Note Tasks - POST
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPost('api/apps/notes/tasks')
.reply(({request}) => {
// Get note and task
let updatedNote = request.body.note;
const task = request.body.task;
// Update the note
this._notes = this._notes.map((note) => {
if ( note.id === updatedNote.id )
{
// Update the tasks
if ( !note.tasks )
{
note.tasks = [];
}
note.tasks.push({
id : FuseMockApiUtils.guid(),
content : task,
completed: false
});
// Update the updatedNote with the new task
updatedNote = cloneDeep(note);
return {
...note
};
}
return note;
});
return [
200,
updatedNote
];
});
// -----------------------------------------------------------------------------------------------------
// @ Notes - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/apps/notes/all')
.reply(() => {
// Clone the labels and notes
const labels = cloneDeep(this._labels);
let notes = cloneDeep(this._notes);
// Attach the labels to the notes
notes = notes.map((note) => (
{
...note,
labels: note.labels.map((labelId) => labels.find((label) => label.id === labelId))
}
));
return [
200,
notes
];
});
// -----------------------------------------------------------------------------------------------------
// @ Notes - POST
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPost('api/apps/notes')
.reply(({request}) => {
// Get note
const note = request.body.note;
// Add an id
note.id = FuseMockApiUtils.guid();
// Push the note
this._notes.push(note);
return [
200,
note
];
});
// -----------------------------------------------------------------------------------------------------
// @ Notes - PATCH
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPatch('api/apps/notes')
.reply(({request}) => {
// Get note
const updatedNote = request.body.updatedNote;
// Update the note
this._notes = this._notes.map((note) => {
if ( note.id === updatedNote.id )
{
return {
...updatedNote
};
}
return note;
});
return [
200,
updatedNote
];
});
// -----------------------------------------------------------------------------------------------------
// @ Notes - DELETE
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onDelete('api/apps/notes')
.reply(({request}) => {
// Get the id
const id = request.params.get('id');
// Find the note and delete it
this._notes.forEach((item, index) => {
if ( item.id === id )
{
this._notes.splice(index, 1);
}
});
// Return the response
return [200, true];
});
}
}

View File

@@ -0,0 +1,314 @@
/* tslint:disable:max-line-length */
import moment from 'moment';
export const labels = [
{
id : 'f47c92e5-20b9-44d9-917f-9ff4ad25dfd0',
title: 'Family'
},
{
id : 'e2f749f5-41ed-49d0-a92a-1c83d879e371',
title: 'Work'
},
{
id : 'b1cde9ee-e54d-4142-ad8b-cf55dafc9528',
title: 'Tasks'
},
{
id : '6c288794-47eb-4605-8bdf-785b61a449d3',
title: 'Priority'
},
{
id : 'bbc73458-940b-421c-8d5f-8dcd23a9b0d6',
title: 'Personal'
},
{
id : '2dc11344-3507-48e0-83d6-1c047107f052',
title: 'Friends'
}
];
export const notes = [
{
id : '8f011ac5-b71c-4cd7-a317-857dcd7d85e0',
title : '',
content : 'Find a new company name',
tasks : null,
image : null,
reminder : null,
labels : ['e2f749f5-41ed-49d0-a92a-1c83d879e371'],
archived : false,
createdAt: moment().hour(10).minute(19).subtract(98, 'day').toISOString(),
updatedAt: null
},
{
id : 'ced0a1ce-051d-41a3-b080-e2161e4ae621',
title : '',
content : 'Send the photos of last summer to John',
tasks : null,
image : 'assets/images/cards/14-640x480.jpg',
reminder : null,
labels : [
'bbc73458-940b-421c-8d5f-8dcd23a9b0d6',
'b1cde9ee-e54d-4142-ad8b-cf55dafc9528'
],
archived : false,
createdAt: moment().hour(15).minute(37).subtract(80, 'day').toISOString(),
updatedAt: null
},
{
id : 'd3ac02a9-86e4-4187-bbd7-2c965518b3a3',
title : '',
content : 'Update the design of the theme',
tasks : null,
image : null,
reminder : null,
labels : ['6c288794-47eb-4605-8bdf-785b61a449d3'],
archived : false,
createdAt: moment().hour(19).minute(27).subtract(74, 'day').toISOString(),
updatedAt: moment().hour(15).minute(36).subtract(50, 'day').toISOString()
},
{
id : '89861bd4-0144-4bb4-8b39-332ca10371d5',
title : '',
content : 'Theming support for all apps',
tasks : null,
image : null,
reminder : moment().hour(12).minute(34).add(50, 'day').toISOString(),
labels : ['e2f749f5-41ed-49d0-a92a-1c83d879e371'],
archived : false,
createdAt: moment().hour(12).minute(34).subtract(59, 'day').toISOString(),
updatedAt: null
},
{
id : 'ffd20f3c-2d43-4c6b-8021-278032fc9e92',
title : 'Gift Ideas',
content : 'Stephanie\'s birthday is coming and I need to pick a present for her. Take a look at the below list and buy one of them (or all of them)',
tasks : [
{
id : '330a924f-fb51-48f6-a374-1532b1dd353d',
content : 'Scarf',
completed: false
},
{
id : '781855a6-2ad2-4df4-b0af-c3cb5f302b40',
content : 'A new bike helmet',
completed: true
},
{
id : 'bcb8923b-33cd-42c2-9203-170994fa24f5',
content : 'Necklace',
completed: false
},
{
id : '726bdf6e-5cd7-408a-9a4f-0d7bb98c1c4b',
content : 'Flowers',
completed: false
}
],
image : null,
reminder : null,
labels : ['f47c92e5-20b9-44d9-917f-9ff4ad25dfd0'],
archived : false,
createdAt: moment().hour(16).minute(4).subtract(47, 'day').toISOString(),
updatedAt: null
},
{
id : '71d223bb-abab-4183-8919-cd3600a950b4',
title : 'Shopping list',
content : '',
tasks : [
{
id : 'e3cbc986-641c-4448-bc26-7ecfa0549c22',
content : 'Bread',
completed: true
},
{
id : '34013111-ab2c-4b2f-9352-d2ae282f57d3',
content : 'Milk',
completed: false
},
{
id : '0fbdea82-cc79-4433-8ee4-54fd542c380d',
content : 'Onions',
completed: false
},
{
id : '66490222-743e-4262-ac91-773fcd98a237',
content : 'Coffee',
completed: true
},
{
id : 'ab367215-d06a-48b0-a7b8-e161a63b07bd',
content : 'Toilet Paper',
completed: true
}
],
image : null,
reminder : moment().hour(10).minute(44).subtract(35, 'day').toISOString(),
labels : ['b1cde9ee-e54d-4142-ad8b-cf55dafc9528'],
archived : false,
createdAt: moment().hour(10).minute(44).subtract(35, 'day').toISOString(),
updatedAt: null
},
{
id : '11fbeb98-ae5e-41ad-bed6-330886fd7906',
title : 'Keynote Schedule',
content : '',
tasks : [
{
id : '2711bac1-7d8a-443a-a4fe-506ef51d3fcb',
content : 'Breakfast',
completed: true
},
{
id : 'e3a2d675-a3e5-4cef-9205-feeccaf949d7',
content : 'Opening ceremony',
completed: true
},
{
id : '7a721b6d-9d85-48e0-b6c3-f927079af582',
content : 'Talk 1: How we did it!',
completed: true
},
{
id : 'bdb4d5cd-5bb8-45e2-9186-abfd8307e429',
content : 'Talk 2: How can you do it!',
completed: false
},
{
id : 'c8293bb4-8ab4-4310-bbc2-52ecf8ec0c54',
content : 'Lunch break',
completed: false
}
],
image : null,
reminder : moment().hour(11).minute(27).subtract(14, 'day').toISOString(),
labels : [
'b1cde9ee-e54d-4142-ad8b-cf55dafc9528',
'e2f749f5-41ed-49d0-a92a-1c83d879e371'
],
archived : false,
createdAt: moment().hour(11).minute(27).subtract(24, 'day').toISOString(),
updatedAt: null
},
{
id : 'd46dee8b-8761-4b6d-a1df-449d6e6feb6a',
title : '',
content : 'Organize the dad\'s surprise retirement party',
tasks : null,
image : null,
reminder : moment().hour(14).minute(56).subtract(25, 'day').toISOString(),
labels : ['f47c92e5-20b9-44d9-917f-9ff4ad25dfd0'],
archived : false,
createdAt: moment().hour(14).minute(56).subtract(20, 'day').toISOString(),
updatedAt: null
},
{
id : '6bc9f002-1675-417c-93c4-308fba39023e',
title : 'Plan the road trip',
content : '',
tasks : null,
image : 'assets/images/cards/17-640x480.jpg',
reminder : null,
labels : [
'2dc11344-3507-48e0-83d6-1c047107f052',
'b1cde9ee-e54d-4142-ad8b-cf55dafc9528'
],
archived : false,
createdAt: moment().hour(9).minute(32).subtract(15, 'day').toISOString(),
updatedAt: moment().hour(17).minute(6).subtract(12, 'day').toISOString()
},
{
id : '15188348-78aa-4ed6-b5c2-028a214ba987',
title : 'Office Address',
content : '933 8th Street Stamford, CT 06902',
tasks : null,
image : null,
reminder : null,
labels : ['e2f749f5-41ed-49d0-a92a-1c83d879e371'],
archived : false,
createdAt: moment().hour(20).minute(5).subtract(12, 'day').toISOString(),
updatedAt: null
},
{
id : '1dbfc685-1a0a-4070-9ca7-ed896c523037',
title : 'Tasks',
content : '',
tasks : [
{
id : '004638bf-3ee6-47a5-891c-3be7b9f3df09',
content : 'Wash the dishes',
completed: true
},
{
id : '86e6820b-1ae3-4c14-a13e-35605a0d654b',
content : 'Walk the dog',
completed: false
}
],
image : null,
reminder : moment().hour(13).minute(43).subtract(2, 'day').toISOString(),
labels : ['bbc73458-940b-421c-8d5f-8dcd23a9b0d6'],
archived : false,
createdAt: moment().hour(13).minute(43).subtract(7, 'day').toISOString(),
updatedAt: null
},
{
id : '49548409-90a3-44d4-9a9a-f5af75aa9a66',
title : '',
content : 'Dinner with parents',
tasks : null,
image : null,
reminder : null,
labels : [
'f47c92e5-20b9-44d9-917f-9ff4ad25dfd0',
'6c288794-47eb-4605-8bdf-785b61a449d3'
],
archived : false,
createdAt: moment().hour(7).minute(12).subtract(2, 'day').toISOString(),
updatedAt: null
},
{
id : 'c6d13a35-500d-4491-a3f3-6ca05d6632d3',
title : '',
content : 'Re-fill the medicine cabinet',
tasks : null,
image : null,
reminder : null,
labels : [
'bbc73458-940b-421c-8d5f-8dcd23a9b0d6',
'6c288794-47eb-4605-8bdf-785b61a449d3'
],
archived : true,
createdAt: moment().hour(17).minute(14).subtract(100, 'day').toISOString(),
updatedAt: null
},
{
id : 'c6d13a35-500d-4491-a3f3-6ca05d6632d3',
title : '',
content : 'Update the icons pack',
tasks : null,
image : null,
reminder : null,
labels : ['e2f749f5-41ed-49d0-a92a-1c83d879e371'],
archived : true,
createdAt: moment().hour(10).minute(29).subtract(85, 'day').toISOString(),
updatedAt: null
},
{
id : '46214383-f8e7-44da-aa2e-0b685e0c5027',
title : 'Team Meeting',
content : 'Talk about the future of the web apps',
tasks : null,
image : null,
reminder : null,
labels : [
'e2f749f5-41ed-49d0-a92a-1c83d879e371',
'b1cde9ee-e54d-4142-ad8b-cf55dafc9528'
],
archived : true,
createdAt: moment().hour(15).minute(30).subtract(69, 'day').toISOString(),
updatedAt: null
}
];

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@ import { AcademyMockApi } from 'app/mock-api/apps/academy/api';
import { AnalyticsMockApi } from 'app/mock-api/dashboards/analytics/api';
import { AuthMockApi } from 'app/mock-api/common/auth/api';
import { CalendarMockApi } from 'app/mock-api/apps/calendar/api';
import { ChatMockApi } from 'app/mock-api/apps/chat/api';
import { ContactsMockApi } from 'app/mock-api/apps/contacts/api';
import { ECommerceInventoryMockApi } from 'app/mock-api/apps/ecommerce/inventory/api';
import { FileManagerMockApi } from 'app/mock-api/apps/file-manager/api';
@@ -10,6 +11,7 @@ import { IconsMockApi } from 'app/mock-api/ui/icons/api';
import { MailboxMockApi } from 'app/mock-api/apps/mailbox/api';
import { MessagesMockApi } from 'app/mock-api/common/messages/api';
import { NavigationMockApi } from 'app/mock-api/common/navigation/api';
import { NotesMockApi } from 'app/mock-api/apps/notes/api';
import { NotificationsMockApi } from 'app/mock-api/common/notifications/api';
import { ProjectMockApi } from 'app/mock-api/dashboards/project/api';
import { SearchMockApi } from 'app/mock-api/common/search/api';
@@ -22,6 +24,7 @@ export const mockApiServices = [
AnalyticsMockApi,
AuthMockApi,
CalendarMockApi,
ChatMockApi,
ContactsMockApi,
ECommerceInventoryMockApi,
FileManagerMockApi,
@@ -30,6 +33,7 @@ export const mockApiServices = [
MailboxMockApi,
MessagesMockApi,
NavigationMockApi,
NotesMockApi,
NotificationsMockApi,
ProjectMockApi,
SearchMockApi,

View File

@@ -0,0 +1 @@
<router-outlet></router-outlet>

View File

@@ -0,0 +1,17 @@
import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core';
@Component({
selector : 'academy',
templateUrl : './academy.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademyComponent
{
/**
* Constructor
*/
constructor()
{
}
}

View File

@@ -0,0 +1,44 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FuseFindByKeyPipeModule } from '@fuse/pipes/find-by-key';
import { SharedModule } from 'app/shared/shared.module';
import { academyRoutes } from 'app/modules/admin/apps/academy/academy.routing';
import { AcademyComponent } from 'app/modules/admin/apps/academy/academy.component';
import { AcademyDetailsComponent } from 'app/modules/admin/apps/academy/details/details.component';
import { AcademyListComponent } from 'app/modules/admin/apps/academy/list/list.component';
import { MatTabsModule } from '@angular/material/tabs';
@NgModule({
declarations: [
AcademyComponent,
AcademyDetailsComponent,
AcademyListComponent
],
imports: [
RouterModule.forChild(academyRoutes),
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatSidenavModule,
MatSlideToggleModule,
MatTooltipModule,
FuseFindByKeyPipeModule,
SharedModule,
MatTabsModule
]
})
export class AcademyModule
{
}

View File

@@ -0,0 +1,110 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Category, Course } from 'app/modules/admin/apps/academy/academy.types';
import { AcademyService } from 'app/modules/admin/apps/academy/academy.service';
@Injectable({
providedIn: 'root'
})
export class AcademyCategoriesResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _academyService: AcademyService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Category[]>
{
return this._academyService.getCategories();
}
}
@Injectable({
providedIn: 'root'
})
export class AcademyCoursesResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _academyService: AcademyService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Course[]>
{
return this._academyService.getCourses();
}
}
@Injectable({
providedIn: 'root'
})
export class AcademyCourseResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _router: Router,
private _academyService: AcademyService
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Course>
{
return this._academyService.getCourseById(route.paramMap.get('id'))
.pipe(
// Error here means the requested task is not available
catchError((error) => {
// Log the error
console.error(error);
// Get the parent url
const parentUrl = state.url.split('/').slice(0, -1).join('/');
// Navigate to there
this._router.navigateByUrl(parentUrl);
// Throw an error
return throwError(error);
})
);
}
}

View File

@@ -0,0 +1,32 @@
import { Route } from '@angular/router';
import { AcademyComponent } from 'app/modules/admin/apps/academy/academy.component';
import { AcademyListComponent } from 'app/modules/admin/apps/academy/list/list.component';
import { AcademyDetailsComponent } from 'app/modules/admin/apps/academy/details/details.component';
import { AcademyCategoriesResolver, AcademyCourseResolver, AcademyCoursesResolver } from 'app/modules/admin/apps/academy/academy.resolvers';
export const academyRoutes: Route[] = [
{
path : '',
component: AcademyComponent,
resolve : {
categories: AcademyCategoriesResolver
},
children : [
{
path : '',
pathMatch: 'full',
component: AcademyListComponent,
resolve : {
courses: AcademyCoursesResolver
}
},
{
path : ':id',
component: AcademyDetailsComponent,
resolve : {
course: AcademyCourseResolver
}
}
]
}
];

View File

@@ -0,0 +1,105 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import { Category, Course } from 'app/modules/admin/apps/academy/academy.types';
@Injectable({
providedIn: 'root'
})
export class AcademyService
{
// Private
private _categories: BehaviorSubject<Category[] | null> = new BehaviorSubject(null);
private _course: BehaviorSubject<Course | null> = new BehaviorSubject(null);
private _courses: BehaviorSubject<Course[] | null> = new BehaviorSubject(null);
/**
* Constructor
*/
constructor(private _httpClient: HttpClient)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Getter for categories
*/
get categories$(): Observable<Category[]>
{
return this._categories.asObservable();
}
/**
* Getter for courses
*/
get courses$(): Observable<Course[]>
{
return this._courses.asObservable();
}
/**
* Getter for course
*/
get course$(): Observable<Course>
{
return this._course.asObservable();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Get categories
*/
getCategories(): Observable<Category[]>
{
return this._httpClient.get<Category[]>('api/apps/academy/categories').pipe(
tap((response: any) => {
this._categories.next(response);
})
);
}
/**
* Get courses
*/
getCourses(): Observable<Course[]>
{
return this._httpClient.get<Course[]>('api/apps/academy/courses').pipe(
tap((response: any) => {
this._courses.next(response);
})
);
}
/**
* Get course by id
*/
getCourseById(id: string): Observable<Course>
{
return this._httpClient.get<Course>('api/apps/academy/courses/course', {params: {id}}).pipe(
map((course) => {
// Update the course
this._course.next(course);
// Return the course
return course;
}),
switchMap((course) => {
if ( !course )
{
return throwError('Could not found course with id of ' + id + '!');
}
return of(course);
})
);
}
}

View File

@@ -0,0 +1,29 @@
export interface Category
{
id?: string;
title?: string;
slug?: string;
}
export interface Course
{
id?: string;
title?: string;
slug?: string;
description?: string;
category?: string;
duration?: number;
steps?: {
order?: number;
title?: string;
subtitle?: string;
content?: string;
}[];
totalSteps?: number;
updatedAt?: number;
featured?: boolean;
progress?: {
currentStep?: number;
completed?: number;
};
}

View File

@@ -0,0 +1,200 @@
<div class="absolute inset-0 flex flex-col min-w-0 overflow-hidden">
<mat-drawer-container class="flex-auto h-full">
<!-- Drawer -->
<mat-drawer
class="w-90 dark:bg-gray-900"
[autoFocus]="false"
[mode]="drawerMode"
[opened]="drawerOpened"
#matDrawer>
<div class="flex flex-col items-start p-8 border-b">
<!-- Back to courses -->
<a
class="inline-flex items-center leading-6 text-primary hover:underline"
[routerLink]="['..']">
<span class="inline-flex items-center">
<mat-icon
class="icon-size-5 text-current"
[svgIcon]="'heroicons_solid:arrow-sm-left'"></mat-icon>
<span class="ml-1.5 font-medium leading-5">Back to courses</span>
</span>
</a>
<!-- Course category -->
<ng-container *ngIf="(course.category | fuseFindByKey:'slug':categories) as category">
<div
class="mt-7 py-0.5 px-3 rounded-full text-sm font-semibold"
[ngClass]="{'text-blue-800 bg-blue-100 dark:text-blue-50 dark:bg-blue-500': category.slug === 'web',
'text-green-800 bg-green-100 dark:text-green-50 dark:bg-green-500': category.slug === 'android',
'text-pink-800 bg-pink-100 dark:text-pink-50 dark:bg-pink-500': category.slug === 'cloud',
'text-amber-800 bg-amber-100 dark:text-amber-50 dark:bg-amber-500': category.slug === 'firebase'}">
{{category.title}}
</div>
</ng-container>
<!-- Course title & description -->
<div class="mt-3 text-2xl font-semibold">{{course.title}}</div>
<div class="text-secondary">{{course.description}}</div>
<!-- Course time -->
<div class="mt-6 flex items-center leading-5 text-md text-secondary">
<mat-icon
class="icon-size-5 text-hint"
[svgIcon]="'heroicons_solid:clock'"></mat-icon>
<div class="ml-1.5">{{course.duration}} minutes</div>
</div>
</div>
<!-- Steps -->
<div class="py-2 px-8">
<ol>
<ng-container *ngFor="let step of course.steps; let last = last; trackBy: trackByFn">
<li class="relative group py-6"
[class.current-step]="step.order === currentStep">
<ng-container *ngIf="!last">
<div
class="absolute top-6 left-4 w-0.5 h-full -ml-px"
[ngClass]="{'bg-primary': step.order < currentStep,
'bg-gray-300 dark:bg-gray-600': step.order >= currentStep}"></div>
</ng-container>
<div
class="relative flex items-start cursor-pointer"
(click)="goToStep(step.order)">
<div
class="flex flex-0 items-center justify-center w-8 h-8 rounded-full ring-2 ring-inset ring-transparent bg-card dark:bg-default"
[ngClass]="{'bg-primary dark:bg-primary text-on-primary group-hover:bg-primary-800': step.order < currentStep,
'ring-primary': step.order === currentStep,
'ring-gray-300 dark:ring-gray-600 group-hover:ring-gray-400': step.order > currentStep}">
<!-- Check icon, show if the step is completed -->
<ng-container *ngIf="step.order < currentStep">
<mat-icon
class="icon-size-5 text-current"
[svgIcon]="'heroicons_solid:check'"></mat-icon>
</ng-container>
<!-- Step order, show if the step is the current step -->
<ng-container *ngIf="step.order === currentStep">
<div class="text-md font-semibold text-primary dark:text-primary-500">{{step.order + 1}}</div>
</ng-container>
<!-- Step order, show if the step is not completed -->
<ng-container *ngIf="step.order > currentStep">
<div class="text-md font-semibold text-hint group-hover:text-secondary">{{step.order + 1}}</div>
</ng-container>
</div>
<div class="ml-4">
<div class="font-medium leading-4">{{step.title}}</div>
<div class="mt-1.5 text-md leading-4 text-secondary">{{step.subtitle}}</div>
</div>
</div>
</li>
</ng-container>
</ol>
</div>
</mat-drawer>
<!-- Drawer content -->
<mat-drawer-content class="flex flex-col overflow-hidden">
<!-- Header -->
<div class="lg:hidden flex flex-0 items-center py-2 pl-4 pr-6 sm:py-4 md:pl-6 md:pr-8 border-b lg:border-b-0 bg-card dark:bg-transparent">
<!-- Title & Actions -->
<button
mat-icon-button
[routerLink]="['..']">
<mat-icon [svgIcon]="'heroicons_outline:arrow-sm-left'"></mat-icon>
</button>
<h2 class="ml-2.5 text-md sm:text-xl font-medium tracking-tight truncate">
{{course.title}}
</h2>
</div>
<mat-progress-bar
class="hidden lg:block flex-0 h-0.5 w-full"
[value]="100 * (currentStep + 1) / course.totalSteps"></mat-progress-bar>
<!-- Main -->
<div
class="flex-auto overflow-y-auto"
cdkScrollable>
<!-- Steps -->
<mat-tab-group
class="fuse-mat-no-header"
[animationDuration]="'200'"
#courseSteps>
<ng-container *ngFor="let step of course.steps; trackBy: trackByFn">
<mat-tab>
<ng-template matTabContent>
<div
class="prose prose-sm max-w-3xl mx-auto sm:my-2 lg:mt-4 p-6 sm:p-10 sm:py-12 rounded-2xl shadow overflow-hidden bg-card"
[innerHTML]="step.content"></div>
</ng-template>
</mat-tab>
</ng-container>
</mat-tab-group>
<!-- Navigation - Desktop -->
<div class="z-10 sticky hidden lg:flex bottom-4 p-4">
<div class="flex items-center justify-center mx-auto p-2 rounded-full shadow-lg bg-primary">
<button
class="flex-0"
mat-flat-button
[color]="'primary'"
(click)="goToPreviousStep()">
<mat-icon
class="mr-2"
[svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
<span class="mr-1">Prev</span>
</button>
<div class="flex items-center justify-center mx-2.5 font-medium leading-5 text-on-primary">
<span>{{currentStep + 1}}</span>
<span class="mx-0.5 text-hint">/</span>
<span>{{course.totalSteps}}</span>
</div>
<button
class="flex-0"
mat-flat-button
[color]="'primary'"
(click)="goToNextStep()">
<span class="ml-1">Next</span>
<mat-icon
class="ml-2"
[svgIcon]="'heroicons_outline:arrow-narrow-right'"></mat-icon>
</button>
</div>
</div>
</div>
<!-- Progress & Navigation - Mobile -->
<div class="lg:hidden flex items-center p-4 border-t bg-card">
<button
mat-icon-button
(click)="matDrawer.toggle()">
<mat-icon [svgIcon]="'heroicons_outline:view-list'"></mat-icon>
</button>
<div class="flex items-center justify-center ml-1 lg:ml-2 font-medium leading-5">
<span>{{currentStep + 1}}</span>
<span class="mx-0.5 text-hint">/</span>
<span>{{course.totalSteps}}</span>
</div>
<mat-progress-bar
class="flex-auto ml-6 rounded-full"
[value]="100 * (currentStep + 1) / course.totalSteps"></mat-progress-bar>
<button
class="ml-4"
mat-icon-button
(click)="goToPreviousStep()">
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
</button>
<button
class="ml-0.5"
mat-icon-button
(click)="goToNextStep()">
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-right'"></mat-icon>
</button>
</div>
</mat-drawer-content>
</mat-drawer-container>
</div>

View File

@@ -0,0 +1,204 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Inject, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { MatTabGroup } from '@angular/material/tabs';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FuseMediaWatcherService } from '@fuse/services/media-watcher';
import { Category, Course } from 'app/modules/admin/apps/academy/academy.types';
import { AcademyService } from 'app/modules/admin/apps/academy/academy.service';
@Component({
selector : 'academy-details',
templateUrl : './details.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademyDetailsComponent implements OnInit, OnDestroy
{
@ViewChild('courseSteps', {static: true}) courseSteps: MatTabGroup;
categories: Category[];
course: Course;
currentStep: number = 0;
drawerMode: 'over' | 'side' = 'side';
drawerOpened: boolean = true;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
@Inject(DOCUMENT) private _document: Document,
private _academyService: AcademyService,
private _changeDetectorRef: ChangeDetectorRef,
private _elementRef: ElementRef,
private _fuseMediaWatcherService: FuseMediaWatcherService
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Get the categories
this._academyService.categories$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((categories: Category[]) => {
// Get the categories
this.categories = categories;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Get the course
this._academyService.course$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((course: Course) => {
// Get the course
this.course = course;
// Go to step
this.goToStep(course.progress.currentStep);
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Subscribe to media changes
this._fuseMediaWatcherService.onMediaChange$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe(({matchingAliases}) => {
// Set the drawerMode and drawerOpened
if ( matchingAliases.includes('lg') )
{
this.drawerMode = 'side';
this.drawerOpened = true;
}
else
{
this.drawerMode = 'over';
this.drawerOpened = false;
}
// Mark for check
this._changeDetectorRef.markForCheck();
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Go to given step
*
* @param step
*/
goToStep(step: number): void
{
// Set the current step
this.currentStep = step;
// Go to the step
this.courseSteps.selectedIndex = this.currentStep;
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Go to previous step
*/
goToPreviousStep(): void
{
// Return if we already on the first step
if ( this.currentStep === 0 )
{
return;
}
// Go to step
this.goToStep(this.currentStep - 1);
// Scroll the current step selector from sidenav into view
this._scrollCurrentStepElementIntoView();
}
/**
* Go to next step
*/
goToNextStep(): void
{
// Return if we already on the last step
if ( this.currentStep === this.course.totalSteps - 1 )
{
return;
}
// Go to step
this.goToStep(this.currentStep + 1);
// Scroll the current step selector from sidenav into view
this._scrollCurrentStepElementIntoView();
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Scrolls the current step element from
* sidenav into the view. This only happens when
* previous/next buttons pressed as we don't want
* to change the scroll position of the sidebar
* when the user actually clicks around the sidebar.
*
* @private
*/
private _scrollCurrentStepElementIntoView(): void
{
// Wrap everything into setTimeout so we can make sure that the 'current-step' class points to correct element
setTimeout(() => {
// Get the current step element and scroll it into view
const currentStepElement = this._document.getElementsByClassName('current-step')[0];
if ( currentStepElement )
{
currentStepElement.scrollIntoView({
behavior: 'smooth',
block : 'start'
});
}
});
}
}

View File

@@ -0,0 +1,196 @@
<div
class="absolute inset-0 flex flex-col min-w-0 overflow-y-auto"
cdkScrollable>
<!-- Header -->
<div class="relative flex-0 py-8 px-4 sm:p-16 overflow-hidden bg-gray-800 dark">
<!-- Background - @formatter:off -->
<!-- Rings -->
<svg class="absolute inset-0 pointer-events-none"
viewBox="0 0 960 540" width="100%" height="100%" preserveAspectRatio="xMidYMax slice" xmlns="http://www.w3.org/2000/svg">
<g class="text-gray-700 opacity-25" fill="none" stroke="currentColor" stroke-width="100">
<circle r="234" cx="196" cy="23"></circle>
<circle r="234" cx="790" cy="491"></circle>
</g>
</svg>
<!-- @formatter:on -->
<div class="z-10 relative flex flex-col items-center">
<h2 class="text-xl font-semibold">FUSE ACADEMY</h2>
<div class="mt-1 text-4xl sm:text-7xl font-extrabold tracking-tight leading-tight text-center">
What do you want to learn today?
</div>
<div class="max-w-2xl mt-6 sm:text-2xl text-center tracking-tight text-secondary">
Our courses will step you through the process of a building small applications, or adding new features to existing applications.
</div>
</div>
</div>
<!-- Main -->
<div class="flex flex-auto p-6 sm:p-10">
<div class="flex flex-col flex-auto w-full max-w-xs sm:max-w-5xl mx-auto">
<!-- Filters -->
<div class="flex flex-col sm:flex-row items-center justify-between w-full max-w-xs sm:max-w-none">
<mat-form-field class="fuse-mat-no-subscript w-full sm:w-36">
<mat-select
[value]="'all'"
(selectionChange)="filterByCategory($event)">
<mat-option [value]="'all'">All</mat-option>
<ng-container *ngFor="let category of categories; trackBy: trackByFn">
<mat-option [value]="category.slug">{{category.title}}</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
<mat-form-field
class="fuse-mat-no-subscript w-full sm:w-72 mt-4 sm:mt-0 sm:ml-4"
[floatLabel]="'always'">
<mat-icon
matPrefix
class="icon-size-5"
[svgIcon]="'heroicons_solid:search'"></mat-icon>
<input
(input)="filterByQuery(query.value)"
placeholder="Search by title or description"
matInput
#query>
</mat-form-field>
<mat-slide-toggle
class="mt-8 sm:mt-0 sm:ml-auto"
[color]="'primary'"
(change)="toggleCompleted($event)">
Hide completed
</mat-slide-toggle>
</div>
<!-- Courses -->
<ng-container *ngIf="this.filteredCourses.length; else noCourses">
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8 mt-8 sm:mt-10">
<ng-container *ngFor="let course of filteredCourses; trackBy: trackByFn">
<!-- Course -->
<div class="flex flex-col h-96 shadow rounded-2xl overflow-hidden bg-card">
<div class="flex flex-col p-6">
<div class="flex items-center justify-between">
<!-- Course category -->
<ng-container *ngIf="(course.category | fuseFindByKey:'slug':categories) as category">
<div
class="py-0.5 px-3 rounded-full text-sm font-semibold"
[ngClass]="{'text-blue-800 bg-blue-100 dark:text-blue-50 dark:bg-blue-500': category.slug === 'web',
'text-green-800 bg-green-100 dark:text-green-50 dark:bg-green-500': category.slug === 'android',
'text-pink-800 bg-pink-100 dark:text-pink-50 dark:bg-pink-500': category.slug === 'cloud',
'text-amber-800 bg-amber-100 dark:text-amber-50 dark:bg-amber-500': category.slug === 'firebase'}">
{{category.title}}
</div>
</ng-container>
<!-- Completed at least once -->
<div class="flex items-center">
<ng-container *ngIf="course.progress.completed > 0">
<mat-icon
class="icon-size-5 text-green-600"
[svgIcon]="'heroicons_solid:badge-check'"
[matTooltip]="'You completed this course at least once'"></mat-icon>
</ng-container>
</div>
</div>
<!-- Course title & description -->
<div class="mt-4 text-lg font-medium">{{course.title}}</div>
<div class="mt-0.5 line-clamp-2 text-secondary">{{course.description}}</div>
<div class="w-12 h-1 my-6 border-t-2"></div>
<!-- Course time -->
<div class="flex items-center leading-5 text-md text-secondary">
<mat-icon
class="icon-size-5 text-hint"
[svgIcon]="'heroicons_solid:clock'"></mat-icon>
<div class="ml-1.5">{{course.duration}} minutes</div>
</div>
<!-- Course completion -->
<div class="flex items-center mt-2 leading-5 text-md text-secondary">
<mat-icon
class="icon-size-5 text-hint"
[svgIcon]="'heroicons_solid:academic-cap'"></mat-icon>
<ng-container *ngIf="course.progress.completed === 0">
<div class="ml-1.5">Never completed</div>
</ng-container>
<ng-container *ngIf="course.progress.completed > 0">
<div class="ml-1.5">
<span>Completed</span>
<span class="ml-1">
<!-- Once -->
<ng-container *ngIf="course.progress.completed === 1">once</ng-container>
<!-- Twice -->
<ng-container *ngIf="course.progress.completed === 2">twice</ng-container>
<!-- Others -->
<ng-container *ngIf="course.progress.completed > 2">{{course.progress.completed}}
{{course.progress.completed | i18nPlural: {
'=0' : 'time',
'=1' : 'time',
'other': 'times'
} }}
</ng-container>
</span>
</div>
</ng-container>
</div>
</div>
<!-- Footer -->
<div class="flex flex-col w-full mt-auto">
<!-- Course progress -->
<div class="relative h-0.5">
<div
class="z-10 absolute inset-x-0 h-6 -mt-3"
[matTooltip]="course.progress.currentStep / course.totalSteps | percent"
[matTooltipPosition]="'above'"
[matTooltipClass]="'-mb-0.5'"></div>
<mat-progress-bar
class="h-0.5"
[value]="(100 * course.progress.currentStep) / course.totalSteps"></mat-progress-bar>
</div>
<!-- Course launch button -->
<div class="px-6 py-4 text-right bg-gray-50 dark:bg-transparent">
<button
mat-stroked-button
[routerLink]="[course.id]">
<span class="inline-flex items-center">
<!-- Not started -->
<ng-container *ngIf="course.progress.currentStep === 0">
<!-- Never completed -->
<ng-container *ngIf="course.progress.completed === 0">
<span>Start</span>
</ng-container>
<!-- Completed before -->
<ng-container *ngIf="course.progress.completed > 0">
<span>Start again</span>
</ng-container>
</ng-container>
<!-- Started -->
<ng-container *ngIf="course.progress.currentStep > 0">
<span>Continue</span>
</ng-container>
<mat-icon
class="ml-1.5 icon-size-5"
[svgIcon]="'heroicons_solid:arrow-sm-right'"></mat-icon>
</span>
</button>
</div>
</div>
</div>
</ng-container>
</div>
</ng-container>
<!-- No courses -->
<ng-template #noCourses>
<div class="flex flex-auto flex-col items-center justify-center bg-gray-100 dark:bg-transparent">
<mat-icon
class="icon-size-20"
[svgIcon]="'iconsmind:file_search'"></mat-icon>
<div class="mt-6 text-2xl font-semibold tracking-tight text-secondary">No courses found!</div>
</div>
</ng-template>
</div>
</div>
</div>

View File

@@ -0,0 +1,159 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MatSelectChange } from '@angular/material/select';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
import { BehaviorSubject, combineLatest, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { AcademyService } from 'app/modules/admin/apps/academy/academy.service';
import { Category, Course } from 'app/modules/admin/apps/academy/academy.types';
@Component({
selector : 'academy-list',
templateUrl : './list.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AcademyListComponent implements OnInit, OnDestroy
{
categories: Category[];
courses: Course[];
filteredCourses: Course[];
filters: {
categorySlug$: BehaviorSubject<string>;
query$: BehaviorSubject<string>;
hideCompleted$: BehaviorSubject<boolean>;
} = {
categorySlug$ : new BehaviorSubject('all'),
query$ : new BehaviorSubject(''),
hideCompleted$: new BehaviorSubject(false)
};
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _activatedRoute: ActivatedRoute,
private _changeDetectorRef: ChangeDetectorRef,
private _router: Router,
private _academyService: AcademyService
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Get the categories
this._academyService.categories$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((categories: Category[]) => {
this.categories = categories;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Get the courses
this._academyService.courses$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((courses: Course[]) => {
this.courses = this.filteredCourses = courses;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Filter the courses
combineLatest([this.filters.categorySlug$, this.filters.query$, this.filters.hideCompleted$])
.subscribe(([categorySlug, query, hideCompleted]) => {
// Reset the filtered courses
this.filteredCourses = this.courses;
// Filter by category
if ( categorySlug !== 'all' )
{
this.filteredCourses = this.filteredCourses.filter((course) => course.category === categorySlug);
}
// Filter by search query
if ( query !== '' )
{
this.filteredCourses = this.filteredCourses.filter((course) => {
return course.title.toLowerCase().includes(query.toLowerCase())
|| course.description.toLowerCase().includes(query.toLowerCase())
|| course.category.toLowerCase().includes(query.toLowerCase());
});
}
// Filter by completed
if ( hideCompleted )
{
this.filteredCourses = this.filteredCourses.filter((course) => course.progress.completed === 0);
}
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Filter by search query
*
* @param query
*/
filterByQuery(query: string): void
{
this.filters.query$.next(query);
}
/**
* Filter by category
*
* @param change
*/
filterByCategory(change: MatSelectChange): void
{
this.filters.categorySlug$.next(change.value);
}
/**
* Show/hide completed courses
*
* @param change
*/
toggleCompleted(change: MatSlideToggleChange): void
{
this.filters.hideCompleted$.next(change.checked);
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
}

View File

@@ -0,0 +1,386 @@
<div class="absolute inset-0 flex flex-col min-w-0 overflow-hidden dark:bg-gray-900">
<mat-drawer-container class="flex-auto h-full bg-transparent">
<!-- Drawer -->
<mat-drawer
class="w-60 dark:bg-gray-900"
[autoFocus]="false"
[mode]="drawerMode"
[opened]="drawerOpened"
#drawer>
<calendar-sidebar (calendarUpdated)="onCalendarUpdated($event)"></calendar-sidebar>
</mat-drawer>
<mat-drawer-content class="flex">
<!-- Main -->
<div class="flex flex-col flex-auto">
<!-- Header -->
<div class="flex flex-0 flex-wrap items-center p-4 border-b bg-card">
<button
mat-icon-button
(click)="toggleDrawer()">
<mat-icon [svgIcon]="'heroicons_outline:menu'"></mat-icon>
</button>
<div class="ml-4 text-2xl font-semibold tracking-tight whitespace-nowrap">
{{viewTitle}}
</div>
<button
class="ml-5"
mat-icon-button
(click)="previous()">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:chevron-left'"></mat-icon>
</button>
<button
mat-icon-button
(click)="next()">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:chevron-right'"></mat-icon>
</button>
<button
class="hidden md:inline-flex"
mat-icon-button
(click)="today()">
<mat-icon [svgIcon]="'heroicons_outline:calendar'"></mat-icon>
</button>
<div class="hidden md:block ml-auto">
<mat-form-field class="fuse-mat-dense fuse-mat-no-subscript w-30 ml-2">
<mat-select
(selectionChange)="changeView(viewChanger.value)"
[value]="view"
#viewChanger="matSelect">
<mat-option [value]="'dayGridMonth'">Month</mat-option>
<mat-option [value]="'timeGridWeek'">Week</mat-option>
<mat-option [value]="'timeGridDay'">Day</mat-option>
<mat-option [value]="'listYear'">Schedule</mat-option>
</mat-select>
</mat-form-field>
</div>
<!-- Mobile menu -->
<div class="md:hidden ml-auto">
<button
class=""
[matMenuTriggerFor]="actionsMenu"
mat-icon-button>
<mat-icon [svgIcon]="'heroicons_outline:dots-vertical'"></mat-icon>
<mat-menu #actionsMenu="matMenu">
<button
mat-menu-item
(click)="today()">
<mat-icon [svgIcon]="'heroicons_outline:calendar'"></mat-icon>
<span>Go to today</span>
</button>
<button
[matMenuTriggerFor]="actionsViewsMenu"
mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:view-grid'"></mat-icon>
<span>View</span>
</button>
</mat-menu>
<mat-menu #actionsViewsMenu="matMenu">
<button
mat-menu-item
[disabled]="view === 'dayGridMonth'"
(click)="changeView('dayGridMonth')">
<span>Month</span>
</button>
<button
mat-menu-item
[disabled]="view === 'timeGridWeek'"
(click)="changeView('timeGridWeek')">
<span>Week</span>
</button>
<button
mat-menu-item
[disabled]="view === 'timeGridDay'"
(click)="changeView('timeGridDay')">
<span>Day</span>
</button>
<button
mat-menu-item
[disabled]="view === 'listYear'"
(click)="changeView('listYear')">
<span>Schedule</span>
</button>
</mat-menu>
</button>
</div>
</div>
<!-- FullCalendar -->
<div class="flex flex-col flex-auto">
<full-calendar
[defaultView]="view"
[events]="events"
[firstDay]="settings.startWeekOn"
[handleWindowResize]="false"
[header]="false"
[height]="'parent'"
[plugins]="calendarPlugins"
[views]="views"
(dateClick)="onDateClick($event)"
(eventClick)="onEventClick($event)"
(eventRender)="onEventRender($event)"
#fullCalendar></full-calendar>
</div>
<!-- Event panel -->
<ng-template #eventPanel>
<!-- Preview mode -->
<ng-container *ngIf="panelMode === 'view'">
<div class="flex-auto p-8">
<!-- Info -->
<div class="flex">
<mat-icon [svgIcon]="'heroicons_outline:information-circle'"></mat-icon>
<div class="flex flex-auto justify-between ml-6">
<!-- Info -->
<div>
<div class="text-3xl font-semibold tracking-tight leading-none">{{event.title || '(No title)'}}</div>
<div class="mt-0.5 text-secondary">{{event.start | date:'EEEE, MMMM d'}}</div>
<div class="text-secondary">{{recurrenceStatus}}</div>
</div>
<!-- Actions -->
<div class="flex -mt-2 -mr-2 ml-10">
<!-- Non-recurring event -->
<ng-container *ngIf="!event.recurrence">
<!-- Edit -->
<button
mat-icon-button
(click)="changeEventPanelMode('edit', 'single')">
<mat-icon [svgIcon]="'heroicons_outline:pencil-alt'"></mat-icon>
</button>
<!-- Delete -->
<button
mat-icon-button
(click)="deleteEvent(event)">
<mat-icon [svgIcon]="'heroicons_outline:trash'"></mat-icon>
</button>
</ng-container>
<!-- Recurring event -->
<ng-container *ngIf="event.recurrence">
<!-- Edit -->
<button
mat-icon-button
[matMenuTriggerFor]="editMenu">
<mat-icon [svgIcon]="'heroicons_outline:pencil-alt'"></mat-icon>
</button>
<mat-menu #editMenu="matMenu">
<button
mat-menu-item
(click)="changeEventPanelMode('edit', 'single')">
This event
</button>
<button
mat-menu-item
*ngIf="!event.isFirstInstance"
(click)="changeEventPanelMode('edit', 'future')">
This and following events
</button>
<button
mat-menu-item
(click)="changeEventPanelMode('edit', 'all')">
All events
</button>
</mat-menu>
<!-- Delete -->
<button
mat-icon-button
[matMenuTriggerFor]="deleteMenu">
<mat-icon [svgIcon]="'heroicons_outline:trash'"></mat-icon>
</button>
<mat-menu #deleteMenu="matMenu">
<button
mat-menu-item
(click)="deleteEvent(event, 'single')">
This event
</button>
<button
mat-menu-item
*ngIf="!event.isFirstInstance"
(click)="deleteEvent(event, 'future')">
This and following events
</button>
<button
mat-menu-item
(click)="deleteEvent(event, 'all')">
All events
</button>
</mat-menu>
</ng-container>
</div>
</div>
</div>
<!-- Description -->
<div
class="flex mt-6"
*ngIf="event.description">
<mat-icon [svgIcon]="'heroicons_outline:menu-alt-2'"></mat-icon>
<div class="flex-auto ml-6">{{event.description}}</div>
</div>
<!-- Calendar -->
<div class="flex mt-6">
<mat-icon [svgIcon]="'heroicons_outline:calendar'"></mat-icon>
<div class="flex flex-auto items-center ml-6">
<div
class="w-2 h-2 rounded-full"
[ngClass]="getCalendar(event.calendarId).color"></div>
<div class="ml-3 leading-none">{{getCalendar(event.calendarId).title}}</div>
</div>
</div>
</div>
</ng-container>
<!-- Add / Edit mode -->
<ng-container *ngIf="panelMode === 'add' || panelMode === 'edit'">
<form
class="flex flex-col w-full p-6 pt-8 sm:pt-10 sm:pr-8"
[formGroup]="eventForm">
<!-- Title -->
<div class="flex items-center">
<mat-icon
class="hidden sm:inline-flex mr-6"
[svgIcon]="'heroicons_outline:pencil-alt'"></mat-icon>
<mat-form-field class="fuse-mat-no-subscript flex-auto">
<input
matInput
[formControlName]="'title'"
[placeholder]="'Event title'">
</mat-form-field>
</div>
<!-- Dates -->
<div class="flex items-start mt-6">
<mat-icon
class="hidden sm:inline-flex mt-3 mr-6"
[svgIcon]="'heroicons_outline:calendar'"></mat-icon>
<div class="flex-auto">
<fuse-date-range
[formControlName]="'range'"
[dateFormat]="settings.dateFormat"
[timeRange]="!eventForm.get('allDay').value"
[timeFormat]="settings.timeFormat"></fuse-date-range>
<mat-checkbox
class="mt-4"
[color]="'primary'"
[formControlName]="'allDay'">
All day
</mat-checkbox>
</div>
</div>
<!-- Recurrence -->
<div
class="flex items-center mt-6"
*ngIf="!event.recurrence || eventEditMode !== 'single'">
<mat-icon
class="hidden sm:inline-flex mr-6 transform -scale-x-1"
[svgIcon]="'heroicons_outline:refresh'"></mat-icon>
<div
class="flex flex-auto items-center h-12 px-4 rounded-md border cursor-pointer shadow-sm border-gray-300 dark:bg-black dark:bg-opacity-5 dark:border-gray-500"
(click)="openRecurrenceDialog()">
<div class="flex-auto">
{{recurrenceStatus || 'Does not repeat'}}
</div>
</div>
</div>
<!-- Calendar -->
<div class="flex items-center mt-6">
<mat-icon
class="hidden sm:inline-flex mr-6"
[svgIcon]="'heroicons_outline:tag'"></mat-icon>
<mat-form-field class="fuse-mat-no-subscript flex-auto">
<mat-select
[formControlName]="'calendarId'"
(change)="$event.stopImmediatePropagation()">
<mat-select-trigger class="inline-flex items-center leading-none">
<span
class="w-3 h-3 rounded-full"
[ngClass]="getCalendar(eventForm.get('calendarId').value)?.color"></span>
<span class="ml-3">{{getCalendar(eventForm.get('calendarId').value)?.title}}</span>
</mat-select-trigger>
<mat-option
*ngFor="let calendar of calendars"
[value]="calendar.id">
<div class="inline-flex items-center">
<span
class="w-3 h-3 rounded-full"
[ngClass]="calendar.color"></span>
<span class="ml-3">{{calendar.title}}</span>
</div>
</mat-option>
</mat-select>
</mat-form-field>
</div>
<!-- Description -->
<div class="flex items-start mt-6">
<mat-icon
class="hidden sm:inline-flex mr-6 mt-3"
[svgIcon]="'heroicons_outline:menu-alt-2'"></mat-icon>
<mat-form-field class="fuse-mat-textarea fuse-mat-no-subscript flex-auto">
<textarea
matInput
cdkTextareaAutosize
[cdkAutosizeMinRows]="1"
[formControlName]="'description'"
[placeholder]="'Event description'">
</textarea>
</mat-form-field>
</div>
<!-- Actions -->
<div class="ml-auto mt-6">
<button
class="add"
*ngIf="panelMode === 'add'"
mat-flat-button
type="button"
[color]="'primary'"
(click)="addEvent()">
Add
</button>
<button
class="save"
*ngIf="panelMode === 'edit'"
mat-flat-button
type="button"
[color]="'primary'"
(click)="updateEvent()">
Save
</button>
</div>
</form>
</ng-container>
</ng-template>
</div>
</mat-drawer-content>
</mat-drawer-container>
</div>

View File

@@ -0,0 +1,121 @@
calendar {
/* Tweak: FullCalendar CSS only height to improve resize performance */
/* With this tweak, we can disable "handleWindowResize" option of FullCalendar */
/* which disables the height calculations on window resize and increases the */
/* overall performance. */
/* This tweak only affects the Calendar app's FullCalendar. */
full-calendar {
display: flex;
flex-direction: column;
flex: 1 0 auto;
width: 100%;
height: 100%;
.fc-view-container {
display: flex;
flex-direction: column;
flex: 1 0 auto;
width: 100%;
height: 100%;
.fc-view {
/* Day grid - Month view */
/* Time grid - Week view */
/* Time grid - Day view */
&.fc-dayGridMonth-view,
&.fc-timeGridWeek-view,
&.fc-timeGridDay-view {
display: flex;
flex-direction: column;
flex: 1 0 auto;
width: 100%;
height: 100%;
> table {
display: flex;
flex-direction: column;
flex: 1 0 auto;
height: 100%;
> thead {
display: flex;
}
> tbody {
display: flex;
flex: 1 1 auto;
overflow: hidden;
> tr {
display: flex;
> td {
display: flex;
flex-direction: column;
.fc-scroller {
flex: 1 1 auto;
overflow: hidden scroll !important;
height: auto !important;
}
}
}
}
}
}
/* Day grid - Month view */
&.fc-dayGridMonth-view {
> table {
> tbody {
> tr {
> td {
.fc-scroller {
display: flex;
> .fc-day-grid {
display: flex;
flex-direction: column;
min-height: 580px;
> .fc-row {
flex: 1 0 0;
height: auto !important;
}
}
}
}
}
}
}
}
/* List - Year view */
&.fc-listYear-view {
width: 100%;
height: 100%;
.fc-scroller {
width: 100%;
height: 100% !important;
overflow: hidden !important;
}
}
}
}
}
}
/* Event panel */
.calendar-event-panel {
border-radius: 8px;
@apply shadow-2xl bg-card;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FullCalendarModule } from '@fullcalendar/angular';
import { FuseDateRangeModule } from '@fuse/components/date-range';
import { SharedModule } from 'app/shared/shared.module';
import { CalendarComponent } from 'app/modules/admin/apps/calendar/calendar.component';
import { CalendarRecurrenceComponent } from 'app/modules/admin/apps/calendar/recurrence/recurrence.component';
import { CalendarSettingsComponent } from 'app/modules/admin/apps/calendar/settings/settings.component';
import { CalendarSidebarComponent } from 'app/modules/admin/apps/calendar/sidebar/sidebar.component';
import { calendarRoutes } from 'app/modules/admin/apps/calendar/calendar.routing';
@NgModule({
declarations: [
CalendarComponent,
CalendarRecurrenceComponent,
CalendarSettingsComponent,
CalendarSidebarComponent
],
imports : [
RouterModule.forChild(calendarRoutes),
ScrollingModule,
MatButtonModule,
MatButtonToggleModule,
MatCheckboxModule,
MatDatepickerModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatMenuModule,
MatMomentDateModule,
MatRadioModule,
MatSelectModule,
MatSidenavModule,
MatTooltipModule,
FullCalendarModule,
FuseDateRangeModule,
SharedModule
],
providers : [
{
provide : MAT_DATE_FORMATS,
useValue: {
parse : {
dateInput: 'DD.MM.YYYY'
},
display: {
dateInput : 'DD.MM.YYYY',
monthYearLabel : 'MMM YYYY',
dateA11yLabel : 'DD.MM.YYYY',
monthYearA11yLabel: 'MMMM YYYY'
}
}
}
]
})
export class CalendarModule
{
}

View File

@@ -0,0 +1,89 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { CalendarService } from 'app/modules/admin/apps/calendar/calendar.service';
import { Calendar, CalendarSettings, CalendarWeekday } from 'app/modules/admin/apps/calendar/calendar.types';
@Injectable({
providedIn: 'root'
})
export class CalendarCalendarsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _calendarService: CalendarService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Calendar[]>
{
return this._calendarService.getCalendars();
}
}
@Injectable({
providedIn: 'root'
})
export class CalendarSettingsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _calendarService: CalendarService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<CalendarSettings>
{
return this._calendarService.getSettings();
}
}
@Injectable({
providedIn: 'root'
})
export class CalendarWeekdaysResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _calendarService: CalendarService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<CalendarWeekday[]>
{
return this._calendarService.getWeekdays();
}
}

View File

@@ -0,0 +1,23 @@
import { Route } from '@angular/router';
import { CalendarComponent } from 'app/modules/admin/apps/calendar/calendar.component';
import { CalendarSettingsComponent } from 'app/modules/admin/apps/calendar/settings/settings.component';
import { CalendarCalendarsResolver, CalendarSettingsResolver, CalendarWeekdaysResolver } from 'app/modules/admin/apps/calendar/calendar.resolvers';
export const calendarRoutes: Route[] = [
{
path : '',
component: CalendarComponent,
resolve : {
calendars: CalendarCalendarsResolver,
settings : CalendarSettingsResolver,
weekdays : CalendarWeekdaysResolver
}
},
{
path : 'settings',
component: CalendarSettingsComponent,
resolve : {
settings: CalendarSettingsResolver
}
}
];

View File

@@ -0,0 +1,475 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { map, switchMap, take, tap } from 'rxjs/operators';
import { Moment } from 'moment';
import { Calendar, CalendarEvent, CalendarEventEditMode, CalendarSettings, CalendarWeekday } from 'app/modules/admin/apps/calendar/calendar.types';
@Injectable({
providedIn: 'root'
})
export class CalendarService
{
// Private
private _calendars: BehaviorSubject<Calendar[] | null> = new BehaviorSubject(null);
private _events: BehaviorSubject<CalendarEvent[] | null> = new BehaviorSubject(null);
private _loadedEventsRange: { start: Moment | null, end: Moment | null } = {
start: null,
end : null
};
private readonly _numberOfDaysToPrefetch = 60;
private _settings: BehaviorSubject<CalendarSettings | null> = new BehaviorSubject(null);
private _weekdays: BehaviorSubject<CalendarWeekday[] | null> = new BehaviorSubject(null);
/**
* Constructor
*/
constructor(private _httpClient: HttpClient)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Getter for calendars
*/
get calendars$(): Observable<Calendar[]>
{
return this._calendars.asObservable();
}
/**
* Getter for events
*/
get events$(): Observable<CalendarEvent[]>
{
return this._events.asObservable();
}
/**
* Getter for settings
*/
get settings$(): Observable<CalendarSettings>
{
return this._settings.asObservable();
}
/**
* Getter for weekdays
*/
get weekdays$(): Observable<CalendarWeekday[]>
{
return this._weekdays.asObservable();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Get calendars
*/
getCalendars(): Observable<Calendar[]>
{
return this._httpClient.get<Calendar[]>('api/apps/calendar/calendars').pipe(
tap((response) => {
this._calendars.next(response);
})
);
}
/**
* Add calendar
*
* @param calendar
*/
addCalendar(calendar: Calendar): Observable<Calendar>
{
return this.calendars$.pipe(
take(1),
switchMap(calendars => this._httpClient.post<Calendar>('api/apps/calendar/calendars', {
calendar
}).pipe(
map((addedCalendar) => {
// Add the calendar
calendars.push(addedCalendar);
// Update the calendars
this._calendars.next(calendars);
// Return the added calendar
return addedCalendar;
})
))
);
}
/**
* Update calendar
*
* @param id
* @param calendar
*/
updateCalendar(id: string, calendar: Calendar): Observable<Calendar>
{
return this.calendars$.pipe(
take(1),
switchMap(calendars => this._httpClient.patch<Calendar>('api/apps/calendar/calendars', {
id,
calendar
}).pipe(
map((updatedCalendar) => {
// Find the index of the updated calendar
const index = calendars.findIndex(item => item.id === id);
// Update the calendar
calendars[index] = updatedCalendar;
// Update the calendars
this._calendars.next(calendars);
// Return the updated calendar
return updatedCalendar;
})
))
);
}
/**
* Delete calendar
*
* @param id
*/
deleteCalendar(id: string): Observable<any>
{
return this.calendars$.pipe(
take(1),
switchMap(calendars => this._httpClient.delete<Calendar>('api/apps/calendar/calendars', {
params: {id}
}).pipe(
map((isDeleted) => {
// Find the index of the deleted calendar
const index = calendars.findIndex(item => item.id === id);
// Delete the calendar
calendars.splice(index, 1);
// Update the calendars
this._calendars.next(calendars);
// Remove the events belong to deleted calendar
const events = this._events.value.filter((event) => event.calendarId !== id);
// Update the events
this._events.next(events);
// Return the deleted status
return isDeleted;
})
))
);
}
/**
* Get events
*
* @param start
* @param end
* @param replace
*/
getEvents(start: Moment, end: Moment, replace = false): Observable<CalendarEvent[]>
{
// Set the new start date for loaded events
if ( replace || !this._loadedEventsRange.start || start.isBefore(this._loadedEventsRange.start) )
{
this._loadedEventsRange.start = start;
}
// Set the new end date for loaded events
if ( replace || !this._loadedEventsRange.end || end.isAfter(this._loadedEventsRange.end) )
{
this._loadedEventsRange.end = end;
}
// Get the events
return this._httpClient.get<CalendarEvent[]>('api/apps/calendar/events', {
params: {
start: start.toISOString(true),
end : end.toISOString(true)
}
}).pipe(
switchMap(response => this._events.pipe(
take(1),
map((events) => {
// If replace...
if ( replace )
{
// Execute the observable with the response replacing the events object
this._events.next(response);
}
// Otherwise...
else
{
// If events is null, replace it with an empty array
events = events || [];
// Execute the observable by appending the response to the current events
this._events.next([...events, ...response]);
}
// Return the response
return response;
})
))
);
}
/**
* Reload events using the loaded events range
*/
reloadEvents(): Observable<CalendarEvent[]>
{
// Get the events
return this._httpClient.get<CalendarEvent[]>('api/apps/calendar/events', {
params: {
start: this._loadedEventsRange.start.toISOString(),
end : this._loadedEventsRange.end.toISOString()
}
}).pipe(
map((response) => {
// Execute the observable with the response replacing the events object
this._events.next(response);
// Return the response
return response;
})
);
}
/**
* Prefetch future events
*
* @param end
*/
prefetchFutureEvents(end: Moment): Observable<CalendarEvent[]>
{
// Calculate the remaining prefetched days
const remainingDays = this._loadedEventsRange.end.diff(end, 'days');
// Return if remaining days is bigger than the number
// of days to prefetch. This means we were already been
// there and fetched the events mock-api so no need for doing
// it again.
if ( remainingDays >= this._numberOfDaysToPrefetch )
{
return of([]);
}
// Figure out the start and end dates
const start = this._loadedEventsRange.end.clone().add(1, 'day');
end = this._loadedEventsRange.end.clone().add(this._numberOfDaysToPrefetch - remainingDays, 'days');
// Prefetch the events
return this.getEvents(start, end);
}
/**
* Prefetch past events
*
* @param start
*/
prefetchPastEvents(start: Moment): Observable<CalendarEvent[]>
{
// Calculate the remaining prefetched days
const remainingDays = start.diff(this._loadedEventsRange.start, 'days');
// Return if remaining days is bigger than the number
// of days to prefetch. This means we were already been
// there and fetched the events mock-api so no need for doing
// it again.
if ( remainingDays >= this._numberOfDaysToPrefetch )
{
return of([]);
}
// Figure out the start and end dates
start = this._loadedEventsRange.start.clone().subtract(this._numberOfDaysToPrefetch - remainingDays, 'days');
const end = this._loadedEventsRange.start.clone().subtract(1, 'day');
// Prefetch the events
return this.getEvents(start, end);
}
/**
* Add event
*
* @param event
*/
addEvent(event): Observable<CalendarEvent>
{
return this.events$.pipe(
take(1),
switchMap(events => this._httpClient.post<CalendarEvent>('api/apps/calendar/event', {
event
}).pipe(
map((addedEvent) => {
// Update the events
this._events.next(events);
// Return the added event
return addedEvent;
})
))
);
}
/**
* Update event
*
* @param id
* @param event
*/
updateEvent(id: string, event): Observable<CalendarEvent>
{
return this.events$.pipe(
take(1),
switchMap(events => this._httpClient.patch<CalendarEvent>('api/apps/calendar/event', {
id,
event
}).pipe(
map((updatedEvent) => {
// Find the index of the updated event
const index = events.findIndex(item => item.id === id);
// Update the event
events[index] = updatedEvent;
// Update the events
this._events.next(events);
// Return the updated event
return updatedEvent;
})
))
);
}
/**
* Update recurring event
*
* @param event
* @param originalEvent
* @param mode
*/
updateRecurringEvent(event, originalEvent, mode: CalendarEventEditMode): Observable<boolean>
{
return this._httpClient.patch<boolean>('api/apps/calendar/recurring-event', {
event,
originalEvent,
mode
});
}
/**
* Delete event
*
* @param id
*/
deleteEvent(id: string): Observable<CalendarEvent>
{
return this.events$.pipe(
take(1),
switchMap(events => this._httpClient.delete<CalendarEvent>('api/apps/calendar/event', {params: {id}}).pipe(
map((isDeleted) => {
// Find the index of the deleted event
const index = events.findIndex(item => item.id === id);
// Delete the event
events.splice(index, 1);
// Update the events
this._events.next(events);
// Return the deleted status
return isDeleted;
})
))
);
}
/**
* Delete recurring event
*
* @param event
* @param mode
*/
deleteRecurringEvent(event, mode: CalendarEventEditMode): Observable<boolean>
{
return this._httpClient.delete<boolean>('api/apps/calendar/recurring-event', {
params: {
event: JSON.stringify(event),
mode
}
});
}
/**
* Get settings
*/
getSettings(): Observable<CalendarSettings>
{
return this._httpClient.get<CalendarSettings>('api/apps/calendar/settings').pipe(
tap((response) => {
this._settings.next(response);
})
);
}
/**
* Update settings
*/
updateSettings(settings: CalendarSettings): Observable<CalendarSettings>
{
return this.events$.pipe(
take(1),
switchMap(events => this._httpClient.patch<CalendarSettings>('api/apps/calendar/settings', {
settings
}).pipe(
map((updatedSettings) => {
// Update the settings
this._settings.next(settings);
// Get weekdays again to get them in correct order
// in case the startWeekOn setting changes
this.getWeekdays().subscribe();
// Return the updated settings
return updatedSettings;
})
))
);
}
/**
* Get weekdays
*/
getWeekdays(): Observable<CalendarWeekday[]>
{
return this._httpClient.get<CalendarWeekday[]>('api/apps/calendar/weekdays').pipe(
tap((response) => {
this._weekdays.next(response);
})
);
}
}

View File

@@ -0,0 +1,47 @@
export interface Calendar
{
id: string;
title: string;
color: string;
visible: boolean;
}
export type CalendarDrawerMode = 'over' | 'side';
export interface CalendarEvent
{
id: string;
calendarId: string;
recurringEventId: string | null;
isFirstInstance: boolean;
title: string;
description: string;
start: string | null;
end: string | null;
allDay: boolean;
recurrence: string;
}
export interface CalendarEventException
{
id: string;
eventId: string;
exdate: string;
}
export type CalendarEventPanelMode = 'view' | 'add' | 'edit';
export type CalendarEventEditMode = 'single' | 'future' | 'all';
export interface CalendarSettings
{
dateFormat: 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY-MM-DD' | 'll';
timeFormat: '12' | '24';
startWeekOn: 6 | 0 | 1;
}
export interface CalendarWeekday
{
abbr: string;
label: string;
value: string;
}

View File

@@ -0,0 +1,120 @@
<form
class="flex flex-col w-full"
[formGroup]="recurrenceForm">
<div class="text-2xl font-semibold tracking-tight">Recurrence rules</div>
<!-- Interval and frequency -->
<div class="flex mt-12">
<mat-form-field class="fuse-mat-no-subscript w-24 -mt-6">
<mat-label>Repeat every</mat-label>
<input
type="number"
matInput
[autocomplete]="'off'"
[formControlName]="'interval'"
[min]="1">
</mat-form-field>
<mat-form-field class="fuse-mat-no-subscript w-40 ml-4">
<mat-select [formControlName]="'freq'">
<mat-option [value]="'DAILY'">day(s)</mat-option>
<mat-option [value]="'WEEKLY'">week(s)</mat-option>
<mat-option [value]="'MONTHLY'">month(s)</mat-option>
<mat-option [value]="'YEARLY'">year(s)</mat-option>
</mat-select>
</mat-form-field>
</div>
<!-- Weekly repeat options -->
<div
class="flex flex-col mt-6"
[formGroupName]="'weekly'"
*ngIf="recurrenceForm.get('freq').value === 'WEEKLY'">
<div class="font-medium">Repeat on</div>
<mat-button-toggle-group
class="mt-1.5 border-0 space-x-1"
[formControlName]="'byDay'"
[multiple]="true">
<mat-button-toggle
class="w-10 h-10 border-0 rounded-full"
*ngFor="let weekday of weekdays"
[disableRipple]="true"
[value]="weekday.value"
[matTooltip]="weekday.label">
{{weekday.abbr}}
</mat-button-toggle>
</mat-button-toggle-group>
</div>
<!-- Monthly repeat options -->
<div
class="flex mt-6"
[formGroupName]="'monthly'"
*ngIf="recurrenceForm.get('freq').value === 'MONTHLY'">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Repeat on</mat-label>
<mat-select [formControlName]="'repeatOn'">
<mat-option [value]="'date'">Monthly on day {{recurrenceForm.get('monthly.date').value}}</mat-option>
<mat-option [value]="'nthWeekday'">Monthly on the {{nthWeekdayText}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<!-- Ends -->
<div
class="flex flex-col mt-12"
[formGroupName]="'end'">
<div class="flex items-center">
<mat-form-field class="fuse-mat-no-subscript w-24 -mt-6">
<mat-label>Ends</mat-label>
<mat-select [formControlName]="'type'">
<mat-option [value]="'never'">Never</mat-option>
<mat-option [value]="'until'">On</mat-option>
<mat-option [value]="'count'">After</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field
class="fuse-mat-no-subscript w-40 ml-4"
*ngIf="recurrenceForm.get('end.type').value === 'until'">
<input
matInput
[matDatepicker]="untilDatePicker"
[formControlName]="'until'">
<mat-datepicker-toggle
matSuffix
[for]="untilDatePicker"></mat-datepicker-toggle>
<mat-datepicker #untilDatePicker></mat-datepicker>
</mat-form-field>
<mat-form-field
class="fuse-mat-no-subscript w-40 ml-4"
*ngIf="recurrenceForm.get('end.type').value === 'count'">
<input
type="number"
matInput
[autocomplete]="'off'"
[formControlName]="'count'"
[min]="1">
<span matSuffix>occurrence(s)</span>
</mat-form-field>
</div>
</div>
<!-- Actions -->
<div class="ml-auto mt-8">
<button
class="clear"
mat-button
[color]="'primary'"
(click)="clear()">
Clear
</button>
<button
mat-flat-button
[disabled]="recurrenceForm.invalid"
[color]="'primary'"
(click)="done()">
Done
</button>
</div>
</form>

View File

@@ -0,0 +1,341 @@
import { Component, Inject, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import * as moment from 'moment';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { CalendarService } from 'app/modules/admin/apps/calendar/calendar.service';
import { CalendarWeekday } from 'app/modules/admin/apps/calendar/calendar.types';
@Component({
selector : 'calendar-recurrence',
templateUrl : './recurrence.component.html',
encapsulation: ViewEncapsulation.None
})
export class CalendarRecurrenceComponent implements OnInit, OnDestroy
{
nthWeekdayText: string;
recurrenceForm: FormGroup;
recurrenceFormValues: any;
weekdays: CalendarWeekday[];
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
public matDialogRef: MatDialogRef<CalendarRecurrenceComponent>,
private _calendarService: CalendarService,
private _formBuilder: FormBuilder
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Get weekdays
this._calendarService.weekdays$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((weekdays) => {
// Store the weekdays
this.weekdays = weekdays;
});
// Initialize
this._init();
// Create the recurrence form
this.recurrenceForm = this._formBuilder.group({
freq : [null],
interval: [null, Validators.required],
weekly : this._formBuilder.group({
byDay: [[]]
}),
monthly : this._formBuilder.group({
repeatOn : [null], // date | nthWeekday
date : [null],
nthWeekday: [null]
}),
end : this._formBuilder.group({
type : [null], // never | until | count
until: [null],
count: [null]
})
});
// Subscribe to 'freq' field value changes
this.recurrenceForm.get('freq').valueChanges.subscribe((value) => {
// Set the end values
this._setEndValues(value);
});
// Subscribe to 'weekly.byDay' field value changes
this.recurrenceForm.get('weekly.byDay').valueChanges.subscribe((value) => {
// Get the event's start date
const startDate = moment(this.data.event.start);
// If nothing is selected, select the original value from
// the event form to prevent an empty value on the field
if ( !value || !value.length )
{
// Get the day of event start date
const eventStartDay = startDate.format('dd').toUpperCase();
// Set the original value back without emitting a
// change event to prevent an infinite loop
this.recurrenceForm.get('weekly.byDay').setValue([eventStartDay], {emitEvent: false});
}
});
// Patch the form with the values
this.recurrenceForm.patchValue(this.recurrenceFormValues);
// Set end values for the first time
this._setEndValues(this.recurrenceForm.get('freq').value);
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Clear
*/
clear(): void
{
// Close the dialog
this.matDialogRef.close({recurrence: 'cleared'});
}
/**
* Done
*/
done(): void
{
// Get the recurrence form values
const recurrenceForm = this.recurrenceForm.value;
// Prepare the rule array and add the base rules
const ruleArr = ['FREQ=' + recurrenceForm.freq, 'INTERVAL=' + recurrenceForm.interval];
// If monthly on certain days...
if ( recurrenceForm.freq === 'MONTHLY' && recurrenceForm.monthly.repeatOn === 'nthWeekday' )
{
ruleArr.push('BYDAY=' + recurrenceForm.monthly.nthWeekday);
}
// If weekly...
if ( recurrenceForm.freq === 'WEEKLY' )
{
// If byDay is an array...
if ( Array.isArray(recurrenceForm.weekly.byDay) )
{
ruleArr.push('BYDAY=' + recurrenceForm.weekly.byDay.join(','));
}
// Otherwise
else
{
ruleArr.push('BYDAY=' + recurrenceForm.weekly.byDay);
}
}
// If one of the end options is selected...
if ( recurrenceForm.end.type === 'until' )
{
ruleArr.push('UNTIL=' + moment(recurrenceForm.end.until).endOf('day').utc().format('YYYYMMDD[T]HHmmss[Z]'));
}
if ( recurrenceForm.end.type === 'count' )
{
ruleArr.push('COUNT=' + recurrenceForm.end.count);
}
// Generate rule text
const ruleText = ruleArr.join(';');
// Close the dialog
this.matDialogRef.close({recurrence: ruleText});
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Initialize
*
* @private
*/
private _init(): void
{
// Get the event's start date
const startDate = moment(this.data.event.start);
// Calculate the weekday
const weekday = moment(this.data.event.start).format('dd').toUpperCase();
// Calculate the nthWeekday
let nthWeekdayNo = 1;
while ( startDate.clone().isSame(startDate.clone().subtract(nthWeekdayNo, 'week'), 'month') )
{
nthWeekdayNo++;
}
const nthWeekday = nthWeekdayNo + weekday;
// Calculate the nthWeekday as text
const ordinalNumberSuffixes = {
1: 'st',
2: 'nd',
3: 'rd',
4: 'th',
5: 'th'
};
this.nthWeekdayText = nthWeekday.slice(0, 1) + ordinalNumberSuffixes[nthWeekday.slice(0, 1)] + ' ' +
this.weekdays.find((item) => item.value === nthWeekday.slice(-2)).label;
// Set the defaults on recurrence form values
this.recurrenceFormValues = {
freq : 'DAILY',
interval: 1,
weekly : {
byDay: weekday
},
monthly : {
repeatOn : 'date',
date : moment(this.data.event.start).date(),
nthWeekday: nthWeekday
},
end : {
type : 'never',
until: null,
count: null
}
};
// If recurrence rule string is available on the
// event meaning that the is a recurring one...
if ( this.data.event.recurrence )
{
// Parse the rules
const parsedRules: any = {};
this.data.event.recurrence.split(';').forEach((rule) => {
parsedRules[rule.split('=')[0]] = rule.split('=')[1];
});
// Overwrite the recurrence form values
this.recurrenceFormValues.freq = parsedRules.FREQ;
this.recurrenceFormValues.interval = parsedRules.INTERVAL;
if ( parsedRules.FREQ === 'WEEKLY' )
{
this.recurrenceFormValues.weekly.byDay = parsedRules.BYDAY.split(',');
}
if ( parsedRules.FREQ === 'MONTHLY' )
{
this.recurrenceFormValues.monthly.repeatOn = parsedRules.BYDAY ? 'nthWeekday' : 'date';
}
this.recurrenceFormValues.end.type = parsedRules.UNTIL ? 'until' : (parsedRules.COUNT ? 'count' : 'never');
this.recurrenceFormValues.end.until = parsedRules.UNTIL || null;
this.recurrenceFormValues.end.count = parsedRules.COUNT || null;
}
}
/**
* Set the end value based on frequency
*
* @param freq
* @private
*/
private _setEndValues(freq: string): void
{
// Return if freq is not available
if ( !freq )
{
return;
}
// Get the event's start date
const startDate = moment(this.data.event.startDate);
// Get the end type
const endType = this.recurrenceForm.get('end.type').value;
// If until is not selected
if ( endType !== 'until' )
{
let until;
// Change the until's default value based on the frequency
if ( freq === 'DAILY' )
{
until = startDate.clone().add(1, 'month').toISOString();
}
if ( freq === 'WEEKLY' )
{
until = startDate.clone().add(12, 'weeks').toISOString();
}
if ( freq === 'MONTHLY' )
{
until = startDate.clone().add(12, 'months').toISOString();
}
if ( freq === 'YEARLY' )
{
until = startDate.clone().add(5, 'years').toISOString();
}
// Set the until
this.recurrenceForm.get('end.until').setValue(until);
}
// If count is not selected...
if ( endType !== 'count' )
{
let count;
// Change the count's default value based on the frequency
if ( freq === 'DAILY' )
{
count = 30;
}
if ( freq === 'WEEKLY' || freq === 'MONTHLY' )
{
count = 12;
}
if ( freq === 'YEARLY' )
{
count = 5;
}
// Set the count
this.recurrenceForm.get('end.count').setValue(count);
}
}
}

View File

@@ -0,0 +1,60 @@
<div
class="absolute inset-0 flex flex-col min-w-0 overflow-y-auto"
cdkScrollable>
<!-- Main -->
<div class="flex flex-col flex-auto">
<!-- Header -->
<div class="flex items-center h-16 px-4 sm:px-6 py-2 border-b">
<a
[routerLink]="['..']"
mat-icon-button>
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
</a>
<div class="ml-1 text-lg font-medium">Settings</div>
</div>
<div class="flex flex-auto p-6 sm:p-8">
<form
class="flex flex-col w-full max-w-xs"
[formGroup]="settingsForm">
<mat-form-field class="w-full">
<mat-label>Date format</mat-label>
<mat-select [formControlName]="'dateFormat'">
<mat-option [value]="'ll'">Aug 20, {{year}}</mat-option>
<mat-option [value]="'MM/DD/YYYY'">12/31/{{year}}</mat-option>
<mat-option [value]="'DD/MM/YYYY'">31/12/{{year}}</mat-option>
<mat-option [value]="'YYYY-MM-DD'">{{year}}-12-31</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="w-full">
<mat-label>Time format</mat-label>
<mat-select [formControlName]="'timeFormat'">
<mat-option [value]="'12'">1:00pm</mat-option>
<mat-option [value]="'24'">13:30</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="w-full">
<mat-label>Start week on</mat-label>
<mat-select [formControlName]="'startWeekOn'">
<mat-option [value]="6">Saturday</mat-option>
<mat-option [value]="0">Sunday</mat-option>
<mat-option [value]="1">Monday</mat-option>
</mat-select>
</mat-form-field>
<button
class="mt-4"
mat-flat-button
[color]="'primary'"
[disabled]="settingsForm.invalid || settingsForm.pristine"
(click)="updateSettings()">
Save
</button>
</form>
</div>
</div>
</div>

View File

@@ -0,0 +1,96 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { CalendarService } from 'app/modules/admin/apps/calendar/calendar.service';
@Component({
selector : 'calendar-settings',
templateUrl : './settings.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation : ViewEncapsulation.None
})
export class CalendarSettingsComponent implements OnInit, OnDestroy
{
settingsForm: FormGroup;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _calendarService: CalendarService,
private _changeDetectorRef: ChangeDetectorRef,
private _formBuilder: FormBuilder
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Getter for current year
*/
get year(): string
{
return new Date().getFullYear().toString();
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Create the event form
this.settingsForm = this._formBuilder.group({
dateFormat : [''],
timeFormat : [''],
startWeekOn: ['']
});
// Get settings
this._calendarService.settings$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((settings) => {
// Fill the settings form
this.settingsForm.patchValue(settings);
// Mark for check
this._changeDetectorRef.markForCheck();
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
updateSettings(): void
{
// Get the settings
const settings = this.settingsForm.value;
// Update the settings on the server
this._calendarService.updateSettings(settings).subscribe((updatedSettings) => {
// Reset the form with the updated settings
this.settingsForm.reset(updatedSettings);
});
}
}

View File

@@ -0,0 +1,12 @@
export const calendarColors = [
'bg-gray-500',
'bg-red-500',
'bg-orange-500',
'bg-yellow-500',
'bg-green-500',
'bg-teal-500',
'bg-blue-500',
'bg-indigo-500',
'bg-purple-500',
'bg-pink-500'
];

View File

@@ -0,0 +1,116 @@
<div class="flex flex-col flex-auto min-h-full p-8">
<div class="pb-6 text-4xl font-extrabold tracking-tight">Calendar</div>
<!-- Calendars -->
<div class="group flex items-center justify-between mb-3">
<span class="text-lg font-medium">Calendars</span>
<mat-icon
class="hidden group-hover:inline-flex icon-size-5 cursor-pointer"
[svgIcon]="'heroicons_solid:plus-circle'"
(click)="addCalendar()"></mat-icon>
</div>
<div
class="group flex items-center justify-between mt-2"
*ngFor="let calendar of calendars">
<div
class="flex items-center"
(click)="toggleCalendarVisibility(calendar)">
<mat-icon
class="cursor-pointer"
[svgIcon]="calendar.visible ? 'check_box' : 'check_box_outline_blank'"></mat-icon>
<span
class="w-3 h-3 ml-2 rounded-full"
[ngClass]="calendar.color"></span>
<span class="ml-2 leading-none">{{calendar.title}}</span>
</div>
<mat-icon
class="hidden group-hover:inline-flex icon-size-5 cursor-pointer"
[svgIcon]="'heroicons_solid:pencil-alt'"
(click)="openEditPanel(calendar)"></mat-icon>
</div>
<!-- Settings -->
<div class="-mx-4 mt-auto">
<a
class="flex items-center w-full py-3 px-4 rounded-full hover:bg-hover"
[routerLink]="['settings']">
<mat-icon [svgIcon]="'heroicons_outline:cog'"></mat-icon>
<span class="ml-2 font-medium leading-none">Settings</span>
</a>
</div>
<!-- Edit panel -->
<ng-template #editPanel>
<div class="flex flex-col w-80 p-8 shadow-2xl rounded-lg bg-card">
<div class="text-2xl font-semibold tracking-tight">
<ng-container *ngIf="!calendar.id">Add calendar</ng-container>
<ng-container *ngIf="calendar.id">Edit calendar</ng-container>
</div>
<div class="flex items-center mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<input
matInput
[(ngModel)]="calendar.title"
[placeholder]="'Title'"
required>
<mat-select
[(value)]="calendar.color"
[disableOptionCentering]="true"
matPrefix>
<mat-select-trigger class="h-6">
<mat-icon [svgIcon]="'heroicons_outline:color-swatch'"></mat-icon>
</mat-select-trigger>
<div class="px-4 pt-5 text-xl font-semibold">Calendar color</div>
<div class="flex flex-wrap w-48 my-4 mx-3 -mr-5">
<mat-option
class="relative flex w-12 h-12 p-0 cursor-pointer rounded-full bg-transparent"
*ngFor="let color of calendarColors"
[value]="color"
#matOption="matOption">
<mat-icon
class="absolute m-3 text-white"
*ngIf="matOption.selected"
[svgIcon]="'heroicons_outline:check'"></mat-icon>
<span
class="flex w-10 h-10 m-1 rounded-full"
[ngClass]="color"></span>
</mat-option>
</div>
</mat-select>
</mat-form-field>
</div>
<!-- Actions -->
<div class="ml-auto mt-8 space-x-2">
<button
mat-button
*ngIf="calendar.id"
(click)="deleteCalendar(calendar)">
Delete
</button>
<button
mat-flat-button
*ngIf="calendar.id"
[color]="'primary'"
[disabled]="!calendar.title"
(click)="saveCalendar(calendar)">
Update
</button>
<button
mat-button
*ngIf="!calendar.id"
(click)="closeEditPanel()">
Cancel
</button>
<button
mat-flat-button
*ngIf="!calendar.id"
[color]="'primary'"
[disabled]="!calendar.title"
(click)="saveCalendar(calendar)">
Add
</button>
</div>
</div>
</ng-template>
</div>

View File

@@ -0,0 +1,217 @@
import { Component, EventEmitter, OnDestroy, OnInit, Output, TemplateRef, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { cloneDeep } from 'lodash-es';
import { Calendar } from 'app/modules/admin/apps/calendar/calendar.types';
import { CalendarService } from 'app/modules/admin/apps/calendar/calendar.service';
import { calendarColors } from 'app/modules/admin/apps/calendar/sidebar/calendar-colors';
@Component({
selector : 'calendar-sidebar',
templateUrl : './sidebar.component.html',
encapsulation: ViewEncapsulation.None
})
export class CalendarSidebarComponent implements OnInit, OnDestroy
{
@ViewChild('editPanel') private _editPanel: TemplateRef<any>;
@Output() readonly calendarUpdated: EventEmitter<any> = new EventEmitter<any>();
calendar: Calendar | null;
calendarColors: any = calendarColors;
calendars: Calendar[];
private _editPanelOverlayRef: OverlayRef;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _calendarService: CalendarService,
private _overlay: Overlay,
private _viewContainerRef: ViewContainerRef
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Get calendars
this._calendarService.calendars$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((calendars) => {
// Store the calendars
this.calendars = calendars;
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
// Dispose the overlay
if ( this._editPanelOverlayRef )
{
this._editPanelOverlayRef.dispose();
}
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Open edit panel
*/
openEditPanel(calendar: Calendar): void
{
// Set the calendar
this.calendar = cloneDeep(calendar);
// Create the overlay if it doesn't exist
if ( !this._editPanelOverlayRef )
{
this._createEditPanelOverlay();
}
// Attach the portal to the overlay
this._editPanelOverlayRef.attach(new TemplatePortal(this._editPanel, this._viewContainerRef));
}
/**
* Close the edit panel
*/
closeEditPanel(): void
{
// Detach the overlay from the portal
if ( this._editPanelOverlayRef )
{
this._editPanelOverlayRef.detach();
}
}
/**
* Toggle the calendar visibility
*
* @param calendar
*/
toggleCalendarVisibility(calendar: Calendar): void
{
// Toggle the visibility
calendar.visible = !calendar.visible;
// Update the calendar
this.saveCalendar(calendar);
}
/**
* Add calendar
*/
addCalendar(): void
{
// Create a new calendar with default values
const calendar = {
id : null,
title : '',
color : 'bg-blue-500',
visible: true
};
// Open the edit panel
this.openEditPanel(calendar);
}
/**
* Save the calendar
*
* @param calendar
*/
saveCalendar(calendar: Calendar): void
{
// If there is no id on the calendar...
if ( !calendar.id )
{
// Add calendar to the server
this._calendarService.addCalendar(calendar).subscribe(() => {
// Close the edit panel
this.closeEditPanel();
// Emit the calendarUpdated event
this.calendarUpdated.emit();
});
}
// Otherwise...
else
{
// Update the calendar on the server
this._calendarService.updateCalendar(calendar.id, calendar).subscribe(() => {
// Close the edit panel
this.closeEditPanel();
// Emit the calendarUpdated event
this.calendarUpdated.emit();
});
}
}
/**
* Delete the calendar
*
* @param calendar
*/
deleteCalendar(calendar: Calendar): void
{
// Delete the calendar on the server
this._calendarService.deleteCalendar(calendar.id).subscribe(() => {
// Close the edit panel
this.closeEditPanel();
// Emit the calendarUpdated event
this.calendarUpdated.emit();
});
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Create the edit panel overlay
* @private
*/
private _createEditPanelOverlay(): void
{
// Create the overlay
this._editPanelOverlayRef = this._overlay.create({
hasBackdrop : true,
scrollStrategy : this._overlay.scrollStrategies.reposition(),
positionStrategy: this._overlay.position()
.global()
.centerHorizontally()
.centerVertically()
});
// Detach the overlay from the portal on backdrop click
this._editPanelOverlayRef.backdropClick().subscribe(() => {
this.closeEditPanel();
this.calendar = null;
});
}
}

View File

@@ -0,0 +1,8 @@
<div class="absolute inset-0 flex flex-col min-w-0 overflow-hidden">
<!-- Main -->
<div class="flex flex-auto overflow-hidden">
<router-outlet></router-outlet>
</div>
</div>

View File

@@ -0,0 +1,17 @@
import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core';
@Component({
selector : 'chat',
templateUrl : './chat.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChatComponent
{
/**
* Constructor
*/
constructor()
{
}
}

View File

@@ -0,0 +1,44 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { FuseAutogrowModule } from '@fuse/directives/autogrow';
import { SharedModule } from 'app/shared/shared.module';
import { chatRoutes } from 'app/modules/admin/apps/chat/chat.routing';
import { ChatComponent } from 'app/modules/admin/apps/chat/chat.component';
import { ChatsComponent } from 'app/modules/admin/apps/chat/chats/chats.component';
import { ContactInfoComponent } from 'app/modules/admin/apps/chat/contact-info/contact-info.component';
import { ConversationComponent } from 'app/modules/admin/apps/chat/conversation/conversation.component';
import { NewChatComponent } from 'app/modules/admin/apps/chat/new-chat/new-chat.component';
import { ProfileComponent } from 'app/modules/admin/apps/chat/profile/profile.component';
@NgModule({
declarations: [
ChatComponent,
ChatsComponent,
ContactInfoComponent,
ConversationComponent,
NewChatComponent,
ProfileComponent
],
imports: [
RouterModule.forChild(chatRoutes),
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatMenuModule,
MatSidenavModule,
FuseAutogrowModule,
SharedModule,
]
})
export class ChatModule
{
}

View File

@@ -0,0 +1,147 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ChatService } from 'app/modules/admin/apps/chat/chat.service';
import { Chat, Contact, Profile } from 'app/modules/admin/apps/chat/chat.types';
@Injectable({
providedIn: 'root'
})
export class ChatChatsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _chatService: ChatService,
private _router: Router
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Chat[]> | any
{
return this._chatService.getChats();
}
}
@Injectable({
providedIn: 'root'
})
export class ChatChatResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _chatService: ChatService,
private _router: Router
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Chat>
{
return this._chatService.getChatById(route.paramMap.get('id'))
.pipe(
// Error here means the requested chat is not available
catchError((error) => {
// Log the error
console.error(error);
// Get the parent url
const parentUrl = state.url.split('/').slice(0, -1).join('/');
// Navigate to there
this._router.navigateByUrl(parentUrl);
// Throw an error
return throwError(error);
})
);
}
}
@Injectable({
providedIn: 'root'
})
export class ChatContactsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _chatService: ChatService,
private _router: Router
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Contact[]> | any
{
return this._chatService.getContacts();
}
}
@Injectable({
providedIn: 'root'
})
export class ChatProfileResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _chatService: ChatService,
private _router: Router
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Profile> | any
{
return this._chatService.getProfile();
}
}

View File

@@ -0,0 +1,37 @@
import { Route } from '@angular/router';
import { ChatChatResolver, ChatChatsResolver, ChatContactsResolver, ChatProfileResolver } from 'app/modules/admin/apps/chat/chat.resolvers';
import { ChatComponent } from 'app/modules/admin/apps/chat/chat.component';
import { ChatsComponent } from 'app/modules/admin/apps/chat/chats/chats.component';
import { ConversationComponent } from 'app/modules/admin/apps/chat/conversation/conversation.component';
export const chatRoutes: Route[] = [
{
path : '',
component: ChatComponent,
resolve : {
chats : ChatChatsResolver,
contacts: ChatContactsResolver,
profile : ChatProfileResolver
},
children : [
{
path : '',
component: ChatsComponent,
children : [
{
path : '',
component: ConversationComponent,
children : [
{
path : ':id',
resolve: {
conversation: ChatChatResolver
}
}
]
}
]
}
]
}
];

View File

@@ -0,0 +1,202 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { filter, map, switchMap, take, tap } from 'rxjs/operators';
import { Chat, Contact, Profile } from 'app/modules/admin/apps/chat/chat.types';
@Injectable({
providedIn: 'root'
})
export class ChatService
{
private _chat: BehaviorSubject<Chat> = new BehaviorSubject(null);
private _chats: BehaviorSubject<Chat[]> = new BehaviorSubject(null);
private _contact: BehaviorSubject<Contact> = new BehaviorSubject(null);
private _contacts: BehaviorSubject<Contact[]> = new BehaviorSubject(null);
private _profile: BehaviorSubject<Profile> = new BehaviorSubject(null);
/**
* Constructor
*/
constructor(private _httpClient: HttpClient)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Getter for chat
*/
get chat$(): Observable<Chat>
{
return this._chat.asObservable();
}
/**
* Getter for chats
*/
get chats$(): Observable<Chat[]>
{
return this._chats.asObservable();
}
/**
* Getter for contact
*/
get contact$(): Observable<Contact>
{
return this._contact.asObservable();
}
/**
* Getter for contacts
*/
get contacts$(): Observable<Contact[]>
{
return this._contacts.asObservable();
}
/**
* Getter for profile
*/
get profile$(): Observable<Profile>
{
return this._profile.asObservable();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Get chats
*/
getChats(): Observable<any>
{
return this._httpClient.get<Chat[]>('api/apps/chat/chats').pipe(
tap((response: Chat[]) => {
this._chats.next(response);
})
);
}
/**
* Get contact
*
* @param id
*/
getContact(id: string): Observable<any>
{
return this._httpClient.get<Contact>('api/apps/chat/contacts', {params: {id}}).pipe(
tap((response: Contact) => {
this._contact.next(response);
})
);
}
/**
* Get contacts
*/
getContacts(): Observable<any>
{
return this._httpClient.get<Contact[]>('api/apps/chat/contacts').pipe(
tap((response: Contact[]) => {
this._contacts.next(response);
})
);
}
/**
* Get profile
*/
getProfile(): Observable<any>
{
return this._httpClient.get<Profile>('api/apps/chat/profile').pipe(
tap((response: Profile) => {
this._profile.next(response);
})
);
}
/**
* Get chat
*
* @param id
*/
getChatById(id: string): Observable<any>
{
return this._httpClient.get<Chat>('api/apps/chat/chat', {params: {id}}).pipe(
map((chat) => {
// Update the chat
this._chat.next(chat);
// Return the chat
return chat;
}),
switchMap((chat) => {
if ( !chat )
{
return throwError('Could not found chat with id of ' + id + '!');
}
return of(chat);
})
);
}
/**
* Update chat
*
* @param id
* @param chat
*/
updateChat(id: string, chat: Chat): Observable<Chat>
{
return this.chats$.pipe(
take(1),
switchMap(chats => this._httpClient.patch<Chat>('api/apps/chat/chat', {
id,
chat
}).pipe(
map((updatedChat) => {
// Find the index of the updated chat
const index = chats.findIndex(item => item.id === id);
// Update the chat
chats[index] = updatedChat;
// Update the chats
this._chats.next(chats);
// Return the updated contact
return updatedChat;
}),
switchMap(updatedChat => this.chat$.pipe(
take(1),
filter(item => item && item.id === id),
tap(() => {
// Update the chat if it's selected
this._chat.next(updatedChat);
// Return the updated chat
return updatedChat;
})
))
))
);
}
/**
* Reset the selected chat
*/
resetChat(): void
{
this._chat.next(null);
}
}

View File

@@ -0,0 +1,55 @@
export interface Profile
{
id?: string;
name?: string;
email?: string;
avatar?: string;
about?: string;
}
export interface Contact
{
id?: string;
avatar?: string;
name?: string;
about?: string;
details?: {
emails?: {
email?: string;
label?: string;
}[];
phoneNumbers?: {
country?: string;
number?: string;
label?: string;
}[];
title?: string;
company?: string;
birthday?: string;
address?: string;
};
attachments?: {
media?: any[]
docs?: any[]
links?: any[]
};
}
export interface Chat
{
id?: string;
contactId?: string;
contact?: Contact;
unreadCount?: number;
muted?: boolean;
lastMessage?: string;
lastMessageAt?: string;
messages?: {
id?: string;
chatId?: string;
contactId?: string;
isMine?: boolean;
value?: string;
createdAt?: string;
}[];
}

View File

@@ -0,0 +1,190 @@
<div class="relative flex flex-auto w-full bg-card dark:bg-transparent">
<mat-drawer-container
class="flex-auto h-full"
[hasBackdrop]="false">
<!-- Drawer -->
<mat-drawer
class="w-full sm:w-100 lg:border-r lg:shadow-none dark:bg-gray-900"
[autoFocus]="false"
[(opened)]="drawerOpened"
#drawer>
<!-- New chat -->
<ng-container *ngIf="drawerComponent === 'new-chat'">
<chat-new-chat [drawer]="drawer"></chat-new-chat>
</ng-container>
<!-- Profile -->
<ng-container *ngIf="drawerComponent === 'profile'">
<chat-profile [drawer]="drawer"></chat-profile>
</ng-container>
</mat-drawer>
<!-- Drawer content -->
<mat-drawer-content class="flex overflow-hidden">
<!-- Chats list -->
<ng-container *ngIf="chats && chats.length > 0; else noChats">
<div class="relative flex flex-auto flex-col w-full min-w-0 lg:min-w-100 lg:max-w-100 bg-card dark:bg-transparent">
<!-- Header -->
<div class="flex flex-col flex-0 py-4 px-8 border-b bg-gray-50 dark:bg-transparent">
<div class="flex items-center">
<div
class="flex items-center mr-1 cursor-pointer"
(click)="openProfile()">
<div class="w-10 h-10">
<ng-container *ngIf="profile.avatar">
<img
class="object-cover w-full h-full rounded-full object-cover"
[src]="profile.avatar"
alt="Profile avatar"/>
</ng-container>
<ng-container *ngIf="!profile.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-lg uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{profile.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="ml-4 font-medium truncate">{{profile.name}}</div>
</div>
<button
class="ml-auto"
mat-icon-button
(click)="openNewChat()">
<mat-icon [svgIcon]="'heroicons_outline:plus-circle'"></mat-icon>
</button>
<button
class="ml-1 -mr-4"
mat-icon-button
[matMenuTriggerFor]="chatsHeaderMenu">
<mat-icon [svgIcon]="'heroicons_outline:dots-vertical'"></mat-icon>
<mat-menu #chatsHeaderMenu>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:user-group'"></mat-icon>
New group
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:chat-alt-2'"></mat-icon>
Create a room
</button>
<button
mat-menu-item
(click)="openProfile()">
<mat-icon [svgIcon]="'heroicons_outline:user-circle'"></mat-icon>
Profile
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:archive'"></mat-icon>
Archived
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:star'"></mat-icon>
Starred
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:cog'"></mat-icon>
Settings
</button>
</mat-menu>
</button>
</div>
<!-- Search -->
<div class="mt-4">
<mat-form-field
class="fuse-mat-no-subscript fuse-mat-rounded fuse-mat-dense w-full"
[floatLabel]="'always'">
<mat-icon
matPrefix
class="icon-size-5"
[svgIcon]="'heroicons_solid:search'"></mat-icon>
<input
matInput
[autocomplete]="'off'"
[placeholder]="'Search or start new chat'"
(input)="filterChats(searchField.value)"
#searchField>
</mat-form-field>
</div>
</div>
<!-- Chats -->
<div class="flex-auto overflow-y-auto">
<ng-container *ngIf="filteredChats.length > 0; else noChats">
<ng-container *ngFor="let chat of filteredChats; trackBy: trackByFn">
<div
class="z-20 flex items-center py-5 px-8 cursor-pointer border-b hover:bg-hover"
[ngClass]="{'bg-primary-50 dark:bg-hover': selectedChat && selectedChat.id === chat.id}"
[routerLink]="[chat.id]">
<div class="relative flex flex-0 items-center justify-center w-10 h-10">
<ng-container *ngIf="chat.unreadCount > 0">
<div
class="absolute bottom-0 right-0 flex-0 w-2 h-2 -ml-0.5 rounded-full ring-2 ring-bg-card dark:ring-gray-900 bg-primary dark:bg-primary-500 text-on-primary"
[class.ring-primary-50]="selectedChat && selectedChat.id === chat.id"></div>
</ng-container>
<ng-container *ngIf="chat.contact.avatar">
<img
class="w-full h-full rounded-full object-cover"
[src]="chat.contact.avatar"
alt="Contact avatar"/>
</ng-container>
<ng-container *ngIf="!chat.contact.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-lg uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{chat.contact.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="min-w-0 ml-4">
<div class="font-medium leading-5 truncate">{{chat.contact.name}}</div>
<div
class="leading-5 truncate text-secondary"
[class.text-primary]="chat.unreadCount > 0"
[class.dark:text-primary-500]="chat.unreadCount > 0">
{{chat.lastMessage}}
</div>
</div>
<div class="flex flex-col items-end self-start ml-auto pl-2">
<div class="text-sm leading-5 text-secondary">{{chat.lastMessageAt}}</div>
<ng-container *ngIf="chat.muted">
<mat-icon
class="icon-size-5 text-hint"
[svgIcon]="'heroicons_solid:volume-off'"></mat-icon>
</ng-container>
</div>
</div>
</ng-container>
</ng-container>
</div>
</div>
</ng-container>
<!-- No chats template -->
<ng-template #noChats>
<div class="flex flex-auto flex-col items-center justify-center h-full">
<mat-icon
class="icon-size-24"
[svgIcon]="'iconsmind:speach_bubble'"></mat-icon>
<div class="mt-4 text-2xl font-semibold tracking-tight text-secondary">No chats</div>
</div>
</ng-template>
<!-- Conversation -->
<ng-container *ngIf="chats && chats.length > 0">
<div
class="flex-auto border-l"
[ngClass]="{'z-20 absolute inset-0 lg:static lg:inset-auto flex': selectedChat && selectedChat.id,
'hidden lg:flex': !selectedChat || !selectedChat.id}">
<router-outlet></router-outlet>
</div>
</ng-container>
</mat-drawer-content>
</mat-drawer-container>
</div>

View File

@@ -0,0 +1,138 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Chat, Profile } from 'app/modules/admin/apps/chat/chat.types';
import { ChatService } from 'app/modules/admin/apps/chat/chat.service';
@Component({
selector : 'chat-chats',
templateUrl : './chats.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChatsComponent implements OnInit, OnDestroy
{
chats: Chat[];
drawerComponent: 'profile' | 'new-chat';
drawerOpened: boolean = false;
filteredChats: Chat[];
profile: Profile;
selectedChat: Chat;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _chatService: ChatService,
private _changeDetectorRef: ChangeDetectorRef
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Chats
this._chatService.chats$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((chats: Chat[]) => {
this.chats = this.filteredChats = chats;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Profile
this._chatService.profile$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((profile: Profile) => {
this.profile = profile;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Selected chat
this._chatService.chat$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((chat: Chat) => {
this.selectedChat = chat;
// Mark for check
this._changeDetectorRef.markForCheck();
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Filter the chats
*
* @param query
*/
filterChats(query: string): void
{
// Reset the filter
if ( !query )
{
this.filteredChats = this.chats;
return;
}
this.filteredChats = this.chats.filter((chat) => chat.contact.name.toLowerCase().includes(query.toLowerCase()));
}
/**
* Open the new chat sidebar
*/
openNewChat(): void
{
this.drawerComponent = 'new-chat';
this.drawerOpened = true;
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Open the profile sidebar
*/
openProfile(): void
{
this.drawerComponent = 'profile';
this.drawerOpened = true;
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
}

View File

@@ -0,0 +1,86 @@
<div class="flex flex-col flex-auto h-full bg-card dark:bg-default">
<!-- Header -->
<div class="flex flex-0 items-center h-18 px-4 border-b bg-gray-50 dark:bg-transparent">
<button
mat-icon-button
(click)="drawer.close()">
<mat-icon [svgIcon]="'heroicons_outline:x'"></mat-icon>
</button>
<div class="ml-2 text-lg font-medium">Contact info</div>
</div>
<div class="overflow-y-auto">
<!-- Contact avatar & info -->
<div class="flex flex-col items-center mt-8">
<div class="w-40 h-40 rounded-full">
<ng-container *ngIf="chat.contact.avatar">
<img
class="w-full h-full rounded-full object-cover"
[src]="chat.contact.avatar"
[alt]="'Contact avatar'">
</ng-container>
<ng-container *ngIf="!chat.contact.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-8xl font-semibold uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{chat.contact.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="mt-4 text-lg font-medium">{{chat.contact.name}}</div>
<div class="mt-0.5 text-md text-secondary">{{chat.contact.about}}</div>
</div>
<div class="py-10 px-7">
<!-- Media -->
<div class="text-lg font-medium">Media</div>
<div class="grid grid-cols-4 gap-1 mt-4">
<ng-container *ngFor="let media of chat.contact.attachments.media">
<img
class="h-20 rounded object-cover"
[src]="media"/>
</ng-container>
</div>
<!-- Details -->
<div class="mt-10 space-y-4">
<div class="text-lg font-medium mb-3">Details</div>
<ng-container *ngIf="chat.contact.details.emails.length">
<div>
<div class="font-medium text-secondary">Email</div>
<div class="">{{chat.contact.details.emails[0].email}}</div>
</div>
</ng-container>
<ng-container *ngIf="chat.contact.details.phoneNumbers.length">
<div>
<div class="font-medium text-secondary">Phone number</div>
<div class="">{{chat.contact.details.phoneNumbers[0].number}}</div>
</div>
</ng-container>
<ng-container *ngIf="chat.contact.details.title">
<div>
<div class="font-medium text-secondary">Title</div>
<div class="">{{chat.contact.details.title}}</div>
</div>
</ng-container>
<ng-container *ngIf="chat.contact.details.company">
<div>
<div class="font-medium text-secondary">Company</div>
<div class="">{{chat.contact.details.company}}</div>
</div>
</ng-container>
<ng-container *ngIf="chat.contact.details.birthday">
<div>
<div class="font-medium text-secondary">Birthday</div>
<div class="">{{chat.contact.details.birthday}}</div>
</div>
</ng-container>
<ng-container *ngIf="chat.contact.details.address">
<div>
<div class="font-medium text-secondary">Address</div>
<div class="">{{chat.contact.details.address}}</div>
</div>
</ng-container>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,22 @@
import { ChangeDetectionStrategy, Component, Input, ViewEncapsulation } from '@angular/core';
import { MatDrawer } from '@angular/material/sidenav';
import { Chat, Contact } from 'app/modules/admin/apps/chat/chat.types';
@Component({
selector : 'chat-contact-info',
templateUrl : './contact-info.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContactInfoComponent
{
@Input() chat: Chat;
@Input() drawer: MatDrawer;
/**
* Constructor
*/
constructor()
{
}
}

View File

@@ -0,0 +1,215 @@
<div class="flex flex-col flex-auto overflow-y-auto lg:overflow-hidden bg-card dark:bg-default">
<ng-container *ngIf="chat; else selectChatOrStartNew">
<mat-drawer-container
class="flex-auto h-full"
[hasBackdrop]="false">
<!-- Drawer -->
<mat-drawer
class="w-full sm:w-100 lg:border-l lg:shadow-none dark:bg-gray-900"
[autoFocus]="false"
[mode]="drawerMode"
[position]="'end'"
[(opened)]="drawerOpened"
#drawer>
<!-- Contact info -->
<chat-contact-info
[drawer]="drawer"
[chat]="chat"></chat-contact-info>
</mat-drawer>
<!-- Drawer content -->
<mat-drawer-content class="flex flex-col overflow-hidden">
<!-- Header -->
<div class="flex flex-0 items-center h-18 px-4 md:px-6 border-b bg-gray-50 dark:bg-transparent">
<!-- Back button -->
<a
class="lg:hidden md:-ml-2"
mat-icon-button
[routerLink]="['./']"
(click)="resetChat()">
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
</a>
<!-- Contact info -->
<div
class="flex items-center ml-2 lg:ml-0 mr-2 cursor-pointer"
(click)="openContactInfo()">
<div class="relative flex flex-0 items-center justify-center w-10 h-10">
<ng-container *ngIf="chat.contact.avatar">
<img
class="w-full h-full rounded-full object-cover"
[src]="chat.contact.avatar"
alt="Contact avatar"/>
</ng-container>
<ng-container *ngIf="!chat.contact.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-lg uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{chat.contact.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="ml-4 text-lg font-medium leading-5 truncate">{{chat.contact.name}}</div>
</div>
<button
class="ml-auto"
mat-icon-button
[matMenuTriggerFor]="conversationHeaderMenu">
<mat-icon [svgIcon]="'heroicons_outline:dots-vertical'"></mat-icon>
<mat-menu #conversationHeaderMenu>
<button
mat-menu-item
(click)="openContactInfo()">
<mat-icon [svgIcon]="'heroicons_outline:user-circle'"></mat-icon>
Contact info
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:check-circle'"></mat-icon>
Select messages
</button>
<button
mat-menu-item
(click)="toggleMuteNotifications()">
<ng-container *ngIf="!chat.muted">
<mat-icon [svgIcon]="'heroicons_outline:volume-off'"></mat-icon>
Mute notifications
</ng-container>
<ng-container *ngIf="chat.muted">
<mat-icon [svgIcon]="'heroicons_outline:volume-up'"></mat-icon>
Unmute notifications
</ng-container>
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:backspace'"></mat-icon>
Clear messages
</button>
<button mat-menu-item>
<mat-icon [svgIcon]="'heroicons_outline:trash'"></mat-icon>
Delete chat
</button>
</mat-menu>
</button>
</div>
<!-- Conversation -->
<div class="flex overflow-y-auto flex-col-reverse">
<div class="flex flex-col flex-auto flex-shrink p-6 bg-card dark:bg-transparent">
<ng-container *ngFor="let message of chat.messages; let i = index; let first = first; let last = last; trackBy: trackByFn">
<!-- Start of the day -->
<ng-container *ngIf="first || (chat.messages[i - 1].createdAt | date:'d') !== (message.createdAt | date:'d')">
<div class="flex items-center justify-center my-3 -mx-6">
<div class="flex-auto border-b"></div>
<div class="flex-0 mx-4 text-sm font-medium leading-5 text-secondary">
{{message.createdAt | date: 'longDate'}}
</div>
<div class="flex-auto border-b"></div>
</div>
</ng-container>
<div
class="flex flex-col"
[ngClass]="{'items-end': message.isMine,
'items-start': !message.isMine,
'mt-0.5': i > 0 && chat.messages[i - 1].isMine === message.isMine,
'mt-3': i > 0 && chat.messages[i - 1].isMine !== message.isMine}">
<!-- Bubble -->
<div
class="relative max-w-3/4 px-3 py-2 rounded-lg"
[ngClass]="{'bg-blue-500 text-blue-50': message.isMine,
'bg-gray-500 text-gray-50': !message.isMine}">
<!-- Speech bubble tail -->
<ng-container *ngIf="last || chat.messages[i + 1].isMine !== message.isMine">
<div
class="absolute bottom-0 w-3 transform"
[ngClass]="{'text-blue-500 -right-1 -mr-px mb-px': message.isMine,
'text-gray-500 -left-1 -ml-px mb-px -scale-x-1': !message.isMine}">
<ng-container *ngTemplateOutlet="speechBubbleExtension"></ng-container>
</div>
</ng-container>
<!-- Message -->
<div
class="min-w-4 leading-5"
[innerHTML]="message.value">
</div>
</div>
<!-- Time -->
<ng-container
*ngIf="first
|| last
|| chat.messages[i + 1].isMine !== message.isMine
|| chat.messages[i + 1].createdAt !== message.createdAt">
<div
class="my-0.5 text-sm font-medium text-secondary"
[ngClass]="{'mr-3': message.isMine,
'ml-3': !message.isMine}">
{{message.createdAt | date:'HH:mm'}}
</div>
</ng-container>
</div>
</ng-container>
</div>
</div>
<!-- Message field -->
<div class="flex items-end p-4 border-t bg-gray-50 dark:bg-transparent">
<div class="flex items-center h-11 my-px">
<button mat-icon-button>
<mat-icon [svgIcon]="'heroicons_outline:emoji-happy'"></mat-icon>
</button>
<button
class="ml-0.5"
mat-icon-button>
<mat-icon [svgIcon]="'heroicons_outline:paper-clip'"></mat-icon>
</button>
</div>
<mat-form-field class="fuse-mat-dense fuse-mat-no-subscript fuse-mat-rounded fuse-mat-bold w-full ml-4">
<textarea
class="min-h-5 my-0 resize-none"
style="margin: 11px 0 !important; padding: 0 !important;"
[rows]="1"
matInput
#messageInput></textarea>
</mat-form-field>
<div class="flex items-center h-11 my-px ml-4">
<button
mat-icon-button>
<mat-icon
class="transform rotate-90"
[svgIcon]="'heroicons_outline:paper-airplane'"></mat-icon>
</button>
</div>
</div>
</mat-drawer-content>
</mat-drawer-container>
</ng-container>
<!-- Select chat or start new template -->
<ng-template #selectChatOrStartNew>
<div class="flex flex-col flex-auto items-center justify-center bg-gray-100 dark:bg-transparent">
<mat-icon
class="icon-size-24"
[svgIcon]="'iconsmind:speach_bubble'"></mat-icon>
<div class="mt-4 text-2xl font-semibold tracking-tight text-secondary">Select a conversation or start a new chat</div>
</div>
</ng-template>
<!-- Speech bubble tail SVG -->
<!-- @formatter:off -->
<ng-template #speechBubbleExtension>
<svg width="100%" height="100%" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg">
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<path d="M1.01522827,0.516204834 C-8.83532715,54.3062744 61.7609863,70.5215302 64.8009949,64.3061218 C68.8074951,54.8859711 30.1663208,52.9997559 37.5036011,0.516204834 L1.01522827,0.516204834 Z" fill="currentColor" fill-rule="nonzero"></path>
</g>
</svg>
</ng-template>
<!-- @formatter:on -->
</div>

View File

@@ -0,0 +1,168 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostListener, NgZone, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { FuseMediaWatcherService } from '@fuse/services/media-watcher';
import { Chat } from 'app/modules/admin/apps/chat/chat.types';
import { ChatService } from 'app/modules/admin/apps/chat/chat.service';
@Component({
selector : 'chat-conversation',
templateUrl : './conversation.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConversationComponent implements OnInit, OnDestroy
{
@ViewChild('messageInput') messageInput: ElementRef;
chat: Chat;
drawerMode: 'over' | 'side' = 'side';
drawerOpened: boolean = false;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _changeDetectorRef: ChangeDetectorRef,
private _chatService: ChatService,
private _fuseMediaWatcherService: FuseMediaWatcherService,
private _ngZone: NgZone
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Chat
this._chatService.chat$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((chat: Chat) => {
this.chat = chat;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Subscribe to media changes
this._fuseMediaWatcherService.onMediaChange$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe(({matchingAliases}) => {
// Set the drawerMode if the given breakpoint is active
if ( matchingAliases.includes('lg') )
{
this.drawerMode = 'side';
}
else
{
this.drawerMode = 'over';
}
// Mark for check
this._changeDetectorRef.markForCheck();
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Open the contact info
*/
openContactInfo(): void
{
// Open the drawer
this.drawerOpened = true;
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Reset the chat
*/
resetChat(): void
{
this._chatService.resetChat();
// Close the contact info in case it's opened
this.drawerOpened = false;
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Toggle mute notifications
*/
toggleMuteNotifications(): void
{
// Toggle the muted
this.chat.muted = !this.chat.muted;
// Update the chat on the server
this._chatService.updateChat(this.chat.id, this.chat).subscribe();
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Resize on 'input' and 'ngModelChange' events
*
* @private
*/
@HostListener('input')
@HostListener('ngModelChange')
private _resizeMessageInput(): void
{
// This doesn't need to trigger Angular's change detection by itself
this._ngZone.runOutsideAngular(() => {
setTimeout(() => {
// Set the height to 'auto' so we can correctly read the scrollHeight
this.messageInput.nativeElement.style.height = 'auto';
// Detect the changes so the height is applied
this._changeDetectorRef.detectChanges();
// Get the scrollHeight and subtract the vertical padding
this.messageInput.nativeElement.style.height = `${this.messageInput.nativeElement.scrollHeight}px`;
// Detect the changes one more time to apply the final height
this._changeDetectorRef.detectChanges();
});
});
}
}

View File

@@ -0,0 +1,51 @@
<div class="flex flex-col flex-auto h-full overflow-hidden bg-card dark:bg-default">
<!-- Header -->
<div class="flex flex-0 items-center h-18 -mb-px px-6 bg-gray-50 dark:bg-transparent">
<button
mat-icon-button
(click)="drawer.close()">
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
</button>
<div class="ml-2 text-2xl font-semibold">New chat</div>
</div>
<div class="relative overflow-y-auto">
<ng-container *ngIf="contacts.length; else noContacts">
<ng-container *ngFor="let contact of contacts; let i = index; trackBy: trackByFn">
<!-- Group -->
<ng-container *ngIf="i === 0 || contact.name.charAt(0) !== contacts[i - 1].name.charAt(0)">
<div class="z-10 sticky top-0 -mt-px px-6 py-1 md:px-8 border-t border-b font-medium uppercase text-secondary bg-gray-100 dark:bg-gray-900">
{{contact.name.charAt(0)}}
</div>
</ng-container>
<!-- Contact -->
<div class="z-20 flex items-center px-6 py-4 md:px-8 cursor-pointer hover:bg-hover border-b">
<div class="flex flex-0 items-center justify-center w-10 h-10 rounded-full overflow-hidden">
<ng-container *ngIf="contact.avatar">
<img
class="object-cover w-full h-full"
[src]="contact.avatar"
alt="Contact avatar"/>
</ng-container>
<ng-container *ngIf="!contact.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-lg uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{contact.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="min-w-0 ml-4">
<div class="font-medium leading-5 truncate">{{contact.name}}</div>
<div class="leading-5 truncate text-secondary">{{contact.about}}</div>
</div>
</div>
</ng-container>
</ng-container>
</div>
<!-- No contacts -->
<ng-template #noContacts>
<div class="p-8 sm:p-16 border-t text-4xl font-semibold tracking-tight text-center">There are no contacts!</div>
</ng-template>
</div>

View File

@@ -0,0 +1,68 @@
import { ChangeDetectionStrategy, Component, Input, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { MatDrawer } from '@angular/material/sidenav';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Contact } from 'app/modules/admin/apps/chat/chat.types';
import { ChatService } from 'app/modules/admin/apps/chat/chat.service';
@Component({
selector : 'chat-new-chat',
templateUrl : './new-chat.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NewChatComponent implements OnInit, OnDestroy
{
@Input() drawer: MatDrawer;
contacts: Contact[] = [];
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(private _chatService: ChatService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Contacts
this._chatService.contacts$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((contacts: Contact[]) => {
this.contacts = contacts;
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
}

View File

@@ -0,0 +1,80 @@
<div class="flex flex-col flex-auto overflow-y-auto bg-card dark:bg-default">
<!-- Header -->
<div class="flex flex-0 items-center h-18 px-6 border-b bg-gray-50 dark:bg-transparent">
<button
mat-icon-button
(click)="drawer.close()">
<mat-icon [svgIcon]="'heroicons_outline:arrow-narrow-left'"></mat-icon>
</button>
<div class="ml-2 text-2xl font-semibold">Profile</div>
</div>
<div class="px-6">
<!-- Profile photo -->
<div class="group relative flex flex-0 mt-8 mx-auto w-40 h-40 rounded-full">
<div class="hidden group-hover:flex absolute inset-0 flex-col items-center justify-center backdrop-filter backdrop-blur bg-opacity-80 rounded-full cursor-pointer bg-gray-800">
<mat-icon
class="text-white"
[svgIcon]="'heroicons_outline:camera'"></mat-icon>
<div class="mt-2 mx-6 font-medium text-center text-white">Change Profile Photo</div>
</div>
<ng-container *ngIf="profile.avatar">
<img
class="w-full h-full rounded-full object-cover"
[src]="profile.avatar"
[alt]="'Profile avatar'">
</ng-container>
<ng-container *ngIf="!profile.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-8xl font-semibold uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{profile.name.charAt(0)}}
</div>
</ng-container>
</div>
<!-- Profile info -->
<div class="flex flex-col mt-8 mx-2">
<mat-form-field>
<mat-label>Name</mat-label>
<mat-icon
class="icon-size-5"
matPrefix
[svgIcon]="'heroicons_solid:user-circle'"></mat-icon>
<input
matInput
[ngModel]="profile.name">
</mat-form-field>
<mat-form-field>
<mat-label>Email</mat-label>
<mat-icon
class="icon-size-5"
matPrefix
[svgIcon]="'heroicons_solid:mail'"></mat-icon>
<input
matInput
[ngModel]="profile.email">
</mat-form-field>
<mat-form-field>
<mat-label>About</mat-label>
<mat-icon
class="icon-size-5"
matPrefix
[svgIcon]="'heroicons_solid:identification'"></mat-icon>
<input
matInput
[ngModel]="profile.about">
</mat-form-field>
<div class="flex items-center justify-end mt-4">
<button
(click)="drawer.close()"
mat-button>Cancel
</button>
<button
class="ml-2"
mat-flat-button
[color]="'primary'">Save
</button>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,53 @@
import { ChangeDetectionStrategy, Component, Input, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { MatDrawer } from '@angular/material/sidenav';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Profile } from 'app/modules/admin/apps/chat/chat.types';
import { ChatService } from 'app/modules/admin/apps/chat/chat.service';
@Component({
selector : 'chat-profile',
templateUrl : './profile.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileComponent implements OnInit, OnDestroy
{
@Input() drawer: MatDrawer;
profile: Profile;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(private _chatService: ChatService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Profile
this._chatService.profile$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((profile: Profile) => {
this.profile = profile;
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
}

View File

@@ -0,0 +1 @@
<router-outlet></router-outlet>

View File

@@ -0,0 +1,17 @@
import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/core';
@Component({
selector : 'contacts',
templateUrl : './contacts.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContactsComponent
{
/**
* Constructor
*/
constructor()
{
}
}

View File

@@ -0,0 +1,49 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { ContactsDetailsComponent } from 'app/modules/admin/apps/contacts/details/details.component';
@Injectable({
providedIn: 'root'
})
export class CanDeactivateContactsDetails implements CanDeactivate<ContactsDetailsComponent>
{
canDeactivate(
component: ContactsDetailsComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
{
// Get the next route
let nextRoute: ActivatedRouteSnapshot = nextState.root;
while ( nextRoute.firstChild )
{
nextRoute = nextRoute.firstChild;
}
// If the next state doesn't contain '/contacts'
// it means we are navigating away from the
// contacts app
if ( !nextState.url.includes('/contacts') )
{
// Let it navigate
return true;
}
// If we are navigating to another contact...
if ( nextRoute.paramMap.get('id') )
{
// Just navigate
return true;
}
// Otherwise...
else
{
// Close the drawer first, and then navigate
return component.closeDrawer().then(() => {
return true;
});
}
}
}

View File

@@ -0,0 +1,75 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MAT_DATE_FORMATS, MatRippleModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import * as moment from 'moment';
import { FuseAutogrowModule } from '@fuse/directives/autogrow';
import { FuseFindByKeyPipeModule } from '@fuse/pipes/find-by-key';
import { SharedModule } from 'app/shared/shared.module';
import { contactsRoutes } from 'app/modules/admin/apps/contacts/contacts.routing';
import { ContactsComponent } from 'app/modules/admin/apps/contacts/contacts.component';
import { ContactsDetailsComponent } from 'app/modules/admin/apps/contacts/details/details.component';
import { ContactsListComponent } from 'app/modules/admin/apps/contacts/list/list.component';
@NgModule({
declarations: [
ContactsComponent,
ContactsListComponent,
ContactsDetailsComponent
],
imports : [
RouterModule.forChild(contactsRoutes),
MatButtonModule,
MatCheckboxModule,
MatDatepickerModule,
MatDividerModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatMenuModule,
MatMomentDateModule,
MatProgressBarModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatTableModule,
MatTooltipModule,
FuseAutogrowModule,
FuseFindByKeyPipeModule,
SharedModule
],
providers : [
{
provide : MAT_DATE_FORMATS,
useValue: {
parse : {
dateInput: moment.ISO_8601
},
display: {
dateInput : 'LL',
monthYearLabel : 'MMM YYYY',
dateA11yLabel : 'LL',
monthYearA11yLabel: 'MMMM YYYY'
}
}
}
]
})
export class ContactsModule
{
}

View File

@@ -0,0 +1,138 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ContactsService } from 'app/modules/admin/apps/contacts/contacts.service';
import { Contact, Country, Tag } from 'app/modules/admin/apps/contacts/contacts.types';
@Injectable({
providedIn: 'root'
})
export class ContactsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _contactsService: ContactsService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Contact[]>
{
return this._contactsService.getContacts();
}
}
@Injectable({
providedIn: 'root'
})
export class ContactsContactResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(
private _contactsService: ContactsService,
private _router: Router
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Contact>
{
return this._contactsService.getContactById(route.paramMap.get('id'))
.pipe(
// Error here means the requested contact is not available
catchError((error) => {
// Log the error
console.error(error);
// Get the parent url
const parentUrl = state.url.split('/').slice(0, -1).join('/');
// Navigate to there
this._router.navigateByUrl(parentUrl);
// Throw an error
return throwError(error);
})
);
}
}
@Injectable({
providedIn: 'root'
})
export class ContactsCountriesResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _contactsService: ContactsService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Country[]>
{
return this._contactsService.getCountries();
}
}
@Injectable({
providedIn: 'root'
})
export class ContactsTagsResolver implements Resolve<any>
{
/**
* Constructor
*/
constructor(private _contactsService: ContactsService)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Tag[]>
{
return this._contactsService.getTags();
}
}

View File

@@ -0,0 +1,37 @@
import { Route } from '@angular/router';
import { CanDeactivateContactsDetails } from 'app/modules/admin/apps/contacts/contacts.guards';
import { ContactsContactResolver, ContactsCountriesResolver, ContactsResolver, ContactsTagsResolver } from 'app/modules/admin/apps/contacts/contacts.resolvers';
import { ContactsComponent } from 'app/modules/admin/apps/contacts/contacts.component';
import { ContactsListComponent } from 'app/modules/admin/apps/contacts/list/list.component';
import { ContactsDetailsComponent } from 'app/modules/admin/apps/contacts/details/details.component';
export const contactsRoutes: Route[] = [
{
path : '',
component: ContactsComponent,
resolve : {
tags: ContactsTagsResolver
},
children : [
{
path : '',
component: ContactsListComponent,
resolve : {
tasks : ContactsResolver,
countries: ContactsCountriesResolver
},
children : [
{
path : ':id',
component : ContactsDetailsComponent,
resolve : {
task : ContactsContactResolver,
countries: ContactsCountriesResolver
},
canDeactivate: [CanDeactivateContactsDetails]
}
]
}
]
}
];

View File

@@ -0,0 +1,389 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of, throwError } from 'rxjs';
import { filter, map, switchMap, take, tap } from 'rxjs/operators';
import { Contact, Country, Tag } from 'app/modules/admin/apps/contacts/contacts.types';
@Injectable({
providedIn: 'root'
})
export class ContactsService
{
// Private
private _contact: BehaviorSubject<Contact | null> = new BehaviorSubject(null);
private _contacts: BehaviorSubject<Contact[] | null> = new BehaviorSubject(null);
private _countries: BehaviorSubject<Country[] | null> = new BehaviorSubject(null);
private _tags: BehaviorSubject<Tag[] | null> = new BehaviorSubject(null);
/**
* Constructor
*/
constructor(private _httpClient: HttpClient)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Getter for contact
*/
get contact$(): Observable<Contact>
{
return this._contact.asObservable();
}
/**
* Getter for contacts
*/
get contacts$(): Observable<Contact[]>
{
return this._contacts.asObservable();
}
/**
* Getter for countries
*/
get countries$(): Observable<Country[]>
{
return this._countries.asObservable();
}
/**
* Getter for tags
*/
get tags$(): Observable<Tag[]>
{
return this._tags.asObservable();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Get contacts
*/
getContacts(): Observable<Contact[]>
{
return this._httpClient.get<Contact[]>('api/apps/contacts/all').pipe(
tap((contacts) => {
this._contacts.next(contacts);
})
);
}
/**
* Search contacts with given query
*
* @param query
*/
searchContacts(query: string): Observable<Contact[]>
{
return this._httpClient.get<Contact[]>('api/apps/contacts/search', {
params: {query}
}).pipe(
tap((contacts) => {
this._contacts.next(contacts);
})
);
}
/**
* Get contact by id
*/
getContactById(id: string): Observable<Contact>
{
return this._contacts.pipe(
take(1),
map((contacts) => {
// Find the contact
const contact = contacts.find(item => item.id === id) || null;
// Update the contact
this._contact.next(contact);
// Return the contact
return contact;
}),
switchMap((contact) => {
if ( !contact )
{
return throwError('Could not found contact with id of ' + id + '!');
}
return of(contact);
})
);
}
/**
* Create contact
*/
createContact(): Observable<Contact>
{
return this.contacts$.pipe(
take(1),
switchMap((contacts) => this._httpClient.post<Contact>('api/apps/contacts/contact', {}).pipe(
map((newContact) => {
// Update the contacts with the new contact
this._contacts.next([newContact, ...contacts]);
// Return the new contact
return newContact;
})
))
);
}
/**
* Update contact
*
* @param id
* @param contact
*/
updateContact(id: string, contact: Contact): Observable<Contact>
{
return this.contacts$.pipe(
take(1),
switchMap(contacts => this._httpClient.patch<Contact>('api/apps/contacts/contact', {
id,
contact
}).pipe(
map((updatedContact) => {
// Find the index of the updated contact
const index = contacts.findIndex(item => item.id === id);
// Update the contact
contacts[index] = updatedContact;
// Update the contacts
this._contacts.next(contacts);
// Return the updated contact
return updatedContact;
}),
switchMap(updatedContact => this.contact$.pipe(
take(1),
filter(item => item && item.id === id),
tap(() => {
// Update the contact if it's selected
this._contact.next(updatedContact);
// Return the updated contact
return updatedContact;
})
))
))
);
}
/**
* Delete the contact
*
* @param id
*/
deleteContact(id: string): Observable<boolean>
{
return this.contacts$.pipe(
take(1),
switchMap(contacts => this._httpClient.delete('api/apps/contacts/contact', {params: {id}}).pipe(
map((isDeleted: boolean) => {
// Find the index of the deleted contact
const index = contacts.findIndex(item => item.id === id);
// Delete the contact
contacts.splice(index, 1);
// Update the contacts
this._contacts.next(contacts);
// Return the deleted status
return isDeleted;
})
))
);
}
/**
* Get countries
*/
getCountries(): Observable<Country[]>
{
return this._httpClient.get<Country[]>('api/apps/contacts/countries').pipe(
tap((countries) => {
this._countries.next(countries);
})
);
}
/**
* Get tags
*/
getTags(): Observable<Tag[]>
{
return this._httpClient.get<Tag[]>('api/apps/contacts/tags').pipe(
tap((tags) => {
this._tags.next(tags);
})
);
}
/**
* Create tag
*
* @param tag
*/
createTag(tag: Tag): Observable<Tag>
{
return this.tags$.pipe(
take(1),
switchMap(tags => this._httpClient.post<Tag>('api/apps/contacts/tag', {tag}).pipe(
map((newTag) => {
// Update the tags with the new tag
this._tags.next([...tags, newTag]);
// Return new tag from observable
return newTag;
})
))
);
}
/**
* Update the tag
*
* @param id
* @param tag
*/
updateTag(id: string, tag: Tag): Observable<Tag>
{
return this.tags$.pipe(
take(1),
switchMap(tags => this._httpClient.patch<Tag>('api/apps/contacts/tag', {
id,
tag
}).pipe(
map((updatedTag) => {
// Find the index of the updated tag
const index = tags.findIndex(item => item.id === id);
// Update the tag
tags[index] = updatedTag;
// Update the tags
this._tags.next(tags);
// Return the updated tag
return updatedTag;
})
))
);
}
/**
* Delete the tag
*
* @param id
*/
deleteTag(id: string): Observable<boolean>
{
return this.tags$.pipe(
take(1),
switchMap(tags => this._httpClient.delete('api/apps/contacts/tag', {params: {id}}).pipe(
map((isDeleted: boolean) => {
// Find the index of the deleted tag
const index = tags.findIndex(item => item.id === id);
// Delete the tag
tags.splice(index, 1);
// Update the tags
this._tags.next(tags);
// Return the deleted status
return isDeleted;
}),
filter(isDeleted => isDeleted),
switchMap(isDeleted => this.contacts$.pipe(
take(1),
map((contacts) => {
// Iterate through the contacts
contacts.forEach((contact) => {
const tagIndex = contact.tags.findIndex(tag => tag === id);
// If the contact has the tag, remove it
if ( tagIndex > -1 )
{
contact.tags.splice(tagIndex, 1);
}
});
// Return the deleted status
return isDeleted;
})
))
))
);
}
/**
* Update the avatar of the given contact
*
* @param id
* @param avatar
*/
uploadAvatar(id: string, avatar: File): Observable<Contact>
{
return this.contacts$.pipe(
take(1),
switchMap(contacts => this._httpClient.post<Contact>('api/apps/contacts/avatar', {
id,
avatar
}, {
headers: {
'Content-Type': avatar.type
}
}).pipe(
map((updatedContact) => {
// Find the index of the updated contact
const index = contacts.findIndex(item => item.id === id);
// Update the contact
contacts[index] = updatedContact;
// Update the contacts
this._contacts.next(contacts);
// Return the updated contact
return updatedContact;
}),
switchMap(updatedContact => this.contact$.pipe(
take(1),
filter(item => item && item.id === id),
tap(() => {
// Update the contact if it's selected
this._contact.next(updatedContact);
// Return the updated contact
return updatedContact;
})
))
))
);
}
}

View File

@@ -0,0 +1,37 @@
export interface Contact
{
id: string;
avatar?: string | null;
background?: string | null;
name: string;
emails?: {
email: string,
label: string
}[];
phoneNumbers?: {
country: string;
number: string;
label: string
}[];
title?: string;
company?: string;
birthday?: string | null;
address?: string | null;
notes?: string | null;
tags: string[];
}
export interface Country
{
id: string;
iso: string;
name: string;
code: string;
flagImagePos: string;
}
export interface Tag
{
id?: string;
title?: string;
}

View File

@@ -0,0 +1,642 @@
<div class="flex flex-col w-full">
<!-- View mode -->
<ng-container *ngIf="!editMode">
<!-- Header -->
<div class="relative w-full h-40 sm:h-48 px-8 sm:px-12 bg-accent-100 dark:bg-accent-700">
<!-- Background -->
<ng-container *ngIf="contact.background">
<img
class="absolute inset-0 object-cover w-full h-full"
[src]="contact.background">
</ng-container>
<!-- Close button -->
<div class="flex items-center justify-end w-full max-w-3xl mx-auto pt-6">
<button
mat-icon-button
[matTooltip]="'Close'"
[routerLink]="['../']">
<mat-icon
class="text-white"
[svgIcon]="'heroicons_outline:x'"></mat-icon>
</button>
</div>
</div>
<!-- Contact -->
<div class="relative flex flex-col flex-auto items-center p-6 pt-0 sm:p-12 sm:pt-0">
<div class="w-full max-w-3xl">
<!-- Avatar and actions -->
<div class="flex flex-auto items-end -mt-16">
<!-- Avatar -->
<div class="flex items-center justify-center w-32 h-32 rounded-full overflow-hidden ring-4 ring-bg-card">
<img
class="object-cover w-full h-full"
*ngIf="contact.avatar"
[src]="contact.avatar">
<div
class="flex items-center justify-center w-full h-full rounded overflow-hidden uppercase text-8xl font-bold leading-none bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200"
*ngIf="!contact.avatar">
{{contact.name.charAt(0)}}
</div>
</div>
<!-- Actions -->
<div class="flex items-center ml-auto mb-1">
<button
mat-stroked-button
(click)="toggleEditMode(true)">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:pencil-alt'"></mat-icon>
<span class="ml-2">Edit</span>
</button>
</div>
</div>
<!-- Name -->
<div class="mt-3 text-4xl font-bold truncate">{{contact.name}}</div>
<!-- Tags -->
<ng-container *ngIf="contact.tags.length">
<div class="flex flex-wrap items-center mt-2">
<!-- Tag -->
<ng-container *ngFor="let tag of (contact.tags | fuseFindByKey:'id':tags); trackBy: trackByFn">
<div class="flex items-center justify-center py-1 px-3 mr-3 mb-3 rounded-full leading-normal text-gray-500 bg-gray-100 dark:text-gray-300 dark:bg-gray-700">
<span class="text-sm font-medium whitespace-nowrap">{{tag.title}}</span>
</div>
</ng-container>
</div>
</ng-container>
<div class="flex flex-col mt-4 pt-6 border-t space-y-8">
<!-- Title -->
<ng-container *ngIf="contact.title">
<div class="flex sm:items-center">
<mat-icon [svgIcon]="'heroicons_outline:briefcase'"></mat-icon>
<div class="ml-6 leading-6">{{contact.title}}</div>
</div>
</ng-container>
<!-- Company -->
<ng-container *ngIf="contact.company">
<div class="flex sm:items-center">
<mat-icon [svgIcon]="'heroicons_outline:office-building'"></mat-icon>
<div class="ml-6 leading-6">{{contact.company}}</div>
</div>
</ng-container>
<!-- Emails -->
<ng-container *ngIf="contact.emails.length">
<div class="flex">
<mat-icon [svgIcon]="'heroicons_outline:mail'"></mat-icon>
<div class="min-w-0 ml-6 space-y-1">
<ng-container *ngFor="let email of contact.emails; trackBy: trackByFn">
<div class="flex items-center leading-6">
<a
class="hover:underline text-primary-500"
[href]="'mailto:' + email.email"
target="_blank">
{{email.email}}
</a>
<div
class="text-md truncate text-secondary"
*ngIf="email.label">
<span class="mx-2">&bull;</span>
<span class="font-medium">{{email.label}}</span>
</div>
</div>
</ng-container>
</div>
</div>
</ng-container>
<!-- Phone -->
<ng-container *ngIf="contact.phoneNumbers.length">
<div class="flex">
<mat-icon [svgIcon]="'heroicons_outline:phone'"></mat-icon>
<div class="min-w-0 ml-6 space-y-1">
<ng-container *ngFor="let phoneNumber of contact.phoneNumbers; trackBy: trackByFn">
<div class="flex items-center leading-6">
<div
class="hidden sm:flex w-6 h-4 overflow-hidden"
[matTooltip]="getCountryByIso(phoneNumber.country).name"
[style.background]="'url(\'/assets/images/apps/contacts/flags.png\') no-repeat 0 0'"
[style.backgroundSize]="'24px 3876px'"
[style.backgroundPosition]="getCountryByIso(phoneNumber.country).flagImagePos"></div>
<div class="sm:ml-3 font-mono">{{getCountryByIso(phoneNumber.country).code}}</div>
<div class="ml-2.5 font-mono">{{phoneNumber.number}}</div>
<div
class="text-md truncate text-secondary"
*ngIf="phoneNumber.label">
<span class="mx-2">&bull;</span>
<span class="font-medium">{{phoneNumber.label}}</span>
</div>
</div>
</ng-container>
</div>
</div>
</ng-container>
<!-- Address -->
<ng-container *ngIf="contact.address">
<div class="flex sm:items-center">
<mat-icon [svgIcon]="'heroicons_outline:location-marker'"></mat-icon>
<div class="ml-6 leading-6">{{contact.address}}</div>
</div>
</ng-container>
<!-- Birthday -->
<ng-container *ngIf="contact.birthday">
<div class="flex sm:items-center">
<mat-icon [svgIcon]="'heroicons_outline:cake'"></mat-icon>
<div class="ml-6 leading-6">{{contact.birthday | date:'longDate'}}</div>
</div>
</ng-container>
<!-- Notes -->
<ng-container *ngIf="contact.notes">
<div class="flex">
<mat-icon [svgIcon]="'heroicons_outline:menu-alt-2'"></mat-icon>
<div
class="max-w-none ml-6 prose prose-sm"
[innerHTML]="contact.notes"></div>
</div>
</ng-container>
</div>
</div>
</div>
</ng-container>
<!-- Edit mode -->
<ng-container *ngIf="editMode">
<!-- Header -->
<div class="relative w-full h-40 sm:h-48 px-8 sm:px-12 bg-accent-100 dark:bg-accent-700">
<!-- Background -->
<ng-container *ngIf="contact.background">
<img
class="absolute inset-0 object-cover w-full h-full"
[src]="contact.background">
</ng-container>
<!-- Close button -->
<div class="flex items-center justify-end w-full max-w-3xl mx-auto pt-6">
<button
mat-icon-button
[matTooltip]="'Close'"
[routerLink]="['../']">
<mat-icon
class="text-white"
[svgIcon]="'heroicons_outline:x'"></mat-icon>
</button>
</div>
</div>
<!-- Contact form -->
<div class="relative flex flex-col flex-auto items-center px-6 sm:px-12">
<div class="w-full max-w-3xl">
<form [formGroup]="contactForm">
<!-- Avatar -->
<div class="flex flex-auto items-end -mt-16">
<div class="relative flex items-center justify-center w-32 h-32 rounded-full overflow-hidden ring-4 ring-bg-card">
<!-- Upload / Remove avatar -->
<div class="absolute inset-0 bg-black bg-opacity-50 z-10"></div>
<div class="absolute inset-0 flex items-center justify-center z-20">
<div>
<input
id="avatar-file-input"
class="absolute h-0 w-0 opacity-0 invisible pointer-events-none"
type="file"
[multiple]="false"
[accept]="'image/jpeg, image/png'"
(change)="uploadAvatar(avatarFileInput.files)"
#avatarFileInput>
<label
class="flex items-center justify-center w-10 h-10 rounded-full cursor-pointer hover:bg-hover"
for="avatar-file-input"
matRipple>
<mat-icon
class="text-white"
[svgIcon]="'heroicons_outline:camera'"></mat-icon>
</label>
</div>
<div>
<button
mat-icon-button
(click)="removeAvatar()">
<mat-icon
class="text-white"
[svgIcon]="'heroicons_outline:trash'"></mat-icon>
</button>
</div>
</div>
<!-- Image/Letter -->
<img
class="object-cover w-full h-full"
*ngIf="contact.avatar"
[src]="contact.avatar">
<div
class="flex items-center justify-center w-full h-full rounded overflow-hidden uppercase text-8xl font-bold leading-none bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200"
*ngIf="!contact.avatar">
{{contact.name.charAt(0)}}
</div>
</div>
</div>
<!-- Name -->
<div class="mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Name</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:user-circle'"></mat-icon>
<input
matInput
[formControlName]="'name'"
[placeholder]="'Name'"
[spellcheck]="false">
</mat-form-field>
</div>
<!-- Tags -->
<div class="flex flex-wrap items-center -m-1.5 mt-6">
<!-- Tags -->
<ng-container *ngIf="contact.tags.length">
<ng-container *ngFor="let tag of (contact.tags | fuseFindByKey:'id':tags); trackBy: trackByFn">
<div class="flex items-center justify-center px-4 m-1.5 rounded-full leading-9 text-gray-500 bg-gray-100 dark:text-gray-300 dark:bg-gray-700">
<span class="text-md font-medium whitespace-nowrap">{{tag.title}}</span>
</div>
</ng-container>
</ng-container>
<!-- Tags panel and its button -->
<div
class="flex items-center justify-center px-4 m-1.5 rounded-full leading-9 cursor-pointer text-gray-500 bg-gray-100 dark:text-gray-300 dark:bg-gray-700"
(click)="openTagsPanel()"
#tagsPanelOrigin>
<ng-container *ngIf="contact.tags.length">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:pencil-alt'"></mat-icon>
<span class="ml-1.5 text-md font-medium whitespace-nowrap">Edit</span>
</ng-container>
<ng-container *ngIf="!contact.tags.length">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:plus-circle'"></mat-icon>
<span class="ml-1.5 text-md font-medium whitespace-nowrap">Add</span>
</ng-container>
<!-- Tags panel -->
<ng-template #tagsPanel>
<div class="w-60 rounded border shadow-md bg-card">
<!-- Tags panel header -->
<div class="flex items-center m-3 mr-2">
<div class="flex items-center">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:search'"></mat-icon>
<div class="ml-2">
<input
class="w-full min-w-0 py-1 border-0"
type="text"
placeholder="Enter tag name"
(input)="filterTags($event)"
(keydown)="filterTagsInputKeyDown($event)"
[maxLength]="30"
#newTagInput>
</div>
</div>
<button
class="ml-1"
mat-icon-button
(click)="toggleTagsEditMode()">
<mat-icon
*ngIf="!tagsEditMode"
class="icon-size-5"
[svgIcon]="'heroicons_solid:pencil-alt'"></mat-icon>
<mat-icon
*ngIf="tagsEditMode"
class="icon-size-5"
[svgIcon]="'heroicons_solid:check'"></mat-icon>
</button>
</div>
<div
class="flex flex-col max-h-64 py-2 border-t overflow-y-auto">
<!-- Tags -->
<ng-container *ngIf="!tagsEditMode">
<div
*ngFor="let tag of filteredTags; trackBy: trackByFn"
class="flex items-center h-10 min-h-10 px-4 cursor-pointer hover:bg-hover"
(click)="toggleContactTag(tag)"
matRipple>
<mat-checkbox
class="flex items-center h-10 min-h-10 pointer-events-none"
[checked]="contact.tags.includes(tag.id)"
[color]="'primary'"
[disableRipple]="true">
</mat-checkbox>
<div class="ml-1">{{tag.title}}</div>
</div>
</ng-container>
<!-- Tags editing -->
<ng-container *ngIf="tagsEditMode">
<div class="py-2 space-y-2">
<div
class="flex items-center"
*ngFor="let tag of filteredTags; trackBy: trackByFn">
<mat-form-field class="fuse-mat-dense fuse-mat-no-subscript w-full mx-4">
<input
matInput
[value]="tag.title"
(input)="updateTagTitle(tag, $event)">
<button
mat-icon-button
(click)="deleteTag(tag)"
matSuffix>
<mat-icon
class="icon-size-5 ml-2"
[svgIcon]="'heroicons_solid:trash'"></mat-icon>
</button>
</mat-form-field>
</div>
</div>
</ng-container>
<!-- Create tag -->
<div
class="flex items-center h-10 min-h-10 -ml-0.5 pl-4 pr-3 leading-none cursor-pointer hover:bg-hover"
*ngIf="shouldShowCreateTagButton(newTagInput.value)"
(click)="createTag(newTagInput.value); newTagInput.value = ''"
matRipple>
<mat-icon
class="mr-2 icon-size-5"
[svgIcon]="'heroicons_solid:plus-circle'"></mat-icon>
<div class="break-all">Create "<b>{{newTagInput.value}}</b>"</div>
</div>
</div>
</div>
</ng-template>
</div>
</div>
<!-- Title -->
<div class="mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Title</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:briefcase'"></mat-icon>
<input
matInput
[formControlName]="'title'"
[placeholder]="'Job title'">
</mat-form-field>
</div>
<!-- Company -->
<div class="mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Company</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:office-building'"></mat-icon>
<input
matInput
[formControlName]="'company'"
[placeholder]="'Company'">
</mat-form-field>
</div>
<!-- Emails -->
<div class="mt-8">
<div class="space-y-4">
<ng-container *ngFor="let email of contactForm.get('emails')['controls']; let i = index; let first = first; let last = last; trackBy: trackByFn">
<div class="flex">
<mat-form-field class="fuse-mat-no-subscript flex-auto">
<mat-label *ngIf="first">Email</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:mail'"></mat-icon>
<input
matInput
[formControl]="email.get('email')"
[placeholder]="'Email address'"
[spellcheck]="false">
</mat-form-field>
<mat-form-field class="fuse-mat-no-subscript flex-auto w-full max-w-24 sm:max-w-40 ml-2 sm:ml-4">
<mat-label *ngIf="first">Label</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:tag'"></mat-icon>
<input
matInput
[formControl]="email.get('label')"
[placeholder]="'Label'">
</mat-form-field>
<!-- Remove email -->
<ng-container *ngIf="!(first && last)">
<div
class="flex items-center w-10 pl-2"
[ngClass]="{'mt-6': first}">
<button
class="w-8 h-8 min-h-8"
mat-icon-button
(click)="removeEmailField(i)"
matTooltip="Remove">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:trash'"></mat-icon>
</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
<div
class="group inline-flex items-center mt-2 -ml-4 py-2 px-4 rounded cursor-pointer"
(click)="addEmailField()">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:plus-circle'"></mat-icon>
<span class="ml-2 font-medium text-secondary group-hover:underline">Add an email address</span>
</div>
</div>
<!-- Phone numbers -->
<div class="mt-8">
<div class="space-y-4">
<ng-container *ngFor="let phoneNumber of contactForm.get('phoneNumbers')['controls']; let i = index; let first = first; let last = last; trackBy: trackByFn">
<div class="relative flex">
<mat-form-field class="fuse-mat-no-subscript flex-auto">
<mat-label *ngIf="first">Phone</mat-label>
<input
matInput
[formControl]="phoneNumber.get('number')"
[placeholder]="'Phone'">
<mat-select
class="mr-1.5"
[formControl]="phoneNumber.get('country')"
matPrefix>
<mat-select-trigger>
<span class="flex items-center">
<span
class="hidden sm:flex w-6 h-4 mr-1 overflow-hidden"
[style.background]="'url(\'/assets/images/apps/contacts/flags.png\') no-repeat 0 0'"
[style.backgroundSize]="'24px 3876px'"
[style.backgroundPosition]="getCountryByIso(phoneNumber.get('country').value).flagImagePos"></span>
<span class="sm:mx-0.5 font-medium text-default">{{getCountryByIso(phoneNumber.get('country').value).code}}</span>
</span>
</mat-select-trigger>
<mat-option
*ngFor="let country of countries; trackBy: trackByFn"
[value]="country.iso">
<span class="flex items-center">
<span
class="w-6 h-4 overflow-hidden"
[style.background]="'url(\'/assets/images/apps/contacts/flags.png\') no-repeat 0 0'"
[style.backgroundSize]="'24px 3876px'"
[style.backgroundPosition]="country.flagImagePos"></span>
<span class="ml-2">{{country.name}}</span>
<span class="ml-2 font-medium">{{country.code}}</span>
</span>
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="fuse-mat-no-subscript flex-auto w-full max-w-24 sm:max-w-40 ml-2 sm:ml-4">
<mat-label *ngIf="first">Label</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:tag'"></mat-icon>
<input
matInput
[formControl]="phoneNumber.get('label')"
[placeholder]="'Label'">
</mat-form-field>
<!-- Remove phone number -->
<ng-container *ngIf="!(first && last)">
<div
class="flex items-center w-10 pl-2"
[ngClass]="{'mt-6': first}">
<button
class="w-8 h-8 min-h-8"
mat-icon-button
(click)="removePhoneNumberField(i)"
matTooltip="Remove">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:trash'"></mat-icon>
</button>
</div>
</ng-container>
</div>
</ng-container>
</div>
<div
class="group inline-flex items-center mt-2 -ml-4 py-2 px-4 rounded cursor-pointer"
(click)="addPhoneNumberField()">
<mat-icon
class="icon-size-5"
[svgIcon]="'heroicons_solid:plus-circle'"></mat-icon>
<span class="ml-2 font-medium text-secondary group-hover:underline">Add a phone number</span>
</div>
</div>
<!-- Address -->
<div class="mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Address</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:location-marker'"></mat-icon>
<input
matInput
[formControlName]="'address'"
[placeholder]="'Address'">
</mat-form-field>
</div>
<!-- Birthday -->
<div class="mt-8">
<mat-form-field class="fuse-mat-no-subscript w-full">
<mat-label>Birthday</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:cake'"></mat-icon>
<input
matInput
[matDatepicker]="birthdayDatepicker"
[formControlName]="'birthday'"
[placeholder]="'Birthday'">
<mat-datepicker-toggle
matSuffix
[for]="birthdayDatepicker">
</mat-datepicker-toggle>
<mat-datepicker #birthdayDatepicker></mat-datepicker>
</mat-form-field>
</div>
<!-- Notes -->
<div class="mt-8">
<mat-form-field class="fuse-mat-textarea fuse-mat-no-subscript w-full">
<mat-label>Notes</mat-label>
<mat-icon
matPrefix
class="hidden sm:flex icon-size-5"
[svgIcon]="'heroicons_solid:menu-alt-2'"></mat-icon>
<textarea
matInput
fuseAutogrow
[rows]="5"
[formControlName]="'notes'"
[placeholder]="'Notes'"
[spellcheck]="false"></textarea>
</mat-form-field>
</div>
<!-- Actions -->
<div class="flex items-center mt-10 -mx-6 sm:-mx-12 py-4 pr-4 pl-1 sm:pr-12 sm:pl-7 border-t bg-gray-50 dark:bg-transparent">
<!-- Delete -->
<button
mat-button
[color]="'warn'"
[matTooltip]="'Delete'"
(click)="deleteContact()">
Delete
</button>
<!-- Cancel -->
<button
class="ml-auto"
mat-button
[matTooltip]="'Cancel'"
(click)="toggleEditMode(false)">
Cancel
</button>
<!-- Save -->
<button
class="ml-2"
mat-flat-button
[color]="'primary'"
[disabled]="contactForm.invalid"
[matTooltip]="'Save'"
(click)="updateContact()">
Save
</button>
</div>
</form>
</div>
</div>
</ng-container>
</div>

View File

@@ -0,0 +1,711 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, Renderer2, TemplateRef, ViewChild, ViewContainerRef, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { TemplatePortal } from '@angular/cdk/portal';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { MatDrawerToggleResult } from '@angular/material/sidenav';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Contact, Country, Tag } from 'app/modules/admin/apps/contacts/contacts.types';
import { ContactsListComponent } from 'app/modules/admin/apps/contacts/list/list.component';
import { ContactsService } from 'app/modules/admin/apps/contacts/contacts.service';
@Component({
selector : 'contacts-details',
templateUrl : './details.component.html',
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ContactsDetailsComponent implements OnInit, OnDestroy
{
@ViewChild('avatarFileInput') private _avatarFileInput: ElementRef;
@ViewChild('tagsPanel') private _tagsPanel: TemplateRef<any>;
@ViewChild('tagsPanelOrigin') private _tagsPanelOrigin: ElementRef;
editMode: boolean = false;
tags: Tag[];
tagsEditMode: boolean = false;
filteredTags: Tag[];
contact: Contact;
contactForm: FormGroup;
contacts: Contact[];
countries: Country[];
private _tagsPanelOverlayRef: OverlayRef;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _activatedRoute: ActivatedRoute,
private _changeDetectorRef: ChangeDetectorRef,
private _contactsListComponent: ContactsListComponent,
private _contactsService: ContactsService,
private _formBuilder: FormBuilder,
private _renderer2: Renderer2,
private _router: Router,
private _overlay: Overlay,
private _viewContainerRef: ViewContainerRef
)
{
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Open the drawer
this._contactsListComponent.matDrawer.open();
// Create the contact form
this.contactForm = this._formBuilder.group({
id : [''],
avatar : [null],
name : ['', [Validators.required]],
emails : this._formBuilder.array([]),
phoneNumbers: this._formBuilder.array([]),
title : [''],
company : [''],
birthday : [null],
address : [null],
notes : [null],
tags : [[]]
});
// Get the contacts
this._contactsService.contacts$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((contacts: Contact[]) => {
this.contacts = contacts;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Get the contact
this._contactsService.contact$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((contact: Contact) => {
// Open the drawer in case it is closed
this._contactsListComponent.matDrawer.open();
// Get the contact
this.contact = contact;
// Clear the emails and phoneNumbers form arrays
(this.contactForm.get('emails') as FormArray).clear();
(this.contactForm.get('phoneNumbers') as FormArray).clear();
// Patch values to the form
this.contactForm.patchValue(contact);
// Setup the emails form array
const emailFormGroups = [];
if ( contact.emails.length > 0 )
{
// Iterate through them
contact.emails.forEach((email) => {
// Create an email form group
emailFormGroups.push(
this._formBuilder.group({
email: [email.email],
label: [email.label]
})
);
});
}
else
{
// Create an email form group
emailFormGroups.push(
this._formBuilder.group({
email: [''],
label: ['']
})
);
}
// Add the email form groups to the emails form array
emailFormGroups.forEach((emailFormGroup) => {
(this.contactForm.get('emails') as FormArray).push(emailFormGroup);
});
// Setup the phone numbers form array
const phoneNumbersFormGroups = [];
if ( contact.phoneNumbers.length > 0 )
{
// Iterate through them
contact.phoneNumbers.forEach((phoneNumber) => {
// Create an email form group
phoneNumbersFormGroups.push(
this._formBuilder.group({
country: [phoneNumber.country],
number : [phoneNumber.number],
label : [phoneNumber.label]
})
);
});
}
else
{
// Create a phone number form group
phoneNumbersFormGroups.push(
this._formBuilder.group({
country: ['us'],
number : [''],
label : ['']
})
);
}
// Add the phone numbers form groups to the phone numbers form array
phoneNumbersFormGroups.forEach((phoneNumbersFormGroup) => {
(this.contactForm.get('phoneNumbers') as FormArray).push(phoneNumbersFormGroup);
});
// Toggle the edit mode off
this.toggleEditMode(false);
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Get the country telephone codes
this._contactsService.countries$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((codes: Country[]) => {
this.countries = codes;
// Mark for check
this._changeDetectorRef.markForCheck();
});
// Get the tags
this._contactsService.tags$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((tags: Tag[]) => {
this.tags = tags;
this.filteredTags = tags;
// Mark for check
this._changeDetectorRef.markForCheck();
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
// Dispose the overlays if they are still on the DOM
if ( this._tagsPanelOverlayRef )
{
this._tagsPanelOverlayRef.dispose();
}
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Close the drawer
*/
closeDrawer(): Promise<MatDrawerToggleResult>
{
return this._contactsListComponent.matDrawer.close();
}
/**
* Toggle edit mode
*
* @param editMode
*/
toggleEditMode(editMode: boolean | null = null): void
{
if ( editMode === null )
{
this.editMode = !this.editMode;
}
else
{
this.editMode = editMode;
}
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Update the contact
*/
updateContact(): void
{
// Get the contact object
const contact = this.contactForm.getRawValue();
// Go through the contact object and clear empty values
contact.emails = contact.emails.filter((email) => {
return email.email;
});
contact.phoneNumbers = contact.phoneNumbers.filter((phoneNumber) => {
return phoneNumber.number;
});
// Update the contact on the server
this._contactsService.updateContact(contact.id, contact).subscribe(() => {
// Toggle the edit mode off
this.toggleEditMode(false);
});
}
/**
* Delete the contact
*/
deleteContact(): void
{
// Get the current contact's id
const id = this.contact.id;
// Get the next/previous contact's id
const currentContactIndex = this.contacts.findIndex(item => item.id === id);
const nextContactIndex = currentContactIndex + ((currentContactIndex === (this.contacts.length - 1)) ? -1 : 1);
const nextContactId = (this.contacts.length === 1 && this.contacts[0].id === id) ? null : this.contacts[nextContactIndex].id;
// Delete the contact
this._contactsService.deleteContact(id)
.subscribe((isDeleted) => {
// Return if the contact wasn't deleted...
if ( !isDeleted )
{
return;
}
// Get the current activated route
let route = this._activatedRoute;
while ( route.firstChild )
{
route = route.firstChild;
}
// Navigate to the next contact if available
if ( nextContactId )
{
this._router.navigate(['../', nextContactId], {relativeTo: route});
}
// Otherwise, navigate to the parent
else
{
this._router.navigate(['../'], {relativeTo: route});
}
// Toggle the edit mode off
this.toggleEditMode(false);
});
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Upload avatar
*
* @param fileList
*/
uploadAvatar(fileList: FileList): void
{
// Return if canceled
if ( !fileList.length )
{
return;
}
const allowedTypes = ['image/jpeg', 'image/png'];
const file = fileList[0];
// Return if the file is not allowed
if ( !allowedTypes.includes(file.type) )
{
return;
}
// Upload the avatar
this._contactsService.uploadAvatar(this.contact.id, file).subscribe();
}
/**
* Remove the avatar
*/
removeAvatar(): void
{
// Get the form control for 'avatar'
const avatarFormControl = this.contactForm.get('avatar');
// Set the avatar as null
avatarFormControl.setValue(null);
// Set the file input value as null
this._avatarFileInput.nativeElement.value = null;
// Update the contact
this.contact.avatar = null;
}
/**
* Open tags panel
*/
openTagsPanel(): void
{
// Create the overlay
this._tagsPanelOverlayRef = this._overlay.create({
backdropClass : '',
hasBackdrop : true,
scrollStrategy : this._overlay.scrollStrategies.block(),
positionStrategy: this._overlay.position()
.flexibleConnectedTo(this._tagsPanelOrigin.nativeElement)
.withFlexibleDimensions()
.withViewportMargin(64)
.withLockedPosition()
.withPositions([
{
originX : 'start',
originY : 'bottom',
overlayX: 'start',
overlayY: 'top'
}
])
});
// Subscribe to the attachments observable
this._tagsPanelOverlayRef.attachments().subscribe(() => {
// Add a class to the origin
this._renderer2.addClass(this._tagsPanelOrigin.nativeElement, 'panel-opened');
// Focus to the search input once the overlay has been attached
this._tagsPanelOverlayRef.overlayElement.querySelector('input').focus();
});
// Create a portal from the template
const templatePortal = new TemplatePortal(this._tagsPanel, this._viewContainerRef);
// Attach the portal to the overlay
this._tagsPanelOverlayRef.attach(templatePortal);
// Subscribe to the backdrop click
this._tagsPanelOverlayRef.backdropClick().subscribe(() => {
// Remove the class from the origin
this._renderer2.removeClass(this._tagsPanelOrigin.nativeElement, 'panel-opened');
// If overlay exists and attached...
if ( this._tagsPanelOverlayRef && this._tagsPanelOverlayRef.hasAttached() )
{
// Detach it
this._tagsPanelOverlayRef.detach();
// Reset the tag filter
this.filteredTags = this.tags;
// Toggle the edit mode off
this.tagsEditMode = false;
}
// If template portal exists and attached...
if ( templatePortal && templatePortal.isAttached )
{
// Detach it
templatePortal.detach();
}
});
}
/**
* Toggle the tags edit mode
*/
toggleTagsEditMode(): void
{
this.tagsEditMode = !this.tagsEditMode;
}
/**
* Filter tags
*
* @param event
*/
filterTags(event): void
{
// Get the value
const value = event.target.value.toLowerCase();
// Filter the tags
this.filteredTags = this.tags.filter(tag => tag.title.toLowerCase().includes(value));
}
/**
* Filter tags input key down event
*
* @param event
*/
filterTagsInputKeyDown(event): void
{
// Return if the pressed key is not 'Enter'
if ( event.key !== 'Enter' )
{
return;
}
// If there is no tag available...
if ( this.filteredTags.length === 0 )
{
// Create the tag
this.createTag(event.target.value);
// Clear the input
event.target.value = '';
// Return
return;
}
// If there is a tag...
const tag = this.filteredTags[0];
const isTagApplied = this.contact.tags.find((id) => id === tag.id);
// If the found tag is already applied to the contact...
if ( isTagApplied )
{
// Remove the tag from the contact
this.removeTagFromContact(tag);
}
else
{
// Otherwise add the tag to the contact
this.addTagToContact(tag);
}
}
/**
* Create a new tag
*
* @param title
*/
createTag(title: string): void
{
const tag = {
title
};
// Create tag on the server
this._contactsService.createTag(tag)
.subscribe((response) => {
// Add the tag to the contact
this.addTagToContact(response);
});
}
/**
* Update the tag title
*
* @param tag
* @param event
*/
updateTagTitle(tag: Tag, event): void
{
// Update the title on the tag
tag.title = event.target.value;
// Update the tag on the server
this._contactsService.updateTag(tag.id, tag)
.pipe(debounceTime(300))
.subscribe();
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Delete the tag
*
* @param tag
*/
deleteTag(tag: Tag): void
{
// Delete the tag from the server
this._contactsService.deleteTag(tag.id).subscribe();
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Add tag to the contact
*
* @param tag
*/
addTagToContact(tag: Tag): void
{
// Add the tag
this.contact.tags.unshift(tag.id);
// Update the contact form
this.contactForm.get('tags').patchValue(this.contact.tags);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Remove tag from the contact
*
* @param tag
*/
removeTagFromContact(tag: Tag): void
{
// Remove the tag
this.contact.tags.splice(this.contact.tags.findIndex(item => item === tag.id), 1);
// Update the contact form
this.contactForm.get('tags').patchValue(this.contact.tags);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Toggle contact tag
*
* @param tag
*/
toggleContactTag(tag: Tag): void
{
if ( this.contact.tags.includes(tag.id) )
{
this.removeTagFromContact(tag);
}
else
{
this.addTagToContact(tag);
}
}
/**
* Should the create tag button be visible
*
* @param inputValue
*/
shouldShowCreateTagButton(inputValue: string): boolean
{
return !!!(inputValue === '' || this.tags.findIndex(tag => tag.title.toLowerCase() === inputValue.toLowerCase()) > -1);
}
/**
* Add the email field
*/
addEmailField(): void
{
// Create an empty email form group
const emailFormGroup = this._formBuilder.group({
email: [''],
label: ['']
});
// Add the email form group to the emails form array
(this.contactForm.get('emails') as FormArray).push(emailFormGroup);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Remove the email field
*
* @param index
*/
removeEmailField(index: number): void
{
// Get form array for emails
const emailsFormArray = this.contactForm.get('emails') as FormArray;
// Remove the email field
emailsFormArray.removeAt(index);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Add an empty phone number field
*/
addPhoneNumberField(): void
{
// Create an empty phone number form group
const phoneNumberFormGroup = this._formBuilder.group({
country: ['us'],
number : [''],
label : ['']
});
// Add the phone number form group to the phoneNumbers form array
(this.contactForm.get('phoneNumbers') as FormArray).push(phoneNumberFormGroup);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Remove the phone number field
*
* @param index
*/
removePhoneNumberField(index: number): void
{
// Get form array for phone numbers
const phoneNumbersFormArray = this.contactForm.get('phoneNumbers') as FormArray;
// Remove the phone number field
phoneNumbersFormArray.removeAt(index);
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Get country info by iso code
*
* @param iso
*/
getCountryByIso(iso: string): Country
{
return this.countries.find((country) => country.iso === iso);
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
}

View File

@@ -0,0 +1,120 @@
<div class="absolute inset-0 flex flex-col min-w-0 overflow-hidden">
<mat-drawer-container
class="flex-auto h-full bg-card dark:bg-transparent"
(backdropClick)="onBackdropClicked()">
<!-- Drawer -->
<mat-drawer
class="w-full md:w-160 dark:bg-gray-900"
[mode]="drawerMode"
[opened]="false"
[position]="'end'"
[disableClose]="true"
#matDrawer>
<router-outlet></router-outlet>
</mat-drawer>
<mat-drawer-content class="flex flex-col">
<!-- Main -->
<div class="flex-auto">
<!-- Header -->
<div class="flex flex-col sm:flex-row md:flex-col flex-auto justify-between py-8 px-6 md:px-8 border-b">
<!-- Title -->
<div>
<div class="text-4xl font-extrabold tracking-tight leading-none">Contacts</div>
<div class="ml-0.5 font-medium text-secondary">
<ng-container *ngIf="contactsCount > 0">
{{contactsCount}}
</ng-container>
{{contactsCount | i18nPlural: {
'=0' : 'No contacts',
'=1' : 'contact',
'other': 'contacts'
} }}
</div>
</div>
<!-- Main actions -->
<div class="flex items-center mt-4 sm:mt-0 md:mt-4">
<!-- Search -->
<div class="flex-auto">
<mat-form-field class="fuse-mat-dense fuse-mat-no-subscript w-full min-w-50">
<mat-icon
class="icon-size-5"
matPrefix
[svgIcon]="'heroicons_solid:search'"></mat-icon>
<input
matInput
[formControl]="searchInputControl"
[autocomplete]="'off'"
[placeholder]="'Search contacts'">
</mat-form-field>
</div>
<!-- Add contact button -->
<button
class="ml-4"
mat-flat-button
[color]="'primary'"
(click)="createContact()">
<mat-icon [svgIcon]="'heroicons_outline:plus'"></mat-icon>
<span class="ml-2 mr-1">Add</span>
</button>
</div>
</div>
<!-- Contacts list -->
<div class="relative">
<ng-container *ngIf="contacts$ | async as contacts">
<ng-container *ngIf="contacts.length; else noContacts">
<ng-container *ngFor="let contact of contacts; let i = index; trackBy: trackByFn">
<!-- Group -->
<ng-container *ngIf="i === 0 || contact.name.charAt(0) !== contacts[i - 1].name.charAt(0)">
<div class="z-10 sticky top-0 -mt-px px-6 py-1 md:px-8 border-t border-b font-medium uppercase text-secondary bg-gray-50 dark:bg-gray-900">
{{contact.name.charAt(0)}}
</div>
</ng-container>
<!-- Contact -->
<div
class="z-20 flex items-center px-6 py-4 md:px-8 cursor-pointer hover:bg-hover border-b"
[ngClass]="{'bg-primary-50 dark:bg-hover': selectedContact && selectedContact.id === contact.id}"
(click)="goToContact(contact.id)">
<div class="flex flex-0 items-center justify-center w-10 h-10 rounded-full overflow-hidden">
<ng-container *ngIf="contact.avatar">
<img
class="object-cover w-full h-full"
[src]="contact.avatar"
alt="Contact avatar"/>
</ng-container>
<ng-container *ngIf="!contact.avatar">
<div class="flex items-center justify-center w-full h-full rounded-full text-lg uppercase bg-gray-200 text-gray-600 dark:bg-gray-700 dark:text-gray-200">
{{contact.name.charAt(0)}}
</div>
</ng-container>
</div>
<div class="min-w-0 ml-4">
<div class="font-medium leading-5 truncate">{{contact.name}}</div>
<div class="leading-5 truncate text-secondary">{{contact.title}}</div>
</div>
</div>
</ng-container>
</ng-container>
</ng-container>
<!-- No contacts -->
<ng-template #noContacts>
<div class="p-8 sm:p-16 border-t text-4xl font-semibold tracking-tight text-center">There are no contacts!</div>
</ng-template>
</div>
</div>
</mat-drawer-content>
</mat-drawer-container>
</div>

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