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
2 changes: 1 addition & 1 deletion examples/changesets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function main() {
}
);

const message = await p.text({
const message = await p.multiline({
placeholder: 'Summary',
message: 'Please enter a summary for this change',
});
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export type { DateFormat, DateOptions, DateParts } from './prompts/date.js';
export { default as DatePrompt } from './prompts/date.js';
export type { GroupMultiSelectOptions } from './prompts/group-multiselect.js';
export { default as GroupMultiSelectPrompt } from './prompts/group-multiselect.js';
export type { MultiLineOptions } from './prompts/multi-line.js';
export { default as MultiLinePrompt } from './prompts/multi-line.js';
export type { MultiSelectOptions } from './prompts/multi-select.js';
export { default as MultiSelectPrompt } from './prompts/multi-select.js';
export type { PasswordOptions } from './prompts/password.js';
Expand Down
118 changes: 118 additions & 0 deletions packages/core/src/prompts/multi-line.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { styleText } from 'node:util';
import { type Action, settings } from '../utils/index.js';
import Prompt, { type PromptOptions } from './prompt.js';

export interface MultiLineOptions extends PromptOptions<string, MultiLinePrompt> {
placeholder?: string;
defaultValue?: string;
}

export default class MultiLinePrompt extends Prompt<string> {
get valueWithCursor() {
if (this.state === 'submit') {
return this.userInput;
}
const userInput = this.userInput;
if (this.cursor >= userInput.length) {
return `${userInput}█`;
}
const s1 = userInput.slice(0, this.cursor);
const [s2, ...s3] = userInput.slice(this.cursor);
return `${s1}${styleText('inverse', s2)}${s3.join('')}`;
}
get cursor() {
return this._cursor;
}
insertAtCursor(char: string) {
if (this.userInput.length === 0) {
this._setUserInput(char);
return;
}
this._setUserInput(
this.userInput.substr(0, this.cursor) + char + this.userInput.substr(this.cursor)
);
}
handleCursor(key?: Action) {
const text = this.value ?? '';
const lines = text.split('\n');
const beforeCursor = text.substr(0, this.cursor);
const currentLine = beforeCursor.split('\n').length - 1;
const lineStart = beforeCursor.lastIndexOf('\n');
const cursorOffet = this.cursor - lineStart;
switch (key) {
case 'up':
if (currentLine === 0) {
this._cursor = 0;
return;
}
this._cursor +=
-cursorOffet -
lines[currentLine - 1].length +
Math.min(lines[currentLine - 1].length, cursorOffet - 1);
return;
case 'down':
if (currentLine === lines.length - 1) {
this._cursor = text.length;
return;
}
this._cursor +=
-cursorOffet +
1 +
lines[currentLine].length +
Math.min(lines[currentLine + 1].length + 1, cursorOffet);
return;
case 'left':
this._cursor = Math.max(0, this._cursor - 1);
return;
case 'right':
this._cursor = Math.min(text.length, this._cursor + 1);
return;
}
}
constructor(opts: MultiLineOptions) {
super(opts, false);

this.on('key', (char, key) => {
if (key?.name && settings.actions.has(key.name as Action)) {
this.handleCursor(key.name as Action);
}
if (char === '\r') {
this.insertAtCursor('\n');
this._cursor++;
return;
}
if (char === '\u0004') {
return;
}
if (key?.name === 'backspace' && this.cursor > 0) {
this._setUserInput(
this.userInput.substr(0, this.cursor - 1) + this.userInput.substr(this.cursor)
);
this._cursor--;
return;
}
if (key?.name === 'delete' && this.cursor < this.userInput.length) {
this._setUserInput(
this.userInput.substr(0, this.cursor) + this.userInput.substr(this.cursor + 1)
);
return;
}
if (char) {
this.insertAtCursor(char ?? '');
this._cursor++;
}
});

this.on('userInput', (input) => {
this._setValue(input);
});
this.on('finalize', () => {
if (!this.value) {
this.value = opts.defaultValue;
}
if (this.value === undefined) {
this.value = '';
}
});
}
}
6 changes: 5 additions & 1 deletion packages/core/src/prompts/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
diffLines,
getRows,
isActionKey,
isSameKey,
setRawMode,
settings,
} from '../utils/index.js';
Expand All @@ -23,6 +24,7 @@ export interface PromptOptions<TValue, Self extends Prompt<TValue>> {
output?: Writable;
debug?: boolean;
signal?: AbortSignal;
submitKey?: Key;
}

export default class Prompt<TValue> {
Expand All @@ -37,6 +39,7 @@ export default class Prompt<TValue> {
private _prevFrame = '';
private _subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();
protected _cursor = 0;
private _submitKey: Key;

public state: ClackState = 'initial';
public error = '';
Expand All @@ -53,6 +56,7 @@ export default class Prompt<TValue> {
this._render = render.bind(this);
this._track = trackValue;
this._abortSignal = signal;
this._submitKey = options.submitKey ?? { name: 'return' };

this.input = input;
this.output = output;
Expand Down Expand Up @@ -225,7 +229,7 @@ export default class Prompt<TValue> {
// Call the key event handler and emit the key event
this.emit('key', char?.toLowerCase(), key);

if (key?.name === 'return') {
if (isSameKey(key, this._submitKey)) {
if (this.opts.validate) {
const problem = this.opts.validate(this.value);
if (problem) {
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ export function wrapTextWithPrefix(
output: Writable | undefined,
text: string,
prefix: string,
startPrefix: string = prefix
startPrefix: string = prefix,
lineFormatter?: (line: string, index: number) => string
): string {
const columns = getColumns(output ?? stdout);
const wrapped = wrapAnsi(text, columns - prefix.length, {
Expand All @@ -112,7 +113,8 @@ export function wrapTextWithPrefix(
const lines = wrapped
.split('\n')
.map((line, index) => {
return `${index === 0 ? startPrefix : prefix}${line}`;
const lineString = lineFormatter ? lineFormatter(line, index) : line;
return `${index === 0 ? startPrefix : prefix}${lineString}`;
})
.join('\n');
return lines;
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/utils/settings.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Key } from 'node:readline';

const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel'] as const;
export type Action = (typeof actions)[number];

Expand Down Expand Up @@ -189,3 +191,15 @@ export function isActionKey(key: string | Array<string | undefined>, action: Act
}
return false;
}

export function isSameKey(actual: Key | undefined, expected: Key): boolean {
if (actual === undefined) {
return false;
}
return (
actual.name === expected.name &&
(actual.ctrl ?? false) === (expected.ctrl ?? false) &&
(actual.meta ?? false) === (expected.meta ?? false) &&
(actual.shift ?? false) === (expected.shift ?? false)
);
}
1 change: 1 addition & 0 deletions packages/prompts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from './group-multi-select.js';
export * from './limit-options.js';
export * from './log.js';
export * from './messages.js';
export * from './multi-line.js';
export * from './multi-select.js';
export * from './note.js';
export * from './password.js';
Expand Down
59 changes: 59 additions & 0 deletions packages/prompts/src/multi-line.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { styleText } from 'node:util';
import { MultiLinePrompt, wrapTextWithPrefix } from '@clack/core';
import { S_BAR, S_BAR_END, symbol } from './common.js';
import type { TextOptions } from './text.js';

export type MultiLineOptions = TextOptions;

export const multiline = (opts: MultiLineOptions) => {
return new MultiLinePrompt({
validate: opts.validate,
placeholder: opts.placeholder,
defaultValue: opts.defaultValue,
initialValue: opts.initialValue,
submitKey: { name: 'd', ctrl: true },
render() {
const title = `${styleText('gray', S_BAR)}\n${symbol(this.state)} ${opts.message}\n`;
const placeholder = opts.placeholder
? styleText('inverse', opts.placeholder[0]) + styleText('dim', opts.placeholder.slice(1))
: styleText(['inverse', 'hidden'], '_');
const value = `${!this.value ? placeholder : this.valueWithCursor}`;
switch (this.state) {
case 'error': {
const lines = wrapTextWithPrefix(
opts.output,
value,
`${styleText('yellow', S_BAR)} `,
undefined,
(str) => styleText('yellow', str)
);
return `${title.trim()}${lines}\n${styleText('yellow', S_BAR_END)} ${styleText('yellow', this.error)}\n`;
}
case 'submit': {
const lines = wrapTextWithPrefix(
opts.output,
this.value ?? '',
`${styleText('gray', S_BAR)} `,
undefined,
(str) => styleText('dim', str)
);
return `${title}${lines}`;
}
case 'cancel': {
const lines = wrapTextWithPrefix(
opts.output,
value,
`${styleText('gray', S_BAR)} `,
undefined,
(str) => styleText(['strikethrough', 'dim'], str)
);
return `${title}${lines}${this.value?.trim() ? `\n${styleText('gray', S_BAR)}` : ''}`;
}
default: {
const lines = wrapTextWithPrefix(opts.output, value, `${styleText('cyan', S_BAR)} `);
return `${title}${lines}\n${styleText('cyan', S_BAR_END)}\n`;
}
}
},
}).prompt() as Promise<string | symbol>;
};
Loading