flagstaff 1.0.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/boxen.js CHANGED
@@ -1,4 +1,4 @@
1
- import { width as stringWidth } from 'linegauge';
1
+ import { slice as sliceAnsi, widest, width as stringWidth } from 'linegauge';
2
2
  import { wrap as wrapAnsi } from 'linegauge/wrap';
3
3
  import chalk from 'roundel/chalk';
4
4
  import { processRuntime } from './runtime.js';
@@ -7,10 +7,12 @@ const NEWLINE = '\n';
7
7
  const PAD = ' ';
8
8
  const NONE = 'none';
9
9
  const FALLBACK_COLUMNS = 80;
10
- const DECIMAL = 10;
11
- const BORDERED = 2;
10
+ const BAR_ROWS = 2;
11
+ const LABEL_FRAME = 2;
12
12
  const SIDE_MARGIN_RATIO = 3;
13
13
  const HALF = 2;
14
+ const ESC = '\u{1B}';
15
+ const BACKSPACE = '\u{8}';
14
16
  const BOXES = {
15
17
  single: { topLeft: '┌', top: '─', topRight: '┐', right: '│', bottomRight: '┘', bottom: '─', bottomLeft: '└', left: '│' },
16
18
  double: { topLeft: '╔', top: '═', topRight: '╗', right: '║', bottomRight: '╝', bottom: '═', bottomLeft: '╚', left: '║' },
@@ -21,131 +23,161 @@ const BOXES = {
21
23
  classic: { topLeft: '+', top: '-', topRight: '+', right: '|', bottomRight: '+', bottom: '-', bottomLeft: '+', left: '|' },
22
24
  arrow: { topLeft: '↘', top: '↓', topRight: '↙', right: '←', bottomRight: '↖', bottom: '↑', bottomLeft: '↗', left: '→' },
23
25
  };
24
- function terminalColumns() {
25
- const { env, stdout, stderr } = rt;
26
- if (stdout?.columns)
27
- return stdout.columns;
28
- if (stderr?.columns)
29
- return stderr.columns;
30
- if (env['COLUMNS'] !== undefined)
31
- return Number.parseInt(env['COLUMNS'], DECIMAL);
32
- return FALLBACK_COLUMNS;
26
+ const LINE_BREAKS = /\r\n|[\n\v\f\r]/gu;
27
+ const STYLING_ESCAPE = /^(?:\u{1B}\[[0-9:;]*m|\u{1B}\]8;[^\u{0}-\u{1F};\u{7F}]*;[^\u{0}-\u{1F}\u{7F}]*(?:\u{7}|\u{1B}\\))$/u;
28
+ const CONTROL_ESCAPE = /(\u{1B}\].*?(?:\u{7}|\u{1B}\\|$)|\u{1B}\[[\u{20}-\u{3F}]*[\u{40}-\u{7E}]|\u{1B}[^\u{7}\u{5B}\u{5D}]?)/gsu;
29
+ function writeControls(text) {
30
+ const characters = [];
31
+ for (const [index, part] of text.split(CONTROL_ESCAPE).entries()) {
32
+ if (index % HALF === 1) {
33
+ if (STYLING_ESCAPE.test(part))
34
+ characters.push(part);
35
+ continue;
36
+ }
37
+ for (const character of part.replaceAll('\t', PAD)) {
38
+ if (character !== BACKSPACE) {
39
+ characters.push(character);
40
+ continue;
41
+ }
42
+ const previous = characters.findLastIndex((c) => !c.startsWith(ESC));
43
+ if (previous !== -1 && characters[previous] !== NEWLINE)
44
+ characters.splice(previous, 1);
45
+ }
46
+ }
47
+ return characters.join('');
33
48
  }
49
+ const oneRow = (text) => writeControls(text.replaceAll(LINE_BREAKS, PAD)).toWellFormed();
50
+ const columnsOf = (value) => Number(value);
51
+ const terminalColumns = () => rt.stdout?.columns || rt.stderr?.columns || columnsOf(rt.env['COLUMNS']) || FALLBACK_COLUMNS;
52
+ const terminalRows = () => rt.stdout?.rows || rt.stderr?.rows || columnsOf(rt.env['LINES']);
34
53
  function getObject(detail) {
35
- if (typeof detail === 'number') {
36
- return { top: detail, right: detail * SIDE_MARGIN_RATIO, bottom: detail, left: detail * SIDE_MARGIN_RATIO };
37
- }
38
- return { top: 0, right: 0, bottom: 0, left: 0, ...detail };
54
+ const object = typeof detail === 'number'
55
+ ? { top: detail, right: detail * SIDE_MARGIN_RATIO, bottom: detail, left: detail * SIDE_MARGIN_RATIO }
56
+ : { top: 0, right: 0, bottom: 0, left: 0, ...detail };
57
+ const side = (name) => {
58
+ const value = Number(object[name]);
59
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
60
+ };
61
+ return { top: side('top'), right: side('right'), bottom: side('bottom'), left: side('left') };
39
62
  }
40
- const getBorderWidth = (borderStyle) => (borderStyle === NONE ? 0 : BORDERED);
41
63
  const SIDES = ['topLeft', 'topRight', 'bottomRight', 'bottomLeft', 'left', 'right', 'top', 'bottom'];
42
- const widestLine = (text) => Math.max(0, ...text.split(NEWLINE).map((line) => stringWidth(line)));
43
- function ansiAlign(text, align) {
44
- if (text === '' || align === 'left')
45
- return text;
46
- const lines = text.split(NEWLINE).map((line) => ({ line, width: stringWidth(line) }));
47
- const maxWidth = Math.max(0, ...lines.map((l) => l.width));
48
- const diff = (w) => (align === 'right' ? maxWidth - w : Math.floor((maxWidth - w) / HALF));
49
- return lines.map((l) => PAD.repeat(diff(l.width)) + l.line).join(NEWLINE);
50
- }
51
64
  function getBorderChars(borderStyle) {
65
+ let characters;
52
66
  if (borderStyle === NONE) {
53
- return { topLeft: '', top: '', topRight: '', left: '', right: '', bottomLeft: '', bottom: '', bottomRight: '' };
67
+ characters = Object.fromEntries(SIDES.map((side) => [side, '']));
54
68
  }
55
- if (typeof borderStyle === 'string') {
56
- const characters = BOXES[borderStyle];
57
- if (!characters)
69
+ else if (typeof borderStyle === 'string') {
70
+ if (!Object.hasOwn(BOXES, borderStyle))
58
71
  throw new TypeError(`Invalid border style: ${borderStyle}`);
59
- return characters;
60
- }
61
- const style = { ...borderStyle };
62
- if (typeof style.vertical === 'string') {
63
- style.left = style.vertical;
64
- style.right = style.vertical;
72
+ characters = BOXES[borderStyle];
65
73
  }
66
- if (typeof style.horizontal === 'string') {
67
- style.top = style.horizontal;
68
- style.bottom = style.horizontal;
69
- }
70
- for (const side of SIDES) {
71
- if (typeof style[side] !== 'string')
72
- throw new TypeError(`Invalid border style: ${side}`);
74
+ else {
75
+ const given = borderStyle;
76
+ characters = { ...given, left: given?.left ?? given?.vertical, right: given?.right ?? given?.vertical, top: given?.top ?? given?.horizontal, bottom: given?.bottom ?? given?.horizontal };
77
+ for (const side of SIDES) {
78
+ if (typeof characters[side] !== 'string')
79
+ throw new TypeError(`Invalid border style: ${side}`);
80
+ }
73
81
  }
74
- return style;
82
+ return Object.fromEntries(SIDES.map((side) => [side, oneRow(characters[side])]));
75
83
  }
76
- function makeTitle(text, horizontalRun, alignment) {
77
- const textWidth = stringWidth(text);
78
- if (alignment === 'left')
79
- return text + horizontalRun.slice(textWidth);
80
- if (alignment === 'right')
81
- return horizontalRun.slice(textWidth) + text;
82
- let horizontal = horizontalRun.slice(textWidth);
83
- if (horizontal.length % HALF === 1) {
84
- horizontal = horizontal.slice(Math.floor(horizontal.length / HALF));
85
- return horizontal.slice(1) + text + horizontal;
86
- }
87
- horizontal = horizontal.slice(horizontal.length / HALF);
88
- return horizontal + text + horizontal;
84
+ function getBorderWidth(borderStyle) {
85
+ if (borderStyle === NONE)
86
+ return 0;
87
+ const { left, right } = getBorderChars(borderStyle);
88
+ return stringWidth(left || PAD) + stringWidth(right || PAD);
89
89
  }
90
- function rewrap(line, max, align) {
91
- const alignedLines = ansiAlign(wrapAnsi(line, max, { hard: true }), align).split(NEWLINE);
92
- const longest = Math.max(0, ...alignedLines.map((s) => stringWidth(s)));
93
- if (align === 'center')
94
- return alignedLines.map((l) => PAD.repeat((max - longest) / HALF) + l);
95
- if (align === 'right')
96
- return alignedLines.map((l) => PAD.repeat(max - longest) + l);
97
- return alignedLines;
90
+ const getBorderHeight = (borderStyle) => (borderStyle === NONE ? 0 : BAR_ROWS);
91
+ function getCornerWidths(borderStyle) {
92
+ const { topLeft, topRight, bottomLeft, bottomRight } = getBorderChars(borderStyle);
93
+ return { top: stringWidth(topLeft) + stringWidth(topRight), bottom: stringWidth(bottomLeft) + stringWidth(bottomRight) };
98
94
  }
99
- function padRows(lines, padding, width) {
100
- const left = PAD.repeat(padding.left);
101
- const right = PAD.repeat(padding.right);
102
- const padded = lines.map((line) => {
103
- const newLine = left + line + right;
104
- return newLine + PAD.repeat(width - stringWidth(newLine));
105
- });
106
- return [
107
- ...Array.from({ length: padding.top }, () => PAD.repeat(width)),
108
- ...padded,
109
- ...Array.from({ length: padding.bottom }, () => PAD.repeat(width)),
110
- ];
95
+ function sanitizeSize(size, borderWidth, minimum = 1) {
96
+ const value = Number(size);
97
+ return Number.isFinite(value) && value > 0 ? Math.max(minimum, value - borderWidth) : undefined;
98
+ }
99
+ const isValidSize = (size) => sanitizeSize(size, 0) !== undefined;
100
+ const wrapLine = (line, width) => (stringWidth(line) > width ? wrapAnsi(line, width, { hard: true }) : line);
101
+ const widestLine = (text) => widest(text.split(NEWLINE));
102
+ function alignText(text, alignment, width) {
103
+ if (alignment === 'left')
104
+ return text;
105
+ return text
106
+ .split(NEWLINE)
107
+ .map((line) => {
108
+ const padding = Math.max(0, width - stringWidth(line));
109
+ return PAD.repeat(alignment === 'right' ? padding : Math.floor(padding / HALF)) + line;
110
+ })
111
+ .join(NEWLINE);
111
112
  }
112
- function fitHeight(lines, height, width) {
113
- if (height === undefined || height <= 0)
114
- return lines;
115
- if (lines.length > height)
116
- return lines.slice(0, height);
117
- return [...lines, ...Array.from({ length: height - lines.length }, () => PAD.repeat(width))];
113
+ function makeLabel(text, horizontal, alignment) {
114
+ const textWidth = stringWidth(text);
115
+ if (alignment === 'left')
116
+ return text + sliceAnsi(horizontal, textWidth);
117
+ if (alignment === 'right')
118
+ return sliceAnsi(horizontal, textWidth) + text;
119
+ const spare = Math.max(0, stringWidth(horizontal) - textWidth);
120
+ if (spare % HALF === 1) {
121
+ const rest = sliceAnsi(horizontal, Math.floor(spare / HALF) + textWidth);
122
+ return sliceAnsi(rest, 1) + text + rest;
123
+ }
124
+ const rest = sliceAnsi(horizontal, spare / HALF + textWidth);
125
+ return rest + text + rest;
118
126
  }
119
127
  function makeContentText(text, { padding, width, textAlignment, height }) {
120
- const align = textAlignment ?? 'left';
121
- const aligned = ansiAlign(text, align);
122
- let lines = aligned.split(NEWLINE);
123
- const textWidth = widestLine(aligned);
124
128
  const max = width - padding.left - padding.right;
125
- if (textWidth > max)
126
- lines = lines.flatMap((line) => rewrap(line, max, align));
127
- if (align === 'center' && textWidth < max)
128
- lines = lines.map((line) => PAD.repeat((max - textWidth) / HALF) + line);
129
- else if (align === 'right' && textWidth < max)
130
- lines = lines.map((line) => PAD.repeat(max - textWidth) + line);
131
- return fitHeight(padRows(lines, padding, width), height, width).join(NEWLINE);
129
+ const wrappedText = text
130
+ .split(NEWLINE)
131
+ .map((line) => wrapLine(line, max))
132
+ .join(NEWLINE);
133
+ const textWidth = Math.min(max, widestLine(wrappedText));
134
+ const alignedText = alignText(wrappedText, textAlignment, textWidth);
135
+ let offset = 0;
136
+ if (textAlignment === 'right')
137
+ offset = max - textWidth;
138
+ else if (textAlignment === 'center')
139
+ offset = Math.floor((max - textWidth) / HALF);
140
+ const paddingLeft = PAD.repeat(padding.left);
141
+ const paddingRight = PAD.repeat(padding.right);
142
+ let lines = alignedText.split(NEWLINE).map((line) => {
143
+ const newLine = paddingLeft + PAD.repeat(offset) + line + paddingRight;
144
+ return newLine + PAD.repeat(Math.max(0, width - stringWidth(newLine)));
145
+ });
146
+ const textRows = height === undefined ? undefined : Math.max(0, height - padding.top - padding.bottom);
147
+ if (textRows !== undefined && lines.length > textRows)
148
+ lines = lines.slice(0, textRows);
149
+ const blank = (count) => Array.from({ length: count }, () => PAD.repeat(width));
150
+ lines = [...blank(padding.top), ...lines, ...blank(padding.bottom)];
151
+ if (height !== undefined && lines.length < height)
152
+ lines = [...lines, ...blank(height - lines.length)];
153
+ return lines.join(NEWLINE);
132
154
  }
133
- const isHex = (color) => /^#(?:[0-f]{3}){1,2}$/i.test(color);
134
- function named(name) {
135
- const value = Reflect.get(chalk, name);
136
- return typeof value === 'function' ? value : undefined;
155
+ function fillBar(character, width) {
156
+ const fill = character || PAD;
157
+ const count = Math.ceil(Math.max(0, width) / Math.max(1, stringWidth(fill)));
158
+ return sliceAnsi(fill.repeat(count), 0, Math.max(0, width));
137
159
  }
138
- const bgName = (color) => `bg${color.charAt(0).toUpperCase()}${color.slice(1)}`;
139
- const asIs = (text) => text;
140
- const isColorValid = (color) => typeof color === 'string' && (named(color) !== undefined || isHex(color));
141
- const colorFunction = (color) => (isHex(color) ? chalk.hex(color) : (named(color) ?? asIs));
142
- const bgColorFunction = (color) => (isHex(color) ? chalk.bgHex(color) : (named(bgName(color)) ?? asIs));
160
+ const isHex = (color) => /^#(?:[\da-f]{3}){1,2}$/iu.test(color);
161
+ const COLOR_NAMES = new Set(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'grey', 'blackBright', 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright']);
162
+ const named = (name) => Reflect.get(chalk, name);
163
+ const isColorValid = (color) => typeof color === 'string' && (COLOR_NAMES.has(color) || isHex(color));
164
+ const colorFunction = (color) => (isHex(color) ? chalk.hex(color) : named(color));
165
+ const bgColorFunction = (color) => (isHex(color) ? chalk.bgHex(color) : named(`bg${color.charAt(0).toUpperCase()}${color.slice(1)}`));
143
166
  function boxContent(content, contentWidth, options) {
144
167
  const colorizeBorder = (border) => {
145
- const painted = options.borderColor === undefined ? border : colorFunction(options.borderColor)(border);
146
- return options.dimBorder === true ? chalk.dim(painted) : painted;
168
+ const colored = options.borderColor ? colorFunction(options.borderColor)(border) : border;
169
+ let background = colored;
170
+ if (options.borderBackgroundColor === 'inherit') {
171
+ if (options.backgroundColor)
172
+ background = bgColorFunction(options.backgroundColor)(colored);
173
+ }
174
+ else if (options.borderBackgroundColor !== undefined) {
175
+ background = bgColorFunction(options.borderBackgroundColor)(colored);
176
+ }
177
+ return options.dimBorder ? chalk.dim(background) : background;
147
178
  };
148
- const colorizeContent = (line) => (options.backgroundColor === undefined ? line : bgColorFunction(options.backgroundColor)(line));
179
+ const colorizeContent = (text) => (options.backgroundColor ? bgColorFunction(options.backgroundColor)(text) : text);
180
+ const colorizeTitle = (title) => (options.titleColor ? colorFunction(options.titleColor)(title) : title);
149
181
  const chars = getBorderChars(options.borderStyle);
150
182
  const columns = terminalColumns();
151
183
  let marginLeft = PAD.repeat(options.margin.left);
@@ -155,99 +187,141 @@ function boxContent(content, contentWidth, options) {
155
187
  else if (options.float === 'right') {
156
188
  marginLeft = PAD.repeat(Math.max(columns - contentWidth - options.margin.right - getBorderWidth(options.borderStyle), 0));
157
189
  }
158
- let result = '';
159
- if (options.margin.top)
160
- result += NEWLINE.repeat(options.margin.top);
161
- if (options.borderStyle !== NONE || options.title !== undefined) {
162
- const run = chars.top.repeat(contentWidth);
163
- const top = options.title === undefined ? run : makeTitle(options.title, run, options.titleAlignment);
164
- result += `${colorizeBorder(marginLeft + chars.topLeft + top + chars.topRight)}${NEWLINE}`;
190
+ const hasBorder = options.borderStyle !== NONE;
191
+ const left = hasBorder ? chars.left || PAD : '';
192
+ const right = hasBorder ? chars.right || PAD : '';
193
+ const rowWidth = contentWidth + stringWidth(left) + stringWidth(right);
194
+ const bar = (character, cornerStart, cornerEnd, label, alignment) => {
195
+ const span = Math.max(0, rowWidth - stringWidth(cornerStart) - stringWidth(cornerEnd));
196
+ const fill = fillBar(character, span);
197
+ const filled = label ? makeLabel(label, fill, alignment) : fill;
198
+ return sliceAnsi(filled + PAD.repeat(Math.max(0, span - stringWidth(filled))), 0, Math.max(0, span));
199
+ };
200
+ const rows = [];
201
+ if (hasBorder || options.title) {
202
+ const topBar = bar(chars.top, chars.topLeft, chars.topRight, options.title ? colorizeTitle(options.title) : '', options.titleAlignment);
203
+ rows.push(marginLeft + colorizeBorder(chars.topLeft + topBar + chars.topRight));
165
204
  }
166
- result += content
167
- .split(NEWLINE)
168
- .map((line) => marginLeft + colorizeBorder(chars.left) + colorizeContent(line) + colorizeBorder(chars.right))
169
- .join(NEWLINE);
170
- if (options.borderStyle !== NONE) {
171
- result += NEWLINE + colorizeBorder(marginLeft + chars.bottomLeft + chars.bottom.repeat(contentWidth) + chars.bottomRight);
205
+ for (const line of content === '' ? [] : content.split(NEWLINE)) {
206
+ const padded = line + PAD.repeat(Math.max(0, contentWidth - stringWidth(line)));
207
+ rows.push(marginLeft + colorizeBorder(left) + colorizeContent(padded) + colorizeBorder(right));
208
+ }
209
+ if (hasBorder || options.footer) {
210
+ const bottomBar = bar(chars.bottom, chars.bottomLeft, chars.bottomRight, options.footer ?? '', options.footerAlignment);
211
+ rows.push(marginLeft + colorizeBorder(chars.bottomLeft + bottomBar + chars.bottomRight));
172
212
  }
173
- if (options.margin.bottom)
174
- result += NEWLINE.repeat(options.margin.bottom);
175
- return result;
213
+ return NEWLINE.repeat(options.margin.top) + rows.join(NEWLINE) + NEWLINE.repeat(options.margin.bottom);
176
214
  }
177
215
  function sanitizeOptions(options) {
178
- if (options.fullscreen !== undefined && options.fullscreen !== false && rt.stdout) {
179
- let dimensions = [rt.stdout.columns, rt.stdout.rows];
216
+ if (options.fullscreen) {
217
+ let dimensions = [terminalColumns(), terminalRows()];
180
218
  if (typeof options.fullscreen === 'function')
181
219
  dimensions = options.fullscreen(...dimensions);
182
- options.width ||= dimensions[0];
183
- options.height ||= dimensions[1];
220
+ if (!isValidSize(options.width))
221
+ options.width = dimensions[0];
222
+ if (!isValidSize(options.height))
223
+ options.height = dimensions[1];
184
224
  }
185
- if (options.width)
186
- options.width = Math.max(1, options.width - getBorderWidth(options.borderStyle));
187
- if (options.height)
188
- options.height = Math.max(1, options.height - getBorderWidth(options.borderStyle));
225
+ const borderWidth = getBorderWidth(options.borderStyle);
226
+ options.width = sanitizeSize(options.width, borderWidth);
227
+ options.maxWidth = sanitizeSize(options.maxWidth, borderWidth);
228
+ options.height = sanitizeSize(options.height, getBorderHeight(options.borderStyle), 0);
189
229
  return options;
190
230
  }
191
- const formatTitle = (title, borderStyle) => (borderStyle === NONE ? title : ` ${title} `);
192
- function sizeTitle(options, { widthOverride, maxWidth, widest }) {
193
- if (options.title === undefined)
194
- return;
195
- if (widthOverride) {
196
- options.title = options.title.slice(0, Math.max(0, options.width - HALF));
197
- if (options.title)
198
- options.title = formatTitle(options.title, options.borderStyle);
199
- return;
200
- }
201
- options.title = options.title.slice(0, Math.max(0, maxWidth - HALF));
202
- if (!options.title)
203
- return;
204
- options.title = formatTitle(options.title, options.borderStyle);
205
- if (stringWidth(options.title) > widest)
206
- options.width = stringWidth(options.title);
231
+ const formatLabel = (label, borderStyle) => (borderStyle === NONE ? label : ` ${label} `);
232
+ function fitLabel(label, width, borderStyle, cornerWidth) {
233
+ if (!label)
234
+ return label;
235
+ const frame = borderStyle === NONE ? 0 : LABEL_FRAME;
236
+ const fitted = sliceAnsi(oneRow(label), 0, Math.max(0, width + getBorderWidth(borderStyle) - cornerWidth - frame));
237
+ return fitted && formatLabel(fitted, borderStyle);
207
238
  }
208
239
  function determineDimensions(text, input) {
209
240
  const options = sanitizeOptions(input);
210
- const widthOverride = options.width !== undefined && options.width !== 0;
241
+ const isWidthOverride = options.width !== undefined;
211
242
  const columns = terminalColumns();
212
243
  const borderWidth = getBorderWidth(options.borderStyle);
213
- const maxWidth = columns - options.margin.left - options.margin.right - borderWidth;
214
- const widest = widestLine(wrapAnsi(text, columns - borderWidth, { hard: true, trim: false })) + options.padding.left + options.padding.right;
215
- sizeTitle(options, { widthOverride, maxWidth, widest });
216
- options.width ||= widest;
217
- if (!widthOverride) {
218
- if (options.margin.left && options.margin.right && options.width > maxWidth) {
219
- const spaceForMargins = columns - options.width - borderWidth;
220
- const multiplier = spaceForMargins / (options.margin.left + options.margin.right);
221
- options.margin.left = Math.max(0, Math.floor(options.margin.left * multiplier));
222
- options.margin.right = Math.max(0, Math.floor(options.margin.right * multiplier));
244
+ const cornerWidths = getCornerWidths(options.borderStyle);
245
+ const corners = Math.max(cornerWidths.top, cornerWidths.bottom);
246
+ const terminalWidth = columns - borderWidth;
247
+ const maxContentWidth = Math.min(terminalWidth, options.maxWidth || terminalWidth);
248
+ const marginWidth = () => {
249
+ if (options.float === 'center')
250
+ return 0;
251
+ if (options.float === 'right')
252
+ return options.margin.right;
253
+ return options.margin.left + options.margin.right;
254
+ };
255
+ const availableWidth = isWidthOverride ? columns - borderWidth - (options.float === 'left' ? options.margin.left : 0) : terminalWidth - marginWidth();
256
+ const maxTextWidth = Math.max(1, maxContentWidth - options.padding.left - options.padding.right);
257
+ const wrappedText = text
258
+ .split(NEWLINE)
259
+ .map((line) => wrapLine(line, maxTextWidth))
260
+ .join(NEWLINE);
261
+ let widestRow = Math.min(widestLine(wrappedText) + options.padding.left + options.padding.right, maxContentWidth);
262
+ options.width ||= widestRow;
263
+ if ((options.margin.left || options.margin.right) && Math.max(1, options.width) > availableWidth) {
264
+ const spaceForMargins = columns - Math.max(1, options.width) - borderWidth;
265
+ const multiplier = spaceForMargins / (options.margin.left + options.margin.right);
266
+ options.margin.left = Math.max(0, Math.floor(options.margin.left * multiplier));
267
+ options.margin.right = Math.max(0, Math.floor(options.margin.right * multiplier));
268
+ }
269
+ const labelWidth = isWidthOverride ? options.width : Math.min(columns - borderWidth - marginWidth(), maxContentWidth);
270
+ options.title = fitLabel(options.title, labelWidth, options.borderStyle, cornerWidths.top);
271
+ options.footer = fitLabel(options.footer, labelWidth, options.borderStyle, cornerWidths.bottom);
272
+ if (getBorderHeight(options.borderStyle) === 0 && options.height !== undefined) {
273
+ options.height = Math.max(0, options.height - (options.title ? 1 : 0) - (options.footer ? 1 : 0));
274
+ }
275
+ if (!isWidthOverride) {
276
+ for (const [label, cornerWidth] of [
277
+ [options.title, cornerWidths.top],
278
+ [options.footer, cornerWidths.bottom],
279
+ ]) {
280
+ if (label)
281
+ widestRow = Math.max(widestRow, stringWidth(label) - borderWidth + cornerWidth);
223
282
  }
224
- options.width = Math.min(options.width, columns - borderWidth - options.margin.left - options.margin.right);
283
+ options.width = Math.max(1, Math.min(widestRow, columns - borderWidth - marginWidth()));
225
284
  }
226
- if (options.width - (options.padding.left + options.padding.right) <= 0) {
285
+ options.width = Math.max(options.width, corners - borderWidth, 1);
286
+ if (options.padding.left + options.padding.right >= options.width) {
227
287
  options.padding.left = 0;
228
288
  options.padding.right = 0;
229
289
  }
230
- if (options.height !== undefined && options.height - (options.padding.top + options.padding.bottom) <= 0) {
290
+ if (options.height !== undefined && options.padding.top + options.padding.bottom >= options.height) {
231
291
  options.padding.top = 0;
232
292
  options.padding.bottom = 0;
233
293
  }
234
294
  return options;
235
295
  }
236
296
  export { BOXES as _borderStyles };
237
- export default function boxen(text, options = {}) {
238
- const merged = { borderStyle: 'single', dimBorder: false, textAlignment: 'left', float: 'left', titleAlignment: 'left', padding: 0, ...options };
239
- if (merged.align !== undefined)
240
- merged.textAlignment = merged.align;
241
- if (merged.borderColor !== undefined && !isColorValid(merged.borderColor))
242
- throw new Error(`${merged.borderColor} is not a valid borderColor`);
243
- if (merged.backgroundColor !== undefined && !isColorValid(merged.backgroundColor))
244
- throw new Error(`${merged.backgroundColor} is not a valid backgroundColor`);
297
+ export default function boxen(input, options = {}) {
298
+ const text = writeControls(input.replaceAll(LINE_BREAKS, NEWLINE)).toWellFormed();
299
+ const merged = { padding: 0, dimBorder: false, float: 'left', ...options };
300
+ const borderStyle = merged.borderStyle ?? 'single';
301
+ const textAlignment = merged.textAlignment ?? merged.align ?? 'left';
302
+ for (const name of ['borderColor', 'titleColor', 'backgroundColor']) {
303
+ const color = merged[name];
304
+ if (color && !isColorValid(color))
305
+ throw new Error(`${color} is not a valid ${name}`);
306
+ }
307
+ const borderBackgroundColor = 'borderBackgroundColor' in merged ? merged.borderBackgroundColor : 'inherit';
308
+ if (borderBackgroundColor !== undefined && borderBackgroundColor !== 'inherit' && !isColorValid(borderBackgroundColor)) {
309
+ throw new Error(`${borderBackgroundColor} is not a valid borderBackgroundColor`);
310
+ }
245
311
  const resolved = {
246
312
  ...merged,
313
+ borderStyle,
314
+ textAlignment,
315
+ titleAlignment: merged.titleAlignment ?? 'left',
316
+ footerAlignment: merged.footerAlignment ?? 'left',
317
+ borderBackgroundColor,
247
318
  padding: getObject(merged.padding),
248
319
  margin: getObject(merged.margin),
249
- width: merged.width ?? 0,
320
+ width: merged.width,
321
+ maxWidth: merged.maxWidth,
322
+ height: merged.height,
250
323
  };
251
324
  const dimensions = determineDimensions(text, resolved);
252
- return boxContent(makeContentText(text, dimensions), dimensions.width, dimensions);
325
+ const content = makeContentText(text, dimensions);
326
+ return boxContent(content, Math.max(dimensions.width, widestLine(content)), dimensions);
253
327
  }
package/dist/builtins.js CHANGED
@@ -3,7 +3,7 @@ const LINE_INTERVAL = 130;
3
3
  export const builtins = {
4
4
  name: 'flagstaff',
5
5
  contract: 1,
6
- glyphs: { running: '…', ok: '✔', fail: '✖', warn: '⚠', info: 'ℹ' },
6
+ glyphs: { running: '…', ok: '✔', fail: '✖', warn: '⚠', info: 'ℹ', pending: ' ', tail: '┊', step: '◆' },
7
7
  spinners: {
8
8
  dots: { frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], interval: DOTS_INTERVAL, static: '…' },
9
9
  line: { frames: ['-', '\\', '|', '/'], interval: LINE_INTERVAL, static: '…' },
package/dist/diff.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type Component } from './plugin.js';
2
+ export interface DiffState {
3
+ /** A unified diff, as `git diff` or `diff -u` prints it. */
4
+ diff: string;
5
+ }
6
+ /** A unified diff: unchanged off a terminal, numbered and coloured on one. */
7
+ export declare function diff(): Component<DiffState>;
package/dist/diff.js ADDED
@@ -0,0 +1,40 @@
1
+ import { error, hint, muted, ok } from 'roundel/tokens';
2
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
3
+ function rows(diff) {
4
+ let old = 0;
5
+ let next = 0;
6
+ let oldLeft = 0;
7
+ let newLeft = 0;
8
+ return diff.split('\n').map((line) => {
9
+ const mark = line[0];
10
+ if ((oldLeft > 0 || newLeft > 0) && mark !== '\\') {
11
+ const inOld = mark !== '+';
12
+ const inNew = mark !== '-';
13
+ const paint = inOld ? error : ok;
14
+ const row = { old: inOld ? String(old) : '', new: inNew ? String(next) : '', text: inOld && inNew ? line : paint(line) };
15
+ old += Number(inOld);
16
+ oldLeft -= Number(inOld);
17
+ next += Number(inNew);
18
+ newLeft -= Number(inNew);
19
+ return row;
20
+ }
21
+ const hunk = HUNK.exec(line);
22
+ if (hunk !== null) {
23
+ [old, oldLeft, next, newLeft] = [Number(hunk[1]), Number(hunk[2] ?? 1), Number(hunk[3]), Number(hunk[4] ?? 1)];
24
+ return { old: '', new: '', text: hint(line) };
25
+ }
26
+ return { old: '', new: '', text: muted(line) };
27
+ });
28
+ }
29
+ const body = (diff) => (diff.endsWith('\n') ? diff.slice(0, -1) : diff);
30
+ export function diff() {
31
+ return {
32
+ name: 'diff',
33
+ static: (state) => body(state.diff),
34
+ frame: (_t, state) => {
35
+ const numbered = rows(body(state.diff));
36
+ const gutter = Math.max(...numbered.map((row) => Math.max(row.old.length, row.new.length)));
37
+ return numbered.map((row) => `${muted(`${row.old.padStart(gutter)} ${row.new.padStart(gutter)} │`)} ${row.text}`).join('\n');
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,15 @@
1
+ import { type Component } from './plugin.js';
2
+ /** One entry of the stream: a line of output, or the start of a step. */
3
+ export type LogLine = string | {
4
+ step: string;
5
+ };
6
+ export interface LogTailState {
7
+ /** Every entry the stream has produced so far, oldest first. */
8
+ lines: readonly LogLine[];
9
+ }
10
+ export interface LogTailOptions {
11
+ /** Rows the tail shows on a terminal. Default 5; anything below 1 is 1. */
12
+ height?: number;
13
+ }
14
+ /** A log tail: the whole stream, appended, off a terminal; its last `height` rows on one. */
15
+ export declare function logTail({ height }?: LogTailOptions): Component<LogTailState>;
@@ -0,0 +1,45 @@
1
+ import { heading, muted } from 'roundel/tokens';
2
+ import { glyph, register } from './plugin.js';
3
+ const HEIGHT = 5;
4
+ const tail = (text) => ({ text: `${muted(glyph('tail'))} ${text}`, current: false });
5
+ function rows(entry, current) {
6
+ if (typeof entry === 'string')
7
+ return entry.split('\n').map(tail);
8
+ const [first, ...rest] = entry.step.split('\n');
9
+ const mark = current ? heading(glyph('step')) : muted(glyph('step'));
10
+ return [{ text: `${mark} ${current ? heading(first) : first}`, current }, ...rest.map(tail)];
11
+ }
12
+ export function logTail({ height = HEIGHT } = {}) {
13
+ const shown = Math.max(1, Math.floor(height));
14
+ return {
15
+ name: 'log-tail',
16
+ static: ({ lines }) => lines
17
+ .flatMap((entry) => rows(entry, false))
18
+ .map((row) => row.text)
19
+ .join('\n'),
20
+ frame: (_t, { lines }) => {
21
+ const current = lines.findLastIndex((entry) => typeof entry !== 'string');
22
+ let window = [];
23
+ for (let i = lines.length - 1; i >= 0 && window.length < shown; i -= 1)
24
+ window = [...rows(lines[i], i === current), ...window];
25
+ window = window.slice(-shown);
26
+ if (current >= 0 && !window.some((row) => row.current))
27
+ window = [...rows(lines[current], true).slice(0, 1), ...window.slice(window.length - (shown - 1))];
28
+ return window.map((row) => row.text).join('\n');
29
+ },
30
+ };
31
+ }
32
+ const builtin = logTail();
33
+ register({
34
+ name: 'flagstaff',
35
+ components: {
36
+ 'log-tail': {
37
+ static: builtin.static,
38
+ frame: builtin.frame,
39
+ sample: {
40
+ running: { lines: [{ step: 'Installing packages' }, 'npm install', 'added 12 packages'] },
41
+ done: { lines: [{ step: 'Installing packages' }, 'npm install', 'added 12 packages', { step: 'Done' }] },
42
+ },
43
+ },
44
+ },
45
+ });