automerge / automerge-repo

MIT License
419 stars 43 forks source link

svelte: provide a way to await the document becoming ready #342

Open artm opened 2 months ago

artm commented 2 months ago

The automerge svelte store hides the doc handle so there is no way to do something like

<script>
    // automerge
    import { Repo } from "@automerge/automerge-repo";
    import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb";
    import { document, setContextRepo } from "@automerge/automerge-repo-svelte-store";
    // own stuff
    import ActualComponent from "$lib/components/ActualComponent.svelte";

    setContextRepo(
        new Repo({
            storage: new IndexedDBStorageAdapter(),
            network: [],
        }),
    );
    const doc = document( URL_GOT_ELSEWHERE );
</script>

<!-- wait for the document to become ready, imaginary method by analogy with DocHandle -->
{#await doc.whenReady()}
    <div>Loading...</div>
{:then _}
    <!-- ActualComponent may assume doc (the store) is ready and $doc is not undefined -->
    <ActualComponent {doc} />
{/await}

I'm not sure what makes sense API-wise, maybe just expose the doc handle on the object returned from document, so the first line would be something like:

{#await doc.handle().whenReady()}
artm commented 2 months ago

A workaround for now:

<script>
    // automerge
    import { Repo } from "@automerge/automerge-repo";
    import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb";
    import { document, setContextRepo } from "@automerge/automerge-repo-svelte-store";
    // own stuff
    import ActualComponent from "$lib/components/ActualComponent.svelte";

    setContextRepo(
        new Repo({
            storage: new IndexedDBStorageAdapter(),
            network: [],
        }),
    );
    const docHandle = repo.find( URL_GOT_ELSEWHERE );
</script>

{#await docHandle.whenReady()}
    <div>Loading...</div>
{:then _} <!-- the async value of whenReady doesn't matter -->
    <!-- I guess the documents are cached in the repo so now the docHandle inside the store will be ready right away -->
    {@const doc = document( URL_GOT_ELSEWHERE )}
    <!-- ActualComponent may assume doc (the store) is ready and $doc is not undefined -->
    <ActualComponent {doc} />
{/await}