@datocms/svelte 1.4.3 → 2.0.1

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.
Files changed (28) hide show
  1. package/README.md +19 -5
  2. package/package/components/Head/Head.svelte.d.ts +1 -1
  3. package/package/components/Head/README.md +24 -19
  4. package/package/components/Image/Image.svelte +107 -119
  5. package/package/components/Image/Image.svelte.d.ts +6 -30
  6. package/package/components/Image/README.md +120 -67
  7. package/package/components/Image/utils.d.ts +13 -0
  8. package/package/components/Image/utils.js +36 -0
  9. package/package/components/NakedImage/NakedImage.svelte +71 -0
  10. package/package/components/NakedImage/NakedImage.svelte.d.ts +39 -0
  11. package/package/components/NakedImage/utils.d.ts +31 -0
  12. package/package/components/NakedImage/utils.js +48 -0
  13. package/package/components/StructuredText/README.md +9 -2
  14. package/package/components/StructuredText/StructuredText.svelte +3 -1
  15. package/package/components/StructuredText/nodes/Span.svelte +1 -1
  16. package/package/components/StructuredText/nodes/ThematicBreak.svelte +1 -1
  17. package/package/components/VideoPlayer/README.md +16 -4
  18. package/package/components/VideoPlayer/VideoPlayer.svelte.d.ts +2 -2
  19. package/package/components/VideoPlayer/__tests__/VideoPlayer.svelte.test.js +2 -2
  20. package/package/index.d.ts +4 -2
  21. package/package/index.js +3 -2
  22. package/package.json +6 -5
  23. package/package/components/Image/Placeholder.svelte +0 -30
  24. package/package/components/Image/Placeholder.svelte.d.ts +0 -22
  25. package/package/components/Image/Sizer.svelte +0 -17
  26. package/package/components/Image/Sizer.svelte.d.ts +0 -19
  27. package/package/components/Image/Source.svelte +0 -6
  28. package/package/components/Image/Source.svelte.d.ts +0 -18
@@ -1,16 +1,10 @@
1
- ## Progressive responsive image
1
+ # Progressive responsive image
2
2
 
