Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decentralize Authentication, Encrypt communication, and show current online status #79

Draft
wants to merge 7 commits into
base: main
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
2 changes: 1 addition & 1 deletion examples/grid/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"baseUrl": "src",
"esModuleInterop": true,
"importHelpers": true,
"jsx": "react-jsx",
"jsx": "react",
"lib": ["dom", "esnext"],
"moduleResolution": "node",
"noEmit": true,
Expand Down
Binary file added examples/todo/public/favicon.ico
Binary file not shown.
21 changes: 21 additions & 0 deletions examples/todo/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,33 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Offline and Synchronized TODO List App that can be installed on your phone"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
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>@localfirst/state example: todo</title>
<link rel="stylesheet" href="index.css" />
<link rel="stylesheet" href="base.css" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Binary file added examples/todo/public/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/todo/public/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions examples/todo/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "TODO Lists",
"name": "Offline and Synchronized TODO List App",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
8 changes: 7 additions & 1 deletion examples/todo/src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { randomDiscoveryKey } from 'lib/randomName'
import React from 'react'
import React, { useState } from 'react'
import Redux from 'redux'
import { Provider } from 'react-redux'
import { useQueryParam } from 'use-query-params'
import { Toolbar } from '@localfirst/toolbar'
import { Todos } from '.'
import { useStore } from '../redux/useStore'
import { storeManager } from '../redux/store'

export const App: React.FC = () => {
const [key, setKey] = useQueryParam<string>('key')
Expand All @@ -15,9 +18,12 @@ export const App: React.FC = () => {
}

const appStore = useStore(key, generateNewKey)
const [_, setAppStore] = useState<Redux.Store>()
const onStoreReady = (store: Redux.Store) => setAppStore(store)

return appStore ? (
<Provider store={appStore}>
<Toolbar storeManager={storeManager} onStoreReady={onStoreReady}/>
<Todos />
</Provider>
) : null
Expand Down
6 changes: 6 additions & 0 deletions examples/todo/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import React from 'react'
import ReactDOM from 'react-dom'
import { App } from './components'
import * as serviceWorker from './serviceWorker'

const start = () => {
ReactDOM.render(<App />, document.getElementById('root'))
}

start()

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register()
142 changes: 142 additions & 0 deletions examples/todo/src/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);

export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}

function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);

// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');

// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}

function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}

export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

2 changes: 1 addition & 1 deletion examples/toolbar/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
"dependencies": {
"@emotion/react": "11",
"@localfirst/state": "^1.0.12",
"@philschatz/auth": "0.0.2",
"formik": "^2.0.1-rc.13",
"friendly-words": "1",
"react": "17",
"react-dom": "^16.0.1",
"redux": "4",
"taco-js": "0",
"tailwindcss": "^1.7.6",
"use-persisted-state": "0",
"use-query-params": "0"
Expand Down
39 changes: 35 additions & 4 deletions examples/toolbar/src/components/Status.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/** @jsxImportSource @emotion/react */
import { CLOSE, OPEN, PEER, PEER_REMOVE, StoreManager } from '@localfirst/state'
import { useEffect, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { Group } from './Group'
import { StatusLight } from './StatusLight'
import { PEER_UPDATE } from '@localfirst/state/dist/src/constants'

interface StatusProps {
storeManager: StoreManager<any>
Expand All @@ -12,8 +13,8 @@ export const Status = ({ storeManager }: StatusProps) => {
const [online, setOnline] = useState<boolean>(false)
const [peers, setPeers] = useState<string[]>([])

const onPeer = (updatedPeers: string[]) => {
setPeers(updatedPeers)
const onPeer = (updatedPeers: string[], updatedAuthenticatedUserInfo: {generation: number, name: string, type: 'ADMIN' | 'MEMBER'}[]) => {
setPeers(updatedAuthenticatedUserInfo.map((v, i) => `${(v && v.type) === 'ADMIN' ? '👑' : ''} ${(v && v.name) ? v.name : `?${updatedPeers[i]}?`}`))
}

const onOpen = () => {
Expand All @@ -31,6 +32,7 @@ export const Status = ({ storeManager }: StatusProps) => {
storeManager.on(CLOSE, onClose)
storeManager.on(PEER, onPeer)
storeManager.on(PEER_REMOVE, onPeer)
storeManager.on(PEER_UPDATE, onPeer)
return removeListeners // return cleanup function
}

Expand All @@ -50,12 +52,41 @@ export const Status = ({ storeManager }: StatusProps) => {
? `one peer is connected`
: `${peers.length} other peers are connected`
const statusMessage = online ? `online; ${peerCountMessage}` : 'offline'

const peerItems = peers.map(p => <li key={p}><button>{getAvatar(p)}{p}</button></li>)

return (
<Group title={statusMessage}>
<label>
<StatusLight online={online} />
{online ? <span css={{ marginLeft: '.5em' }}>{peers.length}</span> : ''}
{online ? <span style={{ marginLeft: '.5em' }}>{peers.length} online</span> : ''}
</label>
<ul>
{peerItems}
</ul>
</Group>
)
}


const avatars = [
'👶', // Baby
'🧒', // Child
'🧑', // Person
'👱', // Person: Blond Hair
'🧔', // Person: Beard
'👨‍🦰', // Man: Red Hair
'👨‍🦳', // Man: White Hair
'👩', // Woman
'👩‍🦰', // Woman: Red Hair
'🧑‍🦰', // Person: Red Hair
'👩‍🦱', // Woman: Curly Hair
'🧑‍🦳', // Person: White Hair
'👱‍♀️', // Woman: Blond Hair
'🧓', // Older Person
]
const hashCode = (s: string) => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)
function getAvatar(username: string) {
if (username.endsWith('?')) { return null }
return avatars[Math.abs(hashCode(username)) % avatars.length]
}
4 changes: 3 additions & 1 deletion examples/toolbar/src/components/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const Toolbar = ({
children,
}: React.PropsWithChildren<ToolbarProps<any>>) => {
// Hooks
const [discoveryKey, setDiscoveryKey] = useQueryParam('id', StringParam)
const [discoveryKey, setDiscoveryKey] = useQueryParam('key', StringParam)
const [, setAppStore] = useState<Redux.Store>()
const [busy, setBusy] = useState(false)

Expand All @@ -39,6 +39,7 @@ export const Toolbar = ({
const newDiscoveryKey = randomDiscoveryKey()
setDiscoveryKey(newDiscoveryKey)
const newStore = await storeManager.createStore(newDiscoveryKey)
await storeManager.listenToConnections(newDiscoveryKey)
setAppStore(newStore)
onStoreReady(newStore, newDiscoveryKey)
setBusy(false)
Expand All @@ -52,6 +53,7 @@ export const Toolbar = ({
setBusy(true)
setDiscoveryKey(newDiscoveryKey)
const newStore = await storeManager.joinStore(newDiscoveryKey)
await storeManager.listenToConnections(newDiscoveryKey)
setAppStore(newStore)
onStoreReady(newStore, newDiscoveryKey)
setBusy(false)
Expand Down
2 changes: 1 addition & 1 deletion examples/toolbar/src/lib/localUser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { loadUser, createUser } from 'taco-js'
import { loadUser, createUser } from '@philschatz/auth'
import { randomUserName } from './randomName'

const _createUser = () => {
Expand Down
2 changes: 1 addition & 1 deletion examples/toolbar/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"composite": true,
"declaration": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"jsx": "react",
"lib": ["dom", "esnext"],
"module": "commonjs",
"moduleResolution": "node",
Expand Down
Loading