@datocms/svelte 3.0.3 → 3.0.5

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
@@ -4,6 +4,8 @@
4
4
 
5
5
  👉 [Visit the DatoCMS homepage](https://www.datocms.com) or see [What is DatoCMS?](#what-is-datocms)
6
6
 
7
+ ---
8
+
7
9
  <!--datocms-autoinclude-header end-->
8
10
 
9
11
  # @datocms/svelte
@@ -35,11 +37,15 @@ A set of components to work faster with [DatoCMS](https://www.datocms.com/) in S
35
37
 
36
38
  Components:
37
39
 
38
- - [`<Image />`](src/lib/components/Image)
40
+ - [`<Image />` and `<NakedImage />`](src/lib/components/Image)
39
41
  - [`<VideoPlayer />`](src/lib/components/VideoPlayer)
40
42
  - [`<StructuredText />`](src/lib/components/StructuredText)
41
43
  - [`<Head />`](src/lib/components/Head)
42
44
 
45
+ Stores:
46
+
47
+ - [`querySubscription`](src/lib/stores/querySubscription)
48
+
43
49
  ## Installation
44
50
 
45
51
  ```
@@ -63,7 +69,9 @@ npm run build
63
69
  ```
64
70
 
65
71
  <!--datocms-autoinclude-footer start-->
66
- -----------------
72
+
73
+ ---
74
+
67
75
  # What is DatoCMS?
68
76
  <a href="https://www.datocms.com/"><img src="https://www.datocms.com/images/full_logo.svg" height="60"></a>
69
77
 
@@ -86,4 +94,5 @@ Trusted by over 25,000 enterprise businesses, agency partners, and individuals a
86
94
  - [DatoCMS Starters](https://www.datocms.com/marketplace/starters) has examples for various Javascript frontend frameworks
87
95
 
88
96
  Or see [all our public repos](https://github.com/orgs/datocms/repositories?q=&type=public&language=&sort=stargazers)
97
+
89
98
  <!--datocms-autoinclude-footer end-->
@@ -119,7 +119,7 @@ $:
119
119
  'background-color': data.bgColor,
120
120
  ...basePlaceholderStyle
121
121
  })}
122
- />
122
+ ></div>
123
123
  {/if}
124
124
  {/if}
125
125
 
@@ -7,7 +7,6 @@
7
7
  <!-- START doctoc generated TOC please keep comment here to allow auto update -->
8
8
  <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
9
9
 
10
- - [Setup](#setup)
11
10
  - [Basic usage](#basic-usage)
12
11
  - [Customization](#customization)
13
12
  - [Custom components for blocks](#custom-components-for-blocks)
@@ -86,8 +85,8 @@ Here is an example using custom components for blocks, inline and item links. Ta
86
85
 
87
86
  ```svelte
88
87
  <script>
89
-
90
88
  import { onMount } from 'svelte';
89
+ import { executeQuery } from '@datocms/cda-client';
91
90
 
92
91
  import { isBlock, isInlineItem, isItemLink } from 'datocms-structured-text-utils';
93
92
 
@@ -104,33 +103,23 @@ const query = `
104
103
  content {
105
104
  value
106
105
  links {
107
- __typename
108
- ... on TeamMemberRecord {
106
+ ... on RecordInterface {
109
107
  id
108
+ __typename
109
+ }
110
+ ... on TeamMemberRecord {
110
111
  firstName
111
112
  slug
112
113
  }
113
114
  }
114
115
  blocks {
115
- __typename
116
- ... on ImageRecord {
116
+ ... on RecordInterface {
117
117
  id
118
- image {
119
- responsiveImage(
120
- imgixParams: { fit: crop, w: 300, h: 300, auto: format }
121
- ) {
122
- srcSet
123
- webpSrcSet
124
- sizes
125
- src
126
- width
127
- height
128
- aspectRatio
129
- alt
130
- title
131
- base64
132
- }
133
- }
118
+ __typename
119
+ }
120
+ ... on CtaRecord {
121
+ title
122
+ url
134
123
  }
135
124
  }
136
125
  }
@@ -141,18 +130,7 @@ const query = `
141
130
  export let data = null;
142
131
 
143
132
  onMount(async () => {
144
- const response = await fetch('https://graphql.datocms.com/', {
145
- method: 'POST',
146
- headers: {
147
- 'Content-Type': 'application/json',
148
- Authorization: "Bearer AN_API_TOKEN",
149
- },
150
- body: JSON.stringify({ query })
151
- })
152
-
153
- const json = await response.json()
154
-
155
- data = json.data;
133
+ data = await executeQuery(query, { token: '<YOUR-API-TOKEN>' });
156
134
  });
157
135
 
158
136
  </script>
@@ -1,11 +1,13 @@
1
1
  <script>import {
2
- isStructuredText
2
+ isStructuredText,
3
+ isDocument,
4
+ isNode
3
5
  } from "datocms-structured-text-utils";
4
6
  import Node from "./Node.svelte";
5
7
  export let data = null;
6
8
  export let components = [];
7
9
  $:
8
- node = data != null && (isStructuredText(data) ? data.value : data).document;
10
+ node = !data ? null : isStructuredText(data) && isDocument(data.value) ? data.value.document : isDocument(data) ? data.document : isNode(data) ? data : void 0;
9
11
  $:
10
12
  blocks = isStructuredText(data) ? data?.blocks : void 0;
11
13
  $:
@@ -1,9 +1,9 @@
1
1
  import { SvelteComponentTyped } from "svelte";
2
- import { type StructuredText, type Document } from 'datocms-structured-text-utils';
2
+ import { type StructuredText, type Document, type Node as DastNode } from 'datocms-structured-text-utils';
3
3
  import type { PredicateComponentTuple } from '../..';
4
4
  declare const __propDef: {
5
5
  props: {
6
- /** The actual field value you get from DatoCMS **/ data?: StructuredText | Document | null | undefined;
6
+ /** The actual field value you get from DatoCMS **/ data?: StructuredText | Document | DastNode | null | undefined;
7
7
  components?: PredicateComponentTuple[] | undefined;
8
8
  };
9
9
  events: {
@@ -134,4 +134,4 @@ onMount(async () => {
134
134
  on:error
135
135
  on:cuepointchange
136
136
  on:cuepointschange
137
- />
137
+ ></mux-player>
@@ -6,6 +6,7 @@ export { default as Head } from './components/Head/Head.svelte';
6
6
  export { default as Image } from './components/Image/Image.svelte';
7
7
  export { default as StructuredText } from './components/StructuredText/StructuredText.svelte';
8
8
  export { default as VideoPlayer } from './components/VideoPlayer/VideoPlayer.svelte';
9
+ export * from './stores/querySubscription';
9
10
  export type PredicateComponentTuple = [
10
11
  (n: Node) => boolean,
11
12
  new (...any: any) => SvelteComponent
package/package/index.js CHANGED
@@ -3,3 +3,4 @@ export { default as Head } from './components/Head/Head.svelte';
3
3
  export { default as Image } from './components/Image/Image.svelte';
4
4
  export { default as StructuredText } from './components/StructuredText/StructuredText.svelte';
5
5
  export { default as VideoPlayer } from './components/VideoPlayer/VideoPlayer.svelte';
6
+ export * from './stores/querySubscription';
@@ -0,0 +1,110 @@
1
+ # Live real-time updates
2
+
3
+ `querySubscription` returns a Svelte store that you can use to implement client-side updates of the page as soon as the content changes. It uses DatoCMS's [Real-time Updates API](https://www.datocms.com/docs/real-time-updates-api/api-reference) to receive the updated query results in real-time, and is able to reconnect in case of network failures.
4
+
5
+ Live updates are great both to get instant previews of your content while editing it inside DatoCMS, or to offer real-time updates of content to your visitors (ie. news site).
6
+
7
+ ## Table of Contents
8
+
9
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
10
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
11
+
12
+ - [Reference](#reference)
13
+ - [Initialization options](#initialization-options)
14
+ - [Connection status](#connection-status)
15
+ - [Error object](#error-object)
16
+ - [Example](#example)
17
+
18
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
19
+
20
+ ## Reference
21
+
22
+ Import `querySubscription` from `datocms-svelte` and use it inside your components like this:
23
+
24
+ ```js
25
+ import { querySubscription } from '@datocms/svelte';
26
+
27
+ const subscription = querySubscription(options: Options);
28
+ ```
29
+
30
+ ## Initialization options
31
+
32
+ | prop | type | required | description | default |
33
+ | ------------------ | ------------------------------------------------------------------------------------------ | ------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------ |
34
+ | enabled | boolean | :x: | Whether the subscription has to be performed or not | true |
35
+ | query | string \| [`TypedDocumentNode`](https://github.com/dotansimha/graphql-typed-document-node) | :white_check_mark: | The GraphQL query to subscribe | |
36
+ | token | string | :white_check_mark: | DatoCMS API token to use | |
37
+ | variables | Object | :x: | GraphQL variables for the query | |
38
+ | includeDrafts | boolean | :x: | If true, draft records will be returned | |
39
+ | excludeInvalid | boolean | :x: | If true, invalid records will be filtered out | |
40
+ | environment | string | :x: | The name of the DatoCMS environment where to perform the query (defaults to primary environment) | |
41
+ | contentLink | `'vercel-1'` or `undefined` | :x: | If true, embed metadata that enable Content Link | |
42
+ | baseEditingUrl | string | :x: | The base URL of the DatoCMS project | |
43
+ | cacheTags | boolean | :x: | If true, receive the Cache Tags associated with the query | |
44
+ | initialData | Object | :x: | The initial data to use on the first render | |
45
+ | reconnectionPeriod | number | :x: | In case of network errors, the period (in ms) to wait to reconnect | 1000 |
46
+ | fetcher | a [fetch-like function](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | :x: | The fetch function to use to perform the registration query | window.fetch |
47
+ | eventSourceClass | an [EventSource-like](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) class | :x: | The EventSource class to use to open up the SSE connection | window.EventSource |
48
+ | baseUrl | string | :x: | The base URL to use to perform the query | `https://graphql-listen.datocms.com` |
49
+
50
+ ## Connection status
51
+
52
+ The `status` property represents the state of the server-sent events connection. It can be one of the following:
53
+
54
+ - `connecting`: the subscription channel is trying to connect
55
+ - `connected`: the channel is open, we're receiving live updates
56
+ - `closed`: the channel has been permanently closed due to a fatal error (ie. an invalid query)
57
+
58
+ ## Error object
59
+
60
+ | prop | type | description |
61
+ | -------- | ------ | ------------------------------------------------------- |
62
+ | code | string | The code of the error (ie. `INVALID_QUERY`) |
63
+ | message | string | An human friendly message explaining the error |
64
+ | response | Object | The raw response returned by the endpoint, if available |
65
+
66
+ ## Example
67
+
68
+ ```svelte
69
+ <script>
70
+ import { querySubscription } from 'react-datocms';
71
+
72
+ const subscription = useQuerySubscription({
73
+ enabled: true,
74
+ query: `
75
+ query AppQuery($first: IntType) {
76
+ allBlogPosts {
77
+ slug
78
+ title
79
+ }
80
+ }`,
81
+ variables: { first: 10 },
82
+ token: 'YOUR_API_TOKEN',
83
+ });
84
+
85
+ $: ({ data, error, status } = $subscription)
86
+
87
+ const statusMessage = {
88
+ connecting: 'Connecting to DatoCMS...',
89
+ connected: 'Connected to DatoCMS, receiving live updates!',
90
+ closed: 'Connection closed',
91
+ };
92
+ </script>
93
+
94
+ <p>Connection status: {statusMessage[status]}</p>
95
+
96
+ {#if error}
97
+ <h1>Error: {error.code}</h1>
98
+ <p>{error.message}</p>
99
+ {#if error.response}
100
+ <pre>{JSON.stringify(error.response, null, 2)}</pre>
101
+ {/if}
102
+ {/if}
103
+
104
+ {#if data}
105
+ <ul>
106
+ {#each data.allBlogPosts as blogPost (blogPost.slug)}
107
+ <li>{blogPost.title}</li>
108
+ </ul>
109
+ {/if}
110
+ ```
@@ -0,0 +1,24 @@
1
+ /// <reference types="svelte" />
2
+ import { type ChannelErrorData, type ConnectionStatus, type Options } from 'datocms-listen';
3
+ export type SubscribeToQueryOptions<QueryResult, QueryVariables> = Omit<Options<QueryResult, QueryVariables>, 'onStatusChange' | 'onUpdate' | 'onChannelError'>;
4
+ export type EnabledQuerySubscriptionOptions<QueryResult, QueryVariables> = {
5
+ /** Whether the subscription has to be performed or not */
6
+ enabled?: true;
7
+ /** The initial data to use while the initial request is being performed */
8
+ initialData?: QueryResult;
9
+ } & SubscribeToQueryOptions<QueryResult, QueryVariables>;
10
+ export type DisabledQuerySubscriptionOptions<QueryResult, QueryVariables> = {
11
+ /** Whether the subscription has to be performed or not */
12
+ enabled: false;
13
+ /** The initial data to use while the initial request is being performed */
14
+ initialData?: QueryResult;
15
+ } & Partial<SubscribeToQueryOptions<QueryResult, QueryVariables>>;
16
+ export type QuerySubscriptionOptions<QueryResult, QueryVariables> = EnabledQuerySubscriptionOptions<QueryResult, QueryVariables> | DisabledQuerySubscriptionOptions<QueryResult, QueryVariables>;
17
+ export type Subscription<QueryResult> = {
18
+ error: ChannelErrorData | null;
19
+ data: QueryResult | null;
20
+ status: ConnectionStatus | null;
21
+ };
22
+ export declare function querySubscription<QueryResult = unknown, QueryVariables = unknown>(options: QuerySubscriptionOptions<QueryResult, QueryVariables>): {
23
+ subscribe: (this: void, run: import("svelte/store").Subscriber<Subscription<QueryResult>>, invalidate?: import("svelte/store").Invalidator<Subscription<QueryResult>> | undefined) => import("svelte/store").Unsubscriber;
24
+ };
@@ -0,0 +1,44 @@
1
+ import { subscribeToQuery } from 'datocms-listen';
2
+ import { onMount } from 'svelte';
3
+ import { writable } from 'svelte/store';
4
+ export function querySubscription(options) {
5
+ const { enabled, initialData, ...other } = options;
6
+ const subscribeToQueryOptions = other;
7
+ const { subscribe, update } = writable({
8
+ error: null,
9
+ data: initialData || null,
10
+ status: enabled ? 'connecting' : 'closed'
11
+ });
12
+ onMount(() => {
13
+ if (enabled === false) {
14
+ update((old) => ({ ...old, status: 'closed' }));
15
+ return;
16
+ }
17
+ let unsubscribe;
18
+ async function subscribe() {
19
+ unsubscribe = await subscribeToQuery({
20
+ ...subscribeToQueryOptions,
21
+ onStatusChange: (status) => {
22
+ update((old) => ({ ...old, status }));
23
+ },
24
+ onUpdate: (updateData) => {
25
+ update((old) => ({
26
+ ...old,
27
+ error: null,
28
+ data: updateData.response.data
29
+ }));
30
+ },
31
+ onChannelError: (errorData) => {
32
+ update((old) => ({ ...old, error: errorData, data: null }));
33
+ }
34
+ });
35
+ }
36
+ subscribe();
37
+ return () => {
38
+ if (unsubscribe) {
39
+ unsubscribe();
40
+ }
41
+ };
42
+ });
43
+ return { subscribe };
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datocms/svelte",
3
- "version": "3.0.3",
3
+ "version": "3.0.5",
4
4
  "description": "A set of components and utilities to work faster with DatoCMS in Svelte",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@mux/mux-player": "*",
30
- "svelte": "^3.59.2 || ^4.0.0"
30
+ "svelte": "^3.59.2 || ^4.0.0 || ^5.0.0"
31
31
  },
32
32
  "peerDependenciesMeta": {
33
33
  "@mux/mux-player": {
@@ -65,6 +65,7 @@
65
65
  },
66
66
  "type": "module",
67
67
  "dependencies": {
68
+ "datocms-listen": "^0.1.15",
68
69
  "datocms-structured-text-utils": "^4.0.1",
69
70
  "svelte-intersection-observer": "^1.0.0"
70
71
  },