Skip to content
This repository was archived by the owner on Mar 4, 2020. It is now read-only.

Checkbox base prototype #2263

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
10 changes: 7 additions & 3 deletions packages/react/src/components/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Accessibility, checkboxBehavior } from '@fluentui/accessibility'
import CheckboxBase from './CheckboxBase'
import * as customPropTypes from '@fluentui/react-proptypes'
import * as _ from 'lodash'
import * as React from 'react'
Expand Down Expand Up @@ -149,11 +150,14 @@ class Checkbox extends AutoControlledComponent<WithAsProp<CheckboxProps>, Checkb
})

return (
<ElementType
className={classes.root}
<CheckboxBase
slots={{ root: ElementType }}
slotProps={{ input: { style: { visibility: 'hidden', display: 'none' } } }}
Copy link
Member

Choose a reason for hiding this comment

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

You might want to pull this out of the render function in a const object so that this isn't recomputed on every render.

classes={classes}
onClick={this.handleClick}
onChange={this.handleChange}
onFocus={this.handleFocus}
checked={this.state.checked}
{...accessibility.attributes.root}
{...unhandledProps}
{...applyAccessibilityKeyHandlers(accessibility.keyHandlers.root, unhandledProps)}
Expand All @@ -169,7 +173,7 @@ class Checkbox extends AutoControlledComponent<WithAsProp<CheckboxProps>, Checkb
}),
})}
{labelPosition === 'end' && labelElement}
</ElementType>
</CheckboxBase>
)
}
}
Expand Down
80 changes: 80 additions & 0 deletions packages/react/src/components/Checkbox/CheckboxBase.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import * as React from 'react'

interface CheckboxBaseProps {
checked?: boolean
onChange?: React.ChangeEventHandler
onClick?: React.MouseEventHandler
slots?: {
root?: any
input?: any
}
slotProps?: {
root?: any
input?: any
}
classes?: any
Comment on lines +7 to +15
Copy link
Member

Choose a reason for hiding this comment

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

Will these types be more refined in the final version?

}

const Testhelper = (prop?: Function, propName?: string) => {
Copy link
Member

Choose a reason for hiding this comment

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

Maybe TestHelper?

if (!prop) {
return {}
}
return {
[propName]: prop,
}
}

