@codady/coax 0.0.1 → 0.0.3

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.
Files changed (43) hide show
  1. package/dist/coax.cjs.js +829 -140
  2. package/dist/coax.cjs.min.js +3 -3
  3. package/dist/coax.esm.js +823 -140
  4. package/dist/coax.esm.min.js +3 -3
  5. package/dist/coax.umd.js +849 -138
  6. package/dist/coax.umd.min.js +3 -3
  7. package/examples/.htaccess +0 -0
  8. package/examples/append-highlight.html +82 -0
  9. package/examples/color-selector.html +412 -0
  10. package/examples/css-highlight.html +2 -18
  11. package/examples/deepseek-highlight.html +91 -0
  12. package/examples/js-highlight.html +2 -17
  13. package/examples/md-highlight.html +60 -0
  14. package/examples/nginx.htaccess +0 -0
  15. package/examples/plain-highlight.html +47 -0
  16. package/examples/replace-highlight.html +69 -0
  17. package/examples/stream-highlight.html +64 -0
  18. package/examples/theme-highlight.html +69 -0
  19. package/package.json +19 -3
  20. package/rollup.config.js +3 -3
  21. package/src/Coax.js +50 -184
  22. package/src/Coax.ts +56 -207
  23. package/src/components/CoaxElem.js +457 -0
  24. package/src/components/CoaxElem.ts +488 -0
  25. package/src/modules.js +12 -0
  26. package/src/modules.ts +23 -0
  27. package/src/rules/css.js +11 -0
  28. package/src/rules/css.ts +11 -0
  29. package/src/rules/html.js +13 -0
  30. package/src/rules/html.ts +13 -0
  31. package/src/rules/javascript.js +10 -0
  32. package/src/rules/javascript.ts +10 -0
  33. package/src/rules/markdown.js +29 -0
  34. package/src/rules/markdown.ts +41 -0
  35. package/src/rules/ruleCss - /345/211/257/346/234/254.js" +10 -0
  36. package/src/rules/ruleHTML - /345/211/257/346/234/254.js" +12 -0
  37. package/src/rules/ruleJs - /345/211/257/346/234/254.js" +10 -0
  38. package/src/rules/ruleTs - /345/211/257/346/234/254.js" +12 -0
  39. package/src/rules/typescript.js +12 -0
  40. package/src/rules/typescript.ts +12 -0
  41. package/src/tools/copy.js +26 -0
  42. package/src/tools/copy.ts +29 -0
  43. package/tsconfig.json +2 -2
