fresh-web-editor 0.0.0-stage → 0.1.4

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.
package/README.md CHANGED
@@ -1,3 +1,158 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # Fresh Web Editor
2
+
3
+ [English](https://github.com/Kor-Fresh/fresh-web-editor/blob/main/README.md) · [한국어](https://github.com/Kor-Fresh/fresh-web-editor/blob/main/docs/README.ko.md) · [简体中文](https://github.com/Kor-Fresh/fresh-web-editor/blob/main/docs/README.zh-CN.md)
4
+
5
+ Fresh Web Editor is a rich text editor with a Korean interface for React, Vue 3, and plain JavaScript. For a standalone preview, open `index.html` from the repository root in a browser.
6
+
7
+ ![Fresh Web Editor with its Korean formatting toolbar and a sample meeting document](https://raw.githubusercontent.com/Kor-Fresh/fresh-web-editor/main/docs/images/editor-preview.png)
8
+
9
+ ## Editing tools
10
+
11
+ Select text to change its formatting.
12
+
13
+ ![Select text to change its formatting.](https://raw.githubusercontent.com/Kor-Fresh/fresh-web-editor/main/docs/images/text-quick-toolbar.png)
14
+
15
+ Select an inserted image to align, resize, or delete it.
16
+
17
+ ![Select an inserted image to align, resize, or delete it.](https://raw.githubusercontent.com/Kor-Fresh/fresh-web-editor/main/docs/images/image-quick-toolbar.png)
18
+
19
+ Use the + on the left to insert a row and the + at the top to insert a column.
20
+
21
+ ![Use the + on the left to insert a row and the + at the top to insert a column.](https://raw.githubusercontent.com/Kor-Fresh/fresh-web-editor/main/docs/images/table-insertion.gif)
22
+
23
+ Select cells to open the table tools for merging, splitting, and adjusting widths.
24
+
25
+ ![Select cells to open the table tools for merging, splitting, and adjusting widths.](https://raw.githubusercontent.com/Kor-Fresh/fresh-web-editor/main/docs/images/cell-quick-toolbar.png)
26
+
27
+ ## Run an example
28
+
29
+ With Node.js 22 and npm installed, clone the repository.
30
+
31
+ ```sh
32
+ git clone https://github.com/Kor-Fresh/fresh-web-editor.git
33
+ cd fresh-web-editor
34
+ ```
35
+
36
+ Start either example from the repository root. Each app builds the local editor package when its development server starts.
37
+
38
+ ### React
39
+
40
+ ```sh
41
+ cd examples/react
42
+ npm install
43
+ npm run dev
44
+ ```
45
+
46
+ ### Vue 3
47
+
48
+ ```sh
49
+ cd examples/vue
50
+ npm install
51
+ npm run dev
52
+ ```
53
+
54
+ Open the local URL printed in the terminal, edit the document, and click **저장하기** (Save). The **저장한 HTML** (Saved HTML) section shows the markup as it was when you clicked. To run both apps at once, use separate terminals.
55
+
56
+ ## Install in an existing project
57
+
58
+ The components support React 18 or 19 and Vue 3.3 or later in the 3.x series.
59
+
60
+ ```sh
61
+ npm install fresh-web-editor
62
+ ```
63
+
64
+ ## React integration
65
+
66
+ Save the following component as `src/DocumentForm.jsx`. The editor passes the current HTML to `onChange` after each edit. The Save button copies that value into `savedHtml`. [React example source](https://github.com/Kor-Fresh/fresh-web-editor/blob/main/examples/react/DocumentForm.jsx)
67
+
68
+ ```jsx
69
+ import { useState } from 'react';
70
+ import { Editor } from 'fresh-web-editor/react';
71
+
72
+ export default function DocumentForm() {
73
+ const [html, setHtml] = useState('<p>문서를 편집해 보세요.</p>');
74
+ const [savedHtml, setSavedHtml] = useState(null);
75
+
76
+ function saveDocument() {
77
+ setSavedHtml(html);
78
+ }
79
+
80
+ return (
81
+ <section>
82
+ <Editor value={html} onChange={setHtml} />
83
+ <button type="button" onClick={saveDocument}>저장하기</button>
84
+ <h2>저장한 HTML</h2>
85
+ <pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}><code>{savedHtml ?? '저장하면 HTML 코드가 표시됩니다.'}</code></pre>
86
+ </section>
87
+ );
88
+ }
89
+ ```
90
+
91
+ Render the form in `src/App.jsx`.
92
+
93
+ ```jsx
94
+ import DocumentForm from './DocumentForm.jsx';
95
+
96
+ export default function App() {
97
+ return <DocumentForm />;
98
+ }
99
+ ```
100
+
101
+ ## Vue 3 integration
102
+
103
+ Save the following component as `src/DocumentForm.vue`. The editor updates the HTML through `v-model`. The Save button’s `@click` handler copies it into `savedHtml`. [Vue example source](https://github.com/Kor-Fresh/fresh-web-editor/blob/main/examples/vue/DocumentForm.vue)
104
+
105
+ ```vue
106
+ <script setup>
107
+ import { ref } from 'vue';
108
+ import { Editor } from 'fresh-web-editor/vue';
109
+
110
+ const html = ref('<p>문서를 편집해 보세요.</p>');
111
+ const savedHtml = ref(null);
112
+
113
+ function saveDocument() {
114
+ savedHtml.value = html.value;
115
+ }
116
+ </script>
117
+
118
+ <template>
119
+ <section>
120
+ <Editor v-model="html" />
121
+ <button type="button" @click="saveDocument">저장하기</button>
122
+ <h2>저장한 HTML</h2>
123
+ <pre style="white-space: pre-wrap; overflow-wrap: anywhere"><code>{{ savedHtml ?? '저장하면 HTML 코드가 표시됩니다.' }}</code></pre>
124
+ </section>
125
+ </template>
126
+ ```
127
+
128
+ Render the form in `src/App.vue`.
129
+
130
+ ```vue
131
+ <script setup>
132
+ import DocumentForm from './DocumentForm.vue';
133
+ </script>
134
+
135
+ <template>
136
+ <DocumentForm />
137
+ </template>
138
+ ```
139
+
140
+ ## Check the saved HTML
141
+
142
+ Start your app’s development server (`npm run dev` in a standard Vite project). Click **저장하기** with the initial document to see `<p>문서를 편집해 보세요.</p>` below the button. Edit the text again. The output keeps its previous value until you click Save again.
143
+
144
+ Both examples keep the saved HTML in component state. To persist it on a server, send the HTML string to your app’s save endpoint from `saveDocument`. The host app also handles attachment uploads. For browser drafts, supply a `draftKey` unique to the user and document.
145
+
146
+ In the standalone [preview](index.html), **문서 저장** at the top downloads an HTML file. **저장하기** below the editor displays the code on screen. The embedded editor uses an iframe, so test it against your production content security policy if inline scripts or styles are restricted.
147
+
148
+ ## Editor features
149
+
150
+ | Area | Features |
151
+ | --- | --- |
152
+ | Documents | Create documents, open HTML or text, save HTML, save and restore browser drafts, preview, and print on A4 paper |
153
+ | Editing | Undo and redo, find and replace, paragraphs and headings, fonts, sizes, colors, highlights, superscript and subscript, lists, indentation, alignment, line spacing, and text direction |
154
+ | Insertion | Links, automatic links, anchors, images, media URLs, dates and times, symbols and emoji, collapsible sections, code blocks, horizontal rules, and page breaks |
155
+ | Tables | Insert via a grid or row and column counts, add or delete rows and columns, merge or split cells, navigate with Tab, and insert a purchase details table |
156
+ | Editing aids | Contextual tools for selections and tables, paragraph boundaries, hidden characters, character and word counts, and HTML source |
157
+
158
+ Importing external CSS classes, advanced list numbering, and automatic embedding of third-party videos have limited support. Find operates on contiguous runs of text. Before a production rollout, test deletion and undo during Korean IME composition, pasting from Hancom Hangul and Excel, mobile text selection, large tables, and multi-page printing.
@@ -0,0 +1,4 @@
1
+ import type { HTMLAttributes, ReactElement } from 'react';
2
+ import type { EditorOptions } from '../index.js';
3
+ export declare function Editor(props: EditorOptions & Omit<HTMLAttributes<HTMLDivElement>, 'onChange'>): ReactElement;
4
+ export default Editor;
@@ -0,0 +1,28 @@
1
+ import { createElement, useEffect, useRef } from 'react';
2
+ import { mountEditor } from '../core.js';
3
+
4
+ export function Editor({ value = '', onChange, draftKey, label, ...props }) {
5
+ const host = useRef(null);
6
+ const editor = useRef(null);
7
+ const latest = useRef({ value, onChange });
8
+ useEffect(() => {
9
+ latest.current = { value, onChange };
10
+ }, [value, onChange]);
11
+ useEffect(() => {
12
+ editor.current = mountEditor(host.current, {
13
+ value: latest.current.value,
14
+ draftKey,
15
+ label,
16
+ onChange: (html) => latest.current.onChange?.(html),
17
+ });
18
+ return () => {
19
+ editor.current.destroy();
20
+ editor.current = null;
21
+ };
22
+ }, [draftKey, label]);
23
+ useEffect(() => {
24
+ editor.current?.setHTML(value);
25
+ }, [value]);
26
+ return createElement('div', { ...props, ref: host });
27
+ }
28
+ export default Editor;
@@ -0,0 +1,8 @@
1
+ import type { DefineComponent } from 'vue';
2
+ export declare const Editor: DefineComponent<{
3
+ modelValue?: string;
4
+ draftKey?: string;
5
+ label?: string;
6
+ 'onUpdate:modelValue'?: (value: string) => void;
7
+ }>;
8
+ export default Editor;
@@ -0,0 +1,30 @@
1
+ import { defineComponent, h, onMounted, onBeforeUnmount, ref, watch } from 'vue';
2
+ import { mountEditor } from '../core.js';
3
+
4
+ export const Editor = defineComponent({
5
+ name: 'Editor',
6
+ props: { modelValue: { type: String, default: '' }, draftKey: String, label: String },
7
+ emits: ['update:modelValue'],
8
+ setup(props, { emit }) {
9
+ const host = ref(null);
10
+ let editor;
11
+ function mount() {
12
+ editor?.destroy();
13
+ editor = mountEditor(host.value, {
14
+ value: props.modelValue,
15
+ label: props.label,
16
+ draftKey: props.draftKey,
17
+ onChange: (html) => emit('update:modelValue', html),
18
+ });
19
+ }
20
+ onMounted(mount);
21
+ watch(() => [props.label, props.draftKey], mount, { flush: 'post' });
22
+ watch(
23
+ () => props.modelValue,
24
+ (html) => editor?.setHTML(html),
25
+ );
26
+ onBeforeUnmount(() => editor?.destroy());
27
+ return () => h('div', { ref: host });
28
+ },
29
+ });
30
+ export default Editor;
package/core.js ADDED
@@ -0,0 +1,39 @@
1
+ import editorDocument from './dist/document.js';
2
+
3
+ export function mountEditor(container, { value = '', onChange, draftKey, label = '문서 편집기' } = {}) {
4
+ const frame = container.ownerDocument.createElement('iframe');
5
+ frame.title = label;
6
+ frame.setAttribute('allowfullscreen', '');
7
+ frame.style.cssText = 'display:block;width:100%;height:100%;min-height:24rem;border:0';
8
+ if (draftKey) frame.dataset.draftKey = draftKey;
9
+ let current = value;
10
+ let runtime;
11
+ function changed(event) {
12
+ current = event.detail;
13
+ onChange?.(current);
14
+ }
15
+ function ready() {
16
+ runtime = frame.contentWindow.koreanEditor;
17
+ if (!runtime) return;
18
+ runtime.setHTML(current);
19
+ frame.contentDocument.addEventListener('editor-change', changed);
20
+ }
21
+ frame.addEventListener('load', ready);
22
+ frame.srcdoc = editorDocument;
23
+ container.append(frame);
24
+ return {
25
+ getHTML: () => runtime?.getHTML() ?? current,
26
+ setHTML(html) {
27
+ if (current === html) return;
28
+ current = html;
29
+ runtime?.setHTML(html);
30
+ },
31
+ destroy() {
32
+ frame.removeEventListener('load', ready);
33
+ frame.contentDocument?.removeEventListener('editor-change', changed);
34
+ runtime?.flush();
35
+ frame.remove();
36
+ runtime = undefined;
37
+ },
38
+ };
39
+ }
@@ -0,0 +1 @@
1
+ export default "<!doctype html>\r\n<html lang=\"ko\">\r\n\t<meta charset=\"utf-8\" /><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\r\n\t<title>Fresh Web Editor</title>\r\n\t<style>* {\r\n\tbox-sizing: border-box;\r\n}\r\nbody {\r\n\tmargin: 0;\r\n\tbackground: #f2f5f7;\r\n\tcolor: #192d40;\r\n\tfont:\r\n\t\t15px/1.6 system-ui,\r\n\t\t'Malgun Gothic',\r\n\t\tsans-serif;\r\n}\r\nmain {\r\n\tmax-width: 1180px;\r\n\tmargin: auto;\r\n\tpadding: 30px clamp(12px, 4vw, 54px);\r\n}\r\nheader,\r\nfooter,\r\nnav,\r\n.tools,\r\n.actions {\r\n\tdisplay: flex;\r\n\talign-items: center;\r\n\tgap: 6px;\r\n\tflex-wrap: wrap;\r\n}\r\nheader,\r\nfooter {\r\n\tjustify-content: space-between;\r\n}\r\nheader {\r\n\tmargin-bottom: 20px;\r\n}\r\nheader p {\r\n\tmargin: 0;\r\n\tcolor: #536b78;\r\n\tfont-size: 13px;\r\n}\r\nh1 {\r\n\tmargin: 0;\r\n\tfont-size: clamp(22px, 4vw, 30px);\r\n}\r\nbutton,\r\nselect,\r\ninput,\r\ntextarea {\r\n\tfont: inherit;\r\n}\r\nbutton,\r\nselect {\r\n\tborder: 1px solid transparent;\r\n\tbackground: transparent;\r\n\tcolor: inherit;\r\n\tcursor: pointer;\r\n\tborder-radius: 5px;\r\n\tpadding: 5px 10px;\r\n}\r\nbutton:hover,\r\nsummary:hover,\r\nbutton[aria-pressed='true'] {\r\n\tbackground: #e0eff0;\r\n}\r\nbutton:focus-visible,\r\nselect:focus-visible,\r\nsummary:focus-visible {\r\n\toutline: 2px solid #057872;\r\n}\r\n#download,\r\n#accept {\r\n\tbackground: #066660;\r\n\tcolor: white;\r\n\tpadding: 8px 16px;\r\n}\r\n.frame {\r\n\tbackground: white;\r\n\tborder: 1px solid #cbd7dc;\r\n\tborder-radius: 10px;\r\n\tbox-shadow: 0 5px 24px #2447590a;\r\n}\r\nnav,\r\n.tools,\r\nfooter {\r\n\tpadding: 8px 12px;\r\n\tborder-bottom: 1px solid #dbe3e6;\r\n}\r\nnav {\r\n\tgap: 2px;\r\n}\r\ndetails.menu {\r\n\tposition: relative;\r\n}\r\nsummary {\r\n\tcursor: pointer;\r\n\tlist-style: none;\r\n\tpadding: 4px 9px;\r\n\tborder-radius: 5px;\r\n}\r\nsummary::-webkit-details-marker {\r\n\tdisplay: none;\r\n}\r\n.menu > div {\r\n\tposition: absolute;\r\n\tz-index: 4;\r\n\ttop: 100%;\r\n\tleft: 0;\r\n\tbackground: white;\r\n\tpadding: 5px;\r\n\tborder: 1px solid #cbd7dc;\r\n\tborder-radius: 7px;\r\n\tbox-shadow: 0 4px 18px #203a4524;\r\n\tmin-width: 145px;\r\n}\r\n.menu button {\r\n\tdisplay: block;\r\n\twidth: 100%;\r\n\ttext-align: left;\r\n\twhite-space: nowrap;\r\n}\r\n.tools {\r\n\tbackground: #f7fafb;\r\n}\r\n.tools select,\r\n.tools button {\r\n\tbackground: white;\r\n\tborder-color: #d6dfe3;\r\n}\r\n#context {\r\n\tbackground: #eaf6f4;\r\n}\r\n.sheet {\r\n\tpadding: 24px;\r\n\tbackground: #eaf0f2;\r\n}\r\n.document {\r\n\tbackground: white;\r\n\tmargin: auto;\r\n\t--document-padding: clamp(16px, 4vw, 48px);\r\n\tpadding: var(--document-padding);\r\n\tmin-height: 50vh;\r\n\tmax-width: 850px;\r\n\toutline: none;\r\n\toverflow-wrap: anywhere;\r\n\tcolor: #1e293b;\r\n}\r\n.document p {\r\n\tmargin: 0 0 0.65em;\r\n}\r\n.document table {\r\n\tborder-collapse: collapse;\r\n\twidth: 100%;\r\n\ttable-layout: fixed;\r\n}\r\n.document td,\r\n.document th {\r\n\tborder: 1px solid #95a7b4;\r\n\tpadding: 6px;\r\n\tmin-width: 2em;\r\n\tvertical-align: middle;\r\n}\r\n.document th {\r\n\tbackground: #eaf2f5;\r\n}\r\n.document img,\r\n.document video {\r\n\tmax-width: 100%;\r\n\theight: auto;\r\n}\r\n.document pre {\r\n\twhite-space: pre-wrap;\r\n\tbackground: #f0f4f5;\r\n\tpadding: 12px;\r\n}\r\n.document blockquote {\r\n\tmargin-left: 0;\r\n\tpadding-left: 14px;\r\n\tborder-left: 3px solid #53918d;\r\n}\r\n.document .pagebreak {\r\n\tborder: 0;\r\n\tborder-top: 2px dashed #9daeb7;\r\n\tbreak-after: page;\r\n}\r\n.blocks :is(p, div, h1, h2, h3, blockquote, pre) {\r\n\toutline: 1px dashed #b7c6ce;\r\n}\r\n.chars {\r\n\twhite-space: pre-wrap;\r\n}\r\n.chars br::after {\r\n\tcontent: '↵';\r\n\tcolor: #738b90;\r\n}\r\n.selected {\r\n\toutline: 2px solid #147970 !important;\r\n\toutline-offset: -2px;\r\n}\r\nfooter {\r\n\tborder: 0;\r\n\tcolor: #536b78;\r\n\tfont-size: 13px;\r\n}\r\ndialog {\r\n\tmax-width: min(92vw, 860px);\r\n\twidth: 440px;\r\n\tmax-height: 88vh;\r\n\tborder: 1px solid #bbcdd2;\r\n\tborder-radius: 12px;\r\n\tpadding: 22px;\r\n\tcolor: inherit;\r\n}\r\ndialog::backdrop {\r\n\tbackground: #172d4059;\r\n}\r\ndialog h2 {\r\n\tfont-size: 20px;\r\n\tmargin: 0 0 12px;\r\n}\r\ndialog label {\r\n\tdisplay: block;\r\n\tmargin-bottom: 10px;\r\n}\r\ndialog input,\r\ndialog select,\r\ndialog textarea {\r\n\tdisplay: block;\r\n\twidth: 100%;\r\n\tborder: 1px solid #aabcc5;\r\n\tborder-radius: 5px;\r\n\tpadding: 7px;\r\n}\r\n.actions {\r\n\tmargin-top: 16px;\r\n\tjustify-content: flex-end;\r\n}\r\n#fields textarea {\r\n\theight: 180px;\r\n}\r\n.grid {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: repeat(8, 24px);\r\n\tgap: 3px;\r\n\tmargin: 10px 0;\r\n}\r\n.grid button {\r\n\tborder: 1px solid #a8bdc4;\r\n\theight: 22px;\r\n\tpadding: 0;\r\n}\r\n.grid .on {\r\n\tbackground: #5cb7aa;\r\n}\r\ndialog.preview {\r\n\twidth: 850px;\r\n}\r\nbody.expanded main {\r\n\tmax-width: none;\r\n\tpadding: 8px;\r\n}\r\n[hidden] {\r\n\tdisplay: none !important;\r\n}\r\n@media (max-width: 650px) {\r\n\tmain {\r\n\t\tpadding: 12px 6px;\r\n\t}\r\n\t.sheet {\r\n\t\tpadding: 4px;\r\n\t}\r\n\t.menu:nth-last-child(-n + 3) > div {\r\n\t\tleft: auto;\r\n\t\tright: 0;\r\n\t}\r\n}\r\n@media print {\r\n\t@page {\r\n\t\tsize: A4;\r\n\t\tmargin: 18mm;\r\n\t}\r\n\tbody,\r\n\tmain,\r\n\t.frame,\r\n\t.sheet,\r\n\t.document {\r\n\t\tmargin: 0 !important;\r\n\t\tpadding: 0 !important;\r\n\t\tborder: none;\r\n\t\tbox-shadow: none;\r\n\t\tbackground: white;\r\n\t\tmax-width: none;\r\n\t\tmin-height: 0;\r\n\t}\r\n\tmain > header,\r\n\tnav,\r\n\t.tools,\r\n\tfooter,\r\n\tdialog {\r\n\t\tdisplay: none !important;\r\n\t}\r\n\t.document tr {\r\n\t\tbreak-inside: avoid;\r\n\t}\r\n\t.document .pagebreak {\r\n\t\tvisibility: hidden;\r\n\t}\r\n\t.selected,\r\n\t.blocks * {\r\n\t\toutline: none !important;\r\n\t}\r\n}\r\n.menu > div {\r\n\tmax-height: min(64vh, 440px);\r\n\toverflow: auto;\r\n}\r\n.embedded main {\r\n\tmax-width: none;\r\n\tpadding: 0;\r\n}\r\n.embedded main > header {\r\n\tdisplay: none;\r\n}\r\n#insert-tools {\r\n\tdisplay: flex;\r\n\talign-items: center;\r\n\tgap: 3px;\r\n\tpadding: 6px 10px;\r\n\toverflow-x: auto;\r\n\tbackground: white;\r\n\tborder-radius: 10px 10px 0 0;\r\n\tborder-bottom: 1px solid #e3e8ec;\r\n}\r\n.insert-tool,\r\n.format-tool {\r\n\tdisplay: inline-flex;\r\n\talign-items: center;\r\n\tjustify-content: center;\r\n\tflex-shrink: 0;\r\n\tcolor: #354650;\r\n}\r\n.insert-tool {\r\n\tflex-direction: column;\r\n\tgap: 4px;\r\n\tmin-width: 57px;\r\n\tpadding: 6px 8px;\r\n\tfont-size: 12px;\r\n\tline-height: 1.35;\r\n}\r\n.insert-tool svg,\r\n.format-tool svg {\r\n\twidth: 21px;\r\n\theight: 21px;\r\n\tfill: none;\r\n\tstroke: currentColor;\r\n\tstroke-width: 1.5;\r\n\tstroke-linecap: round;\r\n\tstroke-linejoin: round;\r\n}\r\n.insert-tool:last-child svg {\r\n\tstroke-width: 3.5;\r\n}\r\n#tools {\r\n\tgap: 3px;\r\n\tbackground: white;\r\n}\r\n#tools select {\r\n\tfont-size: 13px;\r\n\tborder: 0;\r\n\tpadding: 4px;\r\n\theight: 32px;\r\n}\r\n.format-group {\r\n\tdisplay: inline-flex;\r\n\talign-items: center;\r\n\tpadding-inline: 5px;\r\n\tborder-inline-start: 1px solid #d9e0e3;\r\n}\r\n#tools .format-tool {\r\n\tbackground: transparent;\r\n\tborder: 0;\r\n\twidth: 31px;\r\n\theight: 32px;\r\n\tpadding: 6px;\r\n}\r\n.format-tool svg {\r\n\twidth: 17px;\r\n\theight: 17px;\r\n\tstroke-width: 1.8;\r\n}\r\n#tools .format-tool:hover,\r\n.insert-tool:hover {\r\n\tbackground: #ecf4f3;\r\n\tcolor: #065c55;\r\n}\r\n.command-list {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: repeat(auto-fit, minmax(100px, 1fr));\r\n\tgap: 4px;\r\n\tmargin-top: 12px;\r\n\tmax-height: 52vh;\r\n\toverflow: auto;\r\n}\r\n.command-list button {\r\n\ttext-align: left;\r\n\tbackground: #f3f6f7;\r\n}\r\n@media (max-width: 650px) {\r\n\t#tools {\r\n\t\tflex-wrap: nowrap;\r\n\t\toverflow-x: auto;\r\n\t}\r\n\t#tools select {\r\n\t\tflex-shrink: 0;\r\n\t}\r\n\t.insert-tool {\r\n\t\tmin-width: 51px;\r\n\t}\r\n}\r\n@media print {\r\n\t#insert-tools {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n.document.cell-selecting {\r\n\tuser-select: none;\r\n}\r\n.document :is(td, th).selected {\r\n\tbackground-color: #d4eafc;\r\n\tbox-shadow: inset 0 0 0 1px #4d92c8;\r\n}\r\n.grid {\r\n\ttouch-action: none;\r\n}\r\n.sheet {\r\n\tposition: relative;\r\n}\r\n.table-overlay {\r\n\tposition: absolute;\r\n\tz-index: 2;\r\n\twidth: 0;\r\n\theight: 0;\r\n\tpointer-events: none;\r\n}\r\n.table-overlay button,\r\n.cell-menu {\r\n\tpointer-events: auto;\r\n}\r\n.table-rail,\r\n.table-plus,\r\n.cell-menu {\r\n\tposition: absolute;\r\n}\r\n.table-rail {\r\n\tborder: 0;\r\n\tborder-radius: 0;\r\n\tbackground: #e5e9e7;\r\n\tpadding: 0;\r\n}\r\n.table-rail.row {\r\n\tleft: -10px;\r\n\twidth: 10px;\r\n}\r\n.table-rail.column {\r\n\ttop: -10px;\r\n\theight: 10px;\r\n}\r\n.table-rail.active,\r\n.table-rail:hover {\r\n\tbackground: #a8eac0;\r\n}\r\n.table-plus {\r\n\tborder: 1px solid #bac8be;\r\n\tbackground: white;\r\n\tborder-radius: 50%;\r\n\theight: 12px;\r\n\twidth: 12px;\r\n\tline-height: 10px;\r\n\tfont-size: 11px;\r\n\tcolor: #4b7059;\r\n\tpadding: 0;\r\n\tz-index: 1;\r\n\ttransform: translate(-50%, -50%);\r\n}\r\n.table-plus.row {\r\n\tleft: -5px;\r\n}\r\n.table-plus.column {\r\n\ttop: -5px;\r\n}\r\n.table-plus:hover,\r\n.table-plus:focus-visible {\r\n\tcolor: #08753a;\r\n\tborder-color: #198746;\r\n\ttransform: translate(-50%, -50%) scale(1.35);\r\n}\r\n.cell-menu {\r\n\tdisplay: grid;\r\n\tmin-width: 104px;\r\n\tpadding: 3px;\r\n\tbackground: white;\r\n\tborder: 1px solid #d2dcd5;\r\n\tbox-shadow: 0 3px 9px #14291d1c;\r\n\tborder-radius: 3px;\r\n}\r\n.cell-menu .insert-tool {\r\n\tflex-direction: row;\r\n\tjustify-content: flex-start;\r\n\twhite-space: nowrap;\r\n\tgap: 7px;\r\n\tfont-size: 12px;\r\n\tpadding: 5px 8px;\r\n}\r\n.cell-menu svg {\r\n\twidth: 15px;\r\n\theight: 15px;\r\n}\r\n.table-group {\r\n\tborder-color: #b5cdbe;\r\n}\r\n.table-group button:disabled,\r\n.cell-menu button:disabled {\r\n\topacity: 0.38;\r\n\tcursor: default;\r\n}\r\n.document :is(td, th).selected {\r\n\tbackground-color: #daf5e3;\r\n\toutline: 1px solid #8bcda3 !important;\r\n\tbox-shadow: none;\r\n}\r\n@media print {\r\n\t.table-overlay {\r\n\t\tdisplay: none;\r\n\t}\r\n\t.document :is(td, th).selected {\r\n\t\tbackground: revert;\r\n\t\toutline: none !important;\r\n\t}\r\n}\r\n.editor-context-menu,\r\n.text-quick {\r\n\tposition: fixed;\r\n\tz-index: 8;\r\n\tbackground: white;\r\n\tborder: 1px solid #cfd7d7;\r\n\tborder-radius: 5px;\r\n\tbox-shadow: 0 3px 14px #172c3d26;\r\n}\r\n.editor-context-menu {\r\n\tpadding: 4px;\r\n\tmin-width: 134px;\r\n\tmax-height: 90vh;\r\n\toverflow: auto;\r\n}\r\n.editor-context-menu button {\r\n\tdisplay: block;\r\n\twidth: 100%;\r\n\ttext-align: left;\r\n\tfont-size: 13px;\r\n}\r\n.editor-context-menu button:disabled {\r\n\topacity: 0.4;\r\n}\r\n.editor-context-menu hr {\r\n\tborder: 0;\r\n\tborder-top: 1px solid #e1e6e8;\r\n}\r\n#context.text-quick {\r\n\tbackground: #fff;\r\n\tgap: 2px;\r\n\tpadding: 3px 5px;\r\n\tmax-width: calc(100vw - 8px);\r\n\tflex-wrap: wrap;\r\n}\r\n.text-quick select,\r\n.text-quick .format-tool {\r\n\tborder: 0;\r\n\tbackground: transparent;\r\n\tfont-size: 12px;\r\n\tpadding: 3px;\r\n\tmin-height: 28px;\r\n}\r\n.text-quick .format-tool {\r\n\twidth: 27px;\r\n}\r\n.text-quick .format-tool[aria-pressed='true'] {\r\n\tcolor: #087946;\r\n\tbackground: #e6f6ea;\r\n}\r\n@media print {\r\n\t.editor-context-menu,\r\n\t#context.text-quick {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n.document figure {\r\n\tmargin: 8px 0;\r\n}\r\n.document figcaption {\r\n\tfont-size: 13px;\r\n\tcolor: #52636a;\r\n\ttext-align: center;\r\n}\r\n.picture-frame {\r\n\tposition: fixed;\r\n\tpointer-events: none;\r\n\toutline: 2px solid #20bb67;\r\n\tz-index: 4;\r\n}\r\n.picture-frame button,\r\n.picture-grip {\r\n\tpointer-events: auto;\r\n}\r\n.picture-bar {\r\n\tposition: absolute;\r\n\tdisplay: flex;\r\n\tgap: 2px;\r\n\twhite-space: nowrap;\r\n\tbackground: white;\r\n\tpadding: 3px;\r\n\tborder: 1px solid #ced9d3;\r\n\tborder-radius: 5px;\r\n\tbox-shadow: 0 2px 8px #192b2424;\r\n}\r\n.picture-bar button {\r\n\twidth: 31px;\r\n\theight: 28px;\r\n\tpadding: 5px;\r\n}\r\n.picture-grip {\r\n\tposition: absolute;\r\n\twidth: 10px;\r\n\theight: 10px;\r\n\tborder: 2px solid #22bb68;\r\n\tbackground: white;\r\n\ttouch-action: none;\r\n}\r\n.picture-grip.nw,\r\n.picture-grip.sw {\r\n\tleft: -5px;\r\n}\r\n.picture-grip.ne,\r\n.picture-grip.se {\r\n\tright: -5px;\r\n}\r\n.picture-grip.nw,\r\n.picture-grip.ne {\r\n\ttop: -5px;\r\n}\r\n.picture-grip.sw,\r\n.picture-grip.se {\r\n\tbottom: -5px;\r\n}\r\n.picture-grip.nw,\r\n.picture-grip.se {\r\n\tcursor: nwse-resize;\r\n}\r\n.picture-grip.ne,\r\n.picture-grip.sw {\r\n\tcursor: nesw-resize;\r\n}\r\n@media print {\r\n\t.picture-frame {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n\r\n.dialog-heading {\r\n\tdisplay: flex;\r\n\talign-items: center;\r\n\tjustify-content: space-between;\r\n\tposition: sticky;\r\n\ttop: -22px;\r\n\tbackground: white;\r\n\tpadding: 5px 0;\r\n\tz-index: 1;\r\n}\r\n.dialog-heading h2 {\r\n\tmargin: 0;\r\n}\r\n#dialog-close {\r\n\tdisplay: grid;\r\n\tplace-items: center;\r\n\twidth: 36px;\r\n\theight: 36px;\r\n\tpadding: 7px;\r\n}\r\n#dialog-close svg {\r\n\twidth: 20px;\r\n\theight: 20px;\r\n\tstroke: currentColor;\r\n\tstroke-width: 1.7;\r\n\tstroke-linecap: round;\r\n\tfill: none;\r\n}\r\n.actions:has(#accept[hidden]) {\r\n\tdisplay: none;\r\n}\r\n@media (hover: hover) and (prefers-reduced-motion: no-preference) {\r\n\t:is(.insert-tool, .format-tool) svg {\r\n\t\ttransition: transform 160ms cubic-bezier(0.2, 0.8, 0.2, 1.3);\r\n\t}\r\n\t:is(.insert-tool, .format-tool):not(:disabled):hover svg {\r\n\t\ttransform: scale(1.14);\r\n\t}\r\n\t#dialog-close:hover svg {\r\n\t\tanimation: preview-close-turn 420ms ease-out;\r\n\t}\r\n}\r\n@keyframes preview-close-turn {\r\n\tto {\r\n\t\ttransform: rotate(360deg);\r\n\t}\r\n}\r\n.table-style-panel {\r\n\tposition: fixed;\r\n\tz-index: 8;\r\n\twidth: min(240px, 96vw);\r\n\tmax-height: 70vh;\r\n\toverflow: auto;\r\n\tpadding: 10px;\r\n\tbackground: white;\r\n\tborder: 1px solid #ced8db;\r\n\tborder-radius: 7px;\r\n\tbox-shadow: 0 4px 18px #233f4826;\r\n\tfont-size: 13px;\r\n}\r\n.table-style-panel strong,\r\n.table-style-panel > button,\r\n.table-style-panel > select {\r\n\tdisplay: block;\r\n\twidth: 100%;\r\n\ttext-align: left;\r\n}\r\n.table-style-panel strong {\r\n\tpadding: 4px 2px;\r\n}\r\n.table-style-panel label {\r\n\tdisplay: flex;\r\n\talign-items: center;\r\n\tjustify-content: space-between;\r\n\tmargin: 5px 0;\r\n}\r\n.table-style-panel button i {\r\n\tdisplay: inline-block;\r\n\twidth: 52px;\r\n\tmargin-inline-start: 12px;\r\n\tvertical-align: middle;\r\n}\r\n.swatches {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: repeat(8, 1fr);\r\n\tgap: 2px;\r\n}\r\n.swatches button {\r\n\tpadding: 0;\r\n\theight: 22px;\r\n\tborder: 1px solid #0002;\r\n\tborder-radius: 2px;\r\n}\r\n.table-presets {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: 1fr 1fr;\r\n\tgap: 3px;\r\n}\r\n.sample-grid {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: repeat(3, 1fr);\r\n\twidth: 52px;\r\n\tmargin: 3px auto;\r\n}\r\n.sample-grid i {\r\n\twidth: auto !important;\r\n\theight: 7px;\r\n\tborder: 1px solid #9ba8ae;\r\n\tmargin: 0 !important;\r\n}\r\n.sample-grid.lines i {\r\n\tborder-width: 0 0 1px;\r\n}\r\n.sample-grid.stripe i:nth-child(n + 4):nth-child(-n + 6) {\r\n\tbackground: #bdcbd0;\r\n}\r\n.sample-grid.dots i {\r\n\tborder-style: dotted;\r\n}\r\n.grid button,\r\n.grid button.on {\r\n\tposition: relative;\r\n\tborder: 0;\r\n\tbackground: transparent;\r\n}\r\n.grid button::before {\r\n\tcontent: '';\r\n\tposition: absolute;\r\n\tinset: 0;\r\n\tpointer-events: none;\r\n\tborder: 1px solid #a8bdc4;\r\n\tborder-radius: 4px;\r\n\tbackground: white;\r\n}\r\n.grid .on::before {\r\n\tbackground: #5cb7aa;\r\n}\r\n@media (prefers-reduced-motion: no-preference) {\r\n\t.grid .grid-tip::before {\r\n\t\tanimation: grid-bounce 230ms ease-out;\r\n\t}\r\n}\r\n@keyframes grid-bounce {\r\n\t35% {\r\n\t\ttransform: translateY(-2px) scale(1.12);\r\n\t}\r\n\t70% {\r\n\t\ttransform: scale(0.96);\r\n\t}\r\n}\r\n@media print {\r\n\t.table-style-panel {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n\r\n.document img[data-size='full'] {\r\n\tdisplay: block;\r\n\twidth: calc(100% + 2 * var(--document-padding)) !important;\r\n\tmax-width: none;\r\n\tmargin-inline: calc(-1 * var(--document-padding)) !important;\r\n}\r\n.document :is(td, th, li, blockquote) img[data-size='full'] {\r\n\twidth: 100% !important;\r\n\tmax-width: 100%;\r\n\tmargin-inline: 0 !important;\r\n}\r\n.picture-bar button[aria-pressed='true'] {\r\n\tcolor: #087946;\r\n\tbackground: #e6f6ea;\r\n}\r\n@media print {\r\n\t.document img[data-size='full'] {\r\n\t\twidth: 100% !important;\r\n\t\tmax-width: 100%;\r\n\t\tmargin-inline: 0 !important;\r\n\t}\r\n}\r\n.table-style-panel > .header-option {\r\n\tdisplay: flex;\r\n\talign-items: center;\r\n\tjustify-content: space-between;\r\n\tgap: 12px;\r\n}\r\n.header-sample {\r\n\tdisplay: grid;\r\n\tgrid-template-columns: repeat(3, 1fr);\r\n\twidth: 48px;\r\n\theight: 23px;\r\n\tpadding: 1px;\r\n\tgap: 1px;\r\n\tbackground: #99aab1;\r\n}\r\n.header-sample span {\r\n\tbackground: white;\r\n}\r\n.header-sample .is-header {\r\n\tbackground: #53978f;\r\n}\r\n.emoji-picker h3 {\r\n\tfont-size: 13px;\r\n\tcolor: #42635b;\r\n\tmargin: 12px 0 3px;\r\n}\r\n.emoji-picker button {\r\n\tfont-size: 20px;\r\n\tpadding: 4px 6px;\r\n}\r\n.image-drop-line {\r\n\tposition: fixed;\r\n\tpointer-events: none;\r\n\tz-index: 6;\r\n\theight: 3px;\r\n\ttransform: translateY(-50%);\r\n\tborder-radius: 2px;\r\n\tbackground: #147c70;\r\n\tbox-shadow: 0 0 0 1px white;\r\n}\r\n.image-drop-line::before,\r\n.image-drop-line::after {\r\n\tcontent: '';\r\n\tposition: absolute;\r\n\ttop: 50%;\r\n\twidth: 7px;\r\n\theight: 7px;\r\n\tborder-radius: 50%;\r\n\tbackground: inherit;\r\n\ttransform: translateY(-50%);\r\n}\r\n.image-drop-line::before {\r\n\tleft: 0;\r\n}\r\n.image-drop-line::after {\r\n\tright: 0;\r\n}\r\n@media print {\r\n\t.image-drop-line {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n#save-example {\r\n\tmargin-top: 1rem;\r\n}\r\n#save-example pre {\r\n\twhite-space: pre-wrap;\r\n\toverflow-wrap: anywhere;\r\n}\r\n@media print {\r\n\t#save-example {\r\n\t\tdisplay: none;\r\n\t}\r\n}\r\n</style>\r\n\t<main>\r\n\t\t<header>\r\n\t\t\t<div>\r\n\r\n\t\t\t\t<h1>Fresh Web Editor</h1>\r\n\t\t\t</div>\r\n\t\t\t<button id=\"download\">문서 저장</button>\r\n\t\t</header>\r\n\t\t<section class=\"frame\" aria-label=\"문서 편집\">\r\n\t\t\t<div id=\"insert-tools\" role=\"toolbar\" aria-label=\"삽입 및 문서 도구\"></div>\r\n\t\t\t<div id=\"tools\" class=\"tools\" role=\"toolbar\" aria-label=\"본문 서식\"></div>\r\n\t\t\t<div id=\"context\" class=\"tools\" hidden aria-label=\"빠른 편집\"></div>\r\n\t\t\t<div class=\"sheet\">\r\n\t\t\t\t<article\r\n\t\t\t\t\tid=\"body\"\r\n\t\t\t\t\tclass=\"document\"\r\n\t\t\t\t\tcontenteditable=\"true\"\r\n\t\t\t\t\trole=\"textbox\"\r\n\t\t\t\t\taria-multiline=\"true\"\r\n\t\t\t\t\taria-label=\"품의 본문\"\r\n\t\t\t\t\tspellcheck=\"true\"\r\n\t\t\t\t>\r\n\t\t\t\t\t<p><br /></p>\r\n\t\t\t\t</article>\r\n\t\t\t</div>\r\n\t\t\t<footer>\r\n\t\t\t\t<span id=\"status\" role=\"status\">이 브라우저에 임시저장됩니다</span><span id=\"count\">0자</span>\r\n\t\t\t</footer>\r\n\t\t</section>\r\n\t\t<section id=\"save-example\" hidden>\r\n\t\t\t<button id=\"save-example-button\" type=\"button\">저장하기</button>\r\n\t\t\t<h2>저장한 HTML</h2>\r\n\t\t\t<pre><code id=\"saved-html\">저장하면 HTML 코드가 표시됩니다.</code></pre>\r\n\t\t</section>\r\n\t</main>\r\n\t<dialog id=\"panel\">\r\n\t\t<form method=\"dialog\">\r\n\t\t\t<div class=\"dialog-heading\">\r\n\t\t\t\t<h2></h2>\r\n\t\t\t\t<button id=\"dialog-close\" type=\"button\" aria-label=\"닫기\" title=\"닫기\">\r\n\t\t\t\t\t<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"m6 6 12 12 M18 6 6 18\" /></svg>\r\n\t\t\t\t</button>\r\n\t\t\t</div>\r\n\t\t\t<div id=\"fields\"></div>\r\n\t\t\t<div class=\"actions\">\r\n\t\t\t\t<button id=\"accept\" value=\"ok\">적용</button>\r\n\t\t\t</div>\r\n\t\t</form>\r\n\t</dialog>\r\n\t<input type=\"file\" id=\"openfile\" accept=\".html,.htm,.txt,text/html,text/plain\" hidden />\r\n\t<input type=\"file\" id=\"imagefile\" accept=\"image/png,image/jpeg,image/gif,image/webp\" hidden />\r\n\t<script>'use strict';\r\nconst $ = (id) => document.getElementById(id);\r\nconst editor = $('body'),\r\n\tpanel = $('panel'),\r\n\tfields = $('fields');\r\nconst embedded = window.frameElement?.hasAttribute('srcdoc');\r\nconst draftId = window.frameElement?.dataset.draftKey;\r\nconst draftKey = embedded ? (draftId ? 'korean-editor.draft.' + draftId : null) : 'erp.proposal-editor.preview.v1';\r\nconst actions = new Map();\r\nlet savedRange,\r\n\tcellStart,\r\n\ttargetRect,\r\n\tcomposing = false,\r\n\tdirty = false;\r\nconst status = (message) => {\r\n\t$('status').textContent = message;\r\n};\r\nconst escapeText = (value) =>\r\n\tString(value).replace(\r\n\t\t/[&<>\"']/g,\r\n\t\t(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', \"'\": '&#39;' })[c],\r\n\t);\r\nconst allowedTags = new Set(\r\n\t'p div br span strong b em i u s strike sub sup h1 h2 h3 h4 ul ol li blockquote pre code a figure figcaption img video audio table colgroup col thead tbody tfoot tr td th caption hr details summary time font'.split(\r\n\t\t' ',\r\n\t),\r\n);\r\nconst allowedStyles = new Set(\r\n\t'font-family font-size font-weight font-style text-align text-decoration text-decoration-line color background-color line-height margin-left padding-left list-style-type vertical-align width height border border-color border-width border-style border-top border-right border-bottom border-left border-collapse'.split(\r\n\t\t' ',\r\n\t),\r\n);\r\nfunction validUrl(raw, media = false) {\r\n\tif (!raw) return '';\r\n\tif (!media && /^#[\\w가-힣-]+$/.test(raw)) return raw;\r\n\ttry {\r\n\t\tconst url = new URL(raw);\r\n\t\treturn (media ? ['https:', 'http:'] : ['https:', 'http:', 'mailto:', 'tel:']).includes(url.protocol)\r\n\t\t\t? url.href\r\n\t\t\t: '';\r\n\t} catch {\r\n\t\treturn '';\r\n\t}\r\n}\r\nfunction clean(html) {\r\n\tconst template = document.createElement('template');\r\n\ttemplate.innerHTML = html;\r\n\tfunction copy(node) {\r\n\t\tif (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.data);\r\n\t\tif (\r\n\t\t\tnode.nodeType !== Node.ELEMENT_NODE ||\r\n\t\t\t/^(script|style|title|meta|base|link|iframe|object|embed|svg|math|template|head)$/i.test(node.localName)\r\n\t\t)\r\n\t\t\treturn document.createDocumentFragment();\r\n\t\tconst tag = node.localName,\r\n\t\t\tout = allowedTags.has(tag) ? document.createElement(tag) : document.createDocumentFragment();\r\n\t\tif (out.nodeType === Node.ELEMENT_NODE) {\r\n\t\t\tfor (const key of allowedStyles) {\r\n\t\t\t\tconst value = node.style?.getPropertyValue(key);\r\n\t\t\t\tif (value && !/[()]/.test(value.replace(/rgba?\\([\\d\\s.,%]+\\)/g, ''))) out.style.setProperty(key, value);\r\n\t\t\t}\r\n\t\t\tif (tag === 'th' && ['row', 'col'].includes(node.scope)) out.scope = node.scope;\r\n\t\t\tif (tag === 'a') {\r\n\t\t\t\tconst url = validUrl(node.getAttribute('href'));\r\n\t\t\t\tif (url) out.setAttribute('href', url);\r\n\t\t\t}\r\n\t\t\tif (['img', 'audio', 'video'].includes(tag)) {\r\n\t\t\t\tconst src = node.getAttribute('src') || '';\r\n\t\t\t\tif (tag === 'img' && /^data:image\\/(png|jpeg|webp|gif);base64,[a-z0-9+/=\\s]+$/i.test(src))\r\n\t\t\t\t\tout.src = src;\r\n\t\t\t\telse if (validUrl(src, true)) out.src = validUrl(src, true);\r\n\t\t\t\tif (tag === 'img') {\r\n\t\t\t\t\tif (['small', 'document', 'full'].includes(node.dataset.size)) out.dataset.size = node.dataset.size;\r\n\t\t\t\t\tif (['left', 'center', 'right'].includes(node.dataset.align)) {\r\n\t\t\t\t\t\tout.dataset.align = node.dataset.align;\r\n\t\t\t\t\t\tout.style.display = 'block';\r\n\t\t\t\t\t\tout.style.marginInlineStart = node.dataset.align === 'left' ? '0' : 'auto';\r\n\t\t\t\t\t\tout.style.marginInlineEnd = node.dataset.align === 'right' ? '0' : 'auto';\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (tag === 'img') out.alt = node.getAttribute('alt') || '';\r\n\t\t\t\telse out.controls = true;\r\n\t\t\t}\r\n\t\t\tfor (const attr of ['colspan', 'rowspan', 'start', 'width', 'height', 'size'])\r\n\t\t\t\tif (/^\\d{1,4}$/.test(node.getAttribute(attr) || '')) out.setAttribute(attr, node.getAttribute(attr));\r\n\t\t\tif (tag === 'font')\r\n\t\t\t\tfor (const attr of ['color', 'face'])\r\n\t\t\t\t\tif (node.hasAttribute(attr)) out.setAttribute(attr, node.getAttribute(attr));\r\n\t\t\tif (['ltr', 'rtl'].includes(node.dir)) out.dir = node.dir;\r\n\t\t\tif (node.id && /^doc-[\\w가-힣-]+$/.test(node.id)) out.id = node.id;\r\n\t\t\tif (tag === 'hr' && node.classList.contains('pagebreak')) out.className = 'pagebreak';\r\n\t\t\tif (tag === 'details') out.open = true;\r\n\t\t}\r\n\t\tfor (const child of node.childNodes) out.append(copy(child));\r\n\t\treturn out;\r\n\t}\r\n\tconst result = document.createElement('div');\r\n\tfor (const node of template.content.childNodes) result.append(copy(node));\r\n\treturn result.innerHTML;\r\n}\r\nfunction remember() {\r\n\tconst sel = getSelection();\r\n\tif (sel.rangeCount && editor.contains(sel.getRangeAt(0).commonAncestorContainer))\r\n\t\tsavedRange = sel.getRangeAt(0).cloneRange();\r\n}\r\nfunction restore() {\r\n\teditor.focus();\r\n\tconst sel = getSelection();\r\n\tif (!savedRange || !editor.contains(savedRange.commonAncestorContainer)) {\r\n\t\tsavedRange = document.createRange();\r\n\t\tsavedRange.selectNodeContents(editor);\r\n\t\tsavedRange.collapse(false);\r\n\t}\r\n\tsel.removeAllRanges();\r\n\tsel.addRange(savedRange);\r\n}\r\nfunction changed() {\r\n\tdirty = true;\r\n\tconst words = editor.innerText.trim();\r\n\t$('count').textContent = Array.from(words).length + '자 · ' + (words ? words.split(/\\s+/).length : 0) + '어절';\r\n\tstatus('편집 중');\r\n\tremember();\r\n\tif (embedded && !composing)\r\n\t\tdocument.dispatchEvent(new CustomEvent('editor-change', { detail: clean(editor.innerHTML) }));\r\n}\r\nfunction command(name, value = null) {\r\n\trestore();\r\n\tdocument.execCommand(name, false, value);\r\n\tremember();\r\n\tchanged();\r\n}\r\nfunction insert(html) {\r\n\tcommand('insertHTML', html);\r\n}\r\nfunction persist() {\r\n\tif (!draftKey || !dirty) return;\r\n\ttry {\r\n\t\tlocalStorage.setItem(draftKey, clean(editor.innerHTML));\r\n\t\tdirty = false;\r\n\t\tstatus('브라우저에 임시저장됨');\r\n\t} catch {\r\n\t\tstatus('임시저장 공간이 부족합니다. 문서 저장을 이용하세요.');\r\n\t}\r\n}\r\nsetInterval(() => {\r\n\tif (!composing) persist();\r\n}, 30000);\r\naddEventListener('pagehide', persist);\r\neditor.addEventListener('compositionstart', () => (composing = true));\r\neditor.addEventListener('compositionend', () => {\r\n\tcomposing = false;\r\n\tchanged();\r\n});\r\neditor.addEventListener('input', changed);\r\neditor.addEventListener('paste', (e) => {\r\n\te.preventDefault();\r\n\tremember();\r\n\tconst data = e.clipboardData;\r\n\tif (data.files.length) {\r\n\t\timage(data.files[0]);\r\n\t\treturn;\r\n\t}\r\n\tconst html = data.getData('text/html');\r\n\tif (html) insert(clean(html));\r\n\telse command('insertText', data.getData('text/plain'));\r\n});\r\nconst dropLine = document.createElement('div');\r\ndropLine.className = 'image-drop-line';\r\ndropLine.setAttribute('aria-hidden', 'true');\r\ndropLine.hidden = true;\r\ndocument.body.append(dropLine);\r\nconst imageTypes = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];\r\nfunction draggingImage(data) {\r\n\treturn (\r\n\t\tArray.from(data.items).some((item) => item.kind === 'file' && (!item.type || imageTypes.includes(item.type))) ||\r\n\t\t(!data.items.length && Array.from(data.types).includes('Files'))\r\n\t);\r\n}\r\n// 가이드선과 실제 삽입 범위를 같은 문단 경계에서 계산한다.\r\nfunction dropPosition(event) {\r\n\tconst inner = event.target.closest?.('td,th,li');\r\n\tconst host = inner && editor.contains(inner) ? inner : editor;\r\n\tconst bounds = host.getBoundingClientRect(),\r\n\t\tstyle = getComputedStyle(host);\r\n\tconst left = bounds.left + parseFloat(style.paddingLeft),\r\n\t\tright = bounds.right - parseFloat(style.paddingRight);\r\n\tconst range = document.createRange();\r\n\tlet lastBottom = null;\r\n\tfor (const node of host.childNodes) {\r\n\t\tif (node.nodeType === Node.TEXT_NODE && !node.textContent.trim()) continue;\r\n\t\trange.selectNode(node);\r\n\t\tconst rect = range.getBoundingClientRect();\r\n\t\tif (!rect.height) continue;\r\n\t\tif (event.clientY < rect.top + rect.height / 2) {\r\n\t\t\trange.collapse(true);\r\n\t\t\treturn { range, left, right, y: lastBottom === null ? rect.top : (lastBottom + rect.top) / 2 };\r\n\t\t}\r\n\t\tlastBottom = rect.bottom;\r\n\t}\r\n\trange.selectNodeContents(host);\r\n\trange.collapse(false);\r\n\treturn { range, left, right, y: lastBottom ?? bounds.top + parseFloat(style.paddingTop) };\r\n}\r\neditor.addEventListener('dragover', (event) => {\r\n\tevent.preventDefault();\r\n\tif (!draggingImage(event.dataTransfer)) {\r\n\t\tdropLine.hidden = true;\r\n\t\treturn;\r\n\t}\r\n\tevent.dataTransfer.dropEffect = 'copy';\r\n\tconst { left, right, y } = dropPosition(event);\r\n\tObject.assign(dropLine.style, { left: left + 'px', width: Math.max(0, right - left) + 'px', top: y + 'px' });\r\n\tdropLine.hidden = false;\r\n});\r\neditor.addEventListener('dragleave', (event) => {\r\n\tif (!editor.contains(event.relatedTarget)) dropLine.hidden = true;\r\n});\r\ndocument.addEventListener('dragend', () => {\r\n\tdropLine.hidden = true;\r\n});\r\nwindow.addEventListener('blur', () => {\r\n\tdropLine.hidden = true;\r\n});\r\ndocument.addEventListener(\r\n\t'drop',\r\n\t() => {\r\n\t\tdropLine.hidden = true;\r\n\t},\r\n\ttrue,\r\n);\r\nfunction readImage(file) {\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tconst reader = new FileReader();\r\n\t\treader.onload = () => resolve(pictureMarkup(reader.result, file.name));\r\n\t\treader.onerror = () => reject(reader.error);\r\n\t\treader.readAsDataURL(file);\r\n\t});\r\n}\r\neditor.addEventListener('drop', async (event) => {\r\n\tevent.preventDefault();\r\n\tconst data = event.dataTransfer;\r\n\tif (data.files.length) {\r\n\t\tconst files = Array.from(data.files).filter((file) => imageTypes.includes(file.type));\r\n\t\tif (!files.length) return status('PNG, JPEG, WebP, GIF 이미지를 선택하세요.');\r\n\t\tconst { range } = dropPosition(event);\r\n\t\ttry {\r\n\t\t\tconst pictures = await Promise.all(files.map(readImage));\r\n\t\t\tif (!editor.contains(range.commonAncestorContainer)) return;\r\n\t\t\tsavedRange = range;\r\n\t\t\tinsert(pictures.map((html) => '<figure>' + html + '</figure>').join(''));\r\n\t\t} catch {\r\n\t\t\tstatus('이미지 파일을 읽지 못했습니다.');\r\n\t\t}\r\n\t\treturn;\r\n\t}\r\n\tconst pos = document.caretRangeFromPoint?.(event.clientX, event.clientY);\r\n\tif (pos && editor.contains(pos.commonAncestorContainer)) savedRange = pos;\r\n\tinsert(clean(data.getData('text/html')) || escapeText(data.getData('text/plain')));\r\n});\r\nfunction button(label, fn) {\r\n\tconst el = document.createElement('button');\r\n\tel.type = 'button';\r\n\tel.textContent = label;\r\n\tel.onclick = fn;\r\n\treturn el;\r\n}\r\nfunction run(label) {\r\n\tactions.get(label)?.();\r\n}\r\nfunction add(label, fn) {\r\n\tactions.set(label, fn);\r\n}\r\nfunction form(title, inputs, apply, setup) {\r\n\tfields.replaceChildren();\r\n\tpanel.className = '';\r\n\tpanel.querySelector('h2').textContent = title;\r\n\t$('accept').hidden = false;\r\n\tconst controls = {};\r\n\tfor (const [key, label, value = '', type = 'text'] of inputs) {\r\n\t\tconst wrap = document.createElement('label');\r\n\t\twrap.textContent = label;\r\n\t\tconst el = document.createElement(type === 'textarea' ? 'textarea' : 'input');\r\n\t\tif (type !== 'textarea') el.type = type;\r\n\t\tel.value = value;\r\n\t\twrap.append(el);\r\n\t\tfields.append(wrap);\r\n\t\tcontrols[key] = el;\r\n\t}\r\n\tconst values = () => Object.fromEntries(Object.entries(controls).map(([k, el]) => [k, el.value]));\r\n\tsetup?.(controls);\r\n\tpanel.returnValue = '';\r\n\tpanel.onclose = () => {\r\n\t\tif (panel.returnValue === 'ok') apply(values());\r\n\t};\r\n\tpanel.showModal();\r\n\t(Object.values(controls)[0] || panel.querySelector('#fields button') || dialog - close).focus();\r\n}\r\n$('dialog-close').onclick = () => panel.close('cancel');\r\nfunction confirmDocument(title, text, apply) {\r\n\tform(title, [], apply, () => {\r\n\t\tconst message = document.createElement('p');\r\n\t\tmessage.textContent = text;\r\n\t\tfields.append(message);\r\n\t});\r\n}\r\nfunction inspect(title, content) {\r\n\tform(\r\n\t\ttitle,\r\n\t\t[],\r\n\t\t() => {},\r\n\t\t() => {\r\n\t\t\tfields.append(content);\r\n\t\t\t$('accept').hidden = true;\r\n\t\t},\r\n\t);\r\n}\r\nfunction selectionNode() {\r\n\tconst node = savedRange?.startContainer;\r\n\treturn node?.nodeType === 1 ? node : node?.parentElement;\r\n}\r\nfunction selectNode(el) {\r\n\tsavedRange = document.createRange();\r\n\tsavedRange.selectNode(el);\r\n}\r\nfunction blockNode() {\r\n\tconst el = selectionNode()?.closest('p,div,h1,h2,h3,h4,li,blockquote,pre,td,th');\r\n\treturn el && el !== editor && editor.contains(el) ? el : null;\r\n}\r\nfunction updateBlock(key, value) {\r\n\trestore();\r\n\tlet el = blockNode();\r\n\tif (!el) {\r\n\t\tcommand('formatBlock', 'p');\r\n\t\tel = blockNode();\r\n\t}\r\n\tif (el) {\r\n\t\tconst clone = el.cloneNode(true);\r\n\t\tif (key === 'dir') clone.dir = value;\r\n\t\telse clone.style[key] = value;\r\n\t\tselectNode(el);\r\n\t\tinsert(clone.outerHTML);\r\n\t}\r\n}\r\nfor (const [label, name, value] of [\r\n\t['실행 취소', 'undo'],\r\n\t['다시 실행', 'redo'],\r\n\t['굵게', 'bold'],\r\n\t['기울임', 'italic'],\r\n\t['밑줄', 'underline'],\r\n\t['취소선', 'strikeThrough'],\r\n\t['아래 첨자', 'subscript'],\r\n\t['위 첨자', 'superscript'],\r\n\t['서식 지우기', 'removeFormat'],\r\n\t['왼쪽 정렬', 'justifyLeft'],\r\n\t['가운데 정렬', 'justifyCenter'],\r\n\t['오른쪽 정렬', 'justifyRight'],\r\n\t['양쪽 정렬', 'justifyFull'],\r\n\t['번호 목록', 'insertOrderedList'],\r\n\t['글머리 목록', 'insertUnorderedList'],\r\n\t['들여쓰기', 'indent'],\r\n\t['내어쓰기', 'outdent'],\r\n\t['인용문', 'formatBlock', 'blockquote'],\r\n\t['본문', 'formatBlock', 'p'],\r\n\t['제목 1', 'formatBlock', 'h1'],\r\n\t['제목 2', 'formatBlock', 'h2'],\r\n\t['제목 3', 'formatBlock', 'h3'],\r\n\t['구분선', 'insertHorizontalRule'],\r\n\t['링크 해제', 'unlink'],\r\n])\r\n\tadd(label, () => command(name, value));\r\nadd('전체 선택', () => {\r\n\trestore();\r\n\tsavedRange.selectNodeContents(editor);\r\n\trestore();\r\n});\r\nfor (const [label, cmd, initial] of [\r\n\t['글자색', 'foreColor', '#173858'],\r\n\t['강조색', 'hiliteColor', '#fff3a6'],\r\n])\r\n\tadd(label, () => form(label, [['color', '색상', initial, 'color']], (v) => command(cmd, v.color)));\r\nadd('왼쪽에서 오른쪽', () => updateBlock('dir', 'ltr'));\r\nadd('오른쪽에서 왼쪽', () => updateBlock('dir', 'rtl'));\r\nadd('링크', () => {\r\n\tconst selected = savedRange?.toString() || '';\r\n\tform(\r\n\t\t'링크 삽입',\r\n\t\t[\r\n\t\t\t['url', '웹 주소 또는 #doc-위치이름', 'https://'],\r\n\t\t\t['label', '표시할 글자', selected],\r\n\t\t],\r\n\t\t(v) => {\r\n\t\t\tconst url = validUrl(v.url.trim());\r\n\t\t\tif (!url) return status('올바른 주소를 입력하세요.');\r\n\t\t\tinsert('<a href=\"' + escapeText(url) + '\">' + escapeText(v.label || url) + '</a>');\r\n\t\t},\r\n\t);\r\n});\r\nadd('문서 위치', () =>\r\n\tform('문서 위치 지정', [['name', '위치 이름']], (v) => {\r\n\t\tif (!/^[\\w가-힣-]+$/.test(v.name))\r\n\t\t\treturn status('위치 이름에는 글자, 숫자, 밑줄, 하이픈을 사용할 수 있습니다.');\r\n\t\tinsert('<span id=\"doc-' + escapeText(v.name) + '\">' + escapeText(savedRange?.toString() || v.name) + '</span>');\r\n\t}),\r\n);\r\nfunction pictureMarkup(src, alt) {\r\n\treturn (\r\n\t\t'<img data-size=\"small\" style=\"width:75%;height:auto\" src=\"' +\r\n\t\tescapeText(src) +\r\n\t\t'\" alt=\"' +\r\n\t\tescapeText(alt) +\r\n\t\t'\">'\r\n\t);\r\n}\r\nasync function image(file) {\r\n\tif (!file || !imageTypes.includes(file.type)) return status('PNG, JPEG, WebP, GIF 이미지를 선택하세요.');\r\n\tconst range = savedRange?.cloneRange();\r\n\ttry {\r\n\t\tconst markup = await readImage(file);\r\n\t\tif (range && editor.contains(range.commonAncestorContainer)) savedRange = range;\r\n\t\tinsert(markup);\r\n\t} catch {\r\n\t\tstatus('이미지 파일을 읽지 못했습니다.');\r\n\t}\r\n}\r\nadd('그림 파일', () => $('imagefile').click());\r\n$('imagefile').onchange = (e) => {\r\n\timage(e.target.files[0]);\r\n\te.target.value = '';\r\n};\r\nfor (const [label, tag] of [\r\n\t['그림 주소', 'img'],\r\n\t['동영상', 'video'],\r\n\t['오디오', 'audio'],\r\n])\r\n\tadd(label, () =>\r\n\t\tform(\r\n\t\t\tlabel,\r\n\t\t\t[\r\n\t\t\t\t['url', '파일 주소', 'https://'],\r\n\t\t\t\t['alt', '설명'],\r\n\t\t\t],\r\n\t\t\t(v) => {\r\n\t\t\t\tconst u = validUrl(v.url.trim(), true);\r\n\t\t\t\tif (!u) return status('올바른 파일 주소를 입력하세요.');\r\n\t\t\t\tinsert(\r\n\t\t\t\t\ttag === 'img'\r\n\t\t\t\t\t\t? pictureMarkup(u, v.alt)\r\n\t\t\t\t\t\t: '<' + tag + ' controls src=\"' + escapeText(u) + '\"></' + tag + '>',\r\n\t\t\t\t);\r\n\t\t\t},\r\n\t\t),\r\n\t);\r\nadd('코드 블록', () =>\r\n\tform('코드 블록', [['code', '코드', savedRange?.toString() || '', 'textarea']], (v) =>\r\n\t\tinsert('<pre><code>' + escapeText(v.code) + '</code></pre><p><br></p>'),\r\n\t),\r\n);\r\nadd('접기 영역', () =>\r\n\tform(\r\n\t\t'접기 영역',\r\n\t\t[\r\n\t\t\t['title', '제목', '세부 내용'],\r\n\t\t\t['body', '내용', '', 'textarea'],\r\n\t\t],\r\n\t\t(v) =>\r\n\t\t\tinsert(\r\n\t\t\t\t'<details open><summary>' +\r\n\t\t\t\t\tescapeText(v.title) +\r\n\t\t\t\t\t'</summary><p>' +\r\n\t\t\t\t\tescapeText(v.body).replace(/\\n/g, '<br>') +\r\n\t\t\t\t\t'</p></details><p><br></p>',\r\n\t\t\t),\r\n\t),\r\n);\r\nadd('접기 해제', () => {\r\n\tconst el = selectionNode()?.closest('details');\r\n\tif (!el) return status('접기 영역 안을 선택하세요.');\r\n\tconst html =\r\n\t\t'<p>' +\r\n\t\tescapeText(el.querySelector('summary')?.textContent || '') +\r\n\t\t'</p>' +\r\n\t\tArray.from(el.children)\r\n\t\t\t.filter((child) => child.tagName !== 'SUMMARY')\r\n\t\t\t.map((child) => child.outerHTML)\r\n\t\t\t.join('');\r\n\tselectNode(el);\r\n\tinsert(html);\r\n});\r\nadd('페이지 나누기', () => insert('<hr class=\"pagebreak\"><p><br></p>'));\r\nadd('줄바꿈 없는 공백', () => insert('&nbsp;'));\r\nadd('날짜', () => command('insertText', new Date().toLocaleDateString('ko-KR')));\r\nadd('시각', () =>\r\n\tcommand('insertText', new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })),\r\n);\r\nfor (const [label, options] of [['특수문자', '※ ㎡ ㎥ ㎜ ㎏ ₁ ± × ÷ ① ② ③ ④ ⑤ ⑥ ○ ● □ ■ △ ▲ ✓ → ← ℃ ㎞ ₩ € ©']])\r\n\tadd(label, () => {\r\n\t\tconst group = document.createElement('div');\r\n\t\tfor (const c of options.split(' '))\r\n\t\t\tgroup.append(\r\n\t\t\t\tbutton(c, () => {\r\n\t\t\t\t\tpanel.close();\r\n\t\t\t\t\tcommand('insertText', c);\r\n\t\t\t\t}),\r\n\t\t\t);\r\n\t\tinspect(label, group);\r\n\t});\r\nadd('이모지', () => {\r\n\tconst groups = [\r\n\t\t['진행·결재', '✅완료 ⏳대기 🔄진행 🔍검토 ☑️확인 ❌반려 ⛔중지 🚩중요'],\r\n\t\t['일정·회의', '📅일정 🗓️계획 ⏰마감 🔔알림 📍장소 🤝협의 📢공지 💬의견'],\r\n\t\t['문서·자료', '📄문서 📋체크리스트 📝작성 📎첨부 📁폴더 📊통계 📈증가 📉감소'],\r\n\t\t['현장·안전', '🏗️건설현장 👷작업자 🦺안전조끼 ⛑️안전모 ⚠️주의 🚧공사중 🧯소화기 🛠️보수'],\r\n\t\t['자재·비용', '📦자재 🚚운송 🧾영수증 💳결제 💰예산 🧮정산 📐설계 📏치수'],\r\n\t\t['소통·연락', '👍동의 👏칭찬 🙏감사 💡제안 📞전화 ✉️메일 📣안내 🎯목표'],\r\n\t];\r\n\tconst list = document.createElement('div');\r\n\tlist.className = 'emoji-picker';\r\n\tfor (const [title, entries] of groups) {\r\n\t\tconst section = document.createElement('section'),\r\n\t\t\theading = document.createElement('h3');\r\n\t\theading.textContent = title;\r\n\t\tsection.append(heading);\r\n\t\tfor (const entry of entries.split(' ')) {\r\n\t\t\tconst split = entry.search(/[가-힣]/u),\r\n\t\t\t\tsymbol = entry.slice(0, split),\r\n\t\t\t\tname = entry.slice(split);\r\n\t\t\tconst control = button(symbol, () => {\r\n\t\t\t\tpanel.close();\r\n\t\t\t\tcommand('insertText', symbol);\r\n\t\t\t});\r\n\t\t\tcontrol.title = name;\r\n\t\t\tcontrol.setAttribute('aria-label', name);\r\n\t\t\tsection.append(control);\r\n\t\t}\r\n\t\tlist.append(section);\r\n\t}\r\n\tinspect('이모지', list);\r\n});\r\nfunction replaceBody(html) {\r\n\trestore();\r\n\tsavedRange.selectNodeContents(editor);\r\n\tinsert(html || '<p><br></p>');\r\n}\r\nadd('HTML 원본', () =>\r\n\tform('HTML 원본 편집', [['html', '문서 HTML', clean(editor.innerHTML), 'textarea']], (v) =>\r\n\t\treplaceBody(clean(v.html)),\r\n\t),\r\n);\r\nadd('새 문서', () => {\r\n\tconfirmDocument('새 문서', '현재 본문을 비우고 새 문서를 시작할까요?', () => replaceBody('<p><br></p>'));\r\n});\r\nadd('열기', () => $('openfile').click());\r\n$('openfile').onchange = async (e) => {\r\n\tconst file = e.target.files[0];\r\n\tif (!file) return;\r\n\tconst raw = await file.text();\r\n\treplaceBody(/\\.txt$/i.test(file.name) ? escapeText(raw).replace(/\\n/g, '<br>') : clean(raw));\r\n\te.target.value = '';\r\n};\r\nadd('임시저장', () => {\r\n\tdirty = true;\r\n\tpersist();\r\n});\r\nadd('임시저장 복구', () => {\r\n\ttry {\r\n\t\tconst draft = localStorage.getItem(draftKey);\r\n\t\tif (draft) confirmDocument('임시저장 복구', '임시저장한 본문을 불러올까요?', () => replaceBody(clean(draft)));\r\n\t\telse if (!draft) status('임시저장된 문서가 없습니다.');\r\n\t} catch {\r\n\t\tstatus('임시저장을 읽을 수 없습니다.');\r\n\t}\r\n});\r\nadd('문서 저장', () => {\r\n\tconst css =\r\n\t\t'body{font:16px/1.6 sans-serif;max-width:800px;margin:auto}table{border-collapse:collapse;width:100%}td,th{border:1px solid #999;padding:6px;vertical-align:middle}img,video{max-width:100%}img[data-size=full]{display:block;width:100%!important;margin-inline:0!important}.pagebreak{break-after:page}';\r\n\tconst html =\r\n\t\t'<!doctype html><html lang=\"ko\"><meta charset=\"utf-8\"><title>품의 문서</title><style>' +\r\n\t\tcss +\r\n\t\t'</style><body>' +\r\n\t\tclean(editor.innerHTML) +\r\n\t\t'</body></html>';\r\n\tconst url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));\r\n\tconst a = document.createElement('a');\r\n\ta.href = url;\r\n\ta.download = '품의문서.html';\r\n\ta.click();\r\n\tsetTimeout(() => URL.revokeObjectURL(url), 2000);\r\n\tpersist();\r\n\tstatus('문서 파일을 저장했습니다.');\r\n});\r\n$('download').onclick = () => run('문서 저장');\r\nadd('미리보기', () => {\r\n\tconst doc = document.createElement('div');\r\n\tdoc.className = 'document';\r\n\tdoc.innerHTML = clean(editor.innerHTML);\r\n\tinspect('인쇄 전 미리보기', doc);\r\n\tpanel.classList.add('preview');\r\n\tdocument.getElementById('dialog-close').focus();\r\n});\r\nadd('인쇄', () => window.print());\r\nadd('전체 화면', async () => {\r\n\ttry {\r\n\t\tif (document.fullscreenElement) await document.exitFullscreen();\r\n\t\telse await document.documentElement.requestFullscreen();\r\n\t} catch {\r\n\t\tdocument.body.classList.toggle('expanded');\r\n\t}\r\n});\r\nadd('문단 경계', () => editor.classList.toggle('blocks'));\r\nadd('숨은 문자 보기', () => {\r\n\tconst pre = document.createElement('pre');\r\n\tpre.style.whiteSpace = 'pre-wrap';\r\n\tpre.textContent = editor.innerText\r\n\t\t.replace(/ /g, '·')\r\n\t\t.replace(/\\u00a0/g, '⍽')\r\n\t\t.replace(/\\t/g, '→')\r\n\t\t.replace(/\\n/g, '↵\\n');\r\n\tinspect('공백 및 줄바꿈', pre);\r\n});\r\nadd('도움말', () => {\r\n\tconst p = document.createElement('p');\r\n\tp.textContent =\r\n\t\t'Ctrl+B 굵게 · Ctrl+Z 실행 취소 · Ctrl+S 파일 저장. 표에서 ↑·↓는 같은 열의 위·아래 칸으로 이동합니다. Tab은 다음 칸, Shift+Tab은 이전 칸으로 이동합니다. 셀 합치기는 시작 셀에서 마지막 셀을 Shift+클릭하거나 표 도구에서 병합 범위를 선택하세요. 임시저장은 이 브라우저에만 보관됩니다.';\r\n\tinspect('편집기 도움말', p);\r\n});\r\n\r\n// 병합된 셀을 포함해 화면상의 행과 열 좌표를 계산한다.\r\nfunction layout(table) {\r\n\tconst rows = Array.from(table.rows),\r\n\t\tgrid = rows.map(() => []),\r\n\t\tcells = [];\r\n\trows.forEach((row, y) => {\r\n\t\tlet x = 0;\r\n\t\tfor (const el of row.cells) {\r\n\t\t\twhile (grid[y][x]) x++;\r\n\t\t\tconst w = el.colSpan,\r\n\t\t\t\th = Math.min(el.rowSpan || rows.length - y, rows.length - y);\r\n\t\t\tconst entry = { el, x, y, w, h };\r\n\t\t\tcells.push(entry);\r\n\t\t\tfor (let yy = y; yy < y + h; yy++) for (let xx = x; xx < x + w; xx++) grid[yy][xx] = entry;\r\n\t\t\tx += w;\r\n\t\t}\r\n\t});\r\n\treturn { grid, cells, height: rows.length, width: Math.max(0, ...grid.map((row) => row.length)) };\r\n}\r\nfunction locateCell() {\r\n\tconst el = selectionNode()?.closest('td,th');\r\n\treturn el && el !== editor && editor.contains(el) ? el : null;\r\n}\r\nfunction clearMarked() {\r\n\teditor.querySelectorAll('.selected').forEach((el) => el.classList.remove('selected'));\r\n\ttargetRect = null;\r\n}\r\nfunction mark(first, last) {\r\n\tclearMarked();\r\n\tconst tbl = first?.closest('table');\r\n\tif (!tbl || tbl !== last?.closest('table')) return;\r\n\tconst { cells } = layout(tbl),\r\n\t\ta = cells.find((c) => c.el === first),\r\n\t\tb = cells.find((c) => c.el === last);\r\n\tconst r = {\r\n\t\tx: Math.min(a.x, b.x),\r\n\t\ty: Math.min(a.y, b.y),\r\n\t\tendX: Math.max(a.x + a.w, b.x + b.w),\r\n\t\tendY: Math.max(a.y + a.h, b.y + b.h),\r\n\t};\r\n\tconst intersect = cells.filter((c) => c.x < r.endX && c.x + c.w > r.x && c.y < r.endY && c.y + c.h > r.y);\r\n\tif (intersect.some((c) => c.x < r.x || c.x + c.w > r.endX || c.y < r.y || c.y + c.h > r.endY))\r\n\t\treturn status('병합된 셀 전체가 포함되도록 범위를 선택하세요.');\r\n\tintersect.forEach((c) => c.el.classList.add('selected'));\r\n\ttargetRect = r;\r\n}\r\nlet cellGesture = null;\r\nlet keepDragSelection = false;\r\neditor.addEventListener('pointerdown', (event) => {\r\n\tkeepDragSelection = false;\r\n\tconst first = event.target.closest('td,th');\r\n\tif (!first || event.button !== 0 || event.pointerType === 'touch' || rangeMode || event.shiftKey) return;\r\n\tcellGesture = { id: event.pointerId, first, last: first, dragging: false };\r\n});\r\nfunction trackCell(event) {\r\n\tconst gesture = cellGesture;\r\n\tif (!gesture || event.pointerId !== gesture.id) return;\r\n\tconst cell = document.elementFromPoint(event.clientX, event.clientY)?.closest('td,th');\r\n\tif (!cell || cell.closest('table') !== gesture.first.closest('table') || cell === gesture.last) return;\r\n\tgesture.last = cell;\r\n\tgesture.dragging = true;\r\n\teditor.classList.add('cell-selecting');\r\n\tmark(gesture.first, cell);\r\n\tgetSelection().removeAllRanges();\r\n}\r\ndocument.addEventListener('pointermove', trackCell);\r\ndocument.addEventListener('pointerup', (event) => {\r\n\tconst gesture = cellGesture;\r\n\tif (!gesture || event.pointerId !== gesture.id) return;\r\n\ttrackCell(event);\r\n\tcellGesture = null;\r\n\teditor.classList.remove('cell-selecting');\r\n\tif (!gesture.dragging) return;\r\n\tcellStart = gesture.first;\r\n\tsavedRange = document.createRange();\r\n\tsavedRange.selectNodeContents(cellStart);\r\n\tsavedRange.collapse(true);\r\n\trestore();\r\n\tkeepDragSelection = true;\r\n\tquick();\r\n});\r\nfunction cancelCellGesture() {\r\n\tif (cellGesture?.dragging) clearMarked();\r\n\tcellGesture = null;\r\n\teditor.classList.remove('cell-selecting');\r\n}\r\ndocument.addEventListener('pointercancel', cancelCellGesture);\r\nwindow.addEventListener('blur', cancelCellGesture);\r\neditor.addEventListener('dragstart', (event) => {\r\n\tif (cellGesture && !event.target.closest('img,a')) event.preventDefault();\r\n});\r\nlet rangeMode = false;\r\neditor.addEventListener('click', (e) => {\r\n\tif (keepDragSelection) {\r\n\t\tkeepDragSelection = false;\r\n\t\treturn;\r\n\t}\r\n\tconst el = e.target.closest('td,th');\r\n\tif (el && (e.shiftKey || rangeMode) && cellStart) {\r\n\t\tmark(cellStart, el);\r\n\t\trangeMode = false;\r\n\t} else {\r\n\t\tclearMarked();\r\n\t\tcellStart = el;\r\n\t}\r\n\tremember();\r\n\tquick();\r\n});\r\nfunction tableInsert(rows, cols, headers) {\r\n\tif (!Number.isInteger(rows) || !Number.isInteger(cols) || rows < 1 || cols < 1 || rows > 50 || cols > 20)\r\n\t\treturn status('표 크기는 1~50행, 1~20열로 입력하세요.');\r\n\tlet html = '<table><tbody>';\r\n\tfor (let r = 0; r < rows; r++) {\r\n\t\thtml += '<tr>';\r\n\t\tfor (let c = 0; c < cols; c++) {\r\n\t\t\tconst tag = headers && r === 0 ? 'th' : 'td';\r\n\t\t\thtml += '<' + tag + '>' + (headers && r === 0 ? escapeText(headers[c]) : '<br>') + '</' + tag + '>';\r\n\t\t}\r\n\t\thtml += '</tr>';\r\n\t}\r\n\tinsert(html + '</tbody></table><p><br></p>');\r\n}\r\nadd('표 삽입', () =>\r\n\tform(\r\n\t\t'표 삽입',\r\n\t\t[\r\n\t\t\t['rows', '행', '3', 'number'],\r\n\t\t\t['cols', '열', '4', 'number'],\r\n\t\t],\r\n\t\t(v) => tableInsert(Number(v.rows), Number(v.cols)),\r\n\t\t(controls) => {\r\n\t\t\tfor (const [el, max] of [\r\n\t\t\t\t[controls.rows, 50],\r\n\t\t\t\t[controls.cols, 20],\r\n\t\t\t]) {\r\n\t\t\t\tel.required = true;\r\n\t\t\t\tel.min = 1;\r\n\t\t\t\tel.max = max;\r\n\t\t\t}\r\n\t\t\tconst grid = document.createElement('div');\r\n\t\t\tgrid.className = 'grid';\r\n\t\t\tfields.prepend(grid);\r\n\t\t\tlet pointerId = null;\r\n\t\t\tfunction gridCell(event) {\r\n\t\t\t\tconst cell = document.elementFromPoint(event.clientX, event.clientY)?.closest('button');\r\n\t\t\t\treturn cell?.parentElement === grid ? cell : null;\r\n\t\t\t}\r\n\t\t\tlet hoveredCell;\r\n\t\t\tfunction previewCell(cell) {\r\n\t\t\t\tif (hoveredCell !== cell) {\r\n\t\t\t\t\thoveredCell?.classList.remove('grid-tip');\r\n\t\t\t\t\tcell.classList.add('grid-tip');\r\n\t\t\t\t\thoveredCell = cell;\r\n\t\t\t\t}\r\n\t\t\t\tconst index = Array.prototype.indexOf.call(grid.children, cell);\r\n\t\t\t\tcontrols.rows.value = Math.floor(index / 8) + 1;\r\n\t\t\t\tcontrols.cols.value = (index % 8) + 1;\r\n\t\t\t\tArray.from(grid.children).forEach((item, i) =>\r\n\t\t\t\t\titem.classList.toggle(\r\n\t\t\t\t\t\t'on',\r\n\t\t\t\t\t\ti % 8 < Number(controls.cols.value) && Math.floor(i / 8) < Number(controls.rows.value),\r\n\t\t\t\t\t),\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t\tgrid.onpointerdown = (event) => {\r\n\t\t\t\tif (event.button !== 0 || !gridCell(event)) return;\r\n\t\t\t\tpointerId = event.pointerId;\r\n\t\t\t\tgrid.setPointerCapture(pointerId);\r\n\t\t\t\tpreviewCell(gridCell(event));\r\n\t\t\t};\r\n\t\t\tgrid.onpointermove = (event) => {\r\n\t\t\t\tconst cell = gridCell(event);\r\n\t\t\t\tif (cell && (pointerId === null || pointerId === event.pointerId)) previewCell(cell);\r\n\t\t\t};\r\n\t\t\tgrid.onpointerup = (event) => {\r\n\t\t\t\tif (event.pointerId !== pointerId) return;\r\n\t\t\t\tpointerId = null;\r\n\t\t\t\tconst cell = gridCell(event);\r\n\t\t\t\tif (cell) {\r\n\t\t\t\t\tpreviewCell(cell);\r\n\t\t\t\t\tpanel.close('ok');\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tgrid.onlostpointercapture = () => {\r\n\t\t\t\tpointerId = null;\r\n\t\t\t};\r\n\t\t\tfor (let y = 1; y <= 6; y++)\r\n\t\t\t\tfor (let x = 1; x <= 8; x++) {\r\n\t\t\t\t\tconst b = button('', () => {\r\n\t\t\t\t\t\tcontrols.rows.value = y;\r\n\t\t\t\t\t\tcontrols.cols.value = x;\r\n\t\t\t\t\t\tpanel.close('ok');\r\n\t\t\t\t\t});\r\n\t\t\t\t\tb.setAttribute('aria-label', y + '행 ' + x + '열');\r\n\t\t\t\t\tb.title = y + '행 ' + x + '열';\r\n\t\t\t\t\tgrid.append(b);\r\n\t\t\t\t}\r\n\t\t},\r\n\t),\r\n);\r\nadd('구매 내역표', () => tableInsert(4, 4, ['품목', '수량', '단가', '금액']));\r\nadd('병합 범위 선택', () => {\r\n\tcellStart = locateCell();\r\n\tif (!cellStart) return status('시작 셀을 먼저 선택하세요.');\r\n\trangeMode = true;\r\n\tstatus('합칠 범위의 마지막 셀을 누르세요.');\r\n});\r\nfunction editTable(op, boundary) {\r\n\tconst cell = locateCell() || cellStart;\r\n\tif (!cell || !editor.contains(cell)) return status('표 안의 셀을 먼저 선택하세요.');\r\n\tconst original = cell.closest('table'),\r\n\t\ttable = original.cloneNode(true),\r\n\t\t{ cells, width, height } = layout(table);\r\n\tconst current = cells.find(\r\n\t\t(c) => c.el.parentElement.rowIndex === cell.parentElement.rowIndex && c.el.cellIndex === cell.cellIndex,\r\n\t);\r\n\tif (!current) return;\r\n\tlet { x, y } = current;\r\n\tconst fresh = (xx, yy) => {\r\n\t\tconst el = document.createElement('td');\r\n\t\tel.append(document.createElement('br'));\r\n\t\treturn { el, x: xx, y: yy, h: 1, w: 1 };\r\n\t};\r\n\tlet entries = cells.slice(),\r\n\t\tH = height,\r\n\t\tW = width;\r\n\tif (op === '표 삭제') entries = [];\r\n\telse if (op === '셀 합치기') {\r\n\t\tconst r = targetRect;\r\n\t\tif (!r) return status('먼저 병합 범위를 선택하세요.');\r\n\t\tconst inside = entries.filter((c) => c.x >= r.x && c.x < r.endX && c.y >= r.y && c.y < r.endY);\r\n\t\tif (inside.length < 2) return status('두 개 이상의 셀을 선택하세요.');\r\n\t\tconst keep = inside[0];\r\n\t\tfor (const other of inside.slice(1)) {\r\n\t\t\tif (other.el.textContent.trim() || other.el.querySelector('img,video,audio')) {\r\n\t\t\t\tkeep.el.append(document.createElement('br'), ...other.el.childNodes);\r\n\t\t\t}\r\n\t\t}\r\n\t\tkeep.w = r.endX - r.x;\r\n\t\tkeep.h = r.endY - r.y;\r\n\t\tentries = entries.filter((c) => c === keep || !inside.includes(c));\r\n\t\tx = r.x;\r\n\t\ty = r.y;\r\n\t} else if (op === '행 분할' || op === '열 분할') {\r\n\t\tconst vertical = op === '행 분할';\r\n\t\tconst axis = vertical ? 'y' : 'x',\r\n\t\t\tspan = vertical ? 'h' : 'w';\r\n\t\tif (current[span] === 1) {\r\n\t\t\tfor (const entry of entries) {\r\n\t\t\t\tif (entry === current) continue;\r\n\t\t\t\tif (entry[axis] > current[axis]) entry[axis]++;\r\n\t\t\t\telse if (entry[axis] + entry[span] > current[axis]) entry[span]++;\r\n\t\t\t}\r\n\t\t\tcurrent[span]++;\r\n\t\t\tif (vertical) H++;\r\n\t\t\telse W++;\r\n\t\t}\r\n\t\tconst second = fresh(x, y);\r\n\t\tsecond.w = current.w;\r\n\t\tsecond.h = current.h;\r\n\t\tcurrent[span] = Math.ceil(current[span] / 2);\r\n\t\tsecond[axis] += current[span];\r\n\t\tsecond[span] -= current[span];\r\n\t\tentries.push(second);\r\n\t} else if (op === '너비 맞춤') {\r\n\t\tfor (const entry of entries) {\r\n\t\t\tentry.el.removeAttribute('width');\r\n\t\t\tentry.el.style.removeProperty('width');\r\n\t\t}\r\n\t\ttable.style.width = '100%';\r\n\t\ttable.style.tableLayout = 'fixed';\r\n\t} else if (op === '셀 나누기') {\r\n\t\tfor (let i = 0; i < current.h; i++)\r\n\t\t\tfor (let j = 0; j < current.w; j++) if (i || j) entries.push(fresh(x + j, y + i));\r\n\t\tcurrent.w = 1;\r\n\t\tcurrent.h = 1;\r\n\t} else {\r\n\t\tconst row = op.startsWith('행'),\r\n\t\t\taxis = row ? 'y' : 'x',\r\n\t\t\tspan = row ? 'h' : 'w',\r\n\t\t\tdel = op.endsWith('삭제'),\r\n\t\t\tat = boundary ?? current[axis] + (op.endsWith('뒤 추가') ? current[span] : 0);\r\n\t\tfor (const c of entries) {\r\n\t\t\tif (del) {\r\n\t\t\t\tif (c[axis] > at) c[axis]--;\r\n\t\t\t\telse if (c[axis] + c[span] > at) c[span]--;\r\n\t\t\t} else if (c[axis] >= at) c[axis]++;\r\n\t\t\telse if (c[axis] + c[span] > at) c[span]++;\r\n\t\t}\r\n\t\tentries = entries.filter((c) => c.w && c.h);\r\n\t\tif (row) H += del ? -1 : 1;\r\n\t\telse W += del ? -1 : 1;\r\n\t\tif (!del)\r\n\t\t\tfor (let q = 0; q < (row ? W : H); q++) {\r\n\t\t\t\tconst xx = row ? q : at,\r\n\t\t\t\t\tyy = row ? at : q;\r\n\t\t\t\tif (!entries.some((c) => xx >= c.x && xx < c.x + c.w && yy >= c.y && yy < c.y + c.h))\r\n\t\t\t\t\tentries.push(fresh(xx, yy));\r\n\t\t\t}\r\n\t}\r\n\tconst anchor = document.createRange();\r\n\tanchor.selectNode(original);\r\n\tsavedRange = anchor;\r\n\tif (!entries.length) {\r\n\t\tinsert('<p><br></p>');\r\n\t\tclearMarked();\r\n\t\tcellStart = null;\r\n\t\treturn;\r\n\t}\r\n\tconst tbody = document.createElement('tbody');\r\n\tfor (let i = 0; i < H; i++) {\r\n\t\tconst tr = tbody.insertRow();\r\n\t\tfor (const c of entries.filter((c) => c.y === i).sort((a, b) => a.x - b.x)) {\r\n\t\t\tc.el.colSpan = c.w;\r\n\t\t\tc.el.rowSpan = c.h;\r\n\t\t\tc.el.classList.remove('selected');\r\n\t\t\ttr.append(c.el);\r\n\t\t}\r\n\t}\r\n\tconst caption = table.caption?.cloneNode(true);\r\n\ttable.replaceChildren(tbody);\r\n\tif (caption) table.prepend(caption);\r\n\tconst tables = Array.from(editor.querySelectorAll('table')),\r\n\t\tindex = tables.indexOf(original);\r\n\tinsert(table.outerHTML);\r\n\tclearMarked();\r\n\tconst next = editor.querySelectorAll('table')[index];\r\n\tcellStart = next && layout(next).grid[Math.min(y, H - 1)]?.[Math.min(x, W - 1)]?.el;\r\n\tif (cellStart) {\r\n\t\tsavedRange = document.createRange();\r\n\t\tsavedRange.selectNodeContents(cellStart);\r\n\t\tsavedRange.collapse(true);\r\n\t\trestore();\r\n\t}\r\n}\r\nfor (const op of [\r\n\t'행 분할',\r\n\t'열 분할',\r\n\t'너비 맞춤',\r\n\t'행 앞 추가',\r\n\t'행 뒤 추가',\r\n\t'행 삭제',\r\n\t'열 앞 추가',\r\n\t'열 뒤 추가',\r\n\t'열 삭제',\r\n\t'셀 합치기',\r\n\t'셀 나누기',\r\n\t'표 삭제',\r\n])\r\n\tadd(op, () => editTable(op));\r\nlet verticalDestination = null;\r\nlet verticalColumn = 0;\r\neditor.addEventListener('pointerdown', () => {\r\n\tverticalDestination = null;\r\n});\r\neditor.addEventListener('keydown', (e) => {\r\n\tconst vertical = e.key === 'ArrowDown' || e.key === 'ArrowUp';\r\n\tif (!vertical) verticalDestination = null;\r\n\tif (composing || e.isComposing || e.altKey || e.ctrlKey || e.metaKey) return;\r\n\tif (e.key !== 'Tab' && !(vertical && !e.shiftKey && getSelection().isCollapsed)) return;\r\n\tremember();\r\n\tconst cell = locateCell();\r\n\tif (!cell) return;\r\n\tconst { cells, grid } = layout(cell.closest('table'));\r\n\tconst index = cells.findIndex((entry) => entry.el === cell);\r\n\tif (index < 0) return;\r\n\tlet next;\r\n\tif (vertical) {\r\n\t\tconst current = cells[index];\r\n\t\t// 가로로 병합된 셀을 통과해도 출발한 열을 유지한다.\r\n\t\tif (verticalDestination !== cell) verticalColumn = current.x;\r\n\t\tconst row = e.key === 'ArrowDown' ? current.y + current.h : current.y - 1;\r\n\t\tnext = grid[row]?.[verticalColumn];\r\n\t\te.preventDefault();\r\n\t} else {\r\n\t\tnext = cells[index + (e.shiftKey ? -1 : 1)];\r\n\t\tif (next) e.preventDefault();\r\n\t}\r\n\tif (!next) return;\r\n\tverticalDestination = vertical ? next.el : null;\r\n\tclearMarked();\r\n\tfocusCell(next.el);\r\n\tnext.el.scrollIntoView({ block: 'nearest', inline: 'nearest' });\r\n});\r\nfunction matches(query) {\r\n\tconst ranges = [];\r\n\tif (!query) return ranges;\r\n\tconst walk = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);\r\n\tfor (let node; (node = walk.nextNode()); ) {\r\n\t\tlet pos = 0;\r\n\t\twhile ((pos = node.data.indexOf(query, pos)) !== -1) {\r\n\t\t\tconst r = document.createRange();\r\n\t\t\tr.setStart(node, pos);\r\n\t\t\tpos += query.length;\r\n\t\t\tr.setEnd(node, pos);\r\n\t\t\tranges.push(r);\r\n\t\t}\r\n\t}\r\n\treturn ranges;\r\n}\r\nadd('찾기·바꾸기', () =>\r\n\tform(\r\n\t\t'찾기·바꾸기',\r\n\t\t[\r\n\t\t\t['find', '찾을 글자', savedRange?.toString() || ''],\r\n\t\t\t['replacement', '바꿀 글자'],\r\n\t\t],\r\n\t\t() => {},\r\n\t\t(ctrl) => {\r\n\t\t\t$('accept').hidden = true;\r\n\t\t\tlet index = 0;\r\n\t\t\tconst note = document.createElement('p');\r\n\t\t\tnote.setAttribute('role', 'status');\r\n\t\t\tfields.append(\r\n\t\t\t\tbutton('다음 찾기', () => {\r\n\t\t\t\t\tconst hits = matches(ctrl.find.value);\r\n\t\t\t\t\tif (!hits.length) {\r\n\t\t\t\t\t\tnote.textContent = '찾은 결과가 없습니다.';\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tindex %= hits.length;\r\n\t\t\t\t\tconst r = hits[index++];\r\n\t\t\t\t\tsavedRange = r;\r\n\t\t\t\t\tr.startContainer.parentElement.scrollIntoView({ block: 'nearest' });\r\n\t\t\t\t\tgetSelection().removeAllRanges();\r\n\t\t\t\t\tgetSelection().addRange(r);\r\n\t\t\t\t\tnote.textContent = index + ' / ' + hits.length + '번째 결과';\r\n\t\t\t\t}),\r\n\t\t\t\tbutton('모두 바꾸기', () => {\r\n\t\t\t\t\tconst hits = matches(ctrl.find.value);\r\n\t\t\t\t\tif (!hits.length) {\r\n\t\t\t\t\t\tnote.textContent = '찾은 결과가 없습니다.';\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpanel.close();\r\n\t\t\t\t\tfor (const r of hits.reverse()) {\r\n\t\t\t\t\t\tsavedRange = r;\r\n\t\t\t\t\t\tcommand('insertText', ctrl.replacement.value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tstatus(hits.length + '곳을 바꿨습니다.');\r\n\t\t\t\t}),\r\n\t\t\t\tnote,\r\n\t\t\t);\r\n\t\t},\r\n\t),\r\n);\r\nadd('글자 수', () => {\r\n\tconst p = document.createElement('p');\r\n\tp.textContent = $('count').textContent;\r\n\tinspect('문서 통계', p);\r\n});\r\nconst iconPaths = {\r\n\tphoto: 'M3 4h18v16H3z M3 16l5-5 4 4 3-3 6 6 M16 8h.01',\r\n\tvideo: 'M3 6h12v12H3z M15 10l6-4v12l-6-4',\r\n\tsmile: 'M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0 M8 9h.01 M16 9h.01 M7.5 14q4.5 6 9 0',\r\n\tquote: 'M4 14q0-6 6-8 M4 13h6v6H4z M14 14q0-6 6-8 M14 13h6v6h-6z',\r\n\tline: 'M3 12h18',\r\n\tlink: 'M10 14l4-4 M8 15l-1 1a3 3 0 0 1-4-4l4-4a4 4 0 0 1 6 0 M16 9l1-1a3 3 0 0 1 4 4l-4 4a4 4 0 0 1-6 0',\r\n\tcalendar: 'M3 5h18v16H3z M3 10h18 M7 3v5 M17 3v5 M7 14h2 M12 14h2',\r\n\tcode: 'M8 7l-5 5 5 5 M16 7l5 5-5 5 M14 4l-4 16',\r\n\ttable: 'M3 4h18v16H3z M3 10h18 M3 15h18 M9 4v16 M15 4v16',\r\n\tpreview: 'M2 12q10-15 20 0-10 15-20 0 M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0',\r\n\tmore: 'M5 12h.1 M12 12h.1 M19 12h.1',\r\n\tundo: 'M8 5L3 10l5 5 M4 10h10a6 6 0 0 1 6 6',\r\n\tredo: 'M16 5l5 5-5 5 M20 10H10a6 6 0 0 0-6 6',\r\n\tbold: 'M6 4h7a4 4 0 0 1 0 8H6z M6 12h8a4 4 0 0 1 0 8H6z',\r\n\titalic: 'M11 4h8 M5 20h8 M15 4L9 20',\r\n\tunderline: 'M6 4v7a6 6 0 0 0 12 0V4 M4 21h16',\r\n\tstrike: 'M17 6q-2-3-6-2-7 1-4 6 M17 14q3 5-3 6-5 1-8-2 M3 12h18',\r\n\tcolor: 'M6 17l6-13 6 13 M9 13h6 M4 21h16',\r\n\thighlight: 'M4 20h8 M7 15l9-11 4 4-9 11z',\r\n\tleft: 'M3 5h18 M3 10h11 M3 15h18 M3 20h11',\r\n\tcenter: 'M3 5h18 M7 10h10 M3 15h18 M7 20h10',\r\n\tright: 'M3 5h18 M10 10h11 M3 15h18 M10 20h11',\r\n\tlist: 'M4 6h.1 M4 12h.1 M4 18h.1 M9 6h12 M9 12h12 M9 18h12',\r\n\tnumber: 'M3 4h1v5 M2 13q5-2 2 2l-2 3h4 M9 6h12 M9 16h12',\r\n};\r\nfunction iconTool(action, icon, caption, handler) {\r\n\tconst el = button('', handler || (() => run(action)));\r\n\tel.className = caption ? 'insert-tool' : 'format-tool';\r\n\tel.title = action;\r\n\tel.setAttribute('aria-label', action);\r\n\tconst ns = 'http://www.w3.org/2000/svg';\r\n\tconst svg = document.createElementNS(ns, 'svg');\r\n\tsvg.setAttribute('viewBox', '0 0 24 24');\r\n\tsvg.setAttribute('aria-hidden', 'true');\r\n\tconst path = document.createElementNS(ns, 'path');\r\n\tpath.setAttribute('d', iconPaths[icon]);\r\n\tsvg.append(path);\r\n\tel.append(svg);\r\n\tif (caption) el.append(document.createTextNode(caption));\r\n\treturn el;\r\n}\r\nfunction showAllTools() {\r\n\tconst content = document.createElement('div');\r\n\tconst search = document.createElement('input');\r\n\tsearch.type = 'search';\r\n\tsearch.placeholder = '기능 이름 검색';\r\n\tsearch.setAttribute('aria-label', search.placeholder);\r\n\tconst list = document.createElement('div');\r\n\tlist.className = 'command-list';\r\n\tcontent.append(search, list);\r\n\tfunction filter() {\r\n\t\tlist.replaceChildren();\r\n\t\tfor (const label of actions.keys()) {\r\n\t\t\tif (!draftKey && ['임시저장', '임시저장 복구'].includes(label)) continue;\r\n\t\t\tif (!label.includes(search.value.trim())) continue;\r\n\t\t\tlist.append(\r\n\t\t\t\tbutton(label, () => {\r\n\t\t\t\t\tpanel.addEventListener('close', () => run(label), { once: true });\r\n\t\t\t\t\tpanel.close();\r\n\t\t\t\t}),\r\n\t\t\t);\r\n\t\t}\r\n\t\tif (!list.childElementCount) list.textContent = '검색된 기능이 없습니다.';\r\n\t}\r\n\tfilter();\r\n\tsearch.oninput = filter;\r\n\tinspect('전체 도구', content);\r\n\tsearch.focus();\r\n}\r\nfor (const [action, icon, caption] of [\r\n\t['그림 파일', 'photo', '사진'],\r\n\r\n\t['이모지', 'smile', '이모지'],\r\n\t['인용문', 'quote', '인용구'],\r\n\t['구분선', 'line', '구분선'],\r\n\t['링크', 'link', '링크'],\r\n\r\n\t['코드 블록', 'code', '코드'],\r\n\t['표 삽입', 'table', '표'],\r\n\t['미리보기', 'preview', '미리보기'],\r\n])\r\n\t$('insert-tools').append(iconTool(action, icon, caption));\r\n$('insert-tools').append(iconTool('전체 도구', 'more', '더보기', showAllTools));\r\nfunction selector(label, values, fn) {\r\n\tconst select = document.createElement('select');\r\n\tselect.setAttribute('aria-label', label);\r\n\tselect.add(new Option(label, ''));\r\n\tfor (const [text, value] of values) select.add(new Option(text, value));\r\n\tselect.onchange = () => {\r\n\t\tfn(select.value);\r\n\t\tselect.selectedIndex = 0;\r\n\t};\r\n\t$('tools').append(select);\r\n}\r\nselector(\r\n\t'문단',\r\n\t[\r\n\t\t['본문', 'p'],\r\n\t\t['큰 제목', 'h1'],\r\n\t\t['중간 제목', 'h2'],\r\n\t\t['작은 제목', 'h3'],\r\n\t],\r\n\t(v) => command('formatBlock', v),\r\n);\r\nselector(\r\n\t'글꼴',\r\n\t['맑은 고딕', '굴림', '바탕', 'Arial', 'Georgia', 'monospace'].map((v) => [v, v]),\r\n\t(v) => command('fontName', v),\r\n);\r\nselector(\r\n\t'글자 크기',\r\n\t['작게', '기본', '중간', '크게', '아주 크게'].map((v, i) => [v, String(i + 2)]),\r\n\t(v) => command('fontSize', v),\r\n);\r\nselector(\r\n\t'줄 간격',\r\n\t['1', '1.3', '1.6', '2', '2.5'].map((v) => [v + '배', v]),\r\n\t(v) => updateBlock('lineHeight', v),\r\n);\r\nfor (const group of [\r\n\t[\r\n\t\t['굵게', 'bold'],\r\n\t\t['기울임', 'italic'],\r\n\t\t['밑줄', 'underline'],\r\n\t\t['취소선', 'strike'],\r\n\t\t['글자색', 'color'],\r\n\t\t['강조색', 'highlight'],\r\n\t],\r\n\t[\r\n\t\t['왼쪽 정렬', 'left'],\r\n\t\t['가운데 정렬', 'center'],\r\n\t\t['오른쪽 정렬', 'right'],\r\n\t\t['글머리 목록', 'list'],\r\n\t\t['번호 목록', 'number'],\r\n\t],\r\n\t[\r\n\t\t['실행 취소', 'undo'],\r\n\t\t['다시 실행', 'redo'],\r\n\t],\r\n]) {\r\n\tconst section = document.createElement('span');\r\n\tsection.className = 'format-group';\r\n\tfor (const [action, icon] of group) section.append(iconTool(action, icon));\r\n\t$('tools').append(section);\r\n}\r\nconst tableIcons = {\r\n\t'셀 합치기': 'M3 5h18v14H3z M6 12h12 M9 9v6 M15 9v6',\r\n\t'행 분할': 'M3 5h18v14H3z M2 12h20',\r\n\t'열 분할': 'M3 5h18v14H3z M12 3v18',\r\n\t'너비 맞춤': 'M3 13h18v7H3z M9 13v7 M15 13v7 M3 7h18 M6 4L3 7l3 3 M18 4l3 3-3 3',\r\n\t'행 뒤 추가': 'M3 3h18v9H3z M3 7h18 M12 14v8 M8 18h8',\r\n\t'열 뒤 추가': 'M3 3h9v18H3z M7 3v18 M14 12h8 M18 8v8',\r\n\t'행 삭제': 'M3 3h18v10H3z M3 8h18 M8 18h8',\r\n\t'열 삭제': 'M3 3h9v18H3z M7 3v18 M15 12h7',\r\n};\r\nObject.assign(iconPaths, tableIcons);\r\nconst tableGroup = document.createElement('span');\r\ntableGroup.className = 'format-group table-group';\r\ntableGroup.setAttribute('role', 'group');\r\ntableGroup.setAttribute('aria-label', '표 전용 도구');\r\ntableGroup.hidden = true;\r\nfor (const action of Object.keys(tableIcons)) tableGroup.append(iconTool(action, action));\r\n$('tools').append(tableGroup);\r\n\r\nconst stylesPopup = document.createElement('div');\r\nstylesPopup.className = 'table-style-panel';\r\nstylesPopup.hidden = true;\r\ndocument.body.append(stylesPopup);\r\nlet styleButton;\r\nfunction hideStyles() {\r\n\tstylesPopup.hidden = true;\r\n\tstyleButton?.setAttribute('aria-expanded', 'false');\r\n\tstyleButton = null;\r\n}\r\nfunction changeStyle(apply) {\r\n\tconst active = locateCell() || cellStart,\r\n\t\toriginal = active?.closest('table');\r\n\tif (!original || !editor.contains(original)) return hideStyles();\r\n\tconst index = Array.from(editor.querySelectorAll('table')).indexOf(original);\r\n\tconst pos = layout(original).cells.find((c) => c.el === active),\r\n\t\trange = targetRect;\r\n\tconst copy = original.cloneNode(true),\r\n\t\tmodel = layout(copy);\r\n\tconst chosen = model.cells.filter((c) =>\r\n\t\trange\r\n\t\t\t? c.x >= range.x && c.x < range.endX && c.y >= range.y && c.y < range.endY\r\n\t\t\t: c.x === pos.x && c.y === pos.y,\r\n\t);\r\n\tapply(model, chosen);\r\n\tcopy.querySelectorAll('.selected').forEach((el) => el.classList.remove('selected'));\r\n\thideStyles();\r\n\tselectNode(original);\r\n\tinsert(copy.outerHTML);\r\n\tclearMarked();\r\n\tconst next = layout(editor.querySelectorAll('table')[index]).grid;\r\n\tfocusCell(next[pos.y][pos.x].el);\r\n\tif (range) mark(next[range.y][range.x].el, next[range.endY - 1][range.endX - 1].el);\r\n\tscheduleOverlay();\r\n}\r\nconst recentColors = [];\r\nfunction titleLine(label) {\r\n\tconst el = document.createElement('strong');\r\n\tel.textContent = label;\r\n\tstylesPopup.append(el);\r\n}\r\nfunction colorField(label, value) {\r\n\tconst wrap = document.createElement('label'),\r\n\t\tinput = document.createElement('input');\r\n\twrap.textContent = label;\r\n\tinput.type = 'color';\r\n\tinput.value = value;\r\n\twrap.append(input);\r\n\tstylesPopup.append(wrap);\r\n\treturn input;\r\n}\r\nfunction setFill(color) {\r\n\tif (color) {\r\n\t\tconst i = recentColors.indexOf(color);\r\n\t\tif (i >= 0) recentColors.splice(i, 1);\r\n\t\trecentColors.unshift(color);\r\n\t\trecentColors.splice(8);\r\n\t}\r\n\tchangeStyle((model, chosen) => chosen.forEach((c) => (c.el.style.backgroundColor = color)));\r\n}\r\nfunction swatches(colors) {\r\n\tconst group = document.createElement('div');\r\n\tgroup.className = 'swatches';\r\n\tfor (const color of colors) {\r\n\t\tconst el = button('', () => setFill(color));\r\n\t\tel.title = color;\r\n\t\tel.setAttribute('aria-label', '셀 배경색 ' + color);\r\n\t\tel.style.backgroundColor = color;\r\n\t\tgroup.append(el);\r\n\t}\r\n\tstylesPopup.append(group);\r\n}\r\nfunction showFill() {\r\n\tif (recentColors.length) {\r\n\t\ttitleLine('최근 사용한 색');\r\n\t\tswatches(recentColors);\r\n\t}\r\n\ttitleLine('셀 배경색');\r\n\tswatches(\r\n\t\t'#ffffff #e2e8f0 #fca5a5 #fdba74 #fde68a #bbf7d0 #bae6fd #bfdbfe #ddd6fe #fbcfe8 #94a3b8 #ef4444 #f97316 #eab308 #22c55e #14b8a6 #0ea5e9 #3b82f6 #8b5cf6 #ec4899 #334155 #991b1b #9a3412 #854d0e #166534 #115e59 #075985 #1e40af #5b21b6 #831843'.split(\r\n\t\t\t' ',\r\n\t\t),\r\n\t);\r\n\tconst color = colorField('사용자 지정 색', '#93c5fd');\r\n\tstylesPopup.append(\r\n\t\tbutton('색 적용', () => setFill(color.value)),\r\n\t\tbutton('배경색 지우기', () => setFill('')),\r\n\t);\r\n}\r\nfunction paintBorders(model, line, outer) {\r\n\tfor (const { el, x, y, w, h } of model.cells) {\r\n\t\tel.style.border = outer ? 'none' : line;\r\n\t\tif (outer) {\r\n\t\t\tif (!x) el.style.borderLeft = line;\r\n\t\t\tif (!y) el.style.borderTop = line;\r\n\t\t\tif (x + w === model.width) el.style.borderRight = line;\r\n\t\t\tif (y + h === model.height) el.style.borderBottom = line;\r\n\t\t}\r\n\t}\r\n}\r\nfunction showVerticalAlignment() {\r\n\ttitleLine('셀 세로 정렬');\r\n\tconst active = locateCell() || cellStart;\r\n\tconst cells = targetRect ? Array.from(active.closest('table').querySelectorAll('.selected')) : [active];\r\n\tfor (const [label, value] of [\r\n\t\t['위쪽 정렬', 'top'],\r\n\t\t['가운데 정렬', 'middle'],\r\n\t\t['아래쪽 정렬', 'bottom'],\r\n\t]) {\r\n\t\tconst option = button(label, () =>\r\n\t\t\tchangeStyle((model, chosen) => {\r\n\t\t\t\tfor (const { el } of chosen) el.style.verticalAlign = value;\r\n\t\t\t}),\r\n\t\t);\r\n\t\toption.setAttribute(\r\n\t\t\t'aria-pressed',\r\n\t\t\tString(cells.length > 0 && cells.every((el) => getComputedStyle(el).verticalAlign === value)),\r\n\t\t);\r\n\t\tstylesPopup.append(option);\r\n\t}\r\n}\r\nfunction showBorders() {\r\n\ttitleLine('표 테두리');\r\n\tconst color = colorField('선 색상', '#64748b');\r\n\tconst scope = document.createElement('select');\r\n\tscope.setAttribute('aria-label', '테두리 적용 범위');\r\n\tscope.add(new Option('전체 테두리', 'all'));\r\n\tscope.add(new Option('바깥쪽 테두리', 'outer'));\r\n\tstylesPopup.append(scope);\r\n\tfor (const [label, line] of [\r\n\t\t['가는 실선', '1px solid'],\r\n\t\t['굵은 실선', '2px solid'],\r\n\t\t['점선', '1px dotted'],\r\n\t\t['파선', '1px dashed'],\r\n\t\t['이중선', '3px double'],\r\n\t\t['테두리 없음', 'none'],\r\n\t]) {\r\n\t\tconst el = button(label, () =>\r\n\t\t\tchangeStyle((model) =>\r\n\t\t\t\tpaintBorders(model, line === 'none' ? line : line + ' ' + color.value, scope.value === 'outer'),\r\n\t\t\t),\r\n\t\t);\r\n\t\tconst sample = document.createElement('i');\r\n\t\tsample.style.borderTop = line + ' currentColor';\r\n\t\tel.append(sample);\r\n\t\tstylesPopup.append(el);\r\n\t}\r\n}\r\nfunction showPresets() {\r\n\ttitleLine('표 스타일');\r\n\tconst group = document.createElement('div');\r\n\tgroup.className = 'table-presets';\r\n\tstylesPopup.append(group);\r\n\tfor (const [label, kind] of [\r\n\t\t['기본 격자', 'grid-style'],\r\n\t\t['행 구분선', 'lines'],\r\n\t\t['줄무늬', 'stripe'],\r\n\t\t['점선 격자', 'dots'],\r\n\t]) {\r\n\t\tconst el = button(label, () =>\r\n\t\t\tchangeStyle((model) => {\r\n\t\t\t\tpaintBorders(\r\n\t\t\t\t\tmodel,\r\n\t\t\t\t\tkind === 'dots' ? '1px dotted #94a3b8' : kind === 'lines' ? 'none' : '1px solid #94a3b8',\r\n\t\t\t\t\tfalse,\r\n\t\t\t\t);\r\n\t\t\t\tfor (const { el, y } of model.cells) {\r\n\t\t\t\t\tel.style.backgroundColor = kind === 'stripe' && y % 2 ? '#edf2f6' : '';\r\n\t\t\t\t\tif (kind === 'lines') el.style.borderBottom = '1px solid #94a3b8';\r\n\t\t\t\t}\r\n\t\t\t}),\r\n\t\t);\r\n\t\tconst sample = document.createElement('span');\r\n\t\tsample.className = 'sample-grid ' + kind;\r\n\t\tfor (let n = 0; n < 9; n++) sample.append(document.createElement('i'));\r\n\t\tel.prepend(sample);\r\n\t\tgroup.append(el);\r\n\t}\r\n\ttitleLine('헤더 위치');\r\n\tfor (const [label, top, side] of [\r\n\t\t['헤더 없음', false, false],\r\n\t\t['첫 행 (가로)', true, false],\r\n\t\t['첫 열 (세로)', false, true],\r\n\t\t['첫 행과 첫 열', true, true],\r\n\t]) {\r\n\t\tconst option = button(label, () =>\r\n\t\t\tchangeStyle((model) => {\r\n\t\t\t\tfor (const { el, x, y } of model.cells) {\r\n\t\t\t\t\tconst scope = top && !y ? 'col' : side && !x ? 'row' : '',\r\n\t\t\t\t\t\tnext = document.createElement(scope ? 'th' : 'td');\r\n\t\t\t\t\tfor (const attr of el.attributes)\r\n\t\t\t\t\t\tif (attr.name !== 'scope') next.setAttribute(attr.name, attr.value);\r\n\t\t\t\t\tif (scope) next.scope = scope;\r\n\t\t\t\t\tnext.append(...el.childNodes);\r\n\t\t\t\t\tel.replaceWith(next);\r\n\t\t\t\t}\r\n\t\t\t}),\r\n\t\t);\r\n\t\toption.className = 'header-option';\r\n\t\tconst sample = document.createElement('span');\r\n\t\tsample.className = 'header-sample';\r\n\t\tsample.setAttribute('aria-hidden', 'true');\r\n\t\tfor (let row = 0; row < 3; row++) {\r\n\t\t\tfor (let col = 0; col < 3; col++) {\r\n\t\t\t\tconst cell = document.createElement('span');\r\n\t\t\t\tif ((top && row === 0) || (side && col === 0)) cell.className = 'is-header';\r\n\t\t\t\tsample.append(cell);\r\n\t\t\t}\r\n\t\t}\r\n\t\toption.append(sample);\r\n\t\tstylesPopup.append(option);\r\n\t}\r\n}\r\nObject.assign(iconPaths, {\r\n\tfill: 'M4 12l8-8 8 8-8 8z M7 3l6 6 M21 16q-4 5 0 5 3 0 0-5',\r\n\tverticalAlign: 'M3 12h18 M12 2v7l-3-3 M12 9l3-3 M12 22v-7l-3 3 M12 15l3 3',\r\n\tborders: 'M3 5h18 M3 12h18 M3 19h18',\r\n\tpreset: 'M3 4h18v16H3z M3 9h18 M9 9v11 M15 9v11 M3 14h18',\r\n});\r\nfor (const [name, icon, render] of [\r\n\t['셀 세로 정렬', 'verticalAlign', showVerticalAlignment],\r\n\t['셀 배경색', 'fill', showFill],\r\n\t['표 테두리', 'borders', showBorders],\r\n\t['표 스타일 및 헤더', 'preset', showPresets],\r\n]) {\r\n\tconst trigger = iconTool(name, icon, null, () => {\r\n\t\tconst same = styleButton === trigger;\r\n\t\thideStyles();\r\n\t\tif (same) return;\r\n\t\tstylesPopup.replaceChildren();\r\n\t\trender();\r\n\t\tstylesPopup.hidden = false;\r\n\t\tstyleButton = trigger;\r\n\t\ttrigger.setAttribute('aria-expanded', 'true');\r\n\t\tconst r = trigger.getBoundingClientRect();\r\n\t\tstylesPopup.style.left = Math.max(4, Math.min(r.left, innerWidth - stylesPopup.offsetWidth - 4)) + 'px';\r\n\t\tstylesPopup.style.top =\r\n\t\t\t(r.bottom + 4 + stylesPopup.offsetHeight <= innerHeight\r\n\t\t\t\t? r.bottom + 4\r\n\t\t\t\t: Math.max(4, r.top - stylesPopup.offsetHeight - 4)) + 'px';\r\n\t});\r\n\ttrigger.setAttribute('aria-expanded', 'false');\r\n\ttableGroup.append(trigger);\r\n}\r\ndocument.addEventListener('pointerdown', (e) => {\r\n\tif (!stylesPopup.contains(e.target) && !tableGroup.contains(e.target)) hideStyles();\r\n});\r\ndocument.addEventListener('keydown', (e) => {\r\n\tif (e.key === 'Escape' && styleButton) {\r\n\t\tconst trigger = styleButton;\r\n\t\thideStyles();\r\n\t\ttrigger.focus();\r\n\t}\r\n});\r\nconst overlay = document.createElement('div');\r\noverlay.className = 'table-overlay';\r\nconst sheet = editor.closest('.sheet');\r\nsheet.append(overlay);\r\nconst koreanMenu = document.createElement('div');\r\nkoreanMenu.className = 'editor-context-menu';\r\nkoreanMenu.setAttribute('aria-label', '편집 바로가기');\r\nkoreanMenu.setAttribute('role', 'menu');\r\nkoreanMenu.hidden = true;\r\ndocument.body.append(koreanMenu);\r\nasync function clipboardAction(label) {\r\n\trestore();\r\n\tconst range = savedRange.cloneRange();\r\n\ttry {\r\n\t\tif (label === '붙여넣기') {\r\n\t\t\tconst text = await navigator.clipboard.readText();\r\n\t\t\tif (text) {\r\n\t\t\t\tsavedRange = range;\r\n\t\t\t\tcommand('insertText', text);\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tconst table = cellStart?.closest('table');\r\n\t\tif (targetRect && table) {\r\n\t\t\tconst rows = Array.from(table.rows, (row) =>\r\n\t\t\t\tArray.from(row.cells).filter((c) => c.classList.contains('selected')),\r\n\t\t\t).filter((r) => r.length);\r\n\t\t\tawait navigator.clipboard.writeText(rows.map((row) => row.map((c) => c.innerText).join('\\t')).join('\\n'));\r\n\t\t\tif (label === '잘라내기') {\r\n\t\t\t\tconst copy = table.cloneNode(true);\r\n\t\t\t\tfor (const cell of copy.querySelectorAll('.selected')) {\r\n\t\t\t\t\tcell.replaceChildren(document.createElement('br'));\r\n\t\t\t\t\tcell.classList.remove('selected');\r\n\t\t\t\t}\r\n\t\t\t\tselectNode(table);\r\n\t\t\t\tinsert(copy.outerHTML);\r\n\t\t\t\tclearMarked();\r\n\t\t\t\tcellStart = null;\r\n\t\t\t}\r\n\t\t} else if (!document.execCommand(label === '복사' ? 'copy' : 'cut')) {\r\n\t\t\tawait navigator.clipboard.writeText(range.toString());\r\n\t\t\tif (label === '잘라내기') {\r\n\t\t\t\tsavedRange = range;\r\n\t\t\t\tcommand('delete');\r\n\t\t\t}\r\n\t\t}\r\n\t} catch {\r\n\t\tstatus('클립보드 접근을 허용하거나 키보드 단축키를 사용하세요.');\r\n\t}\r\n}\r\neditor.addEventListener('contextmenu', (event) => {\r\n\tevent.preventDefault();\r\n\tconst cell = event.target.closest('td,th');\r\n\tif (!cell?.classList.contains('selected')) clearMarked();\r\n\tif (cell && (targetRect || !savedRange?.toString())) focusCell(cell);\r\n\telse remember();\r\n\tkoreanMenu.replaceChildren();\r\n\tfunction item(label, fn, disabled = false) {\r\n\t\tconst el = button(label, () => {\r\n\t\t\tkoreanMenu.hidden = true;\r\n\t\t\tfn();\r\n\t\t\tquick();\r\n\t\t});\r\n\t\tel.setAttribute('role', 'menuitem');\r\n\t\tel.disabled = disabled;\r\n\t\tkoreanMenu.append(el);\r\n\t}\r\n\tconst selected = Boolean(targetRect || savedRange?.toString());\r\n\tfor (const label of ['잘라내기', '복사', '붙여넣기'])\r\n\t\titem(label, () => clipboardAction(label), label !== '붙여넣기' && !selected);\r\n\tif (cell) {\r\n\t\tkoreanMenu.append(document.createElement('hr'));\r\n\t\tfor (const label of ['셀 합치기', '행 분할', '열 분할', '너비 맞춤', '행 삭제', '열 삭제'])\r\n\t\t\titem(\r\n\t\t\t\tlabel,\r\n\t\t\t\t() => {\r\n\t\t\t\t\tif (!targetRect) focusCell(cell);\r\n\t\t\t\t\teditTable(label);\r\n\t\t\t\t},\r\n\t\t\t\tlabel === '셀 합치기' && editor.querySelectorAll('td.selected,th.selected').length < 2,\r\n\t\t\t);\r\n\t} else item('전체 선택', () => run('전체 선택'));\r\n\tkoreanMenu.hidden = false;\r\n\tkoreanMenu.style.left = Math.max(0, Math.min(event.clientX, innerWidth - koreanMenu.offsetWidth)) + 'px';\r\n\tkoreanMenu.style.top = Math.max(0, Math.min(event.clientY, innerHeight - koreanMenu.offsetHeight)) + 'px';\r\n\tquick();\r\n});\r\nkoreanMenu.addEventListener('mousedown', (event) => event.preventDefault());\r\ndocument.addEventListener('pointerdown', (event) => {\r\n\tif (!koreanMenu.contains(event.target)) koreanMenu.hidden = true;\r\n});\r\ndocument.addEventListener('keydown', (event) => {\r\n\tif (event.key === 'Escape') {\r\n\t\tkoreanMenu.hidden = true;\r\n\t\tclearMarked();\r\n\t\t$('context').hidden = true;\r\n\t\tscheduleOverlay();\r\n\t}\r\n});\r\nlet overlayKey = '',\r\n\toverlayTable,\r\n\tpendingOverlay;\r\nfunction scheduleOverlay() {\r\n\tcancelAnimationFrame(pendingOverlay);\r\n\tpendingOverlay = requestAnimationFrame(drawOverlay);\r\n}\r\nfunction focusCell(cell) {\r\n\tcellStart = cell;\r\n\tsavedRange = document.createRange();\r\n\tsavedRange.selectNodeContents(cell);\r\n\tsavedRange.collapse(true);\r\n\trestore();\r\n}\r\nfunction drawOverlay() {\r\n\tif (activePicture) {\r\n\t\toverlay.replaceChildren();\r\n\t\toverlayKey = '';\r\n\t\ttableGroup.hidden = true;\r\n\t\treturn;\r\n\t}\r\n\tconst cell = locateCell();\r\n\tconst table = cell?.closest('table');\r\n\ttableGroup.hidden = !table;\r\n\tif (!table) {\r\n\t\toverlay.replaceChildren();\r\n\t\toverlayTable = null;\r\n\t\toverlayKey = '';\r\n\t\treturn;\r\n\t}\r\n\tconst bounds = table.getBoundingClientRect(),\r\n\t\tbase = sheet.getBoundingClientRect();\r\n\tconst rows = Array.from(table.rows);\r\n\tconst { grid, width, height, cells } = layout(table);\r\n\tconst rowEdges = rows.map((row) => row.getBoundingClientRect().top - bounds.top);\r\n\trowEdges.push(bounds.height);\r\n\tconst columnEdges = Array.from({ length: width }, (_, x) => {\r\n\t\tconst entry = cells.find((item) => item.x === x);\r\n\t\treturn entry ? entry.el.getBoundingClientRect().left - bounds.left : (bounds.width * x) / width;\r\n\t});\r\n\tcolumnEdges.push(bounds.width);\r\n\tconst left = bounds.left - base.left,\r\n\t\ttop = bounds.top - base.top;\r\n\tconst active = cells.find((item) => item.el === cell);\r\n\tconst range = targetRect || { x: active.x, y: active.y, endX: active.x + active.w, endY: active.y + active.h };\r\n\tconst key = JSON.stringify([left, top, rowEdges, columnEdges, range, Boolean(targetRect), koreanMenu.hidden]);\r\n\tif (table === overlayTable && key === overlayKey) return;\r\n\toverlayTable = table;\r\n\toverlayKey = key;\r\n\toverlay.replaceChildren();\r\n\toverlay.style.left = left + 'px';\r\n\toverlay.style.top = top + 'px';\r\n\tconst selectedCount = table.querySelectorAll('.selected').length;\r\n\ttableGroup.querySelector('[aria-label=\"셀 합치기\"]').disabled = selectedCount < 2;\r\n\tfunction rail(isRow, index) {\r\n\t\tconst axis = isRow ? '행' : '열',\r\n\t\t\tedges = isRow ? rowEdges : columnEdges;\r\n\t\tconst first = isRow ? grid[index][0] : grid[0][index];\r\n\t\tconst last = isRow ? grid[index][width - 1] : grid[height - 1][index];\r\n\t\tif (!first || !last) return;\r\n\t\tconst choose = button('', () => {\r\n\t\t\tfocusCell(first.el);\r\n\t\t\tmark(first.el, last.el);\r\n\t\t\tscheduleOverlay();\r\n\t\t});\r\n\t\tchoose.className = 'table-rail ' + (isRow ? 'row' : 'column');\r\n\t\tchoose.setAttribute('aria-label', index + 1 + axis + ' 선택');\r\n\t\tchoose.title = choose.getAttribute('aria-label');\r\n\t\tchoose.classList.toggle(\r\n\t\t\t'active',\r\n\t\t\tisRow ? index >= range.y && index < range.endY : index >= range.x && index < range.endX,\r\n\t\t);\r\n\t\tchoose.style[isRow ? 'top' : 'left'] = edges[index] + 'px';\r\n\t\tchoose.style[isRow ? 'height' : 'width'] = edges[index + 1] - edges[index] + 'px';\r\n\t\toverlay.append(choose);\r\n\t\tconst plus = button('+', () => {\r\n\t\t\tfocusCell(first.el);\r\n\t\t\tclearMarked();\r\n\t\t\teditTable(isRow ? '행 뒤 추가' : '열 뒤 추가', index + 1);\r\n\t\t\tscheduleOverlay();\r\n\t\t});\r\n\t\tplus.className = 'table-plus ' + (isRow ? 'row' : 'column');\r\n\t\tplus.setAttribute('aria-label', index + 1 + axis + ' 다음에 추가');\r\n\t\tplus.title = plus.getAttribute('aria-label');\r\n\t\tplus.style[isRow ? 'top' : 'left'] = edges[index + 1] + 'px';\r\n\t\toverlay.append(plus);\r\n\t}\r\n\tfor (let i = 0; i < height; i++) rail(true, i);\r\n\tfor (let i = 0; i < width; i++) rail(false, i);\r\n\tif (!targetRect || !koreanMenu.hidden) return;\r\n\tconst pop = document.createElement('div');\r\n\tpop.className = 'cell-menu';\r\n\tpop.setAttribute('role', 'group');\r\n\tpop.setAttribute('aria-label', '선택한 셀 도구');\r\n\tfor (const action of ['셀 합치기', '행 분할', '열 분할', '너비 맞춤']) {\r\n\t\tconst control = iconTool(action, action, action, () => {\r\n\t\t\teditTable(action);\r\n\t\t\tscheduleOverlay();\r\n\t\t});\r\n\t\tcontrol.disabled = action === '셀 합치기' && selectedCount < 2;\r\n\t\tpop.append(control);\r\n\t}\r\n\tconst entireRow = range.x === 0 && range.endX === width && range.endY - range.y === 1;\r\n\tconst entireCol = range.y === 0 && range.endY === height && range.endX - range.x === 1;\r\n\tconst deletion = entireRow ? '행 삭제' : '열 삭제';\r\n\tconst remove = iconTool(deletion, deletion, '삭제', () => {\r\n\t\teditTable(deletion);\r\n\t\tscheduleOverlay();\r\n\t});\r\n\tremove.disabled = !targetRect || !(entireRow || entireCol);\r\n\tpop.append(remove);\r\n\toverlay.append(pop);\r\n\t// 선택 영역 옆에 표시하고 오른쪽 여백이 부족하면 아래에 배치한다.\r\n\tconst right = columnEdges[range.endX] + 4;\r\n\tif (left + right + pop.offsetWidth <= base.width) {\r\n\t\tpop.style.left = right + 'px';\r\n\t\tpop.style.top = rowEdges[range.y] + 'px';\r\n\t} else {\r\n\t\tpop.style.left = Math.max(-left, Math.min(columnEdges[range.x], base.width - left - pop.offsetWidth)) + 'px';\r\n\t\tpop.style.top = rowEdges[range.endY] + 4 + 'px';\r\n\t}\r\n}\r\nnew ResizeObserver(scheduleOverlay).observe(editor);\r\nwindow.addEventListener('resize', scheduleOverlay);\r\noverlay.addEventListener('mousedown', (event) => event.preventDefault());\r\ntableGroup.addEventListener('mousedown', (event) => event.preventDefault());\r\nconst quickBar = $('context');\r\nquickBar.classList.add('text-quick');\r\nquickBar.setAttribute('role', 'toolbar');\r\nquickBar.setAttribute('aria-label', '선택한 글자 서식');\r\ndocument.body.append(quickBar);\r\nfor (const label of ['글꼴', '글자 크기']) {\r\n\tconst original = $('tools').querySelector('select[aria-label=\"' + label + '\"]');\r\n\tconst select = original.cloneNode(true);\r\n\tselect.onchange = () => {\r\n\t\toriginal.value = select.value;\r\n\t\toriginal.dispatchEvent(new Event('change'));\r\n\t\tquick();\r\n\t};\r\n\tquickBar.append(select);\r\n}\r\nfor (const [action, icon] of [\r\n\t['굵게', 'bold'],\r\n\t['기울임', 'italic'],\r\n\t['밑줄', 'underline'],\r\n\t['글자색', 'color'],\r\n\t['인용문', 'quote'],\r\n\t['왼쪽 정렬', 'left'],\r\n\t['글머리 목록', 'list'],\r\n\t['링크', 'link'],\r\n]) {\r\n\tquickBar.append(iconTool(action, icon));\r\n}\r\nquickBar.addEventListener('mousedown', (event) => {\r\n\tif (event.target.closest('button')) event.preventDefault();\r\n});\r\nfunction quick() {\r\n\tif (activePicture) {\r\n\t\tquickBar.hidden = true;\r\n\t\treturn;\r\n\t}\r\n\tif (cellGesture) return;\r\n\tscheduleOverlay();\r\n\tconst selection = getSelection();\r\n\tconst switching = quickBar.contains(document.activeElement);\r\n\tconst range = switching ? savedRange : selection.rangeCount ? selection.getRangeAt(0) : null;\r\n\tquickBar.hidden =\r\n\t\tpanel.open ||\r\n\t\t!koreanMenu.hidden ||\r\n\t\tBoolean(targetRect) ||\r\n\t\t!range ||\r\n\t\trange.collapsed ||\r\n\t\t!editor.contains(range.commonAncestorContainer) ||\r\n\t\t!range.toString().trim();\r\n\tif (quickBar.hidden) return;\r\n\tconst rect = range.getBoundingClientRect();\r\n\tif (rect.bottom < 0 || rect.top > innerHeight) {\r\n\t\tquickBar.hidden = true;\r\n\t\treturn;\r\n\t}\r\n\tconst left = rect.left + (rect.width - quickBar.offsetWidth) / 2;\r\n\tquickBar.style.left = Math.max(4, Math.min(left, innerWidth - quickBar.offsetWidth - 4)) + 'px';\r\n\tquickBar.style.top =\r\n\t\t(rect.top >= quickBar.offsetHeight + 8\r\n\t\t\t? rect.top - quickBar.offsetHeight - 7\r\n\t\t\t: Math.min(rect.bottom + 7, innerHeight - quickBar.offsetHeight)) + 'px';\r\n\tfor (const [label, cmd] of [\r\n\t\t['굵게', 'bold'],\r\n\t\t['기울임', 'italic'],\r\n\t\t['밑줄', 'underline'],\r\n\t]) {\r\n\t\tquickBar\r\n\t\t\t.querySelector('[aria-label=\"' + label + '\"]')\r\n\t\t\t.setAttribute('aria-pressed', String(document.queryCommandState(cmd)));\r\n\t}\r\n}\r\ndocument.addEventListener(\r\n\t'scroll',\r\n\t() => {\r\n\t\tkoreanMenu.hidden = true;\r\n\t\tquick();\r\n\t},\r\n\ttrue,\r\n);\r\nwindow.addEventListener('resize', quick);\r\ndocument.addEventListener('selectionchange', () => {\r\n\tif (panel.open) return;\r\n\tremember();\r\n\tquick();\r\n});\r\ndocument.addEventListener('pointerdown', (e) => {\r\n\tif (!editor.contains(e.target)) remember();\r\n});\r\ndocument.addEventListener('keydown', (e) => {\r\n\tif (composing || e.isComposing) return;\r\n\r\n\tif (panel.open) return;\r\n\tif ((e.ctrlKey || e.metaKey) && !e.altKey && editor.contains(document.activeElement)) {\r\n\t\tconst key = e.key.toLowerCase();\r\n\t\tconst shortcuts = {\r\n\t\t\tb: '굵게',\r\n\t\t\ti: '기울임',\r\n\t\t\tu: '밑줄',\r\n\t\t\tk: '링크',\r\n\t\t\ta: '전체 선택',\r\n\t\t\tz: '실행 취소',\r\n\t\t\ty: '다시 실행',\r\n\t\t};\r\n\t\tconst action = e.shiftKey ? (key === 'z' ? '다시 실행' : null) : shortcuts[key];\r\n\t\tif (action) {\r\n\t\t\te.preventDefault();\r\n\t\t\tremember();\r\n\t\t\trun(action);\r\n\t\t\tquick();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tif ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {\r\n\t\te.preventDefault();\r\n\t\trun('문서 저장');\r\n\t}\r\n\tif ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f' && editor.contains(document.activeElement)) {\r\n\t\te.preventDefault();\r\n\t\trun('찾기·바꾸기');\r\n\t}\r\n});\r\neditor.addEventListener('keyup', (e) => {\r\n\tif (composing || e.isComposing || e.key !== ' ') return;\r\n\tremember();\r\n\tconst sel = getSelection(),\r\n\t\tn = sel.anchorNode;\r\n\tif (!sel.isCollapsed || n?.nodeType !== 3 || n.parentElement.closest('a,code,pre')) return;\r\n\tconst m = n.data.slice(0, sel.anchorOffset).match(/https?:\\/\\/[^\\s]+(?=[\\s\\u00a0]$)/);\r\n\tif (!m || !validUrl(m[0])) return;\r\n\tconst r = document.createRange();\r\n\tr.setStart(n, m.index);\r\n\tr.setEnd(n, sel.anchorOffset);\r\n\tsavedRange = r;\r\n\tinsert('<a href=\"' + escapeText(m[0]) + '\">' + escapeText(m[0]) + '</a>&nbsp;');\r\n});\r\n\r\nif (embedded) {\r\n\tdocument.documentElement.classList.add('embedded');\r\n\tif (!draftKey) {\r\n\t\tstatus('문서를 입력하세요.');\r\n\t}\r\n}\r\n// 선택 장식은 본문 밖에 두어 저장되는 HTML에 섞이지 않게 한다.\r\nlet activePicture = null,\r\n\tresizeGesture = null;\r\nconst pictureFrame = document.createElement('div');\r\npictureFrame.className = 'picture-frame';\r\npictureFrame.hidden = true;\r\ndocument.body.append(pictureFrame);\r\nconst pictureBar = document.createElement('div');\r\npictureBar.className = 'picture-bar';\r\npictureBar.setAttribute('role', 'toolbar');\r\npictureBar.setAttribute('aria-label', '이미지 빠른 도구');\r\npictureFrame.append(pictureBar);\r\nObject.assign(iconPaths, {\r\n\tsmallImage: 'M3 3h18 M3 21h18 M7 7h10v10H7z',\r\n\toriginalImage: 'M3 3h18 M3 21h18 M5 7h14v10H5z',\r\n\twideImage: 'M3 3h18 M3 21h18 M2 7h20v10H2z',\r\n\ttrash: 'M3 6h18 M8 6V3h8v3 M6 6l1 15h10l1-15 M10 10v7 M14 10v7',\r\n});\r\nfunction pictureBox(img) {\r\n\treturn img.parentElement?.tagName === 'FIGURE' ? img.parentElement : img;\r\n}\r\nfunction selectPicture(img) {\r\n\tactivePicture = img;\r\n\tif (img) {\r\n\t\tselectNode(img);\r\n\t\tquickBar.hidden = true;\r\n\t\tclearMarked();\r\n\t\toverlay.replaceChildren();\r\n\t\toverlayKey = '';\r\n\t\ttableGroup.hidden = true;\r\n\t}\r\n\tpositionPicture();\r\n}\r\nfunction positionPicture() {\r\n\tif (!activePicture || !editor.contains(activePicture)) {\r\n\t\tactivePicture = null;\r\n\t\tpictureFrame.hidden = true;\r\n\t\treturn;\r\n\t}\r\n\tconst r = activePicture.getBoundingClientRect();\r\n\tpictureFrame.hidden = r.bottom < 0 || r.top >= innerHeight || r.width <= 0;\r\n\tif (pictureFrame.hidden) return;\r\n\tObject.assign(pictureFrame.style, {\r\n\t\tleft: r.left + 'px',\r\n\t\ttop: r.top + 'px',\r\n\t\twidth: r.width + 'px',\r\n\t\theight: r.height + 'px',\r\n\t});\r\n\tconst barWidth = pictureBar.offsetWidth;\r\n\tpictureBar.style.left =\r\n\t\tMath.max(3, Math.min(r.left + (r.width - barWidth) / 2, innerWidth - barWidth - 3)) - r.left + 'px';\r\n\tpictureBar.style.top = (r.top >= pictureBar.offsetHeight + 8 ? -pictureBar.offsetHeight - 7 : 3) + 'px';\r\n\talignButton.hidden = activePicture.dataset.size !== 'small';\r\n\tconst align = activePicture.dataset.align || 'left';\r\n\talignButton.querySelector('path').setAttribute('d', iconPaths[align]);\r\n\talignButton.title = '이미지 정렬 · ' + { left: '왼쪽', center: '가운데', right: '오른쪽' }[align];\r\n\tfor (const mode of pictureBar.querySelectorAll('[data-size]'))\r\n\t\tmode.setAttribute('aria-pressed', String(mode.dataset.size === activePicture.dataset.size));\r\n}\r\nfunction editPicture(change) {\r\n\tif (!activePicture) return;\r\n\tconst index = Array.from(editor.querySelectorAll('img')).indexOf(activePicture);\r\n\tconst box = pictureBox(activePicture),\r\n\t\tcopy = box.cloneNode(true);\r\n\tconst img = copy.matches('img') ? copy : copy.querySelector('img');\r\n\tconst result = change(img, copy) ?? copy;\r\n\tselectNode(box);\r\n\tinsert(result.outerHTML);\r\n\tselectPicture(editor.querySelectorAll('img')[index]);\r\n}\r\nfunction tool(label, icon, fn) {\r\n\tpictureBar.append(iconTool(label, icon, null, fn));\r\n}\r\nconst alignButton = iconTool('이미지 정렬', 'left', null, () =>\r\n\teditPicture((img) => {\r\n\t\tconst next = { left: 'center', center: 'right', right: 'left' }[img.dataset.align || 'left'];\r\n\t\timg.dataset.align = next;\r\n\t\timg.style.display = 'block';\r\n\t\timg.style.marginInlineStart = next === 'left' ? '0' : 'auto';\r\n\t\timg.style.marginInlineEnd = next === 'right' ? '0' : 'auto';\r\n\t}),\r\n);\r\npictureBar.append(alignButton);\r\nfor (const [label, icon, mode] of [\r\n\t['작게', 'smallImage', 'small'],\r\n\t['문서 너비', 'originalImage', 'document'],\r\n\t['문서 여백 없이 채우기', 'wideImage', 'full'],\r\n]) {\r\n\tconst control = iconTool(label, icon, null, () =>\r\n\t\teditPicture((img) => {\r\n\t\t\timg.removeAttribute('width');\r\n\t\t\timg.removeAttribute('height');\r\n\t\t\timg.dataset.size = mode;\r\n\t\t\timg.style.width = mode === 'small' ? '75%' : '100%';\r\n\t\t\timg.style.height = 'auto';\r\n\t\t}),\r\n\t);\r\n\tcontrol.dataset.size = mode;\r\n\tpictureBar.append(control);\r\n}\r\nfunction deletePicture() {\r\n\tif (!activePicture) return;\r\n\tselectNode(pictureBox(activePicture));\r\n\tactivePicture = null;\r\n\tcommand('delete');\r\n\tpositionPicture();\r\n}\r\ntool('이미지 삭제', 'trash', deletePicture);\r\nfor (const corner of ['nw', 'ne', 'sw', 'se']) {\r\n\tconst grip = document.createElement('span');\r\n\tgrip.className = 'picture-grip ' + corner;\r\n\tgrip.onpointerdown = (e) => {\r\n\t\tif (e.button !== 0) return;\r\n\t\te.preventDefault();\r\n\t\tgrip.setPointerCapture(e.pointerId);\r\n\t\tconst rect = activePicture.getBoundingClientRect();\r\n\t\tresizeGesture = {\r\n\t\t\tid: e.pointerId,\r\n\t\t\tx: e.clientX,\r\n\t\t\ty: e.clientY,\r\n\t\t\tw: rect.width,\r\n\t\t\th: rect.height,\r\n\t\t\tmode: activePicture.dataset.size,\r\n\t\t\twidth: activePicture.style.width,\r\n\t\t\theight: activePicture.style.height,\r\n\t\t};\r\n\t};\r\n\tgrip.onpointermove = (e) => {\r\n\t\tif (resizeGesture?.id !== e.pointerId) return;\r\n\t\tconst g = resizeGesture,\r\n\t\t\tdx = (e.clientX - g.x) * (corner.endsWith('w') ? -1 : 1),\r\n\t\t\tdy = (e.clientY - g.y) * (corner.startsWith('n') ? -1 : 1);\r\n\t\tconst scale = 1 + (dx * g.w + dy * g.h) / (g.w * g.w + g.h * g.h);\r\n\t\tdelete activePicture.dataset.size;\r\n\t\tactivePicture.style.width = Math.max(24, Math.round(g.w * scale)) + 'px';\r\n\t\tactivePicture.style.height = 'auto';\r\n\t\tpositionPicture();\r\n\t};\r\n\tfunction end(commit) {\r\n\t\tif (!resizeGesture || !activePicture) return;\r\n\t\tconst width = activePicture.style.width;\r\n\t\tif (resizeGesture.mode) activePicture.dataset.size = resizeGesture.mode;\r\n\t\tactivePicture.style.width = resizeGesture.width;\r\n\t\tactivePicture.style.height = resizeGesture.height;\r\n\t\tresizeGesture = null;\r\n\t\tif (commit)\r\n\t\t\teditPicture((img) => {\r\n\t\t\t\tdelete img.dataset.size;\r\n\t\t\t\timg.style.width = width;\r\n\t\t\t\timg.style.height = 'auto';\r\n\t\t\t});\r\n\t\telse positionPicture();\r\n\t}\r\n\tgrip.onpointerup = () => end(true);\r\n\tgrip.onpointercancel = () => end(false);\r\n\tpictureFrame.append(grip);\r\n}\r\npictureFrame.addEventListener('mousedown', (e) => e.preventDefault());\r\neditor.addEventListener('click', (e) => {\r\n\tif (e.target.matches('img')) {\r\n\t\te.preventDefault();\r\n\t\tselectPicture(e.target);\r\n\t}\r\n});\r\ndocument.addEventListener('pointerdown', (e) => {\r\n\tif (activePicture && !pictureFrame.contains(e.target) && !panel.contains(e.target) && e.target !== activePicture)\r\n\t\tselectPicture(null);\r\n});\r\ndocument.addEventListener('keydown', (e) => {\r\n\tif (!activePicture || panel.open || e.isComposing) return;\r\n\tif (e.key === 'Escape') {\r\n\t\tselectPicture(null);\r\n\t\treturn;\r\n\t}\r\n\tif (['Backspace', 'Delete'].includes(e.key)) {\r\n\t\te.preventDefault();\r\n\t\tdeletePicture();\r\n\t}\r\n});\r\ndocument.addEventListener('scroll', positionPicture, true);\r\neditor.addEventListener('load', positionPicture, true);\r\nnew ResizeObserver(positionPicture).observe(editor);\r\nwindow.koreanEditor = {\r\n\tgetHTML() {\r\n\t\treturn clean(editor.innerHTML);\r\n\t},\r\n\tsetHTML(html) {\r\n\t\teditor.innerHTML = clean(html || '');\r\n\t\tsavedRange = null;\r\n\t\tclearMarked();\r\n\t\tcellStart = null;\r\n\t\tdirty = false;\r\n\t\tconst text = editor.innerText.trim();\r\n\t\t$('count').textContent = Array.from(text).length + '자 · ' + (text ? text.split(/\\s+/).length : 0) + '어절';\r\n\t},\r\n\tflush: persist,\r\n};\r\nif (!embedded) {\r\n\t$('save-example').hidden = false;\r\n\t$('save-example-button').onclick = () => {\r\n\t\t$('saved-html').textContent = window.koreanEditor.getHTML();\r\n\t};\r\n}\r\n</script>\r\n</html>\r\n";
@@ -0,0 +1,20 @@
1
+ import { useState } from 'react';
2
+ import { Editor } from 'fresh-web-editor/react';
3
+
4
+ export default function DocumentForm() {
5
+ const [html, setHtml] = useState('<p>문서를 편집해 보세요.</p>');
6
+ const [savedHtml, setSavedHtml] = useState(null);
7
+
8
+ function saveDocument() {
9
+ setSavedHtml(html);
10
+ }
11
+
12
+ return (
13
+ <section>
14
+ <Editor value={html} onChange={setHtml} />
15
+ <button type="button" onClick={saveDocument}>저장하기</button>
16
+ <h2>저장한 HTML</h2>
17
+ <pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}><code>{savedHtml ?? '저장하면 HTML 코드가 표시됩니다.'}</code></pre>
18
+ </section>
19
+ );
20
+ }
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Fresh Web Editor · React 예제</title>
7
+ </head>
8
+ <body>
9
+ <div id="app"></div>
10
+ <script type="module" src="/main.jsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,4 @@
1
+ import { createRoot } from 'react-dom/client';
2
+ import DocumentForm from './DocumentForm.jsx';
3
+
4
+ createRoot(document.getElementById('app')).render(<DocumentForm />);