Created
January 6, 2023 22:03
-
-
Save cowboyd/44f3311bf5b7412d6ffed402c7fca5c8 to your computer and use it in GitHub Desktop.
Trying to instantiate Monaco in fresh.deno.dev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useRef, useEffect } from "preact/hooks"; | |
import { useCSP } from "$fresh/runtime.ts"; | |
const monacoSrc = 'https://esm.sh/v102/monaco-editor@0.34.1/es2021/monaco-editor.js'; | |
export function Editor() { | |
useCSP(csp => { | |
let scriptSrc = csp.directives.scriptSrc = csp.directives.scriptSrc ?? []; | |
scriptSrc.push(monacoSrc); | |
}); | |
let ref = useRef(null); | |
let lib = useAsync(() => import(`${monacoSrc}`), [ref]); | |
if (lib.type === 'pending') { | |
return <h1>Loading</h1> | |
} else if (lib.type === 'rejected') { | |
return <h1>{String(lib.error)}</h1> | |
} else { | |
return <h1>Worked: {lib.value}</h1> | |
} | |
} | |
type AsyncState<T> = { | |
type: 'resolved'; | |
value: T; | |
} | { | |
type: 'rejected'; | |
error: Error; | |
} | { | |
type: 'pending'; | |
} | |
function useAsync<T>(fn: () => Promise<T>, deps: unknown[] = []): AsyncState<T> { | |
let [state, setState] = useState<AsyncState<T>>({ type: 'pending' }); | |
useEffect(() => { | |
fn() | |
.then(value => setState({ type: 'resolved', value })) | |
.catch(error => setState({ type: 'rejected', error })); | |
}, deps); | |
return state; | |
} | |
export default Editor; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment