Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
Heenawter committed May 16, 2022
1 parent aaf7ac4 commit 2e7d2ef
Show file tree
Hide file tree
Showing 10 changed files with 66 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ export const ControlFrame = ({
if (embeddableRoot.current && embeddable) {
embeddable.render(embeddableRoot.current);
}
const subscription = embeddable?.getInput$().subscribe((newInput) => {
setTitle(newInput.title);
});
const subscription = embeddable?.getInput$().subscribe((newInput) => setTitle(newInput.title));
return () => {
subscription?.unsubscribe();
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ export const ControlGroupStrings = {
i18n.translate('controls.controlGroup.manageControl.selectFieldMessage', {
defaultMessage: 'Please select a field',
}),
getSelectDataViewMessage: () =>
i18n.translate('controls.controlGroup.manageControl.selectDataViewMessage', {
defaultMessage: 'Please select a data view',
}),
},
management: {
getAddControlTitle: () =>
Expand Down
29 changes: 15 additions & 14 deletions src/plugins/controls/public/control_group/editor/control_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ interface EditControlProps {
isCreate: boolean;
title?: string;
width: ControlWidth;
onSave: (type: string, factory?: IEditableControlFactory) => void;
onSave: (type?: string) => void;
onCancel: () => void;
removeControl?: () => void;
updateTitle: (title?: string) => void;
Expand Down Expand Up @@ -107,11 +107,10 @@ export const ControlEditor = ({
embeddable ? embeddable.getInput().fieldName : undefined
);

const getCompatibleControlTypes = (dataView?: DataView) => {
if (!dataView) return {};
const doubleLinkFields = (dataView: DataView) => {
// double link the parent-child relationship specifically for case-sensitivity support for options lists
const fieldRegistry: DataControlFieldRegistry = {};

// double link the parent-child relationship specifically for case-sensitivity support for options lists
for (const field of dataView.fields.getAll()) {
if (!fieldRegistry[field.name]) {
fieldRegistry[field.name] = { field, compatibleControlTypes: [] };
Expand All @@ -127,6 +126,12 @@ export const ControlEditor = ({
fieldRegistry[parentFieldName].childFieldName = field.name;
}
}
return fieldRegistry;
};

const getCompatibleControlTypes = (dataView?: DataView) => {
if (!dataView) return {};
const fieldRegistry: DataControlFieldRegistry = doubleLinkFields(dataView);

const controlFactories = getControlTypes().map(
(controlType) => getControlFactory(controlType) as IEditableControlFactory
Expand All @@ -143,7 +148,6 @@ export const ControlEditor = ({
}
});
setState((s) => ({ ...s, fieldRegistry }));
// setSelectedField(Object.keys(fieldRegistry)[0]);
};

useMount(() => {
Expand All @@ -160,12 +164,12 @@ export const ControlEditor = ({
dataView = await get(initialId);
}
if (!mounted) return;
getCompatibleControlTypes(dataView);
setState((s) => ({
...s,
selectedDataView: dataView,
dataViewListItems,
}));
getCompatibleControlTypes(dataView);
})();
return () => {
mounted = false;
Expand Down Expand Up @@ -207,12 +211,14 @@ export const ControlEditor = ({
onTypeEditorChange({ dataViewId });
setSelectedField(undefined);
get(dataViewId).then((newDataView) => {
setState((s) => ({ ...s, selectedDataView: newDataView }));
getCompatibleControlTypes(newDataView);
setState((s) => ({ ...s, selectedDataView: newDataView }));
});
}}
trigger={{
label: state.selectedDataView?.title ?? 'Select data view',
label:
state.selectedDataView?.title ??
ControlGroupStrings.manageControl.getSelectDataViewMessage(),
}}
/>
</EuiFormRow>
Expand All @@ -229,11 +235,6 @@ export const ControlEditor = ({
parentFieldName: state.fieldRegistry?.[field.name].parentFieldName,
childFieldName: state.fieldRegistry?.[field.name].childFieldName,
});
// console.log('on select field:');
// console.log('File registry: ', state.fieldRegistry);
// console.log('----> field: ', field.name);
// console.log('----> parent: ', state.fieldRegistry?.[field.name].parentFieldName);
// console.log('----> child: ', state.fieldRegistry?.[field.name].childFieldName);

const newDefaultTitle = field.displayName ?? field.name;
setDefaultTitle(newDefaultTitle);
Expand Down Expand Up @@ -322,7 +323,7 @@ export const ControlEditor = ({
iconType="check"
color="primary"
disabled={!controlEditorValid}
onClick={() => controlType && onSave(controlType, factory as IEditableControlFactory)}
onClick={() => onSave(controlType)}
>
{ControlGroupStrings.manageControl.getSaveChangesTitle()}
</EuiButton>
Expand Down
26 changes: 16 additions & 10 deletions src/plugins/controls/public/control_group/editor/create_control.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ export const CreateControlButton = ({
});
};

const onSave = (ref: OverlayRef, type?: string) => {
if (!type) {
reject();
ref.close();
return;
}

const factory = getControlFactory(type) as IEditableControlFactory;
if (factory.presaveTransformFunction) {
inputToReturn = factory.presaveTransformFunction(inputToReturn);
}
resolve({ type, controlInput: inputToReturn });
ref.close();
};

const flyoutInstance = openFlyout(
toMountPoint(
<PresentationUtilProvider>
Expand All @@ -83,16 +98,7 @@ export const CreateControlButton = ({
width={defaultControlWidth ?? DEFAULT_CONTROL_WIDTH}
updateTitle={(newTitle) => (inputToReturn.title = newTitle)}
updateWidth={updateDefaultWidth}
onSave={(type: string, factory?: IEditableControlFactory) => {
if (!factory) {
factory = getControlFactory(type) as IEditableControlFactory;
}
if (factory.presaveTransformFunction) {
inputToReturn = factory.presaveTransformFunction(inputToReturn);
}
resolve({ type, controlInput: inputToReturn });
flyoutInstance.close();
}}
onSave={(type) => onSave(flyoutInstance, type)}
onCancel={() => onCancel(flyoutInstance)}
onTypeEditorChange={(partialInput) =>
(inputToReturn = { ...inputToReturn, ...partialInput })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,13 @@ export const EditControlButton = ({ embeddableId }: { embeddableId: string }) =>
});
};

const onSave = (type: string, ref: OverlayRef) => {
const onSave = (ref: OverlayRef, type?: string) => {
if (!type) {
reject();
ref.close();
return;
}

// if the control now has a new type, need to replace the old factory with
// one of the correct new type
if (latestPanelState.current.type !== type) {
Expand Down Expand Up @@ -135,7 +141,7 @@ export const EditControlButton = ({ embeddableId }: { embeddableId: string }) =>
onTypeEditorChange={(partialInput) => {
inputToReturn = { ...inputToReturn, ...partialInput };
}}
onSave={(type) => onSave(type, flyoutInstance)}
onSave={(type) => onSave(flyoutInstance, type)}
removeControl={() => {
openConfirm(ControlGroupStrings.management.deleteControls.getSubtitle(), {
confirmButtonText: ControlGroupStrings.management.deleteControls.getConfirm(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,19 @@ import './field_picker.scss';
export interface FieldPickerProps {
dataView?: DataView;
selectedFieldName?: string;
// showFields?: string[];
filterPredicate?: (f: DataViewField) => boolean;
onSelectField?: (selectedField: DataViewField) => void;
}

export const FieldPicker = ({
dataView,
onSelectField,
// showFields,
filterPredicate,
selectedFieldName,
}: FieldPickerProps) => {
const [nameFilter, setNameFilter] = useState<string>('');
const [typesFilter, setTypesFilter] = useState<string[]>([]);

// Retrieve, filter, and sort fields from data view
const fields = dataView
? sortBy(
Expand All @@ -49,7 +48,13 @@ export const FieldPicker = ({
)
: [];

const uniqueTypes = dataView ? uniq(fields.map((f) => f.type as string)) : [];
const uniqueTypes = dataView
? uniq(
dataView.fields
.filter((f) => (filterPredicate ? filterPredicate(f) : true))
.map((f) => f.type as string)
)
: [];

return (
<EuiFlexGroup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
expect(await saveButton.isEnabled()).to.be(true);
await dashboardControls.controlsEditorSetDataView('animals-*');
expect(await saveButton.isEnabled()).to.be(false);
await dashboardControls.controlsEditorSetfield('animal.keyword');
await dashboardControls.controlsEditorSetfield('animal.keyword', OPTIONS_LIST_CONTROL);
await dashboardControls.controlEditorSave();

// when creating a new filter, the ability to select a data view should be removed, because the dashboard now only has one data view
Expand All @@ -129,7 +129,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await dashboardControls.optionsListEnsurePopoverIsClosed(secondId);

await dashboardControls.editExistingControl(secondId);
await dashboardControls.controlsEditorSetfield('animal.keyword');
await dashboardControls.controlsEditorSetfield('animal.keyword', OPTIONS_LIST_CONTROL);
await dashboardControls.controlEditorSave();

const selectionString = await dashboardControls.optionsListGetSelectionsString(secondId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
expect(await saveButton.isEnabled()).to.be(true);
await dashboardControls.controlsEditorSetDataView('kibana_sample_data_flights');
expect(await saveButton.isEnabled()).to.be(false);
await dashboardControls.controlsEditorSetfield('dayOfWeek');
await dashboardControls.controlsEditorSetfield('dayOfWeek', RANGE_SLIDER_CONTROL);
await dashboardControls.controlEditorSave();
await dashboardControls.rangeSliderWaitForLoading();
validateRange('placeholder', firstId, '0', '6');
Expand Down Expand Up @@ -164,7 +164,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
it('editing field clears selections', async () => {
const secondId = (await dashboardControls.getAllControlIds())[1];
await dashboardControls.editExistingControl(secondId);
await dashboardControls.controlsEditorSetfield('FlightDelayMin');
await dashboardControls.controlsEditorSetfield('FlightDelayMin', RANGE_SLIDER_CONTROL);
await dashboardControls.controlEditorSave();

await dashboardControls.rangeSliderWaitForLoading();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

const changeFieldType = async (controlId: string, newField: string, expectedType?: string) => {
await dashboardControls.editExistingControl(controlId);
await dashboardControls.controlsEditorSetfield(newField);
if (expectedType) await dashboardControls.controlEditorVerifyType(expectedType);
await dashboardControls.controlsEditorSetfield(newField, expectedType);
await dashboardControls.controlEditorSave();
};

Expand Down
17 changes: 9 additions & 8 deletions test/functional/page_objects/dashboard_page_controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ export class DashboardPageControls extends FtrService {
await this.retry.try(async () => {
await this.testSubjects.existOrFail('control-editor-flyout');
});
const autoSelectedType = await this.testSubjects.getVisibleText('control-editor-type');
expect(autoSelectedType).to.equal(CONTROL_DISPLAY_NAMES.default);
await this.controlEditorVerifyType('default');
}

/* -----------------------------------------------------------
Expand Down Expand Up @@ -259,8 +258,7 @@ export class DashboardPageControls extends FtrService {

if (dataViewTitle) await this.controlsEditorSetDataView(dataViewTitle);

if (fieldName) await this.controlsEditorSetfield(fieldName);
await this.controlEditorVerifyType(controlType);
if (fieldName) await this.controlsEditorSetfield(fieldName, controlType);

if (title) await this.controlEditorSetTitle(title);
if (width) await this.controlEditorSetWidth(width);
Expand Down Expand Up @@ -410,7 +408,11 @@ export class DashboardPageControls extends FtrService {
await this.testSubjects.click(`data-view-picker-${dataViewTitle}`);
}

public async controlsEditorSetfield(fieldName: string, shouldSearch: boolean = false) {
public async controlsEditorSetfield(
fieldName: string,
expectedType?: string,
shouldSearch: boolean = false
) {
this.log.debug(`Setting control field to ${fieldName}`);
if (shouldSearch) {
await this.testSubjects.setValue('field-search-input', fieldName);
Expand All @@ -419,14 +421,13 @@ export class DashboardPageControls extends FtrService {
await this.testSubjects.existOrFail(`field-picker-select-${fieldName}`);
});
await this.testSubjects.click(`field-picker-select-${fieldName}`);
if (expectedType) await this.controlEditorVerifyType(expectedType);
}

public async controlEditorVerifyType(type: string) {
this.log.debug(`Verifying that control type has type ${type}`);
this.log.debug(`Verifying that the control editor picked the type ${type}`);
const autoSelectedType = await this.testSubjects.getVisibleText('control-editor-type');
expect(autoSelectedType).to.equal(CONTROL_DISPLAY_NAMES[type]);

// await this.testSubjects.click(`create-${type}-control`);
}

// Options List editor functions
Expand Down

0 comments on commit 2e7d2ef

Please sign in to comment.