Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
Co-authored-by: Qix <[email protected]>
  • Loading branch information
sindresorhus and Qix- committed Apr 22, 2021
0 parents commit c0ddf60
Show file tree
Hide file tree
Showing 9 changed files with 432 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
133 changes: 133 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;

const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);

function unescape(c) {
const u = c[0] === 'u';
const bracket = c[1] === '{';

if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(Number.parseInt(c.slice(1), 16));
}

if (u && bracket) {
return String.fromCodePoint(Number.parseInt(c.slice(2, -1), 16));
}

return ESCAPES.get(c) || c;
}

function parseArguments(name, arguments_) {
const results = [];
const chunks = arguments_.trim().split(/\s*,\s*/g);
let matches;

for (const chunk of chunks) {
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}

return results;
}

function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;

const results = [];
let matches;

while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];

if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name, ...args]);
} else {
results.push([name]);
}
}

return results;
}

function buildStyle(chalk, styles) {
const enabled = {};

for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}

let current = chalk;
for (const [styleName, styles] of Object.entries(enabled)) {
if (!Array.isArray(styles)) {
continue;
}

if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}

current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
}

return current;
}

export default function template(chalk, temporary) {
const styles = [];
const chunks = [];
let chunk = [];

// eslint-disable-next-line max-params
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const string = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}

chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(character);
}
});

chunks.push(chunk.join(''));

if (styles.length > 0) {
const errorMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errorMessage);
}

return chunks.join('');
}
10 changes: 10 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
MIT License

Copyright (c) Josh Junon
Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
48 changes: 48 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "chalk-template",
"version": "0.0.0",
"description": "TODO",
"license": "MIT",
"repository": "chalk/chalk-template",
"funding": "https://github.com/chalk/chalk-template?sponsor=1",
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"chalk",
"template",
"templates",
"templating",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"ava": "^3.15.0",
"xo": "^0.38.2"
}
}
31 changes: 31 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# chalk-template

> TODO
## Install

```
$ npm install chalk-template
```

## Usage

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

//
```

## API

### chalkTemplate()

## Related

- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
- [chalk-cli](https://github.com/chalk/chalk-cli) - Style text from the terminal

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
Loading

0 comments on commit c0ddf60

Please sign in to comment.