@dao42/d42paas-front 0.4.5 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/package.json +3 -2
  2. package/src/app.tsx +250 -0
  3. package/src/assets/code-brackets.svg +1 -0
  4. package/src/assets/colors.svg +1 -0
  5. package/src/assets/comments.svg +1 -0
  6. package/src/assets/direction.svg +1 -0
  7. package/src/assets/flow.svg +1 -0
  8. package/src/assets/plugin.svg +1 -0
  9. package/src/assets/repo.svg +1 -0
  10. package/src/assets/stackalt.svg +1 -0
  11. package/src/components/Avatar/index.tsx +27 -0
  12. package/src/components/CanvasHelper/index.tsx +89 -0
  13. package/src/components/Console/index.tsx +88 -0
  14. package/src/components/Editor/index.tsx +979 -0
  15. package/src/components/FileTree/index.tsx +477 -0
  16. package/src/components/LiveContent/index.tsx +221 -0
  17. package/src/components/LiveContent/video.tsx +213 -0
  18. package/src/components/LottieAnim/index.tsx +41 -0
  19. package/src/components/Message/index.tsx +64 -0
  20. package/src/components/Model/index.tsx +42 -0
  21. package/src/components/OutputBrowser/index.tsx +180 -0
  22. package/src/components/Skeleton/index.tsx +41 -0
  23. package/src/components/Tabs/index.tsx +23 -0
  24. package/src/components/Terminal/index.tsx +127 -0
  25. package/src/components/ToolBar/index.tsx +169 -0
  26. package/src/components/XTerm/index.tsx +113 -0
  27. package/src/components/index.tsx +4 -0
  28. package/src/components/loading/index.tsx +282 -0
  29. package/src/enum/FExtension.ts +168 -0
  30. package/src/helpers/collections/IoClient.tsx +314 -0
  31. package/src/helpers/collections/errorCatcher.tsx +0 -0
  32. package/src/helpers/collections/idb.tsx +186 -0
  33. package/src/helpers/collections/localStorage.tsx +13 -0
  34. package/src/helpers/collections/mock.tsx +30 -0
  35. package/src/helpers/collections/playgroundInit.tsx +311 -0
  36. package/src/helpers/collections/replay.tsx +168 -0
  37. package/src/helpers/collections/socket.tsx +6 -0
  38. package/src/helpers/collections/toast.tsx +19 -0
  39. package/src/helpers/collections/userTool.tsx +12 -0
  40. package/src/helpers/collections/util.tsx +4 -0
  41. package/src/helpers/index.tsx +6 -0
  42. package/src/helpers/monaco/monaco-ot-adapter.tsx +476 -0
  43. package/src/hooks/collections/useOT.tsx +38 -0
  44. package/src/hooks/index.tsx +1 -0
  45. package/src/pages/index.tsx +450 -0
  46. package/src/public/dev.html +35 -0
  47. package/src/public/index.html +45 -0
  48. package/src/public/sdkserver.html +35 -0
  49. package/src/stores/index.tsx +1 -0
  50. package/src/stores/oTStore.tsx +288 -0
  51. package/src/stories/BrowserWindow.tsx +30 -0
  52. package/src/stories/Console.tsx +46 -0
  53. package/src/stories/Editor.tsx +37 -0
  54. package/src/stories/FileTree.tsx +50 -0
  55. package/src/stories/Shell.tsx +53 -0
  56. package/src/stories/introduction.stories.mdx +193 -0
  57. package/src/stories/page.tsx +71 -0
  58. package/src/styles/collections/iconfont.scss +1 -0
  59. package/src/styles/collections/tabs-costumers.scss +20 -0
  60. package/src/styles/collections/tailwind.scss +3 -0
  61. package/src/styles/collections/tree-costumers.scss +53 -0
  62. package/src/styles/collections/utility.scss +10 -0
  63. package/src/styles/collections/xterm-costumers.scss +47 -0
  64. package/src/styles/index.scss +19 -0
  65. package/src/types/editor.d.ts +31 -0
  66. package/src/types/index.d.ts +158 -0
