UNPKG

symfony-style-console

Version:

Use the style and utilities of the Symfony Console in Node.js

91 lines (90 loc) 2.15 kB
import OutputFormatterStyle from './OutputFormatterStyle'; /** * Manages nesting of [[OutputFormatterStyleInterface]] styles. * * * @author Jean-François Simon <contact@jfsimon.fr> * * Original PHP class * * @author Florian Reuschel <florian@loilo.de> * * Port to TypeScript * */ class OutputFormatterStyleStack { /** * Constructor. * * @param emptyStyle */ constructor(emptyStyle = null) { this.emptyStyle = emptyStyle || new OutputFormatterStyle(); this.reset(); } /** * Resets stack (ie. empty internal arrays). */ reset() { this.styles = []; } /** * Pushes a style in the stack. * * @param style */ push(style) { this.styles.push(style); } /** * Pops a style from the stack. * * @param OutputFormatterStyle|null style * * @return OutputFormatterStyle * * @throws InvalidArgumentException When style tags incorrectly nested */ pop(style = null) { if (!this.styles.length) { return this.emptyStyle; } if (null === style) { return this.styles.pop(); } for (let index = this.styles.length - 1; index >= 0; index--) { const stackedStyle = this.styles[index]; if (style.apply('') === stackedStyle.apply('')) { this.styles = this.styles.slice(0, index); return stackedStyle; } } throw new SyntaxError('Incorrectly nested style tag found.'); } /** * Computes current style with stacks top codes. * * @return OutputFormatterStyle */ getCurrent() { if (!this.styles.length) { return this.emptyStyle; } return this.styles[this.styles.length - 1]; } /** * @param emptyStyle * @return this */ setEmptyStyle(emptyStyle) { this.emptyStyle = emptyStyle; return this; } /** * @return OutputFormatterStyle */ getEmptyStyle() { return this.emptyStyle; } } export default OutputFormatterStyleStack;