mdsquare 0.0.0-stage → 0.2.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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/dist/callout.d.ts +17 -0
  4. package/dist/callout.js +541 -0
  5. package/dist/calloutHeader.d.ts +47 -0
  6. package/dist/calloutHeader.js +75 -0
  7. package/dist/codeBlock.d.ts +78 -0
  8. package/dist/codeBlock.js +686 -0
  9. package/dist/codeTheme.d.ts +47 -0
  10. package/dist/codeTheme.js +394 -0
  11. package/dist/delimiter.d.ts +20 -0
  12. package/dist/delimiter.js +73 -0
  13. package/dist/editor.d.ts +132 -0
  14. package/dist/editor.js +225 -0
  15. package/dist/emphasis.d.ts +6 -0
  16. package/dist/emphasis.js +101 -0
  17. package/dist/escape.d.ts +4 -0
  18. package/dist/escape.js +39 -0
  19. package/dist/extensions.d.ts +74 -0
  20. package/dist/extensions.js +81 -0
  21. package/dist/footnote.d.ts +24 -0
  22. package/dist/footnote.js +456 -0
  23. package/dist/footnoteSyntax.d.ts +23 -0
  24. package/dist/footnoteSyntax.js +107 -0
  25. package/dist/hashtag.d.ts +4 -0
  26. package/dist/hashtag.js +64 -0
  27. package/dist/hashtagSyntax.d.ts +36 -0
  28. package/dist/hashtagSyntax.js +99 -0
  29. package/dist/heading.d.ts +7 -0
  30. package/dist/heading.js +159 -0
  31. package/dist/highlight.d.ts +5 -0
  32. package/dist/highlight.js +6 -0
  33. package/dist/horizontalRule.d.ts +21 -0
  34. package/dist/horizontalRule.js +142 -0
  35. package/dist/image.d.ts +58 -0
  36. package/dist/image.js +344 -0
  37. package/dist/index.d.ts +16 -0
  38. package/dist/index.js +16 -0
  39. package/dist/inlineCode.d.ts +4 -0
  40. package/dist/inlineCode.js +68 -0
  41. package/dist/link.d.ts +47 -0
  42. package/dist/link.js +217 -0
  43. package/dist/list.d.ts +14 -0
  44. package/dist/list.js +136 -0
  45. package/dist/listEnter.d.ts +20 -0
  46. package/dist/listEnter.js +72 -0
  47. package/dist/listIndent.d.ts +23 -0
  48. package/dist/listIndent.js +335 -0
  49. package/dist/markVision.d.ts +17 -0
  50. package/dist/markVision.js +56 -0
  51. package/dist/math.d.ts +45 -0
  52. package/dist/math.js +233 -0
  53. package/dist/mathSyntax.d.ts +24 -0
  54. package/dist/mathSyntax.js +179 -0
  55. package/dist/mention.d.ts +4 -0
  56. package/dist/mention.js +58 -0
  57. package/dist/mentionSyntax.d.ts +14 -0
  58. package/dist/mentionSyntax.js +71 -0
  59. package/dist/quote.d.ts +9 -0
  60. package/dist/quote.js +122 -0
  61. package/dist/setup.d.ts +13 -0
  62. package/dist/setup.js +40 -0
  63. package/dist/style.css +6 -0
  64. package/dist/style.css.d.ts +2 -0
  65. package/dist/table.d.ts +38 -0
  66. package/dist/table.js +960 -0
  67. package/dist/tableEdit.d.ts +30 -0
  68. package/dist/tableEdit.js +305 -0
  69. package/dist/tableMenu.d.ts +65 -0
  70. package/dist/tableMenu.js +1125 -0
  71. package/dist/tableModel.d.ts +168 -0
  72. package/dist/tableModel.js +433 -0
  73. package/dist/tableState.d.ts +36 -0
  74. package/dist/tableState.js +96 -0
  75. package/dist/task.d.ts +13 -0
  76. package/dist/task.js +179 -0
  77. package/dist/textMate.d.ts +49 -0
  78. package/dist/textMate.js +284 -0
  79. package/dist/tikz.d.ts +56 -0
  80. package/dist/tikz.js +343 -0
  81. package/dist/underline.d.ts +5 -0
  82. package/dist/underline.js +6 -0
  83. package/dist/utils/blockMargin.d.ts +6 -0
  84. package/dist/utils/blockMargin.js +6 -0
  85. package/dist/utils/codePoint.d.ts +13 -0
  86. package/dist/utils/codePoint.js +43 -0
  87. package/dist/utils/container.d.ts +10 -0
  88. package/dist/utils/container.js +10 -0
  89. package/dist/utils/reveal.d.ts +99 -0
  90. package/dist/utils/reveal.js +161 -0
  91. package/dist/utils/selection.d.ts +33 -0
  92. package/dist/utils/selection.js +45 -0
  93. package/dist/utils/syntaxTree.d.ts +18 -0
  94. package/dist/utils/syntaxTree.js +23 -0
  95. package/package.json +79 -4
