@raster-app/react 0.2.1 → 0.3.0-canary-66199c2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -134,12 +134,18 @@ function Library() {
134
134
  | `useSignIn()` | Sign-in with Raster's device flow or an API key. |
135
135
  | `useOrganizations()` | The organizations the user can reach, in `data`. |
136
136
  | `useLibraries({ organizationId })` | An organization's libraries, in `data`, each with the user's `access`. |
137
- | `useAssets({ organizationId, libraryId })` | A library's `assets`, with `loadMore()`. |
137
+ | `useAssets({ organizationId, libraryId })` | A library's `assets` and `total`, with `loadMore()`. |
138
138
  | `useAssetSearch(scope, query)` | Search results, `hits` and `found`, as the user types. |
139
139
  | `useAssetUpload()` | `upload()` a file, then wait for Raster to process it. |
140
140
  | `usePromoteVariant()` | Make a variant its asset's default. |
141
141
  | `useRasterNavigation({ organizations })` | The open organization, library and asset, remembered between visits. |
142
142
 
143
+ `useAssets` pages as Raster's own grid does: it fetches the page after the last one shown ahead of
144
+ time, with its thumbnails, so `loadMore()` shows it at once. Call it as the grid nears its end.
145
+
146
+ The hooks run in React Native too, with the client a server would use (see the SDK's README).
147
+ `RasterPicker` and its stylesheet need a browser.
148
+
143
149
  `RasterProvider` takes a `client`, or a `config` to create one, and `state`, where navigation is
144
150
  remembered: `memoryStateStore()` by default, or `localStorageStateStore()`.
145
151
 
@@ -5,7 +5,12 @@ export type AssetsResource = {
5
5
  isLoading: boolean;
6
6
  error: RasterApiError | null;
7
7
  hasMore: boolean;
8
- /** Fetch the next page. A no-op while one is already in flight, at the end, or after a failure. */
8
+ /** Assets in the library, or null while Raster does not report it. */
9
+ total: number | null;
10
+ /**
11
+ * Show the next page: at once when it is already prefetched, else once it lands. A no-op at
12
+ * the end, after a failure, or while the page asked for is still in flight.
13
+ */
9
14
  loadMore: () => void;
10
15
  };
11
16
  /**
@@ -14,7 +19,8 @@ export type AssetsResource = {
14
19
  */
15
20
  export declare function usePrefetchAssets(): (organizationId: string, libraryId: string) => void;
16
21
  /**
17
- * A library's assets, paged.
22
+ * A library's assets, paged as Raster's own grid pages them: the page after the last one shown
23
+ * is fetched ahead, with its thumbnails, so `loadMore` shows it at once.
18
24
  *
19
25
  * Pass a null `libraryId` before a library is open; the hook then sits idle.
20
26
  */
@@ -1,17 +1,33 @@
1
1
  import { skipToken, useInfiniteQuery, useQueryClient, } from '@tanstack/react-query';
2
- import { useCallback } from 'react';
3
- import { ASSETS_PAGE_SIZE, listAssets, } from '@raster-app/sdk';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+ import { getThumbUrl, listAssetPage, } from '@raster-app/sdk';
4
4
  import { useRasterClient } from './context.js';
5
5
  import { rasterKeys } from './query-keys.js';
6
6
  import { useCredentialIdentity } from './use-session.js';
7
+ /** How long a fetched page is fresh, so a prefetched page is the one that mounts. */
8
+ const STALE_TIME_MS = 60 * 1000;
7
9
  /** A library can change between pages; an asset already shown is not shown twice. */
8
- function toAssets(data) {
9
- return Array.from(new Map(data.pages.flat().map((asset) => [asset.id, asset])).values());
10
+ function toAssets(pages) {
11
+ return Array.from(new Map(pages.flatMap((page) => page.assets).map((a) => [a.id, a])).values());
10
12
  }
11
- /** One page of a library, as the grid reads it and a hover warms it. */
13
+ /** Start loading each thumbnail, so a page paints at once when it is shown. Browsers only. */
14
+ function prefetchThumbs(assets) {
15
+ if (typeof Image !== 'function')
16
+ return;
17
+ for (const asset of assets) {
18
+ const src = getThumbUrl(asset);
19
+ if (src !== undefined)
20
+ new Image().src = src;
21
+ }
22
+ }
23
+ /** One page of a library, as the grid reads it and a hover warms it, with its thumbnails. */
12
24
  function listPage(client, organizationId, libraryId) {
13
25
  // `signal` aborts a page nobody wants any more, which would otherwise hold the connection pool.
14
- return ({ pageParam, signal }) => listAssets(client, { organizationId, libraryId, page: pageParam, signal });
26
+ return async ({ pageParam, signal }) => {
27
+ const page = await listAssetPage(client, { organizationId, libraryId, page: pageParam, signal });
28
+ prefetchThumbs(page.assets);
29
+ return page;
30
+ };
15
31
  }
16
32
  /**
17
33
  * Warm a library's first page, as a hover does before the click that opens it. A library already
@@ -29,11 +45,13 @@ export function usePrefetchAssets() {
29
45
  queryKey,
30
46
  queryFn: listPage(client, organizationId, libraryId),
31
47
  initialPageParam: 1,
48
+ staleTime: STALE_TIME_MS,
32
49
  });
33
50
  }, [client, queryClient, identity]);
34
51
  }
35
52
  /**
36
- * A library's assets, paged.
53
+ * A library's assets, paged as Raster's own grid pages them: the page after the last one shown
54
+ * is fetched ahead, with its thumbnails, so `loadMore` shows it at once.
37
55
  *
38
56
  * Pass a null `libraryId` before a library is open; the hook then sits idle.
39
57
  */
@@ -41,23 +59,47 @@ export function useAssets(options) {
41
59
  const { organizationId, libraryId } = options;
42
60
  const client = useRasterClient();
43
61
  const identity = useCredentialIdentity();
44
- const { data, error, isFetching, isError, hasNextPage, fetchNextPage } = useInfiniteQuery({
45
- queryKey: rasterKeys.assets(identity, organizationId, libraryId),
62
+ const queryKey = rasterKeys.assets(identity, organizationId, libraryId);
63
+ const { data, error, isFetching, isError, hasNextPage, isFetchingNextPage, fetchNextPage } = useInfiniteQuery({
64
+ queryKey,
46
65
  queryFn: organizationId === null || libraryId === null
47
66
  ? skipToken
48
67
  : listPage(client, organizationId, libraryId),
49
68
  initialPageParam: 1,
50
- getNextPageParam: (lastPage, pages) => lastPage.length === ASSETS_PAGE_SIZE ? pages.length + 1 : undefined,
51
- select: toAssets,
69
+ getNextPageParam: (lastPage, pages) => (lastPage.hasMore ? pages.length + 1 : undefined),
70
+ staleTime: STALE_TIME_MS,
52
71
  enabled: identity !== null && organizationId !== null && libraryId !== null,
53
72
  });
54
- // A failure also stops paging, rather than let a scroll observer retry it on every frame.
55
- const hasMore = hasNextPage && !isError;
56
- // Without `cancelRefetch: false`, a call while a page is in flight would abort it to ask again.
73
+ // How many pages are shown, per scope, so another library starts at its first page.
74
+ const scope = JSON.stringify(queryKey);
75
+ const [reveal, setReveal] = useState({ scope, pages: 1 });
76
+ const shown = reveal.scope === scope ? reveal.pages : 1;
77
+ const pages = data?.pages ?? [];
78
+ // Keep one page ahead of the ones shown. A failure stops it, rather than retry every render.
79
+ const prefetch = hasNextPage && !isError && !isFetchingNextPage && pages.length <= shown;
80
+ useEffect(() => {
81
+ // Without `cancelRefetch: false`, a call while a page is in flight would abort it to ask again.
82
+ if (prefetch)
83
+ void fetchNextPage({ cancelRefetch: false });
84
+ }, [prefetch, fetchNextPage]);
85
+ // An empty last page, as a library whose size is a multiple of the page size ends with, is
86
+ // no more to show.
87
+ const hasMore = pages.slice(shown).some((page) => page.assets.length > 0) || (hasNextPage && !isError);
88
+ // From this render's count, so repeated calls before the next render show one page, not
89
+ // several, and never more than one past those loaded.
90
+ const next = Math.min(shown + 1, pages.length + 1);
57
91
  const loadMore = useCallback(() => {
58
92
  if (hasMore)
59
- void fetchNextPage({ cancelRefetch: false });
60
- }, [hasMore, fetchNextPage]);
61
- return { assets: data ?? null, isLoading: isFetching, error, hasMore, loadMore };
93
+ setReveal({ scope, pages: next });
94
+ }, [hasMore, scope, next]);
95
+ return {
96
+ assets: data === undefined ? null : toAssets(pages.slice(0, shown)),
97
+ // A page fetched ahead is not loading anything the grid waits on.
98
+ isLoading: isFetching && (data === undefined || shown > pages.length),
99
+ error,
100
+ hasMore,
101
+ total: pages[0]?.total ?? null,
102
+ loadMore,
103
+ };
62
104
  }
63
105
  //# sourceMappingURL=use-assets.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-assets.js","sourceRoot":"","sources":["../src/use-assets.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,SAAS,EACT,gBAAgB,EAChB,cAAc,GACd,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAEnC,OAAO,EAIN,gBAAgB,EAChB,UAAU,GACV,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,UAAU,EAAE,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AM,EAAE,IAAI,IAAI,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAA;AACjF,CAAC","sourcesContent":["import {\n\ttype InfiniteData,\n\ttype QueryFunctionContext,\n\ttype QueryKey,\n\tskipToken,\n\tuseInfiniteQuery,\n\tuseQueryClient,\n} from '@tanstack/react-query'\nimport { useCallback } from 'react'\n\nimport {\n\ttype Asset,\n\ttype RasterApiError,\n\ttype RasterClient,\n\tASSETS_PAGE_SIZE,\n\tlistAssets,\n} from '@raster-app/sdk'\n\nimport { useRasterClient } from './context.js'\nimport { rasterKeys } from './query-keys.js'\nimport { useCredentialIdentity } from './use-session.js'\n\nexport type AssetsResource = {\n\t/** Null until the first page lands. */\n\tassets: Array<Asset> | null\n\tisLoading: boolean\n\terror: RasterApiError | null\n\thasMore: boolean\n\t/** Fetch the next page. A no-op while one is already in flight, at the end, or after a failure. */\n\tloadMore: () => void\n}\n\n/** A library can change between pages; an asset already shown is not shown twice. */\nfunction toAssets(data: InfiniteData<Array<Asset>>): Array<Asset> {\n\treturn Array.from(new Map(data.pages.flat().map((asset) => [asset.id, asset])).values())\n}\n\n/** One page of a library, as the grid reads it and a hover warms it. */\nfunction listPage(client: RasterClient, organizationId: string, libraryId: string) {\n\t// `signal` aborts a page nobody wants any more, which would otherwise hold the connection pool.\n\treturn ({ pageParam, signal }: QueryFunctionContext<QueryKey, number>) =>\n\t\tlistAssets(client, { organizationId, libraryId, page: pageParam, signal })\n}\n\n/**\n * Warm a library's first page, as a hover does before the click that opens it. A library already\n * cached is left alone: its grid paints on the click and refreshes itself.\n */\nexport function usePrefetchAssets(): (organizationId: string, libraryId: string) => void {\n\tconst client = useRasterClient()\n\tconst queryClient = useQueryClient()\n\tconst identity = useCredentialIdentity()\n\n\treturn useCallback(\n\t\t(organizationId, libraryId) => {\n\t\t\tconst queryKey = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\tif (identity === null || queryClient.getQueryData(queryKey) !== undefined) return\n\t\t\tvoid queryClient.prefetchInfiniteQuery({\n\t\t\t\tqueryKey,\n\t\t\t\tqueryFn: listPage(client, organizationId, libraryId),\n\t\t\t\tinitialPageParam: 1,\n\t\t\t})\n\t\t},\n\t\t[client, queryClient, identity]\n\t)\n}\n\n/**\n * A library's assets, paged.\n *\n * Pass a null `libraryId` before a library is open; the hook then sits idle.\n */\nexport function useAssets(options: {\n\torganizationId: string | null\n\tlibraryId: string | null\n}): AssetsResource {\n\tconst { organizationId, libraryId } = options\n\n\tconst client = useRasterClient()\n\n\tconst identity = useCredentialIdentity()\n\tconst { data, error, isFetching, isError, hasNextPage, fetchNextPage } = useInfiniteQuery<\n\t\tArray<Asset>,\n\t\tRasterApiError,\n\t\tArray<Asset>,\n\t\tQueryKey,\n\t\tnumber\n\t>({\n\t\tqueryKey: rasterKeys.assets(identity, organizationId, libraryId),\n\t\tqueryFn:\n\t\t\torganizationId === null || libraryId === null\n\t\t\t\t? skipToken\n\t\t\t\t: listPage(client, organizationId, libraryId),\n\t\tinitialPageParam: 1,\n\t\tgetNextPageParam: (lastPage, pages) =>\n\t\t\tlastPage.length === ASSETS_PAGE_SIZE ? pages.length + 1 : undefined,\n\t\tselect: toAssets,\n\t\tenabled: identity !== null && organizationId !== null && libraryId !== null,\n\t})\n\n\t// A failure also stops paging, rather than let a scroll observer retry it on every frame.\n\tconst hasMore = hasNextPage && !isError\n\n\t// Without `cancelRefetch: false`, a call while a page is in flight would abort it to ask again.\n\tconst loadMore = useCallback(() => {\n\t\tif (hasMore) void fetchNextPage({ cancelRefetch: false })\n\t}, [hasMore, fetchNextPage])\n\n\treturn { assets: data ?? null, isLoading: isFetching, error, hasMore, loadMore }\n}\n"]}
1
+ {"version":3,"file":"use-assets.js","sourceRoot":"","sources":["../src/use-assets.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,SAAS,EACT,gBAAgB,EAChB,cAAc,GACd,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,WAA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O,GACZ,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,IAAI,CAAC,OAAO,CAAC,CAAA;IAEvF,wFAAwF;IACxF,sDAAsD;IACtD,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IAClD,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE;QACjC,IAAI,OAAO;YAAE,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;IAC/C,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;IAE1B,OAAO;QACN,MAAM,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QACnE,kEAAkE;QAClE,SAAS,EAAE,UAAU,IAAI,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC;QACrE,KAAK;QACL,OAAO;QACP,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,IAAI;QAC9B,QAAQ;KACR,CAAA;AACF,CAAC","sourcesContent":["import {\n\ttype InfiniteData,\n\ttype QueryFunctionContext,\n\ttype QueryKey,\n\tskipToken,\n\tuseInfiniteQuery,\n\tuseQueryClient,\n} from '@tanstack/react-query'\nimport { useCallback, useEffect, useState } from 'react'\n\nimport {\n\ttype Asset,\n\ttype AssetPage,\n\ttype RasterApiError,\n\ttype RasterClient,\n\tgetThumbUrl,\n\tlistAssetPage,\n} from '@raster-app/sdk'\n\nimport { useRasterClient } from './context.js'\nimport { rasterKeys } from './query-keys.js'\nimport { useCredentialIdentity } from './use-session.js'\n\nexport type AssetsResource = {\n\t/** Null until the first page lands. */\n\tassets: Array<Asset> | null\n\tisLoading: boolean\n\terror: RasterApiError | null\n\thasMore: boolean\n\t/** Assets in the library, or null while Raster does not report it. */\n\ttotal: number | null\n\t/**\n\t * Show the next page: at once when it is already prefetched, else once it lands. A no-op at\n\t * the end, after a failure, or while the page asked for is still in flight.\n\t */\n\tloadMore: () => void\n}\n\n/** How long a fetched page is fresh, so a prefetched page is the one that mounts. */\nconst STALE_TIME_MS = 60 * 1000\n\n/** A library can change between pages; an asset already shown is not shown twice. */\nfunction toAssets(pages: Array<AssetPage>): Array<Asset> {\n\treturn Array.from(new Map(pages.flatMap((page) => page.assets).map((a) => [a.id, a])).values())\n}\n\n/** Start loading each thumbnail, so a page paints at once when it is shown. Browsers only. */\nfunction prefetchThumbs(assets: Array<Asset>): void {\n\tif (typeof Image !== 'function') return\n\tfor (const asset of assets) {\n\t\tconst src = getThumbUrl(asset)\n\t\tif (src !== undefined) new Image().src = src\n\t}\n}\n\n/** One page of a library, as the grid reads it and a hover warms it, with its thumbnails. */\nfunction listPage(client: RasterClient, organizationId: string, libraryId: string) {\n\t// `signal` aborts a page nobody wants any more, which would otherwise hold the connection pool.\n\treturn async ({ pageParam, signal }: QueryFunctionContext<QueryKey, number>) => {\n\t\tconst page = await listAssetPage(client, { organizationId, libraryId, page: pageParam, signal })\n\t\tprefetchThumbs(page.assets)\n\t\treturn page\n\t}\n}\n\n/**\n * Warm a library's first page, as a hover does before the click that opens it. A library already\n * cached is left alone: its grid paints on the click and refreshes itself.\n */\nexport function usePrefetchAssets(): (organizationId: string, libraryId: string) => void {\n\tconst client = useRasterClient()\n\tconst queryClient = useQueryClient()\n\tconst identity = useCredentialIdentity()\n\n\treturn useCallback(\n\t\t(organizationId, libraryId) => {\n\t\t\tconst queryKey = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\tif (identity === null || queryClient.getQueryData(queryKey) !== undefined) return\n\t\t\tvoid queryClient.prefetchInfiniteQuery({\n\t\t\t\tqueryKey,\n\t\t\t\tqueryFn: listPage(client, organizationId, libraryId),\n\t\t\t\tinitialPageParam: 1,\n\t\t\t\tstaleTime: STALE_TIME_MS,\n\t\t\t})\n\t\t},\n\t\t[client, queryClient, identity]\n\t)\n}\n\n/**\n * A library's assets, paged as Raster's own grid pages them: the page after the last one shown\n * is fetched ahead, with its thumbnails, so `loadMore` shows it at once.\n *\n * Pass a null `libraryId` before a library is open; the hook then sits idle.\n */\nexport function useAssets(options: {\n\torganizationId: string | null\n\tlibraryId: string | null\n}): AssetsResource {\n\tconst { organizationId, libraryId } = options\n\n\tconst client = useRasterClient()\n\n\tconst identity = useCredentialIdentity()\n\tconst queryKey = rasterKeys.assets(identity, organizationId, libraryId)\n\tconst { data, error, isFetching, isError, hasNextPage, isFetchingNextPage, fetchNextPage } =\n\t\tuseInfiniteQuery<AssetPage, RasterApiError, InfiniteData<AssetPage>, QueryKey, number>({\n\t\t\tqueryKey,\n\t\t\tqueryFn:\n\t\t\t\torganizationId === null || libraryId === null\n\t\t\t\t\t? skipToken\n\t\t\t\t\t: listPage(client, organizationId, libraryId),\n\t\t\tinitialPageParam: 1,\n\t\t\tgetNextPageParam: (lastPage, pages) => (lastPage.hasMore ? pages.length + 1 : undefined),\n\t\t\tstaleTime: STALE_TIME_MS,\n\t\t\tenabled: identity !== null && organizationId !== null && libraryId !== null,\n\t\t})\n\n\t// How many pages are shown, per scope, so another library starts at its first page.\n\tconst scope = JSON.stringify(queryKey)\n\tconst [reveal, setReveal] = useState({ scope, pages: 1 })\n\tconst shown = reveal.scope === scope ? reveal.pages : 1\n\tconst pages = data?.pages ?? []\n\n\t// Keep one page ahead of the ones shown. A failure stops it, rather than retry every render.\n\tconst prefetch = hasNextPage && !isError && !isFetchingNextPage && pages.length <= shown\n\tuseEffect(() => {\n\t\t// Without `cancelRefetch: false`, a call while a page is in flight would abort it to ask again.\n\t\tif (prefetch) void fetchNextPage({ cancelRefetch: false })\n\t}, [prefetch, fetchNextPage])\n\n\t// An empty last page, as a library whose size is a multiple of the page size ends with, is\n\t// no more to show.\n\tconst hasMore =\n\t\tpages.slice(shown).some((page) => page.assets.length > 0) || (hasNextPage && !isError)\n\n\t// From this render's count, so repeated calls before the next render show one page, not\n\t// several, and never more than one past those loaded.\n\tconst next = Math.min(shown + 1, pages.length + 1)\n\tconst loadMore = useCallback(() => {\n\t\tif (hasMore) setReveal({ scope, pages: next })\n\t}, [hasMore, scope, next])\n\n\treturn {\n\t\tassets: data === undefined ? null : toAssets(pages.slice(0, shown)),\n\t\t// A page fetched ahead is not loading anything the grid waits on.\n\t\tisLoading: isFetching && (data === undefined || shown > pages.length),\n\t\terror,\n\t\thasMore,\n\t\ttotal: pages[0]?.total ?? null,\n\t\tloadMore,\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { useMutation, useQueryClient, } from '@tanstack/react-query';
2
2
  import { useCallback } from 'react';
3
- import { promoteVariant, waitUntilPromoted } from '@raster-app/sdk';
3
+ import { promoteVariant, waitUntilPromoted, } from '@raster-app/sdk';
4
4
  import { useRasterClient } from './context.js';
5
5
  import { rasterKeys } from './query-keys.js';
6
6
  import { useCredentialIdentity } from './use-session.js';
@@ -9,7 +9,10 @@ function replaceAsset(data, assetId, update) {
9
9
  return undefined;
10
10
  return {
11
11
  ...data,
12
- pages: data.pages.map((page) => page.map((asset) => (asset.id === assetId ? update(asset) : asset))),
12
+ pages: data.pages.map((page) => ({
13
+ ...page,
14
+ assets: page.assets.map((asset) => (asset.id === assetId ? update(asset) : asset)),
15
+ })),
13
16
  };
14
17
  }
15
18
  function promoteState(mutation) {
@@ -1 +1 @@
1
- {"version":3,"file":"use-promote-variant.js","sourceRoot":"","sources":["../src/use-promote-variant.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,WAAW,EACX,cAAc,GACd,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,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CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAA;YACtD,CAAC;YACD,KAAK,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,QAAQ,EAAE,cAAc,CAAC,EAAE,CAAC,CAAA;QAC9F,CAAC;KACD,CAAC,CAAA;IAEF,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAA;IACvC,MAAM,KAAK,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAA;IAEpC,MAAM,OAAO,GAAG,WAAW,CAC1B,KAAK,EAAE,OAAO,EAAE,EAAE;QACjB,IAAI,CAAC;YACJ,OAAO,MAAM,WAAW,CAAC,OAAO,CAAC,CAAA;QAClC,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,IAAI,CAAA;QACZ,CAAC;IACF,CAAC,EACD,CAAC,WAAW,CAAC,CACb,CAAA;IAED,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;AACjC,CAAC","sourcesContent":["import {\n\ttype InfiniteData,\n\ttype UseMutationResult,\n\tuseMutation,\n\tuseQueryClient,\n} from '@tanstack/react-query'\nimport { useCallback } from 'react'\n\nimport { type Asset, type RasterApiError, promoteVariant, waitUntilPromoted } from '@raster-app/sdk'\n\nimport { useRasterClient } from './context.js'\nimport { rasterKeys } from './query-keys.js'\nimport { useCredentialIdentity } from './use-session.js'\n\ntype PromoteOptions = {\n\torganizationId: string\n\tlibraryId: string\n\t/** The asset whose default is being replaced. */\n\tassetId: string\n\t/** The variant to make the new default. */\n\tvariantId: string\n\t/**\n\t * Applied to the asset in the library's cached list straight away, and kept until the swap\n\t * lands or fails — say, to show the variant as the default already.\n\t */\n\toptimistic?: (asset: Asset) => Asset\n}\n\nexport type PromoteState =\n\t| { status: 'idle' }\n\t| { status: 'promoting' }\n\t/** The swap landed; `asset` is the asset as it now reads. */\n\t| { status: 'done'; asset: Asset }\n\t/** Raster took the promote, but had not swapped the files when the wait gave up. */\n\t| { status: 'timed-out' }\n\t| { status: 'error'; error: RasterApiError }\n\nexport type VariantPromote = {\n\tstate: PromoteState\n\t/**\n\t * Promote a variant to be its asset's default, then wait until Raster has swapped the files\n\t * (`waitUntilPromoted`). Resolves with the asset as it then reads; null leaves the\n\t * rest to `state`.\n\t */\n\tpromote: (options: PromoteOptions) => Promise<Asset | null>\n\treset: () => void\n}\n\ntype AssetPages = InfiniteData<Array<Asset>>\n\nfunction replaceAsset(\n\tdata: AssetPages | undefined,\n\tassetId: string,\n\tupdate: (asset: Asset) => Asset\n): AssetPages | undefined {\n\tif (data === undefined) return undefined\n\treturn {\n\t\t...data,\n\t\tpages: data.pages.map((page) =>\n\t\t\tpage.map((asset) => (asset.id === assetId ? update(asset) : asset))\n\t\t),\n\t}\n}\n\nfunction promoteState(\n\tmutation: UseMutationResult<Asset | null, RasterApiError, PromoteOptions>\n): PromoteState {\n\tif (mutation.isPending) return { status: 'promoting' }\n\tif (mutation.isError) return { status: 'error', error: mutation.error }\n\tif (!mutation.isSuccess) return { status: 'idle' }\n\treturn mutation.data === null ? { status: 'timed-out' } : { status: 'done', asset: mutation.data }\n}\n\nexport function usePromoteVariant(): VariantPromote {\n\tconst client = useRasterClient()\n\tconst queryClient = useQueryClient()\n\n\tconst identity = useCredentialIdentity()\n\tconst mutation = useMutation<Asset | null, RasterApiError, PromoteOptions>({\n\t\tmutationFn: async (options) => {\n\t\t\tawait promoteVariant(client, options)\n\t\t\treturn waitUntilPromoted(client, options)\n\t\t},\n\t\tonMutate: async ({ organizationId, libraryId, assetId, optimistic }) => {\n\t\t\tif (optimistic === undefined) return\n\t\t\tconst key = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\t// A page landing after this would put the asset back as it was.\n\t\t\tawait queryClient.cancelQueries({ queryKey: key })\n\t\t\tqueryClient.setQueryData<AssetPages>(key, (data) => replaceAsset(data, assetId, optimistic))\n\t\t},\n\t\t// Landed, the asset as it now reads replaces the cached one. Otherwise the list is read\n\t\t// again, which also undoes an optimistic update that never landed.\n\t\tonSettled: (asset, _error, { organizationId, libraryId, assetId }) => {\n\t\t\tconst key = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\tif (asset) {\n\t\t\t\tqueryClient.setQueryData<AssetPages>(key, (data) =>\n\t\t\t\t\treplaceAsset(data, assetId, () => asset)\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tvoid queryClient.invalidateQueries({ queryKey: key })\n\t\t\t}\n\t\t\tvoid queryClient.invalidateQueries({ queryKey: rasterKeys.search(identity, organizationId) })\n\t\t},\n\t})\n\n\tconst { mutateAsync, reset } = mutation\n\tconst state = promoteState(mutation)\n\n\tconst promote = useCallback<VariantPromote['promote']>(\n\t\tasync (options) => {\n\t\t\ttry {\n\t\t\t\treturn await mutateAsync(options)\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[mutateAsync]\n\t)\n\n\treturn { state, promote, reset }\n}\n"]}
1
+ {"version":3,"file":"use-promote-variant.js","sourceRoot":"","sources":["../src/use-promote-variant.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,WAAW,EACX,cAAc,GACd,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AAEnC,OAAO,EAIN,cAAc,EACd,iBAAiB,GACjB,MAAM,iBAAiB,CAAA;AAExB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAA;AAsCxD,SAAS,YAAY,CACpB,IAA4B,EAC5B,OAAe,EACf,MAA+B;IAE/B,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACxC,OAAO;QACN,GAAG,IAAI;QACP,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAA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EAAE,EAAE;QACjB,IAAI,CAAC;YACJ,OAAO,MAAM,WAAW,CAAC,OAAO,CAAC,CAAA;QAClC,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,IAAI,CAAA;QACZ,CAAC;IACF,CAAC,EACD,CAAC,WAAW,CAAC,CACb,CAAA;IAED,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;AACjC,CAAC","sourcesContent":["import {\n\ttype InfiniteData,\n\ttype UseMutationResult,\n\tuseMutation,\n\tuseQueryClient,\n} from '@tanstack/react-query'\nimport { useCallback } from 'react'\n\nimport {\n\ttype Asset,\n\ttype AssetPage,\n\ttype RasterApiError,\n\tpromoteVariant,\n\twaitUntilPromoted,\n} from '@raster-app/sdk'\n\nimport { useRasterClient } from './context.js'\nimport { rasterKeys } from './query-keys.js'\nimport { useCredentialIdentity } from './use-session.js'\n\ntype PromoteOptions = {\n\torganizationId: string\n\tlibraryId: string\n\t/** The asset whose default is being replaced. */\n\tassetId: string\n\t/** The variant to make the new default. */\n\tvariantId: string\n\t/**\n\t * Applied to the asset in the library's cached list straight away, and kept until the swap\n\t * lands or fails — say, to show the variant as the default already.\n\t */\n\toptimistic?: (asset: Asset) => Asset\n}\n\nexport type PromoteState =\n\t| { status: 'idle' }\n\t| { status: 'promoting' }\n\t/** The swap landed; `asset` is the asset as it now reads. */\n\t| { status: 'done'; asset: Asset }\n\t/** Raster took the promote, but had not swapped the files when the wait gave up. */\n\t| { status: 'timed-out' }\n\t| { status: 'error'; error: RasterApiError }\n\nexport type VariantPromote = {\n\tstate: PromoteState\n\t/**\n\t * Promote a variant to be its asset's default, then wait until Raster has swapped the files\n\t * (`waitUntilPromoted`). Resolves with the asset as it then reads; null leaves the\n\t * rest to `state`.\n\t */\n\tpromote: (options: PromoteOptions) => Promise<Asset | null>\n\treset: () => void\n}\n\ntype AssetPages = InfiniteData<AssetPage>\n\nfunction replaceAsset(\n\tdata: AssetPages | undefined,\n\tassetId: string,\n\tupdate: (asset: Asset) => Asset\n): AssetPages | undefined {\n\tif (data === undefined) return undefined\n\treturn {\n\t\t...data,\n\t\tpages: data.pages.map((page) => ({\n\t\t\t...page,\n\t\t\tassets: page.assets.map((asset) => (asset.id === assetId ? update(asset) : asset)),\n\t\t})),\n\t}\n}\n\nfunction promoteState(\n\tmutation: UseMutationResult<Asset | null, RasterApiError, PromoteOptions>\n): PromoteState {\n\tif (mutation.isPending) return { status: 'promoting' }\n\tif (mutation.isError) return { status: 'error', error: mutation.error }\n\tif (!mutation.isSuccess) return { status: 'idle' }\n\treturn mutation.data === null ? { status: 'timed-out' } : { status: 'done', asset: mutation.data }\n}\n\nexport function usePromoteVariant(): VariantPromote {\n\tconst client = useRasterClient()\n\tconst queryClient = useQueryClient()\n\n\tconst identity = useCredentialIdentity()\n\tconst mutation = useMutation<Asset | null, RasterApiError, PromoteOptions>({\n\t\tmutationFn: async (options) => {\n\t\t\tawait promoteVariant(client, options)\n\t\t\treturn waitUntilPromoted(client, options)\n\t\t},\n\t\tonMutate: async ({ organizationId, libraryId, assetId, optimistic }) => {\n\t\t\tif (optimistic === undefined) return\n\t\t\tconst key = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\t// A page landing after this would put the asset back as it was.\n\t\t\tawait queryClient.cancelQueries({ queryKey: key })\n\t\t\tqueryClient.setQueryData<AssetPages>(key, (data) => replaceAsset(data, assetId, optimistic))\n\t\t},\n\t\t// Landed, the asset as it now reads replaces the cached one. Otherwise the list is read\n\t\t// again, which also undoes an optimistic update that never landed.\n\t\tonSettled: (asset, _error, { organizationId, libraryId, assetId }) => {\n\t\t\tconst key = rasterKeys.assets(identity, organizationId, libraryId)\n\t\t\tif (asset) {\n\t\t\t\tqueryClient.setQueryData<AssetPages>(key, (data) =>\n\t\t\t\t\treplaceAsset(data, assetId, () => asset)\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tvoid queryClient.invalidateQueries({ queryKey: key })\n\t\t\t}\n\t\t\tvoid queryClient.invalidateQueries({ queryKey: rasterKeys.search(identity, organizationId) })\n\t\t},\n\t})\n\n\tconst { mutateAsync, reset } = mutation\n\tconst state = promoteState(mutation)\n\n\tconst promote = useCallback<VariantPromote['promote']>(\n\t\tasync (options) => {\n\t\t\ttry {\n\t\t\t\treturn await mutateAsync(options)\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[mutateAsync]\n\t)\n\n\treturn { state, promote, reset }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raster-app/react",
3
- "version": "0.2.1",
3
+ "version": "0.3.0-canary-66199c2",
4
4
  "description": "React provider and hooks for the Raster SDK: session, organizations, libraries, assets, search and uploads.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://raster.app/docs/api/sdk",
@@ -40,7 +40,7 @@
40
40
  "test": "bun test"
41
41
  },
42
42
  "dependencies": {
43
- "@raster-app/sdk": "0.2.1",
43
+ "@raster-app/sdk": "0.3.0-canary-66199c2",
44
44
  "@tanstack/react-query": "^5.103.1",
45
45
  "@tanstack/react-virtual": "^3.14.13"
46
46
  },