don't exclude docs

This commit is contained in:
hobbes7878 2024-11-21 22:18:54 +00:00
parent 37f5fc61bf
commit 3f37c9ed03
13 changed files with 1111 additions and 3 deletions

3
.gitignore vendored
View file

@ -190,6 +190,3 @@ dist
.svelte-kit
# End of https://www.toptal.com/developers/gitignore/api/node,macos,linux
dist/
docs/

View file

@ -0,0 +1,37 @@
```yaml
[blocks]
type: photo
width: normal
src: images/shark.jpg
altText: The king of the sea
caption: Carcharodon carcharias - REUTERS
[]
```
```svelte
<!-- App.svelte -->
<script>
import { FeaturePhoto } from '@reuters-graphics/graphics-components';
import content from '$locales/en/content.json';
import { assets } from '$app/paths';
</script>
{#each content.blocks as block}
{#if block.Type === 'text'}
<!-- ... -->
{:else if block.type === 'photo'}
<FeaturePhoto
width="{block.width}"
src="{`${assets}/${block.src}`}"
altText="{block.altText}"
caption="{block.caption}"
/>
<!-- ... -->
{/if}
{/each}
```

View file

@ -0,0 +1,40 @@
For Graphics Kit users, the `GraphicBlock` component is built-in to handle [ai2svelte](https://github.com/reuters-graphics/ai2svelte) graphics.
First, import your ai2svelte graphic in `App.svelte` and add it to the `aiCharts` object;
```svelte
<!-- App.svelte -->
<script>
// Other stuff...
import AiMap from './ai2svelte/my-map.svelte';
const aiCharts = {
// Other charts...
AiMap,
};
</script>
```
Then add the following structure to your ArchieML doc, taking care that the name of your chart in the `aiCharts` object matches the name of your `chart`:
```yaml
[blocks]
# ...
type: ai-graphic
chart: AiMap
width: normal
textWidth: normal
title: Earthquake in Haiti
description: The 7.2-magnitude earthquake struck at 8:29 a.m. EST, Aug. 14, 2021.
notes: \Note: A shakemap represents the ground shaking produced by an earthquake.
\Source: USGIS
:end
altText: A map that shows the shake intensity of the earthquake, which was worst in central Haiti.
:end
# ...
[]
```

View file

@ -0,0 +1,63 @@
```yaml
[blocks]
# ...
type: photo-pack
id: my-photo-pack
class: mb-2
width: wide
textWidth: normal
gap: 10
[.images]
src: images/my-img-1.jpg
altText: Alt text
caption: Lorem ipsum. REUTERS/Photog
src: images/my-img-2.jpg
altText: Alt text
caption: Lorem ipsum. REUTERS/Photog
src: images/my-img-3.jpg
altText: Alt text
caption: Lorem ipsum. REUTERS/Photog
src: images/my-img-4.jpg
altText: Alt text
caption: Lorem ipsum. REUTERS/Photog
src: images/my-img-5.jpg
altText: Alt text
caption: Lorem ipsum. REUTERS/Photog
[]
# ...
[]
```
```svelte
<!-- App.svelte -->
{#each content.blocks as block}
{#if block.type === 'text'}
<!-- ... -->
{:else if block.type === 'photo-pack'}
<PhotoPack
id={block.id}
class={block.class}
width={block.width}
textWidth={block.textWidth}
images={block.images.map((img) => ({
src: `${assets}/${img.src}`,
altText: img.altText,
caption: img.caption,
}))}
layouts={[
{ breakpoint: 750, rows: [2, 3] },
{ breakpoint: 450, rows: [1, 2, 2] },
]}
/>
<!-- ... -->
{/if}
{/each}
```

View file

@ -0,0 +1,36 @@
```yaml
slug: ROOT-SLUG/WILD
seoTitle: Page title for search
seoDescription: Page description for search
shareTitle: Page title for social media
shareDescription: Page description for social media
shareImgPath: images/reuters-graphics.jpg
shareImgAlt: Alt text for share image.
```
```svelte
<script>
import { SEO } from '@reuters-graphics/graphics-components';
import pkg from '$pkg';
import content from '$locales/en/content.json';
import { assets } from '$app/paths';
import { page } from '$app/stores';
</script>
<SEO
baseUrl="{VITE_BASE_URL}"
pageUrl="{$page.url}"
seoTitle="{content.seoTitle}"
seoDescription="{content.seoDescription}"
shareTitle="{content.shareTitle}"
shareDescription="{content.shareDescription}"
shareImgPath="{`${assets}/${content.shareImgPath}`}"
shareImgAlt="{content.shareImgAlt}"
publishTime="{pkg?.reuters?.graphic?.published}"
updateTime="{pkg?.reuters?.graphic?.updated}"
authors="{pkg?.reuters?.graphic?.authors}"
/>
```
> **Note:** For _reasons_, we can't document the value of `VITE_BASE_URL` below. It's `import` + `.meta.env.BASE_URL` (concatenate all that) in the Graphics Kit and other Vite-based rigs.

View file

@ -0,0 +1,87 @@
First, import your ai2svelte graphics in `App.svelte` and add them to the `aiCharts` object;
```svelte
<!-- App.svelte -->
<script>
// Other stuff...
import AiMap1 from './ai2svelte/my-map-1.svelte';
import AiMap2 from './ai2svelte/my-map-2.svelte';
import AiMap3 from './ai2svelte/my-map-3.svelte';
const aiCharts = {
// Other charts...
AiMap1,
AiMap2,
AiMap3,
};
</script>
```
Then add the following structure to your ArchieML Doc, taking care that the names of your charts in the `aiCharts` object match the names of your step backgrounds:
```yaml
[blocks]
# ...
type: ai-scroller
id: my-map-scroller
width: normal
foregroundPosition: middle
stackBackground: true
[.steps]
background: AiMap1
text: #### Step 1
Lorem ipsum
:end
altText: A map showing the Upper West side in New York City.
Can add paragraphs of alt text if you want to break up sentences.
:end
background: AiMap2
text: #### Step 2
Lorem ipsum
:end
altText: The same map now highlights 98th Street.
:end
background: AiMap3
text: #### Step 3
Lorem ipsum
:end
altText: The same map now highlights three locations near 98th Street where something particulary important happened.
:end
[]
# ...
[]
```
```svelte
<!-- App.svelte -->
{#each content.blocks as block}
{#if block.type === 'text'}
<!-- ... -->
{:else if block.type === 'ai-scroller'}
<Scroller
id="{block.id}"
backgroundWidth="{block.width}"
foregroundPosition="{block.foregroundPosition}"
stackBackground="{block.stackBackground === 'true'}"
steps="{block.steps.map((step) => ({
background: aiCharts[step.background],
backgroundProps: assets || '/',
foreground: step.text,
altText: step.altText,
}))}"
/>
<!-- ... -->
{/if}
{/each}
```

View file

@ -0,0 +1,26 @@
```yaml
section: Graphics
sectionUrl: https://www.reuters.com/graphics/
hed: A beautiful page
authors: Samuel Granados,Dea Bankova
published: 2022-09-12T08:30:00.000Z
updated:
```
```svelte
<!-- App.svelte -->
<script>
import { SiteHeadline } from '@reuters-graphics/graphics-components';
import content from '$locales/en/content.json';
</script>
<SiteHeadline
section="{content.section}"
sectionUrl="{content.sectionUrl}"
hed="{content.hed}"
authors="{content.authors.split(',')}"
publishTime="{content.published}"
updateTime="{content.updated}"
/>
```

View file

@ -0,0 +1,47 @@
import React from 'react';
interface InlineNumberProps {
number: number;
children: React.ReactNode; // Allow children to be passed
}
const InlineNumber: React.FC<InlineNumberProps> = ({ number, children }) => {
const containerStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'flex-start', // Align items at the top
gap: '0.5em',
marginTop: '1.5em',
};
const numberStyle: React.CSSProperties = {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgb(0 156 253)',
color: 'white',
borderRadius: '50%',
width: '1.8em',
height: '1.8em',
fontSize: '1em',
fontWeight: 'bold',
lineHeight: '1',
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
flexShrink: 0, // Prevent shrinking
};
const textStyle: React.CSSProperties = {
paddingTop: '0.25em',
fontSize: '1em',
lineHeight: '1.4em', // Adjust line height for readability
wordBreak: 'break-word', // Handle long words gracefully
};
return (
<div style={containerStyle}>
<div style={numberStyle}>{number}</div>
<div style={textStyle}>{children}</div>
</div>
);
};
export default InlineNumber;

