Socket
Book a DemoInstallSign in
Socket

@codady/coax

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@codady/coax

Coax is a lightweight web component for elegant code display with syntax highlighting, typewriter effects, and theme switching. Supports JavaScript, HTML, CSS, TypeScript, and Markdown with copy tools and customization.

latest
Source
npmnpm
Version
0.0.5
Version published
Weekly downloads
151
Maintainers
1
Weekly downloads
 
Created
Source

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 使用

<!-- 直接引入 UMD 版本 -->
<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 / 属性

AttributeTypeDefaultDescription描述
langstring'plain'Programming language编程语言
speednumber5Typing speed (higher = slower)打字速度(值越高越慢)
indexedbooleanfalseShow line numbers显示行号
stripedbooleanfalseZebra striping斑马纹背景
hoverablebooleanfalseHighlight line on hover鼠标悬停高亮
wrappedbooleanfalseLine wrapping自动换行
unnamedbooleanfalseHide language name隐藏语言名称
sanitizedbooleanfalseRemove empty lines移除空行
schemestring'auto'Color scheme: light, dark, auto配色方案
heightstring'auto'Container height容器高度
max-heightstring'500px'Max container height最大容器高度
toolsstring''Comma-separated tools逗号分隔的工具

Supported Languages / 支持的语言

LanguageAliasKey
JavaScriptJavascriptjs
TypeScriptTypescriptts
HTMLHTMLhtml
CSSCSScss
MarkdownMarkdownmd
Plain TextPlain Textplain

Methods / 方法

Static Methods / 静态方法

// Register a new language
Coax.register('python', {
    alias: 'Python',
    rules: [
        { token: 'keyword', pattern: /\b(def|class|if|else|for|while)\b/, light: '#d73a49', dark: '#ff7b72' },
        // ... more rules
    ]
});

// Register custom tools
Coax.addTools([
    {
        name: 'download',
        icon: '<svg>...</svg>',
        action: function() {
            // Download code as file
        }
    }
]);

Instance Methods / 实例方法

const codeElement = document.querySelector('ax-code');

// Replace all code
codeElement.replace('const x = 10;');

// Append new code
codeElement.append('\nconsole.log(x);');

// Stream code with typewriter effect
codeElement.stream('function test() {\n', true);

// Clear all code
codeElement.clear();

// Get current source
console.log(codeElement.source);

// Control auto-scroll
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
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() {
        // 使用 Prettier 或其他格式化工具
        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 / 联系

  • Email: 3217728223@qq.com
  • Author: AXUI development team

Made with ❤️ by the AXUI Development Team

由 AXUI 开发团队用心打造

"Elegant code deserves elegant display."
"优雅的代码值得优雅的展示。"

Keywords

javascript

FAQs

Package last updated on 12 Jan 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts