Repository: pyscript/pyscript
File: pyscriptjs/src/components/pyrepl.ts (TypeScript)

Code before:

        /**
         * Fetch url from src attribute of py-repl tags and
         * preload the code from fetch response into the Corresponding py-repl tag,
         * but please note that they will not be pre-run unless you click the runbotton.
         */
        async loadReplSrc() {
            await fetch(this.src)
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        logger.error(
                            `loading code from ${this.src} to repl...Failed ${response.status} (${response.statusText})`,
                        );
                    }
                })
                .then(content => {
                    if (content !== void 0) {
                        const code = content.toString().replace(/[<&]/g, match => (match === '<' ? '&lt;' : '&amp;'));
                        const parentElement = this.querySelector("div[class='cm-content']");
                        let childCounts = parentElement.children.length;
                        while (childCounts-- > 1) {
                            parentElement.removeChild(parentElement.firstChild);
                        }
                        parentElement.firstElementChild.innerHTML = code;
                        logger.info(`loading code from ${this.src} to repl...success`);
                    }
                });
        }

        /** Create and configure the codemirror editor
         */
        makeEditor(pySrc: string): EditorView {
            const languageConf = new Compartment();
            const extensions = [
                indentUnit.of('    '),
                basicSetup,
                languageConf.of(python()),
                keymap.of([
                    ...defaultKeymap,
                    { key: 'Ctrl-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
                    { key: 'Shift-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
                ]),
            ];

            if (this.getAttribute('theme') === 'dark') {
                extensions.push(oneDarkTheme);
            }

            return new EditorView({

Review comment (suggestion):
if we are sure there is at least an element all you need to do here is:

```js
const { lastElementChild } = parentElement;
parentElement.replaceChildren(lastElementChild);
lastElementChild.innerHTML = code;
```

this simplifies the `while` loop which, if I understood, removes all children in front and then uses the remaining one (last one) to inject the code.

https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren

Code after:
            }
        }

        /**
         * Fetch url from src attribute of py-repl tags and
         * preload the code from fetch response into the Corresponding py-repl tag,
         * but please note that they will not be pre-run unless you click the runbotton.
         */
        async loadReplSrc() {
            try {
                const response = await robustFetch(this.src);
                if (!response.ok) {
                    return;
                }
                const cmcontentElement = this.querySelector("div[class='cm-content']");
                const { lastElementChild } = cmcontentElement;
                cmcontentElement.replaceChildren(lastElementChild);
                lastElementChild.textContent = await response.text();
                logger.info(`loading code from ${this.src} to repl...success`);
            } catch (err) {
                const e = err as Error;
                _createAlertBanner(e.message);
            }
        }

        /** Create and configure the codemirror editor
         */
        makeEditor(pySrc: string): EditorView {
            const languageConf = new Compartment();
            const extensions = [
                indentUnit.of('    '),
                basicSetup,
                languageConf.of(python()),
                keymap.of([
                    ...defaultKeymap,
                    { key: 'Ctrl-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
                    { key: 'Shift-Enter', run: this.execute.bind(this) as Command, preventDefault: true },
                ]),
            ];

            if (this.getAttribute('theme') === 'dark') {
                extensions.push(oneDarkTheme);
            }

            return new EditorView({
                doc: pySrc,
                extensions,
            });
        }

        // ******** main entry point for py-repl DOM building **********