|
| 1 | +import { HighTable, OrderBy, Selection } from 'hightable' |
| 2 | +import { useState } from 'react' |
| 3 | +import { data } from './data' |
| 4 | +import Layout from './Layout' |
| 5 | + |
| 6 | +function createRandomSelection(): Selection { |
| 7 | + const maxStep = 8 |
| 8 | + const maxLength = 5 |
| 9 | + const minRanges = 1 |
| 10 | + const maxRanges = 5 |
| 11 | + const numRanges = Math.floor(Math.random() * (maxRanges - minRanges + 1) + minRanges) |
| 12 | + const ranges = [] |
| 13 | + let start = 0 |
| 14 | + for (let i = 0; i < numRanges; i++) { |
| 15 | + const length = Math.floor(Math.random() * maxLength + 1) |
| 16 | + const step = Math.floor(Math.random() * maxStep + 1) |
| 17 | + start += step |
| 18 | + const end = start + length |
| 19 | + ranges.push({ start, end }) |
| 20 | + start = end |
| 21 | + } |
| 22 | + return { ranges } |
| 23 | +} |
| 24 | + |
| 25 | +function createRandomOrderBy(): OrderBy { |
| 26 | + const columns = data.header |
| 27 | + const column = columns[Math.floor(Math.random() * columns.length)] |
| 28 | + return { column } |
| 29 | +} |
| 30 | + |
| 31 | +function getNumSelected(selection: Selection): number { |
| 32 | + return selection.ranges.reduce((acc, range) => acc + (range.end - range.start), 0) |
| 33 | +} |
| 34 | + |
| 35 | +export default function Controlled() { |
| 36 | + const [selection, setSelection] = useState<Selection>({ ranges: [] }) |
| 37 | + const [orderBy, setOrderBy] = useState<OrderBy>({}) |
| 38 | + |
| 39 | + const numSelectedRows = getNumSelected(selection) |
| 40 | + |
| 41 | + return <Layout> |
| 42 | + <div>{/* <- to collapse margins */} |
| 43 | + <section> |
| 44 | + <button onClick={() => { setSelection(createRandomSelection()) }}>Set random selection</button> |
| 45 | + <button onClick={() => { setSelection({ ranges: [] }) }}>Clear selection</button> |
| 46 | + <span>{numSelectedRows.toLocaleString('en-US')} selected {numSelectedRows === 1 ? 'row' : 'rows'}</span> |
| 47 | + </section> |
| 48 | + <section> |
| 49 | + <button onClick={() => { setOrderBy(createRandomOrderBy()) }}>Order by a random column</button> |
| 50 | + <button onClick={() => { setOrderBy({}) }}>Clear order</button> |
| 51 | + <span>{orderBy.column ? `Ordered by '${orderBy.column}'` : 'Unordered'}</span> |
| 52 | + </section> |
| 53 | + </div> |
| 54 | + <HighTable data={data} selection={selection} onSelectionChange={setSelection} orderBy={orderBy} onOrderByChange={setOrderBy} /> |
| 55 | + </Layout> |
| 56 | +} |
0 commit comments