### One-Line Setup with DraftLog's into() Method Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Shows a concise, one-line setup for DraftLog using the `into` method. It also demonstrates how to integrate line listeners for manual input handling, such as processing user input from stdin. Remember to pause stdin or exit the process when using line listeners. ```javascript // Simple one-liner setup require('draftlog').into(console) // With line listener for manual input (e.g., user pressing Enter) require('draftlog').into(console).addLineListener(process.stdin) // Create a draft and update it var elapsed = 0 var draft = console.draft('Timer: 0 seconds') setInterval(() => { elapsed++ draft('Timer:', elapsed, 'seconds') }, 1000) // Note: When using addLineListener, call process.stdin.pause() // or process.exit() to allow the program to exit ``` -------------------------------- ### Basic Setup and Usage of DraftLog Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Demonstrates the basic setup of DraftLog by injecting the `draft` method into the console object. It shows how to create an initial log message and update it multiple times. Production mode is also illustrated, where draft functionality is mocked. ```javascript const DraftLog = require('draftlog') // Development mode - enables draft functionality DraftLog(console) // Production mode - draft becomes an alias for console.log DraftLog(console, true) // Create an updatable log var update = console.draft('Initial message') // Update the same line multiple times setTimeout(() => update('Updated message after 1 second'), 1000) setTimeout(() => update('Final message after 2 seconds'), 2000) // Output: Only one line appears, updating in place ``` -------------------------------- ### Installing DraftLog Source: https://github.com/ivanseidel/node-draftlog/blob/master/README.md The command to install the DraftLog package via npm. ```bash $ npm install draftlog ``` -------------------------------- ### Install DraftLog using npm Source: https://context7.com/ivanseidel/node-draftlog/llms.txt This command installs the DraftLog library using npm. It is a prerequisite for using DraftLog in your Node.js project. ```bash npm install draftlog ``` -------------------------------- ### Initialization and Setup Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Methods to initialize DraftLog on the console object, including development and production modes. ```APIDOC ## DraftLog(console) ### Description Initializes DraftLog by injecting a `draft` method into the console object. Pass `true` as the second parameter to enable production mode, which mocks the functionality to behave like standard `console.log`. ### Method Initialization ### Parameters #### Arguments - **console** (Object) - Required - The global console object to extend. - **production** (Boolean) - Optional - If true, disables draft functionality for optimized performance. ### Request Example ```javascript const DraftLog = require('draftlog'); DraftLog(console); // Development mode DraftLog(console, true); // Production mode ``` ``` -------------------------------- ### Creating Dynamic CLI Elements Source: https://github.com/ivanseidel/node-draftlog/blob/master/README.md Examples showing how to use DraftLog for real-time updates like clocks, async status tracking, and progress bars. ```javascript // Clock example var draft = console.draft() var elapsed = 1 setInterval( () => { draft('Elapsed', elapsed++, 'seconds') }, 1000) // Progress bar example function ProgressBar(progress) { var units = Math.round(progress / 2) return '[' + '='.repeat(units) + ' '.repeat(50 - units) + '] ' + progress + '%' } var barLine = console.draft('Starting download...') barLine(ProgressBar(56)) ``` -------------------------------- ### Scrolling Text Banner Example Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Demonstrates how to create animated text effects by manipulating string arrays and updating the draft line at regular intervals. ```APIDOC ## Scrolling Text Banner ### Description Create animated text effects by manipulating string arrays and updating the draft line at regular intervals. ### Method `setInterval` (used in conjunction with `console.draft()`) ### Endpoint N/A (This is a code example, not an API endpoint) ### Parameters - None directly for the banner creation, relies on `DraftLog` setup and `setInterval`. ### Request Example ```javascript const DraftLog = require('draftlog') DraftLog(console).addLineListener(process.stdin) var text = ' Welcome to DraftLog! Create amazing terminal UIs! ' var chars = text.split('') console.log('\n' + '*'.repeat(text.length)) var banner = console.draft(text) console.log('*'.repeat(text.length) + '\n') // Rotate text for scrolling effect setInterval(() => { chars.push(chars.shift()) // Move first char to end banner(chars.join('')) }, 100) ``` ### Response #### Success Response (200) - The response is the animated text displayed in the terminal. #### Response Example ``` ******************************************************** Welcome to DraftLog! Create amazing terminal UIs! ******************************************************** ``` (This output animates by scrolling) ``` -------------------------------- ### into(console) Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Chainable initialization method for DraftLog. ```APIDOC ## into(console) ### Description Provides a chainable one-liner for initialization that returns the LineCountStream, allowing for immediate attachment of listeners for manual input handling. ### Method Static Method ### Parameters #### Arguments - **console** (Object) - Required - The console object to extend. ### Request Example ```javascript require('draftlog').into(console).addLineListener(process.stdin); ``` ``` -------------------------------- ### Configure DraftLog Global Defaults Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Demonstrates how to modify global configuration settings like maximum line tracking and off-screen rewrite behavior before initializing the library. ```javascript const DraftLog = require('draftlog') DraftLog.defaults.maximumLinesUp = 50 DraftLog.defaults.canReWrite = false DraftLog(console) var draft = console.draft('This line may become invalid if scrolled off') for (var i = 0; i < 60; i++) { console.log('Log line', i) } draft('Attempted update') ``` -------------------------------- ### Create Animated Console Loading Spinner Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Demonstrates how to create a CLI loading indicator by cycling through an array of characters and updating a single draft line at a fixed interval. ```javascript require('draftlog').into(console) var frame = 0 var frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] function Spinner(text) { frame = (frame + 1) % frames.length return frames[frame] + ' ' + text } console.log('Starting task...') var loading = console.draft() var interval = setInterval(() => { loading(Spinner('Processing data...')) }, 80) setTimeout(() => { clearInterval(interval) loading('✓ Processing complete!') process.exit(0) }, 3000) ``` -------------------------------- ### Initializing DraftLog Source: https://github.com/ivanseidel/node-draftlog/blob/master/README.md How to attach DraftLog to the global console object to enable the draft method. ```javascript const DraftLog = require('draftlog') DraftLog(console) // Or, in a single line: require('draftlog').into(console) // Account for manual line breaks with: require('draftlog').into(console).addLineListener(process.stdin) ``` -------------------------------- ### Building a Progress Bar with DraftLog Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Illustrates how to build a dynamic progress bar in the terminal using DraftLog. It defines a `ProgressBar` function to render the bar based on a percentage and simulates a download process, updating the progress bar line in place until completion. ```javascript const chalk = require('chalk') // optional, for colors require('draftlog').into(console) // Progress bar renderer (0-100) function ProgressBar(progress) { progress = Math.min(100, Math.max(0, progress)) var units = Math.round(progress / 2) var bar = '='.repeat(units) + ' '.repeat(50 - units) return '[' + bar + '] ' + progress + '%' } // Simulate a download var barLine = console.draft('Starting download...') var progress = 0 var interval = setInterval(() => { progress += Math.round(Math.random() * 10) if (progress >= 100) { barLine(ProgressBar(100), '✓ Download complete!') clearInterval(interval) } else { barLine(ProgressBar(progress)) } }, 100) // Output: [========================== ] 52% // Updates in place until: [==================================================] 100% ✓ Download complete! ``` -------------------------------- ### Creating and Updating Draft Logs Source: https://github.com/ivanseidel/node-draftlog/blob/master/README.md Demonstrates how to create an updatable log line using console.draft and updating it later. ```javascript var update = console.draft('Hi, my name is') console.log('Something else') update('Hi, my name is Ivan!') ``` -------------------------------- ### Direct LogDraft Class Instantiation Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Shows how to instantiate the LogDraft class directly for advanced use cases requiring manual line management and state validation. ```javascript const DraftLog = require('draftlog') const LogDraft = DraftLog.LogDraft DraftLog(console) // Create LogDraft directly (normally done by console.draft()) var logDraft = new LogDraft(console, 'log') // Write initial content logDraft.write('Initial content') // Check if draft is still valid (not scrolled off-screen) console.log('Is valid:', logDraft.valid) // true // Get lines between draft and current cursor console.log('Lines up:', logDraft.linesUp()) // 1 // Update the draft (same as calling the update function) logDraft.update('Updated content') // Check if off-screen console.log('Is off-screen:', logDraft.isOffScreen()) // false // Manually save current line position logDraft.saveLine() // Reset reference point ``` -------------------------------- ### Creating and Updating Log Lines with console.draft() Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Explains how to use the `console.draft()` method to create log lines that can be updated in place. It covers creating drafts with initial content, empty drafts as placeholders, and simulating asynchronous processes with status updates. Other `console.log` messages are shown to appear below without affecting the draft. ```javascript require('draftlog').into(console) // Create draft with initial content var statusUpdate = console.draft('[Status] Initializing...') // Create empty draft (placeholder) var progressUpdate = console.draft() // Simulate async process with status updates function runProcess() { statusUpdate('[Status] Loading configuration...') setTimeout(() => { statusUpdate('[Status] Connecting to database...') }, 500) setTimeout(() => { statusUpdate('[Status] Processing data...') }, 1000) setTimeout(() => { statusUpdate('[Status] Complete!') process.exit(0) }, 1500) } // Other logs appear below without affecting the draft console.log('Process started') runProcess() console.log('Waiting for completion...') // Output: // [Status] Complete! <- updates in place // Process started // Waiting for completion... ``` -------------------------------- ### Creating Animated Scrolling Text Banners Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Demonstrates how to create animated text effects in the terminal by manipulating character arrays and updating a draft log at a fixed interval. ```javascript const DraftLog = require('draftlog') DraftLog(console).addLineListener(process.stdin) var text = ' Welcome to DraftLog! Create amazing terminal UIs! ' var chars = text.split('') console.log('\n' + '*'.repeat(text.length)) var banner = console.draft(text) console.log('*'.repeat(text.length) + '\n') // Rotate text for scrolling effect setInterval(() => { chars.push(chars.shift()) // Move first char to end banner(chars.join('')) }, 100) ``` -------------------------------- ### console.draft() Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Creates an updatable log line in the terminal. ```APIDOC ## console.draft() ### Description Creates a new log line that can be updated in place. It accepts the same arguments as `console.log` and returns an update function that overwrites the original line when called. ### Method Function Call ### Parameters #### Arguments - **...args** (Any) - Optional - Initial content to display on the draft line. ### Response - **updateFunction** (Function) - Returns a function that accepts arguments to update the specific log line content. ### Request Example ```javascript var update = console.draft('Initial message'); update('Updated message'); ``` ``` -------------------------------- ### Manage Multiple Concurrent Progress Bars Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Shows how to track multiple asynchronous tasks simultaneously by creating independent draft lines for each progress bar. ```javascript require('draftlog').into(console) function ProgressBar(name, progress) { var units = Math.round(progress / 2) var bar = '█'.repeat(units) + '░'.repeat(50 - units) return name.padEnd(12) + ' [' + bar + '] ' + String(progress).padStart(3) + '%' } console.log('\nDownloading files:\n') var downloads = [ { name: 'file1.zip', progress: 0, update: console.draft('file1.zip [starting...]') }, { name: 'file2.zip', progress: 0, update: console.draft('file2.zip [starting...]') }, { name: 'file3.zip', progress: 0, update: console.draft('file3.zip [starting...]') }, ] console.log('') downloads.forEach(dl => { var interval = setInterval(() => { dl.progress += Math.round(Math.random() * 8) if (dl.progress >= 100) { dl.progress = 100 dl.update(ProgressBar(dl.name, 100) + ' ✓') clearInterval(interval) } else { dl.update(ProgressBar(dl.name, dl.progress)) } }, 50 + Math.random() * 100) }) ``` -------------------------------- ### LogDraft Class - Direct Instantiation Source: https://context7.com/ivanseidel/node-draftlog/llms.txt The LogDraft class can be instantiated directly for fine-grained control over draft log behavior, including manual line saving and validity checking. ```APIDOC ## LogDraft Class - Direct Instantiation ### Description The LogDraft class can be instantiated directly for fine-grained control over draft log behavior, including manual line saving and validity checking. ### Methods - `new LogDraft(console, type)`: Constructor for LogDraft. - `write(content)`: Writes initial content to the draft. - `update(content)`: Updates the draft content. - `saveLine()`: Manually saves the current line position. - `linesUp()`: Returns the number of lines between the draft and the current cursor. - `isOffScreen()`: Checks if the draft is off-screen. ### Properties - `valid` (boolean): Indicates if the draft is still valid (not scrolled off-screen). ### Parameters - `console` (object): The console object (e.g., `console`). - `type` (string): The type of log, typically 'log'. - `content` (string): The text content to write or update. ### Request Example ```javascript const DraftLog = require('draftlog') const LogDraft = DraftLog.LogDraft DraftLog(console) // Create LogDraft directly (normally done by console.draft()) var logDraft = new LogDraft(console, 'log') // Write initial content logDraft.write('Initial content') // Check if draft is still valid (not scrolled off-screen) console.log('Is valid:', logDraft.valid) // true // Get lines between draft and current cursor console.log('Lines up:', logDraft.linesUp()) // 1 // Update the draft (same as calling the update function) logDraft.update('Updated content') // Check if off-screen console.log('Is off-screen:', logDraft.isOffScreen()) // false // Manually save current line position logDraft.saveLine() // Reset reference point // The update function returned by console.draft() is: // logDraft.update.bind(logDraft) ``` ### Response #### Success Response (200) - The primary response is the manipulation of terminal output. Methods like `valid`, `linesUp`, and `isOffScreen` return boolean or number values. #### Response Example ```json { "Is valid": true, "Lines up": 1, "Is off-screen": false } ``` ``` -------------------------------- ### Disable DraftLog Initialization Source: https://github.com/ivanseidel/node-draftlog/blob/master/README.md Shows how to disable DraftLog during initialization by passing a boolean flag. This is recommended for production environments to avoid unnecessary overhead. ```javascript // Disable Initialization (true = production; false = development) DraftLog(console, true) // Or, with one line require-init: require('draftlog').into(console, true) ``` -------------------------------- ### CSIHelper - ANSI Escape Code Utilities Source: https://context7.com/ivanseidel/node-draftlog/llms.txt The CSIHelper module provides low-level ANSI escape sequence functions for cursor manipulation. These are used internally but can be accessed for advanced terminal control. ```APIDOC ## CSIHelper - ANSI Escape Code Utilities ### Description The CSIHelper module provides low-level ANSI escape sequence functions for cursor manipulation. These are used internally but can be accessed for advanced terminal control. ### Methods - `CSIHelper.ESC`: Access the escape character. - `CSIHelper.up(n)`: Move cursor up `n` lines. - `CSIHelper.down(n)`: Move cursor down `n` lines. - `CSIHelper.save()`: Save cursor position. - `CSIHelper.restore()`: Restore cursor position. - `CSIHelper.clearLine()`: Clear the current line. ### Parameters - `n` (number): The number of lines for cursor movement. ### Request Example ```javascript const DraftLog = require('draftlog') const CSIHelper = DraftLog.CSIHelper // Access escape character console.log('ESC character:', JSON.stringify(CSIHelper.ESC)) // '\u001b' // Cursor movement sequences console.log('Move up 5 lines:', JSON.stringify(CSIHelper.up(5))) // '\u001b[5A' console.log('Move down 3 lines:', JSON.stringify(CSIHelper.down(3))) // '\u001b[3B' // Cursor save/restore console.log('Save cursor:', JSON.stringify(CSIHelper.save())) // '\u001b7' console.log('Restore cursor:', JSON.stringify(CSIHelper.restore())) // '\u001b8' // Clear current line console.log('Clear line:', JSON.stringify(CSIHelper.clearLine())) // '\u001b[2K\u001b[1G' // Manual cursor control example DraftLog(console) console.log('Line 1') console.log('Line 2') console.log('Line 3') // Move up 2 lines, clear, write, restore process.stdout.write(CSIHelper.save()) process.stdout.write(CSIHelper.up(2)) process.stdout.write(CSIHelper.clearLine()) process.stdout.write('Modified Line 1') process.stdout.write(CSIHelper.restore()) ``` ### Response #### Success Response (200) - The response consists of ANSI escape codes written to `process.stdout` to control the terminal cursor and display. #### Response Example (Output will be visible in the terminal as cursor movements and text modifications, not a direct JSON response.) ``` -------------------------------- ### Manipulating ANSI Sequences with CSIHelper Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Provides access to low-level ANSI escape sequences for precise cursor control, including moving, saving, restoring, and clearing lines in the terminal. ```javascript const DraftLog = require('draftlog') const CSIHelper = DraftLog.CSIHelper // Access escape character console.log('ESC character:', JSON.stringify(CSIHelper.ESC)) // '\u001b' // Cursor movement sequences console.log('Move up 5 lines:', JSON.stringify(CSIHelper.up(5))) // '\u001b[5A' console.log('Move down 3 lines:', JSON.stringify(CSIHelper.down(3))) // '\u001b[3B' // Cursor save/restore console.log('Save cursor:', JSON.stringify(CSIHelper.save())) // '\u001b7' console.log('Restore cursor:', JSON.stringify(CSIHelper.restore())) // '\u001b8' // Clear current line console.log('Clear line:', JSON.stringify(CSIHelper.clearLine())) // '\u001b[2K\u001b[1G' // Manual cursor control example DraftLog(console) console.log('Line 1') console.log('Line 2') console.log('Line 3') // Move up 2 lines, clear, write, restore process.stdout.write(CSIHelper.save()) process.stdout.write(CSIHelper.up(2)) process.stdout.write(CSIHelper.clearLine()) process.stdout.write('Modified Line 1') process.stdout.write(CSIHelper.restore()) ``` -------------------------------- ### Handling User Input with LineCountStream Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Registers a line listener to ensure terminal logs account for manual line breaks caused by user input. This is critical for maintaining correct log positioning when reading from stdin. ```javascript const DraftLog = require('draftlog') // Method 1: Chain from into() var lineStream = require('draftlog').into(console) lineStream.addLineListener(process.stdin) // Method 2: Access from initialization var stream = DraftLog(console) stream.addLineListener(process.stdin) // Now draft logs correctly account for user pressing Enter var status = console.draft('Type something and press Enter...') process.stdin.on('data', (data) => { status('You typed: ' + data.toString().trim()) }) // Important: Pause stdin when done to allow process to exit setTimeout(() => { process.stdin.pause() status('Done!') }, 10000) ``` -------------------------------- ### Implement Queue Worker Status Display Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Utilizes multiple draft lines to represent the state of individual workers in a pool, providing a real-time dashboard for task execution. ```javascript require('draftlog').into(console) function QueueWorker(name) { this.name = name this.status = console.draft() this.working = false this.setIdle() } QueueWorker.prototype.setIdle = function() { this.working = false this.status('[' + this.name + '] idle') } QueueWorker.prototype.run = function(taskName) { var self = this self.working = true self.status('[' + self.name + '] executing: ' + taskName) setTimeout(() => { self.status('[' + self.name + '] completed: ' + taskName) setTimeout(() => self.setIdle(), 200) }, 200 + Math.random() * 500) } console.log('\n> Worker Pool Status:\n') var workers = [ new QueueWorker('worker-1'), new QueueWorker('worker-2'), new QueueWorker('worker-3'), ] console.log('') var tasks = ['task-a', 'task-b', 'task-c', 'task-d', 'task-e'] var taskIndex = 0 var interval = setInterval(() => { if (taskIndex >= tasks.length) { clearInterval(interval) return } var idle = workers.find(w => !w.working) if (idle) { idle.run(tasks[taskIndex++]) } }, 100) ``` -------------------------------- ### LineCountStream.addLineListener(stream) Source: https://context7.com/ivanseidel/node-draftlog/llms.txt Adds a line listener to account for manual line breaks from user input (e.g., pressing Enter). This is essential when your application accepts stdin input while using draft logs. ```APIDOC ## LineCountStream.addLineListener(stream) ### Description Add a line listener to account for manual line breaks from user input (like pressing Enter). This is essential when your application accepts stdin input while using draft logs. ### Method `addLineListener` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript const DraftLog = require('draftlog') // Method 1: Chain from into() var lineStream = require('draftlog').into(console) lineStream.addLineListener(process.stdin) // Method 2: Access from initialization var stream = DraftLog(console) stream.addLineListener(process.stdin) // Now draft logs correctly account for user pressing Enter var status = console.draft('Type something and press Enter...') process.stdin.on('data', (data) => { status('You typed: ' + data.toString().trim()) }) // Important: Pause stdin when done to allow process to exit setTimeout(() => { process.stdin.pause() status('Done!') }, 10000) ``` ### Response #### Success Response (200) - No specific response body defined, as this method modifies stream behavior. #### Response Example N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.