Skip to content

Commit

Permalink
[Mappings editor] Add json editor to edit field settings (#47674)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga authored Oct 9, 2019
1 parent c9ffd0f commit 183ed1e
Show file tree
Hide file tree
Showing 12 changed files with 295 additions and 168 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export function useForm<T extends object = FormData>(
const [isValid, setIsValid] = useState<boolean | undefined>(undefined);
const fieldsRefs = useRef<FieldsMap>({});
const formUpdateSubscribers = useRef<Subscription[]>([]);
const isUnmounted = useRef<boolean>(false);

// formData$ is an observable we can subscribe to in order to receive live
// update of the raw form data. As an observable it does not trigger any React
Expand All @@ -64,6 +65,7 @@ export function useForm<T extends object = FormData>(
return () => {
formUpdateSubscribers.current.forEach(subscription => subscription.unsubscribe());
formUpdateSubscribers.current = [];
isUnmounted.current = true;
};
}, []);

Expand Down Expand Up @@ -225,7 +227,9 @@ export function useForm<T extends object = FormData>(
const validate = async () => await validateAllFields();

const subscription = formData$.current.subscribe(raw => {
handler({ isValid, data: { raw, format }, validate });
if (!isUnmounted.current) {
handler({ isValid, data: { raw, format }, validate });
}
});

formUpdateSubscribers.current.push(subscription);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
*/

export * from './json_editor';

export { OnUpdateHandler } from './use_json';
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import { i18n } from '@kbn/i18n';
import { isJSON } from '../../../../../../../src/plugins/es_ui_shared/static/validators/string';

export type OnUpdateHandler<T = { [key: string]: any }> = (arg: {
getData(): T;
data: {
raw: string;
format(): T;
};
validate(): boolean;
isValid: boolean;
}) => void;
Expand Down Expand Up @@ -45,7 +48,7 @@ export const useJson = <T extends object = { [key: string]: any }>({
return isValid;
};

const getData = () => {
const formatContent = () => {
const isValid = validate();
const data = isValid && content.trim() !== '' ? JSON.parse(content) : {};
return data as T;
Expand All @@ -54,7 +57,10 @@ export const useJson = <T extends object = { [key: string]: any }>({
useEffect(() => {
const isValid = validate();
onUpdate({
getData,
data: {
raw: content,
format: formatContent,
},
validate,
isValid,
});
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React, { useRef, useEffect } from 'react';
import {
EuiFlyout,
EuiFlyoutHeader,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiTitle,
EuiButton,
EuiFlexGroup,
EuiFlexItem,
} from '@elastic/eui';

import { useForm, Form, ValidationFunc, OnFormUpdateArg } from '../../../../shared_imports';
import { OnUpdateHandler } from '../../../../../json_editor';
import { useDispatch } from '../../../../mappings_state';
import { Field, NormalizedField } from '../../../../types';
import { UpdateFieldProvider, UpdateFieldFunc } from './update_field_provider';
import { EditFieldHeaderForm } from './edit_field_header_form';
import { FieldSettingsJsonEditor } from './field_settings_json_editor';

const formWrapper = (props: any) => <form {...props} />;

interface Props {
field: NormalizedField;
uniqueNameValidator: ValidationFunc;
}

export const EditField = React.memo(({ field, uniqueNameValidator }: Props) => {
const { form } = useForm<Field>({ defaultValue: field.source });
const dispatch = useDispatch();

const fieldsSettings = useRef<Parameters<OnUpdateHandler>[0] | undefined>(undefined);
const fieldFormUpdate = useRef<OnFormUpdateArg<Field> | undefined>(undefined);

const getSubmitForm = (updateField: UpdateFieldFunc) => async (e?: React.FormEvent) => {
if (e) {
e.preventDefault();
}

const { isValid: isFormValid, data: formData } = await form.submit();

const {
isValid: isFieldsSettingsValid,
data: { format: getFieldsSettingsData },
} = fieldsSettings.current!;

if (isFormValid && isFieldsSettingsValid) {
const fieldsSettingsData = getFieldsSettingsData();
updateField({ ...field, source: { ...formData, ...fieldsSettingsData } });
}
};

const getUpdatedField = (): OnFormUpdateArg<Field> | void => {
if (fieldFormUpdate.current === undefined || fieldsSettings.current === undefined) {
return;
}

const isFormValid = fieldFormUpdate.current.isValid;
const isFieldsSettingsValid = fieldsSettings.current.isValid;

return {
isValid: isFormValid === undefined ? undefined : isFormValid && isFieldsSettingsValid,
data: {
raw: { ...fieldFormUpdate.current.data.raw, settings: fieldsSettings.current.data.raw },
format() {
return {
...fieldFormUpdate.current!.data.format(),
...fieldsSettings.current!.data.format(),
};
},
},
validate: async () => {
const isFieldFormValid = await fieldFormUpdate.current!.validate();
return isFieldFormValid && fieldsSettings.current!.isValid;
},
};
};

useEffect(() => {
const subscription = form.subscribe(updatedFieldForm => {
fieldFormUpdate.current = updatedFieldForm;

const updatedField = getUpdatedField();
if (updatedField) {
dispatch({ type: 'fieldForm.update', value: updatedField });
}
});

return subscription.unsubscribe;
}, [form]);

const onFieldsSettingsUpdate: OnUpdateHandler = fieldsSettingsUpdate => {
fieldsSettings.current = fieldsSettingsUpdate;

const updatedField = getUpdatedField();
if (updatedField) {
dispatch({ type: 'fieldForm.update', value: updatedField });
}
};

const exitEdit = () => {
dispatch({ type: 'documentField.changeStatus', value: 'idle' });
};

const cancel = () => {
exitEdit();
};

const {
source: { name, type, ...fieldsSettingsDefault },
} = field;

return (
<UpdateFieldProvider>
{updateField => (
<EuiFlyout
data-test-subj="mappingsEditorFieldEdit"
onClose={exitEdit}
aria-labelledby="mappingsEditorFieldEditTitle"
size="m"
maxWidth={400}
>
<EuiFlyoutHeader>
<EuiTitle size="m">
<h2>Edit field '{field.source.name}'</h2>
</EuiTitle>
</EuiFlyoutHeader>

<EuiFlyoutBody>
<Form
form={form}
style={{ padding: '20px 0' }}
FormWrapper={formWrapper}
onSubmit={getSubmitForm(updateField)}
>
<EditFieldHeaderForm uniqueNameValidator={uniqueNameValidator} />
</Form>
<FieldSettingsJsonEditor
onUpdate={onFieldsSettingsUpdate}
defaultValue={fieldsSettingsDefault}
/>
</EuiFlyoutBody>

<EuiFlyoutFooter>
<EuiFlexGroup>
<EuiFlexItem>
<EuiButton onClick={getSubmitForm(updateField)} type="submit">
Update
</EuiButton>
</EuiFlexItem>
<EuiFlexItem>
<EuiButton onClick={cancel}>Cancel</EuiButton>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</EuiFlyout>
)}
</UpdateFieldProvider>
);
});
Loading

0 comments on commit 183ed1e

Please sign in to comment.