···11+import { wrap } from '@clack/core';
22+import { stdin, stdout } from 'node:process';
33+import * as readline from 'readline';
44+import { cursor, erase } from 'sisteransi';
55+import color from 'picocolors';
66+77+function createLogger({ input = stdin, output = stdout } = {}) {
88+ let previousLineCount = 0;
99+ let previousWidth = output.columns ?? 80;
1010+ let previousFormatted = '';
1111+1212+ function log(message = '') {
1313+ const width = output.columns ?? 80;
1414+ let formatted = wrap(message, width) + '\n'
1515+ let currLineCount = formatted.split('\n').length;
1616+ if (previousLineCount > 0 && currLineCount > previousLineCount) {
1717+ previousLineCount = wrap(previousFormatted, width).split('\n').length;
1818+ }
1919+ if (formatted === previousFormatted && previousWidth === width) {
2020+ return;
2121+ }
2222+ previousFormatted = formatted;
2323+ previousWidth = width;
2424+2525+ output.write(erase.lines(previousLineCount) + formatted);
2626+ previousLineCount = formatted.split('\n').length;
2727+ }
2828+2929+ return { log };
3030+}
3131+3232+const paragraph = `Lorem ipsum dolor sit ${color.red('amet')}, ${color.green('consectetur')} adipiscing elit. Fusce sed urna a ${color.inverse(' sem ')} aliquet efficitur sit amet quis turpis.\n\nDonec consectetur neque eget consequat ultricies. Integer ornare ipsum quis maximus tempor. Fusce quis sem eget dolor maximus sollicitudin quis sodales enim. Mauris a finibus risus, vitae porta dolor. Aliquam nec dui vitae dui fermentum dictum eget mattis mauris. Suspendisse condimentum sodales nisl, quis vestibulum dolor pretium vel. Etiam dignissim maximus leo, eget auctor felis congue non. Vestibulum venenatis mi sapien, nec sagittis dui finibus quis. Ut neque lacus, vestibulum nec congue non, finibus in lorem. Cras consectetur, neque non pretium luctus, orci massa auctor orci, id scelerisque velit mi quis erat. Proin a nibh placerat, sollicitudin dui ut, pretium nisi.`;
3333+3434+const rl = readline.createInterface({
3535+ input: process.stdin,
3636+ output: process.stdout,
3737+ prompt: ''
3838+});
3939+4040+async function main() {
4141+ const logger = createLogger();
4242+ logger.log(paragraph)
4343+ process.stdout.on('resize', () => logger.log(paragraph))
4444+}
4545+4646+main();
···11+MIT License
22+33+Copyright (c) Nate Moore
44+55+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:
66+77+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
88+99+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.
1010+1111+---
1212+1313+`ansi-regex` is adapted from https://github.com/chalk/ansi-regex
1414+1515+MIT License
1616+1717+Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
1818+1919+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:
2020+2121+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
2222+2323+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.
···77export { default as SelectPrompt } from './prompts/select';
88export { default as SelectKeyPrompt } from './prompts/select-key';
99export { default as TextPrompt } from './prompts/text';
1010-export { block } from './utils';
1010+export * from './utils';
+81
packages/core/src/utils.ts
···33import { stdin, stdout } from 'node:process';
44import * as readline from 'node:readline';
55import { cursor } from 'sisteransi';
66+// @ts-expect-error no types
77+import ea from 'eastasianwidth';
6879export function block({
810 input = stdin,
···4648 rl.close();
4749 };
4850}
5151+5252+// Adapted from https://github.com/chalk/ansi-regex
5353+// @see LICENSE
5454+function ansiRegex() {
5555+ const pattern = [
5656+ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
5757+ '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))',
5858+ ].join('|');
5959+6060+ return new RegExp(pattern, 'g');
6161+}
6262+6363+export function strip(str: string) {
6464+ return str.replace(ansiRegex(), '');
6565+}
6666+6767+export function width(str: string): number {
6868+ return Array.from(graphemes.segment(str)).map(({ segment: c }) => ea.characterLength(c)).reduce((a, b) => a + b, 0);
6969+}
7070+7171+const words = new Intl.Segmenter([], { granularity: 'word' });
7272+const graphemes = new Intl.Segmenter([], { granularity: 'grapheme' });
7373+7474+export function wrap(str: string, cols = process.stdout.columns): string {
7575+ const parts: string[] = [];
7676+ let part = '';
7777+ let i = 0;
7878+ const handle = (chunk: string, { prefix = "", suffix = '' } = {}) => {
7979+ for (const word of words.segment(chunk)) {
8080+ if (word.segment === '\n') {
8181+ parts.push(part)
8282+ i = 0
8383+ part = ''
8484+ continue;
8585+ }
8686+ const len = width(word.segment);
8787+ // Gracefully handle trailing punctuation by ensuring it is always joined with the previous word
8888+ if (len === 1 && word.segment.trim() && /\W/.test(word.segment)) {
8989+ part += word.segment;
9090+ i += 1
9191+ continue;
9292+ }
9393+ if ((i + len) > cols - 1) {
9494+ parts.push(part.trim())
9595+ i = 0
9696+ part = ''
9797+ }
9898+ part += `${prefix}${word.segment}${suffix}`
9999+ i += len;
100100+ }
101101+ }
102102+103103+ const re = ansiRegex();
104104+ let lastIndex = 0;
105105+ let lastPart = "";
106106+ let m;
107107+ while (m = re.exec(str)) {
108108+ const chunk = m.input.slice(lastIndex, m.index);
109109+ const [prefix, suffix] = [lastPart, m[0]]
110110+ if (prefix) {
111111+ const [pCode, sCode] = [Number(prefix.slice(2, -1)), Number(suffix.slice(2, -1))]
112112+ if (sCode > pCode) {
113113+ handle(chunk, { prefix, suffix });
114114+ } else {
115115+ handle(chunk)
116116+ }
117117+ } else {
118118+ handle(chunk)
119119+ }
120120+ lastPart = m[0];
121121+ lastIndex = m.index + m[0].length;
122122+ }
123123+ const chunk = str.slice(lastIndex);
124124+ handle(chunk);
125125+ parts.push(part);
126126+127127+ return parts.map(p => /^\s{2,}/.test(p) ? p : p.trimStart()).join('\n');
128128+}
129129+
···77The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8899THE 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.
1010-1111----
1212-1313-`ansi-regex` is adapted from https://github.com/chalk/ansi-regex
1414-1515-MIT License
1616-1717-Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
1818-1919-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:
2020-2121-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
2222-2323-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.