Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiospampinato committed Feb 27, 2024
0 parents commit 5e32fca
Show file tree
Hide file tree
Showing 11 changed files with 727 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
*~
*.err
*.log
._*
.cache
.fseventsd
.DocumentRevisions*
.DS_Store
.TemporaryItems
.Trashes
Thumbs.db

dist
node_modules
package-lock.json
21 changes: 21 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024-present Fabio Spampinato

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.
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "fast-string-truncated-width",
"repository": "github:fabiospampinato/fast-string-truncated-width",
"description": "A fast function for calculating where a string should be truncated, given an optional width limit and an ellipsis string.",
"version": "1.0.4",
"type": "module",
"main": "dist/index.js",
"exports": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"benchmark": "tsex benchmark",
"benchmark:watch": "tsex benchmark --watch",
"clean": "tsex clean",
"compile": "tsex compile",
"compile:watch": "tsex compile --watch",
"test": "tsex test",
"test:watch": "tsex test --watch",
"prepublishOnly": "tsex prepare"
},
"keywords": [
"fast",
"string",
"truncated",
"width",
"cli",
"terminal"
],
"devDependencies": {
"benchloop": "^2.1.1",
"fava": "^0.3.2",
"tsex": "^3.0.2",
"typescript": "^5.3.3"
}
}
39 changes: 39 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Fast String Truncated Width

A fast function for calculating where a string should be truncated, given a width limit and an ellipsis string.

This is a low-level function that basically calculates the visual width of a string and the index at which it should be truncated once printed to the terminal, but taking into account an optional width limit and an optional ellipsis string, so that the string doesn't have to be processed multiple times to be truncated, and how long the part after the truncation point is doesn't cost us anything because we can just ignore it.

## Install

```sh
npm install --save fast-string-truncated-width
```

## Usage

```ts
import fastStringTruncatedWidth from 'fast-string-truncated-width';

// Retrieving the result for a string that fits within our width limit

const result1 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: Infinity, ellipsis: '' } );

result1.truncated; // => false, the string fits within the width limit, it doesn't have to be truncated
result1.ellipsed; // => false, the ellipsis string doesn't need to be appended to the string
result1.width; // => 5, the visual width of the string once printed to the terminal
result1.index; // => 10, the end index at which the string should be sliced, equal to input.length in this case

// Retrieving the result for a string that doesn't fit within our width limit

const result2 = fastStringTruncatedWidth ( '\x1b[31mhello', { limit: 3, ellipsis: '' } );

result2.truncated; // => true, the string doesn't fit within the width limit, it has to be truncated
result2.ellipsed; // => true, the ellipsis string should be appended to the string (this isn't always the case, for example if our limit is 0)
result2.width; // => 2, the visual width of the string once printed to the terminal (this doesn't account for the width of the ellipsis string itself)
result2.index; // => 7, the end index at which the string should be sliced to truncate it correctly
```

## License

MIT © Fabio Spampinato
222 changes: 222 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@

/* IMPORT */

import {isAmbiguous, isFullWidth, isWide} from './utils';
import type {TruncationOptions, WidthOptions, Result} from './types';

/* HELPERS */

const ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y;
const CONTROL_RE = /[\x00-\x1F\x7F-\x9F]+/y;
const EMOJI_RE = /(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(?:\u200d(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*/yu;
const LATIN_RE = /[\x20-\x7E\xA0-\xFF]+/y;
const MODIFIER_RE = /\p{M}+/gu;
const NO_TRUNCATION: TruncationOptions = { limit: Infinity, ellipsis: '' };

/* MAIN */

//TODO: Optimize matching non-latin letters

const getStringTruncatedWidth = ( input: string, truncationOptions: TruncationOptions = {}, widthOptions: WidthOptions = {} ): Result => {

/* CONSTANTS */

const LIMIT = truncationOptions.limit ?? Infinity;
const ELLIPSIS = truncationOptions.ellipsis ?? '';
const ELLIPSIS_WIDTH = ELLIPSIS ? getStringTruncatedWidth ( ELLIPSIS, NO_TRUNCATION, widthOptions ).width : 0;

const ANSI_WIDTH = widthOptions.ansiWidth ?? 0;
const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;

const AMBIGUOUS_WIDTH = widthOptions.ambiguousWidth ?? 1;
const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
const FULL_WIDTH_WIDTH = widthOptions.fullWidthWidth ?? 2;
const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
const WIDE_WIDTH = widthOptions.wideWidth ?? 2;

/* STATE */

let indexPrev = 0;
let index = 0;
let length = input.length;
let lengthExtra = 0;
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;

/* PARSE LOOP */

outer:
while ( true ) {

/* UNMATCHED */

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

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

lengthExtra = 0;

for ( const char of unmatched.replaceAll ( MODIFIER_RE, '' ) ) {

const codePoint = char.codePointAt ( 0 ) || 0;

if ( isFullWidth ( codePoint ) ) {
widthExtra = FULL_WIDTH_WIDTH;
} else if ( isWide ( codePoint ) ) {
widthExtra = WIDE_WIDTH;
} else if ( AMBIGUOUS_WIDTH !== REGULAR_WIDTH && isAmbiguous ( codePoint ) ) {
widthExtra = AMBIGUOUS_WIDTH;
} else {
widthExtra = REGULAR_WIDTH;
}

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

if ( ( width + widthExtra ) > LIMIT ) {
truncationEnabled = true;
break outer;
}

lengthExtra += char.length;
width += widthExtra;

}

unmatchedStart = unmatchedEnd = 0;

}

/* EXITING */

if ( index >= length ) break;

/* LATIN */

LATIN_RE.lastIndex = index;

if ( LATIN_RE.test ( input ) ) {

lengthExtra = LATIN_RE.lastIndex - index;
widthExtra = lengthExtra * REGULAR_WIDTH;

if ( ( width + widthExtra ) > truncationLimit ) {
truncationIndex = Math.min ( truncationIndex, index + Math.floor ( ( truncationLimit - width ) / REGULAR_WIDTH ) );
}

if ( ( width + widthExtra ) > LIMIT ) {
truncationEnabled = true;
break;
}

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

continue;

}

/* ANSI */

ANSI_RE.lastIndex = index;

if ( ANSI_RE.test ( input ) ) {

if ( ( width + ANSI_WIDTH ) > truncationLimit ) {
truncationIndex = Math.min ( truncationIndex, index );
}

if ( ( width + ANSI_WIDTH ) > LIMIT ) {
truncationEnabled = true;
break;
}

width += ANSI_WIDTH;
unmatchedStart = indexPrev;
unmatchedEnd = index;
index = indexPrev = ANSI_RE.lastIndex;

continue;

}

/* CONTROL */

CONTROL_RE.lastIndex = index;

if ( CONTROL_RE.test ( input ) ) {

lengthExtra = CONTROL_RE.lastIndex - index;
widthExtra = lengthExtra * CONTROL_WIDTH;

if ( ( width + widthExtra ) > truncationLimit ) {
truncationIndex = Math.min ( truncationIndex, index + Math.floor ( ( truncationLimit - width ) / CONTROL_WIDTH ) );
}

if ( ( width + widthExtra ) > LIMIT ) {
truncationEnabled = true;
break;
}

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

continue;

}

/* EMOJI */

EMOJI_RE.lastIndex = index;

if ( EMOJI_RE.test ( input ) ) {

if ( ( width + EMOJI_WIDTH ) > truncationLimit ) {
truncationIndex = Math.min ( truncationIndex, index );
}

if ( ( width + EMOJI_WIDTH ) > LIMIT ) {
truncationEnabled = true;
break;
}

width += EMOJI_WIDTH;
unmatchedStart = indexPrev;
unmatchedEnd = index;
index = indexPrev = EMOJI_RE.lastIndex;

continue;

}

/* UNMATCHED INDEX */

index += 1;

}

/* RETURN */

return {
width: truncationEnabled ? truncationLimit : width,
index: truncationEnabled ? truncationIndex : length,
truncated: truncationEnabled,
ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
};

};

/* EXPORT */

export default getStringTruncatedWidth;
export type {TruncationOptions, WidthOptions, Result};
30 changes: 30 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

/* MAIN */

type TruncationOptions = {
limit?: number,
ellipsis?: string
};

type WidthOptions = {
/* SPECIAL */
ansiWidth?: number,
controlWidth?: number,
/* UNICODE */
ambiguousWidth?: number,
emojiWidth?: number,
fullWidthWidth?: number,
regularWidth?: number,
wideWidth?: number
};

type Result = {
width: number,
index: number,
truncated: boolean,
ellipsed: boolean
};

/* EXPORT */

export type {TruncationOptions, WidthOptions, Result};
Loading

0 comments on commit 5e32fca

Please sign in to comment.