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: adding monaco support #2281

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions packages/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"@types/humanize-duration": "^3.27.4",
"@typescript-eslint/eslint-plugin": "8.18.1",
"jsdom": "^25.0.1",
"monaco-editor": "^0.52.2",
"postcss": "^8.4.49",
"postcss-load-config": "^6.0.1",
"svelte": "5.14.2",
Expand Down
81 changes: 81 additions & 0 deletions packages/frontend/src/lib/monaco-editor/MonacoEditor.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import type * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';
import './monaco';
import type { HTMLAttributes } from 'svelte/elements';

interface Props extends HTMLAttributes<HTMLElement> {
content: string;
// supported languages https://github.com/microsoft/monaco-editor/tree/main/src/basic-languages
language: string;
readOnly?: boolean;
onChange?: (content: string) => void;
}

let { content = $bindable(), language, readOnly = false, onChange, class: className, ...restProps }: Props = $props();

let editorInstance: Monaco.editor.IStandaloneCodeEditor;
let editorContainer: HTMLElement;

function getTerminalBg(): string {
const app = document.getElementById('app');
if (!app) throw new Error('cannot found app element');
const style = window.getComputedStyle(app);

let color = style.getPropertyValue('--pd-terminal-background').trim();

// convert to 6 char RGB value since some things don't support 3 char format
if (color?.length < 6) {
color = color
.split('')
.map(c => {
return c === '#' ? c : c + c;
})
.join('');
}
return color;
}

onMount(async () => {
const terminalBg = getTerminalBg();
const isDarkTheme: boolean = terminalBg === '#000000';

// solution from https://github.com/vitejs/vite/discussions/1791#discussioncomment-9281911
import('monaco-editor/esm/vs/editor/editor.api')
.then(monaco => {
// define custom theme
monaco.editor.defineTheme('podmanDesktopTheme', {
base: isDarkTheme ? 'vs-dark' : 'vs',
inherit: true,
rules: [{ token: 'custom-color', background: terminalBg }],
colors: {
'editor.background': terminalBg,
// make the --vscode-focusBorder transparent
focusBorder: '#00000000',
},
});

editorInstance = monaco.editor.create(editorContainer, {
value: content,
language: language,
automaticLayout: true,
scrollBeyondLastLine: false,
readOnly: readOnly,
theme: 'podmanDesktopTheme',
glyphMargin: true, // Enable glyph margin
});

editorInstance.onDidChangeModelContent(() => {
content = editorInstance.getValue();
onChange?.(content);
});
})
.catch(console.error);
});

onDestroy(() => {
editorInstance?.dispose();
});
</script>

<div class="h-full w-full {className}" {...restProps} bind:this={editorContainer}></div>
28 changes: 28 additions & 0 deletions packages/frontend/src/lib/monaco-editor/monaco.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';

self.MonacoEnvironment = {
getWorker(_: unknown): Worker {
return new editorWorker();
},
};

monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);

Check failure on line 28 in packages/frontend/src/lib/monaco-editor/monaco.ts

View workflow job for this annotation

GitHub Actions / linter, formatters and unit tests / windows-2022

src/App.spec.ts

TypeError: Cannot read properties of undefined (reading 'typescriptDefaults') ❯ src/lib/monaco-editor/monaco.ts:28:29 ❯ src/lib/monaco-editor/MonacoEditor.svelte:4:31

Check failure on line 28 in packages/frontend/src/lib/monaco-editor/monaco.ts

View workflow job for this annotation

GitHub Actions / linter, formatters and unit tests / ubuntu-22.04

src/App.spec.ts

TypeError: Cannot read properties of undefined (reading 'typescriptDefaults') ❯ src/lib/monaco-editor/monaco.ts:28:29 ❯ src/lib/monaco-editor/MonacoEditor.svelte:4:31

Check failure on line 28 in packages/frontend/src/lib/monaco-editor/monaco.ts

View workflow job for this annotation

GitHub Actions / linter, formatters and unit tests / macos-14

src/App.spec.ts

TypeError: Cannot read properties of undefined (reading 'typescriptDefaults') ❯ src/lib/monaco-editor/monaco.ts:28:29 ❯ src/lib/monaco-editor/MonacoEditor.svelte:4:31
20 changes: 20 additions & 0 deletions packages/frontend/src/pages/InferenceServerDetails.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type { Language } from 'postman-code-generators';
import { studioClient } from '/@/utils/client';
import { router } from 'tinro';
import type { ModelInfo } from '@shared/src/models/IModelInfo';
import MonacoEditor from '../lib/monaco-editor/MonacoEditor.svelte';