3
- `<Image>` is a Svelte component specially designed to work seamlessly with DatoCMS’s [`responsiveImage` GraphQL query](https://www.datocms.com/docs/content-delivery-api/uploads#responsive-images) that optimizes image loading for your sites.
3
+ `<Image>` and `<NakedImage />` are Svelte component specially designed to work seamlessly with DatoCMS’s [`responsiveImage` GraphQL query](https://www.datocms.com/docs/content-delivery-api/uploads#responsive-images) which optimizes image loading for your websites.
4
4
 
5
- ### Table of contents
6
-
7
- - [Out-of-the-box features](#out-of-the-box-features)
8
- - [Setup](#setup)
9
- - [Usage](#usage)
10
- - [Example](#example)
11
- - [Props](#props)
12
- - [Layout mode](#layout-mode)
13
- - [The `ResponsiveImage` object](#the-responsiveimage-object)
5
+ - TypeScript ready;
6
+ - Usable both client and server side;
7
+ - Compatible with vanilla Svelte and Sveltekit;
14
8
 
15
9
  ### Out-of-the-box features
16
10
 
@@ -20,28 +14,50 @@
20
14
  - Holds the image position so your page doesn’t jump while images load
21
15
  - Uses either blur-up or background color techniques to show a preview of the image while it loads
22
16
 
23
- ## Intersection Observer
17
+ ### Table of contents
24
18
 
25
- Intersection Observer is the API used to determine if the image is inside the viewport or not. [Browser support is really good](https://caniuse.com/intersectionobserver) - With Safari adding support in 12.1, all major browsers now support Intersection Observers natively.
19
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
20
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
26
21
 
27
- If the IntersectionObserver object is not available, the component treats the image as it's always visible in the viewport. Feel free to add a [polyfill](https://www.npmjs.com/package/intersection-observer) so that it will also 100% work on older versions of iOS and IE11.
22
+ - [Setup](#setup)
23
+ - [Usage](#usage)
24
+ - [`<Image />` vs `<NakedImage />`](#image--vs-nakedimage-)
25
+ - [Example](#example)
26
+ - [The `ResponsiveImage` object](#the-responsiveimage-object)
27
+ - [`<NakedImage />`](#nakedimage-)
28
+ - [Props](#props)
29
+ - [Events](#events)
30
+ - [`<Image />`](#image-)
31
+ - [Props](#props-1)
32
+ - [Events](#events-1)
33
+ - [Layout mode](#layout-mode)
34
+ - [Intersection Observer](#intersection-observer)
35
+
36
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
28
37
 
29
38
  ### Setup
30
39
 
31
40
  You can import the components like this:
32
41
 
33
42
  ```js
34
- import { Image } from '@datocms/svelte';
43
+ import { Image, NakedImage } from '@datocms/svelte';
35
44
  ```
36
45
 
37
- ### Usage
46
+ ## Usage
38
47
 
39
- 1. Use `<Image>` it in place of the regular `<img />` tag
48
+ 1. Use `<Image>` or `<NakedImage />` in place of the regular `<img />` tag
40
49
  2. Write a GraphQL query to your DatoCMS project using the [`responsiveImage` query](https://www.datocms.com/docs/content-delivery-api/images-and-videos#responsive-images)
41
50
 
42
- The GraphQL query returns multiple thumbnails with optimized compression. The `<Image>` component automatically sets up the "blur-up" effect as well as lazy loading of images further down the screen.
51
+ The GraphQL query returns multiple thumbnails with optimized compression. The components automatically set up the "blur-up" effect as well as lazy loading of images further down the screen.
52
+
53
+ ## `<Image />` vs `<NakedImage />`
43
54
 
44
- ### Example
55
+ Even though their purpose is the same, there are some significant differences between these two components. Depending on your specific needs, you can choose to use one or the other:
56
+
57
+ - `<NakedImage />` generates minimum JS footprint, outputs a single `<picture />` element and implements lazy-loading using the native [`loading="lazy"` attribute](https://web.dev/articles/browser-level-image-lazy-loading). The placeholder is set as the background to the image itself.
58
+ - `<Image />` has the ability to set a cross-fade effect between the placeholder and the original image, but at the cost of generating more complex HTML output composed of multiple elements around the main `<picture />` element. It also implements lazy-loading through `IntersectionObserver`, which allows customization of the thresholds at which lazy loading occurs.
59
+
60
+ ## Example
45
61
 
46
62
  For a fully working example take a look at [`routes` directory](https://github.com/datocms/datocms-svelte/tree/main/src/routes/image/+page.svelte).
47
63
 
@@ -52,7 +68,7 @@ Here is a minimal starting point:
52
68
 
53
69
  import { onMount } from 'svelte';
54
70
 
55
- import { Image } from '@datocms/svelte';
71
+ import { Image, NakedImage } from '@datocms/svelte';
56
72
 
57
73
  const query = gql`
58
74
  query {
@@ -101,34 +117,92 @@ onMount(async () => {
101
117
  </script>
102
118
 
103
119
  {#if data}
104
- <Image data={data.blogPost.cover.responsiveImage} />
120
+ <Image data={data.blogPost.cover.responsiveImage} />
121
+ <NakedImage data={data.blogPost.cover.responsiveImage} />
105
122
  {/if}
106
123
  ```
107
124
 
125
+ ## The `ResponsiveImage` object
126
+
127
+ The `data` prop of both components expects an object with the same shape as the one returned by `responsiveImage` GraphQL call. It's up to you to make a GraphQL query that will return the properties you need for a specific use of the `<datocms-image>` component.
128
+
129
+ - The minimum required properties for `data` are: `src`, `width` and `height`;
130
+ - `alt` and `title`, while not mandatory, are all highly suggested, so remember to use them!
131
+ - If you don't request `srcSet`, the component will auto-generate an `srcset` based on `src` + the `srcSetCandidates` prop (it can help reducing the GraphQL response size drammatically when many images are returned);
132
+ - We strongly to suggest to always specify [`{ auto: format }`](https://docs.imgix.com/apis/rendering/auto/auto#format) in your `imgixParams`, instead of requesting `webpSrcSet`, so that you can also take advantage of more performant optimizations (AVIF), without increasing GraphQL response size;
133
+ - If you request both the `bgColor` and `base64` property, the latter will take precedence, so just avoid querying both fields at the same time, as it will only make the GraphQL response bigger :wink:;
134
+ - You can avoid requesting `sizes` and directly pass a `sizes` prop to the component to reduce the GraphQL response size;
135
+
136
+ Here's a complete recap of what `responsiveImage` offers:
137
+
138
+ | property | type | required | description |
139
+ | ----------- | ------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
140
+ | src | string | :white_check_mark: | The `src` attribute for the image |
141
+ | width | integer | :white_check_mark: | The width of the image |
142
+ | height | integer | :white_check_mark: | The height of the image |
143
+ | alt | string | :x: | Alternate text (`alt`) for the image (not required, but strongly suggested!) |
144
+ | title | string | :x: | Title attribute (`title`) for the image (not required, but strongly suggested!) |
145
+ | sizes | string | :x: | The HTML5 `sizes` attribute for the image (omit it if you're already passing a `sizes` prop to the Image component) |
146
+ | base64 | string | :x: | A base64-encoded thumbnail to offer during image loading |
147
+ | bgColor | string | :x: | The background color for the image placeholder (omit it if you're already requesting `base64`) |
148
+ | srcSet | string | :x: | The HTML5 `srcSet` attribute for the image (can be omitted, the Image component knows how to build it based on `src`) |
149
+ | webpSrcSet | string | :x: | The HTML5 `srcSet` attribute for the image in WebP format (deprecated, it's better to use the [`auto=format`](https://docs.imgix.com/apis/rendering/auto/auto#format) Imgix transform instead) |
150
+ | aspectRatio | float | :x: | The aspect ratio (width/height) of the image |
151
+
152
+ ## `<NakedImage />`
153
+
154
+ ### Props
155
+
156
+ | prop | type | default | required | description |
157
+ | ---------------- | ------------------------ | ---------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
158
+ | data | `ResponsiveImage` object | | :white_check_mark: | The actual response you get from a DatoCMS `responsiveImage` GraphQL query \*\*\*\* |
159
+ | class | string | null | :x: | Additional CSS class for image |
160
+ | style | CSS properties | null | :x: | Additional CSS rules to add to the image |
161
+ | priority | Boolean | false | :x: | Disables lazy loading, and sets the image [fetchPriority](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority) to "high" |
162
+ | sizes | string | undefined | :x: | The HTML5 [`sizes`](https://web.dev/learn/design/responsive-images/#sizes) attribute for the image (will be used `data.sizes` as a fallback) |
163
+ | usePlaceholder | Boolean | true | :x: | Whether the image should use a blurred image placeholder |
164
+ | srcSetCandidates | Array<number> | [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4] | :x: | If `data` does not contain `srcSet`, the candidates for the `srcset` attribute of the image will be auto-generated based on these width multipliers |
165
+
166
+ ### Events
167
+
168
+ | prop | description |
169
+ | ----- | ------------------------------------------- |
170
+ | @load | Emitted when the image has finished loading |
171
+
172
+ ## `<Image />`
173
+
108
174
  ### Props
109
175
 
110
- | prop | type | default | required | description |
111
- | --------------------- | ------------------------------------------------ | ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
112
- | data | `ResponsiveImage` object | | :white_check_mark: | The actual response you get from a DatoCMS `responsiveImage` GraphQL query. |
113
- | class | string | null | :x: | Additional CSS class of root node |
114
- | style | CSS properties | null | :x: | Additional CSS rules to add to the root node |
115
- | pictureClass | string | null | :x: | Additional CSS class for the inner `<picture />` tag |
116
- | pictureStyle | CSS properties | null | :x: | Additional CSS rules to add to the inner `<picture />` tag |
117
- | layout | 'intrinsic' \| 'fixed' \| 'responsive' \| 'fill' | "intrinsic" | :x: | The layout behavior of the image as the viewport changes size |
118
- | fadeInDuration | integer | 500 | :x: | Duration (in ms) of the fade-in transition effect upoad image loading |
119
- | intersectionThreshold | float | 0 | :x: | Indicate at what percentage of the placeholder visibility the loading of the image should be triggered. A value of 0 means that as soon as even one pixel is visible, the callback will be run. A value of 1.0 means that the threshold isn't considered passed until every pixel is visible. |
120
- | intersectionMargin | string | "0px 0px 0px 0px" | :x: | Margin around the placeholder. Can have values similar to the CSS margin property (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the placeholder element's bounding box before computing intersections. |
121
- | lazyLoad | Boolean | true | :x: | Wheter enable lazy loading or not |
122
- | explicitWidth | Boolean | false | :x: | Wheter the image wrapper should explicitely declare the width of the image or keep it fluid |
123
- | objectFit | String | null | :x: | Defines how the image will fit into its parent container when using layout="fill" |
124
- | objectPosition | String | null | :x: | Defines how the image is positioned within its parent element when using layout="fill". |
125
- | priority | Boolean | false | :x: | Disables lazy loading, and sets the image [fetchPriority](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority) to "high" |
126
- | srcSetCandidates | Array<number> | [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4] | :x: | If `data` does not contain `srcSet`, the candidates for the `srcset` attribute of the image will be auto-generated based on these width multipliers |
127
- | sizes | string | undefined | :x: | The HTML5 [`sizes`](https://web.dev/learn/design/responsive-images/#sizes) attribute for the image (will be used `data.sizes` as a fallback) |
128
- | onLoad | () => void | undefined | :x: | Function triggered when the image has finished loading |
129
- | usePlaceholder | Boolean | true | :x: | Whether the component should use a blurred image placeholder |
130
-
131
- #### Layout mode
176
+ | prop | type | default | required | description |
177
+ | --------------------- | ------------------------------------------------ | ---------------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
178
+ | data | `ResponsiveImage` object | | :white_check_mark: | The actual response you get from a DatoCMS `responsiveImage` GraphQL query. |
179
+ | class | string | null | :x: | Additional CSS class of root node |
180
+ | style | string | null | :x: | Additional CSS rules to add to the root node |
181
+ | pictureClass | string | null | :x: | Additional CSS class for the inner `<picture />` tag |
182
+ | pictureStyle | string | null | :x: | Additional CSS rules to add to the inner `<picture />` tag |
183
+ | layout | 'intrinsic' \| 'fixed' \| 'responsive' \| 'fill' | "intrinsic" | :x: | The layout behavior of the image as the viewport changes size |
184
+ | fadeInDuration | integer | 500 | :x: | Duration (in ms) of the fade-in transition effect upoad image loading |
185
+ | intersectionThreshold | float | 0 | :x: | Indicate at what percentage of the placeholder visibility the loading of the image should be triggered. A value of 0 means that as soon as even one pixel is visible, the callback will be run. A value of 1.0 means that the threshold isn't considered passed until every pixel is visible. |
186
+ | intersectionMargin | string | "0px 0px 0px 0px" | :x: | Margin around the placeholder. Can have values similar to the CSS margin property (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the placeholder element's bounding box before computing intersections. |
187
+ | lazyLoad | Boolean | true | :x: | Wheter enable lazy loading or not |
188
+ | explicitWidth | Boolean | false | :x: | Wheter the image wrapper should explicitely declare the width of the image or keep it fluid |
189
+ | objectFit | String | null | :x: | Defines how the image will fit into its parent container when using layout="fill" |
190
+ | objectPosition | String | null | :x: | Defines how the image is positioned within its parent element when using layout="fill". |
191
+ | priority | Boolean | false | :x: | Disables lazy loading, and sets the image [fetchPriority](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority) to "high" |
192
+ | srcSetCandidates | Array<number> | [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4] | :x: | If `data` does not contain `srcSet`, the candidates for the `srcset` attribute of the image will be auto-generated based on these width multipliers |
193
+ | sizes | string | undefined | :x: | The HTML5 [`sizes`](https://web.dev/learn/design/responsive-images/#sizes) attribute for the image (will be used `data.sizes` as a fallback) |
194
+ | onLoad | () => void | undefined | :x: | Function triggered when the image has finished loading |
195
+ | usePlaceholder | Boolean | true | :x: | Whether the component should use a blurred image placeholder |
196
+
197
+ ### Events
198
+
199
+ | prop | description |
200
+ | ----- | ------------------------------------------- |
201
+ | @load | Emitted when the image has finished loading |
202
+
203
+ ---
204
+
205
+ ### Layout mode
132
206
 
133
207
  With the `layout` property, you can configure the behavior of the image as the viewport changes size:
134
208
 
@@ -139,29 +213,8 @@ With the `layout` property, you can configure the behavior of the image as the v
139
213
  - This is usually paired with the `objectFit` and `objectPosition` properties.
140
214
  - Ensure the parent element has `position: relative` in their stylesheet.
141
215
 
142
- #### The `ResponsiveImage` object
216
+ ### Intersection Observer
143
217
 
144
- The `data` prop expects an object with the same shape as the one returned by `responsiveImage` GraphQL call. It's up to you to make a GraphQL query that will return the properties you need for a specific use of the `<datocms-image>` component.
218
+ `IntersectionObserver` is the API used to determine if the image is inside the viewport or not. [Browser support is really good](https://caniuse.com/intersectionobserver): with Safari adding support in 12.1, all major browsers now support `IntersectionObserver` natively.
145
219
 
146
- - The minimum required properties for `data` are: `src`, `width` and `height`;
147
- - `alt` and `title`, while not mandatory, are all highly suggested, so remember to use them!
148
- - If you don't request `srcSet`, the component will auto-generate an `srcset` based on `src` + the `srcSetCandidates` prop (it can help reducing the GraphQL response size drammatically when many images are returned);
149
- - We strongly to suggest to always specify [`{ auto: format }`](https://docs.imgix.com/apis/rendering/auto/auto#format) in your `imgixParams`, instead of requesting `webpSrcSet`, so that you can also take advantage of more performant optimizations (AVIF), without increasing GraphQL response size;
150
- - If you request both the `bgColor` and `base64` property, the latter will take precedence, so just avoid querying both fields at the same time, as it will only make the GraphQL response bigger :wink:;
151
- - You can avoid requesting `sizes` and directly pass a `sizes` prop to the component to reduce the GraphQL response size;
152
-
153
- Here's a complete recap of what `responsiveImage` offers:
154
-
155
- | property | type | required | description |
156
- | ----------- | ------- | ------------------ | ----------------------------------------------------------------------------------------------- |
157
- | src | string | :white_check_mark: | The `src` attribute for the image |
158
- | width | integer | :white_check_mark: | The width of the image |
159
- | height | integer | :white_check_mark: | The height of the image |
160
- | alt | string | :x: | Alternate text (`alt`) for the image (not required, but strongly suggested!) |
161
- | title | string | :x: | Title attribute (`title`) for the image (not required, but strongly suggested!) |
162
- | sizes | string | :x: | The HTML5 `sizes` attribute for the image (omit it if you're already passing a `sizes` prop to the Image component) |
163
- | base64 | string | :x: | A base64-encoded thumbnail to offer during image loading |
164
- | bgColor | string | :x: | The background color for the image placeholder (omit it if you're already requesting `base64`) |
165
- | srcSet | string | :x: | The HTML5 `srcSet` attribute for the image (can be omitted, the Image component knows how to build it based on `src`) |
166
- | webpSrcSet | string | :x: | The HTML5 `srcSet` attribute for the image in WebP format (deprecated, it's better to use the [`auto=format`](https://docs.imgix.com/apis/rendering/auto/auto#format) Imgix transform instead) |
167
- | aspectRatio | float | :x: | The aspect ratio (width/height) of the image |
220
+ If `IntersectionObserver` object is not available, the component treats the image as it's always visible in the viewport. Feel free to add a [polyfill](https://www.npmjs.com/package/intersection-observer) so that it will also 100% work on older versions of iOS and IE11.
@@ -0,0 +1,13 @@
1
+ import type * as CSS from 'csstype';
2
+ export declare const isSsr: () => boolean;
3
+ export declare const isIntersectionObserverAvailable: () => boolean;
4
+ export declare const universalBtoa: (str: string) => string;
5
+ type State = {
6
+ priority: boolean;
7
+ inView: boolean;
8
+ loaded: boolean;
9
+ };
10
+ export declare const imageAddStrategy: ({ priority, inView, loaded }: State) => boolean;
11
+ export declare const imageShowStrategy: ({ priority, loaded }: State) => boolean;
12
+ export declare const absolutePositioning: CSS.PropertiesHyphen;
13
+ export {};
@@ -0,0 +1,36 @@
1
+ export const isSsr = () => typeof window === 'undefined';
2
+ export const isIntersectionObserverAvailable = () => isSsr() ? false : !!window.IntersectionObserver;
3
+ export const universalBtoa = (str) => isSsr() ? Buffer.from(str.toString(), 'binary').toString('base64') : window.btoa(str);
4
+ export const imageAddStrategy = ({ priority, inView, loaded }) => {
5
+ if (priority) {
6
+ return true;
7
+ }
8
+ if (isSsr()) {
9
+ return false;
10
+ }
11
+ if (isIntersectionObserverAvailable()) {
12
+ return inView || loaded;
13
+ }
14
+ return true;
15
+ };
16
+ export const imageShowStrategy = ({ priority, loaded }) => {
17
+ if (priority) {
18
+ return true;
19
+ }
20
+ if (isSsr()) {
21
+ return false;
22
+ }
23
+ if (isIntersectionObserverAvailable()) {
24
+ return loaded;
25
+ }
26
+ return true;
27
+ };
28
+ export const absolutePositioning = {
29
+ position: 'absolute',
30
+ left: '0px',
31
+ top: '0px',
32
+ width: '100%',
33
+ height: '100%',
34
+ 'max-width': 'none',
35
+ 'max-height': 'none'
36
+ };
@@ -0,0 +1,71 @@
1
+ <script>import { createEventDispatcher } from "svelte";
2
+ import {
3
+ buildSrcSet,
4
+ dumpStyleAttributes,
5
+ noTypeCheck,
6
+ parseStyleAttributes
7
+ } from "./utils";
8
+ export let data;
9
+ let rootClass = null;
10
+ export { rootClass as class };
11
+ export let style = null;
12
+ export let usePlaceholder = true;
13
+ export let sizes = null;
14
+ export let priority = false;
15
+ export let srcSetCandidates = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4];
16
+ const dispatch = createEventDispatcher();
17
+ let loaded = false;
18
+ let placeholderStyle;
19
+ $:
20
+ placeholderStyle = usePlaceholder && !loaded && data.base64 ? {
21
+ "background-image": `url("${data.base64}")`,
22
+ "background-size": "cover",
23
+ "background-repeat": "no-repeat",
24
+ "background-position": "50% 50%",
25
+ color: "transparent"
26
+ } : usePlaceholder && !loaded && data.bgColor ? { "background-color": data.bgColor ?? void 0, color: "transparent" } : void 0;
27
+ $:
28
+ ({ width } = data);
29
+ $:
30
+ height = data.height ?? Math.round(data.aspectRatio ? width / data.aspectRatio : 0);
31
+ let sizingStyle;
32
+ $:
33
+ sizingStyle = {
34
+ "aspect-ratio": `${width} / ${height}`,
35
+ width: "100%",
36
+ "max-width": `${width}px`,
37
+ height: "auto"
38
+ };
39
+ </script>
40
+
41
+ <picture data-testid="picture">
42
+ {#if data.webpSrcSet}
43
+ <source srcset={data.webpSrcSet} sizes={sizes ?? data.sizes ?? null} type="image/webp" />
44
+ {/if}
45
+ <source
46
+ srcset={data.srcSet ?? buildSrcSet(data.src, data.width, srcSetCandidates) ?? null}
47
+ sizes={sizes ?? data.sizes ?? null}
48
+ />
49
+ {#if data.src}
50
+ <img
51
+ src={data.src}
52
+ alt={data.alt ?? ''}
53
+ title={data.title ?? null}
54
+ on:load={() => {
55
+ dispatch('load');
56
+ loaded = true;
57
+ }}
58
+ {...noTypeCheck({
59
+ fetchpriority: priority ? 'high' : undefined
60
+ })}
61
+ loading={priority ? undefined : 'lazy'}
62
+ class={rootClass}
63
+ style={dumpStyleAttributes({
64
+ ...placeholderStyle,
65
+ ...sizingStyle,
66
+ ...parseStyleAttributes(style)
67
+ })}
68
+ data-testid="img"
69
+ />
70
+ {/if}
71
+ </picture>
@@ -0,0 +1,39 @@
1
+ import { SvelteComponentTyped } from "svelte";
2
+ import { type ResponsiveImageType } from './utils';
3
+ declare const __propDef: {
4
+ props: {
5
+ /** The actual response you get from a DatoCMS `responsiveImage` GraphQL query */ data: ResponsiveImageType;
6
+ /** Additional CSS className for root node */ class?: string | null | undefined;
7
+ /** Additional CSS rules to add to the root node */ style?: string | null | undefined;
8
+ /** Whether the component should use a blurred image placeholder */ usePlaceholder?: boolean | undefined;
9
+ /**
10
+ * The HTML5 `sizes` attribute for the image
11
+ *
12
+ * Learn more about srcset and sizes:
13
+ * -> https://web.dev/learn/design/responsive-images/#sizes
14
+ * -> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes
15
+ **/ sizes?: string | null | undefined;
16
+ /**
17
+ * When true, the image will be considered high priority. Lazy loading is automatically disabled, and fetchpriority="high" is added to the image.
18
+ * You should use the priority property on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
19
+ * Should only be used when the image is visible above the fold.
20
+ **/ priority?: boolean | undefined;
21
+ /**
22
+ * If `data` does not contain `srcSet`, the candidates for the `srcset` of the image will be auto-generated based on these width multipliers
23
+ *
24
+ * Default candidate multipliers are [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4]
25
+ **/ srcSetCandidates?: number[] | undefined;
26
+ };
27
+ events: {
28
+ load: CustomEvent<any>;
29
+ } & {
30
+ [evt: string]: CustomEvent<any>;
31
+ };
32
+ slots: {};
33
+ };
34
+ export type NakedImageProps = typeof __propDef.props;
35
+ export type NakedImageEvents = typeof __propDef.events;
36
+ export type NakedImageSlots = typeof __propDef.slots;
37
+ export default class NakedImage extends SvelteComponentTyped<NakedImageProps, NakedImageEvents, NakedImageSlots> {
38
+ }
39
+ export {};
@@ -0,0 +1,31 @@
1
+ import type * as CSS from 'csstype';
2
+ type Maybe<T> = T | null;
3
+ export type ResponsiveImageType = {
4
+ /** A base64-encoded thumbnail to offer during image loading */
5
+ base64?: Maybe<string>;
6
+ /** The height of the image */
7
+ height?: Maybe<number>;
8
+ /** The width of the image */
9
+ width: number;
10
+ /** The aspect ratio (width/height) of the image */
11
+ aspectRatio?: number;
12
+ /** The HTML5 `sizes` attribute for the image */
13
+ sizes?: Maybe<string>;
14
+ /** The fallback `src` attribute for the image */
15
+ src?: Maybe<string>;
16
+ /** The HTML5 `srcSet` attribute for the image */
17
+ srcSet?: Maybe<string>;
18
+ /** The HTML5 `srcSet` attribute for the image in WebP format, for browsers that support the format */
19
+ webpSrcSet?: Maybe<string>;
20
+ /** The background color for the image placeholder */
21
+ bgColor?: Maybe<string>;
22
+ /** Alternate text (`alt`) for the image */
23
+ alt?: Maybe<string>;
24
+ /** Title attribute (`title`) for the image */
25
+ title?: Maybe<string>;
26
+ };
27
+ export declare const parseStyleAttributes: (styleString: string | null) => CSS.PropertiesHyphen;
28
+ export declare const dumpStyleAttributes: (style: CSS.PropertiesHyphen) => string;
29
+ export declare const noTypeCheck: (x: object) => object;
30
+ export declare const buildSrcSet: (src: string | null | undefined, width: number | undefined, candidateMultipliers: number[]) => string | undefined;
31
+ export {};
@@ -0,0 +1,48 @@
1
+ export const parseStyleAttributes = (styleString) => {
2
+ const styleRules = {};
3
+ if (styleString) {
4
+ for (const rule of styleString.split(';')) {
5
+ const [key, value] = rule.split(':').map((part) => part.trim());
6
+ if (key && value) {
7
+ styleRules[key] = value;
8
+ }
9
+ }
10
+ }
11
+ return styleRules;
12
+ };
13
+ export const dumpStyleAttributes = (style) => {
14
+ return Object.entries(style)
15
+ .map(([key, value]) => typeof value !== 'undefined' && value !== 'null' ? `${key}: ${value};` : undefined)
16
+ .filter(Boolean)
17
+ .join(' ');
18
+ };
19
+ // See: https://github.com/sveltejs/language-tools/issues/1026#issuecomment-1002839154
20
+ export const noTypeCheck = (x) => x;
21
+ const bogusBaseUrl = 'https://example.com/';
22
+ export const buildSrcSet = (src, width, candidateMultipliers) => {
23
+ if (!(src && width)) {
24
+ return undefined;
25
+ }
26
+ return candidateMultipliers
27
+ .map((multiplier) => {
28
+ const url = new URL(src, bogusBaseUrl);
29
+ if (multiplier !== 1) {
30
+ url.searchParams.set('dpr', `${multiplier}`);
31
+ const maxH = url.searchParams.get('max-h');
32
+ const maxW = url.searchParams.get('max-w');
33
+ if (maxH) {
34
+ url.searchParams.set('max-h', `${Math.floor(Number.parseInt(maxH) * multiplier)}`);
35
+ }
36
+ if (maxW) {
37
+ url.searchParams.set('max-w', `${Math.floor(Number.parseInt(maxW) * multiplier)}`);
38
+ }
39
+ }
40
+ const finalWidth = Math.floor(width * multiplier);
41
+ if (finalWidth < 50) {
42
+ return null;
43
+ }
44
+ return `${url.toString().replace(bogusBaseUrl, '/')} ${finalWidth}w`;
45
+ })
46
+ .filter(Boolean)
47
+ .join(',');
48
+ };
@@ -4,11 +4,18 @@
4
4
 
5
5
  ### Table of contents
6
6
 
7
- - [Setup](#setup)
7
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
8
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
9
+
10
+ - [Setup](#setup)
8
11
  - [Basic usage](#basic-usage)
9
- - [Custom renderers](#custom-renderers)
12
+ - [Customization](#customization)
13
+ - [Custom components for blocks](#custom-components-for-blocks)
14
+ - [Override default rendering of nodes](#override-default-rendering-of-nodes)
10
15
  - [Props](#props)
11
16
 
17
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
18
+
12
19
  ### Setup
13
20
 
14
21
  Import the component like this:
@@ -1,4 +1,6 @@
1
- <script>import { isStructuredText } from "datocms-structured-text-utils";
1
+ <script>import {
2
+ isStructuredText
3
+ } from "datocms-structured-text-utils";
2
4
  import Node from "./Node.svelte";
3
5
  export let data = null;
4
6
  export let components = [];
@@ -18,7 +18,7 @@ $:
18
18
  {:else if mark === 'underline'}
19
19
  <u><svelte:self node={{ type, value, marks: otherMarks }}><slot /></svelte:self></u>
20
20
  {:else if mark === 'code'}
21
- <pre><svelte:self node={{ type, value, marks: otherMarks }}><slot /></svelte:self></pre>
21
+ <code><svelte:self node={{ type, value, marks: otherMarks }}><slot /></svelte:self></code>
22
22
  {/if}
23
23
  {:else}
24
24
  <Lines lines={node.value.split(/\n/)} />
@@ -2,4 +2,4 @@
2
2
  node;
3
3
  </script>
4
4
 
5
- <hr />
5
+ <hr />
@@ -17,10 +17,22 @@ optimal videos to your users.
17
17
 
18
18
  - Offers optimized streaming so smartphones and tablets don’t request desktop-sized videos
19
19
  - Lazy loads the underlying video player web component and the video to be
20
- played to speed initial page load and save bandwidth
20
+ played to speed initial page load and save bandwidth
21
21
  - Holds the video position so your page doesn’t jump while the player loads
22
22
  - Uses blur-up technique to show a placeholder of the video while it loads
23
23
 
24
+ ### Table of contents
25
+
26
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
27
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
28
+
29
+ - [Installation](#installation)
30
+ - [Usage](#usage)
31
+ - [Example](#example)
32
+ - [Props](#props)
33
+
34
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
35
+
24
36
  ## Installation
25
37
 
26
38
  ```sh {"id":"01HP46D8MDP5Y76HY788MWNDMX"}
@@ -118,10 +130,10 @@ inner `<mux-player />`.
118
130
  `<VideoPlayer />` generate some default attributes:
119
131
 
120
132
  - when not declared, the `disableCookies` prop is true, unless you explicitly
121
- set the prop to `false` (therefore it generates a `disable-cookies` attribute)
133
+ set the prop to `false` (therefore it generates a `disable-cookies` attribute)
122
134
  - `preload` defaults to `metadata`, for an optimal UX experience together with saved bandwidth
123
135
  - the video height and width, when available in the `data` props, are used to
124
- set a default `aspect-ratio: [width] / [height];` for the `<mux-player />`'s
125
- `style` attribute
136
+ set a default `aspect-ratio: [width] / [height];` for the `<mux-player />`'s
137
+ `style` attribute
126
138
 
127
139
  All the other props are forwarded to the `<mux-player />` web component that is used internally.
@@ -119,8 +119,8 @@ declare const __propDef: {
119
119
  suspend: Event;
120
120
  ended: Event;
121
121
  error: ErrorEvent;
122
- cuepointchange: Event | UIEvent | ProgressEvent<EventTarget> | ErrorEvent | MouseEvent | FocusEvent | AnimationEvent | InputEvent | CompositionEvent | ClipboardEvent | DragEvent | FormDataEvent | PointerEvent | KeyboardEvent | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent;
123
- cuepointschange: Event | UIEvent | ProgressEvent<EventTarget> | ErrorEvent | MouseEvent | FocusEvent | AnimationEvent | InputEvent | CompositionEvent | ClipboardEvent | DragEvent | FormDataEvent | PointerEvent | KeyboardEvent | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent;
122
+ cuepointchange: Event | UIEvent | ProgressEvent<EventTarget> | ErrorEvent | ClipboardEvent | DragEvent | MouseEvent | FocusEvent | AnimationEvent | InputEvent | CompositionEvent | FormDataEvent | PointerEvent | KeyboardEvent | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent;
123
+ cuepointschange: Event | UIEvent | ProgressEvent<EventTarget> | ErrorEvent | ClipboardEvent | DragEvent | MouseEvent | FocusEvent | AnimationEvent | InputEvent | CompositionEvent | FormDataEvent | PointerEvent | KeyboardEvent | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent;
124
124
  } & {
125
125
  [evt: string]: CustomEvent<any>;
126
126
  };
@@ -54,13 +54,13 @@ describe('VideoPlayer', () => {
54
54
  });
55
55
  describe('and `preload` is passed', () => {
56
56
  it('uses it for the <mux-player /> element', () => {
57
- const props = { data, preload: "auto" };
57
+ const props = { data, preload: 'auto' };
58
58
  const { container } = render(VideoPlayer, { props });
59
59
  expect(container).toMatchSnapshot();
60
60
  });
61
61
  describe('with value `none`', () => {
62
62
  it("doesn't use it for the <mux-player /> element", () => {
63
- const props = { data, preload: "none" };
63
+ const props = { data, preload: 'none' };
64
64
  const { container } = render(VideoPlayer, { props });
65
65
  expect(container).toMatchSnapshot();
66
66
  });