@codady/coax 0.0.2 → 0.0.4

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/LICENSE +1 -1
  2. package/README.md +331 -166
  3. package/dist/coax.cjs.js +450 -271
  4. package/dist/coax.cjs.min.js +4 -4
  5. package/dist/coax.esm.js +444 -271
  6. package/dist/coax.esm.min.js +4 -4
  7. package/dist/coax.umd.js +466 -266
  8. package/dist/coax.umd.min.js +4 -4
  9. package/examples/.htaccess +0 -0
  10. package/examples/append-highlight.html +82 -0
  11. package/examples/color-selector.html +412 -0
  12. package/examples/deepseek-highlight.html +100 -0
  13. package/examples/js-highlight.html +1 -1
  14. package/examples/md-highlight.html +60 -0
  15. package/examples/nginx.htaccess +0 -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 +4 -4
  20. package/rollup.config.js +3 -3
  21. package/script-note.js +2 -2
  22. package/src/Coax.js +25 -414
  23. package/src/Coax.ts +28 -443
  24. package/src/components/Coax.js +528 -0
  25. package/src/components/Coax.ts +556 -0
  26. package/src/modules.js +12 -0
  27. package/src/modules.ts +23 -0
  28. package/src/rules/css.js +11 -0
  29. package/src/rules/css.ts +11 -0
  30. package/src/rules/html.js +13 -0
  31. package/src/rules/html.ts +13 -0
  32. package/src/rules/javascript.js +10 -0
  33. package/src/rules/javascript.ts +10 -0
  34. package/src/rules/markdown.js +29 -0
  35. package/src/rules/markdown.ts +41 -0
  36. package/src/rules/ruleCss - /345/211/257/346/234/254.js" +10 -0
  37. package/src/rules/ruleHTML - /345/211/257/346/234/254.js" +12 -0
  38. package/src/rules/ruleJs - /345/211/257/346/234/254.js" +10 -0
  39. package/src/rules/ruleTs - /345/211/257/346/234/254.js" +12 -0
  40. package/src/rules/typescript.js +12 -0
  41. package/src/rules/typescript.ts +12 -0
  42. package/src/tools/copy.js +26 -0
  43. package/src/tools/copy.ts +29 -0
package/src/Coax.js CHANGED
@@ -1,365 +1,19 @@
1
1
  /**
2
- * Last modified: 2026/01/08 16:55:35
2
+ * Last modified: 2026/01/12 14:12:01
3
3
  */
