slice-ansi 0.1.0 → 1.0.0

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 (2) hide show
  1. package/index.js +15 -4
  2. package/package.json +5 -2
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ const isFullwidthCodePoint = require('is-fullwidth-code-point');
2
3
 
3
4
  const ESCAPES = [
4
5
  '\u001B',
@@ -6,6 +7,7 @@ const ESCAPES = [
6
7
  ];
7
8
 
8
9
  const END_CODE = 39;
10
+ const ASTRAL_REGEX = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
9
11
 
10
12
  const ESCAPE_CODES = new Map([
11
13
  [0, 0],
@@ -38,15 +40,20 @@ const ESCAPE_CODES = new Map([
38
40
  const wrapAnsi = code => `${ESCAPES[0]}[${code}m`;
39
41
 
40
42
  module.exports = (str, begin, end) => {
41
- end = end || str.length;
43
+ const arr = Array.from(str.normalize());
44
+
45
+ end = typeof end === 'number' ? end : arr.length;
46
+
42
47
  let insideEscape = false;
43
48
  let escapeCode;
44
49
  let visible = 0;
45
50
  let output = '';
46
51
 
47
- for (let i = 0; i < str.length; i++) {
52
+ for (const item of arr.entries()) {
53
+ const i = item[0];
54
+ const x = item[1];
55
+
48
56
  let leftEscape = false;
49
- const x = str[i];
50
57
 
51
58
  if (ESCAPES.indexOf(x) !== -1) {
52
59
  insideEscape = true;
@@ -61,9 +68,13 @@ module.exports = (str, begin, end) => {
61
68
  ++visible;
62
69
  }
63
70
 
71
+ if (!ASTRAL_REGEX.test(x) && isFullwidthCodePoint(x.codePointAt())) {
72
+ ++visible;
73
+ }
74
+
64
75
  if (visible > begin && visible <= end) {
65
76
  output += x;
66
- } else if (visible === begin && escapeCode !== undefined && escapeCode !== END_CODE) {
77
+ } else if (visible === begin && !insideEscape && escapeCode !== undefined && escapeCode !== END_CODE) {
67
78
  output += wrapAnsi(escapeCode);
68
79
  } else if (visible >= end) {
69
80
  if (escapeCode !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slice-ansi",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "Slice a string with ANSI escape codes",
5
5
  "license": "MIT",
6
6
  "repository": "chalk/slice-ansi",
@@ -40,9 +40,12 @@
40
40
  "command-line",
41
41
  "text"
42
42
  ],
43
+ "dependencies": {
44
+ "is-fullwidth-code-point": "^2.0.0"
45
+ },
43
46
  "devDependencies": {
44
47
  "ava": "*",
45
- "chalk": "^1.1.1",
48
+ "chalk": "^2.0.1",
46
49
  "random-item": "^1.0.0",
47
50
  "strip-ansi": "^4.0.0",
48
51
  "xo": "*"