import {Component, OnInit, ViewChildren} from '@angular/core'; import HostRecord from '../../structures/HostRecord'; @Component({ selector: 'app-editor', templateUrl: './editor.page.html', styleUrls: ['./editor.page.scss'], }) export class EditorPage implements OnInit { public hostRecords: Array = [new HostRecord('I am a record.')]; @ViewChildren('editorHosts') editorHosts; constructor() { } ngOnInit() { console.log('Editor component: ', this); } onNewHostRequested($event) { const insertAfter = this.getIndexFromRecord($event.record); const record = new HostRecord(''); const newHosts = [] this.hostRecords.forEach((rec, i) => { newHosts.push(rec); if ( i === insertAfter ) { newHosts.push(record); } }) this.hostRecords = newHosts; setTimeout(() => { const host = this.editorHosts.toArray()[insertAfter + 1].hostContainer.nativeElement; const s = window.getSelection(); const r = document.createRange(); r.setStart(host, 0); r.setEnd(host, 0); s.removeAllRanges(); s.addRange(r); }, 0); } onDestroyHostRequested($event) { let removedIndex = 0; const newHostRecords = this.editorHosts.filter((host, i) => { if ( $event.record === host.record ) { removedIndex = i; } return host.record !== $event.record; }); const removedHost = this.editorHosts[removedIndex]; const hostRecords = newHostRecords.map(host => host.record); this.hostRecords = hostRecords; setTimeout(() => { let focusIndex; if ( removedIndex === 0 && this.editorHosts.toArray().length ) { focusIndex = 0; } else if ( removedIndex !== 0 ) { focusIndex = removedIndex - 1; } if ( focusIndex >= 0 ) { const host = this.editorHosts.toArray()[focusIndex].hostContainer.nativeElement; const s = window.getSelection(); const r = document.createRange(); r.setStart(host, 0); r.setEnd(host, 0); s.removeAllRanges(); s.addRange(r); } }, 0); } protected getIndexFromRecord(record) { let index; this.editorHosts.toArray().forEach((host, i) => { if ( host.record === record ) { index = i; } }); return index; } }