Skip to content

Commit

Permalink
feat: support file sync & support format code
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanba committed Jan 24, 2024
1 parent 4f5a238 commit 6662cb6
Show file tree
Hide file tree
Showing 28 changed files with 445 additions and 189 deletions.
6 changes: 3 additions & 3 deletions packages/libro-code-cell/src/code-cell-model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ExecutionCount } from '@difizen/libro-common';
import type { ICodeCell } from '@difizen/libro-common';
import { MIME } from '@difizen/libro-common';
import type { ICodeCell, ExecutionCount } from '@difizen/libro-common';
import type { ExecutableCellModel } from '@difizen/libro-core';
import { CellOptions, LibroCellModel } from '@difizen/libro-core';
import type { Event as ManaEvent } from '@difizen/mana-app';
Expand Down Expand Up @@ -39,7 +39,7 @@ export class LibroCodeCellModel extends LibroCellModel implements ExecutableCell
this.executing = false;
this.msgChangeEmitter = new Emitter<any>();
this.executeCount = (options.cell as ICodeCell).execution_count || null;
this.mimeType = 'text/x-python';
this.mimeType = MIME.python;
this.hasOutputHidden = false;
this.hasOutputsScrolled = false;
this.viewManager = viewManager;
Expand Down
28 changes: 21 additions & 7 deletions packages/libro-code-cell/src/code-cell-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
LirboContextKey,
} from '@difizen/libro-core';
import type { ViewSize } from '@difizen/mana-app';
import { Disposable } from '@difizen/mana-app';
import { DisposableCollection } from '@difizen/mana-app';
import {
getOrigin,
inject,
Expand Down Expand Up @@ -100,6 +102,7 @@ const CodeEditorViewComponent = forwardRef<HTMLDivElement>(
@transient()
@view('code-editor-cell-view')
export class LibroCodeCellView extends LibroExecutableCellView {
protected toDisposeOnEditor = new DisposableCollection();
@inject(LirboContextKey) protected readonly lirboContextKey: LirboContextKey;
override view = CodeEditorViewComponent;

Expand Down Expand Up @@ -256,19 +259,30 @@ export class LibroCodeCellView extends LibroExecutableCellView {
if (e.status === 'ready') {
this.editor = this.editorView!.editor;
this.afterEditorReady();
} else if (e.status === 'disposed') {
this.toDisposeOnEditor.dispose();
}
});
}

protected async afterEditorReady() {
watch(this.parent.model, 'readOnly', () => {
this.editorView?.editor?.setOption(
'readOnly',
getOrigin(this.parent.model.readOnly),
);
});
this.editorView?.onModalChange((val) => (this.hasModal = val));
this.focusEditor();
this.toDisposeOnEditor.push(
watch(this.parent.model, 'readOnly', () => {
this.editorView?.editor?.setOption(
'readOnly',
getOrigin(this.parent.model.readOnly),
);
}),
);
this.toDisposeOnEditor.push(
this.editorView?.onModalChange((val) => (this.hasModal = val)) ?? Disposable.NONE,
);
this.toDisposeOnEditor.push(
this.editor?.onModelContentChanged?.((e) => {
this.parent.model.onCellContentChange({ cell: this, changes: e });
}) ?? Disposable.NONE,
);
}

protected focusEditor() {
Expand Down
23 changes: 23 additions & 0 deletions packages/libro-code-editor/src/code-editor-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ export interface IEditor<S = any> extends ISelectionOwner, Disposable {
dispose: () => void;

getState: () => EditorState<S>;

format: () => void;

onModelContentChanged?: Event<IModelContentChange[]>;
}

export type EditorTheme = Record<ThemeType, string>;
Expand Down Expand Up @@ -656,3 +660,22 @@ export interface CodeEditorContribution<T = any> {
stateFactory?: EditorStateFactory<T>;
defaultConfig: IEditorConfig;
}

export interface IModelContentChange {
/**
* The range that got replaced.
*/
readonly range: IRange;
/**
* The offset of the range that got replaced.
*/
readonly rangeOffset: number;
/**
* The length of the range that got replaced.
*/
readonly rangeLength: number;
/**
* The new text for the range.
*/
readonly text: string;
}
10 changes: 8 additions & 2 deletions packages/libro-codemirror/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ import type {
KeydownHandler,
SearchMatch,
} from '@difizen/libro-code-editor';
import { findFirstArrayIndex, removeAllWhereFromArray } from '@difizen/libro-common';
import {
findFirstArrayIndex,
MIME,
removeAllWhereFromArray,
} from '@difizen/libro-common';
import type { LSPProvider } from '@difizen/libro-lsp';
import { Deferred, Disposable, Emitter } from '@difizen/mana-app';
import { getOrigin, watch } from '@difizen/mana-app';
Expand Down Expand Up @@ -93,7 +97,7 @@ const DOWN_ARROW = 40;
export const codeMirrorDefaultConfig: Required<CodeMirrorConfig> = {
...defaultConfig,
mode: 'null',
mimetype: 'text/x-python',
mimetype: MIME.python,
theme: { light: 'jupyter', dark: 'jupyter', hc: 'jupyter' },
smartIndent: true,
electricChars: true,
Expand Down Expand Up @@ -875,6 +879,8 @@ export class CodeMirrorEditor implements IEditor {
command(this.editor);
}

format: () => void;

/**
* Handle keydown events from the editor.
*/
Expand Down
7 changes: 2 additions & 5 deletions packages/libro-cofine-editor/src/editor-contribution.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { CodeEditorFactory, EditorStateFactory } from '@difizen/libro-code-editor';
import { CodeEditorContribution } from '@difizen/libro-code-editor';
import { MIME } from '@difizen/libro-common';
import { inject, singleton } from '@difizen/mana-app';

import { LanguageSpecRegistry } from './language-specs.js';
Expand Down Expand Up @@ -32,11 +33,7 @@ export class LibroE2EditorContribution implements CodeEditorContribution {
};

canHandle(mime: string): number {
const mimes = [
'application/vnd.libro.sql+json',
'text/x-python',
'application/vnd.libro.prompt+json',
];
const mimes = [MIME.odpssql, MIME.python, MIME.prompt];
if (mimes.includes(mime)) {
return 50 + 1;
}
Expand Down
81 changes: 54 additions & 27 deletions packages/libro-cofine-editor/src/libro-e2-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
IEditorConfig,
IEditorOptions,
IModel,
IModelContentChange,
IPosition,
IRange,
SearchMatch,
Expand All @@ -16,6 +17,7 @@ import type {
import { defaultConfig } from '@difizen/libro-code-editor';
import type { E2Editor } from '@difizen/libro-cofine-editor-core';
import { EditorProvider, MonacoEnvironment } from '@difizen/libro-cofine-editor-core';
import { MIME } from '@difizen/libro-common';
import { NotebookCommands } from '@difizen/libro-core';
import type { LSPProvider } from '@difizen/libro-lsp';
import {
Expand All @@ -28,7 +30,7 @@ import {
watch,
} from '@difizen/mana-app';
import { Disposable, DisposableCollection, Emitter } from '@difizen/mana-app';
import { editor, Selection } from '@difizen/monaco-editor-core';
import { editor, KeyCode, Selection } from '@difizen/monaco-editor-core';
import 'resize-observer-polyfill';
import { v4 } from 'uuid';

Expand Down Expand Up @@ -228,7 +230,7 @@ export const libroE2DefaultConfig: Required<LibroE2EditorConfig> = {
},
scrollBarHeight: 12,
mode: 'null',
mimetype: 'text/x-python',
mimetype: MIME.python,
smartIndent: true,
electricChars: true,
keyMap: 'default',
Expand Down Expand Up @@ -371,6 +373,9 @@ export class LibroE2Editor implements IEditor {
return this.monacoEditor?.getModel()?.getLineCount() || 0;
}

protected onModelContentChangedEmitter = new Emitter<IModelContentChange[]>();
onModelContentChanged = this.onModelContentChangedEmitter.event;

lspProvider?: LSPProvider;

completionProvider?: CompletionProvider;
Expand Down Expand Up @@ -458,7 +463,7 @@ export class LibroE2Editor implements IEditor {
*
*/
// overflowWidgetsDomNode: document.getElementById('monaco-editor-overflow-widgets-root')!,
// fixedOverflowWidgets: true,
fixedOverflowWidgets: true,
suggest: { snippetsPreventQuickSuggestions: false },
autoClosingQuotes: editorConfig.autoClosingBrackets ? 'always' : 'never',
autoDetectHighContrast: false,
Expand Down Expand Up @@ -519,15 +524,24 @@ export class LibroE2Editor implements IEditor {
*/
language: this.languageSpec.language,
theme: this.theme,
model,
model: getOrigin(model),
};

this._editor = editorPorvider.create(host, options);
this.toDispose.push(
this.monacoEditor?.onDidChangeModelContent(() => {
this.monacoEditor?.onDidChangeModelContent((e) => {
const value = this.monacoEditor?.getValue();
this.model.value = value ?? '';
// this.updateEditorSize();
this.onModelContentChangedEmitter.fire(
e.changes.map((item) => {
return {
range: this.toEditorRange(item.range),
rangeLength: item.rangeLength,
rangeOffset: item.rangeOffset,
text: item.text,
};
}),
);
}) ?? Disposable.NONE,
);
this.toDispose.push(
Expand Down Expand Up @@ -556,11 +570,6 @@ export class LibroE2Editor implements IEditor {
// this.monacoEditor._themeService,
// this.monacoEditor._themeService.getColorTheme(),
// );

// setTimeout(() => {
// this.monacoEditor?.trigger('editor', 'editor.action.formatDocument');
// console.log('trigger format');
// }, 5000);
}

protected inspectResize() {
Expand Down Expand Up @@ -607,22 +616,23 @@ export class LibroE2Editor implements IEditor {
*/
protected handleCommand(commandRegistry: CommandRegistry) {
// need monaco 0.34
// editor.addKeybindingRules([
// {
// // disable show command center
// keybinding: KeyCode.F1,
// command: null,
// },
// {
// // disable show error command
// keybinding: KeyCode.F8,
// command: null,
// },
// {
// // disable toggle debugger breakpoint
// keybinding: KeyCode.F9,
// command: null,
// },
editor.addKeybindingRules([
{
// disable show command center
keybinding: KeyCode.F1,
command: null,
},
{
// disable show error command
keybinding: KeyCode.F8,
command: null,
},
{
// disable toggle debugger breakpoint
keybinding: KeyCode.F9,
command: null,
},
]);
this.monacoEditor?.addCommand(
9,
() => {
Expand Down Expand Up @@ -812,6 +822,19 @@ export class LibroE2Editor implements IEditor {
return monacoSelection;
}

protected toEditorRange(range: monaco.IRange): IRange {
return {
start: {
line: range.startLineNumber - 1,
column: range.startColumn - 1,
},
end: {
line: range.endLineNumber - 1,
column: range.endColumn - 1,
},
};
}

getSelectionValue = (range?: IRange | undefined) => {
const selection = range ?? this.getSelection();
return this.monacoEditor
Expand Down Expand Up @@ -955,6 +978,10 @@ export class LibroE2Editor implements IEditor {
}
};

format = () => {
this.monacoEditor?.trigger('libro-format', 'editor.action.formatDocument', '');
};

protected _isDisposed = false;
/**
* Tests whether the editor is disposed.
Expand Down
1 change: 1 addition & 0 deletions packages/libro-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './polling/index.js';
export * from './display-wrapper.js';
export * from './protocol/index.js';
export * from './dom.js';
export * from './mime.js';
12 changes: 12 additions & 0 deletions packages/libro-common/src/mime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const MIME = {
text: 'text/plain',
binary: 'application/octet-stream',
unknown: 'application/unknown',
markdown: 'text/markdown',
latex: 'text/latex',
uriList: 'text/uri-list',
json: 'application/json',
python: 'text/x-python',
prompt: 'application/vnd.libro.prompt+json',
odpssql: 'application/vnd.libro.sql+json',
} as const;
4 changes: 2 additions & 2 deletions packages/libro-core/src/cell/libro-cell-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,13 @@ export class LibroCellView extends BaseView implements CellView {
this.toDispose.push(
watch(this.model, 'value', () => {
this.parent.model.onChange?.();
this.parent.model.onSourceChange?.();
this.parent.model.onSourceChange?.([this]);
}),
);
this.toDispose.push(
watch(this.model, 'type', () => {
this.parent.model.onChange?.();
this.parent.model.onSourceChange?.();
this.parent.model.onSourceChange?.([this]);
}),
);
if (ExecutableCellModel.is(this.model)) {
Expand Down
11 changes: 10 additions & 1 deletion packages/libro-core/src/command/document-commands.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { SaveOutlined, SettingOutlined } from '@ant-design/icons';
import {
FormatPainterOutlined,
SaveOutlined,
SettingOutlined,
} from '@ant-design/icons';
import type { Command } from '@difizen/mana-app';

export const DocumentCommands: Record<string, Command & { keybind?: string }> = {
Expand All @@ -13,4 +17,9 @@ export const DocumentCommands: Record<string, Command & { keybind?: string }> =
icon: SettingOutlined,
label: 'Setting',
},
FormatCell: {
id: 'document.notebook.format_cell',
icon: FormatPainterOutlined,
label: 'format cell code',
},
};
Loading

0 comments on commit 6662cb6

Please sign in to comment.