xrsh-com/com/isoterminal/feat/jsconsole.js

79 lines
2.5 KiB
JavaScript
Raw Normal View History

ISOTerminal.prototype.redirectConsole = function(handler){
const log = console.log;
const dir = console.dir;
const err = console.error;
const warn = console.warn;
2025-01-15 22:36:54 +01:00
const addLineFeeds = (str) => str.replace(/\n/g,"\n\r")
console.log = (...args)=>{
const textArg = args[0];
2025-01-15 22:36:54 +01:00
handler( addLineFeeds(textArg) );
log.apply(log, args);
};
console.error = (...args)=>{
const textArg = args[0]
2025-01-15 22:36:54 +01:00
handler( addLineFeeds(textArg), '\x1b[31merror\x1b[0m');
err.apply(log, args);
};
console.dir = (...args)=>{
const textArg = args[0]
2025-01-15 22:36:54 +01:00
let str = JSON.stringify(textArg,null,2)+'\n'
handler( addLineFeeds(str) )
dir.apply(log, args);
};
console.warn = (...args)=>{
const textArg = args[0]
2025-01-15 22:36:54 +01:00
handler( addLineFeeds(textArg),'\x1b[38;5;208mwarn\x1b[0m');
err.apply(log, args);
};
}
2025-01-15 22:36:54 +01:00
ISOTerminal.prototype.enableConsole = function(opts){
opts = opts || {stdout:false}
this.redirectConsole( (str,prefix) => {
let finalStr = "";
2025-01-15 22:36:54 +01:00
prefix = prefix ? prefix+' ' : ''
str.trim().split("\n").map( (line) => {
2025-01-15 22:36:54 +01:00
finalStr += `${opts.stdout ? '' : "\x1b[38;5;165m/dev/browser: \x1b[0m"}`+prefix+line+'\n'
})
2025-01-15 22:36:54 +01:00
if( opts.stdout ){
this.emit('serial-output-string', finalStr)
}else this.emit('append_file', ["/dev/browser/console",finalStr])
})
window.addEventListener('error', function(event) {
2024-09-25 15:58:40 +02:00
if( event.filename ){
console.error(event.filename+":"+event.lineno+":"+event.colno)
console.error(event.message);
console.error(event.error);
}else console.error(event)
});
window.addEventListener('unhandledrejection', function(event) {
2024-09-25 15:58:40 +02:00
console.error(event);
});
2025-01-15 22:36:54 +01:00
if( opts.stdout ){
this.emit('serial-output-string', "\n\n\r☑ initialized javascript console\n");
this.emit('serial-output-string', "\r☑ please use these functions to print:\n");
this.emit('serial-output-string', "\r└☑ console.log(\"foo\")\n");
this.emit('serial-output-string', "\r└☑ console.warn(\"foo\")\n");
this.emit('serial-output-string', "\r└☑ console.dir({foo:12})\n");
this.emit('serial-output-string', "\r└☑ console.error(\"foo\")\n");
this.emit('serial-output-string', "\r\n");
}
}
ISOTerminal.addEventListener('emulator-started', function(){
this.enableConsole()
})
ISOTerminal.addEventListener('init', function(){
this.addEventListener('enable-console', function(opts){
this.enableConsole(opts.detail)
})
})