ronantakizawa/codereview-bench huggingface dataset:
Repository: h2oai/wave
File: ui/src/dialog.tsx (TypeScript)

Code before:
  /** True if the dialog should have closing 'X' button in top right corner. */
  has_x?: B
  /** Text displayed on submit button. Defaults to 'Submit'. */
  submitText?: S
  /** Text displayed on cancel button. Defaults to 'Cancel'. */
  cancelText?: S
}

export default bond(() => {
  const
    { dialogB } = qd,
    toggleDialog = () => dialogB(null),
    submit = () => {
      qd.args[dialogB()!.name] = true
      qd.sync()
      toggleDialog()
    },
    render = () => {
      const dialog = dialogB()
      if (!dialog) return <></>
      const
        { title, cancelText = 'Cancel', submitText = 'Submit', width = '600px', items, disabled, has_x } = dialog,
        dialogContentProps: Fluent.IDialogContentProps = { title, type: has_x ? Fluent.DialogType.close : undefined }

      return (
        <Fluent.Dialog hidden={!dialog} dialogContentProps={dialogContentProps} minWidth={width} maxWidth={width} onDismiss={toggleDialog}>
          <XComponents items={items} />
          <Fluent.DialogFooter>
            <Fluent.DefaultButton onClick={toggleDialog} text={cancelText} />
            <Fluent.PrimaryButton onClick={submit} text={submitText} disabled={disabled} />
          </Fluent.DialogFooter>
        </Fluent.Dialog>
      )
    }
  return { render, dialogB }
})

Review comment (suggestion):
I believe `hidden` will never be true because of the condition on line 41. The downside of this implementation is that the fade in / fade out animations from fluent won't work, but that's not a huge deal. Just wanted to make a note of it =) 

Code after:
  blocking?: B
  /** Dialog with large header banner, mutually exclusive with `closable` prop. Defaults to false. */
  primary?: B
}

export default bond(() => {
  const
    { dialogB } = qd,
    render = () => {
      const
        { title, width = '600px', items = [], closable, primary, blocking } = dialogB() || {},
        dialogContentProps: Fluent.IDialogContentProps = {
          title,
          type: closable
            ? Fluent.DialogType.close
            : primary
              ? Fluent.DialogType.largeHeader
              : Fluent.DialogType.normal
        },
        lastComponent = items.pop()

      return (
        <Fluent.Dialog hidden={!dialogB()} dialogContentProps={dialogContentProps} modalProps={{ isBlocking: blocking }} minWidth={width} maxWidth={width}>
          <XComponents items={items} />
          {lastComponent?.buttons && <Fluent.DialogFooter><XButtons model={lastComponent.buttons} /></Fluent.DialogFooter>}
        </Fluent.Dialog>
      )
    }
  return { render, dialogB }
})
Repository: h2oai/wave
File: py/examples/nav.py (Python)

Code before:
# Nav
# Use nav cards to display sidebar navigation.
# ---
from h2o_wave import main, app, Q, ui


@app('/demo')
async def serve(q: Q):
    if '#' in q.args:
        hash_ = q.args['#']
        q.page['nav'] = ui.form_card(box='1 1 2 5', items=[
            ui.text(f'#={hash_}'),
            ui.button(name='show_nav', label='Back', primary=True),
        ])
    else:
        q.page['nav'] = ui.nav_card(
            box='1 1 2 5',
            value='#menu/spam',
            items=[
                ui.nav_group('Menu', items=[
                    ui.nav_item(name='#menu/spam', label='Spam'),
                    ui.nav_item(name='#menu/ham', label='Ham'),
                    ui.nav_item(name='#menu/eggs', label='Eggs'),
                    ui.nav_item(name='#menu/disabled', label='Disabled', disabled=True),
                ]),
                ui.nav_group('Help', items=[
                    ui.nav_item(name='#about', label='About', icon='Info'),
                    ui.nav_item(name='#support', label='Support', icon='Help'),
                ])
            ],
        )
    await q.page.save()


Review comment (suggestion):
```suggestion
                    ui.nav_item(name='#menu/toast', label='Toast', disabled=True),
```

Code after:
# Nav
# Use nav cards to display sidebar navigation.
# ---
from h2o_wave import main, app, Q, ui


