import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; import * as brace from 'brace'; import 'brace/ext/modelist'; import 'brace/mode/c_cpp'; import 'brace/mode/csharp'; import 'brace/mode/java'; import 'brace/mode/javascript'; import 'brace/mode/json'; import 'brace/mode/python'; import 'brace/mode/sql'; import 'brace/theme/monokai'; import { SourceCode } from './source-code'; import { WebSocketService } from '../websocket.service'; const modelist = brace.acequire('ace/ext/modelist'); const defaultSourceCode = `alert( 'Hello, world!' );`; @Component({ selector: 'app-webide', templateUrl: './webide.component.html', styleUrls: ['./webide.component.scss'] }) export class WebideComponent implements OnInit { anchor_id = 'anchor_webide'; filename = 'demo.js'; code: string = defaultSourceCode; language = 'javascript'; theme = 'monokai'; files: string[]; saveButtonState = 'DIRTY'; command_handlers = { 'reload': this.reloadHandler.bind(this), 'read': this.readHandler.bind(this), 'select': this.selectHandler.bind(this), 'write': this.writeHandler.bind(this)}; constructor(private webSocketService: WebSocketService, private changeDetectorRef: ChangeDetectorRef) { } ngOnInit() { this.subscribeWS(); this.requestCode(); } subscribeWS() { this.webSocketService.observeAnchor(this.anchor_id).subscribe((event) => { this.command_handlers[event.data.command](event.data); this.changeDetectorRef.detectChanges(); }); } updateFileData(data: SourceCode) { this.filename = data.filename; this.code = data.content; this.language = modelist.getModeForPath(this.filename).name; this.files = data.files; } selectHandler(data: SourceCode) { this.updateFileData(data); } reloadHandler(data: SourceCode) { this.requestCode(); } readHandler(data: SourceCode) { this.updateFileData(data); } writeHandler(data: SourceCode) { this.saveButtonState = 'SAVED'; } setButtonStateDirty() { setTimeout(() => {this.saveButtonState = 'DIRTY'; }, 0); } sendCode() { this.webSocketService.send(this.anchor_id, { 'command': 'write', 'content': this.code }); this.saveButtonState = 'SAVING'; } requestCode() { this.webSocketService.send(this.anchor_id, { 'command': 'read' }); } selectCode(filename: string) { this.webSocketService.send(this.anchor_id, { 'command': 'select', 'filename': filename }); } }