Closed jonnydungeons closed 3 years ago
This library produces terminal encoded ascii art using ansi codes ( https://en.wikipedia.org/wiki/ANSI_escape_code ) expanding this to work with html styles is a pretty major task (but one I'd love someone to pick up). Currently I'm working on support for ansi256 which lays the groundwork for supporting ansiart and after that petscii(these goals support other input formats, rather than display formats). My main priority is support for the existing standards and formats. It would be cake to plug this library into ansi-to-html
( https://www.npmjs.com/package/ansi-to-html ) or strip-ansi
( https://www.npmjs.com/package/strip-ansi ) to get what you want though (however, it maybe questionable to do all that work: transfer the image, work in canvas, transform it to ascii, then strip ansi codes (and not save any of it) for what is ultimately displayed as text).
Are the ANSI codes the same, just different escape sequences in the terminal vs browser?
There are no ansi codes in the browser. Usually (in the browser) people want span-wrapped characters or ansi-free art, which is why I suggest the modules above.
The next major release (3.0) will emphasize a webcomponent to do all the browser interaction as well as introducing some new functionality. Until then, the above still applies.
So I've long been recommending other libs for converting to HTML, however given the other libs are all using regex, that can lead to security issues. So instead, I'd just offer a simple stopgap:
var ansi = reuire('ascii-art-ansi');
var Color = reuire('ascii-art-ansi/color');
module.exports = function(str){
return ansi.map(str, function(chr, codes, rowcol, pos, shortcircuit){
if(chr === "\n") return '<br>';
var foregroundList = codes.filter(function(code){
return ansi.is.it.foregroundcolor(code);
});
var backgroundList = codes.filter(function(code){
return ansi.is.it.backgroundcolor(code);
});
var foreground = foregroundList[foregroundList.length-1];
var background = backgroundList[foregroundList.length-1];
var style = '';
if(foreground) style += ' color: '+Color.value(foreground)+';';
if(background) style += ' background-color: '+Color.value(background)+';';
if(chr === " ") return '<span style="'+style+'">'+" "+'</span>';
return '<span style="'+style+'">'+chr+'</span>';
}, true);
};
This will use a single pass scan to convert, respects background and foreground and should have a better performance with respect to long strings (make sure to put in a container that uses a monospace font and a line-height of 1
).
webcomponent support has landed, so closing this out... you are still welcome to use ascii-art programmatically, though.
Can you please provide a new or existing example of using this with reactjs and outputting the art to the console? Currently I have a static txt file which contains ascii.