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