ide-assi 0.331.0 → 0.334.0

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.
@@ -1,11 +1,72 @@
1
- import { EditorView } from "@codemirror/view";
2
- import { EditorState } from "@codemirror/state";
3
- import { javascript } from "@codemirror/lang-javascript"; // 예시 언어
4
- import { lineNumbers } from "@codemirror/view";
5
- import { DiffEditor } from "codemirror-editor-diff"; // Diff 기능 라이브러리 (예시)
1
+ import ninegrid from "ninegrid2";
2
+
3
+ // CodeMirror 6 핵심 확장 임포트
4
+ import {
5
+ EditorView, lineNumbers, highlightSpecialChars, drawSelection,
6
+ dropCursor, keymap, highlightActiveLine, highlightActiveLineGutter,
7
+ // 데코레이션을 위한 Decoration 클래스 임포트
8
+ Decoration
9
+ } from "@codemirror/view";
10
+ import {
11
+ EditorState, Compartment, StateField,
12
+ // 데코레이션 빌더를 위한 RangeSetBuilder 임포트
13
+ RangeSetBuilder
14
+ } from "@codemirror/state";
15
+ import { history, historyKeymap, indentWithTab } from "@codemirror/commands";
16
+ import { defaultKeymap, selectAll } from "@codemirror/commands";
17
+ import { searchKeymap, highlightSelectionMatches } from "@codemirror/search";
18
+ import { bracketMatching } from "@codemirror/language";
19
+ import { javascript } from "@codemirror/lang-javascript";
20
+ import { indentOnInput, syntaxHighlighting, defaultHighlightStyle } from "@codemirror/language";
21
+ import { lintKeymap } from "@codemirror/lint";
22
+ import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
23
+
24
+ // Diff 로직을 위해 diff-match-patch 사용
25
+ import { diff_match_patch } from 'diff-match-patch';
26
+
27
+ // Diff 데코레이션을 위한 StateField 정의 (asis 에디터용)
28
+ const asisDiffDecorations = StateField.define({
29
+ create() { return Decoration.none; }, // 초기 상태
30
+ update(decorations, tr) {
31
+ // 트랜잭션에 포함된 Effects를 처리하여 데코레이션을 업데이트
32
+ // `#applyDiffDecorations` 함수에서 데코레이션 업데이트 요청을 보낼 때 사용
33
+ return tr.effects.reduce((currentDecos, effect) => {
34
+ if (effect.is(setAsisDecorationsEffect)) {
35
+ return effect.value;
36
+ }
37
+ return currentDecos;
38
+ }, decorations);
39
+ },
40
+ // 데코레이션을 뷰에 제공
41
+ provide: f => EditorView.decorations.from(f)
42
+ });
43
+
44
+ // Diff 데코레이션을 위한 StateField 정의 (tobe 에디터용)
45
+ const tobeDiffDecorations = StateField.define({
46
+ create() { return Decoration.none; },
47
+ update(decorations, tr) {
48
+ return tr.effects.reduce((currentDecos, effect) => {
49
+ if (effect.is(setTobeDecorationsEffect)) {
50
+ return effect.value;
51
+ }
52
+ return currentDecos;
53
+ }, decorations);
54
+ },
55
+ provide: f => EditorView.decorations.from(f)
56
+ });
57
+
58
+ // 데코레이션 업데이트를 위한 Effect (트랜잭션에 포함시켜 상태 변경 알림)
59
+ const setAsisDecorationsEffect = EditorState.define.effect();
60
+ const setTobeDecorationsEffect = EditorState.define.effect();
61
+
6
62
 