4
- import createTools from "@codady/utils/src/createTools.js";
5
- import icaxCopy from "@codady/icax/src/icaxCopy";
6
- import getEl from "@codady/utils/src/getEl.js";
7
- import createEl from "@codady/utils/src/createEl.js";
8
- import NAMESPACE from "@codady/utils/src/namespace.js";
9
- import icaxCheck from "@codady/icax/src/icaxCheck";
10
- import parseClasses from "@codady/utils/src/parseClasses.js";
11
- class Coax extends HTMLElement {
12
- // A static Map to hold the configuration for different languages
13
- static languages = new Map();
14
- static tools = [];
15
- source;
16
- _renderQueued = false;
17
- baseStylesEl;
18
- themeStylesEl;
19
- dynamicStylesEl;
20
- highlightedCodeEl;
21
- headerEl;
22
- nameEl;
23
- toolsEl;
24
- alias;
25
- constructor() {
26
- super();
27
- // Attach a Shadow DOM to the custom element
28
- this.attachShadow({ mode: 'open' });
29
- // Remove leading/trailing whitespace from the raw code content
30
- this.source = this.textContent?.replace(/^\s*\n|\n\s*$/g, '') || '';
31
- this.lang = 'plain';
32
- this.alias = 'Plain Text';
33
- // 1. 初始化基础骨架
34
- this.shadowRoot.innerHTML = `
35
- <style id="base-styles">
36
- :host {
37
- --border-width:1px;
38
- --border-style:solid;
39
- --radius:9px;
40
- --height:auto;
41
- --max-height:500px;
42
- --radius:9px;
43
- --padding:1em;
44
- --font-size:16px;
45
- --line-height:1.8;
46
- --background:rgb(247, 247, 247);
47
- --border-color:rgb(224, 224, 224);
48
- --color-code:rgb(51, 51, 51);
49
- --color-index:rgb(153, 153, 153);
50
- --color-stripe:rgb(224, 224, 224);
51
- --color-hover:rgb(224, 224, 224);
52
- }
53
- :host([scheme="dark"]){
54
- --background: #282c34;
55
- --border-color: transparent;
56
- --color-code: #abb2bf;
57
- --color-index:rgb(153, 153, 153);
58
- --color-stripe:rgb(66, 66, 66);
59
- --color-hover:rgb(66, 66, 66);
60
- }
61
- @media (prefers-color-scheme: dark) {
62
- :host{
63
- --background: #282c34;
64
- --border-color: transparent;
65
- --color-code: #abb2bf;
66
- --color-index:rgb(153, 153, 153);
67
- --color-stripe:rgb(66, 66, 66);
68
- --color-hover:rgb(66, 66, 66);
69
- }
70
- }
71
- :host {
72
- font-size: var(--${NAMESPACE}-code-font-size,var(--font-size));
73
- display: block;
74
- box-sizing:border-box;
75
- background:var(--${NAMESPACE}-code-background-color,var(--background));
76
- color:var(--${NAMESPACE}-code-color,var(--color-code));
77
- 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));
78
- overflow:auto;
79
- transition: border-color 0.3s ease,color 0.3s ease;
80
- border-radius: var(--${NAMESPACE}-code-radius,var(--radius));
81
- }
82
- #code-header{
83
- line-height:calc(var(--${NAMESPACE}-code-line-height,var(--line-height))*1.5);
84
- padding-inline-start:var(--${NAMESPACE}-code-padding,var(--padding));
85
- display:flex;
86
-
87
- >:first-child{
88
- flex:auto;
89
- }
90
- }
91
- #code-body{
92
- padding: var(--${NAMESPACE}-code-padding,var(--padding)) 0;
93
- height:var(--${NAMESPACE}-code-height,var(--height));
94
- max-height:var(--${NAMESPACE}-code-max-height,var(--max-height));
95
- }
96
- pre,code{
97
- font-family:"Consolas", "Monaco", "Andale Mono", "Ubuntu Mono", "monospace";
98
- margin:0; padding:0;
99
- }
100
- code>div{
101
- display:flex;
102
- padding:0 var(--${NAMESPACE}-code-padding,var(--padding));
103
- line-height: var(--${NAMESPACE}-code-line-height,var(--line-height));
104
- box-sizing:border-box;
105
-
106
- >div{
107
- flex:auto;
108
- }
109
- }
110
- :host([indexed]) code>div:before{
111
- display:inline-flex;
112
- color:var(--color-index);
113
- content: attr(data-index);
114
- min-width:var(--${NAMESPACE}-code-index-width,2em);
115
- margin-inline-end:var(--${NAMESPACE}-code-padding,8px);
116
- }
117
- :host([hoverable]) code>div:hover{
118
- background-color:var(--color-hover);
119
- }
120
- :host([striped]) code>div:nth-child(odd){
121
- background-color:var(--color-stripe);
122
- }
123
- :host([wrapped]) code>div{
124
- white-space: pre-wrap;
125
- }
126
- :host([unnamed]) #code-name{
127
- display:none;
128
- }
129
- .${NAMESPACE}-box-tools{
130
- >*{
131
- font-size:14px;
132
- display:inline-flex;
133
- align-items:center;
134
- justify-content:center;
135
- height:2em;
136
- line-height:2em;
137
- aspect-ratio:1/1;
138
- margin-inline-end:8px;
139
- transition:all 200ms ease;
140
- border-radius:6px;
141
- &:hover{
142
- cursor:pointer;
143
- background-color:rgba(0,0,0,.04);
144
- }
145
- }
146
- [rep=icon]{
147
- display:inline-flex;
148
- align-items:center;
149
- justify-content:center;
150
- }
151
- }
152
- [disabled]{
153
- pointer-event:none;
154
- }
155
- </style>
156
- <style id="dynamic-styles"></style>
157
- <style id="theme-styles"></style>
158
- <div id="code-header"><span id="code-name">${this.alias}</span><div id="code-tools"></div></div>
159
- <div id="code-body">
160
- <pre><code id="highlight-code"></code></pre>
161
- </div>
162
- `;
163
- // 缓存引用
164
- this.baseStylesEl = getEl('#base-styles', this.shadowRoot);
165
- this.themeStylesEl = getEl('#theme-styles', this.shadowRoot);
166
- this.dynamicStylesEl = getEl('#dynamic-styles', this.shadowRoot);
167
- this.headerEl = getEl('#code-header', this.shadowRoot);
168
- this.nameEl = getEl('#code-name', this.shadowRoot);
169
- this.toolsEl = getEl('#code-tools', this.shadowRoot);
170
- this.highlightedCodeEl = getEl('#highlight-code', this.shadowRoot);
171
- }
172
- /**
173
- * Registers a new language with a set of syntax highlighting rules.
174
- * @param name - The name of the programming language.
175
- * @param config - Configuration for the language, including rules, theme, and optional CSS.
176
- */
177
- static register(name, config) {
178
- // Store the language configuration in the static map
179
- this.languages.set(name, { ...config });
180
- }
181
- //注册工具箱
182
- static addTools(items) {
183
- Coax.tools = items;
184
- }
185
- //加入工具箱
186
- mountTools(toolItems) {
187
- requestAnimationFrame(() => {
188
- this.toolsEl.innerHTML = '';
189
- let items = toolItems.map(k => {
190
- k.action = k.action.bind(this);
191
- return k;
192
- });
193
- this.toolsEl.appendChild(createTools(items));
194
- });
195
- }
196
- // Called when the element is connected to the DOM
197
- connectedCallback() {
198
- this.render();
199
- }
200
- // Observed attributes for changes
201
- static get observedAttributes() { return ['lang', 'height', 'max-height', 'tools']; }
202
- /**
203
- * Called when any of the observed attributes change.
204
- */
205
- attributeChangedCallback(name, oldVal, newVal) {
206
- if (oldVal === newVal)
207
- return;
208
- if (name === 'height' || name === 'max-height') {
209
- this.updateStyleByRegExp(name, newVal);
210
- }
211
- else if (name === 'lang') {
212
- //更新当前语言
213
- this.lang = newVal;
214
- this.render();
215
- }
216
- else if (name === 'unnamed') {
217
- this.nameEl.innerHTML = newVal === null ? (this.alias || this.lang) : '';
218
- this.nameEl.innerHTML = '';
219
- }
220
- else if (name === 'tools') {
221
- if (!newVal)
222
- this.toolsEl.innerHTML = '';
223
- const tools = parseClasses(newVal), toolItems = Coax.tools.filter(k => tools.includes(k.name));
224
- if (!toolItems.length)
225
- return;
226
- this.mountTools(toolItems);
227
- }
228
- }
229
- /**
230
- * 使用正则替换基础样式表中的特定属性,避免操作行内样式
231
- */
232
- updateStyleByRegExp(prop, value) {
233
- // 构建正则:匹配属性名后面跟着冒号,直到分号或换行
234
- // 例如:height:\s*[^;]+;
235
- const regex = new RegExp(`;\\n\\s*${prop}:\\s*[^;]+;`, 'g');
236
- // 替换为新的属性值
237
- this.baseStylesEl.textContent = this.baseStylesEl.textContent.replace(regex, `;\n${prop}: ${value};`);
238
- }
239
- getCssPrefix(config) {
240
- return (config?.cssPrefix || this.lang).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
241
- }
242
- /**
243
- * 处理新源码,按行高亮并追加到高亮区域
244
- * @param newCode - 新的源码片段
245
- */
246
- highlight(newCode) {
247
- const config = Coax.languages.get(this.lang), startIndex = this.highlightedCodeEl.children.length,
248
- // 将新源码按行分割
249
- newCodeLines = newCode.split('\n'),
250
- // 如果没有找到配置,则输出原始代码,并不进行高亮处理
251
- highlightedLines = newCodeLines.map((line, index) => {
252
- let highlightedLine = line;
253
- // 如果找到了配置,则进行高亮处理
254
- if (config) {
255
- const cssPrefix = this.getCssPrefix(config);
256
- // 获取用于语法高亮的正则表达式
257
- const combinedRegex = new RegExp(config.rules.map((r) => `(${r.pattern.source})`).join('|'), 'g');
258
- // 进行高亮替换
259
- highlightedLine = line.replace(combinedRegex, (match, ...args) => {
260
- const i = args.findIndex(val => val !== undefined);
261
- return i !== -1 && config.rules[i] ? `<span class="${NAMESPACE}-${cssPrefix}-${config.rules[i].token}">${match}</span>` : match;
262
- });
263
- }
264
- // 创建一个 div 包裹每一行
265
- const lineDiv = createEl('div', { 'data-index': startIndex + index });
266
- lineDiv.innerHTML = `<div>${highlightedLine}</div>`; // 将高亮后的内容填充到 div 中
267
- return lineDiv;
268
- });
269
- //
270
- // 将新生成的行节点追加到 highlightedCodeEl 节点中
271
- this.highlightedCodeEl.append(...highlightedLines);
272
- }
273
- injectThemeStyles() {
274
- const config = Coax.languages.get(this.lang);
275
- if (!config)
276
- return;
277
- // Get language name, fallback to 'js' if not provided
278
- let cssPrefix = this.getCssPrefix(config),
279
- //Generate dynamic CSS classes for each syntax rule
280
- // 为 rules 中的每一个 name 生成类似 .hl-name { color: var(--ax-code-name); }
281
- lightStyles = config.rules.map((rule) => `
282
- .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token}${rule.color ? ',' + rule.color : ''});}`).join('\n'), darkStyles = '', schemeStyles = '';
283
- darkStyles += `:host([scheme="dark"]){`;
284
- darkStyles += config.rules.map((rule) => `
285
- ${rule.color ? `
286
- .${NAMESPACE}-${cssPrefix}-${rule.token} {color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark});}` : ``}`).join('\n');
287
- darkStyles += `}`;
288
- schemeStyles = `@media (prefers-color-scheme: dark){
289
- :host{
290
- `;
291
- schemeStyles += config.rules.map((rule) => `
292
- ${rule.color ? `
293
- .${NAMESPACE}-${cssPrefix}-${rule.token} { color: var(--${NAMESPACE}-${cssPrefix}-${rule.token},${rule.dark}); }` : ``} `).join('\n');
294
- schemeStyles += `}`;
295
- // Set the inner HTML of the shadow root, including styles and highlighted code
296
- // 2. 精确更新 DOM 节点而非重写 ShadowRoot
297
- this.dynamicStylesEl.textContent = lightStyles + darkStyles + schemeStyles;
298
- //附加主题样式
299
- if (config?.themeStyles) {
300
- this.themeStylesEl.textContent = config.themeStyles;
301
- }
302
- //更新别名
303
- this.updateName(config);
304
- }
305
- updateName(config) {
306
- if (this.hasAttribute('unnamed'))
307
- return;
308
- //更新别名
309
- this.alias = config.alias || this.lang;
310
- this.nameEl.innerHTML = this.alias;
311
- }
312
- /**
313
- * Renders the highlighted code within the shadow DOM.
314
- */
315
- render() {
316
- //同时多次改变属性,只执行一次
317
- // 如果已经在队列中,则直接返回
318
- if (this._renderQueued)
319
- return;
320
- this._renderQueued = true;
321
- // 使用 requestAnimationFrame 将渲染推迟到下一帧
322
- requestAnimationFrame(() => {
323
- this.highlightedCodeEl.innerHTML = '';
324
- //一次性渲染
325
- this.highlight(this.source);
326
- this.injectThemeStyles();
327
- this._renderQueued = false;
328
- });
329
- }
330
- /**
331
- * 替换现有的源码并重新渲染
332
- * @param newCode - 新的源码
333
- */
334
- replaceCode(newCode) {
335
- // 更新原始代码为新代码
336
- this.source = newCode;
337
- //清空
338
- this.highlightedCodeEl.innerHTML = '';
339
- this.highlight(newCode);
340
- }
341
- /**
342
- * 末尾新增源码,仅高亮新增的部分
343
- * @param newCode - 新的源码片段
344
- */
345
- appendCode(newCode) {
346
- // 将新的代码追加到现有代码末尾
347
- this.source += `\n${newCode}`;
348
- // 高亮新的部分
349
- this.highlight(newCode);
350
- }
351
- }
4
+ 'use strict';
5
+ import NAMESPACE from "@codady/utils/namespace";
6
+ import html from "./rules/html.js";
7
+ import javascript from "./rules/javascript.js";
8
+ import markdown from "./rules/markdown.js";
9
+ import typescript from "./rules/typescript.js";
10
+ import copy from "./tools/copy.js";
11
+ import css from "./rules/css.js";
12
+ import Coax from "./components/Coax.js";
13
+ //注册语言类型
352
14
  Coax.register('css', {
353
- rules: [
354
- { token: 'comment', pattern: /\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
355
- { token: 'value', pattern: /(?:'|")(?:\\.|[^\\'"\b])*?(?:'|")/, color: '#61afef', dark: '#a5d6ff' },
356
- { token: 'func', pattern: /[a-z-]+\(?=/, color: '#e36209', dark: '#ffa657' },
357
- { token: 'property', pattern: /[a-z-]+(?=\s*:)/, color: '#005cc5', dark: '#79c0ff' },
358
- { token: 'selector', pattern: /[.#a-z0-9, \n\t>:+()_-]+(?=\s*\{)/i, color: '#6f42c1', dark: '#d2a8ff' },
359
- { token: 'unit', pattern: /(?<=\d)(px|em|rem|%|vh|vw|ms|s|deg)/, color: '#d73a49', dark: '#ff7b72' },
360
- { token: 'number', pattern: /\b\d+(\.\d+)?\b/, color: '#005cc5', dark: '#79c0ff' },
361
- { token: 'punct', pattern: /[{}();:]/, color: '#24292e', dark: '#c9d1d9' }
362
- ],
15
+ alias: 'CSS',
16
+ rules: css,
363
17
  /* cssPrefix: 'css',
364
18
  themeStyles: `
365
19
  :host {
@@ -382,65 +36,22 @@ Coax.register('css', {
382
36
  ` */
383
37
  });
384
38
  Coax.register('html', {
385
- rules: [
386
- { token: 'comment', pattern: /&lt;!--[\s\S]*?--&gt;/, color: '#6a737d', dark: '#8b949e' },
387
- { token: 'doctype', pattern: /&lt;!DOCTYPE[\s\S]*?&gt;/i, color: '#005cc5', dark: '#56b6c2' },
388
- // 匹配标签名: <div, </div
389
- { token: 'tag', pattern: /&lt;\/?[a-zA-Z0-9]+/, color: '#22863a', dark: '#abb2bf' },
390
- // 匹配属性名: class=
391
- { token: 'attr', pattern: /[a-zA-Z-]+(?=\s*=\s*)/, color: '#6f42c1', dark: '#e06c75' },
392
- // 匹配属性值: "value"
393
- { token: 'string', pattern: /(['"])(?:\\.|[^\\])*?\1/, color: '#032f62', dark: '#f39c12' },
394
- // 匹配标签闭合: >, />
395
- { token: 'bracket', pattern: /\/?&gt;/, color: '#24292e', dark: '#f1f1f1' }
396
- ],
39
+ alias: 'HTML',
40
+ rules: html,
397
41
  });
398
42
  Coax.register('js', {
399
43
  alias: 'Javascript',
400
- rules: [
401
- { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
402
- { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, color: '#032f62', dark: '#61afef' },
403
- { 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' },
404
- { token: 'builtin', pattern: /\b(console|window|document|Math|JSON|true|false|null|undefined|Object|Array|Promise)\b/, color: '#56b6c2', dark: '#61afef' },
405
- { token: 'number', pattern: /\b\d+\b/, color: '#61afef', dark: '#d19a66' },
406
- { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, color: '#e5c07b', dark: '#98c379' },
407
- { token: 'op', pattern: /[+\-*/%=<>!&|^~]+/, color: '#d73a49', dark: '#e06c75' }
408
- ],
44
+ rules: javascript,
409
45
  });
410
46
  Coax.register('ts', {
411
- rules: [
412
- { token: 'comment', pattern: /\/\/[^\n]*|\/\*[\s\S]*?\*\//, color: '#6a737d', dark: '#8b949e' },
413
- { token: 'string', pattern: /(?:'|"|`)(?:\\.|[^\\'"\b])*?(?:'|"|`)/, color: '#032f62', dark: '#61afef' },
414
- { token: 'decorator', pattern: /@[a-zA-Z_]\w*/, color: '#d19a66', dark: '#e5c07b' },
415
- { 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' },
416
- { 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' },
417
- { token: 'type', pattern: /\b[A-Z]\w*\b/, color: '#22863a', dark: '#8b949e' },
418
- { token: 'number', pattern: /\b\d+\b/, color: '#61afef', dark: '#d19a66' },
419
- { token: 'func', pattern: /\b[a-zA-Z_]\w*(?=\s*\()/, color: '#e5c07b', dark: '#98c379' },
420
- { token: 'op', pattern: /(\?\.|![:\.]|[+\-*/%=<>!&|^~]+)/, color: '#d73a49', dark: '#e06c75' }
421
- ],
47
+ alias: 'Typescript',
48
+ rules: typescript,
422
49
  });
423
- Coax.addTools([{
424
- name: 'copy',
425
- icon: icaxCopy(),
426
- action: function (arg) {
427
- arg.wrapEl.onclick = () => {
428
- //this只是组件实例
429
- navigator.clipboard.writeText(this.source)
430
- .then(() => {
431
- console.log('Text successfully copied to clipboard');
432
- arg.iconEl.innerHTML = icaxCheck();
433
- arg.iconEl.toggleAttribute('disabled', true);
434
- setTimeout(() => {
435
- //恢复
436
- arg.iconEl.removeAttribute('disabled');
437
- arg.iconEl.innerHTML = icaxCopy();
438
- }, 2000);
439
- })
440
- .catch(err => {
441
- console.error('Error copying text to clipboard: ', err);
442
- });
443
- };
444
- }
445
- }]);
50
+ Coax.register('md', {
51
+ alias: 'Markdown',
52
+ rules: markdown
53
+ });
54
+ //注册工具箱
55
+ Coax.addTools([copy]);
446
56
  customElements.define(`${NAMESPACE}-code`, Coax);
57
+ export default Coax;