├── .gitignore
├── README.md
├── package.json
├── packages
├── site
│ ├── .eslintrc
│ ├── package.json
│ └── src
│ │ ├── components
│ │ ├── Combobox.js
│ │ ├── Grid.js
│ │ ├── LazyOption.js
│ │ ├── MegaNav.js
│ │ ├── Select.js
│ │ └── data.js
│ │ └── pages
│ │ ├── index.js
│ │ └── select.js
├── three
│ ├── .env
│ ├── .gitignore
│ ├── README.md
│ ├── package.json
│ └── src
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── logo.svg
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
└── use-item-list
│ ├── .gitignore
│ ├── LICENSE
│ ├── package.json
│ ├── src
│ ├── index.ts
│ └── utils.ts
│ ├── tsconfig.json
│ └── yarn.lock
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # Mac files
2 | .DS_Store
3 |
4 | # NPM
5 | .npm
6 | node_modules
7 |
8 | # Yarn
9 | .yarn-integrity
10 | yarn-debug.log*
11 | yarn-error.log*
12 |
13 | # ESLint
14 | .eslintcache
15 |
16 | # NextJS
17 | .next
18 | out
19 |
20 | # General
21 | *.log
22 | coverage
23 | dist
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🕹 useItemList
2 |
3 | A primitive React hook used to coordinate indexed collections effortlessly.
4 |
5 | ## Why?
6 |
7 | The ergonmics of managing indexes in React is lacking. When building lower level components for accessibility purposes, managing indexes can become painful and expose internals of an API that consumers shouldn't necessarily need to know about.
8 |
9 | This library aims to solve managing indexed collections of items as easily as possible while letting users still compose, optimize, and use React like they are used to.
10 |
11 | ## API
12 |
13 | ```jsx
14 | import React, { useRef } from 'react'
15 | import { useItemList } from 'use-item-list'
16 |
17 | function Item({ useItem, children }) {
18 | const ref = useRef()
19 | const { id, index, highlight, select, selected, useHighlighted } = useItem({
20 | ref, // required ref used to scroll item into view when highlighted
21 | value: children, // value passed back in useItemList onSelect
22 | disabled: false, // prevents item from being highlighted/selected
23 | text: null, // used for highlightItemByString function
24 | })
25 | return (
26 |
27 | {children}
28 |
29 | )
30 | }
31 |
32 | function List({ value, onChange }) {
33 | const {
34 | controllerId,
35 | listId,
36 | getHighlightedIndex,
37 | getHighlightedItem,
38 | setHighlightedItem,
39 | moveHighlightedItem,
40 | clearHighlightedItem,
41 | selectHighlightedItem,
42 | useHighlightedItemId,
43 | highlightItemByString,
44 | useItem,
45 | } = useItemList({
46 | selected: value, // the current selected value
47 | onSelect: onChange, // callback when item has been selected
48 | })
49 | return (
50 |
51 | - Item 1
52 | - Item 2
53 | - Item 3
54 |
55 | )
56 | }
57 | ```
58 |
59 | ## Usage
60 |
61 | In a somewhat trivial example, we can see how to build a custom select menu:
62 |
63 | ```jsx
64 | import React, { createContext, useContext, useRef } from 'react'
65 | import { useItemList } from 'use-item-list'
66 |
67 | const SelectContext = createContext()
68 |
69 | export function Select({ children, value, onChange }) {
70 | const itemList = useItemList({
71 | selected: value,
72 | onSelect: onChange,
73 | })
74 | const itemId = itemList.useHighlightedItemId()
75 | return (
76 |
77 | {
84 | if (event.key === 'ArrowUp') {
85 | event.preventDefault()
86 | itemList.moveHighlightedItem(-1)
87 | }
88 | if (event.key === 'ArrowDown') {
89 | event.preventDefault()
90 | itemList.moveHighlightedItem(1)
91 | }
92 | if (event.key === ' ' || event.key === 'Enter') {
93 | event.preventDefault()
94 | itemList.selectHighlightedItem()
95 | }
96 | itemList.highlightItemByString(event)
97 | }}
98 | >
99 | {children}
100 |
101 |
102 | )
103 | }
104 |
105 | export function Option({ children, text, value }) {
106 | const { useItem, clearHighlightedItem } = useContext(SelectContext)
107 | const ref = useRef()
108 | const { id, highlight, select, selected, useHighlighted } = useItem({
109 | ref,
110 | text,
111 | value,
112 | })
113 | const highlighted = useHighlighted()
114 | return (
115 |
124 | {children} {selected && '✅'}
125 |
126 | )
127 | }
128 | ```
129 |
130 | Now users of our component have an easy-to-use API that resembles the ergonomics of the web's select element:
131 |
132 | ```jsx
133 |
138 | ```
139 |
140 | Please note this is not a fully accessible example. See the examples directory for more full-fledged examples.
141 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "scripts": {
4 | "three": "yarn workspace three",
5 | "site": "yarn workspace site",
6 | "use-item-list": "yarn workspace use-item-list"
7 | },
8 | "workspaces": [
9 | "packages/*"
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/packages/site/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "parser": "babel-eslint",
3 | "extends": ["react-app", "plugin:jsx-a11y/recommended"],
4 | "plugins": ["react-hooks", "jsx-a11y"],
5 | "rules": {
6 | "semi": 0,
7 | "react-hooks/rules-of-hooks": "error",
8 | "react-hooks/exhaustive-deps": "warn"
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/packages/site/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "name": "site",
4 | "version": "0.0.0",
5 | "license": "UNLICENSED",
6 | "scripts": {
7 | "dev": "next dev",
8 | "build": "next build && next export"
9 | },
10 | "dependencies": {
11 | "calendarize": "^1.1.1",
12 | "faker": "^5.5.3",
13 | "next": "12.0.2",
14 | "lodash": "^4.17.21",
15 | "moment": "^2.29.1",
16 | "react": "^17.0.2",
17 | "react-dom": "^17.0.2",
18 | "use-item-list": "*"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/packages/site/src/components/Combobox.js:
--------------------------------------------------------------------------------
1 | import React, {
2 | createContext,
3 | useContext,
4 | useEffect,
5 | useRef,
6 | useState,
7 | } from 'react'
8 | import { useItemList } from 'use-item-list'
9 |
10 | import data from './data'
11 |
12 | // https://www.w3.org/TR/wai-aria-practices-1.1/examples/combobox/aria1.1pattern/listbox-combo.html
13 |
14 | const ComboboxContext = createContext(null)
15 |
16 | function Combobox({ children, onSelect }) {
17 | const itemList = useItemList({ onSelect })
18 | return (
19 |
20 | {children}
21 |
22 | )
23 | }
24 |
25 | function Input({ autoComplete, autoSelect, value, onChange }) {
26 | const {
27 | controllerId,
28 | listId,
29 | moveHighlightedItem,
30 | setHighlightedItem,
31 | selectHighlightedItem,
32 | useHighlightedItemId,
33 | } = useContext(ComboboxContext)
34 | const itemId = useHighlightedItemId()
35 | useEffect(() => {
36 | setHighlightedItem(0)
37 | }, [value])
38 | return (
39 | {
47 | if (event.key === 'ArrowUp') {
48 | event.preventDefault()
49 | moveHighlightedItem(-1)
50 | } else if (event.key === 'ArrowDown') {
51 | event.preventDefault()
52 | moveHighlightedItem(1)
53 | } else if (event.key === 'Enter') {
54 | selectHighlightedItem()
55 | }
56 | }}
57 | />
58 | )
59 | }
60 |
61 | function List({ children }) {
62 | const { listId, controllerId } = useContext(ComboboxContext)
63 | return (
64 |
77 | )
78 | }
79 |
80 | function Option({ children, value }) {
81 | const ref = useRef()
82 | const { useItem, clearHighlightedItem } = useContext(ComboboxContext)
83 | const { id, index, highlight, select, useHighlighted } = useItem({
84 | ref,
85 | value,
86 | })
87 | const highlighted = useHighlighted()
88 | return (
89 |
103 | {index} {children}
104 |
105 | )
106 | }
107 |
108 | export function Demo() {
109 | const [inputValue, setInputValue] = useState('')
110 | const filteredData = data.filter(
111 | (item) =>
112 | !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase())
113 | )
114 | return (
115 | setInputValue(item.value.name)}>
116 |
117 | setInputValue(event.target.value)}
120 | />
121 |
122 | {filteredData.length > 0
123 | ? filteredData.map((item) => (
124 |
127 | ))
128 | : 'No results found'}
129 |
130 |
131 |
132 | )
133 | }
134 |
--------------------------------------------------------------------------------
/packages/site/src/components/Grid.js:
--------------------------------------------------------------------------------
1 | import React, { createContext, useContext, useRef } from 'react'
2 | import calendarize from 'calendarize'
3 | import { useItemList } from 'use-item-list'
4 |
5 | const GridContext = createContext(null)
6 |
7 | const DAYS_IN_WEEK = 7
8 | const CELL_SIZE = 48
9 |
10 | function Grid({ children, initialHighlightedIndex }) {
11 | const itemList = useItemList({
12 | initialHighlightedIndex,
13 | })
14 | return (
15 | {
18 | console.log(itemList.items, itemList.getHighlightedIndex())
19 | const highlightedIndex = itemList.getHighlightedIndex()
20 | if (event.key === 'ArrowLeft') {
21 | event.preventDefault()
22 | itemList.setHighlightedItem(highlightedIndex - 1)
23 | } else if (event.key === 'ArrowRight') {
24 | event.preventDefault()
25 | itemList.setHighlightedItem(highlightedIndex + 1)
26 | } else if (event.key === 'ArrowUp') {
27 | event.preventDefault()
28 | itemList.setHighlightedItem(highlightedIndex - DAYS_IN_WEEK)
29 | } else if (event.key === 'ArrowDown') {
30 | event.preventDefault()
31 | itemList.setHighlightedItem(highlightedIndex + DAYS_IN_WEEK)
32 | } else if (event.key === 'Enter') {
33 | itemList.selectHighlightedItem()
34 | }
35 | }}
36 | style={{
37 | display: 'grid',
38 | gridTemplateColumns: `repeat(7, ${CELL_SIZE}px)`,
39 | gridAutoRows: CELL_SIZE,
40 | width: CELL_SIZE * DAYS_IN_WEEK,
41 | }}
42 | >
43 | {children}
44 |
45 | )
46 | }
47 |
48 | function GridCell({ children }) {
49 | const ref = useRef(null)
50 | const { useItem } = useContext(GridContext)
51 | const { useHighlighted } = useItem({
52 | ref,
53 | value: children,
54 | })
55 | const highlighted = useHighlighted()
56 | return (
57 |
66 | {children}
67 |
68 | )
69 | }
70 |
71 | const MONTH_NAMES = [
72 | 'January',
73 | 'February',
74 | 'March',
75 | 'April',
76 | 'May',
77 | 'June',
78 | 'July',
79 | 'August',
80 | 'September',
81 | 'October',
82 | 'November',
83 | 'December',
84 | ]
85 | const WEEK_NAMES = [
86 | 'Sunday',
87 | 'Monday',
88 | 'Tuesday',
89 | 'Wednesday',
90 | 'Thursday',
91 | 'Friday',
92 | 'Saturday',
93 | ]
94 | const TODAY = new Date()
95 | const MONTH = MONTH_NAMES[TODAY.getMonth()]
96 |
97 | export function Demo() {
98 | const currentMonth = calendarize()
99 | return (
100 |
101 |
{MONTH}
102 |
108 | {WEEK_NAMES.map((day) => (
109 |
117 | {day.slice(0, 3)}
118 |
119 | ))}
120 |
121 |
124 | {currentMonth.map((week) =>
125 | week
126 | .filter((day) => day !== 0)
127 | .map((day) => {day})
128 | )}
129 |
130 |
131 | )
132 | }
133 |
--------------------------------------------------------------------------------
/packages/site/src/components/LazyOption.js:
--------------------------------------------------------------------------------
1 | import React, { memo, useMemo } from 'react'
2 | import moment from 'moment'
3 | import * as lodash from 'lodash'
4 |
5 | import { Option } from './Select'
6 |
7 | function MemoOption({ value }) {
8 | return useMemo(() => , [])
9 | }
10 |
11 | export default memo(
12 | function LazyOption() {
13 | const time = moment().format('h:mm:ss a')
14 | const value = `${lodash.add(40, 2)}@${time}`
15 | return
16 | },
17 | () => true
18 | )
19 |
--------------------------------------------------------------------------------
/packages/site/src/components/MegaNav.js:
--------------------------------------------------------------------------------
1 | import React, { createContext, useContext, useRef, useState } from 'react'
2 | import { useItemList } from 'use-item-list'
3 |
4 | const MenuGroupContext = createContext(null)
5 | const MenuItemContext = createContext(null)
6 |
7 | function MenuItem({ children }) {
8 | const ref = useRef()
9 | const { useItem, clearHighlightedItem } = useContext(MenuItemContext)
10 | const { id, highlight, select, useHighlighted } = useItem({
11 | ref,
12 | value: children,
13 | })
14 | const highlighted = useHighlighted()
15 | return (
16 |
30 | {children}
31 |
32 | )
33 | }
34 |
35 | function MenuSubGroup({ title, children }) {
36 | const menuGroup = useContext(MenuGroupContext)
37 | const menuItem = useItemList({
38 | initialHighlightedIndex: null,
39 | onSelect: (item) => console.log(item),
40 | })
41 | menuGroup.useItem({ value: menuItem })
42 | return (
43 |
44 |
45 | {title}
46 |
54 |
55 |
56 | )
57 | }
58 |
59 | function MenuGroup({ title, children }) {
60 | const [menuOpen, setMenuOpen] = useState(false)
61 | const menuGroup = useItemList()
62 | return (
63 |
64 | {
67 | if (event.key === 'ArrowLeft') {
68 | event.preventDefault()
69 | const item = menuGroup.getHighlightedItem()
70 | if (item) {
71 | const highlightedIndex = item.value.getHighlightedIndex()
72 | if (highlightedIndex === null) {
73 | item.value.setHighlightedItem(0)
74 | } else {
75 | menuGroup.moveHighlightedItem(-1)
76 | const nextItem = menuGroup.getHighlightedItem()
77 | if (nextItem) {
78 | item.value.clearHighlightedItem()
79 | nextItem.value.setHighlightedItem(0)
80 | }
81 | }
82 | }
83 | }
84 | if (event.key === 'ArrowRight') {
85 | event.preventDefault()
86 | const item = menuGroup.getHighlightedItem()
87 | if (item) {
88 | const highlightedIndex = item.value.getHighlightedIndex()
89 | if (highlightedIndex === null) {
90 | item.value.setHighlightedItem(0)
91 | } else {
92 | menuGroup.moveHighlightedItem(1)
93 | const nextItem = menuGroup.getHighlightedItem()
94 | if (nextItem) {
95 | item.value.clearHighlightedItem()
96 | nextItem.value.setHighlightedItem(0)
97 | }
98 | }
99 | }
100 | }
101 | if (event.key === 'ArrowUp') {
102 | const item = menuGroup.getHighlightedItem()
103 | if (item) {
104 | const highlightedIndex = item.value.getHighlightedIndex()
105 | if (highlightedIndex === null) {
106 | item.value.setHighlightedItem(0)
107 | } else if (highlightedIndex === 0) {
108 | menuGroup.moveHighlightedItem(-1)
109 | const nextItem = menuGroup.getHighlightedItem()
110 | if (nextItem) {
111 | item.value.clearHighlightedItem()
112 | nextItem.value.moveHighlightedItem(-1)
113 | }
114 | } else {
115 | item.value.moveHighlightedItem(-1)
116 | }
117 | }
118 | }
119 | if (event.key === 'ArrowDown') {
120 | const item = menuGroup.getHighlightedItem()
121 | if (item) {
122 | const lastIndex = item.value.items.current.length - 1
123 | const highlightedIndex = item.value.getHighlightedIndex()
124 | if (highlightedIndex === null) {
125 | item.value.setHighlightedItem(0)
126 | } else if (highlightedIndex === lastIndex) {
127 | menuGroup.moveHighlightedItem(1)
128 | const nextItem = menuGroup.getHighlightedItem()
129 | if (nextItem) {
130 | item.value.clearHighlightedItem()
131 | nextItem.value.moveHighlightedItem(1)
132 | }
133 | } else {
134 | item.value.moveHighlightedItem(1)
135 | }
136 | }
137 | }
138 | }}
139 | onMouseEnter={(event) => {
140 | setMenuOpen(true)
141 | event.target.focus()
142 | }}
143 | onMouseLeave={(event) => {
144 | setMenuOpen(false)
145 | event.target.blur()
146 | }}
147 | onFocus={() => setMenuOpen(true)}
148 | onBlur={() => {
149 | setMenuOpen(false)
150 | menuGroup.setHighlightedItem(0)
151 | const item = menuGroup.getHighlightedItem()
152 | if (item) {
153 | item.value.setHighlightedItem(0)
154 | }
155 | }}
156 | style={{
157 | padding: 8,
158 | color: menuOpen && 'coral',
159 | }}
160 | >
161 | {title}
162 | {menuOpen && (
163 |
181 | )}
182 |
183 |
184 | )
185 | }
186 |
187 | function Menu({ children }) {
188 | return (
189 |
203 | )
204 | }
205 |
206 | const foodGroups = {
207 | Fruits: {
208 | Citrus: ['Oranges', 'Grapefruits', 'Mandarins', 'Limes'],
209 | Stone: ['Nectarines', 'Apricots', 'Peaches', 'Plums'],
210 | Tropical: ['Bananas', 'Mangoes'],
211 | Berries: ['Strawberries', 'Raspberries', 'Blueberries', 'Kiwis'],
212 | Melons: ['Watermelons', 'Rockmelons', 'Honeydew'],
213 | Miscellaneous: ['Apples', 'Pears', 'Tomatoes', 'Avocados'],
214 | },
215 | Vegetables: {
216 | Leafy: ['Lettuce', 'Spinach', 'Silverbeet'],
217 | Cruciferous: ['Cabbage', 'Cauliflower', 'Brussels Sprout', 'Broccoli'],
218 | Marrow: ['Pumpkin', 'Cucumber', 'Zucchini'],
219 | Root: ['Potato', 'Sweet Potato'],
220 | Stem: ['Celery', 'Asparagus'],
221 | Allium: ['Onion', 'Garlic', 'Shallot'],
222 | },
223 | Meats: {
224 | 'Red Meat': ['Beef', 'Goat', 'Lamb'],
225 | Poultry: ['Chicken', 'Turkey'],
226 | Pork: [`Pig's meat`],
227 | Seafood: ['Fish', 'Crab', 'Lobster'],
228 | },
229 | }
230 |
231 | export function Demo() {
232 | return (
233 |
246 | )
247 | }
248 |
--------------------------------------------------------------------------------
/packages/site/src/components/Select.js:
--------------------------------------------------------------------------------
1 | import React, {
2 | Suspense,
3 | lazy,
4 | createContext,
5 | useContext,
6 | useRef,
7 | useState,
8 | } from 'react'
9 | import { useItemList } from 'use-item-list'
10 |
11 | const SelectContext = createContext(null)
12 |
13 | export function Select({ children, value, onChange }) {
14 | const itemList = useItemList({
15 | selected: value,
16 | onSelect: (item) => onChange(item.value),
17 | })
18 | const itemId = itemList.useHighlightedItemId()
19 | return (
20 |
21 | {
28 | if (event.key === 'ArrowUp') {
29 | event.preventDefault()
30 | itemList.moveHighlightedItem(-1)
31 | }
32 | if (event.key === 'ArrowDown') {
33 | event.preventDefault()
34 | itemList.moveHighlightedItem(1)
35 | }
36 | if (event.key === ' ' || event.key === 'Enter') {
37 | event.preventDefault()
38 | itemList.selectHighlightedItem()
39 | }
40 | itemList.highlightItemByString(event)
41 | }}
42 | >
43 | {children}
44 |
45 |
46 | )
47 | }
48 |
49 | export function Option({ children, text, value, disabled }) {
50 | const { useItem, clearHighlightedItem } = useContext(SelectContext)
51 | const ref = useRef()
52 | const { id, index, highlight, select, selected, useHighlighted } = useItem({
53 | ref,
54 | text,
55 | value,
56 | disabled,
57 | })
58 | const highlighted = useHighlighted()
59 | return (
60 |
77 | {index} {children} {selected && '✅'}
78 |
79 | )
80 | }
81 |
82 | const LazyOption = lazy(() => import('../components/LazyOption'))
83 | const assortedFruits = ['Apple', 'Orange', 'Pear', 'Kiwi', 'Banana', 'Mango']
84 | const staticObjectValue = { foo: 'bar' }
85 |
86 | export function Demo() {
87 | const [fruits, setFruits] = useState(assortedFruits.slice(1, 4))
88 | const [selectedFruits, setSelectedFruits] = useState([])
89 | return (
90 |
91 |
92 |
130 |
131 | )
132 | }
133 |
--------------------------------------------------------------------------------
/packages/site/src/components/data.js:
--------------------------------------------------------------------------------
1 | import faker from 'faker'
2 |
3 | function generateFakeData(callback, size = 10) {
4 | const data = []
5 | for (let i = 0; i < size; i++) {
6 | data.push(callback(faker))
7 | }
8 | return data
9 | }
10 |
11 | export default generateFakeData(faker => ({
12 | id: faker.random.uuid(),
13 | avatar: faker.image.avatar(),
14 | name: `${faker.name.firstName()} ${faker.name.lastName()}`,
15 | phoneNumber: faker.phone.phoneNumber(),
16 | email: faker.internet.email(),
17 | }))
18 |
--------------------------------------------------------------------------------
/packages/site/src/pages/index.js:
--------------------------------------------------------------------------------
1 | import React, { Fragment, StrictMode, useState } from 'react'
2 |
3 | import { Demo as ComboboxDemo } from '../components/Combobox'
4 | import { Demo as GridDemo } from '../components/Grid'
5 | import { Demo as MegaNavDemo } from '../components/MegaNav'
6 | import { Demo as SelectDemo } from '../components/Select'
7 |
8 | function App() {
9 | const [strict, setStrict] = useState(false)
10 | const Wrapper = strict ? StrictMode : Fragment
11 | return (
12 |
13 |
21 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | )
39 | }
40 |
41 | export default App
42 |
--------------------------------------------------------------------------------
/packages/site/src/pages/select.js:
--------------------------------------------------------------------------------
1 | import React, { createContext, useContext, useRef, useState } from 'react'
2 | import { useItemList } from 'use-item-list'
3 |
4 | const SelectContext = createContext(null)
5 |
6 | function Select({ children, value, onChange }) {
7 | const itemList = useItemList({
8 | selected: value,
9 | onSelect: (item) => onChange(item.value),
10 | })
11 | const itemId = itemList.useHighlightedItemId()
12 | return (
13 |
14 | {
21 | if (event.key === 'ArrowUp') {
22 | event.preventDefault()
23 | itemList.moveHighlightedItem(-1)
24 | }
25 | if (event.key === 'ArrowDown') {
26 | event.preventDefault()
27 | itemList.moveHighlightedItem(1)
28 | }
29 | if (event.key === ' ' || event.key === 'Enter') {
30 | event.preventDefault()
31 | itemList.selectHighlightedItem()
32 | }
33 | itemList.highlightItemByString(event)
34 | }}
35 | >
36 | {children}
37 |
38 |
39 | )
40 | }
41 |
42 | function Option({ children, text = null, value, disabled = false }) {
43 | const { useItem, clearHighlightedItem } = useContext(SelectContext)
44 | const ref = useRef()
45 | const { id, highlight, select, selected, useHighlighted } = useItem({
46 | ref,
47 | text,
48 | value,
49 | disabled,
50 | })
51 | const highlighted = useHighlighted()
52 | return (
53 |
72 | {children} {selected && '✅'}
73 |
74 | )
75 | }
76 |
77 | const range = (size) => {
78 | const numbers = []
79 | for (let i = 0; i < size; i++) {
80 | numbers.push(i)
81 | }
82 | return numbers
83 | }
84 |
85 | const items = range(10)
86 |
87 | export default function App() {
88 | const [selectedFruits, setSelectedFruits] = useState([])
89 | return (
90 |
91 |
112 |
113 | )
114 | }
115 |
--------------------------------------------------------------------------------
/packages/three/.env:
--------------------------------------------------------------------------------
1 | SKIP_PREFLIGHT_CHECK=true
--------------------------------------------------------------------------------
/packages/three/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/packages/three/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `yarn start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.\
15 | You will also see any lint errors in the console.
16 |
17 | ### `yarn test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `yarn build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `yarn eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35 |
36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39 |
40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `yarn build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/packages/three/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "three",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@react-three/a11y": "^2.2.3",
7 | "@testing-library/jest-dom": "^5.14.1",
8 | "@testing-library/react": "^12.1.2",
9 | "@testing-library/user-event": "^13.5.0",
10 | "react": "^17.0.2",
11 | "react-dom": "^17.0.2",
12 | "react-scripts": "4.0.3",
13 | "react-three-fiber": "^6.0.13",
14 | "three": "^0.134.0",
15 | "use-item-list": "*",
16 | "web-vitals": "^2.1.2"
17 | },
18 | "scripts": {
19 | "start": "react-scripts start",
20 | "build": "react-scripts build",
21 | "test": "react-scripts test",
22 | "eject": "react-scripts eject"
23 | },
24 | "eslintConfig": {
25 | "extends": [
26 | "react-app",
27 | "react-app/jest"
28 | ]
29 | },
30 | "browserslist": {
31 | "production": [
32 | ">0.2%",
33 | "not dead",
34 | "not op_mini all"
35 | ],
36 | "development": [
37 | "last 1 chrome version",
38 | "last 1 firefox version",
39 | "last 1 safari version"
40 | ]
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/packages/three/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/packages/three/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Canvas, useFrame } from 'react-three-fiber'
3 | import { A11yAnnouncer, A11y, useA11y } from '@react-three/a11y'
4 | import { useItemList } from 'use-item-list'
5 |
6 | const ItemListContext = React.createContext(null)
7 |
8 | function InnerBox({ innerRef, item, ...props }) {
9 | const ally = useA11y()
10 | const itemList = React.useContext(ItemListContext)
11 | const highlighted = item.useHighlighted()
12 |
13 | // ideally we'd use a pooled listener
14 | React.useEffect(() => {
15 | function handlKeyDown(event) {
16 | if (ally.focus) {
17 | if (event.key === 'ArrowLeft') {
18 | event.preventDefault()
19 | itemList.moveHighlightedItem(-1)
20 | }
21 | if (event.key === 'ArrowRight') {
22 | event.preventDefault()
23 | itemList.moveHighlightedItem(1)
24 | }
25 | if (event.key === ' ' || event.key === 'Enter') {
26 | event.preventDefault()
27 | itemList.selectHighlightedItem()
28 | }
29 | itemList.highlightItemByString(event)
30 | }
31 | }
32 | document.addEventListener('keydown', handlKeyDown)
33 | return () => {
34 | document.removeEventListener('keydown', handlKeyDown)
35 | }
36 | }, [ally.focus])
37 |
38 | return (
39 |
44 |
45 |
46 |
47 | )
48 | }
49 |
50 | function Box({ value, ...props }) {
51 | const itemList = React.useContext(ItemListContext)
52 | const ref = React.useRef()
53 | const item = itemList.useItem({ ref, value })
54 |
55 | useFrame(() => {
56 | ref.current.rotation.x = ref.current.rotation.y += 0.01
57 | })
58 |
59 | return (
60 | item.select()}
63 | focusCall={() => item.highlight()}
64 | >
65 |
66 |
67 | )
68 | }
69 |
70 | function Page() {
71 | const [selected, setSelected] = React.useState([])
72 | const itemList = useItemList({
73 | selected: (value) => selected.includes(value),
74 | onSelect: ({ value }) => {
75 | setSelected((currentSelected) => {
76 | const nextSelected = [...currentSelected]
77 | const index = currentSelected.indexOf(value)
78 | if (index > -1) {
79 | nextSelected.splice(index, 1)
80 | } else {
81 | nextSelected.push(value)
82 | }
83 | return nextSelected
84 | })
85 | },
86 | })
87 | return (
88 | <>
89 |
98 |
99 | >
100 | )
101 | }
102 |
103 | export default Page
104 |
--------------------------------------------------------------------------------
/packages/three/src/App.test.js:
--------------------------------------------------------------------------------
1 | import { render, screen } from '@testing-library/react';
2 | import App from './App';
3 |
4 | test('renders learn react link', () => {
5 | render();
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
9 |
--------------------------------------------------------------------------------
/packages/three/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 | code {
10 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
11 | monospace;
12 | }
13 | #root {
14 | position: fixed;
15 | top: 0;
16 | left: 0;
17 | height: 100vh;
18 | width: 100%;
19 | background: #f0f0f0;
20 | transition: background 0.25s ease-in-out;
21 | }
22 |
--------------------------------------------------------------------------------
/packages/three/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import reportWebVitals from './reportWebVitals';
6 |
7 | ReactDOM.render(
8 |
9 |
10 | ,
11 | document.getElementById('root')
12 | );
13 |
14 | // If you want to start measuring performance in your app, pass a function
15 | // to log results (for example: reportWebVitals(console.log))
16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
17 | reportWebVitals();
18 |
--------------------------------------------------------------------------------
/packages/three/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/packages/three/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/packages/three/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/packages/use-item-list/.gitignore:
--------------------------------------------------------------------------------
1 | *.log
2 | .DS_Store
3 | node_modules
4 | .cache
5 | dist
6 |
--------------------------------------------------------------------------------
/packages/use-item-list/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Travis Arnold
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/packages/use-item-list/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "use-item-list",
3 | "version": "0.1.2",
4 | "author": "Travis Arnold",
5 | "description": "Manage indexed collections in React using hooks.",
6 | "license": "MIT",
7 | "repository": {
8 | "type": "git",
9 | "url": "git+https://github.com/souporserious/use-item-list.git"
10 | },
11 | "module": "dist/use-item-list.esm.js",
12 | "main": "dist/index.js",
13 | "typings": "dist/index.d.ts",
14 | "files": [
15 | "dist"
16 | ],
17 | "keywords": [
18 | "react",
19 | "indexed",
20 | "collection",
21 | "lists",
22 | "accessibility",
23 | "aria",
24 | "activedescendant"
25 | ],
26 | "scripts": {
27 | "develop": "tsdx watch",
28 | "build": "tsdx build",
29 | "test": "tsdx test --passWithNoTests",
30 | "lint": "tsdx lint",
31 | "prepare": "tsdx build"
32 | },
33 | "peerDependencies": {
34 | "react": ">=16.8"
35 | },
36 | "devDependencies": {
37 | "@types/jest": "^27.0.2",
38 | "@types/react": "^17.0.33",
39 | "@types/react-dom": "^17.0.10",
40 | "husky": "^7.0.4",
41 | "react": "^17.0.2",
42 | "react-dom": "^17.0.2",
43 | "tsdx": "^0.14.1",
44 | "tslib": "^2.3.1",
45 | "typescript": "^4.4.4"
46 | },
47 | "husky": {
48 | "hooks": {
49 | "pre-commit": "tsdx lint"
50 | }
51 | },
52 | "prettier": {
53 | "printWidth": 80,
54 | "semi": false,
55 | "singleQuote": true,
56 | "trailingComma": "es5"
57 | },
58 | "dependencies": {
59 | "mitt": "^3.0.0",
60 | "use-constant": "^1.1.0"
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/packages/use-item-list/src/index.ts:
--------------------------------------------------------------------------------
1 | import {
2 | useEffect,
3 | useCallback,
4 | useRef,
5 | useLayoutEffect,
6 | useState,
7 | } from 'react'
8 | import useConstant from 'use-constant'
9 | import mitt from 'mitt'
10 |
11 | import { scrollIntoView } from './utils'
12 |
13 | const isServer = typeof window !== 'undefined'
14 | const useIsomorphicEffect = isServer ? useEffect : useLayoutEffect
15 |
16 | function isNumberKey(event) {
17 | return event.keyCode >= 48 && event.keyCode <= 57
18 | }
19 |
20 | function isLetterKey(event) {
21 | return event.keyCode >= 65 && event.keyCode <= 90
22 | }
23 |
24 | function isSpecialKey(event) {
25 | return event.keyCode >= 188 && event.keyCode <= 190
26 | }
27 |
28 | function isComboKey(event) {
29 | return event.ctrlKey || event.metaKey || event.altKey
30 | }
31 |
32 | function modulo(val, max) {
33 | return val >= 0 ? val % max : ((val % max) + max) % max
34 | }
35 |
36 | function useForceUpdate() {
37 | const [, forceUpdate] = useState()
38 | return useCallback(() => forceUpdate(Object.create(null)), [])
39 | }
40 |
41 | let localId = 0
42 |
43 | export type ItemOptions = {
44 | /** Used to scroll item into view when highlighted. */
45 | ref
46 |
47 | /** Value passed back in useItemList onSelect. */
48 | value: any
49 |
50 | /** Prevents item from being highlighted/selected */
51 | disabled?: boolean
52 |
53 | /** Used for highlightItemByString function */
54 | text?: string
55 | }
56 |
57 | export type ItemListOptions = {
58 | /** Unique identifier for item list. */
59 | id?: number | string
60 |
61 | /** Highlighted index on initial render. */
62 | initialHighlightedIndex?: number
63 |
64 | /** Callback when an item has been highlighted. */
65 | onHighlight?: (item: any, index: number) => void
66 |
67 | /** Callback when an item has been selected. */
68 | onSelect?: (item: any, index: number) => void
69 |
70 | /** Controls the currently selected items. */
71 | selected?: (itemValue: any) => boolean | string
72 | }
73 |
74 | export function useItemList({
75 | id = localId++,
76 | initialHighlightedIndex = 0,
77 | onHighlight,
78 | onSelect,
79 | selected = null,
80 | }: ItemListOptions = {}) {
81 | const controllerId = useRef('controller-' + id)
82 | const listId = useRef('list-' + id)
83 | const getItemId = index => listId.current + `-item-${index}`
84 | const itemListEmitter = useConstant(() => mitt())
85 | const itemListForceUpdate = useForceUpdate()
86 | const highlightedIndex = useRef(initialHighlightedIndex)
87 | const items = useRef([])
88 | const nextItems = useRef([])
89 | const shouldCollectItems = useRef(true)
90 | const invalidatedItems = useRef(false)
91 | const storeItem = useCallback(({ ref, text, value, disabled }) => {
92 | let itemIndex = nextItems.current.findIndex(item => item.value === value)
93 |
94 | // First, we check if the incoming ref is new and
95 | // determine if the parent has set shouldCollectRefs or not.
96 | // If it hasn't, we need to refetch refs by their tree order
97 | if (
98 | itemIndex === -1 &&
99 | nextItems.current.length > 0 &&
100 | shouldCollectItems.current === false
101 | ) {
102 | // stop collecting refs and start over in forced parent render
103 | // since the collection has been invalidated
104 | invalidatedItems.current = true
105 | } else if (itemIndex === -1) {
106 | itemIndex = nextItems.current.length
107 | nextItems.current.push({
108 | id: getItemId(itemIndex),
109 | ref,
110 | text,
111 | value,
112 | disabled,
113 | })
114 | }
115 |
116 | return itemIndex
117 | }, [])
118 |
119 | // Clear nextItems on every render before collecting items
120 | nextItems.current = []
121 | shouldCollectItems.current = true
122 |
123 | useIsomorphicEffect(() => {
124 | // This effect runs after all children were stored, so we
125 | // can now apply the collected items to the items array
126 | items.current = nextItems.current
127 | shouldCollectItems.current = false
128 | })
129 |
130 | // Select
131 | useEffect(() => {
132 | function handleSelect(selectedIndex) {
133 | const item = items.current[selectedIndex]
134 | if (onSelect && item) {
135 | onSelect(item, selectedIndex)
136 | }
137 | }
138 | itemListEmitter.on('SELECT_ITEM', handleSelect)
139 | return () => {
140 | itemListEmitter.off('SELECT_ITEM', handleSelect)
141 | }
142 | }, [onSelect])
143 |
144 | const selectedRef = useRef(null)
145 | selectedRef.current = selected
146 | function isItemSelected(value) {
147 | return typeof selectedRef.current === 'function'
148 | ? selectedRef.current(value)
149 | : selectedRef.current === value
150 | }
151 |
152 | // Highlight
153 | function setHighlightedItem(index) {
154 | highlightedIndex.current = index
155 | itemListEmitter.emit('HIGHLIGHT_ITEM', index)
156 | if (onHighlight) {
157 | onHighlight(items.current[index], index)
158 | }
159 | }
160 |
161 | function moveHighlightedItem(amount, { contain = true } = {}) {
162 | const itemCount = items.current.length
163 | let index = highlightedIndex.current
164 | if (index === null) {
165 | index = amount >= 0 ? 0 : itemCount - 1
166 | } else {
167 | const getNextIndex = index => {
168 | let nextIndex = index + amount
169 | if (nextIndex < 0 || nextIndex >= itemCount) {
170 | nextIndex = contain
171 | ? modulo(highlightedIndex.current + amount, itemCount)
172 | : null
173 | }
174 | const item = items.current[nextIndex]
175 | if (item.disabled) {
176 | nextIndex = getNextIndex(nextIndex)
177 | }
178 | return nextIndex
179 | }
180 | index = getNextIndex(index)
181 | }
182 | setHighlightedItem(index)
183 | }
184 |
185 | function clearHighlightedItem() {
186 | setHighlightedItem(null)
187 | }
188 |
189 | function selectHighlightedItem() {
190 | if (highlightedIndex.current !== null) {
191 | itemListEmitter.emit('SELECT_ITEM', highlightedIndex.current)
192 | }
193 | }
194 |
195 | function getHighlightedIndex() {
196 | return highlightedIndex.current
197 | }
198 |
199 | function getHighlightedItem() {
200 | return items.current[highlightedIndex.current] ?? null
201 | }
202 |
203 | function getHighlightedItemId(index) {
204 | return items.current[index]?.id ?? null
205 | }
206 |
207 | const useHighlightedItemId = useCallback(() => {
208 | const [highlightedItemId, setHighlightedItemId] = useState(() =>
209 | getHighlightedItemId(highlightedIndex.current)
210 | )
211 | useEffect(() => {
212 | function handleHighlight(newIndex) {
213 | setHighlightedItemId(getHighlightedItemId(newIndex))
214 | }
215 | itemListEmitter.on('HIGHLIGHT_ITEM', handleHighlight)
216 | return () => {
217 | itemListEmitter.off('HIGHLIGHT_ITEM', handleHighlight)
218 | }
219 | }, [])
220 | return highlightedItemId
221 | }, [])
222 |
223 | // String Search
224 | const searchString = useRef('')
225 | const searchStringTimer = useRef(null)
226 |
227 | function highlightItemByString(event, delay = 300) {
228 | if (
229 | (isNumberKey(event) || isLetterKey(event) || isSpecialKey(event)) &&
230 | !isComboKey(event)
231 | ) {
232 | event.preventDefault()
233 | addToSearchString(event.key)
234 | startSearchStringTimer(delay)
235 | highlightItemFromString(searchString.current)
236 | }
237 | }
238 |
239 | function addToSearchString(letter) {
240 | searchString.current += letter.toLowerCase()
241 | }
242 |
243 | function clearSearchString() {
244 | searchString.current = ''
245 | }
246 |
247 | function startSearchStringTimer(delay) {
248 | clearSearchStringTimer()
249 | searchStringTimer.current = setTimeout(() => {
250 | clearSearchString()
251 | }, delay)
252 | }
253 |
254 | function clearSearchStringTimer() {
255 | clearTimeout(searchStringTimer.current)
256 | }
257 |
258 | function highlightItemFromString(text) {
259 | for (let index = 0; index < items.current.length; index++) {
260 | const item = items.current[index]
261 | const itemText = item.text || String(item.value)
262 | if (itemText.toLowerCase().indexOf(text) === 0) {
263 | setHighlightedItem(index)
264 | break
265 | }
266 | }
267 | }
268 |
269 | const useItem = useCallback(
270 | ({ ref, text, value, disabled = false }: ItemOptions) => {
271 | const itemEmitter = useConstant(() => mitt())
272 | const itemForceUpdate = useForceUpdate()
273 | const itemIndex = storeItem({ ref, text, value, disabled })
274 | const itemIndexRef = useRef(itemIndex)
275 |
276 | function highlight() {
277 | if (disabled === false) {
278 | setHighlightedItem(itemIndexRef.current)
279 | }
280 | }
281 |
282 | function select() {
283 | if (disabled === false) {
284 | itemListEmitter.emit('SELECT_ITEM', itemIndexRef.current)
285 | }
286 | }
287 |
288 | useIsomorphicEffect(() => {
289 | // if collection was invalidated, we need to trigger an update in the parent
290 | if (invalidatedItems.current) {
291 | itemListForceUpdate()
292 | invalidatedItems.current = false
293 | }
294 | })
295 |
296 | useIsomorphicEffect(() => {
297 | // patch the index if new children were added
298 | if (itemIndexRef.current !== itemIndex) {
299 | itemIndexRef.current = itemIndex
300 | itemForceUpdate()
301 | }
302 | itemEmitter.emit('UPDATE_ITEM_INDEX', itemIndex)
303 | }, [itemIndex])
304 |
305 | useEffect(() => {
306 | function handleHighlight(newIndex) {
307 | if (itemIndexRef.current === newIndex) {
308 | const itemNode = ref?.current
309 | if (itemNode) {
310 | scrollIntoView(itemNode)
311 | }
312 | }
313 | }
314 | itemListEmitter.on('HIGHLIGHT_ITEM', handleHighlight)
315 | return () => {
316 | itemListEmitter.off('HIGHLIGHT_ITEM', handleHighlight)
317 | }
318 | }, [])
319 |
320 | const useHighlighted = useCallback(() => {
321 | const [highlighted, setHighlighted] = useState(null)
322 | useIsomorphicEffect(() => {
323 | function handleHighlight(newIndex) {
324 | setHighlighted(itemIndexRef.current === newIndex)
325 | }
326 | function handleIndex(itemIndex) {
327 | // update the highlight state in case of a mismatch
328 | const nextHighlighted = highlightedIndex.current === itemIndex
329 | if (highlighted !== nextHighlighted) {
330 | setHighlighted(nextHighlighted)
331 | }
332 | }
333 | itemListEmitter.on('HIGHLIGHT_ITEM', handleHighlight)
334 | itemEmitter.on('UPDATE_ITEM_INDEX', handleIndex)
335 | return () => {
336 | itemListEmitter.off('HIGHLIGHT_ITEM', handleHighlight)
337 | itemEmitter.off('UPDATE_ITEM_INDEX', handleIndex)
338 | }
339 | }, [])
340 | useIsomorphicEffect(() => {
341 | const nextHighlighted =
342 | itemIndexRef.current === highlightedIndex.current
343 | if (highlighted !== nextHighlighted) {
344 | setHighlighted(nextHighlighted)
345 | }
346 | })
347 | return highlighted
348 | }, [])
349 |
350 | return {
351 | id: getItemId(itemIndex),
352 | index: itemIndexRef.current,
353 | highlight,
354 | select,
355 | selected: isItemSelected(value),
356 | useHighlighted,
357 | }
358 | },
359 | []
360 | )
361 |
362 | return {
363 | controllerId: controllerId.current,
364 | listId: listId.current,
365 | items,
366 | getHighlightedIndex,
367 | getHighlightedItem,
368 | setHighlightedItem,
369 | moveHighlightedItem,
370 | clearHighlightedItem,
371 | selectHighlightedItem,
372 | useHighlightedItemId,
373 | highlightItemByString,
374 | useItem,
375 | }
376 | }
377 |
--------------------------------------------------------------------------------
/packages/use-item-list/src/utils.ts:
--------------------------------------------------------------------------------
1 | function scroller(node) {
2 | if (node === document.body) {
3 | return {
4 | offsetTop: 0,
5 | scrollY: window.pageYOffset,
6 | height: window.innerHeight,
7 | setPosition: top => window.scrollTo(0, top),
8 | }
9 | } else {
10 | return {
11 | offsetTop: node.getBoundingClientRect().top,
12 | scrollY: node.scrollTop,
13 | height: node.offsetHeight,
14 | setPosition: top => (node.scrollTop = top),
15 | }
16 | }
17 | }
18 |
19 | /**
20 | * Get the closest element that scrolls
21 | * @param {HTMLElement} node - the child element to start searching for scroll parent at
22 | * @param {HTMLElement} rootNode - the root element of the component
23 | * @return {HTMLElement} the closest parentNode that scrolls
24 | */
25 | export function getClosestScrollParent(node) {
26 | if (node !== null) {
27 | if (node === document.body || node.scrollHeight > node.clientHeight) {
28 | return scroller(node)
29 | } else {
30 | return getClosestScrollParent(node.parentNode)
31 | }
32 | } else {
33 | return null
34 | }
35 | }
36 |
37 | /**
38 | * Scroll node into view if necessary
39 | * @param {HTMLElement} node - the element that should scroll into view
40 | * @param {HTMLElement} rootNode - the root element of the component
41 | * @param {Boolean} alignToTop - align element to the top of the visible area of the scrollable ancestor
42 | */
43 | export function scrollIntoView(node) {
44 | const scrollParent = getClosestScrollParent(node)
45 | if (scrollParent === null) {
46 | return
47 | }
48 | const nodeRect = node.getBoundingClientRect()
49 | const nodeTop = scrollParent.scrollY + (nodeRect.top - scrollParent.offsetTop)
50 | if (nodeTop < scrollParent.scrollY) {
51 | // the item is above the scrollable area
52 | scrollParent.setPosition(nodeTop)
53 | } else if (
54 | nodeTop + nodeRect.height >
55 | scrollParent.scrollY + scrollParent.height
56 | ) {
57 | // the item is below the scrollable area
58 | scrollParent.setPosition(nodeTop + nodeRect.height - scrollParent.height)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/packages/use-item-list/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "include": ["src", "types", "test"],
3 | "compilerOptions": {
4 | "target": "es5",
5 | "module": "esnext",
6 | "lib": ["dom", "esnext"],
7 | "importHelpers": true,
8 | "declaration": true,
9 | "sourceMap": true,
10 | "rootDir": "./src",
11 | "strict": false,
12 | "noImplicitAny": false,
13 | "strictNullChecks": false,
14 | "strictFunctionTypes": false,
15 | "strictPropertyInitialization": false,
16 | "noImplicitThis": false,
17 | "alwaysStrict": false,
18 | "noUnusedLocals": false,
19 | "noUnusedParameters": false,
20 | "noImplicitReturns": false,
21 | "noFallthroughCasesInSwitch": true,
22 | "moduleResolution": "node",
23 | "baseUrl": "./",
24 | "paths": {
25 | "*": ["src/*", "node_modules/*"]
26 | },
27 | "esModuleInterop": true
28 | }
29 | }
30 |
--------------------------------------------------------------------------------