From 8948760a148e26f37accdce3b8cc891585fc902a Mon Sep 17 00:00:00 2001 From: sarahrainsberger Date: Tue, 15 Oct 2024 15:43:20 +0000 Subject: [PATCH 01/32] split api reference into module pages and update nav --- .../docs/en/reference/api-reference.mdx | 1284 ----------------- .../modules/actions-api-reference.mdx | 163 +++ .../modules/assets-api-reference.mdx | 55 + .../modules/content-api-reference.mdx | 352 +++++ .../reference/modules/i18n-api-reference.mdx | 310 ++++ .../modules/middleware-api-reference.mdx | 90 ++ .../view-transitions-api-reference.mdx | 350 +++++ src/i18n/en/nav.ts | 36 +- 8 files changed, 1343 insertions(+), 1297 deletions(-) create mode 100644 src/content/docs/en/reference/modules/actions-api-reference.mdx create mode 100644 src/content/docs/en/reference/modules/assets-api-reference.mdx create mode 100644 src/content/docs/en/reference/modules/content-api-reference.mdx create mode 100644 src/content/docs/en/reference/modules/i18n-api-reference.mdx create mode 100644 src/content/docs/en/reference/modules/middleware-api-reference.mdx create mode 100644 src/content/docs/en/reference/modules/view-transitions-api-reference.mdx diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index dbe515b787e48..c90487bdf563c 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -1364,1287 +1364,3 @@ export default function () { return import.meta.env.SSR ?
: ; } ``` - -## Images (`astro:assets`) - -### `getImage()` - -

- -**Type:** `(options: UnresolvedImageTransform) => Promise` -

- -:::caution -`getImage()` relies on server-only APIs and breaks the build when used on the client. -::: - -The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/guides/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component. - -`getImage()` takes an options object with the [same properties as the Image component](/en/reference/components-reference/#properties) (except `alt`). - -```astro ---- -import { getImage } from "astro:assets"; -import myBackground from "../background.png" - -const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) ---- - -
-``` - -It returns an object with the following type: - -```ts -type GetImageResult = { - /* Additional HTML attributes needed to render the image (width, height, style, etc..) */ - attributes: Record; - /* Validated parameters passed */ - options: ImageTransform; - /* Original parameters passed */ - rawOptions: ImageTransform; - /* Path to the generated image */ - src: string; - srcSet: { - /* Generated values for srcset, every entry has a url and a size descriptor */ - values: SrcSetValue[]; - /* A value ready to use in`srcset` attribute */ - attribute: string; - }; -} -``` - -## Content Collections (`astro:content`) - -

- -Content collections offer APIs to configure and query your Markdown or MDX documents in `src/content/`. For features and usage examples, [see our content collections guide](/en/guides/content-collections/). - -### `defineCollection()` - -

- -**Type:** `(input: CollectionConfig) => CollectionConfig` -

- -`defineCollection()` is a utility to configure a collection in a `src/content/config.*` file. - -```ts -// src/content/config.ts -import { z, defineCollection } from 'astro:content'; -const blog = defineCollection({ - type: 'content', - schema: z.object({ - title: z.string(), - permalink: z.string().optional(), - }), -}); - -// Expose your defined collection to Astro -// with the `collections` export -export const collections = { blog }; -``` - -This function accepts the following properties: - -#### `type` - -

- -**Type:** `'content' | 'data'`
-**Default:** `'content'`
- -

- -`type` is a string that defines the type of entries stored within a collection: - -- `'content'` - for content-authoring formats like Markdown (`.md`), MDX (`.mdx`), or Markdoc (`.mdoc`) -- `'data'` - for data-only formats like JSON (`.json`) or YAML (`.yaml`) - -:::tip -This means collections **cannot** store a mix of content and data formats. You must split these entries into separate collections by type. -::: - -#### `schema` - -

- -**Type:** ZodType | (context: SchemaContext) => ZodType -

