@mark1russell7/text 0.0.5 → 0.0.7
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.
- package/README.md +73 -1
- package/build/length.d.ts +91 -0
- package/build/length.d.ts.map +1 -0
- package/build/length.js +118 -0
- package/build/length.js.map +1 -0
- package/build/parts.d.ts +32 -0
- package/build/parts.d.ts.map +1 -0
- package/build/parts.js +61 -0
- package/build/parts.js.map +1 -0
- package/package.json +14 -2
- package/src/length.ts +167 -0
- package/src/parts.ts +60 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @mark1russell7/text
|
|
2
2
|
|
|
3
|
-
Plain text helpers in
|
|
3
|
+
Plain text helpers in seven groups: the escapes of a text for five targets, the English word forms and a word search. The other four groups are the text of a thrown value, the removal of secrets, lengths with cuts and padding, and marked parts.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
pnpm add @mark1russell7/text
|
|
@@ -100,10 +100,78 @@ redactSecrets("token=k/y!", secrets, options); // "token=***"
|
|
|
100
100
|
|
|
101
101
|
The function examines the text one time. At each position, it removes the longest form that agrees, so a secret in a secret gives one mark. It ignores an empty secret.
|
|
102
102
|
|
|
103
|
+
## Lengths, truncation and padding
|
|
104
|
+
|
|
105
|
+
The entry `@mark1russell7/text/length` has three functions. Each function counts in the unit that you give. The default unit is `code-unit`.
|
|
106
|
+
|
|
107
|
+
| Unit | One unit | Length of the family emoji 👨👩👧👦 | Length of `e` and U+0301 (é) |
|
|
108
|
+
| --- | --- | --- | --- |
|
|
109
|
+
| `code-unit` | One UTF-16 code unit, as in `String.prototype.length` | 11 | 2 |
|
|
110
|
+
| `code-point` | One Unicode code point. A surrogate pair is one unit | 7 | 2 |
|
|
111
|
+
| `grapheme` | One extended grapheme cluster of `Intl.Segmenter` (UAX #29) | 1 | 1 |
|
|
112
|
+
|
|
113
|
+
- `textLength(text, unit?)` gives the length of a text in a unit.
|
|
114
|
+
- `truncate(text, max, options?)` cuts a text to `max` units or fewer, with a mark at the end. The default mark is "…".
|
|
115
|
+
- `pad(text, width, options?)` adds a fill at the start, at the end or at the two sides, to `width` units or fewer.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { pad, textLength, truncate } from "@mark1russell7/text/length";
|
|
119
|
+
|
|
120
|
+
textLength("🇯🇵 ok", "grapheme"); // 4
|
|
121
|
+
truncate("Water main break on Elm Road", 12); // "Water main …"
|
|
122
|
+
truncate(title, 250, { unit: "code-point" }); // 250 code points or fewer, with "…" at the end
|
|
123
|
+
truncate("ab🇯🇵cd", 5); // "ab…": the cut does not break the flag
|
|
124
|
+
truncate("ab🇯🇵cd", 5, { boundary: "code-point" }); // "ab🇯…"
|
|
125
|
+
truncate("hello", 2, { mark: "..." }); // "he": the mark is longer than max, so the result has no mark
|
|
126
|
+
pad("7", 3, { side: "start", fill: "0" }); // "007"
|
|
127
|
+
pad("ab", 7, { fill: "-=" }); // "ab-=-=-"
|
|
128
|
+
pad("ab", 5, { fill: "😀" }); // "ab😀": the emoji has two code units, so one half does not go in
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`truncate` obeys these rules:
|
|
132
|
+
|
|
133
|
+
- A text with `max` units or fewer comes back as it is, with no mark.
|
|
134
|
+
- The cut keeps each grapheme whole by default. With `boundary: "code-point"`, the cut keeps only each surrogate pair whole. The unit `grapheme` always keeps each grapheme whole.
|
|
135
|
+
- The result has `max` units or fewer, with the mark. A grapheme that does not fit goes out, so the result can be shorter than `max`.
|
|
136
|
+
- When the mark has more units than `max`, the result has no mark. It is the start of the text, with `max` units or fewer. Thus `truncate("hello", 0)` gives "".
|
|
137
|
+
- A `max` that is not an integer of 0 or more gives a `RangeError`. A unit or a boundary that is not in its type also gives a `RangeError`.
|
|
138
|
+
|
|
139
|
+
`pad` obeys these rules:
|
|
140
|
+
|
|
141
|
+
- A text with `width` units or more comes back as it is. The function does not cut a text.
|
|
142
|
+
- The fill goes again and again from its start, as in `padStart` and `padEnd`. The last copy can be a part of the fill.
|
|
143
|
+
- That part keeps each grapheme whole by default. Thus the result can be shorter than `width`.
|
|
144
|
+
- The side `both` puts the half of the fill at the start and the other half at the end. For an odd count, the end gets one more unit.
|
|
145
|
+
- An empty fill, a bad side and a `width` that is not an integer of 0 or more give a `RangeError`.
|
|
146
|
+
|
|
147
|
+
## Marked parts
|
|
148
|
+
|
|
149
|
+
The entry `@mark1russell7/text/parts` divides a text into parts. A part with `hit` is in a range or is a copy of a search. A page puts a `mark` element on each part with `hit`.
|
|
150
|
+
|
|
151
|
+
- `partsAt(text, ranges)` gives the parts at ranges of UTF-16 code units, `[start, end)`. It sorts the ranges, joins the ranges that overlap and clamps each range to the text.
|
|
152
|
+
- `partsOf(text, find)` gives the parts at each copy of `find`, from the start, with no overlap. The comparison is exact.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { partsAt, partsOf } from "@mark1russell7/text/parts";
|
|
156
|
+
|
|
157
|
+
partsOf("one cat, two cats", "cat");
|
|
158
|
+
// [{ text: "one ", hit: false }, { text: "cat", hit: true }, { text: ", two ", hit: false }, { text: "cat", hit: true }, { text: "s", hit: false }]
|
|
159
|
+
partsAt("A wide river", [[2, 6]]);
|
|
160
|
+
// [{ text: "A ", hit: false }, { text: "wide", hit: true }, { text: " river", hit: false }]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The parts obey these rules:
|
|
164
|
+
|
|
165
|
+
- The texts of the parts, in their order, make the text again. No part is empty.
|
|
166
|
+
- Two ranges that touch stay two parts. Two ranges that overlap become one part.
|
|
167
|
+
- An empty range, an empty `find` and an empty text give no part with `hit`.
|
|
168
|
+
|
|
103
169
|
## The copies that this package replaces
|
|
104
170
|
|
|
105
171
|
The tests run 58 copies of these functions from other repositories of the owner. Each copy comes from a list of the duplication atlas, at a pinned commit. The file `test/copies.json` has each copy, and `test/differences.ts` has each difference from the function of this package, with its reason. A copy that is not in the list gives the same output on each of the 1000 test strings.
|
|
106
172
|
|
|
173
|
+
The tests also examine 18 copies of a cut with a mark, from a later list of the atlas. The file `test/cut-copies.json` has each copy and the call of `truncate` that replaces it. The file `test/cut-differences.ts` has each difference, with its reason. Most copies cut at a code unit, so they can break a surrogate pair or a grapheme. The atlas has no copy of a padding function. The repositories call `padStart` and `padEnd` directly.
|
|
174
|
+
|
|
107
175
|
## Limits
|
|
108
176
|
|
|
109
177
|
- `escapeHtml` does not escape quotes. For an attribute value, use `escapeAttribute`.
|
|
@@ -113,3 +181,7 @@ The tests run 58 copies of these functions from other repositories of the owner.
|
|
|
113
181
|
- `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
|
|
114
182
|
- `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
|
|
115
183
|
- `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
|
|
184
|
+
- `textLength`, `truncate` and `pad` count graphemes with the `Intl.Segmenter` of the runtime. An old runtime can count a new emoji as more than one grapheme.
|
|
185
|
+
- In `pad`, a grapheme of the fill can join the text or the next copy of the fill. A combining mark and a lone regional indicator do this. Then the result has fewer graphemes than the width.
|
|
186
|
+
- `partsAt` counts in code units, as `String.prototype.slice` does. A range can cut a surrogate pair or a grapheme.
|
|
187
|
+
- The three functions count units, not the width on a screen. A wide character, for example 日, is one unit, as a narrow character is.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The
|
|
3
|
+
* unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for
|
|
4
|
+
* example a letter with an accent, a flag or an emoji sequence.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,
|
|
8
|
+
* so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).
|
|
9
|
+
*/
|
|
10
|
+
export type TextUnit = "code-unit" | "code-point" | "grapheme";
|
|
11
|
+
/**
|
|
12
|
+
* The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,
|
|
13
|
+
* so the unit `grapheme` keeps each grapheme whole with each boundary.
|
|
14
|
+
*/
|
|
15
|
+
export type TextBoundary = "code-point" | "grapheme";
|
|
16
|
+
/** The options of `truncate`. */
|
|
17
|
+
export interface TruncateOptions {
|
|
18
|
+
/** The unit of the length `max`. The default is `code-unit`. */
|
|
19
|
+
readonly unit?: TextUnit;
|
|
20
|
+
/** The part of the text that the cut keeps whole. The default is `grapheme`. */
|
|
21
|
+
readonly boundary?: TextBoundary;
|
|
22
|
+
/** The text at the end of a text that the function cuts. The default is the ellipsis "…" (U+2026). */
|
|
23
|
+
readonly mark?: string;
|
|
24
|
+
}
|
|
25
|
+
/** The options of `pad`. */
|
|
26
|
+
export interface PadOptions {
|
|
27
|
+
/** The unit of the width. The default is `code-unit`. */
|
|
28
|
+
readonly unit?: TextUnit;
|
|
29
|
+
/** The part of the fill that the function keeps whole. The default is `grapheme`. */
|
|
30
|
+
readonly boundary?: TextBoundary;
|
|
31
|
+
/** The text that the function adds. It can have more than one unit. The default is one space. */
|
|
32
|
+
readonly fill?: string;
|
|
33
|
+
/**
|
|
34
|
+
* The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.
|
|
35
|
+
* The default is `end`.
|
|
36
|
+
*/
|
|
37
|
+
readonly side?: "start" | "end" | "both";
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* This function gives the length of a text in a unit.
|
|
41
|
+
*
|
|
42
|
+
* - `code-unit` gives `text.length`.
|
|
43
|
+
* - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
|
|
44
|
+
* - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
|
|
45
|
+
* locale.
|
|
46
|
+
*
|
|
47
|
+
* @param text - The text.
|
|
48
|
+
* @param unit - The unit of the length. The default is `code-unit`.
|
|
49
|
+
* @returns The count of units in the text.
|
|
50
|
+
* @throws RangeError for a unit that is not in the type `TextUnit`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function textLength(text: string, unit?: TextUnit): number;
|
|
53
|
+
/**
|
|
54
|
+
* This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
|
|
55
|
+
* fewer, with the mark.
|
|
56
|
+
*
|
|
57
|
+
* - A text with `max` units or fewer comes back as it is, with no mark.
|
|
58
|
+
* - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
|
|
59
|
+
* an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
|
|
60
|
+
* whole.
|
|
61
|
+
* - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
|
|
62
|
+
* than `max`.
|
|
63
|
+
* - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
|
|
64
|
+
* or fewer.
|
|
65
|
+
*
|
|
66
|
+
* @param text - The text to cut.
|
|
67
|
+
* @param max - The most units in the result. It is an integer of 0 or more.
|
|
68
|
+
* @param options - The unit, the boundary and the mark.
|
|
69
|
+
* @returns The text, or the start of the text with the mark at the end.
|
|
70
|
+
* @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
|
|
71
|
+
*/
|
|
72
|
+
export declare function truncate(text: string, max: number, options?: TruncateOptions): string;
|
|
73
|
+
/**
|
|
74
|
+
* This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
|
|
75
|
+
* units or fewer.
|
|
76
|
+
*
|
|
77
|
+
* - A text with `width` units or more comes back as it is. The function does not cut a text.
|
|
78
|
+
* - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
|
|
79
|
+
* `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
|
|
80
|
+
* grapheme by default.
|
|
81
|
+
* - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
|
|
82
|
+
*
|
|
83
|
+
* @param text - The text.
|
|
84
|
+
* @param width - The length of the result with the fill. It is an integer of 0 or more.
|
|
85
|
+
* @param options - The unit, the boundary, the fill and the side.
|
|
86
|
+
* @returns The text with the fill.
|
|
87
|
+
* @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
|
|
88
|
+
* or side.
|
|
89
|
+
*/
|
|
90
|
+
export declare function pad(text: string, width: number, options?: PadOptions): string;
|
|
91
|
+
//# sourceMappingURL=length.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"length.d.ts","names":[],"sources":["../src/length.ts"],"mappings":";;;;;;;;;YAUY;;;;;YAMA;;iBAGK;;WAEN,OAAO;;WAEP,WAAW;;WAEX;;;iBAIM;;WAEN,OAAO;;WAEP,WAAW;;WAEX;;;;;WAKA;;;;;;;;;;;;;;;wBAwDK,WAAW,cAAc,OAAM;;;;;;;;;;;;;;;;;;;;wBA2B/B,SAAS,cAAc,aAAa,UAAS;;;;;;;;;;;;;;;;;;wBA4B7C,IAAI,cAAc,eAAe,UAAS"}
|
package/build/length.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// src/length.ts
|
|
2
|
+
let segmenter;
|
|
3
|
+
/** This function gives the parts of a text at a boundary, in their order. */
|
|
4
|
+
function* partsOf(text, boundary) {
|
|
5
|
+
if (boundary === "code-point") yield* text;
|
|
6
|
+
else for (const { segment } of (segmenter ??= new Intl.Segmenter(void 0, { granularity: "grapheme" })).segment(text)) yield segment;
|
|
7
|
+
}
|
|
8
|
+
/** This function stops a bad option with a `RangeError` and its message. */
|
|
9
|
+
function check(good, message) {
|
|
10
|
+
if (!good) throw new RangeError(message);
|
|
11
|
+
}
|
|
12
|
+
/** This function stops a count that is not an integer of 0 or more. */
|
|
13
|
+
function checkCount(value, name) {
|
|
14
|
+
check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);
|
|
15
|
+
}
|
|
16
|
+
/** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */
|
|
17
|
+
function boundaryOf(unit, boundary) {
|
|
18
|
+
check(unit === "code-unit" || unit === "code-point" || unit === "grapheme", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);
|
|
19
|
+
check(boundary === "code-point" || boundary === "grapheme", `boundary is ${String(boundary)}, not code-point or grapheme`);
|
|
20
|
+
return unit === "grapheme" ? unit : boundary;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,
|
|
24
|
+
* as an index of code units.
|
|
25
|
+
*/
|
|
26
|
+
function endOf(text, room, unit, boundary) {
|
|
27
|
+
let size = 0;
|
|
28
|
+
let end = 0;
|
|
29
|
+
for (const part of partsOf(text, boundary)) {
|
|
30
|
+
size += unit === "code-unit" ? part.length : unit === "code-point" ? [...part].length : 1;
|
|
31
|
+
if (size > room) break;
|
|
32
|
+
end += part.length;
|
|
33
|
+
}
|
|
34
|
+
return end;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* This function gives the length of a text in a unit.
|
|
38
|
+
*
|
|
39
|
+
* - `code-unit` gives `text.length`.
|
|
40
|
+
* - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
|
|
41
|
+
* - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
|
|
42
|
+
* locale.
|
|
43
|
+
*
|
|
44
|
+
* @param text - The text.
|
|
45
|
+
* @param unit - The unit of the length. The default is `code-unit`.
|
|
46
|
+
* @returns The count of units in the text.
|
|
47
|
+
* @throws RangeError for a unit that is not in the type `TextUnit`.
|
|
48
|
+
*/
|
|
49
|
+
function textLength(text, unit = "code-unit") {
|
|
50
|
+
boundaryOf(unit, "code-point");
|
|
51
|
+
if (unit === "code-unit") return text.length;
|
|
52
|
+
let count = 0;
|
|
53
|
+
for (const _ of partsOf(text, unit)) count += 1;
|
|
54
|
+
return count;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
|
|
58
|
+
* fewer, with the mark.
|
|
59
|
+
*
|
|
60
|
+
* - A text with `max` units or fewer comes back as it is, with no mark.
|
|
61
|
+
* - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
|
|
62
|
+
* an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
|
|
63
|
+
* whole.
|
|
64
|
+
* - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
|
|
65
|
+
* than `max`.
|
|
66
|
+
* - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
|
|
67
|
+
* or fewer.
|
|
68
|
+
*
|
|
69
|
+
* @param text - The text to cut.
|
|
70
|
+
* @param max - The most units in the result. It is an integer of 0 or more.
|
|
71
|
+
* @param options - The unit, the boundary and the mark.
|
|
72
|
+
* @returns The text, or the start of the text with the mark at the end.
|
|
73
|
+
* @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
|
|
74
|
+
*/
|
|
75
|
+
function truncate(text, max, options = {}) {
|
|
76
|
+
const { unit = "code-unit", mark = "…" } = options;
|
|
77
|
+
const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
|
|
78
|
+
checkCount(max, "max");
|
|
79
|
+
if (text.length <= max || unit !== "code-unit" && endOf(text, max, unit, unit) === text.length) return text;
|
|
80
|
+
const end = textLength(mark, unit) <= max ? mark : "";
|
|
81
|
+
return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
|
|
85
|
+
* units or fewer.
|
|
86
|
+
*
|
|
87
|
+
* - A text with `width` units or more comes back as it is. The function does not cut a text.
|
|
88
|
+
* - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
|
|
89
|
+
* `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
|
|
90
|
+
* grapheme by default.
|
|
91
|
+
* - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
|
|
92
|
+
*
|
|
93
|
+
* @param text - The text.
|
|
94
|
+
* @param width - The length of the result with the fill. It is an integer of 0 or more.
|
|
95
|
+
* @param options - The unit, the boundary, the fill and the side.
|
|
96
|
+
* @returns The text with the fill.
|
|
97
|
+
* @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
|
|
98
|
+
* or side.
|
|
99
|
+
*/
|
|
100
|
+
function pad(text, width, options = {}) {
|
|
101
|
+
const { unit = "code-unit", fill = " ", side = "end" } = options;
|
|
102
|
+
const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
|
|
103
|
+
checkCount(width, "width");
|
|
104
|
+
check(side === "start" || side === "end" || side === "both", `side is ${String(side)}, not start, end or both`);
|
|
105
|
+
const size = textLength(fill, unit);
|
|
106
|
+
check(size > 0, "fill is an empty text");
|
|
107
|
+
const missing = width - textLength(text, unit);
|
|
108
|
+
if (missing <= 0) return text;
|
|
109
|
+
const fillOf = (count) => {
|
|
110
|
+
const copies = Math.floor(count / size);
|
|
111
|
+
return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));
|
|
112
|
+
};
|
|
113
|
+
const start = side === "start" ? missing : side === "end" ? 0 : Math.floor(missing / 2);
|
|
114
|
+
return fillOf(start) + text + fillOf(missing - start);
|
|
115
|
+
}
|
|
116
|
+
export { pad, textLength, truncate };
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=length.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"length.js","names":[],"sources":["../src/length.ts"],"sourcesContent":["/**\n * This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The\n * unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for\n * example a letter with an accent, a flag or an emoji sequence.\n */\n\n/**\n * The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,\n * so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).\n */\nexport type TextUnit = \"code-unit\" | \"code-point\" | \"grapheme\";\n\n/**\n * The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,\n * so the unit `grapheme` keeps each grapheme whole with each boundary.\n */\nexport type TextBoundary = \"code-point\" | \"grapheme\";\n\n/** The options of `truncate`. */\nexport interface TruncateOptions {\n /** The unit of the length `max`. The default is `code-unit`. */\n readonly unit?: TextUnit;\n /** The part of the text that the cut keeps whole. The default is `grapheme`. */\n readonly boundary?: TextBoundary;\n /** The text at the end of a text that the function cuts. The default is the ellipsis \"…\" (U+2026). */\n readonly mark?: string;\n}\n\n/** The options of `pad`. */\nexport interface PadOptions {\n /** The unit of the width. The default is `code-unit`. */\n readonly unit?: TextUnit;\n /** The part of the fill that the function keeps whole. The default is `grapheme`. */\n readonly boundary?: TextBoundary;\n /** The text that the function adds. It can have more than one unit. The default is one space. */\n readonly fill?: string;\n /**\n * The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.\n * The default is `end`.\n */\n readonly side?: \"start\" | \"end\" | \"both\";\n}\n\nlet segmenter: Intl.Segmenter | undefined;\n\n/** This function gives the parts of a text at a boundary, in their order. */\nfunction* partsOf(text: string, boundary: TextBoundary): Generator<string> {\n if (boundary === \"code-point\") yield* text;\n else for (const { segment } of (segmenter ??= new Intl.Segmenter(undefined, { granularity: \"grapheme\" })).segment(text)) yield segment;\n}\n\n/** This function stops a bad option with a `RangeError` and its message. */\nfunction check(good: boolean, message: string): void {\n if (!good) throw new RangeError(message);\n}\n\n/** This function stops a count that is not an integer of 0 or more. */\nfunction checkCount(value: number, name: string): void {\n check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);\n}\n\n/** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */\nfunction boundaryOf(unit: TextUnit, boundary: TextBoundary): TextBoundary {\n check(unit === \"code-unit\" || unit === \"code-point\" || unit === \"grapheme\", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);\n check(boundary === \"code-point\" || boundary === \"grapheme\", `boundary is ${String(boundary)}, not code-point or grapheme`);\n return unit === \"grapheme\" ? unit : boundary;\n}\n\n/**\n * This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,\n * as an index of code units.\n */\nfunction endOf(text: string, room: number, unit: TextUnit, boundary: TextBoundary): number {\n let size = 0;\n let end = 0;\n for (const part of partsOf(text, boundary)) {\n size += unit === \"code-unit\" ? part.length : unit === \"code-point\" ? [...part].length : 1;\n if (size > room) break;\n end += part.length;\n }\n return end;\n}\n\n/**\n * This function gives the length of a text in a unit.\n *\n * - `code-unit` gives `text.length`.\n * - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.\n * - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the\n * locale.\n *\n * @param text - The text.\n * @param unit - The unit of the length. The default is `code-unit`.\n * @returns The count of units in the text.\n * @throws RangeError for a unit that is not in the type `TextUnit`.\n */\nexport function textLength(text: string, unit: TextUnit = \"code-unit\"): number {\n boundaryOf(unit, \"code-point\");\n if (unit === \"code-unit\") return text.length;\n let count = 0;\n for (const _ of partsOf(text, unit)) count += 1;\n return count;\n}\n\n/**\n * This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or\n * fewer, with the mark.\n *\n * - A text with `max` units or fewer comes back as it is, with no mark.\n * - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,\n * an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair\n * whole.\n * - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter\n * than `max`.\n * - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units\n * or fewer.\n *\n * @param text - The text to cut.\n * @param max - The most units in the result. It is an integer of 0 or more.\n * @param options - The unit, the boundary and the mark.\n * @returns The text, or the start of the text with the mark at the end.\n * @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.\n */\nexport function truncate(text: string, max: number, options: TruncateOptions = {}): string {\n const { unit = \"code-unit\", mark = \"…\" } = options;\n const boundary = boundaryOf(unit, options.boundary ?? \"grapheme\");\n checkCount(max, \"max\");\n // The count of code units is the largest count. Thus a text with `max` code units or fewer fits in each unit.\n if (text.length <= max || (unit !== \"code-unit\" && endOf(text, max, unit, unit) === text.length)) return text;\n const end = textLength(mark, unit) <= max ? mark : \"\";\n // A grapheme of the text can join a grapheme of the mark. A join gives fewer graphemes, never more (UAX #29).\n return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;\n}\n\n/**\n * This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`\n * units or fewer.\n *\n * - A text with `width` units or more comes back as it is. The function does not cut a text.\n * - The fill goes again and again. The last copy of the fill can be a part of the fill, as in\n * `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a\n * grapheme by default.\n * - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.\n *\n * @param text - The text.\n * @param width - The length of the result with the fill. It is an integer of 0 or more.\n * @param options - The unit, the boundary, the fill and the side.\n * @returns The text with the fill.\n * @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary\n * or side.\n */\nexport function pad(text: string, width: number, options: PadOptions = {}): string {\n const { unit = \"code-unit\", fill = \" \", side = \"end\" } = options;\n const boundary = boundaryOf(unit, options.boundary ?? \"grapheme\");\n checkCount(width, \"width\");\n check(side === \"start\" || side === \"end\" || side === \"both\", `side is ${String(side)}, not start, end or both`);\n const size = textLength(fill, unit);\n check(size > 0, \"fill is an empty text\");\n const missing = width - textLength(text, unit);\n if (missing <= 0) return text;\n const fillOf = (count: number): string => {\n const copies = Math.floor(count / size);\n return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));\n };\n const start = side === \"start\" ? missing : side === \"end\" ? 0 : Math.floor(missing / 2);\n return fillOf(start) + text + fillOf(missing - start);\n}\n"],"mappings":";AA2CA,IAAI;;AAGJ,UAAU,QAAQ,MAAc,UAA2C;CACzE,IAAI,aAAa,cAAc,OAAO;MACjC,KAAK,MAAM,EAAE,cAAc,cAAc,IAAI,KAAK,UAAU,KAAA,GAAW,EAAE,aAAa,WAAW,CAAC,EAAA,CAAG,QAAQ,IAAI,GAAG,MAAM;AACjI;;AAGA,SAAS,MAAM,MAAe,SAAuB;CACnD,IAAI,CAAC,MAAM,MAAM,IAAI,WAAW,OAAO;AACzC;;AAGA,SAAS,WAAW,OAAe,MAAoB;CACrD,MAAM,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,GAAG,KAAK,MAAM,OAAO,KAAK,EAAE,8BAA8B;AACzG;;AAGA,SAAS,WAAW,MAAgB,UAAsC;CACxE,MAAM,SAAS,eAAe,SAAS,gBAAgB,SAAS,YAAY,WAAW,OAAO,IAAI,EAAE,wCAAwC;CAC5I,MAAM,aAAa,gBAAgB,aAAa,YAAY,eAAe,OAAO,QAAQ,EAAE,6BAA6B;CACzH,OAAO,SAAS,aAAa,OAAO;AACtC;;;;;AAMA,SAAS,MAAM,MAAc,MAAc,MAAgB,UAAgC;CACzF,IAAI,OAAO;CACX,IAAI,MAAM;CACV,KAAK,MAAM,QAAQ,QAAQ,MAAM,QAAQ,GAAG;EAC1C,QAAQ,SAAS,cAAc,KAAK,SAAS,SAAS,eAAe,CAAC,GAAG,IAAI,CAAC,CAAC,SAAS;EACxF,IAAI,OAAO,MAAM;EACjB,OAAO,KAAK;CACd;CACA,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,WAAW,MAAc,OAAiB,aAAqB;CAC7E,WAAW,MAAM,YAAY;CAC7B,IAAI,SAAS,aAAa,OAAO,KAAK;CACtC,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ,MAAM,IAAI,GAAG,SAAS;CAC9C,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,MAAc,KAAa,UAA2B,CAAC,GAAW;CACzF,MAAM,EAAE,OAAO,aAAa,OAAO,QAAQ;CAC3C,MAAM,WAAW,WAAW,MAAM,QAAQ,YAAY,UAAU;CAChE,WAAW,KAAK,KAAK;CAErB,IAAI,KAAK,UAAU,OAAQ,SAAS,eAAe,MAAM,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,QAAS,OAAO;CACzG,MAAM,MAAM,WAAW,MAAM,IAAI,KAAK,MAAM,OAAO;CAEnD,OAAO,KAAK,MAAM,GAAG,MAAM,MAAM,MAAM,WAAW,KAAK,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI;AACnF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,IAAI,MAAc,OAAe,UAAsB,CAAC,GAAW;CACjF,MAAM,EAAE,OAAO,aAAa,OAAO,KAAK,OAAO,UAAU;CACzD,MAAM,WAAW,WAAW,MAAM,QAAQ,YAAY,UAAU;CAChE,WAAW,OAAO,OAAO;CACzB,MAAM,SAAS,WAAW,SAAS,SAAS,SAAS,QAAQ,WAAW,OAAO,IAAI,EAAE,yBAAyB;CAC9G,MAAM,OAAO,WAAW,MAAM,IAAI;CAClC,MAAM,OAAO,GAAG,uBAAuB;CACvC,MAAM,UAAU,QAAQ,WAAW,MAAM,IAAI;CAC7C,IAAI,WAAW,GAAG,OAAO;CACzB,MAAM,UAAU,UAA0B;EACxC,MAAM,SAAS,KAAK,MAAM,QAAQ,IAAI;EACtC,OAAO,KAAK,OAAO,MAAM,IAAI,KAAK,MAAM,GAAG,MAAM,MAAM,QAAQ,SAAS,MAAM,MAAM,QAAQ,CAAC;CAC/F;CACA,MAAM,QAAQ,SAAS,UAAU,UAAU,SAAS,QAAQ,IAAI,KAAK,MAAM,UAAU,CAAC;CACtF,OAAO,OAAO,KAAK,IAAI,OAAO,OAAO,UAAU,KAAK;AACtD"}
|
package/build/parts.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module divides a text into marked parts: the parts at ranges, or the parts at each copy of a text. A page puts a
|
|
3
|
+
* `mark` element on each part with `hit`, and a terminal puts a color on it.
|
|
4
|
+
*/
|
|
5
|
+
/** A part of a text. A part with `hit` is in a range or is a copy of the text that the search found. */
|
|
6
|
+
export interface TextPart {
|
|
7
|
+
readonly text: string;
|
|
8
|
+
readonly hit: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* This function divides a text into parts at ranges of UTF-16 code units, `[start, end)`. Each range gives a part with
|
|
12
|
+
* `hit`, and the text between the ranges gives parts with no `hit`. The function sorts the ranges, joins the ranges
|
|
13
|
+
* that overlap, and clamps each range to the text. Two ranges that touch stay two parts. An empty range gives no part.
|
|
14
|
+
*
|
|
15
|
+
* The texts of the parts, in their order, make the text again.
|
|
16
|
+
*
|
|
17
|
+
* @param text - The text.
|
|
18
|
+
* @param ranges - The ranges, as `[start, end)` in code units, in any order.
|
|
19
|
+
* @returns The parts of the text, with no empty part.
|
|
20
|
+
*/
|
|
21
|
+
export declare function partsAt(text: string, ranges: readonly (readonly [start: number, end: number])[]): TextPart[];
|
|
22
|
+
/**
|
|
23
|
+
* This function divides a text into parts at each copy of `find`, from the start, with no overlap. Each copy gives a
|
|
24
|
+
* part with `hit`. An empty `find` gives one part with no `hit`. The comparison is exact: the case and the
|
|
25
|
+
* normalization of the letters are significant.
|
|
26
|
+
*
|
|
27
|
+
* @param text - The text.
|
|
28
|
+
* @param find - The text to find.
|
|
29
|
+
* @returns The parts of the text, with no empty part.
|
|
30
|
+
*/
|
|
31
|
+
export declare function partsOf(text: string, find: string): TextPart[];
|
|
32
|
+
//# sourceMappingURL=parts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parts.d.ts","names":[],"sources":["../src/parts.ts"],"mappings":";;;;;iBAMiB;WACN;WACA;;;;;;;;;;;;;wBAcK,QAAQ,cAAc,4BAA4B,eAAe,kBAAkB;;;;;;;;;;wBAgCnF,QAAQ,cAAc,eAAe"}
|
package/build/parts.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// src/parts.ts
|
|
2
|
+
/**
|
|
3
|
+
* This function divides a text into parts at ranges of UTF-16 code units, `[start, end)`. Each range gives a part with
|
|
4
|
+
* `hit`, and the text between the ranges gives parts with no `hit`. The function sorts the ranges, joins the ranges
|
|
5
|
+
* that overlap, and clamps each range to the text. Two ranges that touch stay two parts. An empty range gives no part.
|
|
6
|
+
*
|
|
7
|
+
* The texts of the parts, in their order, make the text again.
|
|
8
|
+
*
|
|
9
|
+
* @param text - The text.
|
|
10
|
+
* @param ranges - The ranges, as `[start, end)` in code units, in any order.
|
|
11
|
+
* @returns The parts of the text, with no empty part.
|
|
12
|
+
*/
|
|
13
|
+
function partsAt(text, ranges) {
|
|
14
|
+
const clamp = (n) => Math.min(Math.max(Math.trunc(n), 0), text.length);
|
|
15
|
+
const sorted = ranges.map(([start, end]) => [clamp(start), clamp(end)]).filter(([start, end]) => end > start).sort((a, b) => a[0] - b[0]);
|
|
16
|
+
const parts = [];
|
|
17
|
+
let at = 0;
|
|
18
|
+
for (const [start, end] of sorted) {
|
|
19
|
+
if (end <= at) continue;
|
|
20
|
+
if (start < at) {
|
|
21
|
+
const last = parts[parts.length - 1];
|
|
22
|
+
parts[parts.length - 1] = {
|
|
23
|
+
text: last.text + text.slice(at, end),
|
|
24
|
+
hit: true
|
|
25
|
+
};
|
|
26
|
+
} else {
|
|
27
|
+
if (start > at) parts.push({
|
|
28
|
+
text: text.slice(at, start),
|
|
29
|
+
hit: false
|
|
30
|
+
});
|
|
31
|
+
parts.push({
|
|
32
|
+
text: text.slice(start, end),
|
|
33
|
+
hit: true
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
at = end;
|
|
37
|
+
}
|
|
38
|
+
if (at < text.length) parts.push({
|
|
39
|
+
text: text.slice(at),
|
|
40
|
+
hit: false
|
|
41
|
+
});
|
|
42
|
+
return parts;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* This function divides a text into parts at each copy of `find`, from the start, with no overlap. Each copy gives a
|
|
46
|
+
* part with `hit`. An empty `find` gives one part with no `hit`. The comparison is exact: the case and the
|
|
47
|
+
* normalization of the letters are significant.
|
|
48
|
+
*
|
|
49
|
+
* @param text - The text.
|
|
50
|
+
* @param find - The text to find.
|
|
51
|
+
* @returns The parts of the text, with no empty part.
|
|
52
|
+
*/
|
|
53
|
+
function partsOf(text, find) {
|
|
54
|
+
if (find === "") return partsAt(text, []);
|
|
55
|
+
const ranges = [];
|
|
56
|
+
for (let at = text.indexOf(find); at >= 0; at = text.indexOf(find, at + find.length)) ranges.push([at, at + find.length]);
|
|
57
|
+
return partsAt(text, ranges);
|
|
58
|
+
}
|
|
59
|
+
export { partsAt, partsOf };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=parts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parts.js","names":[],"sources":["../src/parts.ts"],"sourcesContent":["/**\n * This module divides a text into marked parts: the parts at ranges, or the parts at each copy of a text. A page puts a\n * `mark` element on each part with `hit`, and a terminal puts a color on it.\n */\n\n/** A part of a text. A part with `hit` is in a range or is a copy of the text that the search found. */\nexport interface TextPart {\n readonly text: string;\n readonly hit: boolean;\n}\n\n/**\n * This function divides a text into parts at ranges of UTF-16 code units, `[start, end)`. Each range gives a part with\n * `hit`, and the text between the ranges gives parts with no `hit`. The function sorts the ranges, joins the ranges\n * that overlap, and clamps each range to the text. Two ranges that touch stay two parts. An empty range gives no part.\n *\n * The texts of the parts, in their order, make the text again.\n *\n * @param text - The text.\n * @param ranges - The ranges, as `[start, end)` in code units, in any order.\n * @returns The parts of the text, with no empty part.\n */\nexport function partsAt(text: string, ranges: readonly (readonly [start: number, end: number])[]): TextPart[] {\n const clamp = (n: number): number => Math.min(Math.max(Math.trunc(n), 0), text.length);\n const sorted = ranges\n .map(([start, end]) => [clamp(start), clamp(end)] as const)\n .filter(([start, end]) => end > start)\n .sort((a, b) => a[0] - b[0]);\n const parts: TextPart[] = [];\n let at = 0;\n for (const [start, end] of sorted) {\n if (end <= at) continue;\n if (start < at) {\n const last = parts[parts.length - 1]!;\n parts[parts.length - 1] = { text: last.text + text.slice(at, end), hit: true };\n } else {\n if (start > at) parts.push({ text: text.slice(at, start), hit: false });\n parts.push({ text: text.slice(start, end), hit: true });\n }\n at = end;\n }\n if (at < text.length) parts.push({ text: text.slice(at), hit: false });\n return parts;\n}\n\n/**\n * This function divides a text into parts at each copy of `find`, from the start, with no overlap. Each copy gives a\n * part with `hit`. An empty `find` gives one part with no `hit`. The comparison is exact: the case and the\n * normalization of the letters are significant.\n *\n * @param text - The text.\n * @param find - The text to find.\n * @returns The parts of the text, with no empty part.\n */\nexport function partsOf(text: string, find: string): TextPart[] {\n if (find === \"\") return partsAt(text, []);\n const ranges: (readonly [number, number])[] = [];\n for (let at = text.indexOf(find); at >= 0; at = text.indexOf(find, at + find.length)) ranges.push([at, at + find.length]);\n return partsAt(text, ranges);\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,SAAgB,QAAQ,MAAc,QAAwE;CAC5G,MAAM,SAAS,MAAsB,KAAK,IAAI,KAAK,IAAI,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,MAAM;CACrF,MAAM,SAAS,OACZ,KAAK,CAAC,OAAO,SAAS,CAAC,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,CAAU,CAAC,CAC1D,QAAQ,CAAC,OAAO,SAAS,MAAM,KAAK,CAAC,CACrC,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE;CAC7B,MAAM,QAAoB,CAAC;CAC3B,IAAI,KAAK;CACT,KAAK,MAAM,CAAC,OAAO,QAAQ,QAAQ;EACjC,IAAI,OAAO,IAAI;EACf,IAAI,QAAQ,IAAI;GACd,MAAM,OAAO,MAAM,MAAM,SAAS;GAClC,MAAM,MAAM,SAAS,KAAK;IAAE,MAAM,KAAK,OAAO,KAAK,MAAM,IAAI,GAAG;IAAG,KAAK;GAAK;EAC/E,OAAO;GACL,IAAI,QAAQ,IAAI,MAAM,KAAK;IAAE,MAAM,KAAK,MAAM,IAAI,KAAK;IAAG,KAAK;GAAM,CAAC;GACtE,MAAM,KAAK;IAAE,MAAM,KAAK,MAAM,OAAO,GAAG;IAAG,KAAK;GAAK,CAAC;EACxD;EACA,KAAK;CACP;CACA,IAAI,KAAK,KAAK,QAAQ,MAAM,KAAK;EAAE,MAAM,KAAK,MAAM,EAAE;EAAG,KAAK;CAAM,CAAC;CACrE,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,QAAQ,MAAc,MAA0B;CAC9D,IAAI,SAAS,IAAI,OAAO,QAAQ,MAAM,CAAC,CAAC;CACxC,MAAM,SAAwC,CAAC;CAC/C,KAAK,IAAI,KAAK,KAAK,QAAQ,IAAI,GAAG,MAAM,GAAG,KAAK,KAAK,QAAQ,MAAM,KAAK,KAAK,MAAM,GAAG,OAAO,KAAK,CAAC,IAAI,KAAK,KAAK,MAAM,CAAC;CACxH,OAAO,QAAQ,MAAM,MAAM;AAC7B"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/text",
|
|
4
|
-
"version": "0.0.
|
|
5
|
-
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch), the text of a thrown value (errorMessage)
|
|
4
|
+
"version": "0.0.7",
|
|
5
|
+
"description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch), the text of a thrown value (errorMessage), the removal of secrets (redactSecrets), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad).",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"text",
|
|
8
8
|
"escape",
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
"redact",
|
|
15
15
|
"secrets",
|
|
16
16
|
"error",
|
|
17
|
+
"truncate",
|
|
18
|
+
"pad",
|
|
19
|
+
"grapheme",
|
|
20
|
+
"unicode",
|
|
17
21
|
"typescript"
|
|
18
22
|
],
|
|
19
23
|
"homepage": "https://github.com/mark1russell7/text#readme",
|
|
@@ -40,6 +44,14 @@
|
|
|
40
44
|
"types": "./build/redact.d.ts",
|
|
41
45
|
"default": "./build/redact.js"
|
|
42
46
|
},
|
|
47
|
+
"./length": {
|
|
48
|
+
"types": "./build/length.d.ts",
|
|
49
|
+
"default": "./build/length.js"
|
|
50
|
+
},
|
|
51
|
+
"./parts": {
|
|
52
|
+
"types": "./build/parts.d.ts",
|
|
53
|
+
"default": "./build/parts.js"
|
|
54
|
+
},
|
|
43
55
|
"./package.json": "./package.json"
|
|
44
56
|
},
|
|
45
57
|
"files": [
|
package/src/length.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module has three functions for a text: its length in a unit, a cut to a length and padding to a width. The
|
|
3
|
+
* unit is a UTF-16 code unit, a Unicode code point or a grapheme. A grapheme is one character as a person sees it, for
|
|
4
|
+
* example a letter with an accent, a flag or an emoji sequence.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The unit of a length. `code-unit` is the unit of `String.prototype.length`. `code-point` is one Unicode code point,
|
|
9
|
+
* so a surrogate pair is one unit. `grapheme` is one extended grapheme cluster of Unicode (UAX #29).
|
|
10
|
+
*/
|
|
11
|
+
export type TextUnit = "code-unit" | "code-point" | "grapheme";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The smallest part of a text that a cut or a fill keeps whole. The function uses the larger of this part and the unit,
|
|
15
|
+
* so the unit `grapheme` keeps each grapheme whole with each boundary.
|
|
16
|
+
*/
|
|
17
|
+
export type TextBoundary = "code-point" | "grapheme";
|
|
18
|
+
|
|
19
|
+
/** The options of `truncate`. */
|
|
20
|
+
export interface TruncateOptions {
|
|
21
|
+
/** The unit of the length `max`. The default is `code-unit`. */
|
|
22
|
+
readonly unit?: TextUnit;
|
|
23
|
+
/** The part of the text that the cut keeps whole. The default is `grapheme`. */
|
|
24
|
+
readonly boundary?: TextBoundary;
|
|
25
|
+
/** The text at the end of a text that the function cuts. The default is the ellipsis "…" (U+2026). */
|
|
26
|
+
readonly mark?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The options of `pad`. */
|
|
30
|
+
export interface PadOptions {
|
|
31
|
+
/** The unit of the width. The default is `code-unit`. */
|
|
32
|
+
readonly unit?: TextUnit;
|
|
33
|
+
/** The part of the fill that the function keeps whole. The default is `grapheme`. */
|
|
34
|
+
readonly boundary?: TextBoundary;
|
|
35
|
+
/** The text that the function adds. It can have more than one unit. The default is one space. */
|
|
36
|
+
readonly fill?: string;
|
|
37
|
+
/**
|
|
38
|
+
* The side of the fill. `both` puts the half of the fill at each side. For an odd count, the end gets one more unit.
|
|
39
|
+
* The default is `end`.
|
|
40
|
+
*/
|
|
41
|
+
readonly side?: "start" | "end" | "both";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let segmenter: Intl.Segmenter | undefined;
|
|
45
|
+
|
|
46
|
+
/** This function gives the parts of a text at a boundary, in their order. */
|
|
47
|
+
function* partsOf(text: string, boundary: TextBoundary): Generator<string> {
|
|
48
|
+
if (boundary === "code-point") yield* text;
|
|
49
|
+
else for (const { segment } of (segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" })).segment(text)) yield segment;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** This function stops a bad option with a `RangeError` and its message. */
|
|
53
|
+
function check(good: boolean, message: string): void {
|
|
54
|
+
if (!good) throw new RangeError(message);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** This function stops a count that is not an integer of 0 or more. */
|
|
58
|
+
function checkCount(value: number, name: string): void {
|
|
59
|
+
check(Number.isInteger(value) && value >= 0, `${name} is ${String(value)}, not an integer of 0 or more`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** This function stops a unit and a boundary that are not in their types, and gives the boundary to use. */
|
|
63
|
+
function boundaryOf(unit: TextUnit, boundary: TextBoundary): TextBoundary {
|
|
64
|
+
check(unit === "code-unit" || unit === "code-point" || unit === "grapheme", `unit is ${String(unit)}, not code-unit, code-point or grapheme`);
|
|
65
|
+
check(boundary === "code-point" || boundary === "grapheme", `boundary is ${String(boundary)}, not code-point or grapheme`);
|
|
66
|
+
return unit === "grapheme" ? unit : boundary;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* This function gives the end of the longest start of a text that has `room` units or fewer. The end is at a boundary,
|
|
71
|
+
* as an index of code units.
|
|
72
|
+
*/
|
|
73
|
+
function endOf(text: string, room: number, unit: TextUnit, boundary: TextBoundary): number {
|
|
74
|
+
let size = 0;
|
|
75
|
+
let end = 0;
|
|
76
|
+
for (const part of partsOf(text, boundary)) {
|
|
77
|
+
size += unit === "code-unit" ? part.length : unit === "code-point" ? [...part].length : 1;
|
|
78
|
+
if (size > room) break;
|
|
79
|
+
end += part.length;
|
|
80
|
+
}
|
|
81
|
+
return end;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* This function gives the length of a text in a unit.
|
|
86
|
+
*
|
|
87
|
+
* - `code-unit` gives `text.length`.
|
|
88
|
+
* - `code-point` counts a surrogate pair as one unit, and a lone surrogate as one unit.
|
|
89
|
+
* - `grapheme` counts the extended grapheme clusters of `Intl.Segmenter`. The rules of Unicode do not change with the
|
|
90
|
+
* locale.
|
|
91
|
+
*
|
|
92
|
+
* @param text - The text.
|
|
93
|
+
* @param unit - The unit of the length. The default is `code-unit`.
|
|
94
|
+
* @returns The count of units in the text.
|
|
95
|
+
* @throws RangeError for a unit that is not in the type `TextUnit`.
|
|
96
|
+
*/
|
|
97
|
+
export function textLength(text: string, unit: TextUnit = "code-unit"): number {
|
|
98
|
+
boundaryOf(unit, "code-point");
|
|
99
|
+
if (unit === "code-unit") return text.length;
|
|
100
|
+
let count = 0;
|
|
101
|
+
for (const _ of partsOf(text, unit)) count += 1;
|
|
102
|
+
return count;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* This function cuts a text to a length, and puts a mark at the end of the cut text. The result has `max` units or
|
|
107
|
+
* fewer, with the mark.
|
|
108
|
+
*
|
|
109
|
+
* - A text with `max` units or fewer comes back as it is, with no mark.
|
|
110
|
+
* - The cut keeps each part of `boundary` whole. The default part is the grapheme, so the cut does not break a flag,
|
|
111
|
+
* an emoji sequence or a letter with a combining mark. With `code-point`, the cut keeps only each surrogate pair
|
|
112
|
+
* whole.
|
|
113
|
+
* - A part that does not fit in the length goes out with all the parts after it. Thus the result can be shorter
|
|
114
|
+
* than `max`.
|
|
115
|
+
* - When the mark has more than `max` units, the result has no mark. It is the start of the text, with `max` units
|
|
116
|
+
* or fewer.
|
|
117
|
+
*
|
|
118
|
+
* @param text - The text to cut.
|
|
119
|
+
* @param max - The most units in the result. It is an integer of 0 or more.
|
|
120
|
+
* @param options - The unit, the boundary and the mark.
|
|
121
|
+
* @returns The text, or the start of the text with the mark at the end.
|
|
122
|
+
* @throws RangeError for a `max` that is not an integer of 0 or more, and for a bad unit or boundary.
|
|
123
|
+
*/
|
|
124
|
+
export function truncate(text: string, max: number, options: TruncateOptions = {}): string {
|
|
125
|
+
const { unit = "code-unit", mark = "…" } = options;
|
|
126
|
+
const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
|
|
127
|
+
checkCount(max, "max");
|
|
128
|
+
// The count of code units is the largest count. Thus a text with `max` code units or fewer fits in each unit.
|
|
129
|
+
if (text.length <= max || (unit !== "code-unit" && endOf(text, max, unit, unit) === text.length)) return text;
|
|
130
|
+
const end = textLength(mark, unit) <= max ? mark : "";
|
|
131
|
+
// A grapheme of the text can join a grapheme of the mark. A join gives fewer graphemes, never more (UAX #29).
|
|
132
|
+
return text.slice(0, endOf(text, max - textLength(end, unit), unit, boundary)) + end;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* This function adds a fill to a text, at the start, at the end or at the two sides, to a width. The result has `width`
|
|
137
|
+
* units or fewer.
|
|
138
|
+
*
|
|
139
|
+
* - A text with `width` units or more comes back as it is. The function does not cut a text.
|
|
140
|
+
* - The fill goes again and again. The last copy of the fill can be a part of the fill, as in
|
|
141
|
+
* `String.prototype.padEnd`. That part keeps each part of `boundary` whole, so the function does not add a part of a
|
|
142
|
+
* grapheme by default.
|
|
143
|
+
* - When the next part of the fill does not fit, the function stops. Thus the result can be shorter than `width`.
|
|
144
|
+
*
|
|
145
|
+
* @param text - The text.
|
|
146
|
+
* @param width - The length of the result with the fill. It is an integer of 0 or more.
|
|
147
|
+
* @param options - The unit, the boundary, the fill and the side.
|
|
148
|
+
* @returns The text with the fill.
|
|
149
|
+
* @throws RangeError for a `width` that is not an integer of 0 or more, for an empty fill, and for a bad unit, boundary
|
|
150
|
+
* or side.
|
|
151
|
+
*/
|
|
152
|
+
export function pad(text: string, width: number, options: PadOptions = {}): string {
|
|
153
|
+
const { unit = "code-unit", fill = " ", side = "end" } = options;
|
|
154
|
+
const boundary = boundaryOf(unit, options.boundary ?? "grapheme");
|
|
155
|
+
checkCount(width, "width");
|
|
156
|
+
check(side === "start" || side === "end" || side === "both", `side is ${String(side)}, not start, end or both`);
|
|
157
|
+
const size = textLength(fill, unit);
|
|
158
|
+
check(size > 0, "fill is an empty text");
|
|
159
|
+
const missing = width - textLength(text, unit);
|
|
160
|
+
if (missing <= 0) return text;
|
|
161
|
+
const fillOf = (count: number): string => {
|
|
162
|
+
const copies = Math.floor(count / size);
|
|
163
|
+
return fill.repeat(copies) + fill.slice(0, endOf(fill, count - copies * size, unit, boundary));
|
|
164
|
+
};
|
|
165
|
+
const start = side === "start" ? missing : side === "end" ? 0 : Math.floor(missing / 2);
|
|
166
|
+
return fillOf(start) + text + fillOf(missing - start);
|
|
167
|
+
}
|
package/src/parts.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This module divides a text into marked parts: the parts at ranges, or the parts at each copy of a text. A page puts a
|
|
3
|
+
* `mark` element on each part with `hit`, and a terminal puts a color on it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** A part of a text. A part with `hit` is in a range or is a copy of the text that the search found. */
|
|
7
|
+
export interface TextPart {
|
|
8
|
+
readonly text: string;
|
|
9
|
+
readonly hit: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* This function divides a text into parts at ranges of UTF-16 code units, `[start, end)`. Each range gives a part with
|
|
14
|
+
* `hit`, and the text between the ranges gives parts with no `hit`. The function sorts the ranges, joins the ranges
|
|
15
|
+
* that overlap, and clamps each range to the text. Two ranges that touch stay two parts. An empty range gives no part.
|
|
16
|
+
*
|
|
17
|
+
* The texts of the parts, in their order, make the text again.
|
|
18
|
+
*
|
|
19
|
+
* @param text - The text.
|
|
20
|
+
* @param ranges - The ranges, as `[start, end)` in code units, in any order.
|
|
21
|
+
* @returns The parts of the text, with no empty part.
|
|
22
|
+
*/
|
|
23
|
+
export function partsAt(text: string, ranges: readonly (readonly [start: number, end: number])[]): TextPart[] {
|
|
24
|
+
const clamp = (n: number): number => Math.min(Math.max(Math.trunc(n), 0), text.length);
|
|
25
|
+
const sorted = ranges
|
|
26
|
+
.map(([start, end]) => [clamp(start), clamp(end)] as const)
|
|
27
|
+
.filter(([start, end]) => end > start)
|
|
28
|
+
.sort((a, b) => a[0] - b[0]);
|
|
29
|
+
const parts: TextPart[] = [];
|
|
30
|
+
let at = 0;
|
|
31
|
+
for (const [start, end] of sorted) {
|
|
32
|
+
if (end <= at) continue;
|
|
33
|
+
if (start < at) {
|
|
34
|
+
const last = parts[parts.length - 1]!;
|
|
35
|
+
parts[parts.length - 1] = { text: last.text + text.slice(at, end), hit: true };
|
|
36
|
+
} else {
|
|
37
|
+
if (start > at) parts.push({ text: text.slice(at, start), hit: false });
|
|
38
|
+
parts.push({ text: text.slice(start, end), hit: true });
|
|
39
|
+
}
|
|
40
|
+
at = end;
|
|
41
|
+
}
|
|
42
|
+
if (at < text.length) parts.push({ text: text.slice(at), hit: false });
|
|
43
|
+
return parts;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* This function divides a text into parts at each copy of `find`, from the start, with no overlap. Each copy gives a
|
|
48
|
+
* part with `hit`. An empty `find` gives one part with no `hit`. The comparison is exact: the case and the
|
|
49
|
+
* normalization of the letters are significant.
|
|
50
|
+
*
|
|
51
|
+
* @param text - The text.
|
|
52
|
+
* @param find - The text to find.
|
|
53
|
+
* @returns The parts of the text, with no empty part.
|
|
54
|
+
*/
|
|
55
|
+
export function partsOf(text: string, find: string): TextPart[] {
|
|
56
|
+
if (find === "") return partsAt(text, []);
|
|
57
|
+
const ranges: (readonly [number, number])[] = [];
|
|
58
|
+
for (let at = text.indexOf(find); at >= 0; at = text.indexOf(find, at + find.length)) ranges.push([at, at + find.length]);
|
|
59
|
+
return partsAt(text, ranges);
|
|
60
|
+
}
|