cli-truncate 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +17 -3
  2. package/package.json +1 -1
  3. package/readme.md +18 -1
package/index.js CHANGED
@@ -2,7 +2,10 @@
2
2
  var sliceAnsi = require('slice-ansi');
3
3
  var stringWidth = require('string-width');
4
4
 
5
- module.exports = function (input, columns) {
5
+ module.exports = function (input, columns, options) {
6
+ options = options || {};
7
+
8
+ var position = options.position || 'end';
6
9
  var ellipsis = '…';
7
10
 
8
11
  if (typeof input !== 'string') {
@@ -21,9 +24,20 @@ module.exports = function (input, columns) {
21
24
  return ellipsis;
22
25
  }
23
26
 
24
- if (stringWidth(input) <= columns) {
27
+ var length = stringWidth(input);
28
+
29
+ if (length <= columns) {
25
30
  return input;
26
31
  }
27
32
 
28
- return sliceAnsi(input, 0, columns - 1) + ellipsis;
33
+ if (position === 'start') {
34
+ return ellipsis + sliceAnsi(input, length - columns + 1, length);
35
+ } else if (position === 'middle') {
36
+ var half = Math.floor(columns / 2);
37
+ return sliceAnsi(input, 0, half) + ellipsis + sliceAnsi(input, length - (columns - half) + 1, length);
38
+ } else if (position === 'end') {
39
+ return sliceAnsi(input, 0, columns - 1) + ellipsis;
40
+ }
41
+
42
+ throw new Error('Expected `options.position` to be either `start`, `middle` or `end`, got ' + position);
29
43
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cli-truncate",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Truncate a string to a specific width in the terminal",
5
5
  "license": "MIT",
6
6
  "repository": "sindresorhus/cli-truncate",
package/readme.md CHANGED
@@ -20,6 +20,13 @@ const cliTruncate = require('cli-truncate');
20
20
  cliTruncate('unicorn', 4);
21
21
  //=> 'uni…'
22
22
 
23
+ // truncate at different positions
24
+ cliTruncate('unicorn', 4, {position: 'start'});
25
+ //=> '…orn'
26
+
27
+ cliTruncate('unicorn', 4, {position: 'middle'});
28
+ //=> 'un…n'
29
+
23
30
  cliTruncate('\u001b[31municorn\u001b[39m', 4);
24
31
  //=> '\u001b[31muni\u001b[39m…'
25
32
 
@@ -32,7 +39,7 @@ cliTruncate(paragraph, process.stdout.columns));
32
39
 
33
40
  ## API
34
41
 
35
- ### cliTruncate(input, columns)
42
+ ### cliTruncate(input, columns, [options])
36
43
 
37
44
  #### input
38
45
 
@@ -46,6 +53,16 @@ Type: `number`
46
53
 
47
54
  Columns to occupy in the terminal.
48
55
 
56
+ #### options
57
+
58
+ ##### position
59
+
60
+ Type: `string`<br>
61
+ Default: `'end'`<br>
62
+ Values: `'start'`, `'middle'`, `'end'`
63
+
64
+ Position to truncate the string.
65
+
49
66
 
50
67
  ## Related
51
68