View file

@ -0,0 +1,19 @@
import React, { ReactNode } from 'react';
interface HighlightProps {
children: ReactNode;
}
const Highlight: React.FC<HighlightProps> = ({ children }) => {
const style: React.CSSProperties = {
backgroundColor: '#FFF8DC', // Light yellow (Cornsilk)
padding: '0.15em 0.25em',
border: '1px solid rgb(255 239 177)',
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)', // Subtle shadow for depth
fontWeight: 'bold',
};
return <span style={style}>{children}</span>;
};
export default Highlight;

View file

@ -0,0 +1,16 @@
import React, { ReactNode } from 'react';
interface HighlightProps {
children: ReactNode;
}
const Highlight: React.FC<HighlightProps> = ({ children }) => {
const style: React.CSSProperties = {
backgroundColor: '#fff5cd',
padding: '0.15em 0.3em',
};
return <span style={style}>{children}</span>;
};
export default Highlight;

View file

@ -0,0 +1,161 @@
import type React from 'react';
type PrismStyles = Record<string, React.CSSProperties>;
/**
* Nord syntax highlighting to match syntax highlighting in .storybook/syntax.scss
*/
export const prismNord: PrismStyles = {
'code[class*="language-"]': {
color: '#f8f8f2',
background: 'none',
fontFamily:
"\"Fira Code\", Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",
textAlign: 'left',
whiteSpace: 'pre',
wordSpacing: 'normal',
wordBreak: 'normal',
wordWrap: 'normal',
lineHeight: '1.5',
MozTabSize: '4',
OTabSize: '4',
tabSize: '4',
WebkitHyphens: 'none',
MozHyphens: 'none',
msHyphens: 'none',
hyphens: 'none',
},
'pre[class*="language-"]': {
color: '#f8f8f2',
background: '#2E3440',
fontFamily:
"\"Fira Code\", Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace",
textAlign: 'left',
whiteSpace: 'pre',
wordSpacing: 'normal',
wordBreak: 'normal',
wordWrap: 'normal',
lineHeight: '1.5',
MozTabSize: '4',
OTabSize: '4',
tabSize: '4',
WebkitHyphens: 'none',
MozHyphens: 'none',
msHyphens: 'none',
hyphens: 'none',
padding: '1em',
margin: '.5em 0',
overflow: 'auto',
borderRadius: '0.3em',
},
':not(pre) > code[class*="language-"]': {
background: '#2E3440',
padding: '.1em',
borderRadius: '.3em',
whiteSpace: 'normal',
},
comment: {
color: '#9199aa',
},
prolog: {
color: '#9199aa',
},
doctype: {
color: '#9199aa',
},
cdata: {
color: '#9199aa',
},
punctuation: {
color: '#81A1C1',
},
'.namespace': {
opacity: '.7',
},
property: {
color: '#81A1C1',
},
tag: {
color: '#81A1C1',
},
constant: {
color: '#81A1C1',
},
symbol: {
color: '#81A1C1',
},
deleted: {
color: '#81A1C1',
},
number: {
color: '#B48EAD',
},
boolean: {
color: '#81A1C1',
},
selector: {
color: '#A3BE8C',
},
'attr-name': {
color: '#A3BE8C',
},
string: {
color: '#A3BE8C',
},
char: {
color: '#A3BE8C',
},
builtin: {
color: '#A3BE8C',
},
inserted: {
color: '#A3BE8C',
},
operator: {
color: '#81A1C1',
},
entity: {
color: '#81A1C1',
cursor: 'help',
},
url: {
color: '#81A1C1',
},
'.language-css .token.string': {
color: '#81A1C1',
},
'.style .token.string': {
color: '#81A1C1',
},
variable: {
color: '#81A1C1',
},
atrule: {
color: '#88C0D0',
},
'attr-value': {
color: '#88C0D0',
},
function: {
color: '#88C0D0',
},
'class-name': {
color: '#88C0D0',
},
keyword: {
color: '#81A1C1',
},
regex: {
color: '#EBCB8B',
},
important: {
color: '#EBCB8B',
fontWeight: 'bold',
},
bold: {
fontWeight: 'bold',
},
italic: {
fontStyle: 'italic',
},
};

