@eliceio/cdk-cli 0.1.0-alpha.5 → 0.1.0-alpha.7
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 +110 -84
- package/es/cli.js +7 -22
- package/es/commands/build/index.d.ts +5 -3
- package/es/commands/build/index.js +20 -11
- package/es/commands/create/scaffold.d.ts +2 -0
- package/es/commands/create/scaffold.js +15 -1
- package/es/commands/dev/index.d.ts +1 -1
- package/es/commands/dev/index.js +1 -1
- package/es/commands/doctor/index.d.ts +1 -1
- package/es/commands/doctor/index.js +5 -6
- package/es/commands/setup/index.d.ts +4 -7
- package/es/commands/setup/index.js +41 -70
- package/es/commands/uninstall/index.d.ts +9 -8
- package/es/commands/uninstall/index.js +41 -47
- package/es/commands/update/index.d.ts +4 -2
- package/es/commands/update/index.js +27 -18
- package/es/core/collect.js +1 -1
- package/es/core/config.d.ts +1 -1
- package/es/core/config.js +3 -3
- package/es/{commands/mcp/index.d.ts → core/mcp.d.ts} +11 -18
- package/es/{commands/mcp/index.js → core/mcp.js} +29 -51
- package/es/core/minify.js +31 -2
- package/es/core/prepare.js +1 -1
- package/es/core/sandbox.d.ts +25 -0
- package/es/core/sandbox.js +110 -8
- package/es/{commands/skill/index.d.ts → core/skills.d.ts} +1 -17
- package/es/{commands/skill/index.js → core/skills.js} +6 -22
- package/es/dev/grading.d.ts +1 -1
- package/es/dev/grading.js +1 -1
- package/es/dev/host-page.js +20 -5
- package/es/dev/inject.d.ts +6 -0
- package/es/dev/inject.js +16 -1
- package/es/dev/mock-api.js +0 -16
- package/es/dev/server.d.ts +4 -2
- package/es/dev/server.js +11 -3
- package/es/rules/check.js +71 -8
- package/es/rules/csp.d.ts +26 -0
- package/es/rules/csp.js +42 -0
- package/es/rules/index.d.ts +2 -1
- package/es/rules/index.js +2 -1
- package/es/rules/refs.d.ts +12 -2
- package/es/rules/refs.js +50 -18
- package/es/rules/types.d.ts +5 -0
- package/es/rules/unused.d.ts +2 -0
- package/es/rules/unused.js +4 -3
- package/es/rules.json.js +2 -2
- package/package.json +2 -2
- package/rules.json +37 -15
- package/skills/_shared/always.md +2 -1
- package/skills/elice-content-create/SKILL.md +2 -1
- package/skills/elice-content-guide/SKILL.md +1 -1
- package/skills/elice-content-guide/topics/01-check-the-environment.md +2 -2
- package/skills/elice-content-guide/topics/02-design-the-material.md +2 -0
- package/skills/elice-content-guide/topics/03-create-the-project.md +2 -2
- package/skills/elice-content-guide/topics/04-rules.md +3 -1
- package/skills/elice-content-guide/topics/05-screen-code.md +44 -13
- package/skills/elice-content-guide/topics/07-move-existing-html.md +1 -1
- package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -18
- package/skills/elice-content-guide/topics/09-check.md +1 -0
- package/skills/elice-content-guide/topics/10-build.md +1 -1
- package/skills/elice-content-guide/topics/12-upload-with-the-material-mcp.md +2 -2
- package/skills/elice-content-migrate/SKILL.md +4 -3
- package/skills/elice-content-publish/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.js +3 -3
- package/templates/_shared/lib/elice-content-editor.d.ts +80 -0
- package/templates/_shared/lib/elice-content-editor.js +1062 -0
- package/templates/_shared/lib/elice-content.css +354 -1
- package/templates/_shared/lib/elice-content.js +10 -3
- package/templates/blank/README.md +27 -2
- package/templates/blank/commentary.txt +5 -0
- package/templates/blank/screens/edit.js +38 -17
- package/templates/blank/screens/instructor.js +20 -8
- package/templates/blank/screens/learn.js +151 -13
- package/templates/blank/styles.css +171 -0
- package/templates/blank/template.json +2 -2
- package/templates/quiz/README.md +2 -2
- package/templates/quiz/core/editor.d.ts +2 -0
- package/templates/quiz/core/editor.js +16 -6
- package/templates/quiz/core/model.js +1 -1
- package/templates/quiz/screens/edit.js +117 -24
- package/templates/quiz/styles.css +86 -12
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/edit.d.ts +4 -0
- package/templates/quiz/ui/templates/edit.js +46 -10
- package/templates/quiz/ui/templates/page.js +1 -2
- package/templates/quiz/ui/templates/text.js +10 -7
- package/templates/quiz/ui/texts.js +13 -9
|
@@ -0,0 +1,1062 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Elice Content 내용 편집기 · 템플릿이 제공하는 키트 (이 파일은 고치지 마세요)
|
|
3
|
+
*
|
|
4
|
+
* 편집 화면에서 내용(JSON)을 **폼 보기**(칸을 값에서 만들어 줌) · **코드 보기**(JSON 글)로 고친다.
|
|
5
|
+
* 저장 버튼 · 저장 문구 · 나가기 경고는 useSave가 한다: 이 편집기는 getContent · validate만 준다.
|
|
6
|
+
*
|
|
7
|
+
* import { start } from '../lib/elice-content.js';
|
|
8
|
+
* import { useContentEditor } from '../lib/elice-content-editor.js';
|
|
9
|
+
* const app = await start({ screen: 'edit' });
|
|
10
|
+
* const editor = useContentEditor(app, { initial: SAMPLE, schema: SCHEMA });
|
|
11
|
+
* app.useSave({ getContent: editor.getContent, validate: editor.validate });
|
|
12
|
+
*
|
|
13
|
+
* 저장한 내용(app.content)이 없으면 initial(견본)로 시작한다. 내용은 학생에게도 내려가므로 정답은 넣지 않는다.
|
|
14
|
+
*
|
|
15
|
+
* 스키마(선택, JSON Schema를 줄인 일반 객체): 이름마다 칸 하나
|
|
16
|
+
* { title: { label: '제목', required: true },
|
|
17
|
+
* items: { label: '항목', min: 2, max: 12,
|
|
18
|
+
* item: { name: { label: '이름' }, value: { label: '값', type: 'number', required: true } } } }
|
|
19
|
+
* 칸: label · type(string · number · boolean · object · array) · required · min · max(숫자 범위, 목록은 개수) ·
|
|
20
|
+
* multiline(여러 줄) · enum(고르기) · hint(도움말) · item(목록 항목) · fields(묶음 안 칸, 이름 → 칸)
|
|
21
|
+
* 스키마가 없으면 이름은 키, 종류는 initial 값에서 정한다. 목록 새 항목은 item(없으면 첫 항목) 모양의 빈 값.
|
|
22
|
+
*
|
|
23
|
+
* 화면 코드에는 키트(elice-content.js)만 있어도 되지만, 편집 화면만 이 파일을 부른다:
|
|
24
|
+
* build가 화면마다 코드를 묶으므로 학생 화면 묶음에는 이 편집기가 들어가지 않는다.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const NODE_KEYS = new Set([
|
|
28
|
+
'type',
|
|
29
|
+
'label',
|
|
30
|
+
'required',
|
|
31
|
+
'min',
|
|
32
|
+
'max',
|
|
33
|
+
'multiline',
|
|
34
|
+
'enum',
|
|
35
|
+
'hint',
|
|
36
|
+
'item',
|
|
37
|
+
'fields',
|
|
38
|
+
'placeholder',
|
|
39
|
+
]);
|
|
40
|
+
/** 글이 이보다 길거나 줄바꿈이 있으면 여러 줄 칸 */
|
|
41
|
+
const LONG_TEXT = 60;
|
|
42
|
+
/** 삭제 되돌리기 알림이 떠 있는 시간 */
|
|
43
|
+
export const UNDO_MS = 6000;
|
|
44
|
+
|
|
45
|
+
const isObj = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
46
|
+
const clone = v => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
47
|
+
|
|
48
|
+
/** 값의 종류: string · number · boolean · object · array (null · undefined는 모름) */
|
|
49
|
+
export function typeOf(v) {
|
|
50
|
+
if (Array.isArray(v)) return 'array';
|
|
51
|
+
if (v === null || v === undefined) return undefined;
|
|
52
|
+
const t = typeof v;
|
|
53
|
+
if (t === 'string' || t === 'number' || t === 'boolean') return t;
|
|
54
|
+
return t === 'object' ? 'object' : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 스키마 칸을 { type, fields, item, … } 모양으로. 이름 → 칸 묶음({ name: {…}, value: {…} })이면 객체 칸.
|
|
59
|
+
* 칸 속성(label · type …)만 있으면 칸 하나로 본다 (내용 이름이 칸 속성과 같으면 fields로 감싸 쓴다)
|
|
60
|
+
*/
|
|
61
|
+
export function asNode(s) {
|
|
62
|
+
if (!isObj(s)) return {};
|
|
63
|
+
const keys = Object.keys(s);
|
|
64
|
+
if (keys.length > 0 && !keys.every(k => NODE_KEYS.has(k))) return { type: 'object', fields: s };
|
|
65
|
+
return s;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 값에서 스키마: 이름은 키, 종류는 값, 목록 항목은 첫 항목 모양 */
|
|
69
|
+
export function inferSchema(value) {
|
|
70
|
+
const type = typeOf(value);
|
|
71
|
+
if (type === 'object')
|
|
72
|
+
return {
|
|
73
|
+
type,
|
|
74
|
+
fields: Object.fromEntries(Object.entries(value).map(([k, v]) => [k, inferSchema(v)])),
|
|
75
|
+
};
|
|
76
|
+
if (type === 'array') return value.length > 0 ? { type, item: inferSchema(value[0]) } : { type };
|
|
77
|
+
return type ? { type } : {};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 작성자 스키마에 값에서 정한 것을 더한다 (작성자 것이 먼저, 칸 순서도 작성자 순서 먼저) */
|
|
81
|
+
export function mergeSchema(user, inferred) {
|
|
82
|
+
const u = asNode(user);
|
|
83
|
+
const i = asNode(inferred);
|
|
84
|
+
const out = { ...i, ...u };
|
|
85
|
+
const type = u.type ?? i.type;
|
|
86
|
+
if (type) out.type = type;
|
|
87
|
+
if (u.fields || i.fields) {
|
|
88
|
+
const keys = [...new Set([...Object.keys(u.fields ?? {}), ...Object.keys(i.fields ?? {})])];
|
|
89
|
+
out.fields = Object.fromEntries(keys.map(k => [k, mergeSchema(u.fields?.[k], i.fields?.[k])]));
|
|
90
|
+
out.type ??= 'object';
|
|
91
|
+
}
|
|
92
|
+
if (u.item || i.item) {
|
|
93
|
+
out.item = mergeSchema(u.item, i.item);
|
|
94
|
+
out.type ??= 'array';
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 목록에 더할 새 항목: 스키마 모양의 빈 값. 글 '' · 켜고 끄기 false · 고르기는 첫 값 · 목록 [] (min이면 그만큼).
|
|
101
|
+
* 숫자는 필수면 null(비워 두어 입력하게), 아니면 min 또는 0
|
|
102
|
+
*/
|
|
103
|
+
export function emptyValue(node) {
|
|
104
|
+
const n = asNode(node);
|
|
105
|
+
if (Array.isArray(n.enum) && n.enum.length > 0) return n.enum[0];
|
|
106
|
+
switch (n.type) {
|
|
107
|
+
case 'number':
|
|
108
|
+
return n.required ? null : typeof n.min === 'number' ? n.min : 0;
|
|
109
|
+
case 'boolean':
|
|
110
|
+
return false;
|
|
111
|
+
case 'object':
|
|
112
|
+
return Object.fromEntries(Object.entries(n.fields ?? {}).map(([k, f]) => [k, emptyValue(f)]));
|
|
113
|
+
case 'array':
|
|
114
|
+
return n.item ? Array.from({ length: n.min ?? 0 }, () => emptyValue(n.item)) : [];
|
|
115
|
+
default:
|
|
116
|
+
return '';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 경로 잇기: items → items[2] → items[2].value */
|
|
121
|
+
export const joinPath = (base, key) =>
|
|
122
|
+
typeof key === 'number' ? `${base}[${key}]` : base ? `${base}.${key}` : String(key);
|
|
123
|
+
|
|
124
|
+
const TYPE_MESSAGES = {
|
|
125
|
+
string: '글자여야 합니다',
|
|
126
|
+
number: '숫자여야 합니다',
|
|
127
|
+
boolean: 'true 또는 false여야 합니다',
|
|
128
|
+
object: '{ … } 묶음이어야 합니다',
|
|
129
|
+
array: '[ … ] 목록이어야 합니다',
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 스키마로 검사. 문제마다 { path, message, kind }: kind 'type'은 모양이 달라 폼으로 보일 수 없음,
|
|
134
|
+
* 'rule'은 필수 · 범위 · 개수처럼 폼에서 고치면 되는 것
|
|
135
|
+
* @returns {{ path: string, message: string, kind: 'type' | 'rule' }[]}
|
|
136
|
+
*/
|
|
137
|
+
export function validateContent(value, schema, path = '') {
|
|
138
|
+
const out = [];
|
|
139
|
+
check(value, asNode(schema), path, out);
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function check(value, n, path, out) {
|
|
144
|
+
const push = (message, kind = 'rule') => out.push({ path, message, kind });
|
|
145
|
+
if (value === undefined || value === null) {
|
|
146
|
+
if (n.required) push('입력해 주세요');
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const type = n.type ?? (n.fields ? 'object' : n.item ? 'array' : undefined);
|
|
150
|
+
const actual = typeOf(value);
|
|
151
|
+
if (type && actual !== type) {
|
|
152
|
+
push(TYPE_MESSAGES[type] ?? `${type}이어야 합니다`, 'type');
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (Array.isArray(n.enum) && !n.enum.includes(value))
|
|
156
|
+
push(`다음 중 하나여야 합니다: ${n.enum.join(', ')}`);
|
|
157
|
+
if (actual === 'string' && n.required && value.trim() === '') push('입력해 주세요');
|
|
158
|
+
if (actual === 'number') {
|
|
159
|
+
if (typeof n.min === 'number' && value < n.min) push(`${n.min} 이상이어야 합니다`);
|
|
160
|
+
if (typeof n.max === 'number' && value > n.max) push(`${n.max} 이하여야 합니다`);
|
|
161
|
+
}
|
|
162
|
+
if (actual === 'array') {
|
|
163
|
+
if (typeof n.min === 'number' && value.length < n.min) push(`${n.min}개 이상이어야 합니다`);
|
|
164
|
+
if (typeof n.max === 'number' && value.length > n.max) push(`${n.max}개 이하여야 합니다`);
|
|
165
|
+
const item = asNode(n.item);
|
|
166
|
+
value.forEach((v, i) => check(v, item, joinPath(path, i), out));
|
|
167
|
+
}
|
|
168
|
+
if (actual === 'object')
|
|
169
|
+
for (const [k, f] of Object.entries(n.fields ?? {}))
|
|
170
|
+
check(value[k], asNode(f), joinPath(path, k), out);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 경로를 사람이 읽는 이름으로: items[2].value → 항목 3 › 값 */
|
|
174
|
+
export function labelPath(schema, path) {
|
|
175
|
+
if (!path) return '내용';
|
|
176
|
+
const parts = [];
|
|
177
|
+
let n = asNode(schema);
|
|
178
|
+
for (const m of path.matchAll(/([^.[\]]+)|\[(\d+)\]/g)) {
|
|
179
|
+
if (m[2] !== undefined) {
|
|
180
|
+
const last = parts.pop() ?? '';
|
|
181
|
+
parts.push(`${last} ${Number(m[2]) + 1}`.trim());
|
|
182
|
+
n = asNode(n.item);
|
|
183
|
+
} else {
|
|
184
|
+
const f = asNode(n.fields?.[m[1]]);
|
|
185
|
+
parts.push(f.label ?? m[1]);
|
|
186
|
+
n = f;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return parts.join(' › ');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* JSON 글 읽기. 틀리면 위치(줄 · 칸, 1부터)와 이유를 한국어로 (브라우저마다 다른 JSON.parse 문구 대신)
|
|
194
|
+
* @returns {{ ok: true, value: unknown } | { ok: false, index: number, line: number, column: number, message: string }}
|
|
195
|
+
*/
|
|
196
|
+
export function parseJson(text) {
|
|
197
|
+
try {
|
|
198
|
+
return { ok: true, value: JSON.parse(text) };
|
|
199
|
+
} catch {
|
|
200
|
+
const { index, message } = findJsonError(text);
|
|
201
|
+
return { ok: false, index, ...lineColumn(text, index), message };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 글자 위치 → 줄 · 칸 (1부터) */
|
|
206
|
+
export function lineColumn(text, index) {
|
|
207
|
+
const before = text.slice(0, index);
|
|
208
|
+
const line = before.split('\n').length;
|
|
209
|
+
return { line, column: index - before.lastIndexOf('\n') };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const show = c => (c === '\n' ? '줄바꿈' : `'${c}'`);
|
|
213
|
+
const NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
|
|
214
|
+
|
|
215
|
+
/** 처음 틀린 곳 찾기 (JSON 문법만 따라가는 작은 읽개) */
|
|
216
|
+
function findJsonError(s) {
|
|
217
|
+
let i = 0;
|
|
218
|
+
const fail = (message, at = i) => {
|
|
219
|
+
throw { index: Math.min(at, s.length), message };
|
|
220
|
+
};
|
|
221
|
+
const ws = () => {
|
|
222
|
+
while (i < s.length && ' \t\n\r'.includes(s[i])) i++;
|
|
223
|
+
};
|
|
224
|
+
const string = () => {
|
|
225
|
+
const from = i++;
|
|
226
|
+
for (;;) {
|
|
227
|
+
const c = s[i];
|
|
228
|
+
if (c === undefined || c === '\n') fail('글자가 큰따옴표(")로 닫히지 않았습니다', from);
|
|
229
|
+
if (c === '"') {
|
|
230
|
+
i++;
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (c === '\\') {
|
|
234
|
+
const e = s[i + 1];
|
|
235
|
+
if (e === 'u' && /^[0-9a-fA-F]{4}$/.test(s.slice(i + 2, i + 6))) i += 6;
|
|
236
|
+
else if (e !== undefined && '"\\/bfnrt'.includes(e)) i += 2;
|
|
237
|
+
else fail('잘못된 \\ 표기입니다 (\\n · \\" · \\\\ 등만 씀)');
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (c < ' ') fail('글자 안의 탭 · 줄바꿈은 \\t · \\n으로 씁니다');
|
|
241
|
+
i++;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
const value = () => {
|
|
245
|
+
ws();
|
|
246
|
+
const c = s[i];
|
|
247
|
+
if (c === undefined)
|
|
248
|
+
fail(i === 0 ? '비어 있습니다. { }부터 써 주세요' : '값이 와야 하는데 글이 끝났습니다');
|
|
249
|
+
if (c === '{') return object();
|
|
250
|
+
if (c === '[') return array();
|
|
251
|
+
if (c === '"') return string();
|
|
252
|
+
if (c === '-' || (c >= '0' && c <= '9')) {
|
|
253
|
+
NUMBER.lastIndex = i;
|
|
254
|
+
const m = NUMBER.exec(s);
|
|
255
|
+
if (!m) fail('숫자 형식이 올바르지 않습니다');
|
|
256
|
+
i += m[0].length;
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
for (const w of ['true', 'false', 'null'])
|
|
260
|
+
if (s.startsWith(w, i)) {
|
|
261
|
+
i += w.length;
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (c === "'") fail('글자는 작은따옴표가 아니라 큰따옴표(")로 감쌉니다');
|
|
265
|
+
fail(`값이 올 자리에 ${show(c)}가 있습니다 (글자는 "…"로 감쌉니다)`);
|
|
266
|
+
};
|
|
267
|
+
const list = (close, item) => {
|
|
268
|
+
i++;
|
|
269
|
+
ws();
|
|
270
|
+
if (s[i] === close) {
|
|
271
|
+
i++;
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
for (;;) {
|
|
275
|
+
item();
|
|
276
|
+
ws();
|
|
277
|
+
const c = s[i];
|
|
278
|
+
if (c === ',') {
|
|
279
|
+
const comma = i++;
|
|
280
|
+
ws();
|
|
281
|
+
if (s[i] === ',') fail('쉼표(,)가 겹쳤습니다');
|
|
282
|
+
if (s[i] === close) fail('마지막 항목 뒤에는 쉼표(,)를 쓰지 않습니다', comma);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (c === close) {
|
|
286
|
+
i++;
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (c === undefined) fail(`${close}로 닫히지 않았습니다`);
|
|
290
|
+
fail(`쉼표(,)나 ${close}가 와야 합니다`);
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const object = () =>
|
|
294
|
+
list('}', () => {
|
|
295
|
+
ws();
|
|
296
|
+
if (s[i] !== '"')
|
|
297
|
+
fail(
|
|
298
|
+
s[i] === undefined
|
|
299
|
+
? '}로 닫히지 않았습니다'
|
|
300
|
+
: '이름은 큰따옴표(")로 감싸야 합니다 ("이름": 값)'
|
|
301
|
+
);
|
|
302
|
+
string();
|
|
303
|
+
ws();
|
|
304
|
+
if (s[i] !== ':') fail('이름 뒤에 콜론(:)이 와야 합니다');
|
|
305
|
+
i++;
|
|
306
|
+
value();
|
|
307
|
+
});
|
|
308
|
+
const array = () => list(']', value);
|
|
309
|
+
try {
|
|
310
|
+
value();
|
|
311
|
+
ws();
|
|
312
|
+
if (i < s.length) fail('내용이 끝난 뒤에 글자가 더 있습니다');
|
|
313
|
+
} catch (e) {
|
|
314
|
+
if (e && typeof e.index === 'number') return e;
|
|
315
|
+
throw e;
|
|
316
|
+
}
|
|
317
|
+
return { index: 0, message: 'JSON 형식이 올바르지 않습니다' };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** 코드 보기 색: 이름 · 글자 · 숫자 · true/false/null · 괄호 */
|
|
321
|
+
const TOKEN =
|
|
322
|
+
/("(?:[^"\\\n]|\\.)*"?)(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b|([{}[\],])/g;
|
|
323
|
+
|
|
324
|
+
/** JSON 글 → 색칠한 노드들 (innerHTML 없이). errorAt이 있으면 그 글자를 표시 */
|
|
325
|
+
export function highlightJson(text, errorAt) {
|
|
326
|
+
const frag = document.createDocumentFragment();
|
|
327
|
+
const paint = part => {
|
|
328
|
+
let last = 0;
|
|
329
|
+
for (const m of part.matchAll(TOKEN)) {
|
|
330
|
+
if (m.index > last) frag.append(part.slice(last, m.index));
|
|
331
|
+
const [, str, colon, num, lit, punc] = m;
|
|
332
|
+
const span = (cls, t) => frag.append(h('span', { className: cls, textContent: t }));
|
|
333
|
+
if (str !== undefined) {
|
|
334
|
+
span(colon ? 'ec-json-key' : 'ec-json-str', str);
|
|
335
|
+
if (colon) frag.append(colon);
|
|
336
|
+
} else if (num !== undefined) span('ec-json-num', num);
|
|
337
|
+
else if (lit !== undefined) span('ec-json-lit', lit);
|
|
338
|
+
else if (punc !== undefined) span('ec-json-punc', punc);
|
|
339
|
+
last = m.index + m[0].length;
|
|
340
|
+
}
|
|
341
|
+
if (last < part.length) frag.append(part.slice(last));
|
|
342
|
+
};
|
|
343
|
+
if (typeof errorAt === 'number' && errorAt >= 0) {
|
|
344
|
+
paint(text.slice(0, errorAt));
|
|
345
|
+
const c = text[errorAt];
|
|
346
|
+
// 줄 끝 · 글 끝이면 빈칸에 표시 (줄바꿈은 그대로 둔다)
|
|
347
|
+
frag.append(h('mark', { className: 'ec-json-bad', textContent: !c || c === '\n' ? ' ' : c }));
|
|
348
|
+
if (c === '\n') frag.append('\n');
|
|
349
|
+
paint(text.slice(errorAt + 1));
|
|
350
|
+
} else paint(text);
|
|
351
|
+
// 마지막 빈 줄도 높이를 차지하게
|
|
352
|
+
frag.append('\n');
|
|
353
|
+
return frag;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** 목록 안에서 from 항목을 to 자리로 (제자리 · 범위 밖이면 false) */
|
|
357
|
+
export function moveItem(list, from, to) {
|
|
358
|
+
if (to === from || to < 0 || to >= list.length || from < 0 || from >= list.length) return false;
|
|
359
|
+
const [item] = list.splice(from, 1);
|
|
360
|
+
list.splice(to, 0, item);
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const h = (tag, props = {}) => Object.assign(document.createElement(tag), props);
|
|
365
|
+
/** 화면 읽기 프로그램에서 숨김 */
|
|
366
|
+
function hidden$(el) {
|
|
367
|
+
el.setAttribute('aria-hidden', 'true');
|
|
368
|
+
return el;
|
|
369
|
+
}
|
|
370
|
+
/** 선택자 "…" 안에 넣을 값 (경로의 " · \\만 막으면 됨) */
|
|
371
|
+
const q = s => String(s).replace(/["\\]/g, '\\$&');
|
|
372
|
+
|
|
373
|
+
const svg = (paths, size, width) => {
|
|
374
|
+
const ns = 'http://www.w3.org/2000/svg';
|
|
375
|
+
const el = document.createElementNS(ns, 'svg');
|
|
376
|
+
for (const [k, v] of Object.entries({
|
|
377
|
+
viewBox: '0 0 24 24',
|
|
378
|
+
width: size,
|
|
379
|
+
height: size,
|
|
380
|
+
fill: 'none',
|
|
381
|
+
stroke: 'currentColor',
|
|
382
|
+
'stroke-width': width,
|
|
383
|
+
'stroke-linecap': 'round',
|
|
384
|
+
'stroke-linejoin': 'round',
|
|
385
|
+
'aria-hidden': 'true',
|
|
386
|
+
}))
|
|
387
|
+
el.setAttribute(k, String(v));
|
|
388
|
+
for (const [tag, attrs] of paths) {
|
|
389
|
+
const p = document.createElementNS(ns, tag);
|
|
390
|
+
for (const [k, v] of Object.entries(attrs)) p.setAttribute(k, String(v));
|
|
391
|
+
el.append(p);
|
|
392
|
+
}
|
|
393
|
+
return el;
|
|
394
|
+
};
|
|
395
|
+
/** 아이콘 (개발 가이드 5 UI 패턴): 줄 하나 빼기는 빨간 ✕, 카드 삭제는 휴지통 */
|
|
396
|
+
const icons = {
|
|
397
|
+
xmark: () => svg([['path', { d: 'M6 6l12 12M18 6L6 18' }]], 18, 2),
|
|
398
|
+
trash: () =>
|
|
399
|
+
svg(
|
|
400
|
+
[
|
|
401
|
+
[
|
|
402
|
+
'path',
|
|
403
|
+
{ d: 'M4 7h16M10 11v6M14 11v6M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2l1-12M9 7V4h6v3' },
|
|
404
|
+
],
|
|
405
|
+
],
|
|
406
|
+
18,
|
|
407
|
+
2
|
|
408
|
+
),
|
|
409
|
+
up: () => svg([['path', { d: 'M6 15l6-6 6 6' }]], 20, 2),
|
|
410
|
+
down: () => svg([['path', { d: 'M6 9l6 6 6-6' }]], 20, 2),
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
let uid = 0;
|
|
414
|
+
const nextId = () => `ec-json-${++uid}`;
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* @typedef {object} ContentEditorOptions
|
|
418
|
+
* @property {Record<string, unknown>} [initial] 저장한 내용이 없을 때 시작할 견본 (정답 넣지 않음)
|
|
419
|
+
* @property {Record<string, unknown>} [schema] 칸 이름 · 종류 · 필수 · 범위 (위 머리 주석)
|
|
420
|
+
* @property {(content: Record<string, unknown>) => true | string} [validate] 스키마 다음에 할 검사
|
|
421
|
+
* @property {Element} [root] 편집기를 그릴 곳 (기본 #app, 안을 비우고 그림)
|
|
422
|
+
*/
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 편집 화면의 JSON 내용 편집기. 돌려준 getContent · validate를 useSave에 넘긴다
|
|
426
|
+
* @param {{ screen: string, hasContent: boolean, content: Record<string, unknown> }} app start()가 준 app
|
|
427
|
+
* @param {ContentEditorOptions} [opts]
|
|
428
|
+
*/
|
|
429
|
+
export function useContentEditor(app, opts = {}) {
|
|
430
|
+
if (app.screen !== 'edit')
|
|
431
|
+
throw new Error('useContentEditor는 편집 화면(screen: edit)에서만 씁니다.');
|
|
432
|
+
const area = opts.root ?? document.getElementById('app') ?? document.body;
|
|
433
|
+
const initial = isObj(opts.initial) ? opts.initial : {};
|
|
434
|
+
const fromSample = !app.hasContent;
|
|
435
|
+
let value = clone(fromSample ? initial : app.content);
|
|
436
|
+
// 종류는 견본에서 정한다: 코드 보기에서 숫자 칸에 글자를 넣으면 잡는다
|
|
437
|
+
const schema = mergeSchema(opts.schema, inferSchema(initial));
|
|
438
|
+
schema.type = 'object';
|
|
439
|
+
let view = 'form';
|
|
440
|
+
/** 삭제 되돌리기 { list, index, item, path, timer } */
|
|
441
|
+
let undo = null;
|
|
442
|
+
/** 코드 보기로 바꿀 때 쓴 글 (그대로면 폼을 다시 그리지 않는다) */
|
|
443
|
+
let shownText = '';
|
|
444
|
+
|
|
445
|
+
const editor = h('section', { className: 'ec-json' });
|
|
446
|
+
const note = h('p', {
|
|
447
|
+
className: 'ec-json-note',
|
|
448
|
+
textContent:
|
|
449
|
+
'아직 저장한 내용이 없어 견본으로 시작합니다. 고쳐서 저장하면 학생 화면에 보입니다.',
|
|
450
|
+
hidden: !fromSample,
|
|
451
|
+
});
|
|
452
|
+
note.setAttribute('role', 'note');
|
|
453
|
+
|
|
454
|
+
// 보기 바꾸기 (탭)
|
|
455
|
+
const tabs = h('div', { className: 'ec-json-tabs' });
|
|
456
|
+
tabs.setAttribute('role', 'tablist');
|
|
457
|
+
tabs.setAttribute('aria-label', '편집 방식');
|
|
458
|
+
const formPanel = h('div', { className: 'ec-json-form', id: nextId() });
|
|
459
|
+
const codePanel = h('div', { className: 'ec-json-code-view', id: nextId(), hidden: true });
|
|
460
|
+
const tab = (name, text, panel) => {
|
|
461
|
+
const b = h('button', { type: 'button', textContent: text, id: nextId() });
|
|
462
|
+
b.setAttribute('role', 'tab');
|
|
463
|
+
b.setAttribute('aria-controls', panel.id);
|
|
464
|
+
panel.setAttribute('role', 'tabpanel');
|
|
465
|
+
panel.setAttribute('aria-labelledby', b.id);
|
|
466
|
+
b.addEventListener('click', () => switchTo(name));
|
|
467
|
+
b.addEventListener('keydown', e => {
|
|
468
|
+
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
|
469
|
+
e.preventDefault();
|
|
470
|
+
const other = name === 'form' ? 'code' : 'form';
|
|
471
|
+
if (switchTo(other)) tabButtons[other].focus();
|
|
472
|
+
});
|
|
473
|
+
return b;
|
|
474
|
+
};
|
|
475
|
+
const tabButtons = {
|
|
476
|
+
form: tab('form', '폼 보기', formPanel),
|
|
477
|
+
code: tab('code', '코드 보기', codePanel),
|
|
478
|
+
};
|
|
479
|
+
tabs.append(tabButtons.form, tabButtons.code);
|
|
480
|
+
|
|
481
|
+
// 코드 보기: 글 칸 위에 색칠한 글을 겹친다 (글 칸 글자는 투명, 커서만 보임)
|
|
482
|
+
const toolbar = h('div', { className: 'ec-json-toolbar' });
|
|
483
|
+
const format = h('button', { type: 'button', className: 'ec-text-button', textContent: '정렬' });
|
|
484
|
+
format.title = '들여쓰기를 맞춥니다';
|
|
485
|
+
const status = h('p', { className: 'ec-json-status' });
|
|
486
|
+
status.setAttribute('role', 'status');
|
|
487
|
+
status.dataset.ecQuiet = '';
|
|
488
|
+
const jump = h('button', {
|
|
489
|
+
type: 'button',
|
|
490
|
+
className: 'ec-text-button',
|
|
491
|
+
textContent: '오류 위치로',
|
|
492
|
+
hidden: true,
|
|
493
|
+
});
|
|
494
|
+
toolbar.append(format, status, jump);
|
|
495
|
+
const codeBox = h('div', { className: 'ec-json-code' });
|
|
496
|
+
const pre = h('pre', { className: 'ec-json-highlight' });
|
|
497
|
+
pre.setAttribute('aria-hidden', 'true');
|
|
498
|
+
pre.dataset.ecQuiet = '';
|
|
499
|
+
const code = h('textarea', { spellcheck: false, autocapitalize: 'off', autocomplete: 'off' });
|
|
500
|
+
code.setAttribute('wrap', 'off');
|
|
501
|
+
code.setAttribute('aria-label', '내용 JSON');
|
|
502
|
+
code.setAttribute('aria-describedby', (status.id = nextId()));
|
|
503
|
+
codeBox.append(pre, code);
|
|
504
|
+
codePanel.append(toolbar, codeBox);
|
|
505
|
+
|
|
506
|
+
editor.append(note, tabs, formPanel, codePanel);
|
|
507
|
+
area.replaceChildren(editor);
|
|
508
|
+
|
|
509
|
+
// ---------- 코드 보기 ----------
|
|
510
|
+
let errorAt = -1;
|
|
511
|
+
let paintQueued = false;
|
|
512
|
+
const paintCode = () => {
|
|
513
|
+
paintQueued = false;
|
|
514
|
+
pre.replaceChildren(highlightJson(code.value, errorAt >= 0 ? errorAt : undefined));
|
|
515
|
+
};
|
|
516
|
+
const queuePaint = () => {
|
|
517
|
+
if (paintQueued) return;
|
|
518
|
+
paintQueued = true;
|
|
519
|
+
(globalThis.requestAnimationFrame ?? setTimeout)(paintCode);
|
|
520
|
+
};
|
|
521
|
+
/** 코드 글 검사: 결과를 상태 줄에 보이고 { parsed, problems } */
|
|
522
|
+
const checkCode = () => {
|
|
523
|
+
const r = parseJson(code.value);
|
|
524
|
+
if (!r.ok) {
|
|
525
|
+
errorAt = r.index;
|
|
526
|
+
setStatus(`${r.line}줄 ${r.column}칸: ${r.message}`, true);
|
|
527
|
+
jump.hidden = false;
|
|
528
|
+
return { parsed: r, problems: [] };
|
|
529
|
+
}
|
|
530
|
+
errorAt = -1;
|
|
531
|
+
jump.hidden = true;
|
|
532
|
+
const problems = isObj(r.value)
|
|
533
|
+
? validateContent(r.value, schema)
|
|
534
|
+
: [{ path: '', message: '{ … } 묶음이어야 합니다', kind: 'type' }];
|
|
535
|
+
if (problems.length > 0)
|
|
536
|
+
setStatus(
|
|
537
|
+
problems
|
|
538
|
+
.slice(0, 3)
|
|
539
|
+
.map(p => `${p.path || '내용'}: ${p.message}`)
|
|
540
|
+
.join(' · ') + more(problems, 3),
|
|
541
|
+
true
|
|
542
|
+
);
|
|
543
|
+
else setStatus('올바른 JSON입니다.', false);
|
|
544
|
+
return { parsed: r, problems };
|
|
545
|
+
};
|
|
546
|
+
const setStatus = (text, bad) => {
|
|
547
|
+
status.textContent = text;
|
|
548
|
+
status.classList.toggle('ec-error', bad);
|
|
549
|
+
};
|
|
550
|
+
const goToError = () => {
|
|
551
|
+
if (errorAt < 0) return;
|
|
552
|
+
code.focus();
|
|
553
|
+
code.setSelectionRange(errorAt, Math.min(errorAt + 1, code.value.length));
|
|
554
|
+
};
|
|
555
|
+
code.addEventListener('input', () => {
|
|
556
|
+
checkCode();
|
|
557
|
+
queuePaint();
|
|
558
|
+
});
|
|
559
|
+
// 전체를 바꿔 붙여 넣은 올바른 JSON은 바로 정렬
|
|
560
|
+
code.addEventListener('paste', () => {
|
|
561
|
+
const whole = code.selectionStart === 0 && code.selectionEnd === code.value.length;
|
|
562
|
+
if (!whole) return;
|
|
563
|
+
setTimeout(() => {
|
|
564
|
+
const r = parseJson(code.value);
|
|
565
|
+
if (r.ok) setCode(JSON.stringify(r.value, null, 2));
|
|
566
|
+
});
|
|
567
|
+
});
|
|
568
|
+
format.addEventListener('click', () => {
|
|
569
|
+
const r = parseJson(code.value);
|
|
570
|
+
if (r.ok) setCode(JSON.stringify(r.value, null, 2));
|
|
571
|
+
else {
|
|
572
|
+
checkCode();
|
|
573
|
+
paintCode();
|
|
574
|
+
goToError();
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
jump.addEventListener('click', goToError);
|
|
578
|
+
const setCode = text => {
|
|
579
|
+
code.value = text;
|
|
580
|
+
checkCode();
|
|
581
|
+
paintCode();
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
/** 보기 바꾸기. 코드 → 폼은 JSON이 올바를 때만 (틀리면 코드 보기에 남고 false) */
|
|
585
|
+
function switchTo(next) {
|
|
586
|
+
if (next === view) return true;
|
|
587
|
+
if (next === 'code') {
|
|
588
|
+
shownText = JSON.stringify(value, null, 2);
|
|
589
|
+
setCode(shownText);
|
|
590
|
+
} else {
|
|
591
|
+
const { parsed, problems } = checkCode();
|
|
592
|
+
paintCode();
|
|
593
|
+
if (!parsed.ok) {
|
|
594
|
+
setStatus(`${status.textContent} · 고쳐야 폼 보기로 바꿀 수 있습니다.`, true);
|
|
595
|
+
goToError();
|
|
596
|
+
return false;
|
|
597
|
+
}
|
|
598
|
+
const shape = problems.filter(p => p.kind === 'type');
|
|
599
|
+
if (shape.length > 0) {
|
|
600
|
+
setStatus(
|
|
601
|
+
`${shape.map(p => `${p.path || '내용'}: ${p.message}`).join(' · ')} · 고쳐야 폼 보기로 바꿀 수 있습니다.`,
|
|
602
|
+
true
|
|
603
|
+
);
|
|
604
|
+
code.focus();
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
if (code.value !== shownText) {
|
|
608
|
+
value = parsed.value;
|
|
609
|
+
dropUndo();
|
|
610
|
+
renderForm();
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
view = next;
|
|
614
|
+
for (const [name, b] of Object.entries(tabButtons)) {
|
|
615
|
+
const on = name === view;
|
|
616
|
+
b.setAttribute('aria-selected', String(on));
|
|
617
|
+
b.tabIndex = on ? 0 : -1;
|
|
618
|
+
}
|
|
619
|
+
formPanel.hidden = view !== 'form';
|
|
620
|
+
codePanel.hidden = view !== 'code';
|
|
621
|
+
return true;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// ---------- 폼 보기 ----------
|
|
625
|
+
/** 다시 그린 뒤 초점을 둘 곳 (data-path · data-sort 값) */
|
|
626
|
+
let focusNext = null;
|
|
627
|
+
|
|
628
|
+
function renderForm() {
|
|
629
|
+
const active = document.activeElement;
|
|
630
|
+
const keep =
|
|
631
|
+
focusNext ??
|
|
632
|
+
(active instanceof HTMLElement && formPanel.contains(active)
|
|
633
|
+
? active.dataset.path
|
|
634
|
+
? `[data-path="${q(active.dataset.path)}"]`
|
|
635
|
+
: active.dataset.sort
|
|
636
|
+
? `[data-sort="${q(active.dataset.sort)}"]`
|
|
637
|
+
: null
|
|
638
|
+
: null);
|
|
639
|
+
focusNext = null;
|
|
640
|
+
formPanel.replaceChildren(...fields(schema, value, ''));
|
|
641
|
+
if (keep) formPanel.querySelector(keep)?.focus();
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** 묶음(객체)의 칸들: 스키마 칸 먼저, 그다음 값에만 있는 키 */
|
|
645
|
+
function fields(node, obj, path) {
|
|
646
|
+
const n = asNode(node);
|
|
647
|
+
const keys = [...new Set([...Object.keys(n.fields ?? {}), ...Object.keys(obj)])];
|
|
648
|
+
return keys.map(k =>
|
|
649
|
+
control(
|
|
650
|
+
asNode(n.fields?.[k]),
|
|
651
|
+
obj[k],
|
|
652
|
+
v => (obj[k] = v),
|
|
653
|
+
joinPath(path, k),
|
|
654
|
+
asNode(n.fields?.[k]).label ?? k
|
|
655
|
+
)
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** 칸 하나: 값의 종류에 맞는 입력 */
|
|
660
|
+
function control(n, current, set, path, label) {
|
|
661
|
+
const type = n.type ?? typeOf(current) ?? (n.fields ? 'object' : n.item ? 'array' : 'string');
|
|
662
|
+
if (type === 'array') {
|
|
663
|
+
if (!Array.isArray(current)) set((current = []));
|
|
664
|
+
return list(n, current, path, label);
|
|
665
|
+
}
|
|
666
|
+
if (type === 'object') {
|
|
667
|
+
if (!isObj(current)) set((current = {}));
|
|
668
|
+
const group = h('fieldset', { className: 'ec-json-group' });
|
|
669
|
+
group.dataset.path = path;
|
|
670
|
+
group.append(h('legend', { textContent: label }));
|
|
671
|
+
if (n.hint) group.append(h('p', { className: 'ec-json-hint', textContent: n.hint }));
|
|
672
|
+
group.append(...fields(n, current, path));
|
|
673
|
+
return group;
|
|
674
|
+
}
|
|
675
|
+
const id = nextId();
|
|
676
|
+
const wrap = h('div', { className: 'ec-json-field' });
|
|
677
|
+
let input;
|
|
678
|
+
if (type === 'boolean') {
|
|
679
|
+
wrap.classList.add('ec-json-switch');
|
|
680
|
+
input = h('input', { type: 'checkbox', id, checked: current === true });
|
|
681
|
+
input.setAttribute('role', 'switch');
|
|
682
|
+
input.addEventListener('change', () => set(input.checked));
|
|
683
|
+
const l = h('label', { htmlFor: id, textContent: label });
|
|
684
|
+
wrap.append(input, l);
|
|
685
|
+
if (n.hint) wrap.append(h('p', { className: 'ec-json-hint', textContent: n.hint }));
|
|
686
|
+
input.dataset.path = path;
|
|
687
|
+
return wrap;
|
|
688
|
+
}
|
|
689
|
+
if (Array.isArray(n.enum)) {
|
|
690
|
+
input = h('select', { id });
|
|
691
|
+
for (const opt of n.enum)
|
|
692
|
+
input.append(h('option', { value: String(opt), textContent: String(opt) }));
|
|
693
|
+
input.value = String(current ?? '');
|
|
694
|
+
input.addEventListener('change', () => {
|
|
695
|
+
const picked = n.enum.find(o => String(o) === input.value);
|
|
696
|
+
set(picked);
|
|
697
|
+
});
|
|
698
|
+
} else if (type === 'number') {
|
|
699
|
+
input = h('input', { type: 'number', id, step: 'any', inputMode: 'decimal' });
|
|
700
|
+
if (typeof n.min === 'number') input.min = String(n.min);
|
|
701
|
+
if (typeof n.max === 'number') input.max = String(n.max);
|
|
702
|
+
input.value = typeof current === 'number' ? String(current) : '';
|
|
703
|
+
input.addEventListener('input', () => {
|
|
704
|
+
const raw = input.value.trim();
|
|
705
|
+
set(raw === '' ? null : Number(raw));
|
|
706
|
+
});
|
|
707
|
+
} else {
|
|
708
|
+
const text = typeof current === 'string' ? current : current == null ? '' : String(current);
|
|
709
|
+
const long = n.multiline === true || text.length > LONG_TEXT || text.includes('\n');
|
|
710
|
+
input = long ? h('textarea', { id, rows: 3 }) : h('input', { type: 'text', id });
|
|
711
|
+
input.value = text;
|
|
712
|
+
if (n.placeholder) input.placeholder = n.placeholder;
|
|
713
|
+
input.addEventListener('input', () => set(input.value));
|
|
714
|
+
}
|
|
715
|
+
input.dataset.path = path;
|
|
716
|
+
if (n.required) input.setAttribute('aria-required', 'true');
|
|
717
|
+
const l = h('label', { htmlFor: id, textContent: label });
|
|
718
|
+
if (n.required)
|
|
719
|
+
l.append(hidden$(h('span', { className: 'ec-json-required', textContent: ' *' })));
|
|
720
|
+
wrap.append(l);
|
|
721
|
+
if (n.hint) {
|
|
722
|
+
const hint = h('p', { className: 'ec-json-hint', textContent: n.hint, id: nextId() });
|
|
723
|
+
input.setAttribute('aria-describedby', hint.id);
|
|
724
|
+
wrap.append(hint);
|
|
725
|
+
}
|
|
726
|
+
wrap.append(input);
|
|
727
|
+
input.addEventListener('input', () => clearError(input));
|
|
728
|
+
input.addEventListener('change', () => clearError(input));
|
|
729
|
+
return wrap;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** 목록: 글 · 숫자 목록은 줄, 묶음 목록은 카드. 추가 · 삭제(되돌리기) · 끌어서 · 키보드로 순서 */
|
|
733
|
+
function list(n, arr, path, label) {
|
|
734
|
+
const itemNode = asNode(n.item ?? (arr.length > 0 ? inferSchema(arr[0]) : { type: 'string' }));
|
|
735
|
+
const itemType = itemNode.type ?? typeOf(arr[0]) ?? 'string';
|
|
736
|
+
const asCard = itemType === 'object' || itemType === 'array';
|
|
737
|
+
const min = typeof n.min === 'number' ? n.min : 0;
|
|
738
|
+
const max = typeof n.max === 'number' ? n.max : Infinity;
|
|
739
|
+
const box = h('fieldset', { className: 'ec-json-list' });
|
|
740
|
+
box.dataset.path = path;
|
|
741
|
+
const legend = h('legend', { textContent: label });
|
|
742
|
+
legend.append(h('span', { className: 'ec-json-count', textContent: ` ${arr.length}개` }));
|
|
743
|
+
box.append(legend);
|
|
744
|
+
if (n.hint) box.append(h('p', { className: 'ec-json-hint', textContent: n.hint }));
|
|
745
|
+
const rows = h('div', { className: asCard ? 'ec-json-cards' : 'ec-json-rows' });
|
|
746
|
+
const name = i => `${label} ${i + 1}`;
|
|
747
|
+
arr.forEach((item, i) => {
|
|
748
|
+
if (undo?.list === arr && undo.index === i) rows.append(undoNotice());
|
|
749
|
+
const row = asCard
|
|
750
|
+
? card(itemNode, arr, i, path, name(i), arr.length > min)
|
|
751
|
+
: line(itemNode, arr, i, path, name(i), arr.length > min);
|
|
752
|
+
rows.append(row);
|
|
753
|
+
});
|
|
754
|
+
if (undo?.list === arr && undo.index >= arr.length) rows.append(undoNotice());
|
|
755
|
+
box.append(rows);
|
|
756
|
+
|
|
757
|
+
// 최소 개수: 닿으면 늘 보이는 안내 (삭제 버튼이 꺼진 까닭)
|
|
758
|
+
if (min > 0 && arr.length <= min)
|
|
759
|
+
box.append(
|
|
760
|
+
h('p', {
|
|
761
|
+
className: arr.length < min ? 'ec-json-hint ec-error' : 'ec-json-hint',
|
|
762
|
+
textContent: `${min}개 이상이어야 합니다`,
|
|
763
|
+
})
|
|
764
|
+
);
|
|
765
|
+
const full = arr.length >= max;
|
|
766
|
+
const add = h('button', {
|
|
767
|
+
type: 'button',
|
|
768
|
+
className: 'ec-json-add',
|
|
769
|
+
textContent: `+ ${label} 추가`,
|
|
770
|
+
disabled: full,
|
|
771
|
+
});
|
|
772
|
+
add.dataset.path = `${path}+`;
|
|
773
|
+
if (full)
|
|
774
|
+
box.append(
|
|
775
|
+
h('p', { className: 'ec-json-hint', textContent: `최대 ${max}개까지 넣을 수 있습니다` })
|
|
776
|
+
);
|
|
777
|
+
add.addEventListener('click', () => {
|
|
778
|
+
const sample = n.item ? emptyValue(itemNode) : emptyValue(inferSchema(arr[0] ?? ''));
|
|
779
|
+
arr.push(sample);
|
|
780
|
+
dropUndo();
|
|
781
|
+
const at = q(joinPath(path, arr.length - 1));
|
|
782
|
+
focusNext = `[data-path="${at}"], [data-path^="${at}."]`;
|
|
783
|
+
renderForm();
|
|
784
|
+
});
|
|
785
|
+
box.append(add);
|
|
786
|
+
return box;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** 글 · 숫자 목록의 한 줄: 손잡이 → 번호 → 입력 → 빼기(✕) */
|
|
790
|
+
function line(itemNode, arr, i, path, name, canDelete) {
|
|
791
|
+
const row = h('div', { className: 'ec-json-row' });
|
|
792
|
+
row.dataset.role = 'row';
|
|
793
|
+
const handle = sortHandle(arr, i, path, name);
|
|
794
|
+
const marker = hidden$(h('span', { className: 'ec-json-no', textContent: String(i + 1) }));
|
|
795
|
+
const field = control(itemNode, arr[i], v => (arr[i] = v), joinPath(path, i), name);
|
|
796
|
+
field.classList.add('ec-json-inline');
|
|
797
|
+
// 줄 안에서는 라벨을 숨기고 aria로만
|
|
798
|
+
const label = field.querySelector('label');
|
|
799
|
+
if (label) label.className = 'ec-visually-hidden';
|
|
800
|
+
const del = h('button', {
|
|
801
|
+
type: 'button',
|
|
802
|
+
className: 'ec-icon-button ec-danger',
|
|
803
|
+
disabled: !canDelete,
|
|
804
|
+
});
|
|
805
|
+
del.setAttribute('aria-label', `${name} 삭제`);
|
|
806
|
+
if (!canDelete) del.title = '더 줄일 수 없습니다';
|
|
807
|
+
del.append(icons.xmark());
|
|
808
|
+
del.addEventListener('click', () => remove(arr, i, path));
|
|
809
|
+
row.append(handle, marker, field, del);
|
|
810
|
+
return row;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** 묶음 목록의 카드: 머리(손잡이 · 이름 · ↑ · ↓ · 휴지통) + 칸들 */
|
|
814
|
+
function card(itemNode, arr, i, path, name, canDelete) {
|
|
815
|
+
const item = arr[i];
|
|
816
|
+
const node = h('section', { className: 'ec-json-card' });
|
|
817
|
+
node.dataset.role = 'row';
|
|
818
|
+
const head = h('header', { className: 'ec-json-card-head' });
|
|
819
|
+
const title = h('strong', { textContent: name });
|
|
820
|
+
// 첫 글 칸 값을 곁들여 어느 항목인지 보이게 (예: 항목 2 · 금성)
|
|
821
|
+
const first = isObj(item)
|
|
822
|
+
? Object.values(item).find(v => typeof v === 'string' && v.trim())
|
|
823
|
+
: undefined;
|
|
824
|
+
if (first)
|
|
825
|
+
title.append(h('span', { className: 'ec-json-card-sub', textContent: ` · ${first}` }));
|
|
826
|
+
const btn = (icon, aria, disabled, onClick, cls = 'ec-icon-button') => {
|
|
827
|
+
const b = h('button', { type: 'button', className: cls, disabled });
|
|
828
|
+
b.setAttribute('aria-label', aria);
|
|
829
|
+
b.append(icon());
|
|
830
|
+
b.addEventListener('click', onClick);
|
|
831
|
+
return b;
|
|
832
|
+
};
|
|
833
|
+
const move = d => () => {
|
|
834
|
+
if (!moveItem(arr, i, i + d)) return;
|
|
835
|
+
dropUndo();
|
|
836
|
+
const same = `[data-move="${q(joinPath(path, i + d))}:${d}"]`;
|
|
837
|
+
focusNext = same;
|
|
838
|
+
renderForm();
|
|
839
|
+
// 끝에 닿아 그 버튼이 꺼졌으면 손잡이로
|
|
840
|
+
const f = formPanel.querySelector(same);
|
|
841
|
+
if (!f || f.disabled) formPanel.querySelector(`[data-sort="${q(path)}:${i + d}"]`)?.focus();
|
|
842
|
+
};
|
|
843
|
+
const up = btn(icons.up, `${name} 위로`, i === 0, move(-1));
|
|
844
|
+
up.dataset.move = `${joinPath(path, i)}:-1`;
|
|
845
|
+
const down = btn(icons.down, `${name} 아래로`, i === arr.length - 1, move(1));
|
|
846
|
+
down.dataset.move = `${joinPath(path, i)}:1`;
|
|
847
|
+
const del = btn(icons.trash, `${name} 삭제`, !canDelete, () => remove(arr, i, path));
|
|
848
|
+
if (!canDelete) del.title = '더 줄일 수 없습니다';
|
|
849
|
+
if (arr.length === 1) up.hidden = down.hidden = true;
|
|
850
|
+
head.append(sortHandle(arr, i, path, name), title, up, down, del);
|
|
851
|
+
node.append(head);
|
|
852
|
+
const body = h('div', { className: 'ec-json-card-body' });
|
|
853
|
+
if (isObj(item)) body.append(...fields(itemNode, item, joinPath(path, i)));
|
|
854
|
+
else body.append(control(itemNode, item, v => (arr[i] = v), joinPath(path, i), name));
|
|
855
|
+
node.append(body);
|
|
856
|
+
return node;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function remove(arr, i, path) {
|
|
860
|
+
const [item] = arr.splice(i, 1);
|
|
861
|
+
dropUndo();
|
|
862
|
+
undo = { list: arr, index: i, item, path };
|
|
863
|
+
undo.timer = setTimeout(expireUndo, UNDO_MS);
|
|
864
|
+
focusNext = '[data-role="undo"] button';
|
|
865
|
+
renderForm();
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** "항목을 삭제했습니다. 되돌리기" (지운 자리에, UNDO_MS 뒤 사라짐) */
|
|
869
|
+
function undoNotice() {
|
|
870
|
+
// 키트 공통 알림(.ec-notice, 퀴즈 편집 화면의 문항 되돌리기와 같은 모양)
|
|
871
|
+
const box = h('div', { className: 'ec-notice' });
|
|
872
|
+
box.dataset.role = 'undo';
|
|
873
|
+
box.setAttribute('role', 'status');
|
|
874
|
+
box.dataset.ecQuiet = '';
|
|
875
|
+
const back = h('button', {
|
|
876
|
+
type: 'button',
|
|
877
|
+
className: 'ec-text-button',
|
|
878
|
+
textContent: '되돌리기',
|
|
879
|
+
});
|
|
880
|
+
back.addEventListener('click', () => {
|
|
881
|
+
if (!undo) return;
|
|
882
|
+
const { list: arr, index, item, path } = undo;
|
|
883
|
+
arr.splice(Math.min(index, arr.length), 0, item);
|
|
884
|
+
dropUndo();
|
|
885
|
+
focusNext = `[data-sort="${q(path)}:${Math.min(index, arr.length - 1)}"]`;
|
|
886
|
+
renderForm();
|
|
887
|
+
});
|
|
888
|
+
box.append(h('span', { textContent: '항목을 삭제했습니다.' }), back);
|
|
889
|
+
if (undo) undo.element = box;
|
|
890
|
+
return box;
|
|
891
|
+
}
|
|
892
|
+
function expireUndo() {
|
|
893
|
+
if (!undo) return;
|
|
894
|
+
const box = undo.element;
|
|
895
|
+
const hadFocus = box?.contains(document.activeElement);
|
|
896
|
+
const sel = `[data-path="${q(undo.path)}+"]`;
|
|
897
|
+
undo = null;
|
|
898
|
+
// 지우지 않고 숨긴다 (저장 안 한 변경 표시가 다시 켜지지 않게)
|
|
899
|
+
if (box) box.hidden = true;
|
|
900
|
+
if (hadFocus) formPanel.querySelector(sel)?.focus();
|
|
901
|
+
}
|
|
902
|
+
function dropUndo() {
|
|
903
|
+
if (undo) clearTimeout(undo.timer);
|
|
904
|
+
undo = null;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* 끌어서 순서 바꾸는 손잡이 (마우스 · 터치 공용). 키보드: 손잡이에서 ↑ · ↓.
|
|
909
|
+
* 끄는 동안 다른 줄이 비켜 자리를 보여 준다 (끄는 줄에 data-dragging)
|
|
910
|
+
*/
|
|
911
|
+
function sortHandle(arr, i, path, name) {
|
|
912
|
+
const handle = h('button', { type: 'button', className: 'ec-json-handle', textContent: '⠿' });
|
|
913
|
+
handle.setAttribute('aria-label', `${name} 순서 바꾸기 (끌거나 ↑ · ↓ 키)`);
|
|
914
|
+
handle.title = '끌어서 순서 바꾸기';
|
|
915
|
+
handle.dataset.sort = `${path}:${i}`;
|
|
916
|
+
const go = (to, keyboard) => {
|
|
917
|
+
if (!moveItem(arr, i, to)) return;
|
|
918
|
+
dropUndo();
|
|
919
|
+
if (keyboard) focusNext = `[data-sort="${q(path)}:${to}"]`;
|
|
920
|
+
renderForm();
|
|
921
|
+
};
|
|
922
|
+
handle.addEventListener('keydown', e => {
|
|
923
|
+
const d = { ArrowUp: -1, ArrowDown: 1 }[e.key];
|
|
924
|
+
if (!d) return;
|
|
925
|
+
e.preventDefault();
|
|
926
|
+
go(i + d, true);
|
|
927
|
+
});
|
|
928
|
+
handle.addEventListener('pointerdown', down => {
|
|
929
|
+
if (down.button !== 0) return;
|
|
930
|
+
down.preventDefault();
|
|
931
|
+
const row = handle.closest('[data-role="row"]');
|
|
932
|
+
const rows = [...row.parentElement.querySelectorAll(':scope > [data-role="row"]')];
|
|
933
|
+
const rects = rows.map(r => r.getBoundingClientRect());
|
|
934
|
+
const at = rows.indexOf(row);
|
|
935
|
+
const step = rects.length > 1 ? Math.abs(rects[1].top - rects[0].top) : rects[0].height;
|
|
936
|
+
handle.setPointerCapture?.(down.pointerId);
|
|
937
|
+
row.dataset.dragging = '';
|
|
938
|
+
let to = at;
|
|
939
|
+
const onMove = e => {
|
|
940
|
+
const dy = e.clientY - down.clientY;
|
|
941
|
+
row.style.transform = `translateY(${dy}px)`;
|
|
942
|
+
const center = rects[at].top + rects[at].height / 2 + dy;
|
|
943
|
+
to = rects.filter((r, j) => j !== at && r.top + r.height / 2 < center).length;
|
|
944
|
+
rows.forEach((r, j) => {
|
|
945
|
+
if (j === at) return;
|
|
946
|
+
const shift = j > at && j <= to ? -step : j < at && j >= to ? step : 0;
|
|
947
|
+
r.style.transform = shift ? `translateY(${shift}px)` : '';
|
|
948
|
+
});
|
|
949
|
+
};
|
|
950
|
+
const end = e => {
|
|
951
|
+
handle.removeEventListener('pointermove', onMove);
|
|
952
|
+
handle.removeEventListener('pointerup', end);
|
|
953
|
+
handle.removeEventListener('pointercancel', end);
|
|
954
|
+
delete row.dataset.dragging;
|
|
955
|
+
for (const r of rows) r.style.transform = '';
|
|
956
|
+
if (e.type === 'pointerup') go(to, false);
|
|
957
|
+
};
|
|
958
|
+
handle.addEventListener('pointermove', onMove);
|
|
959
|
+
handle.addEventListener('pointerup', end);
|
|
960
|
+
handle.addEventListener('pointercancel', end);
|
|
961
|
+
});
|
|
962
|
+
return handle;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// ---------- 검사 표시 ----------
|
|
966
|
+
function clearError(input) {
|
|
967
|
+
input.removeAttribute('aria-invalid');
|
|
968
|
+
const msg = input.parentElement?.querySelector(':scope > .ec-json-error');
|
|
969
|
+
msg?.remove();
|
|
970
|
+
}
|
|
971
|
+
function clearErrors() {
|
|
972
|
+
for (const el of formPanel.querySelectorAll('[aria-invalid="true"]'))
|
|
973
|
+
el.removeAttribute('aria-invalid');
|
|
974
|
+
for (const el of formPanel.querySelectorAll('.ec-json-error')) el.remove();
|
|
975
|
+
}
|
|
976
|
+
/** 폼 보기에서 문제 칸에 표시하고 첫 칸에 초점 */
|
|
977
|
+
function markErrors(problems) {
|
|
978
|
+
clearErrors();
|
|
979
|
+
let first = null;
|
|
980
|
+
for (const p of problems) {
|
|
981
|
+
const target =
|
|
982
|
+
formPanel.querySelector(`[data-path="${q(p.path)}"]`) ??
|
|
983
|
+
formPanel.querySelector(`[data-path="${q(p.path)}+"]`);
|
|
984
|
+
if (!target) continue;
|
|
985
|
+
const msg = h('p', { className: 'ec-json-error ec-error', textContent: p.message });
|
|
986
|
+
msg.dataset.ecQuiet = '';
|
|
987
|
+
if (target.matches('fieldset')) target.append(msg);
|
|
988
|
+
else {
|
|
989
|
+
target.setAttribute('aria-invalid', 'true');
|
|
990
|
+
msg.id = nextId();
|
|
991
|
+
target.setAttribute('aria-errormessage', msg.id);
|
|
992
|
+
target.after(msg);
|
|
993
|
+
}
|
|
994
|
+
first ??= target.matches('fieldset')
|
|
995
|
+
? (target.querySelector(`[data-path="${q(p.path)}+"]`) ??
|
|
996
|
+
target.querySelector('input, select, textarea, button'))
|
|
997
|
+
: target;
|
|
998
|
+
}
|
|
999
|
+
first?.focus();
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const more = (list, shown) => (list.length > shown ? ` (외 ${list.length - shown}개)` : '');
|
|
1003
|
+
|
|
1004
|
+
const api = {
|
|
1005
|
+
element: editor,
|
|
1006
|
+
/** 지금 보기: 'form' · 'code' */
|
|
1007
|
+
get view() {
|
|
1008
|
+
return view;
|
|
1009
|
+
},
|
|
1010
|
+
/** 보기 바꾸기. 코드 → 폼은 JSON이 올바를 때만 (아니면 false) */
|
|
1011
|
+
showView: next => switchTo(next),
|
|
1012
|
+
/** 저장할 내용. 코드 보기에서 JSON이 틀리면 마지막으로 올바른 내용 (validate가 막음) */
|
|
1013
|
+
getContent() {
|
|
1014
|
+
if (view === 'code') {
|
|
1015
|
+
const r = parseJson(code.value);
|
|
1016
|
+
if (r.ok && isObj(r.value)) return r.value;
|
|
1017
|
+
}
|
|
1018
|
+
return clone(value);
|
|
1019
|
+
},
|
|
1020
|
+
/** 내용을 통째로 바꾼다 (폼 · 코드 모두 다시 그림) */
|
|
1021
|
+
setContent(next) {
|
|
1022
|
+
value = clone(isObj(next) ? next : {});
|
|
1023
|
+
dropUndo();
|
|
1024
|
+
renderForm();
|
|
1025
|
+
if (view === 'code') setCode((shownText = JSON.stringify(value, null, 2)));
|
|
1026
|
+
},
|
|
1027
|
+
/**
|
|
1028
|
+
* useSave에 넘길 검사: 코드 보기 JSON 오류(줄 · 칸) → 스키마(경로) → 작성자 validate.
|
|
1029
|
+
* 통과면 true, 아니면 보여 줄 문장 (폼 보기면 문제 칸에 초점)
|
|
1030
|
+
*/
|
|
1031
|
+
validate(content = api.getContent()) {
|
|
1032
|
+
if (view === 'code') {
|
|
1033
|
+
const { parsed } = checkCode();
|
|
1034
|
+
paintCode();
|
|
1035
|
+
if (!parsed.ok) return `코드 보기 ${parsed.line}줄 ${parsed.column}칸: ${parsed.message}`;
|
|
1036
|
+
}
|
|
1037
|
+
if (!isObj(content)) return '내용은 { … } 묶음이어야 합니다.';
|
|
1038
|
+
const problems = validateContent(content, schema);
|
|
1039
|
+
if (problems.length > 0) {
|
|
1040
|
+
const p = problems[0];
|
|
1041
|
+
if (view === 'form') {
|
|
1042
|
+
markErrors(problems);
|
|
1043
|
+
return `${labelPath(schema, p.path)}: ${p.message}${more(problems, 1)}`;
|
|
1044
|
+
}
|
|
1045
|
+
return `${p.path || '내용'}: ${p.message}${more(problems, 1)}`;
|
|
1046
|
+
}
|
|
1047
|
+
const extra = opts.validate ? opts.validate(content) : true;
|
|
1048
|
+
if (extra === true || extra === undefined) return true;
|
|
1049
|
+
return typeof extra === 'string' ? extra : '내용을 확인해 주세요.';
|
|
1050
|
+
},
|
|
1051
|
+
};
|
|
1052
|
+
// useSave({ getContent: editor.getContent, validate: editor.validate })로 떼어 넘겨도 되게
|
|
1053
|
+
api.getContent = api.getContent.bind(api);
|
|
1054
|
+
api.validate = api.validate.bind(api);
|
|
1055
|
+
|
|
1056
|
+
renderForm();
|
|
1057
|
+
switchTo('form');
|
|
1058
|
+
tabButtons.form.setAttribute('aria-selected', 'true');
|
|
1059
|
+
tabButtons.code.setAttribute('aria-selected', 'false');
|
|
1060
|
+
tabButtons.code.tabIndex = -1;
|
|
1061
|
+
return api;
|
|
1062
|
+
}
|