diff --git a/examples/dql-create-react-app-typescript-example/.gitignore b/examples/dql-create-react-app-typescript-example/.gitignore new file mode 100644 index 0000000..26919a9 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/.gitignore @@ -0,0 +1,26 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# editors +.idea \ No newline at end of file diff --git a/examples/dql-create-react-app-typescript-example/README.md b/examples/dql-create-react-app-typescript-example/README.md new file mode 100644 index 0000000..46b48d5 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/README.md @@ -0,0 +1,48 @@ +# Getting Started with Create React App + +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +**Note: on newer versions of Node, you may run into `ERR_OSSL_EVP_UNSUPPORTED` errors. You may pass the command-line option of `--openssl-legacy-provider` to work around this. Refer to [Node v17 release notes](https://nodejs.org/es/blog/release/v17.0.0/#openssl-3-0).** + +In the project directory, you can run: + +### `yarn start` + +Runs the app in the development mode.\ +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.\ +You will also see any lint errors in the console. + +### `yarn test` + +Launches the test runner in the interactive watch mode.\ +See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `yarn build` + +Builds the app for production to the `build` folder.\ +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.\ +Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `yarn eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +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. + +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. + +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. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). diff --git a/examples/dql-create-react-app-typescript-example/package.json b/examples/dql-create-react-app-typescript-example/package.json new file mode 100644 index 0000000..f208ba5 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/package.json @@ -0,0 +1,61 @@ +{ + "name": "create-react-app-typescript-example", + "version": "0.1.0", + "private": true, + "dependencies": { + "@dittolive/ditto": "link:../../node_modules/@dittolive/ditto", + "@dittolive/react-ditto": "link:../..", + "@testing-library/jest-dom": "^6.4.2", + "@testing-library/react": "^15.0.2", + "@testing-library/user-event": "^14.5.2", + "@types/jest": "^29.5.12", + "@types/node": "^20.12.7", + "@types/react": "^18.2.79", + "@types/react-dom": "^18.2.25", + "react": "link:../../node_modules/react", + "react-dom": "link:../../node_modules/react-dom", + "react-scripts": "5.0.1", + "react-select": "^5.8.0", + "typescript": "^4.9", + "uuid": "^9.0.1", + "web-vitals": "^3.5.2" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + }, + "devDependencies": { + "@types/uuid": "^9.0.8", + "eslint": "^8.0.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-react": "^7.34.1", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-simple-import-sort": "^12.1.0", + "prettier": "3.2.5", + "prettier-eslint": "^16.3.0" + }, + "engines": { + "node": ">=18" + } +} diff --git a/examples/dql-create-react-app-typescript-example/public/favicon.ico b/examples/dql-create-react-app-typescript-example/public/favicon.ico new file mode 100644 index 0000000..a11777c Binary files /dev/null and b/examples/dql-create-react-app-typescript-example/public/favicon.ico differ diff --git a/examples/dql-create-react-app-typescript-example/public/index.html b/examples/dql-create-react-app-typescript-example/public/index.html new file mode 100644 index 0000000..aa069f2 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/examples/dql-create-react-app-typescript-example/public/logo192.png b/examples/dql-create-react-app-typescript-example/public/logo192.png new file mode 100644 index 0000000..fc44b0a Binary files /dev/null and b/examples/dql-create-react-app-typescript-example/public/logo192.png differ diff --git a/examples/dql-create-react-app-typescript-example/public/logo512.png b/examples/dql-create-react-app-typescript-example/public/logo512.png new file mode 100644 index 0000000..a4e47a6 Binary files /dev/null and b/examples/dql-create-react-app-typescript-example/public/logo512.png differ diff --git a/examples/dql-create-react-app-typescript-example/public/manifest.json b/examples/dql-create-react-app-typescript-example/public/manifest.json new file mode 100644 index 0000000..080d6c7 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "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" +} diff --git a/examples/dql-create-react-app-typescript-example/public/robots.txt b/examples/dql-create-react-app-typescript-example/public/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/examples/dql-create-react-app-typescript-example/src/App.css b/examples/dql-create-react-app-typescript-example/src/App.css new file mode 100644 index 0000000..0def93f --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/src/App.css @@ -0,0 +1,44 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; + pointer-events: none; +} + +@media (prefers-reduced-motion: no-preference) { + .App-logo { + animation: App-logo-spin infinite 20s linear; + } +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #61dafb; +} + +@keyframes App-logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +ul.no-bullets { + list-style-type: none; /* Remove bullets */ + padding: 0; /* Remove padding */ + margin: 0; /* Remove margins */ +} \ No newline at end of file diff --git a/examples/dql-create-react-app-typescript-example/src/App.test.tsx b/examples/dql-create-react-app-typescript-example/src/App.test.tsx new file mode 100644 index 0000000..626b969 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/src/App.test.tsx @@ -0,0 +1,9 @@ +import { render, screen } from '@testing-library/react' + +import App from './App' + +test('renders learn react link', () => { + render() + const linkElement = screen.getByText(/Using Ditto with path/i) + expect(linkElement).toBeInTheDocument() +}) diff --git a/examples/dql-create-react-app-typescript-example/src/App.tsx b/examples/dql-create-react-app-typescript-example/src/App.tsx new file mode 100644 index 0000000..ce8ba05 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/src/App.tsx @@ -0,0 +1,145 @@ +import './App.css' + +import { useExecuteQuery, useQuery } from '@dittolive/react-ditto' +import React, { useState } from 'react' + +type Task = { + _id: string + body: string + isCompleted: boolean + isDeleted: boolean +} + +const styles: Record = { + app: { + maxWidth: '600px', + margin: '3em auto', + textAlign: 'left', + }, + error: { + color: 'red', + }, + header: { + backgroundColor: '#f5f5f5', + padding: '1em', + }, +} + +type Props = { + path: string +} + +function isError(error: unknown): error is Error { + return error instanceof Error +} + +const App: React.FC = ({ path: persistenceDirectory }) => { + const [newBodyText, setNewBodyText] = useState('') + const { + items: tasks, + error, + storeObserver, + isLoading, + } = useQuery('select * from tasks where isDeleted = false', { + queryArguments: { val: false }, + persistenceDirectory, + }) + + const [upsert] = useExecuteQuery }>( + 'insert into tasks documents (:value) on id conflict do update', + { + queryArguments: { value: { isDeleted: false } }, + persistenceDirectory, + }, + ) + + const [removeByID] = useExecuteQuery( + 'update tasks set isDeleted = true where _id = :id', + { + persistenceDirectory, + }, + ) + + const [setCompletedByID] = useExecuteQuery< + unknown, + Pick + >('update tasks set isCompleted = :isCompleted where _id = :_id', { + persistenceDirectory, + }) + + if (isLoading) { + return

