@datocms/svelte 1.2.2 → 1.3.0

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 (42) hide show
  1. package/package/components/Head/Head.svelte +14 -0
  2. package/package/components/Head/Head.svelte.d.ts +61 -0
  3. package/package/components/Head/README.md +68 -0
  4. package/package/components/Image/Image.svelte +172 -0
  5. package/package/components/Image/Image.svelte.d.ts +83 -0
  6. package/package/components/Image/Placeholder.svelte +30 -0
  7. package/package/components/Image/Placeholder.svelte.d.ts +22 -0
  8. package/package/components/Image/README.md +167 -0
  9. package/package/components/Image/Sizer.svelte +17 -0
  10. package/package/components/Image/Sizer.svelte.d.ts +19 -0
  11. package/package/components/Image/Source.svelte +6 -0
  12. package/package/components/Image/Source.svelte.d.ts +18 -0
  13. package/package/components/StructuredText/Node.svelte +112 -0
  14. package/package/components/StructuredText/Node.svelte.d.ts +22 -0
  15. package/package/components/StructuredText/README.md +201 -0
  16. package/package/components/StructuredText/StructuredText.svelte +15 -0
  17. package/package/components/StructuredText/StructuredText.svelte.d.ts +19 -0
  18. package/package/components/StructuredText/nodes/Blockquote.svelte +5 -0
  19. package/package/components/StructuredText/nodes/Blockquote.svelte.d.ts +19 -0
  20. package/package/components/StructuredText/nodes/Code.svelte +6 -0
  21. package/package/components/StructuredText/nodes/Code.svelte.d.ts +17 -0
  22. package/package/components/StructuredText/nodes/Heading.svelte +8 -0
  23. package/package/components/StructuredText/nodes/Heading.svelte.d.ts +19 -0
  24. package/package/components/StructuredText/nodes/Link.svelte +20 -0
  25. package/package/components/StructuredText/nodes/Link.svelte.d.ts +19 -0
  26. package/package/components/StructuredText/nodes/List.svelte +10 -0
  27. package/package/components/StructuredText/nodes/List.svelte.d.ts +19 -0
  28. package/package/components/StructuredText/nodes/ListItem.svelte +5 -0
  29. package/package/components/StructuredText/nodes/ListItem.svelte.d.ts +19 -0
  30. package/package/components/StructuredText/nodes/Paragraph.svelte +5 -0
  31. package/package/components/StructuredText/nodes/Paragraph.svelte.d.ts +19 -0
  32. package/package/components/StructuredText/nodes/Root.svelte +5 -0
  33. package/package/components/StructuredText/nodes/Root.svelte.d.ts +19 -0
  34. package/package/components/StructuredText/nodes/Span.svelte +49 -0
  35. package/package/components/StructuredText/nodes/Span.svelte.d.ts +19 -0
  36. package/package/components/StructuredText/nodes/ThematicBreak.svelte +5 -0
  37. package/package/components/StructuredText/nodes/ThematicBreak.svelte.d.ts +17 -0
  38. package/package/components/StructuredText/utils/Lines.svelte +11 -0
  39. package/package/components/StructuredText/utils/Lines.svelte.d.ts +16 -0
  40. package/package/index.d.ts +9 -0
  41. package/package/index.js +3 -0
  42. package/package.json +222 -215