const CheckboxBase: React.FunctionComponent<CheckboxBaseProps> = props => {
const { checked, onChange, onClick, classes = {}, slots = {}, slotProps = {}, ...rest } = props
const { root: RootSlot = 'div', input: InputSlot = 'input' } = slots
const { root: rootClass, input: inputClass } = classes
const { root: rootProps, input: inputProps } = slotProps

const [isChecked, setIsChecked] = React.useState(!!checked)
Copy link
Contributor

Choose a reason for hiding this comment

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

is it still valid that the state will need to be pulled out of the base component?

const realIsChecked = checked === undefined ? isChecked : !!checked
Copy link
Member

Choose a reason for hiding this comment

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

I'm having a really hard time figuring out why we need this instead of using the regular isChecked.


const onChangeHandler = React.useCallback(
(ev: any) => {
if (onClick) {
onClick(ev)
}
if (!ev.defaultPrevented) {
if (onChange) {
onChange(ev)
}
}
if (!ev.defaultPrevented) {
setIsChecked(!realIsChecked)
}
Comment on lines +41 to +48
Copy link
Member

Choose a reason for hiding this comment

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

You could fuse this two ifs into one.

},
[setIsChecked, realIsChecked, onChange],
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to add setIsChecked here? From my understanding, since the function will never change its value, it is a variable that will never trigger a different callback.

)

const onKeyDown = React.useCallback(
(ev: React.KeyboardEvent) => {
console.log(ev.keyCode)
switch (ev.keyCode) {
case 13:
case 32: {
Copy link
Contributor

Choose a reason for hiding this comment

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

according to ARIA only space should toggle the checked state. How would we allow customization (if some partner wants to toggle on enter as well)? Would that need to be a separate or a custom component?

setIsChecked(!realIsChecked)
Copy link
Contributor

Choose a reason for hiding this comment

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

In both Semantic UI React and Stardust there is the concept of auto controlled state which allows the consumer to take over and control the state from outside by using a combination of the chnge handler and override state prop. It is especially useful in components like Popup or Dialog where the consumer can add control if the surface should be opened/closed initially or based on external event, as well as additional logic to extend the internal handlers. Maybe this is a simplified version of the API, but it would be good to keep it as it turned out to be very effective and consistent way of controlling the state from outside.

Copy link
Member

Choose a reason for hiding this comment

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

Small note, the concept of "auto controlled state" comes from React itself. Form controls, like the <input />, will automatically control their value when the user inputs values. However, if the dev controls the value prop, then it will defer to the dev's props. If the dev removes the prop, then React resumes control of the <input />.

The principles that follow from this is that:

  1. Components should work without requiring the consumer to wire them up. Dropdowns should open on click, inputs should update their value on input, etc.
  2. Components should defer to controlled mode if the dev provides props
  3. Components should resume control if the developer "unsets" the prop value (i.e. undefined).

}
}
},
[setIsChecked, realIsChecked],
)

return (
<RootSlot
onKeyDown={onKeyDown}
onClick={onChangeHandler}
Copy link
Contributor

Choose a reason for hiding this comment

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

should this be called onClickHandlefr?

Copy link
Member

Choose a reason for hiding this comment

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

Convention is handleClick, this is a common community convention based on popular libs and the React docs:

https://reactjs.org/docs/handling-events.html

In React, this could instead be:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}```

className={rootClass}
{...rest}
{...rootProps}
{...Testhelper(onChange, 'onChange')}
>
<InputSlot checked={realIsChecked} type="checkbox" className={inputClass} {...inputProps} />
{props.children}
</RootSlot>
)
}
export default CheckboxBase
4 changes: 4 additions & 0 deletions packages/react/test/specs/commonTests/isConformant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export interface Conformant {
rendersPortal?: boolean
/** This component uses wrapper slot to wrap the 'meaningful' element. */
wrapperComponent?: React.ReactType
/** This component uses a base element */
baseComponent?: React.ReactType
}

/**
Expand All @@ -53,6 +55,7 @@ export default function isConformant(
requiredProps = {},
rendersPortal = false,
wrapperComponent = null,
baseComponent = null,
} = options
const { throwError } = helpers('isConformant', Component)

Expand All @@ -61,6 +64,7 @@ export default function isConformant(
const helperComponentNames = [
...[Ref, RefFindNode],
...(wrapperComponent ? [wrapperComponent] : []),
...(baseComponent ? [baseComponent] : []),
].map(getDisplayName)

const toNextNonTrivialChild = (from: ReactWrapper) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import * as React from 'react'
import Checkbox from 'src/components/Checkbox/Checkbox'
import CheckboxBase from 'src/components/Checkbox/CheckboxBase'
import {
isConformant,
handlesAccessibility,
htmlIsAccessibilityCompliant,
} from 'test/specs/commonTests'

describe('Checkbox', () => {
isConformant(Checkbox)
isConformant(Checkbox, { baseComponent: CheckboxBase })
handlesAccessibility(Checkbox, { defaultRootRole: 'checkbox' })

describe('HTML accessibility rules validation', () => {
Expand Down
185 changes: 185 additions & 0 deletions packages/react/test/specs/components/Checkbox/CheckboxBase-test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import * as React from 'react'
import { mount } from 'enzyme'
import CheckboxBase from 'src/components/Checkbox/CheckboxBase'

describe("Baby's first test", () => {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
describe("Baby's first test", () => {
describe("CheckboxBase", () => {

Copy link
Member

@levithomason levithomason Jan 23, 2020

Choose a reason for hiding this comment

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

Let's organize our tests by:

describe(displayName, () => {
  describe(propName, () => {
    it('does something', () => {})
    it('does not do something', () => {})
  })
})

This pattern of Component > prop is used for all tests and docs. Following it ensures we can do a better of job of ensuring we have full coverage of documentation and tests. Having complete docs/tests on public APIs means we can also rev the library with more confidence and less bugs.

it('renders something', () => {
expect(mount(<CheckboxBase />)).toBeTruthy()
})

it('has an input', () => {
const control = mount(<CheckboxBase />)
const input = control
.find('input')
.first()
.getDOMNode()
expect(input).toBeTruthy()
})

it('can be checked', () => {
const control = mount(<CheckboxBase checked={true} />)
const inputChecked = control
.find('input')
.first()
.prop('checked')
expect(inputChecked).toBe(true)
})

it('can be unchecked', () => {
const control = mount(<CheckboxBase />)
const inputChecked = control
.find('input')
.first()
.prop('checked')
expect(inputChecked).toBe(false)
})

it('can switch check state', () => {
const control = mount(<CheckboxBase />)
const inputChecked = control
.find('input')
.first()
.prop('checked')
expect(inputChecked).toBe(false)
control.setProps({ checked: true })
const inputCheckedAfter = control
.find('input')
.first()
.prop('checked')
expect(inputCheckedAfter).toBe(true)
})

it('changes state when clicked', () => {
const control = mount(<CheckboxBase />)
expect(
control
.find('input')
.first()
.prop('checked'),
).toBe(false)
control.simulate('click')
expect(
control
.find('input')
.first()
.prop('checked'),
).toBe(true)
control.simulate('click')
expect(
control
.find('input')
.first()
.prop('checked'),
).toBe(false)
})

it('calls onChange when checked state changes', () => {
const change = jest.fn()
const control = mount(<CheckboxBase onChange={change} />) // let, the only constant is change
Copy link
Member

Choose a reason for hiding this comment

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

What's with the comment here? I don't understand it very well.

Copy link
Member

@levithomason levithomason Jan 23, 2020

Choose a reason for hiding this comment

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

Event handlers are tested as part of the baseline isConformant() test. This test checks every synthetic event type and asserts more things:

import { isConformant } from 'test/specs/commonTests'

describe('CheckboxBase', () => {
  isConformant(CheckboxBase)
})

See .github/test-a-feature.md for more.

control.simulate('click')
expect(change).toHaveBeenCalled()
})

it('does not change value when onChange prevents default', () => {
const change = jest.fn((e: any) => e.preventDefault())
const control = mount(<CheckboxBase onChange={change} />)
expect(
control
.find('input')
.first()
.prop('checked'),
).toBe(false)
control.simulate('click')
expect(
control
.find('input')
.first()
.prop('checked'),
).toBe(false)
})

it('does not call onChange value when onClick prevents default', () => {
const click = jest.fn((e: any) => e.preventDefault())
const change = jest.fn()
const control = mount(<CheckboxBase onClick={click} onChange={change} />)
control.simulate('click')
expect(change).not.toHaveBeenCalled()
})

it('calls onClick', () => {
const click = jest.fn()
const control = mount(<CheckboxBase onClick={click} />)
control.simulate('click')
expect(click).toHaveBeenCalled()
})

it('renders content', () => {
const control = mount(
<CheckboxBase>
<label>foo</label>
</CheckboxBase>,
)
expect(control.find('label').length).toBe(1)
})

it('can render with a different root type', () => {
const control = mount(<CheckboxBase slots={{ root: 'span' }} />)
expect(control.find('span').length).toBe(1)
})

it('can render with a different input type', () => {
const MyInput = () => (
<a>
<input type="hidden" value="I don't even know why anymore..." />
</a>
)
const control = mount(<CheckboxBase slots={{ input: MyInput }} />)
expect(control.find('a').length).toBe(1)
})

it('changes on enter press', () => {
const control = mount(<CheckboxBase />)
control.simulate('keydown', {
keyCode: 13,
key: 'Enter',
Comment on lines +143 to +144
Copy link
Member

Choose a reason for hiding this comment

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

Wouldn't the keyCode have been enough here?

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member

@khmakoto khmakoto Jan 23, 2020

Choose a reason for hiding this comment

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

@levithomason sure, what I meant is that having both was redundant, I don't actually have a preference for one over the other.

})
expect(control.find('input').prop('checked')).toBe(true)
})

it('changes on space press', () => {
const control = mount(<CheckboxBase />)
control.simulate('keydown', {
keyCode: 32,
})
expect(control.find('input').prop('checked')).toBe(true)
})

describe('class handling', () => {
it('renders classes', () => {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
it('renders classes', () => {
it('renders classes for root', () => {

const control = mount(<CheckboxBase classes={{ root: 'foo' }} />)
expect(control.find('div.foo').length).toBe(1)
})

it('renders classes for input', () => {
const control = mount(<CheckboxBase classes={{ input: 'foo' }} />)
expect(control.find('input.foo').length).toBe(1)
})
})

describe('slotProps', () => {
it('renders slotProps for input', () => {
const control = mount(<CheckboxBase slotProps={{ input: { 'data-foo': 'bar' } }} />)
expect(control.find('input[data-foo="bar"]').length).toBe(1)
})

it('renders slotProps for root', () => {
const control = mount(<CheckboxBase slotProps={{ root: { 'data-foo': 'bar' } }} />)
expect(control.find('div[data-foo="bar"]').length).toBe(1)
})

it('applies unused props to the root element', () => {
const control = mount(<CheckboxBase data-foo="bar" />)
expect(control.find('div[data-foo="bar"]').length).toBe(1)
})
})
})