Coax - Code Display Web Component
一个优雅的代码高亮和显示 Web 组件。
An elegant code highlighting and display web component.
🌟 Features / 功能特性
- Syntax Highlighting - Built-in support for HTML, CSS, JavaScript, TypeScript, Markdown
- 语法高亮 - 内置 HTML、CSS、JavaScript、TypeScript、Markdown 支持
- Typewriter Effect - Real-time streaming with adjustable speed
- 打字机效果 - 实时流式显示,速度可调
- Dark/Light Mode - Automatic theme switching based on system preference
- 明暗模式 - 基于系统偏好自动切换主题
- Interactive Tools - Copy button with visual feedback
- 交互工具 - 带视觉反馈的复制按钮
- Customizable - Extensive CSS custom properties for styling
- 高度可定制 - 丰富的 CSS 自定义属性
- Line Features - Line numbers, zebra striping, hover effects
- 行功能 - 行号、斑马纹、悬停效果
📦 Installation / 安装
CDN Usage / CDN 使用
<script src="https://unpkg.com/@codady/coax@latest"></script>
<script type="module">
import 'https://unpkg.com/@codady/coax@latest';
</script>
NPM Installation / NPM 安装
npm install @codady/coax
yarn add @codady/coax
import '@codady/coax';
🚀 Quick Start / 快速开始
Basic Usage / 基本使用
<ax-code lang="js">
function greet(name) {
console.log(`Hello, ${name}!`);
return true;
}
</ax-code>
All Features / 全部功能
<ax-code
lang="ts"
speed="5"
indexed
striped
hoverable
wrapped
scheme="dark"
tools="copy"
height="300px"
max-height="500px"
>
interface User {
id: number;
name: string;
email: string;
greet(): string;
}
const user: User = {
id: 1,
name: "John",
email: "john@example.com",
greet() {
return `Hello, ${this.name}!`;
}
};
</ax-code>
📚 API Reference / API 参考
Attributes / 属性
lang | string | 'plain' | Programming language | 编程语言 |
speed | number | 5 | Typing speed (higher = slower) | 打字速度(值越高越慢) |
indexed | boolean | false | Show line numbers | 显示行号 |
striped | boolean | false | Zebra striping | 斑马纹背景 |
hoverable | boolean | false | Highlight line on hover | 鼠标悬停高亮 |
wrapped | boolean | false | Line wrapping | 自动换行 |
unnamed | boolean | false | Hide language name | 隐藏语言名称 |
sanitized | boolean | false | Remove empty lines | 移除空行 |
scheme | string | 'auto' | Color scheme: light, dark, auto | 配色方案 |
height | string | 'auto' | Container height | 容器高度 |
max-height | string | '500px' | Max container height | 最大容器高度 |
tools | string | '' | Comma-separated tools | 逗号分隔的工具 |
Supported Languages / 支持的语言
| JavaScript | Javascript | js |
| TypeScript | Typescript | ts |
| HTML | HTML | html |
| CSS | CSS | css |
| Markdown | Markdown | md |
| Plain Text | Plain Text | plain |
Methods / 方法
Static Methods / 静态方法
Coax.register('python', {
alias: 'Python',
rules: [
{ token: 'keyword', pattern: /\b(def|class|if|else|for|while)\b/, light: '#d73a49', dark: '#ff7b72' },
]
});
Coax.addTools([
{
name: 'download',
icon: '<svg>...</svg>',
action: function() {
}
}
]);
Instance Methods / 实例方法
const codeElement = document.querySelector('ax-code');
codeElement.replace('const x = 10;');
codeElement.append('\nconsole.log(x);');
codeElement.stream('function test() {\n', true);
codeElement.clear();
console.log(codeElement.source);
codeElement.autoScroll = false;
🎨 Customization / 自定义
CSS Custom Properties / CSS 自定义属性
ax-code {
--ax-code-font-size: 14px;
--ax-code-line-height: 1.6;
--ax-code-padding: 1rem;
--ax-code-radius: 8px;
--ax-js-keyword: #d73a49;
--ax-js-string: #032f62;
--ax-code-background-color: #f8f9fa;
--ax-code-color: #212529;
--ax-code-border-color: #dee2e6;
}
ax-code[scheme]{
--ax-code-dark-background: #1a1d23;
--ax-code-dark-color: #e9ecef;
--ax-code-dark-border: #495057;
}
Register Custom Language / 注册自定义语言
const pythonRules = [
{
token: 'keyword',
pattern: /\b(def|class|if|elif|else|for|while|try|except|finally|with|import|from|as)\b/,
light: '#d73a49',
dark: '#ff7b72'
},
{
token: 'string',
pattern: /(['"`])(?:\\.|[^\\'"\b])*?(?:['"`])/,
light: '#032f62',
dark: '#98c379'
},
{
token: 'comment',
pattern: /#.*/,
light: '#6a737d',
dark: '#8b949e'
},
{
token: 'decorator',
pattern: /@\w+/,
light: '#6f42c1',
dark: '#d2a8ff'
}
];
Coax.register('python', {
alias: 'Python 3',
rules: pythonRules,
themeStyles: `
/* 额外样式 */
.ax-python-decorator {
font-style: italic;
}
`
});
Create Custom Tools / 创建自定义工具
const formatTool = {
name: 'format',
icon: `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<polygon points="3 11 22 2 13 21 11 13 3 11"></polygon>
</svg>`,
title: 'Format Code',
action: function() {
const formatted = prettier.format(this.source, {
parser: 'babel',
semi: true,
singleQuote: true
});
this.replace(formatted);
}
};
const shareTool = {
name: 'share',
icon: `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
<polyline points="16 6 12 2 8 6"></polyline><line x1="12" y1="2" x2="12" y2="15"></line>
</svg>`,
title: 'Share Code',
action: function() {
const code = encodeURIComponent(this.source);
const url = `${window.location.origin}/share?code=${code}`;
navigator.clipboard.writeText(url);
alert('Share link copied to clipboard!');
}
};
Coax.addTools([formatTool, shareTool]);
📝 Examples / 示例
Interactive Demo / 交互式演示
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coax</title>
<style>
</style>
</head>
<body>
<ax-code streaming tools="copy" indexed lang="js">
<code>
/**
* Simple animation function
*/
async function animate(element, duration) {
const start = Date.now();
if (!element) return false;
console.log("Animation started...");
while (Date.now() - start < duration) {
let progress = (Date.now() - start) / duration;
element.style.opacity = Math.min(progress, 1);
await Promise.resolve();
}
return true;
}
</code>
</ax-code>
<script src="https://unpkg.com/@codady/coax@latest/dist/coax.umd.js" type='text/javascript'></script>
</body>
</html>
Advanced Usage / 高级用法
const createCodeBlock = (lang, code) => {
const codeBlock = document.createElement('ax-code');
codeBlock.setAttribute('lang', lang);
codeBlock.textContent = code;
return codeBlock;
};
document.body.appendChild(createCodeBlock('js', 'const x = 10;'));
const codeElement = document.querySelector('ax-code');
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'lang') {
console.log('Language changed to:', codeElement.lang);
}
});
});
observer.observe(codeElement, { attributes: true });
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'c' && document.activeElement === codeElement) {
e.preventDefault();
navigator.clipboard.writeText(codeElement.source);
}
});
📄 License / 许可证
MIT License. See LICENSE file for details.
This software supports the MIT License, allowing free learning and commercial use, but please retain the terms 'coax', 'Coax' and 'COAX' within the software.
MIT 许可证。详见 LICENSE 文件。
本软件支持 MIT 许可证,允许自由学习和商业使用,但请保留软件中的 'coax'、'Coax' 和 'COAX' 字样。
Contact / 联系
Made with ❤️ by the AXUI Development Team
由 AXUI 开发团队用心打造
"Elegant code deserves elegant display."
"优雅的代码值得优雅的展示。"