@codady/coax 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-8 16:55:44
4
4
  * @name Coax event management system.
5
- * @version 0.0.1
5
+ * @version 0.0.2
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,691 @@
16
16
 
17
17
  'use strict';
18
18
 
19
+ const getDataType = (obj) => {
20
+ let tmp = Object.prototype.toString.call(obj).slice(8, -1), result;
21
+ if (tmp === 'Function' && /^\s*class\s+/.test(obj.toString())) {
22
+ result = 'Class';
23
+ }
24
+ else if (tmp === 'Object' && Object.getPrototypeOf(obj) !== Object.prototype) {
25
+ result = 'Instance';
26
+ }
27
+ else {
28
+ result = tmp;
29
+ }
30
+ return result;
31
+ //document.createElement -> HTMLxxxElement
32
+ //document.createDocumentFragment() -> DocumentFragment
33
+ //document.createComment() -> Comment
34
+ //document.createTextNode -> Text
35
+ //document.createCDATASection() -> XMLDocument
36
+ //document.createProcessingInstruction() -> ProcessingInstruction
37
+ //document.createRange() -> Range
38
+ //document.createTreeWalker() -> TreeWalker
39
+ //document.createNodeIterator() -> NodeIterator
40
+ //document.createElementNS('http://www.w3.org/2000/svg', 'svg'); -> SVGSVGElement
41
+ //document.createElementNS('http://www.w3.org/1998/Math/MathML', 'math'); -> MathMLElement
42
+ };
43
+
44
+ const getEl = (obj, wrap = document.body) => {
45
+ let objType = getDataType(obj), parType = getDataType(wrap), parent = parType.includes('HTML') || parType === 'ShadowRoot' ? wrap : document.querySelector(wrap),
46
+ //如果parent是template节点,需要通过node.content.querySelector取得子节点
47
+ root = parent && parent instanceof HTMLTemplateElement ? parent.content : parent, result = null;
48
+ if (obj) {
49
+ if (objType.includes('HTML')) {
50
+ result = obj;
51
+ }
52
+ else if (objType === 'String') {
53
+ try {
54
+ result = (root || document).querySelector(obj.trim());
55
+ //可能会报错,报错则返回null
56
+ }
57
+ catch {
58
+ result = null;
59
+ }
60
+ }
61
+ }
62
+ return result;
63
+ };
64
+
65
+ const createEl = (name, attrs, content) => {
66
+ //默认为div
67
+ name = name || 'div';
68
+ //统一大小写
69
+ let rootName = name.toUpperCase().trim(), rootEl = document.createElement(rootName), attrsType = getDataType(attrs), loop = (host, data) => {
70
+ if (data === '' || data === null || data === undefined) {
71
+ //为空、未定义则不再执行
72
+ return false;
73
+ }
74
+ let dataType = getDataType(data);
75
+ //template是DocumentFragment类型不能用insertAdjacentHTML
76
+ if (rootName === 'TEMPLATE') {
77
+ host.innerHTML = data.toString();
78
+ }
79
+ else {
80
+ if (dataType === 'Array' && data.length > 0) {
81
+ //节点数组
82
+ //data.forEach((i: T_obj) => loop(el, i));
83
+ for (let k of data) {
84
+ let childType = getDataType(k);
85
+ if (childType.includes('HTML')) {
86
+ //是个节点
87
+ host.appendChild(k);
88
+ }
89
+ else {
90
+ //是个对象{name:'',attrs:{},content:''}
91
+ let child = createEl(k.name, k.attrs, k.content);
92
+ child && host.appendChild(child);
93
+ }
94
+ }
95
+ }
96
+ else if (dataType.includes('HTML')) {
97
+ //HTML节点
98
+ host.appendChild(data);
99
+ }
100
+ else if (dataType === 'String' && data.trim().startsWith('#') && data.trim().length > 1) {
101
+ //是字符串且是#id选择器,则取其文本
102
+ let el = getEl(data);
103
+ if (!el)
104
+ return;
105
+ //如果是template模板节点则需要特殊处理
106
+ el.nodeName === 'TEMPLATE' ? host.appendChild(el.content.cloneNode(true)) : host.insertAdjacentHTML('beforeEnd', el.innerHTML);
107
+ }
108
+ else {
109
+ //字符串数字等
110
+ host.insertAdjacentHTML('beforeEnd', data);
111
+ }
112
+ }
113
+ };
114
+ //添加属性
115
+ if (attrs && attrsType === 'Object') {
116
+ for (let k in attrs) {
117
+ //注意,attrs[k]可能是一个{}或[],不一定是字符串
118
+ // JSON.stringify可以将所有格式的数据都转成文本,会忽略函数和节点数据
119
+ //字符串则不需要stringify,否则会将字符串的引号也一并输出
120
+ attrs.hasOwnProperty(k) && rootEl.setAttribute(k, typeof attrs[k] === 'string' ? attrs[k] : JSON.stringify(attrs[k]));
121
+ }
122
+ }
123
+ //执行循环创建子节点
124
+ loop(rootEl, content);
125
+ return rootEl;
126
+ };
127
+
128
+ const isEmpty = (data) => {
129
+ let type = getDataType(data), flag;
130
+ if (!data) {
131
+ //0,'',false,undefined,null
132
+ flag = true;
133
+ }
134
+ else {
135
+ //function(){}|()=>{}
136
+ //[null]|[undefined]|['']|[""]
137
+ //[]|{}
138
+ //Symbol()|Symbol.for()
139
+ //Set,Map
140
+ //Date/Regex
141
+ flag = (type === 'Object') ? (Object.keys(data).length === 0) :
142
+ (type === 'Array') ? data.join('') === '' :
143
+ (type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
144
+ (type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
145
+ (type === 'Set' || type === 'Map') ? data.size === 0 :
146
+ type === 'Date' ? isNaN(data.getTime()) :
147
+ type === 'RegExp' ? data.source === '' :
148
+ type === 'ArrayBuffer' ? data.byteLength === 0 :
149
+ (type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
150
+ ('length' in data && typeof data.length === 'number') ? data.length === 0 :
151
+ ('size' in data && typeof data.size === 'number') ? data.size === 0 :
152
+ (type === 'Error' || data instanceof Error) ? data.message === '' :
153
+ (type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
154
+ false;
155
+ }
156
+ return flag;
157
+ };
158
+
159
+ const ALIAS = 'rep';
160
+
161
+ const NAMESPACE = 'ax';
162
+
163
+ const COMMA$1 = ',';
164
+
165
+ const SPACE$1 = ' ';
166
+
167
+ const trim$1 = (str, placement = '') => {
168
+ if (typeof str !== 'string') {
169
+ console.warn('Expected a string input');
170
+ return '';
171
+ }
172
+ switch (placement) {
173
+ case 'start':
174
+ return str.trimStart();
175
+ case 'end':
176
+ return str.trimEnd();
177
+ case 'both':
178
+ return str.trim();
179
+ case 'global':
180
+ return str.replace(/[\s\r\n]+/g, '');
181
+ default:
182
+ return str.trim().replace(/[\s\r\n]+/g, ' '); // Default behavior, trims both ends and replaces inner spaces
183
+ }
184
+ };
185
+
186
+ const parseClasses$1 = (data) => {
187
+ let separator, result = [];
188
+ if (Array.isArray(data)) {
189
+ // If data is already an array, filter out invalid values
190
+ result = data.filter((k) => k && typeof k === 'string');
191
+ }
192
+ else {
193
+ // Trim the input string and handle multiple spaces
194
+ data = trim$1(data);
195
+ // Use comma as the separator if present, otherwise use space
196
+ separator = data.includes(COMMA$1) ? COMMA$1 : SPACE$1;
197
+ result = data.split(separator);
198
+ }
199
+ // Trim each item globally and filter out any empty strings
200
+ return result.map((k) => trim$1(k, 'global')).filter(Boolean);
201
+ };
202
+
203
+ const addClasses = (target, classes, intercept) => {
204
+ const el = getEl(target), arr = parseClasses$1(classes);
205
+ if (!el || arr.length === 0) {
206
+ return;
207
+ }
208
+ arr.forEach((k) => {
209
+ {
210
+ el.classList.add(k);
211
+ }
212
+ });
213
+ };
214
+
215
+ const createTools = (data) => {
216
+
217
+ const toolsEl = createEl('span', { class: `${NAMESPACE}-box-tools` }), renderFn = (props) => {
218
+ 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;
219
+ //使用title提示
220
+ props.title && (dftAttrs.title = props.title);
221
+ //可聚焦,增加tabindex=1
222
+ props.focusable && (dftAttrs.tabindex = 1);
223
+ //attrs是其他属性,可能会覆盖title、tabindex
224
+ props.wrapEl = createEl(props.nodeName || 'span', Object.assign(dftAttrs, props.attrs), html);
225
+ props.iconEl = props.wrapEl.querySelector(`[${ALIAS}="icon"]`);
226
+ props.cubeEl = props.wrapEl.querySelector(`[${ALIAS}="cube"]`);
227
+ props.diskEl = props.wrapEl.querySelector(`[${ALIAS}="disk"]`);
228
+ props.imageEl = props.wrapEl.querySelector(`[${ALIAS}="image"]`);
229
+ props.labelEl = props.wrapEl.querySelector(`[${ALIAS}="label"]`);
230
+ //增加classes和styles
231
+ !isEmpty(props.classes) && addClasses(props.wrapEl, props.classes);
232
+ !isEmpty(props.styles) && (props.wrapEl.style.cssText += props.styles);
233
+ };
234
+ //此处不用map方法,是避免改变原data的内存地址指向
235
+ for (let item of data) {
236
+ //data=[{},{},'toggle','close']
237
+ renderFn(item);
238
+ toolsEl.appendChild(item.wrapEl);
239
+ item?.action?.(item);
240
+ }
241
+ return toolsEl;
242
+ };
243
+
244
+ const COMMA = ',';
245
+
246
+ const SPACE = ' ';
247
+
248
+ const trim = (str, placement = '') => {
249
+ if (typeof str !== 'string') {
250
+ console.warn('Expected a string input');
251
+ return '';
252
+ }
253
+ switch (placement) {
254
+ case 'start':
255
+ return str.trimStart();
256
+ case 'end':
257
+ return str.trimEnd();
258
+ case 'both':
259
+ return str.trim();
260
+ case 'global':
261
+ return str.replace(/[\s\r\n]+/g, '');
262
+ default:
263
+ return str.trim().replace(/[\s\r\n]+/g, ' '); // Default behavior, trims both ends and replaces inner spaces
264
+ }
265
+ };
266
+
267
+ const parseClasses = (data) => {
268
+ let separator, result = [];
269
+ if (Array.isArray(data)) {
270
+ // If data is already an array, filter out invalid values
271
+ result = data.filter((k) => k && typeof k === 'string');
272
+ }
273
+ else {
274
+ // Trim the input string and handle multiple spaces
275
+ data = trim(data);
276
+ // Use comma as the separator if present, otherwise use space
277
+ separator = data.includes(COMMA) ? COMMA : SPACE;
278
+ result = data.split(separator);
279
+ }
280
+ // Trim each item globally and filter out any empty strings
281
+ return result.map((k) => trim(k, 'global')).filter(Boolean);
282
+ };
283
+
284
+ const rtlStyle = (name = '') => `
285
+ <style>
286
+ :where([dir="rtl"]) .icax-${name},
287
+ :where(:dir(rtl)) .icax-${name} {
288
+ transform: scaleX(-1);
289
+ transform-origin: center;
290
+ }
291
+ </style>
292
+ `;
293
+
294
+ const wrap = (content, fun, isRtl = false, options) => {
295
+ const size = options?.size || '1em', color = options?.color || 'currentColor', thickness = options?.thickness || 2, classes = options?.classes ? parseClasses(options.classes).join(' ') : '',
296
+ // 得到 "icax-left"
297
+ origName = fun.name.replace(/([A-Z])/g, "-$1").toLowerCase();
298
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="${color}"
299
+ stroke-width="${thickness}" stroke-linecap="round" stroke-linejoin="round" class="${origName} ${classes}">
300
+ ${isRtl ? rtlStyle(origName.split('-')[1]) : ''}
301
+ ${content}
302
+ </svg>`;
303
+ };
304
+
305
+ 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);
306
+
307
+ const icaxCheck = (options) => wrap(`<polyline points="20 6 9 17 4 12"></polyline>`, icaxCheck, false, options);
308
+
19
309
  class Coax extends HTMLElement {
20
310
  // A static Map to hold the configuration for different languages
21
311
  static languages = new Map();
22
- // Raw code as text from the HTML content
23
- rawCode;
312
+ static tools = [];
313
+ source;
314
+ _renderQueued = false;
315
+ baseStylesEl;
316
+ themeStylesEl;
317
+ dynamicStylesEl;
318
+ highlightedCodeEl;
319
+ headerEl;
320
+ nameEl;
321
+ toolsEl;
322
+ alias;
24
323
  constructor() {
25
324
  super();
26
325
  // Attach a Shadow DOM to the custom element
27
326
  this.attachShadow({ mode: 'open' });
28
327
  // Remove leading/trailing whitespace from the raw code content
29
- this.rawCode = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
328
+ this.source = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
329
+ this.lang = 'plain';
330
+ this.alias = 'Plain Text';
331
+ // 1. 初始化基础骨架
332
+ this.shadowRoot.innerHTML = `
333
+ <style id="base-styles">
334
+ :host {
335
+ --border-width:1px;
336
+ --border-style:solid;
337
+ --radius:9px;
338
+ --height:auto;
339
+ --max-height:500px;
340
+ --radius:9px;
341
+ --padding:1em;
342
+ --font-size:16px;
343
+ --line-height:1.8;
344
+ --background:rgb(247, 247, 247);
345
+ --border-color:rgb(224, 224, 224);
346
+ --color-code:rgb(51, 51, 51);
347
+ --color-index:rgb(153, 153, 153);
348
+ --color-stripe:rgb(224, 224, 224);
349
+ --color-hover:rgb(224, 224, 224);
350
+ }
351
+ :host([scheme="dark"]){
352
+ --background: #282c34;
353
+ --border-color: transparent;
354
+ --color-code: #abb2bf;
355
+ --color-index:rgb(153, 153, 153);
356
+ --color-stripe:rgb(66, 66, 66);
357
+ --color-hover:rgb(66, 66, 66);
358
+ }
359
+ @media (prefers-color-scheme: dark) {
360
+ :host{
361
+ --background: #282c34;
362
+ --border-color: transparent;
363
+ --color-code: #abb2bf;
364
+ --color-index:rgb(153, 153, 153);
365
+ --color-stripe:rgb(66, 66, 66);
366
+ --color-hover:rgb(66, 66, 66);
367
+ }
368
+ }
369
+ :host {
370
+ font-size: var(--${NAMESPACE}-code-font-size,var(--font-size));
371
+ display: block;
372
+ box-sizing:border-box;
373
+ background:var(--${NAMESPACE}-code-background-color,var(--background));
374
+ color:var(--${NAMESPACE}-code-color,var(--color-code));
375
+ 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));
376
+ overflow:auto;
377
+ transition: border-color 0.3s ease,color 0.3s ease;
378
+ border-radius: var(--${NAMESPACE}-code-radius,var(--radius));
379
+ }
380
+ #code-header{
381
+ line-height:calc(var(--${NAMESPACE}-code-line-height,var(--line-height))*1.5);
382
+ padding-inline-start:var(--${NAMESPACE}-code-padding,var(--padding));
383
+ display:flex;
384
+
385
+ >:first-child{
386
+ flex:auto;
387
+ }
388
+ }
389
+ #code-body{
390
+ padding: var(--${NAMESPACE}-code-padding,var(--padding)) 0;
391
+ height:var(--${NAMESPACE}-code-height,var(--height));
392
+ max-height:var(--${NAMESPACE}-code-max-height,var(--max-height));
393
+ }
394
+ pre,code{
395
+ font-family:"Consolas", "Monaco", "Andale Mono", "Ubuntu Mono", "monospace";
396
+ margin:0; padding:0;
397
+ }
398
+ code>div{
399
+ display:flex;
400
+ padding:0 var(--${NAMESPACE}-code-padding,var(--padding));
401
+ line-height: var(--${NAMESPACE}-code-line-height,var(--line-height));
402
+ box-sizing:border-box;
403
+
404
+ >div{
405
+ flex:auto;
406
+ }
407
+ }
408
+ :host([indexed]) code>div:before{
409
+ display:inline-flex;
410
+ color:var(--color-index);
411
+ content: attr(data-index);
412
+ min-width:var(--${NAMESPACE}-code-index-width,2em);
413
+ margin-inline-end:var(--${NAMESPACE}-code-padding,8px);
414
+ }
415
+ :host([hoverable]) code>div:hover{
416
+ background-color:var(--color-hover);
417
+ }
418
+ :host([striped]) code>div:nth-child(odd){
419
+ background-color:var(--color-stripe);
420
+ }
421
+ :host([wrapped]) code>div{
422
+ white-space: pre-wrap;
423
+ }
424
+ :host([unnamed]) #code-name{
425
+ display:none;
426
+ }
427
+ .${NAMESPACE}-box-tools{
428
+ >*{
429
+ font-size:14px;
430
+ display:inline-flex;
431
+ align-items:center;
432
+ justify-content:center;
433
+ height:2em;
434
+ line-height:2em;
435
+ aspect-ratio:1/1;
436
+ margin-inline-end:8px;
437
+ transition:all 200ms ease;
438
+ border-radius:6px;
439
+ &:hover{
440
+ cursor:pointer;
441
+ background-color:rgba(0,0,0,.04);
442
+ }
443
+ }
444
+ [rep=icon]{
445
+ display:inline-flex;
446
+ align-items:center;
447
+ justify-content:center;
448
+ }
449
+ }
450
+ [disabled]{
451
+ pointer-event:none;
452
+ }
453
+ </style>
454
+ <style id="dynamic-styles"></style>
455
+ <style id="theme-styles"></style>
456
+ <div id="code-header"><span id="code-name">${this.alias}</span><div id="code-tools"></div></div>
457
+ <div id="code-body">
458
+ <pre><code id="highlight-code"></code></pre>
459
+ </div>
460
+ `;
461
+ // 缓存引用
462
+ this.baseStylesEl = getEl('#base-styles', this.shadowRoot);
463
+ this.themeStylesEl = getEl('#theme-styles', this.shadowRoot);
464
+ this.dynamicStylesEl = getEl('#dynamic-styles', this.shadowRoot);
465
+ this.headerEl = getEl('#code-header', this.shadowRoot);
466
+ this.nameEl = getEl('#code-name', this.shadowRoot);
467
+ this.toolsEl = getEl('#code-tools', this.shadowRoot);
468
+ this.highlightedCodeEl = getEl('#highlight-code', this.shadowRoot);
30
469
  }
31
470
 
32
- static register(name, { rules, theme = {}, internalCss = '', cssPrefix = '' }) {
471
+ static register(name, config) {
33
472
  // 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();
473
+ this.languages.set(name, { ...config });
474
+ }
475
+ //注册工具箱
476
+ static addTools(items) {
477
+ Coax.tools = items;
478
+ }
479
+ //加入工具箱
480
+ mountTools(toolItems) {
481
+ requestAnimationFrame(() => {
482
+ this.toolsEl.innerHTML = '';
483
+ let items = toolItems.map(k => {
484
+ k.action = k.action.bind(this);
485
+ return k;
486
+ });
487
+ this.toolsEl.appendChild(createTools(items));
39
488
  });
40
489
  }
41
490
  // Called when the element is connected to the DOM
42
- connectedCallback() { this.render(); }
43
- // Observed attributes for changes
44
- static get observedAttributes() { return ['lang', 'height', 'max-height']; }
45
-
46
- attributeChangedCallback() {
491
+ connectedCallback() {
47
492
  this.render();
48
493
  }
494
+ // Observed attributes for changes
495
+ static get observedAttributes() { return ['lang', 'height', 'max-height', 'tools']; }
49
496
 
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');
497
+ attributeChangedCallback(name, oldVal, newVal) {
498
+ if (oldVal === newVal)
499
+ return;
500
+ if (name === 'height' || name === 'max-height') {
501
+ this.updateStyleByRegExp(name, newVal);
71
502
  }
72
- else {
73
- // If no config, display raw code without highlighting
74
- highlightedCode = this.rawCode;
503
+ else if (name === 'lang') {
504
+ //更新当前语言
505
+ this.lang = newVal;
506
+ this.render();
507
+ }
508
+ else if (name === 'unnamed') {
509
+ this.nameEl.innerHTML = newVal === null ? (this.alias || this.lang) : '';
510
+ this.nameEl.innerHTML = '';
75
511
  }
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
- : '';
512
+ else if (name === 'tools') {
513
+ if (!newVal)
514
+ this.toolsEl.innerHTML = '';
515
+ const tools = parseClasses$1(newVal), toolItems = Coax.tools.filter(k => tools.includes(k.name));
516
+ if (!toolItems.length)
517
+ return;
518
+ this.mountTools(toolItems);
519
+ }
520
+ }
521
+
522
+ updateStyleByRegExp(prop, value) {
523
+ // 构建正则:匹配属性名后面跟着冒号,直到分号或换行
524
+ // 例如:height:\s*[^;]+;
525
+ const regex = new RegExp(`;\\n\\s*${prop}:\\s*[^;]+;`, 'g');
526
+ // 替换为新的属性值
527
+ this.baseStylesEl.textContent = this.baseStylesEl.textContent.replace(regex, `;\n${prop}: ${value};`);
528
+ }
529
+ getCssPrefix(config) {
530
+ return (config?.cssPrefix || this.lang).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
531
+ }
532
+
533
+ highlight(newCode) {
534
+ const config = Coax.languages.get(this.lang), startIndex = this.highlightedCodeEl.children.length,
535
+ // 将新源码按行分割
536
+ newCodeLines = newCode.split('\n'),
537
+ // 如果没有找到配置,则输出原始代码,并不进行高亮处理
538
+ highlightedLines = newCodeLines.map((line, index) => {
539
+ let highlightedLine = line;
540
+ // 如果找到了配置,则进行高亮处理
541
+ if (config) {
542
+ const cssPrefix = this.getCssPrefix(config);
543
+ // 获取用于语法高亮的正则表达式
544
+ const combinedRegex = new RegExp(config.rules.map((r) => `(${r.pattern.source})`).join('|'), 'g');
545
+ // 进行高亮替换
546
+ highlightedLine = line.replace(combinedRegex, (match, ...args) => {
547
+ const i = args.findIndex(val => val !== undefined);
548
+ return i !== -1 && config.rules[i] ? `<span class="${NAMESPACE}-${cssPrefix}-${config.rules[i].token}">${match}</span>` : match;
549
+ });
550
+ }
551
+ // 创建一个 div 包裹每一行
552
+ const lineDiv = createEl('div', { 'data-index': startIndex + index });
553
+ lineDiv.innerHTML = `<div>${highlightedLine}</div>`; // 将高亮后的内容填充到 div 中
554
+ return lineDiv;
555
+ });
556
+ //
557
+ // 将新生成的行节点追加到 highlightedCodeEl 节点中
558
+ this.highlightedCodeEl.append(...highlightedLines);
559
+ }
560
+ injectThemeStyles() {
561
+ const config = Coax.languages.get(this.lang);
562
+ if (!config)
563
+ return;
564
+ // Get language name, fallback to 'js' if not provided
565
+ let cssPrefix = this.getCssPrefix(config),
566
+ //Generate dynamic CSS classes for each syntax rule
567
+ // 为 rules 中的每一个 name 生成类似 .hl-name { color: var(--ax-code-name); }
568
+ lightStyles = config.rules.map((rule) => `
569
+ .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token}${rule.color ? ',' + rule.color : ''});}`).join('\n'), darkStyles = '', schemeStyles = '';
570
+ darkStyles += `:host([scheme="dark"]){`;
571
+ darkStyles += config.rules.map((rule) => `
572
+ ${rule.color ? `
573
+ .${NAMESPACE}-${cssPrefix}-${rule.token} {color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark});}` : ``}`).join('\n');
574
+ darkStyles += `}`;
575
+ schemeStyles = `@media (prefers-color-scheme: dark){
576
+ :host{
577
+ `;
578
+ schemeStyles += config.rules.map((rule) => `
579
+ ${rule.color ? `
580
+ .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark}); }` : ``} `).join('\n');
581
+ schemeStyles += `}`;
80
582
  // 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>`;
583
+ // 2. 精确更新 DOM 节点而非重写 ShadowRoot
584
+ this.dynamicStylesEl.textContent = lightStyles + darkStyles + schemeStyles;
585
+ //附加主题样式
586
+ if (config?.themeStyles) {
587
+ this.themeStylesEl.textContent = config.themeStyles;
588
+ }
589
+ //更新别名
590
+ this.updateName(config);
591
+ }
592
+ updateName(config) {
593
+ if (this.hasAttribute('unnamed'))
594
+ return;
595
+ //更新别名
596
+ this.alias = config.alias || this.lang;
597
+ this.nameEl.innerHTML = this.alias;
598
+ }
599
+
600
+ render() {
601
+ //同时多次改变属性,只执行一次
602
+ // 如果已经在队列中,则直接返回
603
+ if (this._renderQueued)
604
+ return;
605
+ this._renderQueued = true;
606
+ // 使用 requestAnimationFrame 将渲染推迟到下一帧
607
+ requestAnimationFrame(() => {
608
+ this.highlightedCodeEl.innerHTML = '';
609
+ //一次性渲染
610
+ this.highlight(this.source);
611
+ this.injectThemeStyles();
612
+ this._renderQueued = false;
613
+ });
614
+ }
615
+
616
+ replaceCode(newCode) {
617
+ // 更新原始代码为新代码
618
+ this.source = newCode;
619
+ //清空
620
+ this.highlightedCodeEl.innerHTML = '';
621
+ this.highlight(newCode);
622
+ }
623
+
624
+ appendCode(newCode) {
625
+ // 将新的代码追加到现有代码末尾
626
+ this.source += `\n${newCode}`;
627
+ // 高亮新的部分
628
+ this.highlight(newCode);
114
629
  }
