Skip to content
Open
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
86 changes: 86 additions & 0 deletions airflow-core/src/airflow/ui/src/components/JsonEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";

import { JsonEditor } from "./JsonEditor";

vi.mock("src/components/MonacoEditor", () => ({
default: ({
onChange,
value,
}: {
readonly onChange?: (value: string | undefined) => void;
readonly value?: string;
}) => (
<textarea aria-label="JSON editor" onChange={(event) => onChange?.(event.target.value)} value={value} />
),
}));

vi.mock("src/context/colorMode", () => ({
useMonacoTheme: () => ({ beforeMount: vi.fn(), theme: "airflow-light" }),
}));

describe("JsonEditor", () => {
it("passes the raw value through when prettify is off", () => {
const onChange = vi.fn();

render(<JsonEditor onChange={onChange} value="{}" />);

fireEvent.change(screen.getByLabelText("JSON editor"), { target: { value: '{"key":1}' } });

expect(onChange).toHaveBeenCalledWith('{"key":1}');
});

it("prettifies valid JSON and clears the error when prettify is on", () => {
const onChange = vi.fn();
const onError = vi.fn();

render(<JsonEditor onChange={onChange} onError={onError} prettify value="{}" />);

fireEvent.change(screen.getByLabelText("JSON editor"), { target: { value: '{"key":1}' } });

expect(onError).toHaveBeenCalledWith(undefined);
expect(onChange).toHaveBeenCalledWith(JSON.stringify({ key: 1 }, undefined, 2));
});

it("does not call onChange when the prettified JSON is unchanged", () => {
const onChange = vi.fn();
const formatted = JSON.stringify({ key: 1 }, undefined, 2);

render(<JsonEditor onChange={onChange} prettify value={formatted} />);

fireEvent.change(screen.getByLabelText("JSON editor"), { target: { value: '{"key": 1}' } });

expect(onChange).not.toHaveBeenCalled();
});

it("reports a parse error and skips onChange for invalid JSON when prettify is on", () => {
const onChange = vi.fn();
const onError = vi.fn();

render(<JsonEditor onChange={onChange} onError={onError} prettify value="{}" />);

fireEvent.change(screen.getByLabelText("JSON editor"), { target: { value: "{invalid" } });

expect(onError).toHaveBeenCalledWith(expect.any(String));
expect(onChange).not.toHaveBeenCalled();
});
});
23 changes: 21 additions & 2 deletions airflow-core/src/airflow/ui/src/components/JsonEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ type JsonEditorProps = {
readonly name?: string;
readonly onBlur?: () => void;
readonly onChange?: (value: string) => void;
readonly onError?: (error: string | undefined) => void;
readonly prettify?: boolean;
readonly value?: string;
};

Expand All @@ -36,6 +38,8 @@ export const JsonEditor = ({
height = "200px",
onBlur,
onChange,
onError,
prettify = false,
value,
...rest
}: JsonEditorProps) => {
Expand All @@ -55,8 +59,23 @@ export const JsonEditor = ({
scrollBeyondLastLine: false,
};

const handleChange = (val: string | undefined) => {
onChange?.(val ?? "");
const handleChange = (val: string | undefined = "") => {
if (!prettify) {
onChange?.(val);

return;
}

try {
const formattedJson = JSON.stringify(JSON.parse(val) as unknown, undefined, 2);

onError?.(undefined);
if (formattedJson !== value) {
onChange?.(formattedJson);
}
} catch (error) {
onError?.(error instanceof Error ? error.message : String(error));
}
};

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,25 +72,6 @@ export const CreateAssetEventModal = ({ asset, onClose, open }: Props) => {
const [upstreamDag] = upstreamDags;
const upstreamDagId = hasUpstreamDag ? upstreamDag?.source_id.replace("dag:", "") : undefined;

// TODO move validate + prettify into JsonEditor
const validateAndPrettifyJson = (newValue: string) => {
try {
const parsedJson = JSON.parse(newValue) as JSON;

setExtraError(undefined);

const formattedJson = JSON.stringify(parsedJson, undefined, 2);

if (formattedJson !== extra) {
setExtra(formattedJson); // Update only if the value is different
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : translate("common:error.unknown");

setExtraError(errorMessage);
}
};

const onSuccess = async (response: AssetEventResponse | DAGRunResponse) => {
setExtra("{}");
setExtraError(undefined);
Expand Down Expand Up @@ -219,7 +200,7 @@ export const CreateAssetEventModal = ({ asset, onClose, open }: Props) => {
{eventType === "manual" ? (
<Field.Root mt={6}>
<Field.Label fontSize="md">{translate("createEvent.manual.extra")}</Field.Label>
<JsonEditor onChange={validateAndPrettifyJson} value={extra} />
<JsonEditor onChange={setExtra} onError={setExtraError} prettify value={extra} />
<Text color="fg.error">{extraError}</Text>
</Field.Root>
) : undefined}
Expand Down