Files
pyscript/pyscriptjs/src/components/pyconfig.ts
Antonio Cuni f3157b377f Improve JS logging (#743)
This PR tries to improve and rationalize what we log. Key points:
- introduce `logger.ts`: each file/component is encouraged to use the logger instead of writing directly to `console.*`
    * the logger automatically prepend a prefix like `[py-config]`, `[py-env]` which make it easier to understand where a certain message is printed from
    * it provide a central place where to add more features in the future. E.g., I can imagine having a config setting to completely silence the logs (not implemented yet)
- use the new loggers everywhere
- write to `.info()` instead of `.log()`. The idea is to keep `console.log` free, so that for the users it's easier to tell apart their own messages and the pyscript ones
- generally improve what we log. This is an endless exercise, but I tried to print more things which are useful to understand what's going on and in which order the various things are executed, and remove prints which were clearly debugging leftovers
2022-09-06 15:18:41 +02:00

75 lines
2.1 KiB
TypeScript

import * as jsyaml from 'js-yaml';
import { BaseEvalElement } from './base';
import { appConfig } from '../stores';
import type { AppConfig, Runtime } from '../runtime';
import { PyodideRuntime, DEFAULT_RUNTIME_CONFIG } from '../pyodide';
import { getLogger } from '../logger';
const logger = getLogger('py-config');
/**
* Configures general metadata about the PyScript application such
* as a list of runtimes, name, version, closing the loader
* automatically, etc.
*
* Also initializes the different runtimes passed. If no runtime is passed,
* the default runtime based on Pyodide is used.
*/
export class PyConfig extends BaseEvalElement {
widths: Array<string>;
label: string;
mount_name: string;
details: HTMLElement;
operation: HTMLElement;
values: AppConfig;
constructor() {
super();
}
connectedCallback() {
this.code = this.innerHTML;
this.innerHTML = '';
const loadedValues = jsyaml.load(this.code);
if (loadedValues === undefined) {
this.values = {
autoclose_loader: true,
runtimes: [DEFAULT_RUNTIME_CONFIG]
};
} else {
// eslint-disable-next-line
// @ts-ignore
this.values = loadedValues;
}
appConfig.set(this.values);
logger.info('config set:', this.values);
this.loadRuntimes();
}
log(msg: string) {
const newLog = document.createElement('p');
newLog.innerText = msg;
this.details.appendChild(newLog);
}
close() {
this.remove();
}
loadRuntimes() {
logger.info('Initializing runtimes');
for (const runtime of this.values.runtimes) {
const runtimeObj: Runtime = new PyodideRuntime(runtime.src, runtime.name, runtime.lang);
const script = document.createElement('script'); // create a script DOM node
script.src = runtimeObj.src; // set its src to the provided URL
script.addEventListener('load', () => {
void runtimeObj.initialize();
});
document.head.appendChild(script);
}
}
}