Giter Site home page Giter Site logo

chalk-template's Introduction

chalk-template

Terminal string styling with tagged template literals

Install

npm install chalk-template

Usage

For printing to standard output (stdout):

import chalkTemplate from 'chalk-template';
import chalk from 'chalk';

console.log(chalkTemplate`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);

console.log(chalk.red.bgBlack(chalkTemplate`2 + 3 = {bold ${2 + 3}}`));

const miles = 18;
const calculateFeet = miles => miles * 5280;

console.log(chalkTemplate`
	There are {bold 5280 feet} in a mile.
	In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);

console.log(chalkTemplate`
	There are also {#FF0000 shorthand hex styles} for
	both the {#ABCDEF foreground}, {#:123456 background},
	or {#ABCDEF:123456 both}.
`);

For printing to standard error (stderr):

import {chalkTemplateStderr} from 'chalk-template';

console.error(chalkTemplateStderr`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);

API

Blocks are delimited by an opening curly brace ({), a style, some content, and a closing curly brace (}).

Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:

import chalk from 'chalk';
import chalkTemplate from 'chalk-template';

console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalkTemplate`{bold.rgb(10,100,200) Hello!}`);

Note that function styles (rgb(), etc.) may not contain spaces between parameters.

All interpolated values (chalkTemplate`${foo}`) are converted to strings via the .toString() method. All curly braces ({ and }) in interpolated value strings are escaped.

Template function

This function can be useful if you need to wrap the template function. However, prefer the default export whenever possible.

Note: It's up to you to properly escape the input.

import {template} from 'chalk-template';

console.log(template('Today is {red hot}'));
import {templateStderr} from 'chalk-template';

console.error(templateStderr('Today is {red hot}'));

Create template functions using a custom Chalk instance

The makeTemplate and makeTaggedTemplate functions are exported so functions can be created using a custom Chalk instance.

Note: When using a function created with makeTemplate, it's up to you to properly escape the input.

import {Chalk} from 'chalk'
import {makeTemplate, makeTaggedTemplate} from 'chalk-template';

const template = makeTemplate(new Chalk({level: 3}));
const chalkTemplate = makeTaggedTemplate(new Chalk({level: 3}));

console.log(template('Today is {red hot}'));
console.log(chalkTemplate`Today is {red hot}`);

Related

  • chalk - Terminal string styling done right
  • chalk-cli - Style text from the terminal

Maintainers

chalk-template's People

Contributors

billymoroney1 avatar fantua avatar georgetaveras1231 avatar lukekarrys avatar qix- avatar richienb avatar sindresorhus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chalk-template's Issues

chalk properties are still exposed

chalk-template provides a separate way to use chalk. The highlighting properties (e.g. chalk.red) are not intended to be used, but they are still available. They work, but break on ttys (see chalk/chalk#568).

Use raw length instead of escaped length when traversing string parts

Easy fix but I don't have time for it at the moment. Just need to remember to do it at some point, or allow someone else to do it at some point.

for (let index = 1; index < firstString.length; index++) {

Instead of firstString.length it needs to be firstString.raw.length.

In fact, firstString is a misnomer here, dunno if I wrote that or if that got changed but it's not right. Template functions are weird and take an array as the first parameter, which itself has a property called .raw that is also an array (of the same arity) with the unescaped strings. The latter is what chalk-template uses.

Therefore, the entire thing can just be summarized as const rawStrings = strings.raw and use rawStrings for everything. Feel free to make that change.

Also change arguments_ back to args. If XO complains, ping me. There is no reason to use a _ postfix here to appease the builtin check. Alternatively, just call it values.

PR welcome, would be swiftly merged. Great beginner fix!

Is there anyway to pass a programmatically built string in?

import { Chalk } from "chalk";
const chalk = new Chalk({ level: 3 });
import chalkTemplate from "chalk-template";
import { convertToChalk } from "./convertToChalk.js";

const block = `A deep well of <c="#E56399">transylexic</c> <color value="silver">ambiphobia</color> pulses in and out of existence. What was in that potion?!`;
const templateString = convertToChalk(block);
console.log(chalkTemplate`${templateString}`); //this doesn't work

console.log(
  chalkTemplate`A deep well of {#E56399 transylexic} {#E56399 ambiphobia} pulses in and out of existence. What was in that potion?!`
); //this works fine, both strings are the same

So I am trying to write a little script to automatically output some strings with custom color tags to the terminal. So my convertToChalk function is correctly formatting the template string, but I'm having trouble getting chalkTemplate to interpret it. If I pass the string in 'raw' not as a variable, it works fine.

Any suggestions or insights would be greatly appreciated! I'm sure I"m just not understanding this.
Output looks like this

A deep well of {#E56399 transylexic} {#c0c0c0 ambiphobia} pulses in and out of existence. What was in that potion?!
A deep well of transylexic ambiphobia pulses in and out of existence. What was in that potion?!

note edited to remove swear word that was in my text string

Call template literal as normal function

Hello,

I try to parse a string (e.g. "hello {green world}") that contains the chalk template syntax.

My first try was to parse that in the template literal like this:

const myString = "hello {green world}";
console.log(chalk`${myString}`);

but without success. It returned the exact string I passed in without the green color format. So I debugged a little bit and found out that following works.

const d = ["hello {green world}"];
d.raw = [...d];
console.log(chalk(d));

But that looks very messy. Is there a better approche?

Use chalk-template with a custom chalk instance

Taking a quick look at the code, I don’t think this is possible currently.

It would be helpful if both makeTemplate and makeChalkTemplate were exported so I could do the following:

import {Chalk} from 'chalk'
import {makeTemplate, makeChalkTemplate} from 'chalk-template'

const chalk = new Chalk({ level: 0  })
const chalkTemplate = makeChalkTemplate(makeTemplate(chalk))

console.log(chalkTemplate`{red Hi!}`)

The code above should print Hi! with no coloring. This is a silly example, but I would like a way to write strings with predefined colors and also be able to pass those strings to a template function that would remove them. This would also be possible by using the regexes in the source to strip colors, but the way in my example seems easier to write.

Also for my use case, I would want to use both functions together, so a single export that wraps makeChalkTemplate(makeTemplate()) would be nice, but not required.

Allow special case shorthand syntax

I find myself using 256 colors quite a bit and having to do ansi256(xxx) in my template tags is less than ideal.

Since we don't support any numeric colors as methods, would it make sense to allow the shorthands for RGB + 256 such that the following works?

chalk`{#FF0000 foo}` // truecolor output
chalk`{127 foo}` // ansi256 output

Better documentation of escape characters to avoid: throw new Error('Found extraneous } in Chalk template literal');

Hi I hit this error while using template literals for a long string. I'm coming at this from a backend PHP and shell programming perspective where heredoc syntax (EOF, 'EOF') is often used when working with multiline text verbatim.

Anyway, the closest thing to that in Javascript is template literals using backticks. But since they're interpolated before Chalk receives them, it can be difficult to find the right escape sequence that provides proper formatting without triggering parsing errors. Also, some packages apply multiple levels of template parsing and character escaping, which makes it difficult to derive the exact incantation.

The project's readme.md barely mentions curly braces or escape characters. And so far even project issues don't reveal much:

chalk/chalk#498
chalk/chalk#349

I usually try every permutation of {{, \{, \\{, \{{, \\{{, etc. But sometimes things refuse to cooperate, and once programming becomes a random walk like that, it's better to reference a pre-built table of working examples. Which is why I'd like to see more open source projects adopt a third person view of themselves and understand that the smallest breadcrumbs can save their users many hours or sometimes even days of work. So I'm going to list some working examples here, and hopefully other people can add more permutations as they discover what works for other packages that use Chalk:

const chalk = require('chalk');

console.log(chalk`Hello, ${'world'}!`);
const chalk = require('chalk');

console.log(chalk`puppeteer.launch(\{ headless: false \}`);
const commandLineUsage = require('command-line-usage'); // uses chalk internally

const sections = [{
  content: `puppeteer.launch(\\{ headless: false \\}`
}];

console.log(commandLineUsage(sections));

Confusion with README

shouldn't last console.log's be also used with chalkTemplate instead of just chalk?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.