package/dist/coax.cjs.js CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
2
  /*!
3
- * @since Last modified: 2026-1-4 16:0:48
3
+ * @since Last modified: 2026-1-12 9:47:5
4
4
  * @name Coax event management system.
5
- * @version 0.0.1
5
+ * @version 0.0.3
6
6
  * @author AXUI development team <3217728223@qq.com>
7
7
  * @description Coax is a custom web component that enables syntax highlighting for various programming languages inside your HTML documents.
8
8
  * @see {@link https://coax.axui.cn|Official website}
@@ -16,166 +16,855 @@
16
16
 
17
17
  'use strict';
18
18
 
19
- class Coax extends HTMLElement {
19
+ const typeWriter = (text, options) => {
20
+ const speed = options.speed || 100; // Set typing speed (default to 100ms per character)
21
+ return new Promise((resolve) => {
22
+ // Callback before typing starts
23
+ options?.onBeforeType?.(text);
24
+ let index = 0;
25
+ // Timer to type the text character by character at the given speed
26
+ const timer = setInterval(() => {
27
+ if (index < text.length) {
28
+ const char = text.charAt(index); // Get the character at the current index
29
+ const typedText = text.substring(0, index + 1); // The text typed so far
30
+ // Callback during typing each character
31
+ options?.onDuringType?.(char, typedText);
32
+ index++;
33
+ }
34
+ else {
35
+ // Clear the timer once typing is complete
36
+ clearInterval(timer);
37
+ // Resolve the Promise when typing is complete
38
+ resolve(text);
39
+ // Callback after typing is finished
40
+ options?.onAfterType?.(text);
41
+ }
42
+ }, speed);
43
+ });
44
+ };
45
+
46
+ const COMMA$1 = ',';
47
+
48
+ const SPACE$1 = ' ';
49
+
50
+ const trim$1 = (str, placement = 'compress') => {
51
+ if (typeof str !== 'string') {
52
+ console.warn('Expected a string input');
53
+ return '';
54
+ }
55
+ switch (placement) {
56
+ case 'start':
57
+ return str.trimStart();
58
+ case 'end':
59
+ return str.trimEnd();
60
+ case 'both':
61
+ return str.trim();
62
+ case 'global':
63
+ return str.replace(/[\s\r\n]+/g, '');
64
+ default:
65
+ return str.trim().replace(/[\s\r\n]+/g, ' '); // Default behavior, trims both ends and replaces inner spaces
66
+ }
67
+ };
68
+
69
+ const parseClasses$1 = (data) => {
70
+ let separator, result = [];
71
+ if (Array.isArray(data)) {
72
+ // If data is already an array, filter out invalid values
73
+ result = data.filter((k) => k && typeof k === 'string');
74
+ }
75
+ else {
76
+ // Trim the input string and handle multiple spaces
77
+ data = trim$1(data);
78
+ // Use comma as the separator if present, otherwise use space
79
+ separator = data.includes(COMMA$1) ? COMMA$1 : SPACE$1;
80
+ result = data.split(separator);
81
+ }
82
+ // Trim each item globally and filter out any empty strings
83
+ return result.map((k) => trim$1(k, 'global')).filter(Boolean);
84
+ };
85
+
86
+ const NAMESPACE = 'ax';
87
+
88
+ const getDataType = (obj) => {
89
+ let tmp = Object.prototype.toString.call(obj).slice(8, -1), result;
90
+ if (tmp === 'Function' && /^\s*class\s+/.test(obj.toString())) {
91
+ result = 'Class';
92
+ }
93
+ else if (tmp === 'Object' && Object.getPrototypeOf(obj) !== Object.prototype) {
94
+ result = 'Instance';
95
+ }
96
+ else {
97
+ result = tmp;
98
+ }
99
+ return result;
100
+ //document.createElement -> HTMLxxxElement
101
+ //document.createDocumentFragment() -> DocumentFragment
102
+ //document.createComment() -> Comment
103
+ //document.createTextNode -> Text
104
+ //document.createCDATASection() -> XMLDocument
105
+ //document.createProcessingInstruction() -> ProcessingInstruction
106
+ //document.createRange() -> Range
107
+ //document.createTreeWalker() -> TreeWalker
108
+ //document.createNodeIterator() -> NodeIterator
109
+ //document.createElementNS('http://www.w3.org/2000/svg', 'svg'); -> SVGSVGElement
110
+ //document.createElementNS('http://www.w3.org/1998/Math/MathML', 'math'); -> MathMLElement
111
+ };
112
+
113
+ const getEl = (obj, wrap = document.body) => {
114
+ let objType = getDataType(obj), parType = getDataType(wrap), parent = parType.includes('HTML') || parType === 'ShadowRoot' ? wrap : document.querySelector(wrap),
115
+ //如果parent是template节点,需要通过node.content.querySelector取得子节点
116
+ root = parent && parent instanceof HTMLTemplateElement ? parent.content : parent, result = null;
117
+ if (obj) {
118
+ if (objType.includes('HTML')) {
119
+ result = obj;
120
+ }
121
+ else if (objType === 'String') {
122
+ try {
123
+ result = (root || document).querySelector(obj.trim());
124
+ //可能会报错,报错则返回null
125
+ }
126
+ catch {
127
+ result = null;
128
+ }
129
+ }
130
+ }
131
+ return result;
132
+ };
133
+
134
+ const createEl = (name, attrs, content) => {
135
+ //默认为div
136
+ name = name || 'div';
137
+ //统一大小写
138
+ let rootName = name.toUpperCase().trim(), rootEl = document.createElement(rootName), attrsType = getDataType(attrs), loop = (host, data) => {
139
+ if (data === '' || data === null || data === undefined) {
140
+ //为空、未定义则不再执行
141
+ return false;
142
+ }
143
+ let dataType = getDataType(data);
144
+ //template是DocumentFragment类型不能用insertAdjacentHTML
145
+ if (rootName === 'TEMPLATE') {
146
+ host.innerHTML = data.toString();
147
+ }
148
+ else {
149
+ if (dataType === 'Array' && data.length > 0) {
150
+ //节点数组
151
+ //data.forEach((i: T_obj) => loop(el, i));
152
+ for (let k of data) {
153
+ let childType = getDataType(k);
154
+ if (childType.includes('HTML')) {
155
+ //是个节点
156
+ host.appendChild(k);
157
+ }
158
+ else {
159
+ //是个对象{name:'',attrs:{},content:''}
160
+ let child = createEl(k.name, k.attrs, k.content);
161
+ child && host.appendChild(child);
162
+ }
163
+ }
164
+ }
165
+ else if (dataType.includes('HTML')) {
166
+ //HTML节点
167
+ host.appendChild(data);
168
+ }
169
+ else if (dataType === 'String' && data.trim().startsWith('#') && data.trim().length > 1) {
170
+ //是字符串且是#id选择器,则取其文本
171
+ let el = getEl(data);
172
+ if (!el)
173
+ return;
174
+ //如果是template模板节点则需要特殊处理
175
+ el.nodeName === 'TEMPLATE' ? host.appendChild(el.content.cloneNode(true)) : host.insertAdjacentHTML('beforeEnd', el.innerHTML);
176
+ }
177
+ else {
178
+ //字符串数字等
179
+ host.insertAdjacentHTML('beforeEnd', data);
180
+ }
181
+ }
182
+ };
183
+ //添加属性
184
+ if (attrs && attrsType === 'Object') {
185
+ for (let k in attrs) {
186
+ //注意,attrs[k]可能是一个{}或[],不一定是字符串
187
+ // JSON.stringify可以将所有格式的数据都转成文本,会忽略函数和节点数据
188
+ //字符串则不需要stringify,否则会将字符串的引号也一并输出
189
+ attrs.hasOwnProperty(k) && rootEl.setAttribute(k, typeof attrs[k] === 'string' ? attrs[k] : JSON.stringify(attrs[k]));
190
+ }
191
+ }
192
+ //执行循环创建子节点
193
+ loop(rootEl, content);
194
+ return rootEl;
195
+ };
196
+
197
+ const isEmpty = (data) => {
198
+ let type = getDataType(data), flag;
199
+ if (!data) {
200
+ //0,'',false,undefined,null
201
+ flag = true;
202
+ }
203
+ else {
204
+ //function(){}|()=>{}
205
+ //[null]|[undefined]|['']|[""]
206
+ //[]|{}
207
+ //Symbol()|Symbol.for()
208
+ //Set,Map
209
+ //Date/Regex
210
+ flag = (type === 'Object') ? (Object.keys(data).length === 0) :
211
+ (type === 'Array') ? data.join('') === '' :
212
+ (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
213
+ (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
214
+ (type === 'Set' || type === 'Map') ? data.size === 0 :
215
+ type === 'Date' ? isNaN(data.getTime()) :
216
+ type === 'RegExp' ? data.source === '' :
217
+ type === 'ArrayBuffer' ? data.byteLength === 0 :
218
+ (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
219
+ ('length' in data && typeof data.length === 'number') ? data.length === 0 :
220
+ ('size' in data && typeof data.size === 'number') ? data.size === 0 :
221
+ (type === 'Error' || data instanceof Error) ? data.message === '' :
222
+ (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
223
+ false;
224
+ }
225
+ return flag;
226
+ };
227
+
228
+ const ALIAS = 'rep';
229
+
230
+ const addClasses = (target, classes, intercept) => {
231
+ const el = getEl(target), arr = parseClasses$1(classes);
232
+ if (!el || arr.length === 0) {
233
+ return;
234
+ }
235
+ arr.forEach((k) => {
236
+ {
237
+ el.classList.add(k);
238
+ }
239
+ });
240
+ };
241
+
242
+ const createTools = (data) => {
243
+
244
+ const toolsEl = createEl('span', { class: `${NAMESPACE}-box-tools` }), renderFn = (props) => {
245
+ const dftAttrs = {}, arrow = props.extendable ? `<i ${ALIAS}="arrow"></i>` : '', iconStr = props.icon ? `<i ${ALIAS}="icon">${props.icon}</i>` : '', diskStr = props.disk ? `<i ${ALIAS}="disk"><img src="${props.disk}"/></i>` : '', cubeStr = props.cube ? `<i ${ALIAS}="cube"><img src="${props.cube}"/></i>` : '', imageStr = props.image ? `<i ${ALIAS}="image"><img src="${props.image}"/></i>` : '', label = props.label ? `<i ${ALIAS}="label">${props.label}</i>` : '', html = iconStr + diskStr + cubeStr + imageStr + label + arrow;
246
+ //使用title提示
247
+ props.title && (dftAttrs.title = props.title);
248
+ //可聚焦,增加tabindex=1
249
+ props.focusable && (dftAttrs.tabindex = 1);
250
+ //attrs是其他属性,可能会覆盖title、tabindex
251
+ props.wrapEl = createEl(props.nodeName || 'span', Object.assign(dftAttrs, props.attrs), html);
252
+ props.iconEl = props.wrapEl.querySelector(`[${ALIAS}="icon"]`);
253
+ props.cubeEl = props.wrapEl.querySelector(`[${ALIAS}="cube"]`);
254
+ props.diskEl = props.wrapEl.querySelector(`[${ALIAS}="disk"]`);
255
+ props.imageEl = props.wrapEl.querySelector(`[${ALIAS}="image"]`);
256
+ props.labelEl = props.wrapEl.querySelector(`[${ALIAS}="label"]`);
257
+ //增加classes和styles
258
+ !isEmpty(props.classes) && addClasses(props.wrapEl, props.classes);
259
+ !isEmpty(props.styles) && (props.wrapEl.style.cssText += props.styles);
260
+ };
261
+ //此处不用map方法,是避免改变原data的内存地址指向
262
+ for (let item of data) {
263
+ //data=[{},{},'toggle','close']
264
+ renderFn(item);
265
+ toolsEl.appendChild(item.wrapEl);
266
+ item?.action?.(item);
267
+ }
268
+ return toolsEl;
269
+ };
270
+
271
+ class CoaxElem extends HTMLElement {
20
272
  // A static Map to hold the configuration for different languages
21
273
  static languages = new Map();
22
- // Raw code as text from the HTML content
23
- rawCode;
274
+ static tools = [];
275
+ source;
276
+ _renderQueued = false;
277
+ baseStylesEl;
278
+ themeStylesEl;
279
+ dynamicStylesEl;
280
+ highlightedCodeEl;
281
+ headerEl;
282
+ codeNameEl;
283
+ codeToolsEl;
284
+ codeBodyEl;
285
+ alias;
286
+ lineString;
287
+ speed;
288
+ autoScroll;
24
289
  constructor() {
25
290
  super();
26
291
  // Attach a Shadow DOM to the custom element
27
292
  this.attachShadow({ mode: 'open' });
28
293
  // Remove leading/trailing whitespace from the raw code content
29
- this.rawCode = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
294
+ this.source = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
295
+ this.lang = 'plain';
296
+ this.alias = 'Plain Text';
297
+ this.lineString = '';
298
+ this.speed = 5;
299
+ this.autoScroll = true;
300
+ // 1. 初始化基础骨架
301
+ this.shadowRoot.innerHTML = `
302
+ <style id="base-styles">
303
+ :host {
304
+ --border-width:1px;
305
+ --border-style:solid;
306
+ --radius:9px;
307
+ --height:auto;
308
+ --max-height:500px;
309
+ --radius:9px;
310
+ --padding:1em;
311
+ --font-size:16px;
312
+ --line-height:1.8;
313
+ --background:rgb(247, 247, 247);
314
+ --border-color:rgb(224, 224, 224);
315
+ --color-code:rgb(51, 51, 51);
316
+ --color-index:rgb(153, 153, 153);
317
+ --color-stripe:rgba(0,0,0,0.04);
318
+ --color-hover:rgba(0,0,0,0.06);
319
+ }
320
+ :host([scheme="dark"]){
321
+ --background: #282c34;
322
+ --border-color: transparent;
323
+ --color-code: #abb2bf;
324
+ --color-index:rgb(153, 153, 153);
325
+ --color-stripe:rgba(255,255,255,0.04);
326
+ --color-hover:rgba(255,255,255,0.06);
327
+ }
328
+ @media (prefers-color-scheme: dark) {
329
+ :host{
330
+ --background: #282c34;
331
+ --border-color: transparent;
332
+ --color-code: #abb2bf;
333
+ --color-index:rgb(153, 153, 153);
334
+ --color-stripe:rgba(255,255,255,0.04);
335
+ --color-hover:rgba(255,255,255,0.06);
336
+ }
337
+ }
338
+ :host {
339
+ font-size: var(--${NAMESPACE}-code-font-size,var(--font-size));
340
+ display: block;
341
+ box-sizing:border-box;
342
+ background:var(--${NAMESPACE}-code-background-color,var(--background));
343
+ color:var(--${NAMESPACE}-code-color,var(--color-code));
344
+ border:var(--${NAMESPACE}-code-border-width,var(--border-width)) var(--${NAMESPACE}-code-border-style,var(--border-style)) var(--${NAMESPACE}-code-border-color,var(--border-color));
345
+ transition: border-color 0.3s ease,color 0.3s ease;
346
+ border-radius: var(--${NAMESPACE}-code-radius,var(--radius));
347
+ }
348
+ #code-header{
349
+ line-height:calc(var(--${NAMESPACE}-code-line-height,var(--line-height))*1.5);
350
+ padding-inline-start:var(--${NAMESPACE}-code-padding,var(--padding));
351
+ display:flex;
352
+
353
+ >:first-child{
354
+ flex:auto;
355
+ }
356
+ }
357
+ #code-body{
358
+ padding: var(--${NAMESPACE}-code-padding,var(--padding)) 0;
359
+ height:var(--${NAMESPACE}-code-height,var(--height));
360
+ max-height:var(--${NAMESPACE}-code-max-height,var(--max-height));
361
+ overflow:auto;
362
+ }
363
+ pre,code{
364
+ font-family:"Consolas", "Monaco", "Andale Mono", "Ubuntu Mono", "monospace";
365
+ margin:0; padding:0;
366
+ }
367
+ code>div{
368
+ display:flex;
369
+ padding:0 var(--${NAMESPACE}-code-padding,var(--padding));
370
+ line-height: var(--${NAMESPACE}-code-line-height,var(--line-height));
371
+ box-sizing:border-box;
372
+
373
+ >div{
374
+ flex:auto;
375
+ }
376
+ }
377
+ code>div>div:empty:before{
378
+ content:' ';
379
+ }
380
+ :host([indexed]) code>div:before{
381
+ display:inline-flex;
382
+ color:var(--color-index);
383
+ content: attr(data-index);
384
+ min-width:var(--${NAMESPACE}-code-index-width,2em);
385
+ margin-inline-end:var(--${NAMESPACE}-code-padding,8px);
386
+ }
387
+ :host([striped]) code>div:nth-child(odd){
388
+ background-color:var(--color-stripe);
389
+ }
390
+ :host([hoverable]) code>div:hover{
391
+ background-color:var(--color-hover);
392
+ }
393
+ :host([wrapped]) code>div>div{
394
+ white-space: pre-wrap;
395
+ }
396
+ :host([unnamed]) #code-name{
397
+ display:none;
398
+ }
399
+ .${NAMESPACE}-box-tools{
400
+ >*{
401
+ font-size:14px;
402
+ display:inline-flex;
403
+ align-items:center;
404
+ justify-content:center;
405
+ height:2em;
406
+ line-height:2em;
407
+ aspect-ratio:1/1;
408
+ margin-inline-end:8px;
409
+ transition:all 200ms ease;
410
+ border-radius:6px;
411
+ &:hover{
412
+ cursor:pointer;
413
+ background-color:rgba(0,0,0,.04);
414
+ }
415
+ }
416
+ [rep=icon]{
417
+ display:inline-flex;
418
+ align-items:center;
419
+ justify-content:center;
420
+ }
421
+ }
422
+ [disabled]{
423
+ pointer-event:none;
424
+ }
425
+ </style>
426
+ <style id="dynamic-styles"></style>
427
+ <style id="theme-styles"></style>
428
+ <div id="code-header"><span id="code-name">${this.alias}</span><div id="code-tools"></div></div>
429
+ <div id="code-body">
430
+ <pre><code id="highlight-code"></code></pre>
431
+ </div>
432
+ `;
433
+ // 缓存引用
434
+ this.baseStylesEl = getEl('#base-styles', this.shadowRoot);
435
+ this.themeStylesEl = getEl('#theme-styles', this.shadowRoot);
436
+ this.dynamicStylesEl = getEl('#dynamic-styles', this.shadowRoot);
437
+ this.headerEl = getEl('#code-header', this.shadowRoot);
438
+ this.codeNameEl = getEl('#code-name', this.shadowRoot);
439
+ this.codeToolsEl = getEl('#code-tools', this.shadowRoot);
440
+ this.codeBodyEl = getEl('#code-body', this.shadowRoot);
441
+ this.highlightedCodeEl = getEl('#highlight-code', this.shadowRoot);
442
+ this.codeBodyEl.addEventListener('scroll', () => {
443
+ let flag = this.codeBodyEl.scrollTop + this.codeBodyEl.clientHeight < this.codeBodyEl.scrollHeight;
444
+ // 检测是否是用户手动滚动
445
+ this.autoScroll = !flag;
446
+ });
30
447
  }
31
448
 
32
- static register(name, { rules, theme = {}, internalCss = '', cssPrefix = '' }) {
449
+ static register(name, config) {
33
450
  // Store the language configuration in the static map
34
- this.languages.set(name, { rules, theme, internalCss, cssPrefix });
35
- // Render the highlighted code for all elements with the registered language
36
- document.querySelectorAll('ax-code').forEach(el => {
37
- if (el.getAttribute('lang') === name)
38
- el.render();
451
+ this.languages.set(name, { ...config });
452
+ }
453
+ //注册工具箱
454
+ static addTools(items) {
455
+ CoaxElem.tools = items;
456
+ }
457
+ //加入工具箱
458
+ mountTools(toolItems) {
459
+ requestAnimationFrame(() => {
460
+ this.codeToolsEl.innerHTML = '';
461
+ let items = toolItems.map(k => {
462
+ k.action = k.action.bind(this);
463
+ return k;
464
+ });
465
+ this.codeToolsEl.appendChild(createTools(items));
39
466
  });
40
467
  }
41
468
  // Called when the element is connected to the DOM
42
- connectedCallback() { this.render(); }
469
+ connectedCallback() {
470
+ this.render();
471
+ }
43
472
  // Observed attributes for changes
44
- static get observedAttributes() { return ['lang', 'height', 'max-height']; }
473
+ static get observedAttributes() { return ['lang', 'height', 'max-height', 'tools', 'speed']; }
45
474
 
46
- attributeChangedCallback() {
47
- this.render();
475
+ attributeChangedCallback(name, oldVal, newVal) {
476
+ if (oldVal === newVal)
477
+ return;
478
+ if (name === 'height' || name === 'max-height') {
479
+ this.updateStyleByRegExp(name, newVal);
480
+ }
481
+ if (name === 'speed') {
482
+ this.speed = ~~(!!newVal);
483
+ }
484
+ if (name === 'lang') {
485
+ //更新当前语言
486
+ this.lang = newVal;
487
+ this.render();
488
+ }
489
+ if (name === 'tools') {
490
+ if (!newVal)
491
+ this.codeToolsEl.innerHTML = '';
492
+ const tools = parseClasses$1(newVal), toolItems = CoaxElem.tools.filter(k => tools.includes(k.name));
493
+ if (!toolItems.length)
494
+ return;
495
+ this.mountTools(toolItems);
496
+ }
48
497
  }
49
498
 
50
- render() {
51
- // Get language name, fallback to 'js' if not provided
52
- const lang = this.getAttribute('lang') || 'js',
53
- // Get the language configuration
54
- config = Coax.languages.get(lang),
55
- // Default to language name if no prefix is set
56
- cssPrefix = config?.cssPrefix || lang, height = this.getAttribute('height'), maxHeight = this.getAttribute('max-height');
57
- let highlightedCode = '', dynamicStyles = '';
58
- if (config) {
59
- //Generate the highlighted HTML by applying the syntax rules
60
- const combinedRegex = new RegExp(config.rules.map((r) => `(${r.reg.source})`).join('|'), 'g'), escaped = this.rawCode.replace(/[&<>]/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m]));
61
- // Replace code with highlighted syntax
62
- highlightedCode = escaped.replace(combinedRegex, (match, ...args) => {
63
- const index = args.findIndex(val => val !== undefined);
64
- return index !== -1 && config.rules[index] ? `<span class="ax-${cssPrefix}-${config.rules[index].name}">${match}</span>` : match;
65
- });
66
- //Generate dynamic CSS classes for each syntax rule
67
- // rules 中的每一个 name 生成类似 .hl-name { color: var(--ax-code-name); }
68
- dynamicStyles = config.rules.map((rule) => `
69
- .ax-${cssPrefix}-${rule.name} { color: var(--ax-${cssPrefix}-${rule.name}); }
70
- `).join('\n');
499
+ updateStyleByRegExp(prop, value) {
500
+ // 构建正则:匹配属性名后面跟着冒号,直到分号或换行
501
+ // 例如:height:\s*[^;]+;
502
+ const regex = new RegExp(`;\\n\\s*${prop}:\\s*[^;]+;`, 'g');
503
+ // 替换为新的属性值
504
+ this.baseStylesEl.textContent = this.baseStylesEl.textContent.replace(regex, `;\n${prop}: ${value};`);
505
+ }
506
+ getCssPrefix(config) {
507
+ return (config?.cssPrefix || this.lang).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
508
+ }
509
+ getHighLightString(string, config) {
510
+ config = config || CoaxElem.languages.get(this.lang);
511
+ if (!config)
512
+ return string;
513
+ // 如果找到了配置,则进行高亮处理
514
+ const cssPrefix = this.getCssPrefix(config),
515
+ // 获取用于语法高亮的正则表达式
516
+ combinedRegex = new RegExp(config.rules.map((r) => `(${r.pattern.source})`).join('|'), 'g');
517
+ return string.replace(combinedRegex, (match, ...args) => {
518
+ const i = args.findIndex(val => val !== undefined);
519
+ return i !== -1 && config.rules[i] ? `<span class="${NAMESPACE}-${cssPrefix}-${config.rules[i].token}">${match}</span>` : match;
520
+ });
521
+ }
522
+ createLineWrap(index, startIndex) {
523
+ let dataIndex = 0;
524
+ if (index == null && startIndex == null) {
525
+ dataIndex = this.highlightedCodeEl.children.length;
71
526
  }
72
527
  else {
73
- // If no config, display raw code without highlighting
74
- highlightedCode = this.rawCode;
528
+ const start = startIndex || this.highlightedCodeEl.children.length;
529
+ dataIndex = start + index;
75
530
  }
76
- //Generate CSS theme variables if a theme is provided
77
- const themeVars = config?.theme
78
- ? Object.entries(config.theme).map(([k, v]) => `--ax-${cssPrefix}-${k}: ${v};`).join('\n')
79
- : '';
531
+ return createEl('div', { 'data-index': dataIndex }, '<div></div>');
532
+ }
533
+ getLineToFill(codeWrap, line, config) {
534
+ config = config || CoaxElem.languages.get(this.lang);
535
+ let highlightedLine = this.getHighLightString(line, config);
536
+ // 将高亮后的内容填充到 div 中
537
+ codeWrap.innerHTML = highlightedLine;
538
+ }
539
+ ;
540
+
541
+ async highlight(newCode) {
542
+ const config = CoaxElem.languages.get(this.lang), startIndex = this.highlightedCodeEl.children.length,
543
+ // 将新源码按行分割
544
+ newCodeLines = newCode ? newCode.split('\n') : [];
545
+ //更新别名
546
+ this.updateName(config);
547
+ if (!newCodeLines.length)
548
+ return true;
549
+ // 如果没有找到配置,则输出原始代码,并不进行高亮处理
550
+ for (let [index, lineString] of newCodeLines.entries()) {
551
+ //如果是空行则跳过
552
+ if (!lineString.trim() && this.hasAttribute('sanitized'))
553
+ continue;
554
+ // 创建一个 div 包裹每一行
555
+ const lineWrap = this.createLineWrap(index, startIndex), codeWrap = lineWrap.lastElementChild;
556
+ //标记完成
557
+ this.closeLine(lineWrap);
558
+ if (this.hasAttribute('speed')) {
559
+ this.highlightedCodeEl.appendChild(lineWrap);
560
+ //流式打字
561
+ await typeWriter(lineString, {
562
+ speed: this.speed,
563
+ onDuringType: (char, fullText) => {
564
+ codeWrap.innerHTML = fullText;
565
+ }
566
+ });
567
+ this.getLineToFill(codeWrap, lineString, config);
568
+ }
569
+ else {
570
+ //直接打出
571
+ this.getLineToFill(codeWrap, lineString, config);
572
+ //
573
+ this.highlightedCodeEl.appendChild(lineWrap);
574
+ }
575
+ }
576
+ //滚动到最底部
577
+ this.autoScrollCode();
578
+ return true;
579
+ }
580
+ autoScrollCode() {
581
+ if (this.autoScroll) {
582
+ this.codeBodyEl.scrollTop = this.codeBodyEl.scrollHeight;
583
+ }
584
+ }
585
+ injectThemeStyles() {
586
+ const config = CoaxElem.languages.get(this.lang);
587
+ if (!config)
588
+ return;
589
+ // Get language name, fallback to 'js' if not provided
590
+ let cssPrefix = this.getCssPrefix(config),
591
+ //Generate dynamic CSS classes for each syntax rule
592
+ // 为 rules 中的每一个 name 生成类似 .hl-name { color: var(--ax-code-name); }
593
+ lightStyles = config.rules.map((rule) => `
594
+ .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token}${rule.light ? ',' + rule.light : ''});}`).join('\n'), darkStyles = '', schemeStyles = '';
595
+ darkStyles += `:host([scheme="dark"]){`;
596
+ darkStyles += config.rules.map((rule) => `
597
+ ${rule.light ? `
598
+ .${NAMESPACE}-${cssPrefix}-${rule.token} {color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark});}` : ``}`).join('\n');
599
+ darkStyles += `}`;
600
+ schemeStyles = `@media (prefers-color-scheme: dark){
601
+ :host{
602
+ `;
603
+ schemeStyles += config.rules.map((rule) => `
604
+ ${rule.light ? `
605
+ .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark}); }` : ``} `).join('\n');
606
+ schemeStyles += `}`;
80
607
  // Set the inner HTML of the shadow root, including styles and highlighted code
81
- this.shadowRoot.innerHTML = `
82
- <style>
83
- :host {
84
- ${themeVars}
85
-
86
- font-size: var(--ax-code-fs,14px);
87
- display: block;
88
- padding: var(--ax-code-p,1em);
89
- box-sizing:border-box;
90
- line-height: var(--ax-code-lh,1.5);
91
- background-color:var(--ax-code-bg,rgba(0,0,0,0.02));
92
- color:var(--ax-code-c,#333);
93
- border:var(--ax-code-bw,1px) solid var(--ax-code-bc,rgba(0,0,0,0.08));
94
- height:${height || 'var(--ax-code-h,auto)'};
95
- max-height:${maxHeight || 'var(--ax-code-mh,500px)'};
96
- overflow:auto;
97
- transition: border-color 0.3s ease,color 0.3s ease;
98
- border-radius: var(--ax-code-r,9px);
99
- }
100
- pre,code{
101
- font-family:"Consolas", "Monaco", "Andale Mono", "Ubuntu Mono", "monospace", "microsoft yahei", "Microsoft JhengHei", "Yu Mincho", "simsun";
102
- margin:0;
103
- padding:0;
104
- }
105
-
106
-
107
-
108
- ${dynamicStyles}
109
-
110
-
111
- ${config?.internalCss || ''}
112
- </style>
113
- <pre><code>${highlightedCode}</code></pre>`;
608
+ // 2. 精确更新 DOM 节点而非重写 ShadowRoot
609
+ this.dynamicStylesEl.textContent = lightStyles + darkStyles + schemeStyles;
610
+ //附加主题样式
611
+ if (config?.themeStyles) {
612
+ this.themeStylesEl.textContent = config.themeStyles;
613
+ }
614
+ }
615
+ updateName(config) {
616
+ if (this.hasAttribute('unnamed'))
617
+ return;
618
+ if (!config) {
619
+ this.codeNameEl.innerHTML = 'Plain Text';
620
+ }
621
+ else {
622
+ //更新别名
623
+ this.alias = config.alias || this.lang;
624
+ this.codeNameEl.innerHTML = this.alias;
625
+ }
114
626
  }
115
- }
116
- customElements.define('ax-code', Coax);
117
- Coax.register('html', {
118
- rules: [
119
- { name: 'comment', reg: /&lt;!--[\s\S]*?--&gt;/ },
120
- { name: 'doctype', reg: /&lt;!DOCTYPE[\s\S]*?&gt;/i },
121
- // 匹配标签名: <div, </div
122
- { name: 'tag', reg: /&lt;\/?[a-zA-Z0-9]+/ },
123
- // 匹配属性名: class=
124
- { name: 'attr', reg: /[a-zA-Z-]+(?=\s*=\s*)/ },
125
- // 匹配属性值: "value"
126
- { name: 'string', reg: /(['"])(?:\\.|[^\\])*?\1/ },
127
- // 匹配标签闭合: >, />
128
- { name: 'bracket', reg: /\/?&gt;/ }
129
- ],
130
- //添加root变量:--ax-html-keyword
131
627
 
132
- });
133
- Coax.register('css', {
134
- rules: [
135
- { name: 'comment', reg: /\/\*[\s\S]*?\*\// },
136
- { name: 'value', reg: /(?:'|")(?:\\.|[^\\'"\b])*?(?:'|")/ },
137
- { name: 'func', reg: /[a-z-]+\(?=/ },
138
- { name: 'property', reg: /[a-z-]+(?=\s*:)/ },
139
- { name: 'selector', reg: /[.#a-z0-9, \n\t>:+()_-]+(?=\s*\{)/i },
140
- { name: 'unit', reg: /(?<=\d)(px|em|rem|%|vh|vw|ms|s|deg)/ },
141
- { name: 'number', reg: /\b\d+(\.\d+)?\b/ },
142
- { name: 'punct', reg: /[{}();:]/ }
143
- ],
144
- //添加root变量:--ax-code-keyword
145
- theme: {
146
- 'type': '#61afef', // 蓝色选择器
147
- 'keyword': '#d19a66', // 橙色属性名
148
- 'string': '#98c379', // 绿色属性值
149
- 'op': '#abb2bf' // 灰色符号
150
- },
151
- internalCss: `
152
- .ax-css-string { color: var(--ax-code-string); }
153
- .ax-css-string::first-letter { color: var(--ax-code-c); }
154
- `
155
- });
156
- Coax.register('js', {
157
- rules: [
158
- { name: 'comment', reg: /\/\/[^\n]*|\/\*[\s\S]*?\*\// },
159
- { name: 'string', reg: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/ },
160
- { name: 'keyword', reg: /\b(async|await|break|case|catch|class|const|continue|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|while|with|yield|let|static)\b/ },
161
- { name: 'builtin', reg: /\b(console|window|document|Math|JSON|true|false|null|undefined|Object|Array|Promise)\b/ },
162
- { name: 'number', reg: /\b\d+\b/ },
163
- { name: 'func', reg: /\b[a-zA-Z_]\w*(?=\s*\()/ },
164
- { name: 'op', reg: /[+\-*/%=<>!&|^~]+/ }
165
- ],
628
+ render(code = this.source) {
629
+ //同时多次改变属性,只执行一次
630
+ // 如果已经在队列中,则直接返回
631
+ if (this._renderQueued)
632
+ return;
633
+ this._renderQueued = true;
634
+ // 使用 requestAnimationFrame 将渲染推迟到下一帧
635
+ requestAnimationFrame(async () => {
636
+ this.clear();
637
+ this.injectThemeStyles();
638
+ //一次性渲染
639
+ await this.highlight(code);
640
+ this._renderQueued = false;
641
+ });
642
+ }
643
+ clear() {
644
+ this.highlightedCodeEl.innerHTML = this.source = this.lineString = '';
645
+ }
166
646
 
