feat(workspace): rename editor components to workspace group and move terminal & TypeScript intellisense into workspace

This commit is contained in:
2025-12-31 12:37:14 +00:00
parent 08b302bd46
commit 15bca09086
29 changed files with 517 additions and 91 deletions

View File

@@ -0,0 +1,938 @@
import {
DeesElement,
property,
html,
customElement,
type TemplateResult,
css,
cssManager,
state,
} from '@design.estate/dees-element';
import * as domtools from '@design.estate/dees-domtools';
import { themeDefaultStyles } from '../../00theme.js';
import type { IExecutionEnvironment, IFileEntry, IFileWatcher } from '../../00group-runtime/index.js';
import '../../dees-icon/dees-icon.js';
import '../../dees-contextmenu/dees-contextmenu.js';
import { DeesContextmenu } from '../../dees-contextmenu/dees-contextmenu.js';
import { DeesModal } from '../../dees-modal/dees-modal.js';
import '../../00group-input/dees-input-text/dees-input-text.js';
import { DeesInputText } from '../../00group-input/dees-input-text/dees-input-text.js';
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-filetree': DeesWorkspaceFiletree;
}
}
interface ITreeNode extends IFileEntry {
children?: ITreeNode[];
expanded?: boolean;
level: number;
}
@customElement('dees-workspace-filetree')
export class DeesWorkspaceFiletree extends DeesElement {
public static demo = () => html`
<div style="width: 300px; height: 400px; position: relative;">
<dees-workspace-filetree></dees-workspace-filetree>
</div>
`;
// INSTANCE
@property({ type: Object })
accessor executionEnvironment: IExecutionEnvironment | null = null;
@property({ type: String })
accessor rootPath: string = '/';
@property({ type: String })
accessor selectedPath: string = '';
@state()
accessor treeData: ITreeNode[] = [];
@state()
accessor isLoading: boolean = false;
@state()
accessor errorMessage: string = '';
private expandedPaths: Set<string> = new Set();
private loadTreeStarted: boolean = false;
// Clipboard state for copy/paste operations
private clipboardPath: string | null = null;
private clipboardOperation: 'copy' | 'cut' | null = null;
// File watcher for auto-refresh
private fileWatcher: IFileWatcher | null = null;
private refreshDebounceTimeout: ReturnType<typeof setTimeout> | null = null;
private lastExecutionEnvironment: IExecutionEnvironment | null = null;
public static styles = [
themeDefaultStyles,
cssManager.defaultStyles,
css`
:host {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: auto;
background: ${cssManager.bdTheme('hsl(0 0% 98%)', 'hsl(0 0% 9%)')};
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 13px;
}
.tree-container {
padding: 8px 0;
}
.tree-item {
display: flex;
align-items: center;
padding: 4px 8px;
cursor: pointer;
user-select: none;
border-radius: 4px;
margin: 1px 4px;
transition: background 0.1s ease;
}
.tree-item:hover {
background: ${cssManager.bdTheme('hsl(0 0% 93%)', 'hsl(0 0% 14%)')};
}
.tree-item.selected {
background: ${cssManager.bdTheme('hsl(210 100% 95%)', 'hsl(210 50% 20%)')};
color: ${cssManager.bdTheme('hsl(210 100% 40%)', 'hsl(210 100% 70%)')};
}
.tree-item.selected:hover {
background: ${cssManager.bdTheme('hsl(210 100% 92%)', 'hsl(210 50% 25%)')};
}
.indent {
display: inline-block;
width: 16px;
flex-shrink: 0;
}
.expand-icon {
width: 16px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: ${cssManager.bdTheme('hsl(0 0% 50%)', 'hsl(0 0% 60%)')};
transition: transform 0.15s ease;
}
.expand-icon.expanded {
transform: rotate(90deg);
}
.expand-icon.hidden {
visibility: hidden;
}
.file-icon {
width: 16px;
height: 16px;
margin-right: 6px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
.file-icon dees-icon {
width: 16px;
height: 16px;
}
.file-icon.folder {
color: ${cssManager.bdTheme('hsl(45 80% 45%)', 'hsl(45 70% 55%)')};
}
.file-icon.file {
color: ${cssManager.bdTheme('hsl(0 0% 50%)', 'hsl(0 0% 60%)')};
}
.file-icon.typescript {
color: hsl(211 60% 48%);
}
.file-icon.javascript {
color: hsl(53 93% 54%);
}
.file-icon.json {
color: hsl(45 80% 50%);
}
.file-icon.html {
color: hsl(14 77% 52%);
}
.file-icon.css {
color: hsl(228 77% 59%);
}
.file-icon.markdown {
color: hsl(0 0% 50%);
}
.file-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: ${cssManager.bdTheme('hsl(0 0% 20%)', 'hsl(0 0% 85%)')};
}
.loading {
padding: 16px;
text-align: center;
color: ${cssManager.bdTheme('hsl(0 0% 50%)', 'hsl(0 0% 60%)')};
}
.error {
padding: 16px;
text-align: center;
color: hsl(0 70% 50%);
}
.empty {
padding: 16px;
text-align: center;
color: ${cssManager.bdTheme('hsl(0 0% 50%)', 'hsl(0 0% 60%)')};
font-style: italic;
}
.filetree-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
height: 36px;
padding: 0 12px;
border-bottom: 1px solid ${cssManager.bdTheme('hsl(0 0% 85%)', 'hsl(0 0% 15%)')};
background: ${cssManager.bdTheme('hsl(0 0% 96%)', 'hsl(0 0% 8%)')};
position: sticky;
top: 0;
z-index: 1;
}
.toolbar-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: ${cssManager.bdTheme('hsl(0 0% 40%)', 'hsl(0 0% 60%)')};
}
.toolbar-actions {
display: flex;
gap: 4px;
}
.toolbar-button {
padding: 4px;
border-radius: 4px;
cursor: pointer;
opacity: 0.7;
transition: opacity 0.15s, background 0.15s;
display: flex;
align-items: center;
justify-content: center;
color: ${cssManager.bdTheme('hsl(0 0% 30%)', 'hsl(0 0% 70%)')};
}
.toolbar-button:hover {
opacity: 1;
background: ${cssManager.bdTheme('hsl(0 0% 0% / 0.08)', 'hsl(0 0% 100% / 0.1)')};
}
`,
];
public render(): TemplateResult {
if (!this.executionEnvironment) {
return html`
<div class="empty">
No execution environment provided.
</div>
`;
}
if (this.isLoading) {
return html`
<div class="loading">
Loading files...
</div>
`;
}
if (this.errorMessage) {
return html`
<div class="error">
${this.errorMessage}
</div>
`;
}
return html`
<div class="filetree-toolbar">
<span class="toolbar-title">Explorer</span>
<div class="toolbar-actions">
<div class="toolbar-button" @click=${() => this.createNewFile('/')} title="New File">
<dees-icon .icon=${'lucide:filePlus'} iconSize="16"></dees-icon>
</div>
<div class="toolbar-button" @click=${() => this.createNewFolder('/')} title="New Folder">
<dees-icon .icon=${'lucide:folderPlus'} iconSize="16"></dees-icon>
</div>
</div>
</div>
${this.treeData.length === 0
? html`<div class="empty">No files found.</div>`
: html`
<div class="tree-container" @contextmenu=${this.handleEmptySpaceContextMenu}>
${this.renderTree(this.treeData)}
</div>
`}
`;
}
private renderTree(nodes: ITreeNode[]): TemplateResult[] {
return nodes.map(node => this.renderNode(node));
}
private renderNode(node: ITreeNode): TemplateResult {
const isDirectory = node.type === 'directory';
const isExpanded = this.expandedPaths.has(node.path);
const isSelected = node.path === this.selectedPath;
const iconClass = this.getFileIconClass(node);
return html`
<div
class="tree-item ${isSelected ? 'selected' : ''}"
style="padding-left: ${8 + node.level * 16}px"
@click=${(e: MouseEvent) => this.handleItemClick(e, node)}
@contextmenu=${(e: MouseEvent) => this.handleContextMenu(e, node)}
>
<span class="expand-icon ${isExpanded ? 'expanded' : ''} ${!isDirectory ? 'hidden' : ''}">
<dees-icon .icon=${'lucide:chevronRight'} iconSize="12"></dees-icon>
</span>
<span class="file-icon ${iconClass}">
<dees-icon .icon=${this.getFileIcon(node)} iconSize="16"></dees-icon>
</span>
<span class="file-name">${node.name}</span>
</div>
${isDirectory && isExpanded && node.children
? this.renderTree(node.children)
: ''}
`;
}
private getFileIcon(node: ITreeNode): string {
if (node.type === 'directory') {
return this.expandedPaths.has(node.path) ? 'lucide:folderOpen' : 'lucide:folder';
}
const ext = node.name.split('.').pop()?.toLowerCase();
switch (ext) {
case 'ts':
case 'tsx':
return 'lucide:fileCode';
case 'js':
case 'jsx':
return 'lucide:fileCode';
case 'json':
return 'lucide:fileJson';
case 'html':
return 'lucide:fileCode';
case 'css':
case 'scss':
case 'less':
return 'lucide:fileCode';
case 'md':
return 'lucide:fileText';
case 'png':
case 'jpg':
case 'jpeg':
case 'gif':
case 'svg':
return 'lucide:image';
default:
return 'lucide:file';
}
}
private getFileIconClass(node: ITreeNode): string {
if (node.type === 'directory') return 'folder';
const ext = node.name.split('.').pop()?.toLowerCase();
switch (ext) {
case 'ts':
case 'tsx':
return 'typescript';
case 'js':
case 'jsx':
return 'javascript';
case 'json':
return 'json';
case 'html':
return 'html';
case 'css':
case 'scss':
case 'less':
return 'css';
case 'md':
return 'markdown';
default:
return 'file';
}
}
private async handleItemClick(e: MouseEvent, node: ITreeNode) {
e.stopPropagation();
if (node.type === 'directory') {
await this.toggleDirectory(node);
} else {
this.selectedPath = node.path;
this.dispatchEvent(
new CustomEvent('file-select', {
detail: { path: node.path, name: node.name },
bubbles: true,
composed: true,
})
);
}
}
private async toggleDirectory(node: ITreeNode) {
if (this.expandedPaths.has(node.path)) {
this.expandedPaths.delete(node.path);
} else {
this.expandedPaths.add(node.path);
// Load children if not already loaded
if (!node.children || node.children.length === 0) {
await this.loadDirectoryContents(node);
}
}
this.requestUpdate();
}
private async loadDirectoryContents(node: ITreeNode) {
if (!this.executionEnvironment) return;
try {
const entries = await this.executionEnvironment.readDir(node.path);
node.children = this.sortEntries(entries).map(entry => ({
...entry,
level: node.level + 1,
expanded: false,
children: entry.type === 'directory' ? [] : undefined,
}));
} catch (error) {
console.error(`Failed to load directory ${node.path}:`, error);
}
}
private async handleContextMenu(e: MouseEvent, node: ITreeNode) {
e.preventDefault();
e.stopPropagation();
const menuItems = [];
if (node.type === 'directory') {
// Directory-specific options
menuItems.push(
{
name: 'New File',
iconName: 'filePlus',
action: async () => this.createNewFile(node.path),
},
{
name: 'New Folder',
iconName: 'folderPlus',
action: async () => this.createNewFolder(node.path),
},
{ divider: true }
);
}
// Common options for both files and directories
menuItems.push(
{
name: 'Rename',
iconName: 'pencil',
action: async () => this.renameItem(node),
},
{
name: 'Duplicate',
iconName: 'files',
action: async () => this.duplicateItem(node),
},
{
name: 'Copy',
iconName: 'copy',
action: async () => this.copyItem(node),
}
);
// Paste option (only for directories and when clipboard has content)
if (node.type === 'directory' && this.clipboardPath) {
menuItems.push({
name: 'Paste',
iconName: 'clipboard',
action: async () => this.pasteItem(node.path),
});
}
menuItems.push(
{ divider: true },
{
name: 'Delete',
iconName: 'trash2',
action: async () => this.deleteItem(node),
}
);
await DeesContextmenu.openContextMenuWithOptions(e, menuItems);
}
private async handleEmptySpaceContextMenu(e: MouseEvent) {
// Only trigger if clicking on the container itself, not a tree item
const target = e.target as HTMLElement;
if (target.closest('.tree-item')) return;
e.preventDefault();
e.stopPropagation();
const menuItems: any[] = [
{
name: 'New File',
iconName: 'filePlus',
action: async () => this.createNewFile('/'),
},
{
name: 'New Folder',
iconName: 'folderPlus',
action: async () => this.createNewFolder('/'),
},
];
// Add Paste option if clipboard has content
if (this.clipboardPath) {
menuItems.push(
{ divider: true },
{
name: 'Paste',
iconName: 'clipboard',
action: async () => this.pasteItem('/'),
}
);
}
await DeesContextmenu.openContextMenuWithOptions(e, menuItems);
}
private async showInputModal(options: {
heading: string;
label: string;
value?: string;
buttonName?: string;
}): Promise<string | null> {
return new Promise(async (resolve) => {
const modal = await DeesModal.createAndShow({
heading: options.heading,
width: 'small',
content: html`
<dees-input-text
.label=${options.label}
.value=${options.value || ''}
></dees-input-text>
`,
menuOptions: [
{
name: 'Cancel',
action: async (modalRef) => {
await modalRef.destroy();
resolve(null);
},
},
{
name: options.buttonName || 'Create',
action: async (modalRef) => {
// Query the input element directly and read its value
const contentEl = modalRef.shadowRoot?.querySelector('.modal .content');
const inputElement = contentEl?.querySelector('dees-input-text') as DeesInputText | null;
const inputValue = inputElement?.value?.trim() || '';
await modalRef.destroy();
resolve(inputValue || null);
},
},
],
});
// Focus the input after modal renders
await modal.updateComplete;
const contentEl = modal.shadowRoot?.querySelector('.modal .content');
if (contentEl) {
const inputElement = contentEl.querySelector('dees-input-text') as DeesInputText | null;
if (inputElement) {
await inputElement.updateComplete;
inputElement.focus();
}
}
});
}
private async createNewFile(parentPath: string) {
const fileName = await this.showInputModal({
heading: 'New File',
label: 'File name',
});
if (!fileName || !this.executionEnvironment) return;
const newPath = parentPath === '/' ? `/${fileName}` : `${parentPath}/${fileName}`;
try {
await this.executionEnvironment.writeFile(newPath, '');
await this.refresh();
this.dispatchEvent(
new CustomEvent('file-created', {
detail: { path: newPath },
bubbles: true,
composed: true,
})
);
} catch (error) {
console.error('Failed to create file:', error);
}
}
private async createNewFolder(parentPath: string) {
const folderName = await this.showInputModal({
heading: 'New Folder',
label: 'Folder name',
});
if (!folderName || !this.executionEnvironment) return;
const newPath = parentPath === '/' ? `/${folderName}` : `${parentPath}/${folderName}`;
try {
await this.executionEnvironment.mkdir(newPath);
await this.refresh();
this.dispatchEvent(
new CustomEvent('folder-created', {
detail: { path: newPath },
bubbles: true,
composed: true,
})
);
} catch (error) {
console.error('Failed to create folder:', error);
}
}
private async deleteItem(node: ITreeNode) {
if (!this.executionEnvironment) return;
const confirmed = confirm(`Delete ${node.name}?`);
if (!confirmed) return;
try {
await this.executionEnvironment.rm(node.path, { recursive: node.type === 'directory' });
await this.refresh();
this.dispatchEvent(
new CustomEvent('item-deleted', {
detail: { path: node.path, type: node.type },
bubbles: true,
composed: true,
})
);
} catch (error) {
console.error('Failed to delete item:', error);
}
}
/**
* Rename a file or folder
*/
private async renameItem(node: ITreeNode) {
if (!this.executionEnvironment) return;
const newName = await this.showInputModal({
heading: 'Rename',
label: 'New name',
value: node.name,
buttonName: 'Rename',
});
if (!newName || newName === node.name) return;
// Calculate new path
const parentPath = node.path.substring(0, node.path.lastIndexOf('/')) || '/';
const newPath = parentPath === '/' ? `/${newName}` : `${parentPath}/${newName}`;
try {
if (node.type === 'file') {
// For files: read content, write to new path, delete old
const content = await this.executionEnvironment.readFile(node.path);
await this.executionEnvironment.writeFile(newPath, content);
await this.executionEnvironment.rm(node.path);
} else {
// For directories: recursively copy contents then delete old
await this.copyDirectoryContents(node.path, newPath);
await this.executionEnvironment.rm(node.path, { recursive: true });
}
await this.refresh();
this.dispatchEvent(
new CustomEvent('item-renamed', {
detail: { oldPath: node.path, newPath, type: node.type },
bubbles: true,
composed: true,
})
);
} catch (error) {
console.error('Failed to rename item:', error);
}
}
/**
* Duplicate a file or folder
*/
private async duplicateItem(node: ITreeNode) {
if (!this.executionEnvironment) return;
const parentPath = node.path.substring(0, node.path.lastIndexOf('/')) || '/';
let newName: string;
if (node.type === 'file') {
// Add _copy before extension
const lastDot = node.name.lastIndexOf('.');
if (lastDot > 0) {
const baseName = node.name.substring(0, lastDot);
const ext = node.name.substring(lastDot);
newName = `${baseName}_copy${ext}`;
} else {
newName = `${node.name}_copy`;
}
} else {
newName = `${node.name}_copy`;
}
const newPath = parentPath === '/' ? `/${newName}` : `${parentPath}/${newName}`;
try {
if (node.type === 'file') {
const content = await this.executionEnvironment.readFile(node.path);
await this.executionEnvironment.writeFile(newPath, content);
} else {
await this.copyDirectoryContents(node.path, newPath);
}
await this.refresh();
this.dispatchEvent(
new CustomEvent('item-duplicated', {
detail: { sourcePath: node.path, newPath, type: node.type },
bubbles: true,
composed: true,
})
);
} catch (error) {
console.error('Failed to duplicate item:', error);
}
}
/**
* Copy item path to clipboard
*/
private async copyItem(node: ITreeNode) {
this.clipboardPath = node.path;
this.clipboardOperation = 'copy';
}
/**
* Paste copied item to target directory
*/
private async pasteItem(targetPath: string) {
if (!this.executionEnvironment || !this.clipboardPath) return;
// Get the name from clipboard path
const name = this.clipboardPath.split('/').pop() || 'pasted';
const newPath = targetPath === '/' ? `/${name}` : `${targetPath}/${name}`;
try {
// Check if source exists
if (!(await this.executionEnvironment.exists(this.clipboardPath))) {
console.error('Source file no longer exists');
this.clipboardPath = null;
this.clipboardOperation = null;
return;
}
// Check if it's a file or directory by trying to read as file
try {
const content = await this.executionEnvironment.readFile(this.clipboardPath);
await this.executionEnvironment.writeFile(newPath, content);
} catch {
// If reading fails, it's a directory
await this.copyDirectoryContents(this.clipboardPath, newPath);
}
await this.refresh();
this.dispatchEvent(
new CustomEvent('item-pasted', {
detail: { sourcePath: this.clipboardPath, targetPath: newPath },
bubbles: true,
composed: true,
})
);
// Clear clipboard after paste
this.clipboardPath = null;
this.clipboardOperation = null;
} catch (error) {
console.error('Failed to paste item:', error);
}
}
/**
* Recursively copy directory contents to a new path
*/
private async copyDirectoryContents(sourcePath: string, destPath: string) {
if (!this.executionEnvironment) return;
// Create destination directory
await this.executionEnvironment.mkdir(destPath);
// Read source directory contents
const entries = await this.executionEnvironment.readDir(sourcePath);
for (const entry of entries) {
const srcEntryPath = sourcePath === '/' ? `/${entry.name}` : `${sourcePath}/${entry.name}`;
const destEntryPath = destPath === '/' ? `/${entry.name}` : `${destPath}/${entry.name}`;
if (entry.type === 'directory') {
await this.copyDirectoryContents(srcEntryPath, destEntryPath);
} else {
const content = await this.executionEnvironment.readFile(srcEntryPath);
await this.executionEnvironment.writeFile(destEntryPath, content);
}
}
}
public async firstUpdated() {
await this.loadTree();
}
public async updated(changedProperties: Map<string, any>) {
if (changedProperties.has('executionEnvironment')) {
// Stop watching the old environment
if (this.lastExecutionEnvironment !== this.executionEnvironment) {
this.stopFileWatcher();
this.lastExecutionEnvironment = this.executionEnvironment;
}
if (this.executionEnvironment) {
await this.loadTree();
this.startFileWatcher();
}
}
}
public async disconnectedCallback() {
await super.disconnectedCallback();
this.stopFileWatcher();
if (this.refreshDebounceTimeout) {
clearTimeout(this.refreshDebounceTimeout);
this.refreshDebounceTimeout = null;
}
}
private startFileWatcher() {
if (!this.executionEnvironment || this.fileWatcher) return;
try {
this.fileWatcher = this.executionEnvironment.watch(
'/',
(_event, _filename) => {
// Debounce refresh to avoid excessive updates
if (this.refreshDebounceTimeout) {
clearTimeout(this.refreshDebounceTimeout);
}
this.refreshDebounceTimeout = setTimeout(() => {
this.refresh();
}, 300);
},
{ recursive: true }
);
} catch (error) {
console.warn('File watching not supported:', error);
}
}
private stopFileWatcher() {
if (this.fileWatcher) {
this.fileWatcher.stop();
this.fileWatcher = null;
}
}
private async loadTree() {
if (!this.executionEnvironment) return;
// Prevent double loading on initial render
if (this.loadTreeStarted) return;
this.loadTreeStarted = true;
this.isLoading = true;
this.errorMessage = '';
try {
// Wait for environment to be ready
if (!this.executionEnvironment.ready) {
await this.executionEnvironment.init();
}
const entries = await this.executionEnvironment.readDir(this.rootPath);
this.treeData = this.sortEntries(entries).map(entry => ({
...entry,
level: 0,
expanded: false,
children: entry.type === 'directory' ? [] : undefined,
}));
} catch (error) {
this.errorMessage = `Failed to load files: ${error}`;
console.error('Failed to load file tree:', error);
// Reset flag to allow retry
this.loadTreeStarted = false;
} finally {
this.isLoading = false;
}
}
private sortEntries(entries: IFileEntry[]): IFileEntry[] {
return entries.sort((a, b) => {
// Directories first
if (a.type !== b.type) {
return a.type === 'directory' ? -1 : 1;
}
// Then alphabetically
return a.name.localeCompare(b.name);
});
}
public async refresh() {
this.expandedPaths.clear();
this.loadTreeStarted = false; // Reset to allow loading
await this.loadTree();
}
public selectFile(path: string) {
this.selectedPath = path;
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-filetree.js';

View File

@@ -0,0 +1,102 @@
import {
DeesElement,
property,
html,
customElement,
type TemplateResult,
css,
cssManager,
domtools
} from '@design.estate/dees-element';
import { themeDefaultStyles } from '../../00theme.js';
import { DeesWorkspaceMonaco } from '../dees-workspace-monaco/dees-workspace-monaco.js';
const deferred = domtools.plugins.smartpromise.defer();
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-markdown': DeesWorkspaceMarkdown;
}
}
@customElement('dees-workspace-markdown')
export class DeesWorkspaceMarkdown extends DeesElement {
public static demo = () => html`<dees-workspace-markdown></dees-workspace-markdown>`;
public static styles = [
themeDefaultStyles,
cssManager.defaultStyles,
css`
/* TODO: Migrate hardcoded values to --dees-* CSS variables */
.gridcontainer {
position: absolute;
height: 100%;
width: 100%;
display: grid;
grid-template-columns: 60% 40%;
}
.editorContainer {
position: relative;
}
.outletContainer {
background: #111;
color: #fff;
font-family: 'Roboto Slab';
padding: 20px;
overflow-y: scroll;
}
`,
];
public render() {
return html`
<div class="gridcontainer">
<div class="editorContainer">
<dees-workspace-monaco
.language=${'markdown'}
.content=${`# a test content
This is test content that is of longer form an hopefully starts to wrap when I need it. And yes, it does perfectly. nice.
Test | Hello
--- | ---
Yeah | So good
This is real asset I think. Why would we want to leave that on the table? Can you tell my that?
Why are we here?
Do you know?
> note:
There is something going on.
\`\`\`typescript
const hello = 'yes'
\`\`\`
`}
wordWrap="bounded"
></dees-workspace-monaco>
</div>
<div class="outletContainer">
<dees-workspace-markdownoutlet></dees-workspace-markdownoutlet>
</div>
</div>
`;
}
public async firstUpdated(_changedPropertiesArg) {
await super.firstUpdated(_changedPropertiesArg);
const editor = this.shadowRoot.querySelector('dees-workspace-monaco') as DeesWorkspaceMonaco;
// lets care about wiring the markdown stuff.
const markdownOutlet = this.shadowRoot.querySelector('dees-workspace-markdownoutlet');
const smartmarkdownInstance = new domtools.plugins.smartmarkdown.SmartMarkdown();
const mdParsedResult = await smartmarkdownInstance.getMdParsedResultFromMarkdown('loading...')
editor.contentSubject.subscribe(async contentArg => {
await mdParsedResult.updateFromMarkdownString(contentArg)
const html = mdParsedResult.html;
markdownOutlet.updateHtmlText(html);
})
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-markdown.js';

View File

@@ -0,0 +1,42 @@
import { customElement, DeesElement, html, type TemplateResult } from '@design.estate/dees-element';
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-markdownoutlet': DeesWorkspaceMarkdownoutlet;
}
}
@customElement('dees-workspace-markdownoutlet')
export class DeesWorkspaceMarkdownoutlet extends DeesElement {
// DEMO
public static demo = () => html`<dees-workspace-markdownoutlet></dees-workspace-markdownoutlet>`;
// INSTANCE
private outlet: HTMLElement;
public render(): TemplateResult {
return html`
<div class="outlet markdown-body">
<h1>Hi there</h1>
</div>
`;
}
public async firstUpdated(_changedProperties: Map<string | number | symbol, unknown>) {
await super.firstUpdated(_changedProperties);
const styleElement = document.createElement('style');
const cssText = await (
await fetch('https://unpkg.com/github-markdown-css@5.1.0/github-markdown-dark.css')
).text();
styleElement.textContent = cssText;
this.shadowRoot.append(styleElement);
}
public async updateHtmlText(htmlTextArg: string) {
await this.updateComplete;
if (!this.outlet) {
this.outlet = this.shadowRoot.querySelector('.outlet');
}
this.outlet.innerHTML = htmlTextArg;
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-markdownoutlet.js';

View File

@@ -0,0 +1,245 @@
import {
DeesElement,
property,
html,
customElement,
type TemplateResult,
css,
cssManager,
} from '@design.estate/dees-element';
import * as domtools from '@design.estate/dees-domtools';
import { MONACO_VERSION } from './version.js';
import { themeDefaultStyles } from '../../00theme.js';
import type * as monaco from 'monaco-editor';
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-monaco': DeesWorkspaceMonaco;
}
}
@customElement('dees-workspace-monaco')
export class DeesWorkspaceMonaco extends DeesElement {
// DEMO
public static demo = () => html`<dees-workspace-monaco></dees-workspace-monaco>`;
// STATIC
public static monacoDeferred: ReturnType<typeof domtools.plugins.smartpromise.defer>;
// INSTANCE
public editorDeferred = domtools.plugins.smartpromise.defer<monaco.editor.IStandaloneCodeEditor>();
@property({
type: String
})
accessor content = "function hello() {\n\talert('Hello world!');\n}";
@property({
type: String
})
accessor language = 'typescript';
@property({
type: String
})
accessor filePath: string = '';
@property({
type: Object
})
accessor contentSubject = new domtools.plugins.smartrx.rxjs.Subject<string>();
@property({
type: Boolean
})
accessor wordWrap: monaco.editor.IStandaloneEditorConstructionOptions['wordWrap'] = 'off';
private monacoThemeSubscription: domtools.plugins.smartrx.rxjs.Subscription | null = null;
private isUpdatingFromExternal: boolean = false;
constructor() {
super();
domtools.DomTools.setupDomTools();
}
public static styles = [
themeDefaultStyles,
cssManager.defaultStyles,
css`
/* TODO: Migrate hardcoded values to --dees-* CSS variables */
:host {
}
* {
box-sizing: border-box;
}
#container {
position: absolute;
height: 100%;
width: 100%;
}
`,
];
public render(): TemplateResult {
return html`
<div class="mainbox">
<div id="container"></div>
</div>
`;
}
public async firstUpdated(
_changedProperties: Map<string | number | symbol, unknown>
): Promise<void> {
super.firstUpdated(_changedProperties);
const container = this.shadowRoot.getElementById('container');
const monacoCdnBase = `https://cdn.jsdelivr.net/npm/monaco-editor@${MONACO_VERSION}`;
if (!DeesWorkspaceMonaco.monacoDeferred) {
DeesWorkspaceMonaco.monacoDeferred = domtools.plugins.smartpromise.defer();
const scriptUrl = `${monacoCdnBase}/min/vs/loader.js`;
const script = document.createElement('script');
script.src = scriptUrl;
script.onload = () => {
DeesWorkspaceMonaco.monacoDeferred.resolve();
};
document.head.appendChild(script);
}
await DeesWorkspaceMonaco.monacoDeferred.promise;
(window as any).require.config({
paths: { vs: `${monacoCdnBase}/min/vs` },
});
(window as any).require(['vs/editor/editor.main'], async () => {
// Get current theme from domtools
const domtoolsInstance = await this.domtoolsPromise;
const isBright = domtoolsInstance.themeManager.goBrightBoolean;
const initialTheme = isBright ? 'vs' : 'vs-dark';
const monacoInstance = (window as any).monaco as typeof monaco;
// Create or get model with proper file URI for TypeScript IntelliSense
let model: monaco.editor.ITextModel | null = null;
if (this.filePath) {
const uri = monacoInstance.Uri.parse(`file://${this.filePath}`);
model = monacoInstance.editor.getModel(uri);
if (!model) {
model = monacoInstance.editor.createModel(this.content, this.language, uri);
} else {
model.setValue(this.content);
}
}
const editor = (monacoInstance.editor as typeof monaco.editor).create(container, {
model: model || undefined,
value: model ? undefined : this.content,
language: model ? undefined : this.language,
theme: initialTheme,
useShadowDOM: true,
fontSize: 16,
automaticLayout: true,
wordWrap: this.wordWrap,
hover: {
enabled: true,
delay: 300,
sticky: true,
above: false,
},
});
// Subscribe to theme changes
this.monacoThemeSubscription = domtoolsInstance.themeManager.themeObservable.subscribe((goBright: boolean) => {
const newTheme = goBright ? 'vs' : 'vs-dark';
editor.updateOptions({ theme: newTheme });
});
this.editorDeferred.resolve(editor);
});
const css = await (
await fetch(`${monacoCdnBase}/min/vs/editor/editor.main.css`)
).text();
const styleElement = document.createElement('style');
styleElement.textContent = css;
this.shadowRoot.append(styleElement);
// editor is setup let do the rest
const editor = await this.editorDeferred.promise;
editor.onDidChangeModelContent(async eventArg => {
// Don't emit events when we're programmatically updating the content
if (this.isUpdatingFromExternal) return;
const value = editor.getValue();
this.contentSubject.next(value);
this.dispatchEvent(new CustomEvent('content-change', {
detail: value,
bubbles: true,
composed: true,
}));
});
this.contentSubject.next(editor.getValue());
}
public async updated(changedProperties: Map<string, any>): Promise<void> {
super.updated(changedProperties);
const monacoInstance = (window as any).monaco as typeof monaco;
if (!monacoInstance) return;
// Handle filePath changes - switch to different model
if (changedProperties.has('filePath') && this.filePath) {
const editor = await this.editorDeferred.promise;
const uri = monacoInstance.Uri.parse(`file://${this.filePath}`);
let model = monacoInstance.editor.getModel(uri);
if (!model) {
model = monacoInstance.editor.createModel(this.content, this.language, uri);
} else {
// Update model content if different
if (model.getValue() !== this.content) {
this.isUpdatingFromExternal = true;
model.setValue(this.content);
this.isUpdatingFromExternal = false;
}
}
// Switch editor to use this model
const currentModel = editor.getModel();
if (currentModel?.uri.toString() !== uri.toString()) {
editor.setModel(model);
}
return; // filePath change handles content too
}
// Handle content changes (when no filePath or filePath unchanged)
if (changedProperties.has('content')) {
const editor = await this.editorDeferred.promise;
const currentValue = editor.getValue();
if (currentValue !== this.content) {
this.isUpdatingFromExternal = true;
editor.setValue(this.content);
this.isUpdatingFromExternal = false;
}
}
// Handle language changes
if (changedProperties.has('language')) {
const editor = await this.editorDeferred.promise;
const model = editor.getModel();
if (model) {
monacoInstance.editor.setModelLanguage(model, this.language);
}
}
}
public async disconnectedCallback(): Promise<void> {
await super.disconnectedCallback();
if (this.monacoThemeSubscription) {
this.monacoThemeSubscription.unsubscribe();
this.monacoThemeSubscription = null;
}
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-monaco.js';

View File

@@ -0,0 +1,2 @@
// Auto-generated by scripts/update-monaco-version.cjs
export const MONACO_VERSION = '0.55.1';

View File

@@ -0,0 +1,361 @@
import {
DeesElement,
property,
html,
customElement,
type TemplateResult,
css,
cssManager,
} from '@design.estate/dees-element';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { themeDefaultStyles } from '../../00theme.js';
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-terminal-preview': DeesWorkspaceTerminalPreview;
}
}
/**
* A read-only terminal preview component using xterm.js for rendering.
* Used during workspace initialization to show onInit command progress.
*/
@customElement('dees-workspace-terminal-preview')
export class DeesWorkspaceTerminalPreview extends DeesElement {
public static demo = () => html`
<dees-workspace-terminal-preview
.command=${'pnpm install'}
.lines=${[
'Packages: +42',
'Progress: resolved 142, reused 140, downloaded 2, added 42, done',
'',
'dependencies:',
'+ @push.rocks/smartpromise 4.2.3',
'+ typescript 5.3.3',
'',
'Done in 2.3s'
]}
></dees-workspace-terminal-preview>
`;
/**
* The command being displayed (shown in header)
*/
@property({ type: String })
accessor command: string = '';
/**
* Output lines to display
*/
@property({ type: Array })
accessor lines: string[] = [];
private terminal: Terminal | null = null;
private fitAddon: FitAddon | null = null;
private lastLineCount: number = 0;
private resizeObserver: ResizeObserver | null = null;
public static styles = [
themeDefaultStyles,
cssManager.defaultStyles,
css`
:host {
display: block;
height: 200px;
}
.terminal-preview {
height: 100%;
border-radius: 8px;
overflow: hidden;
background: #000000;
border: 1px solid hsl(0 0% 20%);
display: flex;
flex-direction: column;
}
.terminal-header {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: hsl(0 0% 10%);
font-size: 12px;
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', monospace;
color: hsl(0 0% 60%);
border-bottom: 1px solid hsl(0 0% 20%);
flex-shrink: 0;
}
.terminal-header-icon {
color: hsl(0 0% 50%);
}
.terminal-header-command {
color: hsl(0 0% 80%);
font-weight: 500;
}
.terminal-container {
flex: 1;
position: relative;
padding: 8px;
}
#xterm-container {
position: absolute;
top: 8px;
left: 8px;
right: 8px;
bottom: 8px;
}
/* xterm.js styles */
.xterm {
font-feature-settings: 'liga' 0;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
background: #000000;
color: #fff;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
background-color: #000000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm {
cursor: text;
}
.xterm.enable-mouse-events {
cursor: default;
}
.xterm.xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
opacity: 0.5;
}
.xterm-underline {
text-decoration: underline;
}
/* Custom scrollbar for xterm viewport */
.xterm .xterm-viewport::-webkit-scrollbar {
width: 8px;
}
.xterm .xterm-viewport::-webkit-scrollbar-track {
background: hsl(0 0% 8%);
}
.xterm .xterm-viewport::-webkit-scrollbar-thumb {
background: hsl(0 0% 25%);
border-radius: 4px;
}
.xterm .xterm-viewport::-webkit-scrollbar-thumb:hover {
background: hsl(0 0% 35%);
}
`,
];
public render(): TemplateResult {
return html`
<div class="terminal-preview">
<div class="terminal-header">
<span class="terminal-header-icon">$</span>
<span class="terminal-header-command">${this.command || 'Waiting...'}</span>
</div>
<div class="terminal-container">
<div id="xterm-container"></div>
</div>
</div>
`;
}
public async firstUpdated(
_changedProperties: Map<string | number | symbol, unknown>
): Promise<void> {
super.firstUpdated(_changedProperties);
const container = this.shadowRoot?.getElementById('xterm-container');
if (!container) return;
// Create xterm terminal in read-only mode
this.terminal = new Terminal({
convertEol: true,
cursorBlink: false,
disableStdin: true,
fontSize: 12,
fontFamily: "'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', monospace",
theme: {
background: '#000000',
foreground: '#cccccc',
},
scrollback: 1000,
});
this.fitAddon = new FitAddon();
this.terminal.loadAddon(this.fitAddon);
this.terminal.open(container);
this.fitAddon.fit();
// Set up resize observer to refit terminal
this.resizeObserver = new ResizeObserver(() => {
if (this.fitAddon) {
this.fitAddon.fit();
}
});
this.resizeObserver.observe(container);
// Write any existing lines
this.writeNewLines();
}
public async updated(changedProperties: Map<string, any>) {
super.updated(changedProperties);
if (changedProperties.has('lines')) {
this.writeNewLines();
}
}
private writeNewLines() {
if (!this.terminal) return;
// Write only new lines since last update
const newLines = this.lines.slice(this.lastLineCount);
for (const line of newLines) {
this.terminal.writeln(line);
}
this.lastLineCount = this.lines.length;
}
public async disconnectedCallback(): Promise<void> {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
if (this.terminal) {
this.terminal.dispose();
this.terminal = null;
}
await super.disconnectedCallback();
}
/**
* Add a new line to the output
*/
public addLine(line: string) {
this.lines = [...this.lines, line];
}
/**
* Clear all output lines
*/
public clear() {
this.lines = [];
this.lastLineCount = 0;
if (this.terminal) {
this.terminal.clear();
}
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-terminal-preview.js';

View File

@@ -0,0 +1,434 @@
import {
DeesElement,
property,
html,
customElement,
type TemplateResult,
css,
cssManager,
} from '@design.estate/dees-element';
import * as domtools from '@design.estate/dees-domtools';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { themeDefaultStyles } from '../../00theme.js';
import type { IExecutionEnvironment } from '../../00group-runtime/index.js';
import { WebContainerEnvironment } from '../../00group-runtime/index.js';
declare global {
interface HTMLElementTagNameMap {
'dees-workspace-terminal': DeesWorkspaceTerminal;
}
}
@customElement('dees-workspace-terminal')
export class DeesWorkspaceTerminal extends DeesElement {
public static demo = () => {
const env = new WebContainerEnvironment();
return html`<dees-workspace-terminal .executionEnvironment=${env}></dees-workspace-terminal>`;
};
// INSTANCE
private resizeObserver: ResizeObserver;
/**
* The execution environment (required).
* Use WebContainerEnvironment for browser-based execution.
*/
@property({ type: Object })
accessor executionEnvironment: IExecutionEnvironment | null = null;
@property()
accessor setupCommand = `pnpm install @serve.zone/cli && servezone cli\n`;
/**
* Environment variables to set in the shell
*/
@property()
accessor environmentVariables: { [key: string]: string } = {};
@property()
accessor background: string = '#000000';
/**
* Promise that resolves when the environment is ready.
* @deprecated Use executionEnvironment directly
*/
private environmentDeferred = new domtools.plugins.smartpromise.Deferred<IExecutionEnvironment>();
public environmentPromise = this.environmentDeferred.promise;
constructor() {
super();
this.resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
// Handle the resize event
console.log(`Terminal Resized`);
this.handleResize();
}
});
}
public static styles = [
themeDefaultStyles,
cssManager.defaultStyles,
css`
/* TODO: Migrate hardcoded values to --dees-* CSS variables */
:host {
padding: 20px;
background: var(--dees-terminal-background, #000000);
position: absolute;
height: 100%;
width: 100%;
}
* {
box-sizing: border-box;
}
#container {
position: absolute;
height: calc(100% - 40px);
width: calc(100% - 40px);
}
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
font-feature-settings: 'liga' 0;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: var(--dees-terminal-background, #000000);
color: #fff;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: var(--dees-terminal-background, #000000);
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm {
cursor: text;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
opacity: 0.5;
}
.xterm-underline {
text-decoration: underline;
}
`,
];
public render(): TemplateResult {
return html`
<div class="mainbox">
<div id="container"></div>
</div>
`;
}
private fitAddon: FitAddon;
private terminal: Terminal | null = null;
public async firstUpdated(
_changedProperties: Map<string | number | symbol, unknown>
): Promise<void> {
const domtools = await this.domtoolsPromise;
super.firstUpdated(_changedProperties);
// Sync CSS variable with background property
this.style.setProperty('--dees-terminal-background', this.background);
const container = this.shadowRoot.getElementById('container');
const term = new Terminal({
convertEol: true,
cursorBlink: true,
theme: {
background: this.background,
},
});
this.terminal = term;
this.fitAddon = new FitAddon();
term.loadAddon(this.fitAddon);
// Open the terminal in #terminal-container
term.open(container);
// Make the terminal's size and geometry fit the size of #terminal-container
this.fitAddon.fit();
// Check if execution environment is provided
if (!this.executionEnvironment) {
term.write('\x1b[31m'); // Red color
term.write('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\r\n');
term.write(' ❌ No execution environment provided.\r\n');
term.write('\r\n');
term.write(' Pass an IExecutionEnvironment via the\r\n');
term.write(' \'executionEnvironment\' property.\r\n');
term.write('\r\n');
term.write(' Example:\r\n');
term.write(' const env = new WebContainerEnvironment();\r\n');
term.write(' <dees-terminal .executionEnvironment=${env}>\r\n');
term.write('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\r\n');
term.write('\x1b[0m'); // Reset color
return;
}
term.write('Initializing execution environment...\r\n');
// Initialize the execution environment
try {
await this.executionEnvironment.init();
term.write('Environment ready. Starting shell...\r\n');
} catch (error) {
term.write('\x1b[31m'); // Red color
term.write(`\r\n❌ Failed to initialize environment: ${error}\r\n`);
term.write('\x1b[0m'); // Reset color
console.error('Failed to initialize execution environment:', error);
return;
}
// Spawn shell process
let shellProcess;
try {
shellProcess = await this.executionEnvironment.spawn('jsh');
} catch (error) {
term.write('\x1b[31m'); // Red color
term.write(`\r\n❌ Failed to spawn shell: ${error}\r\n`);
term.write('\x1b[0m'); // Reset color
console.error('Failed to spawn shell:', error);
return;
}
shellProcess.output.pipeTo(
new WritableStream({
write(data) {
term.write(data);
},
})
);
const input = shellProcess.input.getWriter();
term.onData((data) => {
input.write(data);
});
await this.waitForPrompt(term, '~/');
// Set environment variables if provided
if (Object.keys(this.environmentVariables).length > 0) {
await this.setEnvironmentVariables(this.environmentVariables);
input.write(`source source.env\n`);
await this.waitForPrompt(term, '~/');
}
// Run setup command if provided
if (this.setupCommand) {
input.write(this.setupCommand);
await this.waitForPrompt(term, '~/');
}
input.write(`clear && echo 'Terminal ready.'\n`);
this.environmentDeferred.resolve(this.executionEnvironment);
}
async connectedCallback(): Promise<void> {
await super.connectedCallback();
this.resizeObserver.observe(this);
}
async disconnectedCallback(): Promise<void> {
this.resizeObserver.unobserve(this);
await super.disconnectedCallback();
}
handleResize() {
this.fitAddon.fit();
}
public async waitForPrompt(term: Terminal, prompt: string): Promise<void> {
return new Promise<void>((resolve) => {
const checkPrompt = () => {
const lines = term.buffer.active;
for (let i = 0; i < lines.length; i++) {
const line = lines.getLine(i);
if (line && line.translateToString().includes(prompt)) {
setTimeout(() => {
resolve();
}, 100);
return;
}
}
setTimeout(checkPrompt, 100); // check every 100 ms
};
checkPrompt();
});
}
public async setEnvironmentVariables(envArg: { [key: string]: string }): Promise<void> {
if (!this.executionEnvironment) {
throw new Error('No execution environment available');
}
let envFile = '';
for (const key in envArg) {
envFile += `export ${key}="${envArg[key]}"\n`;
}
// Write the environment file using the filesystem API
await this.executionEnvironment.writeFile('/source.env', envFile);
}
/**
* Get the underlying execution environment.
* Useful for advanced operations like filesystem access.
*/
public getExecutionEnvironment(): IExecutionEnvironment | null {
return this.executionEnvironment;
}
}

