@libs-ui/components-preview-text-data 0.2.357-3 → 0.2.357-30
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 +406 -187
- package/editor/editor-completions.d.ts +8 -0
- package/editor/editor-forbidden.d.ts +8 -0
- package/editor/editor-height.d.ts +21 -0
- package/esm2022/editor/editor-completions.mjs +36 -0
- package/esm2022/editor/editor-forbidden.mjs +65 -0
- package/esm2022/editor/editor-height.mjs +136 -0
- package/esm2022/index.mjs +2 -1
- package/esm2022/linters/js-linter.mjs +348 -0
- package/esm2022/linters/json-linter.mjs +14 -0
- package/esm2022/linters/linter-shared.mjs +8 -0
- package/esm2022/linters/python-linter.mjs +52 -0
- package/esm2022/linters/sql-linter.mjs +34 -0
- package/esm2022/preview-text-data.component.mjs +109 -317
- package/esm2022/preview-text-data.define.mjs +42 -1
- package/esm2022/preview-text-data.type.mjs +2 -0
- package/esm2022/sql-format.define.mjs +364 -0
- package/fesm2022/libs-ui-components-preview-text-data.mjs +1191 -318
- package/fesm2022/libs-ui-components-preview-text-data.mjs.map +1 -1
- package/index.d.ts +1 -0
- package/linters/js-linter.d.ts +45 -0
- package/linters/json-linter.d.ts +4 -0
- package/linters/linter-shared.d.ts +3 -0
- package/linters/python-linter.d.ts +4 -0
- package/linters/sql-linter.d.ts +4 -0
- package/package.json +9 -7
- package/preview-text-data.component.d.ts +49 -31
- package/preview-text-data.define.d.ts +26 -0
- package/preview-text-data.type.d.ts +33 -0
- package/sql-format.define.d.ts +58 -0
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
2
|
import { signal, inject, DestroyRef, computed, input, model, output, viewChild, effect, Component, ChangeDetectionStrategy } from '@angular/core';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { lintGutter, linter } from '@codemirror/lint';
|
|
6
|
-
import { Compartment, Prec, EditorState, Transaction } from '@codemirror/state';
|
|
3
|
+
import { linter, lintGutter } from '@codemirror/lint';
|
|
4
|
+
import { EditorState, Transaction, Compartment, Prec } from '@codemirror/state';
|
|
7
5
|
import { EditorView, lineNumbers } from '@codemirror/view';
|
|
8
6
|
import { LibsUiComponentsButtonsButtonComponent } from '@libs-ui/components-buttons-button';
|
|
9
7
|
import { LibsUiComponentsDropdownComponent } from '@libs-ui/components-dropdown';
|
|
10
8
|
import { LibsUiNotificationService } from '@libs-ui/services-notification';
|
|
11
|
-
import { UtilsHttpParamsRequest, get } from '@libs-ui/utils';
|
|
12
9
|
import { basicSetup } from 'codemirror6';
|
|
13
10
|
import { returnListObject } from '@libs-ui/services-http-request';
|
|
11
|
+
import { UtilsHttpParamsRequest, get } from '@libs-ui/utils';
|
|
12
|
+
import { syntaxTree } from '@codemirror/language';
|
|
13
|
+
import { autocompletion } from '@codemirror/autocomplete';
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
16
|
* Danh sách các ngôn ngữ được hỗ trợ
|
|
@@ -154,6 +154,47 @@ const DEFAULT_SECURITY_PATTERNS = [
|
|
|
154
154
|
/document\.write\s*\(/i,
|
|
155
155
|
/window\.location\s*=/i,
|
|
156
156
|
];
|
|
157
|
+
/**
|
|
158
|
+
* Bộ pattern chặn mặc định cho ô soạn **SQL** — dùng với `[forbiddenPatterns]`.
|
|
159
|
+
*
|
|
160
|
+
* 🔴 `DEFAULT_SECURITY_PATTERNS` ở trên CHỈ chặn API JavaScript (`eval`, `fetch`, `localStorage`…)
|
|
161
|
+
* nên không dùng được cho SQL. Bộ này chặn câu lệnh GHI và truy vấn siêu dữ liệu, dành cho các màn
|
|
162
|
+
* chỉ cho phép đọc (BI, dashboard, báo cáo).
|
|
163
|
+
*
|
|
164
|
+
* 🔴 Đây là lớp THUẬN TIỆN cho người dùng — báo sớm ngay khi gõ sai loại câu lệnh, KHÔNG phải lớp
|
|
165
|
+
* bảo mật: người dùng vẫn gọi API trực tiếp được. Backend BẮT BUỘC tự kiểm lại.
|
|
166
|
+
*
|
|
167
|
+
* Màn thật sự cần chạy câu lệnh ghi thì tự truyền bộ pattern riêng, hoặc lọc bớt bộ này:
|
|
168
|
+
* `DEFAULT_SQL_FORBIDDEN_PATTERNS.filter((p) => !String(p).includes('delete'))`.
|
|
169
|
+
*/
|
|
170
|
+
const DEFAULT_SQL_FORBIDDEN_PATTERNS = [
|
|
171
|
+
// Câu lệnh đổi lược đồ.
|
|
172
|
+
/\b(drop|truncate|alter|create)\b/i,
|
|
173
|
+
// Câu lệnh ghi dữ liệu.
|
|
174
|
+
/\b(delete|update|insert)\b/i,
|
|
175
|
+
// Câu lệnh đổi quyền.
|
|
176
|
+
/\b(grant|revoke)\b/i,
|
|
177
|
+
// Ghi kết quả ra tệp trên máy chủ cơ sở dữ liệu.
|
|
178
|
+
/\binto\s+outfile\b/i,
|
|
179
|
+
// Đọc siêu dữ liệu — lộ toàn bộ danh sách bảng/cột của hệ thống.
|
|
180
|
+
/\binformation_schema\b/i,
|
|
181
|
+
// Bảng/hàm hệ thống của PostgreSQL.
|
|
182
|
+
/\bpg_[a-z_]+\b/i,
|
|
183
|
+
// Dấu chấm phẩy rồi còn nội dung phía sau ⇒ nối thêm câu lệnh thứ hai.
|
|
184
|
+
/;\s*\S/,
|
|
185
|
+
];
|
|
186
|
+
/**
|
|
187
|
+
* Các key của AST node KHÔNG phải node con (metadata vị trí, comment...) — bỏ qua khi duyệt.
|
|
188
|
+
*/
|
|
189
|
+
const astSkipKeys = new Set(['loc', 'start', 'end', 'range', 'leadingComments', 'trailingComments', 'innerComments', 'extra', 'comments', 'tokens']);
|
|
190
|
+
/**
|
|
191
|
+
* Các key chứa annotation kiểu TypeScript → con của nó nằm trong "type context" (không phải biến giá trị).
|
|
192
|
+
*/
|
|
193
|
+
const astTypeKeys = new Set(['typeAnnotation', 'returnType', 'typeParameters', 'typeArguments', 'superTypeParameters']);
|
|
194
|
+
/**
|
|
195
|
+
* Các node `TS*` mang GIÁ TRỊ (không phải type thuần) → con của chúng vẫn là biến giá trị bình thường.
|
|
196
|
+
*/
|
|
197
|
+
const tsValueNodes = new Set(['TSEnumDeclaration', 'TSEnumMember', 'TSModuleDeclaration', 'TSModuleBlock', 'TSAsExpression', 'TSNonNullExpression', 'TSParameterProperty', 'TSExportAssignment', 'TSImportEqualsDeclaration', 'TSExternalModuleReference', 'TSSatisfiesExpression']);
|
|
157
198
|
/**
|
|
158
199
|
* Tạo default language extension cho plain text
|
|
159
200
|
* Sử dụng khi ngôn ngữ không được hỗ trợ
|
|
@@ -168,6 +209,1051 @@ const createDefaultLanguage = async () => {
|
|
|
168
209
|
});
|
|
169
210
|
};
|
|
170
211
|
|
|
212
|
+
/** Lấy token (chuỗi không khoảng trắng) liền trước vị trí `pos` trong document. Dùng chung cho JS/SQL/Python. */
|
|
213
|
+
const getTokenBefore = (doc, pos) => {
|
|
214
|
+
const start = Math.max(0, pos - 30);
|
|
215
|
+
const text = doc.sliceString(start, pos);
|
|
216
|
+
const match = /(\S+)\s*$/.exec(text);
|
|
217
|
+
return match?.[1] ?? '';
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// Cache module-level (chia sẻ giữa các instance editor) — đều immutable, lazy-load 1 lần.
|
|
221
|
+
let babelParserModule;
|
|
222
|
+
let knownGlobalsSet;
|
|
223
|
+
/** Lazy-load + cache module @babel/parser (chỉ tải lần đầu khi lint JS/TS). */
|
|
224
|
+
const getBabelParser = async () => {
|
|
225
|
+
if (!babelParserModule) {
|
|
226
|
+
babelParserModule = await import('@babel/parser');
|
|
227
|
+
}
|
|
228
|
+
return babelParserModule;
|
|
229
|
+
};
|
|
230
|
+
/** Lazy-load + cache tập biến toàn cục JS/DOM hợp lệ từ package `globals` (JSON thuần, browser-safe). */
|
|
231
|
+
const getKnownGlobals = async () => {
|
|
232
|
+
if (!knownGlobalsSet) {
|
|
233
|
+
const globalsModule = (await import('globals'));
|
|
234
|
+
const globalsData = (globalsModule.default ?? globalsModule);
|
|
235
|
+
knownGlobalsSet = new Set([...Object.keys(globalsData['builtin'] ?? {}), ...Object.keys(globalsData['browser'] ?? {}), ...Object.keys(globalsData['es2021'] ?? {})]);
|
|
236
|
+
}
|
|
237
|
+
return knownGlobalsSet;
|
|
238
|
+
};
|
|
239
|
+
/**
|
|
240
|
+
* Parse code, trả về vừa danh sách lỗi cú pháp vừa AST (nếu parse sạch).
|
|
241
|
+
* `errorRecovery` gom nhiều lỗi vào `result.errors`; lỗi nặng vẫn `throw` → bắt thêm ở catch.
|
|
242
|
+
*/
|
|
243
|
+
const parseJs = (parser, code) => {
|
|
244
|
+
try {
|
|
245
|
+
const result = parser.parse(code, {
|
|
246
|
+
sourceType: 'module',
|
|
247
|
+
errorRecovery: true,
|
|
248
|
+
plugins: ['typescript', 'jsx'],
|
|
249
|
+
allowReturnOutsideFunction: true,
|
|
250
|
+
allowAwaitOutsideFunction: true,
|
|
251
|
+
allowImportExportEverywhere: true,
|
|
252
|
+
allowSuperOutsideMethod: true,
|
|
253
|
+
allowNewTargetOutsideFunction: true,
|
|
254
|
+
allowUndeclaredExports: true,
|
|
255
|
+
});
|
|
256
|
+
return { errors: result.errors, ast: result };
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
const loc = get(error, 'loc');
|
|
260
|
+
const message = get(error, 'message') || 'JavaScript syntax error';
|
|
261
|
+
return { errors: [{ loc, message }] };
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
/** Giữ cho test/back-compat: chỉ lấy danh sách lỗi cú pháp. */
|
|
265
|
+
const collectBabelErrors = (parser, code) => parseJs(parser, code).errors;
|
|
266
|
+
/**
|
|
267
|
+
* Quét text từng dòng, flag dấu "." cuối dòng (incomplete property access) tại ĐÚNG vị trí dấu chấm.
|
|
268
|
+
* Thu thập `taintedLines` (dòng có trailing dot) + `dotPositions` (offset dấu chấm để vá khi parse).
|
|
269
|
+
*/
|
|
270
|
+
const collectTrailingDotDiagnostics = (doc, diagnostics, taintedLines, dotPositions) => {
|
|
271
|
+
for (let lineNumber = 1; lineNumber <= doc.lines; lineNumber++) {
|
|
272
|
+
const line = doc.line(lineNumber);
|
|
273
|
+
const trimmed = line.text.trimEnd();
|
|
274
|
+
const match = /(\w+)\.\s*$/.exec(trimmed);
|
|
275
|
+
if (!match) {
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
taintedLines.add(lineNumber);
|
|
279
|
+
const dotPosition = line.from + trimmed.lastIndexOf('.');
|
|
280
|
+
dotPositions.push(dotPosition);
|
|
281
|
+
diagnostics.push({ from: dotPosition, to: dotPosition + 1, severity: 'error', message: `Incomplete property access on "${match[1]}"` });
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
/** Thay các ký tự tại `positions` bằng space, giữ nguyên độ dài chuỗi (để offset không đổi). */
|
|
285
|
+
const replaceCharsWithSpace = (code, positions) => {
|
|
286
|
+
if (!positions.length) {
|
|
287
|
+
return code;
|
|
288
|
+
}
|
|
289
|
+
const chars = code.split('');
|
|
290
|
+
for (const position of positions) {
|
|
291
|
+
if (position >= 0 && position < chars.length) {
|
|
292
|
+
chars[position] = ' ';
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return chars.join('');
|
|
296
|
+
};
|
|
297
|
+
/** VariableDeclaration ở `for(let i=0;...)` / `for..in` / `for..of` KHÔNG cần `;` cuối. */
|
|
298
|
+
const requiresSemicolon = (nodeType, parentType, keyInParent) => {
|
|
299
|
+
if (nodeType === 'VariableDeclaration') {
|
|
300
|
+
if (parentType === 'ForStatement' && keyInParent === 'init')
|
|
301
|
+
return false;
|
|
302
|
+
if ((parentType === 'ForInStatement' || parentType === 'ForOfStatement') && keyInParent === 'left')
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
return true;
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Rule custom "require semicolon": câu lệnh (const/let/return/expression...) không kết thúc bằng `;` → báo lỗi.
|
|
309
|
+
* Dùng vị trí `node.end` của AST babel; bỏ qua dòng tainted (trailing dot) để không chồng lỗi.
|
|
310
|
+
*/
|
|
311
|
+
const collectMissingSemicolonDiagnostics = (ast, code, diagnostics, taintedLines) => {
|
|
312
|
+
const semiNodes = new Set(['ExpressionStatement', 'VariableDeclaration', 'ReturnStatement', 'ThrowStatement', 'BreakStatement', 'ContinueStatement', 'DoWhileStatement', 'DebuggerStatement']);
|
|
313
|
+
const seen = new Set();
|
|
314
|
+
const lineOf = (offset) => code.slice(0, offset).split('\n').length;
|
|
315
|
+
const walk = (node, parentType, keyInParent) => {
|
|
316
|
+
if (Array.isArray(node)) {
|
|
317
|
+
for (const item of node)
|
|
318
|
+
walk(item, parentType, keyInParent);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (!node || typeof node !== 'object')
|
|
322
|
+
return;
|
|
323
|
+
const current = node;
|
|
324
|
+
if (typeof current.type !== 'string')
|
|
325
|
+
return;
|
|
326
|
+
if (semiNodes.has(current.type) && requiresSemicolon(current.type, parentType, keyInParent) && typeof current.end === 'number') {
|
|
327
|
+
const end = Math.min(current.end, code.length);
|
|
328
|
+
if (end > 0 && code.charAt(end - 1) !== ';' && !seen.has(end) && !taintedLines.has(lineOf(end - 1))) {
|
|
329
|
+
seen.add(end);
|
|
330
|
+
diagnostics.push({ from: end - 1, to: end, severity: 'error', message: 'Missing semicolon' });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
for (const childKey of Object.keys(current)) {
|
|
334
|
+
if (astSkipKeys.has(childKey))
|
|
335
|
+
continue;
|
|
336
|
+
walk(current[childKey], current.type, childKey);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
walk(ast.program ?? ast, '', '');
|
|
340
|
+
};
|
|
341
|
+
/** Chuẩn hóa message: thân thiện cho trailing dot + heuristic kiểu cũ cho "Unexpected token"; bỏ hậu tố "(line:col)". */
|
|
342
|
+
const buildJsErrorMessage = (doc, from, rawMessage) => {
|
|
343
|
+
const charBefore = from > 0 ? doc.sliceString(from - 1, from) : '';
|
|
344
|
+
if (charBefore === '.') {
|
|
345
|
+
const owner = getTokenBefore(doc, from).replace(/\.$/, '');
|
|
346
|
+
return owner ? `Incomplete property access on "${owner}"` : 'Incomplete property access';
|
|
347
|
+
}
|
|
348
|
+
const cleaned = rawMessage.replace(/\s*\(\d+:\d+\)\s*$/, '').trim();
|
|
349
|
+
if (/missing semicolon/i.test(cleaned)) {
|
|
350
|
+
return 'Unexpected token — missing operator or separator between expressions';
|
|
351
|
+
}
|
|
352
|
+
if (/^unexpected token$/i.test(cleaned)) {
|
|
353
|
+
const prevToken = getTokenBefore(doc, from);
|
|
354
|
+
if (prevToken.endsWith('('))
|
|
355
|
+
return 'Missing closing ")"';
|
|
356
|
+
if (prevToken.endsWith('['))
|
|
357
|
+
return 'Missing closing "]"';
|
|
358
|
+
if (/^function$/i.test(prevToken))
|
|
359
|
+
return 'Expected function name or "("';
|
|
360
|
+
if (/^return$/i.test(prevToken))
|
|
361
|
+
return 'Invalid expression after "return"';
|
|
362
|
+
if (/^=>$/.test(prevToken))
|
|
363
|
+
return 'Expected function body after "=>"';
|
|
364
|
+
if (/^const$|^let$|^var$/i.test(prevToken))
|
|
365
|
+
return 'Expected variable name';
|
|
366
|
+
}
|
|
367
|
+
return `JavaScript syntax error: ${cleaned}`;
|
|
368
|
+
};
|
|
369
|
+
/** Lấy tên binding từ pattern (Identifier, destructuring object/array, default, rest). */
|
|
370
|
+
const collectPatternNames = (node, declared) => {
|
|
371
|
+
if (!node || typeof node.type !== 'string')
|
|
372
|
+
return;
|
|
373
|
+
switch (node.type) {
|
|
374
|
+
case 'Identifier':
|
|
375
|
+
if (node.name)
|
|
376
|
+
declared.add(node.name);
|
|
377
|
+
return;
|
|
378
|
+
case 'ObjectPattern':
|
|
379
|
+
if (node.properties)
|
|
380
|
+
for (const property of node.properties)
|
|
381
|
+
collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, declared);
|
|
382
|
+
return;
|
|
383
|
+
case 'ArrayPattern':
|
|
384
|
+
if (node.elements)
|
|
385
|
+
for (const element of node.elements)
|
|
386
|
+
collectPatternNames(element, declared);
|
|
387
|
+
return;
|
|
388
|
+
case 'AssignmentPattern':
|
|
389
|
+
collectPatternNames(node.left, declared);
|
|
390
|
+
return;
|
|
391
|
+
case 'RestElement':
|
|
392
|
+
collectPatternNames(node.argument, declared);
|
|
393
|
+
return;
|
|
394
|
+
case 'TSParameterProperty':
|
|
395
|
+
collectPatternNames(node.parameter, declared);
|
|
396
|
+
return;
|
|
397
|
+
default:
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
/** Thu thập tên binding (biến/hàm/class/param/import/enum...) từ 1 node vào tập `declared`. */
|
|
402
|
+
const collectBindingNames = (node, declared) => {
|
|
403
|
+
switch (node.type) {
|
|
404
|
+
case 'VariableDeclarator':
|
|
405
|
+
collectPatternNames(node.id, declared);
|
|
406
|
+
return;
|
|
407
|
+
case 'FunctionDeclaration':
|
|
408
|
+
case 'FunctionExpression':
|
|
409
|
+
case 'ClassDeclaration':
|
|
410
|
+
case 'ClassExpression':
|
|
411
|
+
if (node.id?.name)
|
|
412
|
+
declared.add(node.id.name);
|
|
413
|
+
if (node.params)
|
|
414
|
+
for (const param of node.params)
|
|
415
|
+
collectPatternNames(param, declared);
|
|
416
|
+
return;
|
|
417
|
+
case 'ArrowFunctionExpression':
|
|
418
|
+
if (node.params)
|
|
419
|
+
for (const param of node.params)
|
|
420
|
+
collectPatternNames(param, declared);
|
|
421
|
+
return;
|
|
422
|
+
case 'CatchClause':
|
|
423
|
+
collectPatternNames(node.param, declared);
|
|
424
|
+
return;
|
|
425
|
+
case 'ImportDefaultSpecifier':
|
|
426
|
+
case 'ImportNamespaceSpecifier':
|
|
427
|
+
case 'ImportSpecifier':
|
|
428
|
+
if (node.local?.name)
|
|
429
|
+
declared.add(node.local.name);
|
|
430
|
+
return;
|
|
431
|
+
case 'TSEnumDeclaration':
|
|
432
|
+
case 'TSModuleDeclaration':
|
|
433
|
+
if (node.id?.name)
|
|
434
|
+
declared.add(node.id.name);
|
|
435
|
+
return;
|
|
436
|
+
default:
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
/** Xác định 1 Identifier có phải tham chiếu giá trị không (loại property access, key object, declaration id, label...). */
|
|
441
|
+
const isReferenceIdentifier = (parent, keyInParent) => {
|
|
442
|
+
if (!parent)
|
|
443
|
+
return true;
|
|
444
|
+
const parentType = parent.type;
|
|
445
|
+
if ((parentType === 'MemberExpression' || parentType === 'OptionalMemberExpression') && keyInParent === 'property' && !parent.computed)
|
|
446
|
+
return false;
|
|
447
|
+
if ((parentType === 'ObjectProperty' || parentType === 'ObjectMethod' || parentType === 'ClassMethod' || parentType === 'ClassProperty' || parentType === 'ClassPrivateProperty' || parentType === 'PropertyDefinition') && keyInParent === 'key' && !parent.computed)
|
|
448
|
+
return false;
|
|
449
|
+
if (keyInParent === 'label')
|
|
450
|
+
return false;
|
|
451
|
+
if (parentType === 'TSQualifiedName' && keyInParent === 'right')
|
|
452
|
+
return false;
|
|
453
|
+
if (parentType === 'VariableDeclarator' && keyInParent === 'id')
|
|
454
|
+
return false;
|
|
455
|
+
if ((parentType === 'FunctionDeclaration' || parentType === 'FunctionExpression' || parentType === 'ClassDeclaration' || parentType === 'ClassExpression') && keyInParent === 'id')
|
|
456
|
+
return false;
|
|
457
|
+
if (parentType === 'ImportSpecifier' || parentType === 'ImportDefaultSpecifier' || parentType === 'ImportNamespaceSpecifier' || parentType === 'ExportSpecifier')
|
|
458
|
+
return false;
|
|
459
|
+
if (parentType === 'MetaProperty')
|
|
460
|
+
return false;
|
|
461
|
+
if (parentType === 'TSEnumMember' && keyInParent === 'id')
|
|
462
|
+
return false;
|
|
463
|
+
return true;
|
|
464
|
+
};
|
|
465
|
+
/** Duyệt đệ quy AST: gom binding name vào `declared`, gom identifier tham chiếu vào `references`. */
|
|
466
|
+
const walkAstNode = (node, parent, keyInParent, inType, declared, references) => {
|
|
467
|
+
if (Array.isArray(node)) {
|
|
468
|
+
for (const item of node)
|
|
469
|
+
walkAstNode(item, parent, keyInParent, inType, declared, references);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (!node || typeof node !== 'object')
|
|
473
|
+
return;
|
|
474
|
+
const current = node;
|
|
475
|
+
if (typeof current.type !== 'string')
|
|
476
|
+
return;
|
|
477
|
+
collectBindingNames(current, declared);
|
|
478
|
+
if (current.type === 'Identifier' && !inType && isReferenceIdentifier(parent, keyInParent)) {
|
|
479
|
+
const start = current.loc?.start;
|
|
480
|
+
if (current.name && start)
|
|
481
|
+
references.push({ name: current.name, line: start.line, column: start.column });
|
|
482
|
+
}
|
|
483
|
+
const opensType = inType || (current.type.startsWith('TS') && !tsValueNodes.has(current.type));
|
|
484
|
+
for (const childKey of Object.keys(current)) {
|
|
485
|
+
if (astSkipKeys.has(childKey))
|
|
486
|
+
continue;
|
|
487
|
+
const child = current[childKey];
|
|
488
|
+
const childOpensType = typeof child === 'object' && child !== null && typeof child.type === 'string' && child.type.startsWith('TS') && !tsValueNodes.has(child.type);
|
|
489
|
+
const childInType = opensType || astTypeKeys.has(childKey) || childOpensType;
|
|
490
|
+
walkAstNode(child, current, childKey, childInType, declared, references);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
/**
|
|
494
|
+
* Pass ngữ nghĩa: báo biến CHƯA KHAI BÁO. Tự duyệt AST (object thuần) — KHÔNG dùng `@babel/traverse`
|
|
495
|
+
* (cần `process` của Node → crash browser). Hợp lệ = binding trong code + global JS/DOM + `completionLabels`.
|
|
496
|
+
*/
|
|
497
|
+
const collectUndeclaredIdentifiers = async (ast, doc, completionLabels, taintedLines = new Set()) => {
|
|
498
|
+
const globalsSet = await getKnownGlobals();
|
|
499
|
+
const declared = new Set();
|
|
500
|
+
const references = [];
|
|
501
|
+
walkAstNode(ast, null, '', false, declared, references);
|
|
502
|
+
const diagnostics = [];
|
|
503
|
+
const seen = new Set();
|
|
504
|
+
for (const reference of references) {
|
|
505
|
+
const { name, line: startLine, column: startColumn } = reference;
|
|
506
|
+
if (declared.has(name) || globalsSet.has(name) || completionLabels.has(name))
|
|
507
|
+
continue;
|
|
508
|
+
if (taintedLines.has(startLine))
|
|
509
|
+
continue;
|
|
510
|
+
const dedupeKey = `${startLine}:${startColumn}:${name}`;
|
|
511
|
+
if (seen.has(dedupeKey))
|
|
512
|
+
continue;
|
|
513
|
+
seen.add(dedupeKey);
|
|
514
|
+
const line = doc.line(Math.min(Math.max(startLine, 1), doc.lines));
|
|
515
|
+
const from = Math.min(line.from + Math.max(startColumn, 0), doc.length);
|
|
516
|
+
const to = Math.min(from + name.length, doc.length);
|
|
517
|
+
diagnostics.push({ from, to: Math.max(from + 1, to), severity: 'error', message: `"${name}" is not defined` });
|
|
518
|
+
}
|
|
519
|
+
return diagnostics;
|
|
520
|
+
};
|
|
521
|
+
/**
|
|
522
|
+
* Toàn bộ pipeline validate JS/TS:
|
|
523
|
+
* - Pass 1: trailing dot (text) — flag đúng vị trí dấu `.` cuối dòng + đánh dấu dòng tainted.
|
|
524
|
+
* - Pass 2: lỗi cú pháp babel — bỏ lỗi trên dòng tainted (cascading).
|
|
525
|
+
* - Pass 3: rule cần AST (thiếu `;`, biến chưa khai báo). Trailing dot được "vá" (`.`→space) để babel
|
|
526
|
+
* vẫn parse được phần còn lại → rule vẫn chạy cho các dòng KHÁC.
|
|
527
|
+
*/
|
|
528
|
+
const computeJsDiagnostics = async (doc, code, completionLabels) => {
|
|
529
|
+
const diagnostics = [];
|
|
530
|
+
if (code.trim() === '') {
|
|
531
|
+
return diagnostics;
|
|
532
|
+
}
|
|
533
|
+
const taintedLines = new Set();
|
|
534
|
+
const dotPositions = [];
|
|
535
|
+
collectTrailingDotDiagnostics(doc, diagnostics, taintedLines, dotPositions);
|
|
536
|
+
const parseCode = replaceCharsWithSpace(code, dotPositions);
|
|
537
|
+
const parser = await getBabelParser();
|
|
538
|
+
const { errors, ast } = parseJs(parser, parseCode);
|
|
539
|
+
const seen = new Set();
|
|
540
|
+
for (const error of errors) {
|
|
541
|
+
const location = error.loc;
|
|
542
|
+
if (!location)
|
|
543
|
+
continue;
|
|
544
|
+
const lineNumber = Math.min(Math.max(location.line, 1), doc.lines);
|
|
545
|
+
if (taintedLines.has(lineNumber))
|
|
546
|
+
continue;
|
|
547
|
+
const line = doc.line(lineNumber);
|
|
548
|
+
const errorPos = Math.min(line.from + Math.max(location.column, 0), doc.length);
|
|
549
|
+
const to = Math.min(errorPos + 1, doc.length);
|
|
550
|
+
const from = errorPos >= to && errorPos > 0 ? errorPos - 1 : errorPos;
|
|
551
|
+
const message = buildJsErrorMessage(doc, errorPos, error.message);
|
|
552
|
+
const dedupeKey = `${from}:${message}`;
|
|
553
|
+
if (seen.has(dedupeKey))
|
|
554
|
+
continue;
|
|
555
|
+
seen.add(dedupeKey);
|
|
556
|
+
diagnostics.push({ from, to: Math.max(from + 1, to), severity: 'error', message });
|
|
557
|
+
}
|
|
558
|
+
if (errors.length === 0 && ast) {
|
|
559
|
+
collectMissingSemicolonDiagnostics(ast, code, diagnostics, taintedLines);
|
|
560
|
+
diagnostics.push(...(await collectUndeclaredIdentifiers(ast, doc, completionLabels, taintedLines)));
|
|
561
|
+
}
|
|
562
|
+
return diagnostics;
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
/** Validate JSON bằng `JSON.parse`. Lỗi → 1 diagnostic phủ toàn bộ nội dung. */
|
|
566
|
+
const computeJsonDiagnostics = (view) => {
|
|
567
|
+
const text = view.state.doc.toString();
|
|
568
|
+
const diagnostics = [];
|
|
569
|
+
try {
|
|
570
|
+
JSON.parse(text);
|
|
571
|
+
}
|
|
572
|
+
catch (error) {
|
|
573
|
+
diagnostics.push({ from: 0, to: text.length, severity: 'error', message: get(error, 'message', '') });
|
|
574
|
+
}
|
|
575
|
+
return diagnostics;
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
const buildSqlErrorMessage = (doc, node) => {
|
|
579
|
+
if (node.from !== node.to) {
|
|
580
|
+
const text = doc.sliceString(node.from, node.to);
|
|
581
|
+
return `SQL syntax error near "${text}"`;
|
|
582
|
+
}
|
|
583
|
+
const prevToken = getTokenBefore(doc, node.from);
|
|
584
|
+
if (!prevToken)
|
|
585
|
+
return 'SQL syntax error at beginning of statement';
|
|
586
|
+
if (/FROM$/i.test(prevToken))
|
|
587
|
+
return 'Expected table name after FROM';
|
|
588
|
+
if (/SELECT$/i.test(prevToken))
|
|
589
|
+
return 'Expected column list after SELECT';
|
|
590
|
+
if (/WHERE$/i.test(prevToken))
|
|
591
|
+
return 'Expected condition after WHERE';
|
|
592
|
+
if (prevToken.endsWith('('))
|
|
593
|
+
return 'Missing closing ")"';
|
|
594
|
+
return `Unexpected end of SQL after "${prevToken}"`;
|
|
595
|
+
};
|
|
596
|
+
/** Phát hiện lỗi cú pháp SQL từ error node của syntaxTree (Lezer). */
|
|
597
|
+
const computeSqlDiagnostics = (view) => {
|
|
598
|
+
const diagnostics = [];
|
|
599
|
+
const doc = view.state.doc;
|
|
600
|
+
syntaxTree(view.state).iterate({
|
|
601
|
+
enter: (node) => {
|
|
602
|
+
if (!node.type.isError)
|
|
603
|
+
return;
|
|
604
|
+
diagnostics.push({ from: Math.max(0, node.from - 1), to: node.from, severity: 'error', message: buildSqlErrorMessage(doc, node) });
|
|
605
|
+
},
|
|
606
|
+
});
|
|
607
|
+
return diagnostics;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
const buildPythonErrorMessage = (doc, node) => {
|
|
611
|
+
if (node.from !== node.to) {
|
|
612
|
+
const text = doc.sliceString(node.from, node.to).trim();
|
|
613
|
+
return `Python syntax error${text ? ` near "${text}"` : ''}`;
|
|
614
|
+
}
|
|
615
|
+
const prevToken = getTokenBefore(doc, node.from);
|
|
616
|
+
if (!prevToken)
|
|
617
|
+
return 'Python syntax error';
|
|
618
|
+
if (/^def$/i.test(prevToken))
|
|
619
|
+
return 'Expected function name after "def"';
|
|
620
|
+
if (/^class$/i.test(prevToken))
|
|
621
|
+
return 'Expected class name after "class"';
|
|
622
|
+
if (/^return$/i.test(prevToken))
|
|
623
|
+
return 'Invalid expression after "return"';
|
|
624
|
+
if (/^import$/i.test(prevToken))
|
|
625
|
+
return 'Expected module name after "import"';
|
|
626
|
+
if (/^from$/i.test(prevToken))
|
|
627
|
+
return 'Expected module name after "from"';
|
|
628
|
+
if (/^if$/i.test(prevToken))
|
|
629
|
+
return 'Expected condition after "if"';
|
|
630
|
+
if (/^elif$/i.test(prevToken))
|
|
631
|
+
return 'Expected condition after "elif"';
|
|
632
|
+
if (/^while$/i.test(prevToken))
|
|
633
|
+
return 'Expected condition after "while"';
|
|
634
|
+
if (/^for$/i.test(prevToken))
|
|
635
|
+
return 'Expected variable after "for"';
|
|
636
|
+
if (prevToken.endsWith('.'))
|
|
637
|
+
return `Incomplete attribute access on "${prevToken.slice(0, -1)}"`;
|
|
638
|
+
if (prevToken.endsWith('('))
|
|
639
|
+
return 'Missing closing ")"';
|
|
640
|
+
if (prevToken.endsWith('['))
|
|
641
|
+
return 'Missing closing "]"';
|
|
642
|
+
return `Python syntax error near "${prevToken}"`;
|
|
643
|
+
};
|
|
644
|
+
/** Phát hiện lỗi cú pháp Python từ error node của syntaxTree (Lezer) — cùng approach SQL. */
|
|
645
|
+
const computePythonDiagnostics = (view) => {
|
|
646
|
+
const diagnostics = [];
|
|
647
|
+
const doc = view.state.doc;
|
|
648
|
+
syntaxTree(view.state).iterate({
|
|
649
|
+
enter: (node) => {
|
|
650
|
+
if (!node.type.isError)
|
|
651
|
+
return;
|
|
652
|
+
const from = Math.max(0, node.from - 1);
|
|
653
|
+
const to = node.from === node.to ? node.from + 1 : node.to;
|
|
654
|
+
diagnostics.push({ from, to: Math.min(to, doc.length), severity: 'error', message: buildPythonErrorMessage(doc, node) });
|
|
655
|
+
},
|
|
656
|
+
});
|
|
657
|
+
return diagnostics;
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Tạo extension autocomplete từ danh sách `items`:
|
|
662
|
+
* 1. Gõ `obj.` → gợi ý properties của obj (dot-notation).
|
|
663
|
+
* 2. Gõ ký tự → gợi ý tên biến/object top-level.
|
|
664
|
+
*/
|
|
665
|
+
const buildCompletionExtension = (items) => {
|
|
666
|
+
const completionSource = (context) => {
|
|
667
|
+
// Cho phép path nhiều cấp (a.b.c.) — [\w.]+ bắt trọn chuỗi trước con trỏ.
|
|
668
|
+
const dotMatch = context.matchBefore(/[\w.]+\.\w*/);
|
|
669
|
+
if (dotMatch) {
|
|
670
|
+
const segments = dotMatch.text.split('.');
|
|
671
|
+
const partial = segments[segments.length - 1]; // phần đang gõ dở sau dấu '.' cuối
|
|
672
|
+
const pathSegments = segments.slice(0, -1); // các cấp đã hoàn tất
|
|
673
|
+
let current = items.find((item) => item.label === pathSegments[0]);
|
|
674
|
+
for (let level = 1; level < pathSegments.length && current; level++) {
|
|
675
|
+
current = current.properties?.find((property) => property.label === pathSegments[level]);
|
|
676
|
+
}
|
|
677
|
+
if (current?.properties?.length) {
|
|
678
|
+
return {
|
|
679
|
+
from: context.pos - partial.length,
|
|
680
|
+
options: current.properties.map((p) => ({ label: p.label, type: p.type ?? 'property', detail: p.detail ?? '', info: p.info ?? '' })),
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const word = context.matchBefore(/\w*/);
|
|
685
|
+
if (!word || (word.from === word.to && !context.explicit))
|
|
686
|
+
return null;
|
|
687
|
+
return {
|
|
688
|
+
from: word.from,
|
|
689
|
+
options: items.map((item) => ({ label: item.label, type: item.type ?? 'variable', detail: item.detail ?? '', info: item.info ?? '' })),
|
|
690
|
+
};
|
|
691
|
+
};
|
|
692
|
+
return autocompletion({ override: [completionSource] });
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
696
|
+
const toGlobalRegex = (pattern) => {
|
|
697
|
+
if (pattern instanceof RegExp) {
|
|
698
|
+
const flags = pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`;
|
|
699
|
+
return new RegExp(pattern.source, flags);
|
|
700
|
+
}
|
|
701
|
+
return new RegExp(escapeRegex(pattern), 'gi');
|
|
702
|
+
};
|
|
703
|
+
/**
|
|
704
|
+
* Extension bảo mật gồm 2 layer:
|
|
705
|
+
* 1. Linter: highlight đỏ tại đúng vị trí match (bỏ qua match trong comment) + gọi `emitViolations`.
|
|
706
|
+
* 2. Transaction filter: chặn paste nếu nội dung paste chứa pattern cấm.
|
|
707
|
+
*/
|
|
708
|
+
const buildForbiddenExtension = (patterns, emitViolations) => {
|
|
709
|
+
const forbiddenLinter = linter((view) => {
|
|
710
|
+
const diagnostics = [];
|
|
711
|
+
const violations = [];
|
|
712
|
+
const text = view.state.doc.toString();
|
|
713
|
+
const commentRanges = [];
|
|
714
|
+
syntaxTree(view.state).iterate({
|
|
715
|
+
enter: (node) => {
|
|
716
|
+
if (node.type.name.toLowerCase().includes('comment')) {
|
|
717
|
+
commentRanges.push({ from: node.from, to: node.to });
|
|
718
|
+
}
|
|
719
|
+
},
|
|
720
|
+
});
|
|
721
|
+
const isInComment = (from, to) => commentRanges.some((r) => from >= r.from && to <= r.to);
|
|
722
|
+
for (const pattern of patterns) {
|
|
723
|
+
const re = toGlobalRegex(pattern);
|
|
724
|
+
re.lastIndex = 0;
|
|
725
|
+
let match;
|
|
726
|
+
while ((match = re.exec(text)) !== null) {
|
|
727
|
+
const from = match.index;
|
|
728
|
+
const to = from + match[0].length;
|
|
729
|
+
if (isInComment(from, to))
|
|
730
|
+
continue;
|
|
731
|
+
const line = view.state.doc.lineAt(from).number;
|
|
732
|
+
const patternLabel = pattern instanceof RegExp ? pattern.source : pattern;
|
|
733
|
+
diagnostics.push({ from, to, severity: 'error', message: `Mã bị cấm: "${match[0]}" — vi phạm chính sách bảo mật` });
|
|
734
|
+
violations.push({ from, to, line, pattern: patternLabel, matched: match[0] });
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
emitViolations(violations);
|
|
738
|
+
return diagnostics;
|
|
739
|
+
});
|
|
740
|
+
const pasteFilter = EditorState.transactionFilter.of((tr) => {
|
|
741
|
+
if (!tr.docChanged)
|
|
742
|
+
return tr;
|
|
743
|
+
if (!tr.annotation(Transaction.userEvent)?.startsWith('input.paste'))
|
|
744
|
+
return tr;
|
|
745
|
+
const newText = tr.newDoc.toString();
|
|
746
|
+
for (const pattern of patterns) {
|
|
747
|
+
const re = toGlobalRegex(pattern);
|
|
748
|
+
re.lastIndex = 0;
|
|
749
|
+
if (re.test(newText))
|
|
750
|
+
return [];
|
|
751
|
+
}
|
|
752
|
+
return tr;
|
|
753
|
+
});
|
|
754
|
+
return [forbiddenLinter, pasteFilter];
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
/** Parse giá trị CSS px → number. Trả về undefined nếu không phải px hợp lệ (vd `none`, `0`). */
|
|
758
|
+
const parsePx = (raw) => {
|
|
759
|
+
if (!raw || !raw.endsWith('px')) {
|
|
760
|
+
return undefined;
|
|
761
|
+
}
|
|
762
|
+
const value = parseFloat(raw);
|
|
763
|
+
return Number.isFinite(value) && value > 0 ? value : undefined;
|
|
764
|
+
};
|
|
765
|
+
/**
|
|
766
|
+
* Chiều cao MỘT dòng, lấy từ CSS `line-height` của vùng nội dung.
|
|
767
|
+
*
|
|
768
|
+
* 🔴 KHÔNG đo `getBoundingClientRect()` của `.cm-line`: số đó phụ thuộc thời điểm gọi và cho ra
|
|
769
|
+
* hàng loạt giá trị sai khi editor vừa dựng — đo trên modal 08–09/09/2026 với dòng thật `18.19px`
|
|
770
|
+
* đã gặp `5.82` · `11.61` · `15.88` · `24` · `59`, mỗi lần mở một số khác. `defaultLineHeight` của
|
|
771
|
+
* CodeMirror cũng không dùng được vì là số mặc định (20/24px), không theo font sản phẩm.
|
|
772
|
+
*
|
|
773
|
+
* `line-height` trong CSS thì có ngay khi phần tử gắn vào DOM và không đổi theo thời điểm đọc.
|
|
774
|
+
*/
|
|
775
|
+
const readLineHeight = (view) => {
|
|
776
|
+
const style = getComputedStyle(view.contentDOM);
|
|
777
|
+
const lineHeight = parseFloat(style.lineHeight);
|
|
778
|
+
if (Number.isFinite(lineHeight) && lineHeight > 0) {
|
|
779
|
+
return lineHeight;
|
|
780
|
+
}
|
|
781
|
+
// `line-height: normal` → suy ra từ cỡ chữ, hệ số 1.4 là mức CodeMirror dùng cho editor.
|
|
782
|
+
const fontSize = parseFloat(style.fontSize);
|
|
783
|
+
if (Number.isFinite(fontSize) && fontSize > 0) {
|
|
784
|
+
return fontSize * 1.4;
|
|
785
|
+
}
|
|
786
|
+
return view.defaultLineHeight || 20;
|
|
787
|
+
};
|
|
788
|
+
/**
|
|
789
|
+
* Chạy `apply` khi đã CÓ dòng thật để đo.
|
|
790
|
+
*
|
|
791
|
+
* Vì sao không chỉ chờ `document.fonts.ready`: editor có thể dựng SAU lúc font đã nạp (vd ô JSON chỉ
|
|
792
|
+
* hiện khi người dùng bấm chạy thử). Lúc đó `fonts.ready` giải quyết ngay nhưng `.cm-line` chưa
|
|
793
|
+
* render, phép đo rơi vào `defaultLineHeight` — đo 08/09/2026: khung JSON thành 895px (48 dòng)
|
|
794
|
+
* thay vì 281px. Nên: chờ cả font VÀ dòng đầu tiên xuất hiện, thử lại tối đa `SO_LAN_THU` nhịp.
|
|
795
|
+
*/
|
|
796
|
+
const SO_LAN_THU_DO = 30;
|
|
797
|
+
const runWhenFontReady = (view, apply) => {
|
|
798
|
+
const fonts = typeof document === 'undefined' ? undefined : document.fonts;
|
|
799
|
+
const doKhiSanSang = (conLai) => {
|
|
800
|
+
// Chỉ cần vùng nội dung đã gắn vào DOM là `line-height` đọc được — không cần chờ vẽ dòng.
|
|
801
|
+
if (view.contentDOM.isConnected) {
|
|
802
|
+
apply();
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
if (conLai <= 0) {
|
|
806
|
+
// Hết nhịp chờ vẫn chưa có dòng thật — đo bằng số dự phòng, thà lệch hơn không chặn chiều cao.
|
|
807
|
+
apply();
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
requestAnimationFrame(() => doKhiSanSang(conLai - 1));
|
|
811
|
+
};
|
|
812
|
+
if (!fonts?.ready) {
|
|
813
|
+
doKhiSanSang(SO_LAN_THU_DO);
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
fonts.ready.then(() => doKhiSanSang(SO_LAN_THU_DO)).catch(() => doKhiSanSang(SO_LAN_THU_DO));
|
|
817
|
+
};
|
|
818
|
+
/** Bù dòng trống cho đủ `minLines` (xử lý 1 lần khi khởi tạo). Đủ rồi giữ nguyên, không cắt bớt. */
|
|
819
|
+
const applyMinLines = (content, minLines) => {
|
|
820
|
+
const value = content ?? '';
|
|
821
|
+
if (!minLines || minLines <= 0) {
|
|
822
|
+
return value;
|
|
823
|
+
}
|
|
824
|
+
const currentLines = value === '' ? 1 : value.split('\n').length;
|
|
825
|
+
if (currentLines >= minLines) {
|
|
826
|
+
return value;
|
|
827
|
+
}
|
|
828
|
+
return value + '\n'.repeat(minLines - currentLines);
|
|
829
|
+
};
|
|
830
|
+
/**
|
|
831
|
+
* Tính min/max-height vùng cuộn theo CSS của container ngoài, snap về bội số dòng.
|
|
832
|
+
* Trừ offset phần header/toolbar (giữa đỉnh container và đỉnh vùng cuộn) để vừa khít container.
|
|
833
|
+
*/
|
|
834
|
+
const applyContainerHeight = (view, container) => {
|
|
835
|
+
const style = getComputedStyle(container);
|
|
836
|
+
const minPx = parsePx(style.minHeight);
|
|
837
|
+
const maxPx = parsePx(style.maxHeight);
|
|
838
|
+
if (minPx === undefined && maxPx === undefined) {
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
runWhenFontReady(view, () => view.requestMeasure({
|
|
842
|
+
read: (measureView) => {
|
|
843
|
+
const lineHeight = readLineHeight(measureView);
|
|
844
|
+
const offsetTop = Math.max(measureView.scrollDOM.getBoundingClientRect().top - container.getBoundingClientRect().top, 0);
|
|
845
|
+
const toLines = (px) => Math.max(1, Math.floor((px - offsetTop - 8) / lineHeight));
|
|
846
|
+
return { lineHeight, minLines: minPx === undefined ? undefined : toLines(minPx), maxLines: maxPx === undefined ? undefined : toLines(maxPx) };
|
|
847
|
+
},
|
|
848
|
+
write: ({ lineHeight, minLines, maxLines }, writeView) => {
|
|
849
|
+
if (maxLines !== undefined) {
|
|
850
|
+
writeView.scrollDOM.style.maxHeight = `${maxLines * lineHeight + 8}px`;
|
|
851
|
+
writeView.scrollDOM.style.overflowY = 'auto';
|
|
852
|
+
}
|
|
853
|
+
// min-height: bù dòng trống vào content (hiện đủ line-number 1..N), giống cơ chế minLines.
|
|
854
|
+
if (minLines !== undefined) {
|
|
855
|
+
const currentLines = writeView.state.doc.lines;
|
|
856
|
+
if (currentLines < minLines) {
|
|
857
|
+
queueMicrotask(() => writeView.dispatch({ changes: { from: writeView.state.doc.length, insert: '\n'.repeat(minLines - currentLines) } }));
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
},
|
|
861
|
+
}));
|
|
862
|
+
};
|
|
863
|
+
/**
|
|
864
|
+
* Giới hạn chiều cao editor (xử lý 1 lần). 2 chế độ loại trừ nhau:
|
|
865
|
+
* - `maxLines`: cap theo số dòng truyền vào.
|
|
866
|
+
* - `container`: tự tính số dòng theo `min-height`/`max-height` (CSS) của container, snap bội số dòng.
|
|
867
|
+
* Cấu hình đồng thời `container` + `minLines`/`maxLines` → throw.
|
|
868
|
+
*/
|
|
869
|
+
const applyMaxHeight = (view, options) => {
|
|
870
|
+
const { minLines, maxLines, container } = options;
|
|
871
|
+
if (container && (minLines || maxLines)) {
|
|
872
|
+
throw new Error('[preview-text-data] CẤM cấu hình [containerElement] cùng [minLines]/[maxLines]. Container tự quản lý min/max height.');
|
|
873
|
+
}
|
|
874
|
+
if (!view) {
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (container) {
|
|
878
|
+
applyContainerHeight(view, container);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (!maxLines || maxLines <= 0) {
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
runWhenFontReady(view, () => view.requestMeasure({
|
|
885
|
+
read: (measureView) => readLineHeight(measureView),
|
|
886
|
+
write: (lineHeight, writeView) => {
|
|
887
|
+
writeView.scrollDOM.style.maxHeight = `${maxLines * lineHeight + 8}px`;
|
|
888
|
+
writeView.scrollDOM.style.overflowY = 'auto';
|
|
889
|
+
},
|
|
890
|
+
}));
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Định dạng lại câu lệnh SQL cho dễ đọc — người dùng không phải tự căn chỉnh bằng tay.
|
|
895
|
+
*
|
|
896
|
+
* 🔴 Đây là bộ định dạng THUẦN (không thêm phụ thuộc nào vào thư viện dùng chung). Nó xử lý được
|
|
897
|
+
* phần lớn câu lệnh truy vấn thường gặp; câu quá lạ thì giữ nguyên chứ KHÔNG làm sai — xem
|
|
898
|
+
* `sqlFormat` đoạn về nguyên tắc "không đổi nghĩa".
|
|
899
|
+
*
|
|
900
|
+
* Việc nó làm:
|
|
901
|
+
* - mỗi từ khoá mở đầu một mệnh đề (`SELECT`, `FROM`, `WHERE`, `GROUP BY`…) xuống dòng mới;
|
|
902
|
+
* - mỗi cột trong `SELECT` một dòng, thụt vào một cấp;
|
|
903
|
+
* - `AND` / `OR` trong `WHERE` xuống dòng, thụt vào;
|
|
904
|
+
* - `JOIN … ON …` xuống dòng, `ON` thụt vào một cấp;
|
|
905
|
+
* - ngoặc lồng (câu con) tăng một cấp thụt;
|
|
906
|
+
* - toán tử so sánh có đúng một dấu cách hai bên (`c=1` → `c = 1`);
|
|
907
|
+
* - từ khoá viết HOA, tên bảng/cột giữ nguyên nguyên văn người dùng gõ;
|
|
908
|
+
* - gom nhiều dòng trắng liên tiếp thành một.
|
|
909
|
+
*/
|
|
910
|
+
/** Một cấp thụt = 2 dấu cách. Hai cấp là đủ thấy tầng mà không đẩy chữ ra xa mép. */
|
|
911
|
+
const INDENT_STEP = ' ';
|
|
912
|
+
/**
|
|
913
|
+
* Từ khoá mở đầu một MỆNH ĐỀ — luôn bắt đầu một dòng mới, ở cấp thụt hiện tại.
|
|
914
|
+
*
|
|
915
|
+
* 🔴 Xếp cụm DÀI trước cụm ngắn (`GROUP BY` trước `GROUP`, `LEFT JOIN` trước `JOIN`): bộ so khớp
|
|
916
|
+
* lấy cụm khớp đầu tiên, để ngắn trước thì `GROUP BY` bị cắt thành `GROUP` rồi `BY` lạc ra ngoài.
|
|
917
|
+
*/
|
|
918
|
+
const CLAUSE_KEYWORDS = [
|
|
919
|
+
'SELECT DISTINCT', 'SELECT',
|
|
920
|
+
'FROM',
|
|
921
|
+
'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN',
|
|
922
|
+
'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'CROSS JOIN', 'FULL JOIN', 'JOIN',
|
|
923
|
+
'WHERE',
|
|
924
|
+
'GROUP BY', 'HAVING',
|
|
925
|
+
'ORDER BY',
|
|
926
|
+
'LIMIT', 'OFFSET',
|
|
927
|
+
'UNION ALL', 'UNION', 'INTERSECT', 'EXCEPT',
|
|
928
|
+
'WITH',
|
|
929
|
+
];
|
|
930
|
+
/** Từ khoá xuống dòng nhưng THỤT THÊM một cấp — nằm trong mệnh đề chứ không mở mệnh đề mới. */
|
|
931
|
+
const INDENTED_KEYWORDS = ['AND', 'OR', 'ON'];
|
|
932
|
+
/** Từ khoá chỉ viết HOA, không đụng tới dòng — nằm giữa biểu thức. */
|
|
933
|
+
const INLINE_KEYWORDS = [
|
|
934
|
+
'CASE', 'WHEN', 'THEN', 'ELSE', 'END',
|
|
935
|
+
'AS', 'IN', 'NOT', 'NULL', 'IS', 'LIKE', 'ILIKE', 'BETWEEN', 'EXISTS',
|
|
936
|
+
'ASC', 'DESC', 'OVER', 'PARTITION BY', 'CAST', 'INTERVAL', 'USING',
|
|
937
|
+
];
|
|
938
|
+
/**
|
|
939
|
+
* Toán tử so sánh / tính toán — luôn có ĐÚNG MỘT dấu cách hai bên.
|
|
940
|
+
*
|
|
941
|
+
* 🔴 Xếp toán tử HAI KÝ TỰ trước một ký tự (`<=` trước `<`, `!=` trước `!`): so khớp lấy cụm đầu
|
|
942
|
+
* tiên, để ngắn trước thì `a <= b` bị tách thành `a < = b` — sai cú pháp.
|
|
943
|
+
*
|
|
944
|
+
* 🔴 KHÔNG có `*`: `select *` và `count(*)` là dùng phổ biến nhất, chèn dấu cách quanh nó thành
|
|
945
|
+
* `select *` thì vô hại nhưng `count( * )` thì khó đọc. Phép nhân thật thì người dùng tự gõ cách.
|
|
946
|
+
*/
|
|
947
|
+
const OPERATORS = ['<=', '>=', '<>', '!=', '||', '=', '<', '>', '+', '-', '/', '%'];
|
|
948
|
+
/**
|
|
949
|
+
* Tách câu lệnh thành các mẩu, đánh dấu mẩu nào phải giữ nguyên văn.
|
|
950
|
+
*
|
|
951
|
+
* 🔴 Chuỗi · định danh trích dẫn · chú thích KHÔNG được đụng tới: đổi chữ trong `'Hà Nội'` thành
|
|
952
|
+
* `'HÀ NỘI'` là đổi DỮ LIỆU, còn chèn dòng mới vào giữa chuỗi là làm hỏng câu lệnh. Đây là lý do
|
|
953
|
+
* phải quét một lượt có trạng thái thay vì dùng regex trần.
|
|
954
|
+
*/
|
|
955
|
+
const sqlSplitPreservingLiterals = (sql) => {
|
|
956
|
+
const fragments = [];
|
|
957
|
+
let buffer = '';
|
|
958
|
+
let i = 0;
|
|
959
|
+
const flushBuffer = () => {
|
|
960
|
+
if (buffer) {
|
|
961
|
+
fragments.push({ text: buffer, isLiteral: false });
|
|
962
|
+
}
|
|
963
|
+
buffer = '';
|
|
964
|
+
};
|
|
965
|
+
while (i < sql.length) {
|
|
966
|
+
const ch = sql[i];
|
|
967
|
+
const next = sql[i + 1];
|
|
968
|
+
// Chú thích dòng `-- …`.
|
|
969
|
+
if (ch === '-' && next === '-') {
|
|
970
|
+
const end = sql.indexOf('\n', i);
|
|
971
|
+
const stop = end === -1 ? sql.length : end;
|
|
972
|
+
flushBuffer();
|
|
973
|
+
fragments.push({ text: sql.slice(i, stop), isLiteral: true });
|
|
974
|
+
i = stop;
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
// Chú thích khối `/* … */`.
|
|
978
|
+
if (ch === '/' && next === '*') {
|
|
979
|
+
const end = sql.indexOf('*/', i + 2);
|
|
980
|
+
const stop = end === -1 ? sql.length : end + 2;
|
|
981
|
+
flushBuffer();
|
|
982
|
+
fragments.push({ text: sql.slice(i, stop), isLiteral: true });
|
|
983
|
+
i = stop;
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
// Chuỗi và định danh trích dẫn: `'…'`, `"…"`, `` `…` ``.
|
|
987
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
988
|
+
let j = i + 1;
|
|
989
|
+
while (j < sql.length) {
|
|
990
|
+
if (sql[j] === '\\') {
|
|
991
|
+
j += 2;
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
if (sql[j] !== ch) {
|
|
995
|
+
j += 1;
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
// Nhân đôi dấu đóng = một dấu theo nghĩa đen, chuỗi chưa kết thúc.
|
|
999
|
+
if (sql[j + 1] === ch) {
|
|
1000
|
+
j += 2;
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
break;
|
|
1004
|
+
}
|
|
1005
|
+
const stop = Math.min(j + 1, sql.length);
|
|
1006
|
+
flushBuffer();
|
|
1007
|
+
fragments.push({ text: sql.slice(i, stop), isLiteral: true });
|
|
1008
|
+
i = stop;
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
buffer += ch;
|
|
1012
|
+
i += 1;
|
|
1013
|
+
}
|
|
1014
|
+
flushBuffer();
|
|
1015
|
+
return fragments;
|
|
1016
|
+
};
|
|
1017
|
+
/** Từ khoá khớp tại vị trí này (đã chuẩn hoá khoảng trắng), hoặc rỗng. */
|
|
1018
|
+
const matchKeyword = (text, position, keywordList) => {
|
|
1019
|
+
for (const keyword of keywordList) {
|
|
1020
|
+
const slice = text.slice(position, position + keyword.length);
|
|
1021
|
+
if (slice.toUpperCase() !== keyword) {
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
// Phải là RANH GIỚI TỪ hai đầu: `FROM` trong `FROMAGE` không phải từ khoá, và `x.on` cũng vậy.
|
|
1025
|
+
const prevChar = position === 0 ? ' ' : text[position - 1];
|
|
1026
|
+
const nextChar = text[position + keyword.length] ?? ' ';
|
|
1027
|
+
if (/[a-zA-Z0-9_$.]/.test(prevChar) || /[a-zA-Z0-9_$.]/.test(nextChar)) {
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
return keyword;
|
|
1031
|
+
}
|
|
1032
|
+
return '';
|
|
1033
|
+
};
|
|
1034
|
+
/**
|
|
1035
|
+
* Thêm một dòng mới ở cấp thụt cho trước, gộp khoảng trắng đuôi.
|
|
1036
|
+
*
|
|
1037
|
+
* 🔴 Đang ở ĐẦU DÒNG rồi thì chỉ đặt lại mức thụt, KHÔNG thêm `\n` nữa: mở ngoặc câu con rồi gặp
|
|
1038
|
+
* ngay `SELECT` là hai lần gọi liên tiếp, thêm cả hai thì sinh một dòng trắng giữa `FROM (` và
|
|
1039
|
+
* `SELECT` (đo 21/09/2026).
|
|
1040
|
+
*/
|
|
1041
|
+
const breakLine = (state, indentLevel) => {
|
|
1042
|
+
const indent = INDENT_STEP.repeat(Math.max(indentLevel, 0));
|
|
1043
|
+
const trimmed = state.out.replace(/[ \t]+$/, '');
|
|
1044
|
+
state.out = trimmed.endsWith('\n') ? `${trimmed}${indent}` : `${trimmed}\n${indent}`;
|
|
1045
|
+
};
|
|
1046
|
+
/**
|
|
1047
|
+
* Định dạng lại một câu lệnh SQL.
|
|
1048
|
+
*
|
|
1049
|
+
* 🔴 NGUYÊN TẮC BẤT BIẾN: chỉ đổi KHOẢNG TRẮNG và CHỮ HOA-THƯỜNG CỦA TỪ KHOÁ. Không thêm, không bớt,
|
|
1050
|
+
* không đổi thứ tự bất kỳ ký tự nào khác — nhờ vậy định dạng lại không bao giờ làm sai câu lệnh.
|
|
1051
|
+
* Bỏ khoảng trắng và chuẩn hoá chữ thì chuỗi trước và sau phải trùng khít; spec có ca kiểm điều này.
|
|
1052
|
+
*
|
|
1053
|
+
* 🔴 Câu lệnh rỗng hoặc chỉ có khoảng trắng thì trả `''` — nơi gọi không phải tự kiểm.
|
|
1054
|
+
*/
|
|
1055
|
+
const sqlFormat = (sql) => {
|
|
1056
|
+
if (!sql?.trim()) {
|
|
1057
|
+
return '';
|
|
1058
|
+
}
|
|
1059
|
+
const fragments = sqlSplitPreservingLiterals(sql);
|
|
1060
|
+
const state = { out: '', depth: 0, fnDepth: 0 };
|
|
1061
|
+
for (const fragment of fragments) {
|
|
1062
|
+
if (fragment.isLiteral) {
|
|
1063
|
+
state.out += fragment.text;
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
// Gộp mọi chuỗi khoảng trắng thành một dấu cách để xử lý đồng nhất.
|
|
1067
|
+
const text = fragment.text.replace(/\s+/g, ' ');
|
|
1068
|
+
let i = 0;
|
|
1069
|
+
while (i < text.length) {
|
|
1070
|
+
const ch = text[i];
|
|
1071
|
+
// Mở ngoặc: tăng cấp. Ngoặc của HÀM thì đánh dấu để dấu phẩy bên trong không xuống dòng.
|
|
1072
|
+
if (ch === '(') {
|
|
1073
|
+
// 🔴 Phải xét TỪ đứng ngay trước: ngoặc dán liền một định danh (`coalesce(`) là ngoặc hàm,
|
|
1074
|
+
// còn ngoặc sau một TỪ KHOÁ (`FROM (`, `IN (`, `EXISTS (`) mở một CÂU CON và phải được định
|
|
1075
|
+
// dạng như câu lệnh đầy đủ. Chỉ kiểm `[a-zA-Z0-9_$]\s*$` thì `FROM (` bị nhận nhầm là hàm,
|
|
1076
|
+
// nên toàn bộ câu con giữ nguyên chữ thường và không xuống dòng (đo 21/09/2026).
|
|
1077
|
+
const prevWord = (/([a-zA-Z0-9_$]+)\s*$/.exec(state.out)?.[1] ?? '').toUpperCase();
|
|
1078
|
+
const isGluedToPrev = /[a-zA-Z0-9_$]$/.test(state.out);
|
|
1079
|
+
const isKeyword = [...CLAUSE_KEYWORDS, ...INDENTED_KEYWORDS, ...INLINE_KEYWORDS].includes(prevWord);
|
|
1080
|
+
/**
|
|
1081
|
+
* 🔴 Ngoặc sau các từ khoá này chứa DANH SÁCH GIÁ TRỊ hoặc một biểu thức ngắn, không phải
|
|
1082
|
+
* câu con — giữ trên một dòng. Tách ra thì `y IN (1, 2, 3)` thành 5 dòng, đọc còn khó hơn
|
|
1083
|
+
* lúc chưa định dạng (đo 21/09/2026).
|
|
1084
|
+
*/
|
|
1085
|
+
const isInlineParen = ['IN', 'VALUES', 'OVER', 'PARTITION BY', 'USING', 'CAST'].includes(prevWord);
|
|
1086
|
+
const isFnCall = (isGluedToPrev && !isKeyword) || isInlineParen;
|
|
1087
|
+
state.out += '(';
|
|
1088
|
+
state.depth += 1;
|
|
1089
|
+
if (isFnCall) {
|
|
1090
|
+
state.fnDepth += 1;
|
|
1091
|
+
}
|
|
1092
|
+
else {
|
|
1093
|
+
breakLine(state, state.depth);
|
|
1094
|
+
}
|
|
1095
|
+
i += 1;
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
if (ch === ')') {
|
|
1099
|
+
state.depth = Math.max(state.depth - 1, 0);
|
|
1100
|
+
if (state.fnDepth > 0) {
|
|
1101
|
+
state.fnDepth -= 1;
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
breakLine(state, state.depth);
|
|
1105
|
+
}
|
|
1106
|
+
state.out += ')';
|
|
1107
|
+
i += 1;
|
|
1108
|
+
continue;
|
|
1109
|
+
}
|
|
1110
|
+
// Dấu phẩy: xuống dòng, TRỪ khi đang trong ngoặc của hàm (`sum(a, b)` giữ một dòng).
|
|
1111
|
+
if (ch === ',') {
|
|
1112
|
+
state.out = state.out.replace(/[ \t]+$/, '');
|
|
1113
|
+
state.out += ',';
|
|
1114
|
+
if (!state.fnDepth) {
|
|
1115
|
+
breakLine(state, state.depth + 1);
|
|
1116
|
+
}
|
|
1117
|
+
else {
|
|
1118
|
+
state.out += ' ';
|
|
1119
|
+
}
|
|
1120
|
+
i += 1;
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
// Dấu chấm phẩy kết câu: sát chữ trước rồi xuống dòng.
|
|
1124
|
+
if (ch === ';') {
|
|
1125
|
+
state.out = `${state.out.replace(/[ \t]+$/, '')};`;
|
|
1126
|
+
state.depth = 0;
|
|
1127
|
+
state.fnDepth = 0;
|
|
1128
|
+
breakLine(state, 0);
|
|
1129
|
+
i += 1;
|
|
1130
|
+
continue;
|
|
1131
|
+
}
|
|
1132
|
+
// 🔴 Trong ngoặc của HÀM thì không xét từ khoá mệnh đề: `count(*) over (partition by x)` mà
|
|
1133
|
+
// tách `PARTITION BY` ra dòng riêng thì đọc còn khó hơn.
|
|
1134
|
+
if (!state.fnDepth) {
|
|
1135
|
+
const clauseKeyword = matchKeyword(text, i, CLAUSE_KEYWORDS);
|
|
1136
|
+
if (clauseKeyword) {
|
|
1137
|
+
if (state.out.trim()) {
|
|
1138
|
+
breakLine(state, state.depth);
|
|
1139
|
+
}
|
|
1140
|
+
state.out += `${clauseKeyword} `;
|
|
1141
|
+
i += clauseKeyword.length;
|
|
1142
|
+
// Bỏ dấu cách ngay sau từ khoá, đã tự thêm ở trên.
|
|
1143
|
+
if (text[i] === ' ') {
|
|
1144
|
+
i += 1;
|
|
1145
|
+
}
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
const indentedKeyword = matchKeyword(text, i, INDENTED_KEYWORDS);
|
|
1149
|
+
if (indentedKeyword) {
|
|
1150
|
+
if (state.out.trim()) {
|
|
1151
|
+
breakLine(state, state.depth + 1);
|
|
1152
|
+
}
|
|
1153
|
+
state.out += `${indentedKeyword} `;
|
|
1154
|
+
i += indentedKeyword.length;
|
|
1155
|
+
if (text[i] === ' ') {
|
|
1156
|
+
i += 1;
|
|
1157
|
+
}
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
const inlineKeyword = matchKeyword(text, i, INLINE_KEYWORDS);
|
|
1162
|
+
if (inlineKeyword) {
|
|
1163
|
+
state.out += inlineKeyword;
|
|
1164
|
+
i += inlineKeyword.length;
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
// Toán tử: đúng một dấu cách hai bên, dù người dùng gõ `c=1` hay `c = 1`.
|
|
1168
|
+
const operator = OPERATORS.find((op) => text.startsWith(op, i));
|
|
1169
|
+
if (operator) {
|
|
1170
|
+
/**
|
|
1171
|
+
* 🔴 Dấu trừ đứng đầu biểu thức là DẤU ÂM, không phải phép trừ: `-1` giữ nguyên, `a - 1`
|
|
1172
|
+
* thì tách. Nhận nhầm thì `limit -1` thành `limit - 1` — đổi hẳn nghĩa câu lệnh.
|
|
1173
|
+
*
|
|
1174
|
+
* Ba chỗ nó là dấu âm: đầu câu, ngay sau một dấu ngắt/toán tử khác, và ngay sau một TỪ KHOÁ
|
|
1175
|
+
* (`LIMIT -1`, `WHERE -1 = x`). Trường hợp cuối phải xét riêng vì ký tự liền trước là chữ
|
|
1176
|
+
* cái, không khớp bảng dấu ngắt (đo 21/09/2026).
|
|
1177
|
+
*/
|
|
1178
|
+
const trimmedLeft = state.out.replace(/[ \t]+$/, '');
|
|
1179
|
+
const adjacentWord = /([a-zA-Z0-9_$]+)$/.exec(trimmedLeft)?.[1] ?? '';
|
|
1180
|
+
const afterKeyword = Boolean(adjacentWord) && [...CLAUSE_KEYWORDS, ...INDENTED_KEYWORDS, ...INLINE_KEYWORDS].includes(adjacentWord.toUpperCase());
|
|
1181
|
+
const isNegativeSign = operator === '-' && (!trimmedLeft || /[(,=<>+\-*/%]$/.test(trimmedLeft) || afterKeyword);
|
|
1182
|
+
if (isNegativeSign) {
|
|
1183
|
+
/**
|
|
1184
|
+
* 🔴 Dán liền dấu âm vào SỐ, nhưng phải giữ khoảng cách với thứ đứng trước nó — chỉ có
|
|
1185
|
+
* `(` và `,` là dán được:
|
|
1186
|
+
* `(-1)` · `(a, -1)` → dán liền
|
|
1187
|
+
* `LIMIT -1` · `b = -1` → phải có dấu cách, cắt sạch thì ra `LIMIT-1` / `b =-1`
|
|
1188
|
+
*/
|
|
1189
|
+
const glueToPrev = /[(,]$/.test(trimmedLeft);
|
|
1190
|
+
state.out = glueToPrev ? `${trimmedLeft}${operator}` : `${trimmedLeft} ${operator}`;
|
|
1191
|
+
i += operator.length;
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
state.out = `${trimmedLeft} ${operator} `;
|
|
1195
|
+
i += operator.length;
|
|
1196
|
+
// Bỏ khoảng trắng người dùng đã gõ sau toán tử, đã tự thêm một dấu cách ở trên.
|
|
1197
|
+
while (text[i] === ' ') {
|
|
1198
|
+
i += 1;
|
|
1199
|
+
}
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
// Không gộp hai dấu cách liền nhau, và không mở đầu dòng bằng dấu cách.
|
|
1203
|
+
if (ch === ' ' && (state.out.endsWith(' ') || state.out.endsWith('\n') || !state.out)) {
|
|
1204
|
+
i += 1;
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
state.out += ch;
|
|
1208
|
+
i += 1;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
return state.out
|
|
1212
|
+
// Gom nhiều dòng trắng liên tiếp thành một dòng trắng.
|
|
1213
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
1214
|
+
// Bỏ khoảng trắng cuối mỗi dòng.
|
|
1215
|
+
.split('\n')
|
|
1216
|
+
.map((line) => line.replace(/\s+$/, ''))
|
|
1217
|
+
.join('\n')
|
|
1218
|
+
.trim();
|
|
1219
|
+
};
|
|
1220
|
+
/**
|
|
1221
|
+
* Bỏ mọi khoảng trắng và chuẩn hoá chữ — dùng để KIỂM việc định dạng không đổi nghĩa câu lệnh.
|
|
1222
|
+
*
|
|
1223
|
+
* 🔴 Giữ nguyên nội dung vùng chuỗi/chú thích khi chuẩn hoá: chữ trong `'Hà Nội'` là dữ liệu, không
|
|
1224
|
+
* phải mã lệnh, nên không được viết hoa nó khi so sánh.
|
|
1225
|
+
*/
|
|
1226
|
+
const sqlNormalizeForCompare = (sql) => sqlSplitPreservingLiterals(sql)
|
|
1227
|
+
.map((fragment) => (fragment.isLiteral ? fragment.text : fragment.text.replace(/\s+/g, '').toUpperCase()))
|
|
1228
|
+
.join('');
|
|
1229
|
+
/** Ngôn ngữ có bộ định dạng — nơi khác hỏi trước khi hiện nút "Định dạng". */
|
|
1230
|
+
const FORMATTABLE_LANGUAGES = ['sql', 'json'];
|
|
1231
|
+
/**
|
|
1232
|
+
* Định dạng nội dung theo NGÔN NGỮ đang chọn. Ngôn ngữ chưa hỗ trợ thì trả nguyên văn.
|
|
1233
|
+
*
|
|
1234
|
+
* 🔴 Trả NGUYÊN VĂN khi không định dạng được (kể cả JSON hỏng cú pháp), KHÔNG ném lỗi và cũng không
|
|
1235
|
+
* trả rỗng: người dùng bấm nhầm nút trên một đoạn đang viết dở mà mất sạch chữ thì còn tệ hơn nhiều
|
|
1236
|
+
* so với việc nút không làm gì.
|
|
1237
|
+
*/
|
|
1238
|
+
const formatByLanguage = (content, language) => {
|
|
1239
|
+
if (!content?.trim()) {
|
|
1240
|
+
return content ?? '';
|
|
1241
|
+
}
|
|
1242
|
+
if (language === 'sql') {
|
|
1243
|
+
return sqlFormat(content);
|
|
1244
|
+
}
|
|
1245
|
+
if (language === 'json') {
|
|
1246
|
+
try {
|
|
1247
|
+
return JSON.stringify(JSON.parse(content), null, 2);
|
|
1248
|
+
}
|
|
1249
|
+
catch {
|
|
1250
|
+
// JSON chưa hợp lệ (đang gõ dở) — giữ nguyên, người dùng tự sửa rồi bấm lại.
|
|
1251
|
+
return content;
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
return content;
|
|
1255
|
+
};
|
|
1256
|
+
|
|
171
1257
|
class LibsUiComponentsPreviewTextDataComponent {
|
|
172
1258
|
// ==========================================================================
|
|
173
1259
|
// PRIVATE PROPERTIES
|
|
@@ -211,6 +1297,23 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
211
1297
|
hiddenAction = input(false, {
|
|
212
1298
|
transform: (value) => value ?? false,
|
|
213
1299
|
});
|
|
1300
|
+
/** Số dòng tối thiểu: nếu content ít dòng hơn sẽ tự bù dòng trống (xử lý 1 lần khi khởi tạo editor). Bỏ trống = không bù. */
|
|
1301
|
+
minLines = input();
|
|
1302
|
+
/** Số dòng tối đa: vượt quá editor sẽ giới hạn chiều cao và xuất hiện vùng cuộn (xử lý 1 lần khi khởi tạo editor). Bỏ trống = không giới hạn. */
|
|
1303
|
+
maxLines = input();
|
|
1304
|
+
/**
|
|
1305
|
+
* Element container bên ngoài để editor tự tính chiều cao theo `min-height`/`max-height` (CSS) của nó.
|
|
1306
|
+
* Khi truyền, editor đọc min/max-height của container, trừ phần header/toolbar phía trên, rồi snap
|
|
1307
|
+
* chiều cao vùng cuộn về đúng bội số dòng (không cắt nửa dòng) + bật scroll khi vượt max.
|
|
1308
|
+
* CẤM cấu hình đồng thời với `minLines`/`maxLines` (sẽ throw lỗi) — container tự quản lý min/max.
|
|
1309
|
+
*/
|
|
1310
|
+
containerElement = input();
|
|
1311
|
+
/** z-index cho popover dropdown chọn ngôn ngữ. */
|
|
1312
|
+
zIndexPopover = input();
|
|
1313
|
+
/** Ẩn ô search trong dropdown chọn ngôn ngữ (danh sách ngôn ngữ ngắn thường không cần tìm kiếm). */
|
|
1314
|
+
hiddenSearchLang = input(false, {
|
|
1315
|
+
transform: (value) => value ?? false,
|
|
1316
|
+
});
|
|
214
1317
|
lintIgnorePatterns = input(['Cannot use import statement outside a module', 'Unexpected token export', 'import ', '@angular/core'], {
|
|
215
1318
|
transform: (value) => value ?? ['Cannot use import statement outside a module', 'Unexpected token export', 'import ', '@angular/core'],
|
|
216
1319
|
});
|
|
@@ -237,6 +1340,26 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
237
1340
|
background = input('#f8f9fa', {
|
|
238
1341
|
transform: (value) => value ?? '#f8f9fa',
|
|
239
1342
|
});
|
|
1343
|
+
/**
|
|
1344
|
+
* Hiện nút "Định dạng" trên thanh công cụ — bấm một lần là nội dung tự căn chỉnh gọn gàng, người
|
|
1345
|
+
* dùng không phải gõ dấu cách và xuống dòng bằng tay.
|
|
1346
|
+
*
|
|
1347
|
+
* 🔴 Mặc định BẬT nhưng CHỈ hiện khi ô đang sửa được và ngôn ngữ đang chọn có bộ định dạng
|
|
1348
|
+
* (hiện có `sql` và `json`) — xem `coTheDinhDang`. Nhờ vậy nơi dùng không phải khai gì thêm, mà
|
|
1349
|
+
* ô chỉ-đọc hay ngôn ngữ chưa hỗ trợ cũng không mọc ra một nút bấm không làm gì.
|
|
1350
|
+
*/
|
|
1351
|
+
showFormatAction = input(true, {
|
|
1352
|
+
transform: (value) => value ?? true,
|
|
1353
|
+
});
|
|
1354
|
+
/**
|
|
1355
|
+
* Tự định dạng NGAY khi nạp nội dung vào ô.
|
|
1356
|
+
*
|
|
1357
|
+
* 🔴 Mặc định TẮT: nội dung người dùng đã lưu có thể đang được họ căn theo ý riêng, tự sửa lúc mở
|
|
1358
|
+
* ra là ghi đè công của họ mà không ai bấm gì. Bật khi nguồn nội dung là máy sinh (mock, mẫu).
|
|
1359
|
+
*/
|
|
1360
|
+
autoFormatOnLoad = input(false, {
|
|
1361
|
+
transform: (value) => value ?? false,
|
|
1362
|
+
});
|
|
240
1363
|
// ==========================================================================
|
|
241
1364
|
// OUTPUTS
|
|
242
1365
|
// ==========================================================================
|
|
@@ -253,7 +1376,11 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
253
1376
|
constructor() {
|
|
254
1377
|
// Effect để sync content từ input vào editor
|
|
255
1378
|
effect(() => {
|
|
256
|
-
|
|
1379
|
+
// 🔴 `autoFormatOnLoad` áp NGAY TẠI ĐÂY, không ở `ngOnInit`: nội dung có thể về sau một nhịp
|
|
1380
|
+
// (từ API), lúc `ngOnInit` chạy thì `content()` còn rỗng.
|
|
1381
|
+
// 🔴 Đọc `langSelected` (model.required) CHỈ khi editor đã dựng — trước đó nó chưa có giá trị
|
|
1382
|
+
// và đọc là văng `NG0952`.
|
|
1383
|
+
const newContent = this.autoFormatOnLoad() && this.isInitialized ? formatByLanguage(this.content(), this.langSelected()) : this.content();
|
|
257
1384
|
if (this.isInitialized && this.editorViewInstance) {
|
|
258
1385
|
const currentContent = this.editorViewInstance.state.doc.toString();
|
|
259
1386
|
if (newContent !== currentContent) {
|
|
@@ -273,7 +1400,7 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
273
1400
|
if (!this.isInitialized || !this.editorViewInstance)
|
|
274
1401
|
return;
|
|
275
1402
|
this.editorViewInstance.dispatch({
|
|
276
|
-
effects: this.completionsCompartment.reconfigure(items.length ?
|
|
1403
|
+
effects: this.completionsCompartment.reconfigure(items.length ? buildCompletionExtension(items) : []),
|
|
277
1404
|
});
|
|
278
1405
|
});
|
|
279
1406
|
// Effect để cập nhật forbidden patterns khi input thay đổi
|
|
@@ -282,7 +1409,7 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
282
1409
|
if (!this.isInitialized || !this.editorViewInstance)
|
|
283
1410
|
return;
|
|
284
1411
|
this.editorViewInstance.dispatch({
|
|
285
|
-
effects: this.forbiddenCompartment.reconfigure(patterns.length ?
|
|
1412
|
+
effects: this.forbiddenCompartment.reconfigure(patterns.length ? buildForbiddenExtension(patterns, (violations) => this.outViolations.emit(violations)) : []),
|
|
286
1413
|
});
|
|
287
1414
|
});
|
|
288
1415
|
// Cleanup khi component bị destroy
|
|
@@ -314,10 +1441,11 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
314
1441
|
const languageExtension = await this.loadLanguageExtension(this.langSelected());
|
|
315
1442
|
const linterExtension = await this.loadLinterExtension(this.langSelected());
|
|
316
1443
|
this.editorViewInstance = new EditorView({
|
|
317
|
-
doc: this.content(),
|
|
1444
|
+
doc: applyMinLines(this.content(), this.minLines()),
|
|
318
1445
|
parent: this.containerPreview().nativeElement,
|
|
319
1446
|
extensions: this.createExtensions(languageExtension, linterExtension),
|
|
320
1447
|
});
|
|
1448
|
+
applyMaxHeight(this.editorViewInstance, { minLines: this.minLines(), maxLines: this.maxLines(), container: this.containerElement() });
|
|
321
1449
|
}
|
|
322
1450
|
/**
|
|
323
1451
|
* Tạo danh sách extensions cho editor
|
|
@@ -330,8 +1458,8 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
330
1458
|
this.languageCompartment.of(languageExtension),
|
|
331
1459
|
this.linterCompartment.of(linterExtension),
|
|
332
1460
|
// Compartment cho custom completions — Prec.highest để override basicSetup's autocompletion
|
|
333
|
-
Prec.highest(this.completionsCompartment.of(initialCompletions.length ?
|
|
334
|
-
this.forbiddenCompartment.of(initialPatterns.length ?
|
|
1461
|
+
Prec.highest(this.completionsCompartment.of(initialCompletions.length ? buildCompletionExtension(initialCompletions) : [])),
|
|
1462
|
+
this.forbiddenCompartment.of(initialPatterns.length ? buildForbiddenExtension(initialPatterns, (violations) => this.outViolations.emit(violations)) : []),
|
|
335
1463
|
this.createLightTheme(),
|
|
336
1464
|
EditorView.editable.of(this.editable()),
|
|
337
1465
|
this.wrapCompartment.of(EditorView.lineWrapping),
|
|
@@ -411,339 +1539,84 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
411
1539
|
// ==========================================================================
|
|
412
1540
|
// PUBLIC METHODS - Linter factories (được gọi từ registry)
|
|
413
1541
|
// ==========================================================================
|
|
414
|
-
/**
|
|
415
|
-
* Tạo JavaScript linter với 2-pass detection:
|
|
416
|
-
* 1. Text-based scan cho trailing dot (parser thường đặt error node sai vị trí với pattern này)
|
|
417
|
-
* 2. syntaxTree cho các lỗi thực sự khác, bỏ qua vùng bị ảnh hưởng bởi trailing dot
|
|
418
|
-
*/
|
|
1542
|
+
/** JavaScript/TypeScript linter — pipeline trong `linters/js-linter.ts` (babel + trailing-dot + thiếu `;` + biến chưa khai báo). */
|
|
419
1543
|
createJsLinter() {
|
|
420
|
-
return linter((view) => {
|
|
421
|
-
const diagnostics =
|
|
422
|
-
const doc = view.state.doc;
|
|
423
|
-
// Pass 1: Text-based trailing dot detection — đặt diagnostic đúng tại vị trí dấu chấm
|
|
424
|
-
const trailingDotLines = new Set();
|
|
425
|
-
for (let lineNum = 1; lineNum <= doc.lines; lineNum++) {
|
|
426
|
-
const line = doc.line(lineNum);
|
|
427
|
-
const trimmed = line.text.trimEnd();
|
|
428
|
-
const match = /(\w+)\.\s*$/.exec(trimmed);
|
|
429
|
-
if (!match)
|
|
430
|
-
continue;
|
|
431
|
-
trailingDotLines.add(lineNum);
|
|
432
|
-
const dotPos = line.from + trimmed.lastIndexOf('.');
|
|
433
|
-
diagnostics.push({
|
|
434
|
-
from: dotPos,
|
|
435
|
-
to: dotPos + 1,
|
|
436
|
-
severity: 'error',
|
|
437
|
-
message: `Incomplete property access on "${match[1]}"`,
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
// Đánh dấu các dòng bị ảnh hưởng bởi trailing dot (trailing-dot line + 4 dòng tiếp theo)
|
|
441
|
-
// để lọc cascading errors từ syntaxTree
|
|
442
|
-
const taintedLines = new Set();
|
|
443
|
-
for (const lineNum of trailingDotLines) {
|
|
444
|
-
for (let i = lineNum; i <= Math.min(lineNum + 4, doc.lines); i++) {
|
|
445
|
-
taintedLines.add(i);
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
// Pass 2: syntaxTree cho các lỗi khác (chỉ non-empty range, bỏ qua vùng tainted)
|
|
449
|
-
const tree = syntaxTree(view.state);
|
|
450
|
-
tree.iterate({
|
|
451
|
-
enter: (node) => {
|
|
452
|
-
if (!node.type.isError)
|
|
453
|
-
return;
|
|
454
|
-
if (node.from === node.to)
|
|
455
|
-
return; // Bỏ qua empty-range node (cascading error)
|
|
456
|
-
const errorLineNum = doc.lineAt(node.from).number;
|
|
457
|
-
if (taintedLines.has(errorLineNum))
|
|
458
|
-
return;
|
|
459
|
-
diagnostics.push({
|
|
460
|
-
from: node.from,
|
|
461
|
-
to: Math.min(node.to, doc.length),
|
|
462
|
-
severity: 'error',
|
|
463
|
-
message: this.buildJsErrorMessage(doc, node),
|
|
464
|
-
});
|
|
465
|
-
},
|
|
466
|
-
});
|
|
1544
|
+
return linter(async (view) => {
|
|
1545
|
+
const diagnostics = await computeJsDiagnostics(view.state.doc, view.state.doc.toString(), new Set(this.completions().map((item) => item.label)));
|
|
467
1546
|
this.syntaxErrors.emit(diagnostics);
|
|
468
1547
|
return diagnostics;
|
|
469
1548
|
});
|
|
470
1549
|
}
|
|
471
|
-
|
|
472
|
-
const text = doc.sliceString(node.from, node.to).trim();
|
|
473
|
-
if (text)
|
|
474
|
-
return `JavaScript syntax error near "${text}"`;
|
|
475
|
-
const prevToken = this.getTokenBefore(doc, node.from);
|
|
476
|
-
if (!prevToken)
|
|
477
|
-
return 'JavaScript syntax error';
|
|
478
|
-
if (prevToken.endsWith('('))
|
|
479
|
-
return 'Missing closing ")"';
|
|
480
|
-
if (prevToken.endsWith('['))
|
|
481
|
-
return 'Missing closing "]"';
|
|
482
|
-
if (/^function$/i.test(prevToken))
|
|
483
|
-
return 'Expected function name or "("';
|
|
484
|
-
if (/^return$/i.test(prevToken))
|
|
485
|
-
return 'Invalid expression after "return"';
|
|
486
|
-
if (/^=>$/.test(prevToken))
|
|
487
|
-
return 'Expected function body after "=>"';
|
|
488
|
-
if (/^const$|^let$|^var$/i.test(prevToken))
|
|
489
|
-
return 'Expected variable name';
|
|
490
|
-
return `JavaScript syntax error near "${prevToken}"`;
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Tạo JSON linter
|
|
494
|
-
* Sử dụng JSON.parse để validate
|
|
495
|
-
*/
|
|
1550
|
+
/** JSON linter — logic trong `linters/json-linter.ts`. */
|
|
496
1551
|
createJsonLinter() {
|
|
497
1552
|
return linter((view) => {
|
|
498
|
-
const
|
|
499
|
-
const diagnostics = [];
|
|
500
|
-
try {
|
|
501
|
-
JSON.parse(text);
|
|
502
|
-
}
|
|
503
|
-
catch (err) {
|
|
504
|
-
diagnostics.push({
|
|
505
|
-
from: 0,
|
|
506
|
-
to: text.length,
|
|
507
|
-
severity: 'error',
|
|
508
|
-
message: get(err, 'message', ''),
|
|
509
|
-
});
|
|
510
|
-
}
|
|
1553
|
+
const diagnostics = computeJsonDiagnostics(view);
|
|
511
1554
|
this.syntaxErrors.emit(diagnostics);
|
|
512
1555
|
return diagnostics;
|
|
513
1556
|
});
|
|
514
1557
|
}
|
|
515
|
-
/**
|
|
516
|
-
* Tạo SQL linter
|
|
517
|
-
*/
|
|
1558
|
+
/** SQL linter — logic trong `linters/sql-linter.ts`. */
|
|
518
1559
|
createSqlLinter() {
|
|
519
1560
|
return linter((view) => {
|
|
520
|
-
const diagnostics =
|
|
521
|
-
const doc = view.state.doc;
|
|
522
|
-
const tree = syntaxTree(view.state);
|
|
523
|
-
tree.iterate({
|
|
524
|
-
enter: (node) => {
|
|
525
|
-
if (!node.type.isError)
|
|
526
|
-
return;
|
|
527
|
-
diagnostics.push({
|
|
528
|
-
from: Math.max(0, node.from - 1),
|
|
529
|
-
to: node.from,
|
|
530
|
-
severity: 'error',
|
|
531
|
-
message: this.buildSqlErrorMessage(doc, node),
|
|
532
|
-
});
|
|
533
|
-
},
|
|
534
|
-
});
|
|
1561
|
+
const diagnostics = computeSqlDiagnostics(view);
|
|
535
1562
|
this.syntaxErrors.emit(diagnostics);
|
|
536
1563
|
return diagnostics;
|
|
537
1564
|
});
|
|
538
1565
|
}
|
|
539
|
-
|
|
540
|
-
if (node.from !== node.to) {
|
|
541
|
-
const text = doc.sliceString(node.from, node.to);
|
|
542
|
-
return `SQL syntax error near "${text}"`;
|
|
543
|
-
}
|
|
544
|
-
const prevToken = this.getTokenBefore(doc, node.from);
|
|
545
|
-
if (!prevToken) {
|
|
546
|
-
return 'SQL syntax error at beginning of statement';
|
|
547
|
-
}
|
|
548
|
-
if (/FROM$/i.test(prevToken)) {
|
|
549
|
-
return 'Expected table name after FROM';
|
|
550
|
-
}
|
|
551
|
-
if (/SELECT$/i.test(prevToken)) {
|
|
552
|
-
return 'Expected column list after SELECT';
|
|
553
|
-
}
|
|
554
|
-
if (/WHERE$/i.test(prevToken)) {
|
|
555
|
-
return 'Expected condition after WHERE';
|
|
556
|
-
}
|
|
557
|
-
if (prevToken.endsWith('(')) {
|
|
558
|
-
return 'Missing closing ")"';
|
|
559
|
-
}
|
|
560
|
-
return `Unexpected end of SQL after "${prevToken}"`;
|
|
561
|
-
}
|
|
562
|
-
getTokenBefore(doc, pos) {
|
|
563
|
-
const start = Math.max(0, pos - 30);
|
|
564
|
-
const text = doc.sliceString(start, pos);
|
|
565
|
-
const match = /(\S+)\s*$/.exec(text);
|
|
566
|
-
return match?.[1] ?? '';
|
|
567
|
-
}
|
|
568
|
-
/**
|
|
569
|
-
* Tạo Python linter dựa trên syntaxTree parse error — cùng approach với SQL linter.
|
|
570
|
-
* Phát hiện lỗi cú pháp mà CodeMirror Python parser đánh dấu là error node.
|
|
571
|
-
*/
|
|
1566
|
+
/** Python linter — logic trong `linters/python-linter.ts`. */
|
|
572
1567
|
createPythonLinter() {
|
|
573
1568
|
return linter((view) => {
|
|
574
|
-
const diagnostics =
|
|
575
|
-
const doc = view.state.doc;
|
|
576
|
-
const tree = syntaxTree(view.state);
|
|
577
|
-
tree.iterate({
|
|
578
|
-
enter: (node) => {
|
|
579
|
-
if (!node.type.isError)
|
|
580
|
-
return;
|
|
581
|
-
const from = Math.max(0, node.from - 1);
|
|
582
|
-
const to = node.from === node.to ? node.from + 1 : node.to;
|
|
583
|
-
diagnostics.push({
|
|
584
|
-
from,
|
|
585
|
-
to: Math.min(to, doc.length),
|
|
586
|
-
severity: 'error',
|
|
587
|
-
message: this.buildPythonErrorMessage(doc, node),
|
|
588
|
-
});
|
|
589
|
-
},
|
|
590
|
-
});
|
|
1569
|
+
const diagnostics = computePythonDiagnostics(view);
|
|
591
1570
|
this.syntaxErrors.emit(diagnostics);
|
|
592
1571
|
return diagnostics;
|
|
593
1572
|
});
|
|
594
1573
|
}
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
const textSuffix = text ? ` near "${text}"` : '';
|
|
599
|
-
return `Python syntax error${textSuffix}`;
|
|
600
|
-
}
|
|
601
|
-
const prevToken = this.getTokenBefore(doc, node.from);
|
|
602
|
-
if (!prevToken) {
|
|
603
|
-
return 'Python syntax error';
|
|
604
|
-
}
|
|
605
|
-
if (/^def$/i.test(prevToken))
|
|
606
|
-
return 'Expected function name after "def"';
|
|
607
|
-
if (/^class$/i.test(prevToken))
|
|
608
|
-
return 'Expected class name after "class"';
|
|
609
|
-
if (/^return$/i.test(prevToken))
|
|
610
|
-
return 'Invalid expression after "return"';
|
|
611
|
-
if (/^import$/i.test(prevToken))
|
|
612
|
-
return 'Expected module name after "import"';
|
|
613
|
-
if (/^from$/i.test(prevToken))
|
|
614
|
-
return 'Expected module name after "from"';
|
|
615
|
-
if (/^if$/i.test(prevToken))
|
|
616
|
-
return 'Expected condition after "if"';
|
|
617
|
-
if (/^elif$/i.test(prevToken))
|
|
618
|
-
return 'Expected condition after "elif"';
|
|
619
|
-
if (/^while$/i.test(prevToken))
|
|
620
|
-
return 'Expected condition after "while"';
|
|
621
|
-
if (/^for$/i.test(prevToken))
|
|
622
|
-
return 'Expected variable after "for"';
|
|
623
|
-
if (prevToken.endsWith('.'))
|
|
624
|
-
return `Incomplete attribute access on "${prevToken.slice(0, -1)}"`;
|
|
625
|
-
if (prevToken.endsWith('('))
|
|
626
|
-
return 'Missing closing ")"';
|
|
627
|
-
if (prevToken.endsWith('['))
|
|
628
|
-
return 'Missing closing "]"';
|
|
629
|
-
return `Python syntax error near "${prevToken}"`;
|
|
630
|
-
}
|
|
1574
|
+
// ==========================================================================
|
|
1575
|
+
// PROTECTED METHODS - Event handlers
|
|
1576
|
+
// ==========================================================================
|
|
631
1577
|
/**
|
|
632
|
-
*
|
|
633
|
-
*
|
|
634
|
-
*
|
|
635
|
-
*
|
|
1578
|
+
* Nút "Định dạng" có hiện không.
|
|
1579
|
+
*
|
|
1580
|
+
* 🔴 Ba điều kiện cùng lúc: nơi dùng chưa tắt · ô đang SỬA ĐƯỢC · ngôn ngữ đang chọn có bộ định
|
|
1581
|
+
* dạng. Ô chỉ-đọc mà mọc ra nút bấm không làm gì thì người dùng bấm rồi tưởng hỏng.
|
|
636
1582
|
*/
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
type: p.type ?? 'property',
|
|
651
|
-
detail: p.detail ?? '',
|
|
652
|
-
info: p.info ?? '',
|
|
653
|
-
})),
|
|
654
|
-
};
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
// Chế độ top-level: gợi ý tên biến/object khi gõ ký tự
|
|
658
|
-
const word = context.matchBefore(/\w*/);
|
|
659
|
-
if (!word || (word.from === word.to && !context.explicit))
|
|
660
|
-
return null;
|
|
661
|
-
return {
|
|
662
|
-
from: word.from,
|
|
663
|
-
options: items.map((item) => ({
|
|
664
|
-
label: item.label,
|
|
665
|
-
type: item.type ?? 'variable',
|
|
666
|
-
detail: item.detail ?? '',
|
|
667
|
-
info: item.info ?? '',
|
|
668
|
-
})),
|
|
669
|
-
};
|
|
670
|
-
};
|
|
671
|
-
return autocompletion({ override: [completionSource] });
|
|
672
|
-
}
|
|
1583
|
+
canFormat = computed(() => {
|
|
1584
|
+
if (!this.showFormatAction() || !this.editable()) {
|
|
1585
|
+
return false;
|
|
1586
|
+
}
|
|
1587
|
+
// 🔴 `langSelected` là `model.required` — đọc lúc nơi dùng chưa gán là văng `NG0952`, mà
|
|
1588
|
+
// `computed` này chạy ngay nhịp vẽ đầu. Bọc lại để nút chỉ ẩn đi thay vì làm vỡ cả ô soạn.
|
|
1589
|
+
try {
|
|
1590
|
+
return FORMATTABLE_LANGUAGES.includes(this.langSelected());
|
|
1591
|
+
}
|
|
1592
|
+
catch {
|
|
1593
|
+
return false;
|
|
1594
|
+
}
|
|
1595
|
+
});
|
|
673
1596
|
/**
|
|
674
|
-
*
|
|
675
|
-
*
|
|
676
|
-
*
|
|
1597
|
+
* Căn chỉnh lại nội dung đang gõ theo ngôn ngữ đang chọn.
|
|
1598
|
+
*
|
|
1599
|
+
* 🔴 Đọc nội dung từ CHÍNH editor (`state.doc`), không từ `content()`: `content` là input ban đầu,
|
|
1600
|
+
* còn thứ người dùng vừa gõ chỉ có trong doc — lấy nhầm là bấm Định dạng xong chữ nhảy về bản cũ.
|
|
1601
|
+
*
|
|
1602
|
+
* KHÔNG phát `outChange` ở đây: `createUpdateListener` đã nghe `docChanged` và tự phát rồi, phát
|
|
1603
|
+
* thêm là nơi dùng nhận hai lượt cho một thao tác.
|
|
677
1604
|
*/
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
// Build a Set of comment ranges từ AST để skip match nằm trong comment
|
|
692
|
-
const commentRanges = [];
|
|
693
|
-
tree.iterate({
|
|
694
|
-
enter: (node) => {
|
|
695
|
-
if (node.type.name.toLowerCase().includes('comment')) {
|
|
696
|
-
commentRanges.push({ from: node.from, to: node.to });
|
|
697
|
-
}
|
|
698
|
-
},
|
|
699
|
-
});
|
|
700
|
-
const isInComment = (from, to) => commentRanges.some((r) => from >= r.from && to <= r.to);
|
|
701
|
-
for (const pattern of patterns) {
|
|
702
|
-
const re = toGlobalRegex(pattern);
|
|
703
|
-
re.lastIndex = 0;
|
|
704
|
-
let match;
|
|
705
|
-
while ((match = re.exec(text)) !== null) {
|
|
706
|
-
const from = match.index;
|
|
707
|
-
const to = from + match[0].length;
|
|
708
|
-
if (isInComment(from, to))
|
|
709
|
-
continue;
|
|
710
|
-
const line = view.state.doc.lineAt(from).number;
|
|
711
|
-
const patternLabel = pattern instanceof RegExp ? pattern.source : pattern;
|
|
712
|
-
diagnostics.push({
|
|
713
|
-
from,
|
|
714
|
-
to,
|
|
715
|
-
severity: 'error',
|
|
716
|
-
message: `Mã bị cấm: "${match[0]}" — vi phạm chính sách bảo mật`,
|
|
717
|
-
});
|
|
718
|
-
violations.push({ from, to, line, pattern: patternLabel, matched: match[0] });
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
this.outViolations.emit(violations);
|
|
722
|
-
return diagnostics;
|
|
723
|
-
});
|
|
724
|
-
// Chặn paste nếu nội dung paste chứa bất kỳ pattern cấm nào
|
|
725
|
-
const pasteFilter = EditorState.transactionFilter.of((tr) => {
|
|
726
|
-
if (!tr.docChanged)
|
|
727
|
-
return tr;
|
|
728
|
-
if (!tr.annotation(Transaction.userEvent)?.startsWith('input.paste'))
|
|
729
|
-
return tr;
|
|
730
|
-
const newText = tr.newDoc.toString();
|
|
731
|
-
for (const pattern of patterns) {
|
|
732
|
-
const re = toGlobalRegex(pattern);
|
|
733
|
-
re.lastIndex = 0;
|
|
734
|
-
if (re.test(newText))
|
|
735
|
-
return []; // [] = block transaction
|
|
736
|
-
}
|
|
737
|
-
return tr;
|
|
1605
|
+
handlerFormat() {
|
|
1606
|
+
// 🔴 Thoát sớm khi editor CHƯA dựng: `langSelected` là `model.required`, đọc lúc chưa có giá trị
|
|
1607
|
+
// là văng `NG0952`. Không có editor thì cũng chẳng có gì để định dạng.
|
|
1608
|
+
if (!this.editorViewInstance) {
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
const current = this.editorViewInstance.state.doc.toString();
|
|
1612
|
+
const isAligned = formatByLanguage(current, this.langSelected());
|
|
1613
|
+
if (!isAligned || isAligned === current) {
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
this.editorViewInstance.dispatch({
|
|
1617
|
+
changes: { from: 0, to: current.length, insert: isAligned },
|
|
738
1618
|
});
|
|
739
|
-
return [forbiddenLinter, pasteFilter];
|
|
740
|
-
}
|
|
741
|
-
escapeRegex(str) {
|
|
742
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
743
1619
|
}
|
|
744
|
-
// ==========================================================================
|
|
745
|
-
// PROTECTED METHODS - Event handlers
|
|
746
|
-
// ==========================================================================
|
|
747
1620
|
handlerCopy() {
|
|
748
1621
|
navigator.clipboard.writeText(this.content() || '');
|
|
749
1622
|
this.notificationService.showCompTypeTextInfo('Sao chép thành công');
|
|
@@ -786,16 +1659,16 @@ class LibsUiComponentsPreviewTextDataComponent {
|
|
|
786
1659
|
});
|
|
787
1660
|
}
|
|
788
1661
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LibsUiComponentsPreviewTextDataComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
789
|
-
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: LibsUiComponentsPreviewTextDataComponent, isStandalone: true, selector: "libs_ui-components-preview_text_data", inputs: { content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, langSelected: { classPropertyName: "langSelected", publicName: "langSelected", isSignal: true, isRequired: true, transformFunction: null }, langsAccept: { classPropertyName: "langsAccept", publicName: "langsAccept", isSignal: true, isRequired: false, transformFunction: null }, langsChangeLabel: { classPropertyName: "langsChangeLabel", publicName: "langsChangeLabel", isSignal: true, isRequired: false, transformFunction: null }, editable: { classPropertyName: "editable", publicName: "editable", isSignal: true, isRequired: false, transformFunction: null }, hiddenAction: { classPropertyName: "hiddenAction", publicName: "hiddenAction", isSignal: true, isRequired: false, transformFunction: null }, lintIgnorePatterns: { classPropertyName: "lintIgnorePatterns", publicName: "lintIgnorePatterns", isSignal: true, isRequired: false, transformFunction: null }, completions: { classPropertyName: "completions", publicName: "completions", isSignal: true, isRequired: false, transformFunction: null }, forbiddenPatterns: { classPropertyName: "forbiddenPatterns", publicName: "forbiddenPatterns", isSignal: true, isRequired: false, transformFunction: null }, background: { classPropertyName: "background", publicName: "background", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { langSelected: "langSelectedChange", outChange: "outChange", syntaxErrors: "syntaxErrors", outViolations: "outViolations" }, viewQueries: [{ propertyName: "containerPreview", first: true, predicate: ["containerPreview"], descendants: true, isSignal: true }], ngImport: i0, template: "<div\n class=\"libs-ui-preview-data-container flex flex-col w-full h-auto rounded-[8px] libs-ui-border-general px-[8px]\"\n [style.--background-color]=\"background()\"\n [class.pt-[8px]]=\"!hiddenAction()\">\n @if (!hiddenAction()) {\n <div class=\"flex items-center content-between color-[#6a7383]\">\n <libs_ui-components-dropdown\n classInclude=\"w-[200px]\"\n [listConfig]=\"configLoadDataIsHttpConfig()\"\n [listMaxItemShow]=\"5\"\n [isNgContent]=\"true\"\n [readonly]=\"!editable() || !acceptChangeLang()\"\n [listHasButtonUnSelectOption]=\"false\"\n (outSelectKey)=\"handlerSelectKey($event)\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"labelLang() || ''\"\n [sizeButton]=\"'small'\"\n [classIconRight]=\"editable() && acceptChangeLang() ? 'libs-ui-icon-move-right rotate-90' : ''\"\n [classInclude]=\"'!p-[0px]' + (editable() && acceptChangeLang() ? '' : '!pointer-events-none !cursor-default hover:!text-[#6A7383]')\" />\n </libs_ui-components-dropdown>\n <div class=\"flex items-center\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"isWrap() ? 'i18n_remove_line_wrap' : 'i18n_line_wrap'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"isWrap() ? 'libs-ui-icon-unwrap' : 'libs-ui-icon-wrap'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerLineWrap()\" />\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_copy'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-copy'\"\n [classInclude]=\"'mo-lib-p-0px'\"\n (outClick)=\"handlerCopy()\" />\n </div>\n </div>\n }\n <div #containerPreview></div>\n</div>\n", styles: [":host ::ng-deep .libs-ui-preview-data-container{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-line{white-space:pre-wrap}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-error{background-color:#ff323233;border-bottom:2px solid red}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-warning{background-color:#ffc80026}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-lint{background:#fff8f8;color:#d32f2f;border:1px solid #f44336;padding:8px 10px;font-size:13px;font-family:Inter,sans-serif;border-radius:6px;box-shadow:0 2px 8px #ff000026}:host ::ng-deep .libs-ui-preview-data-container .cm-focused{outline:none!important}:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{background-color:var(--background-color)!important}\n"], dependencies: [{ kind: "component", type: LibsUiComponentsDropdownComponent, selector: "libs_ui-components-dropdown", inputs: ["useXssFilter", "popoverElementRefCustom", "classInclude", "ignoreStopPropagationEvent", "flagMouse", "flagMouseContent", "popoverCustomConfig", "isNgContent", "zIndex", "convertItemSelected", "getPopoverItemSelected", "httpRequestDetailItemById", "lengthKeys", "textDisplayWhenNoSelect", "textDisplayWhenMultiSelect", "classIncludeTextDisplayWhenNoSelect", "fieldLabel", "fieldGetLabel", "labelPopoverConfig", "labelPopoverFullWidth", "hasContentUnitRight", "listSearchNoDataTemplateRef", "dropdownTemplateRefNotSearchNoData", "fieldGetImage", "imageSize", "typeShape", "fieldGetIcon", "fieldGetTextAvatar", "fieldGetColorAvatar", "classAvatarInclude", "getLastTextAfterSpace", "linkImageError", "showError", "showBorderError", "disable", "readonly", "labelConfig", "disableLabel", "listSearchConfig", "isSearchOnline", "listHiddenInputSearch", "listSearchPadding", "listKeySearch", "listDividerClassInclude", "listConfig", "listButtonsOther", "listHasButtonUnSelectOption", "listClickExactly", "listBackgroundCustom", "listMaxItemShow", "listKeySelected", "listMultiKeySelected", "listKeysDisable", "listKeysHidden", "validRequired", "validMaxItemSelected", "changeValidUndefinedResetError", "allowSelectItemMultiple", "focusInputSearch", "onlyEmitDataWhenReset", "resetKeyWhenSelectAllKey", "listConfigHasDivider", "classIncludeIcon", "classIncludeContent", "listIgnoreClassDisableDefaultWhenUseKeysDisableItem", "tabKeyActive", "tabsConfig", "ignoreBorderBottom"], outputs: ["flagMouseChange", "flagMouseContentChange", "lengthKeysChange", "showBorderErrorChange", "listKeySelectedChange", "listMultiKeySelectedChange", "tabKeyActiveChange", "outSelectKey", "outSelectMultiKey", "outFunctionsControl", "outValidEvent", "outChangStageFlagMouse", "outDataChange", "outClickButtonOther", "outShowList", "outChangeTabKeyActive"] }, { kind: "component", type: LibsUiComponentsButtonsButtonComponent, selector: "libs_ui-components-buttons-button", inputs: ["flagMouse", "type", "buttonCustom", "sizeButton", "label", "disable", "isPending", "imageLeft", "classInclude", "classIconLeft", "classIconRight", "classLabel", "iconOnlyType", "popover", "ignoreStopPropagationEvent", "zIndex", "widthLabelPopover", "styleIconLeft", "styleButton", "ignoreFocusWhenInputTab", "ignoreSetClickWhenShowPopover", "ignorePointerEvent", "isActive", "isHandlerEnterDocumentClickButton"], outputs: ["outClick", "outPopoverEvent", "outFunctionsControl"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
1662
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: LibsUiComponentsPreviewTextDataComponent, isStandalone: true, selector: "libs_ui-components-preview_text_data", inputs: { content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, langSelected: { classPropertyName: "langSelected", publicName: "langSelected", isSignal: true, isRequired: true, transformFunction: null }, langsAccept: { classPropertyName: "langsAccept", publicName: "langsAccept", isSignal: true, isRequired: false, transformFunction: null }, langsChangeLabel: { classPropertyName: "langsChangeLabel", publicName: "langsChangeLabel", isSignal: true, isRequired: false, transformFunction: null }, editable: { classPropertyName: "editable", publicName: "editable", isSignal: true, isRequired: false, transformFunction: null }, hiddenAction: { classPropertyName: "hiddenAction", publicName: "hiddenAction", isSignal: true, isRequired: false, transformFunction: null }, minLines: { classPropertyName: "minLines", publicName: "minLines", isSignal: true, isRequired: false, transformFunction: null }, maxLines: { classPropertyName: "maxLines", publicName: "maxLines", isSignal: true, isRequired: false, transformFunction: null }, containerElement: { classPropertyName: "containerElement", publicName: "containerElement", isSignal: true, isRequired: false, transformFunction: null }, zIndexPopover: { classPropertyName: "zIndexPopover", publicName: "zIndexPopover", isSignal: true, isRequired: false, transformFunction: null }, hiddenSearchLang: { classPropertyName: "hiddenSearchLang", publicName: "hiddenSearchLang", isSignal: true, isRequired: false, transformFunction: null }, lintIgnorePatterns: { classPropertyName: "lintIgnorePatterns", publicName: "lintIgnorePatterns", isSignal: true, isRequired: false, transformFunction: null }, completions: { classPropertyName: "completions", publicName: "completions", isSignal: true, isRequired: false, transformFunction: null }, forbiddenPatterns: { classPropertyName: "forbiddenPatterns", publicName: "forbiddenPatterns", isSignal: true, isRequired: false, transformFunction: null }, background: { classPropertyName: "background", publicName: "background", isSignal: true, isRequired: false, transformFunction: null }, showFormatAction: { classPropertyName: "showFormatAction", publicName: "showFormatAction", isSignal: true, isRequired: false, transformFunction: null }, autoFormatOnLoad: { classPropertyName: "autoFormatOnLoad", publicName: "autoFormatOnLoad", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { langSelected: "langSelectedChange", outChange: "outChange", syntaxErrors: "syntaxErrors", outViolations: "outViolations" }, viewQueries: [{ propertyName: "containerPreview", first: true, predicate: ["containerPreview"], descendants: true, isSignal: true }], ngImport: i0, template: "<div\n class=\"libs-ui-preview-data-container flex flex-col w-full h-auto rounded-[8px] libs-ui-border-general px-[8px]\"\n [style.--background-color]=\"background()\"\n [class.pt-[8px]]=\"!hiddenAction()\">\n @if (!hiddenAction()) {\n <div class=\"flex items-center content-between color-[#6a7383]\">\n <libs_ui-components-dropdown\n classInclude=\"w-[200px]\"\n [listConfig]=\"configLoadDataIsHttpConfig()\"\n [listMaxItemShow]=\"5\"\n [zIndex]=\"zIndexPopover()\"\n [isNgContent]=\"true\"\n [readonly]=\"!editable() || !acceptChangeLang()\"\n [listHasButtonUnSelectOption]=\"false\"\n [listHiddenInputSearch]=\"hiddenSearchLang()\"\n (outSelectKey)=\"handlerSelectKey($event)\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"labelLang() || ''\"\n [sizeButton]=\"'small'\"\n [classIconRight]=\"editable() && acceptChangeLang() ? 'libs-ui-icon-move-right rotate-90' : ''\"\n [classInclude]=\"'!p-[0px]' + (editable() && acceptChangeLang() ? '' : '!pointer-events-none !cursor-default hover:!text-[#6A7383]')\" />\n </libs_ui-components-dropdown>\n <div class=\"flex items-center\">\n <!-- \u0110\u1ECBnh d\u1EA1ng: \u0111\u1EE9ng tr\u01B0\u1EDBc \"Xu\u1ED1ng d\u00F2ng\" v\u00EC n\u00F3 l\u00E0 thao t\u00E1c tr\u00EAn N\u1ED8I DUNG, hai n\u00FAt sau ch\u1EC9 \u0111\u1ED5i\n c\u00E1ch hi\u1EC3n th\u1ECB. Ch\u1EC9 hi\u1EC7n khi \u00F4 s\u1EEDa \u0111\u01B0\u1EE3c v\u00E0 ng\u00F4n ng\u1EEF c\u00F3 b\u1ED9 \u0111\u1ECBnh d\u1EA1ng \u2014 xem `canFormat`. -->\n @if (canFormat()) {\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_format_code'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-align-left'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerFormat()\" />\n }\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"isWrap() ? 'i18n_remove_line_wrap' : 'i18n_line_wrap'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"isWrap() ? 'libs-ui-icon-unwrap' : 'libs-ui-icon-wrap'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerLineWrap()\" />\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_copy'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-copy'\"\n [classInclude]=\"'mo-lib-p-0px'\"\n (outClick)=\"handlerCopy()\" />\n </div>\n </div>\n }\n <div #containerPreview></div>\n</div>\n", styles: [":host ::ng-deep .libs-ui-preview-data-container{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-line{white-space:pre-wrap}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-error{background-color:#ff323233;border-bottom:2px solid red}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-warning{background-color:#ffc80026}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-lint{background:#fff8f8;color:#d32f2f;border:1px solid #f44336;padding:8px 10px;font-size:13px;font-family:Inter,sans-serif;border-radius:6px;box-shadow:0 2px 8px #ff000026}:host ::ng-deep .libs-ui-preview-data-container .cm-focused{outline:none!important}:host ::ng-deep .libs-ui-preview-data-container .cm-content,:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{font-family:JetBrains Mono,Fira Code,Cascadia Mono,Consolas,DejaVu Sans Mono,monospace;font-size:12px}:host ::ng-deep .libs-ui-preview-data-container .cm-activeLine{background-color:#f4f8ff!important}:host ::ng-deep .libs-ui-preview-data-container .cm-activeLineGutter{background-color:#f4f8ff!important;color:#1a73e8}:host ::ng-deep .libs-ui-preview-data-container .cm-lineNumbers .cm-gutterElement{color:#9aa0a6}:host ::ng-deep .libs-ui-preview-data-container .cm-cursor,:host ::ng-deep .libs-ui-preview-data-container .cm-dropCursor{border-left-color:#1a73e8!important}:host ::ng-deep .libs-ui-preview-data-container .cm-matchingBracket{background-color:#d2e3fc!important;color:inherit!important;font-weight:600}:host ::ng-deep .libs-ui-preview-data-container .cm-nonmatchingBracket{background-color:#fce8e6!important;color:#c5221f!important}:host ::ng-deep .libs-ui-preview-data-container .cm-selectionBackground{background-color:#007aff40!important}:host ::ng-deep .libs-ui-preview-data-container .cm-selectionLayer{z-index:1!important}:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete{border:1px solid #e6e7ea;border-radius:6px;background:#fff;box-shadow:0 4px 12px #0f172a1f;overflow:hidden}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul{max-height:260px;font-family:var(--libs-ui-font-family-name, \"Arial\")}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul>li{display:flex;align-items:baseline;gap:10px;padding:5px 10px!important;line-height:18px}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul>li[aria-selected]{background:#e9f1fe;color:#071631}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionLabel{flex:0 0 auto;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:12px;font-weight:500;color:#071631}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionDetail{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:11px;font-style:normal;color:#6a7383;text-align:right}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionIcon{flex:0 0 auto;font-family:var(--libs-ui-font-family-name, \"Arial\");opacity:.5}:host ::ng-deep .libs-ui-preview-data-container .cm-completionInfo{border:1px solid #e6e7ea;border-radius:6px;background:#fff;padding:8px 10px;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:11px;color:#6a7383}\n"], dependencies: [{ kind: "component", type: LibsUiComponentsDropdownComponent, selector: "libs_ui-components-dropdown", inputs: ["useXssFilter", "popoverElementRefCustom", "classInclude", "ignoreStopPropagationEvent", "flagMouse", "flagMouseContent", "popoverCustomConfig", "isNgContent", "zIndex", "convertItemSelected", "getPopoverItemSelected", "httpRequestDetailItemById", "lengthKeys", "textDisplayWhenNoSelect", "textDisplayWhenMultiSelect", "classIncludeTextDisplayWhenNoSelect", "fieldLabel", "fieldGetLabel", "labelPopoverConfig", "labelPopoverFullWidth", "hasContentUnitRight", "listSearchNoDataTemplateRef", "dropdownTemplateRefNotSearchNoData", "fieldGetImage", "imageSize", "typeShape", "fieldGetIcon", "fieldGetTextAvatar", "fieldGetColorAvatar", "classAvatarInclude", "getLastTextAfterSpace", "linkImageError", "showError", "showBorderError", "disable", "readonly", "labelConfig", "disableLabel", "listSearchConfig", "isSearchOnline", "listHiddenInputSearch", "listSearchPadding", "listKeySearch", "listDividerClassInclude", "listConfig", "listButtonsOther", "listHasButtonUnSelectOption", "listClickExactly", "listBackgroundCustom", "listMaxItemShow", "listKeySelected", "listMultiKeySelected", "listKeysDisable", "listKeysHidden", "validRequired", "validMaxItemSelected", "changeValidUndefinedResetError", "allowSelectItemMultiple", "focusInputSearch", "onlyEmitDataWhenReset", "onlyEmitMultiKeyWhenManualClick", "resetKeyWhenSelectAllKey", "listConfigHasDivider", "classIncludeIcon", "classIncludeContent", "listIgnoreClassDisableDefaultWhenUseKeysDisableItem", "tabKeyActive", "tabsConfig", "ignoreBorderBottom"], outputs: ["flagMouseChange", "flagMouseContentChange", "lengthKeysChange", "showBorderErrorChange", "listKeySelectedChange", "listMultiKeySelectedChange", "tabKeyActiveChange", "outSelectKey", "outSelectMultiKey", "outFunctionsControl", "outValidEvent", "outChangStageFlagMouse", "outDataChange", "outClickButtonOther", "outShowList", "outChangeTabKeyActive"] }, { kind: "component", type: LibsUiComponentsButtonsButtonComponent, selector: "libs_ui-components-buttons-button", inputs: ["flagMouse", "type", "buttonCustom", "sizeButton", "label", "disable", "isPending", "imageLeft", "classInclude", "classIconLeft", "classIconRight", "classLabel", "iconOnlyType", "popover", "ignoreStopPropagationEvent", "zIndex", "widthLabelPopover", "styleIconLeft", "styleButton", "ignoreFocusWhenInputTab", "ignoreSetClickWhenShowPopover", "ignorePointerEvent", "isActive", "isHandlerEnterDocumentClickButton"], outputs: ["outClick", "outPopoverEvent", "outFunctionsControl"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
790
1663
|
}
|
|
791
1664
|
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LibsUiComponentsPreviewTextDataComponent, decorators: [{
|
|
792
1665
|
type: Component,
|
|
793
|
-
args: [{ selector: 'libs_ui-components-preview_text_data', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, imports: [LibsUiComponentsDropdownComponent, LibsUiComponentsButtonsButtonComponent], template: "<div\n class=\"libs-ui-preview-data-container flex flex-col w-full h-auto rounded-[8px] libs-ui-border-general px-[8px]\"\n [style.--background-color]=\"background()\"\n [class.pt-[8px]]=\"!hiddenAction()\">\n @if (!hiddenAction()) {\n <div class=\"flex items-center content-between color-[#6a7383]\">\n <libs_ui-components-dropdown\n classInclude=\"w-[200px]\"\n [listConfig]=\"configLoadDataIsHttpConfig()\"\n [listMaxItemShow]=\"5\"\n [isNgContent]=\"true\"\n [readonly]=\"!editable() || !acceptChangeLang()\"\n [listHasButtonUnSelectOption]=\"false\"\n (outSelectKey)=\"handlerSelectKey($event)\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"labelLang() || ''\"\n [sizeButton]=\"'small'\"\n [classIconRight]=\"editable() && acceptChangeLang() ? 'libs-ui-icon-move-right rotate-90' : ''\"\n [classInclude]=\"'!p-[0px]' + (editable() && acceptChangeLang() ? '' : '!pointer-events-none !cursor-default hover:!text-[#6A7383]')\" />\n </libs_ui-components-dropdown>\n <div class=\"flex items-center\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"isWrap() ? 'i18n_remove_line_wrap' : 'i18n_line_wrap'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"isWrap() ? 'libs-ui-icon-unwrap' : 'libs-ui-icon-wrap'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerLineWrap()\" />\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_copy'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-copy'\"\n [classInclude]=\"'mo-lib-p-0px'\"\n (outClick)=\"handlerCopy()\" />\n </div>\n </div>\n }\n <div #containerPreview></div>\n</div>\n", styles: [":host ::ng-deep .libs-ui-preview-data-container{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-line{white-space:pre-wrap}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-error{background-color:#ff323233;border-bottom:2px solid red}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-warning{background-color:#ffc80026}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-lint{background:#fff8f8;color:#d32f2f;border:1px solid #f44336;padding:8px 10px;font-size:13px;font-family:Inter,sans-serif;border-radius:6px;box-shadow:0 2px 8px #ff000026}:host ::ng-deep .libs-ui-preview-data-container .cm-focused{outline:none!important}:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{background-color:var(--background-color)!important}\n"] }]
|
|
1666
|
+
args: [{ selector: 'libs_ui-components-preview_text_data', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, imports: [LibsUiComponentsDropdownComponent, LibsUiComponentsButtonsButtonComponent], template: "<div\n class=\"libs-ui-preview-data-container flex flex-col w-full h-auto rounded-[8px] libs-ui-border-general px-[8px]\"\n [style.--background-color]=\"background()\"\n [class.pt-[8px]]=\"!hiddenAction()\">\n @if (!hiddenAction()) {\n <div class=\"flex items-center content-between color-[#6a7383]\">\n <libs_ui-components-dropdown\n classInclude=\"w-[200px]\"\n [listConfig]=\"configLoadDataIsHttpConfig()\"\n [listMaxItemShow]=\"5\"\n [zIndex]=\"zIndexPopover()\"\n [isNgContent]=\"true\"\n [readonly]=\"!editable() || !acceptChangeLang()\"\n [listHasButtonUnSelectOption]=\"false\"\n [listHiddenInputSearch]=\"hiddenSearchLang()\"\n (outSelectKey)=\"handlerSelectKey($event)\">\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"labelLang() || ''\"\n [sizeButton]=\"'small'\"\n [classIconRight]=\"editable() && acceptChangeLang() ? 'libs-ui-icon-move-right rotate-90' : ''\"\n [classInclude]=\"'!p-[0px]' + (editable() && acceptChangeLang() ? '' : '!pointer-events-none !cursor-default hover:!text-[#6A7383]')\" />\n </libs_ui-components-dropdown>\n <div class=\"flex items-center\">\n <!-- \u0110\u1ECBnh d\u1EA1ng: \u0111\u1EE9ng tr\u01B0\u1EDBc \"Xu\u1ED1ng d\u00F2ng\" v\u00EC n\u00F3 l\u00E0 thao t\u00E1c tr\u00EAn N\u1ED8I DUNG, hai n\u00FAt sau ch\u1EC9 \u0111\u1ED5i\n c\u00E1ch hi\u1EC3n th\u1ECB. Ch\u1EC9 hi\u1EC7n khi \u00F4 s\u1EEDa \u0111\u01B0\u1EE3c v\u00E0 ng\u00F4n ng\u1EEF c\u00F3 b\u1ED9 \u0111\u1ECBnh d\u1EA1ng \u2014 xem `canFormat`. -->\n @if (canFormat()) {\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_format_code'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-align-left'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerFormat()\" />\n }\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"isWrap() ? 'i18n_remove_line_wrap' : 'i18n_line_wrap'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"isWrap() ? 'libs-ui-icon-unwrap' : 'libs-ui-icon-wrap'\"\n [classInclude]=\"'mo-lib-p-0px mo-lib-mr-16px'\"\n (outClick)=\"handlerLineWrap()\" />\n <libs_ui-components-buttons-button\n [type]=\"'button-link-third'\"\n [label]=\"'i18n_copy'\"\n [sizeButton]=\"'small'\"\n [classIconLeft]=\"'libs-ui-icon-copy'\"\n [classInclude]=\"'mo-lib-p-0px'\"\n (outClick)=\"handlerCopy()\" />\n </div>\n </div>\n }\n <div #containerPreview></div>\n</div>\n", styles: [":host ::ng-deep .libs-ui-preview-data-container{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-line{white-space:pre-wrap}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-error{background-color:#ff323233;border-bottom:2px solid red}:host ::ng-deep .libs-ui-preview-data-container .cm-lintRange-warning{background-color:#ffc80026}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-lint{background:#fff8f8;color:#d32f2f;border:1px solid #f44336;padding:8px 10px;font-size:13px;font-family:Inter,sans-serif;border-radius:6px;box-shadow:0 2px 8px #ff000026}:host ::ng-deep .libs-ui-preview-data-container .cm-focused{outline:none!important}:host ::ng-deep .libs-ui-preview-data-container .cm-content,:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{font-family:JetBrains Mono,Fira Code,Cascadia Mono,Consolas,DejaVu Sans Mono,monospace;font-size:12px}:host ::ng-deep .libs-ui-preview-data-container .cm-activeLine{background-color:#f4f8ff!important}:host ::ng-deep .libs-ui-preview-data-container .cm-activeLineGutter{background-color:#f4f8ff!important;color:#1a73e8}:host ::ng-deep .libs-ui-preview-data-container .cm-lineNumbers .cm-gutterElement{color:#9aa0a6}:host ::ng-deep .libs-ui-preview-data-container .cm-cursor,:host ::ng-deep .libs-ui-preview-data-container .cm-dropCursor{border-left-color:#1a73e8!important}:host ::ng-deep .libs-ui-preview-data-container .cm-matchingBracket{background-color:#d2e3fc!important;color:inherit!important;font-weight:600}:host ::ng-deep .libs-ui-preview-data-container .cm-nonmatchingBracket{background-color:#fce8e6!important;color:#c5221f!important}:host ::ng-deep .libs-ui-preview-data-container .cm-selectionBackground{background-color:#007aff40!important}:host ::ng-deep .libs-ui-preview-data-container .cm-selectionLayer{z-index:1!important}:host ::ng-deep .libs-ui-preview-data-container .cm-gutters{background-color:var(--background-color)!important}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete{border:1px solid #e6e7ea;border-radius:6px;background:#fff;box-shadow:0 4px 12px #0f172a1f;overflow:hidden}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul{max-height:260px;font-family:var(--libs-ui-font-family-name, \"Arial\")}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul>li{display:flex;align-items:baseline;gap:10px;padding:5px 10px!important;line-height:18px}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete>ul>li[aria-selected]{background:#e9f1fe;color:#071631}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionLabel{flex:0 0 auto;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:12px;font-weight:500;color:#071631}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionDetail{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:11px;font-style:normal;color:#6a7383;text-align:right}:host ::ng-deep .libs-ui-preview-data-container .cm-tooltip-autocomplete .cm-completionIcon{flex:0 0 auto;font-family:var(--libs-ui-font-family-name, \"Arial\");opacity:.5}:host ::ng-deep .libs-ui-preview-data-container .cm-completionInfo{border:1px solid #e6e7ea;border-radius:6px;background:#fff;padding:8px 10px;font-family:var(--libs-ui-font-family-name, \"Arial\");font-size:11px;color:#6a7383}\n"] }]
|
|
794
1667
|
}], ctorParameters: () => [] });
|
|
795
1668
|
|
|
796
1669
|
/**
|
|
797
1670
|
* Generated bundle index. Do not edit.
|
|
798
1671
|
*/
|
|
799
1672
|
|
|
800
|
-
export { DEFAULT_SECURITY_PATTERNS, LibsUiComponentsPreviewTextDataComponent, createDefaultLanguage, httpRequestConfigGetOptionsLang, languageRegistry, optionsLangData };
|
|
1673
|
+
export { DEFAULT_SECURITY_PATTERNS, DEFAULT_SQL_FORBIDDEN_PATTERNS, FORMATTABLE_LANGUAGES, LibsUiComponentsPreviewTextDataComponent, astSkipKeys, astTypeKeys, createDefaultLanguage, formatByLanguage, httpRequestConfigGetOptionsLang, languageRegistry, optionsLangData, sqlFormat, sqlNormalizeForCompare, sqlSplitPreservingLiterals, tsValueNodes };
|
|
801
1674
|
//# sourceMappingURL=libs-ui-components-preview-text-data.mjs.map
|