const mocks = vi.hoisted(() => {
return {
Expand All @@ -33,6 +34,10 @@ const mocks = vi.hoisted(() => {
};
});

vi.mock('../lib/monaco-editor/MonacoEditor.svelte', () => ({
default: vi.fn(),
}));

vi.mock('../stores/inferenceServers', () => ({
inferenceServers: {
subscribe: (f: (msg: InferenceServer[]) => void) => {
Expand Down Expand Up @@ -217,6 +222,21 @@ describe('snippets', () => {
);
});

test('generated snippet should be sent to the monaco component', async () => {
const DUMMY_SNIPPET = 'dummy generated snippet';
vi.mocked(studioClient.createSnippet).mockResolvedValue(DUMMY_SNIPPET);
render(InferenceServerDetails, {
containerId: 'dummyContainerId',
});

await vi.waitFor(() => {
expect(MonacoEditor).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ content: DUMMY_SNIPPET, language: 'curl', readOnly: true }),
);
});
});

test('copy snippet should call copyToClipboard', async () => {
vi.mocked(studioClient.createSnippet).mockResolvedValue('dummy generated snippet');
render(InferenceServerDetails, {
Expand Down
25 changes: 5 additions & 20 deletions packages/frontend/src/pages/InferenceServerDetails.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { Button, DetailsPage, Tooltip, Link } from '@podman-desktop/ui-svelte';
import CopyButton from '/@/lib/button/CopyButton.svelte';
import type { RequestOptions } from '@shared/src/models/RequestOptions';
import { filesize } from 'filesize';
import MonacoEditor from '../lib/monaco-editor/MonacoEditor.svelte';

export let containerId: string | undefined = undefined;

Expand Down Expand Up @@ -121,22 +122,6 @@ $: {
}
}

let code: HTMLElement;

$: {
if (code) {
code.addEventListener('copy', event => {
studioClient
.telemetryLogUsage('snippet.copy', {
cpyButton: false,
language: selectedLanguage,
variant: selectedVariant,
})
.catch(err => console.error(`Error reporting telemetry:`, err));
});
}
}

let copied: boolean = false;
function copySnippet(): void {
if (!snippet) return;
Expand Down Expand Up @@ -368,11 +353,11 @@ function handleOnChange(): void {

{#if snippet !== undefined}
<div
class="bg-[var(--pd-details-empty-cmdline-bg)] text-[var(--pd-details-empty-cmdline-text)] rounded-md w-full p-4 mt-2 relative"
class="bg-[var(--pd-details-empty-cmdline-bg)] text-[var(--pd-details-empty-cmdline-text)] rounded-md w-full p-4 mt-2 relative h-[400px]"
aria-label="Code Snippet">
<code class="whitespace-break-spaces text-sm" bind:this={code}>
{snippet}
</code>
{#key snippet}
<MonacoEditor class="h-full" readOnly content={snippet} language={selectedLanguage} />
{/key}
<div class="absolute right-4 top-4 z-10">
<Button icon={copied ? faCheck : faCopy} type="secondary" title="Copy" on:click={copySnippet} />
</div>
Expand Down
3 changes: 2 additions & 1 deletion packages/frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
* of JS in `.svelte` files.
*/
"allowJs": true,
"checkJs": true
"checkJs": true,
"types": ["@testing-library/jest-dom", "vite/client"]
},
"include": [
"src/**/*.d.ts",
Expand Down
12 changes: 8 additions & 4 deletions packages/frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,15 @@ export default defineConfig({
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
globals: true,
environment: 'jsdom',
alias: [{ find: '@testing-library/svelte', replacement: '@testing-library/svelte/svelte5' }],
alias: [
{ find: '@testing-library/svelte', replacement: '@testing-library/svelte/svelte5' },
{
find: /^monaco-editor$/,
replacement: `${PACKAGE_ROOT}/../../node_modules/monaco-editor/esm/vs/editor/editor.api`,
},
],
deps: {
inline: [

],
inline: [],
},
},
base: '',
Expand Down
16 changes: 12 additions & 4 deletions pnpm-lock.yaml

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

Loading