@@ -0,0 +1,979 @@
1
+ import React, { useRef, useEffect, useState } from 'react';
2
+ import * as monacoCore from 'monaco-editor-core';
3
+ import * as monaco from 'monaco-editor';
4
+ import { oTStore } from '~/stores';
5
+ import { SerializedTextOperation, TextOperation } from 'ot';
6
+ import * as ot from 'ot';
7
+ import create from 'zustand';
8
+ import { IoClient, IsMe } from '~/helpers';
9
+ import { useOT } from '~/hooks';
10
+ import { setLocalFile } from '~/helpers/collections/idb';
11
+ import { FExtension } from '~/enum/FExtension';
12
+ import { T_UserInfo, userListStore, userStore } from '~/stores/oTStore';
13
+ import styled from '@emotion/styled';
14
+ import { pick, throttle } from 'lodash';
15
+ import normalizeUrl from 'normalize-url';
16
+ import { listen } from '@codingame/monaco-jsonrpc';
17
+ import ReconnectingWebSocket from 'reconnecting-websocket';
18
+
19
+ import {
20
+ MonacoLanguageClient,
21
+ MessageConnection,
22
+ CloseAction,
23
+ ErrorAction,
24
+ MonacoServices,
25
+ createConnection,
26
+ } from '@codingame/monaco-languageclient';
27
+ import { Toast } from '~/helpers/collections/toast';
28
+
29
+ // eslint-disable-next-line no-var
30
+ var INIT_LANGUAGE = 'ruby';
31
+ let to_save_operation;
32
+ // const OPERATION_SWICHER: boolean = false;
33
+ const docServer = new Map();
34
+
35
+ const useValue = create<{
36
+ delta: any;
37
+ usersDelta: any[];
38
+ selectionOp: unknown;
39
+ selectionAcks: any[];
40
+ setSelectionAck: (val: any) => void;
41
+ clearSelectionAcks: () => void;
42
+ setDelta: (val: any) => void;
43
+ setUsersDelta: (val: any[]) => void;
44
+ position: monaco.Position;
45
+ setPosition: (arg: monaco.Position) => void;
46
+ value: string;
47
+ setValue: (val: string) => void;
48
+ versionId: number;
49
+ setVersionId: (arg?: number) => void;
50
+ setSelectionOp: (arg?: unknown) => void;
51
+ }>((set) => ({
52
+ delta: '',
53
+ selectionOp: null,
54
+ usersDelta: [],
55
+ versionId: 0,
56
+ position: ([] as unknown) as monaco.Position,
57
+ selectionAcks: [],
58
+ setSelectionAck: (arg) =>
59
+ set((state) => ({
60
+ selectionAcks: [...state.selectionAcks, arg],
61
+ })),
62
+ clearSelectionAcks: () =>
63
+ set(() => ({
64
+ selectionAcks: [],
65
+ })),
66
+ setVersionId: (arg) =>
67
+ set(({ versionId }) => ({
68
+ versionId: arg || arg === 0 ? arg : versionId + 1,
69
+ })),
70
+ setDelta: (arg) => set(() => ({ delta: arg })),
71
+ setUsersDelta: (arg) => set(() => ({ usersDelta: arg })),
72
+ setPosition: (arg) => set(() => ({ position: arg })),
73
+ value: '',
74
+ setValue: (arg) => set(() => ({ value: arg })),
75
+ setSelectionOp: (arg) => set(() => ({ selectionOp: arg })),
76
+ }));
77
+
78
+ let editor;
79
+
80
+ // monaco.editor.defineTheme('myTheme', {
81
+ // base: 'vs',
82
+ // inherit: true,
83
+ // rules: [
84
+ // {
85
+ // background: '#EDF9FA',
86
+ // token: 'dasjoajfa',
87
+ // },
88
+ // ],
89
+ // colors: {
90
+ // 'editor.foreground': '#000000',
91
+ // 'editor.background': '#EDF9FA',
92
+ // 'editorCursor.foreground': '#8B0000',
93
+ // 'editor.lineHighlightBackground': '#0000FF20',
94
+ // 'editorLineNumber.foreground': '#008800',
95
+ // 'editor.selectionBackground': '#88000030',
96
+ // 'editor.inactiveSelectionBackground': '#88000015',
97
+ // },
98
+ // });
99
+
100
+ // monaco.editor.setTheme('myTheme');
101
+
102
+ // const color = 'red';
103
+ // const name = 'HOST';
104
+ const EditorLayout = styled.div<{ userList: T_UserInfo[] }>`
105
+ .contentWidgets {
106
+ visibility: hidden;
107
+ }
108
+ .monaco-label {
109
+ font-size: 12px;
110
+ border-radius: 2px;
111
+ padding: 2px 10px;
112
+ transform: scale(0.8);
113
+ visibility: hidden;
114
+ }
115
+ .label-visible {
116
+ visibility: visible !important;
117
+ }
118
+ ${(props) =>
119
+ props.userList.map(
120
+ (u) =>
121
+ '.' +
122
+ u.role +
123
+ '{' +
124
+ 'background:' +
125
+ u.color +
126
+ ';' +
127
+ 'width: 2px !important;' +
128
+ '}',
129
+ )}
130
+ ${(props) =>
131
+ props.userList.map(
132
+ (u) =>
133
+ '.' +
134
+ u.role +
135
+ '-selection' +
136
+ '{' +
137
+ 'background:' +
138
+ u.color +
139
+ 'a6' +
140
+ ';' +
141
+ 'color: #fff' +
142
+ ';' +
143
+ 'width: 2px !important;' +
144
+ '}',
145
+ )}
146
+ `;
147
+
148
+ // const throttled = throttle((a) => {
149
+ // console.log(a);
150
+ // }, 1000);
151
+
152
+ export const Editor: React.FC<{
153
+ doc?: string;
154
+ docType?: string;
155
+ }> = ({ doc, docType }) => {
156
+ // const io = useOT((state) => state.socket);
157
+ const divEl = useRef<HTMLDivElement>(null);
158
+ const [docVal, setDocVal] = useState<string>(doc ? doc : '');
159
+ const [pos, setPos] = useState<monaco.Position>(null!);
160
+ const file = oTStore((state) => state.doc);
161
+ const setFromServer = oTStore((state) => state.setFromServer);
162
+ const [client, setClient] = useState(new IoClient(0));
163
+ const OTSTATE = oTStore((state) => state);
164
+ const USERLISTSTORE = userListStore((state) => state);
165
+ const setPosition = useValue((state) => state.setPosition);
166
+ const setValue = useValue((state) => state.setValue);
167
+ const setDelta = useValue((state) => state.setDelta);
168
+ // const [languageModal, setLanguageModal] = useState({
169
+ // value: docVal,
170
+ // // language: 'typescript',
171
+ // language: FExtension.py,
172
+ // theme: 'vs-dark',
173
+ // // theme: 'myTheme',
174
+ // automaticLayout: true,
175
+ // fixedOverflowWidgets: true,
176
+ // // scrollBeyondLastLine: true,
177
+ // // roundedSelection: true,
178
+ // // showFoldingControls: false,
179
+ // // autoIndent: true,
180
+ // // cursorStyle: "line",
181
+ // // fontWeight: 400,
182
+ // // minimap: false
183
+ // scrollbar: {
184
+ // // Subtle shadows to the left & top. Defaults to true.
185
+ // useShadows: true,
186
+
187
+ // // Render vertical arrows. Defaults to false.
188
+ // verticalHasArrows: true,
189
+ // // Render horizontal arrows. Defaults to false.
190
+ // horizontalHasArrows: false,
191
+
192
+ // // // Render vertical scrollbar.
193
+ // // // Accepted values: 'auto', 'visible', 'hidden'.
194
+ // // // Defaults to 'auto'
195
+ // // vertical: 'hidden',
196
+ // // // Render horizontal scrollbar.
197
+ // // // Accepted values: 'auto', 'hidden', 'hidden'.
198
+ // // // Defaults to 'auto'
199
+ // // horizontal: 'hidden',
200
+
201
+ // verticalScrollbarSize: 8,
202
+ // horizontalScrollbarSize: 8,
203
+ // arrowSize: 5,
204
+ // },
205
+ // });
206
+
207
+ const cursorTool = (evt) => {
208
+ // const { CRDTInfo } = oTStore.getState();
209
+ const { userInfo } = userStore.getState();
210
+
211
+ const selection = [
212
+ [
213
+ evt.selection.startLineNumber,
214
+ evt.selection.startColumn,
215
+ evt.selection.endLineNumber,
216
+ evt.selection.endColumn,
217
+ evt.selection.selectionStartLineNumber,
218
+ evt.selection.selectionStartColumn,
219
+ evt.selection.positionColumn,
220
+ evt.selection.positionLineNumber,
221
+ ],
222
+ ...evt.secondarySelections.map((s) => [
223
+ s.startLineNumber,
224
+ s.startColumn,
225
+ s.endLineNumber,
226
+ s.endColumn,
227
+ s.selectionStartLineNumber,
228
+ s.selectionStartColumn,
229
+ s.positionColumn,
230
+ s.positionLineNumber,
231
+ ]),
232
+ ];
233
+ const crdt: D42_FrontType.CRDT = {
234
+ timestamp: Date.now().toString(),
235
+ selection,
236
+ file: {
237
+ action: 'Update',
238
+ path: oTStore.getState().doc.path,
239
+ },
240
+ userInfo: pick(userInfo, 'uuid', 'role'),
241
+ };
242
+ // sendPos = selection;
243
+ useOT.getState().socket.emit('selection', JSON.stringify(crdt));
244
+ };
245
+
246
+ const receiveOperation = (revision, operation, path) => {
247
+ // const sOperation = docServer.get(path).operation;
248
+ // if (operation.baseLength === sOperation.baseLength) {
249
+ // const { transform } = operation.constructor;
250
+ // operation = transform(operation, sOperation)[1];
251
+ // }
252
+ client.receiveOperation = operation;
253
+ return { operation };
254
+ };
255
+
256
+ const editorEventBinder = () => {
257
+ editor.onKeyDown((evt) => {
258
+ setFromServer(false);
259
+ // if ((evt.ctrlKey || evt.metaKey) && (evt.keyCode === 109 || evt.keyCode === 57)) {
260
+ if (evt.keyCode === 49) {
261
+ (evt.ctrlKey || evt.metaKey) && evt.preventDefault();
262
+ }
263
+ });
264
+
265
+ editor.onDidChangeCursorSelection((evt) => {
266
+ if (oTStore.getState().appStatus === 'replay') return;
267
+
268
+ console.log('当前revision:', client.revision);
269
+ if (evt.source === 'api') {
270
+ cursorTool(evt);
271
+ }
272
+ if (evt.reason === 0 || evt.source === 'model') return;
273
+ cursorTool(evt);
274
+ });
275
+
276
+ editor.onDidChangeModelContent((evt) => {
277
+ const { appStatus, fromServer, doc } = oTStore.getState();
278
+ // 回放状态,不进行文件数据改变
279
+ if (appStatus === 'replay') return;
280
+ if (fromServer) return;
281
+ // const docLength = editor.getModel().getValueLength(); // 文档长度
282
+ const editorValue = editor.getValue();
283
+ // const { isFlush, changes } = evt;
284
+ const { isFlush, changes } = evt;
285
+ // const changes = evt.changes.sort(
286
+ // (c1, c2) => c1.rangeOffset - c2.rangeOffset,
287
+ // );
288
+ if (!isFlush) {
289
+ setPosition(editor.getPosition());
290
+ let keepString = 0;
291
+ let rangeLengthamount = 0;
292
+ const rangeOffsetthamount = 0;
293
+ // let lastRangeOffsetthamount = 0;
294
+
295
+ const valuelength =
296
+ editorValue.length -
297
+ changes.reduce(
298
+ (change, nextChange, i) =>
299
+ change - nextChange.rangeLength + nextChange.text.length,
300
+ 0,
301
+ );
302
+ const operation = changes
303
+ .sort((c1, c2) => c1.rangeOffset - c2.rangeOffset)
304
+ .map((change, i) => {
305
+ rangeLengthamount += i === 0 ? 0 : change.rangeLength;
306
+ keepString += i === 0 ? 0 : change.text.length;
307
+
308
+ return new TextOperation()
309
+ .retain(
310
+ i === 0
311
+ ? change.rangeOffset
312
+ : change.rangeOffset - rangeLengthamount + keepString,
313
+ )
314
+ .delete(change.rangeLength)
315
+ .insert(change.text)
316
+ .retain(
317
+ // useValue.getState().value.length -
318
+ valuelength - change.rangeOffset - change.rangeLength,
319
+ );
320
+ })
321
+ .reduce((a, b) => a.compose(b));
322
+
323
+ // const operation = changes
324
+ // .sort((c1, c2) => c1.rangeOffset - c2.rangeOffset)
325
+ // .map((change, i) => {
326
+ // rangeLengthamount += i === 0 ? 0 : change.rangeLength;
327
+ // keepString += i === 0 ? 0 : change.text.length;
328
+
329
+ // return new TextOperation()
330
+ // .retain(
331
+ // i === 0
332
+ // ? change.rangeOffset
333
+ // : change.rangeOffset - rangeLengthamount + keepString,
334
+ // )
335
+ // .delete(change.rangeLength)
336
+ // .insert(change.text)
337
+ // .retain(
338
+ // // useValue.getState().value.length -
339
+ // valuelength - change.rangeOffset - change.rangeLength,
340
+ // );
341
+ // });
342
+
343
+ /* end */
344
+ // console.log('本地revision', client.revision);
345
+ // 单文件模式
346
+ // setTimeout(() => {
347
+ setLocalFile(doc.path ? doc.path : 'singleFile', editor.getValue());
348
+ // to_save_operation = operation;
349
+ client.applyClient(operation);
350
+ // }, 0);
351
+ } else {
352
+ setValue(changes[0].text);
353
+ }
354
+ });
355
+
356
+ editor.createContextKey('save', true);
357
+
358
+ editor.addCommand(
359
+ monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,
360
+ () => {
361
+ const { doc, setFileSaved } = oTStore.getState();
362
+
363
+ useOT.getState().socket.emit('saveFile', doc.path);
364
+ // alert('保存成功~');
365
+ // Toast.message()
366
+
367
+ Toast.message({
368
+ type: 'success',
369
+ content: '保存成功~~🤘 ↑↑↓↓←→←→ABAB',
370
+ placement: 'topCenter',
371
+ });
372
+ // client.applyClient(to_save_operation);
373
+ },
374
+ 'save',
375
+ );
376
+
377
+ client.sendOperation = function (revision, operation) {
378
+ if (oTStore.getState().appStatus === 'replay') return;
379
+
380
+ const { userInfo } = userStore.getState();
381
+ const { doc } = oTStore.getState();
382
+ console.log(file);
383
+ const crdt: D42_FrontType.CRDT = {
384
+ timestamp: Date.now().toString(),
385
+ userInfo: pick(userInfo, ['role', 'uuid']),
386
+ editor: {
387
+ operation,
388
+ revision,
389
+ evtType: 'Editor',
390
+ },
391
+ file: {
392
+ action: 'Update',
393
+ path: doc.path,
394
+ },
395
+ };
396
+
397
+ useOT.getState().socket.emit('editFile', JSON.stringify(crdt));
398
+ };
399
+ };
400
+
401
+ const updateLspOps = ({ value, path, language, CRDTInfo, doc }) => {
402
+ let gotModel = monaco.editor
403
+ .getModels()
404
+ .find((x) => new RegExp(path).test(x.uri.path));
405
+
406
+ if (!gotModel) {
407
+ gotModel = monaco.editor.createModel(
408
+ value,
409
+ language,
410
+ monaco.Uri.parse(`${path}`),
411
+ // monaco.Uri.parse(
412
+ // 'file:///Users/unamed/git/testForLSP/src/main/java/lsptest/Main.java',
413
+ // ),
414
+
415
+ // monaco.Uri.parse(`inmemory://${path}`),
416
+ // monaco.Uri.parse(`file://${path}`),
417
+ // monaco.Uri.parse(`${path}`),
418
+ // monaco.Uri.parse(`file:///abs/file.rb`),
419
+ // monaco.Uri.parse('inmemory:///abs/path/to/demo/ts/file.rb'),
420
+ );
421
+ // gotModel = monaco.editor.createModel(
422
+ // value,
423
+ // language,
424
+ // // monaco.Uri.parse(`${path}`),
425
+ // monaco.Uri.parse(
426
+ // 'file:///Users/unamed/git/testForLSP/src/main/java/Main.java',
427
+ // ),
428
+
429
+ // // monaco.Uri.parse(`inmemory://${path}`),
430
+ // // monaco.Uri.parse(`file://${path}`),
431
+ // // monaco.Uri.parse(`${path}`),
432
+ // // monaco.Uri.parse(`file:///abs/file.rb`),
433
+ // // monaco.Uri.parse('inmemory:///abs/path/to/demo/ts/file.rb'),
434
+ // );
435
+ // gotModel = monaco.editor.createModel(
436
+ // value,
437
+ // language,
438
+ // // monaco.Uri.parse(`${path}`),
439
+ // monaco.Uri.parse(
440
+ // 'file:///Users/unamed/git/testForLSP/src/main/java/lsptest/sample.java',
441
+ // ),
442
+
443
+ // // monaco.Uri.parse(`inmemory://${path}`),
444
+ // // monaco.Uri.parse(`file://${path}`),
445
+ // // monaco.Uri.parse(`${path}`),
446
+ // // monaco.Uri.parse(`file:///abs/file.rb`),
447
+ // // monaco.Uri.parse('inmemory:///abs/path/to/demo/ts/file.rb'),
448
+ // );
449
+ }
450
+
451
+ client.revision = CRDTInfo.editor.revision ? CRDTInfo.editor.revision : 0;
452
+
453
+ editor.setModel(gotModel);
454
+
455
+ docServer.set(file.path, {
456
+ operation: [],
457
+ revision: client.revision,
458
+ value: file.value,
459
+ });
460
+ setLocalFile(doc.path, file.value);
461
+
462
+ // editor.setValue(file.value);
463
+ };
464
+
465
+ const lspServerInject = (lan, disable?: boolean) => {
466
+ // monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
467
+ // allowNonTsExtensions: true,
468
+ // // allowJs: true,
469
+ // target: 99,
470
+ // paths: {
471
+ // '@/*': ['./'],
472
+ // },
473
+ // baseUrl: './',
474
+ // });
475
+ monaco.languages.register({
476
+ id: 'ruby',
477
+ extensions: ['.rb'],
478
+ aliases: ['ruby', 'RUBY'],
479
+ // extensions: ['.rb', '.rjs', '.gemspec', '.rbx'],
480
+ // aliases: ['Ruby', 'ruby', 'rjs', 'gemspec', 'rb'],
481
+ // mimetypes: ['application/json']
482
+ });
483
+ monaco.languages.register({
484
+ id: 'java',
485
+ extensions: ['.java'],
486
+ aliases: ['java', 'JAVA'],
487
+ // extensions: ['.rb', '.rjs', '.gemspec', '.rbx'],
488
+ // aliases: ['Ruby', 'ruby', 'rjs', 'gemspec', 'rb'],
489
+ // mimetypes: ['application/json']
490
+ });
491
+ monaco.languages.register({
492
+ id: 'typescript',
493
+ extensions: ['.ts'],
494
+ aliases: ['TypeScript', 'ts', 'TS', 'typescript'],
495
+ // mimetypes: ['application/json']
496
+ });
497
+
498
+ /**
499
+ * Uniform Resource Identifier (Uri) http://tools.ietf.org/html/rfc3986.
500
+ * This class is a simple parser which creates the basic component parts
501
+ * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
502
+ * and encoding.
503
+ *
504
+ * ```txt
505
+ * foo://example.com:8042/over/there?name=ferret#nose
506
+ * \_/ \______________/\_________/ \_________/ \__/
507
+ * | | | | |
508
+ * scheme authority path query fragment
509
+ * | _____________________|__
510
+ * / \ / \
511
+ * urn:example:animal:ferret:nose
512
+ * ```
513
+ */
514
+ // monaco.editor.createModel(
515
+ // 'printF',
516
+ // 'typescript',
517
+ // monaco.Uri.parse('file:///index.rb'),
518
+ // );
519
+ // monaco.editor.createModel(
520
+ // 'export const callYou = () => { console.log("hi") }',
521
+ // 'typescript',
522
+ // monaco.Uri.parse('file:///coding2/c2#/sample.ts'),
523
+ // );
524
+
525
+ if (disable) return;
526
+ MonacoServices.install(monaco as typeof monacoCore);
527
+
528
+ const { lspUrl, ticket } = oTStore.getState().dockerInfo;
529
+
530
+ if (!lspUrl) return;
531
+ // const webSocket = (new ReconnectingWebSocket('ws://192.168.2.15:7700', [], {
532
+ const webSocket = (new ReconnectingWebSocket(
533
+ `wss://${lspUrl}/${ticket}`,
534
+ [],
535
+ {
536
+ // const webSocket = (new ReconnectingWebSocket(
537
+ // 'ws://192.168.2.9:3001/runner',
538
+ // [],
539
+ // {
540
+ maxReconnectionDelay: 10000,
541
+ minReconnectionDelay: 1000,
542
+ reconnectionDelayGrowFactor: 1.3,
543
+ connectionTimeout: 10000,
544
+ maxRetries: Infinity,
545
+ debug: false,
546
+ },
547
+ ) as unknown) as WebSocket;
548
+
549
+ // listen when the web socket is opened
550
+ listen({
551
+ webSocket,
552
+ onConnection: (connection) => {
553
+ // create and start the language client
554
+ // const languageClient = createLanguageClient(connection);
555
+ const languageClient = new MonacoLanguageClient({
556
+ name: 'Language Client',
557
+ clientOptions: {
558
+ // use a language id as a document selector
559
+ // documentSelector: [lan],
560
+ // documentSelector: [{ language: 'ruby', pattern: '**∕*.rb' }],
561
+ documentSelector: ['java', 'ruby', 'typescript'],
562
+ // disable the default error handler
563
+ errorHandler: {
564
+ error: () => ErrorAction.Continue,
565
+ closed: () => CloseAction.DoNotRestart,
566
+ },
567
+ },
568
+ // create a language client connection from the JSON RPC connection on demand
569
+ connectionProvider: {
570
+ get: (errorHandler, closeHandler) => {
571
+ return Promise.resolve(
572
+ createConnection(connection, errorHandler, closeHandler),
573
+ );
574
+ },
575
+ },
576
+ });
577
+ const disposable = languageClient.start();
578
+ connection.onClose(() => disposable.dispose());
579
+ },
580
+ });
581
+ };
582
+
583
+ const editorInit = () => {
584
+ if (divEl.current) {
585
+ // register Monaco languages
586
+
587
+ monaco.editor.defineTheme('myCoolTheme', {
588
+ base: 'vs-dark',
589
+ inherit: false,
590
+ rules: [
591
+ {
592
+ token: 'green',
593
+ background: 'FF0000',
594
+ foreground: '00FF00',
595
+ fontStyle: 'italic',
596
+ },
597
+ { token: 'red', foreground: 'FF0000', fontStyle: 'bold underline' },
598
+ ],
599
+ colors: {
600
+ 'editor.foreground': '#FFFFFF',
601
+ 'editor.background': '#000000',
602
+ },
603
+ });
604
+
605
+ // create Monaco editor
606
+ editor = monaco.editor.create(divEl.current, {
607
+ theme: 'vs-dark',
608
+ // model: monaco.editor.createModel(
609
+ // 'printF',
610
+ // 'ruby',
611
+ // monaco.Uri.parse('file:///index.rb'),
612
+ // ),
613
+ glyphMargin: true,
614
+ lightbulb: {
615
+ enabled: true,
616
+ },
617
+ });
618
+
619
+ // // install Monaco language client services
620
+ lspServerInject(INIT_LANGUAGE, oTStore.getState().lspServerDisabled);
621
+
622
+ editorEventBinder();
623
+ const editorService = editor._codeEditorService;
624
+ const openEditorBase = editorService.openCodeEditor.bind(editorService);
625
+ editorService.openCodeEditor = async (input, source, workspacePath) => {
626
+ const result = await openEditorBase(input, source);
627
+ if (result === null) {
628
+ // alert('intercepted');
629
+ // console.log('Open definition for:', input);
630
+ // console.log(
631
+ // 'Corresponding model:',
632
+ // monaco.editor.getModel(input.resource),
633
+ // );
634
+ // console.log('Source: ', source);
635
+ const gotSource = monaco.editor
636
+ .getModels()
637
+ // .find((x) => new RegExp(path).test(x.uri.authority));
638
+ .find((x) => new RegExp(input.resource.path).test(x.uri.path));
639
+ const { CRDTInfo, setCRDTInfo } = oTStore.getState();
640
+ setCRDTInfo({
641
+ ...CRDTInfo,
642
+ file: {
643
+ action: 'Update',
644
+ value: gotSource.getValue(),
645
+ path: gotSource.uri.path,
646
+ },
647
+ });
648
+ }
649
+ return result; // always return the base result
650
+ };
651
+ }
652
+
653
+ window.ot = ot;
654
+ };
655
+
656
+ useEffect(() => {
657
+ editorInit();
658
+ return () => {
659
+ editor.dispose();
660
+ };
661
+ }, []);
662
+
663
+ useEffect(() => {
664
+ const { CRDTInfo, doc, serverAck, appStatus } = oTStore.getState();
665
+ const { usersDelta, setUsersDelta } = useValue.getState();
666
+ const callList = [];
667
+ // if (!OTSTATE.CRDTInfo.revision) return;
668
+ // if (!CRDTInfo.operation) return;
669
+ if (!CRDTInfo.editor || CRDTInfo.editor.evtType !== 'Editor') return;
670
+
671
+ if (
672
+ editor &&
673
+ (doc?.path === CRDTInfo?.file?.path ||
674
+ CRDTInfo?.file?.path === 'singleFile')
675
+ ) {
676
+ const server_operation = (CRDTInfo.editor
677
+ .operation as unknown) as SerializedTextOperation;
678
+
679
+ const CLIENT_OPERATION = receiveOperation(
680
+ CRDTInfo.editor.revision,
681
+ TextOperation.fromJSON(server_operation),
682
+ CRDTInfo.file.path,
683
+ );
684
+ // if (appStatus === 'replay') {
685
+ // callList.push(CLIENT_OPERATION);
686
+ // if (
687
+ // !!editor.getValue().length &&
688
+ // CLIENT_OPERATION.baseLength === editor.getValue().length
689
+ // ) {
690
+ // const m = callList.shift();
691
+ // console.log(m);
692
+ // editor.setValue(m.apply(editor.getValue()));
693
+ // }
694
+ // return;
695
+ // }
696
+ // if (CLIENT_OPERATION.baseLength !== editor.getValue().length) return;
697
+ // client.applyServer(TextOperation.fromJSON(server_operation));
698
+ client.applyServer(CLIENT_OPERATION.operation);
699
+
700
+ const pushStack = true;
701
+ // const { ops } = TextOperation.fromJSON(client.receiveOperation);
702
+ const { ops } = client.receiveOperation;
703
+ const model = editor.getModel();
704
+ let index = 0;
705
+ const results = [];
706
+
707
+ // ops.reduce((a, b, i) => {}, []);
708
+
709
+ ops.forEach((op) => {
710
+ if (TextOperation.isRetain(op)) {
711
+ index += op;
712
+ }
713
+
714
+ if (TextOperation.isInsert(op)) {
715
+ const insert = model.getPositionAt(index);
716
+ const originResult = {
717
+ forceMoveMarkers: true,
718
+ range: new monaco.Range(
719
+ insert.lineNumber,
720
+ insert.column,
721
+ insert.lineNumber,
722
+ insert.column,
723
+ ),
724
+ text: op,
725
+ };
726
+
727
+ results.push(originResult);
728
+ }
729
+
730
+ if (TextOperation.isDelete(op)) {
731
+ const start = model.getPositionAt(index);
732
+ const end = model.getPositionAt(index - op);
733
+
734
+ results.push({
735
+ forceMoveMarkers: false,
736
+ range: new monaco.Range(
737
+ start.lineNumber,
738
+ start.column,
739
+ end.lineNumber,
740
+ end.column,
741
+ ),
742
+ text: null,
743
+ });
744
+ index -= op;
745
+ }
746
+ });
747
+
748
+ // 全局 undo redo stack
749
+ if (pushStack) {
750
+ model.pushEditOperations([], results, null);
751
+ } else {
752
+ model.applyEdits(results);
753
+ }
754
+ }
755
+ }, [OTSTATE.CRDTInfo]);
756
+
757
+ useEffect(() => {
758
+ if (!editor) return;
759
+ const { CRDTInfo, doc, serverAck, appStatus } = oTStore.getState();
760
+ const { usersDelta, setUsersDelta } = useValue.getState();
761
+ // if (!IsMe(CRDTInfo.userInfo)) {
762
+ const model = editor.getModel();
763
+ console.log(CRDTInfo, '回放');
764
+
765
+ if (doc?.path === CRDTInfo?.file?.path) {
766
+ if (!!CRDTInfo.selection) {
767
+ console.log('selection move');
768
+ usersDelta.forEach((u) => {
769
+ // eslint-disable-next-line prefer-const
770
+ let timer;
771
+ const _label = document.querySelector<HTMLElement>(
772
+ `.${u.role}-label`,
773
+ );
774
+ timer && clearTimeout(timer);
775
+
776
+ if (!_label.classList.contains('label-visible')) {
777
+ _label.classList.add('label-visible');
778
+ }
779
+
780
+ timer = setTimeout(() => {
781
+ _label.classList.remove('label-visible');
782
+ }, 8000);
783
+ editor.layoutContentWidget({
784
+ ...u.label,
785
+ getPosition: function () {
786
+ return {
787
+ position: {
788
+ lineNumber: CRDTInfo.selection[0][7],
789
+ column: CRDTInfo.selection[0][6],
790
+ },
791
+ preference: [
792
+ monaco.editor.ContentWidgetPositionPreference.ABOVE,
793
+ monaco.editor.ContentWidgetPositionPreference.BELOW,
794
+ ],
795
+ };
796
+ },
797
+ });
798
+ });
799
+ // evt.selection.startLineNumber,
800
+ // evt.selection.startColumn,
801
+ // evt.selection.endLineNumber,
802
+ // evt.selection.endColumn,
803
+ // evt.selection.selectionStartLineNumber,
804
+ // evt.selection.selectionStartColumn,
805
+ // evt.selection.positionColumn,
806
+ // evt.selection.positionLineNumber,
807
+
808
+ setUsersDelta(
809
+ usersDelta.map((deltaInfo) => {
810
+ if (deltaInfo.uuid === CRDTInfo.userInfo.uuid) {
811
+ // console.log(CRDTInfo);
812
+ return {
813
+ // user: CRDTInfo.userInfo,
814
+ ...deltaInfo,
815
+
816
+ delta: editor.deltaDecorations(
817
+ deltaInfo.delta ? deltaInfo.delta : '',
818
+ CRDTInfo.selection.map((s) => ({
819
+ range: new monaco.Range(s[0], s[1], s[2], s[3]),
820
+ options: {
821
+ isWholeLine: false,
822
+ className: s[5] === s[6] ? deltaInfo.role : '',
823
+ // stickiness:
824
+ // monaco.editor.TrackedRangeStickiness
825
+ // .NeverGrowsWhenTypingAtEdges,
826
+ // linesDecorationsClassName: deltaInfo.role,
827
+ inlineClassName: deltaInfo.role + '-selection',
828
+ // glyphMarginClassName: 'myGlyphMarginClass',
829
+ },
830
+ })),
831
+ ),
832
+ };
833
+ } else {
834
+ return deltaInfo;
835
+ }
836
+ }),
837
+ );
838
+ }
839
+
840
+ if (CRDTInfo?.editor?.evtType === 'Editor') {
841
+ // const server_operation = (CRDTInfo.editor
842
+ // .operation as unknown) as SerializedTextOperation;
843
+ // const CLIENT_OPERATION = TextOperation.fromJSON(server_operation);
844
+ // client.applyServer(TextOperation.fromJSON(server_operation));
845
+ // const { ops } = CLIENT_OPERATION;
846
+ // ops.forEach((_op) => {
847
+ // const op = _op as number;
848
+ // if (TextOperation.isRetain(op)) {
849
+ // const _insert = model.getPositionAt(op);
850
+ // // console.log(_insert);
851
+ // }
852
+ // });
853
+ }
854
+ }
855
+ // }
856
+ // console.log(usersDelta);
857
+ }, [OTSTATE.CRDTInfo.selection]);
858
+
859
+ useEffect(() => {
860
+ if (!editor) return;
861
+ }, [OTSTATE.fileSaved]);
862
+
863
+ useEffect(() => {
864
+ if (!editor) return;
865
+
866
+ // OTSTATE.CRDTInfo.operation &&
867
+ OTSTATE.serverAck && client.serverAck();
868
+ docServer.set(file.path, {
869
+ ...docServer.get(file.path),
870
+ operation: client.operation,
871
+ });
872
+ // if (selectionAcks.length > 0) {
873
+ // if (useValue.getState().selectionAcks.length > 0) {
874
+ // ret1urn;
875
+ // }
876
+
877
+ // }
878
+ // console.log('save');
879
+ // if (useValue.getState().selectionAcks.length > 0) {
880
+ // return;
881
+ // }
882
+ // io.emit('selection', JSON.stringify(crdt));
883
+ }, [OTSTATE.serverAck]);
884
+
885
+ useEffect(() => {
886
+ const egt = /\.(\w+$)/gim.exec(file.path as string);
887
+ const { CRDTInfo, doc } = oTStore.getState();
888
+ if (!editor || !IsMe(CRDTInfo.userInfo)) return;
889
+ if (file.path && egt) {
890
+ updateLspOps({
891
+ value: file.value,
892
+ path: file.path,
893
+ language: FExtension[egt[1]],
894
+ CRDTInfo,
895
+ doc,
896
+ });
897
+ }
898
+ }, [file.path]);
899
+
900
+ useEffect(() => {
901
+ // const egt = /\.(\w+$)/gim.exec(file.path);
902
+ // if (!egt) return;
903
+ // if (!!editor && docType) {
904
+ // monaco.editor.setModelLanguage(editor.getModel(), docType);
905
+ // }
906
+ // editor.setValue(file.value);
907
+ }, [docType]);
908
+
909
+ useEffect(() => {
910
+ // if (!!editor) {
911
+ // const _model = editor.getModel();
912
+ // editor.setValue(doc ? doc : '');
913
+ // _model &&
914
+ // monaco.editor.setModelLanguage(
915
+ // _model,
916
+ // docType ? docType : FExtension[docType],
917
+ // );
918
+ // }
919
+ }, [doc, docType]);
920
+
921
+ useEffect(() => {
922
+ const { usersDelta, setUsersDelta } = useValue.getState();
923
+ // const { userList } = userListStore.getState();
924
+
925
+ setUsersDelta(
926
+ USERLISTSTORE.userList
927
+ .filter((u) => !IsMe(u))
928
+ .map((x) => {
929
+ return {
930
+ ...x,
931
+ label: {
932
+ domNode: null,
933
+ getId: function () {
934
+ return `label-${x.uuid}`;
935
+ },
936
+ getDomNode: function () {
937
+ if (!this.domNode) {
938
+ this.domNode = document.createElement('div');
939
+ this.domNode.className = `monaco-label ${x.role}-label`;
940
+ this.domNode.innerHTML = x.username;
941
+ this.domNode.style.background = x.color;
942
+ this.domNode.style.visibility = 'hidden';
943
+ }
944
+ return this.domNode;
945
+ },
946
+ getPosition: function () {
947
+ return {
948
+ position: {
949
+ lineNumber: 1,
950
+ column: 2,
951
+ },
952
+ preference: [
953
+ monaco.editor.ContentWidgetPositionPreference.ABOVE,
954
+ monaco.editor.ContentWidgetPositionPreference.BELOW,
955
+ ],
956
+ };
957
+ },
958
+ },
959
+ };
960
+ }),
961
+ );
962
+
963
+ editor &&
964
+ usersDelta.forEach((x) => {
965
+ // debugger;
966
+ if (!document.querySelector(`.${x.role}-label`)) {
967
+ editor.addContentWidget(x.label);
968
+ }
969
+ });
970
+ }, [USERLISTSTORE.userList, file.path]);
971
+
972
+ return (
973
+ <EditorLayout
974
+ ref={divEl}
975
+ className="editor-layout"
976
+ userList={userListStore.getState().userList}
977
+ ></EditorLayout>
978
+ );
979
+ };