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

Add YorkieProvider, DocumentProvider and suspense hooks #946

Merged
merged 2 commits into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
36 changes: 10 additions & 26 deletions examples/react-todomvc/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,46 +1,30 @@
import { useDocument, JSONArray, JSONObject } from '@yorkie-js/react';
import 'todomvc-app-css/index.css';
import { JSONArray, JSONObject, useDocument } from '@yorkie-js/react';

import Header from './Header';
import MainSection from './MainSection';
import { Todo } from './model';
import './App.css';

import 'todomvc-app-css/index.css';

/**
* `App` is the root component of the application.
*/
export default function App() {
const { root, update, loading, error } = useDocument<{
todos: JSONArray<Todo>;
}>(
import.meta.env.VITE_YORKIE_API_KEY,
`react-todomvc-${new Date().toISOString().substring(0, 10).replace(/-/g, '')}`,
{
todos: [
{ id: 0, text: 'Yorkie JS SDK', completed: false },
{ id: 1, text: 'Garbage collection', completed: false },
{ id: 2, text: 'RichText datatype', completed: false },
],
},
{
rpcAddr: import.meta.env.VITE_YORKIE_API_ADDR,
},
);

if (loading) {
return <div>Loading...</div>;
}
const { root, update, loading, error } = useDocument<
{ todos: JSONArray<Todo> },
any
>();

if (error) {
return <div>Error: {error.message}</div>;
}
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

const actions = {
addTodo: (text: string) => {
update((root) => {
root.todos.push({
id:
root.todos.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) +
root.todos.reduce((maxID, todo) => Math.max(todo.id, maxID), -1) +
1,
completed: false,
text,
Expand Down
23 changes: 10 additions & 13 deletions examples/react-todomvc/src/MainSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ interface MainSectionProps {
actions: { [name: string]: Function };
}

export default function MainSection(props: MainSectionProps) {
export default function MainSection({ todos, actions }: MainSectionProps) {
const [filter, setFilter] = useState('SHOW_ALL');
const { todos, actions } = props;
const filteredTodos = todos.filter(TODO_FILTERS[filter]);
const completedCount = todos.reduce((count, todo) => {
return todo.completed ? count + 1 : count;
Expand All @@ -37,17 +36,15 @@ export default function MainSection(props: MainSectionProps) {
onChange={actions.completeAll as ChangeEventHandler}
/>
<ul className="todo-list">
{
filteredTodos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
editTodo={actions.editTodo}
deleteTodo={actions.deleteTodo}
completeTodo={actions.completeTodo}
/>
))
}
{filteredTodos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
editTodo={actions.editTodo}
deleteTodo={actions.deleteTodo}
completeTodo={actions.completeTodo}
/>
))}
</ul>
<Footer
completedCount={completedCount}
Expand Down
19 changes: 17 additions & 2 deletions examples/react-todomvc/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { DocumentProvider, YorkieProvider } from '@yorkie-js/react';

const initalRoot = {
todos: [
{ id: 0, text: 'Yorkie JS SDK', completed: false },
{ id: 1, text: 'Garbage collection', completed: false },
{ id: 2, text: 'RichText datatype', completed: false },
],
};

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<App />,
<YorkieProvider apiKey={import.meta.env.VITE_YORKIE_API_KEY}>
<DocumentProvider
docKey={`react-todomvc-${new Date().toISOString().substring(0, 10).replace(/-/g, '')}`}
initialRoot={initalRoot}
>
<App />
</DocumentProvider>
</YorkieProvider>,
);
144 changes: 144 additions & 0 deletions packages/react/src/DocumentProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* Copyright 2025 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { createContext, useContext, useEffect, useState } from 'react';
import { Document, Indexable } from '@yorkie-js/sdk';
import { useYorkie } from './YorkieProvider';

type DocumentContextType<R, P> = {
root: R;
presences: { clientID: string; presence: P }[];
update: (callback: (root: R) => void) => void;
loading: boolean;
error: Error | undefined;
};

const DocumentContext = createContext<DocumentContextType<any, any> | null>(
null,
);

export const DocumentProvider = <R, P extends Indexable>({
docKey,
initialRoot,
children,
}: {
docKey: string;
initialRoot: R;
children: React.ReactNode;
}) => {
const client = useYorkie();
const [doc, setDoc] = useState<Document<R, P> | undefined>(undefined);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | undefined>(undefined);
const [root, setRoot] = useState(initialRoot);
const [presences, setPresences] = useState<
{ clientID: string; presence: any }[]
>([]);

useEffect(() => {
setLoading(true);
setError(undefined);

if (!client) return;

const newDoc = new Document<R, P>(docKey);
async function attachDocument() {
try {
await client?.attach(newDoc);

newDoc.subscribe(() => {
setRoot({ ...newDoc.getRoot() });
});

newDoc.subscribe('presence', () => {
setPresences(newDoc.getPresences());
});

setDoc(newDoc);
setRoot({ ...newDoc.getRoot() });
} catch (err) {
setError(
err instanceof Error ? err : new Error('Failed to attach document'),
);
} finally {
setLoading(false);
}
}

attachDocument();

return () => {
client.detach(newDoc);
};
}, [client, docKey]);

const update = (callback: (root: any) => void) => {
if (doc) {
doc.update(callback);
}
};

return (
<DocumentContext.Provider
value={{ root, presences, update, loading, error }}
>
{children}
</DocumentContext.Provider>
);
};

/**
* `useDocument` is a custom hook that returns the root object and update function of the document.
* This hook must be used within a `DocumentProvider`.
*/
export const useDocument = <R, P extends Indexable>() => {
const context = useContext(DocumentContext);
if (!context) {
throw new Error('useDocument must be used within a DocumentProvider');
}
return {
root: context.root as R,
presences: context.presences as { clientID: string; presence: P }[],
update: context.update as (
callback: (root: R, presence: P) => void,
) => void,
loading: context.loading,
error: context.error,
};
};

/**
* `useRoot` is a custom hook that returns the root object of the document.
* This hook must be used within a `DocumentProvider`.
*/
export const useRoot = () => {
const context = useContext(DocumentContext);
if (!context) {
throw new Error('useRoot must be used within a DocumentProvider');
}
return { root: context.root };
};

/**
* `usePresence` is a custom hook that returns the presence of the document.
*/
export const usePresence = () => {
const context = useContext(DocumentContext);
if (!context) {
throw new Error('usePresence must be used within a DocumentProvider');
}
return context.presences;
};
71 changes: 71 additions & 0 deletions packages/react/src/YorkieProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright 2025 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {
createContext,
PropsWithChildren,
useContext,
useEffect,
useState,
} from 'react';
import { Client } from '@yorkie-js/sdk';

const YorkieContext = createContext<{ client: Client | undefined }>({
client: undefined,
});

/**
* `YorkieProviderProps` is a set of properties for `YorkieProvider`.
*/
interface YorkieProviderProps {
apiKey: string;
rpcAddr?: string;
}

/**
* `YorkieProvider` is a component that provides the Yorkie client to its children.
*/
export const YorkieProvider: React.FC<
PropsWithChildren<YorkieProviderProps>
> = ({ apiKey, rpcAddr = 'https://api.yorkie.dev', children }) => {
const [client, setClient] = useState<Client | undefined>(undefined);

useEffect(() => {
async function initClient() {
const newClient = new Client(rpcAddr, {
apiKey,
});
await newClient.activate();
setClient(newClient);
}
initClient();

return () => {
client?.deactivate({ keepalive: true });
};
}, [apiKey, rpcAddr]);

return (
<YorkieContext.Provider value={{ client }}>
{children}
</YorkieContext.Provider>
);
};

export const useYorkie = () => {
const context = useContext(YorkieContext);
return context?.client;
};
19 changes: 17 additions & 2 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,22 @@
*/

import type { JSONArray, JSONObject } from '@yorkie-js/sdk';
import { useDocument } from './useDocument';

export { useDocument };
import { useYorkieDoc } from './useYorkieDoc';
import { YorkieProvider } from './YorkieProvider';
import {
DocumentProvider,
useDocument,
useRoot,
usePresence,
} from './DocumentProvider';

export type { JSONArray, JSONObject };
export {
YorkieProvider,
DocumentProvider,
useDocument,
useRoot,
usePresence,
useYorkieDoc,
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ import { useCallback, useEffect, useState } from 'react';
import { Client, Document } from '@yorkie-js/sdk';

/**
* `useDocument` is a custom hook that returns the root object of the document.
* `useYorkieDoc` is a custom hook that initializes a Yorkie client and attaches a document.
*
* @param apiKey
* @param docKey
* @param initialRoot
* @returns
*/
export function useDocument<T>(
export function useYorkieDoc<T>(
apiKey: string,
docKey: string,
initialRoot: T,
Expand Down
1 change: 1 addition & 0 deletions packages/react/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"lib": ["ES2020", "DOM"],
"skipLibCheck": true,
"outDir": "./lib",
"jsx": "react-jsx",

/* Bundler mode */
"moduleResolution": "node",
Expand Down
Loading