Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(angular): add angular wrapper #763

Merged
merged 16 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"@codingame/monaco-vscode-typescript-basics-default-extension": "~10.1.1",
"@codingame/monaco-vscode-typescript-language-features-default-extension": "~10.1.1",
"@typefox/monaco-editor-react": "~6.0.0-next.5",
"cors": "^2.8.5",
"express": "~4.21.1",
"langium": "~3.2.0",
"monaco-editor": "npm:@codingame/monaco-vscode-editor-api@~10.1.1",
Expand All @@ -93,6 +94,7 @@
"wtd-core": "~4.0.1"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "~5.0.0",
"@types/ws": "~8.5.12",
"@types/emscripten": "~1.39.13",
Expand Down
22 changes: 21 additions & 1 deletion packages/examples/src/json/server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
* ------------------------------------------------------------------------------------------ */

import { resolve } from 'node:path';
import cors from 'cors';

import { runLanguageServer } from '../../common/node/language-server-runner.js';
import { LanguageName } from '../../common/node/server-commons.js';

import express from 'express';
export const runJsonServer = (baseDir: string, relativeDir: string) => {
const processRunPath = resolve(baseDir, relativeDir);
runLanguageServer({
Expand All @@ -23,4 +25,22 @@ export const runJsonServer = (baseDir: string, relativeDir: string) => {
perMessageDeflate: false
}
});

startMockHttpServerForSavingCodeFromEditor();
};

export const startMockHttpServerForSavingCodeFromEditor = () => {
ls-infra marked this conversation as resolved.
Show resolved Hide resolved
const app = express();
app.use(cors());
app.use(express.json());
app.post('/save-code', (req, res) => {
const { code } = req.body;
console.log('Received code:', code);
res.json({ success: true, message: code});
});

const PORT = 3003;
app.listen(PORT, () => {
console.log(`JSON server running on port ${PORT}`);
});
};
3 changes: 0 additions & 3 deletions verify/angular/src/app/app.component.css

This file was deleted.

13 changes: 10 additions & 3 deletions verify/angular/src/app/app.component.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<h2>Monaco Language Client Angular Client Example</h2>
<div>
<div id="monaco-editor-root" class="monaco-editor"></div>
<h2>Angular Monaco Editor demo with saving code to a mock HTTP server </h2>
<div class="editor-container">
<monaco-angular-wrapper
[wrapperConfig]="wrapperConfig()"
[monacoEditorId]="editorId"
[editorInlineStyle]="editorInlineStyle()"
(onTextChanged)="onTextChanged($event)"
></monaco-angular-wrapper>

<button class="save-button" (click)="save()">Save</button>
</div>
Empty file.
52 changes: 36 additions & 16 deletions verify/angular/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,50 @@
* Licensed under the MIT License. See LICENSE in the package root for license information.
* ------------------------------------------------------------------------------------------ */

import { AfterViewInit, Component } from '@angular/core';
import { MonacoEditorLanguageClientWrapper } from 'monaco-editor-wrapper';
import { AfterViewInit, Component, inject, signal } from '@angular/core';
import { WrapperConfig } from 'monaco-editor-wrapper';
import { MonacoAngularWrapperComponent } from '../monaco-angular-wrapper/monaco-angular-wrapper.component';
import { buildJsonClientUserConfig } from 'monaco-languageclient-examples/json-client';

