修改路径

This commit is contained in:
小海
2020-05-16 22:18:45 +08:00
parent abc792a561
commit 42177a7721
683 changed files with 92 additions and 18398 deletions

View File

@@ -0,0 +1,91 @@
<form nz-form [formGroup]="formGroup" (ngSubmit)="publishArticle()">
<!-- 文章类型 -->
<nz-form-item *ngIf="primaryData.id">
<nz-form-label nzSpan="4">发布为</nz-form-label>
<nz-form-control nzSpan="19" nzOffset="1" nzErrorTip="请选择文章发布类型">
<nz-radio-group formControlName="isUpdate">
<label nz-radio-button [nzValue]="false"><span>新文章</span></label>
<label nz-radio-button [nzValue]="true"><span>更新旧文章</span></label>
</nz-radio-group>
</nz-form-control>
</nz-form-item>
<!-- 文章类型 -->
<nz-form-item>
<nz-form-label nzSpan="4">文章类型</nz-form-label>
<nz-form-control nzSpan="19" nzOffset="1" nzErrorTip="请选择文章的类型">
<nz-radio-group formControlName="type" (ngModelChange)="articleTypeChanged()">
<label nz-radio-button [nzValue]="true"><span>原创</span></label>
<label nz-radio-button [nzValue]="false"><span>转载</span></label>
</nz-radio-group>
</nz-form-control>
</nz-form-item>
<!-- 标签 -->
<nz-form-item>
<nz-form-label [nzSpan]="4" (click)="showTagInput()">文章标签</nz-form-label>
<nz-form-control [nzSpan]="19" [nzOffset]="1">
<input formControlName="tagList" style="display: none">
<nz-tag *ngFor="let t of tagTmpList" nzMode="closeable"
(nzOnClose)="handleClose(t)">{{t}}</nz-tag>
<nz-tag *ngIf="!tagInputVisible&&tagTmpList.length<5" (click)="showTagInput()">
<i nz-icon nzType="plus"></i> New Tag
</nz-tag>
<input #inputElement nz-input nzSize="small" *ngIf="tagInputVisible" formControlName="tags"
type="text" style="width: 78px;" (blur)="handleTagInputConfirm()"
(keydown.enter)="handleTagInputConfirm()">
<div *ngIf="tagListTouched&&formGroup.get('tagList').hasError('required')"
class="errTip">未选择或添加标签
</div>
<nz-card nzSize="small" nzTitle="已有标签" title="最多可选五个标签">
<nz-tag *ngFor="let tag of tagNacList"
style="margin: 4px; border: 1px dashed #6A6A6A;user-select: none"
[nzMode]="(tagTmpList.length<5||tagTmpList.indexOf(tag.name) > -1)?'checkable':'default'"
[nzChecked]="tagTmpList.indexOf(tag.name) > -1"
(nzCheckedChange)="tagChange($event,tag.name)">
{{ tag.name }}
</nz-tag>
</nz-card>
</nz-form-control>
</nz-form-item>
<!-- 文章分类 -->
<nz-form-item>
<nz-form-label nzSpan="4">文章分类</nz-form-label>
<nz-form-control nzSpan="19" nzOffset="1" nzErrorTip="文章的分类不可为空">
<nz-select nzAllowClear nzPlaceHolder="选择分类" formControlName="category">
<nz-option *ngFor="let option of categoryList" [nzValue]="option.name"
[nzLabel]="option.name"></nz-option>
</nz-select>
</nz-form-control>
</nz-form-item>
<!-- 原文链接 -->
<nz-form-item *ngIf="!formGroup.value.type">
<nz-form-label nzSpan="4">原文链接</nz-form-label>
<nz-form-control nzSpan="19" nzOffset="1">
<nz-input-group [nzSuffix]="close">
<input nz-input type="url" placeholder="请输入原文连接" formControlName="url">
</nz-input-group>
<ng-template #close>
<i *ngIf="formGroup.value.url" nz-icon nzType="close-circle" nzTheme="fill"
(click)="clearInput()"></i>
</ng-template>
<div *ngIf="formGroup.get('url').touched&&formGroup.get('url').hasError('required')"
class="errTip">原文链接不可为空
</div>
<div *ngIf="formGroup.get('url').touched&&formGroup.get('url').hasError('pattern')"
class="errTip">原文链接不合法
</div>
</nz-form-control>
</nz-form-item>
<button nz-button style="width: 100%" nzType="primary"
type="submit" [disabled]="!formGroup.valid">提交
</button>
</form>