167
- });
168
- Coax.register('ts', {
169
- rules: [
170
- { name: 'comment', reg: /\/\/[^\n]*|\/\*[\s\S]*?\*\// },
171
- { name: 'string', reg: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/ },
172
- { name: 'decorator', reg: /@[a-zA-Z_]\w*/ },
173
- { name: 'keyword', reg: /\b(abstract|as|async|await|break|case|catch|class|const|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|package|private|protected|public|readonly|return|set|static|super|switch|this|throw|try|type|typeof|var|while|with|yield)\b/ },
174
- { name: 'builtin', reg: /\b(any|boolean|never|number|string|symbol|unknown|void|undefined|null|boolean|true|false|console|window|document)\b/ },
175
- { name: 'type', reg: /\b[A-Z]\w*\b/ },
176
- { name: 'number', reg: /\b\d+\b/ },
177
- { name: 'func', reg: /\b[a-zA-Z_]\w*(?=\s*\()/ },
178
- { name: 'op', reg: /(\?\.|![:\.]|[+\-*/%=<>!&|^~]+)/ }
179
- ],
647
+ async replace(newCode) {
648
+ this.clear();
649
+ await this.highlight(newCode);
650
+ }
180
651
 
181
- });
652
+ async append(newCode) {
653
+ // 将新的代码追加到现有代码末尾
654
+ this.source += `\n${newCode}`;
655
+ // 高亮新的部分
656
+ await this.highlight(newCode);
657
+ }
658
+ getActiveCodeWrap() {
659
+ const lastChild = this.highlightedCodeEl.lastElementChild, lastLine = !lastChild || this.highlightedCodeEl.lastElementChild?.completed ?
660
+ this.createLineWrap() : lastChild;
661
+ return {
662
+ lineWrap: lastLine,
663
+ codeWrap: lastLine.lastElementChild
664
+ };
665
+ }
666
+ closeLine(lineWrap) {
667
+ lineWrap = lineWrap || this.highlightedCodeEl.lastElementChild;
668
+ lineWrap && (lineWrap.completed = true);
669
+ }
670
+ openLine(lineWrap) {
671
+ lineWrap = lineWrap || this.highlightedCodeEl.lastElementChild;
672
+ lineWrap && (lineWrap.completed = false);
673
+ }
674
+ stream(str, forceEnd = false) {
675
+ const { lineWrap, codeWrap } = this.getActiveCodeWrap();
676
+ this.highlightedCodeEl.appendChild(lineWrap);
677
+ //汇集
678
+ this.source += str;
679
+ //如果没有遇到换行符号,也可以强制结束
680
+ forceEnd && this.closeLine(lineWrap);
681
+ if (str.startsWith('\n') || str.startsWith('\r')) {
682
+ //标记完成
683
+ this.closeLine(lineWrap);
684
+ //渲染
685
+ this.getLineToFill(codeWrap, this.lineString);
686
+ //一行结束,清空临时行文本
687
+ this.lineString = '';
688
+ }
689
+ else {
690
+ //插入文本
691
+ codeWrap.innerHTML += str;
692
+ //临时保存行文本
693
+ this.lineString += str;
694
+ }
695
+ //滚动到最底部
696
+ this.autoScrollCode();
697
+ }
698
+ }
699
+
700
+ const css = [
701
+ { token: 'comment', pattern: /\/\*[\s\S]*?\*\//, light: '#6a737d', dark: '#8b949e' },
702
+ { token: 'value', pattern: /(?:'|")(?:\\.|[^\\'"\b])*?(?:'|")/, light: '#032f62', dark: '#a5d6ff' },
703
+ { token: 'func', pattern: /[a-z-]+\(?=/, light: '#e36209', dark: '#ffa657' },
704
+ { token: 'property', pattern: /[a-z-]+(?=\s*:)/, light: '#005cc5', dark: '#79c0ff' },
705
+ { token: 'selector', pattern: /[.#a-z0-9, \n\t>:+()_-]+(?=\s*\{)/i, light: '#22863a', dark: '#7ee787' },
706
+ { token: 'unit', pattern: /(?<=\d)(px|em|rem|%|vh|vw|ms|s|deg)/, light: '#d73a49', dark: '#ff7b72' },
707
+ { token: 'number', pattern: /\b\d+(\.\d+)?\b/, light: '#005cc5', dark: '#79c0ff' },
708
+ { token: 'punct', pattern: /[{}();:]/, light: '#24292e', dark: '#c9d1d9' }
709
+ ];
710
+
711
+ const html = [
712
+ { token: 'comment', pattern: /&lt;!--[\s\S]*?--&gt;/, light: '#999999', dark: '#6e7681' },
713
+ { token: 'doctype', pattern: /&lt;!DOCTYPE[\s\S]*?&gt;/i, light: '#6a737d', dark: '#8b949e' },
714
+ // 匹配标签名: <div, </div
715
+ { token: 'tag', pattern: /&lt;\/?[a-zA-Z0-9]+/, light: '#22863a', dark: '#7ee787' },
716
+ // 匹配属性名: class=
717
+ { token: 'attr', pattern: /[a-zA-Z-]+(?=\s*=\s*)/, light: '#6f42c1', dark: '#d2a8ff' },
718
+ // 匹配属性值: "value"
719
+ { token: 'string', pattern: /(['"])(?:\\.|[^\\])*?\1/, light: '#032f62', dark: '#a5d6ff' },
720
+ // 匹配标签闭合: >, />
721
+ { token: 'bracket', pattern: /\/?&gt;/, light: '#24292e', dark: '#c9d1d9' }
722
+ ];
723
+
724
+ const javascript = [
725
+ { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, light: '#6a737d', dark: '#8b949e' },
726
+ { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, light: '#032f62', dark: '#98c379' },
727
+ { token: 'keyword', pattern: /\b(async|await|break|case|catch|class|const|continue|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|new|return|super|switch|this|throw|try|typeof|var|while|with|yield|let|static)\b/, light: '#d73a49', dark: '#ff7b72' },
728
+ { token: 'builtin', pattern: /\b(console|window|document|Math|JSON|true|false|null|undefined|Object|Array|Promise|Number|String|Boolean)\b/, light: '#e36209', dark: '#ffa657' },
729
+ { token: 'number', pattern: /\b(0x[\da-fA-F]+|0b[01]+|\d+(\.\d+)?)\b/, light: '#005cc5', dark: '#79c0ff' },
730
+ { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, light: '#6f42c1', dark: '#d2a8ff' },
731
+ { token: 'op', pattern: /[+\-*/%=<>!&|^~]+/, light: '#069598', dark: '#56b6c2' }
732
+ ];
733
+
734
+ const markdown = [
735
+ // 注释: 这是 Markdown 中的行内注释
736
+ { token: 'comment', pattern: /<!--[\s\S]*?-->/, light: '#6a737d', dark: '#8b949e' },
737
+ // 标题: 通过 `#` 来定义标题
738
+ { token: 'heading', pattern: /(^|\n)(#{1,6})\s*(.+)/, light: '#e36209', dark: '#ffa657' },
739
+ // 粗体: **text** 或 __text__
740
+ { token: 'bold', pattern: /\*\*([^*]+)\*\*|__([^_]+)__/g, light: '#d73a49', dark: '#ff7b72' },
741
+ // 斜体: *text* 或 _text_
742
+ { token: 'italic', pattern: /\*([^*]+)\*|_([^_]+)_/g, light: '#032f62', dark: '#a5d6ff' },
743
+ // 链接: [text](url)
744
+ { token: 'link', pattern: /\[([^\]]+)\]\(([^)]+)\)/g, light: '#0288d1', dark: '#80c0ff' },
745
+ // 行内代码: `code`
746
+ { token: 'inline-code', pattern: /`([^`]+)`/g, light: '#032f62', dark: '#98c379' },
747
+ // 代码块: ```code```
748
+ { token: 'code-block', pattern: /```([^\n]+)\n([\s\S]*?)```/g, light: '#24292e', dark: '#c9d1d9' },
749
+ // 列表项: - item 或 * item
750
+ { token: 'list-item', pattern: /(^|\n)([-*])\s+(.+)/g, light: '#5c6e7c', dark: '#8b949e' },
751
+ // 引用: > text
752
+ { token: 'quote', pattern: /(^|\n)>[ \t]*(.+)/g, light: '#6f42c1', dark: '#d2a8ff' },
753
+ // 图片: ![alt](url)
754
+ { token: 'image', pattern: /!\[([^\]]+)\]\(([^)]+)\)/g, light: '#d73a49', dark: '#ff7b72' },
755
+ // 分割线: ---
756
+ { token: 'hr', pattern: /^(---|___|\*\*\*)\s*$/gm, light: '#24292e', dark: '#c9d1d9' },
757
+ // 强调和删除: ~~text~~
758
+ { token: 'strikethrough', pattern: /~~([^~]+)~~/g, light: '#e36209', dark: '#ffa657' },
759
+ // 表格: | header1 | header2 |
760
+ { token: 'table', pattern: /\|([^\|]+)\|([^\|]+)\|/g, light: '#5c6e7c', dark: '#8b949e' }
761
+ ];
762
+
763
+ const typescript = [
764
+ { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, light: '#6a737d', dark: '#8b949e' },
765
+ { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, light: '#032f62', dark: '#98c379' },
766
+ { token: 'decorator', pattern: /@[a-zA-Z_]\w*/, light: '#953800', dark: '#ffa657' },
767
+ { token: 'keyword', pattern: /\b(abstract|as|async|await|break|case|catch|class|const|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|package|private|protected|public|readonly|return|set|static|super|switch|this|throw|try|type|typeof|var|while|with|yield)\b/, light: '#d73a49', dark: '#ff7b72' },
768
+ { token: 'builtin', pattern: /\b(any|boolean|never|number|string|symbol|unknown|void|undefined|null|true|false|console|window|document)\b/, light: '#e36209', dark: '#ffa657' },
769
+ { token: 'type', pattern: /\b[A-Z]\w*\b/, light: '#005cc5', dark: '#79c0ff' },
770
+ { token: 'number', pattern: /\b(0x[\da-fA-F]+|0b[01]+|\d+(\.\d+)?)\b/, light: '#005cc5', dark: '#79c0ff' },
771
+ { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, light: '#6f42c1', dark: '#d2a8ff' },
772
+ { token: 'op', pattern: /(\?\.|![:\.]|[+\-*/%=<>!&|^~]+)/, light: '#089ba6', dark: '#79c0ff' }
773
+ ];
774
+
775
+ const COMMA = ',';
776
+
777
+ const SPACE = ' ';
778
+
779
+ const trim = (str, placement = '') => {
780
+ if (typeof str !== 'string') {
781
+ console.warn('Expected a string input');
782
+ return '';
783
+ }
784
+ switch (placement) {
785
+ case 'start':
786
+ return str.trimStart();
787
+ case 'end':
788
+ return str.trimEnd();
789
+ case 'both':
790
+ return str.trim();
791
+ case 'global':
792
+ return str.replace(/[\s\r\n]+/g, '');
793
+ default:
794
+ return str.trim().replace(/[\s\r\n]+/g, ' '); // Default behavior, trims both ends and replaces inner spaces
795
+ }
796
+ };
797
+
798
+ const parseClasses = (data) => {
799
+ let separator, result = [];
800
+ if (Array.isArray(data)) {
801
+ // If data is already an array, filter out invalid values
802
+ result = data.filter((k) => k && typeof k === 'string');
803
+ }
804
+ else {
805
+ // Trim the input string and handle multiple spaces
806
+ data = trim(data);
807
+ // Use comma as the separator if present, otherwise use space
808
+ separator = data.includes(COMMA) ? COMMA : SPACE;
809
+ result = data.split(separator);
810
+ }
811
+ // Trim each item globally and filter out any empty strings
812
+ return result.map((k) => trim(k, 'global')).filter(Boolean);
813
+ };
814
+
815
+ const rtlStyle = (name = '') => `
816
+ <style>
817
+ :where([dir="rtl"]) .icax-${name},
818
+ :where(:dir(rtl)) .icax-${name} {
819
+ transform: scaleX(-1);
820
+ transform-origin: center;
821
+ }
822
+ </style>
823
+ `;
824
+
825
+ const wrap = (content, fun, isRtl = false, options) => {
826
+ const size = options?.size || '1em', color = options?.color || 'currentColor', thickness = options?.thickness || 2, classes = options?.classes ? parseClasses(options.classes).join(' ') : '',
827
+ // 得到 "icax-left"
828
+ origName = fun.name.replace(/([A-Z])/g, "-$1").toLowerCase();
829
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="${color}"
830
+ stroke-width="${thickness}" stroke-linecap="round" stroke-linejoin="round" class="${origName} ${classes}">
831
+ ${isRtl ? rtlStyle(origName.split('-')[1]) : ''}
832
+ ${content}
833
+ </svg>`;
834
+ };
835
+
836
+ const icaxCheck = (options) => wrap(`<polyline points="20 6 9 17 4 12"></polyline>`, icaxCheck, false, options);
837
+
838
+ const icaxCopy = (options) => wrap(`<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>`, icaxCopy, false, options);
839
+
840
+ const copy = {
841
+ name: 'copy',
842
+ icon: icaxCopy(),
843
+ action: function (arg) {
844
+ arg.wrapEl.onclick = () => {
845
+ //this只是组件实例
846
+ navigator.clipboard.writeText(this.source)
847
+ .then(() => {
848
+ console.log('Text successfully copied to clipboard');
849
+ arg.iconEl.innerHTML = icaxCheck();
850
+ arg.iconEl.toggleAttribute('disabled', true);
851
+ setTimeout(() => {
852
+ //恢复
853
+ arg.iconEl.removeAttribute('disabled');
854
+ arg.iconEl.innerHTML = icaxCopy();
855
+ }, 2000);
856
+ })
857
+ .catch(err => {
858
+ console.error('Error copying text to clipboard: ', err);
859
+ });
860
+ };
861
+ }
862
+ };
863
+
864
+ exports.CoaxElem = CoaxElem;
865
+ exports.copy = copy;
866
+ exports.css = css;
867
+ exports.html = html;
868
+ exports.javascript = javascript;
869
+ exports.markdown = markdown;
870
+ exports.typescript = typescript;