Skip to content

[Stage2] Define user model #12

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

Merged
merged 5 commits into from
Aug 12, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,28 @@ import { Awareness } from 'y-protocols/awareness';
import { WebsocketProvider } from 'y-websocket';
import * as Y from 'yjs';

import { Injector } from '@opensumi/di';
import { uuid } from '@opensumi/ide-core-common';
import { ICodeEditor } from '@opensumi/ide-monaco';
import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api';

import { TextModelBinding } from '../../src/browser/textmodel-binding';
import { ICollaborationService } from '../../src/common';

const injector = new Injector();

injector.addProviders({
token: ICollaborationService,
useValue: {
getCursorWidgetRegistry: jest.fn(),
},
});

const createBindingWithTextModel = (doc: Y.Doc, awareness: Awareness) => {
const textModel = monaco.editor.createModel('');
const yText = doc.getText('test');
const binding = new TextModelBinding(yText, textModel, awareness);
// const binding = new TextModelBinding(yText, textModel, awareness);
const binding = injector.get(TextModelBinding, [yText, textModel, awareness]);
return {
textModel,
binding,
Expand All @@ -31,6 +43,7 @@ describe('TextModelBinding test for yText and TextModel', () => {
wsProvider = new WebsocketProvider('ws://127.0.0.1:12345', 'test', doc, { connect: false }); // we don't use wsProvider here
user1 = createBindingWithTextModel(doc, wsProvider.awareness);
user2 = createBindingWithTextModel(doc, wsProvider.awareness);
jest.mock('@opensumi/di');
});

afterEach(() => {
Expand Down
1 change: 1 addition & 0 deletions packages/collaboration/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@opensumi/ide-core-browser": "^2.18.7",
"@opensumi/ide-editor": "2.18.7",
"@opensumi/ide-monaco": "2.18.7",
"@opensumi/ide-theme": "2.18.7",
"@opensumi/ide-dev-tool": "^1.3.1",
"y-protocols": "^1.0.2"
}
Expand Down
23 changes: 21 additions & 2 deletions packages/collaboration/src/browser/collaboration.contribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,20 @@ import {
KeybindingWeight,
PreferenceService,
} from '@opensumi/ide-core-browser';
import { CommandContribution, CommandRegistry, Domain } from '@opensumi/ide-core-common';
import { CommandContribution, CommandRegistry, ContributionProvider, Domain, uuid } from '@opensumi/ide-core-common';

import { ICollaborationService } from '../common';
import { ICollaborationService, UserInfo, UserInfoForCollaborationContribution } from '../common';
import { REDO, UNDO } from '../common/commands';

// mock user info
@Domain(UserInfoForCollaborationContribution)
export class MyUserInfo implements UserInfoForCollaborationContribution {
info: UserInfo = {
id: uuid().slice(0, 4),
nickname: `${uuid().slice(0, 4)}`,
};
}

@Domain(ClientAppContribution, KeybindingContribution, CommandContribution)
export class CollaborationContribution implements ClientAppContribution, KeybindingContribution, CommandContribution {
@Autowired(ICollaborationService)
Expand All @@ -19,10 +28,20 @@ export class CollaborationContribution implements ClientAppContribution, Keybind
@Autowired(PreferenceService)
private preferenceService: PreferenceService;

@Autowired(UserInfoForCollaborationContribution)
private readonly userInfoProvider: ContributionProvider<UserInfoForCollaborationContribution>;

onDidStart() {
if (this.preferenceService.get('editor.askIfDiff') === true) {
this.preferenceService.set('editor.askIfDiff', false);
}

// before init
const providers = this.userInfoProvider.getContributions();
for (const provider of providers) {
this.collaborationService.setUserInfo(provider);
}

this.collaborationService.initialize();
}

Expand Down
103 changes: 102 additions & 1 deletion packages/collaboration/src/browser/collaboration.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@ import { WorkbenchEditorService } from '@opensumi/ide-editor';
import { EditorActiveResourceStateChangedEvent, EditorGroupCloseEvent } from '@opensumi/ide-editor/lib/browser';
import { WorkbenchEditorServiceImpl } from '@opensumi/ide-editor/lib/browser/workbench-editor.service';
import { ITextModel, ICodeEditor } from '@opensumi/ide-monaco';
import { ICSSStyleService } from '@opensumi/ide-theme';

import {
CollaborationServiceForClientPath,
ICollaborationService,
ICollaborationServiceForClient,
ROOM_NAME,
UserInfo,
UserInfoForCollaborationContribution,
Y_REMOTE_SELECTION,
Y_REMOTE_SELECTION_HEAD,
} from '../common';

import { getColorByClientID } from './color';
import { CursorWidgetRegistry } from './cursor-widget';
import { TextModelBinding } from './textmodel-binding';

import './styles.less';
Expand All @@ -36,6 +43,16 @@ export class CollaborationService extends WithEventBus implements ICollaboration
@Autowired(WorkbenchEditorService)
private workbenchEditorService: WorkbenchEditorServiceImpl;

@Autowired(ICSSStyleService)
private cssManager: ICSSStyleService;

private clientIDStyleAddedSet: Set<number> = new Set();

// hold editor => registry
private cursorRegistryMap: Map<ICodeEditor, CursorWidgetRegistry> = new Map();

private userInfo: UserInfo;

private yDoc: Y.Doc;

private yWebSocketProvider: WebsocketProvider;
Expand Down Expand Up @@ -76,15 +93,45 @@ export class CollaborationService extends WithEventBus implements ICollaboration
this.yTextMap = this.yDoc.getMap();
this.yWebSocketProvider = new WebsocketProvider('ws://127.0.0.1:12345', ROOM_NAME, this.yDoc); // TODO configurable uri and room name
this.yTextMap.observe(this.yMapObserver);

// add userInfo to awareness field
this.yWebSocketProvider.awareness.setLocalStateField('user-info', this.userInfo);

this.logger.debug('Collaboration initialized');

this.yWebSocketProvider.awareness.on('update', this.updateCSSManagerWhenAwarenessUpdated);
}

destroy() {
this.yWebSocketProvider.awareness.off('update', this.updateCSSManagerWhenAwarenessUpdated);
this.clientIDStyleAddedSet.forEach((clientID) => {
this.cssManager.removeClass(`${Y_REMOTE_SELECTION}-${clientID}`);
this.cssManager.removeClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}`);
this.cssManager.removeClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}::after`);
});
this.yTextMap.unobserve(this.yMapObserver);
this.yWebSocketProvider.disconnect();
this.bindingMap.forEach((binding) => binding.dispose());
}

getUseInfo(): UserInfo {
if (!this.userInfo) {
throw new Error('User info is not registered');
}

return this.userInfo;
}

setUserInfo(contribution: UserInfoForCollaborationContribution) {
if (this.userInfo) {
throw new Error('User info is already registered');
}

if (contribution.info) {
this.userInfo = contribution.info;
}
}

undoOnCurrentResource() {
const uri = this.workbenchEditorService.currentResource?.uri.toString();
if (uri && this.bindingMap.has(uri)) {
Expand Down Expand Up @@ -131,11 +178,56 @@ export class CollaborationService extends WithEventBus implements ICollaboration
if (binding) {
binding.dispose();
this.bindingMap.delete(uri);
// todo ref = ref - 1 (through back service)
this.logger.debug('Removed binding');
}
}

public getCursorWidgetRegistry(editor: ICodeEditor) {
return this.cursorRegistryMap.get(editor);
}

private updateCSSManagerWhenAwarenessUpdated = (changes: {
added: number[];
updated: number[];
removed: number[];
}) => {
if (changes.removed.length > 0) {
changes.removed.forEach((clientID) => {
this.cssManager.removeClass(`${Y_REMOTE_SELECTION}-${clientID}`);
this.cssManager.removeClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}`);
this.cssManager.removeClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}::after`);
this.clientIDStyleAddedSet.delete(clientID);
});
}
if (changes.added.length > 0 || changes.updated.length > 0) {
changes.added.forEach((clientID) => {
if (!this.clientIDStyleAddedSet.has(clientID)) {
const color = getColorByClientID(clientID);
this.cssManager.addClass(`${Y_REMOTE_SELECTION}-${clientID}`, {
backgroundColor: color,
opacity: '0.25',
});
this.cssManager.addClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}`, {
position: 'absolute',
borderLeft: `${color} solid 2px`,
borderBottom: `${color} solid 2px`,
borderTop: `${color} solid 2px`,
height: '100%',
boxSizing: 'border-box',
});
this.cssManager.addClass(`${Y_REMOTE_SELECTION_HEAD}-${clientID}::after`, {
position: 'absolute',
content: ' ',
border: `3px solid ${color}`,
left: '-4px',
top: '-5px',
});
this.clientIDStyleAddedSet.add(clientID);
}
});
}
};

@OnEvent(EditorGroupCloseEvent)
private groupCloseHandler(e: EditorGroupCloseEvent) {
this.logger.debug('Group close tabs', e);
Expand Down Expand Up @@ -167,6 +259,15 @@ export class CollaborationService extends WithEventBus implements ICollaboration
const monacoEditor = this.workbenchEditorService.currentCodeEditor?.monacoEditor;
const binding = this.getBinding(uri);

// check if editor has its widgetRegistry
if (monacoEditor && !this.cursorRegistryMap.has(monacoEditor)) {
const registry = this.injector.get(CursorWidgetRegistry, [monacoEditor, this.yWebSocketProvider.awareness]);
this.cursorRegistryMap.set(monacoEditor, registry);
monacoEditor.onDidDispose(() => {
registry.destroy();
});
}

// check if there exists any binding
if (!binding) {
if (this.yTextMap.has(uri)) {
Expand Down
4 changes: 4 additions & 0 deletions packages/collaboration/src/browser/color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const color = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violent'];

// get color by clientID
export const getColorByClientID = (id: number): string => color[id % color.length];
Loading