@app('/demo')
async def serve(q: Q):
    if '#' in q.args:
        hash_ = q.args['#']
        q.page['nav'] = ui.form_card(box='1 1 2 5', items=[
            ui.text(f'#={hash_}'),
            ui.button(name='show_nav', label='Back', primary=True),
        ])
    else:
        q.page['nav'] = ui.nav_card(
            box='1 1 2 5',
            value='#menu/spam',
            items=[
                ui.nav_group('Menu', items=[
                    ui.nav_item(name='#menu/spam', label='Spam'),
                    ui.nav_item(name='#menu/ham', label='Ham'),
                    ui.nav_item(name='#menu/eggs', label='Eggs'),
                    ui.nav_item(name='#menu/toast', label='Toast', disabled=True),
                ]),
                ui.nav_group('Help', items=[
                    ui.nav_item(name='#about', label='About', icon='Info'),
                    ui.nav_item(name='#support', label='Support', icon='Help'),
                ])
            ],
        )
    await q.page.save()
Repository: h2oai/wave
File: py/sync_examples.py (Python)

Code before:
slug: /examples/gallery
---

import useBaseUrl from '@docusaurus/useBaseUrl';
''' + '\n' + '\n\n'.join([make_gallery_thumbnail(e) for e in examples])


def main():
    filenames = [line.strip() for line in read_lines(os.path.join(example_dir, 'tour.conf')) if
                 not line.strip().startswith('#')]

    examples = [load_example(filename) for filename in filenames]

    example_md_dir = os.path.join(website_dir, 'docs', 'examples')
    thumbnail_dir = os.path.join(example_md_dir, 'assets')
    for e in examples:
        md = e.to_md()
        write_file(os.path.join(example_md_dir, f'{e.slug}.md'), md)
        if not os.path.exists(os.path.join(thumbnail_dir, f'{e.slug}.png')):
            print(f'*** ALERT: no thumbnail found for example "{e.slug}"')

    example_items = [dict(slug=e.slug) for e in examples]
    example_items.insert(0, dict(slug='index'))
    example_items.insert(1, dict(slug='gallery'))
    write_file(os.path.join(website_dir, 'examples.js'), f'module.exports={json.dumps(example_items)}')
    write_file(os.path.join(example_md_dir, 'index.md'), make_toc(examples))
    write_file(os.path.join(example_md_dir, 'gallery.md'), make_gallery(examples))


if __name__ == '__main__':
    main()


Review comment (suggestion):
The `make_toc()` function needs to use `useBaseUrl()` like the `make_gallery_thumbnail()` function. See #413 

Code after:
    return '''---
title: Gallery
slug: /examples
---