@@ -0,0 +1,1125 @@
1
+ import { Annotation } from "@codemirror/state";
2
+ import { EditorView, ViewPlugin } from "@codemirror/view";
3
+ import { TABLE_COLORS, setColumnAlign, setTableColor, setTableOption, tableNodeAt, tableRowAt, } from "./tableModel.js";
4
+ import { clearCells, commonCellColor, editTableColumn, editTableRow, setCellColor, moveTableColumn, moveTableRow, } from "./tableEdit.js";
5
+ import { cellIndexAt, selectedCells, setTableSelection, tableBlockAt, tableSelectionField, } from "./tableState.js";
6
+ // ---------------------------------------------------------------------------
7
+ // 행/열 손잡이와 메뉴 (Notion 방식)
8
+ // - 칸에 마우스를 올리면 그 행 왼쪽에 ⋮⋮, 그 열 위쪽에 ⋯ 손잡이
9
+ // - 손잡이를 누르면 메뉴(검색, 제목 행/열, 정렬, 색, 삽입, 복제, 내용 지우기, 삭제), 끌면 행/열 옮기기
10
+ // - 메뉴가 열린 동안(또는 끄는 동안) 그 행/열에 테두리
11
+ // ---------------------------------------------------------------------------
12
+ const SVG_NS = "http://www.w3.org/2000/svg";
13
+ function icon(paths, size = 16) {
14
+ const svg = document.createElementNS(SVG_NS, "svg");
15
+ svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
16
+ svg.setAttribute("width", String(size));
17
+ svg.setAttribute("height", String(size));
18
+ svg.setAttribute("aria-hidden", "true");
19
+ svg.innerHTML = paths;
20
+ return svg;
21
+ }
22
+ /** 점 6개 (가로 cols × 세로 rows) */
23
+ function grip(cols, rows) {
24
+ const w = cols * 4 + 2;
25
+ const h = rows * 4 + 2;
26
+ let dots = "";
27
+ for (let x = 0; x < cols; x++)
28
+ for (let y = 0; y < rows; y++)
29
+ dots += `<circle cx="${3 + x * 4}" cy="${3 + y * 4}" r="1.1"/>`;
30
+ const svg = document.createElementNS(SVG_NS, "svg");
31
+ svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
32
+ svg.setAttribute("width", String(w));
33
+ svg.setAttribute("height", String(h));
34
+ svg.setAttribute("fill", "currentColor");
35
+ svg.setAttribute("aria-hidden", "true");
36
+ svg.innerHTML = dots;
37
+ return svg;
38
+ }
39
+ const stroke = (paths) => `<g fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">${paths}</g>`;
40
+ const ICONS = {
41
+ headerRow: '<rect x="1.5" y="2.5" width="13" height="11" rx="1.5" fill="none" stroke="currentColor"/><path d="M2 3h12v3.5H2z" fill="currentColor"/><path d="M1.5 9.5h13M6 6.5v7M10.5 6.5v7" stroke="currentColor" fill="none"/>',
42
+ headerColumn: '<rect x="1.5" y="2.5" width="13" height="11" rx="1.5" fill="none" stroke="currentColor"/><path d="M2 3h4v10H2z" fill="currentColor"/><path d="M6 6.5h8.5M6 10h8.5M10.5 3v10" stroke="currentColor" fill="none"/>',
43
+ alignLeft: '<path d="M2 3.5h12M2 6.5h8M2 9.5h12M2 12.5h8" stroke="currentColor" stroke-linecap="round" fill="none"/>',
44
+ alignCenter: '<path d="M2 3.5h12M4 6.5h8M2 9.5h12M4 12.5h8" stroke="currentColor" stroke-linecap="round" fill="none"/>',
45
+ alignRight: '<path d="M2 3.5h12M6 6.5h8M2 9.5h12M6 12.5h8" stroke="currentColor" stroke-linecap="round" fill="none"/>',
46
+ color: stroke('<path d="M4 2.5h7v3.5H4zM11 4.25h1.5V8H7.5v2"/><rect x="6.5" y="10" width="2" height="4" rx=".5"/>'),
47
+ chevron: stroke('<path d="m6 4 4 4-4 4"/>'),
48
+ back: stroke('<path d="m10 4-4 4 4 4"/>'),
49
+ check: stroke('<path d="m3.5 8.5 3 3 6-7"/>'),
50
+ insertLeft: stroke('<path d="M13 8H3M7 4 3 8l4 4"/>'),
51
+ insertRight: stroke('<path d="M3 8h10M9 4l4 4-4 4"/>'),
52
+ insertAbove: stroke('<path d="M8 13V3M4 7l4-4 4 4"/>'),
53
+ insertBelow: stroke('<path d="M8 3v10M4 9l4 4 4-4"/>'),
54
+ duplicate: stroke('<rect x="5.5" y="5.5" width="8" height="8" rx="1.5"/><path d="M10.5 3.5V3a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6.5a1 1 0 0 0 1 1h.5"/>'),
55
+ clear: stroke('<circle cx="8" cy="8" r="6"/><path d="m6 6 4 4M10 6l-4 4"/>'),
56
+ delete: stroke('<path d="M2.5 4.5h11M6.5 4.5V3h3v1.5M4 4.5l.7 9h6.6l.7-9"/>'),
57
+ };
58
+ const ALIGNS = [
59
+ { align: "left", label: "왼쪽", keywords: "left align", icon: ICONS.alignLeft },
60
+ { align: "center", label: "가운데", keywords: "center align", icon: ICONS.alignCenter },
61
+ { align: "right", label: "오른쪽", keywords: "right align", icon: ICONS.alignRight },
62
+ ];
63
+ const COLOR_LABELS = {
64
+ gray: "회색",
65
+ brown: "갈색",
66
+ orange: "주황",
67
+ yellow: "노랑",
68
+ green: "초록",
69
+ blue: "파랑",
70
+ purple: "보라",
71
+ pink: "분홍",
72
+ red: "빨강",
73
+ };
74
+ const ROW_ACTIONS = [
75
+ { action: "insertAbove", label: "위에 삽입", keywords: "insert above row 행 추가", icon: ICONS.insertAbove },
76
+ { action: "insertBelow", label: "아래에 삽입", keywords: "insert below row 행 추가", icon: ICONS.insertBelow },
77
+ { action: "duplicate", label: "복제", keywords: "duplicate copy 복사", icon: ICONS.duplicate },
78
+ { action: "clear", label: "내용 지우기", keywords: "clear contents 비우기", icon: ICONS.clear },
79
+ { action: "delete", label: "삭제", keywords: "delete remove 지우기", icon: ICONS.delete },
80
+ ];
81
+ const COLUMN_ACTIONS = [
82
+ { action: "insertLeft", label: "왼쪽에 삽입", keywords: "insert left column 열 추가", icon: ICONS.insertLeft },
83
+ { action: "insertRight", label: "오른쪽에 삽입", keywords: "insert right column 열 추가", icon: ICONS.insertRight },
84
+ { action: "duplicate", label: "복제", keywords: "duplicate copy 복사", icon: ICONS.duplicate },
85
+ { action: "clear", label: "내용 지우기", keywords: "clear contents 비우기", icon: ICONS.clear },
86
+ { action: "delete", label: "삭제", keywords: "delete remove 지우기", icon: ICONS.delete },
87
+ ];
88
+ /** 메뉴가 바꾼 문서 변경 (메뉴를 닫지 않음) */
89
+ const fromMenu = Annotation.define();
90
+ /** 표의 index번째 행(0: 머리글 줄) 시작 위치 */
91
+ function rowStart(view, table, index) {
92
+ const node = tableNodeAt(view.state, table.from);
93
+ let i = 0;
94
+ for (let child = node?.firstChild ?? null; child; child = child.nextSibling) {
95
+ if (child.name !== "TableHeader" && child.name !== "TableRow")
96
+ continue;
97
+ if (i++ === index)
98
+ return child.from;
99
+ }
100
+ return null;
101
+ }
102
+ /** 표의 index번째 행 줄 요소 (화면에 그려져 있을 때만) */
103
+ function rowLine(view, table, index) {
104
+ const from = rowStart(view, table, index);
105
+ if (from === null)
106
+ return null;
107
+ try {
108
+ const { node: dom } = view.domAtPos(from);
109
+ const line = (dom instanceof HTMLElement ? dom : dom.parentElement)?.closest(".cm-line") ?? null;
110
+ return line?.classList.contains("cm-table-row") ? line : null;
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ /** 줄 요소의 column번째 칸 (모자란 칸 모양 포함) */
117
+ function cellOf(line, column) {
118
+ const cls = `.cm-table-col-${column}`;
119
+ return line?.querySelector(`:scope > ${cls}, :scope > .cm-table-missing > ${cls}`) ?? null;
120
+ }
121
+ /** 줄의 행 번호 (0: 머리글 줄). 표 노드의 자식만 훑습니다. */
122
+ function rowIndexOf(view, tableFrom, lineFrom) {
123
+ const node = tableNodeAt(view.state, tableFrom);
124
+ let i = 0;
125
+ for (let child = node?.firstChild ?? null; child; child = child.nextSibling) {
126
+ if (child.name !== "TableHeader" && child.name !== "TableRow")
127
+ continue;
128
+ if (view.state.doc.lineAt(child.from).from === lineFrom)
129
+ return i;
130
+ i++;
131
+ }
132
+ return -1;
133
+ }
134
+ /** 화면에 그려진 행 줄들과 번호 */
135
+ function renderedRows(view, table) {
136
+ const out = [];
137
+ const first = rowLine(view, table, 0) ?? null;
138
+ const wrapper = first?.parentElement ?? null;
139
+ if (!wrapper)
140
+ return out;
141
+ for (const line of wrapper.querySelectorAll(":scope > .cm-table-row")) {
142
+ let pos;
143
+ try {
144
+ pos = view.posAtDOM(line);
145
+ }
146
+ catch {
147
+ continue;
148
+ }
149
+ const index = rowIndexOf(view, table.from, view.state.doc.lineAt(pos).from);
150
+ if (index >= 0)
151
+ out.push({ index, line });
152
+ }
153
+ return out;
154
+ }
155
+ class TableHandles {
156
+ dom;
157
+ rowHandle;
158
+ columnHandle;
159
+ /** 끌 때 놓일 자리를 보여주는 선 */
160
+ indicator;
161
+ menu = null;
162
+ /** 칸 메뉴를 연 화면 좌표 */
163
+ menuPoint = null;
164
+ search = null;
165
+ list = null;
166
+ page = "main";
167
+ entries = [];
168
+ active = 0;
169
+ hover = null;
170
+ drag = null;
171
+ /** 끌기를 마친 직후의 click은 메뉴를 열지 않습니다. */
172
+ suppressClick = false;
173
+ hideTimer = -1;
174
+ view;
175
+ onDocumentMouseDown = (event) => {
176
+ if (!this.menu)
177
+ return;
178
+ const target = event.target;
179
+ if (target && (this.menu.contains(target) || this.rowHandle.contains(target) || this.columnHandle.contains(target)))
180
+ return;
181
+ this.closeMenu();
182
+ };
183
+ /** 에디터에 포커스가 없어도(메뉴를 마우스로만 열었을 때) Esc로 닫습니다. */
184
+ onDocumentKeyDown = (event) => {
185
+ if (event.key !== "Escape" || !this.menu)
186
+ return;
187
+ event.preventDefault();
188
+ event.stopPropagation();
189
+ this.closeMenu(true);
190
+ };
191
+ onScroll = (event) => {
192
+ // 메뉴 안(색 목록)의 스크롤은 무시합니다.
193
+ if (event.target instanceof Node && this.menu?.contains(event.target))
194
+ return;
195
+ // 칸 메뉴는 마우스 자리에 열었으므로 스크롤하면 닫고, 손잡이 메뉴는 손잡이를 따라갑니다.
196
+ if (this.view.state.field(tableSelectionField, false)?.kind === "cells")
197
+ this.closeMenu(true);
198
+ else
199
+ this.place();
200
+ };
201
+ onDragMove = (event) => this.dragMove(event);
202
+ onDragEnd = (event) => this.dragEnd(event);
203
+ constructor(view) {
204
+ this.view = view;
205
+ this.dom = document.createElement("div");
206
+ this.dom.className = "cm-table-handles";
207
+ this.rowHandle = this.handle("row", grip(2, 3), "행 메뉴 (끌어서 옮기기)");
208
+ this.columnHandle = this.handle("column", grip(3, 2), "열 메뉴 (끌어서 옮기기)");
209
+ this.indicator = document.createElement("div");
210
+ this.indicator.className = "cm-table-drop";
211
+ this.dom.appendChild(this.indicator);
212
+ view.scrollDOM.appendChild(this.dom);
213
+ }
214
+ handle(kind, svg, label) {
215
+ const button = document.createElement("button");
216
+ button.type = "button";
217
+ button.className = `cm-table-handle cm-table-handle-${kind}`;
218
+ button.setAttribute("aria-label", label);
219
+ button.setAttribute("aria-haspopup", "menu");
220
+ button.appendChild(svg);
221
+ button.addEventListener("mousedown", (event) => {
222
+ // 에디터 포커스와 커서를 유지합니다.
223
+ event.preventDefault();
224
+ if (event.button === 0)
225
+ this.dragStart(kind, event);
226
+ });
227
+ button.addEventListener("click", () => {
228
+ if (this.suppressClick)
229
+ return;
230
+ this.toggleMenu(kind);
231
+ });
232
+ button.addEventListener("mouseenter", () => this.cancelHide());
233
+ button.addEventListener("mouseleave", () => this.scheduleHide());
234
+ this.dom.appendChild(button);
235
+ return button;
236
+ }
237
+ // -- 마우스 올림 --------------------------------------------------------------
238
+ mousemove(event) {
239
+ if (this.menu || this.drag || event.buttons !== 0)
240
+ return;
241
+ const target = event.target instanceof Element ? event.target : null;
242
+ const cell = target?.closest(".cm-table-cell");
243
+ const line = cell?.closest(".cm-table-row");
244
+ if (!cell || !line)
245
+ return this.scheduleHide();
246
+ let pos;
247
+ try {
248
+ pos = this.view.posAtDOM(line);
249
+ }
250
+ catch {
251
+ return this.scheduleHide();
252
+ }
253
+ // 줄 기준으로 찾습니다. (인용/콜아웃 안 표는 줄 처음의 ">"가 Table 노드 밖이라 위치로 찾으면 못 찾음)
254
+ const found = tableRowAt(this.view.state, pos);
255
+ if (!found)
256
+ return this.scheduleHide();
257
+ const node = found.table;
258
+ this.cancelHide();
259
+ const column = /\bcm-table-col-(\d+)\b/.exec(cell.className);
260
+ const row = rowIndexOf(this.view, node.from, found.row.lineFrom);
261
+ if (!column || row < 0)
262
+ return this.scheduleHide();
263
+ this.hover = { table: node.from, row, column: Number(column[1]) };
264
+ this.place();
265
+ }
266
+ mouseleave() {
267
+ if (!this.menu && !this.drag)
268
+ this.scheduleHide();
269
+ }
270
+ scheduleHide() {
271
+ if (this.menu || this.drag || !this.hover || this.hideTimer >= 0)
272
+ return;
273
+ this.hideTimer = window.setTimeout(() => {
274
+ this.hideTimer = -1;
275
+ this.hover = null;
276
+ this.place();
277
+ }, 250);
278
+ }
279
+ cancelHide() {
280
+ if (this.hideTimer >= 0)
281
+ clearTimeout(this.hideTimer);
282
+ this.hideTimer = -1;
283
+ }
284
+ // -- 위치 ----------------------------------------------------------------------
285
+ /** 손잡이/메뉴 위치를 다시 잽니다. (읽기와 쓰기를 나눠 레이아웃을 한 번만 계산) */
286
+ place() {
287
+ this.view.requestMeasure({
288
+ key: this,
289
+ read: (view) => {
290
+ const menuRect = this.menu?.getBoundingClientRect() ?? null;
291
+ const win = view.dom.ownerDocument.defaultView;
292
+ const viewport = { width: win?.innerWidth ?? 0, height: win?.innerHeight ?? 0 };
293
+ const menuSize = menuRect && { width: menuRect.width, height: menuRect.height };
294
+ const handles = this.measureHandles(view);
295
+ return { handles, menuSize, viewport };
296
+ },
297
+ write: ({ handles: m, menuSize, viewport }) => {
298
+ const show = (el, on) => el.classList.toggle("cm-table-handle-visible", on);
299
+ const selection = this.view.state.field(tableSelectionField, false);
300
+ // 화면 밖으로 나가지 않게: 아래가 모자라면 위로(above), 오른쪽이 모자라면 왼쪽으로
301
+ const placeMenu = (anchor) => {
302
+ if (!this.menu)
303
+ return;
304
+ const size = menuSize ?? { width: 0, height: 0 };
305
+ const margin = 8;
306
+ let top = anchor.top;
307
+ if (viewport.height && top + size.height > viewport.height - margin)
308
+ top = Math.max(margin, anchor.above - size.height);
309
+ let left = anchor.left;
310
+ if (viewport.width && left + size.width > viewport.width - margin)
311
+ left = Math.max(margin, viewport.width - margin - size.width);
312
+ this.menu.style.left = `${left}px`;
313
+ this.menu.style.top = `${top}px`;
314
+ };
315
+ if (this.menu && selection?.kind === "cells" && this.menuPoint) {
316
+ placeMenu({ left: this.menuPoint.x, top: this.menuPoint.y, above: this.menuPoint.y });
317
+ }
318
+ if (!m) {
319
+ show(this.rowHandle, false);
320
+ show(this.columnHandle, false);
321
+ this.rowHandle.classList.remove("cm-table-handle-active");
322
+ this.columnHandle.classList.remove("cm-table-handle-active");
323
+ if (this.menu && selection?.kind !== "cells")
324
+ this.closeMenu();
325
+ return;
326
+ }
327
+ const { first, cell } = m;
328
+ show(this.rowHandle, true);
329
+ show(this.columnHandle, true);
330
+ // 행 손잡이: 그 행 첫 칸 왼쪽 테두리 위, 세로 가운데 / 열 손잡이: 그 열 머리글 칸 위쪽 테두리 위, 가로 가운데
331
+ this.rowHandle.style.left = `${first.x}px`;
332
+ this.rowHandle.style.top = `${first.y + first.height / 2}px`;
333
+ this.columnHandle.style.left = `${cell.x + cell.width / 2}px`;
334
+ this.columnHandle.style.top = `${cell.y}px`;
335
+ this.rowHandle.classList.toggle("cm-table-handle-active", selection?.kind === "row");
336
+ this.columnHandle.classList.toggle("cm-table-handle-active", selection?.kind === "column");
337
+ if (this.menu && (selection?.kind === "row" || selection?.kind === "column")) {
338
+ const handle = selection.kind === "row" ? this.rowHandle : this.columnHandle;
339
+ // 메뉴는 에디터 스크롤 영역 밖(fixed)에 그려 문서 끝에서도 잘리지 않게 합니다.
340
+ const s = m.screen;
341
+ placeMenu(selection.kind === "row"
342
+ ? { left: s.first.left + 14, top: s.first.top + s.first.height / 2 - 12, above: s.first.top + s.first.height / 2 - 12 }
343
+ : { left: s.cell.left + s.cell.width / 2 - 12, top: s.cell.top + 14, above: s.cell.top - 14 });
344
+ handle.setAttribute("aria-expanded", "true");
345
+ }
346
+ },
347
+ });
348
+ }
349
+ /** 손잡이 자리 (마우스가 표 위에 있을 때만) */
350
+ measureHandles(view) {
351
+ const hover = this.hover;
352
+ const table = hover ? tableBlockAt(view.state, hover.table) : null;
353
+ // 행 손잡이: 그 행 첫 칸 / 열 손잡이: 머리글 줄의 그 열 칸
354
+ const first = table && hover ? cellOf(rowLine(view, table, hover.row), 0) : null;
355
+ const cell = table && hover ? cellOf(rowLine(view, table, 0), hover.column) : null;
356
+ if (!hover || !first || !cell)
357
+ return null;
358
+ const base = view.scrollDOM.getBoundingClientRect();
359
+ const toLocal = (rect) => ({
360
+ x: rect.left - base.left + view.scrollDOM.scrollLeft,
361
+ y: rect.top - base.top + view.scrollDOM.scrollTop,
362
+ width: rect.width,
363
+ height: rect.height,
364
+ });
365
+ const firstRect = first.getBoundingClientRect();
366
+ const cellRect = cell.getBoundingClientRect();
367
+ return {
368
+ hover,
369
+ first: toLocal(firstRect),
370
+ cell: toLocal(cellRect),
371
+ // 메뉴는 화면 좌표(fixed)로 둡니다.
372
+ screen: { first: firstRect, cell: cellRect },
373
+ };
374
+ }
375
+ // -- 끌어서 옮기기 ----------------------------------------------------------------
376
+ dragStart(kind, event) {
377
+ if (!this.hover)
378
+ return;
379
+ const index = kind === "row" ? this.hover.row : this.hover.column;
380
+ this.drag = { kind, table: this.hover.table, index, x: event.clientX, y: event.clientY, active: false, slot: null };
381
+ const doc = this.view.dom.ownerDocument;
382
+ doc.addEventListener("mousemove", this.onDragMove, true);
383
+ doc.addEventListener("mouseup", this.onDragEnd, true);
384
+ }
385
+ dragMove(event) {
386
+ const drag = this.drag;
387
+ if (!drag)
388
+ return;
389
+ if (!drag.active) {
390
+ if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 4)
391
+ return;
392
+ drag.active = true;
393
+ this.closeMenu();
394
+ this.view.dispatch({ effects: setTableSelection.of({ table: drag.table, kind: drag.kind, index: drag.index }) });
395
+ this.view.dom.classList.add("cm-table-dragging");
396
+ }
397
+ const table = tableBlockAt(this.view.state, drag.table);
398
+ if (!table)
399
+ return;
400
+ const base = this.view.scrollDOM.getBoundingClientRect();
401
+ const sx = this.view.scrollDOM.scrollLeft - base.left;
402
+ const sy = this.view.scrollDOM.scrollTop - base.top;
403
+ const rows = renderedRows(this.view, table);
404
+ if (rows.length === 0)
405
+ return;
406
+ const header = cellOf(rows[0].index === 0 ? rows[0].line : null, 0);
407
+ const lastRect = rows[rows.length - 1].line.getBoundingClientRect();
408
+ const style = this.indicator.style;
409
+ if (drag.kind === "row") {
410
+ // 마우스가 행의 가운데보다 위면 그 행 앞자리
411
+ let slot = rows[rows.length - 1].index + 1;
412
+ let y = lastRect.bottom;
413
+ for (const { index, line } of rows) {
414
+ const rect = line.getBoundingClientRect();
415
+ if (event.clientY < rect.top + rect.height / 2) {
416
+ slot = index;
417
+ y = rect.top;
418
+ break;
419
+ }
420
+ }
421
+ drag.slot = slot;
422
+ const firstCell = cellOf(rows[0].line, 0)?.getBoundingClientRect();
423
+ const lastCell = cellOf(rows[0].line, table.columns - 1)?.getBoundingClientRect();
424
+ if (!firstCell || !lastCell)
425
+ return;
426
+ style.left = `${firstCell.left + sx}px`;
427
+ style.width = `${lastCell.right - firstCell.left}px`;
428
+ style.top = `${y + sy - 1}px`;
429
+ style.height = "2px";
430
+ }
431
+ else {
432
+ const headerLine = header?.closest(".cm-table-row") ?? null;
433
+ if (!headerLine)
434
+ return;
435
+ let slot = table.columns;
436
+ let x = cellOf(headerLine, table.columns - 1)?.getBoundingClientRect().right ?? 0;
437
+ for (let col = 0; col < table.columns; col++) {
438
+ const rect = cellOf(headerLine, col)?.getBoundingClientRect();
439
+ if (rect && event.clientX < rect.left + rect.width / 2) {
440
+ slot = col;
441
+ x = rect.left;
442
+ break;
443
+ }
444
+ }
445
+ drag.slot = slot;
446
+ const top = headerLine.getBoundingClientRect().top;
447
+ style.left = `${x + sx - 1}px`;
448
+ style.width = "2px";
449
+ style.top = `${top + sy}px`;
450
+ style.height = `${lastRect.bottom - top}px`;
451
+ }
452
+ this.indicator.classList.add("cm-table-drop-visible");
453
+ }
454
+ dragEnd(event) {
455
+ const drag = this.drag;
456
+ this.drag = null;
457
+ const doc = this.view.dom.ownerDocument;
458
+ doc.removeEventListener("mousemove", this.onDragMove, true);
459
+ doc.removeEventListener("mouseup", this.onDragEnd, true);
460
+ if (!drag?.active)
461
+ return; // 그냥 누름: click에서 메뉴를 엽니다.
462
+ event.preventDefault();
463
+ this.indicator.classList.remove("cm-table-drop-visible");
464
+ this.view.dom.classList.remove("cm-table-dragging");
465
+ this.suppressClick = true;
466
+ setTimeout(() => (this.suppressClick = false), 0);
467
+ const { state } = this.view;
468
+ const table = tableBlockAt(state, drag.table);
469
+ const spec = table && drag.slot !== null
470
+ ? drag.kind === "row"
471
+ ? moveTableRow(state, table, drag.index, drag.slot)
472
+ : moveTableColumn(state, table, drag.index, drag.slot)
473
+ : null;
474
+ this.view.dispatch({
475
+ ...(spec ?? {}),
476
+ effects: setTableSelection.of(null),
477
+ ...(spec ? { userEvent: "move.table", scrollIntoView: true } : {}),
478
+ });
479
+ this.hover = null;
480
+ this.place();
481
+ }
482
+ // -- 메뉴 ----------------------------------------------------------------------
483
+ toggleMenu(kind) {
484
+ const current = this.view.state.field(tableSelectionField, false);
485
+ if (this.menu && current?.kind === kind)
486
+ return this.closeMenu(true);
487
+ if (!this.hover)
488
+ return;
489
+ const index = kind === "row" ? this.hover.row : this.hover.column;
490
+ this.openMenu({ table: this.hover.table, kind, index }, null);
491
+ }
492
+ /** 칸에서 오른쪽 클릭: 고른 칸 범위 안이면 그 범위, 아니면 그 칸의 메뉴를 마우스 자리에 엽니다. */
493
+ contextmenu(event) {
494
+ const target = event.target instanceof Element ? event.target : null;
495
+ const cellEl = target?.closest(".cm-table-cell");
496
+ if (!cellEl)
497
+ return false;
498
+ let pos;
499
+ try {
500
+ pos = this.view.posAtDOM(cellEl);
501
+ }
502
+ catch {
503
+ return false;
504
+ }
505
+ const at = cellIndexAt(this.view.state, pos);
506
+ const column = /\bcm-table-col-(\d+)\b/.exec(cellEl.className);
507
+ if (!at || !column)
508
+ return false;
509
+ const col = Number(column[1]);
510
+ const picked = selectedCells(this.view.state);
511
+ const inside = picked && picked.table === at.table && at.row >= picked.fromRow && at.row <= picked.toRow && col >= picked.fromColumn && col <= picked.toColumn;
512
+ const { table: _table, ...range } = picked ?? { table: 0, fromRow: 0, toRow: 0, fromColumn: 0, toColumn: 0 };
513
+ const cells = inside ? range : { fromRow: at.row, toRow: at.row, fromColumn: col, toColumn: col };
514
+ event.preventDefault();
515
+ this.openMenu({ table: at.table, kind: "cells", index: 0, cells }, { x: event.clientX, y: event.clientY });
516
+ return true;
517
+ }
518
+ /** 메뉴를 엽니다. point: 칸 메뉴를 열 화면 좌표 (손잡이 메뉴는 null: 손잡이 옆) */
519
+ openMenu(selection, point) {
520
+ this.closeMenu();
521
+ this.menuPoint = point;
522
+ this.view.dispatch({ effects: setTableSelection.of(selection) });
523
+ const menu = document.createElement("div");
524
+ menu.className = "cm-table-menu";
525
+ menu.setAttribute("role", "menu");
526
+ // 검색 칸이 아니면 누를 때 포커스를 옮기지 않습니다.
527
+ menu.addEventListener("mousedown", (event) => {
528
+ if (event.target !== this.search)
529
+ event.preventDefault();
530
+ });
531
+ const search = document.createElement("input");
532
+ search.type = "text";
533
+ search.className = "cm-table-menu-search";
534
+ search.placeholder = "동작 검색…";
535
+ search.setAttribute("aria-label", "동작 검색");
536
+ search.addEventListener("input", () => {
537
+ this.active = 0;
538
+ this.renderMenu();
539
+ });
540
+ search.addEventListener("keydown", (event) => this.menuKey(event));
541
+ const list = document.createElement("div");
542
+ list.className = "cm-table-menu-list";
543
+ menu.append(search, list);
544
+ this.menu = menu;
545
+ this.search = search;
546
+ this.list = list;
547
+ this.page = "main";
548
+ this.active = 0;
549
+ this.view.dom.appendChild(menu);
550
+ this.renderMenu();
551
+ const doc = this.view.dom.ownerDocument;
552
+ doc.addEventListener("mousedown", this.onDocumentMouseDown, true);
553
+ doc.addEventListener("keydown", this.onDocumentKeyDown, true);
554
+ // fixed 메뉴는 스크롤을 따라가지 않으므로 다시 잽니다. (페이지와 에디터 스크롤 모두: capture)
555
+ doc.addEventListener("scroll", this.onScroll, true);
556
+ search.focus({ preventScroll: true });
557
+ this.place();
558
+ // 메뉴 크기를 안 뒤 한 번 더 (아래 공간이 모자라면 위로)
559
+ this.place();
560
+ }
561
+ /** 메뉴 키보드: ↑/↓ 항목 이동, Enter 실행, 빈 검색에서 Backspace는 하위 메뉴에서 돌아가기 (Esc는 문서 전체에서 처리) */
562
+ menuKey(event) {
563
+ const count = this.entries.length;
564
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
565
+ event.preventDefault();
566
+ if (count)
567
+ this.setActive((this.active + (event.key === "ArrowDown" ? 1 : count - 1)) % count);
568
+ }
569
+ else if (event.key === "Enter") {
570
+ event.preventDefault();
571
+ this.entries[this.active]?.run();
572
+ }
573
+ else if (event.key === "Backspace" && this.page !== "main" && this.search?.value === "") {
574
+ event.preventDefault();
575
+ this.page = "main";
576
+ this.active = 0;
577
+ this.renderMenu();
578
+ }
579
+ }
580
+ setActive(index) {
581
+ this.active = index;
582
+ const items = this.list?.querySelectorAll(".cm-table-menu-item[data-entry]") ?? [];
583
+ items.forEach((item, i) => item.classList.toggle("cm-table-menu-active", i === index));
584
+ items[index]?.scrollIntoView?.({ block: "nearest" }); // 레이아웃이 없는 환경(jsdom)에는 없음
585
+ }
586
+ context() {
587
+ const selection = this.view.state.field(tableSelectionField, false);
588
+ const table = selection ? tableBlockAt(this.view.state, selection.table) : null;
589
+ return selection && table ? { table, selection } : null;
590
+ }
591
+ /** 원문을 바꾸는 명령 실행 */
592
+ apply(spec, close) {
593
+ // 커서를 옮기는 동작(행/열 삽입 등)만 그 자리로 스크롤합니다.
594
+ // 색/내용 지우기처럼 커서가 그대로인 동작에서 스크롤하면, 커서가 표 밖에 있을 때 화면이 그쪽으로 튀어 표가 사라집니다.
595
+ if (spec) {
596
+ this.view.dispatch({ ...spec, annotations: fromMenu.of(true), userEvent: "input.table", scrollIntoView: spec.selection !== undefined });
597
+ }
598
+ if (close) {
599
+ this.closeMenu(true);
600
+ this.hover = null;
601
+ this.place();
602
+ }
603
+ }
604
+ /** 지금 상태로 메뉴 항목들을 만듭니다. */
605
+ buildEntries(table, selection, query) {
606
+ const { state } = this.view;
607
+ const { kind, index } = selection;
608
+ const axis = kind === "row" ? "row" : "column";
609
+ const range = kind === "cells" ? (selection.cells ?? null) : null;
610
+ const entries = [];
611
+ /** 지금 색: 글자 색과 배경 색이 따로. 칸은 고른 칸들의 색이 모두 같을 때만 (아니면 undefined: 표시 없음) */
612
+ const current = range
613
+ ? { fg: commonCellColor(state, table, range, "fg"), bg: commonCellColor(state, table, range, "bg") }
614
+ : ((kind === "row" ? table.colors.rows : table.colors.columns).get(index) ?? { fg: null, bg: null });
615
+ /** flat: 검색 결과처럼 하위 메뉴 밖에 보일 때는 "글자 색 · 빨강"처럼 구역 이름을 붙입니다. */
616
+ const colorEntries = (flat) => {
617
+ const out = [];
618
+ for (const bg of [false, true]) {
619
+ const group = bg ? "배경 색" : "글자 색";
620
+ for (const name of [null, ...TABLE_COLORS]) {
621
+ const label = name === null ? "기본" : COLOR_LABELS[name];
622
+ // 글자 색과 배경 색은 따로 정합니다. ("기본"은 그쪽 색만 없앰)
623
+ const checked = (bg ? current.bg : current.fg) === name;
624
+ out.push({
625
+ id: `color:${bg ? "bg" : "fg"}:${name ?? "default"}`,
626
+ label: flat ? `${group} · ${label}` : label,
627
+ keywords: `${group} ${name ?? "default"} ${bg ? "background" : "text"} color 색`,
628
+ icon: () => swatch(name, bg),
629
+ trailing: checked ? "check" : undefined,
630
+ close: true,
631
+ run: () => this.apply(range
632
+ ? setCellColor(state, table, range, bg ? "bg" : "fg", name)
633
+ : setTableColor(state, table, axis, index, bg ? "bg" : "fg", name), true),
634
+ });
635
+ }
636
+ }
637
+ return out;
638
+ };
639
+ if (this.page === "color" && !query) {
640
+ entries.push({
641
+ id: "back",
642
+ label: "색",
643
+ keywords: "back",
644
+ icon: ICONS.back,
645
+ close: false,
646
+ run: () => {
647
+ this.page = "main";
648
+ this.active = 0;
649
+ this.renderMenu();
650
+ },
651
+ });
652
+ entries.push(...colorEntries(false));
653
+ return { entries, align: false };
654
+ }
655
+ if (kind === "row" && index === 0)
656
+ entries.push(this.switchEntry("제목 행", "header row", ICONS.headerRow, table, "headerRow"));
657
+ if (kind === "column" && index === 0)
658
+ entries.push(this.switchEntry("제목 열", "header column", ICONS.headerColumn, table, "headerColumn"));
659
+ // 정렬: 검색하지 않을 때는 버튼 묶음 한 줄, 검색하면 항목 셋
660
+ const showAlignGroup = kind === "column" && !query;
661
+ if (kind === "column" && query) {
662
+ const current = table.aligns[index] ?? "left";
663
+ for (const a of ALIGNS) {
664
+ entries.push({
665
+ id: `align:${a.align}`,
666
+ label: `${a.label} 정렬`,
667
+ keywords: a.keywords,
668
+ icon: a.icon,
669
+ trailing: current === a.align ? "check" : undefined,
670
+ close: false,
671
+ run: () => this.apply(setColumnAlign(state, table, index, a.align), false),
672
+ });
673
+ }
674
+ }
675
+ entries.push({
676
+ id: "color",
677
+ label: "색",
678
+ keywords: "color 글자 배경 background text",
679
+ icon: ICONS.color,
680
+ trailing: "submenu",
681
+ close: false,
682
+ run: () => {
683
+ this.page = "color";
684
+ this.active = 0;
685
+ if (this.search)
686
+ this.search.value = "";
687
+ this.renderMenu();
688
+ },
689
+ });
690
+ if (range) {
691
+ entries.push({
692
+ id: "clear",
693
+ label: "내용 지우기",
694
+ keywords: "clear contents 비우기",
695
+ icon: ICONS.clear,
696
+ close: true,
697
+ run: () => this.apply(clearCells(state, table, range), true),
698
+ });
699
+ if (query)
700
+ entries.push(...colorEntries(true));
701
+ return { entries, align: false };
702
+ }
703
+ for (const item of kind === "row" ? ROW_ACTIONS : COLUMN_ACTIONS) {
704
+ entries.push({
705
+ id: item.action,
706
+ label: item.label,
707
+ keywords: item.keywords,
708
+ icon: item.icon,
709
+ close: true,
710
+ run: () => this.apply(kind === "row"
711
+ ? editTableRow(state, table, index, item.action)
712
+ : editTableColumn(state, table, index, item.action), true),
713
+ });
714
+ }
715
+ // 검색하면 색도 바로 고를 수 있게 합니다.
716
+ if (query)
717
+ entries.push(...colorEntries(true));
718
+ return { entries, align: showAlignGroup };
719
+ }
720
+ switchEntry(label, keywords, svg, table, option) {
721
+ const checked = table.options[option];
722
+ return {
723
+ id: `option:${option}`,
724
+ label,
725
+ keywords,
726
+ icon: svg,
727
+ trailing: checked ? "switch-on" : "switch-off",
728
+ close: false,
729
+ run: () => this.apply(setTableOption(this.view.state, table, option, !table.options[option]), false),
730
+ };
731
+ }
732
+ renderMenu() {
733
+ const list = this.list;
734
+ const cx = this.context();
735
+ if (!list || !cx)
736
+ return;
737
+ const query = (this.search?.value ?? "").trim().toLowerCase();
738
+ const built = this.buildEntries(cx.table, cx.selection, query);
739
+ const entries = query
740
+ ? built.entries.filter((e) => `${e.label} ${e.keywords}`.toLowerCase().includes(query))
741
+ : built.entries;
742
+ this.entries = entries;
743
+ this.active = Math.min(this.active, Math.max(0, entries.length - 1));
744
+ list.textContent = "";
745
+ const separator = () => {
746
+ const line = document.createElement("div");
747
+ line.className = "cm-table-menu-separator";
748
+ line.setAttribute("role", "separator");
749
+ return line;
750
+ };
751
+ const sectionTitle = (text) => {
752
+ const title = document.createElement("div");
753
+ title.className = "cm-table-menu-section";
754
+ title.textContent = text;
755
+ return title;
756
+ };
757
+ if (entries.length === 0) {
758
+ const empty = document.createElement("div");
759
+ empty.className = "cm-table-menu-empty";
760
+ empty.textContent = "일치하는 동작이 없습니다";
761
+ list.appendChild(empty);
762
+ return;
763
+ }
764
+ let previousGroup = "";
765
+ entries.forEach((entry, i) => {
766
+ // 구역 나누기: 하위 메뉴의 글자/배경 색 제목, 주 메뉴에서 설정과 동작 사이 구분선
767
+ const group = entry.id.startsWith("color:") ? entry.id.split(":")[1] : entry.id.startsWith("option:") ? "option" : "action";
768
+ if (!query && this.page === "color" && group !== previousGroup && (group === "fg" || group === "bg")) {
769
+ list.appendChild(sectionTitle(group === "fg" ? "글자 색" : "배경 색"));
770
+ }
771
+ if (!query && this.page === "main" && entry.id === "color") {
772
+ if (built.align)
773
+ list.appendChild(this.alignGroup(cx.table, cx.selection.index));
774
+ if (i > 0 || built.align)
775
+ list.appendChild(separator());
776
+ }
777
+ previousGroup = group;
778
+ list.appendChild(this.renderEntry(entry, i));
779
+ });
780
+ }
781
+ renderEntry(entry, i) {
782
+ const row = document.createElement("button");
783
+ row.type = "button";
784
+ row.className = `cm-table-menu-item${i === this.active ? " cm-table-menu-active" : ""}`;
785
+ row.dataset["entry"] = entry.id;
786
+ if (!entry.id.includes(":") && entry.id !== "color" && entry.id !== "back")
787
+ row.dataset["action"] = entry.id;
788
+ if (entry.id.startsWith("option:"))
789
+ row.dataset["option"] = entry.id.slice(7);
790
+ row.setAttribute("role", entry.trailing === "switch-on" || entry.trailing === "switch-off" ? "menuitemcheckbox" : entry.trailing === "check" ? "menuitemradio" : "menuitem");
791
+ if (entry.trailing === "switch-on" || entry.trailing === "switch-off")
792
+ row.setAttribute("aria-checked", String(entry.trailing === "switch-on"));
793
+ if (entry.trailing === "check")
794
+ row.setAttribute("aria-checked", "true");
795
+ if (entry.trailing === "submenu")
796
+ row.setAttribute("aria-haspopup", "menu");
797
+ const label = document.createElement("span");
798
+ label.className = "cm-table-menu-label";
799
+ label.textContent = entry.label;
800
+ row.append(typeof entry.icon === "string" ? icon(entry.icon) : entry.icon(), label);
801
+ if (entry.trailing === "switch-on" || entry.trailing === "switch-off") {
802
+ const toggle = document.createElement("span");
803
+ toggle.className = `cm-table-switch${entry.trailing === "switch-on" ? " cm-table-switch-on" : ""}`;
804
+ row.appendChild(toggle);
805
+ }
806
+ else if (entry.trailing === "submenu") {
807
+ row.appendChild(icon(ICONS.chevron));
808
+ }
809
+ else if (entry.trailing === "check") {
810
+ row.appendChild(icon(ICONS.check));
811
+ }
812
+ row.addEventListener("mouseenter", () => this.setActive(i));
813
+ row.addEventListener("click", () => entry.run());
814
+ return row;
815
+ }
816
+ /** 정렬: 왼쪽/가운데/오른쪽 버튼 (정렬 표시가 없으면 왼쪽) */
817
+ alignGroup(table, column) {
818
+ const current = table.aligns[column] ?? "left";
819
+ const row = document.createElement("div");
820
+ row.className = "cm-table-menu-item cm-table-menu-align";
821
+ row.setAttribute("role", "group");
822
+ row.setAttribute("aria-label", "정렬");
823
+ const label = document.createElement("span");
824
+ label.className = "cm-table-menu-label";
825
+ label.textContent = "정렬";
826
+ const group = document.createElement("span");
827
+ group.className = "cm-table-segment";
828
+ for (const a of ALIGNS) {
829
+ const button = document.createElement("button");
830
+ button.type = "button";
831
+ button.className = `cm-table-segment-button${a.align === current ? " cm-table-segment-on" : ""}`;
832
+ button.setAttribute("role", "menuitemradio");
833
+ button.setAttribute("aria-checked", String(a.align === current));
834
+ button.setAttribute("aria-label", a.label);
835
+ button.title = a.label;
836
+ button.dataset["align"] = a.align;
837
+ button.appendChild(icon(a.icon));
838
+ button.addEventListener("click", () => this.apply(setColumnAlign(this.view.state, table, column, a.align), false));
839
+ group.appendChild(button);
840
+ }
841
+ const currentIcon = ALIGNS.find((a) => a.align === current).icon;
842
+ row.append(icon(currentIcon), label, group);
843
+ return row;
844
+ }
845
+ closeMenu(refocus = false) {
846
+ if (!this.menu)
847
+ return;
848
+ const hadFocus = this.menu.contains(this.view.dom.ownerDocument.activeElement);
849
+ this.menu.remove();
850
+ this.menu = null;
851
+ this.search = null;
852
+ this.list = null;
853
+ this.entries = [];
854
+ this.rowHandle.removeAttribute("aria-expanded");
855
+ this.columnHandle.removeAttribute("aria-expanded");
856
+ const doc = this.view.dom.ownerDocument;
857
+ doc.removeEventListener("mousedown", this.onDocumentMouseDown, true);
858
+ doc.removeEventListener("keydown", this.onDocumentKeyDown, true);
859
+ doc.removeEventListener("scroll", this.onScroll, true);
860
+ // 검색 칸에 있던 포커스를 에디터로 돌려줍니다.
861
+ if (refocus && hadFocus)
862
+ this.view.focus();
863
+ if (this.view.state.field(tableSelectionField, false) && !this.drag?.active) {
864
+ // 업데이트 도중이면 다음 틱에 해제합니다.
865
+ queueMicrotask(() => {
866
+ if (this.view.state.field(tableSelectionField, false) && !this.drag?.active) {
867
+ this.view.dispatch({ effects: setTableSelection.of(null) });
868
+ }
869
+ });
870
+ }
871
+ this.place();
872
+ }
873
+ update(update) {
874
+ const selection = update.state.field(tableSelectionField, false);
875
+ if (this.menu) {
876
+ const ours = update.transactions.some((tr) => tr.annotation(fromMenu));
877
+ if (!selection || (update.docChanged && !ours)) {
878
+ this.closeMenu();
879
+ return;
880
+ }
881
+ if (this.hover) {
882
+ this.hover = {
883
+ ...this.hover,
884
+ table: selection.table,
885
+ row: selection.kind === "row" ? selection.index : this.hover.row,
886
+ column: selection.kind === "column" ? selection.index : this.hover.column,
887
+ };
888
+ }
889
+ if (update.docChanged || update.startState.field(tableSelectionField, false) !== selection)
890
+ this.renderMenu();
891
+ this.place();
892
+ return;
893
+ }
894
+ if (update.docChanged && this.hover && !this.drag) {
895
+ // 입력 중에는 손잡이를 숨깁니다.
896
+ this.hover = null;
897
+ this.place();
898
+ }
899
+ else if (this.hover && (update.geometryChanged || update.startState.field(tableSelectionField, false) !== selection)) {
900
+ // 메뉴를 닫아 고른 행/열이 풀리면 손잡이의 강조도 풉니다.
901
+ this.place();
902
+ }
903
+ }
904
+ destroy() {
905
+ this.cancelHide();
906
+ const doc = this.view.dom.ownerDocument;
907
+ doc.removeEventListener("mousedown", this.onDocumentMouseDown, true);
908
+ doc.removeEventListener("keydown", this.onDocumentKeyDown, true);
909
+ doc.removeEventListener("scroll", this.onScroll, true);
910
+ doc.removeEventListener("mousemove", this.onDragMove, true);
911
+ doc.removeEventListener("mouseup", this.onDragEnd, true);
912
+ this.menu?.remove();
913
+ this.dom.remove();
914
+ }
915
+ }
916
+ /** 색 견본: 글자 색은 "A", 배경 색은 칠한 네모 */
917
+ function swatch(name, bg) {
918
+ const el = document.createElement("span");
919
+ el.className = `cm-table-swatch${bg ? " cm-table-swatch-bg" : ""}`;
920
+ el.setAttribute("aria-hidden", "true");
921
+ if (bg)
922
+ el.style.backgroundColor = name ? `var(--cm-table-bg-${name})` : "transparent";
923
+ else {
924
+ el.textContent = "A";
925
+ if (name)
926
+ el.style.color = `var(--cm-table-fg-${name})`;
927
+ }
928
+ return el;
929
+ }
930
+ export const tableHandles = ViewPlugin.fromClass(TableHandles, {
931
+ eventHandlers: {
932
+ mousemove(event) {
933
+ this.mousemove(event);
934
+ },
935
+ mouseleave() {
936
+ this.mouseleave();
937
+ },
938
+ contextmenu(event) {
939
+ return this.contextmenu(event);
940
+ },
941
+ mousedown(event) {
942
+ // 칸에서 오른쪽 버튼을 누르면 브라우저가 커서를 그 자리로 옮기는데, 칸 처음이면 색 표식이 펼쳐져
943
+ // 색을 고른 직후 결과 대신 원문(`<!--fg:red-->`)이 보입니다. 오른쪽 버튼은 커서를 옮기지 않게 합니다.
944
+ if (event.button === 2 && event.target instanceof Element && event.target.closest(".cm-table-cell")) {
945
+ event.preventDefault();
946
+ return true;
947
+ }
948
+ return false;
949
+ },
950
+ },
951
+ });
952
+ export const tableMenuTheme = EditorView.baseTheme({
953
+ ".cm-table-handles": { position: "absolute", top: "0", left: "0", width: "0", height: "0", zIndex: "250" },
954
+ ".cm-table-handle": {
955
+ position: "absolute",
956
+ display: "none",
957
+ alignItems: "center",
958
+ justifyContent: "center",
959
+ padding: "0",
960
+ border: "1px solid var(--cm-table-handle-border)",
961
+ borderRadius: "4px",
962
+ background: "var(--cm-table-handle-bg)",
963
+ color: "var(--cm-table-handle-fg)",
964
+ cursor: "grab",
965
+ transform: "translate(-50%, -50%)",
966
+ boxShadow: "0 1px 2px rgba(0, 0, 0, 0.08)",
967
+ },
968
+ ".cm-table-handle.cm-table-handle-visible": { display: "flex" },
969
+ ".cm-table-handle-row": { width: "12px", height: "22px" },
970
+ ".cm-table-handle-column": { width: "22px", height: "12px" },
971
+ ".cm-table-handle:hover": { background: "var(--cm-table-handle-hover)" },
972
+ ".cm-table-handle.cm-table-handle-active": {
973
+ background: "var(--cm-table-select)",
974
+ borderColor: "var(--cm-table-select)",
975
+ color: "#fff",
976
+ },
977
+ "&light .cm-table-handles, &light .cm-table-menu": {
978
+ "--cm-table-handle-bg": "#fff",
979
+ "--cm-table-handle-hover": "#f1f1ef",
980
+ "--cm-table-handle-border": "#dcdcdc",
981
+ "--cm-table-handle-fg": "#9b9a97",
982
+ "--cm-table-select": "#2383e2",
983
+ "--cm-table-menu-bg": "#fff",
984
+ "--cm-table-menu-fg": "#37352f",
985
+ "--cm-table-menu-hover": "rgba(55, 53, 47, 0.08)",
986
+ "--cm-table-switch-off": "rgba(135, 131, 120, 0.3)",
987
+ "--cm-table-menu-border": "rgba(55, 53, 47, 0.16)",
988
+ "--cm-table-menu-input": "rgba(242, 241, 238, 0.6)",
989
+ "--cm-table-select-soft": "rgba(35, 131, 226, 0.2)",
990
+ },
991
+ "&dark .cm-table-handles, &dark .cm-table-menu": {
992
+ "--cm-table-handle-bg": "#2f3437",
993
+ "--cm-table-handle-hover": "#3a4044",
994
+ "--cm-table-handle-border": "#4b5563",
995
+ "--cm-table-handle-fg": "#9ca3af",
996
+ "--cm-table-select": "#4ea1f3",
997
+ "--cm-table-menu-bg": "#252525",
998
+ "--cm-table-menu-fg": "#e5e5e5",
999
+ "--cm-table-menu-hover": "rgba(255, 255, 255, 0.08)",
1000
+ "--cm-table-switch-off": "rgba(255, 255, 255, 0.2)",
1001
+ "--cm-table-menu-border": "rgba(255, 255, 255, 0.14)",
1002
+ "--cm-table-menu-input": "rgba(255, 255, 255, 0.05)",
1003
+ "--cm-table-select-soft": "rgba(78, 161, 243, 0.25)",
1004
+ },
1005
+ ".cm-table-menu": {
1006
+ position: "fixed",
1007
+ zIndex: "500",
1008
+ minWidth: "220px",
1009
+ padding: "6px",
1010
+ borderRadius: "8px",
1011
+ background: "var(--cm-table-menu-bg)",
1012
+ color: "var(--cm-table-menu-fg)",
1013
+ boxShadow: "0 0 0 1px rgba(15, 15, 15, 0.05), 0 3px 6px rgba(15, 15, 15, 0.1), 0 9px 24px rgba(15, 15, 15, 0.2)",
1014
+ font: "14px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
1015
+ },
1016
+ ".cm-table-menu-item": {
1017
+ display: "flex",
1018
+ alignItems: "center",
1019
+ gap: "10px",
1020
+ width: "100%",
1021
+ boxSizing: "border-box",
1022
+ padding: "6px 8px",
1023
+ border: "none",
1024
+ borderRadius: "6px",
1025
+ background: "none",
1026
+ color: "inherit",
1027
+ font: "inherit",
1028
+ textAlign: "left",
1029
+ cursor: "pointer",
1030
+ },
1031
+ ".cm-table-menu-item:hover": { background: "var(--cm-table-menu-hover)" },
1032
+ ".cm-table-menu-label": { flex: "1" },
1033
+ ".cm-table-menu-search": {
1034
+ boxSizing: "border-box",
1035
+ width: "100%",
1036
+ margin: "0 0 4px",
1037
+ padding: "5px 8px",
1038
+ border: "1px solid var(--cm-table-menu-border)",
1039
+ borderRadius: "6px",
1040
+ outline: "none",
1041
+ background: "var(--cm-table-menu-input)",
1042
+ color: "inherit",
1043
+ font: "inherit",
1044
+ },
1045
+ ".cm-table-menu-search:focus": { borderColor: "var(--cm-table-select)", boxShadow: "0 0 0 2px var(--cm-table-select-soft)" },
1046
+ ".cm-table-menu-list": { maxHeight: "min(60vh, 420px)", overflowY: "auto" },
1047
+ ".cm-table-menu-section": { padding: "6px 8px 2px", fontSize: "12px", opacity: "0.6" },
1048
+ ".cm-table-menu-empty": { padding: "8px", opacity: "0.6" },
1049
+ ".cm-table-menu-active": { background: "var(--cm-table-menu-hover)" },
1050
+ ".cm-table-swatch": {
1051
+ display: "inline-flex",
1052
+ alignItems: "center",
1053
+ justifyContent: "center",
1054
+ width: "18px",
1055
+ height: "18px",
1056
+ boxSizing: "border-box",
1057
+ border: "1px solid var(--cm-table-menu-border)",
1058
+ borderRadius: "4px",
1059
+ fontWeight: "600",
1060
+ fontSize: "12px",
1061
+ },
1062
+ ".cm-table-drop": {
1063
+ position: "absolute",
1064
+ display: "none",
1065
+ background: "var(--cm-table-select)",
1066
+ borderRadius: "1px",
1067
+ pointerEvents: "none",
1068
+ },
1069
+ ".cm-table-drop.cm-table-drop-visible": { display: "block" },
1070
+ "&.cm-table-dragging, &.cm-table-dragging *": { cursor: "grabbing !important" },
1071
+ ".cm-table-menu-separator": { height: "1px", margin: "4px 2px", background: "var(--cm-table-menu-hover)" },
1072
+ ".cm-table-menu-align": { cursor: "default" },
1073
+ ".cm-table-menu-align:hover": { background: "none" },
1074
+ ".cm-table-segment": {
1075
+ display: "inline-flex",
1076
+ padding: "2px",
1077
+ gap: "2px",
1078
+ borderRadius: "6px",
1079
+ background: "var(--cm-table-switch-off)",
1080
+ },
1081
+ ".cm-table-segment-button": {
1082
+ display: "inline-flex",
1083
+ alignItems: "center",
1084
+ justifyContent: "center",
1085
+ width: "26px",
1086
+ height: "20px",
1087
+ padding: "0",
1088
+ border: "none",
1089
+ borderRadius: "4px",
1090
+ background: "none",
1091
+ color: "inherit",
1092
+ cursor: "pointer",
1093
+ opacity: "0.65",
1094
+ },
1095
+ ".cm-table-segment-button:hover": { opacity: "1" },
1096
+ ".cm-table-segment-on": {
1097
+ background: "var(--cm-table-menu-bg)",
1098
+ opacity: "1",
1099
+ boxShadow: "0 1px 2px rgba(0, 0, 0, 0.15)",
1100
+ },
1101
+ ".cm-table-switch": {
1102
+ position: "relative",
1103
+ width: "28px",
1104
+ height: "16px",
1105
+ borderRadius: "8px",
1106
+ background: "var(--cm-table-switch-off)",
1107
+ transition: "background 150ms ease",
1108
+ },
1109
+ ".cm-table-switch::after": {
1110
+ content: '""',
1111
+ position: "absolute",
1112
+ top: "2px",
1113
+ left: "2px",
1114
+ width: "12px",
1115
+ height: "12px",
1116
+ borderRadius: "50%",
1117
+ background: "#fff",
1118
+ transition: "transform 150ms ease",
1119
+ },
1120
+ ".cm-table-switch-on": { background: "var(--cm-table-select)" },
1121
+ ".cm-table-switch-on::after": { transform: "translateX(12px)" },
1122
+ "@media (prefers-reduced-motion: reduce)": {
1123
+ ".cm-table-switch, .cm-table-switch::after": { transition: "none" },
1124
+ },
1125
+ });