Created
June 16, 2017 08:37
-
-
Save toniqhz/d00db93c3a4944fdcfb9c80757eb86bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit, OnDestroy, ElementRef, Renderer } from '@angular/core'; | |
import { ActivatedRoute, Router } from '@angular/router'; | |
import { Location } from '@angular/common'; | |
import { FormBuilder, FormGroup } from '@angular/forms'; | |
// import { isBrowser } from 'angular2-universal'; | |
import { PLATFORM_ID, Inject } from '@angular/core'; | |
import { isPlatformBrowser, isPlatformServer } from '@angular/common'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/debounceTime'; | |
import * as _ from 'underscore'; | |
import { Post } from '../+post/post'; | |
import { Category } from '../+category/category'; | |
import { ITagsOfCategory } from '../../backend/tag/tagsOfCategory.model'; | |
import { User } from '../+user/user'; | |
import { CategoryService } from '../+category/category.service'; | |
import { PostService } from '../+post/post.service'; | |
import { AUTH_TOKEN_KEY } from '../shared/global/globals'; | |
import { MAXIMUM_POST_TAG_NUMBER } from '../shared/global/globals'; | |
import { EventEmitterService } from '../shared/event/event.service'; | |
import { AuthService } from '../shared/auth/auth.service'; | |
import { ApiService } from '../shared/api.service'; | |
// import { CacheService } from '../shared/cache.service'; | |
import { Meta, Title } from '@angular/platform-browser'; | |
declare var $: any; | |
@Component({ | |
selector: 'text-editor', | |
templateUrl: './text-editor.component.html' | |
}) | |
export class TextEditorComponent implements OnInit, OnDestroy { | |
thumbnail = process.env.AWS_WEB_ENDPOINT + '/sp-images/'; | |
editorForm: FormGroup; | |
post: Post; | |
categories: Category[]; | |
tags: ITagsOfCategory[]; | |
paramsSub: any; | |
post_slug: string; | |
draft_id: string; | |
selectedTags: Array<any>; | |
isShowTagsList: boolean = false; | |
isSelectedTagsMax: boolean = false; | |
categoryName = 'Chọn danh mục'; | |
isCollapsedCategory = false; | |
user: User; | |
contentError = ''; | |
categoryError = ''; | |
titleError = ''; | |
isDisabled = false; | |
isSaved: boolean = true; | |
isDataChanged = false; | |
constructor( | |
@Inject(PLATFORM_ID) private platformId: Object, | |
private _el: ElementRef, | |
private _renderer: Renderer, | |
private _route: ActivatedRoute, | |
private _router: Router, | |
private _location: Location, | |
private _fb: FormBuilder, | |
private _categoryService: CategoryService, | |
private _postService: PostService, | |
private _eventService: EventEmitterService, | |
private _meta: Meta, | |
private _title: Title, | |
private _auth: AuthService, | |
private _api: ApiService, | |
// private _cache: CacheService | |
) { | |
this.editorForm = this._fb.group({ | |
keyword: [''], | |
title: [''], | |
tagsSearch: [''], | |
description: [''] | |
}); | |
} | |
ngOnInit() { | |
this._eventService.emitEventCreatePost(true); | |
this.user = this._auth.user; | |
this.paramsSub = this._route.params.subscribe(params => { | |
this.post_slug = params['post_slug']; | |
this.draft_id = params['draft_id']; | |
}); | |
this._categoryService.getCategories() | |
.do(categories => { | |
this.categories = categories; | |
this.initData() | |
}) | |
.subscribe(results => {}); | |
this.editorForm.get('keyword') | |
.valueChanges | |
.debounceTime(500) | |
.subscribe(newKeyword => { | |
this._categoryService.getCategoriesByName(newKeyword) | |
.subscribe((categories: Category[]) => this.categories = categories) | |
}); | |
this.editorForm.get('tagsSearch') | |
.valueChanges | |
.debounceTime(500) | |
.subscribe(newKeyword => { | |
//todo search tags | |
this.searchTagsByName(newKeyword); | |
}); | |
if (isPlatformBrowser(this.platformId)) { | |
// var self = this; | |
// Froala: Section break button | |
$.FroalaEditor.DefineIcon('sectionBreak', { NAME: 'ellipsis-h' }); | |
$.FroalaEditor.RegisterCommand('sectionBreak', { | |
title: 'Add a New Section', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
console.log(this); | |
} | |
// refresh: function($btn) { | |
// $btn = $btn.get(0); | |
// let $img = this.selection.element(); | |
// if ($img.classList.contains('alignleft')) { | |
// let btns = $btn.parentNode.children; | |
// for(let i = 0; i < 5; i++) { | |
// btns[i].classList.remove('active'); | |
// } | |
// $btn.classList.add('active'); | |
// } | |
// } | |
}); | |
// Froala: Customized button for aligning the image | |
$.FroalaEditor.DefineIcon('imageLeft', { NAME: 'imageleft' }); | |
$.FroalaEditor.DefineIcon('imageRight', { NAME: 'imageright' }); | |
$.FroalaEditor.DefineIcon('imageCover', { NAME: 'imagecover' }); | |
$.FroalaEditor.DefineIcon('imageCenter', { NAME: 'imagecenter' }); | |
$.FroalaEditor.DefineIcon('imageFullScreen', { NAME: 'imagefullscreen' }); | |
$.FroalaEditor.RegisterCommand('imageLeft', { | |
title: 'Image Align Left', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if(!imageWrapper.classList.contains('alignleft')) { | |
imageWrapper.classList.remove('alignright', 'aligncover', 'aligncenter', 'fullscreen'); | |
imageWrapper.classList.add('alignleft'); | |
} | |
}, | |
refresh: function($btn) { | |
$btn = $btn.get(0); | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if (imageWrapper.classList.contains('alignleft')) { | |
let btns = $btn.parentNode.children; | |
for(let i = 0; i < 5; i++) { | |
btns[i].classList.remove('active'); | |
} | |
$btn.classList.add('active'); | |
} | |
} | |
}); | |
$.FroalaEditor.RegisterCommand('imageRight', { | |
title: 'Image Align Right', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if(!imageWrapper.classList.contains('alignright')) { | |
imageWrapper.classList.remove('alignleft', 'aligncover', 'aligncenter', 'fullscreen'); | |
imageWrapper.classList.add('alignright'); | |
} | |
}, | |
refresh: function($btn) { | |
$btn = $btn.get(0); | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if (imageWrapper.classList.contains('alignright')) { | |
let btns = $btn.parentNode.children; | |
for(let i = 0; i < 5; i++) { | |
btns[i].classList.remove('active'); | |
} | |
$btn.classList.add('active'); | |
} | |
} | |
}); | |
$.FroalaEditor.RegisterCommand('imageCover', { | |
title: 'Image Align Cover', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if(!imageWrapper.classList.contains('aligncover')) { | |
imageWrapper.classList.remove('alignleft', 'alignright', 'aligncenter', 'fullscreen'); | |
imageWrapper.classList.add('aligncover'); | |
} | |
}, | |
refresh: function($btn) { | |
$btn = $btn.get(0); | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if (imageWrapper.classList.contains('aligncover')) { | |
let btns = $btn.parentNode.children; | |
for(let i = 0; i < 5; i++) { | |
btns[i].classList.remove('active'); | |
} | |
$btn.classList.add('active'); | |
} | |
} | |
}); | |
$.FroalaEditor.RegisterCommand('imageCenter', { | |
title: 'Image Align Center', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if(!imageWrapper.classList.contains('aligncenter')) { | |
imageWrapper.classList.remove('alignleft', 'alignright', 'aligncover', 'fullscreen'); | |
imageWrapper.classList.add('aligncenter'); | |
} | |
}, | |
refresh: function($btn) { | |
$btn = $btn.get(0); | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if (imageWrapper.classList.contains('aligncenter')) { | |
let btns = $btn.parentNode.children; | |
for(let i = 0; i < 5; i++) { | |
btns[i].classList.remove('active'); | |
} | |
$btn.classList.add('active'); | |
} | |
} | |
}); | |
$.FroalaEditor.RegisterCommand('imageFullScreen', { | |
title: 'Image Full Screen', | |
focus: false, | |
undo: true, | |
refreshAfterCallback: true, | |
callback: function() { | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if(!imageWrapper.classList.contains('fullscreen')) { | |
imageWrapper.classList.remove('alignleft', 'alignright', 'aligncover', 'aligncenter'); | |
imageWrapper.classList.add('fullscreen'); | |
} | |
}, | |
refresh: function($btn) { | |
$btn = $btn.get(0); | |
let imageWrapper = this.image.get(0)[0].parentElement; | |
if (imageWrapper.classList.contains('fullscreen')) { | |
let btns = $btn.parentNode.children; | |
for(let i = 0; i < 5; i++) { | |
btns[i].classList.remove('active'); | |
} | |
$btn.classList.add('active'); | |
} | |
} | |
}); | |
} | |
} | |
initData() { | |
// this.getAllTags(); | |
if (this.post_slug) { | |
this._postService.getPost(this.post_slug, null).subscribe(result => { | |
this.selectedTags = result.post.tags; | |
if (this.selectedTags && this.selectedTags.length === MAXIMUM_POST_TAG_NUMBER) { | |
this.isSelectedTagsMax = true; | |
} | |
let body = result.post.body; | |
body = body.replace(/contenteditable="false"/g, 'contenteditable="true"') | |
this.post = { | |
title: result.post.title, | |
body: body, | |
type: result.post.type, | |
cat_id: result.post.cat_id._id, | |
post_id: result.post._id, | |
tags: this.selectedTags, | |
url_description: '', | |
content: '', | |
new_title: '', | |
description: result.post.description | |
}; | |
if (this.categories) { | |
for (var i = 0; i < this.categories.length; i++) { | |
if (this.categories[i]._id == this.post.cat_id) { | |
this.categoryName = this.categories[i].name; | |
} | |
} | |
} | |
if (isPlatformBrowser(this.platformId)) { | |
this._title.setTitle('Sửa bài - Spiderum'); | |
} | |
}); | |
} else if (this.draft_id) { | |
this._postService.getDraft(this.draft_id).subscribe((result: any) => { | |
let description = result.post ? result.post.description : ''; | |
this.post = { | |
title: result.title, | |
body: result.body, | |
type: result.type, | |
cat_id: result.cat_id, | |
draft_id: result._id, | |
url_description: '', | |
content: '', | |
new_title: '', | |
description: description | |
}; | |
if (this.categories) { | |
for (var i = 0; i < this.categories.length; i++) { | |
if (this.categories[i]._id == this.post.cat_id) { | |
this.categoryName = this.categories[i].name; | |
// this.getTagsOfCategory(this.categories[i]._id); | |
} | |
} | |
} | |
if (isPlatformBrowser(this.platformId)) { | |
this._title.setTitle('Viết tiếp - Spiderum'); | |
} | |
}); | |
} else { | |
this.post = { | |
title: '', | |
body: '', | |
type: 0, // create post by text editor | |
url_description: '', | |
content: '', | |
new_title: '', | |
description: '' | |
}; | |
if (isPlatformBrowser(this.platformId)) { | |
this._title.setTitle('Viết bài - Spiderum'); | |
} | |
} | |
} | |
ngOnDestroy() { | |
this._eventService.emitEventCreatePost(false); | |
// this.timer.unsubscribe(); | |
} | |
private debouncedOnChange = _.debounce(() => this.onchange(), 3000); | |
onchange() { | |
if(this.draft_id){ | |
this.saveDraft(); | |
} else { | |
this.createNewDraft(); | |
} | |
} | |
createNewDraft(){ | |
this._postService.createDraft().subscribe((newDraft: any) => { | |
this.draft_id = newDraft._id; | |
this.isDataChanged = false; | |
}, error => { | |
// console.log(error); | |
}); | |
} | |
saveDraft() { | |
this._postService.saveDraft(this.post, this.draft_id).subscribe((draft: any) => { | |
this.isDataChanged = false; | |
}, error => { | |
// console.log(error); | |
}); | |
} | |
deleteDraft() { | |
if (this.draft_id) { | |
this._postService.deleteDraft(this.draft_id).subscribe((result: any) => { | |
if (result.deleted) { | |
this.post.draft_id = null; | |
} | |
}, error => { | |
console.log(error); | |
}); | |
} | |
} | |
validate() { | |
var isValid = true; | |
if (this.post && this.post.body.length < 1) { | |
this.contentError = 'Vui lòng nhập nội dung bài viết'; | |
isValid = false; | |
} | |
if (this.post && this.post.title.length < 10) { | |
this.titleError = 'Tiêu đề bài viết phải có ít nhất 10 ký tự'; | |
isValid = false; | |
} | |
if (this.categoryName == 'Chọn danh mục') { | |
this.categoryError = 'Vui lòng chọn danh mục bài viết'; | |
isValid = false; | |
} | |
if (!this.checkUserDenyPermissionInCategory()) { | |
isValid = false; | |
} | |
return isValid; | |
} | |
createPost() { | |
if (!this.validate()) return; | |
this.isDisabled = true; | |
this.post.body = this.post.body.replace(/contenteditable="true"/g, 'contenteditable="false"') | |
this._postService.createPost(this.post).subscribe((post: Post) => { | |
this.deleteDraft(); | |
this._eventService.emitEventCreatePost(false); | |
this._router.navigate(['/bai-dang', post.slug]); | |
setTimeout(() => { | |
this.isDisabled = false; | |
}, 3000); | |
}, error => { | |
this.isDisabled = false; | |
console.log(error); | |
}); | |
} | |
updatePost() { | |
if (!this.validate()) return; | |
this.isDisabled = true; | |
this.post.body = this.post.body.replace(/contenteditable="true"/g, 'contenteditable="false"') | |
this._postService.updatePost(this.post).subscribe((post: Post) => { | |
this._eventService.emitEventCreatePost(false); | |
this._router.navigate(['/bai-dang', post.slug]); | |
setTimeout(() => { | |
this.isDisabled = false; | |
}, 3000); | |
}, error => { | |
this.isDisabled = false; | |
console.log(error); | |
}); | |
} | |
updateTagsList(tag: any) { | |
//todo find check tag exist in array | |
//find tag_id in array | |
// | |
if (this.selectedTags && this.selectedTags.length) { | |
if (this.selectedTags.length < MAXIMUM_POST_TAG_NUMBER) { | |
let indexTag = this.selectedTags.map((x) => { return x.name; }).indexOf(tag.name); | |
if(indexTag == -1){ | |
this.selectedTags.push(tag); | |
// this.displayTags.push(tag); | |
} | |
} | |
this.isSelectedTagsMax = (this.selectedTags.length != MAXIMUM_POST_TAG_NUMBER) ? false : true; | |
} else { | |
this.selectedTags = [tag]; | |
// this.displayTags = [tag]; | |
} | |
this.post.tags = this.selectedTags && this.selectedTags.length ? this.selectedTags : []; | |
this.tags = null; | |
this.isShowTagsList = false; | |
this.editorForm.get('tagsSearch').reset(); | |
} | |
// showTagsListToggle() { | |
// if (this.tags && this.tags.length) { | |
// this.isShowTagsList = !this.isShowTagsList; | |
// } | |
// } | |
removeTag(tagName: string) { | |
let removedTagIndex = this.selectedTags.map((tag) => { return tag.name; }).indexOf(tagName); | |
this.selectedTags.splice(removedTagIndex, 1); | |
this.isSelectedTagsMax = false; | |
// this.displayTags.splice(removedTagIndex, 1); | |
} | |
onTagEnter($event: any){ | |
this.updateTagsList({name: $event.target.value.toUpperCase()}); | |
let tagsSearch = this._el.nativeElement.querySelector('.tag-input-frame'); | |
if (tagsSearch) { | |
setTimeout(() => { | |
tagsSearch.focus(); | |
}, 200); | |
} | |
} | |
insertAfter(newNode: Node, referenceNode: Node) { | |
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); | |
} | |
removeAfter(referenceNode: Node) { | |
referenceNode.parentElement.removeChild(referenceNode.nextSibling); | |
} | |
addElementWrapContent(element: HTMLElement, typeOfWrap: string){ | |
let org_html = element.outerHTML; | |
let newElement = document.createElement(typeOfWrap); | |
newElement.innerHTML = org_html; | |
element.parentNode.replaceChild(newElement, element); | |
} | |
addImageWrapper(image: HTMLElement, root: HTMLElement, isAddNewParagraph?: boolean) { | |
let imageWrapper = document.createElement('figure'); | |
let imageDescription = document.createElement('figcaption'); | |
imageDescription.setAttribute('contenteditable', 'true'); | |
imageDescription.setAttribute('placeholder', 'Chú thích ảnh (không bắt buộc)'); | |
imageDescription.classList.add('image-description'); | |
const br = document.createElement('br'); | |
// let imageCaption = document.createElement('span'); | |
// imageCaption.textContent = 'chú thích ảnh (không bắt buộc)'; | |
// imageDescription.appendChild(imageCaption); | |
// imageDescription.appendChild(br); | |
imageWrapper.appendChild(image); | |
imageWrapper.appendChild(imageDescription); | |
// SET DEFAULT IMAGE POSITION TO CENTER | |
imageWrapper.classList.add('aligncenter'); | |
root.appendChild(imageWrapper); | |
// OBSERVE THE IMAGEWRAPER ELEMENT SO WE CAN KNOW WHEN IT WAS REMOVED | |
// let objConfig = { | |
// childList: true, | |
// subtree : true, | |
// attributes: false, | |
// characterData : false | |
// } | |
// let observer = new MutationObserver((mutations) => { | |
// mutations.forEach((mutation) => { | |
// // REMOVE IMG ALSO REMOVE FIGURE | |
// let removeNodes = mutation.removedNodes; | |
// let node = removeNodes ? removeNodes[0] : undefined; | |
// if(node &&'IMG' === node.nodeName) { | |
// root.removeChild(imageWrapper); | |
// observer.disconnect(); | |
// } | |
// }) | |
// }); | |
// observer.observe(imageWrapper, objConfig); | |
if(isAddNewParagraph) { | |
let newParagraph = document.createElement('div'); | |
newParagraph.appendChild(br); | |
root.parentElement.appendChild(newParagraph); | |
} | |
let textEditor = this._el.nativeElement; | |
imageWrapper.addEventListener('click', ($event) => { | |
image.classList.add('img-focus'); | |
}); | |
textEditor.addEventListener('click', ($event) => { | |
if(!imageWrapper.contains($event.target) && !imageDescription.contains($event.target)) { | |
// CLICK OUTSIDE THE IMAGE CONTAINER | |
image.classList.remove('img-focus'); | |
} | |
}); | |
} | |
public titleOptions: Object = !isPlatformBrowser(this.platformId) ? {} : { | |
key: 'Tb1dA-16rrjlwI2C-21rs==', | |
placeholderText: 'Nội dung bài viết', | |
charCounterCount: false, | |
spellcheck: false, | |
tabSpaces: 4, | |
htmlRemoveTags: ['script', 'style', 'base', 'meta'], | |
// toolbarBottom: true, | |
toolbarButtons: [ | |
'fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', | |
'paragraphFormat', 'align', 'formatOL', 'formatUL', 'quote', | |
'insertLink', 'insertImage', 'insertVideo' | |
], | |
toolbarButtonsMD: [ | |
'fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', | |
'paragraphFormat', 'align', 'formatOL', 'formatUL', 'quote', | |
'insertLink', 'insertImage', 'insertVideo' | |
], | |
toolbarButtonsSM: [ | |
'fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', | |
'paragraphFormat', 'align', 'formatOL', 'formatUL', 'quote', | |
'insertLink', 'insertImage', 'insertVideo' | |
], | |
toolbarButtonsXS: [ | |
'fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', | |
'paragraphFormat', 'align', 'formatOL', 'formatUL', 'quote', | |
'insertLink', 'insertImage', 'insertVideo' | |
], | |
heightMin: 500, | |
dragInline: false, | |
imageResize: false, | |
imageResizeWithPercent: true, | |
imageDefaultWidth: 0, | |
pastePlain: true, | |
imageUploadURL: '/api/v1/media/img/upload', | |
imageEditButtons: [ | |
// 'imageReplace', 'imageAlign', 'imageRemove', 'imageLink', | |
// '|', | |
// 'imageDisplay', 'imageStyle', /*'imageAlt', */'imageSize', 'imageFullScreen' | |
'imageLeft', 'imageRight', 'imageCenter', 'imageCover', 'imageFullScreen' | |
], | |
requestHeaders: { | |
// Authorization: 'Bearer ' + localStorage.getItem(AUTH_TOKEN_KEY) | |
Authorization: 'Bearer ' + this._api.token | |
}, | |
imageUploadParam: 'linkupload', | |
linkAlwaysBlank: true, | |
// imageMaxSize: 2 * 1024 * 1024, | |
pasteDeniedAttrs: ['class', 'id', 'style'], | |
enter: $.FroalaEditor.ENTER_DIV, | |
events: { | |
'froalaEditor.initialized': (e: any, editor: any) => { | |
editor.events.on("keydown", (e) => { | |
if (e.which === 13) { // ENTER KEY | |
let dataEnter = window.getSelection()['focusNode'].textContent; | |
this.crawlDataFromUrl(dataEnter); | |
// BREAK THE CURRENT PARAGRAPH IF PRESS ENTER IN FIGURE OR FIGCAPTION | |
let selection = window.getSelection(); | |
let currentNode = selection['focusNode']; | |
let range = selection.getRangeAt(0); | |
let parent = currentNode ? currentNode.parentElement : currentNode; | |
if(parent && (parent.nodeName === 'FIGCAPTION' || parent.nodeName === 'FIGURE')) { | |
while(parent.nodeName === 'FIGCAPTION' || parent.nodeName === 'FIGURE') { | |
parent = parent.parentElement; | |
} | |
const newParagraph = document.createElement('div'); | |
this.insertAfter(newParagraph, parent); | |
// this.removeAfter(newParagraph); | |
range.setStartAfter(newParagraph); | |
range.setEndBefore(newParagraph); | |
range.collapse(false); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
} | |
// END BREAK THE CURRENT PARAGRAPH IF PRESS ENTER IN FIGURE OR FIGCAPTION | |
} | |
// else if(e.which === 8) { | |
// let currentNode = editor.selection.get(0).anchorNode; | |
// if(currentNode.data) { | |
// currentNode = currentNode.parentElement; | |
// } | |
// let scrapeWraper = currentNode ? currentNode.previousSibling : null; | |
// let childNode = scrapeWraper ? scrapeWraper.firstChild : null; | |
// if(childNode && childNode.className === 'scrape-url') { | |
// scrapeWraper.remove(childNode); | |
// } | |
// } | |
}, true); | |
}, | |
'froalaEditor.contentChanged': (e: any, editor: any) => { | |
this.isDataChanged = true; | |
this.debouncedOnChange(); | |
}, | |
'froalaEditor.image.inserted': (e: any, editor: any, $img: any, response: any) => { | |
// ADD IMAGE CAPTION | |
let image = $img[0]; | |
let root = image.parentElement; | |
if(isPlatformBrowser(this.platformId)) { | |
this.addImageWrapper(image, root, true); | |
let imageWrapper = image.parentElement; | |
imageWrapper.click(); | |
} | |
}, | |
'froalaEditor.image.removed': (e: any, editor: any, $img: any) => { | |
// ADD IMAGE CAPTION | |
let image = $img[0]; | |
let figures = this._el.nativeElement.getElementsByTagName('figure'); | |
if(figures) { | |
for(let i = 0; i < figures.length; i++) { | |
if(figures[i].firstChild.nodeName !== 'IMG') { | |
let wrapper = figures[i].parentElement; | |
let root = wrapper.parentElement; | |
if(wrapper && root) { | |
root.removeChild(wrapper); | |
} | |
} | |
} | |
} | |
}, | |
'froalaEditor.paste.afterCleanup': (e: any, editor: any, clipboard_html: any) => { | |
let clipboardData = new DOMParser().parseFromString(clipboard_html, 'text/html'); | |
let arrayImgs = clipboardData.querySelectorAll('img'); | |
for(let i = 0; i < arrayImgs.length; i++){ | |
this.addElementWrapContent(arrayImgs[i], 'div'); | |
} | |
let newArrayImgs = clipboardData.querySelectorAll('img'); | |
for(let i = 0; i < newArrayImgs.length; i++){ | |
let root = newArrayImgs[i].parentElement; | |
this.addImageWrapper(newArrayImgs[i], root, true); | |
} | |
return clipboardData.body.innerHTML; | |
} | |
} | |
} | |
validURL(str) { | |
var pattern = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/g; | |
if(!pattern.test(str)) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
crawlDataFromUrl(url: string){ | |
if(this.validURL(url)){ | |
this._postService.scrapeUrl(url).subscribe( | |
result => { | |
this._el.nativeElement.querySelectorAll("a[href='" + url + "']:not(.scrape-info):not(.scrape-thumb)") | |
.forEach((item) => { | |
if(item.parentNode){ | |
item.parentNode.innerHTML = '<div class="scrape-url" contenteditable="true">' + | |
'<a class="scrape-info" target="_blank" rel="nofollow" href="' + url + '">' + | |
'<strong class="markup-strong">' + result.title + '</strong>' + | |
'<br>' + | |
'<em class="markup-em">' + result.description + '</em>' + | |
result.domain + | |
'</a>' + | |
'<a class="scrape-thumb" target="_blank" rel="nofollow" href="' + url + '" style="background-image: url(' + this.thumbnail + result.thumbnail + ')"></a>' + | |
'</div>'; | |
} | |
}); | |
} | |
) | |
} | |
} | |
toggleCategory() { | |
this.isCollapsedCategory = !this.isCollapsedCategory; | |
if (this.isCollapsedCategory) { | |
let categorySearch = this._el.nativeElement.querySelector('#category-search'); | |
if (categorySearch) { | |
categorySearch.focus(); | |
} | |
} | |
} | |
closeCategory() { | |
this.isCollapsedCategory = false; | |
} | |
chooseCategory(category: Category) { | |
this.toggleCategory(); | |
this.categoryName = category.name; | |
this.categoryError = ''; | |
this.post.cat_id = category._id; | |
// this.getTagsOfCategory(category._id); | |
this.checkUserDenyPermissionInCategory(); | |
} | |
// getAllTags() { | |
// this._postService.getAllTags().subscribe((tags: any) => { | |
// this.allTags = tags; | |
// this.tags = tags; | |
// }); | |
// } | |
searchTagsByName(tagName: string){ | |
if(!tagName) return; | |
this._postService.searchTagsByName(tagName).subscribe((result: any) => { | |
this.tags = result.result; | |
if (this.selectedTags && this.selectedTags.length) { | |
let selectedTagsId = this.selectedTags.map((tag) => { return tag._id; }); | |
this.tags = this.tags.filter((tag) => { | |
return selectedTagsId.indexOf(tag._id) == -1; | |
}); | |
} | |
if (this.tags && this.tags.length) { | |
this.isShowTagsList = true; | |
} | |
}); | |
} | |
checkUserDenyPermissionInCategory() { | |
if (this.user && this.user.abandon && this.user.abandon.category) { | |
var indexabandonCat_id = this.user.abandon.category.map(function(x: any) { return x.cat_id; }).indexOf(this.post.cat_id); | |
if (indexabandonCat_id > -1) { | |
this.categoryError = 'Bạn không có quyền được tạo bài viết trong category này'; | |
return false; | |
} | |
return true; | |
} | |
return true; | |
} | |
cancel() { | |
this._location.back(); | |
} | |
openConfirmDialog() { | |
this._eventService.emitEventOpenDialog({ | |
type: "confirm", | |
title: "Hủy bỏ bài viết?", | |
body: "Bài viết của bạn chưa được lưu, bạn có muốn hủy bài viết?" | |
}); | |
} | |
disableEnterKey($event: any) { | |
$event.preventDefault(); | |
} | |
closeTagList($event: any) { | |
if ($event) { | |
// this.isCollapsedCategory = false; | |
this.isShowTagsList = false; | |
} | |
} | |
closeCategoryList($event: any) { | |
if ($event) { | |
this.isCollapsedCategory = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment