Skip to content

Commit

Permalink
chore: tokenize in shell output component
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Oct 15, 2020
1 parent 83a2a7b commit 8a767a7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 22 deletions.
23 changes: 21 additions & 2 deletions src/components/Terminal/ShellOutput.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import React from 'react';
import PropTypes from 'prop-types';
import { css } from '@emotion/core';

const TOKENS = /{([a-z]+)}(.*?(?={|$))/g;

const ShellOutput = ({ line }) => (
<div
css={css`
color: #fafafa;
white-space: pre;
`}
>
{line.map((token, key) => (
{tokenize(line).map((token, key) => (
<span
key={key}
css={css`
Expand All @@ -26,6 +28,23 @@ const ShellOutput = ({ line }) => (
</div>
);

const tokenize = (text) => {
const tokens = Array.from(text.matchAll(TOKENS));

if (tokens.length === 0) {
return [{ color: 'plain', text }];
}

const startOfColorIdx = text.indexOf('{');
const coloredTokens = tokens.map(([, color, text]) => ({ color, text }));

return startOfColorIdx === 0
? coloredTokens
: [{ color: 'plain', text: text.slice(0, startOfColorIdx) }].concat(
coloredTokens
);
};

const OUTPUT_COLORS = {
plain: 'currentColor',
green: 'var(--color-nord-14)',
Expand All @@ -42,7 +61,7 @@ OUTPUT_COLORS.success = OUTPUT_COLORS.green;
OUTPUT_COLORS.error = OUTPUT_COLORS.red;

ShellOutput.propTypes = {
line: PropTypes.arrayOf(PropTypes.object).isRequired,
line: PropTypes.string.isRequired,
};

export default ShellOutput;
21 changes: 1 addition & 20 deletions src/components/Terminal/rollupIntoCommands.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const MULTILINE_COMMAND = /\\\s*$/;
const OUTPUT_TAG = /^\[output\](\s|$)/;
const OUTPUT_COLOR_TOKENS = /{([a-z]+)}(.*?(?={|$))/g;

const rollupIntoCommands = (lines, code) => {
const rawLines = code.split('\n');
Expand All @@ -17,7 +16,7 @@ const rollupIntoCommands = (lines, code) => {
if (OUTPUT_TAG.test(command)) {
commands[updateIdx] = {
...data,
output: [...data.output, tokenizeOutputLine(rawLines[idx])],
output: [...data.output, rawLines[idx].replace(OUTPUT_TAG, '')],
};
} else {
commands[updateIdx] = { ...data, lines: [...data.lines, line] };
Expand All @@ -38,22 +37,4 @@ const collapse = (line) => {
.join('');
};

const tokenizeOutputLine = (line) => {
const text = line.replace(OUTPUT_TAG, '');
const tokens = Array.from(text.matchAll(OUTPUT_COLOR_TOKENS));

if (tokens.length === 0) {
return [{ color: 'plain', text }];
}

const startOfColorIdx = text.indexOf('{');
const coloredTokens = tokens.map(([, color, text]) => ({ color, text }));

return startOfColorIdx === 0
? coloredTokens
: [{ color: 'plain', text: text.slice(0, startOfColorIdx) }].concat(
coloredTokens
);
};

export default rollupIntoCommands;

0 comments on commit 8a767a7

Please sign in to comment.