UNPKG

web-gash

Version:

Terminal web game framework in React.

815 lines (804 loc) 41.4 kB
/// <reference types="react" /> import React$1 from 'react'; declare enum AutoCompleteResultType { /** The input already fully matches the attempted solution. */ AlreadyMatching = 0, /** The input can be auto-completed and there is only on choice. */ SingleMatchFound = 1, /** The input can be auto-completed but there are multiple options. */ MultipleMatchesFound = 2, /** The input does not match the attempted solution. */ NotMatching = 3 } /** Result of the auto-completion. */ interface AutoCompleteResult { /** Type of the result. */ type: AutoCompleteResultType; /** Contains the furthest match between the input and the attempted solution. */ fixedValue: string; } /** * Reason for a parsing failure. */ declare enum ParsingFailureReason { /** The input line does not correspond to the command. */ WrongCommand = 0, /** A mandatory parameter missing in the input line for this command. */ MissingParam = 1, /** The input line contains an option unknown by the command. */ UnrecognizedOption = 2 } /** * Result of parsing player's input line by a command. */ interface ParsingResult { /** Whether the parsing was successfully. */ success: boolean; /** If `success` is `false` the reason for the failure */ failureReason?: ParsingFailureReason; /** Name of the command that matches the input line. */ command?: string; } /** * Interface which defines a command. * * @remarks * Commands are the main way player interacts with Gash game. * Commands must be register with `Gash.registerCommand` in order to be recognized by Gash. */ interface ICommand { /** * Name of the command as used to call it. * * @remarks * It has to be one word, no white-spaces. Lowercase is preferred. * * @returns Name of the command */ name: string; /** * Triggered when player commits a new input line. * * @remarks * Used to determine whether the input line matches this command and execute it. * Commands must return `ParsingResult.success` as `false` if the input line does not match their syntax. * If the line matches the syntax, i.e. parsing was successful, the command should execute its functionality in the parse function. * It is recommended to use `CommandParser` to implement this function. * * @param line Line player submitted. * * @returns Result of the parsing, see `ParsingResult`. */ parse(line: string): ParsingResult; /** * Triggered when player attempts to auto-complete a line. * * @remarks * Used to auto-complete an input line that is starting to match this command or its parameters or options. * It is recommended to use `CommandAutoCompleter` to implement this function. * * @param line Line the player is attempting to auto-complete. * * @returns Result of the auto-completion, see `AutoCompleteResult`. */ autocomplete(line: string): AutoCompleteResult; /** * Triggered when player calls built-in `man` command on this command. * * @remarks * It is expected to print a manual page describing the command and how to use it. * It is recommended to use `writeManPage` function to implement this method. */ printManPage(): void; /** * Triggered when player calls built-in `list` command. * * @remarks * If this function returns `true` this command will be included in the list of commands. * Result of this call can depend on the current game state. * * @returns Whether the command should be listed */ available(): boolean; } /** * Interface which defines a keyword. * * @remarks * Keywords are mechanics, resources or entities that are important to the gameplay but are not invocable as commands. They are often parameters for command calls. * Keywords must be register with `Gash.registerKeyword` in order to be recognized by Gash. * Keywords only direct interaction with Gash library is through built-in `man` command but `Parser` methods facilitate easy auto-completion and parsing of keywords during command calls. * See `IKeywordGroup` for keyword groups that improve `man` command output even further. */ interface IKeyword { /** * Name of the keyword that will be checked when `man` command is called with a parameter. * * @returns Name of the keyword */ name(): string; /** * Triggered when player calls built-in `man` command on this keyword. * * @remarks * It is expected to print a manual page describing this keyword. */ printManPage(): void; } /** * Interface which defines a keyword group. * * @remarks * Useful approach for defining keywords is a common class that implements the `IKeyword` interface, whose instances will share the functionality, styling and be all registered to Gash. It is common in Gash games to use coloring to draw attention of the player and so naturally all these keywords instance of the common class might share color. * This is where keyword group becomes useful as it can tell built-in `man` command such group of keywords exist and when `man` command is called on `man` (`man man`) it can inform player about the existence of all these keywords that can be target of `man` command. */ interface IKeywordGroup { /** Common name of the keyword group that will be displayed in one of the `man man` synopsis lines. */ placeholderName: string; /** CSS color representing the keyword group that will be applied to `placeholderName` as background color n the `man man` synopsis lines and to `colorName` as text color in description lines. */ color: string; /** Name of the `color` that will be displayed in the `man man` description. */ colorName: string; } /** Optional properties of the terminal's prompt. */ interface PromptProps { /** * Prompt text, i.e. text that will be rendered in the input line before users input. Defaults to `$ `. */ promptText?: string; } /** Optional properties of the terminal's cursor. */ interface CursorProps { /** * Symbol that will represent the cursor. Defaults to `_`. */ symbol?: string; /** * How many times per second the cursor will blink meaning, i.e. toggle it's visibility. Defaults to 3 or visibility flip every 1.0/3.0 seconds. */ blinkPerSecond?: number; /** * Whether to display the cursor under the text. Implemented via `position: 'absolute'`. Defaults to true. */ underText?: boolean; } /** * Main entry point to Gash library. */ interface IGash { /** * Initialize the Gash library. * * @remarks * Should be called during the application initialization, e.g. in index.tsx or index.js before `ReactDOM.render`. * Note that the Terminal React component might not be mounted immediately after this call. To write any introductory lines you can use `IGash.onTerminalMounted` event. * * @param registerBuiltInCommands Whether the built-in commands `list` and `man` should be registered on init. Defaults to `true`. */ init(registerBuiltInCommands?: boolean): void; /** * Register a command to be recognized by Gash. * * @remarks * Commands must be registered in order for them to be parsed after player submits an input, be listed in `list` command output and their manual page displayed when `man` command is called on them. * * @param command User-created command */ registerCommand(command: ICommand): void; /** * Register a keyword to be recognized by Gash. * * @remarks * Keywords must be register in order to have their manual page displayed when `man` command is called on them. * * @param keyword User-created keyword */ registerKeyword(keyword: IKeyword): void; /** * Register a keyword group to be recognized by Gash. * * @remarks * Keyword groups are displayed in manual page of `man` command (`man man`). See `IKeywordGroup` for more information. * @param keywordGroup User-created keyword group */ registerKeywordGroup(keywordGroup: IKeywordGroup): void; /** * Outputs line to the terminal. * * @param line React component to add to the terminal. It is recommended to use `<Line>` component. */ writeLine(line: JSX.Element): void; /** * Outputs a temporary line to the terminal there are meant to be displayed for limited amount of time. * * @remarks * Temporary lines are always displayed below the regular lines. * There is a limited number of "slots" for temporary lines, albeit dynamically set, which allows for overwriting existing lines. This is especially useful for animated lines. * Temporary lines can be quickly cleared with `Gash.clearTempLines`. * Can be paired with `Gash.enableInput(false)` to give an impression of time passing. * * @param line React component to add to the terminal. It is recommended to use `<Line>` component. * @param slot "Row" index to write the line to. If a line with this index was already written before, it is overwritten. Otherwise array holding the temporary lines is extended to encompass the `slot` index and filled with empty lines if necessary. */ writeTempLine(line: JSX.Element, slot: number): void; /** * Clear all temporary lines, removing them from the terminal. */ clearTempLines(): void; /** * Disables receiving player's input and hides the input line with prompt and cursor. * * @remarks * The input starts enabled upon Gash initialization. * Player has no built-in way to re-enabled a disabled input so it is best disabled only temporarily. * Can be useful for giving impression of time passing together with animated temporary lines. */ disableInput(): void; /** * Enables receiving the player's input and shows the input line with prompt and cursor. * * @remarks * The input starts enabled upon Gash initialization. */ enableInput(): void; /** * Enables user to listen to 'raw' input events before they are processed by Gash and optionally intercept them. * * @remarks * Before Gash will process an input event, the passed callback will be called and depending on the return value of the callback, the processing will either stop there or continue to Gash. * Note that this will work even when input has been disabled with `disableInput()`. In that case Gash won't process the input no matter the callback return value. * Calling this function repeatedly will overwrite the callback meaning there is only one routing at a time. * * @param inputCallback Callback that will called each time Gash receives an input event. The `event` is 'raw' browser `KeyboardEvent` (see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent). The return value is whether to prevent Gash from processing the event further - `true` - or not - `false`. */ routeInput(inputCallback: (event: KeyboardEvent) => boolean): void; /** * Disables listening to 'raw' input events before they are processed by Gash. * * @remarks * Clears any routing set-up with `routeInput`. The passed callback will no longer be called. */ removeInputRouting(): void; /** * Writes a standardized manual page for a command. * * @remarks * The output has following structure and is properly formatted. * Manual page for command `command.name()` * NAME * `command.name()` * SYNOPSIS * `synopsisLines` * DESCRIPTION * `descriptionLines` * OPTIONS (if `optionsLines` are provided) * `optionsLines` * * The built-in commands `man` and `list` use this function. * Note that the `synopsisLines`, `descriptionLines` or `optionsLines` elements are cloned (`React.cloneElement`) prior to being written. Additionally if their `props` do not include `LineProps.tabs`, the cloned element will have the `props.tabs` set to 1 in order to automatically align the lines as show above. * * @param command Command to print manual page for. Its `command.name()` will be used as noted above. * @param synopsisLines Lines that briefly show the syntax of the command. See built-in commands for examples. * @param descriptionLines Lines that describe the command, what it does and any other remarks. * @param optionsLines A Line for each possible option that names it and describes what it does. */ writeManPage(command: ICommand, synopsisLines: JSX.Element[], descriptionLines: JSX.Element[], optionsLines?: JSX.Element[]): void; /** * An event for mounting of the Terminal React component. * * @remarks * Only once the terminal is mounted it is ready to receive and display lines from Gash. * This is ideal for any welcome or introductory messages to the player. * * @param callback Callback function that will be invoked once the terminal has been mounted. */ onTerminalMounted(callback: () => void): void; } /** * Main entry point to the Gash library */ declare const Gash: IGash; /** Optional React properties of the terminal */ interface TerminalProps { /** Properties of the terminal's prompt, see `PromptProps` */ prompt?: PromptProps; /** Properties of the terminal's cursor, see `CursorProps` */ cursor?: CursorProps; } /** * Main React component of the Gash library representing a terminal. * * @remarks * By default it is already styled including taking up the whole window. * The styling is using Inconsolata Google font which is not packed with Gash. You can add it to your project, for example, with the following css link: * `@import url('https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;700&display=swap');` */ declare function Terminal(props: TerminalProps): JSX.Element; interface LineProps { /** * Changes the default content color to be grey. Used by Gash for non-game related message such as man pages. */ systemMessage?: boolean; /** * Optionally align the content by adding space at the beginning of it. Each space is 15px wide. */ tabs?: number; children?: React$1.ReactNode; } /** * Component that formats a single line of output. It is recommended to wrap each `Gash.writeLine` content with this component. */ declare function Line(props: LineProps): JSX.Element; /** Props for BlockTitle component. */ interface BlockTitleProps { /** Primary css color for the main thick block symbols. Defaults to 'white'. */ primaryColor?: string; /** Secondary css color for the depth-giving shadows symbols. Defaults to 'grey'. */ secondaryColor?: string; /** Text to render. Only A-Z, 0-9 and space characters are supported, all others will default to empty space. */ children: string; } /** * Component that renders a text as a big nice-looking block-y text with depth, ideal for the game title. * * @remarks * The text content of this component, that is the props.children, will be transformed to html elements that use various special unicode characters. * Only A-Z, 0-9 and space characters are supported, all others will default to empty space. * The component is not case sensitive for the input but the rendered result always looks like upper case. * There are two colors that can be changed via the props for additional customization. * Design was copied from the 'block' font from an awesome project `cfonts`, a package for sexy fonts in the console: https://github.com/dominikwilkowski/cfonts * * @param props Props of the component that include color stylization and string children content. See `BlockTitleProps`. */ declare function BlockTitle(props: BlockTitleProps): JSX.Element; declare const brown600 = "#6d4c41"; declare const cyan600 = "#00acc1"; declare const deepOrange600 = "#f4511e"; declare const deepPurple400 = "#7e57c2"; declare const green600 = "#43a047"; declare const grey200 = "#eeeeee"; declare const grey600 = "#757575"; declare const indigo400 = "#5c6bc0"; declare const lightBlue600 = "#039be5"; declare const red600 = "#e53935"; declare const yellow600 = "#fdd835"; declare const white0 = "#ffffff"; declare const black900 = "#000000"; interface ColoredProps { /** * Color of the content - foreground - of this component. Implemented using CSS `color` property. */ foreground: string; /** * Background color of the content of this component. Implemented using CSS `backgroundColor`. If not specified the CSS property is not used. Note that default styling of terminal has black background color. */ background?: string; children?: React$1.ReactNode; } /** * Simple component that changes color of its content, optionally changing the background color as well. */ declare function Colored(props: ColoredProps): JSX.Element; /** * Text styled to look as a built-in commands references */ declare function CommandColored(props: { children?: React$1.ReactNode; }): JSX.Element; /** * Creates an input "dialogue" for the player to pick a single option from multiple choices and asynchronously returns the picked choice index. * * @remarks * Player terminal input will be disabled, i.e. `Gash.disableInput`, and routed to the dialogue via `Gash.routeInput`. * The dialogue displays each choice on a new line. Normally choices are prefixed by dot but currently selected choices are colored green and prefixed by dash. Additionally a cursor is displayed on the currently active choice with '>' symbol. * The dialogue includes passed prompt line, controls instruction line, choices lines and optionally an error message line in that order. * Player can navigate the dialogue with up and down arrows, select a choice with Spacebar, confirm the selection with Enter or cancel the dialogue with 'q'. * Additionally player can quickly select and confirm an option if no options are selected with Enter. * Once the player has picked an option all temporary lines are cleared, input routing is removed and terminal input is enabled again. * * @param elements React nodes that represent the choices that player can pick from. Must have length of at least 1. * @param promptLine Line to display at the top of the dialogue. Should describe what is the player picking. * @returns Promise that will resolve with a zero-based index of the choice that the player picked or rejects if the player cancelled the dialogue. */ declare function RadioInput(elements: React.ReactNodeArray, promptLine: JSX.Element): Promise<number>; /** * Creates an input "dialogue" for the player to pick a single option from multiple choices and asynchronously returns the picked choice. * * @remarks * A convenience generic wrapper around RadioInput that returns datum instead of an index. * This is useful when player has to choose between game entities, often `IKeyword` instances and the game then acts on the picked entity. * Only the `elementsComponents` are passed to the `RadioInput` and therefore rendered to the screen. On the other hand, `elements` are only used when resolving the promise. * * @param elements Choices that player is picking from. Must have the same length as `elementsComponents`. Must have length of at least 1. * @param elementsComponents React nodes that represent the choices that player can pick from. Must have the same length as `elements`. * @param promptLine Line to display at the top of the dialogue. Should describe what is the player picking. * @returns Promise that will resolve with the choice that the player picked (one of the `elements`) or rejects if the player cancelled the dialogue. */ declare function RadioDataInput<DataType>(elements: Array<DataType>, elementsComponents: React.ReactNodeArray, promptLine: JSX.Element): Promise<DataType>; /** * Creates an input "dialogue" for the player to pick N options from multiple choices and asynchronously returns the picked choices indexes. * * @remarks * Player terminal input will be disabled, i.e. `Gash.disableInput`, and routed to the dialogue via `Gash.routeInput`. * The dialogue displays each choice on a new line. Normally choices are prefixed by dot but currently selected choices are colored green and prefixed by dash. Additionally a cursor is displayed on the currently active choice with '>' symbol. * The dialogue includes passed prompt line, controls instruction line, choices lines and optionally an error message line in that order. * Player can navigate the dialogue with up and down arrows, select a choice with Spacebar, confirm the selection with Enter or cancel the dialogue with 'q'. * Once the player has picked N options all temporary lines are cleared, input routing is removed and terminal input is enabled again. * For a single option dialogue, i.e. `wantedCount === 1` consider using `RadioInput`. * * @param choicesComponents React nodes that represent the choices that player can pick from. Must have length of at least 1. * @param wantedCount How many options must the player select to be able to confirm and exit the dialogue. Must be at least 1, ideally 2. * @param promptLine Line to display at the top of the dialogue. Should describe what is the player picking. * @returns Promise that will resolve with a zero-based indexes of the choices that the player picked of `wantedCount` length or rejects if the player cancelled the dialogue. */ declare function ListInput(choicesComponents: React.ReactNodeArray, wantedCount: number, promptLine: JSX.Element): Promise<number[]>; /** * Creates an input "dialogue" for the player to pick N options from multiple choices and asynchronously returns the picked choices. * * @remarks * A convenience generic wrapper around ListInput that returns data instead of indexes. * This is useful when player has to choose between game entities, often `IKeyword` instances and the game then acts on the picked entities. * Only the `elementsComponents` are passed to the `RadioInput` and therefore rendered to the screen. On the other hand, `elements` are only used when resolving the promise. * * @param elements Choices that player is picking from. Must have the same length as `elementsComponents`. Must have length of at least 1. * @param elementsComponents React nodes that represent the choices that player can pick from. Must have the same length as `elements`. * @param wantedCount How many options must the player select to be able to confirm and exit the dialogue. Must be at least 1, ideally 2. * @param promptLine Line to display at the top of the dialogue. Should describe what is the player picking. * @returns Promise that will resolve with the choices that the player picked (one of the `elements`) or rejects if the player cancelled the dialogue. */ declare function ListDataInput<DataType>(elements: Array<DataType>, elementsComponents: React.ReactNodeArray, wantedCount: number, promptLine: JSX.Element): Promise<DataType[]>; /** * Result of `LowLevelParser.parse` */ interface LowLevelResult extends ParsingResult { /** Index into the parsed input of how far the parser has advanced - exclusive. */ position: number; /** Command parameters that were parsed out of the input so far. */ params: Array<string>; /** Command options that were parsed out of the input so far. */ options: Array<string>; /** Used by command options LowLevelParser */ optionNotFound?: boolean; } /** * Low level parser interface for parser combinators. * * @remarks * Unless you need to implement your own parser it is recommended to use the provided `TextParameter`, `SingleWordTextParameter`, `NumberParameter` that return this interface. */ interface LowLevelParser { /** * Parse the input * @param input Input string to be parsed * @param initialResult Result of previous parser or dummy initial result if this parser is first or only parser * @param index Optional index into `input` that the parser should start parsing from - inclusive */ parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; /** * Method allowing sequence chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser succeeds the `ac` parser will be called on the remainder. * Easily implemented using `SequenceParser` for example with this one liner: `return new SequenceParser(this, p);` * * @param ac The low level parser that should follow `this` parser. */ then(p: LowLevelParser): LowLevelParser; /** * Method allowing choice chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser succeeds the `ac` parser will be called on the remainder. * Warning: `or()`-ing `optional()` parser will always ignore the second `or`-ed parses. * Easily implemented using `OrParser` for example with this one liner: `return new OrParser(this, p);` * * @param ac The low level parser that should be called instead of `this` parser if `this` parser fails. */ or(p: LowLevelParser): LowLevelParser; /** * Method allowing conditional chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser fails the parsing will return to the previous parser last position and continue in the chain. * Warning: `repeat()`-ing `optional()` parser leads to infinite recursion. * Easily implemented using `OptionalParser` for example with this one liner: `return new OptionalParser(this);` * * @param ac The low level parser that wraps `this` parser and catches failures. */ optional(): LowLevelParser; /** * Method allowing repetition chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser succeeds it will be called recursively on the remainder until it fails. * Warning: `repeat()`-ing `optional()` parser leads to infinite recursion. * Easily implemented using `RepetitionParser` for example with this one liner: `return new RepetitionParser(this);` * * @param ac The low level parser that repeats `this` parser. */ repeat(): LowLevelParser; } /** * Low level parser for implementing `LowLevelParser.then`. * * @remarks * Unless you need to implement your own `LowLevelParser` you shouldn't need to use this class directly. */ declare class SequenceParser implements LowLevelParser { private first; private second; constructor(first: LowLevelParser, second: LowLevelParser); parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; then(p: LowLevelParser): LowLevelParser; or(p: LowLevelParser): LowLevelParser; optional(): LowLevelParser; repeat(): LowLevelParser; } /** * Low level parser for implementing `LowLevelParser.or`. * * @remarks * Unless you need to implement your own `LowLevelParser` you shouldn't need to use this class directly. */ declare class OrParser implements LowLevelParser { private first; private second; constructor(first: LowLevelParser, second: LowLevelParser); parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; then(p: LowLevelParser): LowLevelParser; or(p: LowLevelParser): LowLevelParser; optional(): LowLevelParser; repeat(): LowLevelParser; } /** * Low level parser for implementing `LowLevelParser.optional`. * * @remarks * Unless you need to implement your own `LowLevelParser` you shouldn't need to use this class directly. */ declare class OptionalParser implements LowLevelParser { private parser; constructor(parser: LowLevelParser); parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; then(p: LowLevelParser): LowLevelParser; or(p: LowLevelParser): LowLevelParser; optional(): LowLevelParser; repeat(): LowLevelParser; } /** * Low level parser for implementing `LowLevelParser.repeat`. * * @remarks * Unless you need to implement your own `LowLevelParser` you shouldn't need to use this class directly. */ declare class RepetitionParser implements LowLevelParser { private parser; constructor(parser: LowLevelParser); parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; parseRecurse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; then(p: LowLevelParser): LowLevelParser; or(p: LowLevelParser): LowLevelParser; optional(): LowLevelParser; repeat(): LowLevelParser; } declare class NumberParameterParser implements LowLevelParser { parse(input: string, initialResult: LowLevelResult, index?: number): LowLevelResult; then(p: LowLevelParser): LowLevelParser; or(p: LowLevelParser): LowLevelParser; optional(): LowLevelParser; repeat(): LowLevelParser; } /** * Helper function to parse an input line for a command body. * * @remarks * Used internally by Gash to extract a command name in a case of unrecognized command input line. */ declare function CommandBodyLikeParse(input: string): CommandParserResult; /** * Low-level parser that can be used to parse a text parameter of a command. * * @remarks * Parsers multiple words as a single parameter. * * @returns `LowLevelParser` that can be used in `CommandParser` as `paramsParser` parameter or as a part of a chain of `LowLevelParser`s in there. */ declare function TextParameter(): LowLevelParser; /** * Low-level parser that can be used to parse a text parameter of a command. * * @remarks * Only parses single word parameters - no spaces. * * @returns `LowLevelParser` that can be used in `CommandParser` as `paramsParser` parameter or as a part of a chain of `LowLevelParser`s in there. */ declare function SingleWordTextParameter(): LowLevelParser; /** * Low-level parser that can be used to parse a number parameter of a command. * * @returns `LowLevelParser` that can be used in `CommandParser` as `paramsParser` parameter or as a part of a chain of `LowLevelParser`s in there. */ declare function NumberParameter(): NumberParameterParser; /** * Result of `ICommandParser.parse`. * * @remarks * Extends `ParsingResult` that `ICommand.parse` expects to provide parsed parameters and options to be used by the command implementation. */ interface CommandParserResult extends ParsingResult { /** Parameters that were parsed out of the input using the `paramsParser` parser combinator passed to `CommandParser`. */ params: Array<string>; /** Options that were parsed out of the input using the `options` definitions passed to `CommandParser`. */ options: Array<string>; } /** * Definition of an option to a command. */ interface OptionDefinition { /** Optional short version of the option. Must be one letter, preferably a lower-case. */ short?: string; /** Optional long version of the option. Must be a word or multiple words connected by dash, preferably a lower-case. */ long?: string; } /** * Interface for the return of CommandParser. */ interface ICommandParser { /** * Attempts to parse an input line string. * * @remarks * Should be used to implement `ICommand.parse` including passing through the return value. * * @param input Input line string to be parsed coming from `ICommand.parse` parameter `line`. * @returns See `CommandParserResult` */ parse(input: string): CommandParserResult; } /** * Creates a parser that can parse a command, its options and parameters. * * @remarks * Drastically reduces complexity of implementing `ICommand.parse`. * * @param command Command that the parser is for. `ICommand.name` will be use auto-complete the command body. * @param paramsParser Optional one or chain of `LowLevelParser` that will parse the command parameters. * @param options Definitions of options the command accepts. Options are always optional but unrecognized option will fail the parsing. * @returns Interface that contains `parse` method that should be called on `line` input of `ICommand.parse`. */ declare function CommandParser(command: ICommand, paramsParser?: LowLevelParser, options?: OptionDefinition[]): ICommandParser; /** * Helper function to check whether a result of parsing a command includes an option. * @param result Result of `ICommandParser.parse` to check for option presence. * @param option Short or long option string * @returns Whether the result contains the option `true` or not `false`. */ declare function parserResultHasOption(result: CommandParserResult, option: string): boolean; /** * Result of `LowLevelAutoCompleter.autocomplete` */ interface LowLevelAutoCompleteResult { /** Type of the result, see `AutoCompleteResultType` */ type: AutoCompleteResultType; /** Index into the input string representing how far the auto-completer managed to advance. The input line is usually `String.slice(position)`-ed from the result of the previous auto-completer as an input for the current auto-completer. */ position: number; /** Contains the furthest match between the input and the attempted auto-completion. */ fixedValue: string; /** Used by implementation of command options LowLevelAutoCompleter. */ optionNotFound?: boolean; } /** * Low level parser interface for auto-completion parser combinators. * * @remarks * Unless you need to implement your own parser it is recommended to use the provided `AutoCompleteTextParam`, `AutoCompleteKeywords` and `AutoCompleteNumber` that return this interface. */ interface LowLevelAutoCompleter { /** * Auto-complete the input * @param input Input string to be auto-completed * @param initialResult Result of the previous parser or dummy result if this parser is the first or only parser. * @param index Optional index into input that the auto-completion should start from - inclusive. */ autocomplete(input: string, initialResult: LowLevelAutoCompleteResult, index?: number): LowLevelAutoCompleteResult; /** * Method allowing sequence chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser succeeds the `ac` parser will be called on the remainder. * Easily implemented using `SequenceAutoCompleter` for example with this one liner: `return new SequenceAutoCompleter(this, ac);` * * @param ac The low level parser that should follow `this` parser. */ then(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; /** * Method allowing choice chaining of parsers and therefore creating parser combinators. * * @remarks * If `this` parser fails the `ac` parser will be called the current input instead. * Easily implemented using `OrAutoCompleter` for example with this one liner: `return new OrAutoCompleter(this, ac);` * * @param ac */ or(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; } /** * Low level parser for implementing `LowLevelAutoCompleter.then`. * * @remarks * Unless you need to implement your own `LowLevelAutoCompleter` you shouldn't need to use this class directly. */ declare class SequenceAutoCompleter implements LowLevelAutoCompleter { private first; private second; constructor(first: LowLevelAutoCompleter, second: LowLevelAutoCompleter); autocomplete(input: string, initialResult: LowLevelAutoCompleteResult, index?: number): LowLevelAutoCompleteResult; then(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; or(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; } /** * Low level parser for implementing `LowLevelAutoCompleter.or`. * * @remarks * Unless you need to implement your own `LowLevelAutoCompleter` you shouldn't need to use this class directly. */ declare class OrAutoCompleter implements LowLevelAutoCompleter { private first; private second; constructor(first: LowLevelAutoCompleter, second: LowLevelAutoCompleter); autocomplete(input: string, initialResult: LowLevelAutoCompleteResult, index?: number): LowLevelAutoCompleteResult; then(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; or(ac: LowLevelAutoCompleter): LowLevelAutoCompleter; } /** * Low level parser that can be used to auto-complete a command's text parameter given an array of possible candidates. * @param words Array of words to check each as a possible candidate for auto-completion. * @returns `LowLevelAutoCompleter` that can be used in `CommandAutoCompleter` as `paramsAutoCompleter` parameter or as a part of a chain of `LowLevelAutoCompleter`s in there. */ declare function AutoCompleteTextParam(words: Array<string>): LowLevelAutoCompleter; /** * Low level parser that can be used to auto-complete a command's single-word text parameter given an array of possible candidates. * @param words Array of words to check each as a possible candidate for auto-completion. * @returns `LowLevelAutoCompleter` that can be used in `CommandAutoCompleter` as `paramsAutoCompleter` parameter or as a part of a chain of `LowLevelAutoCompleter`s in there. */ declare function AutoCompleteSingleWordTextParam(words: Array<string>): LowLevelAutoCompleter; /** * Low level parser that can be used to auto-complete command text parameter given an array of possible keywords. * @param keywords Array of keywords to check each as a possible candidate for auto-completion. `IKeyword.name()` will be used as the target string candidate. * @returns `LowLevelAutoCompleter` that can be used in `CommandAutoCompleter` as `paramsAutoCompleter` parameter or as a part of a chain of `LowLevelAutoCompleter`s in there. */ declare function AutoCompleteKeywords(keywords: Array<IKeyword>): LowLevelAutoCompleter; /** * Low level parser that can be used to auto-complete a command's number parameter. * @returns `LowLevelAutoCompleter` that can be used in `CommandAutoCompleter` as `paramsAutoCompleter` parameter or as a part of a chain of `LowLevelAutoCompleter`s in there. */ declare function AutoCompleteNumber(): LowLevelAutoCompleter; /** * Interface for the return of CommandAutoCompleter. */ interface ICommandAutoCompleter { /** * Attempts to auto-complete an input line string. * * @remarks * Should be used to implement `ICommand.autocomplete` including the return value. * * @param input Input line string to be auto-completed coming from `ICommand.autocomplete` parameter `line`. * @returns See `AutoCompleteResult` */ autocomplete(input: string): AutoCompleteResult; } /** * Creates a parser that can auto-complete a command, its options and parameters. * * @remarks * Drastically reduces complexity of implementing `ICommand.autocomplete`. * Note that options are basically skipped if already present and ignored if only body is found. * * @param command Command that the parser is for. `ICommand.name` will be use auto-complete the command body. * @param paramsAutoCompleter Optional one or chain of `LowLevelAutoCompleter` that will auto-complete the command parameters. * @returns Interface that contains `parse` method that should be called on `line` input of `ICommand.autocomplete`. */ declare function CommandAutoCompleter(command: ICommand, paramsAutoCompleter?: LowLevelAutoCompleter): ICommandAutoCompleter; export default Gash; export { AutoCompleteKeywords, AutoCompleteNumber, AutoCompleteResult, AutoCompleteResultType, AutoCompleteSingleWordTextParam, AutoCompleteTextParam, BlockTitle, BlockTitleProps, Colored, ColoredProps, CommandAutoCompleter, CommandBodyLikeParse, CommandColored, CommandParser, CommandParserResult, CursorProps, ICommand, ICommandAutoCompleter, ICommandParser, IKeyword, IKeywordGroup, Line, LineProps, ListDataInput, ListInput, LowLevelAutoCompleteResult, LowLevelAutoCompleter, LowLevelParser, LowLevelResult, NumberParameter, OptionDefinition, OptionalParser, OrAutoCompleter, OrParser, ParsingFailureReason, ParsingResult, PromptProps, RadioDataInput, RadioInput, RepetitionParser, SequenceAutoCompleter, SequenceParser, SingleWordTextParameter, Terminal, TerminalProps, TextParameter, black900, brown600, cyan600, deepOrange600, deepPurple400, green600, grey200, grey600, indigo400, lightBlue600, parserResultHasOption, red600, white0, yellow600 };