mirror of
https://github.com/outline/outline.git
synced 2026-11-29 00:29:36 +03:00
fix: Warn before leaving a document with unsynced edits (#13738)
* fix: Warn before leaving a document with unsynced edits * refactor: Move unsynced change tracking into CollaborationProvider * refactor: Move collaboration event types next to CollaborationProvider * fix: Pending changes stuck after the collaboration connection is restored * chore: Log collaboration sync state changes in development * fix: Report lost local persistence in the leave prompt * fix: Stop local persistence when the initial read fails * fix: Stop local persistence when a write aborts * Remove test
This commit is contained in:
1 parent
d281e991d9
commit
fe409306f4
10 files changed
+484
-73
No files matched your search
@@ -8,6 +8,7 @@ import type { TextStats } from "~/hooks/useTextStats";
|
||||
import { getTextStats } from "~/hooks/useTextStats";
|
||||
import type Document from "~/models/Document";
|
||||
import type { Editor } from "~/editor";
|
||||
import type { ConnectionStatus } from "~/utils/multiplayer/CollaborationProvider";
|
||||
|
||||
class DocumentContext {
|
||||
/** The current document */
|
||||
@@ -33,6 +34,22 @@ class DocumentContext {
|
||||
@observable
|
||||
headings: Heading[] = [];
|
||||
|
||||
/** The connection status of the collaboration provider */
|
||||
@observable
|
||||
multiplayerStatus: ConnectionStatus | undefined = undefined;
|
||||
|
||||
/** The close code of the collaboration connection, when it was closed with an error */
|
||||
@observable
|
||||
multiplayerErrorCode?: number = undefined;
|
||||
|
||||
/** Whether there are local edits the collaboration server has not confirmed */
|
||||
@observable
|
||||
hasUnsyncedChanges = false;
|
||||
|
||||
/** Whether edits are also stored in the browser, so they survive a reload */
|
||||
@observable
|
||||
hasLocalPersistence = true;
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
}
|
||||
@@ -82,6 +99,21 @@ class DocumentContext {
|
||||
this.focusedCommentId = commentId;
|
||||
};
|
||||
|
||||
@action
|
||||
setMultiplayerStatus = (status: ConnectionStatus, errorCode?: number) => {
|
||||
this.multiplayerStatus = status;
|
||||
this.multiplayerErrorCode = errorCode;
|
||||
};
|
||||
|
||||
@action
|
||||
setMultiplayerSyncState = (
|
||||
hasUnsyncedChanges: boolean,
|
||||
hasLocalPersistence: boolean
|
||||
) => {
|
||||
this.hasUnsyncedChanges = hasUnsyncedChanges;
|
||||
this.hasLocalPersistence = hasLocalPersistence;
|
||||
};
|
||||
|
||||
@action
|
||||
updateState = () => {
|
||||
this.editorDoc = this.editor?.view.state.doc;
|
||||
|
||||
@@ -10,13 +10,13 @@ import {
|
||||
EditorUpdateError,
|
||||
TooManyConnections,
|
||||
} from "@shared/collaboration/CloseEvents";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import Fade from "~/components/Fade";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import useStores from "~/hooks/useStores";
|
||||
|
||||
function ConnectionStatus() {
|
||||
const { ui } = useStores();
|
||||
const { multiplayerStatus, multiplayerErrorCode } = useDocumentContext();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const codeToMessage = {
|
||||
@@ -44,12 +44,12 @@ function ConnectionStatus() {
|
||||
},
|
||||
};
|
||||
|
||||
const message = ui.multiplayerErrorCode
|
||||
? codeToMessage[ui.multiplayerErrorCode as keyof typeof codeToMessage]
|
||||
const message = multiplayerErrorCode
|
||||
? codeToMessage[multiplayerErrorCode as keyof typeof codeToMessage]
|
||||
: undefined;
|
||||
|
||||
return ui.multiplayerStatus === "connecting" ||
|
||||
ui.multiplayerStatus === "disconnected" ? (
|
||||
return multiplayerStatus === "connecting" ||
|
||||
multiplayerStatus === "disconnected" ? (
|
||||
<Tooltip
|
||||
content={
|
||||
message ? (
|
||||
|
||||
@@ -14,6 +14,7 @@ import { IconType, TOCPosition, TeamPreference } from "@shared/types";
|
||||
import { determineIconType } from "@shared/utils/icon";
|
||||
import type Document from "~/models/Document";
|
||||
import type Revision from "~/models/Revision";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import DocumentMove from "~/components/DocumentExplorer/DocumentMove";
|
||||
import DocumentPublish from "~/scenes/DocumentPublish";
|
||||
import ErrorBoundary from "~/components/ErrorBoundary";
|
||||
@@ -24,6 +25,7 @@ import RegisterKeyDown from "~/components/RegisterKeyDown";
|
||||
import { MeasuredContainer } from "~/components/MeasuredContainer";
|
||||
import type { Editor as TEditor } from "~/editor";
|
||||
import type { Properties } from "~/types";
|
||||
import useEventListener from "~/hooks/useEventListener";
|
||||
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -83,6 +85,7 @@ function DocumentScene({
|
||||
children,
|
||||
}: Props) {
|
||||
const { auth, ui, dialogs } = useStores();
|
||||
const documentContext = useDocumentContext();
|
||||
const isMobile = useMobile();
|
||||
const { t } = useTranslation();
|
||||
const history = useHistory();
|
||||
@@ -319,6 +322,35 @@ function DocumentScene({
|
||||
const multiplayerEditor =
|
||||
!document.isArchived && !document.isDeleted && !revision && !isShare;
|
||||
|
||||
const hasUnsyncedChanges = !readOnly && documentContext.hasUnsyncedChanges;
|
||||
|
||||
const handleBlockNavigation = () => {
|
||||
if (hasUnsyncedChanges) {
|
||||
return documentContext.hasLocalPersistence
|
||||
? t(
|
||||
`Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?`
|
||||
)
|
||||
: t(
|
||||
`Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?`
|
||||
);
|
||||
}
|
||||
if (isUploading && !isEditorDirty) {
|
||||
return t(
|
||||
`Images are still uploading.\nAre you sure you want to discard them?`
|
||||
);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleUnload = (event: BeforeUnloadEvent) => {
|
||||
if (hasUnsyncedChanges) {
|
||||
event.preventDefault();
|
||||
event.returnValue = "";
|
||||
}
|
||||
};
|
||||
|
||||
useEventListener("beforeunload", handleUnload);
|
||||
|
||||
const hasEmojiInTitle = determineIconType(document.icon) === IconType.Emoji;
|
||||
const pageTitle = hasEmojiInTitle
|
||||
? document.titleWithDefault.replace(document.icon!, "")
|
||||
@@ -359,10 +391,8 @@ function DocumentScene({
|
||||
<Container column auto>
|
||||
{!readOnly && (
|
||||
<Prompt
|
||||
when={isUploading && !isEditorDirty}
|
||||
message={t(
|
||||
`Images are still uploading.\nAre you sure you want to discard them?`
|
||||
)}
|
||||
when={(isUploading && !isEditorDirty) || hasUnsyncedChanges}
|
||||
message={handleBlockNavigation}
|
||||
/>
|
||||
)}
|
||||
{isShare ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { HocuspocusProvider, WebSocketStatus } from "@hocuspocus/provider";
|
||||
import { WebSocketStatus } from "@hocuspocus/provider";
|
||||
import { throttle } from "es-toolkit/compat";
|
||||
import { Node as ProsemirrorNode } from "prosemirror-model";
|
||||
import {
|
||||
@@ -20,6 +20,7 @@ import EDITOR_VERSION from "@shared/editor/version";
|
||||
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
|
||||
import { supportsPassiveListener } from "@shared/utils/browser";
|
||||
import type { Props as EditorProps } from "~/components/Editor";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import Editor from "~/components/Editor";
|
||||
import type { Editor as SharedEditor } from "~/editor";
|
||||
import MultiplayerExtension from "~/editor/extensions/Multiplayer";
|
||||
@@ -30,8 +31,13 @@ import useIsMounted from "~/hooks/useIsMounted";
|
||||
import usePageVisibility from "~/hooks/usePageVisibility";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import type { AwarenessChangeEvent } from "~/types";
|
||||
import { IndexeddbPersistence } from "~/utils/IndexeddbPersistence";
|
||||
import Logger from "~/utils/Logger";
|
||||
import {
|
||||
CollaborationProvider,
|
||||
type ConnectionMessageEvent,
|
||||
type ConnectionStatusEvent,
|
||||
} from "~/utils/multiplayer/CollaborationProvider";
|
||||
import { IndexeddbPersistence } from "~/utils/multiplayer/IndexeddbPersistence";
|
||||
import { homePath } from "~/utils/routeHelpers";
|
||||
import { sleep } from "@shared/utils/timers";
|
||||
|
||||
@@ -40,21 +46,6 @@ type Props = EditorProps & {
|
||||
onSynced?: () => Promise<void>;
|
||||
};
|
||||
|
||||
export type ConnectionStatus =
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "disconnected"
|
||||
| void;
|
||||
|
||||
type ConnectionStatusEvent = { status: ConnectionStatus };
|
||||
|
||||
type MessageEvent = {
|
||||
message: string;
|
||||
event: Event & {
|
||||
code?: number;
|
||||
};
|
||||
};
|
||||
|
||||
function MultiplayerEditor(
|
||||
{ onSynced, ...props }: Props,
|
||||
ref: ForwardedRef<SharedEditor>
|
||||
@@ -65,9 +56,10 @@ function MultiplayerEditor(
|
||||
const currentUser = useCurrentUser();
|
||||
const retryCount = useRef(0);
|
||||
const { presence, auth, ui } = useStores();
|
||||
const documentContext = useDocumentContext();
|
||||
const [editorVersionBehind, setEditorVersionBehind] = useState(false);
|
||||
const [showCursorNames, setShowCursorNames] = useState(false);
|
||||
const [remoteProvider, setRemoteProvider] = useState<HocuspocusProvider>();
|
||||
const [remoteProvider, setRemoteProvider] = useState<CollaborationProvider>();
|
||||
const [hasLocalPersistence, setHasLocalPersistence] = useState(true);
|
||||
const [isLocalSynced, setLocalSynced] = useState(false);
|
||||
const [isRemoteSynced, setRemoteSynced] = useState(false);
|
||||
@@ -96,7 +88,7 @@ function MultiplayerEditor(
|
||||
setHasLocalPersistence(false);
|
||||
}
|
||||
|
||||
const provider = new HocuspocusProvider({
|
||||
const provider = new CollaborationProvider({
|
||||
parameters: {
|
||||
editorVersion: EDITOR_VERSION,
|
||||
},
|
||||
@@ -104,6 +96,7 @@ function MultiplayerEditor(
|
||||
name,
|
||||
document: ydoc,
|
||||
token,
|
||||
localProvider,
|
||||
});
|
||||
|
||||
const syncScrollPosition = throttle(() => {
|
||||
@@ -175,6 +168,17 @@ function MultiplayerEditor(
|
||||
};
|
||||
|
||||
provider.on("awarenessChange", showCursorNames);
|
||||
|
||||
const syncState = () => {
|
||||
documentContext.setMultiplayerSyncState(
|
||||
provider.hasPendingChanges,
|
||||
provider.hasLocalPersistence
|
||||
);
|
||||
};
|
||||
|
||||
provider.on("syncStateChange", syncState);
|
||||
syncState();
|
||||
|
||||
localProvider?.whenSynced
|
||||
.then(() => {
|
||||
if (!isActive || !localProvider.synced) {
|
||||
@@ -198,14 +202,14 @@ function MultiplayerEditor(
|
||||
retryCount.current = 0;
|
||||
});
|
||||
|
||||
provider.on("close", (ev: MessageEvent) => {
|
||||
provider.on("close", (ev: ConnectionMessageEvent) => {
|
||||
if ("code" in ev.event) {
|
||||
// Note other close code are handled internally by the library
|
||||
if (ev.event.code === EditorUpdateError.code) {
|
||||
provider.shouldConnect = false;
|
||||
}
|
||||
|
||||
ui.setMultiplayerStatus("disconnected", ev.event.code);
|
||||
documentContext.setMultiplayerStatus("disconnected", ev.event.code);
|
||||
|
||||
if (ev.event.code === EditorUpdateError.code) {
|
||||
setEditorVersionBehind(true);
|
||||
@@ -214,15 +218,15 @@ function MultiplayerEditor(
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
provider.on("close", (ev: MessageEvent) =>
|
||||
provider.on("close", (ev: ConnectionMessageEvent) =>
|
||||
Logger.debug("collaboration", "close", ev)
|
||||
);
|
||||
provider.on("message", (ev: MessageEvent) =>
|
||||
provider.on("message", (ev: ConnectionMessageEvent) =>
|
||||
Logger.debug("collaboration", "incoming", {
|
||||
message: ev.message,
|
||||
})
|
||||
);
|
||||
provider.on("outgoingMessage", (ev: MessageEvent) =>
|
||||
provider.on("outgoingMessage", (ev: ConnectionMessageEvent) =>
|
||||
Logger.debug("collaboration", "outgoing", {
|
||||
message: ev.message,
|
||||
})
|
||||
@@ -230,8 +234,8 @@ function MultiplayerEditor(
|
||||
}
|
||||
|
||||
provider.on("status", (ev: ConnectionStatusEvent) => {
|
||||
if (ui.multiplayerStatus !== ev.status) {
|
||||
ui.setMultiplayerStatus(ev.status, undefined);
|
||||
if (documentContext.multiplayerStatus !== ev.status) {
|
||||
documentContext.setMultiplayerStatus(ev.status, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -245,7 +249,8 @@ function MultiplayerEditor(
|
||||
provider?.destroy();
|
||||
void localProvider?.destroy();
|
||||
setRemoteProvider(undefined);
|
||||
ui.setMultiplayerStatus(undefined, undefined);
|
||||
documentContext.setMultiplayerStatus(undefined, undefined);
|
||||
documentContext.setMultiplayerSyncState(false, true);
|
||||
};
|
||||
// `token` is intentionally omitted, it is only read when establishing the
|
||||
// connection and a refreshed token must not tear down the provider.
|
||||
@@ -255,6 +260,7 @@ function MultiplayerEditor(
|
||||
t,
|
||||
documentId,
|
||||
ui,
|
||||
documentContext,
|
||||
presence,
|
||||
ydoc,
|
||||
currentUser.id,
|
||||
|
||||
@@ -9,7 +9,6 @@ import Storage from "@shared/utils/Storage";
|
||||
import Document from "~/models/Document";
|
||||
import type Model from "~/models/base/Model";
|
||||
import Collection from "~/models/Collection";
|
||||
import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor";
|
||||
import type { SplitViewPane } from "~/utils/splitView";
|
||||
import { isTruthyQueryValue } from "~/utils/urls";
|
||||
import { startViewTransition } from "~/utils/viewTransition";
|
||||
@@ -110,11 +109,6 @@ class UiStore {
|
||||
@observable
|
||||
sidebarIsResizing = false;
|
||||
|
||||
@observable
|
||||
multiplayerStatus: ConnectionStatus | undefined = undefined;
|
||||
|
||||
@observable
|
||||
multiplayerErrorCode?: number = undefined;
|
||||
@observable
|
||||
debugSafeArea = false;
|
||||
|
||||
@@ -359,15 +353,6 @@ class UiStore {
|
||||
}
|
||||
};
|
||||
|
||||
@action
|
||||
setMultiplayerStatus = (
|
||||
status: ConnectionStatus,
|
||||
errorCode?: number
|
||||
): void => {
|
||||
this.multiplayerStatus = status;
|
||||
this.multiplayerErrorCode = errorCode;
|
||||
};
|
||||
|
||||
@action
|
||||
setSidebarResizing = (sidebarIsResizing: boolean): void => {
|
||||
this.sidebarIsResizing = sidebarIsResizing;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import * as Y from "yjs";
|
||||
import {
|
||||
CollaborationProvider,
|
||||
type SyncStateEvent,
|
||||
} from "./CollaborationProvider";
|
||||
|
||||
describe("CollaborationProvider", () => {
|
||||
let doc: Y.Doc;
|
||||
let provider: CollaborationProvider;
|
||||
let events: SyncStateEvent[];
|
||||
|
||||
const edit = (origin?: unknown) => {
|
||||
doc.transact(() => doc.getText("default").insert(0, "a"), origin);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
doc = new Y.Doc();
|
||||
events = [];
|
||||
provider = new CollaborationProvider({
|
||||
url: "ws://localhost",
|
||||
name: "test",
|
||||
document: doc,
|
||||
connect: false,
|
||||
});
|
||||
provider.on("syncStateChange", (event: SyncStateEvent) => {
|
||||
events.push(event);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
provider.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("starts without pending changes", () => {
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
expect(provider.hasLocalPersistence).toBe(false);
|
||||
});
|
||||
|
||||
it("reports an edit made while disconnected immediately", () => {
|
||||
edit();
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(true);
|
||||
expect(events).toEqual([
|
||||
{ hasUnsyncedChanges: true, hasLocalPersistence: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores updates that came from the provider itself", () => {
|
||||
edit(provider);
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for the grace period while connected", () => {
|
||||
provider.synced = true;
|
||||
edit();
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
|
||||
vi.advanceTimersByTime(2000);
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(true);
|
||||
expect(events).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("clears pending changes once the server confirms a full sync", () => {
|
||||
edit();
|
||||
edit();
|
||||
expect(provider.hasPendingChanges).toBe(true);
|
||||
|
||||
provider.synced = true;
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
expect(events.at(-1)).toEqual({
|
||||
hasUnsyncedChanges: false,
|
||||
hasLocalPersistence: false,
|
||||
});
|
||||
|
||||
vi.advanceTimersByTime(2000);
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps pending changes while the connection is down", () => {
|
||||
provider.synced = true;
|
||||
edit();
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(provider.hasPendingChanges).toBe(true);
|
||||
|
||||
provider.synced = false;
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(true);
|
||||
expect(events).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reports when local persistence stops", () => {
|
||||
provider.destroy();
|
||||
const listeners = new Set<() => void>();
|
||||
const localProvider = {
|
||||
stopped: false,
|
||||
onStop: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
};
|
||||
provider = new CollaborationProvider({
|
||||
url: "ws://localhost",
|
||||
name: "test",
|
||||
document: doc,
|
||||
connect: false,
|
||||
localProvider,
|
||||
});
|
||||
provider.on("syncStateChange", (event: SyncStateEvent) => {
|
||||
events.push(event);
|
||||
});
|
||||
expect(provider.hasLocalPersistence).toBe(true);
|
||||
|
||||
edit();
|
||||
expect(events.at(-1)).toEqual({
|
||||
hasUnsyncedChanges: true,
|
||||
hasLocalPersistence: true,
|
||||
});
|
||||
|
||||
listeners.forEach((listener) => listener());
|
||||
expect(provider.hasLocalPersistence).toBe(false);
|
||||
expect(events.at(-1)).toEqual({
|
||||
hasUnsyncedChanges: true,
|
||||
hasLocalPersistence: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not report after being destroyed", () => {
|
||||
provider.synced = true;
|
||||
edit();
|
||||
provider.destroy();
|
||||
|
||||
vi.advanceTimersByTime(2000);
|
||||
|
||||
expect(provider.hasPendingChanges).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import {
|
||||
HocuspocusProvider,
|
||||
type HocuspocusProviderConfiguration,
|
||||
} from "@hocuspocus/provider";
|
||||
import { Second } from "@shared/utils/time";
|
||||
import Logger from "~/utils/Logger";
|
||||
import type { IndexeddbPersistence } from "./IndexeddbPersistence";
|
||||
|
||||
/** How long a local change may await the server echo before it is unsynced. */
|
||||
const unsyncedGracePeriod = 2 * Second.ms;
|
||||
|
||||
/** The part of local persistence the provider relies on. */
|
||||
type LocalProvider = Pick<IndexeddbPersistence, "stopped" | "onStop">;
|
||||
|
||||
export type CollaborationProviderConfiguration =
|
||||
HocuspocusProviderConfiguration & {
|
||||
/** Local persistence for the same document, if available. */
|
||||
localProvider?: LocalProvider;
|
||||
};
|
||||
|
||||
/** The state of the connection to the collaboration server. */
|
||||
export type ConnectionStatus =
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "disconnected"
|
||||
| void;
|
||||
|
||||
/** Emitted when the connection status changes. */
|
||||
export interface ConnectionStatusEvent {
|
||||
status: ConnectionStatus;
|
||||
}
|
||||
|
||||
/** Emitted for incoming, outgoing and close messages of the connection. */
|
||||
export interface ConnectionMessageEvent {
|
||||
message: string;
|
||||
event: Event & {
|
||||
code?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SyncStateEvent {
|
||||
/** Whether there are local edits the server has not confirmed. */
|
||||
hasUnsyncedChanges: boolean;
|
||||
/** Whether edits are also stored in the browser, so they survive a reload. */
|
||||
hasLocalPersistence: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Hocuspocus provider that also tracks whether local edits have reached the
|
||||
* server, and emits a "syncStateChange" event whenever that changes.
|
||||
*/
|
||||
export class CollaborationProvider extends HocuspocusProvider {
|
||||
constructor(configuration: CollaborationProviderConfiguration) {
|
||||
const { localProvider, ...rest } = configuration;
|
||||
super(rest);
|
||||
this.localProvider = localProvider;
|
||||
this.localPersistence = !!localProvider && !localProvider.stopped;
|
||||
this.stopLocalProviderListener = localProvider?.onStop(() =>
|
||||
this.setLocalPersistence(false)
|
||||
);
|
||||
|
||||
this.document.on("update", this.handleDocumentUpdate);
|
||||
this.on("synced", this.handleSynced);
|
||||
this.updateSyncState();
|
||||
}
|
||||
|
||||
/** Whether there are local edits the server has not confirmed. */
|
||||
get hasPendingChanges(): boolean {
|
||||
return this.syncState.hasUnsyncedChanges;
|
||||
}
|
||||
|
||||
/** Whether edits are also stored in the browser, so they survive a reload. */
|
||||
get hasLocalPersistence(): boolean {
|
||||
return this.localPersistence;
|
||||
}
|
||||
|
||||
onMessage(event: Parameters<HocuspocusProvider["onMessage"]>[0]) {
|
||||
super.onMessage(event);
|
||||
this.updateSyncState();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.clearUnsyncedTimeout();
|
||||
this.stopLocalProviderListener?.();
|
||||
this.document.off("update", this.handleDocumentUpdate);
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
private localProvider?: LocalProvider;
|
||||
|
||||
private localPersistence: boolean;
|
||||
|
||||
private stopLocalProviderListener?: () => void;
|
||||
|
||||
/** The last state reported to listeners. */
|
||||
private syncState: SyncStateEvent = {
|
||||
hasUnsyncedChanges: false,
|
||||
hasLocalPersistence: true,
|
||||
};
|
||||
|
||||
/** Whether an edit was made since the server last confirmed a full sync. */
|
||||
private editedSinceSync = false;
|
||||
|
||||
private unsyncedTimeout?: ReturnType<typeof setTimeout>;
|
||||
|
||||
private handleDocumentUpdate = (_update: Uint8Array, origin: unknown) => {
|
||||
if (origin !== this && origin !== this.localProvider) {
|
||||
this.editedSinceSync = true;
|
||||
}
|
||||
this.updateSyncState();
|
||||
};
|
||||
|
||||
// The sync handshake delivers every local edit, so the inherited count only
|
||||
// covers edits made from here on. It would otherwise keep counting edits
|
||||
// made while reconnecting, which are never echoed individually.
|
||||
private handleSynced = ({ state }: { state: boolean }) => {
|
||||
Logger.debug("collaboration", "synced", {
|
||||
state,
|
||||
unsyncedChanges: this.unsyncedChanges,
|
||||
editedSinceSync: this.editedSinceSync,
|
||||
});
|
||||
if (state) {
|
||||
this.unsyncedChanges = 0;
|
||||
}
|
||||
this.updateSyncState();
|
||||
};
|
||||
|
||||
// While synced the inherited count is reliable, as the server echoes every
|
||||
// update back. Otherwise fall back to whether an edit was made since the
|
||||
// last confirmed sync.
|
||||
private updateSyncState = () => {
|
||||
if (this.synced && !this.hasUnsyncedChanges) {
|
||||
this.editedSinceSync = false;
|
||||
}
|
||||
const hasUnsyncedChanges = this.synced
|
||||
? this.hasUnsyncedChanges
|
||||
: this.editedSinceSync;
|
||||
|
||||
// A connected server echoes each update within milliseconds, so only
|
||||
// report changes as unsynced once they have been pending for a while.
|
||||
if (hasUnsyncedChanges && this.synced) {
|
||||
this.unsyncedTimeout ??= setTimeout(() => {
|
||||
this.unsyncedTimeout = undefined;
|
||||
this.emitSyncState(true);
|
||||
}, unsyncedGracePeriod);
|
||||
return;
|
||||
}
|
||||
this.clearUnsyncedTimeout();
|
||||
this.emitSyncState(hasUnsyncedChanges);
|
||||
};
|
||||
|
||||
private emitSyncState(hasUnsyncedChanges: boolean) {
|
||||
const next: SyncStateEvent = {
|
||||
hasUnsyncedChanges,
|
||||
hasLocalPersistence: this.localPersistence,
|
||||
};
|
||||
if (
|
||||
next.hasUnsyncedChanges === this.syncState.hasUnsyncedChanges &&
|
||||
next.hasLocalPersistence === this.syncState.hasLocalPersistence
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.syncState = next;
|
||||
Logger.debug("collaboration", "sync state", next);
|
||||
this.emit("syncStateChange", next);
|
||||
}
|
||||
|
||||
private setLocalPersistence(value: boolean) {
|
||||
this.localPersistence = value;
|
||||
this.updateSyncState();
|
||||
}
|
||||
|
||||
private clearUnsyncedTimeout() {
|
||||
if (this.unsyncedTimeout !== undefined) {
|
||||
clearTimeout(this.unsyncedTimeout);
|
||||
this.unsyncedTimeout = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Y from "yjs";
|
||||
import Logger from "~/utils/Logger";
|
||||
|
||||
/**
|
||||
* Persists a Y.Doc to IndexedDB so documents can be loaded instantly from the
|
||||
@@ -21,6 +22,12 @@ export class IndexeddbPersistence {
|
||||
/** Whether the state stored in the database has been applied to the document. */
|
||||
public synced = false;
|
||||
|
||||
/**
|
||||
* Whether persisting has stopped for good, because the database could not
|
||||
* be opened or the connection was closed underneath us.
|
||||
*/
|
||||
public stopped = false;
|
||||
|
||||
/**
|
||||
* Resolves once the state stored in the database has been applied to the
|
||||
* document, or immediately if the instance is destroyed beforehand – check
|
||||
@@ -47,10 +54,24 @@ export class IndexeddbPersistence {
|
||||
return this;
|
||||
});
|
||||
|
||||
this.whenSynced.catch((error) => this.stop(error));
|
||||
doc.on("update", this.handleDocUpdate);
|
||||
doc.on("destroy", this.destroy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a listener that is called once persisting stops, see `stopped`.
|
||||
*
|
||||
* @param listener the function to call.
|
||||
* @returns a function that removes the listener.
|
||||
*/
|
||||
public onStop(listener: () => void): () => void {
|
||||
this.stopListeners.add(listener);
|
||||
return () => {
|
||||
this.stopListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges all stored update rows into a single row containing the current
|
||||
* document state.
|
||||
@@ -99,6 +120,8 @@ export class IndexeddbPersistence {
|
||||
|
||||
private destroyed = false;
|
||||
|
||||
private stopListeners = new Set<() => void>();
|
||||
|
||||
/**
|
||||
* Number of stored updates after which they are merged into a single
|
||||
* database row containing the entire document state, keeping loads fast.
|
||||
@@ -119,7 +142,13 @@ export class IndexeddbPersistence {
|
||||
return;
|
||||
}
|
||||
|
||||
this.updatesStore(this.db).add(update);
|
||||
try {
|
||||
this.updatesStore(this.db).add(update);
|
||||
} catch (error) {
|
||||
// A throw here would break every later Y.Doc transaction.
|
||||
this.stop(error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (++this.dbsize >= this.preferredTrimSize) {
|
||||
if (this.storeTimeoutId !== undefined) {
|
||||
@@ -188,10 +217,28 @@ export class IndexeddbPersistence {
|
||||
}
|
||||
}
|
||||
|
||||
private stop(error: unknown) {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
this.stopped = true;
|
||||
this.db = null;
|
||||
|
||||
if (!this.destroyed) {
|
||||
Logger.warn("Local document persistence stopped", { error });
|
||||
}
|
||||
this.stopListeners.forEach((listener) => listener());
|
||||
this.stopListeners.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a read-write transaction on the updates store. Writes report
|
||||
* failures such as a full quota asynchronously by aborting the transaction.
|
||||
*/
|
||||
private updatesStore(db: IDBDatabase): IDBObjectStore {
|
||||
return db
|
||||
.transaction(updatesStoreName, "readwrite")
|
||||
.objectStore(updatesStoreName);
|
||||
const transaction = db.transaction(updatesStoreName, "readwrite");
|
||||
transaction.onabort = () => this.stop(transaction.error);
|
||||
return transaction.objectStore(updatesStoreName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -922,6 +922,8 @@
|
||||
"Edits you make will sync once you’re online": "Edits you make will sync once you’re online",
|
||||
"Offline": "Offline",
|
||||
"Document restored": "Document restored",
|
||||
"Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?": "Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?",
|
||||
"Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?": "Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?",
|
||||
"Images are still uploading.\nAre you sure you want to discard them?": "Images are still uploading.\nAre you sure you want to discard them?",
|
||||
"{{ count }} comment": "{{ count }} comment",
|
||||
"{{ count }} comment_plural": "{{ count }} comments",
|
||||
|
||||
@@ -14451,23 +14451,7 @@ __metadata:
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"markdown-it@npm:^14.0.0":
|
||||
version: 14.3.0
|
||||
resolution: "markdown-it@npm:14.3.0"
|
||||
dependencies:
|
||||
argparse: "npm:^2.0.1"
|
||||
entities: "npm:^4.5.0"
|
||||
linkify-it: "npm:^5.0.2"
|
||||
mdurl: "npm:^2.0.0"
|
||||
punycode.js: "npm:^2.3.1"
|
||||
uc.micro: "npm:^2.1.0"
|
||||
bin:
|
||||
markdown-it: bin/markdown-it.mjs
|
||||
checksum: 10c0/b2dea908968109d6e9088ac972254bca842157d85d2e6838d0eb263cd8106e7e6a72663b138366cc98f57441d9f3f2ebfb842bf7b2f9e1c13187ebe70e0af8f9
|
||||
languageName: node
|
||||
linkType: hard
|
||||
|
||||
"markdown-it@npm:^14.3.1":
|
||||
"markdown-it@npm:^14.0.0, markdown-it@npm:^14.3.1":
|
||||
version: 14.3.1
|
||||
resolution: "markdown-it@npm:14.3.1"
|
||||
dependencies:
|
||||
|
||||
Reference in new issue
Block a user