- -`schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use [a Zod validator](https://github.com/colinhacks/zod). - -[See the `Content Collection` guide](/en/guides/content-collections/#defining-a-collection-schema) for example usage. - -### `reference()` - -

- -**Type:** `(collection: string) => ZodEffects`
- -

- -The `reference()` function is used in the content config to define a relationship, or "reference," from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file. - -This example defines references from a blog author to the `authors` collection and an array of related posts to the same `blog` collection: - -```ts -import { defineCollection, reference, z } from 'astro:content'; - -const blog = defineCollection({ - type: 'content', - schema: z.object({ - // Reference a single author from the `authors` collection by `id` - author: reference('authors'), - // Reference an array of related posts from the `blog` collection by `slug` - relatedPosts: z.array(reference('blog')), - }) -}); - -const authors = defineCollection({ - type: 'data', - schema: z.object({ /* ... */ }) -}); - -export const collections = { blog, authors }; -``` - -[See the `Content Collection` guide](/en/guides/content-collections/#defining-collection-references) for example usage. - -### `getCollection()` - -

- -**Type:** `(collection: string, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]` -

- -`getCollection()` is a function that retrieves a list of content collection entries by collection name. - -It returns all items in the collection by default, and accepts an optional `filter` function to narrow by entry properties. This allows you to query for only some items in a collection based on `id`, `slug`, or frontmatter values via the `data` object. - -```astro ---- -import { getCollection } from 'astro:content'; - -// Get all `src/content/blog/` entries -const allBlogPosts = await getCollection('blog'); - -// Only return posts with `draft: true` in the frontmatter -const draftBlogPosts = await getCollection('blog', ({ data }) => { - return data.draft === true; -}); ---- -``` - -[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. - -### `getEntry()` - -

- -**Types:** -- `(collection: string, contentSlugOrDataId: string) => CollectionEntry` -- `({ collection: string, id: string }) => CollectionEntry` -- `({ collection: string, slug: string }) => CollectionEntry` - -`getEntry()` is a function that retrieves a single collection entry by collection name and either the entry `id` (for `type: 'data'` collections) or entry `slug` (for `type: 'content'` collections). `getEntry()` can also be used to get referenced entries to access the `data`, `body`, or `render()` properties: - -```astro ---- -import { getEntry } from 'astro:content'; - -// Get `src/content/blog/enterprise.md` -const enterprisePost = await getEntry('blog', 'enterprise'); - -// Get `src/content/captains/picard.yaml` -const picardProfile = await getEntry('captains', 'picard'); - -// Get the profile referenced by `data.captain` -const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); ---- -``` - -See the `Content Collections` guide for examples of [querying collection entries](/en/guides/content-collections/#querying-collections). - -### `getEntries()` - -

- -**Types:** -- `(Array<{ collection: string, id: string }>) => CollectionEntry[]` -- `(Array<{ collection: string, slug: string }>) => CollectionEntry[]` - -`getEntries()` is a function that retrieves multiple collection entries from the same collection. This is useful for [returning an array of referenced entries](/en/guides/content-collections/#defining-collection-references) to access their associated `data`, `body`, and `render()` properties. - -```astro ---- -import { getEntries } from 'astro:content'; - -const enterprisePost = await getEntry('blog', 'enterprise'); - -// Get related posts referenced by `data.relatedPosts` -const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts); ---- -``` - -### `getEntryBySlug()` - -

- -**Type:** `(collection: string, slug: string) => Promise>` -

- -:::caution[Deprecated] -Use the [`getEntry()` function](#getentry) to query content entries. This accepts the same arguments as `getEntryBySlug()`, and supports querying by `id` for JSON or YAML collections. -::: - -`getEntryBySlug()` is a function that retrieves a single collection entry by collection name and entry `slug`. - - -```astro ---- -import { getEntryBySlug } from 'astro:content'; - -const enterprise = await getEntryBySlug('blog', 'enterprise'); ---- -``` - -[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. - -### `getDataEntryById()` - -

- -**Type:** `(collection: string, id: string) => Promise>`
- -

- -:::caution[Deprecated] -Use the [`getEntry()` function](#getentry) to query data entries. This accepts the same arguments as `getDataEntryById()`, and supports querying by `slug` for content authoring formats like Markdown. -::: - -`getDataEntryById()` is a function that retrieves a single collection entry by collection name and entry `id`. - - -```astro ---- -import { getDataEntryById } from 'astro:content'; - -const picardProfile = await getDataEntryById('captains', 'picard'); ---- -``` - -### Collection Entry Type - -Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#getentry), and [`getEntries()`](#getentries) each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`: - -```ts -import type { CollectionEntry } from 'astro:content'; -``` - -The `CollectionEntry` type is an object with the following values. `TCollectionName` is the name of the collection you're querying (e.g. `CollectionEntry<'blog'>`). - -#### `id` - -**Available for:** `type: 'content'` and `type: 'data'` collections -**Example Types:** - - content collections: `'entry-1.md' | 'entry-2.md' | ...` - - data collections: `'author-1' | 'author-2' | ...` - -A unique ID using the file path relative to `src/content/[collection]`. Enumerates all possible string values based on the collection entry file paths. Note that collections [defined as `type: 'content'`](#type) include the file extension in their ID, while collections defined as `type: 'data'` do not. - -#### `collection` - -**Available for:** `type: 'content'` and `type: 'data'` collections -**Example Type:** `'blog' | 'authors' | ...` - -The name of a top-level folder under `src/content/` in which entries are located. This is the name used to reference the collection in your schema, and in querying functions. - -#### `data` - -**Available for:** `type: 'content'` and `type: 'data'` collections -**Type:** `CollectionSchema` - -An object of frontmatter properties inferred from your collection schema ([see `defineCollection()` reference](#definecollection)). Defaults to `any` if no schema is configured. - -#### `slug` - -**Available for:** `type: 'content'` collections only -**Example Type:** `'entry-1' | 'entry-2' | ...` - -A URL-ready slug for Markdown or MDX documents. Defaults to the `id` without the file extension, but can be overridden by setting [the `slug` property](/en/guides/content-collections/#defining-custom-slugs) in a file's frontmatter. - -#### `body` - -**Available for:** `type: 'content'` collections only -**Type:** `string` - -A string containing the raw, uncompiled body of the Markdown or MDX document. - -#### `render()` - -**Available for:** `type: 'content'` collections only -**Type:** `() => Promise` - -A function to compile a given Markdown or MDX document for rendering. This returns the following properties: - -- `` - A component used to render the document's contents in an Astro file. -- `headings` - A generated list of headings, [mirroring Astro's `getHeadings()` utility](/en/guides/markdown-content/#available-properties) on Markdown and MDX imports. -- `remarkPluginFrontmatter ` - The modified frontmatter object after any [remark or rehype plugins have been applied](/en/guides/markdown-content/#modifying-frontmatter-programmatically). Set to type `any`. - -```astro ---- -import { getEntryBySlug } from 'astro:content'; -const entry = await getEntryBySlug('blog', 'entry-1'); - -const { Content, headings, remarkPluginFrontmatter } = await entry.render(); ---- -``` - -[See the `Content Collection` guide](/en/guides/content-collections/#rendering-content-to-html) for example usage. - -### Other Content Collection Types - -The `astro:content` module also exports the following types for use in your Astro project: - -#### `CollectionKey` - -

- -A string union of all collection names defined in your `src/content/config.*` file. This type can be useful when defining a generic function that accepts any collection name. - -```ts -import type { CollectionKey, getCollection } from 'astro:content'; - -async function getCollection(collection: CollectionKey) { - return getCollection(collection); -} -``` - -#### `ContentCollectionKey` - -

- -A string union of all the names of `type: 'content'` collections defined in your `src/content/config.*` file. - -#### `DataCollectionKey` - -

- -A string union of all the names of `type: 'data'` collection defined in your `src/content/config.*` file. - -#### `SchemaContext` - -The `context` object that `defineCollection` uses for the function shape of `schema`. This type can be useful when building reusable schemas for multiple collections. - -This includes the following property: - -- `image` - The `image()` schema helper that allows you [to use local images in Content Collections](/en/guides/images/#images-in-content-collections) - -```ts -import type { SchemaContext } from 'astro:content'; - -export const imageSchema = ({ image }: SchemaContext) => - z.object({ - image: image(), - description: z.string().optional(), - }); - -const blog = defineCollection({ - type: 'content', - schema: ({ image }) => z.object({ - title: z.string(), - permalink: z.string().optional(), - image: imageSchema({ image }) - }), -}); -``` - -## Middleware (`astro:middleware`) - -

- -Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, [see our middleware guide](/en/guides/middleware/). - -### `onRequest()` - -**Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` - -A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It receives two arguments: [context](#context) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. - -```js title="src/middleware.js" -export function onRequest (context, next) { - // intercept response data from a request - // optionally, transform the response - // return a Response directly, or the result of calling `next()` - return next(); -}; -``` - -#### `context` - -

- -**Type:** `APIContext` -

- -The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. - -See [Endpoint contexts](#endpoint-context) for more information about the context object. - -#### `next()` - -

- -**Type:** `(rewritePayload?: string | URL | Request) => Promise`
-

- -The second argument of `onRequest()` is a function that calls all the subsequent middleware in the chain and returns a `Response`. For example, other middleware could modify the HTML body of a response and awaiting the result of `next()` would allow your middleware to respond to those changes. - -Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. - -### `sequence()` - -

- -**Type:** `(...handlers: MiddlewareHandler[]) => MiddlewareHandler` -

- -A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed. - -```js title="src/middleware.js" -import { sequence } from "astro:middleware"; - -async function validation(_, next) {...} -async function auth(_, next) {...} -async function greeting(_, next) {...} - -export const onRequest = sequence(validation, auth, greeting); -``` - -### `createContext()` - -

- -**Type:** `(context: CreateContext) => APIContext`
- -

- -A low-level API to create an [`APIContext`](#endpoint-context)to be passed to an Astro middleware `onRequest()` function. - -This function can be used by integrations/adapters to programmatically execute the Astro middleware. - -### `trySerializeLocals()` - -

- -**Type:** `(value: unknown) => string`
- -

- -A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. - -## Internationalization (`astro:i18n`) - -

- -This module provides functions to help you create URLs using your project's configured locales. - -Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for: - -- [`base`](/en/reference/configuration-reference/#base) -- [`trailingSlash`](/en/reference/configuration-reference/#trailingslash) -- [`build.format`](/en/reference/configuration-reference/#buildformat) -- [`site`](/en/reference/configuration-reference/#site) - -Also, note that the returned URLs created by these functions for your `defaultLocale` will reflect your `i18n.routing` configuration. - -For features and usage examples, [see our i18n routing guide](/en/guides/internationalization/). - -### `getRelativeLocaleUrl()` - -

- -**Type:** `(locale: string, path?: string, options?: GetLocaleOptions) => string` -

- -Use this function to retrieve a relative path for a locale. If the locale doesn't exist, Astro throws an error. - -```astro ---- -getRelativeLocaleUrl("fr"); -// returns /fr - -getRelativeLocaleUrl("fr", ""); -// returns /fr - -getRelativeLocaleUrl("fr", "getting-started"); -// returns /fr/getting-started - -getRelativeLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog" -}); -// returns /blog/fr-ca/getting-started - -getRelativeLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog", - normalizeLocale: false -}); -// returns /blog/fr_CA/getting-started ---- -``` - -### `getAbsoluteLocaleUrl()` - -

- -**Type:** `(locale: string, path: string, options?: GetLocaleOptions) => string` -

- -Use this function to retrieve an absolute path for a locale when [`site`] has a value. If [`site`] isn't configured, the function returns a relative URL. If the locale doesn't exist, Astro throws an error. - - -```astro title="src/pages/index.astro" ---- -// If `site` is set to be `https://example.com` - -getAbsoluteLocaleUrl("fr"); -// returns https://example.com/fr - -getAbsoluteLocaleUrl("fr", ""); -// returns https://example.com/fr - -getAbsoluteLocaleUrl("fr", "getting-started"); -// returns https://example.com/fr/getting-started - -getAbsoluteLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog" -}); -// returns https://example.com/blog/fr-ca/getting-started - -getAbsoluteLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog", - normalizeLocale: false -}); -// returns https://example.com/blog/fr_CA/getting-started ---- -``` - -### `getRelativeLocaleUrlList()` - -

- -**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` -

- -Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list of relative paths for all the locales. - - -### `getAbsoluteLocaleUrlList()` - -

- -**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` -

- -Use this like [`getAbsoluteLocaleUrl`](/en/guides/internationalization/#custom-locale-paths) to return a list of absolute paths for all the locales. - -### `getPathByLocale()` - -

- -**Type:** `(locale: string) => string` -

- -A function that returns the `path` associated to one or more `codes` when [custom locale paths](/en/guides/internationalization/#custom-locale-paths) are configured. - -```js title="astro.config.mjs" -export default defineConfig({ - i18n: { - locales: ["es", "en", { - path: "french", - codes: ["fr", "fr-BR", "fr-CA"] - }] - } -}) -``` - -```astro title="src/pages/index.astro" ---- -getPathByLocale("fr"); // returns "french" -getPathByLocale("fr-CA"); // returns "french" ---- -``` - -### `getLocaleByPath()` - -

- -**Type:** `(path: string) => string` -

- -A function that returns the `code` associated to a locale `path`. - -```js title="astro.config.mjs" -export default defineConfig({ - i18n: { - locales: ["es", "en", { - path: "french", - codes: ["fr", "fr-BR", "fr-CA"] - }] - } -}) -``` - -```astro title="src/pages/index.astro" ---- -getLocaleByPath("french"); // returns "fr" because that's the first code configured ---- -``` - -### `redirectToDefaultLocale()` - -

- -**Type:** `(context: APIContext, statusCode?: ValidRedirectStatus) => Promise`
- -

- -:::note -Available only when `i18n.routing` is set to `"manual"` -::: - -A function that returns a `Response` that redirects to the `defaultLocale` configured. It accepts an optional valid redirect status code. - -```js title="middleware.js" -import { defineMiddleware } from "astro:middleware"; -import { redirectToDefaultLocale } from "astro:i18n"; - -export const onRequest = defineMiddleware((context, next) => { - if (context.url.pathname.startsWith("/about")) { - return next(); - } else { - return redirectToDefaultLocale(context, 302); - } -}) -``` - -### `redirectToFallback()` - -

- -**Type:** `(context: APIContext, response: Response) => Promise`
- -

- -:::note -Available only when `i18n.routing` is set to `"manual"` -::: - -A function that allows you to use your [`i18n.fallback` configuration](/en/reference/configuration-reference/#i18nfallback) in your own middleware. - -```js title="middleware.js" -import { defineMiddleware } from "astro:middleware"; -import { redirectToFallback } from "astro:i18n"; - -export const onRequest = defineMiddleware(async (context, next) => { - const response = await next(); - if (response.status >= 300) { - return redirectToFallback(context, response) - } - return response; -}) -``` - -### `notFound()` - -

- -**Type:** `(context: APIContext, response?: Response) => Promise | undefined`
- -

- -:::note -Available only when `i18n.routing` is set to `"manual"` -::: - -Use this function in your routing middleware to return a 404 when: -- the current path isn't a root. e.g. `/` or `/` -- the URL doesn't contain a locale - -When a `Response` is passed, the new `Response` emitted by this function will contain the same headers of the original response. - -```js title="middleware.js" -import { defineMiddleware } from "astro:middleware"; -import { notFound } from "astro:i18n"; - -export const onRequest = defineMiddleware((context, next) => { - const pathNotFound = notFound(context); - if (pathNotFound) { - return pathNotFound; - } - return next(); -}) -``` - -### `middleware()` - -

- -**Type:** `(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler`
- -

- -:::note -Available only when `i18n.routing` is set to `"manual"` -::: - -A function that allows you to programmatically create the Astro i18n middleware. - -This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website. - -```js title="middleware.js" -import { middleware } from "astro:i18n"; -import { sequence, defineMiddleware } from "astro:middleware"; - -const customLogic = defineMiddleware(async (context, next) => { - const response = await next(); - - // Custom logic after resolving the response. - // It's possible to catch the response coming from Astro i18n middleware. - - return response; -}); - -export const onRequest = sequence(customLogic, middleware({ - prefixDefaultLocale: true, - redirectToDefaultLocale: false -})) -``` - -### `requestHasLocale()` - -

- -**Type:** `(context: APIContext) => boolean`
- -

- -:::note -Available only when `i18n.routing` is set to `"manual"` -::: - -Checks whether the current URL contains a configured locale. Internally, this function will use `APIContext#url.pathname`. - -```js title="middleware.js" -import { defineMiddleware } from "astro:middleware"; -import { requestHasLocale } from "astro:i18n"; - -export const onRequest = defineMiddleware(async (context, next) => { - if (requestHasLocale(context)) { - return next(); - } - return new Response("Not found", { status: 404 }); -}) -``` - -## View Transitions client API (`astro:transitions/client`) - -

- -This module provides functions to control and interact with the View Transitions API and client-side router. - -For features and usage examples, [see our View Transitions guide](/en/guides/view-transitions/). - -### `navigate()` - -

- -**Type:** `(href: string, options?: Options) => void`
- -

- -A function that executes a navigation to the given `href` using the View Transitions API. - -This function signature is based on the [`navigate` function from the browser Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate). Although based on the Navigation API, this function is implemented on top of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to allow for navigation without reloading the page. - -#### `history` option - -

- -**Type:** `'auto' | 'push' | 'replace'`
-**Default:** `'auto'`
- -

- -Defines how this navigation should be added to the browser history. - -- `'push'`: the router will use `history.pushState` to create a new entry in the browser history. -- `'replace'`: the router will use `history.replaceState` to update the URL without adding a new entry into navigation. -- `'auto'` (default): the router will attempt `history.pushState`, but if the URL cannot be transitioned to, the current URL will remain with no changes to the browser history. - -This option follows the [`history` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history) from the browser Navigation API but simplified for the cases that can happen on an Astro project. - -#### `formData` option - -

- -**Type:** `FormData`
- -

- -A `FormData` object for `POST` requests. - -When this option is provided, the requests to the navigation target page will be sent as a `POST` request with the form data object as the content. - -Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically. - -#### `info` option - -

- -**Type:** `any`
- -

- -Arbitrary data to be included in the `astro:before-preparation` and `astro:before-swap` events caused by this navigation. - -This option mimics the [`info` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info) from the browser Navigation API. - -#### `state` option - -

- -**Type:** `any`
- -

- -Arbitrary data to be associated with the `NavitationHistoryEntry` object created by this navigation. This data can then be retrieved using the [`history.getState` function](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState) from the History API. - -This option mimics the [`state` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state) from the browser Navigation API. - -#### `sourceElement` option - -

- -**Type:** `Element`
- -

- -The element that triggered this navigation, if any. This element will be available in the following events: -- `astro:before-preparation` -- `astro:before-swap` - -### `supportsViewTransitions` - -

- -**Type:** `boolean`
- -

- -Whether or not view transitions are supported and enabled in the current browser. - -### `transitionEnabledOnThisPage` - -

- -**Type:** `boolean`
- -

- -Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions. - -### `getFallback` - -

- -**Type:** `() => 'none' | 'animate' | 'swap'`
- -

- -Returns the fallback strategy to use in browsers that do not support view transitions. - -See the guide on [Fallback control](/en/guides/view-transitions/#fallback-control) for how to choose and configure the fallback behavior. - - -### `astro:before-preparation` event - -An event dispatched at the beginning of a navigation using View Transitions. This event happens before any request is made and any browser state is changed. - -This event has the attributes: -- [`info`](#info) -- [`sourceElement`](#sourceelement) -- [`navigationType`](#navigationtype) -- [`direction`](#direction) -- [`from`](#from) -- [`to`](#to) -- [`formData`](#formdata) -- [`loader`](#loader) - -Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-preparation). - -### `astro:after-preparation` event - -An event dispatched after the next page in a navigation using View Transitions is loaded. - -This event has no attributes. - -Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astroafter-preparation). - -### `astro:before-swap` event - -An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents. - -This event can't be canceled. Calling `preventDefault()` is a no-op. - -This event has the attributes: -- [`info`](#info) -- [`sourceElement`](#sourceelement) -- [`navigationType`](#navigationtype) -- [`direction`](#direction) -- [`from`](#from) -- [`to`](#to) -- [`viewTransition`](#viewtransition) -- [`swap`](#swap) - -Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-swap). - -### `astro:after-swap` event - -An event dispatched after the contents of the page have been swapped but before the view transition ends. - -The history entry and scroll position have already been updated when this event is triggered. - -### `astro:page-load` event - -An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser. - -When view transitions is enabled on the page, code that would normally execute on `DOMContentLoaded` should be changed to execute on this event. - -### View Transitions events attributes - -

- -#### `info` - -

- -**Type:** `URL` -

- -Arbitrary data defined during navigation. - -This is the literal value passed on the [`info` option](#info-option) of the [`navigate()` function](#navigate). - -#### `sourceElement` - -

- -**Type:** `Element | undefined` -

- -The element that triggered the navigation. This can be, for example, an `` element that was clicked. - -When using the [`navigate()` function](#navigate), this will be the element specified in the call. - -#### `newDocument` - -

- -**Type:** `Document` -

- -The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document. - -#### `navigationType` - -

- -**Type:** `'push' | 'replace' | 'traverse'` -

- -Which kind of history navigation is happening. -- `push`: a new `NavigationHistoryEntry` is being created for the new page. -- `replace`: the current `NavigationHistoryEntry` is being replaced with an entry for the new page. -- `traverse`: no `NavigationHistoryEntry` is created. The position in the history is changing. - The direction of the traversal is given on the [`direction` attribute](#direction) - -#### `direction` - -

- -**Type:** `Direction` -

- -The direction of the transition. -- `forward`: navigating to the next page in the history or to a new page. -- `back`: navigating to the previous page in the history. -- Anything else some other listener might have set. - -#### `from` - -

- -**Type:** `URL` -

- -The URL of the page initiating the navigation. - -#### `to` - -

- -**Type:** `URL` -

- -The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the `NavigationHistoryEntry` for the next page. - -#### `formData` - -

- -**Type:** `FormData | undefined` -

- -A `FormData` object for `POST` requests. - -When this attribute is set, a `POST` request will be sent to the [`to` URL](#to) with the given form data object as the content instead of the normal `GET` request. - -When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the [`navigate()` function](#navigate), this value is the same as given in the options. - -#### `loader` - -

- -**Type:** `() => Promise` -

- -Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior. - -#### `viewTransition` - -

- -**Type:** [`ViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) -

- -The view transition object used in this navigation. On browsers that do not support the [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API), this is an object implementing the same API for convenience but without the DOM integration. - -#### `swap` - -

- -**Type:** `() => void` -

- -Implementation of the document swap logic. - -Read more on how to [build your own custom swap function](/en/guides/view-transitions/#building-a-custom-swap-function) on the View Transitions guide. - -By default, this implementation will call the following functions in order: - -##### `deselectScripts()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using [`data-astro-rerun`](/en/guides/view-transitions/#data-astro-rerun). - -##### `swapRootAttributes()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Swaps the attributes between the document roots, like the `lang` attribute. This also includes Astro-injected internal attributes like `data-astro-transition`, which makes the transition direction available to Astro-generated CSS rules. - -When making a custom swap function, it is important to call this function so as not to break the view transition's animations. - -##### `swapHeadElements()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Removes every element from the current document's `` that is not persisted to the new document. Then appends all new elements from the new document's `` to the current document's ``. - -##### `saveFocus()` - -

- -**Type:** `() => () => void` -

- -Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it. - - -##### `swapBodyElements()` - -

- -**Type:** `(newBody: Element, oldBody: Element) => void` -

- -Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. - -## Actions (`astro:actions`) - -

- -

- -Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the `astro:actions` module. For examples and usage instructions, [see the Actions guide](/en/guides/actions/). - -### `defineAction()` - -

- -

- -The `defineAction()` utility is used to define new actions from the `src/actions/index.ts` file. This accepts a [`handler()`](#handler-property) function containing the server logic to run, and an optional [`input`](#input-validator) property to validate input parameters at runtime. - -```ts -export const server = { - getGreeting: defineAction({ - input: z.object({ - name: z.string(), - }), - handler: async (input, context) => { - return `Hello, ${input.name}!` - } - }) -} -``` - -#### `handler()` property - -

- -**Type:** `(input, context) => any` -

- -`defineAction()` requires a `handler()` function containing the server logic to run when the action is called. Data returned from the handler is automatically serialized and sent to the caller. - -The `handler()` is called with user input as its first argument. If an [`input`](#input-validator) validator is set, the user input will be validated before being passed to the handler. The second argument is a `context` object containing most of Astro’s [standard endpoint context](#endpoint-context), excluding `getActionResult()`, `callAction()`, and `redirect()`. - -Return values are parsed using the [devalue library](https://github.com/Rich-Harris/devalue). This supports JSON values and instances of `Date()`, `Map()`, `Set()`, and `URL()`. - -#### `input` validator - -

- -**Type:** `ZodType | undefined` -

- -The optional `input` property accepts a Zod validator to validate handler inputs at runtime. If the action fails to validate, [a `BAD_REQUEST` error](#actionerror) is returned and the `handler` is not called. - -If `input` is omitted, the `handler` will receive an input of type `unknown` for JSON requests and type `FormData` for form requests. - -##### Use with `accept: 'form'` - -If your action accepts form inputs, use the `z.object()` validator to automatically parse form data to a typed object. The following validators are supported for form data fields: - -- Inputs of type `number` can be validated using `z.number()` -- Inputs of type `checkbox` can be validated using `z.boolean()` -- Inputs of type `file` can be validated using `z.instanceof(File)` -- Multiple inputs of the same `name` can be validated using `z.array(/* validator */)` -- All other inputs can be validated using `z.string()` - -Extension functions including `.refine()`, `.transform()`, and `.pipe()` are also supported on the `z.object()` validator. - -To apply a union of different validators, use the `z.discriminatedUnion()` wrapper to narrow the type based on a specific form field. This example accepts a form submission to either "create" or "update" a user, using the form field with the name `type` to determine which object to validate against: - -```ts -import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; - -export const server = { - changeUser: defineAction({ - accept: 'form', - input: z.discriminatedUnion('type', [ - z.object({ - // Matches when the `type` field has the value `create` - type: z.literal('create'), - name: z.string(), - email: z.string().email(), - }), - z.object({ - // Matches when the `type` field has the value `update` - type: z.literal('update'), - id: z.number(), - name: z.string(), - email: z.string().email(), - }), - ]), - async handler(input) { - if (input.type === 'create') { - // input is { type: 'create', name: string, email: string } - } else { - // input is { type: 'update', id: number, name: string, email: string } - } - }, - }), -}; -``` - -### `isInputError()` - -

- -**Type:** (error?: unknown | ActionError) => boolean
- -

- -The `isInputError()` utility is used to check whether an `ActionError` is an input validation error. When the `input` validator is a `z.object()`, input errors include a `fields` object with error messages grouped by name. - -See the [form input errors guide](/en/guides/actions/#displaying-form-input-errors) for more on using `isInputError()`. - -### `ActionError` - -

- -

- -The `ActionError()` constructor is used to create errors thrown by an action `handler`. This accepts a `code` property describing the error that occurred (example: `"UNAUTHORIZED"`), and an optional `message` property with further details. - -#### `code` - -

- -

- -The `code` property accepts human-readable versions of all HTTP status codes. The following codes are supported: - -- `BAD_REQUEST` (400): The client sent invalid input. This error is thrown when an action `input` validator fails to validate. -- `UNAUTHORIZED` (401): The client lacks valid authentication credentials. -- `FORBIDDEN` (403): The client is not authorized to access a resource. -- `NOT_FOUND` (404): The server cannot find the requested resource. -- `METHOD_NOT_SUPPORTED` (405): The server does not support the requested method. -- `TIMEOUT` (408): The server timed out while processing the request. -- `CONFLICT` (409): The server cannot update a resource due to a conflict. -- `PRECONDITION_FAILED` (412): The server does not meet a precondition of the request. -- `PAYLOAD_TOO_LARGE` (413): The server cannot process the request because the payload is too large. -- `UNSUPPORTED_MEDIA_TYPE` (415): The server does not support the request's media type. Note: Actions already check [the `Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) for JSON and form requests, so you likely won't need to raise this code manually. -- `UNPROCESSABLE_CONTENT` (422): The server cannot process the request due to semantic errors. -- `TOO_MANY_REQUESTS` (429): The server has exceeded a specified rate limit. -- `CLIENT_CLOSED_REQUEST` (499): The client closed the request before the server could respond. -- `INTERNAL_SERVER_ERROR` (500): The server failed unexpectedly. -- `NOT_IMPLEMENTED` (501): The server does not support the requested feature. -- `BAD_GATEWAY` (502): The server received an invalid response from an upstream server. -- `SERVICE_UNAVAILABLE` (503): The server is temporarily unavailable. -- `GATEWAY_TIMEOUT` (504): The server received a timeout from an upstream server. - -#### `message` - -

- -

- -The `message` property accepts a string. (e.g. "User must be logged in.") - -[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element diff --git a/src/content/docs/en/reference/modules/actions-api-reference.mdx b/src/content/docs/en/reference/modules/actions-api-reference.mdx new file mode 100644 index 0000000000000..67d3e1b116c17 --- /dev/null +++ b/src/content/docs/en/reference/modules/actions-api-reference.mdx @@ -0,0 +1,163 @@ +--- +title: Actions API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## Actions (`astro:actions`) + +

+ +

+ +Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the `astro:actions` module. For examples and usage instructions, [see the Actions guide](/en/guides/actions/). + +### `defineAction()` + +

+ +

+ +The `defineAction()` utility is used to define new actions from the `src/actions/index.ts` file. This accepts a [`handler()`](#handler-property) function containing the server logic to run, and an optional [`input`](#input-validator) property to validate input parameters at runtime. + +```ts +export const server = { + getGreeting: defineAction({ + input: z.object({ + name: z.string(), + }), + handler: async (input, context) => { + return `Hello, ${input.name}!` + } + }) +} +``` + +#### `handler()` property + +

+ +**Type:** `(input, context) => any` +

+ +`defineAction()` requires a `handler()` function containing the server logic to run when the action is called. Data returned from the handler is automatically serialized and sent to the caller. + +The `handler()` is called with user input as its first argument. If an [`input`](#input-validator) validator is set, the user input will be validated before being passed to the handler. The second argument is a `context` object containing most of Astro’s [standard endpoint context](#endpoint-context), excluding `getActionResult()`, `callAction()`, and `redirect()`. + +Return values are parsed using the [devalue library](https://github.com/Rich-Harris/devalue). This supports JSON values and instances of `Date()`, `Map()`, `Set()`, and `URL()`. + +#### `input` validator + +

+ +**Type:** `ZodType | undefined` +

+ +The optional `input` property accepts a Zod validator to validate handler inputs at runtime. If the action fails to validate, [a `BAD_REQUEST` error](#actionerror) is returned and the `handler` is not called. + +If `input` is omitted, the `handler` will receive an input of type `unknown` for JSON requests and type `FormData` for form requests. + +##### Use with `accept: 'form'` + +If your action accepts form inputs, use the `z.object()` validator to automatically parse form data to a typed object. The following validators are supported for form data fields: + +- Inputs of type `number` can be validated using `z.number()` +- Inputs of type `checkbox` can be validated using `z.boolean()` +- Inputs of type `file` can be validated using `z.instanceof(File)` +- Multiple inputs of the same `name` can be validated using `z.array(/* validator */)` +- All other inputs can be validated using `z.string()` + +Extension functions including `.refine()`, `.transform()`, and `.pipe()` are also supported on the `z.object()` validator. + +To apply a union of different validators, use the `z.discriminatedUnion()` wrapper to narrow the type based on a specific form field. This example accepts a form submission to either "create" or "update" a user, using the form field with the name `type` to determine which object to validate against: + +```ts +import { defineAction } from 'astro:actions'; +import { z } from 'astro:schema'; + +export const server = { + changeUser: defineAction({ + accept: 'form', + input: z.discriminatedUnion('type', [ + z.object({ + // Matches when the `type` field has the value `create` + type: z.literal('create'), + name: z.string(), + email: z.string().email(), + }), + z.object({ + // Matches when the `type` field has the value `update` + type: z.literal('update'), + id: z.number(), + name: z.string(), + email: z.string().email(), + }), + ]), + async handler(input) { + if (input.type === 'create') { + // input is { type: 'create', name: string, email: string } + } else { + // input is { type: 'update', id: number, name: string, email: string } + } + }, + }), +}; +``` + +### `isInputError()` + +

+ +**Type:** (error?: unknown | ActionError) => boolean
+ +

+ +The `isInputError()` utility is used to check whether an `ActionError` is an input validation error. When the `input` validator is a `z.object()`, input errors include a `fields` object with error messages grouped by name. + +See the [form input errors guide](/en/guides/actions/#displaying-form-input-errors) for more on using `isInputError()`. + +### `ActionError` + +

+ +

+ +The `ActionError()` constructor is used to create errors thrown by an action `handler`. This accepts a `code` property describing the error that occurred (example: `"UNAUTHORIZED"`), and an optional `message` property with further details. + +#### `code` + +

+ +

+ +The `code` property accepts human-readable versions of all HTTP status codes. The following codes are supported: + +- `BAD_REQUEST` (400): The client sent invalid input. This error is thrown when an action `input` validator fails to validate. +- `UNAUTHORIZED` (401): The client lacks valid authentication credentials. +- `FORBIDDEN` (403): The client is not authorized to access a resource. +- `NOT_FOUND` (404): The server cannot find the requested resource. +- `METHOD_NOT_SUPPORTED` (405): The server does not support the requested method. +- `TIMEOUT` (408): The server timed out while processing the request. +- `CONFLICT` (409): The server cannot update a resource due to a conflict. +- `PRECONDITION_FAILED` (412): The server does not meet a precondition of the request. +- `PAYLOAD_TOO_LARGE` (413): The server cannot process the request because the payload is too large. +- `UNSUPPORTED_MEDIA_TYPE` (415): The server does not support the request's media type. Note: Actions already check [the `Content-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) for JSON and form requests, so you likely won't need to raise this code manually. +- `UNPROCESSABLE_CONTENT` (422): The server cannot process the request due to semantic errors. +- `TOO_MANY_REQUESTS` (429): The server has exceeded a specified rate limit. +- `CLIENT_CLOSED_REQUEST` (499): The client closed the request before the server could respond. +- `INTERNAL_SERVER_ERROR` (500): The server failed unexpectedly. +- `NOT_IMPLEMENTED` (501): The server does not support the requested feature. +- `BAD_GATEWAY` (502): The server received an invalid response from an upstream server. +- `SERVICE_UNAVAILABLE` (503): The server is temporarily unavailable. +- `GATEWAY_TIMEOUT` (504): The server received a timeout from an upstream server. + +#### `message` + +

+ +

+ +The `message` property accepts a string. (e.g. "User must be logged in.") + +[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element diff --git a/src/content/docs/en/reference/modules/assets-api-reference.mdx b/src/content/docs/en/reference/modules/assets-api-reference.mdx new file mode 100644 index 0000000000000..e79bbdb4138ef --- /dev/null +++ b/src/content/docs/en/reference/modules/assets-api-reference.mdx @@ -0,0 +1,55 @@ +--- +title: Assets API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## Images (`astro:assets`) + +### `getImage()` + +

+ +**Type:** `(options: UnresolvedImageTransform) => Promise` +

+ +:::caution +`getImage()` relies on server-only APIs and breaks the build when used on the client. +::: + +The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/guides/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component. + +`getImage()` takes an options object with the [same properties as the Image component](/en/reference/components-reference/#properties) (except `alt`). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +It returns an object with the following type: + +```ts +type GetImageResult = { + /* Additional HTML attributes needed to render the image (width, height, style, etc..) */ + attributes: Record; + /* Validated parameters passed */ + options: ImageTransform; + /* Original parameters passed */ + rawOptions: ImageTransform; + /* Path to the generated image */ + src: string; + srcSet: { + /* Generated values for srcset, every entry has a url and a size descriptor */ + values: SrcSetValue[]; + /* A value ready to use in`srcset` attribute */ + attribute: string; + }; +} +``` diff --git a/src/content/docs/en/reference/modules/content-api-reference.mdx b/src/content/docs/en/reference/modules/content-api-reference.mdx new file mode 100644 index 0000000000000..6795ce11063fb --- /dev/null +++ b/src/content/docs/en/reference/modules/content-api-reference.mdx @@ -0,0 +1,352 @@ +--- +title: Content Collections API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## Content Collections (`astro:content`) + +

+ +Content collections offer APIs to configure and query your Markdown or MDX documents in `src/content/`. For features and usage examples, [see our content collections guide](/en/guides/content-collections/). + +### `defineCollection()` + +

+ +**Type:** `(input: CollectionConfig) => CollectionConfig` +

+ +`defineCollection()` is a utility to configure a collection in a `src/content/config.*` file. + +```ts +// src/content/config.ts +import { z, defineCollection } from 'astro:content'; +const blog = defineCollection({ + type: 'content', + schema: z.object({ + title: z.string(), + permalink: z.string().optional(), + }), +}); + +// Expose your defined collection to Astro +// with the `collections` export +export const collections = { blog }; +``` + +This function accepts the following properties: + +#### `type` + +

+ +**Type:** `'content' | 'data'`
+**Default:** `'content'`
+ +

+ +`type` is a string that defines the type of entries stored within a collection: + +- `'content'` - for content-authoring formats like Markdown (`.md`), MDX (`.mdx`), or Markdoc (`.mdoc`) +- `'data'` - for data-only formats like JSON (`.json`) or YAML (`.yaml`) + +:::tip +This means collections **cannot** store a mix of content and data formats. You must split these entries into separate collections by type. +::: + +#### `schema` + +

+ +**Type:** ZodType | (context: SchemaContext) => ZodType +

+ +`schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use [a Zod validator](https://github.com/colinhacks/zod). + +[See the `Content Collection` guide](/en/guides/content-collections/#defining-a-collection-schema) for example usage. + +### `reference()` + +

+ +**Type:** `(collection: string) => ZodEffects`
+ +

+ +The `reference()` function is used in the content config to define a relationship, or "reference," from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file. + +This example defines references from a blog author to the `authors` collection and an array of related posts to the same `blog` collection: + +```ts +import { defineCollection, reference, z } from 'astro:content'; + +const blog = defineCollection({ + type: 'content', + schema: z.object({ + // Reference a single author from the `authors` collection by `id` + author: reference('authors'), + // Reference an array of related posts from the `blog` collection by `slug` + relatedPosts: z.array(reference('blog')), + }) +}); + +const authors = defineCollection({ + type: 'data', + schema: z.object({ /* ... */ }) +}); + +export const collections = { blog, authors }; +``` + +[See the `Content Collection` guide](/en/guides/content-collections/#defining-collection-references) for example usage. + +### `getCollection()` + +

+ +**Type:** `(collection: string, filter?: (entry: CollectionEntry) => boolean) => CollectionEntry[]` +

+ +`getCollection()` is a function that retrieves a list of content collection entries by collection name. + +It returns all items in the collection by default, and accepts an optional `filter` function to narrow by entry properties. This allows you to query for only some items in a collection based on `id`, `slug`, or frontmatter values via the `data` object. + +```astro +--- +import { getCollection } from 'astro:content'; + +// Get all `src/content/blog/` entries +const allBlogPosts = await getCollection('blog'); + +// Only return posts with `draft: true` in the frontmatter +const draftBlogPosts = await getCollection('blog', ({ data }) => { + return data.draft === true; +}); +--- +``` + +[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. + +### `getEntry()` + +

+ +**Types:** +- `(collection: string, contentSlugOrDataId: string) => CollectionEntry` +- `({ collection: string, id: string }) => CollectionEntry` +- `({ collection: string, slug: string }) => CollectionEntry` + +`getEntry()` is a function that retrieves a single collection entry by collection name and either the entry `id` (for `type: 'data'` collections) or entry `slug` (for `type: 'content'` collections). `getEntry()` can also be used to get referenced entries to access the `data`, `body`, or `render()` properties: + +```astro +--- +import { getEntry } from 'astro:content'; + +// Get `src/content/blog/enterprise.md` +const enterprisePost = await getEntry('blog', 'enterprise'); + +// Get `src/content/captains/picard.yaml` +const picardProfile = await getEntry('captains', 'picard'); + +// Get the profile referenced by `data.captain` +const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); +--- +``` + +See the `Content Collections` guide for examples of [querying collection entries](/en/guides/content-collections/#querying-collections). + +### `getEntries()` + +

+ +**Types:** +- `(Array<{ collection: string, id: string }>) => CollectionEntry[]` +- `(Array<{ collection: string, slug: string }>) => CollectionEntry[]` + +`getEntries()` is a function that retrieves multiple collection entries from the same collection. This is useful for [returning an array of referenced entries](/en/guides/content-collections/#defining-collection-references) to access their associated `data`, `body`, and `render()` properties. + +```astro +--- +import { getEntries } from 'astro:content'; + +const enterprisePost = await getEntry('blog', 'enterprise'); + +// Get related posts referenced by `data.relatedPosts` +const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts); +--- +``` + +### `getEntryBySlug()` + +

+ +**Type:** `(collection: string, slug: string) => Promise>` +

+ +:::caution[Deprecated] +Use the [`getEntry()` function](#getentry) to query content entries. This accepts the same arguments as `getEntryBySlug()`, and supports querying by `id` for JSON or YAML collections. +::: + +`getEntryBySlug()` is a function that retrieves a single collection entry by collection name and entry `slug`. + + +```astro +--- +import { getEntryBySlug } from 'astro:content'; + +const enterprise = await getEntryBySlug('blog', 'enterprise'); +--- +``` + +[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. + +### `getDataEntryById()` + +

+ +**Type:** `(collection: string, id: string) => Promise>`
+ +

+ +:::caution[Deprecated] +Use the [`getEntry()` function](#getentry) to query data entries. This accepts the same arguments as `getDataEntryById()`, and supports querying by `slug` for content authoring formats like Markdown. +::: + +`getDataEntryById()` is a function that retrieves a single collection entry by collection name and entry `id`. + + +```astro +--- +import { getDataEntryById } from 'astro:content'; + +const picardProfile = await getDataEntryById('captains', 'picard'); +--- +``` + +### Collection Entry Type + +Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#getentry), and [`getEntries()`](#getentries) each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`: + +```ts +import type { CollectionEntry } from 'astro:content'; +``` + +The `CollectionEntry` type is an object with the following values. `TCollectionName` is the name of the collection you're querying (e.g. `CollectionEntry<'blog'>`). + +#### `id` + +**Available for:** `type: 'content'` and `type: 'data'` collections +**Example Types:** + - content collections: `'entry-1.md' | 'entry-2.md' | ...` + - data collections: `'author-1' | 'author-2' | ...` + +A unique ID using the file path relative to `src/content/[collection]`. Enumerates all possible string values based on the collection entry file paths. Note that collections [defined as `type: 'content'`](#type) include the file extension in their ID, while collections defined as `type: 'data'` do not. + +#### `collection` + +**Available for:** `type: 'content'` and `type: 'data'` collections +**Example Type:** `'blog' | 'authors' | ...` + +The name of a top-level folder under `src/content/` in which entries are located. This is the name used to reference the collection in your schema, and in querying functions. + +#### `data` + +**Available for:** `type: 'content'` and `type: 'data'` collections +**Type:** `CollectionSchema` + +An object of frontmatter properties inferred from your collection schema ([see `defineCollection()` reference](#definecollection)). Defaults to `any` if no schema is configured. + +#### `slug` + +**Available for:** `type: 'content'` collections only +**Example Type:** `'entry-1' | 'entry-2' | ...` + +A URL-ready slug for Markdown or MDX documents. Defaults to the `id` without the file extension, but can be overridden by setting [the `slug` property](/en/guides/content-collections/#defining-custom-slugs) in a file's frontmatter. + +#### `body` + +**Available for:** `type: 'content'` collections only +**Type:** `string` + +A string containing the raw, uncompiled body of the Markdown or MDX document. + +#### `render()` + +**Available for:** `type: 'content'` collections only +**Type:** `() => Promise` + +A function to compile a given Markdown or MDX document for rendering. This returns the following properties: + +- `` - A component used to render the document's contents in an Astro file. +- `headings` - A generated list of headings, [mirroring Astro's `getHeadings()` utility](/en/guides/markdown-content/#available-properties) on Markdown and MDX imports. +- `remarkPluginFrontmatter ` - The modified frontmatter object after any [remark or rehype plugins have been applied](/en/guides/markdown-content/#modifying-frontmatter-programmatically). Set to type `any`. + +```astro +--- +import { getEntryBySlug } from 'astro:content'; +const entry = await getEntryBySlug('blog', 'entry-1'); + +const { Content, headings, remarkPluginFrontmatter } = await entry.render(); +--- +``` + +[See the `Content Collection` guide](/en/guides/content-collections/#rendering-content-to-html) for example usage. + +### Other Content Collection Types + +The `astro:content` module also exports the following types for use in your Astro project: + +#### `CollectionKey` + +

+ +A string union of all collection names defined in your `src/content/config.*` file. This type can be useful when defining a generic function that accepts any collection name. + +```ts +import type { CollectionKey, getCollection } from 'astro:content'; + +async function getCollection(collection: CollectionKey) { + return getCollection(collection); +} +``` + +#### `ContentCollectionKey` + +

+ +A string union of all the names of `type: 'content'` collections defined in your `src/content/config.*` file. + +#### `DataCollectionKey` + +

+ +A string union of all the names of `type: 'data'` collection defined in your `src/content/config.*` file. + +#### `SchemaContext` + +The `context` object that `defineCollection` uses for the function shape of `schema`. This type can be useful when building reusable schemas for multiple collections. + +This includes the following property: + +- `image` - The `image()` schema helper that allows you [to use local images in Content Collections](/en/guides/images/#images-in-content-collections) + +```ts +import type { SchemaContext } from 'astro:content'; + +export const imageSchema = ({ image }: SchemaContext) => + z.object({ + image: image(), + description: z.string().optional(), + }); + +const blog = defineCollection({ + type: 'content', + schema: ({ image }) => z.object({ + title: z.string(), + permalink: z.string().optional(), + image: imageSchema({ image }) + }), +}); +``` diff --git a/src/content/docs/en/reference/modules/i18n-api-reference.mdx b/src/content/docs/en/reference/modules/i18n-api-reference.mdx new file mode 100644 index 0000000000000..f729729c63989 --- /dev/null +++ b/src/content/docs/en/reference/modules/i18n-api-reference.mdx @@ -0,0 +1,310 @@ +--- +title: Internationalization API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## Internationalization (`astro:i18n`) + +

+ +This module provides functions to help you create URLs using your project's configured locales. + +Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for: + +- [`base`](/en/reference/configuration-reference/#base) +- [`trailingSlash`](/en/reference/configuration-reference/#trailingslash) +- [`build.format`](/en/reference/configuration-reference/#buildformat) +- [`site`](/en/reference/configuration-reference/#site) + +Also, note that the returned URLs created by these functions for your `defaultLocale` will reflect your `i18n.routing` configuration. + +For features and usage examples, [see our i18n routing guide](/en/guides/internationalization/). + +### `getRelativeLocaleUrl()` + +

+ +**Type:** `(locale: string, path?: string, options?: GetLocaleOptions) => string` +

+ +Use this function to retrieve a relative path for a locale. If the locale doesn't exist, Astro throws an error. + +```astro +--- +getRelativeLocaleUrl("fr"); +// returns /fr + +getRelativeLocaleUrl("fr", ""); +// returns /fr + +getRelativeLocaleUrl("fr", "getting-started"); +// returns /fr/getting-started + +getRelativeLocaleUrl("fr_CA", "getting-started", { + prependWith: "blog" +}); +// returns /blog/fr-ca/getting-started + +getRelativeLocaleUrl("fr_CA", "getting-started", { + prependWith: "blog", + normalizeLocale: false +}); +// returns /blog/fr_CA/getting-started +--- +``` + +### `getAbsoluteLocaleUrl()` + +

+ +**Type:** `(locale: string, path: string, options?: GetLocaleOptions) => string` +

+ +Use this function to retrieve an absolute path for a locale when [`site`] has a value. If [`site`] isn't configured, the function returns a relative URL. If the locale doesn't exist, Astro throws an error. + + +```astro title="src/pages/index.astro" +--- +// If `site` is set to be `https://example.com` + +getAbsoluteLocaleUrl("fr"); +// returns https://example.com/fr + +getAbsoluteLocaleUrl("fr", ""); +// returns https://example.com/fr + +getAbsoluteLocaleUrl("fr", "getting-started"); +// returns https://example.com/fr/getting-started + +getAbsoluteLocaleUrl("fr_CA", "getting-started", { + prependWith: "blog" +}); +// returns https://example.com/blog/fr-ca/getting-started + +getAbsoluteLocaleUrl("fr_CA", "getting-started", { + prependWith: "blog", + normalizeLocale: false +}); +// returns https://example.com/blog/fr_CA/getting-started +--- +``` + +### `getRelativeLocaleUrlList()` + +

+ +**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` +

+ +Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list of relative paths for all the locales. + + +### `getAbsoluteLocaleUrlList()` + +

+ +**Type:** `(path?: string, options?: GetLocaleOptions) => string[]` +

+ +Use this like [`getAbsoluteLocaleUrl`](/en/guides/internationalization/#custom-locale-paths) to return a list of absolute paths for all the locales. + +### `getPathByLocale()` + +

+ +**Type:** `(locale: string) => string` +

+ +A function that returns the `path` associated to one or more `codes` when [custom locale paths](/en/guides/internationalization/#custom-locale-paths) are configured. + +```js title="astro.config.mjs" +export default defineConfig({ + i18n: { + locales: ["es", "en", { + path: "french", + codes: ["fr", "fr-BR", "fr-CA"] + }] + } +}) +``` + +```astro title="src/pages/index.astro" +--- +getPathByLocale("fr"); // returns "french" +getPathByLocale("fr-CA"); // returns "french" +--- +``` + +### `getLocaleByPath()` + +

+ +**Type:** `(path: string) => string` +

+ +A function that returns the `code` associated to a locale `path`. + +```js title="astro.config.mjs" +export default defineConfig({ + i18n: { + locales: ["es", "en", { + path: "french", + codes: ["fr", "fr-BR", "fr-CA"] + }] + } +}) +``` + +```astro title="src/pages/index.astro" +--- +getLocaleByPath("french"); // returns "fr" because that's the first code configured +--- +``` + +### `redirectToDefaultLocale()` + +

+ +**Type:** `(context: APIContext, statusCode?: ValidRedirectStatus) => Promise`
+ +

+ +:::note +Available only when `i18n.routing` is set to `"manual"` +::: + +A function that returns a `Response` that redirects to the `defaultLocale` configured. It accepts an optional valid redirect status code. + +```js title="middleware.js" +import { defineMiddleware } from "astro:middleware"; +import { redirectToDefaultLocale } from "astro:i18n"; + +export const onRequest = defineMiddleware((context, next) => { + if (context.url.pathname.startsWith("/about")) { + return next(); + } else { + return redirectToDefaultLocale(context, 302); + } +}) +``` + +### `redirectToFallback()` + +

+ +**Type:** `(context: APIContext, response: Response) => Promise`
+ +

+ +:::note +Available only when `i18n.routing` is set to `"manual"` +::: + +A function that allows you to use your [`i18n.fallback` configuration](/en/reference/configuration-reference/#i18nfallback) in your own middleware. + +```js title="middleware.js" +import { defineMiddleware } from "astro:middleware"; +import { redirectToFallback } from "astro:i18n"; + +export const onRequest = defineMiddleware(async (context, next) => { + const response = await next(); + if (response.status >= 300) { + return redirectToFallback(context, response) + } + return response; +}) +``` + +### `notFound()` + +

+ +**Type:** `(context: APIContext, response?: Response) => Promise | undefined`
+ +

+ +:::note +Available only when `i18n.routing` is set to `"manual"` +::: + +Use this function in your routing middleware to return a 404 when: +- the current path isn't a root. e.g. `/` or `/` +- the URL doesn't contain a locale + +When a `Response` is passed, the new `Response` emitted by this function will contain the same headers of the original response. + +```js title="middleware.js" +import { defineMiddleware } from "astro:middleware"; +import { notFound } from "astro:i18n"; + +export const onRequest = defineMiddleware((context, next) => { + const pathNotFound = notFound(context); + if (pathNotFound) { + return pathNotFound; + } + return next(); +}) +``` + +### `middleware()` + +

+ +**Type:** `(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler`
+ +

+ +:::note +Available only when `i18n.routing` is set to `"manual"` +::: + +A function that allows you to programmatically create the Astro i18n middleware. + +This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website. + +```js title="middleware.js" +import { middleware } from "astro:i18n"; +import { sequence, defineMiddleware } from "astro:middleware"; + +const customLogic = defineMiddleware(async (context, next) => { + const response = await next(); + + // Custom logic after resolving the response. + // It's possible to catch the response coming from Astro i18n middleware. + + return response; +}); + +export const onRequest = sequence(customLogic, middleware({ + prefixDefaultLocale: true, + redirectToDefaultLocale: false +})) +``` + +### `requestHasLocale()` + +

+ +**Type:** `(context: APIContext) => boolean`
+ +

+ +:::note +Available only when `i18n.routing` is set to `"manual"` +::: + +Checks whether the current URL contains a configured locale. Internally, this function will use `APIContext#url.pathname`. + +```js title="middleware.js" +import { defineMiddleware } from "astro:middleware"; +import { requestHasLocale } from "astro:i18n"; + +export const onRequest = defineMiddleware(async (context, next) => { + if (requestHasLocale(context)) { + return next(); + } + return new Response("Not found", { status: 404 }); +}) +``` diff --git a/src/content/docs/en/reference/modules/middleware-api-reference.mdx b/src/content/docs/en/reference/modules/middleware-api-reference.mdx new file mode 100644 index 0000000000000..256dc7b251472 --- /dev/null +++ b/src/content/docs/en/reference/modules/middleware-api-reference.mdx @@ -0,0 +1,90 @@ +--- +title: Middleware API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## Middleware (`astro:middleware`) + +

+ +Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, [see our middleware guide](/en/guides/middleware/). + +### `onRequest()` + +**Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` + +A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It receives two arguments: [context](#context) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. + +```js title="src/middleware.js" +export function onRequest (context, next) { + // intercept response data from a request + // optionally, transform the response + // return a Response directly, or the result of calling `next()` + return next(); +}; +``` + +#### `context` + +

+ +**Type:** `APIContext` +

+ +The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. + +See [Endpoint contexts](#endpoint-context) for more information about the context object. + +#### `next()` + +

+ +**Type:** `(rewritePayload?: string | URL | Request) => Promise`
+

+ +The second argument of `onRequest()` is a function that calls all the subsequent middleware in the chain and returns a `Response`. For example, other middleware could modify the HTML body of a response and awaiting the result of `next()` would allow your middleware to respond to those changes. + +Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. + +### `sequence()` + +

+ +**Type:** `(...handlers: MiddlewareHandler[]) => MiddlewareHandler` +

+ +A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed. + +```js title="src/middleware.js" +import { sequence } from "astro:middleware"; + +async function validation(_, next) {...} +async function auth(_, next) {...} +async function greeting(_, next) {...} + +export const onRequest = sequence(validation, auth, greeting); +``` + +### `createContext()` + +

+ +**Type:** `(context: CreateContext) => APIContext`
+ +

+ +A low-level API to create an [`APIContext`](#endpoint-context)to be passed to an Astro middleware `onRequest()` function. + +This function can be used by integrations/adapters to programmatically execute the Astro middleware. + +### `trySerializeLocals()` + +

+ +**Type:** `(value: unknown) => string`
+ +

+ +A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. diff --git a/src/content/docs/en/reference/modules/view-transitions-api-reference.mdx b/src/content/docs/en/reference/modules/view-transitions-api-reference.mdx new file mode 100644 index 0000000000000..ed69a6905703d --- /dev/null +++ b/src/content/docs/en/reference/modules/view-transitions-api-reference.mdx @@ -0,0 +1,350 @@ +--- +title: View Transitions API Reference +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +## View Transitions client API (`astro:transitions/client`) + +

+ +This module provides functions to control and interact with the View Transitions API and client-side router. + +For features and usage examples, [see our View Transitions guide](/en/guides/view-transitions/). + +### `navigate()` + +

+ +**Type:** `(href: string, options?: Options) => void`
+ +

+ +A function that executes a navigation to the given `href` using the View Transitions API. + +This function signature is based on the [`navigate` function from the browser Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate). Although based on the Navigation API, this function is implemented on top of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to allow for navigation without reloading the page. + +#### `history` option + +

+ +**Type:** `'auto' | 'push' | 'replace'`
+**Default:** `'auto'`
+ +

+ +Defines how this navigation should be added to the browser history. + +- `'push'`: the router will use `history.pushState` to create a new entry in the browser history. +- `'replace'`: the router will use `history.replaceState` to update the URL without adding a new entry into navigation. +- `'auto'` (default): the router will attempt `history.pushState`, but if the URL cannot be transitioned to, the current URL will remain with no changes to the browser history. + +This option follows the [`history` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history) from the browser Navigation API but simplified for the cases that can happen on an Astro project. + +#### `formData` option + +

+ +**Type:** `FormData`
+ +

+ +A `FormData` object for `POST` requests. + +When this option is provided, the requests to the navigation target page will be sent as a `POST` request with the form data object as the content. + +Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically. + +#### `info` option + +

+ +**Type:** `any`
+ +

+ +Arbitrary data to be included in the `astro:before-preparation` and `astro:before-swap` events caused by this navigation. + +This option mimics the [`info` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info) from the browser Navigation API. + +#### `state` option + +

+ +**Type:** `any`
+ +

+ +Arbitrary data to be associated with the `NavitationHistoryEntry` object created by this navigation. This data can then be retrieved using the [`history.getState` function](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState) from the History API. + +This option mimics the [`state` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state) from the browser Navigation API. + +#### `sourceElement` option + +

+ +**Type:** `Element`
+ +

+ +The element that triggered this navigation, if any. This element will be available in the following events: +- `astro:before-preparation` +- `astro:before-swap` + +### `supportsViewTransitions` + +

+ +**Type:** `boolean`
+ +

+ +Whether or not view transitions are supported and enabled in the current browser. + +### `transitionEnabledOnThisPage` + +

+ +**Type:** `boolean`
+ +

+ +Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions. + +### `getFallback` + +

+ +**Type:** `() => 'none' | 'animate' | 'swap'`
+ +

+ +Returns the fallback strategy to use in browsers that do not support view transitions. + +See the guide on [Fallback control](/en/guides/view-transitions/#fallback-control) for how to choose and configure the fallback behavior. + + +### `astro:before-preparation` event + +An event dispatched at the beginning of a navigation using View Transitions. This event happens before any request is made and any browser state is changed. + +This event has the attributes: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`formData`](#formdata) +- [`loader`](#loader) + +Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-preparation). + +### `astro:after-preparation` event + +An event dispatched after the next page in a navigation using View Transitions is loaded. + +This event has no attributes. + +Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astroafter-preparation). + +### `astro:before-swap` event + +An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents. + +This event can't be canceled. Calling `preventDefault()` is a no-op. + +This event has the attributes: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`viewTransition`](#viewtransition) +- [`swap`](#swap) + +Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-swap). + +### `astro:after-swap` event + +An event dispatched after the contents of the page have been swapped but before the view transition ends. + +The history entry and scroll position have already been updated when this event is triggered. + +### `astro:page-load` event + +An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser. + +When view transitions is enabled on the page, code that would normally execute on `DOMContentLoaded` should be changed to execute on this event. + +### View Transitions events attributes + +

+ +#### `info` + +

+ +**Type:** `URL` +

+ +Arbitrary data defined during navigation. + +This is the literal value passed on the [`info` option](#info-option) of the [`navigate()` function](#navigate). + +#### `sourceElement` + +

+ +**Type:** `Element | undefined` +

+ +The element that triggered the navigation. This can be, for example, an `` element that was clicked. + +When using the [`navigate()` function](#navigate), this will be the element specified in the call. + +#### `newDocument` + +

+ +**Type:** `Document` +

+ +The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document. + +#### `navigationType` + +

+ +**Type:** `'push' | 'replace' | 'traverse'` +

+ +Which kind of history navigation is happening. +- `push`: a new `NavigationHistoryEntry` is being created for the new page. +- `replace`: the current `NavigationHistoryEntry` is being replaced with an entry for the new page. +- `traverse`: no `NavigationHistoryEntry` is created. The position in the history is changing. + The direction of the traversal is given on the [`direction` attribute](#direction) + +#### `direction` + +

+ +**Type:** `Direction` +

+ +The direction of the transition. +- `forward`: navigating to the next page in the history or to a new page. +- `back`: navigating to the previous page in the history. +- Anything else some other listener might have set. + +#### `from` + +

+ +**Type:** `URL` +

+ +The URL of the page initiating the navigation. + +#### `to` + +

+ +**Type:** `URL` +

+ +The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the `NavigationHistoryEntry` for the next page. + +#### `formData` + +

+ +**Type:** `FormData | undefined` +

+ +A `FormData` object for `POST` requests. + +When this attribute is set, a `POST` request will be sent to the [`to` URL](#to) with the given form data object as the content instead of the normal `GET` request. + +When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the [`navigate()` function](#navigate), this value is the same as given in the options. + +#### `loader` + +

+ +**Type:** `() => Promise` +

+ +Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior. + +#### `viewTransition` + +

+ +**Type:** [`ViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) +

+ +The view transition object used in this navigation. On browsers that do not support the [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API), this is an object implementing the same API for convenience but without the DOM integration. + +#### `swap` + +

+ +**Type:** `() => void` +

+ +Implementation of the document swap logic. + +Read more on how to [build your own custom swap function](/en/guides/view-transitions/#building-a-custom-swap-function) on the View Transitions guide. + +By default, this implementation will call the following functions in order: + +##### `deselectScripts()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using [`data-astro-rerun`](/en/guides/view-transitions/#data-astro-rerun). + +##### `swapRootAttributes()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Swaps the attributes between the document roots, like the `lang` attribute. This also includes Astro-injected internal attributes like `data-astro-transition`, which makes the transition direction available to Astro-generated CSS rules. + +When making a custom swap function, it is important to call this function so as not to break the view transition's animations. + +##### `swapHeadElements()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Removes every element from the current document's `` that is not persisted to the new document. Then appends all new elements from the new document's `` to the current document's ``. + +##### `saveFocus()` + +

+ +**Type:** `() => () => void` +

+ +Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it. + + +##### `swapBodyElements()` + +

+ +**Type:** `(newBody: Element, oldBody: Element) => void` +

+ +Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. diff --git a/src/i18n/en/nav.ts b/src/i18n/en/nav.ts index 7f236ef809189..573b9fa38c965 100644 --- a/src/i18n/en/nav.ts +++ b/src/i18n/en/nav.ts @@ -98,13 +98,25 @@ export default [ { text: 'Testing', slug: 'guides/testing', key: 'guides/testing' }, { text: 'Troubleshooting', slug: 'guides/troubleshooting', key: 'guides/troubleshooting' }, + { text: 'Community Resources', header: true, type: 'learn', key: 'communityResources' }, + { + text: 'Courses, Guides, and Recipes', + slug: 'community-resources/content', + key: 'community-resources/content', + }, + { + text: 'Talks, Interviews, and Streams', + slug: 'community-resources/talks', + key: 'community-resources/talks', + }, + { text: 'Reference', header: true, type: 'api', key: 'reference' }, { text: 'Configuration', slug: 'reference/configuration-reference', key: 'reference/configuration-reference', }, - { text: 'Astro Runtime API', slug: 'reference/api-reference', key: 'reference/api-reference' }, + { text: 'Astro CLI', slug: 'reference/cli-reference', key: 'reference/cli-reference' }, { text: 'Directives Reference', @@ -119,6 +131,16 @@ export default [ { text: 'TypeScript Reference', slug: 'guides/typescript', key: 'guides/typescript' }, { text: 'Error Reference', slug: 'reference/error-reference', key: 'reference/error-reference' }, + { text: 'Astro API Reference', header: true, type: 'api', key: 'api-reference' }, + { text: 'The Astro Global', slug: 'reference/api-reference', key: 'reference/api-reference' }, + { text: 'astro:actions', slug: 'reference/modules/actions-api-reference', key: 'reference/modules/actions-api-reference' }, + { text: 'astro:assets', slug: 'reference/modules/assets-api-reference', key: 'reference/modules/assets-api-reference' }, + { text: 'astro:content', slug: 'reference/modules/content-api-reference', key: 'reference/modules/content-api-reference' }, + { text: 'astro:i18n', slug: 'reference/modules/i18n-api-reference', key: 'reference/modules/i18n-api-reference' }, + { text: 'astro:middleware', slug: 'reference/modules/middleware-api-reference', key: 'reference/modules/middleware-api-reference' }, + { text: 'astro:view-transitions', slug: 'reference/modules/view-transitions-api-reference', key: 'reference/modules/view-transitions-api-reference' }, + + { text: 'Other Development APIs', header: true, type: 'api', key: 'dev' }, { text: 'Integrations API', @@ -142,18 +164,6 @@ export default [ key: 'reference/container-reference', }, - { text: 'Community Resources', header: true, type: 'learn', key: 'communityResources' }, - { - text: 'Courses, Guides, and Recipes', - slug: 'community-resources/content', - key: 'community-resources/content', - }, - { - text: 'Talks, Interviews, and Streams', - slug: 'community-resources/talks', - key: 'community-resources/talks', - }, - // { text: 'Configuration', header: true, type: 'learn', key: 'configuration' }, // { // text: 'The Astro Config File', From cec5809ed1179e4f44a9f741636c934ada31916a Mon Sep 17 00:00:00 2001 From: sarahrainsberger Date: Tue, 15 Oct 2024 16:47:48 +0000 Subject: [PATCH 02/32] fix some links --- src/content/docs/en/guides/actions.mdx | 10 +++++----- src/content/docs/en/guides/content-collections.mdx | 10 +++++----- src/content/docs/en/guides/imports.mdx | 2 +- .../docs/en/guides/internationalization.mdx | 14 +++++++------- src/content/docs/en/guides/markdown-content.mdx | 2 +- src/content/docs/en/guides/middleware.mdx | 4 ++-- .../docs/en/tutorials/add-content-collections.mdx | 2 +- 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/content/docs/en/guides/actions.mdx b/src/content/docs/en/guides/actions.mdx index b91806302bf37..8c1b4df846ec6 100644 --- a/src/content/docs/en/guides/actions.mdx +++ b/src/content/docs/en/guides/actions.mdx @@ -16,7 +16,7 @@ Use actions instead of API endpoints for seamless communication between your cli - Automatically validate JSON and form data inputs using [Zod validation](https://zod.dev/?id=primitives). - Generate type-safe functions to call your backend from the client and even [from HTML form actions](#call-actions-from-an-html-form-action). No need for manual `fetch()` calls. -- Standardize backend errors with the [`ActionError`](/en/reference/api-reference/#actionerror) object. +- Standardize backend errors with the [`ActionError`](/en/reference/modules/actions-api-reference/#actionerror) object. ## Basic usage @@ -129,7 +129,7 @@ Follow these steps to define an action and call it in a `script` tag in your Ast -See the full Actions API documentation for details on [`defineAction()`](/en/reference/api-reference/#defineaction) and its properties. +See the full Actions API documentation for details on [`defineAction()`](/en/reference/modules/actions-api-reference/#defineaction) and its properties. ## Organizing actions @@ -340,7 +340,7 @@ The following example shows a validated newsletter registration form that accept } ``` - See the [`input` API reference](/en/reference/api-reference/#input-validator) for all available form validators. + See the [`input` API reference](/en/reference//modules/actions-api-reference/#input-validator) for all available form validators. 3. Add a ` ``` ## `` From 9dd7063cd727a8ce884dbf45f6b791375bde7d3a Mon Sep 17 00:00:00 2001 From: sarahrainsberger Date: Thu, 24 Oct 2024 15:22:23 +0000 Subject: [PATCH 22/32] typo in code block --- src/content/docs/en/reference/modules/astro-transitions.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index b21930f220cbd..46afc6b8769f6 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -23,7 +23,7 @@ import { navigate, supportsViewTransitions, transitionEnabledOnThisPage, - getFallback + getFallback, } from 'astro:transitions'; --- From ce0463547bd813931b79dcf37e0a7f7f0a31d32e Mon Sep 17 00:00:00 2001 From: sarahrainsberger Date: Thu, 24 Oct 2024 15:32:00 +0000 Subject: [PATCH 23/32] fix other typo --- src/content/docs/en/reference/modules/astro-transitions.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index 46afc6b8769f6..3502692efa233 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -33,7 +33,7 @@ import { slide, swapFunctions, } from 'astro:transitions/client'; - + ``` ## `` From 3f9e1aefa6e5b3e65da4cd3cadf98c4694f1ad64 Mon Sep 17 00:00:00 2001 From: Chris Swithinbank Date: Thu, 24 Oct 2024 21:51:32 +0200 Subject: [PATCH 24/32] Rework module reference heading hierarchies and split `astro:content` type imports into dedicated subheading --- .../en/reference/modules/astro-actions.mdx | 16 +++--- .../en/reference/modules/astro-assets.mdx | 16 +++--- .../en/reference/modules/astro-content.mdx | 53 +++++++++++-------- .../docs/en/reference/modules/astro-i18n.mdx | 22 ++++---- .../en/reference/modules/astro-middleware.mdx | 14 ++--- 5 files changed, 66 insertions(+), 55 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-actions.mdx b/src/content/docs/en/reference/modules/astro-actions.mdx index ff863cd498bac..bc08271b638a0 100644 --- a/src/content/docs/en/reference/modules/astro-actions.mdx +++ b/src/content/docs/en/reference/modules/astro-actions.mdx @@ -25,7 +25,7 @@ import { } from 'astro:actions'; ``` -## `defineAction()` +### `defineAction()`

@@ -49,7 +49,7 @@ export const server = { } ``` -### `handler()` property +#### `handler()` property

@@ -62,7 +62,7 @@ The `handler()` is called with user input as its first argument. If an [`input`] Return values are parsed using the [devalue library](https://github.com/Rich-Harris/devalue). This supports JSON values and instances of `Date()`, `Map()`, `Set()`, and `URL()`. -### `input` validator +#### `input` validator

@@ -73,7 +73,7 @@ The optional `input` property accepts a Zod validator to validate handler inputs If `input` is omitted, the `handler` will receive an input of type `unknown` for JSON requests and type `FormData` for form requests. -#### Use with `accept: 'form'` +##### Use with `accept: 'form'` If your action accepts form inputs, use the `z.object()` validator to automatically parse form data to a typed object. The following validators are supported for form data fields: @@ -120,7 +120,7 @@ export const server = { }; ``` -## `isInputError()` +### `isInputError()`

@@ -132,7 +132,7 @@ The `isInputError()` utility is used to check whether an `ActionError` is an inp See the [form input errors guide](/en/guides/actions/#displaying-form-input-errors) for more on using `isInputError()`. -## `ActionError` +### `ActionError`

@@ -140,7 +140,7 @@ The `isInputError()` utility is used to check whether an `ActionError` is an inp The `ActionError()` constructor is used to create errors thrown by an action `handler`. This accepts a `code` property describing the error that occurred (example: `"UNAUTHORIZED"`), and an optional `message` property with further details. -### `code` +#### `code`

@@ -167,7 +167,7 @@ The `code` property accepts human-readable versions of all HTTP status codes. Th - `SERVICE_UNAVAILABLE` (503): The server is temporarily unavailable. - `GATEWAY_TIMEOUT` (504): The server received a timeout from an upstream server. -### `message` +#### `message`

diff --git a/src/content/docs/en/reference/modules/astro-assets.mdx b/src/content/docs/en/reference/modules/astro-assets.mdx index 0c664e76a3226..4eddc770f34ad 100644 --- a/src/content/docs/en/reference/modules/astro-assets.mdx +++ b/src/content/docs/en/reference/modules/astro-assets.mdx @@ -22,7 +22,7 @@ import { } from 'astro:assets'; ``` -## `` +### `` ```astro title="src/components/MyComponent.astro" --- @@ -47,7 +47,7 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 alt="A description of my image." /> ``` -### Properties +#### Properties - src (required) - alt (required) @@ -61,7 +61,7 @@ In addition to the properties above, the `` component accepts all prope See more in the [Images Guide](/en/guides/images/#image--astroassets). -## `` +### ``

@@ -95,23 +95,23 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 See more in the [Images Guide](/en/guides/images/#picture-). -### Properties +#### Properties `` accepts all the properties of the `` component, plus the following: -#### `formats` +##### `formats` An array of image formats to use for the `` tags. By default, this is set to `['webp']`. -#### `fallbackFormat` +##### `fallbackFormat` Format to use as a fallback value for the `` tag. Defaults to `.png` for static images, `.gif` for animated images, and `.svg` for SVG files. -#### `pictureAttributes` +##### `pictureAttributes` An object of attributes to be added to the `` tag. Use this property to apply attributes to the outer `` element itself. Attributes applied to the `` component directly will apply to the inner `` element, except for those used for image transformation. -## `getImage()` +### `getImage()`

diff --git a/src/content/docs/en/reference/modules/astro-content.mdx b/src/content/docs/en/reference/modules/astro-content.mdx index 2a70cb9c96f57..63f3f3e120e2c 100644 --- a/src/content/docs/en/reference/modules/astro-content.mdx +++ b/src/content/docs/en/reference/modules/astro-content.mdx @@ -29,7 +29,7 @@ import { type SchemaContext, } from 'astro:content'; ``` -## `defineCollection()` +### `defineCollection()`

@@ -56,7 +56,7 @@ export const collections = { blog }; This function accepts the following properties: -### `type` +#### `type`

@@ -74,7 +74,7 @@ This function accepts the following properties: This means collections **cannot** store a mix of content and data formats. You must split these entries into separate collections by type. ::: -### `schema` +#### `schema`

@@ -85,7 +85,7 @@ This means collections **cannot** store a mix of content and data formats. You m [See the `Content Collection` guide](/en/guides/content-collections/#defining-a-collection-schema) for example usage. -## `reference()` +### `reference()`

@@ -120,7 +120,7 @@ export const collections = { blog, authors }; [See the `Content Collection` guide](/en/guides/content-collections/#defining-collection-references) for example usage. -## `getCollection()` +### `getCollection()`

@@ -147,7 +147,7 @@ const draftBlogPosts = await getCollection('blog', ({ data }) => { [See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. -## `getEntry()` +### `getEntry()`

@@ -175,7 +175,7 @@ const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); See the `Content Collections` guide for examples of [querying collection entries](/en/guides/content-collections/#querying-collections). -## `getEntries()` +### `getEntries()`

@@ -196,7 +196,7 @@ const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts --- ``` -## `getEntryBySlug()` +### `getEntryBySlug()`

@@ -220,7 +220,7 @@ const enterprise = await getEntryBySlug('blog', 'enterprise'); [See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage. -## `getDataEntryById()` +### `getDataEntryById()`

@@ -243,7 +243,19 @@ const picardProfile = await getDataEntryById('captains', 'picard'); --- ``` -## Collection Entry Type +## `astro:content` types + +```ts +import type { + CollectionEntry, + CollectionKey, + ContentCollectionKey, + DataCollectionKey, + SchemaContext, + } from 'astro:content'; +``` + +### `CollectionEntry` Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#getentry), and [`getEntries()`](#getentries) each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`: @@ -251,9 +263,12 @@ Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#g import type { CollectionEntry } from 'astro:content'; ``` -The `CollectionEntry` type is an object with the following values. `TCollectionName` is the name of the collection you're querying (e.g. `CollectionEntry<'blog'>`). +`CollectionEntry` is a generic type. Use it with the name of the collection you’re querying. +For example, an entry in your `blog` collection would have the type `CollectionEntry<'blog'>`. + +Each `CollectionEntry` is an object with the following values: -### `id` +#### `id` **Available for:** `type: 'content'` and `type: 'data'` collections **Example Types:** @@ -262,35 +277,35 @@ The `CollectionEntry` type is an object with the following valu A unique ID using the file path relative to `src/content/[collection]`. Enumerates all possible string values based on the collection entry file paths. Note that collections [defined as `type: 'content'`](#type) include the file extension in their ID, while collections defined as `type: 'data'` do not. -### `collection` +#### `collection` **Available for:** `type: 'content'` and `type: 'data'` collections **Example Type:** `'blog' | 'authors' | ...` The name of a top-level folder under `src/content/` in which entries are located. This is the name used to reference the collection in your schema, and in querying functions. -### `data` +#### `data` **Available for:** `type: 'content'` and `type: 'data'` collections **Type:** `CollectionSchema` An object of frontmatter properties inferred from your collection schema ([see `defineCollection()` reference](#definecollection)). Defaults to `any` if no schema is configured. -### `slug` +#### `slug` **Available for:** `type: 'content'` collections only **Example Type:** `'entry-1' | 'entry-2' | ...` A URL-ready slug for Markdown or MDX documents. Defaults to the `id` without the file extension, but can be overridden by setting [the `slug` property](/en/guides/content-collections/#defining-custom-slugs) in a file's frontmatter. -### `body` +#### `body` **Available for:** `type: 'content'` collections only **Type:** `string` A string containing the raw, uncompiled body of the Markdown or MDX document. -### `render()` +#### `render()` **Available for:** `type: 'content'` collections only **Type:** `() => Promise` @@ -312,10 +327,6 @@ const { Content, headings, remarkPluginFrontmatter } = await entry.render(); [See the `Content Collection` guide](/en/guides/content-collections/#rendering-content-to-html) for example usage. -## Other Content Collection Types - -The `astro:content` module also exports the following types for use in your Astro project: - ### `CollectionKey`

diff --git a/src/content/docs/en/reference/modules/astro-i18n.mdx b/src/content/docs/en/reference/modules/astro-i18n.mdx index 6813b7881f752..127f9169e88e4 100644 --- a/src/content/docs/en/reference/modules/astro-i18n.mdx +++ b/src/content/docs/en/reference/modules/astro-i18n.mdx @@ -41,7 +41,7 @@ import { } from 'astro:i18n'; ``` -## `getRelativeLocaleUrl()` +### `getRelativeLocaleUrl()`

@@ -76,7 +76,7 @@ getRelativeLocaleUrl("fr_CA", "getting-started", { --- ``` -## `getAbsoluteLocaleUrl()` +### `getAbsoluteLocaleUrl()`

@@ -114,7 +114,7 @@ getAbsoluteLocaleUrl("fr_CA", "getting-started", { --- ``` -## `getRelativeLocaleUrlList()` +### `getRelativeLocaleUrlList()`

@@ -124,7 +124,7 @@ getAbsoluteLocaleUrl("fr_CA", "getting-started", { Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list of relative paths for all the locales. -## `getAbsoluteLocaleUrlList()` +### `getAbsoluteLocaleUrlList()`

@@ -133,7 +133,7 @@ Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list o Use this like [`getAbsoluteLocaleUrl`](/en/guides/internationalization/#custom-locale-paths) to return a list of absolute paths for all the locales. -## `getPathByLocale()` +### `getPathByLocale()`

@@ -162,7 +162,7 @@ getPathByLocale("fr-CA"); // returns "french" --- ``` -## `getLocaleByPath()` +### `getLocaleByPath()`

@@ -190,7 +190,7 @@ getLocaleByPath("french"); // returns "fr" because that's the first code configu --- ``` -## `redirectToDefaultLocale()` +### `redirectToDefaultLocale()`

@@ -217,7 +217,7 @@ export const onRequest = defineMiddleware((context, next) => { }) ``` -## `redirectToFallback()` +### `redirectToFallback()`

@@ -244,7 +244,7 @@ export const onRequest = defineMiddleware(async (context, next) => { }) ``` -## `notFound()` +### `notFound()`

@@ -275,7 +275,7 @@ export const onRequest = defineMiddleware((context, next) => { }) ``` -## `middleware()` +### `middleware()`

@@ -310,7 +310,7 @@ export const onRequest = sequence(customLogic, middleware({ })) ``` -## `requestHasLocale()` +### `requestHasLocale()`

diff --git a/src/content/docs/en/reference/modules/astro-middleware.mdx b/src/content/docs/en/reference/modules/astro-middleware.mdx index b2119ec0498c5..4ecea955d739c 100644 --- a/src/content/docs/en/reference/modules/astro-middleware.mdx +++ b/src/content/docs/en/reference/modules/astro-middleware.mdx @@ -23,7 +23,7 @@ import { } from 'astro:middleware'; ``` -## `defineMiddleware()` +### `defineMiddleware()` You can import and use the utility function `defineMiddleware()` to take advantage of type safety: @@ -37,7 +37,7 @@ export const onRequest = defineMiddleware((context, next) => { }); ``` -### `onRequest()` +#### `onRequest()` **Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` @@ -52,7 +52,7 @@ export function onRequest (context, next) { }; ``` -#### `context` +##### `context`

@@ -63,7 +63,7 @@ The first argument of `onRequest()` is a context object. It mirrors many of the See [Endpoint contexts](/en/reference/api-reference/#endpoint-context) for more information about the context object. -#### `next()` +##### `next()`

@@ -74,7 +74,7 @@ The second argument of `onRequest()` is a function that calls all the subsequent Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. -## `sequence()` +### `sequence()`

@@ -93,7 +93,7 @@ async function greeting(_, next) {...} export const onRequest = sequence(validation, auth, greeting); ``` -## `createContext()` +### `createContext()`

@@ -105,7 +105,7 @@ A low-level API to create an [`APIContext`](/en/reference/api-reference/#endpoin This function can be used by integrations/adapters to programmatically execute the Astro middleware. -## `trySerializeLocals()` +### `trySerializeLocals()`

From 8ed899555900554ec8172b87328ccfdc4e26b506 Mon Sep 17 00:00:00 2001 From: Chris Swithinbank Date: Thu, 24 Oct 2024 21:52:07 +0200 Subject: [PATCH 25/32] Make the `astro:transitions` reference slightly more truthful --- .../reference/modules/astro-transitions.mdx | 220 +++++++++++------- 1 file changed, 140 insertions(+), 80 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index 3502692efa233..e469fe4a581c7 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -16,27 +16,11 @@ For features and usage examples, [see our View Transitions guide](/en/guides/vie ## Imports from `astro:transitions` -```astro ---- -import { - ViewTransitions, - navigate, - supportsViewTransitions, - transitionEnabledOnThisPage, - getFallback, -} from 'astro:transitions'; ---- - - +```ts +import { fade, slide, ViewTransitions } from 'astro:transitions'; ``` -## `` +### ``

@@ -59,7 +43,65 @@ import { ViewTransitions } from 'astro:transitions'; See more about how to [control the router](/en/guides/view-transitions/#router-control) and [add transition directives](/en/guides/view-transitions/#transition-directives) to page elements and components. -## `navigate()` +### `fade` + +

+ +**Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` + +

+ +Utility function to support customizing the duration of the built-in `fade` animation. + +```astro {2} /fade\\(.+\\)/ +--- +import { fade } from 'astro:transitions'; +--- + + +
+ + +
+``` + +### `slide` + +

+ +**Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` + +

+ +Utility function to support customizing the duration of the built-in `slide` animation. + +```astro {2} /slide\\(.+\\)/ +--- +import { slide } from 'astro:transitions'; +--- + + +
+ + +
+``` + +## Imports from `astro:transitions/client` + +```astro + +``` + +### `navigate()`

@@ -71,7 +113,7 @@ A function that executes a navigation to the given `href` using the View Transit This function signature is based on the [`navigate` function from the browser Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate). Although based on the Navigation API, this function is implemented on top of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to allow for navigation without reloading the page. -### `history` option +#### `history` option

@@ -88,7 +130,7 @@ Defines how this navigation should be added to the browser history. This option follows the [`history` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history) from the browser Navigation API but simplified for the cases that can happen on an Astro project. -### `formData` option +#### `formData` option

@@ -102,7 +144,7 @@ When this option is provided, the requests to the navigation target page will be Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically. -### `info` option +#### `info` option

@@ -114,7 +156,7 @@ Arbitrary data to be included in the `astro:before-preparation` and `astro:befor This option mimics the [`info` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info) from the browser Navigation API. -### `state` option +#### `state` option

@@ -126,7 +168,7 @@ Arbitrary data to be associated with the `NavitationHistoryEntry` object created This option mimics the [`state` option](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state) from the browser Navigation API. -### `sourceElement` option +#### `sourceElement` option

@@ -138,7 +180,7 @@ The element that triggered this navigation, if any. This element will be availab - `astro:before-preparation` - `astro:before-swap` -## `supportsViewTransitions` +### `supportsViewTransitions`

@@ -148,7 +190,7 @@ The element that triggered this navigation, if any. This element will be availab Whether or not view transitions are supported and enabled in the current browser. -## `transitionEnabledOnThisPage` +### `transitionEnabledOnThisPage`

@@ -158,7 +200,7 @@ Whether or not view transitions are supported and enabled in the current browser Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions. -## `getFallback` +### `getFallback()`

@@ -170,6 +212,66 @@ Returns the fallback strategy to use in browsers that do not support view transi See the guide on [Fallback control](/en/guides/view-transitions/#fallback-control) for how to choose and configure the fallback behavior. +### `swapFunctions` + +

+ + +

+ +An object containing the utility functions used to build Astro’s default swap function. +These can be useful when [building a custom swap function](/en/guides/view-transitions/#building-a-custom-swap-function). + +`swapFunctions` provides the following methods: + +#### `deselectScripts()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using [`data-astro-rerun`](/en/guides/view-transitions/#data-astro-rerun). + +#### `swapRootAttributes()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Swaps the attributes between the document roots, like the `lang` attribute. This also includes Astro-injected internal attributes like `data-astro-transition`, which makes the transition direction available to Astro-generated CSS rules. + +When making a custom swap function, it is important to call this function so as not to break the view transition's animations. + +#### `swapHeadElements()` + +

+ +**Type:** `(newDocument: Document) => void` +

+ +Removes every element from the current document's `` that is not persisted to the new document. Then appends all new elements from the new document's `` to the current document's ``. + +#### `saveFocus()` + +

+ +**Type:** `() => () => void` +

+ +Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it. + + +#### `swapBodyElement()` + +

+ +**Type:** `(newBody: Element, oldBody: Element) => void` +

+ +Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. + ## Lifecycle events ### `astro:before-preparation` event @@ -184,7 +286,7 @@ This event has the attributes: - [`from`](#from) - [`to`](#to) - [`formData`](#formdata) -- [`loader`](#loader) +- [`loader()`](#loader) Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-preparation). @@ -210,7 +312,7 @@ This event has the attributes: - [`from`](#from) - [`to`](#to) - [`viewTransition`](#viewtransition) -- [`swap`](#swap) +- [`swap()`](#swap) Read more about how to use this event on the [View Transitions guide](/en/guides/view-transitions/#astrobefore-swap). @@ -317,7 +419,7 @@ When this attribute is set, a `POST` request will be sent to the [`to` URL](#to) When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the [`navigate()` function](#navigate), this value is the same as given in the options. -#### `loader` +#### `loader()`

@@ -335,7 +437,7 @@ Implementation of the following phase in the navigation (loading the next page). The view transition object used in this navigation. On browsers that do not support the [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API), this is an object implementing the same API for convenience but without the DOM integration. -### `swap` +#### `swap()`

@@ -344,54 +446,12 @@ The view transition object used in this navigation. On browsers that do not supp Implementation of the document swap logic. -Read more on how to [build your own custom swap function](/en/guides/view-transitions/#building-a-custom-swap-function) on the View Transitions guide. +Read more about [building a custom swap function](/en/guides/view-transitions/#building-a-custom-swap-function) in the View Transitions guide. By default, this implementation will call the following functions in order: -#### `deselectScripts()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using [`data-astro-rerun`](/en/guides/view-transitions/#data-astro-rerun). - -#### `swapRootAttributes()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Swaps the attributes between the document roots, like the `lang` attribute. This also includes Astro-injected internal attributes like `data-astro-transition`, which makes the transition direction available to Astro-generated CSS rules. - -When making a custom swap function, it is important to call this function so as not to break the view transition's animations. - -#### `swapHeadElements()` - -

- -**Type:** `(newDocument: Document) => void` -

- -Removes every element from the current document's `` that is not persisted to the new document. Then appends all new elements from the new document's `` to the current document's ``. - -#### `saveFocus()` - -

- -**Type:** `() => () => void` -

- -Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it. - - -#### `swapBodyElements()` - -

- -**Type:** `(newBody: Element, oldBody: Element) => void` -

- -Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. +1. [`deselectScripts()`](#deselectscripts) +2. [`swapRootAttributes()`](#swaprootattributes) +3. [`swapHeadElements()`](#swapheadelements) +4. [`saveFocus()`](#savefocus) +5. [`swapBodyElement()`](#swapbodyelement) From 023633c2d21443c274451ecbebff4e3203824f59 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 24 Oct 2024 17:15:49 -0300 Subject: [PATCH 26/32] fix links --- src/content/docs/en/guides/content-collections.mdx | 2 +- src/content/docs/en/guides/markdown-content.mdx | 2 +- src/content/docs/ja/guides/content-collections.mdx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/content/docs/en/guides/content-collections.mdx b/src/content/docs/en/guides/content-collections.mdx index 2d54ef36be838..f10abc4f3c70a 100644 --- a/src/content/docs/en/guides/content-collections.mdx +++ b/src/content/docs/en/guides/content-collections.mdx @@ -343,7 +343,7 @@ const allBlogPosts = await getCollection('blog'); const graceHopperProfile = await getEntry('authors', 'grace-hopper'); ``` -Both functions return content entries as defined by the [`CollectionEntry`](/en/reference/modules/astro-content/#collection-entry-type) type. +Both functions return content entries as defined by the [`CollectionEntry`](/en/reference/modules/astro-content/#collectionentry) type. ### Accessing referenced data diff --git a/src/content/docs/en/guides/markdown-content.mdx b/src/content/docs/en/guides/markdown-content.mdx index bc707f66dd919..135903e9119ce 100644 --- a/src/content/docs/en/guides/markdown-content.mdx +++ b/src/content/docs/en/guides/markdown-content.mdx @@ -61,7 +61,7 @@ const posts = Object.values(await import.meta.glob('../posts/*.md', { eager: tru When fetching data from your collections via helper functions, your Markdown's frontmatter properties are available on a `data` object (e.g. `post.data.title`). Additionally, `body` contains the raw, uncompiled body content as a string. -See the full [CollectionEntry type](/en/reference/modules/astro-content/#collection-entry-type). +See the full [CollectionEntry type](/en/reference/modules/astro-content/#collectionentry). #### Importing Markdown diff --git a/src/content/docs/ja/guides/content-collections.mdx b/src/content/docs/ja/guides/content-collections.mdx index b6704b9f18794..814100ab58a87 100644 --- a/src/content/docs/ja/guides/content-collections.mdx +++ b/src/content/docs/ja/guides/content-collections.mdx @@ -337,7 +337,7 @@ const allBlogPosts = await getCollection('blog'); const graceHopperProfile = await getEntry('authors', 'grace-hopper'); ``` -どちらの関数も、[`CollectionEntry`](/ja/reference/modules/astro-content/#collection-entry-type)型で定義されたコンテンツエントリーを返します。 +どちらの関数も、[`CollectionEntry`](/ja/reference/modules/astro-content/#collectionentry)型で定義されたコンテンツエントリーを返します。 ### 参照データへのアクセス From a53dc596701f445a8dc2c023900bb20522f06ad9 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 24 Oct 2024 17:26:44 -0300 Subject: [PATCH 27/32] fix other link --- src/content/docs/en/guides/content-collections.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/guides/content-collections.mdx b/src/content/docs/en/guides/content-collections.mdx index f10abc4f3c70a..8f314d4cd25f5 100644 --- a/src/content/docs/en/guides/content-collections.mdx +++ b/src/content/docs/en/guides/content-collections.mdx @@ -438,7 +438,7 @@ const blogEntries = await getCollection('blog'); A component can also pass an entire content entry as a prop. -If you do this, you can use the [`CollectionEntry`](/en/reference/modules/astro-content/#collection-entry-type) utility to correctly type your components props using TypeScript. This utility takes a string argument that matches the name of your collection schema, and will inherit all of the properties of that collection's schema. +If you do this, you can use the [`CollectionEntry`](/en/reference/modules/astro-content/#collectionentry) utility to correctly type your components props using TypeScript. This utility takes a string argument that matches the name of your collection schema, and will inherit all of the properties of that collection's schema. ```astro /CollectionEntry(?:<.+>)?/ --- From 205f31ee0942bcedc5d3c76ac46208b7acc9279d Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 24 Oct 2024 18:17:05 -0300 Subject: [PATCH 28/32] still fixing links --- src/content/docs/ja/guides/content-collections.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/ja/guides/content-collections.mdx b/src/content/docs/ja/guides/content-collections.mdx index 814100ab58a87..d37b953a72792 100644 --- a/src/content/docs/ja/guides/content-collections.mdx +++ b/src/content/docs/ja/guides/content-collections.mdx @@ -432,7 +432,7 @@ const blogEntries = await getCollection('blog'); コンポーネントは、コンテンツエントリー全体をプロパティとして渡すこともできます。 -この場合、[`CollectionEntry`](/ja/reference/modules/astro-content/#collection-entry-type)ユーティリティを使用して、TypeScriptでコンポーネントのプロパティを適切に型付けできます。 このユーティリティは、コレクションスキーマの名前と一致する文字列引数を取り、そのコレクションのスキーマのすべてのプロパティを継承します。 +この場合、[`CollectionEntry`](/ja/reference/modules/astro-content/#collectionentry)ユーティリティを使用して、TypeScriptでコンポーネントのプロパティを適切に型付けできます。 このユーティリティは、コレクションスキーマの名前と一致する文字列引数を取り、そのコレクションのスキーマのすべてのプロパティを継承します。 ```astro /CollectionEntry(?:<.+>)?/ --- From ba977cf39fa1899ff5786ac470d7cb785b62106e Mon Sep 17 00:00:00 2001 From: Luiz Ferraz Date: Thu, 24 Oct 2024 18:47:21 -0300 Subject: [PATCH 29/32] Update astro:transitions page --- src/content/docs/en/reference/modules/astro-transitions.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index e469fe4a581c7..db4893828de5e 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -10,14 +10,14 @@ import ReadMore from '~/components/ReadMore.astro';

-This module provides functions to control and interact with the View Transitions API and client-side router. +These modules provides functions to control and interact with the View Transitions API and client-side router. For features and usage examples, [see our View Transitions guide](/en/guides/view-transitions/). ## Imports from `astro:transitions` ```ts -import { fade, slide, ViewTransitions } from 'astro:transitions'; +import { ViewTransitions, fade, slide } from 'astro:transitions'; ``` ### `` From 20e53c3822bc18db840c50c0ff1721ba03dd62c1 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 24 Oct 2024 18:59:44 -0300 Subject: [PATCH 30/32] use 3.0.0 stable version number --- .../docs/en/reference/modules/astro-transitions.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index db4893828de5e..28cec1201cc52 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -8,7 +8,7 @@ tableOfContents: import Since from '~/components/Since.astro'; import ReadMore from '~/components/ReadMore.astro'; -

+

These modules provides functions to control and interact with the View Transitions API and client-side router. @@ -22,7 +22,7 @@ import { ViewTransitions, fade, slide } from 'astro:transitions'; ### `` -

+

Opt in to using view transitions on individual pages by importing and adding the `` routing component to `` on every desired page. @@ -48,7 +48,7 @@ See more about how to [control the router](/en/guides/view-transitions/#router-c

**Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` - +

Utility function to support customizing the duration of the built-in `fade` animation. @@ -70,7 +70,7 @@ import { fade } from 'astro:transitions';

**Type:** `(opts: { duration?: string | number }) => TransitionDirectionalAnimations` - +

Utility function to support customizing the duration of the built-in `slide` animation. From c31325ef3a1893ee8ee8b11869b0b9e137ca5d12 Mon Sep 17 00:00:00 2001 From: sarahrainsberger Date: Fri, 25 Oct 2024 11:35:31 +0000 Subject: [PATCH 31/32] move onRequest out of imports section --- .../en/reference/modules/astro-middleware.mdx | 74 +++++++++---------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-middleware.mdx b/src/content/docs/en/reference/modules/astro-middleware.mdx index 4ecea955d739c..af8e43018fd9f 100644 --- a/src/content/docs/en/reference/modules/astro-middleware.mdx +++ b/src/content/docs/en/reference/modules/astro-middleware.mdx @@ -37,43 +37,6 @@ export const onRequest = defineMiddleware((context, next) => { }); ``` -#### `onRequest()` - -**Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` - -A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It receives two arguments: [context](#context) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. - -```js title="src/middleware.js" -export function onRequest (context, next) { - // intercept response data from a request - // optionally, transform the response - // return a Response directly, or the result of calling `next()` - return next(); -}; -``` - -##### `context` - -

- -**Type:** `APIContext` -

- -The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. - -See [Endpoint contexts](/en/reference/api-reference/#endpoint-context) for more information about the context object. - -##### `next()` - -

- -**Type:** `(rewritePayload?: string | URL | Request) => Promise`
-

- -The second argument of `onRequest()` is a function that calls all the subsequent middleware in the chain and returns a `Response`. For example, other middleware could modify the HTML body of a response and awaiting the result of `next()` would allow your middleware to respond to those changes. - -Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. - ### `sequence()`

@@ -114,3 +77,40 @@ This function can be used by integrations/adapters to programmatically execute t

A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. + +## `onRequest()` + +**Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` + +A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It receives two arguments: [context](#context) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`. + +```js title="src/middleware.js" +export function onRequest (context, next) { + // intercept response data from a request + // optionally, transform the response + // return a Response directly, or the result of calling `next()` + return next(); +}; +``` + +### `context` + +

+ +**Type:** `APIContext` +

+ +The first argument of `onRequest()` is a context object. It mirrors many of the `Astro` global properties. + +See [Endpoint contexts](/en/reference/api-reference/#endpoint-context) for more information about the context object. + +### `next()` + +

+ +**Type:** `(rewritePayload?: string | URL | Request) => Promise`
+

+ +The second argument of `onRequest()` is a function that calls all the subsequent middleware in the chain and returns a `Response`. For example, other middleware could modify the HTML body of a response and awaiting the result of `next()` would allow your middleware to respond to those changes. + +Since Astro v4.13.0, `next()` accepts an optional URL path parameter in the form of a string, `URL`, or `Request` to [rewrite](/en/guides/routing/#rewrites) the current request without retriggering a new rendering phase. \ No newline at end of file From 714ddcd55dbfba70eb43f3218c7abfb758b01d5c Mon Sep 17 00:00:00 2001 From: Chris Swithinbank Date: Fri, 25 Oct 2024 15:33:50 +0200 Subject: [PATCH 32/32] Friday pass --- .../docs/en/reference/modules/astro-content.mdx | 5 ----- .../docs/en/reference/modules/astro-middleware.mdx | 12 +++++++++--- .../docs/en/reference/modules/astro-transitions.mdx | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/reference/modules/astro-content.mdx b/src/content/docs/en/reference/modules/astro-content.mdx index 63f3f3e120e2c..b391ae48835d2 100644 --- a/src/content/docs/en/reference/modules/astro-content.mdx +++ b/src/content/docs/en/reference/modules/astro-content.mdx @@ -22,11 +22,6 @@ import { getEntry, getEntries, reference, - type CollectionEntry, - type CollectionKey, - type ContentCollectionKey, - type DataCollectionKey, - type SchemaContext, } from 'astro:content'; ``` ### `defineCollection()` diff --git a/src/content/docs/en/reference/modules/astro-middleware.mdx b/src/content/docs/en/reference/modules/astro-middleware.mdx index af8e43018fd9f..e05df3b30e88e 100644 --- a/src/content/docs/en/reference/modules/astro-middleware.mdx +++ b/src/content/docs/en/reference/modules/astro-middleware.mdx @@ -78,7 +78,11 @@ This function can be used by integrations/adapters to programmatically execute t A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error. -## `onRequest()` +## Middleware exports + +When defining your project’s middleware in `src/middleware.js`, export the following user-defined functions: + +### `onRequest()` **Type:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` @@ -93,7 +97,9 @@ export function onRequest (context, next) { }; ``` -### `context` +Your `onRequest()` function will be called with the following arguments: + +#### `context`

@@ -104,7 +110,7 @@ The first argument of `onRequest()` is a context object. It mirrors many of the See [Endpoint contexts](/en/reference/api-reference/#endpoint-context) for more information about the context object. -### `next()` +#### `next()`

diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index 28cec1201cc52..6694bd15baad7 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -10,7 +10,7 @@ import ReadMore from '~/components/ReadMore.astro';

-These modules provides functions to control and interact with the View Transitions API and client-side router. +These modules provide functions to control and interact with the View Transitions API and client-side router. For features and usage examples, [see our View Transitions guide](/en/guides/view-transitions/).