115
630
  }
116
- customElements.define('ax-code', Coax);
631
+ Coax.register('css', {
632
+ rules: [
633
+ { token: 'comment', pattern: /\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
634
+ { token: 'value', pattern: /(?:'|")(?:\\.|[^\\'"\b])*?(?:'|")/, color: '#61afef', dark: '#a5d6ff' },
635
+ { token: 'func', pattern: /[a-z-]+\(?=/, color: '#e36209', dark: '#ffa657' },
636
+ { token: 'property', pattern: /[a-z-]+(?=\s*:)/, color: '#005cc5', dark: '#79c0ff' },
637
+ { token: 'selector', pattern: /[.#a-z0-9, \n\t>:+()_-]+(?=\s*\{)/i, color: '#6f42c1', dark: '#d2a8ff' },
638
+ { token: 'unit', pattern: /(?<=\d)(px|em|rem|%|vh|vw|ms|s|deg)/, color: '#d73a49', dark: '#ff7b72' },
639
+ { token: 'number', pattern: /\b\d+(\.\d+)?\b/, color: '#005cc5', dark: '#79c0ff' },
640
+ { token: 'punct', pattern: /[{}();:]/, color: '#24292e', dark: '#c9d1d9' }
641
+ ],
642
+
643
+ });
117
644
  Coax.register('html', {
118
645
  rules: [
119
- { name: 'comment', reg: /&lt;!--[\s\S]*?--&gt;/ },
120
- { name: 'doctype', reg: /&lt;!DOCTYPE[\s\S]*?&gt;/i },
646
+ { token: 'comment', pattern: /&lt;!--[\s\S]*?--&gt;/, color: '#6a737d', dark: '#8b949e' },
647
+ { token: 'doctype', pattern: /&lt;!DOCTYPE[\s\S]*?&gt;/i, color: '#005cc5', dark: '#56b6c2' },
121
648
  // 匹配标签名: <div, </div
122
- { name: 'tag', reg: /&lt;\/?[a-zA-Z0-9]+/ },
649
+ { token: 'tag', pattern: /&lt;\/?[a-zA-Z0-9]+/, color: '#22863a', dark: '#abb2bf' },
123
650
  // 匹配属性名: class=
124
- { name: 'attr', reg: /[a-zA-Z-]+(?=\s*=\s*)/ },
651
+ { token: 'attr', pattern: /[a-zA-Z-]+(?=\s*=\s*)/, color: '#6f42c1', dark: '#e06c75' },
125
652
  // 匹配属性值: "value"
126
- { name: 'string', reg: /(['"])(?:\\.|[^\\])*?\1/ },
653
+ { token: 'string', pattern: /(['"])(?:\\.|[^\\])*?\1/, color: '#032f62', dark: '#f39c12' },
127
654
  // 匹配标签闭合: >, />
128
- { name: 'bracket', reg: /\/?&gt;/ }
655
+ { token: 'bracket', pattern: /\/?&gt;/, color: '#24292e', dark: '#f1f1f1' }
129
656
  ],
130
- //添加root变量:--ax-html-keyword
131
-
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
657
  });
156
658
  Coax.register('js', {
659
+ alias: 'Javascript',
157
660
  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: /[+\-*/%=<>!&|^~]+/ }
661
+ { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
662
+ { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, color: '#032f62', dark: '#61afef' },
663
+ { 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/, color: '#e06c75', dark: '#d73a49' },
664
+ { token: 'builtin', pattern: /\b(console|window|document|Math|JSON|true|false|null|undefined|Object|Array|Promise)\b/, color: '#56b6c2', dark: '#61afef' },
665
+ { token: 'number', pattern: /\b\d+\b/, color: '#61afef', dark: '#d19a66' },
666
+ { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, color: '#e5c07b', dark: '#98c379' },
667
+ { token: 'op', pattern: /[+\-*/%=<>!&|^~]+/, color: '#d73a49', dark: '#e06c75' }
165
668
  ],
166
-
167
669
  });
168
670
  Coax.register('ts', {
169
671
  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: /(\?\.|![:\.]|[+\-*/%=<>!&|^~]+)/ }
672
+ { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
673
+ { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, color: '#032f62', dark: '#61afef' },
674
+ { token: 'decorator', pattern: /@[a-zA-Z_]\w*/, color: '#d19a66', dark: '#e5c07b' },
675
+ { 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/, color: '#e06c75', dark: '#d73a49' },
676
+ { token: 'builtin', pattern: /\b(any|boolean|never|number|string|symbol|unknown|void|undefined|null|boolean|true|false|console|window|document)\b/, color: '#56b6c2', dark: '#61afef' },
677
+ { token: 'type', pattern: /\b[A-Z]\w*\b/, color: '#22863a', dark: '#8b949e' },
678
+ { token: 'number', pattern: /\b\d+\b/, color: '#61afef', dark: '#d19a66' },
679
+ { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, color: '#e5c07b', dark: '#98c379' },
680
+ { token: 'op', pattern: /(\?\.|![:\.]|[+\-*/%=<>!&|^~]+)/, color: '#d73a49', dark: '#e06c75' }
179
681
  ],
180
-
181
682
  });
683
+ Coax.addTools([{
684
+ name: 'copy',
685
+ icon: icaxCopy(),
686
+ action: function (arg) {
687
+ arg.wrapEl.onclick = () => {
688
+ //this只是组件实例
689
+ navigator.clipboard.writeText(this.source)
690
+ .then(() => {
691
+ console.log('Text successfully copied to clipboard');
692
+ arg.iconEl.innerHTML = icaxCheck();
693
+ arg.iconEl.toggleAttribute('disabled', true);
694
+ setTimeout(() => {
695
+ //恢复
696
+ arg.iconEl.removeAttribute('disabled');
697
+ arg.iconEl.innerHTML = icaxCopy();
698
+ }, 2000);
699
+ })
700
+ .catch(err => {
701
+ console.error('Error copying text to clipboard: ', err);
702
+ });
703
+ };
704
+ }
705
+ }]);
706
+ customElements.define(`${NAMESPACE}-code`, Coax);