Skip to content
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
> - :house: [Internal]
> - :nail_care: [Polish]
## master

#### :rocket: New Feature

- Paste as JSON.t or ReScript JSX in VSCode. https://github.com/rescript-lang/rescript-vscode/pull/1141

## 1.66.0

#### :bug: Bug fix
Expand Down
2 changes: 2 additions & 0 deletions client/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export { openCompiled } from "./commands/open_compiled";
export { switchImplIntf } from "./commands/switch_impl_intf";
export { dumpDebug, dumpDebugRetrigger } from "./commands/dump_debug";
export { dumpServerState } from "./commands/dump_server_state";
export { pasteAsRescriptJson } from "./commands/paste_as_rescript_json";
export { pasteAsRescriptJsx } from "./commands/paste_as_rescript_jsx";

export const codeAnalysisWithReanalyze = (
targetDir: string | null,
Expand Down
193 changes: 193 additions & 0 deletions client/src/commands/paste_as_rescript_json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import { env, window, Position, Selection, TextDocument } from "vscode";

const INDENT_SIZE = 2;
const INDENT_UNIT = " ".repeat(INDENT_SIZE);

const indent = (level: number) => INDENT_UNIT.repeat(level);

const isLikelyJson = (text: string): boolean => {
const trimmed = text.trim();
if (trimmed.length === 0) {
return false;
}
const first = trimmed[0];
if (first === "{" || first === "[" || first === '"' || first === "-") {
return true;
}
if (first >= "0" && first <= "9") {
return true;
}
if (
trimmed.startsWith("true") ||
trimmed.startsWith("false") ||
trimmed.startsWith("null")
) {
return true;
}
return false;
};

const ensureFloatString = (value: number): string => {
const raw = Number.isFinite(value) ? String(value) : "0";
if (raw.includes(".") || raw.includes("e") || raw.includes("E")) {
return raw;
}
return `${raw}.`;
};

const formatJsonValue = (value: unknown, level = 0): string => {
if (value === null) {
return "JSON.Null";
}

switch (typeof value) {
case "string":
return `JSON.String(${JSON.stringify(value)})`;
case "number":
return `JSON.Number(${ensureFloatString(value)})`;
case "boolean":
return `JSON.Boolean(${value})`;
case "object":
if (Array.isArray(value)) {
return formatArray(value, level);
}
return formatObject(value as Record<string, unknown>, level);
default:
return "JSON.Null";
}
};

const formatObject = (
value: Record<string, unknown>,
level: number,
): string => {
const entries = Object.entries(value);
if (entries.length === 0) {
return "JSON.Object(dict{})";
}
const nextLevel = level + 1;
const lines = entries.map(
([key, val]) =>
`${indent(nextLevel)}${JSON.stringify(key)}: ${formatJsonValue(
val,
nextLevel,
)}`,
);
return `JSON.Object(dict{\n${lines.join(",\n")}\n${indent(level)}})`;
};

const formatArray = (values: unknown[], level: number): string => {
if (values.length === 0) {
return "JSON.Array([])";
}
const nextLevel = level + 1;
const lines = values.map(
(item) => `${indent(nextLevel)}${formatJsonValue(item, nextLevel)}`,
);
return `JSON.Array([\n${lines.join(",\n")}\n${indent(level)}])`;
};

export type JsonConversionResult =
| { kind: "success"; formatted: string }
| { kind: "notJson" }
| { kind: "error"; errorMessage: string };

export const convertPlainTextToJsonT = (text: string): JsonConversionResult => {
if (!isLikelyJson(text)) {
return { kind: "notJson" };
}

try {
const parsed = JSON.parse(text);
return { kind: "success", formatted: formatJsonValue(parsed) };
} catch {
return {
kind: "error",
errorMessage: "Clipboard JSON could not be parsed.",
};
}
};

export const getBaseIndent = (
document: TextDocument,
position: Position,
): string => {
const linePrefix = document
.lineAt(position)
.text.slice(0, position.character);
return /^\s*$/.test(linePrefix) ? linePrefix : "";
};

export const applyBaseIndent = (formatted: string, baseIndent: string) => {
if (baseIndent.length === 0) {
return formatted;
}

return formatted
.split("\n")
.map((line, index) => (index === 0 ? line : `${baseIndent}${line}`))
.join("\n");
};

export const buildInsertionText = (
document: TextDocument,
position: Position,
formatted: string,
) => {
const baseIndent = getBaseIndent(document, position);
return applyBaseIndent(formatted, baseIndent);
};

const computeEndPosition = (
insertionStart: Position,
indentedText: string,
): Position => {
const lines = indentedText.split("\n");
if (lines.length === 1) {
return insertionStart.translate(0, lines[0].length);
}
return new Position(
insertionStart.line + lines.length - 1,
lines[lines.length - 1].length,
);
};

export const pasteAsRescriptJson = async () => {
const editor = window.activeTextEditor;
if (!editor) {
window.showInformationMessage(
"No active editor to paste the ReScript JSON into.",
);
return;
}

const clipboardText = await env.clipboard.readText();
const conversion = convertPlainTextToJsonT(clipboardText);

if (conversion.kind === "notJson") {
window.showInformationMessage("Clipboard does not appear to contain JSON.");
return;
}

if (conversion.kind === "error") {
window.showErrorMessage("Clipboard JSON could not be parsed.");
return;
}

const formatted = conversion.formatted;
const selection = editor.selection;
const indentedText = buildInsertionText(
editor.document,
selection.start,
formatted,
);
const insertionStart = selection.start;
const didEdit = await editor.edit((editBuilder) => {
editBuilder.replace(selection, indentedText);
});

if (didEdit) {
const endPosition = computeEndPosition(insertionStart, indentedText);
editor.selection = new Selection(endPosition, endPosition);
}
};
90 changes: 90 additions & 0 deletions client/src/commands/paste_as_rescript_jsx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { env, window, Position, Selection } from "vscode";

import { buildInsertionText } from "./paste_as_rescript_json";
import { transformJsx } from "./transform-jsx";

export type JsxConversionResult =
| { kind: "success"; formatted: string }
| { kind: "empty" }
| { kind: "error"; errorMessage: string };

export const convertPlainTextToRescriptJsx = (
text: string,
): JsxConversionResult => {
if (text.trim().length === 0) {
return { kind: "empty" };
}

try {
// If you ever need to fix a bug in transformJsx,
// please do so in https://github.com/nojaf/vanilla-jsx-to-rescript-jsx/blob/main/index.ts
// and then copy the changes to transform-jsx.ts
const formatted = transformJsx(text);
return { kind: "success", formatted };
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Unknown conversion error.";
return {
kind: "error",
errorMessage,
};
}
};

const computeEndPosition = (
insertionStart: Position,
indentedText: string,
): Position => {
const lines = indentedText.split("\n");
if (lines.length === 1) {
return insertionStart.translate(0, lines[0].length);
}
return new Position(
insertionStart.line + lines.length - 1,
lines[lines.length - 1].length,
);
};

export const pasteAsRescriptJsx = async () => {
const editor = window.activeTextEditor;
if (!editor) {
window.showInformationMessage(
"No active editor to paste the ReScript JSX into.",
);
return;
}

const clipboardText = await env.clipboard.readText();
const conversion = convertPlainTextToRescriptJsx(clipboardText);

if (conversion.kind === "empty") {
window.showInformationMessage(
"Clipboard does not appear to contain any JSX content.",
);
return;
}

if (conversion.kind === "error") {
window.showErrorMessage(
`Clipboard JSX could not be transformed: ${conversion.errorMessage}`,
);
return;
}

const formatted = conversion.formatted;
const selection = editor.selection;
const indentedText = buildInsertionText(
editor.document,
selection.start,
formatted,
);
const insertionStart = selection.start;
const didEdit = await editor.edit((editBuilder) => {
editBuilder.replace(selection, indentedText);
});

if (didEdit) {
const endPosition = computeEndPosition(insertionStart, indentedText);
editor.selection = new Selection(endPosition, endPosition);
}
};
Loading