Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Editor component #1434

Merged
merged 9 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/total-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@mdx-js/loader": "^2.3.0",
"@mdx-js/mdx": "^2.3.0",
"@mdx-js/react": "^2.3.0",
"@monaco-editor/react": "^4.6.0",
"@mux/mux-node": "^7.3.1",
"@mux/mux-player-react": "2.3.2",
"@next/mdx": "^14.1.3",
Expand Down
179 changes: 179 additions & 0 deletions apps/total-typescript/src/components/code-editor/code-editor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import Editor from '@monaco-editor/react'
import {ComponentProps, useRef, useState} from 'react'
import {prettierLoader} from './prettier-loader'

type Editor = Parameters<
NonNullable<ComponentProps<typeof Editor>['onMount']>
>[0]

type Monaco = Parameters<
NonNullable<ComponentProps<typeof Editor>['onMount']>
>[1]

const resolveLanguage = (language: Language | undefined): Language => {
switch (language) {
case 'ts':
case undefined:
return 'typescript'
case 'js':
return 'javascript'
default:
return language
}
}

export type Language =
| 'ts'
| 'tsx'
| 'typescript'
| 'json'
| 'js'
| 'javascript'

const THEME_NAME = 'total-typescript'

const EDITOR_THEME = {
base: 'vs-dark' as const,
inherit: true,
rules: [],
name: THEME_NAME,
colors: {'editor.background': '#1e2632'},
}

export type CodeEditorProps = {
language?: Language
code: string
className?: string
fontSize?: number
readonly?: boolean
onChange?: (code: string | undefined) => void
onEmittedJavaScript?: (code: string) => void
}

let incrementable = 0

/**
* Eagerly loaded code editor
*
* This should not be used directly, instead use ./lazy-loaded-editor.tsx
*/
export const EagerlyLoadedEditor = (props: CodeEditorProps) => {
// Needs to be a different file name for each editor on-screen
const [path] = useState(() => {
incrementable++
return `main-${incrementable}.ts`
})

const monacoRef = useRef<Monaco | undefined>(undefined)
const editorRef = useRef<Editor | undefined>(undefined)

const reportEmittedJavaScript = async (): Promise<void> => {
if (!props.onEmittedJavaScript) {
return
}

if (!editorRef.current || !monacoRef.current) {
return
}

const uri = editorRef.current?.getModel()?.uri

if (!uri) {
return
}

try {
const worker =
await monacoRef.current.languages.typescript.getTypeScriptWorker()

const client = await worker(uri)

const emitOutput = await client.getEmitOutput(uri.toString())

props.onEmittedJavaScript(emitOutput.outputFiles[0].text)
} catch (e) {
console.error('Getting emitted JavaScript failed', e)
}
}

return (
<Editor
className={props.className}
path={path}
loading={<div>Loading Code Editor...</div>}
// height={getHeight(props.code)}
{...(props.readonly
? {
value: props.code,
}
: {
defaultValue: props.code,
})}
onChange={(code) => {
props.onChange?.(code)

reportEmittedJavaScript()
}}
language={resolveLanguage(props.language)}
options={{
minimap: {enabled: false, showSlider: 'mouseover'},
fontSize: props.fontSize ?? 16,
glyphMargin: false,
tabSize: 2,
lineNumbers: 'off',
scrollbar: {
vertical: 'hidden',
horizontal: 'auto',
},
automaticLayout: true,
readOnly: props.readonly,
scrollBeyondLastLine: true,
}}
onMount={(editor, monaco) => {
monacoRef.current = monaco
editorRef.current = editor

// Enable prettier
monaco.languages.registerDocumentFormattingEditProvider('typescript', {
provideDocumentFormattingEdits: async (model) => {
try {
return [
{
text: await prettierLoader.format(model.getValue()),
range: model.getFullModelRange(),
},
]
} catch (err) {
console.error(err)
}
},
})

// Adjust the compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
...monaco.languages.typescript.typescriptDefaults.getCompilerOptions(),
module: monaco.languages.typescript.ModuleKind.ESNext,
moduleResolution:
monaco.languages.typescript.ModuleResolutionKind.NodeJs,
strict: true,
})

// Define the custom theme
monaco.editor.defineTheme(THEME_NAME, EDITOR_THEME)
monaco.editor.setTheme(THEME_NAME)

// Enable auto formatting on save
editor.addAction({
id: 'save',
label: 'Save',
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],
run: () => {
editor.getAction('editor.action.formatDocument')?.run(path)
},
})

reportEmittedJavaScript()
}}
/>
)
}
4 changes: 4 additions & 0 deletions apps/total-typescript/src/components/code-editor/js-logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React from 'react'
import type {CodeEditorProps} from './code-editor'

