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

Bump up Yorkie to v0.4.6 #282

Merged
merged 2 commits into from
Aug 25, 2023
Merged
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 docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ services:
# extra_hosts:
# - "host.docker.internal:host-gateway"
yorkie:
image: 'yorkieteam/yorkie:0.4.3'
image: 'yorkieteam/yorkie:0.4.6'
container_name: 'yorkie'
command: [
'server',
Expand Down
Binary file added media/screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"remark-toc": "^8.0.1",
"tss-react": "^4.8.2",
"unique-names-generator": "^4.7.1",
"yorkie-js-sdk": "^0.4.3"
"yorkie-js-sdk": "^0.4.6"
},
"devDependencies": {
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
Expand Down
36 changes: 19 additions & 17 deletions src/components/Editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,7 @@ export default function BaseEditor(props: { docKey: string }) {
return;
}

const unsubscribe = client.subscribe((event) => {
if (event.type === 'peers-changed') {
const changedPeers = client.getPeersByDocKey(doc.getKey()).reduce((acc, peer) => {
acc[peer.clientID] = peer.presence;
return acc;
}, {} as Record<string, Presence>);
dispatch(
syncPeer({
myClientID: client.getID()!,
changedPeers,
}),
);
}

const unsubscribeClient = client.subscribe((event) => {
if (
status === DocStatus.Connect &&
((event.type === 'status-changed' && event.value === 'deactivated') ||
Expand All @@ -107,8 +94,7 @@ export default function BaseEditor(props: { docKey: string }) {
dispatch(setStatus(DocStatus.Disconnect));
} else if (
status === DocStatus.Disconnect &&
(event.type === 'peers-changed' ||
event.type === 'documents-changed' ||
(event.type === 'document-changed' ||
(event.type === 'status-changed' && event.value === 'activated') ||
(event.type === 'stream-connection-status-changed' && event.value === 'connected') ||
(event.type === 'document-synced' && event.value === 'synced'))
Expand All @@ -117,8 +103,24 @@ export default function BaseEditor(props: { docKey: string }) {
}
});

const unsubscribeDoc = doc.subscribe('presence', (event) => {
if (event.type !== 'presence-changed') {
const changedPeers = doc.getPresences().reduce((acc, peer) => {
acc[peer.clientID] = peer.presence;
return acc;
}, {} as Record<string, Presence>);
dispatch(
syncPeer({
myClientID: client.getID()!,
changedPeers,
}),
);
}
});

return () => {
unsubscribe();
unsubscribeClient();
unsubscribeDoc();
};
}, [client, doc, status, dispatch]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
import { useThrottleCallback } from '@react-hook/throttle';
import randomColor from 'randomcolor';
import { uniqueNamesGenerator, names } from 'unique-names-generator';
import { Unsubscribe } from 'yorkie-js-sdk';
import { Unsubscribe, DocEventType } from 'yorkie-js-sdk';
import { debounce } from '@mui/material';
import { setActionStatus } from 'features/actionSlices';

Expand Down Expand Up @@ -225,6 +225,15 @@ export function useMultiplayerState(roomId: string) {
[roomId, client, menu],
);

const displayRemoteCursors = useCallback(() => {
if (!doc) return;
const allPeers = doc
.getPresences()
.map((peer) => peer.presence.whiteboardUser)
.filter(Boolean) as TDUser[];
app?.updateUsers(allPeers);
}, [app, doc]);

// Update Yorkie doc when the app's shapes change.
// Prevent overloading yorkie update api call by throttle
const onChangePage = useThrottleCallback(
Expand Down Expand Up @@ -298,19 +307,23 @@ export function useMultiplayerState(roomId: string) {
// Handle presence updates when the user's pointer / selection changes
const onChangePresence = useThrottleCallback(
(tldrawApp: TldrawApp, user: TDUser) => {
if (!tldrawApp || client === undefined || !client.isActive()) return;
if (!tldrawApp || client === undefined || doc === undefined) return;

client.updatePresence('whiteboardUser', {
...{
id: `${client.getID()}`,
point: [-100, -100],
color: menu?.userColor || randomColor(),
status: TDUserStatus.Connected,
activeShapes: [],
selectedIds: [],
metadata: { name: menu?.userName }, // <-- custom metadata
},
...user,
doc.update((root, presence) => {
presence.set({
whiteboardUser: {
...{
id: `${client.getID()}`,
point: [-100, -100],
color: menu?.userColor || randomColor(),
status: TDUserStatus.Connected,
activeShapes: [],
selectedIds: [],
metadata: { name: menu?.userName }, // <-- custom metadata
},
...user,
},
});
});

dispatch(setActionStatus({ isOver: true }));
Expand All @@ -327,8 +340,8 @@ export function useMultiplayerState(roomId: string) {
let stillAlive = true;
let unsubscribe: Unsubscribe;

// Subscribe to changes
function handleChanges() {
// Subscribe to change in the document
function handleChange() {
const root = doc!.getRoot();

// Parse proxy object to record
Expand All @@ -344,41 +357,16 @@ export function useMultiplayerState(roomId: string) {
async function setupDocument() {
try {
// 01-1. Subscribe peers-changed event and update tldraw users state
unsubscribe = client!.subscribe((event) => {
if (event.type === 'peers-changed') {
const peers = event.value.peers[doc!.getKey()];
// Compare with local user list and get leaved user list
// Then remove leaved users
const localUsers = Object.values(app!.room!.users).filter(Boolean);

const remoteUsers = Object.values(peers || {})
.map((peer) => {
if (!peer.presence.whiteboardUser) return null;
return {
...{
point: [0, 0],
activeShapes: [],
selectedIds: [],
id: `${peer?.clientID}`,
status: TDUserStatus.Connected,
color: peer.presence.color,
metadata: {
name: peer.presence.username,
},
},
...(peer.presence.whiteboardUser || {}),
};
})
.filter(Boolean);
const leavedUsers = localUsers.filter(({ id: id1 }) => !remoteUsers.some((user) => user?.id === id1));

leavedUsers.forEach((user) => {
app?.removeUser(user.id);
});

// Then update users
app?.updateUsers(remoteUsers as any);
if (!doc) return;
unsubscribe = doc.subscribe('others', (event) => {
// remove leaved users
if (event.type === DocEventType.Unwatched) {
// TODO(chacha912): We don't know presence of unwatched client now.
// app?.removeUser(event.value.presence.tdUser.id);
}

// update users
displayRemoteCursors();
});

// 03. Initialize document if document not exists.
Expand Down Expand Up @@ -406,7 +394,7 @@ export function useMultiplayerState(roomId: string) {
// 04. Subscribe document event and handle changes.
doc!.subscribe((event) => {
if (event.type === 'remote-change') {
handleChanges();
handleChange();
}
});

Expand All @@ -415,8 +403,7 @@ export function useMultiplayerState(roomId: string) {

if (stillAlive) {
// Update the document with initial content
handleChanges();
handleChanges();
handleChange();

// Zoom to fit the content & finish loading
if (app) {
Expand All @@ -435,13 +422,14 @@ export function useMultiplayerState(roomId: string) {
}

setupDocument();
displayRemoteCursors();

return () => {
stillAlive = false;

unsubscribe?.();
};
}, [app, client, doc, roomId]);
}, [app, client, doc, roomId, displayRemoteCursors]);

return {
onMount,
Expand Down
54 changes: 31 additions & 23 deletions src/components/Editor/mime/text/md/CodeEditor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -667,27 +667,14 @@ export default function CodeEditor() {
};

// remote to local
const handleOperations = (ops: Array<OperationInfo>, actor: ActorID) => {
const handleOperations = (ops: Array<OperationInfo>) => {
ops.forEach((op) => {
if (op.type === 'edit') {
const { from, to } = op;
const content = op.value?.content || '';
if (actor !== client.getID()) {
const fromPos = editor.posFromIndex(from);
const toPos = editor.posFromIndex(to);
editor.replaceRange(content, fromPos, toPos, 'yorkie');
}
} else if (op.type === 'select') {
const { from, to } = op;
if (actor !== client.getID()) {
let fromPos = editor.posFromIndex(from);
let toPos = editor.posFromIndex(to);
updateCursor(actor, toPos);
if (from > to) {
[toPos, fromPos] = [fromPos, toPos];
}
updateLine(actor, fromPos, toPos);
}
const fromPos = editor.posFromIndex(from);
const toPos = editor.posFromIndex(to);
editor.replaceRange(content, fromPos, toPos, 'yorkie');
}
});
};
Expand Down Expand Up @@ -769,8 +756,13 @@ export default function CodeEditor() {
const to = editor.indexFromPos(change.to);
const content = change.text.join('\n');

doc.update((root) => {
root.content.edit(from, to, content);
doc.update((root, presence) => {
const updatedIndexRange = root.content.edit(from, to, content);
if (updatedIndexRange) {
presence.set({
selection: root.content.indexRangeToPosRange(updatedIndexRange),
});
}
});
});

Expand All @@ -782,16 +774,32 @@ export default function CodeEditor() {
const from = editor.indexFromPos(data.ranges[0].anchor);
const to = editor.indexFromPos(data.ranges[0].head);

doc.update((root) => {
root.content.select(from, to);
doc.update((root, presence) => {
presence.set({
selection: root.content.indexRangeToPosRange([from, to]),
});
});
});

// remote to local
doc.subscribe('$.content', (event) => {
if (event.type === 'remote-change') {
const { actor, operations } = event.value;
handleOperations(operations, actor!);
handleOperations(event.value.operations);
}
});

doc.subscribe('others', (event) => {
if (event.type === 'presence-changed') {
const { clientID, presence } = event.value;
const [from, to] = doc.getRoot().content.posRangeToIndexRange(presence.selection);

let fromPos = editor.posFromIndex(from);
let toPos = editor.posFromIndex(to);
updateCursor(clientID, toPos);
if (from > to) {
[toPos, fromPos] = [fromPos, toPos];
}
updateLine(clientID, fromPos, toPos);
}
});

Expand Down
Loading
Loading