Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[lens][draft] Lens/drag drop #36268

Merged
merged 6 commits into from
May 10, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions x-pack/plugins/lens/public/drag_drop/drag_drop.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.drag-drop_is-drop-target {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you rename these classes to use BEM naming structure? (Guidelines at the bottom of this page).

Also, you'll need a 3-letter prefix for scoping.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do. I haven't done much CSS since joining Kibana. I hadn't seen those guidelines before. I've historically not used camelCasing in CSS, but it looks like that's the norm here, is that right?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's correct. Those guidelines should explain how to name your classes. There's also a link to what BEM naming is.

background-color: transparentize($euiColorSecondary, .9);
}

.drag-drop_is-active-drop-target {
background-color: transparentize($euiColorSecondary, .75);
}
104 changes: 104 additions & 0 deletions x-pack/plugins/lens/public/drag_drop/drag_drop.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* 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 from 'react';
import { render, shallow, mount } from 'enzyme';
import { DragDrop } from './drag_drop';
import { ChildDragDropProvider } from './providers';

jest.useFakeTimers();

describe('DragDrop', () => {
test('renders if nothing is being dragged', () => {
const component = render(
<DragDrop value="hello" draggable>
Hello!
</DragDrop>
);

expect(component).toMatchSnapshot();
});

test('dragover calls preventDefault if droppable is true', () => {
const preventDefault = jest.fn(() => {});
const component = shallow(<DragDrop droppable>Hello!</DragDrop>);

component.find('[data-test-subj="drag-drop"]').simulate('dragover', { preventDefault });

expect(preventDefault).toBeCalled();
});

test('dragover does not call preventDefault if droppable is false', () => {
const preventDefault = jest.fn(() => {});
const component = shallow(<DragDrop>Hello!</DragDrop>);

component.find('[data-test-subj="drag-drop"]').simulate('dragover', { preventDefault });

expect(preventDefault).not.toBeCalled();
});

test('dragstart sets dragging in the context', async () => {
const setDragging = jest.fn(() => {});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think you can also omit the implementation here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aawwww snap. You're right. That's nice.

const dataTransfer = {
setData: jest.fn(() => {}),
getData: jest.fn(() => {}),
};
const value = {};

const component = mount(
<ChildDragDropProvider dragging={undefined} setDragging={setDragging}>
<DragDrop value={value}>Hello!</DragDrop>
</ChildDragDropProvider>
);

component.find('[data-test-subj="drag-drop"]').simulate('dragstart', { dataTransfer });

jest.runAllTimers();

expect(dataTransfer.setData).toBeCalledWith('text', 'dragging');
expect(setDragging).toBeCalledWith(value);
});

test('drop resets all the things', async () => {
const preventDefault = jest.fn(() => {});
const stopPropagation = jest.fn(() => {});
const setDragging = jest.fn(() => {});
const onDrop = jest.fn(() => {});
const value = {};

const component = mount(
<ChildDragDropProvider dragging="hola" setDragging={setDragging}>
<DragDrop onDrop={onDrop} value={value}>
Hello!
</DragDrop>
</ChildDragDropProvider>
);

component
.find('[data-test-subj="drag-drop"]')
.simulate('drop', { preventDefault, stopPropagation });

expect(preventDefault).toBeCalled();
expect(stopPropagation).toBeCalled();
expect(setDragging).toBeCalledWith(undefined);
expect(onDrop).toBeCalledWith('hola');
});

test('droppable is reflected in the className', () => {
const component = render(
<DragDrop
onDrop={(x: any) => {
throw x;
}}
droppable
>
Hello!
</DragDrop>
);

expect(component).toMatchSnapshot();
});
});
137 changes: 137 additions & 0 deletions x-pack/plugins/lens/public/drag_drop/drag_drop.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* 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, { useState, useContext } from 'react';
import { DragContext } from './providers';

type DroppableEvent = React.DragEvent<HTMLElement>;

/**
* A function that handles a drop event.
*/
type DropHandler = (item: any) => void;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't feel so good with this any type here - someone could provide drop items which cause runtime errors and we can't 'normalize' this in the frame as for persisted state.

Can we define some kind of meta information interface including a datasource internal id (this is what gets dragged around, right)?
We could also use unknown here making it a responsibility of the implementer to safely convert it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like either using unknown or saying they at least have to have a signature like { type: 'string' } so that they can be somewhat systematically reasoned about.


/**
* The argument to the DragDrop component.
*/
interface Props {
/**
* The CSS class(es) for the root element.
*/
className?: string;

/**
* The event handler that fires when an item
* is dropped onto this DragDrop component.
*/
onDrop?: DropHandler;

/**
* The value associated with this item, if it is draggable.
* If this component is dragged, this will be the value of
* "dragging" in the root drag/drop context.
*/
value?: any;

/**
* The React children.
*/
children?: any;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

children can be types as React.ReactNode


/**
* Indicates whether or not the currently dragged item
* can be dropped onto this component.
*/
droppable?: boolean;

/**
* Indicates whether or not this component is draggable.
*/
draggable?: boolean;
}