View file

@ -0,0 +1,441 @@
import { Meta } from '@storybook/blocks';
import { parameters } from '../utils/docsPage.js';
import Herbie from '../docs-components/Herbie/Herbie';
<Meta title="Guides/Using with ArchieML docs" parameters={{ ...parameters }} />
# Using components with ArchieML docs
Most of the snippets in these docs show how to use components by passing data into their props directly. In most cases, though, you don't want to hard-code content in your project and instead will get those values from an [ArchieML](https://archieml.org/)-formatted document, hosted in either [RNGS.io](https://rngs.io) or a Google Doc.
In most cases, it's straight forward to fill in component props from ArchieML values, but in some cases you may need to write a small bit of code to translate strings from an ArchieML doc into a different data type or to rearrange data from a doc into a specific format to match a component's props.
## Simple example
Let's look at a basic component, a `ProfileCard`, with a demo that looks like this in the docs:
```svelte
<script>
import { ProfileCard } from '@reuters-graphics/graphics-components';
</script>
<ProfileCard
name="Kitty"
age="{2}"
img="https://cats.com/cat1.jpg"
birthday="{new Date('2020-09-25')}"
bio="Some notes.\n\nWith multiple paragraphs."
isGood="{true}"
/>
```
Notice the component's props includes strings, a date, a number and a boolean.
<Herbie number="1">
{`In our ArchieML doc, we might fill out a block for this component like ...`}
</Herbie>
```yaml
[blocks]
# ...
type: profile-card
name: Tom
age: 10
picture: images/tom-the-cat.jpg
birthday: 2020-09-25
bio: A very frisky feline.
... and an avid mouser!
:end
isGood: true
# ...
[]
```
It's often a good idea to give the properties in your ArchieML doc the same names as the props on the component you're using. That's what we've done above, but you can also name them something else. For example, we went with `picture` instead of `img`.
> If the ArchieML syntax above looks foreign to you, check out the Help docs on any story in [RNGS.io](https://rngs.io) or read the official [ArchieML docs](https://archieml.org/#demo) to get familiar with the basics.
<Herbie number="2">
{`When we download the doc, our ArchieML will turn into JSON data like ...`}
</Herbie>
```json
{
"blocks": [
{
"type": "profile-card",
"name": "Tom",
"age": "10",
"picture": "images/tom-the-cat.jpg",
"birthday": "2020-09-25",
"bio": "A very frisy feline.\n\n... and an avid mouser!",
"isGood": "true"
}
]
}
```
Notice all the values in the data are **strings**. More on that soon.
<Herbie number="3">
{`Now we can use that data to feed our component the information it needs for its props:`}
</Herbie>
```svelte
<script>
// These are usually already imported for you
import { assets } from '$app/paths';
// Your ArchieML doc
import content from '$locales/en/content.json';
// Your component from graphics-components
import { ProfileCard } from '@reuters-graphics/graphics-components';
</script>
{#each content.blocks as block}
{#if block.type === 'text'}
<!-- ... -->
{:else if block.type === 'profile-card'}
<ProfileCard
name="{block.name}"
age="{parseInt(block.age)}"
img="{`${assets}/${block.picture}`}"
birthday="{new Date(block.birthday)}"
bio="{block.bio}"
isGood="{block.isGood === 'true'}"
/>
<!-- ... -->
{/if}
{/each}
```
### But let's break that last bit down ...
This is a loop that goes over each block in the `blocks: []` array in the JSON data we downloaded from our ArchieML doc.
```svelte
{#each content.blocks as block}
<!-- ... -->
{/each}
```
While we're looping over each individual block, we check its `type` so we know which component to match it with. For example, `block.type === 'text'` will signal we want to use our [BodyText](./?path=/docs/components-text-elements-bodytext--docs) component in this case.
```svelte
{#if block.type === 'text'}
<!-- ... -->
{:else if block.type === 'profile-card'}
<!-- ... -->
{/if}
```
Once we've identified we have the right block for our component, we need to convert several of the data values from strings to the appropriate data type for each prop.
```svelte
<ProfileCard
name="{block.name}"
age="{parseInt(block.age)}"
img="{`${assets}/${block.picture}`}"
birthday="{new Date(block.birthday)}"
bio="{block.bio}"
isGood="{block.isGood === 'true'}"
/>
```
For example, we're converting Tom's age into a number with JavaScript's [parseInt](https://www.w3schools.com/jsref/jsref_parseint.asp) function ...
```svelte
{parseInt(block.age)}
```
... and we're parsing his birthday into a JavaScript Date ...
```svelte
{new Date(block.birthday)}
```
... and we're checking if he's a good cat by converting the string into a `true`/`false` boolean:
```svelte
{block.isGood === 'true'}
```
**Especially note** how we're using the `assets` module we talked about in ["Using with the Graphics Kit"](./?path=/docs/guides-using-with-the-graphics-kit--docs) to turn the _relative_ path to Tom's profile pic in our ArchieML doc into an _absolute_ path that will have the full `https://reuters.com...` bit attached.
```svelte
{`${assets}/${block.picture}`}
```
### Sum it all up 🏁
Tying your ArchieML doc to a component is as easy as:
<Herbie number={1}>Read what props your component needs in these docs.</Herbie>
<Herbie number={2}>Write your ArchieML block to match those props.</Herbie>
<Herbie number={3}>
{`Convert the string values in your ArchieML JSON into the data types the
component's props expect and pass them into your component!`}
</Herbie>
## A slightly more complex example
The simple example above is a variation of the majority of the components in these docs. Sometimes, though, a component's props get a little more complex, especially when they require an _array_ of objects with different data.
Let's look at another example component:
```svelte
<Timeline
title="A brief history of BitCoin"
dates="{[
{
date: new Date('1992-01-01'),
subhed:
'Cynthia Dwork and Moni Naor come with an idea for "cryptocurrency"',
img: `${assets}/images/dwork-naor.jpeg`,
},
{
date: new Date('2008-08-18'),
subhed: 'Domain name for bitcoin.org registered',
link: 'https://bitcoin.org',
},
{
date: new Date('2013-07-22'),
subhed: 'The Winklevoss twins buy in',
img: `${assets}/images/winkle-boys.jpeg`,
},
]}"
/>
```
Notice our `Timeline` component's `dates` prop takes an array of objects, each with required `date` and `subhed` properties and what appears to be _optional_ `img` or `link` properties.
To match that structure in our ArchieML doc, we might write it like ...
```yaml
[blocks]
# ...
type: timeline
title: A brief history of Bitcoin
[.dates]
date: 1992-01-01
subhed: Cynthia Dwork and Moni Naor ...
img: images/dwork-naor.jpeg
date: 2008-08-18
subhed: Domain name for bitcoin.org ...
link: https://bitcoin.org
date: 2013-07-22
subhed: The Winklevoss twins ...
img: images/winkle-boys.jpeg
[]
# ...
[]
```
**Especially notice** the `[.dates] ... []` bit. The `.` on `.dates` creates a _nested_ array on this block.
That leaves us with JSON data that looks like ...
```json
{
"blocks": [
{
"type": "timeline",
"title": "A brief history of Bitcoin",
"dates": [
{
"date": "1992-01-01",
"subhed": "Cynthia Dwork and Moni Naor ...",
"img": "images/dwork-naor.jpeg"
},
{
"date": "2008-08-18",
"subhed": "Domain name for bitcoin.org ...",
"link": "https://bitcoin.org"
},
{
"date": "2013-07-22",
"subhed": "The Winklevoss twins ...",
"img": "images/winkle-boys.jpeg"
}
]
}
]
}
```
Now our data looks OK and all the properties on each date object that go into the Timeline component's `dates` prop appear to match. It may look like we can pass our data straight into our component like ...
```svelte
<!-- ... -->
{:else if block.type === 'timeline'}
<Timeline
title="{block.title}"
dates="{block.dates}""
/>
{/else}
<!-- ... -->
```
... but we have a couple problems and they all have to do with data types.
According to the component's docs, our `date` property's value should be a JavaScript Date and our `img` needs to be an absolute path.
But this is a problem we can solve by looping over our JSON data and making a new array where all the values are of the right type for our props.
```svelte
<script>
// ...
const timelineBlock = content.blocks.find((block) => block.type === 'timeline');
const timelineDates = timelineBlock.dates.map((d) => {
const date = new Date(d.date);
const subhed = d.subhed;
let img;
let link;
if (d.img) {
img = `${assets}/${d.img}`;
}
if (d.link) {
link = d.link;
}
return {
date,
subhed,
img,
link,
};
});
</script>
<!-- ... -->
{:else if block.type === 'timeline'}
<Timeline
title="{block.title}"
dates="{timelineDates}""
/>
{/else}
<!-- ... -->
```
### OK, let's break down that new chunk of code ...
First, notice I'm writing this code inside my `script` tags so I can easily just write it with JavaScript.
```svelte
<script>
// Normal JavaScript is OK here ...
</script>
```
Now the first thing I do is get ahold of _just_ my timeline block, leaving behind all the other blocks on my page, using a simple [find](https://www.w3schools.com/jsref/jsref_find.asp) function.
```javascript
// Gets JUST my timeline block from the array of all the blocks that make up my page
const timelineBlock = content.blocks.find((block) => block.type === 'timeline');
```
With my timeline block in hand, I can loop over all my dates and create a _new_ array with all the values correctly parsed using a basic [map](https://www.w3schools.com/jsref/jsref_map.asp) function.
```javascript
const timelineDates = timelineBlock.dates.map((d) => {
// "d" is each date object in the ArchieML JSON
// ...
});
```
Inside my `map` I can convert the required properties into new variables matching my component's prop names. In this case, I need to convert the data, but the subhed is just a string ...
```javascript
const timelineDates = timelineBlock.dates.map((d) => {
const date = new Date(d.date);
const subhed = d.subhed;
// ...
});
```
For the optional ones, I'll do a tiny `if` to check if the date has them before adding them to a variable:
```javascript
const timelineDates = timelineBlock.dates.map((d) => {
// ...
let img; // Start as an empty variable ...
let link;
// If our date has an image, we'll make it an absolute URL
if (d.img) {
img = `${assets}/${d.img}`;
}
// If it has a link, we'll just pass that on, as is
if (d.link) {
link = d.link;
}
// ...
});
```
All that done, I can create my new object by returning it from my `map` ...
```javascript
const timelineDates = timelineBlock.dates.map((d) => {
// ...
return {
date,
subhed,
img,
link,
};
});
```
**Finally**, I have a new array of dates all sorted for my timeline and I can pass them direcly in to the component's `dates` prop:
```svelte
<script>
const timelineDates = timelineBlock.dates.map((d) => {
// ...
});
</script>
{:else if block.type === 'timeline'}
<Timeline
title="{block.title}"
dates="{timelineDates}""
/>
{/else}
```
> This is just _one way_ to prepare your data for your component in JavaScript. In many cases, generative AI tools like ChatGPT can also help you write the small bit of code you need. Just provide it a sample of the ArchieML JSON data and describe the format you need to convert it to for your component.
### Sum it all up 🏁
If your component has more complex props like arrays of objects ...
<Herbie
number={1}
>{`Write your ArchieML doc with nested arrays to match your component's props.`}</Herbie>
<Herbie
number={2}
>{`Format your data in JavaScript using simple \`find\` and \`map\` functions.`}</Herbie>
<Herbie
number={3}
>{`Pass the new formatted array into your components' props instead of the original ArchieML data.`}</Herbie>

View file

@ -0,0 +1,138 @@
import { Meta } from '@storybook/blocks';
import { parameters } from '../utils/docsPage.js';
import Highlight from '../docs-components/Highlight/Highlight';
<Meta title="Guides/Bare minimum Svelte" parameters={{ ...parameters }} />
# Introduction to Svelte components
Svelte is a modern JavaScript framework for building parts of HTML pages. Components are the building blocks of Svelte pages, allowing you to create reusable and interactive parts of your page.
Here's **the bare minimum** you need to know to start using graphics components:
## What's a component?
A Svelte <Highlight>component</Highlight> is just a `.svelte` file.
A component is usually composed of several parts: JavaScript for managing data, HTML to represent the elements it creates on the page and CSS to style those elements.
```svelte
<!-- JavaScript -->
<script>
export let imgSrc = 'https://reuters.com/image.jpg';
export let altText = 'A cat';
export let caption = 'Mousing all day is hard work ...';
</script>
<!-- HTML -->
<figure>
<img src="{imgSrc}" alt="{altText}" />
<figcaption>{caption}</figcaption>
</figure>
<!-- CSS -->
<style>
figure {
max-width: 600px;
margin: 0 auto;
img {
width: 100%;
}
}
</style>
```
## Importing and using components
To use a component, you first need to import it. For example, below is a component called `Button.svelte`:
```svelte
<script>
export let text = 'Click me';
</script>
<!-- Button.svelte -->
<button>{text}</button>
```
You can import and use this component in another file:
```svelte
<!-- App.svelte -->
<script>
import Button from './Button.svelte';
</script>
<main>
<h1>Welcome to Svelte</h1>
<Button text="Press here" />
</main>
```
Here, the `Button` component is imported and used in the `App` component.
The components in this project are pre-made so you can install, import and use them directly in your page without needing to write them yourself or have a copy of each component in your project.
For example, a basic page might look like this:
```svelte
<script>
// Importing our pre-made components from this project
import {
BodyText,
SiteHeader,
SiteFooter,
Headline,
} from '@reuters-graphics/graphics-components';
</script>
<SiteHeader />
<Headline hed="My new story" dek="The beginning of a beautiful page" />
<BodyText text="Lorem ipsum ..." />
<SiteFooter />
```
## Passing data to components with props
All graphics components are written to work across different stories. That means they expect to be given the content they'll add (or "render") on the page by you.
We pass the data components use to render their part of a page using <Highlight>props</Highlight>.
In the `Button.svelte` example above, the `text` prop provides a way to pass the text that will be rendered in the button like this:
```svelte
<Button text="Click me!" />
```
<button>Click me!</button>
## Reading component props
All graphics components are documented with a code snippet showing how to import them and what props that component has with the kind of data each expects.
For example, the default FeaturePhoto example looks like:
```svelte
<script>
import { FeaturePhoto } from '@reuters-graphics/graphics-components';
</script>
<FeaturePhoto
src="https://reuters.com/images/myImage.jpg"
altText="Some alt text"
caption="A caption"
width="normal"
/>
```
The component's props are `src`, `altTtext`, `caption` and `width` and each shows an example of the type of data that should go into that prop. For example, the `src` prop expects a full URL to the image it will render.
## Next steps
To learn more about Svelte, you're not short of great tutorials. There are dozens of YouTube videos, online courses and articles to introduce you to more advanced features of the framework. Watch out for our own training courses on the Graphics Team to learn more about Svelte or JavaScript. But in a pinch, each desk has at least one developer who can help you through any problems as you're working with Svelte.
All are also welcome to join the "⚙️ Graphics Dev Group" channel in Teams, where we occasionally chat about code tips or tricks.
> **NOTE:** As of now, we are using version 4 Svelte syntax. We will soon upgrade to version 5, but for now, we recommend looking for older tutorials online and not the official guides for the latest version.