import { SaveCodeService } from '../save-code.service';
import { firstValueFrom } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
standalone: true
styleUrls: ['./app.component.scss'],
standalone: true,
imports: [MonacoAngularWrapperComponent],
})
export class MonacoEditorComponent implements AfterViewInit {
title = 'angular-client';
initDone = false;
export class AppComponent implements AfterViewInit {
private saveCodeService = inject(SaveCodeService);
wrapperConfig = signal<WrapperConfig | undefined>(undefined); // this can be updated at runtime

title = 'angular demo for saving code';
editorId = 'monaco-editor-root'; // this can be parameterized or it can be in a loop to support multiple editors
editorInlineStyle = signal('height: 50vh;');
readonly codeText = signal('');

async ngAfterViewInit(): Promise<void> {
const wrapper = new MonacoEditorLanguageClientWrapper();
const editorDom = document.getElementById(this.editorId);
if (editorDom) {
const config = buildJsonClientUserConfig({
htmlContainer: editorDom,
});
this.wrapperConfig.set(config);
}
}

const config = buildJsonClientUserConfig({
htmlContainer: document.getElementById('monaco-editor-root')!
});
onTextChanged(text: string) {
this.codeText.set(text);
}

save = async () => {
try {
await wrapper.initAndStart(config);
} catch (e) {
console.error(e);
const response = await firstValueFrom(
this.saveCodeService.saveCode(this.codeText())
);
alert('Code saved:' + JSON.stringify(response));
} catch (error) {
console.error('Error saving code:', error);
}
}
};
}
7 changes: 5 additions & 2 deletions verify/angular/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@
* ------------------------------------------------------------------------------------------ */

import { bootstrapApplication } from '@angular/platform-browser';
import { MonacoEditorComponent } from './app/app.component';
bootstrapApplication(MonacoEditorComponent);
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div>
<div [id]="monacoEditorId()" class='monaco-editor' [style]="editorInlineStyle()"></div>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2024 TypeFox and others.
* Licensed under the MIT License. See LICENSE in the package root for license information.
* ------------------------------------------------------------------------------------------ */

import {
Component,
effect,
EventEmitter,
input,
OnDestroy,
Output,
} from '@angular/core';

import * as monaco from 'monaco-editor';
import {
MonacoEditorLanguageClientWrapper,
TextChanges,
TextModels,
WrapperConfig , didModelContentChange
} from 'monaco-editor-wrapper';

@Component({
standalone: true,
selector: 'monaco-angular-wrapper',
templateUrl: './monaco-angular-wrapper.component.html',
styleUrls: ['./monaco-angular-wrapper.component.scss'],
})
export class MonacoAngularWrapperComponent implements OnDestroy {
@Output() onTextChanged = new EventEmitter<string>();
wrapperConfig = input<WrapperConfig>();
monacoEditorId = input<string>();
editorInlineStyle = input<string>();
private wrapper: MonacoEditorLanguageClientWrapper =
new MonacoEditorLanguageClientWrapper();
private _subscription: monaco.IDisposable | null = null;
private isRestarting?: Promise<void>;

constructor() {
effect(async () => {
try {
if (this.wrapperConfig() !== undefined) {
await this.wrapper.initAndStart(
this.wrapperConfig() as WrapperConfig
);
this.handleOnTextChanged();
}
} catch (e) {
console.error(e);
}
});
}

protected async destroyMonaco(): Promise<void> {
if (this.isRestarting) {
await this.isRestarting;
}
try {
await this.wrapper.dispose();
} catch {
// The language client may throw an error during disposal.
// This should not prevent us from continue working.
console.error('Error during disposal of the language client.');
}
if (this._subscription) {
this._subscription.dispose();
}
}

async ngOnDestroy() {
this.destroyMonaco();
}

handleOnTextChanged() {
const wrapperConfig = this.wrapperConfig();
const textModels = this.wrapper.getTextModels();
if (textModels?.text !== undefined && wrapperConfig !== undefined) {
const newSubscriptions: monaco.IDisposable[] = [];
this.emitCodeChange(textModels, wrapperConfig);
newSubscriptions.push(
textModels.text.onDidChangeContent(() => {
this.emitCodeChange(textModels, wrapperConfig);
})
);
}
}

emitCodeChange(textModels: TextModels , wrapperConfig: WrapperConfig ) {
const onTextChanged = (textChanges: TextChanges) => {
this.onTextChanged.emit(textChanges.text);
};
didModelContentChange(textModels, wrapperConfig.editorAppConfig.codeResources, onTextChanged);
}

}
14 changes: 14 additions & 0 deletions verify/angular/src/save-code.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2024 TypeFox and others.
* Licensed under the MIT License. See LICENSE in the package root for license information.
* ------------------------------------------------------------------------------------------ */

import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class SaveCodeService {
private http = inject(HttpClient);
saveCode(codeText: string) {
return this.http.post('http://localhost:3003/save-code', { code: codeText });
}
}