View File

@@ -0,0 +1,4 @@
.errTip {
color: #f5222d;
line-height: 30px;
}

View File

@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestComponent } from './publish-form.component';
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TestComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,108 @@
import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Tag} from '../../../../class/Tag';
@Component({
selector: 'c-publish-form',
templateUrl: './publish-form.component.html',
styleUrls: ['./publish-form.component.less']
})
export class PublishFormComponent implements OnInit {
constructor(private fb: FormBuilder) {
}
@ViewChild('inputElement', {static: false}) tagInputElement: ElementRef;
@Input() tagNacList: { name: string, size: number }[];
@Input() categoryList: Tag[];
@Input() primaryData: { id: number, type: boolean, tags: string, category: string, url?: string };
@Output() submitEvent = new EventEmitter<{ id: number, type: boolean, tags: string, category: string, url?: string }>();
formGroup: FormGroup;
tagTmpList: string[] = [];
tagInputVisible: boolean = false;
tagListTouched: boolean = false;
ngOnInit(): void {
this.formGroup = this.fb.group({
isUpdate: [true, Validators.required],
type: [true, Validators.required],
tagList: [null, Validators.required],
tags: [null],
category: [null, Validators.required],
url: [null]
});
if (this.primaryData) {
this.formGroup.get('type').setValue(this.primaryData.type);
const tags = this.primaryData.tags;
this.formGroup.get('tagList').setValue(tags ? this.primaryData.tags.split(',') : tags);
this.tagTmpList = tags ? this.primaryData.tags.split(',') : [...tags];
this.formGroup.get('category').setValue(this.primaryData.category);
this.formGroup.get('url').setValue(this.primaryData.url);
}
}
publishArticle() {
const formData = {
id: this.formGroup.value.isUpdate ? this.primaryData.id : null,
type: this.formGroup.value.type,
tags: this.formGroup.value.tagList.toString(),
category: this.formGroup.value.category,
url: this.formGroup.value.type ? null : this.formGroup.value.url
};
this.submitEvent.emit(formData);
}
// 点击New Tag 显示输入框
showTagInput() {
this.tagInputVisible = true;
setTimeout(() => {
this.tagInputElement.nativeElement.focus();
}, 10);
}
// 点击标签右侧的x
handleClose(t: string) {
this.tagTmpList = this.tagTmpList.filter(tag => tag !== t);
this.formGroup.get('tagList').setValue(this.tagTmpList);
}
// 输入框输入完成
handleTagInputConfirm() {
this.tagListTouched = true;
const tmpTag = this.formGroup.get('tags').value;
if (tmpTag && this.tagTmpList.indexOf(tmpTag) === -1) {
this.tagTmpList = [...this.tagTmpList, tmpTag];
}
this.formGroup.get('tags').setValue('');
this.formGroup.get('tagList').setValue(this.tagTmpList.length ? this.tagTmpList : null);
this.formGroup.get('tagList').updateValueAndValidity();
this.tagInputVisible = false;
}
// 点击tag切换
tagChange($event: boolean, name: string) {
this.tagListTouched = true;
if (this.tagTmpList.indexOf(name) > -1) {
this.tagTmpList = this.tagTmpList.filter(v => v !== name);
} else {
this.tagTmpList.push(name);
}
this.formGroup.get('tagList').setValue(this.tagTmpList.length ? this.tagTmpList : null);
this.formGroup.get('tagList').updateValueAndValidity();
}
// 清除url内容
clearInput() {
this.formGroup.get('url').setValue('');
}
// 点选了文章类型
articleTypeChanged() {
this.formGroup.get(`url`).clearValidators();
const type = this.formGroup.get(`type`).value;
this.formGroup.get(`url`).setValidators(type ? null : [Validators.required, Validators.pattern('^(https:\/\/|http:\/\/|)([\\w-]+\\.)+[\\w-]+(\\/[\\w-./?%&=]*)?$')]);
this.formGroup.get(`url`).updateValueAndValidity();
}
}

View File

