@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
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  <!--datocms-autoinclude-header start-->
2
+
2
3
  <a href="https://www.datocms.com/"><img src="https://www.datocms.com/images/full_logo.svg" height="60"></a>
3
4
 
4
5
  👉 [Visit the DatoCMS homepage](https://www.datocms.com) or see [What is DatoCMS?](#what-is-datocms)
6
+
5
7
  <!--datocms-autoinclude-header end-->
6
8
 
7
9
  # @datocms/svelte
@@ -14,11 +16,18 @@ A set of components to work faster with [DatoCMS](https://www.datocms.com/) in S
14
16
  - Written in TypeScript;
15
17
  - Usable both client and server side;
16
18
 
17
- ## Table of Contents
19
+ ### Table of Contents
20
+
21
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
22
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
18
23
 
19
- - [Features](#features)
20
- - [Installation](#installation)
21
- - [Development](#development)
24
+ - [Features](#features)
25
+ - [Installation](#installation)
26
+ - [Development](#development)
27
+ - [Building](#building)
28
+ - [What is DatoCMS?](#what-is-datocms)
29
+
30
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
22
31
 
23
32
  ## Features
24
33
 
@@ -36,6 +45,7 @@ Components:
36
45
  ```
37
46
  npm install @datocms/svelte
38
47
  ```
48
+
39
49
  ## Development
40
50
 
41
51
  This repository contains some examples in the `app/routes` folder. You can use them to locally test your changes to the package:
@@ -43,6 +53,7 @@ This repository contains some examples in the `app/routes` folder. You can use t
43
53
  ```bash
44
54
  npm run dev
45
55
  ```
56
+
46
57
  ## Building
47
58
 
48
59
  To create a production version of this library:
@@ -52,8 +63,9 @@ npm run build
52
63
  ```
53
64
 
54
65
  <!--datocms-autoinclude-footer start-->
55
- -----------------
66
+
56
67
  # What is DatoCMS?
68
+
57
69
  <a href="https://www.datocms.com/"><img src="https://www.datocms.com/images/full_logo.svg" height="60"></a>
58
70
 
59
71
  [DatoCMS](https://www.datocms.com/) is the REST & GraphQL Headless CMS for the modern web.
@@ -68,6 +80,7 @@ Trusted by over 25,000 enterprise businesses, agency partners, and individuals a
68
80
  - 🆕 Stay up to date on new features and fixes on the [changelog](https://www.datocms.com/product-updates)
69
81
 
70
82
  **Our featured repos:**
83
+
71
84
  - [datocms/react-datocms](https://github.com/datocms/react-datocms): React helper components for images, Structured Text rendering, and more
72
85
  - [datocms/js-rest-api-clients](https://github.com/datocms/js-rest-api-clients): Node and browser JavaScript clients for updating and administering your content. For frontend fetches, we recommend using our [GraphQL Content Delivery API](https://www.datocms.com/docs/content-delivery-api) instead.
73
86
  - [datocms/cli](https://github.com/datocms/cli): Command-line interface that includes our [Contentful importer](https://github.com/datocms/cli/tree/main/packages/cli-plugin-contentful) and [Wordpress importer](https://github.com/datocms/cli/tree/main/packages/cli-plugin-wordpress)
@@ -76,4 +89,5 @@ Trusted by over 25,000 enterprise businesses, agency partners, and individuals a
76
89
  - Frontend examples in different frameworks: [Next.js](https://github.com/datocms/nextjs-demo), [Vue](https://github.com/datocms/vue-datocms) and [Nuxt](https://github.com/datocms/nuxtjs-demo), [Svelte](https://github.com/datocms/datocms-svelte) and [SvelteKit](https://github.com/datocms/sveltekit-demo), [Astro](https://github.com/datocms/datocms-astro-blog-demo), [Remix](https://github.com/datocms/remix-example). See [all our starter templates](https://www.datocms.com/marketplace/starters).
77
90
 
78
91
  Or see [all our public repos](https://github.com/orgs/datocms/repositories?q=&type=public&language=&sort=stargazers)
92
+
79
93
  <!--datocms-autoinclude-footer end-->
@@ -1,7 +1,7 @@
1
1
  import { SvelteComponentTyped } from "svelte";
2
2
  export interface TitleMetaLinkTag {
3
3
  /** the tag for the meta information */
4
- tag: "title" | "meta" | "link";
4
+ tag: 'title' | 'meta' | 'link';
5
5
  /** the inner content of the meta tag */
6
6
  content?: string | null | undefined;
7
7
  /** the HTML attributes to attach to the meta tag */
@@ -1,4 +1,4 @@
1
- ## Social share, SEO and Favicon meta tags
1
+ # Social share, SEO and Favicon meta tags
2
2
 
3
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
4
 
@@ -6,27 +6,32 @@ You can use `<Head />` your components, and it will inject title, meta and link
6
6
 
7
7
  ### Table of contents
8
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
+
9
12
  - [Usage](#usage)
10
13
  - [Example](#example)
11
14
 
12
- ### Usage
15
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
16
+
17
+ ## Usage
13
18
 
14
19
  `<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
20
 
16
21
  - `_seoMetaTags` query on any record, or
17
22
  - `faviconMetaTags` on the global `_site` object.
18
23
 
19
- ### Example
24
+ ## Example
20
25
 
21
26
  Here is an example:
22
27
 
23
28
  ```svelte
24
29
  <script>
25
- import { onMount } from 'svelte';
30
+ import { onMount } from 'svelte';
26
31
 
27
- import { Head } from '@datocms/svelte';
32
+ import { Head } from '@datocms/svelte';
28
33
 
29
- const query = `
34
+ const query = `
30
35
  query {
31
36
  page: homepage {
32
37
  title
@@ -46,22 +51,22 @@ Here is an example:
46
51
  }
47
52
  `;
48
53
 
49
- export let data = null;
54
+ export let data = null;
50
55
 
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
- });
56
+ onMount(async () => {
57
+ const response = await fetch('https://graphql.datocms.com/', {
58
+ method: 'POST',
59
+ headers: {
60
+ 'Content-Type': 'application/json',
61
+ Authorization: 'Bearer faeb9172e232a75339242faafb9e56de8c8f13b735f7090964'
62
+ },
63
+ body: JSON.stringify({ query })
64
+ });
60
65
 
61
- const json = await response.json();
66
+ const json = await response.json();
62
67
 
63
- data = [...json.data.page.seo, ...json.data.site.favicon];
64
- });
68
+ data = [...json.data.page.seo, ...json.data.site.favicon];
69
+ });
65
70
  </script>
66
71
 
67
72
  <Head {data} />
@@ -1,79 +1,23 @@
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
1
  <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;
2
+ import IntersectionObserver from "svelte-intersection-observer";
3
+ import { imageAddStrategy, imageShowStrategy, absolutePositioning, universalBtoa } from "./utils";
4
+ import {
5
+ buildSrcSet,
6
+ dumpStyleAttributes,
7
+ noTypeCheck,
8
+ parseStyleAttributes
9
+ } from "../NakedImage/utils";
66
10
  export let data;
67
- let klass = null;
68
- export { klass as class };
11
+ let rootClass = null;
12
+ export { rootClass as class };
69
13
  export let pictureClass = null;
14
+ export let placeholderClass = null;
70
15
  export let fadeInDuration = 500;
71
16
  export let intersectionThreshold = 0;
72
17
  export let intersectionMargin = "0px";
73
- let rawLazyLoad = true;
74
- export { rawLazyLoad as lazyLoad };
75
- export let style = {};
18
+ export let style = null;
76
19
  export let pictureStyle = null;
20
+ export let placeholderStyle = null;
77
21
  export let layout = "intrinsic";
78
22
  export let objectFit = void 0;
79
23
  export let objectPosition = void 0;
@@ -81,88 +25,132 @@ export let usePlaceholder = true;
81
25
  export let sizes = null;
82
26
  export let priority = false;
83
27
  export let srcSetCandidates = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4];
28
+ const dispatch = createEventDispatcher();
29
+ let rootEl;
30
+ let inView = false;
31
+ let loaded = false;
32
+ $:
33
+ addImage = imageAddStrategy({ priority, inView, loaded });
34
+ $:
35
+ showImage = imageShowStrategy({ priority, inView, loaded });
84
36
  $:
85
- ({ width, height, aspectRatio } = data);
37
+ transition = fadeInDuration > 0 ? `opacity ${fadeInDuration}ms` : void 0;
38
+ let basePlaceholderStyle;
86
39
  $:
87
- lazyLoad = priority ? false : rawLazyLoad;
40
+ basePlaceholderStyle = {
41
+ transition,
42
+ opacity: showImage ? 0 : 1,
43
+ // During the opacity transition of the placeholder to the definitive version,
44
+ // hardware acceleration is triggered. This results in the browser trying to render the
45
+ // placeholder with your GPU, causing blurred edges. Solution: style the placeholder
46
+ // so the edges overflow the container
47
+ position: "absolute",
48
+ left: "-5%",
49
+ top: "-5%",
50
+ width: "110%",
51
+ height: "110%",
52
+ "max-width": "none",
53
+ "max-height": "none",
54
+ ...parseStyleAttributes(placeholderStyle)
55
+ };
88
56
  $:
89
- addImage = imageAddStrategy({
90
- lazyLoad,
91
- intersecting,
92
- loaded
93
- });
57
+ ({ width, aspectRatio } = data);
94
58
  $:
95
- showImage = imageShowStrategy({
96
- lazyLoad,
97
- intersecting,
98
- loaded
99
- });
100
- let transition = fadeInDuration > 0 ? `opacity ${fadeInDuration}ms` : void 0;
59
+ height = data.height ?? (aspectRatio ? width / aspectRatio : 0);
60
+ $:
61
+ svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"></svg>`;
101
62
  </script>
102
63
 
103
64
  <IntersectionObserver
104
- {element}
105
- bind:intersecting
65
+ element={rootEl}
66
+ bind:intersecting={inView}
106
67
  threshold={intersectionThreshold}
107
68
  rootMargin={intersectionMargin}
108
69
  >
109
70
  <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}px` : '100%'}
115
- style:max-width={style.maxWidth ?? layout === 'intrinsic' ? `${data.width}px` : null}
116
- style:height={style.height ?? layout === 'fill' ? '100%' : null}
71
+ bind:this={rootEl}
72
+ class={rootClass}
73
+ style={dumpStyleAttributes({
74
+ overflow: 'hidden',
75
+ ...(layout === 'fill'
76
+ ? absolutePositioning
77
+ : layout === 'intrinsic'
78
+ ? { position: 'relative', width: '100%', 'max-width': `${width}px` }
79
+ : layout === 'fixed'
80
+ ? { position: 'relative', width: `${width}px` }
81
+ : { position: 'relative', width: '100%' }),
82
+ ...parseStyleAttributes(style)
83
+ })}
117
84
  data-testid="image"
118
85
  >
119
- {#if layout !== 'fill' && width}
120
- <Sizer {width} {height} {aspectRatio} />
86
+ {#if layout !== 'fill'}
87
+ <img
88
+ class={pictureClass}
89
+ style={dumpStyleAttributes({
90
+ display: 'block',
91
+ width: '100%',
92
+ ...parseStyleAttributes(pictureStyle)
93
+ })}
94
+ src={`data:image/svg+xml;base64,${universalBtoa(svg)}`}
95
+ aria-hidden="true"
96
+ alt=""
97
+ />
121
98
  {/if}
122
99
 
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
- />
100
+ {#if usePlaceholder}
101
+ {#if data.base64}
102
+ <img
103
+ aria-hidden="true"
104
+ alt=""
105
+ src={data.base64}
106
+ class={placeholderClass}
107
+ style={dumpStyleAttributes({
108
+ 'object-fit': objectFit,
109
+ 'object-position': objectPosition,
110
+ ...basePlaceholderStyle
111
+ })}
112
+ />
113
+ {:else if data.bgColor}
114
+ <div
115
+ class={placeholderClass}
116
+ style={dumpStyleAttributes({
117
+ 'background-color': data.bgColor,
118
+ ...basePlaceholderStyle
119
+ })}
120
+ />
121
+ {/if}
132
122
  {/if}
133
123
 
134
124
  {#if addImage}
135
- <picture style={pictureStyle} data-testid="picture">
125
+ <picture data-testid="picture">
136
126
  {#if data.webpSrcSet}
137
- <Source srcset={data.webpSrcSet} sizes={sizes ?? data.sizes ?? null} type="image/webp" />
127
+ <source srcset={data.webpSrcSet} sizes={sizes ?? data.sizes ?? null} type="image/webp" />
138
128
  {/if}
139
- <Source
129
+ <source
140
130
  srcset={data.srcSet ?? buildSrcSet(data.src, data.width, srcSetCandidates) ?? null}
141
131
  sizes={sizes ?? data.sizes ?? null}
142
132
  />
143
133
  {#if data.src}
144
134
  <img
145
- {...noTypeCheck({
146
- // See: https://github.com/sveltejs/language-tools/issues/1026#issuecomment-1002839154
147
- fetchpriority: priority ? 'high' : undefined
148
- })}
149
135
  src={data.src}
150
- alt={alt ?? data.alt ?? ''}
136
+ alt={data.alt ?? ''}
151
137
  title={data.title ?? null}
152
138
  on:load={() => {
153
139
  dispatch('load');
154
140
  loaded = true;
155
141
  }}
142
+ {...noTypeCheck({
143
+ fetchpriority: priority ? 'high' : undefined
144
+ })}
156
145
  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:object-fit={objectFit}
165
- style:object-position={objectPosition}
146
+ style={dumpStyleAttributes({
147
+ opacity: showImage ? 1 : 0,
148
+ transition,
149
+ ...absolutePositioning,
150
+ 'object-fit': objectFit,
151
+ 'object-position': objectPosition,
152
+ ...parseStyleAttributes(pictureStyle)
153
+ })}
166
154
  data-testid="img"
167
155
  />
168
156
  {/if}
@@ -1,42 +1,18 @@
1
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
2
  import type * as CSS from 'csstype';
3
+ import { type ResponsiveImageType } from '../NakedImage/utils';
28
4
  declare const __propDef: {
29
5
  props: {
30
- alt?: string | null | undefined;
31
6
  /** The actual response you get from a DatoCMS `responsiveImage` GraphQL query */ data: ResponsiveImageType;
32
7
  /** Additional CSS className for root node */ class?: string | null | undefined;
33
8
  /** Additional CSS class for the image inside the `<picture />` tag */ pictureClass?: string | null | undefined;
9
+ /** Additional CSS class for the placeholder element */ placeholderClass?: string | null | undefined;
34
10
  /** Duration (in ms) of the fade-in transition effect upoad image loading */ fadeInDuration?: number | undefined;
35
11
  /** 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
12
  /** 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;
13
+ /** Additional CSS rules to add to the root node */ style?: string | null | undefined;
39
14
  /** Additional CSS rules to add to the image inside the `<picture />` tag */ pictureStyle?: string | null | undefined;
15
+ /** Additional CSS rules to add to the placeholder element */ placeholderStyle?: string | null | undefined;
40
16
  /**
41
17
  * The layout behavior of the image as the viewport changes size
42
18
  *
@@ -47,8 +23,8 @@ declare const __propDef: {
47
23
  * * `responsive`: the image will scale the dimensions down for smaller viewports and scale up for larger viewports
48
24
  * * `fill`: image will stretch both width and height to the dimensions of the parent element, provided the parent element is `relative`
49
25
  **/ 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'];
26
+ /** Defines how the image will fit into its parent container when using layout="fill" */ objectFit?: CSS.PropertiesHyphen['object-fit'];
27
+ /** Defines how the image is positioned within its parent element when using layout="fill". */ objectPosition?: CSS.PropertiesHyphen['object-position'];
52
28
  /** Whether the component should use a blurred image placeholder */ usePlaceholder?: boolean | undefined;
53
29
  /**
54
30
  * The HTML5 `sizes` attribute for the image