@codady/coax 0.0.3 → 0.0.5

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.
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Last modified: 2026/01/12 09:40:20
2
+ * Last modified: 2026/01/12 15:11:21
3
+ * Coax - A custom web component for syntax highlighting, code display, and interactive features
4
+ *
3
5
  */
4
6
  import typeWriter from "@codady/utils/typeWriter";
5
7
  import parseClasses from "@codady/utils/parseClasses";
@@ -7,36 +9,35 @@ import NAMESPACE from "@codady/utils/namespace";
7
9
  import getEl from "@codady/utils/getEl";
8
10
  import createTools from "@codady/utils/createTools";
9
11
  import createEl from "@codady/utils/createEl";
10
- class CoaxElem extends HTMLElement {
12
+ class Coax extends HTMLElement {
11
13
  // A static Map to hold the configuration for different languages
12
14
  static languages = new Map();
15
+ // A static array to hold the tools registered with the component
13
16
  static tools = [];
14
- source;
15
- _renderQueued = false;
16
- baseStylesEl;
17
- themeStylesEl;
18
- dynamicStylesEl;
19
- highlightedCodeEl;
20
- headerEl;
21
- codeNameEl;
22
- codeToolsEl;
23
- codeBodyEl;
24
- alias;
25
- lineString;
26
- speed;
27
- autoScroll;
17
+ source; // Source code content to be highlighted
18
+ _renderQueued = false; // Flag to prevent multiple render requests
19
+ baseStylesEl; // Element for base styles
20
+ themeStylesEl; // Element for theme styles
21
+ dynamicStylesEl; // Element for dynamic styles
22
+ highlightEl; // Element that holds the highlighted code
23
+ headerEl; // Header element (for code name, tools, etc.)
24
+ codeNameEl; // Code name element (shows language or alias)
25
+ codeToolsEl; // Code tools element (for interactive tools like copy)
26
+ codeBodyEl; // Code body element (the container for the code)
27
+ lang = 'plain'; // Language of the code (default is plain text)
28
+ alias = 'Plain Text'; // Alias name for the language (default is 'Plain Text')
29
+ lineString = ''; // The current line's string being typed
30
+ lastLineString = ''; // The last line's string
31
+ speed = 5; // Speed of the typing effect (higher is slower)
32
+ autoScroll = true; // Flag to enable/disable auto-scrolling
33
+ canListen = true; // Flag to enable/disable auto-scrolling
28
34
  constructor() {
29
35
  super();
30
36
  // Attach a Shadow DOM to the custom element
31
37
  this.attachShadow({ mode: 'open' });
32
38
  // Remove leading/trailing whitespace from the raw code content
33
39
  this.source = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
34
- this.lang = 'plain';
35
- this.alias = 'Plain Text';
36
- this.lineString = '';
37
- this.speed = 5;
38
- this.autoScroll = true;
39
- // 1. 初始化基础骨架
40
+ // Initialize the basic structure of the component
40
41
  this.shadowRoot.innerHTML = `
41
42
  <style id="base-styles">
42
43
  :host {
@@ -166,10 +167,10 @@ class CoaxElem extends HTMLElement {
166
167
  <style id="theme-styles"></style>
167
168
  <div id="code-header"><span id="code-name">${this.alias}</span><div id="code-tools"></div></div>
168
169
  <div id="code-body">
169
- <pre><code id="highlight-code"></code></pre>
170
+ <pre><code id="highlight"></code></pre>
170
171
  </div>
171
172
  `;
172
- // 缓存引用
173
+ // Cache references to various elements
173
174
  this.baseStylesEl = getEl('#base-styles', this.shadowRoot);
174
175
  this.themeStylesEl = getEl('#theme-styles', this.shadowRoot);
175
176
  this.dynamicStylesEl = getEl('#dynamic-styles', this.shadowRoot);
@@ -177,27 +178,33 @@ class CoaxElem extends HTMLElement {
177
178
  this.codeNameEl = getEl('#code-name', this.shadowRoot);
178
179
  this.codeToolsEl = getEl('#code-tools', this.shadowRoot);
179
180
  this.codeBodyEl = getEl('#code-body', this.shadowRoot);
180
- this.highlightedCodeEl = getEl('#highlight-code', this.shadowRoot);
181
+ this.highlightEl = getEl('#highlight', this.shadowRoot);
181
182
  this.codeBodyEl.addEventListener('scroll', () => {
182
183
  let flag = this.codeBodyEl.scrollTop + this.codeBodyEl.clientHeight < this.codeBodyEl.scrollHeight;
183
- // 检测是否是用户手动滚动
184
+ // Check if the user manually scrolled
184
185
  this.autoScroll = !flag;
185
186
  });
186
187
  }
187
188
  /**
188
- * Registers a new language with a set of syntax highlighting rules.
189
- * @param name - The name of the programming language.
190
- * @param config - Configuration for the language, including rules, theme, and optional CSS.
191
- */
189
+ * Registers a new language with a set of syntax highlighting rules.
190
+ * @param name - The name of the programming language (e.g., 'javascript', 'html', etc.)
191
+ * @param config - Configuration for the language, including rules, theme, and optional CSS.
192
+ */
192
193
  static register(name, config) {
193
194
  // Store the language configuration in the static map
194
195
  this.languages.set(name, { ...config });
195
196
  }
196
- //注册工具箱
197
+ /**
198
+ * Registers tools that can be used with the code editor (e.g., copy, download, etc.).
199
+ * @param items - An array of tool items to register.
200
+ */
197
201
  static addTools(items) {
198
- CoaxElem.tools = items;
202
+ Coax.tools = items;
199
203
  }
200
- //加入工具箱
204
+ /**
205
+ * Mounts the tools to the code tools container.
206
+ * @param toolItems - An array of tool items to be added to the tools container.
207
+ */
201
208
  mountTools(toolItems) {
202
209
  requestAnimationFrame(() => {
203
210
  this.codeToolsEl.innerHTML = '';
@@ -208,41 +215,51 @@ class CoaxElem extends HTMLElement {
208
215
  this.codeToolsEl.appendChild(createTools(items));
209
216
  });
210
217
  }
211
- // Called when the element is connected to the DOM
218
+ /**
219
+ * Called when the element is connected to the DOM.
220
+ */
212
221
  connectedCallback() {
213
222
  this.render();
214
223
  }
215
- // Observed attributes for changes
224
+ /**
225
+ * Observed attributes for changes. These include the language, height, tools, and speed.
226
+ */
216
227
  static get observedAttributes() { return ['lang', 'height', 'max-height', 'tools', 'speed']; }
217
228
  /**
218
- * Called when any of the observed attributes change.
219
- */
229
+ * Called when any of the observed attributes change.
230
+ * @param name - The name of the changed attribute.
231
+ * @param oldVal - The old value of the attribute.
232
+ * @param newVal - The new value of the attribute.
233
+ */
220
234
  attributeChangedCallback(name, oldVal, newVal) {
221
- if (oldVal === newVal)
235
+ if (oldVal === newVal || !this.canListen)
222
236
  return;
223
237
  if (name === 'height' || name === 'max-height') {
224
238
  this.updateStyleByRegExp(name, newVal);
225
239
  }
226
240
  if (name === 'speed') {
241
+ // Convert to integer (0 or 1)
227
242
  this.speed = ~~(!!newVal);
228
243
  }
229
244
  if (name === 'lang') {
230
- //更新当前语言
245
+ // Update the language and re-render
231
246
  this.lang = newVal;
232
247
  this.render();
233
248
  }
234
249
  if (name === 'tools') {
235
250
  if (!newVal)
236
251
  this.codeToolsEl.innerHTML = '';
237
- const tools = parseClasses(newVal), toolItems = CoaxElem.tools.filter(k => tools.includes(k.name));
252
+ const tools = parseClasses(newVal), toolItems = Coax.tools.filter(k => tools.includes(k.name));
238
253
  if (!toolItems.length)
239
254
  return;
240
255
  this.mountTools(toolItems);
241
256
  }
242
257
  }
243
258
  /**
244
- * 使用正则替换基础样式表中的特定属性,避免操作行内样式
245
- */
259
+ * Updates the base style by replacing specific CSS properties using a regular expression.
260
+ * @param prop - The CSS property name to update (e.g., 'height', 'max-height').
261
+ * @param value - The new value for the property.
262
+ */
246
263
  updateStyleByRegExp(prop, value) {
247
264
  // 构建正则:匹配属性名后面跟着冒号,直到分号或换行
248
265
  // 例如:height:\s*[^;]+;
@@ -250,11 +267,22 @@ class CoaxElem extends HTMLElement {
250
267
  // 替换为新的属性值
251
268
  this.baseStylesEl.textContent = this.baseStylesEl.textContent.replace(regex, `;\n${prop}: ${value};`);
252
269
  }
270
+ /**
271
+ * Retrieves the CSS prefix for the language configuration.
272
+ * @param config - The language configuration object.
273
+ * @returns The CSS prefix.
274
+ */
253
275
  getCssPrefix(config) {
254
276
  return (config?.cssPrefix || this.lang).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
255
277
  }
278
+ /**
279
+ * Highlights a given string according to the language configuration.
280
+ * @param string - The string to highlight.
281
+ * @param config - The language configuration object.
282
+ * @returns The highlighted string with HTML spans.
283
+ */
256
284
  getHighLightString(string, config) {
257
- config = config || CoaxElem.languages.get(this.lang);
285
+ config = config || Coax.languages.get(this.lang);
258
286
  if (!config)
259
287
  return string;
260
288
  // 如果找到了配置,则进行高亮处理
@@ -266,30 +294,42 @@ class CoaxElem extends HTMLElement {
266
294
  return i !== -1 && config.rules[i] ? `<span class="${NAMESPACE}-${cssPrefix}-${config.rules[i].token}">${match}</span>` : match;
267
295
  });
268
296
  }
297
+ /**
298
+ * Creates a wrapper element for a line of code.
299
+ * @param index - The line index to assign.
300
+ * @param startIndex - The starting index for the line.
301
+ * @returns A div element wrapping the line of code.
302
+ */
269
303
  createLineWrap(index, startIndex) {
270
304
  let dataIndex = 0;
271
305
  if (index == null && startIndex == null) {
272
- dataIndex = this.highlightedCodeEl.children.length;
306
+ dataIndex = this.highlightEl.children.length;
273
307
  }
274
308
  else {
275
- const start = startIndex || this.highlightedCodeEl.children.length;
309
+ const start = startIndex || this.highlightEl.children.length;
276
310
  dataIndex = start + index;
277
311
  }
278
312
  return createEl('div', { 'data-index': dataIndex }, '<div></div>');
279
313
  }
314
+ /**
315
+ * Fills a line of code with highlighted content.
316
+ * @param codeWrap - The element that will contain the highlighted line of code.
317
+ * @param line - The line of code to highlight.
318
+ * @param config - The language configuration object.
319
+ */
280
320
  getLineToFill(codeWrap, line, config) {
281
- config = config || CoaxElem.languages.get(this.lang);
321
+ config = config || Coax.languages.get(this.lang);
282
322
  let highlightedLine = this.getHighLightString(line, config);
283
323
  // 将高亮后的内容填充到 div 中
284
324
  codeWrap.innerHTML = highlightedLine;
285
325
  }
286
326
  ;
287
327
  /**
288
- * 处理新源码,按行高亮并追加到高亮区域
289
- * @param newCode - 新的源码片段
328
+ * Highlights new source code and appends it to the code body.
329
+ * @param newCode - The new source code to highlight and append.
290
330
  */
291
331
  async highlight(newCode) {
292
- const config = CoaxElem.languages.get(this.lang), startIndex = this.highlightedCodeEl.children.length,
332
+ const config = Coax.languages.get(this.lang), startIndex = this.highlightEl.children.length,
293
333
  // 将新源码按行分割
294
334
  newCodeLines = newCode ? newCode.split('\n') : [];
295
335
  //更新别名
@@ -304,9 +344,9 @@ class CoaxElem extends HTMLElement {
304
344
  // 创建一个 div 包裹每一行
305
345
  const lineWrap = this.createLineWrap(index, startIndex), codeWrap = lineWrap.lastElementChild;
306
346
  //标记完成
307
- this.closeLine(lineWrap);
347
+ lineWrap.completed = true;
308
348
  if (this.hasAttribute('speed')) {
309
- this.highlightedCodeEl.appendChild(lineWrap);
349
+ this.highlightEl.appendChild(lineWrap);
310
350
  //流式打字
311
351
  await typeWriter(lineString, {
312
352
  speed: this.speed,
@@ -320,20 +360,26 @@ class CoaxElem extends HTMLElement {
320
360
  //直接打出
321
361
  this.getLineToFill(codeWrap, lineString, config);
322
362
  //
323
- this.highlightedCodeEl.appendChild(lineWrap);
363
+ this.highlightEl.appendChild(lineWrap);
324
364
  }
325
365
  }
326
366
  //滚动到最底部
327
367
  this.autoScrollCode();
328
368
  return true;
329
369
  }
370
+ /**
371
+ * Automatically scrolls the code body to the bottom.
372
+ */
330
373
  autoScrollCode() {
331
374
  if (this.autoScroll) {
332
375
  this.codeBodyEl.scrollTop = this.codeBodyEl.scrollHeight;
333
376
  }
334
377
  }
378
+ /**
379
+ * Injects the theme styles for syntax highlighting (light/dark modes).
380
+ */
335
381
  injectThemeStyles() {
336
- const config = CoaxElem.languages.get(this.lang);
382
+ const config = Coax.languages.get(this.lang);
337
383
  if (!config)
338
384
  return;
339
385
  // Get language name, fallback to 'js' if not provided
@@ -355,13 +401,16 @@ class CoaxElem extends HTMLElement {
355
401
  .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark}); }` : ``} `).join('\n');
356
402
  schemeStyles += `}`;
357
403
  // Set the inner HTML of the shadow root, including styles and highlighted code
358
- // 2. 精确更新 DOM 节点而非重写 ShadowRoot
359
404
  this.dynamicStylesEl.textContent = lightStyles + darkStyles + schemeStyles;
360
405
  //附加主题样式
361
406
  if (config?.themeStyles) {
362
407
  this.themeStylesEl.textContent = config.themeStyles;
363
408
  }
364
409
  }
410
+ /**
411
+ * Updates the alias name for the language based on the configuration.
412
+ * @param config - The language configuration object.
413
+ */
365
414
  updateName(config) {
366
415
  if (this.hasAttribute('unnamed'))
367
416
  return;
@@ -375,37 +424,36 @@ class CoaxElem extends HTMLElement {
375
424
  }
376
425
  }
377
426
  /**
378
- * Renders the highlighted code within the shadow DOM.
379
- */
427
+ * Renders the highlighted code within the shadow DOM.
428
+ */
380
429
  render(code = this.source) {
381
430
  //同时多次改变属性,只执行一次
382
- // 如果已经在队列中,则直接返回
383
431
  if (this._renderQueued)
384
432
  return;
385
433
  this._renderQueued = true;
386
- // 使用 requestAnimationFrame 将渲染推迟到下一帧
387
- requestAnimationFrame(async () => {
388
- this.clear();
389
- this.injectThemeStyles();
390
- //一次性渲染
391
- await this.highlight(code);
392
- this._renderQueued = false;
393
- });
434
+ this.clear();
435
+ this.injectThemeStyles();
436
+ //一次性渲染
437
+ this.highlight(code);
438
+ this._renderQueued = false;
394
439
  }
440
+ /**
441
+ * Clears the current content and resets the state.
442
+ */
395
443
  clear() {
396
- this.highlightedCodeEl.innerHTML = this.source = this.lineString = '';
444
+ this.highlightEl.innerHTML = this.source = this.lineString = '';
397
445
  }
398
446
  /**
399
- * 替换现有的源码并重新渲染
400
- * @param newCode - 新的源码
401
- */
447
+ * Replaces the existing code with new source code and re-renders.
448
+ * @param newCode - The new source code to replace the existing code.
449
+ */
402
450
  async replace(newCode) {
403
451
  this.clear();
404
452
  await this.highlight(newCode);
405
453
  }
406
454
  /**
407
- * 末尾新增源码,仅高亮新增的部分
408
- * @param newCode - 新的源码片段
455
+ * Appends new source code to the current content and highlights only the new portion.
456
+ * @param newCode - The new source code to append and highlight.
409
457
  */
410
458
  async append(newCode) {
411
459
  // 将新的代码追加到现有代码末尾
@@ -413,36 +461,57 @@ class CoaxElem extends HTMLElement {
413
461
  // 高亮新的部分
414
462
  await this.highlight(newCode);
415
463
  }
416
- getActiveCodeWrap() {
417
- const lastChild = this.highlightedCodeEl.lastElementChild, lastLine = !lastChild || this.highlightedCodeEl.lastElementChild?.completed ?
464
+ /**
465
+ * Retrieves the last line of code that was rendered.
466
+ * @returns An object containing the line wrapper and code wrapper for the last line.
467
+ */
468
+ getLastLine() {
469
+ const lastChild = this.highlightEl.lastElementChild, lastLine = !lastChild || this.highlightEl.lastElementChild?.completed ?
418
470
  this.createLineWrap() : lastChild;
419
471
  return {
420
472
  lineWrap: lastLine,
421
473
  codeWrap: lastLine.lastElementChild
422
474
  };
423
475
  }
424
- closeLine(lineWrap) {
425
- lineWrap = lineWrap || this.highlightedCodeEl.lastElementChild;
426
- lineWrap && (lineWrap.completed = true);
476
+ /**
477
+ * Marks the current line as completed and updates the displayed code.
478
+ */
479
+ close() {
480
+ const lineWrap = this.highlightEl.lastElementChild;
481
+ if (!lineWrap)
482
+ return;
483
+ lineWrap.completed = true;
484
+ //行结束前保存
485
+ this.lastLineString = this.lineString;
486
+ this.getLineToFill(lineWrap?.lastElementChild, this.lineString);
487
+ //一行结束,清空临时行文本
488
+ this.lineString = '';
427
489
  }
428
- openLine(lineWrap) {
429
- lineWrap = lineWrap || this.highlightedCodeEl.lastElementChild;
430
- lineWrap && (lineWrap.completed = false);
490
+ /**
491
+ * Reopens the last closed line and restores its original content.
492
+ */
493
+ open() {
494
+ const lineWrap = this.highlightEl.lastElementChild;
495
+ if (!lineWrap)
496
+ return;
497
+ lineWrap.completed = false;
498
+ //恢复最后一行字符串
499
+ (lineWrap?.lastElementChild).textContent = this.lineString = this.lastLineString;
431
500
  }
432
- stream(str, forceEnd = false) {
433
- const { lineWrap, codeWrap } = this.getActiveCodeWrap();
434
- this.highlightedCodeEl.appendChild(lineWrap);
501
+ /**
502
+ * Streams a string of code into the component, either appending or closing the current line.
503
+ * @param str - The code string to stream into the component.
504
+ * @param forceClose - Forcefully close the line if set to `true`.
505
+ */
506
+ stream(str, forceClose = false) {
507
+ const { lineWrap, codeWrap } = this.getLastLine();
508
+ this.highlightEl.appendChild(lineWrap);
435
509
  //汇集
436
510
  this.source += str;
437
511
  //如果没有遇到换行符号,也可以强制结束
438
- forceEnd && this.closeLine(lineWrap);
439
- if (str.startsWith('\n') || str.startsWith('\r')) {
512
+ if (forceClose || (str.startsWith('\n') || str.endsWith('\n'))) {
440
513
  //标记完成
441
- this.closeLine(lineWrap);
442
- //渲染
443
- this.getLineToFill(codeWrap, this.lineString);
444
- //一行结束,清空临时行文本
445
- this.lineString = '';
514
+ this.close();
446
515
  }
447
516
  else {
448
517
  //插入文本
@@ -454,4 +523,4 @@ class CoaxElem extends HTMLElement {
454
523
  this.autoScrollCode();
455
524
  }
456
525
  }
457
- export default CoaxElem;
526
+ export default Coax;