/**
* A draggable / droppable item. Items can be both draggable and droppable at
* the same time.
*
* @param props
*/
export function DragDrop(props: Props) {
const { dragging, setDragging } = useContext(DragContext);
const [state, setState] = useState({ isActive: false });
const { className, onDrop, value, children, droppable, draggable } = props;
const isDragging = draggable && value === dragging;

const classSuffix =
' drag-drop' +
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we already have the classnames dependency, so might as well use it here:

classNames('drag-drop',
{
 droppable: 'drag-drop_is-drop-target',
 droppable && state.isActive: 'drag-drop_is-active-drop-target',
isDragging: 'drag-drop_is-dragging'
});

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I didn't see the need to pull in a dependency for something so trivial. You think I should?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weird @flash1293 's comments' timestamps are broke and they're saying "An hour from now"... haha....

His example is backwards, you have to put the classname first followed by the condition, but yes it is not trivial since that's all the dependency does and it's used everywhere. Another good pattern to follow throughout Kibana.

(droppable ? ' drag-drop_is-drop-target' : '') +
(droppable && state.isActive ? ' drag-drop_is-active-drop-target' : '') +
(isDragging ? ' drag-drop_is-dragging' : '');

const dragStart = (e: DroppableEvent) => {
// Setting stopPropgagation causes Chrome failures, so
// we are manually checking if we've already handled this
// in a nested child, and doing nothing if so...
if (e.dataTransfer.getData('text')) {
return;
}

e.dataTransfer.setData('text', 'dragging');

// Chrome causes issues if you try to render from within a
// dragStart event, so we drop a setTimeout to avoid that.
setTimeout(() => setDragging(value));
};

const dragEnd = (e: DroppableEvent) => {
e.stopPropagation();
setDragging(undefined);
};

const dragOver = (e: DroppableEvent) => {
if (!droppable) {
return;
}

e.preventDefault();

// An optimization to prevent a bunch of React churn.
if (!state.isActive) {
setState({ ...state, isActive: true });
}
};

const dragLeave = () => {
setState({ ...state, isActive: false });
};

const drop = (e: DroppableEvent) => {
e.preventDefault();
e.stopPropagation();

setState({ ...state, isActive: false });
setDragging(undefined);

if (onDrop) {
onDrop(dragging);
}
};

return (
<div
data-test-subj="drag-drop"
className={`${className || ''}${classSuffix}`}
onDragOver={dragOver}
onDragLeave={dragLeave}
onDrop={drop}
draggable={draggable}
onDragEnd={dragEnd}
onDragStart={dragStart}
>
{children}
</div>
);
}
8 changes: 8 additions & 0 deletions x-pack/plugins/lens/public/drag_drop/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* 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.
*/

export * from './providers';
export * from './drag_drop';
85 changes: 85 additions & 0 deletions x-pack/plugins/lens/public/drag_drop/providers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* 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, { useState } from 'react';

/**
* The shape of the drag / drop context.
*/
export interface DragContextState {
/**
* The item being dragged or undefined.
*/
dragging: any;

/**
* Set the item being dragged.
*/
setDragging: (dragging: any) => void;
}

/**
* The drag / drop context singleton, used like so:
*
* const { dragging, setDragging } = useContext(DragContext);
*/
export const DragContext = React.createContext<DragContextState>({
dragging: undefined,
setDragging: () => {},
});

/**
* The argument to DragDropProvider.
*/
export interface ProviderProps {
/**
* The item being dragged. If unspecified, the provider will
* behave as if it is the root provider.
*/
dragging: any;

/**
* Sets the item being dragged. If unspecified, the provider
* will behave as if it is the root provider.
*/
setDragging: (dragging: any) => void;

/**
* The React children.
*/
children?: any;
}

/**
* A React provider that tracks the dragging state. This should
* be placed at the root of any React application that supports
* drag / drop.
*
* @param props
*/
export function RootDragDropProvider({ children }: { children: any }) {
const [state, setState] = useState<{ dragging: any }>({
dragging: undefined,
});
const setDragging = (dragging: any) => setState({ dragging });

return (
<ChildDragDropProvider dragging={state.dragging} setDragging={setDragging}>
{children}
</ChildDragDropProvider>
);
}

/**
* A React drag / drop provider that derives its state from a RootDragDropProvider. If
* part of a React application is rendered separately from the root, this provider can
* be used to enable drag / drop functionality within the disconnected part.
*
* @param props
*/
export function ChildDragDropProvider({ dragging, setDragging, children }: ProviderProps) {
return <DragContext.Provider value={{ dragging, setDragging }}>{children}</DragContext.Provider>;
}
Loading