import useBaseUrl from '@docusaurus/useBaseUrl';
''' + '\n' + '\n\n'.join([make_gallery_thumbnail(e) for e in examples])


def main():
    filenames = [line.strip() for line in read_lines(os.path.join(example_dir, 'tour.conf')) if
                 not line.strip().startswith('#')]

    examples = [load_example(filename) for filename in filenames]

    example_md_dir = os.path.join(website_dir, 'docs', 'examples')
    thumbnail_dir = os.path.join(example_md_dir, 'assets')
    for e in examples:
        md = e.to_md()
        write_file(os.path.join(example_md_dir, f'{e.slug}.md'), md)
        if not os.path.exists(os.path.join(thumbnail_dir, f'{e.slug}.png')):
            print(f'*** ALERT: no thumbnail found for example "{e.slug}"')

    example_items = [dict(slug=e.slug) for e in examples]
    example_items.insert(0, dict(slug='index'))
    example_items.insert(1, dict(slug='all'))
    write_file(os.path.join(website_dir, 'examples.js'), f'module.exports={json.dumps(example_items)}')
    write_file(os.path.join(example_md_dir, 'index.md'), make_gallery(examples))
    write_file(os.path.join(example_md_dir, 'all.md'), make_toc(examples))


if __name__ == '__main__':
    main()
Repository: h2oai/wave
File: ui/src/date_picker.tsx (TypeScript)

Code before:
    const
      defaultVal = m.value || null,
      parsedVal = defaultVal ? parseDate(defaultVal) : null,
      [value, setValue] = React.useState<Date | undefined>(parsedVal ? new Date(parsedVal) : undefined),
      onSelectDate = (d: Date | null | undefined) => {
        const val = (d === null || d === undefined) ? defaultVal : formatDate(d)
        wave.args[m.name] = val
        setValue(val ? new Date(val) : undefined)
        if (m.trigger) wave.push()
      }
    
    const parsedMin = m.min ? parseDate(m.min) : undefined
    const parsedMax = m.max ? parseDate(m.max) : undefined

    // eslint-disable-next-line react-hooks/exhaustive-deps
    React.useEffect(() => { wave.args[m.name] = defaultVal }, [])

    return (
      <Fluent.DatePicker
        data-test={m.name}
        label={m.label}
        value={value}
        placeholder={m.placeholder}
        disabled={m.disabled}
        onSelectDate={onSelectDate}
        minDate={parsedMin}
        maxDate={parsedMax}
      />
    )
  }

Review comment (suggestion):
```suggestion
        minDate={parseDate(m.min)}
```

same for max

Code after:
    const
      defaultVal = m.value || null,
      parsedVal = defaultVal ? parseDate(defaultVal) : null,
      [value, setValue] = React.useState<Date | undefined>(parsedVal ? new Date(parsedVal) : undefined),
      onSelectDate = (d: Date | null | undefined) => {
        const val = (d === null || d === undefined) ? defaultVal : formatDate(d)
        wave.args[m.name] = val
        setValue(val ? new Date(val) : undefined)
        if (m.trigger) wave.push()
      }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    React.useEffect(() => { wave.args[m.name] = defaultVal }, [])

    return (
      <Fluent.DatePicker
        data-test={m.name}
        label={m.label}
        value={value}
        placeholder={m.placeholder}
        disabled={m.disabled}
        onSelectDate={onSelectDate}
        minDate={parseDate(m.min || null)}
        maxDate={parseDate(m.max || null)}
      />
    )
  }
Repository: h2oai/wave
File: py/examples/tall_stats.py (Python)

Code before:
# Tall stat
# Create a card with stats laid out vertically 
# ---
from h2o_wave import main, app, Q, ui

@app('/demo')
async def serve(q: Q):
    # Modify the page

    q.page['example'] = ui.tall_stats_card(box='2 2 4 4', items=[
        ui.stat(label='PARAMETER NAME', value='125%'),
        ui.stat(label='PARAMETER NAME', value='578 Users'),
        ui.stat(label='PARAMETER NAME', value='25K')
    ])

    # Save the page
    await q.page.save()

Review comment (suggestion):
These comments are not needed.

```suggestion
    q.page['example'] = ui.tall_stats_card(box='2 2 4 4', items=[
        ui.stat(label='PARAMETER NAME', value='125%'),
        ui.stat(label='PARAMETER NAME', value='578 Users'),
        ui.stat(label='PARAMETER NAME', value='25K')
    ])
```

Code after:
# Tall stat
# Create a vertical label-value pairs collection.
# ---
from h2o_wave import site, ui

page = site['/demo']

page.add('example', ui.tall_stats_card(
    box='1 1 2 4',
    items=[
        ui.stat(label='PARAMETER NAME', value='125%'),
        ui.stat(label='PARAMETER NAME', value='578 Users'),
        ui.stat(label='PARAMETER NAME', value='25K')
    ]
))

page.save()
Repository: h2oai/wave
File: ui/src/tall_stats.test.tsx (TypeScript)

Code before:
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { render } from '@testing-library/react'
import * as T from 'h2o-wave'
import React from 'react'
import { View } from './tall_stats'

const
  title = 'tall_stats',
  stats = [
    { label: 'Label 1', value: 'value 1'},
    { label: 'Label 2', value: 'value 2'},
    { label: 'Label 3', value: 'value 3'},
  ],
  tallStatsProps: T.Model<any> = {
    name: title,
    state: {
      items: stats
    },
    changed: T.box(false)
  }

describe('TallStats.tsx', () => {

  it('Renders data-test attr', () => {
    const { queryByTestId } = render(<View {...tallStatsProps} />)
    expect(queryByTestId(title)).toBeInTheDocument()
  })

  it('Renders stats correctly', () => {
    const { queryByText } = render(<View {...tallStatsProps} />)
    stats.forEach(stat => {
      expect(queryByText(stat.label)).toBeInTheDocument()
      expect(queryByText(stat.value)).toBeInTheDocument()
    })
  })
})

Review comment (suggestion):
Not needed, we will implement visual snapshot testing in near future. Use unit tests only for business logic checks.
```suggestion
```

Code after:
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { render } from '@testing-library/react'
import * as T from 'h2o-wave'
import React from 'react'
import { View } from './tall_stats'

const
  name = 'tall_stats',
  tallStatsProps: T.Model<any> = {
    name,
    state: { items: [] },
    changed: T.box(false)
  }
  
describe('TallStats.tsx', () => {
    
  it('Renders data-test attr', () => {
    const { queryByTestId } = render(<View {...tallStatsProps} />)
    expect(queryByTestId(name)).toBeInTheDocument()
  })
})
Repository: h2oai/wave
File: ui/src/tall_stats.tsx (TypeScript)

Code before:
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Model } from 'h2o-wave'
import React from 'react'
import { Stat } from './stats'
import { cards } from './layout'
import { bond } from './ui'
import { stylesheet } from 'typestyle'
import { cssVar } from './theme'

/** Create a set of stats to be displayed vertically. */
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      textAlign: 'center',
      gap: 24,
      padding: 24,
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    
    const
      render = () => {
        const stats = state.items.map(({ label, value }, i) => (
          <div key={`${i}-${label}`}>
            {value && <div className='wave-s40 wave-w4' style={{color: cssVar('themePrimary')}}>{value}</div>}
            <div className='wave-s14 wave-w2' style={{color: cssVar('neutralPrimary'), marginTop: '-8px'}}>{label}</div>
          </div>)
        )
        return (
          <div data-test={name} className={css.card}>
            {stats}
          </div>
        )
      }
      return { render, changed }
  })

Review comment (suggestion):
text-align: center should be enough

```suggestion
```

Code after:
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Model } from 'h2o-wave'
import React from 'react'
import { Stat } from './stats'
import { cards } from './layout'
import { bond } from './ui'
import { stylesheet } from 'typestyle'
import { clas, cssVar } from './theme'

/** Create a vertical label-value pairs collection. */
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      textAlign: 'center',
      padding: 24,
      justifyContent: 'space-around',
    },
    value: {
      color: cssVar('$themePrimary'),
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => (
      <div data-test={name} className={css.card}>
        {
          state.items.map(({ label, value }, i) => (
            <div key={`${i}-${label}`}>
              {value && <div className={clas(css.value, 'wave-s40 wave-w4')}>{value}</div>}
              <div className='wave-s14 wave-w2'>{label}</div>
            </div>)
          )
        }
      </div>
    )

    return { render, changed }
  })
Repository: h2oai/wave
File: ui/src/tall_stats.tsx (TypeScript)

Code before:
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      textAlign: 'center',
      gap: 24,
      padding: 24,
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    
    const
      render = () => {
        const stats = state.items.map(({ label, value }, i) => (
          <div key={`${i}-${label}`}>
            {value && <div className='wave-s40 wave-w4' style={{color: cssVar('themePrimary')}}>{value}</div>}
            <div className='wave-s14 wave-w2' style={{color: cssVar('neutralPrimary'), marginTop: '-8px'}}>{label}</div>
          </div>)
        )
        return (
          <div data-test={name} className={css.card}>
            {stats}
          </div>
        )
      }
      return { render, changed }
  })

cards.register('tall_stats', View)

Review comment (refactor):
Use inline styles only for dynamic stuff, this can be extracted into separate CSS classes.

```suggestion
            {value && <div className={clas('wave-s40 wave-w4', css.value)>{value}</div>}
            <div className={clas('wave-s14 wave-w2', css.label)}>{label}</div>
```

Code after:
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      textAlign: 'center',
      padding: 24,
      justifyContent: 'space-around',
    },
    value: {
      color: cssVar('$themePrimary'),
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => (
      <div data-test={name} className={css.card}>
        {
          state.items.map(({ label, value }, i) => (
            <div key={`${i}-${label}`}>
              {value && <div className={clas(css.value, 'wave-s40 wave-w4')}>{value}</div>}
              <div className='wave-s14 wave-w2'>{label}</div>
            </div>)
          )
        }
      </div>
    )

    return { render, changed }
  })

cards.register('tall_stats', View)
Repository: h2oai/wave
File: ui/src/tall_stats.test.tsx (TypeScript)

Code before:
import { render } from '@testing-library/react'
import * as T from 'h2o-wave'
import React from 'react'
import { View } from './tall_stats'

const
  title = 'tall_stats',
  stats = [
    { label: 'Label 1', value: 'value 1'},
    { label: 'Label 2', value: 'value 2'},
    { label: 'Label 3', value: 'value 3'},
  ],
  tallStatsProps: T.Model<any> = {
    name: title,
    state: {
      items: stats
    },
    changed: T.box(false)
  }

describe('TallStats.tsx', () => {

  it('Renders data-test attr', () => {
    const { queryByTestId } = render(<View {...tallStatsProps} />)
    expect(queryByTestId(title)).toBeInTheDocument()
  })

  it('Renders stats correctly', () => {
    const { queryByText } = render(<View {...tallStatsProps} />)
    stats.forEach(stat => {
      expect(queryByText(stat.label)).toBeInTheDocument()
      expect(queryByText(stat.value)).toBeInTheDocument()
    })
  })
})

Review comment (suggestion):
```suggestion
  name = 'tall_stats',
  tallStatsProps: T.Model<any> = {
    name,
    state: { items: [] },
    changed: T.box(false)
  }

describe('TallStats.tsx', () => {

  it('Renders data-test attr', () => {
    const { queryByTestId } = render(<View {...tallStatsProps} />)
    expect(queryByTestId(name)).toBeInTheDocument()
  })
```

Code after:
// Copyright 2020 H2O.ai, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { render } from '@testing-library/react'
import * as T from 'h2o-wave'
import React from 'react'
import { View } from './tall_stats'

const
  name = 'tall_stats',
  tallStatsProps: T.Model<any> = {
    name,
    state: { items: [] },
    changed: T.box(false)
  }
  
describe('TallStats.tsx', () => {
    
  it('Renders data-test attr', () => {
    const { queryByTestId } = render(<View {...tallStatsProps} />)
    expect(queryByTestId(name)).toBeInTheDocument()
  })
})
Repository: h2oai/wave
File: ui/src/tall_stats.tsx (TypeScript)

Code before:
// Copyright 2020 H2O.ai, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Model } from 'h2o-wave'
import React from 'react'
import { Stat } from './stats'
import { cards } from './layout'
import { bond } from './ui'
import { stylesheet } from 'typestyle'
import { cssVar } from './theme'

/** Create a set of stats to be displayed vertically. */
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      textAlign: 'center',
      gap: 24,
      padding: 24,
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    
    const
      render = () => {
        const stats = state.items.map(({ label, value }, i) => (
          <div key={`${i}-${label}`}>
            {value && <div className='wave-s40 wave-w4' style={{color: cssVar('themePrimary')}}>{value}</div>}

Review comment (suggestion):
```suggestion
/** Create a vertical label-value pairs collection. */
```

Code after:
// Copyright 2020 H2O.ai, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Model } from 'h2o-wave'
import React from 'react'
import { Stat } from './stats'
import { cards } from './layout'
import { bond } from './ui'
import { stylesheet } from 'typestyle'
import { clas, cssVar } from './theme'

/** Create a vertical label-value pairs collection. */
export interface State {
  /** The individual stats to be displayed. */
  items: Stat[]
}

const
  css = stylesheet({
    card: {
      display: 'flex',
      flexDirection: 'column',
      textAlign: 'center',
      padding: 24,
      justifyContent: 'space-around',
    },
    value: {
      color: cssVar('$themePrimary'),
    },
  })

export const
  View = bond(({ name, state, changed }: Model<State>) => {
    const render = () => (
      <div data-test={name} className={css.card}>
        {
          state.items.map(({ label, value }, i) => (