Skip to content

Commit

Permalink
added demo folder for local testing
Browse files Browse the repository at this point in the history
  • Loading branch information
Yair Even Or authored and Yair Even Or committed Oct 17, 2022
1 parent 6774857 commit 3b7e548
Show file tree
Hide file tree
Showing 10 changed files with 28,061 additions and 0 deletions.
27,800 changes: 27,800 additions & 0 deletions demo/package-lock.json

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions demo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "ref-change-listener",
"version": "1.0.0",
"description": "Hooks for detecting ref changes and re-render when they happen",
"keywords": [],
"main": "src/index.js",
"author": "Yair Even Or",
"dependencies": {
"react": "18.0.0",
"react-dom": "18.0.0",
"react-scripts": "5.0.1",
"sass": "1.53.0",
"@yaireo/react-ref-watcher": "file:../"
},
"devDependencies": {
"@babel/runtime": "7.13.8"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
58 changes: 58 additions & 0 deletions demo/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React Ref Watcher - Demo</title>
</head>

<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<!-- <p>
This POC intends to solve the problem where refs are used on the "main" component, to store
different state values, because if <code>"useState"</code> were used, when changed, the main component (<code>List</code>)
will re-render, along with all its sub-components 😢
</p>
<p>
A <code>context</code> is used to pass all sub-components those refs, so each sub-component can chose to register a listener
to a specific ref or, if the ref's <code>"current"</code> property is an Object, listen to changes in that Object.
</p>
<p>
When toggling a list item (checkbox), only it will render, and not any of its siblings.
</p>
<p>
<em>(Open the console below and watch which component renders)</em>
</p> -->
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>

</html>
10 changes: 10 additions & 0 deletions demo/src/Checkbox.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const Checkbox = ({label, checked = false, onChange}) => {
return (
<label>
<input type='checkbox' checked={checked} onChange={onChange}/>
{label}
</label>
)
}

export default Checkbox
3 changes: 3 additions & 0 deletions demo/src/List.context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {createContext} from 'react'

export default createContext()
42 changes: 42 additions & 0 deletions demo/src/List.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {useRef} from 'react'
import {useWatchableRef, propWatcher} from '@yaireo/react-ref-watcher'
import ListItem from './ListItem'
import SelectAll from './SelectAll'
import ListContext from './List.context'
import "./styles.scss"

// Mock data
const DATA = [...Array(3)].map((_, i) =>
({name: `item-${i+1}`, label: `Item ${i+1}`}))

// The idea is that the main component, this one, defines the state at its
// level and shares using "context" with whoever wants to listen to state changes.
// Since "useState" cannot be used (it triggers a re-render) then refs are used.
const List = () => {
console.log('"List" component rendered (only once)')
// A Boolean ref, indicating all list items are selected.
// "useWatchableRef" makes the "current" property watchable
// when it changes (by any child component registering to it)
const allSelectedRef = useWatchableRef(false)

// Initialize the "current" property as a watchable-object
const selectedRef = useRef(propWatcher({}))

const contextValue = { data: DATA, selectedRef, allSelectedRef }

return (
<ListContext.Provider value={contextValue}>
<div className='list-wrapper'>
<header>
<SelectAll label='Select All'/>
</header>

{DATA.map(({ name, label }) =>
<ListItem key={name} {...{name, label}}/>
)}
</div>
</ListContext.Provider>
)
}

export default List
32 changes: 32 additions & 0 deletions demo/src/ListItem.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {useContext} from 'react'
import {useWatchableListener} from '@yaireo/react-ref-watcher'
import ListContext from './List.context'
import Checkbox from './Checkbox'

const ListItem = ({name, label}) => {
// get the smart ref from the context (or props, which ever is better in a certain situation)
const {selectedRef} = useContext(ListContext)

// listen to changes for that ref in a specific property ("name")
useWatchableListener(selectedRef.current, name)

const toggle = e => {
// "selectedRef.current" only contains keys for SELECTED items
if( e.target.checked ) {
selectedRef.current[name] = true
}
else {
delete selectedRef.current[name] // remove the property
}
}

console.log(name, "component rendered")

return (
<div className='list-item'>
<Checkbox label={label} checked={selectedRef.current[name]} onChange={toggle}/>
</div>
)
}

export default ListItem
43 changes: 43 additions & 0 deletions demo/src/SelectAll.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {useContext} from 'react'
import {useWatchableListener, useWatchableEffect} from '@yaireo/react-ref-watcher'
import ListContext from './List.context'
import Checkbox from './Checkbox'

const SelectAll = ({name, label}) => {
console.log('"SelectAll" component rendered')

// get the smart ref from the context (or props, which ever is better in a certain situation)
const {data, selectedRef, allSelectedRef} = useContext(ListContext)

// listen to changes in "allSelectedRef" (boolean) and re-render
const unlisten = useWatchableListener(allSelectedRef)

// unlisten()

// listen to changes in "selectedRef" to track if all have been selected or not.
// does not re-render because the 3rd parameter is a custom function.
useWatchableEffect(() => {
const selectedCount = Object.keys(selectedRef.current).length
allSelectedRef.current = selectedCount === data.length
}, [selectedRef.current])

const toggle = e => {
allSelectedRef.current = e.target.checked

// (de)select all items
data.forEach(({name}) => {
if( e.target.checked )
selectedRef.current[name] = true
else
delete selectedRef.current[name]
})
}

return (
<div className='list-item'>
<Checkbox label={label} checked={allSelectedRef.current} onChange={toggle}/>
</div>
)
}

export default SelectAll
8 changes: 8 additions & 0 deletions demo/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createRoot } from "react-dom/client";

import List from "./List";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(<List />)
35 changes: 35 additions & 0 deletions demo/src/styles.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
body {
font: 16px Arial;
padding: 1em;
max-width: 600px;
margin: auto;
}

#root {
font-size: 20px;
border: 2px dashed salmon;
margin: 2em 0;
padding: 1em;
border-radius: 10px;
}

.list-wrapper {
> header {
margin-bottom: 1em;
}
}

label {
display: inline-flex;
gap: 5px;
cursor: pointer;
user-select: none;

input {
transform: scale(1.3);
}

&:hover {
color: royalblue;
}
}

0 comments on commit 3b7e548

Please sign in to comment.