{"name":"linecraft","version":"0.2.2","keywords":["terminal","tui","progress","spinner","ansi"],"license":"MIT","_id":"linecraft@0.2.2","maintainers":[{"name":"matthew-dean","email":"matthewdean.me@gmail.com"}],"homepage":"https://github.com/matthew-dean/linecraft#readme","bugs":{"url":"https://github.com/matthew-dean/linecraft/issues"},"dist":{"shasum":"0afebe65e5d16a8d21e456d89e77837caa52e0e4","tarball":"http://registry-npm.ywwl.com/linecraft/download/linecraft-0.2.2.tgz","fileCount":303,"integrity":"sha512-Zn4W6yE5uDDGLbE2ZoRoyCDQyz9+SHMCvfkqa5xTMY1KjoeVA7A/LQiSvF5Jx39VfMMK7u/dJ8yoyUKVRt2IUQ==","signatures":[{"sig":"MEUCIQCAlCViDwDDQPc9qRwQX3HlfShhmj4K720G3azxKflWsgIge1z1oy6wM/+S26Vpgv4RJ/dWQXHvLrE1x5o0mSu/+EI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1013664,"size":177156,"noattachment":false,"key":"/linecraft/-/linecraft-0.2.2.tgz"},"main":"./lib/index.js","type":"module","types":"./lib/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./lib/index.d.ts","import":"./lib/index.js"},"./components":{"types":"./lib/components/index.d.ts","import":"./lib/components/index.js"}},"gitHead":"f58a8a8d8fecb1009a2759153fdbc29d7975c26a","scripts":{"dev":"pnpm build:ts --watch","test":"vitest","build":"pnpm build:ts","record":"vhs","example":"node scripts/run-example.js","test:ts":"vitest","build:ts":"tsc -p tsconfig.build.json","typecheck":"tsc --noEmit","record:all":"node scripts/record-all.js"},"_npmUser":{"name":"matthew-dean","email":"matthewdean.me@gmail.com"},"repository":{"url":"git+https://github.com/matthew-dean/linecraft.git","type":"git"},"_npmVersion":"11.6.2","description":"High-performance terminal UI library for Node.js","directories":{},"_nodeVersion":"24.11.1","_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"tsx":"^4.7.0","vitest":"^1.0.0","typescript":"^5.3.0","@types/node":"^20.0.0"},"_npmOperationalInternal":{"tmp":"tmp/linecraft_0.2.2_1768159767863_0.611279631856301","host":"s3://npm-registry-packages-npm-production"},"readme":"# Linecraft\n\nBuild terminal UIs with components. Create progress bars, spinners, code error displays, and responsive layouts without the hassle.\n\n## Installation\n\n```bash\nnpm install linecraft\n# or\npnpm add linecraft\n```\n\n## Quick Start\n\n```typescript\nimport { Region, Styled, Spinner, Section, Grid } from 'linecraft';\n\nconst r = Region();\n\n// Set some content\nr.set(\n  Section({ title: 'Hello' },\n    Grid({ template: [20, '1*'], columnGap: 2 },\n      Styled({ color: 'cyan' }, 'Status:'),\n      Styled({ color: 'green' }, 'Ready')\n    )\n  )\n);\n\n// Add a spinner\nr.set(\n  Section({ title: 'Loading' },\n    Grid({ template: [3, '1*'], columnGap: 1 },\n      Spinner({ style: 'classic-dots', color: 'green' }),\n      Styled({ color: 'white' }, 'Installing packages...')\n    )\n  )\n);\n\n// Clean up when done\nr.destroy(true);\n```\n\n## Terminal Management Features\n\nLinecraft provides advanced terminal management capabilities that go beyond basic terminal logging:\n\n### Color-Aware Line Wrapping\n\nUnlike basic terminal output, Linecraft's text wrapping is **fully ANSI-aware**. When text wraps across multiple lines, ANSI color codes are preserved and correctly re-applied to each wrapped line. This means:\n\n- **Color preservation**: Colored text maintains its styling across line breaks\n- **Accurate width calculation**: Wrapping is based on visible character width, not raw string length\n- **Smart word breaking**: Text never breaks mid-word, ensuring readability\n- **Multi-line styling**: Complex styled text (like error codes with underlines) wraps correctly\n\nThis is especially important for components like `CodeDebug`, where error messages with colored error codes need to wrap across multiple lines while maintaining their visual styling.\n\n### ANSI Code Handling\n\nLinecraft correctly handles ANSI escape sequences throughout the rendering pipeline:\n\n- **Width measurement**: All width calculations account for ANSI codes (colors, styles, cursor movements)\n- **Text splitting**: When truncating or splitting text, ANSI codes are preserved and re-applied\n- **Grid layouts**: Grid components correctly measure and align ANSI-styled content\n- **Text alignment**: Alignment operations work correctly with styled text\n\n### Terminal State Management\n\nLinecraft manages terminal state to prevent common terminal UI issues:\n\n- **Auto-wrap disabled**: Prevents unwanted line breaks from terminal auto-wrapping\n- **Cursor positioning**: Precise cursor control using absolute positioning\n- **Viewport awareness**: Only renders visible content within the terminal viewport\n- **Clean restoration**: Properly restores terminal state on cleanup\n\n### Responsive Layouts\n\nComponents automatically adapt to terminal size changes:\n\n- **Grid layouts**: Flex columns adjust to available width\n- **Text wrapping**: Wraps at appropriate boundaries based on terminal width\n- **Component sizing**: Components receive updated `availableWidth` context on resize\n\nThese features make Linecraft suitable for building complex, interactive terminal UIs that work reliably across different terminal sizes and configurations.\n\n## Performance\n\nLinecraft is built for high-performance terminal rendering from Node.js. The renderer includes several optimizations to minimize terminal updates and CPU usage:\n\n### Frame Diffing\nOnly updates lines that actually changed. Unchanged lines are skipped entirely, reducing terminal writes by up to 90% for static content.\n\n### Render Throttling\nUses high-resolution timing (`process.hrtime.bigint()`) to limit frame rate (default: 30 FPS). Prevents excessive rendering during rapid updates while maintaining smooth animations.\n\n### Batched ANSI Operations\nAll ANSI escape sequences are batched into a single `stdout.write()` call per frame, minimizing syscalls and improving throughput.\n\n### Efficient Cursor Movement\nOptimized ANSI cursor positioning that only moves when necessary. The renderer tracks viewport state to avoid redundant cursor movements.\n\n### Viewport Management\nOnly renders visible lines within the terminal viewport. Content that extends beyond the viewport is efficiently managed without unnecessary rendering.\n\n### Auto-Wrap Disabled\nDisables terminal auto-wrap to prevent unwanted line breaks, ensuring precise control over terminal output layout.\n\nThese optimizations make Linecraft suitable for real-time terminal UIs, progress displays, and animated components without overwhelming the terminal or consuming excessive CPU.\n\n## Core API\n\n### Region\n\nA region is a managed area of your terminal. It handles rendering, resizing, and component updates.\n\n```typescript\nconst r = Region({\n  width: 80,        // Optional: auto-detects if not set\n  height: 1,        // Optional: expands as needed\n  debugLog: 'debug.log' // Optional: log rendering for debugging\n});\n```\n\n### Setting Content\n\n```typescript\n// Replace all content\nr.set('Hello, world!');\n\n// Or use components\nr.set(Styled({ color: 'green' }, 'Success!'));\n\n// Append content (returns a reference you can use to delete later)\nconst ref = r.add('Line 2');\nref.delete(); // Remove it\n```\n\n### Cleanup\n\n```typescript\nr.destroy(true); // Clean up and restore terminal (true = clear first)\n```\n\n## Semantic Themes\n\nLinecraft includes a built-in semantic theme system that automatically adapts colors based on whether the terminal is in light or dark mode. Instead of hardcoding ANSI colors, you can use semantic tokens:\n\n- `base`: The default text color (gray in both themes)\n- `muted`: Dimmed text for line numbers or separators (dimmed white on dark, dimmed gray on light)\n- `highlight`: Emphasized text (white on dark, bold black on light)\n- `accent`: Primary accent color (bold blue in both themes)\n- `location`: For file paths and locations (magenta in both themes)\n- `success`: Success messages (bright green on dark, green on light)\n- `warning`: Warning messages (bright yellow on dark, bright magenta on light)\n- `error`: Error messages (bright red on dark, red on light)\n- `info`: Informational messages (blue in both themes)\n\nYou can use these tokens anywhere a `Color` is expected:\n\n```typescript\nimport { Styled } from 'linecraft';\n\n// Automatically uses appropriate color based on terminal theme\nconst text = Styled({ color: 'base' }, 'Auto-themed text');\nconst error = Styled({ color: 'error' }, 'Error message');\nconst path = Styled({ color: 'location' }, '/path/to/file.ts');\n\n// You can also resolve them manually if needed\nimport { autoColor, autoStyle } from 'linecraft';\nconst color = autoColor('warning'); // Returns just the color\nconst style = autoStyle('accent'); // Returns full TextStyle (color, bold, etc.)\n```\n\n## Components\n\n### Styled\n\nApply colors and styling to text.\n\n```typescript\nimport { Styled } from 'linecraft';\n\nr.set(Styled({ \n  color: 'brightGreen', \n  bold: true\n}, 'Bold green text'));\n```\n\n**Options:**\n- `color?: Color` - Text color\n- `backgroundColor?: Color` - Background color\n- `bold?: boolean` - Bold text\n- `italic?: boolean` - Italic text\n- `underline?: boolean` - Underlined text\n- `overflow?: 'none' | 'ellipsis-end' | 'ellipsis-start' | 'ellipsis-middle' | 'wrap'` - Text overflow handling\n- `align?: 'left' | 'right' | 'center'` - Text alignment\n\n### Section\n\nWrap content in a bordered box with an optional title.\n\n![Section Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/section.gif)\n\n```typescript\nimport { Section } from 'linecraft';\n\nr.set(Section(\n  { title: 'My Section' },\n  'Content goes here'\n));\n```\n\n**Options:**\n- `title?: string` - Title shown in a tab at the top\n- `titleColor?: Color` - Color of the title\n- `borderColor?: Color` - Color of borders\n- `padding?: number` - Internal padding (default: 1)\n- `left?: boolean` - Show left border (default: true)\n- `right?: boolean` - Show right border (default: true)\n- `top?: boolean` - Show top border (default: true)\n- `bottom?: boolean` - Show bottom border (default: true)\n\n### CodeDebug\n\nDisplay code errors and warnings with line numbers, context, and clickable file paths. Perfect for linters, compilers, and development tools that need to show diagnostic information.\n\n![CodeDebug Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/code-debug.gif)\n\n```typescript\nimport { CodeDebug } from 'linecraft';\n\nr.set(CodeDebug({\n  startLine: 42,\n  startColumn: 10,\n  endLine: 42,\n  endColumn: 20,\n  errorLine: '    const result = fetchData();',\n  lineBefore: '  async function load() {',\n  lineAfter: '    return process(result);',\n  message: 'Type error: fetchData is not defined',\n  errorCode: 'typescript(2304)', // Optional: error code with underline\n  shortMessage: 'not defined', // Optional: short message connected to underline\n  filePath: 'src/loaders/data.ts',\n  fullPath: '/absolute/path/to/src/loaders/data.ts',\n  baseDir: process.cwd(),\n  type: 'error' // 'error' | 'warning' | 'info'\n}));\n```\n\n**Features:**\n- **OSC 8 Hyperlinks**: File paths are clickable in modern terminals (VS Code, iTerm2, etc.). Ctrl+Click (or Cmd+Click) opens the file at the correct line and column.\n- **Smart Line Overflow**: Long code lines automatically truncate with ellipsis while keeping the error range visible. Supports ellipsis at start, end, or both sides.\n- **Error Range Highlighting**: The error range (startColumn to endColumn) is highlighted with a brighter color for easy identification.\n- **Context Lines**: Show lines before and after the error for better context (slightly dimmed for visual hierarchy).\n- **Message Wrapping**: Long error messages wrap across multiple lines while preserving ANSI styling and color codes.\n- **Terminal Theme Adaptation**: Line numbers and colors adapt to dark/light terminal themes automatically.\n- **Curved Underlines**: Visual indicators with curved edges (┖─┚) point to the exact error location, with optional T-bar for short messages.\n- **Responsive Layout**: Automatically adjusts to terminal width, truncating paths and code as needed.\n\n### Spinner\n\nAnimated spinners for loading states. Includes built-in styles or use custom frames.\n\n![Spinner Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/spinner.gif)\n\n```typescript\nimport { Spinner } from 'linecraft';\n\n// Built-in styles\nr.set(Spinner({\n  style: 'classic-dots', // or 'bouncing-bar'\n  color: 'green',\n  interval: 100\n}));\n\n// Custom frames\nr.set(Spinner({\n  frames: ['⠋', '⠙', '⠹', '⠸'],\n  color: 'yellow',\n  interval: 80\n}));\n```\n\n**Options:**\n- `style?: 'classic-dots' | 'bouncing-bar'` - Built-in animation style\n- `frames?: string[]` - Custom frames (overrides style if provided)\n- `interval?: number` - Milliseconds between frames (default: 80)\n- `color?: Color` - Spinner color\n- `autoStart?: boolean` - Start automatically (default: true)\n\nSpinners automatically stop when components are replaced or the region is destroyed.\n\n### ProgressBar\n\nProgress bars with customizable colors and styling.\n\n![ProgressBar Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/progressbar.gif)\n\n```typescript\nimport { progressBar } from 'linecraft';\n\nr.set(progressBar({\n  current: 75,\n  total: 100,\n  barColor: 'green',\n  bracketColor: 'brightBlack',\n  percentColor: 'yellow'\n}));\n```\n\n**Options:**\n- `current: number` - Current progress value\n- `total: number` - Total/max value\n- `barColor?: Color` - Color of the filled bar\n- `bracketColor?: Color` - Color of brackets\n- `percentColor?: Color` - Color of percentage text\n\n### Segments\n\nCreate segmented displays (like oh-my-zsh style prompts).\n\n![Segments Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/segments.gif)\n\n```typescript\nimport { Segments } from 'linecraft';\n\nr.set(Segments({\n  segments: [\n    { content: 'user@host', color: 'brightGreen', backgroundColor: 'blue' },\n    { content: '~/projects', color: 'white', backgroundColor: 'brightBlue' },\n    { content: 'main', color: 'black', backgroundColor: 'white' }\n  ],\n  borderStyle: 'cap' // 'cap' | 'brace' | 'round' | 'square' | 'none'\n}));\n```\n\n**Options:**\n- `segments: Array<{ content: string, color?: Color, backgroundColor?: Color, borderStyle?: BorderStyle }>` - Array of segments\n- `borderStyle?: BorderStyle` - Style for segment borders ('cap', 'brace', 'round', 'square', 'none')\n\n### Grid\n\nCreate responsive grid layouts. Children automatically wrap to new rows when they exceed the number of explicit columns.\n\n![Grid Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/grid.gif)\n\n```typescript\nimport { Grid } from 'linecraft';\n\n// Basic grid\nr.set(Grid({ template: [20, '1*'], columnGap: 2 },\n  Styled({ color: 'cyan' }, 'Label:'),\n  Styled({ color: 'yellow' }, 'Value')\n));\n\n// Multiple rows (children wrap automatically)\nr.set(Grid({ \n  columns: [20, 20],  // 2 columns per row\n  autoColumns: 20,     // Size for extra columns\n  columnGap: 2,\n  rowGap: 1\n},\n  Styled({ color: 'cyan' }, 'Left'),\n  Styled({ color: 'cyan' }, 'Right'),\n  fill({ char: '─', color: 'brightCyan' }),\n  fill({ char: '─', color: 'brightCyan' })\n));\n```\n\n**Options:**\n- `columns?: GridTemplateEntry[]` - Explicit column definitions (like CSS `grid-template-columns`)\n- `autoColumns?: GridTemplateEntry` - Size for implicitly created columns (like CSS `grid-auto-columns`)\n- `columnGap?: number` - Spaces between columns (default: 0)\n- `rowGap?: number` - Spaces between rows (default: 0)\n- `spaceBetween?: FillChar | FillChar[]` - Characters to draw between columns\n- `justify?: 'start' | 'end' | 'center' | 'space-between'` - Justify content\n\n**Template entries:**\n- Fixed width: `20`, `30`\n- Flex units: `'1*'`, `'2*'` (like CSS `1fr`, `2fr`)\n- Minmax: `{ min: 40, width: '2*' }`\n- Auto: `'auto'` (content-based sizing)\n\n### Fill\n\nFill available space with a character. Typically used within grids.\n\n![Fill Example](https://raw.githubusercontent.com/matthew-dean/linecraft/main/docs/examples/fill.gif)\n\n```typescript\nimport { fill } from 'linecraft';\n\nr.set(fill({ char: '─', color: 'brightBlack' }));\n```\n\n## Utilities\n\n### Prompt\n\nWait for user input before continuing.\n\n```typescript\nimport { prompt } from 'linecraft';\n\nawait prompt(r, {\n  message: 'continue',\n  key: 'spacebar', // 'spacebar' | 'enter' | 'q' | 'any'\n  color: 'brightBlack'\n});\n```\n\n## Colors\n\nAvailable colors:\n- `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`\n- `brightBlack`, `brightRed`, `brightGreen`, `brightYellow`, `brightBlue`, `brightMagenta`, `brightCyan`, `brightWhite`\n\n## Examples\n\nCheck out the `examples/` directory:\n\n- `progress.ts` - Progress bars (basic and multi-lane)\n- `spinner.ts` - Animated spinners\n- `code-debug.ts` - Code error display\n- `grid-all-features.ts` - Grid layout examples\n- `segments.ts` - Segmented displays\n\nRun examples with:\n```bash\npnpm example <name>\n```\n\n## API Reference\n\n### Region Methods\n\n- `set(content)` - Replace all content\n- `add(content)` - Append content, returns `ComponentReference` or `SectionReference`\n- `destroy(clearFirst?)` - Clean up and restore terminal\n- `width` - Current region width (read-only)\n- `height` - Current region height (read-only)\n\n### ComponentReference\n\n- `delete()` - Remove the component from the region\n\n### SectionReference\n\n- `update(content)` - Update the section content\n- `delete()` - Remove the section from the region\n\n## Contributing\n\nContributions welcome! Please open an issue or PR.\n\n**Creating example recordings?** See [docs/creating-recordings.md](docs/creating-recordings.md) for a guide on using vhs to create animated GIFs.\n\n## License\n\nThis project is licensed under the **Fair Labor License (FLL) v1.2**.\n\n- If you are an individual with a net worth under **$5M USD**, or  \n- Your organization is **Fair Labor Compliant** (your CEO or highest-paid executive makes no more than **15×** your median employee's total annual compensation),\n\nthen you may use this software **for free**, subject to the terms of the license.\n\nIf you do **not** meet these conditions and use this software in production or for business value, you must obtain a **paid license**, for example via [fllicense.org](https://fllicense.org).\n\nYou may freely evaluate and test this software for up to **90 days** before deciding.\n\nSee the full license text in [`LICENSE`](./LICENSE).\n","publish_time":1768159768029,"_cnpm_publish_time":1768159768029,"dist-tags":{"latest":"0.5.8","legacy":"0.2.8"}}