@@ -0,0 +1,14 @@
1
+ <script context="module"></script>
2
+
3
+ <script>export let data = [];
4
+ </script>
5
+
6
+ <svelte:head>
7
+ {#each data as { tag, attributes, content }}
8
+ {#if content}
9
+ <svelte:element this={tag} {...attributes}>{content}</svelte:element>
10
+ {:else}
11
+ <svelte:element this={tag} {...attributes} />
12
+ {/if}
13
+ {/each}
14
+ </svelte:head>
@@ -0,0 +1,61 @@
1
+ import { SvelteComponentTyped } from "svelte";
2
+ export interface TitleMetaLinkTag {
3
+ /** the tag for the meta information */
4
+ tag: "title" | "meta" | "link";
5
+ /** the inner content of the meta tag */
6
+ content?: string | null | undefined;
7
+ /** the HTML attributes to attach to the meta tag */
8
+ attributes?: Record<string, string> | null | undefined;
9
+ }
10
+ export interface SeoTitleTag {
11
+ tag: 'title';
12
+ content: string | null;
13
+ attributes?: null;
14
+ }
15
+ export interface RegularMetaAttributes {
16
+ name: string;
17
+ content: string;
18
+ }
19
+ export interface OgMetaAttributes {
20
+ property: string;
21
+ content: string;
22
+ }
23
+ export interface SeoMetaTag {
24
+ tag: 'meta';
25
+ content?: null;
26
+ attributes: RegularMetaAttributes | OgMetaAttributes;
27
+ }
28
+ export interface FaviconAttributes {
29
+ sizes: string;
30
+ type: string;
31
+ rel: string;
32
+ href: string;
33
+ }
34
+ export interface AppleTouchIconAttributes {
35
+ sizes: string;
36
+ rel: 'apple-touch-icon';
37
+ href: string;
38
+ }
39
+ export interface SeoLinkTag {
40
+ tag: 'link';
41
+ content?: null;
42
+ attributes: FaviconAttributes | AppleTouchIconAttributes;
43
+ }
44
+ export type SeoTag = SeoTitleTag | SeoMetaTag;
45
+ export type FaviconTag = SeoMetaTag | SeoLinkTag;
46
+ export type SeoOrFaviconTag = SeoTag | FaviconTag;
47
+ declare const __propDef: {
48
+ props: {
49
+ data?: (TitleMetaLinkTag | SeoOrFaviconTag)[] | undefined;
50
+ };
51
+ events: {
52
+ [evt: string]: CustomEvent<any>;
53
+ };
54
+ slots: {};
55
+ };
56
+ export type HeadProps = typeof __propDef.props;
57
+ export type HeadEvents = typeof __propDef.events;
58
+ export type HeadSlots = typeof __propDef.slots;
59
+ export default class Head extends SvelteComponentTyped<HeadProps, HeadEvents, HeadSlots> {
60
+ }
61
+ export {};
@@ -0,0 +1,68 @@
1
+ ## Social share, SEO and Favicon meta tags
2
+
3
+ Just like the image component, `<Head />` is a component specially designed to work seamlessly with DatoCMS’s [`_seoMetaTags` and `faviconMetaTags` GraphQL queries](https://www.datocms.com/docs/content-delivery-api/seo) so that you can handle proper SEO in your pages.
4
+
5
+ You can use `<Head />` your components, and it will inject title, meta and link tags in the document's `<head></head>` tag.
6
+
7
+ ### Table of contents
8
+
9
+ - [Usage](#usage)
10
+ - [Example](#example)
11
+
12
+ ### Usage
13
+
14
+ `<Head />`'s `data` prop takes an array of `Tag`s in the exact form they're returned by the following [DatoCMS GraphQL API](https://www.datocms.com/docs/content-delivery-api/seo) queries:
15
+
16
+ - `_seoMetaTags` query on any record, or
17
+ - `faviconMetaTags` on the global `_site` object.
18
+
19
+ ### Example
20
+
21
+ Here is an example:
22
+
23
+ ```svelte
24
+ <script>
25
+ import { onMount } from 'svelte';
26
+
27
+ import { Head } from '@datocms/svelte';
28
+
29
+ const query = `
30
+ query {
31
+ page: homepage {
32
+ title
33
+ seo: _seoMetaTags {
34
+ attributes
35
+ content
36
+ tag
37
+ }
38
+ }
39
+ site: _site {
40
+ favicon: faviconMetaTags {
41
+ attributes
42
+ content
43
+ tag
44
+ }
45
+ }
46
+ }
47
+ `;
48
+
49
+ export let data = null;
50
+
51
+ onMount(async () => {
52
+ const response = await fetch('https://graphql.datocms.com/', {
53
+ method: 'POST',
54
+ headers: {
55
+ 'Content-Type': 'application/json',
56
+ Authorization: 'Bearer faeb9172e232a75339242faafb9e56de8c8f13b735f7090964'
57
+ },
58
+ body: JSON.stringify({ query })
59
+ });
60
+
61
+ const json = await response.json();
62
+
63
+ data = [...json.data.page.seo, ...json.data.site.favicon];
64
+ });
65
+ </script>
66
+
67
+ <Head {data} />
68
+ ```
@@ -0,0 +1,172 @@
1
+ <script context="module">import IntersectionObserver from "svelte-intersection-observer";
2
+ const isWindowDefined = typeof window !== "undefined";
3
+ const noTypeCheck = (x) => x;
4
+ const imageAddStrategy = ({ lazyLoad, intersecting, loaded }) => {
5
+ const isIntersectionObserverAvailable = isWindowDefined ? !!window.IntersectionObserver : false;
6
+ if (!lazyLoad) {
7
+ return true;
8
+ }
9
+ if (!isWindowDefined) {
10
+ return false;
11
+ }
12
+ if (isIntersectionObserverAvailable) {
13
+ return intersecting || loaded;
14
+ }
15
+ return true;
16
+ };
17
+ const imageShowStrategy = ({ lazyLoad, loaded }) => {
18
+ const isIntersectionObserverAvailable = isWindowDefined ? !!window.IntersectionObserver : false;
19
+ if (!lazyLoad) {
20
+ return true;
21
+ }
22
+ if (!isWindowDefined) {
23
+ return false;
24
+ }
25
+ if (isIntersectionObserverAvailable) {
26
+ return loaded;
27
+ }
28
+ return true;
29
+ };
30
+ const bogusBaseUrl = "https://example.com/";
31
+ const buildSrcSet = (src, width, candidateMultipliers) => {
32
+ if (!(src && width)) {
33
+ return void 0;
34
+ }
35
+ return candidateMultipliers.map((multiplier) => {
36
+ const url = new URL(src, bogusBaseUrl);
37
+ if (multiplier !== 1) {
38
+ url.searchParams.set("dpr", `${multiplier}`);
39
+ const maxH = url.searchParams.get("max-h");
40
+ const maxW = url.searchParams.get("max-w");
41
+ if (maxH) {
42
+ url.searchParams.set("max-h", `${Math.floor(parseInt(maxH) * multiplier)}`);
43
+ }
44
+ if (maxW) {
45
+ url.searchParams.set("max-w", `${Math.floor(parseInt(maxW) * multiplier)}`);
46
+ }
47
+ }
48
+ const finalWidth = Math.floor(width * multiplier);
49
+ if (finalWidth < 50) {
50
+ return null;
51
+ }
52
+ return `${url.toString().replace(bogusBaseUrl, "/")} ${finalWidth}w`;
53
+ }).filter(Boolean).join(",");
54
+ };
55
+ </script>
56
+
57
+ <script>import { createEventDispatcher } from "svelte";
58
+ import Sizer from "./Sizer.svelte";
59
+ import Placeholder from "./Placeholder.svelte";
60
+ import Source from "./Source.svelte";
61
+ const dispatch = createEventDispatcher();
62
+ let element;
63
+ let intersecting = false;
64
+ let loaded = false;
65
+ export let alt = null;
66
+ export let data;
67
+ let klass = null;
68
+ export { klass as class };
69
+ export let pictureClass = null;
70
+ export let fadeInDuration = 500;
71
+ export let intersectionThreshold = 0;
72
+ export let intersectionMargin = "0px";
73
+ let rawLazyLoad = true;
74
+ export { rawLazyLoad as lazyLoad };
75
+ export let style = {};
76
+ export let pictureStyle = null;
77
+ export let layout = "intrinsic";
78
+ export let objectFit = void 0;
79
+ export let objectPosition = void 0;
80
+ export let usePlaceholder = true;
81
+ export let sizes = null;
82
+ export let priority = false;
83
+ export let srcSetCandidates = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4];
84
+ $:
85
+ ({ width, height, aspectRatio } = data);
86
+ $:
87
+ lazyLoad = priority ? false : rawLazyLoad;
88
+ $:
89
+ addImage = imageAddStrategy({
90
+ lazyLoad,
91
+ intersecting,
92
+ loaded
93
+ });
94
+ $:
95
+ showImage = imageShowStrategy({
96
+ lazyLoad,
97
+ intersecting,
98
+ loaded
99
+ });
100
+ let transition = fadeInDuration > 0 ? `opacity ${fadeInDuration}ms` : void 0;
101
+ </script>
102
+
103
+ <IntersectionObserver
104
+ {element}
105
+ bind:intersecting
106
+ threshold={intersectionThreshold}
107
+ rootMargin={intersectionMargin}
108
+ >
109
+ <div
110
+ bind:this={element}
111
+ class={klass}
112
+ style:overflow="hidden"
113
+ style:position={style.position ?? layout === 'fill' ? 'absolute' : 'relative'}
114
+ style:width={style.width ?? layout === 'fixed' ? data.width : '100%'}
115
+ style:maxWidth={style.maxWidth ?? layout === 'intrinsic' ? data.width : null}
116
+ style:height={style.height ?? layout === 'fill' ? '100%' : null}
117
+ data-testid="image"
118
+ >
119
+ {#if layout !== 'fill' && width}
120
+ <Sizer {width} {height} {aspectRatio} />
121
+ {/if}
122
+
123
+ {#if usePlaceholder && (data.bgColor || data.base64)}
124
+ <Placeholder
125
+ base64={data.base64}
126
+ backgroundColor={data.bgColor}
127
+ {objectFit}
128
+ {objectPosition}
129
+ {showImage}
130
+ {fadeInDuration}
131
+ />
132
+ {/if}
133
+
134
+ {#if addImage}
135
+ <picture style={pictureStyle} data-testid="picture">
136
+ {#if data.webpSrcSet}
137
+ <Source srcset={data.webpSrcSet} sizes={sizes ?? data.sizes ?? null} type="image/webp" />
138
+ {/if}
139
+ <Source
140
+ srcset={data.srcSet ?? buildSrcSet(data.src, data.width, srcSetCandidates) ?? null}
141
+ sizes={sizes ?? data.sizes ?? null}
142
+ />
143
+ {#if data.src}
144
+ <img
145
+ {...noTypeCheck({
146
+ // See: https://github.com/sveltejs/language-tools/issues/1026#issuecomment-1002839154
147
+ fetchpriority: priority ? 'high' : undefined
148
+ })}
149
+ src={data.src}
150
+ alt={alt ?? data.alt ?? ''}
151
+ title={data.title ?? null}
152
+ on:load={() => {
153
+ dispatch('load');
154
+ loaded = true;
155
+ }}
156
+ class={pictureClass}
157
+ style:opacity={showImage ? 1 : 0}
158
+ style:transition
159
+ style:position="absolute"
160
+ style:left="0"
161
+ style:top="0"
162
+ style:width="100%"
163
+ style:height="100%"
164
+ style:objectFit
165
+ style:objectPosition
166
+ data-testid="img"
167
+ />
168
+ {/if}
169
+ </picture>
170
+ {/if}
171
+ </div>
172
+ </IntersectionObserver>
@@ -0,0 +1,83 @@
1
+ import { SvelteComponentTyped } from "svelte";
2
+ export 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
+ import type * as CSS from 'csstype';
28
+ declare const __propDef: {
29
+ props: {
30
+ alt?: string | null | undefined;
31
+ /** The actual response you get from a DatoCMS `responsiveImage` GraphQL query */ data: ResponsiveImageType;
32
+ /** Additional CSS className for root node */ class?: string | null | undefined;
33
+ /** Additional CSS class for the image inside the `<picture />` tag */ pictureClass?: string | null | undefined;
34
+ /** Duration (in ms) of the fade-in transition effect upoad image loading */ fadeInDuration?: number | undefined;
35
+ /** 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 */ intersectionThreshold?: number | undefined;
36
+ /** 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 */ intersectionMargin?: string | undefined;
37
+ /** Whether enable lazy loading or not */ lazyLoad?: boolean | undefined;
38
+ /** Additional CSS rules to add to the root node */ style?: Record<string, string> | undefined;
39
+ /** Additional CSS rules to add to the image inside the `<picture />` tag */ pictureStyle?: string | null | undefined;
40
+ /**
41
+ * The layout behavior of the image as the viewport changes size
42
+ *
43
+ * Possible values:
44
+ *
45
+ * * `intrinsic` (default): the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports
46
+ * * `fixed`: the image dimensions will not change as the viewport changes (no responsiveness) similar to the native img element
47
+ * * `responsive`: the image will scale the dimensions down for smaller viewports and scale up for larger viewports
48
+ * * `fill`: image will stretch both width and height to the dimensions of the parent element, provided the parent element is `relative`
49
+ **/ layout?: "fill" | "intrinsic" | "fixed" | "responsive" | undefined;
50
+ /** Defines how the image will fit into its parent container when using layout="fill" */ objectFit?: CSS.Properties['objectFit'];
51
+ /** Defines how the image is positioned within its parent element when using layout="fill". */ objectPosition?: CSS.Properties['objectPosition'];
52
+ /** Whether the component should use a blurred image placeholder */ usePlaceholder?: boolean | undefined;
53
+ /**
54
+ * The HTML5 `sizes` attribute for the image
55
+ *
56
+ * Learn more about srcset and sizes:
57
+ * -> https://web.dev/learn/design/responsive-images/#sizes
58
+ * -> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes
59
+ **/ sizes?: string | null | undefined;
60
+ /**
61
+ * When true, the image will be considered high priority. Lazy loading is automatically disabled, and fetchpriority="high" is added to the image.
62
+ * 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.
63
+ * Should only be used when the image is visible above the fold.
64
+ **/ priority?: boolean | undefined;
65
+ /**
66
+ * If `data` does not contain `srcSet`, the candidates for the `srcset` of the image will be auto-generated based on these width multipliers
67
+ *
68
+ * Default candidate multipliers are [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4]
69
+ **/ srcSetCandidates?: number[] | undefined;
70
+ };
71
+ events: {
72
+ load: CustomEvent<any>;
73
+ } & {
74
+ [evt: string]: CustomEvent<any>;
75
+ };
76
+ slots: {};
77
+ };
78
+ export type ImageProps = typeof __propDef.props;
79
+ export type ImageEvents = typeof __propDef.events;
80
+ export type ImageSlots = typeof __propDef.slots;
81
+ export default class Image extends SvelteComponentTyped<ImageProps, ImageEvents, ImageSlots> {
82
+ }
83
+ export {};
@@ -0,0 +1,30 @@
1
+ <script>export let base64 = null;
2
+ export let backgroundColor = null;
3
+ export let objectFit;
4
+ export let objectPosition;
5
+ export let showImage;
6
+ export let fadeInDuration = 0;
7
+ let transition = fadeInDuration > 0 ? `opacity ${fadeInDuration}ms` : void 0;
8
+ let opacity = showImage ? 0 : 1;
9
+ </script>
10
+
11
+ <img
12
+ class="placeholder"
13
+ aria-hidden="true"
14
+ alt=""
15
+ src={base64}
16
+ style:backgroundColor
17
+ style:objectFit
18
+ style:objectPosition
19
+ style:transition
20
+ style:opacity
21
+ />
22
+
23
+ <style>
24
+ .placeholder {
25
+ position: absolute;
26
+ width: 100%;
27
+ top: 0;
28
+ scale: 110%;
29
+ }
30
+ </style>
@@ -0,0 +1,22 @@
1
+ import { SvelteComponentTyped } from "svelte";
2
+ import type * as CSS from 'csstype';
3
+ declare const __propDef: {
4
+ props: {
5
+ base64?: string | null | undefined;
6
+ backgroundColor?: string | null | undefined;
7
+ objectFit: CSS.Properties['objectFit'];
8
+ objectPosition: CSS.Properties['objectPosition'];
9
+ showImage: boolean;
10
+ fadeInDuration?: number | undefined;
11
+ };
12
+ events: {
13
+ [evt: string]: CustomEvent<any>;
14
+ };
15
+ slots: {};
16
+ };
17
+ export type PlaceholderProps = typeof __propDef.props;
18
+ export type PlaceholderEvents = typeof __propDef.events;
19
+ export type PlaceholderSlots = typeof __propDef.slots;
20
+ export default class Placeholder extends SvelteComponentTyped<PlaceholderProps, PlaceholderEvents, PlaceholderSlots> {
21
+ }
22
+ export {};
@@ -0,0 +1,167 @@
1
+ ## Progressive responsive image
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.
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)
14
+
15
+ ### Out-of-the-box features
16
+
17
+ - Offers optimized version of images for browsers that support WebP/AVIF format
18
+ - Generates multiple smaller images so smartphones and tablets don’t download desktop-sized images
19
+ - Efficiently lazy loads images to speed initial page load and save bandwidth
20
+ - Holds the image position so your page doesn’t jump while images load
21
+ - Uses either blur-up or background color techniques to show a preview of the image while it loads
22
+
23
+ ## Intersection Observer
24
+
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.
26
+
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.
28
+
29
+ ### Setup
30
+
31
+ You can import the components like this:
32
+
33
+ ```js
34
+ import { Image } from '@datocms/svelte';
35
+ ```
36
+
37
+ ### Usage
38
+
39
+ 1. Use `<Image>` it in place of the regular `<img />` tag
40
+ 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
+
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.
43
+
44
+ ### Example
45
+
46
+ 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
+
48
+ Here is a minimal starting point:
49
+
50
+ ```svelte
51
+ <script>
52
+
53
+ import { onMount } from 'svelte';
54
+
55
+ import { Image } from '@datocms/svelte';
56
+
57
+ const query = gql`
58
+ query {
59
+ blogPost {
60
+ title
61
+ cover {
62
+ responsiveImage(
63
+ imgixParams: { fit: crop, w: 300, h: 300, auto: format }
64
+ ) {
65
+ # always required
66
+ src
67
+ width
68
+ height
69
+ # not required, but strongly suggested!
70
+ alt
71
+ title
72
+ # blur-up placeholder, JPEG format, base64-encoded, or...
73
+ base64
74
+ # background color placeholder
75
+ bgColor
76
+ # you can omit `sizes` if you explicitly pass the `sizes` prop to the image component
77
+ sizes
78
+ }
79
+ }
80
+ }
81
+ }
82
+ `;
83
+
84
+ export let data = null;
85
+
86
+ onMount(async () => {
87
+ const response = await fetch('https://graphql.datocms.com/', {
88
+ method: 'POST',
89
+ headers: {
90
+ 'Content-Type': 'application/json',
91
+ Authorization: "Bearer faeb9172e232a75339242faafb9e56de8c8f13b735f7090964",
92
+ },
93
+ body: JSON.stringify({ query })
94
+ })
95
+
96
+ const json = await response.json()
97
+
98
+ data = json.data;
99
+ });
100
+
101
+ </script>
102
+
103
+ {#if data}
104
+ <Image data={data.blogPost.cover.responsiveImage} />
105
+ {/if}
106
+ ```
107
+
108
+ ### Props
109
+
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
132
+
133
+ With the `layout` property, you can configure the behavior of the image as the viewport changes size:
134
+
135
+ - When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
136
+ - When `fixed`, the image dimensions will not change as the viewport changes (no responsiveness) similar to the native `img` element.
137
+ - When `responsive` (default behaviour), the image will scale the dimensions down for smaller viewports and scale up for larger viewports.
138
+ - When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.
139
+ - This is usually paired with the `objectFit` and `objectPosition` properties.
140
+ - Ensure the parent element has `position: relative` in their stylesheet.
141
+
142
+ #### The `ResponsiveImage` object
143
+
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.
145
+
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 |
@@ -0,0 +1,17 @@
1
+ <script>import { encode } from "universal-base64";
2
+ let klass = null;
3
+ export { klass as class };
4
+ export let width;
5
+ export let height;
6
+ export let aspectRatio;
7
+ let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height ?? (aspectRatio ? width / aspectRatio : 0)}"></svg>`;
8
+ </script>
9
+
10
+ <img
11
+ class={klass}
12
+ style:display="block"
13
+ style:width="100%"
14
+ src="data:image/svg+xml;base64,{encode(svg)}"
15
+ aria-hidden="true"
16
+ alt=""
17
+ />
@@ -0,0 +1,19 @@
1
+ import { SvelteComponentTyped } from "svelte";
2
+ declare const __propDef: {
3
+ props: {
4
+ class?: string | null | undefined;
5
+ width: number;
6
+ height: number | null | undefined;
7
+ aspectRatio: number | undefined;
8
+ };
9
+ events: {
10
+ [evt: string]: CustomEvent<any>;
11
+ };
12
+ slots: {};
13
+ };
14
+ export type SizerProps = typeof __propDef.props;
15
+ export type SizerEvents = typeof __propDef.events;
16
+ export type SizerSlots = typeof __propDef.slots;
17
+ export default class Sizer extends SvelteComponentTyped<SizerProps, SizerEvents, SizerSlots> {
18
+ }
19
+ export {};