Docs / Packages / Prompts
Prompts
Introduction
Prompts is a package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation.
Prompts is perfect for accepting user input in your Artisan console commands, but it may also be used in any command-line TypeScript project.
Note
Prompts supports macOS, Linux, and Windows with WSL. For more information, please see our documentation on unsupported environments & fallbacks.
Installation
Prompts is already included with laraflare.
Every prompt is a function you import from @laraflare/prompts. Each function takes its arguments in order, or a single object when you would rather name them (the examples below use the object form), and returns a promise, so call it with await:
import { text } from '@laraflare/prompts';
const name = await text('What is your name?');
Available Prompts
Text
The text function will prompt the user with the given question, accept their input, and then return it:
import { text } from '@laraflare/prompts';
const name = await text('What is your name?');
You may also include placeholder text, a default value, and an informational hint:
const name = await text({
label: 'What is your name?',
placeholder: 'E.g. Taylor Otwell',
default: user?.name,
hint: 'This will be displayed on your profile.',
});
Required Values
If you require a value to be entered, you may pass the required argument:
const name = await text({
label: 'What is your name?',
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const name = await text({
label: 'What is your name?',
required: 'Your name is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const name = await text({
label: 'What is your name?',
validate: (value: string) => {
if (value.length < 3) return 'The name must be at least 3 characters.';
if (value.length > 255) return 'The name must not exceed 255 characters.';
return null;
},
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Alternatively, you may leverage the power of laraflare's validator. To do so, provide an object containing the name of the attribute and the desired validation rules to the validate argument:
const name = await text({
label: 'What is your name?',
validate: { name: 'required|max:255|unique:users' },
});
Textarea
The textarea function will prompt the user with the given question, accept their input via a multi-line textarea, and then return it:
import { textarea } from '@laraflare/prompts';
const story = await textarea('Tell me a story.');
You may also include placeholder text, a default value, and an informational hint:
const story = await textarea({
label: 'Tell me a story.',
placeholder: 'This is a story about...',
hint: 'This will be displayed on your profile.',
});
Required Values
If you require a value to be entered, you may pass the required argument:
const story = await textarea({
label: 'Tell me a story.',
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const story = await textarea({
label: 'Tell me a story.',
required: 'A story is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const story = await textarea({
label: 'Tell me a story.',
validate: (value: string) => {
if (value.length < 250) return 'The story must be at least 250 characters.';
if (value.length > 10000) return 'The story must not exceed 10,000 characters.';
return null;
},
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Alternatively, you may leverage the power of laraflare's validator. To do so, provide an object containing the name of the attribute and the desired validation rules to the validate argument:
const story = await textarea({
label: 'Tell me a story.',
validate: { story: 'required|max:10000' },
});
Number
The number function will prompt the user with the given question, accept their numeric input, and then return it. The number function allows the user to use the up and down arrow keys to manipulate the number:
import { number } from '@laraflare/prompts';
const copies = await number('How many copies would you like?');
You may also include placeholder text, a default value, and an informational hint:
const copies = await number({
label: 'How many copies would you like?',
placeholder: '5',
default: '1',
hint: 'This will determine how many copies to create.',
});
Required Values
If you require a value to be entered, you may pass the required argument:
const copies = await number({
label: 'How many copies would you like?',
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const copies = await number({
label: 'How many copies would you like?',
required: 'A number of copies is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const copies = await number({
label: 'How many copies would you like?',
validate: (value: number) => {
if (value < 1) return 'At least one copy is required.';
if (value > 100) return 'You may not create more than 100 copies.';
return null;
},
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Alternatively, you may leverage the power of laraflare's validator. To do so, provide an object containing the name of the attribute and the desired validation rules to the validate argument:
const copies = await number({
label: 'How many copies would you like?',
validate: { copies: 'required|integer|min:1|max:100' },
});
Password
The password function is similar to the text function, but the user's input will be masked as they type in the console. This is useful when asking for sensitive information such as passwords:
import { password } from '@laraflare/prompts';
const secret = await password('What is your password?');
You may also include placeholder text and an informational hint:
const secret = await password({
label: 'What is your password?',
placeholder: 'password',
hint: 'Minimum 8 characters.',
});
Required Values
If you require a value to be entered, you may pass the required argument:
const secret = await password({
label: 'What is your password?',
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const secret = await password({
label: 'What is your password?',
required: 'The password is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const secret = await password({
label: 'What is your password?',
validate: (value: string) => (value.length < 8 ? 'The password must be at least 8 characters.' : null),
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Alternatively, you may leverage the power of laraflare's validator. To do so, provide an object containing the name of the attribute and the desired validation rules to the validate argument:
const secret = await password({
label: 'What is your password?',
validate: { password: 'min:8' },
});
Confirm
If you need to ask the user for a "yes or no" confirmation, you may use the confirm function. Users may use the arrow keys or press y or n to select their response. This function will return either true or false.
import { confirm } from '@laraflare/prompts';
const confirmed = await confirm('Do you accept the terms?');
You may also include a default value, customized wording for the "Yes" and "No" labels, and an informational hint:
const confirmed = await confirm({
label: 'Do you accept the terms?',
default: false,
yes: 'I accept',
no: 'I decline',
hint: 'The terms must be accepted to continue.',
});
Requiring "Yes"
If necessary, you may require your users to select "Yes" by passing the required argument:
const confirmed = await confirm({
label: 'Do you accept the terms?',
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const confirmed = await confirm({
label: 'Do you accept the terms?',
required: 'You must accept the terms to continue.',
});
Select
If you need the user to select from a predefined set of choices, you may use the select function:
import { select } from '@laraflare/prompts';
const role = await select({
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner'],
});
You may also specify the default choice and an informational hint:
const role = await select({
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner'],
default: 'Owner',
hint: 'The role may be changed at any time.',
});
You may also pass an object to the options argument to have the selected key returned instead of its value:
const role = await select({
label: 'What role should the user have?',
options: {
member: 'Member',
contributor: 'Contributor',
owner: 'Owner',
},
default: 'owner',
});
Up to five options will be displayed before the list begins to scroll. You may customize this by passing the scroll argument:
const category = await select({
label: 'Which category would you like to assign?',
options: Object.fromEntries((await Category.all()).map((category) => [category.id, category.name])),
scroll: 10,
});
Secondary Information
The info argument may be used to display additional information about the currently highlighted option. When a function is provided, it will receive the value of the currently highlighted option and should return a string or null:
const role = await select({
label: 'What role should the user have?',
options: {
member: 'Member',
contributor: 'Contributor',
owner: 'Owner',
},
info: (value) => {
switch (value) {
case 'member': return 'Can view and comment.';
case 'contributor': return 'Can view, comment, and edit.';
case 'owner': return 'Full access to all resources.';
default: return null;
}
},
});
You may also pass a static string to the info argument if the information does not depend on the highlighted option:
const role = await select({
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner'],
info: 'The role may be changed at any time.',
});
Additional Validation
Unlike other prompt functions, the select function doesn't accept the required argument because it is not possible to select nothing. However, you may pass a function to the validate argument if you need to present an option but prevent it from being selected:
const role = await select({
label: 'What role should the user have?',
options: {
member: 'Member',
contributor: 'Contributor',
owner: 'Owner',
},
validate: async (value: string) =>
value === 'owner' && (await User.where('role', 'owner').exists())
? 'An owner already exists.'
: null,
});
If the options argument is an object, then the function will receive the selected key, otherwise it will receive the selected value. The function may return an error message, or null if the validation passes.
Multi-select
If you need the user to be able to select multiple options, you may use the multiselect function:
import { multiselect } from '@laraflare/prompts';
const permissions = await multiselect({
label: 'What permissions should be assigned?',
options: ['Read', 'Create', 'Update', 'Delete'],
});
You may also specify default choices and an informational hint:
const permissions = await multiselect({
label: 'What permissions should be assigned?',
options: ['Read', 'Create', 'Update', 'Delete'],
default: ['Read', 'Create'],
hint: 'Permissions may be updated at any time.',
});
You may also pass an object to the options argument to return the selected options' keys instead of their values:
const permissions = await multiselect({
label: 'What permissions should be assigned?',
options: {
read: 'Read',
create: 'Create',
update: 'Update',
delete: 'Delete',
},
default: ['read', 'create'],
});
Up to five options will be displayed before the list begins to scroll. You may customize this by passing the scroll argument:
const categories = await multiselect({
label: 'What categories should be assigned?',
options: Object.fromEntries((await Category.all()).map((category) => [category.id, category.name])),
scroll: 10,
});
Secondary Information
The info argument may be used to display additional information about the options. It is a string, or a function that returns one:
const permissions = await multiselect({
label: 'What permissions should be assigned?',
options: {
read: 'Read',
create: 'Create',
update: 'Update',
delete: 'Delete',
},
info: 'Permissions may be updated at any time.',
});
Requiring a Value
By default, the user may select zero or more options. You may pass the required argument to enforce one or more options instead:
const categories = await multiselect({
label: 'What categories should be assigned?',
options: Object.fromEntries((await Category.all()).map((category) => [category.id, category.name])),
required: true,
});
If you would like to customize the validation message, you may provide a string to the required argument:
const categories = await multiselect({
label: 'What categories should be assigned?',
options: Object.fromEntries((await Category.all()).map((category) => [category.id, category.name])),
required: 'You must select at least one category',
});
Additional Validation
You may pass a function to the validate argument if you need to present an option but prevent it from being selected:
const permissions = await multiselect({
label: 'What permissions should the user have?',
options: {
read: 'Read',
create: 'Create',
update: 'Update',
delete: 'Delete',
},
validate: (values: string[]) =>
!values.includes('read') ? 'All users require the read permission.' : null,
});
If the options argument is an object then the function will receive the selected keys, otherwise it will receive the selected values. The function may return an error message, or null if the validation passes.
Suggest
The suggest function can be used to provide auto-completion for possible choices. The user can still provide any answer, regardless of the auto-completion hints:
import { suggest } from '@laraflare/prompts';
const name = await suggest('What is your name?', ['Taylor', 'Dayle']);
Alternatively, you may pass a function as the second argument to the suggest function. The function will be called each time the user types an input character. The function should accept a string parameter containing the user's input so far and return an array of options for auto-completion:
const name = await suggest({
label: 'What is your name?',
options: (value: string) =>
['Taylor', 'Dayle'].filter((name) => name.toLowerCase().includes(value.toLowerCase())),
});
You may also include placeholder text, a default value, and an informational hint:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
placeholder: 'E.g. Taylor',
default: user?.name,
hint: 'This will be displayed on your profile.',
});
Secondary Information
The info argument may be used to display additional information about the currently highlighted option. When a function is provided, it will receive the value of the currently highlighted option and should return a string or null:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
info: (value: string) => {
switch (value) {
case 'Taylor': return 'Administrator';
case 'Dayle': return 'Contributor';
default: return null;
}
},
});
Required Values
If you require a value to be entered, you may pass the required argument:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
required: 'Your name is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
validate: (value: string) => {
if (value.length < 3) return 'The name must be at least 3 characters.';
if (value.length > 255) return 'The name must not exceed 255 characters.';
return null;
},
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Alternatively, you may leverage the power of laraflare's validator. To do so, provide an object containing the name of the attribute and the desired validation rules to the validate argument:
const name = await suggest({
label: 'What is your name?',
options: ['Taylor', 'Dayle'],
validate: { name: 'required|min:3|max:255' },
});
Search
If you have a lot of options for the user to select from, the search function allows the user to type a search query to filter the results before using the arrow keys to select an option:
import { search } from '@laraflare/prompts';
const id = await search({
label: 'Search for the user that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
});
The function will receive the text that has been typed by the user so far and must return options. If you return an object then the selected option's key will be returned, otherwise its value will be returned instead.
When filtering an array where you intend to return the value, return an array (not an object) so the options stay a list:
const names = ['Taylor', 'Abigail'];
const selected = await search({
label: 'Search for the user that should receive the mail',
options: (value: string) =>
names.filter((name) => name.toLowerCase().includes(value.toLowerCase())),
});
You may also include placeholder text and an informational hint:
const id = await search({
label: 'Search for the user that should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
hint: 'The user will receive an email immediately.',
});
Up to five options will be displayed before the list begins to scroll. You may customize this by passing the scroll argument:
const id = await search({
label: 'Search for the user that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
scroll: 10,
});
Additional Validation
If you would like to perform additional validation logic, you may pass a function to the validate argument:
const id = await search({
label: 'Search for the user that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
validate: async (value: number | string) => {
const user = await User.findOrFail(value);
if (user.opted_out) {
return 'This user has opted-out of receiving mail.';
}
return null;
},
});
If the options function returns an object, then the validate function will receive the selected key, otherwise, it will receive the selected value. The function may return an error message, or null if the validation passes.
Multi-search
If you have a lot of searchable options and need the user to be able to select multiple items, the multisearch function allows the user to type a search query to filter the results before using the arrow keys and space-bar to select options:
import { multisearch } from '@laraflare/prompts';
const ids = await multisearch(
'Search for users who should receive the mail',
async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
);
The function will receive the text that has been typed by the user so far and must return options. If you return an object then the selected options' keys will be returned; otherwise, their values will be returned instead.
When filtering an array where you intend to return the values, return an array (not an object) so the options stay a list:
const names = ['Taylor', 'Abigail'];
const selected = await multisearch({
label: 'Search for users who should receive the mail',
options: (value: string) =>
names.filter((name) => name.toLowerCase().includes(value.toLowerCase())),
});
You may also include placeholder text and an informational hint:
const ids = await multisearch({
label: 'Search for users who should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
hint: 'The user will receive an email immediately.',
});
Up to five options will be displayed before the list begins to scroll. You may customize this by providing the scroll argument:
const ids = await multisearch({
label: 'Search for the users that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
scroll: 10,
});
Secondary Information
The info argument may be used to display additional information about the currently highlighted option. When a function is provided, it will receive the value of the currently highlighted option and should return a string or null:
const ids = await multisearch({
label: 'Search for the users that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
info: (userId) => `User ${userId}`,
});
Requiring a Value
By default, the user may select zero or more options. You may pass the required argument to enforce one or more options instead:
const ids = await multisearch({
label: 'Search for the users that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
required: true,
});
If you would like to customize the validation message, you may also provide a string to the required argument:
const ids = await multisearch({
label: 'Search for the users that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
required: 'You must select at least one user.',
});
Additional Validation
If you would like to perform additional validation logic, you may pass a function to the validate argument:
const ids = await multisearch({
label: 'Search for the users that should receive the mail',
options: async (value: string) =>
value.length > 0
? Object.fromEntries((await User.whereLike('name', `%${value}%`).get()).map((user) => [user.id, user.name]))
: {},
validate: async (values: number[]) => {
const optedOut = await User.whereLike('name', '%a%').findMany(values);
if (optedOut.length > 0) {
return `${optedOut.map((user) => user.name).join(', ')} have opted out.`;
}
return null;
},
});
If the options function returns an object, then the validate function will receive the selected keys; otherwise, it will receive the selected values. The function may return an error message, or null if the validation passes.
Pause
The pause function may be used to display informational text to the user and wait for them to confirm their desire to proceed by pressing the Enter / Return key:
import { pause } from '@laraflare/prompts';
await pause('Press ENTER to continue.');
Autocomplete
The autocomplete function can be used to provide inline auto-completion for possible choices. As the user types, suggestions that match their input will appear as ghost text that can be accepted by pressing Tab or the right arrow key:
import { autocomplete } from '@laraflare/prompts';
const name = await autocomplete({
label: 'What is your name?',
options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'],
});
You may also include placeholder text, a default value, and an informational hint:
const name = await autocomplete({
label: 'What is your name?',
options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'],
placeholder: 'E.g. Taylor',
default: user?.name,
hint: 'Use tab to accept, up/down to cycle.',
});
Dynamic Options
You may also pass a function to dynamically generate options based on the user's input. The function will be called each time the user types a character and should return an array of options for auto-completion:
const file = await autocomplete({
label: 'Which file?',
options: (value: string) =>
files.filter((file) => file.toLowerCase().startsWith(value.toLowerCase())),
});
Required Values
If you require a value to be entered, you may pass the required argument:
const name = await autocomplete({
label: 'What is your name?',
options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'],
required: true,
});
If you would like to customize the validation message, you may also pass a string:
const name = await autocomplete({
label: 'What is your name?',
options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'],
required: 'Your name is required.',
});
Additional Validation
Finally, if you would like to perform additional validation logic, you may pass a function to the validate argument:
const name = await autocomplete({
label: 'What is your name?',
options: ['Taylor', 'Dayle', 'Jess', 'Nuno', 'Tim'],
validate: (value: string) => {
if (value.length < 3) return 'The name must be at least 3 characters.';
if (value.length > 255) return 'The name must not exceed 255 characters.';
return null;
},
});
The function will receive the value that has been entered and may return an error message, or null if the validation passes.
Transforming Input Before Validation
Sometimes you may want to transform the prompt input before validation takes place. For example, you may wish to remove white space from any provided strings. To accomplish this, many of the prompt functions provide a transform argument, which accepts a function:
const name = await text({
label: 'What is your name?',
transform: (value: string) => value.trim(),
validate: (value: string) => {
if (value.length < 3) return 'The name must be at least 3 characters.';
if (value.length > 255) return 'The name must not exceed 255 characters.';
return null;
},
});
Forms
Often, you will have multiple prompts that will be displayed in sequence to collect information before performing additional actions. You may use the form function to create a grouped set of prompts for the user to complete:
import { form } from '@laraflare/prompts';
const responses = await form()
.text({ label: 'What is your name?', required: true })
.password({ label: 'What is your password?', validate: { password: 'min:8' } })
.confirm('Do you accept the terms?')
.submit();
The submit method will return an object containing all of the responses from the form's prompts, keyed by their position. However, you may provide a name for each prompt via the name argument. When a name is provided, the named prompt's response may be accessed via that name:
import { form } from '@laraflare/prompts';
const responses = await form()
.text({ label: 'What is your name?', required: true, name: 'name' })
.password({
label: 'What is your password?',
validate: { password: 'min:8' },
name: 'password',
})
.confirm('Do you accept the terms?')
.submit();
await User.create({
name: responses.name,
password: responses.password,
});
The primary benefit of using the form function is the ability for the user to return to previous prompts in the form using CTRL + U. This allows the user to fix mistakes or alter selections without needing to cancel and restart the entire form.
If you need more granular control over a prompt in a form, you may invoke the add method instead of calling one of the prompt functions directly. The add method is passed all previous responses provided by the user:
import { form, outro, text } from '@laraflare/prompts';
const responses = await form()
.text({ label: 'What is your name?', required: true, name: 'name' })
.add((responses) => text(`How old are you, ${responses.name}?`), 'age')
.submit();
outro(`Your name is ${responses.name} and you are ${responses.age} years old.`);
Informational Messages
The note, info, warning, error, and alert functions may be used to display informational messages:
import { info } from '@laraflare/prompts';
info('Package installed successfully.');
Callouts
The callout function displays a boxed message with a label and content. Callouts are useful for displaying important information that should stand out, such as deployment summaries, error details, or status updates:
import { callout } from '@laraflare/prompts';
callout('Environment Configured', 'Your application is running in production mode with 4 workers.');
You may pass warning or error as the third argument, type, to change the callout's visual style:
callout(
'Deprecation Notice',
'The `--prefer-stable` flag will be removed in v4.0. Use `--stability=stable` instead.',
'warning',
);
callout(
'Database Connection Failed',
'Could not connect to MySQL on 127.0.0.1:3306.',
'error',
);
The fourth argument, info, adds a footer line to the callout, which is useful for displaying metadata like IDs or timestamps:
callout(
'Deployment Summary',
'Your application was deployed to production.',
null,
'deploy-id: d4f8a2c',
);
Rich Content
Instead of passing a string, you may pass an array of strings and elements to build rich, structured callouts. The Element class provides factory methods for creating headings, bulleted lists, numbered lists, key-value lists, and links:
import { callout } from '@laraflare/prompts';
import { Element } from '@laraflare/prompts/Elements/Element';
callout('Deployment Summary', [
'Your application was deployed to production at 2024-03-15 14:32 UTC.',
Element.heading('What Changed'),
Element.bulletedList([
'Migrated 3 pending database migrations',
'Cleared and rebuilt route cache',
'Restarted 4 queue workers',
]),
Element.heading('Next Steps'),
Element.numberedList([
'Verify the health check endpoint at /up',
'Monitor error rates for the next 15 minutes',
'Confirm background jobs are processing',
]),
]);
You may also use Element.keyValueList to display labeled data:
callout('Database Connection Failed', [
'Could not connect to the database server.',
Element.keyValueList({
Host: '127.0.0.1',
Port: '3306',
Database: 'example',
Status: 'Connection refused',
}),
], 'error');
The Element.link method creates a clickable hyperlink in terminals that support OSC 8. You may provide a URL alone, or a URL with a custom label:
callout('Server Health Check', [
'Multiple services are reporting degraded performance.',
Element.heading('Affected Services'),
`Look here: ${Element.link('https://example.com/health', 'Health Dashboard')}`,
Element.link('https://example.com/health'),
]);
If no label is provided, the URL itself will be displayed as the link text.
Tables
The table function makes it easy to display multiple rows and columns of data. All you need to do is provide the column names and the data for the table:
import { table } from '@laraflare/prompts';
table(
['Name', 'Email'],
(await User.all()).map((user) => [user.name, user.email]),
);
Spin
The spin function displays a spinner along with an optional message while executing a specified callback. It serves to indicate ongoing processes and returns the callback's results upon completion:
import { spin } from '@laraflare/prompts';
const response = await spin(
() => fetch('http://example.com'),
'Fetching response...',
);
Progress Bars
For long running tasks, it can be helpful to show a progress bar that informs users how complete the task is. Using the progress function, laraflare will display a progress bar and advance its progress for each iteration over a given iterable value:
import { progress } from '@laraflare/prompts';
const users = await progress(
'Updating users',
await User.all(),
(user) => performTask(user),
);
The progress function acts like a map function and will return an array containing the return value of each iteration of your callback.
The callback may also accept the Progress instance, allowing you to modify the label and hint on each iteration:
const users = await progress(
'Updating users',
await User.all(),
(user, progress) => {
progress
.label(`Updating ${user.name}`)
.hint(`Created on ${user.created_at}`);
return performTask(user);
},
'This may take some time.',
);
Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar via the advance method after processing each item:
const bar = progress('Updating users', 10);
const users = await User.all();
bar.start();
for (const user of users) {
await performTask(user);
bar.advance();
}
bar.finish();
Task
The task function displays a labeled task with a spinner and a scrolling live output area while a given callback is executing. It is ideal for wrapping long-running processes such as dependency installation or deployment scripts, providing real-time visibility into what is happening:
import { task } from '@laraflare/prompts';
await task(
'Installing dependencies',
async (logger) => {
// Long-running process...
},
);
The callback receives a Logger instance that you may use to display log lines, status messages, and streamed text in the task's output area.
Logging Lines
The line method writes a single log line to the task's scrolling output area:
await task(
'Installing dependencies',
async (logger) => {
logger.line('Resolving packages...');
// ...
logger.line('Downloading example/package');
// ...
},
);
Status Messages
You may use the success, warning, and error methods to display status messages. These appear as stable, highlighted messages above the scrolling log area:
await task(
'Deploying application',
async (logger) => {
logger.line('Pulling latest changes...');
// ...
logger.success('Changes pulled!');
logger.line('Running migrations...');
// ...
logger.warning('No new migrations to run.');
logger.line('Clearing cache...');
// ...
logger.success('Cache cleared!');
},
);
Updating the Label
The label method allows you to update the task's label while it is running:
await task(
'Starting deployment...',
async (logger) => {
logger.label('Pulling latest changes...');
// ...
logger.label('Running migrations...');
// ...
logger.label('Clearing cache...');
// ...
},
);
Displaying a Sub-Label
The subLabel method displays a dim line beneath the task's main label, which is useful for communicating ephemeral status such as the step currently in progress. Pass an empty string to clear the sub-label:
await task(
'Deploying',
async (logger) => {
logger.subLabel('Building assets...');
// ...
logger.subLabel('Running migrations...');
// ...
logger.subLabel('');
},
);
You may also provide an initial sub-label as the fifth argument:
await task(
'Deploying',
async (logger) => {
// ...
},
null,
false,
'Preparing...',
);
Streaming Text
For processes that produce output incrementally, such as AI-generated responses, the partial method allows you to stream text word-by-word or chunk-by-chunk. Once the stream is complete, call commitPartial to finalize the output:
await task(
'Generating response...',
async (logger) => {
for (const word of words) {
logger.partial(`${word} `);
}
logger.commitPartial();
},
);
Customizing the Output Limit
By default, the task displays up to 10 lines of scrolling output. You may customize this via the third argument, limit:
await task(
'Installing dependencies',
async (logger) => {
// ...
},
20,
);
Keeping the Summary
By default, the task's output is erased once the callback finishes. If you would like to keep the status messages on screen after the task has completed, you may pass true as the fourth argument, keepSummary:
await task(
'Deploying',
async (logger) => {
logger.success('Assets built');
// ...
logger.success('Migrations complete');
},
null,
true,
);
Stream
The stream function displays text that streams into the terminal, ideal for displaying AI-generated content or any text that arrives incrementally:
import { stream } from '@laraflare/prompts';
const output = stream();
for (const word of words) {
output.append(`${word} `);
await new Promise((resolve) => setTimeout(resolve, 25)); // Simulate delay between chunks...
}
output.close();
The append method adds text to the stream, rendering it with a gradual fade-in effect. When all content has been streamed, call the close method to finalize the output and restore the cursor.
Terminal Title
The title function updates the title of the user's terminal window or tab:
import { title } from '@laraflare/prompts';
title('Installing Dependencies');
To reset the terminal title back to its default, pass an empty string:
title('');
Clearing the Terminal
The clear function may be used to clear the user's terminal:
import { clear } from '@laraflare/prompts';
clear();
Terminal Considerations
Terminal Width
If the length of any label, option, or validation message exceeds the number of "columns" in the user's terminal, it will be automatically truncated to fit. Consider minimizing the length of these strings if your users may be using narrower terminals. A typically safe maximum length is 74 characters to support an 80-character terminal.
Terminal Height
For any prompts that accept the scroll argument, the configured value will automatically be reduced to fit the height of the user's terminal, including space for a validation message.
Unsupported Environments and Fallbacks
Prompts supports macOS, Linux, and Windows with WSL. Outside of WSL, Windows is not currently supported.
For this reason, Prompts supports falling back to an alternative implementation such as a plain question asked through the command's own ask method.
Note
When using Prompts inside a laraflare command, fallbacks for each prompt have been configured for you and will be automatically enabled in unsupported environments.
Fallback Conditions
If you need to customize when the fallback behavior is used, you may pass a boolean to the fallbackWhen static method on the Prompt class:
import { Prompt } from '@laraflare/prompts';
Prompt.fallbackWhen(
!input.isInteractive() || process.platform === 'win32',
);
Fallback Behavior
If you need to customize the fallback behavior, you may pass a function to the fallbackUsing static method on each prompt class:
import { TextPrompt } from '@laraflare/prompts';
TextPrompt.fallbackUsing(async (prompt: TextPrompt) => {
const answer = (await readLine(prompt.label)) || prompt.default || null;
if (prompt.required && answer === null) {
throw new Error(typeof prompt.required === 'string' ? prompt.required : 'Required.');
}
if (typeof prompt.validate === 'function') {
const error = await prompt.validate(answer ?? '');
if (error) {
throw new Error(error);
}
}
return answer;
});
Fallbacks must be configured individually for each prompt class. The function will receive an instance of the prompt class and must return an appropriate type for the prompt.
Testing
laraflare provides a variety of methods for testing that your command displays the expected Prompt messages:
test('report generation', async () => {
await this.artisan('report:generate')
.expectsPromptsInfo('Welcome to the application!')
.expectsPromptsWarning('This action cannot be undone')
.expectsPromptsError('Something went wrong')
.expectsPromptsAlert('Important notice!')
.expectsPromptsIntro('Starting process...')
.expectsPromptsOutro('Process completed!')
.expectsPromptsTable(
['Name', 'Email'],
[
['Taylor Otwell', 'taylor@example.com'],
['Jason Beggs', 'jason@example.com'],
],
)
.assertExitCode(0);
});