7
63
  export class IdeDiff extends HTMLElement {
8
- #diffEditorInstance; // DiffEditor 인스턴스
64
+ #asisEditorView;
65
+ #tobeEditorView;
66
+ #asisEditorEl;
67
+ #tobeEditorEl;
68
+
69
+ #languageCompartment = new Compartment();
9
70
 
10
71
  constructor() {
11
72
  super();
@@ -18,23 +79,46 @@ export class IdeDiff extends HTMLElement {
18
79
  /* ninegrid CSS 및 필요한 기본 스타일 */
19
80
  @import "https://cdn.jsdelivr.net/npm/ninegrid@${ninegrid.version}/dist/css/ideDiff.css";
20
81
  ${ninegrid.getCustomPath(this, "ideDiff.css")}
82
+
83
+ /* CodeMirror를 위한 기본적인 Flexbox 레이아웃 */
21
84
  .wrapper {
22
- width: 100%;
23
- height: 100%;
24
85
  display: flex;
86
+ width: 100%;
87
+ height: 100%; /* 부모의 높이를 채우도록 설정 */
88
+ overflow: hidden; /* 내부 스크롤을 위해 overflow 처리 */
25
89
  }
26
- #editor-container {
27
- flex: 1;
28
- min-height: 0;
90
+ .panel {
91
+ flex: 1; /* 패널들이 남은 공간을 채우도록 */
92
+ overflow: hidden; /* CodeMirror EditorView 자체가 스크롤을 처리 */
93
+ min-width: 0; /* Flexbox 아이템이 content 때문에 늘어나는 것을 방지 */
29
94
  }
30
- /* CodeMirror 기본 스타일 */
31
95
  .cm-editor {
32
- height: 100%;
33
- /* border: 1px solid #eee; */
96
+ height: 100%; /* EditorView가 부모 div의 높이를 채우도록 */
34
97
  }
98
+
99
+ /* Diff 시각화를 위한 CSS 클래스 */
100
+ /* 줄 전체 배경색 */
101
+ .cm-inserted-line-bg { background-color: #e6ffe6; } /* 연한 녹색 */
102
+ .cm-deleted-line-bg { background-color: #ffe6e6; } /* 연한 빨간색 */
103
+
104
+ /* 인라인(단어/문자) 변경 강조 */
105
+ .cm-inserted-inline {
106
+ background-color: #90ee90; /* 밝은 녹색 */
107
+ font-weight: bold;
108
+ }
109
+ .cm-deleted-inline {
110
+ background-color: #ff9999; /* 밝은 빨간색 */
111
+ text-decoration: line-through;
112
+ font-weight: bold;
113
+ }
114
+ /* 선택적: 동일하지만 이동된 줄 강조 (복잡함) */
115
+ /* .cm-moved-line-bg {} */
35
116
  </style>
117
+
36
118
  <div class="wrapper">
37
- <div id="editor-container"></div>
119
+ <div class="panel asis"></div>
120
+ <nx-splitter></nx-splitter>
121
+ <div class="panel tobe"></div>
38
122
  </div>
39
123
  `;
40
124
 
@@ -44,38 +128,243 @@ export class IdeDiff extends HTMLElement {
44
128
  }
45
129
 
46
130
  #initCodeMirror = () => {
47
- const container = this.shadowRoot.getElementById('editor-container');
48
- if (!container) {
49
- console.error('CodeMirror container not found!');
131
+ this.#asisEditorEl = this.shadowRoot.querySelector('.panel.asis');
132
+ this.#tobeEditorEl = this.shadowRoot.querySelector('.panel.tobe');
133
+
134
+ if (!this.#asisEditorEl || !this.#tobeEditorEl) {
135
+ console.error('CodeMirror panel containers not found!');
50
136
  return;
51
137
  }
52
138
 
53
- // DiffEditor 인스턴스 생성
54
- this.#diffEditorInstance = new DiffEditor(container, {
55
- // CodeMirror 확장을 이곳에 배열로 전달
56
- extensions: [
57
- lineNumbers(), // 줄 번호
58
- javascript(), // 구문 하이라이팅 (JavaScript 예시)
59
- EditorState.readOnly.of(true) // 읽기 전용
60
- // ... 기타 CodeMirror 확장
61
- ],
62
- // DiffEditor 자체 옵션 (만약 있다면)
139
+ // CodeMirror 확장 기본 설정
140
+ const basicExtensions = [
141
+ lineNumbers(),
142
+ highlightSpecialChars(),
143
+ history(),
144
+ drawSelection(),
145
+ dropCursor(),
146
+ EditorState.allowMultipleSelections.of(true),
147
+ indentOnInput(),
148
+ bracketMatching(),
149
+ highlightActiveLine(),
150
+ highlightSelectionMatches(),
151
+ keymap.of([
152
+ ...defaultKeymap,
153
+ ...searchKeymap,
154
+ ...historyKeymap,
155
+ ...lintKeymap,
156
+ ...completionKeymap,
157
+ indentWithTab,
158
+ selectAll // selectAll 추가
159
+ ]),
160
+ syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
161
+ autocompletion(),
162
+ ];
163
+
164
+ // asis 에디터 생성 (읽기 전용)
165
+ this.#asisEditorView = new EditorView({
166
+ state: EditorState.create({
167
+ doc: '',
168
+ extensions: [
169
+ basicExtensions,
170
+ javascript(), // JS 언어 모드 (기본)
171
+ EditorState.readOnly.of(true), // asis는 읽기 전용
172
+ this.#languageCompartment.of(javascript()), // 언어 변경 compartment
173
+ asisDiffDecorations // asis 에디터에 Diff 데코레이션 필드 추가
174
+ ]
175
+ }),
176
+ parent: this.#asisEditorEl
177
+ });
178
+
179
+ // tobe 에디터 생성 (읽기 전용, 필요 시 편집 가능하게 설정)
180
+ this.#tobeEditorView = new EditorView({
181
+ state: EditorState.create({
182
+ doc: '',
183
+ extensions: [
184
+ basicExtensions,
185
+ javascript(), // JS 언어 모드 (기본)
186
+ EditorState.readOnly.of(true), // tobe도 읽기 전용
187
+ this.#languageCompartment.of(javascript()), // 언어 변경 compartment
188
+ tobeDiffDecorations // tobe 에디터에 Diff 데코레이션 필드 추가
189
+ ]
190
+ }),
191
+ parent: this.#tobeEditorEl
192
+ });
193
+
194
+ this.#setupScrollSync();
195
+ };
196
+
197
+ #setupScrollSync = () => {
198
+ let scrollingA = false;
199
+ let scrollingB = false;
200
+
201
+ this.#asisEditorView.scrollDOM.addEventListener('scroll', () => {
202
+ if (!scrollingB) {
203
+ scrollingA = true;
204
+ this.#tobeEditorView.scrollDOM.scrollTop = this.#asisEditorView.scrollDOM.scrollTop;
205
+ this.#tobeEditorView.scrollDOM.scrollLeft = this.#asisEditorView.scrollDOM.scrollLeft;
206
+ }
207
+ scrollingB = false;
208
+ });
209
+
210
+ this.#tobeEditorView.scrollDOM.addEventListener('scroll', () => {
211
+ if (!scrollingA) {
212
+ scrollingB = true;
213
+ this.#asisEditorView.scrollDOM.scrollTop = this.#tobeEditorView.scrollDOM.scrollTop;
214
+ this.#asisEditorView.scrollDOM.scrollLeft = this.#tobeEditorView.scrollDOM.scrollLeft;
215
+ }
216
+ scrollingA = false;
63
217
  });
64
- // 이 라이브러리가 내부적으로 두 개의 EditorView를 만들고 관리합니다.
65
- // 스크롤 동기화, Diff 시각화 등은 이 라이브러리가 처리합니다.
66
218
  };
67
219
 
68
- initialize = (src1, src2) => {
69
- if (!this.#diffEditorInstance) {
70
- console.warn('CodeMirror Diff Editor not initialized yet.');
220
+ // ⭐️⭐️⭐️ Diff 데코레이션 적용 로직 구현 ⭐️⭐️⭐️
221
+ #applyDiffDecorations = (asisSrc, tobeSrc) => {
222
+ const dmp = new diff_match_patch();
223
+ const diffs = dmp.diff_main(asisSrc, tobeSrc);
224
+ dmp.diff_cleanupSemantic(diffs);
225
+
226
+ const asisBuilder = new RangeSetBuilder();
227
+ const tobeBuilder = new RangeSetBuilder();
228
+
229
+ let asisCursor = 0; // asis 에디터에서의 현재 텍스트 오프셋
230
+ let tobeCursor = 0; // tobe 에디터에서의 현재 텍스트 오프셋
231
+
232
+ // 줄 단위 데코레이션을 위해 줄 시작 위치를 추적
233
+ const asisLineStartMap = new Map();
234
+ const tobeLineStartMap = new Map();
235
+
236
+ // 각 텍스트에 대한 줄 시작 위치 미리 계산
237
+ let currentPos = 0;
238
+ for (const line of asisSrc.split('\n')) {
239
+ asisLineStartMap.set(currentPos, true);
240
+ currentPos += line.length + 1; // +1은 줄바꿈 문자 포함
241
+ }
242
+ currentPos = 0;
243
+ for (const line of tobeSrc.split('\n')) {
244
+ tobeLineStartMap.set(currentPos, true);
245
+ currentPos += line.length + 1;
246
+ }
247
+
248
+ for (const [op, text] of diffs) {
249
+ const len = text.length;
250
+
251
+ switch (op) {
252
+ case diff_match_patch.DIFF_INSERT: // Added text
253
+ // tobe 쪽에 인라인 데코레이션 추가
254
+ tobeBuilder.add(
255
+ tobeCursor, tobeCursor + len,
256
+ Decoration.mark({ class: "cm-inserted-inline" })
257
+ );
258
+
259
+ // tobe 쪽에 줄 전체 데코레이션 추가 (삽입된 줄)
260
+ // text가 여러 줄일 수 있으므로 각 줄에 적용
261
+ const tobeLines = text.split('\n');
262
+ let currentLineOffset = tobeCursor;
263
+ for(let i = 0; i < tobeLines.length; i++) {
264
+ // 각 줄의 시작 위치를 찾기
265
+ const lineStart = tobeEditorView.state.doc.lineAt(currentLineOffset).from;
266
+ // 만약 다음 줄이 있다면 해당 줄의 끝까지, 마지막 줄이라면 텍스트의 끝까지
267
+ const lineEnd = i === tobeLines.length - 1 ? currentLineOffset + tobeLines[i].length : tobeEditorView.state.doc.lineAt(currentLineOffset).to;
268
+ tobeBuilder.add(
269
+ lineStart, lineEnd, // 줄의 실제 시작부터 끝까지
270
+ Decoration.line({ class: "cm-inserted-line-bg" })
271
+ );
272
+ currentLineOffset += tobeLines[i].length + 1; // 다음 줄 시작 위치로 이동
273
+ }
274
+
275
+
276
+ tobeCursor += len;
277
+ break;
278
+
279
+ case diff_match_patch.DIFF_DELETE: // Deleted text
280
+ // asis 쪽에 인라인 데코레이션 추가
281
+ asisBuilder.add(
282
+ asisCursor, asisCursor + len,
283
+ Decoration.mark({ class: "cm-deleted-inline" })
284
+ );
285
+
286
+ // asis 쪽에 줄 전체 데코레이션 추가 (삭제된 줄)
287
+ const asisLines = text.split('\n');
288
+ let currentAsisLineOffset = asisCursor;
289
+ for(let i = 0; i < asisLines.length; i++) {
290
+ const lineStart = asisEditorView.state.doc.lineAt(currentAsisLineOffset).from;
291
+ const lineEnd = i === asisLines.length - 1 ? currentAsisLineOffset + asisLines[i].length : asisEditorView.state.doc.lineAt(currentAsisLineOffset).to;
292
+ asisBuilder.add(
293
+ lineStart, lineEnd,
294
+ Decoration.line({ class: "cm-deleted-line-bg" })
295
+ );
296
+ currentAsisLineOffset += asisLines[i].length + 1;
297
+ }
298
+
299
+ asisCursor += len;
300
+ break;
301
+
302
+ case diff_match_patch.DIFF_EQUAL: // Unchanged text
303
+ asisCursor += len;
304
+ tobeCursor += len;
305
+ break;
306
+ }
307
+ }
308
+
309
+ // 에디터 뷰에 데코레이션 업데이트 요청 디스패치
310
+ this.#asisEditorView.dispatch({
311
+ effects: setAsisDecorationsEffect.of(asisBuilder.finish())
312
+ });
313
+ this.#tobeEditorView.dispatch({
314
+ effects: setTobeDecorationsEffect.of(tobeBuilder.finish())
315
+ });
316
+ };
317
+
318
+ initialize = (src1, src2, language = 'javascript') => {
319
+ if (!this.#asisEditorView || !this.#tobeEditorView) {
320
+ console.warn('CodeMirror Editors not initialized yet.');
71
321
  return;
72
322
  }
73
- this.#diffEditorInstance.setValues(src1, src2);
323
+
324
+ // 언어 변경 (선택 사항, 필요 시 활성화)
325
+ let langExtension;
326
+ switch(language) {
327
+ case 'javascript':
328
+ langExtension = javascript();
329
+ break;
330
+ // case 'html':
331
+ // import { html } from "@codemirror/lang-html"; // 상단에 임포트 필요
332
+ // langExtension = html();
333
+ // break;
334
+ // case 'css':
335
+ // import { css } from "@codemirror/lang-css"; // 상단에 임포트 필요
336
+ // langExtension = css();
337
+ // break;
338
+ default:
339
+ langExtension = javascript();
340
+ }
341
+
342
+ // 언어 확장 업데이트
343
+ this.#asisEditorView.dispatch({
344
+ effects: this.#languageCompartment.reconfigure(langExtension)
345
+ });
346
+ this.#tobeEditorView.dispatch({
347
+ effects: this.#languageCompartment.reconfigure(langExtension)
348
+ });
349
+
350
+ // 텍스트 내용 업데이트
351
+ this.#asisEditorView.dispatch({
352
+ changes: { from: 0, to: this.#asisEditorView.state.doc.length, insert: src1 }
353
+ });
354
+ this.#tobeEditorView.dispatch({
355
+ changes: { from: 0, to: this.#tobeEditorView.state.doc.length, insert: src2 }
356
+ });
357
+
358
+ // Diff 데코레이션 적용
359
+ this.#applyDiffDecorations(src1, src2);
74
360
  };
75
361
 
76
362
  disconnectedCallback() {
77
- if (this.#diffEditorInstance) {
78
- this.#diffEditorInstance.destroy(); // 인스턴스 정리 메서드 호출 (라이브러리마다 다름)
363
+ if (this.#asisEditorView) {
364
+ this.#asisEditorView.destroy();
365
+ }
366
+ if (this.#tobeEditorView) {
367
+ this.#tobeEditorView.destroy();
79
368
  }
80
369
  }
81
370
  }