many, MANY improvements to admin UI

This commit is contained in:
itzMiney committed 2026-03-19 22:12:59 +01:00
1 parent eac0938ccf
commit 3b6ac1dcab
14 files changed
+2412 -90

No files matched your search

+1470 -1
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -20,6 +20,8 @@
"@ngx-translate/core": "^16.0.4",
"@ngx-translate/http-loader": "^16.0.1",
"axios": "^1.13.5",
"marked": "^17.0.4",
"ngx-markdown": "^21.1.0",
"parallax-js": "^3.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
+15 -10
View File
@@ -68,8 +68,8 @@ img {
}
form {
height: 100%;
box-sizing: border-box;
padding-bottom: 10px;
}
.action-bar {
@@ -118,6 +118,7 @@ form {
#submitBtn {
font-size: 0.9rem;
white-space: nowrap;
}
#modeSel,
@@ -182,13 +183,6 @@ form {
width: 166px;
}
#editContent {
display: flex;
width: 100%;
height: 100%;
box-sizing: border-box
}
.right-section {
display: flex;
flex-direction: column;
@@ -280,8 +274,7 @@ input[type="number"] {
-moz-appearance: textfield;
}
input:disabled,
textarea:disabled {
input:disabled {
background-color: rgba(28, 21, 21, 0.25);
cursor: not-allowed;
}
@@ -342,3 +335,15 @@ button.logout {
button.logout:hover {
background-color: #592840;
}
.create-btn {
background-color: #78cd8b;
}
.edit-btn {
background-color: #8e95e3;
}
.delete-btn {
background-color: #c8002f;
}
+48 -17
View File
@@ -18,19 +18,26 @@
<div class="main-separator"></div>
<div class="article-input-box">
<form #articleForm="ngForm" (ngSubmit)="submitArticle(articleForm)" [ngStyle]="{'height': isNarrow ? 'calc(100% - 272px)' : 'calc(100% - 69px)'}">
<form #articleForm="ngForm" (ngSubmit)="submitArticle()">
<div class="action-bar" [class.mobile]="isNarrow">
<input
id="editTitle"
type="text"
name="title"
ngModel
[(ngModel)]="title"
placeholder="Article Title"
[required]="articleMode === 'create'"
[disabled]="articleMode === 'delete'"
[disabled]="articleMode === 'delete' || (articleMode === 'edit' && !editArticleLoaded)"
/>
<div class="mode-select-button" [ngStyle]="{'justify-content': isNarrow ? 'left' : 'center'}">
<div id=modeSel (click)="toggleDropdown()" [ngStyle]="{'background-color': articleMode === 'create' ? '#78cd8b' : articleMode === 'edit' ? '#8e95e3' : '#ba243a'}">
<div
id=modeSel (click)="toggleDropdown()"
[ngClass]="{
'create-btn': articleMode === 'create',
'edit-btn': articleMode === 'edit',
'delete-btn': articleMode === 'delete'
}"
>
{{ articleMode | titlecase }} Article
</div>
@if (isDropdownOpen) {
@@ -45,30 +52,34 @@
id="articleId"
type="number"
name="articleId"
ngModel
[(ngModel)]="articleIdValue"
placeholder="Article ID"
min="1"
[required]="articleMode !== 'create'"
[disabled]="articleMode === 'create'"
(ngModelChange)="onArticleIdChange($event)"
/>
<button
id="submitBtn"
type="submit"
name="submit"
[disabled]="articleForm.invalid"
[disabled]="isArticleSubmitDisabled() || articleNotFound"
[ngClass]="{
'create-btn': articleMode === 'create',
'edit-btn': articleMode === 'edit',
'delete-btn': articleMode === 'delete'
}"
>
{{ articleMode === 'create' ? 'Create' : articleMode === 'edit' ? 'Edit' : 'Delete' }}
{{ articleNotFound ? 'Article not Found' : (articleMode === 'create' ? 'Create' : articleMode === 'edit' ? 'Edit' : 'Delete') }}
</button>
</div>
<textarea
id="editContent"
<app-markdown-editor
name="content"
ngModel
placeholder="Article Content"
[required]="articleMode === 'create'"
[disabled]="articleMode === 'delete'"
>
</textarea>
id="content"
[(ngModel)]="content"
[disabled]="articleMode === 'delete' || (articleMode === 'edit' && !editArticleLoaded)"
(click)="onContentClick($event)">
</app-markdown-editor>
</form>
</div>
</div>
@@ -95,7 +106,10 @@
@if (!noArticles) {
<ul>
@for (article of articles; track article) {
<li (click)="navigateToArticle(article.slug)">
<li
(click)="loadArticleIntoEditor(article)"
[class.active]="loadedArticle?.id === article.id"
>
<strong>ID {{ article.id }}</strong> - {{ article.title }}
</li>
}
@@ -194,5 +208,22 @@
[title]="modalTitle"
(onClose)="closeShortenerModal()"
>
</app-shortener>
<!-- Image Modal -->
@if (selectedImage) {
<div
class="modal"
animate.enter="modal-enter"
animate.leave="modal-leave"
(click)="closePreview()"
>
<img
[src]="selectedImage"
alt="Full Preview"
class="modal-image"
animate.enter="modal-image-enter"
animate.leave="modal-image-leave"
/>
</div>
}
+224 -34
View File
@@ -2,7 +2,7 @@ import {Component, OnDestroy, OnInit} from '@angular/core';
import {Router, RouterLink} from '@angular/router';
import {ArticleService} from '../shared/services/article.service';
import {UserService} from '../shared/services/user.service';
import {NgStyle, TitleCasePipe} from '@angular/common';
import {NgClass, NgStyle, TitleCasePipe} from '@angular/common';
import {Observer, Subscription, interval} from 'rxjs';
import {FormsModule, NgForm} from '@angular/forms';
import {ViewportService} from '../shared/services/viewport.service';
@@ -10,6 +10,19 @@ import {Title} from '@angular/platform-browser';
import {ModalComponent} from '../shared/modal/modal.component';
import {AuthService} from '../shared/services/auth.service';
import {ShortenerComponent} from '../shared/shortener/shortener.component';
import {MarkdownEditorComponent} from '../shared/markdown-editor/markdown-editor.component';
interface Article {
id: number;
title: string;
slug: string;
content: string;
createdAt: string;
updatedAt: string;
views: number;
authorId: number;
authorName: string;
}
@Component({
selector: 'app-admin',
@@ -21,13 +34,15 @@ import {ShortenerComponent} from '../shared/shortener/shortener.component';
ModalComponent,
TitleCasePipe,
RouterLink,
ShortenerComponent
ShortenerComponent,
MarkdownEditorComponent,
NgClass
]
})
export class AdminComponent implements OnInit, OnDestroy {
tokenValidationInterval: Subscription = new Subscription();
articles: any[] = [];
articles: Article[] = [];
users: any[] = [];
noArticles: boolean = false;
@@ -52,8 +67,20 @@ export class AdminComponent implements OnInit, OnDestroy {
isViewingArticles: boolean = true;
articleMode: 'create' | 'edit' | 'delete' = 'create';
loadedArticle: Article | null = null;
editArticleLoaded = false;
loadingEditArticle = false;
articleIdValue: number | null = null;
articleNotFound = false;
originalTitle = '';
originalContent = '';
isDropdownOpen = false;
selectedImage: string | null = null;
constructor(
private articleService: ArticleService,
private userService: UserService,
@@ -95,6 +122,8 @@ export class AdminComponent implements OnInit, OnDestroy {
this.articleService.postArticle(token, title.trim(), content.trim()).subscribe({
next: () => {
alert('Article created successfully.');
this.articleIdValue = null;
this.resetArticleFormState();
this.loadArticles();
},
error: err => {
@@ -111,40 +140,71 @@ export class AdminComponent implements OnInit, OnDestroy {
return;
}
if (!this.loadedArticle) {
alert('No article loaded for editing.');
return;
}
const id = Number(articleId);
this.authService.validateToken().subscribe(valid => {
const updatedTitle = title?.trim() ?? '';
const updatedContent = content?.trim() ?? '';
const titleChanged = updatedTitle !== this.originalTitle;
const contentChanged = updatedContent !== this.originalContent;
if (!titleChanged && !contentChanged) {
alert('No changes detected.');
return;
}
const updates: { title?: string; content?: string } = {};
if (titleChanged) {
updates.title = updatedTitle;
}
if (contentChanged) {
updates.content = updatedContent;
}
this.authService.validateToken().subscribe({
next: (valid) => {
if (!valid) return;
const token = this.authService.token!;
this.articleService.getArticleById(id).subscribe(
(article) => {
if (!article) {
alert(`Article with ID ${id} not found.`);
return;
}
const updatedTitle = title?.trim() || article.title;
const updatedContent = content?.trim() || article.content;
this.articleService.editArticle(id, token, updatedTitle, updatedContent).subscribe(
(response) => {
this.articleService.editArticle(id, token, updates).subscribe({
next: (response) => {
alert(`Article ${id} updated successfully!`);
console.log('Updated Article:', response);
if (titleChanged) {
this.originalTitle = updatedTitle;
this.title = updatedTitle;
}
if (contentChanged) {
this.originalContent = updatedContent;
this.content = updatedContent;
}
this.loadedArticle = {
...this.loadedArticle,
...response
};
this.loadArticles();
},
(error) => {
error: (error) => {
alert(`Error updating article ${id}: ${error.message}`);
console.error('Error:', error);
}
);
});
},
(error: { message: any }) => {
alert(`Failed to fetch article with ID ${id}: ${error.message}`);
console.error('Error:', error);
error: (error) => {
console.error('Token validation failed:', error);
}
);
});
}
@@ -154,6 +214,11 @@ export class AdminComponent implements OnInit, OnDestroy {
return;
}
if (this.articleNotFound || !this.loadedArticle || this.loadedArticle.id !== Number(articleId)) {
alert('Article not found.');
return;
}
this.authService.validateToken().subscribe(valid => {
if (!valid) return;
@@ -162,18 +227,37 @@ export class AdminComponent implements OnInit, OnDestroy {
this.articleService.deleteArticle(Number(articleId), token).subscribe(
() => {
alert(`Article ${articleId} deleted successfully`);
this.resetArticleFormState();
this.articleIdValue = null;
this.loadArticles();
},
error => {
if (error.status === 404) {
this.markArticleNotFound();
alert('Article not found.');
} else {
alert(`Error deleting article ${articleId}: ${error.message}`);
}
console.error(error);
}
);
});
}
navigateToArticle(slug: string): void {
void this.router.navigate([`/blog/${slug}`]);
loadArticleIntoEditor(article: Article) {
this.setMode('edit');
this.articleIdValue = article.id;
this.loadedArticle = article;
this.originalTitle = article.title ?? '';
this.originalContent = article.content ?? '';
this.title = this.originalTitle;
this.content = this.originalContent;
this.editArticleLoaded = true;
this.loadingEditArticle = false;
this.articleNotFound = false;
}
loadArticles(): void {
@@ -259,6 +343,19 @@ export class AdminComponent implements OnInit, OnDestroy {
return true;
}
onArticleIdChange(value: number | null): void {
if (this.articleMode !== 'edit' && this.articleMode !== 'delete') return;
const id = Number(value);
if (!value || isNaN(id) || id < 1) {
this.resetArticleFormState();
return;
}
this.loadArticleById(id);
}
submitUser(form: NgForm): void {
const { userId, username, password } = form.value;
@@ -376,27 +473,120 @@ export class AdminComponent implements OnInit, OnDestroy {
this.isDropdownOpen = !this.isDropdownOpen;
}
resetArticleFormState(): void {
this.loadedArticle = null;
this.editArticleLoaded = false;
this.loadingEditArticle = false;
this.articleNotFound = false;
this.originalTitle = '';
this.originalContent = '';
this.title = '';
this.content = '';
}
markArticleNotFound(): void {
this.resetArticleFormState();
this.articleNotFound = true;
}
setMode(mode: 'create' | 'edit' | 'delete') {
this.articleMode = mode;
this.isDropdownOpen = false;
this.articleIdValue = null;
this.resetArticleFormState();
}
submitArticle(form: NgForm) {
if (form.invalid) return;
loadArticleById(articleId: number): void {
if (!articleId || isNaN(Number(articleId))) {
this.resetArticleFormState();
return;
}
const { title, articleId, content } = form.value;
const mode = this.articleMode;
this.loadingEditArticle = true;
this.articleNotFound = false;
this.editArticleLoaded = false;
if (mode === 'create') {
this.createArticle(title, content);
} else if (mode === 'edit') {
this.editArticle(articleId, title, content);
} else if (mode === 'delete') {
this.deleteArticle(articleId);
const token = this.authService.token;
this.articleService.getArticleById(articleId, token).subscribe({
next: (article) => {
this.loadingEditArticle = false;
if (!article) {
this.markArticleNotFound();
return;
}
this.loadedArticle = article;
this.originalTitle = article.title ?? '';
this.originalContent = article.content ?? '';
if (this.articleMode === 'edit') {
this.title = this.originalTitle;
this.content = this.originalContent;
this.editArticleLoaded = true;
}
},
error: (error) => {
console.error('Failed to load article for editing', error);
this.markArticleNotFound();
}
});
}
get hasArticleChanges(): boolean {
return this.title !== this.originalTitle || this.content !== this.originalContent;
}
isArticleSubmitDisabled(): boolean {
if (this.loadingEditArticle) {
return true;
}
if (this.articleMode === 'create') {
return !this.title?.trim() || !this.content?.trim();
}
if (this.articleMode === 'edit') {
return !this.articleIdValue || !this.editArticleLoaded || this.articleNotFound || !this.hasArticleChanges;
}
if (this.articleMode === 'delete') {
return !this.articleIdValue || this.articleNotFound || !this.loadedArticle;
}
return true;
}
submitArticle() {
if (this.articleMode === 'create') {
this.createArticle(this.title, this.content);
} else if (this.articleMode === 'edit') {
this.editArticle(Number(this.articleIdValue), this.title, this.content);
} else if (this.articleMode === 'delete') {
this.deleteArticle(Number(this.articleIdValue));
}
}
openShortenerModal() {
this.isShortenerModalOpen = true;
}
onContentClick(event: MouseEvent) {
const target = event.target as HTMLElement;
if (target.tagName === 'IMG') {
const img = target as HTMLImageElement;
this.openPreview(img.src);
}
}
openPreview(src: string) {
this.selectedImage = src;
}
closePreview() {
this.selectedImage = null;
}
}
+2
View File
@@ -7,6 +7,7 @@ import {AuthService} from './shared/services/auth.service';
import {AuthInterceptor} from './auth.interceptor';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import { provideMarkdown } from 'ngx-markdown';
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, '/i18n/', '.json');
@@ -24,6 +25,7 @@ export const appConfig: ApplicationConfig = {
),
provideClientHydration(withEventReplay()),
provideHttpClient(),
provideMarkdown(),
AuthService,
AuthInterceptor,
importProvidersFrom(
+4 -4
View File
@@ -11,8 +11,8 @@ import {SocialsComponent} from './socials/socials.component';
// import {TosComponent} from './tos/tos.component';
import {ImprintComponent} from './imprint/imprint.component';
import {PrivacyComponent} from './privacy/privacy.component';
import {SuccessComponent} from './checkout/success/success.component';
import {CancelComponent} from './checkout/cancel/cancel.component';
// import {SuccessComponent} from './checkout/success/success.component';
// import {CancelComponent} from './checkout/cancel/cancel.component';
export const routes: Routes = [
{ path: '', component: AboutComponent },
@@ -27,7 +27,7 @@ export const routes: Routes = [
{ path: 'privacy', component: PrivacyComponent },
{ path: 'imprint', component: ImprintComponent },
{ path: 'blog/:slug', component: ArticlePageComponent },
{ path: 'checkout/success', pathMatch: 'full', component: SuccessComponent },
{ path: 'checkout/cancel', pathMatch: 'full', component: CancelComponent },
// { path: 'checkout/success', pathMatch: 'full', component: SuccessComponent },
// { path: 'checkout/cancel', pathMatch: 'full', component: CancelComponent },
{ path: '**', pathMatch: 'full', component: NotFoundComponent }
];
@@ -19,12 +19,15 @@
.content-container {
display: inline-grid;
max-width: 960px;
text-align: left;
}
h1 {
font-size: 2.5rem;
color: #fff;
background: linear-gradient(to top, #a0eddb 0%, #ffffff 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
margin-top: 120px;
margin-bottom: 40px;
font-weight: 600;
@@ -32,22 +35,33 @@ h1 {
.article-content {
font-size: 1.2rem;
color: #fff;
color: #ffffff;
line-height: 1.8;
margin-bottom: 30px;
}
.article-content h1, .article-content h2, .article-content h3, .article-content h4, .article-content h5, .article-content h6 {
color:white;
margin: 0;
}
.article-meta {
font-size: 1rem;
color: #e6e6e6;
color: #D6DAEFBD;
text-align: left;
margin: 25px 0;
}
.article-meta p {
margin: 8px 0;
}
.content-container button {
.article-buttons {
display: flex;
align-items: center;
}
.article-buttons button {
background-color: #444893FF;
color: #fff;
border: none;
@@ -57,13 +71,34 @@ h1 {
border-radius: 25px;
transition: background-color 0.3s;
font-weight: 400;
margin-bottom: 20px;
}
.content-container button:hover {
.article-buttons button:hover {
background-color: #707ec5;
}
#shareBtn {
background-color: transparent;
font-size: 1.5rem;
margin: 0;
transition: all ease-in-out 0.2s;
}
#shareBtn:hover {
color: #cfd7f8;
}
#shareBtn.copied {
color: #8798dc;
}
.back-btn {
display: flex;
width: 100%;
margin-right: 64px;
justify-content: center;
}
.error-message h1 {
font-size: 10rem;
margin: 0;
@@ -138,6 +173,10 @@ h1 {
object-fit: cover;
}
.article-content .centered-text {
text-align: center;
}
.modal {
position: fixed;
top: 0;
@@ -16,17 +16,21 @@
<div class="article-container">
<div>
<h1>{{ article.title }}</h1>
<div class="content-container">
<div
#articleContent
<div class="content-container" [ngStyle]="{'width': isNarrow ? '100%' : '70%'}">
<markdown
class="article-content"
[innerHTML]="article.content"
[data]="renderedContent"
(click)="onArticleContentClick($event)"
></div>
<a href="/blog"><button>{{ 'ARTICLE_BACK' | translate }}</button></a>
></markdown>
<div class="article-buttons">
<button id="shareBtn" (click)="copyLink()" [class.copied]="copied" class="fa-solid fa-share"></button>
<div class="back-btn">
<a href="/blog"><button id="backBtn">{{ 'ARTICLE_BACK' | translate }}</button></a>
</div>
</div>
<div class="article-meta">
<p><strong>Author:</strong> {{ article.authorName}}</p>
<p><strong>Views:</strong> {{ article.views }}</p><br><button (click)="copyLink()" [ngStyle]="{'background-color':copied ? '#22b34b' : ''}">{{ copied ? 'Copied' : 'Share' }}</button>
<p><strong>Views:</strong> {{ article.views }}</p>
<p><strong>{{ 'CREATED_AT' | translate }}</strong> {{ article.createdAt | date:'MMM dd, yyyy, HH:mm' }}</p>
</div>
</div>
@@ -5,6 +5,8 @@ import {ActivatedRoute} from '@angular/router';
import {Title} from '@angular/platform-browser';
import {TranslatePipe} from '@ngx-translate/core';
import {ParallaxComponent} from '../../shared/parallax/parallax.component';
import {MarkdownModule} from 'ngx-markdown';
import {ViewportService} from '../../shared/services/viewport.service';
interface Article {
id: number;
@@ -25,7 +27,8 @@ interface Article {
DatePipe,
NgStyle,
TranslatePipe,
ParallaxComponent
ParallaxComponent,
MarkdownModule
],
templateUrl: './article-page.component.html',
styleUrl: './article-page.component.css'
@@ -38,10 +41,15 @@ export class ArticlePageComponent implements OnInit {
copied: boolean = false;
loading: boolean = true;
renderedContent: string = '';
isNarrow: boolean = false;
constructor(
private articleService: ArticleService,
private titleService: Title,
private route: ActivatedRoute
private route: ActivatedRoute,
private viewportService: ViewportService
) {
}
@@ -53,6 +61,8 @@ export class ArticlePageComponent implements OnInit {
this.error = false;
this.article = null;
this.isNarrow = this.viewportService.isNarrow;
if (!slug) {
this.titleService.setTitle('Error | itzMiney');
return;
@@ -68,6 +78,7 @@ export class ArticlePageComponent implements OnInit {
}
this.article = article;
this.renderedContent = this.transformCustomBlocks(article.content);
this.titleService.setTitle(`${article.title} | itzMiney`);
this.loading = false;
},
@@ -93,6 +104,35 @@ export class ArticlePageComponent implements OnInit {
}
}
transformCustomBlocks(content: string): string {
let result = content;
result = result.replace(
/\[gallery\]\s*([\s\S]*?)\s*\[\/gallery\]/g,
(_, inner) => {
const urls = inner
.split('\n')
.map((line: string) => line.trim())
.filter((line: string) => line.length > 0);
const images = urls
.map((url: string) => `<img src="${url}" alt="Gallery image">`)
.join('');
return `<div class="gallery">${images}</div>`;
}
);
result = result.replace(
/\[center\]\s*([\s\S]*?)\s*\[\/center\]/g,
(_, inner) => {
return `<div class="centered-text">${inner}</div>`;
}
);
return result;
}
openPreview(src: string) {
this.selectedImage = src;
}
@@ -0,0 +1,193 @@
.markdown-editor {
display: flex;
flex-direction: column;
width: 100%;
box-sizing: border-box;
background: #26262c;
border-radius: 24px;
}
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
background: #26262c;
border-radius: 24px 24px 0 0;
box-sizing: border-box;
padding: 0 20px;
}
.toolbar-left {
display: flex;
flex-wrap: wrap;
gap: 0;
min-width: 0;
}
.toolbar-right {
display: flex;
flex-shrink: 0;
margin-left: auto;
}
.toolbar.mobile {
flex-direction: column;
align-items: stretch;
}
.toolbar.mobile .toolbar-left {
width: 100%;
}
.toolbar.mobile .toolbar-right {
width: 100%;
margin-left: 0;
justify-content: flex-end;
}
.toolbar button {
width: auto;
white-space: nowrap;
margin: 5px;
background: transparent;
border: none;
color: white;
font-size: 0.9rem;
font-family: "Roboto", sans-serif;
padding: 8px 12px;
cursor: pointer;
border-radius: 12px;
}
.toolbar button:hover {
background: #2c2c33;
}
.preview-toggle button {
margin-left: auto;
}
.toolbar-right button {
background-color: #202025;
}
.separator {
width: 5px;
border-radius: 2px;
margin: 5px 0;
background: #202025;
}
.editor-textarea,
.preview {
order: 2;
}
textarea {
width: calc(100% - 10px);
margin: 0 5px;
resize: none;
overflow-x: hidden;
overflow-y: auto;
border: none;
box-sizing: border-box;
border-radius: 20px;
background: #202025;
color: white;
padding: 15px 20px;
font-family: monospace;
}
textarea:focus {
outline: none;
background: #2b2b32;
}
.preview {
width: calc(100% - 10px);
height: calc(100% - 49px);
margin-left: 5px;
text-align: left;
padding: 0 20px;
border-radius: 20px;
background: #2b2b32;
box-sizing: border-box;
font-family: Roboto, sans-serif;
overflow-x: hidden;
overflow-y: auto;
}
textarea:disabled, .toolbar button:disabled {
background-color: rgba(28, 21, 21, 0.4);
cursor: not-allowed;
}
::ng-deep h1, ::ng-deep h2, ::ng-deep h3, ::ng-deep h4, ::ng-deep h6 {
color: #9993b3;
}
::ng-deep a {
text-decoration: underline;
color: #C985DFFF;
}
::ng-deep a:visited {
color: #8E44A39E;
}
::ng-deep a:hover {
color: #df59ff;
}
::ng-deep a:active {
color: #eea9ff;
}
::ng-deep .centered-text {
text-align: center;
}
::ng-deep img {
max-width: 90%;
padding: 15px;
border-radius: 35px;
height: auto;
box-sizing: border-box;
}
::ng-deep .gallery {
display: grid;
max-width: 90vw;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
margin: auto;
padding: 15px;
}
::ng-deep .gallery img {
width: 100%;
height: auto;
border-radius: 20px;
object-fit: cover;
}
@media (max-width: 768px) {
::ng-deep .gallery img {
flex: 1 1 calc(50% - 15px);
}
}
@media (max-width: 480px) {
::ng-deep .gallery img {
gap: 0;
padding: 0;
flex: 1 1 100%;
}
}
@media (max-width: 480px) {
::ng-deep img {
max-width: 98%;
}
}
@@ -0,0 +1,118 @@
<div
class="markdown-editor"
[class.disabled]="disabled"
[ngStyle]="{'height': isNarrow ? 'calc(100% - 280px)' : 'calc(100% - 75px)'}"
>
@if (!previewMode) {
<textarea
#editorRef
class="editor-textarea"
[value]="value"
[placeholder]="placeholder"
[disabled]="disabled"
(input)="onInput(editorRef.value)"
(blur)="markTouched()"
[ngStyle]="{'height': isNarrow ? 'calc(100% - 192px)' : 'calc(100% - 49px)'}"
></textarea>
<div class="toolbar" [class.mobile]="isNarrow">
<div class="toolbar-left">
<button type="button" (click)="insertAtCursor(editorRef, '**', '**', 'bold')" [disabled]="disabled">
<strong>B</strong>
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertAtCursor(editorRef, '*', '*', 'italic')" [disabled]="disabled">
<em>I</em>
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertLinePrefix(editorRef, '# ')" [disabled]="disabled">
H1
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertLinePrefix(editorRef, '## ')" [disabled]="disabled">
H2
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertLinePrefix(editorRef, '- ')" [disabled]="disabled">
• List
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertLinePrefix(editorRef, '1. ')" [disabled]="disabled">
1. List
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertLink(editorRef)" [disabled]="disabled">
Link
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertImage(editorRef)" [disabled]="disabled">
Image
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertCenter(editorRef)" [disabled]="disabled">
Center
</button>
@if (!isNarrow) {
<div class="separator"></div>
}
<button type="button" (click)="insertGallery(editorRef)" [disabled]="disabled">
Gallery
</button>
</div>
<div class="toolbar-right">
<button type="button" class="preview-toggle" (click)="togglePreview()">
Preview
</button>
</div>
</div>
}
@if (previewMode) {
<div class="toolbar">
<div class="toolbar-right">
<button type="button" class="preview-toggle" (click)="togglePreview()">
Raw Markdown
</button>
</div>
</div>
<div class="preview">
<markdown [data]="previewContent"></markdown>
</div>
}
</div>
@@ -0,0 +1,221 @@
import {Component, forwardRef, OnInit} from '@angular/core';
import { CommonModule } from '@angular/common';
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
import {MarkdownModule} from 'ngx-markdown';
import { ViewportService} from '../services/viewport.service';
@Component({
selector: 'app-markdown-editor',
imports: [CommonModule, FormsModule, MarkdownModule],
templateUrl: './markdown-editor.component.html',
styleUrl: './markdown-editor.component.css',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MarkdownEditorComponent),
multi: true,
},
],
})
export class MarkdownEditorComponent implements ControlValueAccessor, OnInit {
value = '';
placeholder = 'Write your article content here...';
previewMode = false;
disabled = false;
isNarrow: boolean = false;
constructor(private viewportService: ViewportService) { }
private onChange: (value: string) => void = () => {};
private onTouched: () => void = () => {};
ngOnInit() {
this.isNarrow = this.viewportService.isNarrow;
}
writeValue(value: string | null): void {
this.value = value ?? '';
}
registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onInput(value: string): void {
this.value = value;
this.onChange(this.value);
}
markTouched(): void {
this.onTouched();
}
togglePreview(): void {
this.previewMode = !this.previewMode;
}
insertAtCursor(
textarea: HTMLTextAreaElement,
before: string,
after = '',
placeholder = 'text'
): void {
if (this.disabled) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selectedText = this.value.slice(start, end);
const replacement = `${before}${selectedText || placeholder}${after}`;
this.value =
this.value.slice(0, start) +
replacement +
this.value.slice(end);
this.onChange(this.value);
this.onTouched();
queueMicrotask(() => {
textarea.focus();
const cursorStart = start + before.length;
const cursorEnd = selectedText ? start + replacement.length : cursorStart + placeholder.length;
textarea.setSelectionRange(cursorStart, cursorEnd);
});
}
insertLinePrefix(textarea: HTMLTextAreaElement, prefix: string): void {
if (this.disabled) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const beforeSelection = this.value.slice(0, start);
const afterSelection = this.value.slice(end);
const selectionStartLine = beforeSelection.lastIndexOf('\n') + 1;
const fullSelectedBlock = this.value.slice(selectionStartLine, end);
const updatedBlock = fullSelectedBlock
.split('\n')
.map(line => (line.trim().length ? `${prefix}${line}` : line))
.join('\n');
this.value =
this.value.slice(0, selectionStartLine) +
updatedBlock +
afterSelection;
this.onChange(this.value);
this.onTouched();
queueMicrotask(() => {
textarea.focus();
textarea.setSelectionRange(selectionStartLine, selectionStartLine + updatedBlock.length);
});
}
insertLink(textarea: HTMLTextAreaElement): void {
if (this.disabled) return;
const url = window.prompt('Enter URL:', 'https://');
if (!url) return;
this.insertAtCursor(textarea, '[', `](${url})`, 'link text');
}
insertImage(textarea: HTMLTextAreaElement): void {
if (this.disabled) return;
const url = window.prompt('Enter image URL:', 'https://');
if (!url) return;
const alt = window.prompt('Enter alt text:', 'image') || 'image';
this.insertAtCursor(textarea, `![${alt}](`, ')', url);
}
insertCenter(textarea: HTMLTextAreaElement): void {
this.insertAtCursor(textarea, '[center]\n', '\n[/center]', 'centered text');
}
insertGallery(textarea: HTMLTextAreaElement): void {
if (this.disabled) return;
const template = [
'[gallery]',
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
'[/gallery]'
].join('\n');
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selectedText = this.value.slice(start, end).trim();
const replacement = selectedText
? `[gallery]\n${selectedText}\n[/gallery]`
: template;
this.value =
this.value.slice(0, start) +
replacement +
this.value.slice(end);
this.onChange(this.value);
this.onTouched();
queueMicrotask(() => {
textarea.focus();
if (selectedText) {
textarea.setSelectionRange(start, start + replacement.length);
} else {
const firstUrlStart = start + '[gallery]\n'.length;
const firstUrlEnd = firstUrlStart + 'https://example.com/image1.jpg'.length;
textarea.setSelectionRange(firstUrlStart, firstUrlEnd);
}
});
}
get previewContent(): string {
return this.transformCustomBlocks(this.value);
}
transformCustomBlocks(content: string): string {
let result = content;
result = result.replace(
/\[gallery\]\s*([\s\S]*?)\s*\[\/gallery\]/g,
(_, inner) => {
const urls = inner
.split('\n')
.map((line: string) => line.trim())
.filter((line: string) => line.length > 0);
const images = urls
.map((url: string) => `<img src="${url}" alt="Gallery image">`)
.join('');
return `<div class="gallery">${images}</div>`;
}
);
result = result.replace(
/\[center\]\s*([\s\S]*?)\s*\[\/center\]/g,
(_, inner) => `<div class="centered-text">${inner}</div>`
);
return result;
}
}
+16 -8
View File
@@ -28,14 +28,20 @@ export class ArticleService {
return this.http.get<Article[]>(`${this.apiUrl}?timestamp=${new Date().getTime()}`);
}
getArticleBySlug(slug: string): Observable<Article |undefined> {
return this.http.get<Article>(`${this.apiUrl}/slug/${slug}`).pipe(
getArticleBySlug(slug: string, token?: string | null): Observable<Article |undefined> {
const options = token
? { headers: new HttpHeaders().set('Authorization', `Bearer ${token}`) }
: {};
return this.http.get<Article>(`${this.apiUrl}/slug/${slug}`, options).pipe(
map(article => article)
);
}
getArticleById(id: number): Observable<Article |undefined> {
return this.http.get<Article>(`${this.apiUrl}/id/${id}`).pipe(
getArticleById(id: number, token?: string | null): Observable<Article |undefined> {
const options = token
? { headers: new HttpHeaders().set('Authorization', `Bearer ${token}`) }
: {};
return this.http.get<Article>(`${this.apiUrl}/id/${id}`, options).pipe(
map(article => article)
);
}
@@ -61,10 +67,12 @@ export class ArticleService {
);
}
editArticle(id: number, token: string | null, title: string, content: string): Observable<any> {
editArticle(
id: number,
token: string | null,
updates: { title?: string; content?: string }
): Observable<any> {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
const body = { title, content };
return this.http.put<any>(`${this.apiUrl}/${id}`, body, { headers });
return this.http.put<any>(`${this.apiUrl}/${id}`, updates, { headers });
}
}