Skip to content

Commit

Permalink
build(website): use typescript (#3653)
Browse files Browse the repository at this point in the history
Co-authored-by: Boshen <boshenc@gmail.com>
  • Loading branch information
DonIsaac and Boshen committed Jun 13, 2024
1 parent 1edcd87 commit f96b6b1
Show file tree
Hide file tree
Showing 9 changed files with 210 additions and 109 deletions.
6 changes: 5 additions & 1 deletion website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"dev": "pnpm run wasm-dev && concurrently 'vite' 'cd .. && cargo watch --workdir website -s \"pnpm run wasm-dev\"'",
"wasm-dev": "wasm-pack build --out-dir ../../npm/oxc-wasm --target web --dev --scope oxc ../crates/oxc_wasm",
"build": "pnpm run wasm-build && vite build --base=https://oxc-project.github.io/oxc/",
"wasm-build": "wasm-pack build --out-dir ../../npm/oxc-wasm --target web --release --scope oxc ../crates/oxc_wasm"
"wasm-build": "wasm-pack build --out-dir ../../npm/oxc-wasm --target web --release --scope oxc ../crates/oxc_wasm",
"lint": "oxlint"
},
"dependencies": {
"@codemirror/autocomplete": "^6.16.2",
Expand All @@ -27,7 +28,10 @@
"lzma": "^2.3.2"
},
"devDependencies": {
"@types/lodash.throttle": "^4.1.9",
"@types/lzma": "^2.3.0",
"@lezer/common": "^1.2.1",
"oxlint": "link:../apps/oxlint",
"@oxc/oxc_wasm": "link:../npm/oxc-wasm",
"concurrently": "^8.2.2",
"vite": "^5.2.13",
Expand Down
18 changes: 13 additions & 5 deletions website/playground/editor.js → website/playground/editor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
// Go down and find the `start` and `end` keys
export function getStartAndEnd(view, cursor) {
let start, end;
import type { TreeCursor } from "@lezer/common";
import type { EditorView } from "codemirror";

/**
* Go down and find the `start` and `end` keys
*/
export function getStartAndEnd(
view: EditorView,
cursor: TreeCursor
): [start: number | undefined, end: number | undefined] {
let start: number | undefined, end: number | undefined;
while (true) {
if (
!start &&
Expand All @@ -27,6 +35,6 @@ export function getStartAndEnd(view, cursor) {
return [start, end]
}

export const convertToUtf8 = (sourceTextUtf8, d) => {
export const convertToUtf8 = (sourceTextUtf8: ArrayBuffer, d: number) => {
return new TextDecoder().decode(sourceTextUtf8.slice(0, d)).length;
}
}
2 changes: 1 addition & 1 deletion website/playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
</style>
</head>
<body>
<script type="module" src="./index.js"></script>
<script type="module" src="./index.ts"></script>
<div id="loading">Loading Wasm (~400kB)...</div>

<div id="container">
Expand Down
92 changes: 56 additions & 36 deletions website/playground/index.js → website/playground/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@ import {
EditorSelection,
Compartment,
RangeSet,
type Range,
} from "@codemirror/state";
import { convertToUtf8, getStartAndEnd } from './editor.js'
import { findMostInnerNodeForPosition } from './traverseJson.js'
import { convertToUtf8, getStartAndEnd } from './editor.ts'
import { findMostInnerNodeForPosition } from './traverseJson.ts'
import { parser } from '@lezer/json'
import { javascript, javascriptLanguage } from "@codemirror/lang-javascript";
import { rust, rustLanguage } from "@codemirror/lang-rust";
import { json, jsonLanguage } from "@codemirror/lang-json";
import { vscodeKeymap } from "@replit/codemirror-vscode-keymap";
import { githubDark } from "@ddietr/codemirror-themes/github-dark";
import { linter, lintGutter } from "@codemirror/lint";
import { type Diagnostic, linter, lintGutter } from "@codemirror/lint";
import { language, syntaxTree } from "@codemirror/language";
import { autocompletion } from "@codemirror/autocomplete";
import { indentWithTab, deleteLine } from "@codemirror/commands";
Expand All @@ -39,18 +40,18 @@ import { getSymbolAndReferencesSpan, renderSymbols } from "./symbols.js";
const placeholderText = `
import React, { useEffect, useRef } from 'react'
const DummyComponent:React.FC = () => {
const DummyComponent: React.FC = () => {
const ref = useRef<HTMLInputElement>(null)
useEffect(() => {
if (ref.current) ref.current.focus()
}, [])
return (
<div>{Boolean(ref.current) ?? (
<input type="text" ref={ref} />
)}
</div>
<div>{Boolean(ref.current) ?? (
<input type="text" ref={ref} />
)}
</div>
)
}
Expand All @@ -60,15 +61,15 @@ export default DummyComponent
const STORAGE_KEY_CODE = "playground.code";
const ACTIVE_TAB_STORAGE_KEY_CODE = "playground.activeTab";

const getStringFromStorage = (whatToGet) => {
const getStringFromStorage = (whatToGet: string) => {
try {
return localStorage.getItem(whatToGet);
} catch (_e) {
return "";
}
};

const setStringToStorage = (whatToSet, value) => {
const setStringToStorage = (whatToSet: string, value: string) => {
try {
localStorage.setItem(whatToSet, value);
} catch (_e) {
Expand All @@ -77,7 +78,7 @@ const setStringToStorage = (whatToSet, value) => {
};

const tabBtnsBindClick = (callback) => {
const buttons = document.querySelectorAll('.header.controls button');
const buttons = document.querySelectorAll<HTMLButtonElement>('.header.controls button');
buttons.forEach(btn => {
btn.onclick = (e) => {
callback(e?.target?.id);
Expand All @@ -87,7 +88,7 @@ const tabBtnsBindClick = (callback) => {

const switchActiveTab = (tab) => {
const buttons = document.querySelectorAll('.header.controls button');
let targetBtn = null;
let targetBtn: Element | null = null;
buttons.forEach(btn => {
btn.classList.remove('active')
if (tab === btn.id) {
Expand All @@ -109,22 +110,34 @@ const initActiveTab = () => {
btn.classList.add('active');
}

type EditorViewKind =
| 'ast'
| 'codegen'
| 'format'
| 'ir'
| 'minify'
| 'prettier-ir'
| 'prettier'
| 'scope'
| 'symbol'

class Playground {
oxc;
oxc: Oxc;
sourceTextUtf8 // source text in Uint8Array, for converting from utf8 to utf16 span

runOptions;
parserOptions;
codegenOptions;
linterOptions;
minifierOptions;
runOptions: OxcRunOptions;
parserOptions: OxcParserOptions;
codegenOptions: OxcCodegenOptions;
linterOptions: OxcLinterOptions;
minifierOptions: OxcMinifierOptions;

editor;
viewer;
currentView = "ast"; // "ast" | "format" | "minify" | "ir"
languageConf;
urlParams;
viewerIsEditableConf;
editor: EditorView;
viewer: EditorView;
currentView: EditorViewKind = "ast"; // "ast" | "format" | "minify" | "ir"
languageConf: Compartment;
linterConf: Compartment;
urlParams: URLParams;
viewerIsEditableConf: Compartment;

constructor() {
this.languageConf = new Compartment();
Expand All @@ -133,7 +146,7 @@ class Playground {
this.linterConf = new Compartment();
this.editor = this.initEditor();
this.viewer = this.initViewer();
this.currentView = getStringFromStorage(ACTIVE_TAB_STORAGE_KEY_CODE) || "ast";
this.currentView = (getStringFromStorage(ACTIVE_TAB_STORAGE_KEY_CODE) as EditorViewKind | null) || "ast";
}

initOxc() {
Expand All @@ -156,7 +169,7 @@ class Playground {
return linter(() => this.updateDiagnostics(), { delay: 0 })
}

runOxc(text) {
runOxc(text: string | undefined) {
const sourceText = text;
this.urlParams.updateCode(sourceText);
this.oxc.sourceText = sourceText;
Expand Down Expand Up @@ -328,7 +341,7 @@ class Playground {
this.minifierOptions,
);
const elapsed = new Date() - start;
document.getElementById("duration").innerText = `${elapsed}ms`;
document.getElementById("duration")!.innerText = `${elapsed}ms`;
}

currentLanguage() {
Expand All @@ -343,8 +356,12 @@ class Playground {
}
}

updatePanel(diagnostics) {
updatePanel(diagnostics: Diagnostic[]) {
const panel = document.getElementById("panel");
if (!panel) {
console.error(new Error('No #panel found'))
return
}
panel.innerText = diagnostics
.map((d) => {
const emoji = {
Expand All @@ -358,7 +375,7 @@ class Playground {
panel.scrollTop = panel.scrollHeight;
}

updateView(view) {
updateView(view?: EditorViewKind) {
view = view || this.currentView;
this.currentView = view;

Expand All @@ -369,7 +386,7 @@ class Playground {
this.runOptions.format = false;
this.runOptions.minify = false;

let text;
let text: string;
switch (this.currentView) {
case "ast":
this.run();
Expand Down Expand Up @@ -415,25 +432,28 @@ class Playground {
this.run();
text = this.oxc.formattedText;
break;
default:
console.warn('Unknown view', this.currentView)
return
}

this.updateEditorText(this.viewer, text);
}

updateEditorText(instance, text) {
updateEditorText(instance: EditorView, text: string) {
const transaction = instance.state.update({
changes: { from: 0, to: instance.state.doc.length, insert: text },
});
instance.dispatch(transaction);
}

highlightEditorRange(view, range) {
highlightEditorRange(view: EditorView, range: Range<unknown> | Range<unknown>[]) {
let ranges = Array.isArray(range) ? range : [range];
ranges = ranges.filter((range) => range.from !== 0 || range.to !== 0);
if (ranges.length === 0) {
return;
}
const addHighlight = StateEffect.define({
const addHighlight = StateEffect.define<Range<any>>({
map: ({ from, to }, change) => ({
from: change.mapPos(from),
to: change.mapPos(to),
Expand Down Expand Up @@ -465,7 +485,7 @@ class Playground {
view.dispatch({ effects });
}

getTextFromView(view, from, to) {
getTextFromView(view: EditorView, from: number, to?: number) {
return view.state.doc.sliceString(from, to);
}

Expand All @@ -475,7 +495,7 @@ class Playground {
});

// Highlight the editor by searching for `start` and `end` values.
highlightEditorFromViewer(e, view) {
highlightEditorFromViewer(e: MouseEvent, view: EditorView) {
if (this.currentView === 'symbol') {
const pos = view.posAtCoords(e);
const tree = syntaxTree(view.state);
Expand Down Expand Up @@ -684,7 +704,7 @@ function addHorizontalResize() {
}
globalThis.document.body.style.cursor = 'col-resize';

const moveHandler = event => {
const moveHandler = (event: MouseEvent) => {
event.preventDefault();
const newPosition = ( event.pageX - offset) / size * 100;
// Using 99% as the max value prevents the divider from disappearing
Expand Down
50 changes: 0 additions & 50 deletions website/playground/symbols.js

This file was deleted.

Loading

0 comments on commit f96b6b1

Please sign in to comment.