Apply prettier to css, html, js, md, ts, and yml (#1249)

* Apply prettier to css, js, html, md, ts, and yml

As a followup I will add prettier to the .pre-commit config.
This patch is 100% generated by prettier.
I used a forked version of prettier that understands the
py-script tag.
See https://github.com/hoodmane/pyscript-prettier-precommit
for more info.

* Apply old pre-commit

* Revert some problems

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Revert some changes

* More changes

* Fix pre-commit

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Hood Chatham
2023-03-06 15:20:21 +01:00
committed by GitHub
parent 7ffe6a598e
commit 08f34f748b
108 changed files with 4571 additions and 3802 deletions

View File

@@ -34,11 +34,16 @@ export function make_PyScript(interpreter: InterpreterClient, app: PyScriptApp)
const pySrc = await this.getPySrc();
this.innerHTML = '';
app.plugins.beforePyScriptExec({interpreter: interpreter, src: pySrc, pyScriptTag: this});
app.plugins.beforePyScriptExec({ interpreter: interpreter, src: pySrc, pyScriptTag: this });
const result = (await pyExec(interpreter, pySrc, this)).result;
app.plugins.afterPyScriptExec({interpreter: interpreter, src: pySrc, pyScriptTag: this, result: result});
app.plugins.afterPyScriptExec({
interpreter: interpreter,
src: pySrc,
pyScriptTag: this,
result: result,
});
} finally {
releaseLock()
releaseLock();
}
}
@@ -199,8 +204,7 @@ function createElementsWithEventListeners(interpreter: InterpreterClient, pyAttr
void (async () => {
try {
await interpreter.run(handlerCode);
}
catch (err) {
} catch (err) {
displayPyException(err, el.parentElement);
}
})();

View File

@@ -12,51 +12,49 @@ The convention is:
*/
export enum ErrorCode {
GENERIC = "PY0000", // Use this only for development then change to a more specific error code
FETCH_ERROR = "PY0001",
FETCH_NAME_ERROR = "PY0002",
// Currently these are created depending on error code received from fetching
FETCH_UNAUTHORIZED_ERROR = "PY0401",
FETCH_FORBIDDEN_ERROR = "PY0403",
FETCH_NOT_FOUND_ERROR = "PY0404",
FETCH_SERVER_ERROR = "PY0500",
FETCH_UNAVAILABLE_ERROR = "PY0503",
BAD_CONFIG = "PY1000",
MICROPIP_INSTALL_ERROR = "PY1001",
BAD_PLUGIN_FILE_EXTENSION = "PY2000",
NO_DEFAULT_EXPORT = "PY2001",
TOP_LEVEL_AWAIT = "PY9000"
GENERIC = 'PY0000', // Use this only for development then change to a more specific error code
FETCH_ERROR = 'PY0001',
FETCH_NAME_ERROR = 'PY0002',
// Currently these are created depending on error code received from fetching
FETCH_UNAUTHORIZED_ERROR = 'PY0401',
FETCH_FORBIDDEN_ERROR = 'PY0403',
FETCH_NOT_FOUND_ERROR = 'PY0404',
FETCH_SERVER_ERROR = 'PY0500',
FETCH_UNAVAILABLE_ERROR = 'PY0503',
BAD_CONFIG = 'PY1000',
MICROPIP_INSTALL_ERROR = 'PY1001',
BAD_PLUGIN_FILE_EXTENSION = 'PY2000',
NO_DEFAULT_EXPORT = 'PY2001',
TOP_LEVEL_AWAIT = 'PY9000',
}
export class UserError extends Error {
messageType: MessageType;
errorCode: ErrorCode;
messageType: MessageType;
errorCode: ErrorCode;
constructor(errorCode: ErrorCode, message: string, t: MessageType = "text") {
super(message);
this.errorCode = errorCode;
this.name = "UserError";
this.messageType = t;
this.message = `(${errorCode}): ${message}`;
}
constructor(errorCode: ErrorCode, message: string, t: MessageType = 'text') {
super(message);
this.errorCode = errorCode;
this.name = 'UserError';
this.messageType = t;
this.message = `(${errorCode}): ${message}`;
}
}
export class FetchError extends UserError {
errorCode: ErrorCode;
constructor(errorCode: ErrorCode, message: string) {
super(errorCode, message)
this.name = "FetchError";
}
errorCode: ErrorCode;
constructor(errorCode: ErrorCode, message: string) {
super(errorCode, message);
this.name = 'FetchError';
}
}
export class InstallError extends UserError {
errorCode: ErrorCode;
constructor(errorCode: ErrorCode, message: string) {
super(errorCode, message)
this.name = "InstallError";
}
errorCode: ErrorCode;
constructor(errorCode: ErrorCode, message: string) {
super(errorCode, message);
this.name = 'InstallError';
}
}
export function _createAlertBanner(

View File

@@ -11,7 +11,6 @@ InterpreterClient class is responsible to request code execution
(among other things) from a `RemoteInterpreter`
*/
export class InterpreterClient extends Object {
_remote: RemoteInterpreter;
config: AppConfig;
/**
@@ -41,7 +40,7 @@ export class InterpreterClient extends Object {
* the remote interpreter.
* Python exceptions are turned into JS exceptions.
* */
async run(code: string): Promise<{result: any}> {
async run(code: string): Promise<{ result: any }> {
return await this._remote.run(code);
}

View File

@@ -42,7 +42,7 @@ function getLogger(prefix: string): Logger {
}
function _makeLogger(prefix: string): Logger {
prefix =`[${prefix}] `;
prefix = `[${prefix}] `;
function make(level: string) {
const out_fn = console[level].bind(console);

View File

@@ -208,7 +208,7 @@ export class PyScriptApp {
logger.info('importing pyscript');
// Save and load pyscript.py from FS
interpreter._remote.interface.FS.mkdirTree("/home/pyodide/pyscript");
interpreter._remote.interface.FS.mkdirTree('/home/pyodide/pyscript');
interpreter._remote.interface.FS.writeFile('pyscript/__init__.py', pyscript);
//Refresh the module cache so Python consistently finds pyscript module
interpreter._remote.invalidate_module_path_cache();

View File

@@ -5,7 +5,7 @@ import { make_PyScript } from './components/pyscript';
import { InterpreterClient } from './interpreter_client';
const logger = getLogger('plugin');
type PyScriptTag = InstanceType<ReturnType<typeof make_PyScript>>;
type PyScriptTag = InstanceType<ReturnType<typeof make_PyScript>>;
export class Plugin {
/** Validate the configuration of the plugin and handle default values.
@@ -48,7 +48,7 @@ export class Plugin {
* @param options.src {string} The Python source code to be evaluated
* @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation
*/
beforePyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag}) {}
beforePyScriptExec(options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag }) {}
/** The Python in a <py-script> has just been evaluated, but control
* has not been ceded back to the JavaScript event loop yet
@@ -58,7 +58,12 @@ export class Plugin {
* @param options.pyScriptTag The <py-script> HTML tag that originated the evaluation
* @param options.result The returned result of evaluating the Python (if any)
*/
afterPyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag, result: any}) {}
afterPyScriptExec(options: {
interpreter: InterpreterClient;
src: string;
pyScriptTag: PyScriptTag;
result: any;
}) {}
/** Startup complete. The interpreter is initialized and ready, user
* scripts have been executed: the main initialization logic ends here and
@@ -122,13 +127,13 @@ export class PluginManager {
for (const p of this._pythonPlugins) p.afterStartup?.(interpreter);
}
beforePyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag}) {
beforePyScriptExec(options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag }) {
for (const p of this._plugins) p.beforePyScriptExec?.(options);
for (const p of this._pythonPlugins) p.beforePyScriptExec?.callKwargs(options);
}
afterPyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag, result: any}) {
afterPyScriptExec(options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag; result: any }) {
for (const p of this._plugins) p.afterPyScriptExec?.(options);
for (const p of this._pythonPlugins) p.afterPyScriptExec?.callKwargs(options);

View File

@@ -1,5 +1,5 @@
import { joinPaths } from '../utils';
import { FetchConfig } from "../pyconfig";
import { FetchConfig } from '../pyconfig';
import { UserError, ErrorCode } from '../exceptions';
export function calculatePaths(fetch_cfg: FetchConfig[]) {
@@ -10,14 +10,9 @@ export function calculatePaths(fetch_cfg: FetchConfig[]) {
const to_folder = each_fetch_cfg.to_folder || '.';
const to_file = each_fetch_cfg.to_file;
const files = each_fetch_cfg.files;
if (files !== undefined)
{
if (to_file !== undefined)
{
throw new UserError(
ErrorCode.BAD_CONFIG,
`Cannot use 'to_file' and 'files' parameters together!`
);
if (files !== undefined) {
if (to_file !== undefined) {
throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`);
}
for (const each_f of files) {
const each_fetch_path = joinPaths([from, each_f]);
@@ -31,10 +26,9 @@ export function calculatePaths(fetch_cfg: FetchConfig[]) {
if (filename === '') {
throw new UserError(
ErrorCode.BAD_CONFIG,
`Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`
`Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`,
);
}
else {
} else {
paths.push(joinPaths([to_folder, filename]));
}
}

View File

@@ -1,9 +1,9 @@
import { Plugin } from "../plugin";
import { TargetedStdio, StdioMultiplexer } from "../stdio";
import { make_PyScript } from "../components/pyscript";
import { InterpreterClient } from "../interpreter_client";
import { Plugin } from '../plugin';
import { TargetedStdio, StdioMultiplexer } from '../stdio';
import { make_PyScript } from '../components/pyscript';
import { InterpreterClient } from '../interpreter_client';
type PyScriptTag = InstanceType<ReturnType<typeof make_PyScript>>;
type PyScriptTag = InstanceType<ReturnType<typeof make_PyScript>>;
/**
* The StdioDirector plugin captures the output to Python's sys.stdio and
@@ -17,8 +17,8 @@ export class StdioDirector extends Plugin {
_stdioMultiplexer: StdioMultiplexer;
constructor(stdio: StdioMultiplexer) {
super()
this._stdioMultiplexer = stdio
super();
this._stdioMultiplexer = stdio;
}
/** Prior to a <py-script> tag being evaluated, if that tag itself has
@@ -27,30 +27,35 @@ export class StdioDirector extends Plugin {
* with that ID for the duration of the evaluation.
*
*/
beforePyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag}): void {
if (options.pyScriptTag.hasAttribute("output")){
const targeted_io = new TargetedStdio(options.pyScriptTag, "output", true, true)
options.pyScriptTag.stdout_manager = targeted_io
this._stdioMultiplexer.addListener(targeted_io)
beforePyScriptExec(options: { interpreter: InterpreterClient; src: string; pyScriptTag: PyScriptTag }): void {
if (options.pyScriptTag.hasAttribute('output')) {
const targeted_io = new TargetedStdio(options.pyScriptTag, 'output', true, true);
options.pyScriptTag.stdout_manager = targeted_io;
this._stdioMultiplexer.addListener(targeted_io);
}
if (options.pyScriptTag.hasAttribute("stderr")){
const targeted_io = new TargetedStdio(options.pyScriptTag, "stderr", false, true)
options.pyScriptTag.stderr_manager = targeted_io
this._stdioMultiplexer.addListener(targeted_io)
if (options.pyScriptTag.hasAttribute('stderr')) {
const targeted_io = new TargetedStdio(options.pyScriptTag, 'stderr', false, true);
options.pyScriptTag.stderr_manager = targeted_io;
this._stdioMultiplexer.addListener(targeted_io);
}
}
/** After a <py-script> tag is evaluated, if that tag has a 'stdout_manager'
* (presumably TargetedStdio, or some other future IO handler), it is removed.
*/
afterPyScriptExec(options: {interpreter: InterpreterClient, src: string, pyScriptTag: PyScriptTag, result: any}): void {
if (options.pyScriptTag.stdout_manager != null){
this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager)
options.pyScriptTag.stdout_manager = null
afterPyScriptExec(options: {
interpreter: InterpreterClient;
src: string;
pyScriptTag: PyScriptTag;
result: any;
}): void {
if (options.pyScriptTag.stdout_manager != null) {
this._stdioMultiplexer.removeListener(options.pyScriptTag.stdout_manager);
options.pyScriptTag.stdout_manager = null;
}
if (options.pyScriptTag.stderr_manager != null){
this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager)
options.pyScriptTag.stderr_manager = null
if (options.pyScriptTag.stderr_manager != null) {
this._stdioMultiplexer.removeListener(options.pyScriptTag.stderr_manager);
options.pyScriptTag.stderr_manager = null;
}
}
}

View File

@@ -22,14 +22,14 @@ export async function pyExec(interpreter: InterpreterClient, pysrc: string, outE
'\nSee https://docs.pyscript.net/latest/guides/asyncio.html for more information.',
);
}
return (await interpreter.run(pysrc));
return await interpreter.run(pysrc);
} catch (err) {
// XXX: currently we display exceptions in the same position as
// the output. But we probably need a better way to do that,
// e.g. allowing plugins to intercept exceptions and display them
// in a configurable way.
displayPyException(err, outElem);
return {result: undefined};
return { result: undefined };
}
} finally {
pyscript_py.set_current_display_target(undefined);

View File

@@ -37,9 +37,7 @@ export class RemoteInterpreter extends Object {
// TODO: Remove this once `runtimes` is removed!
interpreter: InterpreterInterface;
constructor(
src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js'
) {
constructor(src = 'https://cdn.jsdelivr.net/pyodide/v0.22.1/full/pyodide.js') {
super();
this.src = src;
}
@@ -87,11 +85,11 @@ export class RemoteInterpreter extends Object {
await this.loadPackage('micropip');
}
logger.info('pyodide loaded and initialized');
await this.run('print("Python initialization complete")')
await this.run('print("Python initialization complete")');
}
/* eslint-disable */
async run(code: string): Promise<{result: any}> {
async run(code: string): Promise<{ result: any }> {
/**
* eslint wants `await` keyword to be used i.e.
* { result: await this.interface.runPython(code) }
@@ -134,10 +132,12 @@ export class RemoteInterpreter extends Object {
// for which the signature of `loadPackage` accepts the above params as args i.e.
// the call uses `logger.info.bind(logger), logger.info.bind(logger)`.
const pyodide_version = (await this.run("import sys; sys.modules['pyodide'].__version__")).result.toString();
if (pyodide_version.startsWith("0.22")) {
await this.interface.loadPackage(names, { messageCallback: logger.info.bind(logger), errorCallback: logger.info.bind(logger) });
}
else {
if (pyodide_version.startsWith('0.22')) {
await this.interface.loadPackage(names, {
messageCallback: logger.info.bind(logger),
errorCallback: logger.info.bind(logger),
});
} else {
await this.interface.loadPackage(names, logger.info.bind(logger), logger.info.bind(logger));
}
}

View File

@@ -1,4 +1,4 @@
import { createSingularWarning, escape } from "./utils";
import { createSingularWarning, escape } from './utils';
export interface Stdio {
stdout_writeline: (msg: string) => void;
@@ -42,8 +42,7 @@ export class CaptureStdio implements Stdio {
* specified by ID. Used with "output" keyword.
*
*/
export class TargetedStdio implements Stdio{
export class TargetedStdio implements Stdio {
source_element: HTMLElement;
source_attribute: string;
capture_stdout: boolean;
@@ -66,31 +65,32 @@ export class TargetedStdio implements Stdio{
*
* @param msg The output to be written
*/
writeline_by_attribute(msg:string){
const target_id = this.source_element.getAttribute(this.source_attribute)
const target = document.getElementById(target_id)
if (target === null) { // No matching ID
createSingularWarning(`${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`)
writeline_by_attribute(msg: string) {
const target_id = this.source_element.getAttribute(this.source_attribute);
const target = document.getElementById(target_id);
if (target === null) {
// No matching ID
createSingularWarning(
`${this.source_attribute} = "${target_id}" does not match the id of any element on the page.`,
);
} else {
msg = escape(msg).replace('\n', '<br>');
if (!msg.endsWith('<br/>') && !msg.endsWith('<br>')) {
msg = msg + '<br>';
}
else {
msg = escape(msg).replace("\n", "<br>")
if (!msg.endsWith("<br/>") && !msg.endsWith("<br>")){
msg = msg + "<br>"
}
target.innerHTML += msg
}
}
stdout_writeline (msg: string) {
if (this.capture_stdout){
this.writeline_by_attribute(msg)
target.innerHTML += msg;
}
}
stderr_writeline (msg: string) {
if (this.capture_stderr){
this.writeline_by_attribute(msg)
stdout_writeline(msg: string) {
if (this.capture_stdout) {
this.writeline_by_attribute(msg);
}
}
stderr_writeline(msg: string) {
if (this.capture_stderr) {
this.writeline_by_attribute(msg);
}
}
}
@@ -109,9 +109,9 @@ export class StdioMultiplexer implements Stdio {
}
removeListener(obj: Stdio) {
const index = this._listeners.indexOf(obj)
if (index > -1){
this._listeners.splice(index, 1)
const index = this._listeners.indexOf(obj);
if (index > -1) {
this._listeners.splice(index, 1);
}
}

View File

@@ -1,34 +1,35 @@
/* py-config - not a component */
py-config {
display: none
display: none;
}
/* py-{el} - components not defined */
py-script:not(:defined) {
display: none
display: none;
}
py-repl:not(:defined) {
display: none
display: none;
}
py-title:not(:defined) {
display: none
display: none;
}
py-inputbox:not(:defined) {
display: none
display: none;
}
py-button:not(:defined) {
display: none
display: none;
}
py-box:not(:defined) {
display: none
display: none;
}
html {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue',
Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
line-height: 1.5;
}
@@ -110,7 +111,7 @@ html {
/* Pop-up second layer end */
.alert-banner {
position: relative;
padding: .5rem 1.5rem .5rem .5rem;
padding: 0.5rem 1.5rem 0.5rem 0.5rem;
margin: 5px 0;
}
@@ -118,8 +119,8 @@ html {
margin: 0;
}
.py-error{
background-color: #FFE9E8;
.py-error {
background-color: #ffe9e8;
border: solid;
border-color: #f0625f;
color: #9d041c;
@@ -132,24 +133,24 @@ html {
color: #794700;
}
.alert-banner.py-error>#alert-close-button {
.alert-banner.py-error > #alert-close-button {
color: #9d041c;
}
.alert-banner.py-warning>#alert-close-button {
color: #794700
.alert-banner.py-warning > #alert-close-button {
color: #794700;
}
#alert-close-button {
position: absolute;
right: .5rem;
top: .5rem;
cursor: pointer;
background: transparent;
border: none;
position: absolute;
right: 0.5rem;
top: 0.5rem;
cursor: pointer;
background: transparent;
border: none;
}
.py-box{
.py-box {
display: flex;
flex-direction: row;
justify-content: flex-start;
@@ -168,10 +169,7 @@ border: none;
border-color: rgba(209, 213, 219, var(--tw-border-opacity));
border-width: 1px;
position: relative;
--tw-ring-inset: var(--tw-empty,
/*!*/
/*!*/
);
--tw-ring-inset: var(--tw-empty, /*!*/ /*!*/);
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgba(59, 130, 246, 0.5);
@@ -183,7 +181,7 @@ border: none;
box-sizing: border-box;
border-width: 1px;
border-style: solid;
border-color: rgb(209, 213, 219)
border-color: rgb(209, 213, 219);
}
.editor-box:hover button {

View File

@@ -1,4 +1,4 @@
import { _createAlertBanner } from "./exceptions"
import { _createAlertBanner } from './exceptions';
export function addClasses(element: HTMLElement, classes: string[]) {
for (const entry of classes) {
@@ -127,11 +127,11 @@ export function createLock() {
* @private
*/
async function acquireLock() {
const old_lock = _lock;
let releaseLock: () => void;
_lock = new Promise((resolve) => (releaseLock = resolve));
await old_lock;
return releaseLock;
const old_lock = _lock;
let releaseLock: () => void;
_lock = new Promise(resolve => (releaseLock = resolve));
await old_lock;
return releaseLock;
}
return acquireLock;
}
}