@@ -0,0 +1,8 @@
import { EditorMdDirective } from './editor-md.directive';
describe('EditorMdDirective', () => {
it('should create an instance', () => {
const directive = new EditorMdDirective();
expect(directive).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import {AfterViewInit, Attribute, Directive, EventEmitter, Input, Output} from '@angular/core';
import {EditorConfig} from '../../../class/EditorConfig';
declare var editormd: any;
declare var $: any;
@Directive({
selector: '[appEditorMd]'
})
export class EditorMdDirective implements AfterViewInit {
@Input() editormdConfig: EditorConfig; // 配置选项
@Output() onEditorChange: EventEmitter<string> = new EventEmitter<string>(); // 发射器
editor: any; // editormd编辑器
constructor(@Attribute('id') private id: string) {
}
ngAfterViewInit(): void {
this.editor = editormd(this.id, this.editormdConfig); // 创建编辑器
const out = this.onEditorChange;
const textarea = $('#' + this.id + ' :first'); // 获取textarea元素
// 当编辑器内容改变时触发textarea的change事件
// tslint:disable-next-line:only-arrow-functions
this.editor.on('change', function() {
out.emit(textarea.val());
});
}
}

View File

@@ -0,0 +1,25 @@
<div class="main">
<div class="con">
<input type="text" [(ngModel)]="article.title" id="title" placeholder="文章标题">
<button nz-button nzType="primary" id="submit" (click)="articleSubmit()">提交</button>
</div>
<div id="md" appEditorMd [editormdConfig]="conf" (onEditorChange)="syncModel($event)">
<textarea style="display: block;" [(ngModel)]="article.mdContent"></textarea>
</div>
</div>
<nz-modal [(nzVisible)]="modalVisible" [nzTitle]="title" [nzContent]="content" [nzFooter]="null"
(nzOnCancel)="modalVisible = false">
<ng-template #title>
<h3 style="text-align: center">文章发布</h3>
</ng-template>
<ng-template #content>
<c-publish-form [categoryList]="categoryList" [tagNacList]="tagNacList" [primaryData]="primaryData"
(submitEvent)="publishArticle($event)">
</c-publish-form>
</ng-template>
</nz-modal>

View File

@@ -0,0 +1,34 @@
.main {
z-index: 10;
position: absolute;
left: 0;
right: 0;
top: 70px;
bottom: 0;
.con {
display: flex;
flex-wrap: wrap;
#title {
/* 85% */
flex-grow: 1;
margin: 0 20px 5px 20px;
height: 35px;
border-radius: 5px;
border: none;
padding-left: 6px;
}
#submit {
display: flex;
flex-wrap: wrap
}
}
#md {
position: relative;
}
}

View File

@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { WriteComponent } from './write.component';
describe('WriteComponent', () => {
let component: WriteComponent;
let fixture: ComponentFixture<WriteComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ WriteComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(WriteComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,207 @@
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ArticleReq} from '../../class/Article';
import {EditorConfig} from '../../class/EditorConfig';
import {ActivatedRoute, Router} from '@angular/router';
import {ApiService} from '../../api/api.service';
import {NzMessageService} from 'ng-zorro-antd';
import {User} from '../../class/User';
import {Tag} from '../../class/Tag';
import {Title} from '@angular/platform-browser';
import {GlobalUserService} from '../../services/global-user.service';
@Component({
selector: 'view-write',
templateUrl: './write.component.html',
styleUrls: ['./write.component.less']
})
export class WriteComponent implements OnInit {
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private apiService: ApiService,
private userService: GlobalUserService,
private message: NzMessageService,
private titleService: Title) {
this.titleService.setTitle('小海博客 | 创作');
}
modalVisible: boolean = false;
conf = new EditorConfig();
articleId: number;
isUpdate = false;
public article: ArticleReq = new ArticleReq();
userInfo: User;
categoryList: Tag[];
tagNacList: { name: string, size: number }[];
primaryData = {};
// 发布新文章时,文章相同会被拦回 此处判断一下
title: string;
private lastShowTime: number;
// 同步属性内容
syncModel(str): void {
this.article.mdContent = str;
}
ngOnInit(): void {
this.articleId = this.activatedRoute.snapshot.queryParams.id;
if (this.articleId != null) {
this.isUpdate = true;
this.getArticle();
}
if (!this.articleId && localStorage.getItem('tmpArticle')) {
this.article = JSON.parse(localStorage.getItem('tmpArticle'));
}
this.setSuitableHeight();
// 用户权限判断
this.userService.watchUserInfo({
complete: () => null,
error: (err) => {
if (!this.lastShowTime || Date.now() - this.lastShowTime > 1000) {
this.message.info('你暂时还没有登录,请点击右上角登录后开始创作');
this.lastShowTime = Date.now();
}
},
next: data => {
this.userInfo = data.result;
if ((!data.result || data.result.role !== 'admin')
&& (!this.lastShowTime || Date.now() - this.lastShowTime > 1000)) {
this.message.info('你暂时无发布文章的权限,所写文章将暂存在本地');
}
}
})
;
this.apiService.tagsNac().subscribe(data => {
this.tagNacList = data.result;
this.tagNacList.sort((a, b) => a.name.length - b.name.length);
});
this.apiService.categories().subscribe({
next: data => {
this.categoryList = data.result;
},
error: err => {
this.message.error('获取分类信息失败');
}
});
}
/**
* 设置高度
*/
setSuitableHeight() {
this.conf.height = (window.innerHeight - 120) + '';
}
// 提交按钮的事件
articleSubmit() {
this.modalVisible = true;
if (this.article.title === '' || this.article.mdContent === '') {
this.message.warning(this.article.title === '' ? '标题不能为空' : '文章不能为空');
return;
}
}
/**
* 文章数据提交
*/
publishArticle(e: { id: number, type: boolean, tags: string, category: string, url?: string }) {
this.article.type = e.type;
this.article.tags = e.tags;
this.article.category = e.category;
this.article.url = e.url;
this.article.id = e.id;
if (!this.article.id && this.title === this.article.title) {
this.message.error('文章标题未经更改,请修改后再发布');
return;
}
// 文章 暂存
localStorage.setItem('tmpArticle', JSON.stringify(this.article));
this.article.url = this.article.type ? null : this.article.url;
if (!this.isUpdate) {
// 非文章更新
this.apiService.createArticle(this.article).subscribe({
next: data => {
// TODO 成功
this.message.success('发布成功,即将转跳');
localStorage.removeItem('tmpArticle');
setTimeout(() => {
this.router.navigateByUrl('article/' + data.result.id);
}, 2500);
},
error: err => {
if (err.code === 3010) {
// 未登陆
this.router.navigateByUrl('/user/login');
}
if (err.code === 3020) {
this.message.error('你没有发布文章的权限,文章替你暂存在本地');
}
}
});
} else {
// 文章更新
this.apiService.updateArticle(this.article).subscribe({
next: data => {
this.message.success('更新成功,即将转跳');
localStorage.removeItem('tmpArticle');
setTimeout(() => {
this.router.navigateByUrl('article/' + data.result.id);
}, 2500);
},
error: e => {
if (e.code === 3010) {
this.router.navigateByUrl('login');
} else if (e.code === 3020) {
this.message.error('你没有更新文章的权限');
} else {
this.message.error('失败,原因:' + e.msg);
}
}
});
}
}
/**
* 获取文章 for update
*/
getArticle() {
this.apiService.getArticle(this.articleId, true).subscribe({
next: data => {
this.article.category = data.result.category;
this.article.mdContent = data.result.mdContent;
this.article.tags = String(data.result.tags);
this.article.type = data.result.original;
this.article.url = data.result.url;
this.article.title = data.result.title;
this.article.id = data.result.id;
this.title = data.result.title;
this.primaryData = {
type: this.article.type,
tags: this.article.tags,
category: this.article.category,
url: this.article.url,
id: this.article.id
};
},
error: e => {
if (e.code === 2010) {
// 文章不存在
this.message.error('文章不存在');
}
}
});
}
}

View File

@@ -0,0 +1,44 @@
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {WriteComponent} from './write.component';
import {Route, RouterModule} from '@angular/router';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {EditorMdDirective} from './editor-md/editor-md.directive';
import {PublishFormComponent} from './components/publish-form/publish-form.component';
import {
NzButtonModule, NzCardModule, NzDividerModule,
NzFormModule,
NzIconModule,
NzInputModule,
NzModalModule,
NzRadioModule,
NzSelectModule,
NzTagModule
} from 'ng-zorro-antd';
const routes: Route[] = [
{path: '**', component: WriteComponent}
];
@NgModule({
declarations: [WriteComponent, EditorMdDirective, PublishFormComponent],
imports: [
CommonModule,
RouterModule.forChild(routes),
FormsModule,
NzButtonModule,
NzModalModule,
NzFormModule,
ReactiveFormsModule,
NzInputModule,
NzTagModule,
NzIconModule,
NzRadioModule,
NzSelectModule,
NzCardModule,
NzDividerModule,
]
})
export class WriteModule {
}