View File

@@ -0,0 +1 @@
export * from './dees-workspace-terminal.js';

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
export * from './dees-workspace.js';
export * from './typescript-intellisense.js';

View File

@@ -0,0 +1,450 @@
import type * as monaco from 'monaco-editor';
import type { IExecutionEnvironment } from '../../00group-runtime/index.js';
// Monaco TypeScript API types (runtime API still exists, types deprecated in 0.55+)
interface IExtraLibDisposable {
dispose(): void;
}
interface IMonacoTypeScriptAPI {
typescriptDefaults: {
setCompilerOptions(options: Record<string, unknown>): void;
setDiagnosticsOptions(options: Record<string, unknown>): void;
addExtraLib(content: string, filePath?: string): IExtraLibDisposable;
setEagerModelSync(value: boolean): void;
};
ScriptTarget: { ES2020: number };
ModuleKind: { ESNext: number };
ModuleResolutionKind: { NodeJs: number; Bundler?: number };
}
/**
* Manages TypeScript IntelliSense by loading type definitions
* from the virtual filesystem into Monaco.
*/
export class TypeScriptIntelliSenseManager {
private loadedLibs: Set<string> = new Set();
private notFoundPackages: Set<string> = new Set(); // Packages checked but not found
private monacoInstance: typeof monaco | null = null;
private executionEnvironment: IExecutionEnvironment | null = null;
// Cache of file contents for synchronous access and module resolution
private fileCache: Map<string, string> = new Map();
// Track extra libs added for cleanup
private addedExtraLibs: Map<string, IExtraLibDisposable> = new Map();
/**
* Get TypeScript API with proper typing for Monaco 0.55+
*/
private get tsApi(): IMonacoTypeScriptAPI | null {
if (!this.monacoInstance) return null;
return (this.monacoInstance.languages as any).typescript as IMonacoTypeScriptAPI;
}
/**
* Initialize with Monaco and execution environment
*/
public async init(
monacoInst: typeof monaco,
env: IExecutionEnvironment
): Promise<void> {
this.monacoInstance = monacoInst;
this.executionEnvironment = env;
this.configureCompilerOptions();
// Load all project TypeScript/JavaScript files into Monaco for cross-file resolution
await this.loadAllProjectFiles();
}
/**
* Recursively load all .ts/.js files from the virtual filesystem into Monaco
*/
private async loadAllProjectFiles(): Promise<void> {
if (!this.executionEnvironment) return;
await this.loadFilesFromDirectory('/');
}
/**
* Recursively load files from a directory
*/
private async loadFilesFromDirectory(dirPath: string): Promise<void> {
if (!this.executionEnvironment) return;
try {
const entries = await this.executionEnvironment.readDir(dirPath);
for (const entry of entries) {
const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`;
// Skip node_modules - too large and handled separately via addExtraLib
if (entry.name === 'node_modules') continue;
if (entry.type === 'directory') {
await this.loadFilesFromDirectory(fullPath);
} else if (entry.type === 'file') {
const ext = entry.name.split('.').pop()?.toLowerCase();
if (ext === 'ts' || ext === 'tsx' || ext === 'js' || ext === 'jsx') {
try {
const content = await this.executionEnvironment.readFile(fullPath);
this.addFileModel(fullPath, content);
} catch {
// Ignore files that can't be read
}
}
}
}
} catch {
// Directory might not exist or not be readable
}
}
private configureCompilerOptions(): void {
const ts = this.tsApi;
if (!ts) return;
ts.typescriptDefaults.setCompilerOptions({
target: ts.ScriptTarget.ES2020,
module: ts.ModuleKind.ESNext,
// Use Bundler resolution if available (Monaco 0.45+), fallback to NodeJs
moduleResolution: ts.ModuleResolutionKind.Bundler ?? ts.ModuleResolutionKind.NodeJs,
allowSyntheticDefaultImports: true,
esModuleInterop: true,
strict: true,
noEmit: true,
allowJs: true,
checkJs: false,
allowNonTsExtensions: true,
lib: ['es2020', 'dom', 'dom.iterable'],
// Set baseUrl to root for resolving absolute imports
baseUrl: '/',
// Allow importing .ts extensions directly (useful for some setups)
allowImportingTsExtensions: true,
// Resolve JSON modules
resolveJsonModule: true,
});
ts.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: false,
noSyntaxValidation: false,
});
// Enable eager model sync so TypeScript immediately processes all models
// This is critical for cross-file IntelliSense to work without requiring edits
ts.typescriptDefaults.setEagerModelSync(true);
}
/**
* Parse imports from TypeScript/JavaScript content
*/
public parseImports(content: string): string[] {
const imports: string[] = [];
// Match ES6 imports: import { x } from 'package' or import 'package'
const importRegex = /import\s+(?:[\w*{}\s,]+from\s+)?['"]([^'"]+)['"]/g;
let match: RegExpExecArray | null;
while ((match = importRegex.exec(content)) !== null) {
const importPath = match[1];
// Only process non-relative imports (npm packages)
if (!importPath.startsWith('.') && !importPath.startsWith('/')) {
const packageName = importPath.startsWith('@')
? importPath.split('/').slice(0, 2).join('/') // @scope/package
: importPath.split('/')[0]; // package
imports.push(packageName);
}
}
// Match require calls: require('package')
const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
while ((match = requireRegex.exec(content)) !== null) {
const importPath = match[1];
if (!importPath.startsWith('.') && !importPath.startsWith('/')) {
const packageName = importPath.startsWith('@')
? importPath.split('/').slice(0, 2).join('/')
: importPath.split('/')[0];
imports.push(packageName);
}
}
return [...new Set(imports)];
}
/**
* Load type definitions for a package from virtual FS
*/
public async loadTypesForPackage(packageName: string): Promise<void> {
if (!this.monacoInstance || !this.executionEnvironment) return;
if (this.loadedLibs.has(packageName)) return;
if (this.notFoundPackages.has(packageName)) return; // Skip packages we already checked
try {
let typesLoaded = await this.tryLoadPackageTypes(packageName);
if (!typesLoaded) {
typesLoaded = await this.tryLoadAtTypesPackage(packageName);
}
if (typesLoaded) {
this.loadedLibs.add(packageName);
} else {
// Cache that this package wasn't found to avoid repeated filesystem checks
this.notFoundPackages.add(packageName);
}
} catch (error) {
console.warn(`Failed to load types for ${packageName}:`, error);
}
}
private async tryLoadPackageTypes(packageName: string): Promise<boolean> {
const ts = this.tsApi;
if (!this.executionEnvironment || !ts) return false;
const basePath = `/node_modules/${packageName}`;
try {
// Check package.json for types field
const packageJsonPath = `${basePath}/package.json`;
const packageJsonExists = await this.executionEnvironment.exists(packageJsonPath);
if (packageJsonExists) {
const packageJsonContent = await this.executionEnvironment.readFile(packageJsonPath);
const packageJson = JSON.parse(packageJsonContent);
// Add package.json to Monaco so TypeScript can resolve the types field
ts.typescriptDefaults.addExtraLib(packageJsonContent, `file://${packageJsonPath}`);
const typesPath = packageJson.types || packageJson.typings;
if (typesPath) {
// Load all .d.ts files from the package, not just the entry point
// Modern packages often have multiple declaration files with imports
await this.loadAllDtsFilesFromPackage(basePath);
return true;
}
}
// Try common locations - if any exist, load all .d.ts files
const commonPaths = [
`${basePath}/index.d.ts`,
`${basePath}/dist/index.d.ts`,
`${basePath}/lib/index.d.ts`,
];
for (const dtsPath of commonPaths) {
if (await this.executionEnvironment.exists(dtsPath)) {
await this.loadAllDtsFilesFromPackage(basePath);
return true;
}
}
return false;
} catch (error) {
console.error(`Failed to load package types for ${packageName}:`, error);
return false;
}
}
/**
* Recursively load all .d.ts files from a package directory
*/
private async loadAllDtsFilesFromPackage(basePath: string): Promise<void> {
const ts = this.tsApi;
if (!this.executionEnvironment || !ts) return;
await this.loadDtsFilesFromDirectory(basePath);
}
/**
* Recursively load .d.ts files from a directory
*/
private async loadDtsFilesFromDirectory(dirPath: string): Promise<void> {
const ts = this.tsApi;
if (!this.executionEnvironment || !ts) return;
try {
const entries = await this.executionEnvironment.readDir(dirPath);
for (const entry of entries) {
const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`;
// Skip nested node_modules (shouldn't happen in a package but be safe)
if (entry.name === 'node_modules') continue;
if (entry.type === 'directory') {
await this.loadDtsFilesFromDirectory(fullPath);
} else if (entry.type === 'file' && entry.name.endsWith('.d.ts')) {
try {
const content = await this.executionEnvironment.readFile(fullPath);
ts.typescriptDefaults.addExtraLib(content, `file://${fullPath}`);
} catch {
// Ignore files that can't be read
}
}
}
} catch {
// Directory might not be readable
}
}
private async tryLoadAtTypesPackage(packageName: string): Promise<boolean> {
if (!this.executionEnvironment) return false;
// Handle scoped packages: @scope/package -> @types/scope__package
const typesPackageName = packageName.startsWith('@')
? `@types/${packageName.slice(1).replace('/', '__')}`
: `@types/${packageName}`;
const basePath = `/node_modules/${typesPackageName}`;
try {
const indexPath = `${basePath}/index.d.ts`;
if (await this.executionEnvironment.exists(indexPath)) {
// Load all .d.ts files from the @types package
await this.loadAllDtsFilesFromPackage(basePath);
return true;
}
return false;
} catch {
return false;
}
}
/**
* Process content change and load types for any new imports
*/
public async processContentChange(content: string): Promise<void> {
const imports = this.parseImports(content);
for (const packageName of imports) {
if (!this.loadedLibs.has(packageName)) {
await this.loadTypesForPackage(packageName);
}
}
}
/**
* Scan node_modules for packages and load types for any not yet loaded.
* Called when node_modules changes (e.g., after pnpm install).
*/
public async scanAndLoadNewPackageTypes(): Promise<void> {
if (!this.executionEnvironment) return;
// Clear not-found cache so newly installed packages can be detected
this.notFoundPackages.clear();
try {
// Check if node_modules exists
if (!await this.executionEnvironment.exists('/node_modules')) return;
// Read top-level node_modules
const entries = await this.executionEnvironment.readDir('/node_modules');
for (const entry of entries) {
if (entry.type !== 'directory') continue;
if (entry.name.startsWith('@')) {
// Scoped package - read subdirectories
try {
const scopedPath = `/node_modules/${entry.name}`;
const scopedEntries = await this.executionEnvironment.readDir(scopedPath);
for (const scopedEntry of scopedEntries) {
if (scopedEntry.type === 'directory') {
const packageName = `${entry.name}/${scopedEntry.name}`;
await this.loadTypesForPackage(packageName);
}
}
} catch {
// Skip if we can't read scoped directory
}
} else if (!entry.name.startsWith('.')) {
// Regular package
await this.loadTypesForPackage(entry.name);
}
}
} catch (error) {
console.warn('Failed to scan node_modules:', error);
}
}
/**
* Add a file model to Monaco for cross-file IntelliSense
* Also registers the file with TypeScript via addExtraLib for module resolution
*/
public addFileModel(path: string, content: string): void {
if (!this.monacoInstance) return;
// Cache the content for sync access
this.fileCache.set(path, content);
// Create/update the editor model
const uri = this.monacoInstance.Uri.parse(`file://${path}`);
const existingModel = this.monacoInstance.editor.getModel(uri);
if (existingModel) {
existingModel.setValue(content);
} else {
const language = this.getLanguageFromPath(path);
this.monacoInstance.editor.createModel(content, language, uri);
}
// Also add as extra lib for TypeScript module resolution
// This is critical - TypeScript's resolver uses extra libs, not editor models
this.addFileAsExtraLib(path, content);
}
/**
* Add a file as an extra lib for TypeScript module resolution.
* This enables TypeScript to resolve imports to project files.
*/
private addFileAsExtraLib(path: string, content: string): void {
const ts = this.tsApi;
if (!ts) return;
// Dispose existing lib if present (for updates)
const existing = this.addedExtraLibs.get(path);
if (existing) {
existing.dispose();
}
// Add the file with its actual path
const filePath = `file://${path}`;
const disposable = ts.typescriptDefaults.addExtraLib(content, filePath);
this.addedExtraLibs.set(path, disposable);
// For .ts files, also add with .js extension to handle ESM imports
// (e.g., import from './utils.js' should resolve to ./utils.ts)
if (path.endsWith('.ts') && !path.endsWith('.d.ts')) {
const jsPath = path.replace(/\.ts$/, '.js');
const jsFilePath = `file://${jsPath}`;
const jsDisposable = ts.typescriptDefaults.addExtraLib(content, jsFilePath);
this.addedExtraLibs.set(jsPath, jsDisposable);
this.fileCache.set(jsPath, content);
} else if (path.endsWith('.tsx')) {
const jsxPath = path.replace(/\.tsx$/, '.jsx');
const jsxFilePath = `file://${jsxPath}`;
const jsxDisposable = ts.typescriptDefaults.addExtraLib(content, jsxFilePath);
this.addedExtraLibs.set(jsxPath, jsxDisposable);
this.fileCache.set(jsxPath, content);
}
}
/**
* Get cached file content for synchronous access
*/
public getFileContent(path: string): string | undefined {
return this.fileCache.get(path);
}
private getLanguageFromPath(path: string): string {
const ext = path.split('.').pop()?.toLowerCase();
switch (ext) {
case 'ts':
case 'tsx':
return 'typescript';
case 'js':
case 'jsx':
return 'javascript';
case 'json':
return 'json';
default:
return 'plaintext';
}
}
}

View File

@@ -0,0 +1,8 @@
// Workspace Components
export * from './dees-workspace/index.js';
export * from './dees-workspace-monaco/index.js';
export * from './dees-workspace-filetree/index.js';
export * from './dees-workspace-terminal/index.js';
export * from './dees-workspace-terminal-preview/index.js';
export * from './dees-workspace-markdown/index.js';
export * from './dees-workspace-markdownoutlet/index.js';