Skip to content
This repository has been archived by the owner on Aug 31, 2023. It is now read-only.

feat(playground): Add JSON support #3968

Merged
merged 6 commits into from
Dec 8, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
19 changes: 9 additions & 10 deletions crates/rome_service/src/file_handlers/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ use crate::settings::{
};
use crate::workspace::GetSyntaxTreeResult;
use crate::RomeError;
#[cfg(debug_assertions)]
use rome_formatter::FormatError;
use rome_formatter::Printed;
#[cfg(any(debug_assertions, target_family = "wasm"))]
use rome_formatter::{FormatError, Printed};
use rome_fs::RomePath;
use rome_json_formatter::context::JsonFormatOptions;
use rome_json_formatter::format_node;
use rome_json_syntax::{JsonLanguage, JsonRoot, JsonSyntaxNode};
use rome_parser::AnyParse;
#[cfg(debug_assertions)]
#[cfg(any(debug_assertions, target_family = "wasm"))]
use rome_rowan::{TextRange, TextSize, TokenAtOffset};
use tracing::debug;

impl Language for JsonLanguage {
type FormatterSettings = ();
Expand Down Expand Up @@ -68,7 +66,7 @@ impl ExtensionHandler for JsonFileHandler {
}
}

#[cfg(debug_assertions)]
#[cfg(any(debug_assertions, target_family = "wasm"))]
fn formatter_capabilities() -> FormatterCapabilities {
FormatterCapabilities {
format: Some(format),
Expand All @@ -77,7 +75,7 @@ fn formatter_capabilities() -> FormatterCapabilities {
}
}

#[cfg(not(debug_assertions))]
#[cfg(all(not(debug_assertions), not(target_family = "wasm")))]
fn formatter_capabilities() -> FormatterCapabilities {
FormatterCapabilities::default()
}
Expand Down Expand Up @@ -112,6 +110,7 @@ fn debug_formatter_ir(
Ok(root_element.to_string())
}

#[cfg(any(debug_assertions, target_family = "wasm"))]
#[tracing::instrument(level = "debug", skip(parse))]
fn format(
rome_path: &RomePath,
Expand All @@ -120,7 +119,7 @@ fn format(
) -> Result<Printed, RomeError> {
let options = settings.format_options::<JsonLanguage>(rome_path);

debug!("Format with the following options: \n{}", options);
tracing::debug!("Format with the following options: \n{}", options);

let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
Expand All @@ -131,7 +130,7 @@ fn format(
}
}

#[cfg(debug_assertions)]
#[cfg(any(debug_assertions, target_family = "wasm"))]
fn format_range(
rome_path: &RomePath,
parse: AnyParse,
Expand All @@ -145,7 +144,7 @@ fn format_range(
Ok(printed)
}

#[cfg(debug_assertions)]
#[cfg(any(debug_assertions, target_family = "wasm"))]
fn format_on_type(
rome_path: &RomePath,
parse: AnyParse,
Expand Down
1 change: 1 addition & 0 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@astrojs/react": "^1.2.2",
"@astrojs/rss": "^1.0.3",
"@codemirror/lang-javascript": "^6.1.0",
"@codemirror/lang-json": "^6.0.1",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "6.1.2",
"@codemirror/view": "6.4.0",
Expand Down
46 changes: 26 additions & 20 deletions website/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 14 additions & 12 deletions website/src/playground/Playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import CodeMirror from "./CodeMirror";
import type { ViewUpdate } from "@codemirror/view";
import * as codeMirrorLangRomeAST from "codemirror-lang-rome-ast";
import { javascript } from "@codemirror/lang-javascript";
import { json } from "@codemirror/lang-json";
import SettingsPane from "./components/SettingsPane";
import {
createRef,
Expand All @@ -21,6 +22,7 @@ import FormatterIRTab from "./tabs/FormatterIRTab";
import {
getCurrentCode,
getFileState,
isJSONFilename,
isJSXFilename,
isTypeScriptFilename,
useWindowSize,
Expand All @@ -46,18 +48,18 @@ export default function PlaygroundLoader({
const prettierOutput = file.prettier;

// rome-ignore lint/nursery/useExhaustiveDependencies: dynamic dependencies
const codeMirrorExtensions = useMemo(
() => [
javascript({
jsx: isJSXFilename(playgroundState.currentFile),
typescript: isTypeScriptFilename(playgroundState.currentFile),
}),
],
[
isJSXFilename(playgroundState.currentFile),
isTypeScriptFilename(playgroundState.currentFile),
],
);
const codeMirrorExtensions = useMemo(() => {
if (isJSONFilename(playgroundState.currentFile)) {
return [json()];
} else {
return [
javascript({
jsx: isJSXFilename(playgroundState.currentFile),
typescript: isTypeScriptFilename(playgroundState.currentFile),
}),
];
}
}, [playgroundState.currentFile]);

const romeAstSyntacticDataRef = useRef<RomeAstSyntacticData | null>(null);

Expand Down
86 changes: 6 additions & 80 deletions website/src/playground/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import prettier, { Options as PrettierOptions } from "prettier";
import type { ThemeName } from "../frontend-scripts/util";
// @ts-ignore
import parserBabel from "prettier/esm/parser-babel";
import {
IndentStyle,
PlaygroundState,
QuoteStyle,
QuoteProperties,
TrailingComma,
Semicolons,
PrettierOutput,
PlaygroundSettings,
emptyPrettierOutput,
emptyRomeOutput,
Expand Down Expand Up @@ -147,76 +138,6 @@ export function createPlaygroundSettingsSetter<
};
}

export function formatWithPrettier(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this to the prettierWorker to remove the prettier dependencies from the main bundle.

code: string,
options: {
lineWidth: number;
indentStyle: IndentStyle;
indentWidth: number;
language: "js" | "ts";
quoteStyle: QuoteStyle;
quoteProperties: QuoteProperties;
trailingComma: TrailingComma;
semicolons: Semicolons;
},
): PrettierOutput {
try {
const prettierOptions: PrettierOptions = {
useTabs: options.indentStyle === IndentStyle.Tab,
tabWidth: options.indentWidth,
printWidth: options.lineWidth,
parser: getPrettierParser(options.language),
plugins: [parserBabel],
singleQuote: options.quoteStyle === QuoteStyle.Single,
quoteProps: options.quoteProperties,
trailingComma: options.trailingComma,
semi: options.semicolons === Semicolons.Always,
};

// @ts-ignore
const debug = prettier.__debug;
const document = debug.printToDoc(code, prettierOptions);

// formatDoc must be before printDocToString because printDocToString mutates the document and breaks the ir
const ir = debug.formatDoc(document, {
parser: "babel",
plugins: [parserBabel],
});

const formattedCode = debug.printDocToString(
document,
prettierOptions,
).formatted;

return {
type: "SUCCESS",
code: formattedCode,
ir,
};
} catch (err: unknown) {
if (err instanceof SyntaxError) {
return {
type: "ERROR",
stack: err.message,
};
} else {
return {
type: "ERROR",
stack: (err as Error).stack ?? "",
};
}
}
}

function getPrettierParser(language: "js" | "ts"): string {
switch (language) {
case "js":
return "babel";
case "ts":
return "babel-ts";
}
}

// See https://developer.mozilla.org/en-US/docs/Web/API/btoa#unicode_strings
export function encodeCode(code: string): string {
return btoa(toBinary(code));
Expand Down Expand Up @@ -300,6 +221,10 @@ export function isModuleFilename(filename: string): boolean {
);
}

export function isJSONFilename(filename: string): boolean {
return filename.endsWith(".json");
}

export function modifyFilename(
filename: string,
opts: ExtensionOptions,
Expand Down Expand Up @@ -344,7 +269,8 @@ export function isValidExtension(filename: string): boolean {
isScriptFilename(filename) ||
isModuleFilename(filename) ||
isTypeScriptFilename(filename) ||
isJSXFilename(filename)
isJSXFilename(filename) ||
isJSONFilename(filename)
);
}

Expand Down
Loading