All files ts-code-editor.view.ts

0% Statements 0/67
0% Branches 0/9
0% Functions 0/20
0% Lines 0/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205                                                                                                                                                                                                                                                                                                                                                                                                                         
import { CodeEditorView, SourceCode } from './code-editor.view'
import { BehaviorSubject, ReplaySubject } from 'rxjs'
import { createDefaultMapFromCDN } from './vfs_default_map_cdn'
import CodeMirror from 'codemirror'
import { filter, map, take, tap, withLatestFrom } from 'rxjs/operators'
 
import * as ts from 'typescript'
import {
    createSystem,
    createVirtualTypeScriptEnvironment,
} from '@typescript/vfs'
import { VirtualDOM } from '@youwol/flux-view'
 
type SourcePath = string
 
export class CodeIdeState {
    public readonly entryPoint: SourcePath
    public readonly currentFile$: BehaviorSubject<SourceCode>
 
    public readonly fsMap$ = new BehaviorSubject<Map<string, string>>(undefined)
    public readonly parsedSrc$ = new ReplaySubject<{
        jsSrc: string
        tsSrc: string
    }>(1)
 
    public readonly config = {
        lineNumbers: true,
        theme: 'blackboard',
        lineWrapping: false,
        gutters: ['CodeMirror-lint-markers'],
        indentUnit: 4,
        lint: {
            options: {
                editorKind: 'TsCodeEditorView',
                esversion: 2021,
            },
        },
        extraKeys: {
            'Ctrl-Enter': () => {
                this.parseCurrentFile$().subscribe((parsed) => {
                    this.parsedSrc$.next(parsed)
                })
            },
        },
    }
 
    constructor(params: {
        files: SourceCode[] | SourceCode
        entryPoint: SourcePath
    }) {
        Object.assign(this, params)
        const files = Array.isArray(params.files)
            ? params.files
            : [params.files]
 
        this.currentFile$ = new BehaviorSubject<SourceCode>(
            files.find((sourceCode) => {
                return sourceCode.path == this.entryPoint
            }),
        )
        createDefaultMapFromCDN(
            { target: ts.ScriptTarget.ES2020 },
            '4.6.2',
        ).then((fsMap) => {
            files.forEach((file) => {
                fsMap.set(file.path.substring(1), file.content)
            })
            this.fsMap$.next(fsMap)
        })
 
        this.currentFile$
            .pipe(tap((file) => console.log('Current files changed', file)))
            .subscribe((file) => {
                const fsMap = this.fsMap$.getValue()
                fsMap && fsMap.set(file.path.substring(1), file.content)
                fsMap && this.fsMap$.next(fsMap)
            })
    }
 
    parseCurrentFile$() {
        console.log('Parse Current File')
        return this.currentFile$.pipe(
            take(1),
            map((file) => {
                let transpiled = ts
                    .transpileModule(file.content, {
                        compilerOptions,
                    })
                    .outputText.replace('export {};', '')
                return {
                    tsSrc: file.content,
                    jsSrc: transpiled,
                }
            }),
        )
    }
}
 
export class CodeIdeView implements VirtualDOM {
    public readonly class = 'd-flex h-100'
    public readonly children: VirtualDOM[]
    public readonly ideState: CodeIdeState
    public readonly tsCodeEditorView: TsCodeEditorView
 
    constructor(params: { ideState: CodeIdeState }) {
        Object.assign(this, params)
        this.tsCodeEditorView = new TsCodeEditorView(params)
        this.children = [this.tsCodeEditorView]
    }
}
 
export class TsCodeEditorView extends CodeEditorView {
    public readonly ideState: CodeIdeState
 
    constructor(params: { ideState: CodeIdeState }) {
        super({
            file$: params.ideState.currentFile$,
            language: 'text/typescript',
            config: params.ideState.config,
        })
        Object.assign(this, params)
 
        this.ideState.fsMap$
            .pipe(
                filter((d) => d != undefined),
                withLatestFrom(this.nativeEditor$),
                take(1),
            )
            .subscribe(([_, native]) => {
                native.setValue(native.getValue())
            })
 
        CodeMirror.registerHelper('lint', 'javascript', (text, options) => {
            Iif (options.editorKind != 'TsCodeEditorView') {
                return []
            }
            let fsMapBase = this.ideState.fsMap$.getValue()
            Iif (!fsMapBase) return
            const highlights = getHighlights(fsMapBase, text)
            return (
                highlights
                    // allow 'return' outside a function body
                    .filter((highlight) => highlight.diagnostic.code != 1108)
                    .map((highlight) => ({
                        ...highlight,
                        message: highlight.messageText,
                    }))
            )
        })
    }
}
 
export interface SrcPosition {
    line: number
    ch: number
}
 
export class SrcHighlight {
    public readonly messageText: string
    public readonly from: SrcPosition
    public readonly to: SrcPosition
 
    constructor(public readonly diagnostic: ts.Diagnostic) {
        this.messageText = diagnostic.messageText as string
        Iif (this.messageText['messageText']) {
            this.messageText = this.messageText['messageText']
        }
        const from_location = diagnostic.file.getLineAndCharacterOfPosition(
            diagnostic.start,
        )
        this.from = {
            line: from_location.line,
            ch: from_location.character,
        }
        const to_location = diagnostic.file.getLineAndCharacterOfPosition(
            diagnostic.start + diagnostic.length,
        )
        this.to = { line: to_location.line, ch: to_location.character }
    }
}
 
export const compilerOptions = {
    target: ts.ScriptTarget.ES2020,
    module: ts.ModuleKind.ES2020,
    esModuleInterop: true,
    noImplicitAny: false,
    baseUrl: '/',
}
 
export function getHighlights(fsMap, src) {
    fsMap.set('index.ts', `${src}`)
    const system = createSystem(fsMap)
    const env = createVirtualTypeScriptEnvironment(
        system,
        ['index.ts'],
        ts,
        compilerOptions,
    )
 
    return [
        ...env.languageService.getSyntacticDiagnostics('index.ts'),
        ...env.languageService.getSemanticDiagnostics('index.ts'),
    ].map((d) => new SrcHighlight(d))
}