fixes issue around importing files (#643)

* fixes issue around importing files

fixes: #628

* fixed tests

* fixed moving cursor to end of text area

did have to remove the dirty check because of this
This commit is contained in:
Erik Jan de Wit 2021-06-08 13:49:59 +02:00 committed by GitHub
parent d8f6537375
commit 707380c228
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 429 additions and 440 deletions

View file

@ -32,7 +32,7 @@ export const ImportForm = () => {
const { addAlert } = useAlerts(); const { addAlert } = useAlerts();
const handleFileChange = (value: string | File) => { const handleFileChange = (obj: object) => {
const defaultClient = { const defaultClient = {
protocol: "", protocol: "",
clientId: "", clientId: "",
@ -40,12 +40,11 @@ export const ImportForm = () => {
description: "", description: "",
}; };
const obj = value ? JSON.parse(value as string) : defaultClient; Object.entries(obj || defaultClient).forEach((entries) => {
Object.keys(obj).forEach((k) => { if (entries[0] === "attributes") {
if (k === "attributes") { convertToFormValues(entries[1], "attributes", form.setValue);
convertToFormValues(obj[k], "attributes", form.setValue);
} else { } else {
setValue(k, obj[k]); setValue(entries[0], entries[1]);
} }
}); });
}; };

View file

@ -21,13 +21,9 @@ export type JsonFileUploadEvent =
| React.ChangeEvent<HTMLTextAreaElement> // User typed in the TextArea | React.ChangeEvent<HTMLTextAreaElement> // User typed in the TextArea
| React.MouseEvent<HTMLButtonElement, MouseEvent>; // User clicked Clear button | React.MouseEvent<HTMLButtonElement, MouseEvent>; // User clicked Clear button
export type JsonFileUploadProps = FileUploadProps & { export type JsonFileUploadProps = Omit<FileUploadProps, "onChange"> & {
id: string; id: string;
onChange: ( onChange: (obj: object) => void;
value: string | File,
filename: string,
event: JsonFileUploadEvent
) => void;
helpText?: string; helpText?: string;
unWrap?: boolean; unWrap?: boolean;
}; };
@ -67,27 +63,20 @@ export const JsonFileUpload = ({
value, value,
filename, filename,
}); });
onChange(value, filename, event);
if (value) {
let obj = {};
try {
obj = JSON.parse(value as string);
} catch (error) {
console.warn("Invalid json, ignoring value using {}");
}
onChange(obj);
}
} }
}; };
const JsonFileUploadComp = () => (
<FileUpload
id={id}
{...rest}
type="text"
value={fileUpload.value}
filename={fileUpload.filename}
onChange={handleChange}
onReadStarted={() => setFileUpload({ ...fileUpload, isLoading: true })}
onReadFinished={() => setFileUpload({ ...fileUpload, isLoading: false })}
isLoading={fileUpload.isLoading}
dropzoneProps={{
accept: ".json",
}}
/>
);
return ( return (
<> <>
{fileUpload.modal && ( {fileUpload.modal && (
@ -100,9 +89,9 @@ export const JsonFileUpload = ({
<Button <Button
key="confirm" key="confirm"
variant="primary" variant="primary"
onClick={(event) => { onClick={() => {
setFileUpload(defaultUpload); setFileUpload(defaultUpload);
onChange("", "", event); onChange({});
}} }}
> >
{t("clear")} {t("clear")}
@ -115,14 +104,50 @@ export const JsonFileUpload = ({
{t("clearFileExplain")} {t("clearFileExplain")}
</Modal> </Modal>
)} )}
{unWrap && <JsonFileUploadComp />} {unWrap && (
<FileUpload
id={id}
{...rest}
type="text"
value={fileUpload.value}
filename={fileUpload.filename}
onChange={handleChange}
onReadStarted={() =>
setFileUpload({ ...fileUpload, isLoading: true })
}
onReadFinished={() =>
setFileUpload({ ...fileUpload, isLoading: false })
}
isLoading={fileUpload.isLoading}
dropzoneProps={{
accept: ".json",
}}
/>
)}
{!unWrap && ( {!unWrap && (
<FormGroup <FormGroup
label={t("resourceFile")} label={t("resourceFile")}
fieldId={id} fieldId={id}
helperText={t(helpText)} helperText={t(helpText)}
> >
<JsonFileUploadComp /> <FileUpload
id={id}
{...rest}
type="text"
value={fileUpload.value}
filename={fileUpload.filename}
onChange={handleChange}
onReadStarted={() =>
setFileUpload({ ...fileUpload, isLoading: true })
}
onReadFinished={() =>
setFileUpload({ ...fileUpload, isLoading: false })
}
isLoading={fileUpload.isLoading}
dropzoneProps={{
accept: ".json",
}}
/>
</FormGroup> </FormGroup>
)} )}
</> </>

View file

@ -31,7 +31,6 @@ exports[`<JsonFileUpload /> render 1`] = `
<div <div
className="pf-c-form__group-control" className="pf-c-form__group-control"
> >
<JsonFileUploadComp>
<FileUpload <FileUpload
dropzoneProps={ dropzoneProps={
Object { Object {
@ -261,7 +260,6 @@ exports[`<JsonFileUpload /> render 1`] = `
</FileUploadField> </FileUploadField>
</t> </t>
</FileUpload> </FileUpload>
</JsonFileUploadComp>
<div <div
aria-live="polite" aria-live="polite"
className="pf-c-form__helper-text" className="pf-c-form__helper-text"
@ -306,7 +304,6 @@ exports[`<JsonFileUpload /> upload file 1`] = `
<div <div
className="pf-c-form__group-control" className="pf-c-form__group-control"
> >
<JsonFileUploadComp>
<FileUpload <FileUpload
dropzoneProps={ dropzoneProps={
Object { Object {
@ -537,7 +534,6 @@ exports[`<JsonFileUpload /> upload file 1`] = `
</FileUploadField> </FileUploadField>
</t> </t>
</FileUpload> </FileUpload>
</JsonFileUploadComp>
<div <div
aria-live="polite" aria-live="polite"
className="pf-c-form__helper-text" className="pf-c-form__helper-text"

View file

@ -54,17 +54,17 @@ export const OpenIdConnectSettings = () => {
} }
}, [discovering]); }, [discovering]);
const fileUpload = async (value: string) => { const fileUpload = async (obj: object) => {
if (value !== "") { if (obj) {
const formData = new FormData(); const formData = new FormData();
formData.append("providerId", id); formData.append("providerId", id);
formData.append("file", new Blob([value])); formData.append("file", new Blob([JSON.stringify(obj)]));
try { try {
const response = await fetch( const response = await fetch(
`${getBaseUrl( `${getBaseUrl(
adminClient adminClient
)}/admin/realms/${realm}/identity-provider/import-config`, )}admin/realms/${realm}/identity-provider/import-config`,
{ {
method: "POST", method: "POST",
body: formData, body: formData,
@ -173,7 +173,7 @@ export const OpenIdConnectSettings = () => {
validated={ validated={
discoveryResult && discoveryResult.error ? "error" : "default" discoveryResult && discoveryResult.error ? "error" : "default"
} }
onChange={(value) => fileUpload(value as string)} onChange={(value) => fileUpload(value)}
/> />
</FormGroup> </FormGroup>
)} )}

View file

@ -1,4 +1,5 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { import {
Button, Button,
ButtonVariant, ButtonVariant,
@ -11,12 +12,7 @@ import {
TextContent, TextContent,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import { useTranslation } from "react-i18next"; import { JsonFileUpload } from "../components/json-file-upload/JsonFileUpload";
import {
JsonFileUpload,
JsonFileUploadEvent,
} from "../components/json-file-upload/JsonFileUpload";
export type PartialImportProps = { export type PartialImportProps = {
open: boolean; open: boolean;
@ -33,21 +29,8 @@ export const PartialImportDialog = (props: PartialImportProps) => {
setImportEnabled(false); setImportEnabled(false);
}, [props.open]); }, [props.open]);
const handleFileChange = ( const handleFileChange = (value: object) => {
value: string | File, setImportEnabled(!!value);
filename: string,
event: JsonFileUploadEvent
) => {
setImportEnabled(value !== null);
// if user pressed clear button reset importEnabled
const nativeEvent = event.nativeEvent;
if (
nativeEvent instanceof MouseEvent &&
!(nativeEvent instanceof DragEvent)
) {
setImportEnabled(false);
}
}; };
return ( return (

View file

@ -29,29 +29,15 @@ export const NewRealmForm = () => {
const adminClient = useAdminClient(); const adminClient = useAdminClient();
const { addAlert } = useAlerts(); const { addAlert } = useAlerts();
const { const { register, handleSubmit, control, errors, setValue } = useForm<
register, RealmRepresentation
handleSubmit, >({ mode: "onChange" });
setValue,
control,
formState,
errors,
} = useForm<RealmRepresentation>({ mode: "onChange" });
const handleFileChange = (value: string | File) => { const handleFileChange = (obj: object) => {
const defaultRealm = { id: "", realm: "", enabled: true }; const defaultRealm = { id: "", realm: "", enabled: true };
Object.entries(obj || defaultRealm).map((entry) =>
let obj: { [name: string]: boolean | string } = defaultRealm; setValue(entry[0], entry[1])
if (value) { );
try {
obj = JSON.parse(value as string);
} catch (error) {
console.warn("Invalid json, ignoring value using default");
}
}
Object.keys(obj).forEach((k) => {
setValue(k, obj[k]);
});
}; };
const save = async (realm: RealmRepresentation) => { const save = async (realm: RealmRepresentation) => {
@ -83,7 +69,11 @@ export const NewRealmForm = () => {
onSubmit={handleSubmit(save)} onSubmit={handleSubmit(save)}
role="manage-realm" role="manage-realm"
> >
<JsonFileUpload id="kc-realm-filename" onChange={handleFileChange} /> <JsonFileUpload
id="kc-realm-filename"
allowEditingUploadedText
onChange={handleFileChange}
/>
<FormGroup <FormGroup
label={t("realmName")} label={t("realmName")}
isRequired isRequired
@ -118,11 +108,7 @@ export const NewRealmForm = () => {
/> />
</FormGroup> </FormGroup>
<ActionGroup> <ActionGroup>
<Button <Button variant="primary" type="submit">
variant="primary"
type="submit"
isDisabled={!formState.isValid}
>
{t("common:create")} {t("common:create")}
</Button> </Button>
<Button variant="link" onClick={() => history.goBack()}> <Button variant="link" onClick={() => history.goBack()}>