Loading...

+ } + + return ( +
+
+

+ Using Ditto with persistence directory “{persistenceDirectory} + “ and query “ + {storeObserver.queryString}“ +

+ Number of tasks {tasks?.length} + + {isError(error) &&

Error: {error.message}

} + +
+ setNewBodyText(e.currentTarget.value)} + /> + +
+
+
    + {tasks.map((task) => { + return ( +
  • +

    DocumentId: {task.value._id}

    +

    Body: {task.value.body}

    +

    + Is Completed:{' '} + {task.value.isCompleted ? 'Completed' : 'Not Completed'} +

    + + +
  • + ) + })} +
+
+ ) +} + +export default App diff --git a/examples/dql-create-react-app-typescript-example/src/AppContainer.tsx b/examples/dql-create-react-app-typescript-example/src/AppContainer.tsx new file mode 100644 index 0000000..047b788 --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/src/AppContainer.tsx @@ -0,0 +1,105 @@ +import { Ditto } from '@dittolive/ditto' +import { + DittoProvider, + useOfflinePlaygroundIdentity, + useOnlineIdentity, +} from '@dittolive/react-ditto' +import React, { useState } from 'react' +import { default as ReactSelect, SingleValue } from 'react-select' +import { v4 as uuidv4 } from 'uuid' + +import App from './App' +import AuthenticationPanel from './AuthenticationPanel' + +interface IdentityOption { + name: string + path: string +} +const options: IdentityOption[] = [ + { path: '/path-development', name: 'Development' }, + { path: '/path-online', name: 'Online' }, +] + +/** + * Container component that shows how to initialize the DittoProvider component. + * */ +const AppContainer: React.FC = () => { + const { create: createDevelopment } = useOfflinePlaygroundIdentity() + const { create: createOnline, getAuthenticationRequired } = + useOnlineIdentity() + const [currentPath, setCurrentPath] = useState('/path-development') + + const handleCreateDittoInstances = async () => { + // Example of how to create a development instance + const dittoDevelopment = new Ditto( + createDevelopment({ + appID: '12e5e73c-68af-4af8-9322-5fd262ff5c7d', + siteID: 1234, + }), + '/path-development', + ) + await dittoDevelopment.disableSyncWithV3() + + // Example of how to create an online instance with authentication enabled + const dittoOnline = new Ditto( + createOnline( + { + // If you're using the Ditto cloud this ID should be the app ID shown on your app settings page, on the portal. + appID: uuidv4(), + // enableDittoCloudSync: true, + }, + '/path-online', + ), + '/path-online', + ) + return [dittoDevelopment, dittoOnline] + // eslint-disable-next-line react-hooks/exhaustive-deps + } + + return ( + <> +
+ + + getOptionLabel={(animal: IdentityOption) => animal.name} + getOptionValue={(animal: IdentityOption) => animal.path} + options={options} + value={options.find((opt) => opt.path === currentPath)} + onChange={(nextOption: SingleValue) => + setCurrentPath(nextOption!.path) + } + /> +
+ + {({ loading, error }) => { + if (loading) { + return

Loading

+ } + if (error) { + return

Error: {JSON.stringify(error)}

+ } + + return ( + <> + + + + ) + }} +
+ + ) +} + +export default AppContainer diff --git a/examples/dql-create-react-app-typescript-example/src/AuthenticationPanel.tsx b/examples/dql-create-react-app-typescript-example/src/AuthenticationPanel.tsx new file mode 100644 index 0000000..8e3b20b --- /dev/null +++ b/examples/dql-create-react-app-typescript-example/src/AuthenticationPanel.tsx @@ -0,0 +1,91 @@ +import { useDitto } from '@dittolive/react-ditto' +import React, { useState } from 'react' + +type Props = { + /** True if authentication is required */ + isAuthRequired: boolean + /** Current active path */ + path: string +} + +/** Simple authenticate panel for the user to input a token and a token provider. + */ +const AuthenticationPanel: React.FC = ({ path, isAuthRequired }) => { + const [token, setToken] = useState('') + const [provider, setProvider] = useState('') + const [authError, setAuthError] = useState() + const { ditto } = useDitto(path) + const [isAuthenticated, setIsAuthenticated] = useState( + !!ditto?.auth.status.isAuthenticated, + ) + + if (!ditto || !isAuthRequired || isAuthenticated) { + return null + } + + return ( +
+
{ + evt.preventDefault() + ditto.auth + .loginWithToken(token, provider) + .then(() => setIsAuthenticated(ditto.auth.status.isAuthenticated)) + .catch((err) => { + setAuthError(err) + }) + }} + > +

Authentication required

+
+
+ + setProvider(evt.target.value)} + /> +
+
+ +