Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp
let truncationEnabled = false;
let truncationIndex = length;
let truncationLimit = Math.max ( 0, LIMIT - ELLIPSIS_WIDTH );
let unmatchedStart = 0;
let unmatchedEnd = 0;
let width = 0;
let widthExtra = 0;

Expand All @@ -64,9 +62,9 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp

/* UNMATCHED */

if ( ( unmatchedEnd > unmatchedStart ) || ( index >= length && index > indexPrev ) ) {
if ( index > indexPrev ) {

const unmatched = input.slice ( unmatchedStart, unmatchedEnd ) || input.slice ( indexPrev, index );
const unmatched = input.slice ( indexPrev, index );

lengthExtra = 0;

Expand All @@ -83,7 +81,7 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp
}

if ( ( width + widthExtra ) > truncationLimit ) {
truncationIndex = Math.min ( truncationIndex, Math.max ( unmatchedStart, indexPrev ) + lengthExtra );
truncationIndex = Math.min ( truncationIndex, indexPrev + lengthExtra );
}

if ( ( width + widthExtra ) > LIMIT ) {
Expand All @@ -96,7 +94,7 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp

}

unmatchedStart = unmatchedEnd = 0;
indexPrev = index;

}

Expand Down Expand Up @@ -129,8 +127,6 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp
}

width += widthExtra;
unmatchedStart = indexPrev;
unmatchedEnd = index;
index = indexPrev = BLOCK_RE.lastIndex;

continue outer;
Expand All @@ -141,7 +137,7 @@ const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOp

/* UNMATCHED INDEX */

index += 1;
index += ( input.codePointAt(index) || 0 ) > 0xffff ? 2 : 1;

}

Expand Down
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,18 @@ describe ( 'Fast String Width', () => {

});

it( 'supports "surrogate pairs" in unmatched characters', (t) => {

t.is(getTruncated("██ █", { limit: 4 }), "██ █");
t.is(getTruncated("██ █", { limit: 3 }), "██ ");
t.is(getTruncated("██ █", { limit: 2 }), "██");

t.is(getTruncated("██ █", { limit: 4, ellipsis: "…" }), "██ █");
t.is(getTruncated("██ █", { limit: 3, ellipsis: "…" }), "██…");
t.is(getTruncated("██ █", { limit: 2, ellipsis: "…" }), "█…");

});

});

});