const _LazyLoadedEditor = React.lazy(() =>
import('./code-editor').then((res) => {
return {
default: res.EagerlyLoadedEditor,
}
}),
)

const LoadWhenVisible = (props: {children: React.ReactNode}) => {
const [isVisible, setIsVisible] = React.useState(false)

const ref = React.useRef<HTMLDivElement>(null)

React.useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setIsVisible(entry.isIntersecting)
})

observer.observe(ref.current!)

return () => {
observer.disconnect()
}
}, [])

return (
<div ref={ref} className="h-full">
{isVisible ? props.children : null}
</div>
)
}

export const LazyLoadedEditor = (props: CodeEditorProps) => {
return (
<LoadWhenVisible>
<_LazyLoadedEditor {...props} />
</LoadWhenVisible>
)
}
16 changes: 16 additions & 0 deletions apps/total-typescript/src/components/code-editor/load-script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const loadScript = (src: string) => {
return new Promise<void>((resolve, reject) => {
const scriptElement = document.createElement('script')
scriptElement.src = src

const timeout = setTimeout(() => {
reject('Timeout')
}, 15000)

scriptElement.onload = () => {
resolve()
clearTimeout(timeout)
}
document.body.appendChild(scriptElement)
})
}
86 changes: 86 additions & 0 deletions apps/total-typescript/src/components/code-editor/mdx-editor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import Image from 'next/image'
import {useState} from 'react'
import type {CodeEditorProps, Language} from './code-editor'
import {LazyLoadedEditor} from './lazy-loaded-editor'
import tsSvg from './ts-logo.svg'
import jsSvg from './js-logo.svg'

const getHeight = (code: string) => {
return (code.split('\n').length + 3) * 24
}

const extractCodeAndLanguage = (props: {children?: any}) => {
const code = props.children?.props?.children?.props?.children
let language = props.children?.props?.children?.props?.className

if (!code || !language) {
return null
}

language = language.replace('language-', '') as Language

return {code, language}
}

export const MDXEditor = (props: {children?: any}) => {
// Yes, we're diving into React's internals to grab the
// code from the <pre> element
const extracted = extractCodeAndLanguage(props)

if (!extracted) {
return null
}

const {code, language} = extracted

return (
<div
className="my-10 h-72 rounded bg-[#1e2632] py-6"
style={{
height: getHeight(code),
}}
>
<LazyLoadedEditor code={code} language={language} />
</div>
)
}

export const MDXTranspilePreview = (props: {children?: any}) => {
const extracted = extractCodeAndLanguage(props)
const [jsCode, setJsCode] = useState<string | undefined>(undefined)

if (!extracted) {
return null
}

const {code, language} = extracted

return (
<div className="not-prose my-10 grid grid-cols-1 gap-2 md:grid-cols-2">
<div className="relative h-60 rounded bg-[#1e2632] py-6 md:h-72">
<LazyLoadedEditor
code={code}
language={language}
onEmittedJavaScript={setJsCode}
fontSize={16}
/>
<div className="absolute bottom-6 left-6 flex items-center space-x-3 rounded bg-gray-700 pr-3">
<Image src={tsSvg} alt="TypeScript Logo" className="size-7 rounded" />
<span className="text-xs text-gray-100">TypeScript Code</span>
</div>
</div>
<div className="relative h-60 rounded bg-[#1e2632] py-6 md:h-72">
<LazyLoadedEditor
code={jsCode ?? ''}
language="js"
readonly
fontSize={12}
/>
<div className="absolute bottom-6 left-6 flex items-center space-x-3 rounded bg-gray-700 pr-3">
<Image src={jsSvg} alt="JavaScript Logo" className="size-7 rounded" />
<span className="text-xs text-gray-100">Emitted JavaScript</span>
</div>
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {loadScript} from './load-script'

declare global {
interface Window {
define: any
}
}

const Prettier = () => {
let hasLoaded = false

const loadPrettier = async () => {
if (hasLoaded) return

/**
* Helps Monaco editor get over a too-sensitive error
*
* https://stackoverflow.com/questions/55057425/can-only-have-one-anonymous-define-call-per-script-file
*/
const define = window.define
window.define = () => {}

await Promise.all([
loadScript('https://unpkg.com/[email protected]/standalone.js'),
loadScript('https://unpkg.com/[email protected]/parser-typescript.js'),
])

window.define = define

hasLoaded = true
}

const format = async (code: string) => {
try {
await loadPrettier()
return (window as any).prettier.format(code, {
parser: 'typescript',
plugins: (window as any).prettierPlugins,
})
} catch (e) {
console.error(e)
}
/**
* If loading prettier fails, just
* load the code
*/
return code
}

return {
load: loadPrettier,
format,
}
}

export const prettierLoader = Prettier()
Loading
Loading