From 9e2b10ae0d218240fd0e3f2eecde5ac49b09e0e0 Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 21:32:16 +0900 Subject: [PATCH 01/43] i18n(ko-KR): create `astro-middleware.mdx` (#9817) Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../ko/reference/modules/astro-middleware.mdx | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/content/docs/ko/reference/modules/astro-middleware.mdx diff --git a/src/content/docs/ko/reference/modules/astro-middleware.mdx b/src/content/docs/ko/reference/modules/astro-middleware.mdx new file mode 100644 index 0000000000000..f56145541a414 --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-middleware.mdx @@ -0,0 +1,122 @@ +--- +title: 미들웨어 API 참조 +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +미들웨어를 사용하면 페이지나 엔드포인트가 렌더링될 때마다 요청과 응답을 가로채고 동작을 동적으로 주입할 수 있습니다. 기능 및 사용 예시는 [미들웨어 가이드](/ko/guides/middleware/)를 확인하세요. + +## `astro:middleware`에서 가져오기 + +```js +import { + sequence, + createContext, + trySerializeLocals, + defineMiddleware, + } from 'astro:middleware'; +``` + +### `defineMiddleware()` + +타입 안전성을 활용하기 위해 유틸리티 함수 `defineMiddleware()`를 가져와 사용할 수 있습니다: + +```ts +// src/middleware.ts +import { defineMiddleware } from "astro:middleware"; + +// `context` 및 `next`의 타입이 자동으로 설정됩니다. +export const onRequest = defineMiddleware((context, next) => { + +}); +``` + +### `sequence()` + +

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

+ +미들웨어 함수를 인수로 받아 전달된 순서대로 실행하는 함수입니다. + +```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()` + +

+ +**타입:** `(context: CreateContext) => APIContext`
+ +

+ +Astro 미들웨어 `onRequest()` 함수에 전달될 [`APIContext`](/ko/reference/api-reference/#엔드포인트-context)를 생성하는 저수준 API입니다. + +이 함수는 Astro 미들웨어를 프로그래밍 방식으로 실행하기 위해 통합/어댑터에서 사용할 수 있습니다. + +### `trySerializeLocals()` + +

+ +**타입:** `(value: unknown) => string`
+ +

+ +모든 값을 받아들여 해당 값의 직렬화된 버전 (문자열)을 반환하려고 시도하는 저수준 API입니다. 값을 직렬화할 수 없으면 함수에서 런타임 오류가 발생합니다. + +## 미들웨어 내보내기 + +프로젝트의 미들웨어를 `src/middleware.js`에서 정의할 때, 다음 사용자 정의 함수를 내보내세요: + +### `onRequest()` + +**타입:** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` + +모든 페이지 또는 API 경로를 렌더링하기 전에 호출되는 `src/middleware.js`에서 내보낸 필수 함수입니다. 두 개의 인수 [context](#context) 및 [next()](#next)를 전달받습니다. `onRequest()`는 `Response`를 직접 반환하거나 `next()`를 호출하여 반환해야 합니다. + +```js title="src/middleware.js" +export function onRequest (context, next) { + // 요청의 응답 데이터를 가로챕니다. + // 선택적으로 응답을 변환합니다. + // Response를 직접 반환하거나 `next()` 호출 결과를 반환합니다. + return next(); +}; +``` + +`onRequest()` 함수는 다음 인자를 전달받아 호출됩니다. + +#### `context` + +

+ +**타입:** `APIContext` +

+ +`onRequest()`의 첫 번째 인수는 컨텍스트 객체입니다. 이는 많은 `Astro` 전역 프로퍼티를 반영합니다. + +컨텍스트 객체에 대해 더 자세히 알아보기 위해 [엔드포인트 컨텍스트](/ko/reference/api-reference/#엔드포인트-context)를 방문하세요. + +#### `next()` + +

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

+ +`onRequest()`의 두 번째 인수는 체인의 모든 후속 미들웨어를 호출하고 `Response`를 반환하는 함수입니다. 예를 들어, 다른 미들웨어가 응답의 HTML 본문을 수정할 수 있으며 `next()`의 결과를 기다리면 미들웨어가 이러한 변경 사항에 응답할 수 있습니다. + +Astro v4.13.0부터 `next()`는 새 렌더링 단계를 다시 트리거하지 않고 현재 요청을 [리라이트](/ko/guides/routing/#리라이트)하기 위해 문자열 형식의 선택적 URL 경로 매개 변수인 `URL` 또는 `Request`를 허용합니다. From 87dbd4d457875542c209a31fb5faa86ccafb0cbf Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 21:40:02 +0900 Subject: [PATCH 02/43] i18n(ko-KR): create `astro-transitions.mdx` (#9818) Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../reference/modules/astro-transitions.mdx | 458 ++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 src/content/docs/ko/reference/modules/astro-transitions.mdx diff --git a/src/content/docs/ko/reference/modules/astro-transitions.mdx b/src/content/docs/ko/reference/modules/astro-transitions.mdx new file mode 100644 index 0000000000000..e7c6927fa04bb --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-transitions.mdx @@ -0,0 +1,458 @@ +--- +title: View Transitions API 참조 +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +이 모듈은 View Transitions API 및 클라이언트 측 라우터를 제어하고 상호 작용하는 함수를 제공합니다. + +기능 및 사용 예시는 [View Transitions 가이드](/ko/guides/view-transitions/)를 참조하세요. + +## `astro:transitions`에서 가져오기 + +```ts +import { ViewTransitions, fade, slide } from 'astro:transitions'; +``` + +### `` + +

+ +원하는 모든 페이지의 ``에 `` 라우팅 컴포넌트를 가져오고 추가하여 개별 페이지에서 트랜지션을 사용하도록 선택합니다. + +```astro title="src/pages/index.astro" ins={2,7} +--- +import { ViewTransitions } from 'astro:transitions'; +--- + + + My Homepage + + + +

Welcome to my website!

+ + +``` + +페이지 요소와 컴포넌트에 [라우터 제어](/ko/guides/view-transitions/#라우터-제어) 및 [전환 지시어를 추가](/ko/guides/view-transitions/#전환-지시어)하는 방법에 대해 자세히 알아보세요. + +### `fade` + +

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

+ +기본적으로 제공되는 `fade` 애니메이션의 지속 시간을 설정할 수 있는 유틸리티 함수입니다. + +```astro {2} /fade\\(.+\\)/ +--- +import { fade } from 'astro:transitions'; +--- + + +
+ + +
+``` + +### `slide` + +

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

+ +기본적으로 제공되는 `slide` 애니메이션의 지속 시간을 설정할 수 있는 유틸리티 함수입니다. + +```astro {2} /slide\\(.+\\)/ +--- +import { slide } from 'astro:transitions'; +--- + + +
+ + +
+``` + +## `astro:transitions/client`에서 가져오기 + +```astro + +``` + +### `navigate()` + +

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

+ +View Transitions API를 사용하여 지정된 `href`로 탐색을 실행하는 함수입니다. + +이 함수 시그니처는 [브라우저 Navigation API의 `navigate` 함수](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate)를 기반으로 합니다. 이 함수는 Navigation API를 기반으로 하지만, 페이지를 다시 로드하지 않고 탐색할 수 있도록 [History API](https://developer.mozilla.org/ko/docs/Web/API/History_API) 위에 구현되어 있습니다. + +#### `history` 옵션 + +

+ +**타입:** `'auto' | 'push' | 'replace'`
+**기본값:** `'auto'`
+ +

+ +이 탐색을 브라우저 기록에 추가하는 방법을 정의합니다. + +- `'push'`: 라우터는 `history.pushState`를 사용하여 브라우저 기록에 새 항목을 생성합니다. +- `'replace'`: 라우터는 `history.replaceState`를 사용하여 탐색에 새 항목을 추가하지 않고 URL을 업데이트합니다. +- `'auto'` (기본값): 라우터는 `history.pushState`를 시도하지만, URL을 전환할 수 없는 경우 현재 URL은 브라우저 기록을 변경하지 않고 그대로 유지됩니다. + +이 옵션은 브라우저 Navigation API의 [`history` 옵션](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history)을 따르지만, Astro 프로젝트에서 발생할 수 있는 경우를 위해 단순화되었습니다. + +#### `formData` 옵션 + +

+ +**타입:** `FormData`
+ +

+ +`POST` 요청을 위한 `FormData` 객체입니다. + +이 옵션을 제공하면 탐색 대상 페이지에 대한 요청이 양식 데이터 객체를 콘텐츠로 하는 `POST` 요청으로 전송됩니다. + +트랜지션이 활성화된 HTML 양식을 제출하면 페이지 새로 고침이 있는 기본 탐색 대신 이 메서드가 사용됩니다. 이 메서드를 호출하면 프로그래밍 방식으로 동일한 동작을 트리거할 수 있습니다. + +#### `info` 옵션 + +

+ +**타입:** `any`
+ +

+ +이 탐색으로 인해 발생하는 `astro:before-preparation` 및 `astro:before-swap` 이벤트에 포함될 임의의 데이터입니다. + +이 옵션은 브라우저 Navigation API의 [`info` 옵션](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info)을 모방합니다. + +#### `state` 옵션 + +

+ +**타입:** `any`
+ +

+ +이 탐색에서 생성된 `NavitationHistoryEntry` 객체에 연결할 임의의 데이터입니다. 이 데이터는 History API의 [`history.getState` 함수](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState)를 사용하여 검색할 수 있습니다. + +이 옵션은 브라우저 Navigation API의 [`state` 옵션](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state)을 모방합니다. + +#### `sourceElement` 옵션 + +

+ +**타입:** `Element`
+ +

+ +존재하는 경우, 이 탐색을 트리거한 요소입니다. 이 요소는 다음 이벤트에서 사용할 수 있습니다: +- `astro:before-preparation` +- `astro:before-swap` + +### `supportsViewTransitions` + +

+ +**타입:** `boolean`
+ +

+ +현재 브라우저에서 트랜지션이 지원되고 활성화되어 있는지 여부입니다. + +### `transitionEnabledOnThisPage` + +

+ +**타입:** `boolean`
+ +

+ +현재 페이지에 클라이언트 측 탐색을 위한 트랜지션이 활성화되어 있는지 여부입니다. 트랜지션이 있는 페이지에서 다르게 동작하는 컴포넌트를 만드는 데 사용할 수 있습니다. + +### `getFallback()` + +

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

+ +트랜지션을 지원하지 않는 브라우저에서 사용할 대체 전략을 반환합니다. + +대체 동작을 선택하고 구성하는 방법은 [대체 제어](/ko/guides/view-transitions/#대체-제어) 가이드를 참조하세요. + +### `swapFunctions` + +

+ + +

+ +Astro의 기본 스왑 함수를 빌드하는 데 사용되는 유틸리티 함수가 포함된 객체입니다. +[사용자 정의 스왑 함수를 만들때](/ko/guides/view-transitions/#사용자-정의-스왑-함수-구현) 유용할 수 있습니다. + +`swapFunctions`는 다음과 같은 메서드를 제공합니다: + +#### `deselectScripts()` + +

+ +**타입:** `(newDocument: Document) => void` +

+ +새 문서에서 실행해서는 안 되는 스크립트를 표시합니다. 이러한 스크립트는 이미 현재 문서에 있으며 [`data-astro-rerun`](/ko/guides/view-transitions/#data-astro-rerun)을 사용하여 다시 실행하도록 플래그가 지정되지 않습니다. + +#### `swapRootAttributes()` + +

+ +**타입:** `(newDocument: Document) => void` +

+ +`lang` 속성과 같은 문서 루트 간 속성을 스왑합니다. 여기에는 `data-astro-transition`과 같은 Astro에서 삽입한 내부 속성도 포함되어 있어, 트랜지션 방향을 Astro에서 생성된 CSS 규칙에 사용할 수 있습니다. + +사용자 지정 스왑 함수를 만들 때, 트랜지션의 애니메이션이 깨지지 않도록 이 함수를 호출하는 것이 중요합니다. + +#### `swapHeadElements()` + +

+ +**타입:** `(newDocument: Document) => void` +

+ +현재 문서의 ``에서 새 문서에 유지되지 않는 모든 요소를 제거합니다. 그런 다음 새 문서의 ``에 있는 모든 새 요소를 현재 문서의 ``에 추가합니다. + +#### `saveFocus()` + +

+ +**타입:** `() => () => void` +

+ +현재 페이지에서 포커스된 요소를 저장하고, 포커스된 요소가 유지되는 경우, 호출 시 해당 요소에 포커스를 제공하는 함수를 반환합니다. + + +#### `swapBodyElement()` + +

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

+ +이전 body를 새 body로 교체합니다. 그런 다음 이전 body에서 유지되어야 하는 모든 요소를 검토하고 새 body에서 일치하는 요소를 찾아 이전 요소를 다시 제자리로 바꿉니다. + +## 라이프사이클 이벤트 + +### `astro:before-preparation` 이벤트 + +View Transitions를 사용하여 탐색을 시작할 때 전송되는 이벤트입니다. 이 이벤트는 요청이 이루어지고 브라우저 상태가 변경되기 전에 발생합니다. + +이 이벤트에는 속성이 있습니다: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`formData`](#formdata) +- [`loader()`](#loader) + +이 이벤트의 사용 방법에 대한 자세한 내용은 [View Transitions 가이드](/ko/guides/view-transitions/#astrobefore-preparation)에서 확인하세요. + +### `astro:after-preparation` 이벤트 + +View Transitions를 사용하는 탐색에서 다음 페이지가 로드된 후 전송되는 이벤트입니다. + +이 이벤트에는 속성이 없습니다. + +이 이벤트의 사용 방법에 대한 자세한 내용은 [View Transitions 가이드](/ko/guides/view-transitions/#astroafter-preparation)에서 확인하세요. + +### `astro:before-swap` 이벤트 + +다음 페이지가 구문 분석되고, 준비되고, 트랜지션을 준비하면서 문서에 링크된 후, 문서 간 콘텐츠가 교환되기 전에 전송되는 이벤트입니다. + +이 이벤트는 취소할 수 없습니다. `preventDefault()`를 호출하는 것은 아무 작업도 하지 않습니다. + +이 이벤트에는 속성이 있습니다: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`viewTransition`](#viewtransition) +- [`swap()`](#swap) + +이 이벤트의 사용 방법에 대한 자세한 내용은 [View Transitions 가이드](/ko/guides/view-transitions/#astrobefore-swap)에서 확인하세요. + +### `astro:after-swap` 이벤트 + +페이지의 콘텐츠가 교체된 후, 트랜지션이 끝나기 전에 전달되는 이벤트입니다. + +기록 항목과 스크롤 위치가 업데이트된 후, 이 이벤트가 트리거됩니다. + +### `astro:page-load` 이벤트 + +트랜지션을 사용하는 탐색이나 브라우저의 기본 기능으로 페이지 로드가 완료된 후 전달되는 이벤트입니다. + +페이지에서 트랜지션이 활성화되면 일반적으로 `DOMContentLoaded`에서 실행되는 코드가 이 이벤트에서 실행되도록 변경되어야 합니다. + +### 라이프사이클 이벤트 속성 + +

+ +#### `info` + +

+ +**타입:** `URL` +

+ +탐색 중에 정의된 임의의 데이터입니다. + +이는 [`navigate()` 함수](#navigate)의 [`info` 옵션](#info-옵션)에 전달된 리터럴 값입니다. + +#### `sourceElement` + +

+ +**타입:** `Element | undefined` +

+ +탐색을 트리거한 요소입니다. 예를 들어 클릭된 `` 요소가 될 수 있습니다. + +[`navigate()` 함수](#navigate)를 사용할 때는 호출에서 지정된 요소가 됩니다. + +#### `newDocument` + +

+ +**타입:** `Document` +

+ +탐색의 다음 페이지에 대한 문서입니다. 이 문서의 내용은 현재 문서의 내용 대신 교체됩니다. + +#### `navigationType` + +

+ +**타입:** `'push' | 'replace' | 'traverse'` +

+ +어떤 종류의 기록 탐색이 일어나고 있나요. +- `push`: 새 페이지에 대한 새 `NavigationHistoryEntry`가 만들어지고 있습니다. +- `replace`: 현재 `NavigationHistoryEntry`가 새 페이지의 항목으로 대체되고 있습니다. +- `traverse`: `NavigationHistoryEntry`이 생성되지 않습니다. 히스토리 내 위치가 변경되고 있습니다. + 순회 방향은 [`direction` 속성](#direction)에서 지정됩니다. + +#### `direction` + +

+ +**타입:** `Direction` +

+ +트랜지션 방향입니다. +- `forward`: 기록의 다음 페이지 또는 새 페이지로 이동합니다. +- `back`: 기록의 이전 페이지로 이동합니다. +- 다른 리스너가 설정했을 수 있는 기타 모든 항목. + +#### `from` + +

+ +**타입:** `URL` +

+ +The URL of the page initiating the navigation. +탐색을 시작하는 페이지의 URL입니다. + +#### `to` + +

+ +**타입:** `URL` +

+ +탐색 중인 페이지의 URL입니다. 이 속성을 수정할 수 있으며, 라이프사이클이 끝날 때의 값이 다음 페이지의 `NavigationHistoryEntry`에 사용됩니다. + +#### `formData` + +

+ +**타입:** `FormData | undefined` +

+ +`POST` 요청을 위한 `FormData` 객체입니다. + +이 속성을 설정하면 일반적인 `GET` 요청 대신 지정된 양식 데이터 객체를 콘텐츠로 하는 `POST` 요청이 [`to` URL](#to)로 전송됩니다. + +트랜지션이 활성화된 HTML 양식을 제출할 때 이 필드는 양식의 데이터로 자동 설정됩니다. [`navigate()` 함수](#navigate)를 사용하는 경우 이 값은 옵션에 지정된 것과 동일합니다. + +#### `loader()` + +

+ +**타입:** `() => Promise` +

+ +탐색에서 다음 단계 (다음 페이지 로딩)를 구현합니다. 이 구현을 재정의하여 동작을 추가할 수 있습니다. + +#### `viewTransition` + +

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

+ +이 탐색에 사용된 트랜지션 객체입니다. [View Transitions API](https://developer.mozilla.org/ko/docs/Web/API/View_Transitions_API)를 지원하지 않는 브라우저에서는 편의를 위해 동일한 API를 구현하지만 DOM 통합이 없는 객체입니다. + +#### `swap()` + +

+ +**타입:** `() => void` +

+ +문서 스왑 로직을 구현합니다. + +[사용자 지정 스왑 함수를 구현](/ko/guides/view-transitions/#사용자-정의-스왑-함수-구현)하는 방법에 대한 자세한 내용은 View Transitions 가이드를 참조하세요. + +기본적으로 이 구현은 다음 함수를 순서대로 호출합니다: + +1. [`deselectScripts()`](#deselectscripts) +2. [`swapRootAttributes()`](#swaprootattributes) +3. [`swapHeadElements()`](#swapheadelements) +4. [`saveFocus()`](#savefocus) +5. [`swapBodyElement()`](#swapbodyelement) From 42c872aeb4e63897600108ba2d3ec974b5e520a4 Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 21:47:32 +0900 Subject: [PATCH 03/43] i18n(ko-KR): create `astro-actions.mdx` (#9813) * i18n(ko-KR): create `astro-actions.mdx` * fix typo --------- Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../ko/reference/modules/astro-actions.mdx | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 src/content/docs/ko/reference/modules/astro-actions.mdx diff --git a/src/content/docs/ko/reference/modules/astro-actions.mdx b/src/content/docs/ko/reference/modules/astro-actions.mdx new file mode 100644 index 0000000000000..560316b6d8da7 --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-actions.mdx @@ -0,0 +1,176 @@ +--- +title: 액션 API 참조 +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +

+ +액션을 사용하면 클라이언트 코드 및 HTML 양식에서 호출할 수 있는 타입 안정성을 갖춘 백엔드를 구축할 수 있습니다. 액션을 정의하고 호출하는 모든 유틸리티는 `astro:actions` 모듈에 의해 노출됩니다. 예시 및 사용 지침은 [액션 가이드](/ko/guides/actions/)를 참조하세요. + +## `astro:actions`에서 가져오기 + +```js +import { + actions, + defineAction, + isInputError, + ActionError, + } from 'astro:actions'; +``` + +### `defineAction()` + +

+ +

+ +`defineAction()` 유틸리티는 `src/actions/index.ts` 파일에서 새 액션을 정의하는 데 사용됩니다. 이 함수는 실행할 서버 로직이 포함된 [`handler()`](#handler-속성) 함수와 런타임에 입력 매개변수를 검사하는 선택적인 [`input`](#input-유효성-검사기) 속성을 받습니다. + +```ts title="src/actions/index.ts" +import { defineAction } from 'astro:actions'; +import { z } from 'astro:schema'; + +export const server = { + getGreeting: defineAction({ + input: z.object({ + name: z.string(), + }), + handler: async (input, context) => { + return `Hello, ${input.name}!` + } + }) +} +``` + +#### `handler()` 속성 + +

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

+ +`defineAction()`에는 액션이 호출될 때 실행할 서버 로직이 포함된 `handler()` 함수가 필요합니다. 핸들러에서 반환된 데이터는 자동으로 직렬화되어 호출자에게 전송됩니다. + +`handler()`는 사용자 입력을 첫 번째 인수로 받아 호출됩니다. [`input`](#input-유효성-검사기) 유효성 검사기가 설정되어 있으면 사용자 입력은 핸들러로 전달되기 전에 유효성이 검사됩니다. 두 번째 인수는 `getActionResult()`, `callAction()` 및 `redirect()`를 제외한 대부분의 Astro [표준 엔드포인트 컨텍스트](/ko/reference/api-reference/#엔드포인트-context)를 포함하는 `context` 객체입니다. + +반환 값은 [devalue 라이브러리](https://github.com/Rich-Harris/devalue)를 사용하여 구문 분석됩니다. 이 라이브러리는 `Date()`, `Map()`, `Set()`, `URL()`의 인스턴스와 JSON 값을 지원합니다. + +#### `input` 유효성 검사기 + +

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

+ +선택적 `input` 속성은 런타임에 핸들러 입력의 유효성을 검사하기 위해 Zod 유효성 검사기를 전달받습니다. 액션이 유효성 검사에 실패하면 [`BAD_REQUEST` 오류](#actionerror)가 반환되고 `handler`가 호출되지 않습니다. + +`input`을 생략하면 `handler`는 JSON 요청의 경우 `unknown` 타입의 입력을, 양식 요청의 경우 `FormData` 타입의 입력을 받습니다. + +##### `accept: 'form'`과 함께 사용 + +액션이 양식 입력을 전달받는 경우 `z.object()` 유효성 검사기를 사용하여 양식 데이터를 타입이 정해진 객체로 자동 구문 분석합니다. 양식 데이터 필드에 지원되는 유효성 검사기는 다음과 같습니다: + +- `number` 유형의 입력은 `z.number()`를 사용하여 검증할 수 있습니다. +- `checkbox` 유형의 입력은 `z.boolean()`을 사용하여 검증할 수 있습니다. +- `file` 유형의 입력은 `z.instanceof(File)`을 사용하여 검증할 수 있습니다. +- 동일한 `name`의 여러 입력은 `z.array(/* validator */)`를 사용하여 검증할 수 있습니다. +- 다른 모든 입력은 `z.string()`을 사용하여 검증할 수 있습니다. + +`.refine()`, `.transform()`, `.pipe()`를 포함한 확장 함수도 `z.object()` 유효성 검사기에서 지원됩니다. + +서로 다른 유효성 검사기의 조합을 적용하려면 `z.discriminatedUnion()` 래퍼를 사용하여 특정 양식 필드를 기준으로 타입을 좁히세요. 이 예시는 사용자 "생성" 또는 "업데이트" 중 하나로 양식 제출을 처리하며, `type`이라는 이름의 양식 필드를 사용하여 어떤 객체에 대해 유효성 검사를 수행할지 결정합니다. + +```ts +import { defineAction } from 'astro:actions'; +import { z } from 'astro:schema'; + +export const server = { + changeUser: defineAction({ + accept: 'form', + input: z.discriminatedUnion('type', [ + z.object({ + // `type` 필드에 `create` 값이 있을 때 일치합니다. + type: z.literal('create'), + name: z.string(), + email: z.string().email(), + }), + z.object({ + // `type` 필드에 `update` 값이 있을 때 일치합니다. + type: z.literal('update'), + id: z.number(), + name: z.string(), + email: z.string().email(), + }), + ]), + async handler(input) { + if (input.type === 'create') { + // input은 { type: 'create', name: string, email: string } + } else { + // input은 { type: 'update', id: number, name: string, email: string } + } + }, + }), +}; +``` + +### `isInputError()` + +

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

+ +`isInputError()` 유틸리티는 `ActionError`가 입력 유효성 검사 오류인지 확인하는 데 사용됩니다. `input` 유효성 검사기가 `z.object()`인 경우 입력 오류에는 이름별로 그룹화된 오류 메시지가 있는 `fields` 객체가 포함됩니다. + +[양식 입력 오류 가이드](/ko/guides/actions/#양식-입력-오류-표시)에서 `isInputError()` 사용에 대한 자세한 내용을 참조하세요. + +### `ActionError` + +

+ +

+ +액션 `handler`가 던지는 오류를 생성하는 데 `ActionError()` 생성자가 사용됩니다. 이는 발생한 오류 (예: `"UNAUTHORIZED"`)를 설명하는 `code` 속성과 추가 세부정보가 포함된 선택적 `message` 속성을 허용합니다. + +#### `code` + +

+ +

+ +`code` 속성은 모든 HTTP 상태 코드의 사람이 읽을 수 있는 버전을 허용합니다. 지원되는 코드는 다음과 같습니다: + +- `BAD_REQUEST` (400): 클라이언트가 잘못된 입력을 보냈습니다. 이 오류는 액션 `input` 유효성 검사기가 유효성 검사에 실패할 때 발생합니다. +- `UNAUTHORIZED` (401): 클라이언트에 유효한 인증 자격 증명이 없습니다. +- `FORBIDDEN` (403): 클라이언트가 리소스에 액세스할 수 있는 권한이 없습니다. +- `NOT_FOUND` (404): 서버가 요청된 리소스를 찾을 수 없습니다. +- `METHOD_NOT_SUPPORTED` (405): 서버가 요청된 메서드를 지원하지 않습니다. +- `TIMEOUT` (408): 서버가 요청을 처리하는 동안 시간 초과가 발생했습니다. +- `CONFLICT` (409): 충돌로 인해 서버에서 리소스를 업데이트할 수 없습니다. +- `PRECONDITION_FAILED` (412): 서버가 요청의 전제 조건을 충족하지 않습니다. +- `PAYLOAD_TOO_LARGE` (413): 페이로드가 너무 커서 서버가 요청을 처리할 수 없습니다. +- `UNSUPPORTED_MEDIA_TYPE` (415): 서버가 요청의 미디어 유형을 지원하지 않습니다. 참고: 액션은 이미 JSON 및 양식 요청에 대해 [`Content-Type` 헤더](https://developer.mozilla.org/ko/docs/Web/HTTP/Headers/Content-Type)를 확인하므로 이 코드를 수동으로 사용할 필요가 없을 것입니다. +- `UNPROCESSABLE_CONTENT` (422): 시멘틱 오류로 인해 서버가 요청을 처리할 수 없습니다. +- `TOO_MANY_REQUESTS` (429): 서버가 지정된 속도 제한을 초과했습니다. +- `CLIENT_CLOSED_REQUEST` (499): 서버가 응답하기 전에 클라이언트가 요청을 종료했습니다. +- `INTERNAL_SERVER_ERROR` (500): 서버가 예기치 않게 실패했습니다. +- `NOT_IMPLEMENTED` (501): 서버가 요청된 기능을 지원하지 않습니다. +- `BAD_GATEWAY` (502): 서버가 업스트림 서버로부터 잘못된 응답을 받았습니다. +- `SERVICE_UNAVAILABLE` (503): 서버를 일시적으로 사용할 수 없습니다. +- `GATEWAY_TIMEOUT` (504): 서버가 업스트림 서버로부터 시간 초과를 받았습니다. + +#### `message` + +

+ +

+ +`message` 속성은 문자열을 받습니다. (예: "사용자는 로그인해야 합니다.") \ No newline at end of file From 41f38cc29b95dd1f28d45837ae89f779d04b5f07 Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 21:55:17 +0900 Subject: [PATCH 04/43] i18n(ko-KR): create `astro-assets.mdx` (#9814) * i18n(ko-KR): create `astro-assets.mdx` * fix typo --------- Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../ko/reference/modules/astro-assets.mdx | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 src/content/docs/ko/reference/modules/astro-assets.mdx diff --git a/src/content/docs/ko/reference/modules/astro-assets.mdx b/src/content/docs/ko/reference/modules/astro-assets.mdx new file mode 100644 index 0000000000000..57119e0c66cc8 --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-assets.mdx @@ -0,0 +1,159 @@ +--- +title: 자산 API 참조 +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ + Astro는 최적화된 이미지를 표시하기 위한 기본 컴포넌트와 도우미 함수를 제공합니다. 기능 및 사용 예시는 [이미지 가이드](/ko/guides/images/)를 참조하세요. + +## `astro:assets`에서 가져오기 + +```js +import { + Image, + Picture, + getImage, + } from 'astro:assets'; +``` + +### `` + +```astro title="src/components/MyComponent.astro" +--- +// Image 컴포넌트 및 이미지 가져오기 +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // 1600x900의 이미지 +--- + + +A description of my image. +``` + +```html + + +A description of my image. +``` +#### 속성 + +- src (필수) +- alt (필수) +- width 및 height (`public/` 및 원격 이미지를 사용하는 경우 필수) +- format +- quality +- densities +- widths + +위 속성 외에도 `` 컴포넌트는 HTML `` 태그에서 허용하는 모든 속성을 허용합니다. + +[이미지 가이드](/ko/guides/images/#image--astroassets)에서 자세한 내용을 확인하세요. + +### `` + +

+ +다양한 형식 및/또는 크기로 반응형 이미지를 표시하려면 Astro의 `` 컴포넌트를 사용하세요. + +```astro title="src/pages/index.astro" +--- +import { Picture } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // 1600x900의 이미지 +--- + + + +``` + +```html + + + + + A description of my image. + +``` + +[이미지 안내서](/ko/guides/images/#picture-)에서 자세한 내용을 확인하세요. + +#### 속성 + +``는 `` 컴포넌트의 모든 속성과 함께 다음을 허용합니다. + +##### `formats` + +`` 태그에 사용할 이미지 형식의 배열입니다. 기본적으로 `['webp']`로 설정되어 있습니다. + +##### `fallbackFormat` + +`` 태그에 대한 대체 값으로 사용할 형식입니다. 정적 이미지의 경우 기본값은 `.png`, 애니메이션 이미지의 경우 `.gif`, SVG 파일의 경우 `.svg`입니다. + +##### `pictureAttributes` + +`` 태그에 추가될 속성의 객체입니다. 이 속성을 사용하여 외부 `` 요소 자체에 속성을 적용합니다. `` 컴포넌트에 직접 적용된 속성은 이미지 변환에 사용되는 속성을 제외하고 내부 `` 요소에 적용됩니다. + +### `getImage()` + +

+ +**타입:** `(options: UnresolvedImageTransform) => Promise` +

+ +:::caution +`getImage()`는 서버 전용 API에 의존하며 클라이언트에서 사용될 때 빌드를 중단합니다. +::: + +`getImage()` 함수는 HTML이 아닌 다른 곳 (예: [API 경로](/ko/guides/endpoints/#서버-엔드포인트-api-라우트))에서 사용할 이미지를 생성하기 위한 것입니다. 또한 사용자 정의 `` 컴포넌트를 만들 수도 있습니다. + +`getImage()`는 [Image 컴포넌트와 동일한 속성](/ko/reference/components-reference/#속성)을 가진 옵션 객체를 사용합니다 (`alt` 제외). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +다음 타입을 가진 객체를 반환합니다. + +```ts +type GetImageResult = { + /* 이미지 렌더링에 필요한 추가 HTML 속성 (width, height, style 등) */ + attributes: Record; + /* 검증된 매개변수 전달 */ + options: ImageTransform; + /* 원본 매개변수 전달 */ + rawOptions: ImageTransform; + /* 생성된 이미지의 경로 */ + src: string; + srcSet: { + /* 생성된 srcset의 값, 각 항목에는 URL과 크기 설명자가 있습니다. */ + values: SrcSetValue[]; + /* `srcset` 속성에서 사용할 수 있는 값 */ + attribute: string; + }; +} +``` From ead30afb2a71f2b01eb848f1248aef2a33d24f63 Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 22:02:54 +0900 Subject: [PATCH 05/43] i18n(ko-KR): create `astro-content.mdx` (#9815) * i18n(ko-KR): create `astro-content.mdx` * fix typo --------- Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../ko/reference/modules/astro-content.mdx | 373 ++++++++++++++++++ 1 file changed, 373 insertions(+) create mode 100644 src/content/docs/ko/reference/modules/astro-content.mdx diff --git a/src/content/docs/ko/reference/modules/astro-content.mdx b/src/content/docs/ko/reference/modules/astro-content.mdx new file mode 100644 index 0000000000000..d5fed161485e0 --- /dev/null +++ b/src/content/docs/ko/reference/modules/astro-content.mdx @@ -0,0 +1,373 @@ +--- +title: 콘텐츠 컬렉션 API 참조 +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +콘텐츠 컬렉션은 `src/content/`에서 Markdown 또는 MDX 문서를 구성하고 쿼리하는 API를 제공합니다. 기능 및 사용 예시는 [콘텐츠 컬렉션 안내서를 참조하세요](/ko/guides/content-collections/). + +## `astro:content`에서 가져오기 + +```js +import { + z, + defineCollection, + getCollection, + getEntry, + getEntries, + reference, + } from 'astro:content'; +``` +### `defineCollection()` + +

+ +**타입:** `(input: CollectionConfig) => CollectionConfig` +

+ +`defineCollection()`은 `src/content/config.*` 파일에 컬렉션을 구성하는 유틸리티입니다. + +```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(), + }), +}); + +// `collections` 내보내기를 통해 정의된 컬렉션을 Astro에 노출합니다. +export const collections = { blog }; +``` + +이 함수는 다음 속성을 허용합니다. + +#### `type` + +

+ +**타입:** `'content' | 'data'`
+**기본값:** `'content'`
+ +

+ +`type`은 컬렉션에 저장된 항목의 형식을 정의하는 문자열입니다. + +- `'content'` - Markdown (`.md`), MDX (`.mdx`), Markdoc (`.mdoc`)와 같은 콘텐츠 작성 형식 +- `'data'` - JSON (`.json`) 또는 YAML (`.yaml`)과 같은 데이터 전용 형식의 경우 + +:::tip +즉, 컬렉션은 콘텐츠와 데이터 형식을 혼합하여 저장할 수 **없습니다**. 이러한 항목을 유형별로 별도의 컬렉션으로 분할해야 합니다. +::: + +#### `schema` + +

+ +**타입:** ZodType | (context: SchemaContext) => ZodType +

+ +`schema`는 컬렉션에 대한 문서 프런트매터의 타입과 모양을 구성하는 선택적 Zod 객체입니다. 각 값은 [Zod 유효성 검사기](https://github.com/colinhacks/zod)를 사용해야 합니다. + +사용 예시는 [`콘텐츠 컬렉션` 안내서를 참조하세요](/ko/guides/content-collections/#컬렉션-스키마-정의). + +### `reference()` + +

+ +**타입:** `(collection: string) => ZodEffects`
+ +

+ +`reference()` 함수는 콘텐츠 구성에서 한 컬렉션에서 다른 컬렉션으로의 관계 또는 "reference"를 정의하는 데 사용됩니다. 이는 컬렉션 이름을 전달받고 콘텐츠 프런트매터 또는 데이터 파일에 지정된 항목 식별자의 유효성을 검사합니다. + +이 예시에서는 `authors` 컬렉션에 대한 블로그 작성자의 참조와 동일한 `blog` 컬렉션에 대한 관련 게시물 배열을 정의합니다. + +```ts +import { defineCollection, reference, z } from 'astro:content'; + +const blog = defineCollection({ + type: 'content', + schema: z.object({ + // `id`로 `authors` 컬렉션에서 단일 저자 참조 + author: reference('authors'), + // `slug`의 `blog` 컬렉션에서 관련 게시물 배열을 참조하세요. + relatedPosts: z.array(reference('blog')), + }) +}); + +const authors = defineCollection({ + type: 'data', + schema: z.object({ /* ... */ }) +}); + +export const collections = { blog, authors }; +``` + +사용 예시는 [`콘텐츠 컬렉션` 안내서를 참조하세요](/ko/guides/content-collections/#컬렉션-참조-정의하기). + +### `getCollection()` + +

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

+ +`getCollection()`은 컬렉션 이름별로 콘텐츠 컬렉션 항목 목록을 검색하는 함수입니다. + +기본적으로 컬렉션의 모든 항목을 반환하고 항목 속성별로 범위를 좁힐 수 있는 선택적 `filter` 함수를 허용합니다. 이를 통해 `data` 객체를 통해 `id`, `slug` 또는 프런트매터 값을 기반으로 컬렉션의 일부 항목만 쿼리할 수 있습니다. + +```astro +--- +import { getCollection } from 'astro:content'; + +// 모든 `src/content/blog/` 항목을 가져옵니다. +const allBlogPosts = await getCollection('blog'); + +// 프런트매터에 `draft: true`가 포함된 게시물만 반환합니다. +const draftBlogPosts = await getCollection('blog', ({ data }) => { + return data.draft === true; +}); +--- +``` + +사용 예시는 [`콘텐츠 컬렉션` 안내서를 참조하세요](/ko/guides/content-collections/#컬렉션-쿼리). + +### `getEntry()` + +

+ +**타입:** +- `(collection: string, contentSlugOrDataId: string) => CollectionEntry` +- `({ collection: string, id: string }) => CollectionEntry` +- `({ collection: string, slug: string }) => CollectionEntry` + +`getEntry()`는 컬렉션 이름과 항목 `id` (`type: 'data'` 컬렉션의 경우) 또는 항목 `slug` (`type: 'content'` 컬렉션의 경우)로 단일 컬렉션 항목을 검색하는 함수입니다. `getEntry()`는 `data`, `body`, `render()` 속성에 액세스하기 위해 참조된 항목을 가져오는 데에도 사용할 수 있습니다. + +```astro +--- +import { getEntry } from 'astro:content'; + +// `src/content/blog/enterprise.md` 가져오기 +const enterprisePost = await getEntry('blog', 'enterprise'); + +// `src/content/captains/picard.yaml` 가져오기 +const picardProfile = await getEntry('captains', 'picard'); + +// `data.captain`이 참조하는 프로필 가져오기 +const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); +--- +``` + +[컬렉션 항목 쿼리](/ko/guides/content-collections/#컬렉션-쿼리)의 예시는 `콘텐츠 컬렉션` 가이드를 참조하세요. + +### `getEntries()` + +

+ +**타입:** +- `(Array<{ collection: string, id: string }>) => CollectionEntry[]` +- `(Array<{ collection: string, slug: string }>) => CollectionEntry[]` + +`getEntries()`는 동일한 컬렉션에서 여러 컬렉션 항목을 검색하는 함수입니다. 이는 [참조된 항목의 배열을 반환](/ko/guides/content-collections/#컬렉션-참조-정의하기)하여 관련 `data`, `body`, `render()` 속성에 액세스하는 데 유용합니다. + +```astro +--- +import { getEntries } from 'astro:content'; + +const enterprisePost = await getEntry('blog', 'enterprise'); + +// `data.relatedPosts`에 의해 참조되는 관련 게시물 가져오기 +const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts); +--- +``` + +### `getEntryBySlug()` + +

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

+ +:::caution[사용되지 않음] +콘텐츠 항목을 쿼리하려면 [`getEntry()` 함수](#getentry)를 사용하세요. 이는 `getEntryBySlug()`와 동일한 인수를 허용하며 JSON 또는 YAML 컬렉션에 대해 `id`를 통한 쿼리를 지원합니다. +::: + +`getEntryBySlug()`는 컬렉션 이름과 항목 `slug`로 단일 컬렉션 항목을 검색하는 함수입니다. + +```astro +--- +import { getEntryBySlug } from 'astro:content'; + +const enterprise = await getEntryBySlug('blog', 'enterprise'); +--- +``` + +사용 예시는 [`콘텐츠 컬렉션` 가이드를 참조하세요](/ko/guides/content-collections/#컬렉션-쿼리). + +### `getDataEntryById()` + +

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

+ +:::caution[사용되지 않음] +데이터 항목을 쿼리하려면 [`getEntry()` 함수](#getentry)를 사용합니다. 이 함수는 `getDataEntryById()`와 동일한 인수를 전달받으며, Markdown과 같은 콘텐츠 작성 형식의 경우 `slug`로 쿼리할 수 있습니다. +::: + +`getDataEntryById()`는 컬렉션 이름과 항목 `id`로 단일 컬렉션 항목을 검색하는 함수입니다. + +```astro +--- +import { getDataEntryById } from 'astro:content'; + +const picardProfile = await getDataEntryById('captains', 'picard'); +--- +``` + +## `astro:content` 타입 + +```ts +import type { + CollectionEntry, + CollectionKey, + ContentCollectionKey, + DataCollectionKey, + SchemaContext, + } from 'astro:content'; +``` + +### `CollectionEntry` + +[`getCollection()`](#getcollection), [`getEntry()`](#getentry), [`getEntries()`](#getentries)를 포함한 쿼리 함수는 각각 `CollectionEntry` 타입의 항목을 반환합니다. 이 타입은 `astro:content`에서 유틸리티로 사용할 수 있습니다. + +```ts +import type { CollectionEntry } from 'astro:content'; +``` + +`CollectionEntry`는 제네릭 타입입니다. 이 타입을 쿼리하려는 컬렉션의 이름과 함께 사용하세요. +예를 들어, `blog` 컬렉션의 항목은 `CollectionEntry<'blog'>`와 같은 타입을 가질 것입니다. + +각 `CollectionEntry`는 다음 값을 가지는 객체입니다. + +#### `id` + +**사용 가능 대상:** `type: 'content'` 및 `type: 'data'` 컬렉션 +**타입 예시:** + - 콘텐츠 컬렉션: `'entry-1.md' | 'entry-2.md' | ...` + - 데이터 컬렉션: `'author-1' | 'author-2' | ...` + +`src/content/[collection]`에 상대적인 파일 경로를 사용하는 고유 ID입니다. 컬렉션 항목 파일 경로를 기반으로 가능한 모든 문자열 값을 열거합니다. [`type: 'content'`로 정의된](#type) 컬렉션은 ID에 파일 확장자를 포함하지만 `type: 'data'`로 정의된 컬렉션은 포함하지 않습니다. + +#### `collection` + +**사용 가능 대상:** `type: 'content'` 및 `type: 'data'` 컬렉션 +**타입 예시:** `'blog' | 'authors' | ...` + +항목이 위치한 `src/content/` 아래의 최상위 폴더 이름입니다. 이는 스키마 및 쿼리 함수에서 컬렉션을 참조하는 데 사용되는 이름입니다. + +#### `data` + +**사용 가능 대상:** `type: 'content'` 및 `type: 'data'` 컬렉션 +**타입:** `CollectionSchema` + +컬렉션 스키마에서 추론된 프런트매터 속성의 객체입니다 ([`defineCollection()` 참조를 확인하세요](#definecollection)). 스키마가 구성되지 않은 경우 기본값은 `any`입니다. + +#### `slug` + +**사용 가능 대상:** `type: 'content'` 컬렉션 전용 +**타입 예시:** `'entry-1' | 'entry-2' | ...` + +Markdown 또는 MDX 문서용 URL 지원 슬러그입니다. 파일 확장자가 없는 `id`가 기본값이지만 파일의 프런트매터에서 [`slug` 속성](/ko/guides/content-collections/#사용자-정의-슬러그-정의)을 설정하여 재정의할 수 있습니다. + +#### `body` + +**사용 가능 대상:** `type: 'content'` 컬렉션 전용 +**타입:** `string` + +Markdown 또는 MDX 문서의 컴파일되지 않은 원시 본문을 포함하는 문자열입니다. + +#### `render()` + +**사용 가능 대상:** `type: 'content'` 컬렉션 전용 +**타입:** `() => Promise` + +렌더링을 위해 지정된 Markdown 또는 MDX 문서를 컴파일하는 함수입니다. 이 함수는 다음 속성을 반환합니다. + +- `` - Astro 파일에서 문서의 내용을 렌더링하는 데 사용되는 컴포넌트입니다. +- `headings` - Markdown 및 MDX 가져오기에 대해 생성된 제목 목록, [Astro의 `getHeadings()` 유틸리티 미러링](/ko/guides/markdown-content/#사용-가능한-속성). +- `remarkPluginFrontmatter ` - [remark 또는 rehype 플러그인이 적용된 후](/ko/guides/markdown-content/#프로그래밍-방식으로-프런트매터-수정하기) 수정된 frontmatter 객체. `any` 타입으로 설정됩니다. + +```astro +--- +import { getEntryBySlug } from 'astro:content'; +const entry = await getEntryBySlug('blog', 'entry-1'); + +const { Content, headings, remarkPluginFrontmatter } = await entry.render(); +--- +``` + +사용 예시는 [`콘텐츠 컬렉션` 가이드를 참조하세요](/ko/guides/content-collections/#콘텐츠를-html로-렌더링). + +### `CollectionKey` + +

+ +`src/content/config.*` 파일에 정의된 모든 컬렉션 이름의 문자열 유니언 타입입니다. 이 타입은 모든 컬렉션 이름을 허용하는 일반 함수를 정의할 때 유용할 수 있습니다. + +```ts +import { type CollectionKey, getCollection } from 'astro:content'; + +async function getCollection(collection: CollectionKey) { + return getCollection(collection); +} +``` + +### `ContentCollectionKey` + +

+ +`src/content/config.*` 파일에 정의된 `type: 'content'` 컬렉션의 모든 이름에 대한 문자열 유니언 타입입니다. + +### `DataCollectionKey` + +

+ +`src/content/config.*` 파일에 정의된 `type: 'data'` 컬렉션의 모든 이름에 대한 문자열 유니언 타입입니다. + +### `SchemaContext` + +`defineCollection`이 `schema`의 함수 모양을 위해 사용하는 `context` 객체입니다. 이 타입은 여러 컬렉션에 대해 재사용 가능한 스키마를 구축할 때 유용할 수 있습니다. + +여기에는 다음 속성이 포함됩니다. + +- `image` - [콘텐츠 컬렉션에서 로컬 이미지를 사용](/ko/guides/images/#콘텐츠-컬렉션의-이미지)할 수 있게 해주는 `image()` 스키마 도우미 + +```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 }) + }), +}); +``` From 533ff335219f9a69500f2934acde1cdffd1c1541 Mon Sep 17 00:00:00 2001 From: Junseong Park Date: Sat, 26 Oct 2024 22:09:53 +0900 Subject: [PATCH 06/43] i18n(ko-KR): update `actions.mdx` (#9803) Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- src/content/docs/ko/guides/actions.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/ko/guides/actions.mdx b/src/content/docs/ko/guides/actions.mdx index 9b7bf14b3fa71..cf5b101fc05a1 100644 --- a/src/content/docs/ko/guides/actions.mdx +++ b/src/content/docs/ko/guides/actions.mdx @@ -16,7 +16,7 @@ Astro 액션을 사용하면 타입 안전성을 갖춘 백엔드 함수를 정 - [Zod 유효성 검사](https://zod.dev/?id=primitives)를 사용하여 JSON 및 양식 데이터 입력의 유효성을 자동으로 검사하세요. - 클라이언트는 물론 [HTML 양식 액션에서도](#html-양식-액션에서-액션-호출) 백엔드를 호출할 수 있는 타입이 안전한 함수를 생성하세요. 수동 `fetch()` 호출이 필요 없습니다. -- [`ActionError`](/ko/reference/api-reference/#actionerror) 객체로 백엔드 오류를 표준화하세요. +- [`ActionError`](/ko/reference/modules/astro-actions/#actionerror) 객체로 백엔드 오류를 표준화하세요. ## 기본 사용법 @@ -129,7 +129,7 @@ async () => { -[`defineAction()`](/ko/reference/api-reference/#defineaction) 및 해당 속성에 대한 자세한 내용은 전체 액션 API 설명서를 참조하세요. +[`defineAction()`](/ko/reference/modules/astro-actions/#defineaction) 및 해당 속성에 대한 자세한 내용은 전체 액션 API 설명서를 참조하세요. ## 액션 조직화 @@ -340,7 +340,7 @@ export const server = { } ``` - 사용 가능한 모든 양식 유효성 검사기는 [`input` API 참조](/ko/reference/api-reference/#input-유효성-검사기)를 확인하세요. + 사용 가능한 모든 양식 유효성 검사기는 [`input` API 참조](/ko/reference/modules/astro-actions/#input-유효성-검사기)를 확인하세요. 3. HTML 양식에 ` +``` + +### `navigate()` + +

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

+ +一个使用视图过渡 API 导航到给定 `href` 的函数。 + +此函数签名基于 [浏览器 Navigation API 中的 `navigate` 函数](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate)。虽然基于 Navigation API,但此函数是在 [History API](https://developer.mozilla.org/zh-CN/docs/Web/API/History_API) 之上实现的,以允许在不重新加载页面的情况下进行导航。 + +#### `history` 选项 + +

+ +**类型:**`'auto' | 'push' | 'replace'`
+**默认值:**`'auto'`
+ +

+ +定义了如何将此导航添加到浏览器历史记录中。 + +- `'push'`:路由将使用 `history.pushState` 在浏览器历史记录中创建一个新条目。 +- `'replace'`:路由将使用 `history.replaceState` 更新 URL,而不会在导航中添加新条目。 +- `'auto'`(默认):路由将尝试 `history.pushState`,但如果无法进行过渡,则当前 URL 将保持不变,浏览器历史记录不会发生变化。 + +此选项遵循浏览器 Navigation API 中的 [`history` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history),但简化了在 Astro 项目中可能发生的情况。 + +#### `formData` 选项 + +

+ +**类型:**`FormData`
+ +

+ +一个 `FormData` 对象,用于 `POST` 请求。 + +当提供此选项时,导航目标页面的请求将以 `POST` 请求的形式发送,内容为表单数据对象。 + +当提交一个带有视图过渡的 HTML 表单时,将使用此方法代替默认的页面重新加载导航。调用此方法允许以编程方式触发相同的行为。 + +#### `info` 选项 + +

+ +**类型:**`any`
+ +

+ +与导航相关的 `astro:before-preparation` 和 `astro:before-swap` 事件中包含的任意数据。 + +此选项模仿了浏览器 Navigation API 中的 [`info` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info)。 + +#### `state` 选项 + +

+ +**类型:**`any`
+ +

+ +与导航相关的 `NavitationHistoryEntry` 对象中关联的任意数据。此数据可以通过 [`history.getState` 函数](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState) 从 History API 中检索。 + +此选项模仿了浏览器 Navigation API 中的 [`state` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state)。 + +#### `sourceElement` 选项 + +

+ +**类型:**`Element`
+ +

+ +此导航的触发元素,如果有的话。此元素将在以下事件中可用: +- `astro:before-preparation` +- `astro:before-swap` + +### `supportsViewTransitions` + +

+ +**类型:**`boolean`
+ +

+ +当前浏览器是否支持并启用视图过渡。 + +### `transitionEnabledOnThisPage` + +

+ +**类型:**`boolean`
+ +

+ +当前页面是否启用了视图过渡以进行客户端导航。这可以用于使组件在视图过渡页面上的行为有所不同。 + +### `getFallback` + +

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

+ +返回在浏览器不支持视图过渡时使用的回退策略。 + +有关如何选择和配置回退行为的详细信息,请参阅 [回退控制](/zh-cn/guides/view-transitions/#回退控制) 指南。 + +### `swapFunctions` + +

+ + +

+ +一个对象,其中包含了用于构建 Astro 默认交换函数的工具类函数。 +这些函数在 [构建自定义交换函数](/zh-cn/guides/view-transitions/#构建自定义交换函数) 时非常有用。 + +`swapFunctions` 提供了以下方法: + +#### `deselectScripts()` + +

+ +**类型:** `(newDocument: Document) => void` +

+ +标记在新的 document 中不应执行的脚本。这些脚本已经在当前 document 中,并且没有使用 [`data-astro-rerun`](/zh-cn/guides/view-transitions/#data-astro-rerun) 标记为重新执行。 + +#### `swapRootAttributes()` + +

+ +**类型:**`(newDocument: Document) => void` +

+ +在 document 根节点之间交换属性,如 `lang` 属性。这也包括 Astro 注入的内部属性,如 `data-astro-transition`,这使得过渡方向可用于 Astro 生成的 CSS 规则。 + +在构建自定义交换函数时,重要的是调用此函数,以避免破坏视图过渡的动画。 + +#### `swapHeadElements()` + +

+ +**类型:**`(newDocument: Document) => void` +

+ +从当前 document 的 `` 中删除所有未持久化到新 document 的元素。然后将新 document 的 `` 中的所有新元素附加到当前 document 的 ``。 + +#### `saveFocus()` + +

+ +**类型:**`() => () => void` +

+ +在当前页面上存储聚焦的元素,并返回一个函数,当调用时,如果聚焦的元素被持久化,则将焦点返回给该元素。 + +#### `swapBodyElement()` + +

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

+ +用新 document 的 body 替换旧的 body。然后,遍历旧 body 中应持久化的每个元素,并在新 body 中找到匹配的元素,将旧元素交换回原位。 + +## 生命周期事件 + +### `astro:before-preparation` 事件 + +在视图过渡中导航开始时触发的事件。此事件发生在任何请求之前,并且不会更改任何浏览器状态。 + +此事件具有以下属性: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`formData`](#formdata) +- [`loader()`](#loader) + +有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astrobefore-preparation)。 + +### `astro:after-preparation` 事件 + +使用视图过渡加载导航中的下一个页面后触发的事件。 + +此事件没有属性。 + +有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astroafter-preparation)。 + +### `astro:before-swap` 事件 + +在视图过渡中导航的下一个页面解析、准备并链接到 document 后,但在任何内容在 document 之间交换之前触发的事件。 + +此事件不能取消。调用 `preventDefault()` 是无效的。 + +此事件具有以下属性: +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`viewTransition`](#viewtransition) +- [`swap`](#swap) + +有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astrobefore-swap)。 + +### `astro:after-swap` 事件 + +在视图过渡中导航的下一个页面内容交换后,但在视图过渡结束之前触发的事件。 + +在触发此事件时,历史记录条目和滚动位置已经更新。 + +### `astro:page-load` 事件 + +在页面完成加载后触发的事件,无论是通过视图过渡导航还是浏览器原生导航。 + +当视图过渡在页面上启用时,通常在 `DOMContentLoaded` 上执行的代码应更改为在此事件上执行。 + +### 生命周期事件属性 + +

+ +#### `info` + +

+ +**类型:**`URL` +

+ +在导航期间定义的任意数据。 + +这是在 [`navigate()` 函数](#navigate) 的 [`info` 选项](#info-选项) 中传递的文字值。 + +#### `sourceElement` + +

+ +**类型:**`Element | undefined` +

+ +触发导航的元素。例如,这可以是点击的 `` 元素。 + +当使用 [`navigate()` 函数](#navigate) 时,这将是调用中指定的元素。 + +#### `newDocument` + +

+ +**类型:**`Document` +

+ +导航中下一个页面的 document。此 document 的内容将替换当前 document 的内容。 + +#### `navigationType` + +

+ +**类型:**`'push' | 'replace' | 'traverse'` +

+ +正在发生的导航类型。 +- `push`: 正在为新页面创建一个新的 `NavigationHistoryEntry`。 +- `replace`: 当前的 `NavigationHistoryEntry` 正在被新页面的条目替换。 +- `traverse`: 没有创建 `NavigationHistoryEntry`。历史记录中的位置正在改变。 + 遍历的方向由 [`direction` 属性](#direction) 给出 + +#### `direction` + +

+ +**类型:**`Direction` +

+ +过渡的方向。 +- `forward`: 在历史记录中导航到下一个页面或新页面。 +- `back`: 在历史记录中导航到前一个页面。 +- 其他监听器可能设置的任何其他内容。 + +#### `from` + +

+ +**类型:**`URL` +

+ +正在导航的页面的 URL。 + +#### `to` + +

+ +**类型:**`URL` +

+ +正在导航的页面的 URL。此属性可以修改,在生命周期结束时使用的值将是下一个页面的 `NavigationHistoryEntry` 的值。 + +#### `formData` + +

+ +**类型:**`FormData | undefined` +

+ +一个用于 `POST` 请求的 `FormData` 对象。 + +当此属性设置时,将使用给定的表单数据对象作为内容发送 `POST` 请求到 [`to` URL](#to),而不是正常的 `GET` 请求。 + +当提交一个带有视图过渡的 HTML 表单时,此字段会自动设置为表单中的数据。当使用 [`navigate()` 函数](#navigate) 时,此值与给定的选项相同。 + +#### `loader` + +

+ +**类型:**`() => Promise` +

+ +在导航过程中下个阶段的实现(加载下一个页面)。此实现可以覆盖以添加额外的行为。 + +#### `viewTransition` + +

+ +**类型:**[`ViewTransition`](https://developer.mozilla.org/zh-CN/docs/Web/API/ViewTransition) +

+ +在导航过程中使用的视图过渡对象。在浏览器不支持 [视图过渡 API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) 的情况下,这是一个对象,实现了相同的 API 以方便使用,但没有 DOM 集成。 + +#### `swap` + +

+ +**类型:**`() => void` +

+ +document 交换逻辑的实现。 + +有关如何构建自定义交换函数的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#构建自定义交换函数). + +默认情况下,此实现将按顺序调用以下函数: + +1. [`deselectScripts()`](#deselectscripts) +2. [`swapRootAttributes()`](#swaprootattributes) +3. [`swapHeadElements()`](#swapheadelements) +4. [`saveFocus()`](#savefocus) +5. [`swapBodyElement()`](#swapbodyelement) From ac61ebe58b6a5b1c6d935de5985f0989e1a4e9b3 Mon Sep 17 00:00:00 2001 From: Nin3 <30520689+Nin3lee@users.noreply.github.com> Date: Mon, 28 Oct 2024 16:14:51 +0800 Subject: [PATCH 27/43] i18n(zh-cn): Update `api-reference.mdx` (#9849) Co-authored-by: liruifengv --- .../docs/zh-cn/reference/api-reference.mdx | 1283 +---------------- 1 file changed, 5 insertions(+), 1278 deletions(-) diff --git a/src/content/docs/zh-cn/reference/api-reference.mdx b/src/content/docs/zh-cn/reference/api-reference.mdx index c356917a685bc..2c0cc9417d4ec 100644 --- a/src/content/docs/zh-cn/reference/api-reference.mdx +++ b/src/content/docs/zh-cn/reference/api-reference.mdx @@ -1,5 +1,9 @@ --- -title: API 参考 +title: Astro 运行时 API +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 4 --- import Since from '~/components/Since.astro'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' @@ -1390,1280 +1394,3 @@ export default function () { return import.meta.env.SSR ?
: ; } ``` - -## 图像(`astro:assets`) - -### `getImage()` - -

- -**类型:**`(options: UnresolvedImageTransform) => Promise` -

- -:::caution -`getImage()` 依赖于仅在服务器上可用的 API,当在客户端使用时会导致构建失败。 -::: - -`getImage()`函数旨在生成用于在 HTML 之外的其他地方所使用的图像,例如在 [API 路由](/zh-cn/guides/endpoints/#服务器端点api-路由) 中。它还允许你创建自定义的 `` 组件。 - -`getImage()` 函数接受一个选项对象,其中包含与 [Image 组件相同的属性](/zh-cn/reference/components-reference/#属性)(除了 `alt`)。 - -```astro ---- -import { getImage } from "astro:assets"; -import myBackground from "../background.png" -const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) ---- -
-``` - -它返回了一个具有以下类型的对象: - -```js -type GetImageResult = { - /* 渲染图像所需的附加 HTML 属性(宽度、高度、样式等) */ - attributes: Record; - /* 已通过校验的参数 */ - options: ImageTransform; - /* 传递的原始参数 */ - rawOptions: ImageTransform; - /* 生成图像的路径 */ - src: string; - srcSet: { - /* 为 srcset 生成值,每个条目都有一个 url 和一个 size */ - values: SrcSetValue[]; - /* 准备在`srcset`属性中使用的值 */ - attribute: string; - }; -} -``` - -## 内容集合(`astro:content`) - -

- -内容集合提供了 API 来配置和查询 `src/content/` 中的 Markdown 或 MDX 文档。有关功能和用法示例,请参考[内容集合指南](/zh-cn/guides/content-collections/)。 - -### `defineCollection()` - -

- -**类型:**`(input: CollectionConfig) => CollectionConfig` -

- -`defineCollection()` 是一个用于在 `src/content/config.*` 文件中配置集合的工具函数。 - -```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(), - }), -}); - -// 将定义的集合公开给 Astro -// 通过 `collections` 导出 -export const collections = { blog }; -``` - -这个函数接受以下属性: -#### `type` - -

- -**类型:**`'content' | 'data'`
-**默认:**`'content'`
- -

- -`type` 是一个字符串,用于定义存储在集合中的条目的类型: - -- `'content'` - 用于内容创作格式,如 Markdown (`.md`)、MDX (`.mdx`) 或 Markdoc (`.mdoc`) -- `'data'` - 用于 JSON (`.json`) 或 YAML (`.yaml`) 等纯数据格式 - -:::tip -这意味着集合**不能**存储内容和数据格式的混合。你必须按类型将这些条目分割成单独的集合。 -::: - -#### `schema` - -**类型:**ZodType | (context:
SchemaContext) => ZodType - -`schema` 是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 [Zod 验证器](https://github.com/colinhacks/zod) - -有关示例请[参考 `内容集合`指南](/zh-cn/guides/content-collections/#定义集合模式) - -### `reference()` - -

- -**类型:**`(collection: string) => ZodEffects`
- -

- -在内容配置中使用 `reference()` 函数来定义从一个集合到另一个集合的关系或 "引用"。该函数接受一个集合名称,并验证内容前置事项或数据文件中指定的条目标识符。 - -此示例定义了从博客作者到 "作者 "集合的引用,以及到同一 "博客 "集合的相关文章数组的引用: - -```ts -import { defineCollection, reference, z } from 'astro:content'; - -const blog = defineCollection({ - type: 'content', - schema: z.object({ - // 通过 "id "从 "作者 "集合中引用单个作者 - author: reference('authors'), - // 按 "slug "从 "blog "集合中引用相关帖子数组 - relatedPosts: z.array(reference('blog')), - }) -}); - -const authors = defineCollection({ - type: 'data', - schema: z.object({ /* ... */ }) -}); - -export const collections = { blog, authors }; -``` - -有关示例请[参考 `内容集合`指南](/zh-cn/guides/content-collections/#定义集合引用). - -### `getCollection()` - -

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

- -`getCollection()` 是一个函数,用于通过集合名称检索内容集合条目列表。 - -默认情况下,它返回集合中的所有项目,并接受可选的 `filter` 函数来缩小条目属性。这允许你根据 `id`、`slug` 或 frontmatter 值(通过 `data` 对象)查询集合中的某些项目。 - -```astro ---- -import { getCollection } from 'astro:content'; - -// 获取 `src/content/blog/` 中的所有条目 -const allBlogPosts = await getCollection('blog'); - -// 仅返回 frontmatter 中 `draft: true` 的条目 -const draftBlogPosts = await getCollection('blog', ({ data }) => { - return data.draft === true; -}); ---- -``` - -有关示例请[参考 `内容集合`指南](/zh-cn/guides/content-collections/#查询集合) 以获取示例用法。 - -### `getEntry()` - -

- -**类型:** - -- `(collection: string, contentSlugOrDataId: string) => CollectionEntry` -- `({ collection: string, id: string }) => CollectionEntry` -- `({ collection: string, slug: string }) => CollectionEntry` - -`getEntry()` 是一个函数,可通过集合名称和条目 `id` (对于 `type: 'data'` 集合)或条目 `slug` (对于 `type: 'content'` 集合)检索单个集合条目。`getEntry()`也可用于获取引用条目,以访问`data`、`body`或`render()`属性: - -```astro ---- -import { getEntry } from 'astro:content'; - -// 得到 `src/content/blog/enterprise.md` -const enterprisePost = await getEntry('blog', 'enterprise'); - -// 得到 `src/content/captains/picard.yaml` -const picardProfile = await getEntry('captains', 'picard'); - -// 得到 the profile referenced by `data.captain` -const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); ---- -``` - -有关`内容集合`的示例,请参考 [查询集合条目](/zh-cn/guides/content-collections/#查询集合). - -### `getEntries()` - -

- -**类型:** - -- `(Array<{ collection: string, id: string }>) => CollectionEntry[]` -- `(Array<{ collection: string, slug: string }>) => CollectionEntry[]` - -`getEntries()` 是一个从同一集合中检索多个集合条目的函数。这对于[返回引用条目的数组](/zh-cn/guides/content-collections/#定义集合引用)访问其关联的`data`、`body`和`render()`属性非常有用。 - -```astro ---- -import { getEntries } from 'astro:content'; - -const enterprisePost = await getEntry('blog', 'enterprise'); - -// 获取由 `data.relatedPosts` 引用的相关帖子 -const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts); ---- -``` - -### `getEntryBySlug()` - -

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

- -:::caution[已废弃] -使用 [`getEntry()`函数](#getentry) 查询内容条目。该函数接受与 `getEntryBySlug()` 相同的参数,并支持通过 `id` 查询 JSON 或 YAML 集合。 -::: - -`getEntryBySlug()` 是一个函数,用于通过集合名称和条目 `slug` 检索单个集合条目。 - -```astro ---- -import { getEntryBySlug } from 'astro:content'; - -const enterprise = await getEntryBySlug('blog', 'enterprise'); ---- -``` -有关示例请[参考 `内容集合`指南](/zh-cn/guides/content-collections/#查询集合) 以获取示例用法。 - -### `getDataEntryById()` - -

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

- -:::caution[已废弃] -使用 [`getEntry()`函数](#getentry) 查询数据条目。该函数接受与 `getDataEntryById()` 相同的参数,并支持通过 `slug` 查询 Markdown 等内容创作格式的条目。 -::: - -`getDataEntryById()` 是一个用于通过集合名称和条目 `id` 检索单个集合条目的函数。 - -```astro ---- -import { getDataEntryById } from 'astro:content'; -const picardProfile = await getDataEntryById('captains', 'picard'); ---- -``` - -### 集合条目类型 - -[`getCollection()`](#getcollection)和 [`getEntryBySlug()`](#getentrybyslug) 函数都会返回 `CollectionEntry` 类型的条目。这个类型可以从 `astro:content` 中获取: - -```ts -import type { CollectionEntry } from 'astro:content'; -``` - -`CollectionEntry` 类型是一个对象,具有以下值。 `TCollectionName` 是你正在查询的集合的名称(例如 `CollectionEntry<'blog'>`)。 - -#### `id` - -**适用于:** `type: 'content'` and `type: 'data'` 集合 - -**示例类型:** - - 内容集合: `'entry-1.md' | 'entry-2.md' | ...` - - 数据集合: `'author-1' | 'author-2' | ...` - -一个使用相对于 `src/content/[collection]` 的文件路径的唯一 ID。根据集合条目文件路径枚举所有可能的字符串值。请注意,[`类型: 'content'`](#type) 的集合在其 ID 中包含文件扩展名,而定义为 `type: 'data'` 的集合则不包含。 - -#### `collection` - -**适用于:** `type: 'content'` and `type: 'data'` 集合 - -**示例类型:** `'blog' | 'authors' | ...` - -`src/content/` 下顶级文件夹的名称,条目位于该文件夹中。该名称用于在模式和查询函数中引用集合。 - - -#### `data` -**适用于:** `type: 'content'` and `type: 'data'` 集合 - -**类型:**`CollectionSchema` - -一个从集合模式推断出的 frontmatter 属性对象([参考 `defineCollection()`](#definecollection))。如果没有配置模式,则默认为 `any`。 - -#### `slug` - -**适用于:** 仅仅 `type: 'content'` 集合 - -**示例类型:** `'entry-1' | 'entry-2' | ...` - -可用于 Markdown 或 MDX 文档的 URL 标头。默认为不含文件扩展名的 "id",但可以通过在文件的 frontmatter 中设置[`slug`属性](/zh-cn/guides/content-collections/#定义自定义-slugs)来覆盖。 - -#### `body` -**适用于:** 仅 `type: 'content'` 集合 - -**类型:**`string` - -一个包含 Markdown 或 MDX 文档原始未编译的 body 的字符串。 - -#### `render()` - -**适用于:** 仅 `type: 'content'` 集合 - -**类型:**`() => Promise` - -一个用于编译给定的 Markdown 或 MDX 文档以进行渲染的函数。它返回以下属性: - -- `` - 用于在 Astro 文件中渲染文档内容的组件。 -- `headings` - 生成的标题列表,[与 Astro 的 `getHeadings()` 工具函数相同](/zh-cn/guides/markdown-content/#可用属性) 在 Markdown 和 MDX 导入中。 -- `remarkPluginFrontmatter ` - 在应用 [remark 或 rehype 插件](/zh-cn/guides/markdown-content/#以编程方式修改-frontmatter)后修改后的 frontmatter 对象。设置为类型 `any`。 - -```astro ---- -import { getEntryBySlug } from 'astro:content'; -const entry = await getEntryBySlug('blog', 'entry-1'); - -const { Content, headings, remarkPluginFrontmatter } = await entry.render(); ---- -``` - -有关示例请[参考 `内容集合`指南](/zh-cn/guides/content-collections/#将内容渲染成-html) 以获取示例用法。 - -### 其他内容集合类型 - -`astro:content` 模块也导出了以下类型,供你在 Astro 项目中使用: - -#### `CollectionKey` - -

- -这是一个在 `src/content/config.*` 文件中定义的所有集合名称的字符串联合类型。当定义一个可以接受任何集合名称的通用函数时,这个类型很有用。 - -```ts -import type { CollectionKey, getCollection } from 'astro:content'; - -async function getCollection(collection: CollectionKey) { - return getCollection(collection); -} -``` - -#### `ContentCollectionKey` - -

- -一个在 `src/content/config.*` 文件中定义的所有 `type: 'content'` 集合名称的字符串联合类型。 - -#### `DataCollectionKey` - -

- -一个在 `src/content/config.*` 文件中定义的所有 `type: 'data'` 集合名称的字符串联合类型。 - -#### `SchemaContext` - -即 `defineCollection` 在 `schema` 函数形状中所使用的 `context` 对象。当为多个集合构建可重用的模式时,这个类型很有用。 - -它包括了以下属性: - -- `image()` 模式辅助工具允许你 [在内容集合中使用本地图片](/zh-cn/guides/images/#内容集合中的图像)。 - -```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 }) - }), -}); -``` - -## 中间件(`astro:middleware`) - -

- -中间件使你能拦截请求和响应,并在每次渲染页面或端点时动态注入行为。有关功能和用法示例,请参考[中间件指南](/zh-cn/guides/middleware/)。 - -### `onRequest()` - -

- -**类型:**`(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` -

- -一个在 `src/middleware.js` 里的必须导出的函数,它将在每次渲染页面或端点时被调用。它接受两个参数:[context](#context) 和 [next()](#next)。`onRequest()` 必须返回一个 `Response`:要么直接返回,要么通过调用 `next()` 返回。 - - ```js title="src/middleware.js" - export function onRequest (context, next) { - // 拦截一个请求的响应数据 - // 可选修改响应 - // 直接返回一个 Response 对象,或者调用 `next()` 的结果 - return next(); - }; - ``` - -#### `context` - -

- -**类型:**`APIContext` -

- -`onRequest()` 的第一个参数是一个上下文对象。它反映了许多 `Astro` 全局属性。 - -有关更多信息,请参阅 [端点上下文](#端点上下文)。 - -#### `next()` - -

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

- -`onRequest()` 的第二个参数是一个调用链中的所有后续中间件,并返回一个 `Response` 的函数。例如,其他中间件可以修改响应的 HTML 主体,等待 `next()` 的结果将允许你的中间件响应这些更改。 - -自从 Astro v4.13.0,`next()` 接受一个可选的 URL 路径参数,形式为字符串、`URL` 或 `Request`,用于[重写](/zh-cn/guides/routing/#重写)当前请求而不重新触发新的渲染阶段。 - -### `sequence()` - -

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

- -一个接受中间件函数作为参数的函数,它将按照它们传递的顺序执行它们。 - -```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()` - -

- -**类型:**`(context: CreateContext) => APIContext`
- -

- -一个底层 API,用于创建一个 [`APIContext`](#端点上下文) 以传递给 Astro 中间件的 `onRequest()` 函数。 - -此函数可以由集成/适配器用于执行 Astro 中间件。 - -### `trySerializeLocals()` - -

- -**类型:**`(value: unknown) => string`
- -

- -一个底层 API,它接受任何值并尝试返回它的序列化版本(一个字符串)。如果该值无法序列化,该函数将抛出一个运行时错误。 - -## 国际化(`astro:i18n`) - -

- -此模块提供了一些函数,帮助你使用项目配置的语言环境设置创建 URL。 - -使用 i18n 路由为你的项目创建路由将依赖于你设置的某些配置值,这些值会影响你的页面路由。使用这些函数创建路由时,请确保考虑到你的个人设置,包括: - -- [`base`](/zh-cn/reference/configuration-reference/#base) -- [`trailingSlash`](/zh-cn/reference/configuration-reference/#trailingslash) -- [`build.format`](/zh-cn/reference/configuration-reference/#buildformat) -- [`site`](/zh-cn/reference/configuration-reference/#site) - -另外,请注意,这些函数为你的 `defaultLocale` 创建的返回 URL 将反映你的 `i18n.routing` 配置。 - -有关功能和使用示例,请参阅[我们的 i18n 路由指南](/zh-cn/guides/internationalization/)。 - -### `getRelativeLocaleUrl()` - -

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

- -`getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string` - -使用此函数来检索一个语言环境的相对路径。如果该语言环境不存在,Astro 会抛出一个错误。 - -```astro ---- -getRelativeLocaleUrl("fr"); -// 返回 /fr -getRelativeLocaleUrl("fr", ""); -// 返回 /fr -getRelativeLocaleUrl("fr", "getting-started"); -// 返回 /fr/getting-started -getRelativeLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog" -}); -// 返回 /blog/fr-ca/getting-started -getRelativeLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog", - normalizeLocale: false -}); -// 返回 /blog/fr_CA/getting-started ---- -``` - -### `getAbsoluteLocaleUrl()` - -

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

- -当 [`site`] 配置了值时,使用这个函数来检索一个语言环境的绝对路径。如果 [`site`] 没有被配置,该函数将返回一个相对 URL。如果语言环境不存在,Astro 会抛出一个错误。 - - -```astro title="src/pages/index.astro" ---- -// 如果 `site` 被设置为 `https://example.com` -getAbsoluteLocaleUrl("fr"); -// 返回 https://example.com/fr -getAbsoluteLocaleUrl("fr", ""); -// 返回 https://example.com/fr -getAbsoluteLocaleUrl("fr", "getting-started"); -// 返回 https://example.com/fr/getting-started -getAbsoluteLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog" -}); -// 返回 https://example.com/blog/fr-ca/getting-started -getAbsoluteLocaleUrl("fr_CA", "getting-started", { - prependWith: "blog", - normalizeLocale: false -}); -// 返回 https://example.com/blog/fr_CA/getting-started ---- -``` - -### `getRelativeLocaleUrlList()` - -

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

- -像使用 [`getRelativeLocaleUrl`](#getrelativelocaleurl) 那样使用此函数,返回所有语言环境的相对路径列表。 - -### `getAbsoluteLocaleUrlList()` - -

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

- -像使用 [`getAbsoluteLocaleUrl`](/zh-cn/guides/internationalization/#自定义语言环境路径) 那样使用此函数,返回所有语言环境的绝对路径列表。 - -### `getPathByLocale()` - -

- -**类型:**`(locale: string) => string` -

- -当配置了[自定义语言环境路径](/zh-cn/guides/internationalization/#自定义语言环境路径)时,此函数返回与一个或多个 `codes` 关联的 `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" ---- -getPathByLocale("fr"); // 返回 "french" -getPathByLocale("fr-CA"); // 返回 "french" ---- -``` - -### `getLocaleByPath()` - -

- -**类型:**`(path: string) => string` -

- -此函数返回与语言环境 `path` 关联的 `code`。 - -```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"); // 返回 "fr",因为这是首个配置的代码 ---- -``` - -### `redirectToDefaultLocale()` - -

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

- -:::note -仅当 `i18n.routing` 设置为 `"manual"` 时可用。 -::: - -此函数返回一个 `Response`,将重定向到配置的 `defaultLocale`。它接受一个可选的有效重定向状态码。 - -```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()` - -

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

- -:::note -仅当 `i18n.routing` 设置为 `"manual"` 时可用。 -::: - -此函数允许你在自己的中间件中使用你的 [`i18n.fallback` 配置](/zh-cn/reference/configuration-reference/#i18nfallback)。 - -```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()` - -

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

- -:::note -仅当 `i18n.routing` 设置为 `"manual"` 时可用。 -::: - -当以下情况发生时,在你的路由中间件中使用此函数来返回一个 404 错误: -- 当前路径不是根路径。例如:`/` 或 `/` -- URL 中不包含语言环境代码 - -当传递了一个 `Response`,由此函数发出的新 `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()` - -

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

- -:::note -仅当 `i18n.routing` 设置为 `"manual"` 时可用。 -::: - -此函数允许你以编程方式创建 Astro i18n 中间件。 - -当你仍然想要使用默认的 i18n 逻辑,但只在你的网站添加少数例外时,这个功能非常有用。 - -```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(); - // 在这里解析响应后的自定义逻辑。 - // 可以捕获来自 Astro i18n 中间件的响应。 - - return response; -}); - -export const onRequest = sequence(customLogic, middleware({ - prefixDefaultLocale: true, - redirectToDefaultLocale: false -})) -``` - -### `requestHasLocale()` - -

- -**类型:**`(context: APIContext) => boolean`
- -

- -:::note -仅当 `i18n.routing` 设置为 `"manual"` 时可用。 -::: - -检查当前 URL 是否包含已配置的语言环境代码。在内部,此函数将使用 `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 }); -}) -``` - -## 视图过渡客户端 API (`astro:transitions/client`) - -

- -此模块提供了一些函数,用于控制和与视图过渡 API 和客户端路由进行交互。 - -对于功能和使用示例,[请参阅我们的视图过渡指南](/zh-cn/guides/view-transitions/)。 - -### `navigate()` - -

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

- -一个使用视图过渡 API 导航到给定 `href` 的函数。 - -此函数签名基于 [浏览器 Navigation API 中的 `navigate` 函数](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate)。虽然基于 Navigation API,但此函数是在 [History API](https://developer.mozilla.org/zh-CN/docs/Web/API/History_API) 之上实现的,以允许在不重新加载页面的情况下进行导航。 - -#### `history` 选项 - -

- -**类型:**`'auto' | 'push' | 'replace'`
-**默认值:**`'auto'`
- -

- -定义了如何将此导航添加到浏览器历史记录中。 - -- `'push'`:路由将使用 `history.pushState` 在浏览器历史记录中创建一个新条目。 -- `'replace'`:路由将使用 `history.replaceState` 更新 URL,而不会在导航中添加新条目。 -- `'auto'`(默认):路由将尝试 `history.pushState`,但如果无法进行过渡,则当前 URL 将保持不变,浏览器历史记录不会发生变化。 - -此选项遵循浏览器 Navigation API 中的 [`history` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history),但简化了在 Astro 项目中可能发生的情况。 - -#### `formData` 选项 - -

- -**类型:**`FormData`
- -

- -一个 `FormData` 对象,用于 `POST` 请求。 - -当提供此选项时,导航目标页面的请求将以 `POST` 请求的形式发送,内容为表单数据对象。 - -当提交一个带有视图过渡的 HTML 表单时,将使用此方法代替默认的页面重新加载导航。调用此方法允许以编程方式触发相同的行为。 - -#### `info` 选项 - -

- -**类型:**`any`
- -

- -与导航相关的 `astro:before-preparation` 和 `astro:before-swap` 事件中包含的任意数据。 - -此选项模仿了浏览器 Navigation API 中的 [`info` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info)。 - -#### `state` 选项 - -

- -**类型:**`any`
- -

- -与导航相关的 `NavitationHistoryEntry` 对象中关联的任意数据。此数据可以通过 [`history.getState` 函数](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState) 从 History API 中检索。 - -此选项模仿了浏览器 Navigation API 中的 [`state` 选项](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state)。 - -#### `sourceElement` 选项 - -

- -**类型:**`Element`
- -

- -此导航的触发元素,如果有的话。此元素将在以下事件中可用: -- `astro:before-preparation` -- `astro:before-swap` - -### `supportsViewTransitions` - -

- -**类型:**`boolean`
- -

- -当前浏览器是否支持并启用视图过渡。 - -### `transitionEnabledOnThisPage` - -

- -**类型:**`boolean`
- -

- -当前页面是否启用了视图过渡以进行客户端导航。这可以用于使组件在视图过渡页面上的行为有所不同。 - -### `getFallback` - -

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

- -返回在浏览器不支持视图过渡时使用的回退策略。 - -有关如何选择和配置回退行为的详细信息,请参阅 [回退控制](/zh-cn/guides/view-transitions/#回退控制) 指南。 - - -### `astro:before-preparation` 事件 - -在视图过渡中导航开始时触发的事件。此事件发生在任何请求之前,并且不会更改任何浏览器状态。 - -此事件具有以下属性: -- [`info`](#info) -- [`sourceElement`](#sourceelement) -- [`navigationType`](#navigationtype) -- [`direction`](#direction) -- [`from`](#from) -- [`to`](#to) -- [`formData`](#formdata) -- [`loader`](#loader) - -有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astrobefore-preparation). - -### `astro:after-preparation` 事件 - -使用视图过渡加载导航中的下一个页面后触发的事件。 - -此事件没有属性。 - -有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astroafter-preparation). - -### `astro:before-swap` 事件 - -在视图过渡中导航的下一个页面解析、准备并链接到 document 后,但在任何内容在 document 之间交换之前触发的事件。 - -此事件不能取消。调用 `preventDefault()` 是无效的。 - -此事件具有以下属性: -- [`info`](#info) -- [`sourceElement`](#sourceelement) -- [`navigationType`](#navigationtype) -- [`direction`](#direction) -- [`from`](#from) -- [`to`](#to) -- [`viewTransition`](#viewtransition) -- [`swap`](#swap) - -有关如何使用此事件的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#astrobefore-swap). - -### `astro:after-swap` 事件 - -在视图过渡中导航的下一个页面内容交换后,但在视图过渡结束之前触发的事件。 - -在触发此事件时,历史记录条目和滚动位置已经更新。 - -### `astro:page-load` 事件 - -在页面完成加载后触发的事件,无论是通过视图过渡导航还是浏览器原生导航。 - -当视图过渡在页面上启用时,通常在 `DOMContentLoaded` 上执行的代码应更改为在此事件上执行。 - -### 视图过渡事件属性 - -

- -#### `info` - -

- -**类型:**`URL` -

- -在导航期间定义的任意数据。 - -这是在 [`navigate()` 函数](#navigate) 的 [`info` 选项](#info-选项) 中传递的文字值。 - -#### `sourceElement` - -

- -**类型:**`Element | undefined` -

- -触发导航的元素。例如,这可以是点击的 `` 元素。 - -当使用 [`navigate()` 函数](#navigate) 时,这将是调用中指定的元素。 - -#### `newDocument` - -

- -**类型:**`Document` -

- -导航中下一个页面的 document。此 document 的内容将替换当前 document 的内容。 - -#### `navigationType` - -

- -**类型:**`'push' | 'replace' | 'traverse'` -

- -正在发生的导航类型。 -- `push`: 正在为新页面创建一个新的 `NavigationHistoryEntry`。 -- `replace`: 当前的 `NavigationHistoryEntry` 正在被新页面的条目替换。 -- `traverse`: 没有创建 `NavigationHistoryEntry`。历史记录中的位置正在改变。 - 遍历的方向由 [`direction` 属性](#direction) 给出 - -#### `direction` - -

- -**类型:**`Direction` -

- -过渡的方向。 -- `forward`: 在历史记录中导航到下一个页面或新页面。 -- `back`: 在历史记录中导航到前一个页面。 -- 其他监听器可能设置的任何其他内容。 - -#### `from` - -

- -**类型:**`URL` -

- -正在导航的页面的 URL。 - -#### `to` - -

- -**类型:**`URL` -

- -正在导航的页面的 URL。此属性可以修改,在生命周期结束时使用的值将是下一个页面的 `NavigationHistoryEntry` 的值。 - -#### `formData` - -

- -**类型:**`FormData | undefined` -

- -一个用于 `POST` 请求的 `FormData` 对象。 - -当此属性设置时,将使用给定的表单数据对象作为内容发送 `POST` 请求到 [`to` URL](#to),而不是正常的 `GET` 请求。 - -当提交一个带有视图过渡的 HTML 表单时,此字段会自动设置为表单中的数据。当使用 [`navigate()` 函数](#navigate) 时,此值与给定的选项相同。 - -#### `loader` - -

- -**类型:**`() => Promise` -

- -在导航过程中下个阶段的实现(加载下一个页面)。此实现可以覆盖以添加额外的行为。 - -#### `viewTransition` - -

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

- -在导航过程中使用的视图过渡对象。在浏览器不支持 [视图过渡 API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) 的情况下,这是一个对象,实现了相同的 API 以方便使用,但没有 DOM 集成。 - -#### `swap` - -

- -**类型:**`() => void` -

- -document 交换逻辑的实现。 - -有关如何构建自定义交换函数的详细信息,请参阅 [视图过渡指南](/zh-cn/guides/view-transitions/#构建自定义交换函数). - -默认情况下,此实现将按顺序调用以下函数: - -##### `deselectScripts()` - -

- -**类型:**`(newDocument: Document) => void` -

- -标记在新的 document 中不应执行的脚本。这些脚本已经在当前 document 中,并且没有使用 [`data-astro-rerun`](/zh-cn/guides/view-transitions/#data-astro-rerun) 标记为重新执行。 - -##### `swapRootAttributes()` - -

- -**类型:**`(newDocument: Document) => void` -

- -在 document 根节点之间交换属性,如 `lang` 属性。这也包括 Astro 注入的内部属性,如 `data-astro-transition`,这使得过渡方向可用于 Astro 生成的 CSS 规则。 - -在构建自定义交换函数时,重要的是调用此函数,以避免破坏视图过渡的动画。 - -##### `swapHeadElements()` - -

- -**类型:**`(newDocument: Document) => void` -

- -从当前 document 的 `` 中删除所有未持久化到新 document 的元素。然后将新 document 的 `` 中的所有新元素附加到当前 document 的 ``。 - -##### `saveFocus()` - -

- -**类型:**`() => () => void` -

- -在当前页面上存储聚焦的元素,并返回一个函数,当调用时,如果聚焦的元素被持久化,则将焦点返回给该元素。 - - -##### `swapBodyElements()` - -

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

- -用新 document 的 body 替换旧的 body。然后,遍历旧 body 中应持久化的每个元素,并在新 body 中找到匹配的元素,将旧元素交换回原位。 - -## Actions (`astro:actions`) - -

- -

- -Action 帮助你构建一个类型安全的后端,你可以从客户端代码和 HTML 表单中调用它。所有用于定义和调用 Action 的工具函数都由 `astro:actions` 模块暴露。有关示例和使用说明,请参阅 [Actions 指南](/zh-cn/guides/actions/)。 - -### `defineAction()` - -

- -

- -`defineAction()` 函数接受一个 [`handler()`](#handler-属性) 函数,其中包含在调用 Action 时要运行的服务器逻辑,以及一个可选的 [`input`](#input-验证器) 属性,用于在运行时验证输入参数。 - -```ts -export const server = { - getGreeting: defineAction({ - input: z.object({ - name: z.string(), - }), - handler: async (input, context) => { - return `Hello, ${input.name}!` - } - }) -} -``` - -#### `handler()` 属性 - -

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

- -`defineAction()` 函数接受一个 `handler()` 函数,其中包含在调用 Action 时要运行的服务器逻辑。此函数可以返回数据,这些数据将自动序列化并发送给调用者。 - -`handler()` 函数被调用时,接受用户输入作为其第一个参数。如果设置了 [`input`](#input-验证器) 验证器,那么用户输入将在传递给 `handler()` 前进行验证。第二个参数是一个 `context` 对象,包含大多数 Astro 的 [标准端点上下文](#端点上下文),不包括 `getActionResult()`, `callAction()`, 和 `redirect()`。 - -返回值使用 [devalue 库](https://github.com/Rich-Harris/devalue) 进行解析。它支持 JSON 值,以及 `Date()`, `Map()`, `Set()`, 或 `URL()` 的实例。 - -#### `input` 验证器 - -

- -**类型:**`ZodType | undefined` -

- -可选的 `input` 属性接受一个 Zod 验证器,用于在运行时验证处理程序的输入。如果 action 验证失败,将返回 [`BAD_REQUEST` 错误](#actionerror) 并跳过 `handler`。 - -如果省略 `input`,则 `handler` 将接收 JSON 请求的 `unknown` 类型的输入,以及表单请求的 `FormData` 类型。 - -##### 与 `accept: 'form'` 一起使用 - -如果你的 action 接受表单输入,请使用 `z.object()` 验证器将表单数据自动解析为类型化对象。表单数据字段支持以下验证器: - -- 使用 `z.number()` 验证类型为 `number` 的输入 -- 使用 `z.boolean()` 验证类型为 `checkbox` 的输入 -- 使用 `z.instanceof(File)` 验证类型为 `file` 的输入 -- 使用 `z.array(/* validator */)` 验证相同 `name` 的多个输入 -- 使用 `z.string()` 验证所有其他输入 - -`z.object()` 验证器还支持包括 `.refine()`, `.transform()`, 和 `.pipe()` 在内的扩展函数。 - -要搭配应用不同验证器的组合,请使用 `z.discriminatedUnion()` 包装器,它根据表单的特定字段以缩小类型范围。此示例通过接受表单提交以判断是 “创建(create)” 或是 “更新(update)” 了一名用户信息,判断时使用表单域的 `type` 属性字段来确定要验证的对象: - -```ts -import { defineAction } from 'astro:actions'; -import { z } from 'astro:schema'; - -export const server = { - changeUser: defineAction({ - accept: 'form', - input: z.discriminatedUnion('type', [ - z.object({ - // 当 `type` 字段中的值含有 `create` 时匹配 - type: z.literal('create'), - name: z.string(), - email: z.string().email(), - }), - z.object({ - // 当 `type` 字段中的值含有 `update` 时匹配 - type: z.literal('update'), - id: z.number(), - name: z.string(), - email: z.string().email(), - }), - ]), - async handler(input) { - if (input.type === 'create') { - // input 为 { type: 'create', name: string, email: string } - } else { - // input 为 { type: 'update', id: number, name: string, email: string } - } - }, - }), -}; -``` - -### `isInputError()` - -

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

- -`isInputError()` 函数常用于检查 `ActionError` 是否是输入验证错误。当 `input` 验证器是 `z.object()` 时,输入错误包括一个 `fields` 对象,其中错误消息按名称分组。 - - -更多关于使用 `isInputError()` 的信息,请参见 [表单输入错误指南](/zh-cn/guides/actions/#展示表单输入错误)。 - - -### `ActionError` - -

- -

- -`ActionError` 构造函数常用于在 `handler()` 函数中抛出错误。它接受一个 `code` 属性,描述发生的错误(例如:`"UNAUTHORIZED"`),以及一个可选的 `message` 属性,提供进一步的细节。 - -#### `code` - -

- -

- -`code` 属性接受所有 HTTP 状态码的人类可读版本。以下是支持的 code: - -- `BAD_REQUEST` (400): 客户端发送了无效的输入。当 action `input` 验证器验证失败时会抛出此错误。 -- `UNAUTHORIZED` (401): 客户端缺乏有效的身份验证凭据。 -- `FORBIDDEN` (403): 客户端无权访问资源。 -- `NOT_FOUND` (404): 服务器找不到请求的资源。 -- `METHOD_NOT_SUPPORTED` (405): 服务器不支持请求的方法。 -- `TIMEOUT` (408): 服务器在处理请求时超时。 -- `CONFLICT` (409): 服务器无法更新资源,因为存在冲突。 -- `PRECONDITION_FAILED` (412): 服务器不满足请求的前提条件。 -- `PAYLOAD_TOO_LARGE` (413): 服务器无法处理请求,因为负载过大。 -- `UNSUPPORTED_MEDIA_TYPE` (415): 服务器不支持请求的媒体类型。注意:Actions 已经检查了 JSON 和表单请求的 [`Content-Type` 标头](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Type),所以你可能不需要手动引发此代码。 -- `UNPROCESSABLE_CONTENT` (422): 服务器无法处理请求,因为存在语义错误。 -- `TOO_MANY_REQUESTS` (429): 服务器已超出指定的速率限制。 -- `CLIENT_CLOSED_REQUEST` (499): 客户端在服务器响应之前关闭了请求。 -- `INTERNAL_SERVER_ERROR` (500): 服务器意外失败。 -- `NOT_IMPLEMENTED` (501): 服务器不支持请求的功能。 -- `BAD_GATEWAY` (502): 服务器从上游服务器接收到无效响应。 -- `SERVICE_UNAVAILABLE` (503): 服务器暂时不可用。 -- `GATEWAY_TIMEOUT` (504): 服务器从上游服务器接收到超时。 - -#### `message` - -

- -

- -`message` 属性接受一个字符串。(例如:"用户必须登录。") - -[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element From d732d5efbfc26c7886404200619c4c29edd4ce00 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 11:53:30 +0100 Subject: [PATCH 28/43] i18n(fr): create `reference/modules/astro-actions.mdx` (#9823) See #9687 and #9819 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- .../fr/reference/modules/astro-actions.mdx | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 src/content/docs/fr/reference/modules/astro-actions.mdx diff --git a/src/content/docs/fr/reference/modules/astro-actions.mdx b/src/content/docs/fr/reference/modules/astro-actions.mdx new file mode 100644 index 0000000000000..1ef57e4583696 --- /dev/null +++ b/src/content/docs/fr/reference/modules/astro-actions.mdx @@ -0,0 +1,176 @@ +--- +title: Référence de l'API Actions +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +

+ +Les actions vous aident à créer un backend incluant la sûreté du typage que vous pouvez appeler à partir du code client et des formulaires HTML. Tous les utilitaires permettant de définir et d'appeler des actions sont exposés par le module `astro:actions`. Pour des exemples et des instructions d'utilisation, [consultez le guide Actions](/fr/guides/actions/). + +## Importations depuis `astro:actions` + +```js +import { + actions, + defineAction, + isInputError, + ActionError, + } from 'astro:actions'; +``` + +### `defineAction()` + +

+ +

+ +L'utilitaire `defineAction()` est utilisé pour définir de nouvelles actions à partir du fichier `src/actions/index.ts`. Il accepte une fonction [`handler()`](#propriété-handler) contenant la logique du serveur à exécuter et une propriété facultative [`input`](#validateur-de-saisie-input) pour valider les paramètres d'entrée lors de l'exécution. + +```ts title="src/actions/index.ts" +import { defineAction } from 'astro:actions'; +import { z } from 'astro:schema'; + +export const server = { + getGreeting: defineAction({ + input: z.object({ + name: z.string(), + }), + handler: async (input, context) => { + return `Bonjour, ${input.name}!` + } + }) +} +``` + +#### Propriété `handler()` + +

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

+ +`defineAction()` nécessite une fonction `handler()` contenant la logique du serveur à exécuter lorsque l'action est appelée. Les données renvoyées par le gestionnaire sont automatiquement sérialisées et envoyées à l'appelant. + +Le `handler()` est appelé avec la saisie de l'utilisateur comme premier argument. Si un validateur [`input`](#validateur-de-saisie-input) est défini, la saisie de l'utilisateur sera validée avant d'être transmise au gestionnaire. Le deuxième argument est un objet `context` contenant la plupart du [contexte de point de terminaison standard](/fr/reference/api-reference/#contexte-du-point-de-terminaison) d'Astro, à l'exception de `getActionResult()`, `callAction()` et `redirect()`. + +Les valeurs de retour sont analysées à l'aide de la [bibliothèque devalue](https://github.com/Rich-Harris/devalue). Celle-ci prend en charge les valeurs JSON, ainsi que les instances de `Date()`, `Map()`, `Set()` ou `URL()`. + +#### Validateur de saisie (`input`) + +

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

+ +La propriété facultative `input` accepte un validateur Zod pour vérifier les entrées du gestionnaire lors de l'exécution. Si l'action échoue à la validation, [une erreur `BAD_REQUEST`](#actionerror) est renvoyée et la fonction `handler` n'est pas appelée. + +Si `input` est omis, le `handler` recevra une entrée de type `unknown` pour les requêtes JSON et de type `FormData` pour les requêtes de formulaire. + +##### Utiliser avec `accept: 'form'` + +Si votre action accepte les entrées de formulaire, utilisez le validateur `z.object()` pour analyser automatiquement les données du formulaire en un objet typé. Les validateurs suivants sont pris en charge pour les champs de données de formulaire : + +- Les entrées de type `number` peuvent être validées à l'aide de `z.number()` +- Les entrées de type `checkbox` peuvent être validées à l'aide de `z.boolean()` +- Les entrées de type `file` peuvent être validées à l'aide de `z.instanceof(File)` +- Plusieurs entrées du même nom (`name`) peuvent être validées à l'aide de `z.array(/* validateur */)` +- Toutes les autres entrées peuvent être validées à l'aide de `z.string()` + +Les fonctions d'extension, notamment `.refine()`, `.transform()` et `.pipe()`, sont également prises en charge sur cet objet. Les validateurs suivants sont pris en charge pour les champs de données de formulaire : + +Pour appliquer une union de différents validateurs, utilisez le wrapper `z.discriminatedUnion()` pour affiner le type en fonction d'un champ de formulaire spécifique. Cet exemple accepte une soumission de formulaire pour créer (`create`) ou mettre à jour (`update`) un utilisateur, en utilisant le champ de formulaire avec le nom `type` pour déterminer l'objet à valider : + +```ts +import { defineAction } from 'astro:actions'; +import { z } from 'astro:schema'; + +export const server = { + changeUser: defineAction({ + accept: 'form', + input: z.discriminatedUnion('type', [ + z.object({ + // Correspond lorsque le champ `type` est défini sur la valeur `create` + type: z.literal('create'), + name: z.string(), + email: z.string().email(), + }), + z.object({ + // Correspond lorsque le champ `type` est défini sur la valeur `update` + type: z.literal('update'), + id: z.number(), + name: z.string(), + email: z.string().email(), + }), + ]), + async handler(input) { + if (input.type === 'create') { + // l'entrée correspond à { type: 'create', name: string, email: string } + } else { + // l'entrée correspond à { type: 'update', id: number, name: string, email: string } + } + }, + }), +}; +``` + +### `isInputError()` + +

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

+ +L'utilitaire `isInputError()` permet de vérifier si une `ActionError` est une erreur de validation d'entrée. Lorsque le validateur utilisé pour `input` correspond à `z.object()`, les erreurs d'entrée incluent un objet `fields` avec des messages d'erreur regroupés par nom. + +Consultez le [guide des erreurs de saisie de formulaire](/fr/guides/actions/#affichage-des-erreurs-de-saisie-du-formulaire) pour en savoir plus sur l'utilisation de `isInputError()`. + +### `ActionError` + +

+ +

+ +Le constructeur `ActionError()` est utilisé pour créer des erreurs générées par un gestionnaire d'action (`handler`). Il accepte une propriété `code` décrivant l'erreur qui s'est produite (par exemple : `"UNAUTHORIZED"`), et une propriété facultative `message` contenant plus de détails. + +#### `code` + +

+ +

+ +La propriété `code` accepte les versions lisibles par l'homme de tous les codes d'état HTTP. Les codes suivants sont pris en charge : + +- `BAD_REQUEST` (400) : Le client a envoyé une entrée non valide. Cette erreur est générée lorsqu'un validateur d'entrée d'action (`input`) ne parvient pas à valider. +- `UNAUTHORIZED` (401) : Le client ne dispose pas d’informations d’authentification valides. +- `FORBIDDEN` (403) : Le client n'est pas autorisé à accéder à une ressource. +- `NOT_FOUND` (404) : Le serveur ne trouve pas la ressource demandée. +- `METHOD_NOT_SUPPORTED` (405) : Le serveur ne prend pas en charge la méthode demandée. +- `TIMEOUT` (408) : Le serveur a expiré lors du traitement de la demande. +- `CONFLICT` (409) : Le serveur ne peut pas mettre à jour une ressource en raison d'un conflit. +- `PRECONDITION_FAILED` (412) : Le serveur ne répond pas à une condition préalable de la requête. +- `PAYLOAD_TOO_LARGE` (413) : Le serveur ne peut pas traiter la demande car la charge utile est trop importante. +- `UNSUPPORTED_MEDIA_TYPE` (415) : Le serveur ne prend pas en charge le type de média de la requête. Remarque : les actions vérifient déjà [l'en-tête `Content-Type`](https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Content-Type) pour les requêtes JSON et de formulaire. Vous n'aurez donc probablement pas besoin de générer ce code manuellement. +- `UNPROCESSABLE_CONTENT` (422) : Le serveur ne peut pas traiter la demande en raison d'erreurs sémantiques. +- `TOO_MANY_REQUESTS` (429) : Le serveur a dépassé une limite de débit spécifiée. +- `CLIENT_CLOSED_REQUEST` (499) : Le client a fermé la demande avant que le serveur puisse répondre. +- `INTERNAL_SERVER_ERROR` (500) : Le serveur est tombé en panne de manière inattendue. +- `NOT_IMPLEMENTED` (501) : Le serveur ne prend pas en charge la fonctionnalité demandée. +- `BAD_GATEWAY` (502) : Le serveur a reçu une réponse non valide d’un serveur en amont. +- `SERVICE_UNAVAILABLE` (503) : Le serveur est temporairement indisponible. +- `GATEWAY_TIMEOUT` (504) : Le serveur a reçu un délai d'attente d'un serveur en amont. + +#### `message` + +

+ +

+ +La propriété `message` accepte une chaîne de caractères. (par exemple, « L'utilisateur doit être connecté. ») From 544662f970ee51c07ba9ac46ec422d4e21ee2647 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 12:03:46 +0100 Subject: [PATCH 29/43] i18n(fr): update `guides/actions.mdx` (#9838) See #9687 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- src/content/docs/fr/guides/actions.mdx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/fr/guides/actions.mdx b/src/content/docs/fr/guides/actions.mdx index 791b9fd8bb19c..56f56f68a33d0 100644 --- a/src/content/docs/fr/guides/actions.mdx +++ b/src/content/docs/fr/guides/actions.mdx @@ -16,7 +16,7 @@ Utilisez des actions à la place de points de terminaison d'API pour une communi - Valider automatiquement les entrées de données JSON et de formulaire à l'aide de la [validation Zod](https://zod.dev/?id=primitives). - Générer des fonctions avec sûreté du typage pour appeler votre backend à partir du client et même [à partir des actions de formulaire HTML](#appeler-des-actions-depuis-une-action-de-formulaire-html). Pas besoin d'appels manuels à `fetch()`. -- Standardiser les erreurs du backend avec l'objet [`ActionError`](/fr/reference/api-reference/#actionerror). +- Standardiser les erreurs du backend avec l'objet [`ActionError`](/fr/reference/modules/astro-actions/#actionerror). ## Utilisation de base @@ -129,7 +129,7 @@ Suivez ces étapes pour définir une action et pour l'appeler dans une balise `s -Consultez la documentation complète de l'API Actions pour plus de détails sur [`defineAction()`](/fr/reference/api-reference/#defineaction) et ses propriétés. +Consultez la documentation complète de l'API Actions pour plus de détails sur [`defineAction()`](/fr/reference/modules/astro-actions/#defineaction) et ses propriétés. ## Organiser les actions @@ -340,7 +340,7 @@ L'exemple suivant montre un formulaire d'inscription à une newsletter validé q } ``` - Consultez la [référence de l'API `input`](/fr/reference/api-reference/#validateur-de-saisie-input) pour tous les validateurs de formulaire disponibles. + Consultez la [référence de l'API `input`](/fr/reference/modules/astro-actions/#validateur-de-saisie-input) pour tous les validateurs de formulaire disponibles. 3. Ajoutez un ` +``` + +### `navigate()` + +

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

+ +Une fonction qui exécute une navigation vers le `href` donné à l'aide de l'API Transitions de Vue. + +Cette signature de fonction est basée sur la fonction [`navigate` de l'API Navigation du navigateur](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate). Bien que basée sur l'API Navigation, cette fonction est implémentée sur l'[API History](https://developer.mozilla.org/fr/docs/Web/API/History_API) pour permettre la navigation sans recharger la page. + +#### Option `history` + +

+ +**Type :** `'auto' | 'push' | 'replace'`
+**Par défaut :** `'auto'`
+ +

+ +Définit la manière dont cette navigation doit être ajoutée à l'historique du navigateur. + +- `'push'` : le routeur utilisera `history.pushState` pour créer une nouvelle entrée dans l'historique du navigateur. +- `'replace'` : le routeur utilisera `history.replaceState` pour mettre à jour l'URL sans ajouter de nouvelle entrée dans la navigation. +- `'auto'` (par défaut) : le routeur tentera `history.pushState`, mais si l'URL ne peut pas être transférée, l'URL actuelle restera sans modification de l'historique du navigateur. + +Cette option suit l'[option `history`](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#history) de l'API Navigation du navigateur mais simplifiée pour les cas qui peuvent survenir sur un projet Astro. + +#### Option `formData` + +

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

+ +Un objet `FormData` pour les requêtes `POST`. + +Lorsque cette option est transmise, les requêtes vers la page cible de navigation seront envoyées sous forme de requête `POST` avec l'objet de données du formulaire comme contenu. + +L'envoi d'un formulaire HTML avec les transitions de vue activées utilisera cette méthode au lieu de la navigation par défaut avec rechargement de page. L'appel de cette méthode permet de déclencher le même comportement par programmation. + +#### Option `info` + +

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

+ +Données arbitraires à inclure dans les événements `astro:before-preparation` et `astro:before-swap` provoqués par cette navigation. + +Cette option imite l'[option `info`](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#info) de l'API Navigation du navigateur. + +#### Option `state` + +

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

+ +Données arbitraires à associer à l'objet `NavitationHistoryEntry` créé par cette navigation. Ces données peuvent ensuite être récupérées à l'aide de la fonction [`history.getState`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry/getState) de l'API History. + +Cette option imite l'[option `state`](https://developer.mozilla.org/en-US/docs/Web/API/Navigation/navigate#state) de l'API Navigation du navigateur. + +#### Option `sourceElement` + +

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

+ +L'élément qui a déclenché cette navigation, le cas échéant. Cet élément sera disponible dans les événements suivants : +- `astro:before-preparation` +- `astro:before-swap` + +### `supportsViewTransitions` + +

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

+ +Indique si les transitions de vue sont prises en charge et activées dans le navigateur actuel. + +### `transitionEnabledOnThisPage` + +

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

+ +Indique si la page actuelle comporte ou non des transitions d'affichage activées pour la navigation côté client. Cela peut être utilisé pour créer des composants qui se comportent différemment lorsqu'ils sont utilisés sur des pages avec des transitions de vue. + +### `getFallback()` + +

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

+ +Renvoie la stratégie de secours à utiliser dans les navigateurs qui ne prennent pas en charge les transitions de vue. + +Voir le guide sur la [Gestion de solution de secours](/fr/guides/view-transitions/#gestion-de-solution-de-secours) pour savoir comment choisir et configurer le comportement de repli. + +### `swapFunctions` + +

+ + +

+ +Un objet contenant les fonctions utilitaires utilisées pour créer la fonction d’échange par défaut d’Astro. +Celles-ci peuvent être utiles lors de la [création d'une fonction d'échange personnalisée](/fr/guides/view-transitions/#créer-une-fonction-déchange-personnalisée). + +`swapFunctions` fournit les méthodes suivantes : + +#### `deselectScripts()` + +

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

+ +Marque les scripts du nouveau document qui ne doivent pas être exécutés. Ces scripts sont déjà présents dans le document actuel et ne sont pas signalés pour une réexécution à l'aide de [`data-astro-rerun`](/fr/guides/view-transitions/#data-astro-rerun). + +#### `swapRootAttributes()` + +

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

+ +Échange les attributs entre les racines du document, comme l'attribut `lang`. Cela inclut également les attributs internes injectés par Astro comme `data-astro-transition`, qui rendent la direction de transition disponible pour les règles CSS générées par Astro. + +Lors de la création d'une fonction d'échange personnalisée, il est important d'appeler cette fonction afin de ne pas interrompre les animations de transition de vue. + +#### `swapHeadElements()` + +

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

+ +Supprime tous les éléments présents dans la balise `` du document actuel qui ne sont pas conservés dans le nouveau document. Ajoute ensuite tous les nouveaux éléments présents dans la balise `` du nouveau document dans celle du document courant. + +#### `saveFocus()` + +

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

+ +Stocke l'élément focalisé sur la page actuelle et renvoie une fonction qui, lorsqu'elle est appelée, si l'élément focalisé a été conservé, renvoie le focus sur celui-ci. + + +#### `swapBodyElement()` + +

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

+ +Remplace l'ancien corps par le nouveau. Ensuite, il passe en revue chaque élément de l'ancien corps qui doit être conservé et qui possède un élément correspondant dans le nouveau corps avant de remplacer l'ancien élément en place. + +## Événements du cycle de vie + +### Événement `astro:before-preparation` + +Un événement déclenché au début d'une navigation à l'aide de Transitions de Vue. Cet événement se produit avant toute demande et tout changement d'état du navigateur. + +Cet événement possède les attributs suivants : +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`formData`](#formdata) +- [`loader`](#loader) + +Pour en savoir plus sur l'utilisation de cet événement, consultez le [Guide des Transitions de Vue](/fr/guides/view-transitions/#astrobefore-preparation). + +### Événement `astro:after-preparation` + +Un événement envoyé après le chargement de la page suivante dans une navigation utilisant des Transitions de Vue. + +Cet événement n'a aucun attribut. + +Pour en savoir plus sur l'utilisation de cet événement, consultez le [Guide des Transitions de Vue](/fr/guides/view-transitions/#astroafter-preparation). + +### Événement `astro:before-swap` + +Un événement envoyé après que la page suivante est analysée, préparée et liée à un document en prévision de la transition, mais avant que tout contenu ne soit échangé entre les documents. + +Cet événement ne peut pas être annulé. L'appel de `preventDefault()` est une opération interdite. + +Cet événement possède les attributs suivants : +- [`info`](#info) +- [`sourceElement`](#sourceelement) +- [`navigationType`](#navigationtype) +- [`direction`](#direction) +- [`from`](#from) +- [`to`](#to) +- [`viewTransition`](#viewtransition) +- [`swap`](#swap) + +Pour en savoir plus sur l'utilisation de cet événement, consultez le [Guide des Transitions de Vue](/fr/guides/view-transitions/#astrobefore-swap). + +### Événement `astro:after-swap` + +Un événement envoyé après que le contenu de la page a été échangé mais avant la fin de la transition de vue. + +L'entrée de l'historique et la position de défilement ont déjà été mises à jour lorsque cet événement est déclenché. + +### Événement `astro:page-load` + +Un événement envoyé une fois le chargement d'une page terminé, qu'il s'agisse d'une navigation utilisant des transitions de vue ou native du navigateur. + +Lorsque les transitions de vue sont activées sur la page, le code qui s'exécuterait normalement sur `DOMContentLoaded` doit être modifié pour s'exécuter sur cet événement. + +### Attributs des événements du cycle de vie + +

+ +#### `info` + +

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

+ +Données arbitraires définies lors de la navigation. + +Il s'agit de la valeur littérale transmise à l'[option `info`](#option-info) de la [fonction `navigate()`](#navigate). + +#### `sourceElement` + +

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

+ +L'élément qui a déclenché la navigation. Il peut s'agir, par exemple, d'un élément `` sur lequel on a cliqué. + +Lors de l'utilisation de la [fonction `navigate()`](#navigate), ce sera l'élément spécifié dans l'appel. + +#### `newDocument` + +

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

+ +Le document de la page suivante dans la navigation. Le contenu de ce document sera échangé à la place du contenu du document actuel. + +#### `navigationType` + +

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

+ +Quel type de navigation dans l'historique est en cours. +- `push` : une nouvelle `NavigationHistoryEntry` est en cours de création pour la nouvelle page. +- `replace` : l'actuelle `NavigationHistoryEntry` est remplacée par une entrée pour la nouvelle page. +- `traverse` : aucune `NavigationHistoryEntry` n'est créée. La position dans l'historique change. + La direction du parcours est donnée sur l'[attribut `direction`](#direction) + +#### `direction` + +

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

+ +La direction de la transition. +- `forward` : naviguer vers la page suivante de l'historique ou vers une nouvelle page. +- `back` : naviguer vers la page précédente de l'historique. +- Tout ce qu’un autre écouteur d'événement aurait pu définir. + +#### `from` + +

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

+ +L'URL de la page initiant la navigation. + +#### `to` + +

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

+ +L'URL de la page vers laquelle on navigue. Cette propriété peut être modifiée, la valeur à la fin du cycle de vie sera utilisée dans le `NavigationHistoryEntry` pour la page suivante. + +#### `formData` + +

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

+ +Un objet `FormData` pour les requêtes `POST`. + +Lorsque cet attribut est défini, une requête `POST` sera envoyée à l'[URL`to`](#to) avec l'objet de données de formulaire donné comme contenu au lieu de la requête `GET` normale. + +Lors de la soumission d'un formulaire HTML avec les transitions de vue activées, ce champ est automatiquement défini sur les données du formulaire. Lorsque vous utilisez la [fonction `navigate()`](#navigate), cette valeur est la même que celle donnée dans les options. + +#### `loader()` + +

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

+ +Implémentation de la phase suivante dans la navigation (chargement de la page suivante). Cette implémentation peut être surchargée pour ajouter un comportement supplémentaire. + +#### `viewTransition` + +

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

+ +L'objet de transition de vue utilisé dans cette navigation. Sur les navigateurs qui ne prennent pas en charge l'[API de Transitions de Vue](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API), il s'agit d'un objet implémentant la même API pour plus de commodité, mais sans l'intégration DOM. + +#### `swap()` + +

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

+ +Mise en place de la logique d'échange de documents. + +Apprenez-en davantage sur la façon de [créer votre propre fonction d'échange personnalisée](/fr/guides/view-transitions/#créer-une-fonction-déchange-personnalisée) dans le guide Transitions de Vue. + +Par défaut, cette implémentation appellera les fonctions suivantes dans l’ordre : + +1. [`deselectScripts()`](#deselectscripts) +2. [`swapRootAttributes()`](#swaprootattributes) +3. [`swapHeadElements()`](#swapheadelements) +4. [`saveFocus()`](#savefocus) +5. [`swapBodyElement()`](#swapbodyelement) From ebb91313fc193079dcb45c6193ba3c1a3b607c68 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 13:25:17 +0100 Subject: [PATCH 31/43] i18n(fr): create `reference/modules/astro-content.mdx` (#9825) See #9687 and #9821 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- .../fr/reference/modules/astro-content.mdx | 376 ++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 src/content/docs/fr/reference/modules/astro-content.mdx diff --git a/src/content/docs/fr/reference/modules/astro-content.mdx b/src/content/docs/fr/reference/modules/astro-content.mdx new file mode 100644 index 0000000000000..59c90d06611fb --- /dev/null +++ b/src/content/docs/fr/reference/modules/astro-content.mdx @@ -0,0 +1,376 @@ +--- +title: Référence de l'API des collections de contenu +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +Les collections de contenu proposent des API pour configurer et interroger vos documents Markdown ou MDX dans `src/content/`. Pour connaître les fonctionnalités et les exemples d'utilisation, [consultez notre guide sur les collections de contenu](/fr/guides/content-collections/). + +## Importations depuis `astro:content` + +```js +import { + z, + defineCollection, + getCollection, + getEntry, + getEntries, + reference, + } from 'astro:content'; +``` +### `defineCollection()` + +

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

+ +`defineCollection()` est un utilitaire pour configurer une collection dans un fichier `src/content/config.*`. + +```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(), + }), +}); + +// Exposez votre collection définie à Astro +// avec l'exportation `collections` +export const collections = { blog }; +``` + +Cette fonction accepte les propriétés suivantes : + +#### `type` + +

+ +**Type :** `'content' | 'data'`
+**Par défaut :** `'content'`
+ +

+ +`type` est une chaîne de caractères qui définit le type d'entrées stockées dans une collection : + +- `'content'` - pour les formats de création de contenu comme Markdown (`.md`), MDX (`.mdx`) ou Markdoc (`.mdoc`) +- `'data'` - pour les formats de données uniquement comme JSON (`.json`) ou YAML (`.yaml`) + +:::tip +Cela signifie que les collections **ne peuvent pas** stocker un mélange de contenus et de formats de données. Vous devez diviser ces entrées en collections distinctes par type. +::: + +#### `schema` + +

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

+ +`schema` est un objet Zod facultatif pour configurer le type et la forme du document pour une collection. Chaque valeur doit utiliser [un validateur Zod](https://github.com/colinhacks/zod). + +[Consultez le guide Collections de contenu](/fr/guides/content-collections/#définition-dun-schéma-de-collection) pour un exemple d'utilisation. + +### `reference()` + +

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

+ +La fonction `reference()` est utilisée dans la configuration du contenu pour définir une relation, ou une « référence », entre une collection et une autre. Elle accepte un nom de collection et valide le ou les identifiants d'entrée spécifiés dans le frontmatter de votre contenu ou dans votre fichier de données. + +Cet exemple définit les références d'un auteur de blog à la collection `authors` et un tableau d'articles associés à la même collection `blog` : + +```ts +import { defineCollection, reference, z } from 'astro:content'; + +const blog = defineCollection({ + type: 'content', + schema: z.object({ + // Référence un seul auteur de la collection `authors` par `id` + author: reference('authors'), + // Référence un tableau d'articles connexes de la collection `blog` par `slug` + relatedPosts: z.array(reference('blog')), + }) +}); + +const authors = defineCollection({ + type: 'data', + schema: z.object({ /* ... */ }) +}); + +export const collections = { blog, authors }; +``` + +[Consultez le guide Collections de contenu](/fr/guides/content-collections/#définition-des-références-de-collection) pour un exemple d'utilisation. + +### `getCollection()` + +

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

+ +`getCollection()` est une fonction qui récupère une liste d'entrées de collection de contenu par nom de collection. + +Il renvoie tous les éléments de la collection par défaut et accepte une fonction facultative `filter` pour affiner les propriétés d'entrée. Cela vous permet d'interroger uniquement certains éléments d'une collection en fonction de `id`, `slug` ou des valeurs du frontmatter via l'objet `data`. + +```astro +--- +import { getCollection } from 'astro:content'; + +// Récupère toutes les entrées `src/content/blog/` +const allBlogPosts = await getCollection('blog'); + +// Ne renvoie que les messages avec `draft: true` dans le frontmatter +const draftBlogPosts = await getCollection('blog', ({ data }) => { + return data.draft === true; +}); +--- +``` + +[Consultez le guide Collections de contenu](/fr/guides/content-collections/#interroger-les-collections) pour un exemple d'utilisation. + +### `getEntry()` + +

+ +**Types :** +- `(collection: string, contentSlugOrDataId: string) => CollectionEntry` +- `({ collection: string, id: string }) => CollectionEntry` +- `({ collection: string, slug: string }) => CollectionEntry` + +`getEntry()` est une fonction qui récupère une seule entrée de collection en utilisant le nom de la collection et soit l'entrée `id` (pour les collections utilisant `type: 'data'`) soit l'entrée `slug` (pour les collections utilisant `type: 'content'`). `getEntry()` peut également être utilisée pour obtenir des entrées référencées pour accéder aux propriétés `data`, `body` ou `render()` : + +```astro +--- +import { getEntry } from 'astro:content'; + +// Récupère `src/content/blog/enterprise.md` +const enterprisePost = await getEntry('blog', 'enterprise'); + +// Récupère `src/content/captains/picard.yaml` +const picardProfile = await getEntry('captains', 'picard'); + +// Récupère le profil référencé par `data.captain` +const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain); +--- +``` + +Consultez le guide Collections de contenu pour des exemples d'[interrogation des entrées de collection](/fr/guides/content-collections/#interroger-les-collections). + +### `getEntries()` + +

+ +**Types :** +- `(Array<{ collection: string, id: string }>) => CollectionEntry[]` +- `(Array<{ collection: string, slug: string }>) => CollectionEntry[]` + +`getEntries()` est une fonction qui récupère plusieurs entrées dans une même collection. Ceci est utile pour [renvoyer un tableau d'entrées référencées](/fr/guides/content-collections/#définition-des-références-de-collection) pour accéder à leurs propriétés `data`, `body` et `render()` associées. + +```astro +--- +import { getEntries } from 'astro:content'; + +const enterprisePost = await getEntry('blog', 'enterprise'); + +// Récupère les articles associés référencés par `data.ratedPosts` +const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts); +--- +``` + +### `getEntryBySlug()` + +

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

+ +:::caution[Obsolète] +Utilisez la fonction [`getEntry()`](#getentry) pour interroger les entrées de contenu. Elle accepte les mêmes arguments que `getEntryBySlug()` et prend en charge les requêtes par `id` pour les collections JSON ou YAML. +::: + +`getEntryBySlug()` est une fonction qui récupère une seule entrée de collection en utilisant le nom de la collection et le `slug` d'une entrée. + + +```astro +--- +import { getEntryBySlug } from 'astro:content'; + +const enterprise = await getEntryBySlug('blog', 'enterprise'); +--- +``` + +[Consultez le guide Collections de contenu](/fr/guides/content-collections/#interroger-les-collections) pour un exemple d'utilisation. + +### `getDataEntryById()` + +

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

+ +:::caution[Obsolète] +Utilisez la [fonction `getEntry()`](#getentry) pour interroger les entrées de données. Cela accepte les mêmes arguments que `getDataEntryById()` et prend en charge l'interrogation par `slug` pour les formats de création de contenu comme Markdown. +::: + +`getDataEntryById()` est une fonction qui récupère une seule entrée de collection par nom de collection et par `id` d'entrée. + + +```astro +--- +import { getDataEntryById } from 'astro:content'; + +const picardProfile = await getDataEntryById('captains', 'picard'); +--- +``` + +## Types d'`astro:content` + +```ts +import type { + CollectionEntry, + CollectionKey, + ContentCollectionKey, + DataCollectionKey, + SchemaContext, + } from 'astro:content'; +``` + +### `CollectionEntry` + +Les fonctions de requête, notamment [`getCollection()`](#getcollection), [`getEntry()`](#getentry) et [`getEntries()`](#getentries) renvoient chacune des entrées avec le type `CollectionEntry`. Ce type est disponible en tant qu'utilitaire depuis `astro:content` : + +```ts +import type { CollectionEntry } from 'astro:content'; +``` + +`CollectionEntry` est un type générique. Utilisez-le avec le nom de la collection que vous interrogez. +Par exemple, une entrée de votre collection `blog` aurait le type `CollectionEntry<'blog'>`. + +Chaque `CollectionEntry` est un objet avec les valeurs suivantes : + +#### `id` + +**Disponible pour :** les collections utilisant `type: 'content'` ou `type: 'data'` +**Exemple de types :** + - collections de contenu : `'entry-1.md' | 'entry-2.md' | ...` + - collections de données : `'author-1' | 'author-2' | ...` + +Un identifiant unique utilisant le chemin du fichier relatif à `src/content/[collection]`. Énumère toutes les valeurs de chaîne de caractères possibles en fonction des chemins d’accès au fichier d’entrée de collection. Notez que les collections [définies comme `type: 'content'`](#type) incluent l'extension de fichier dans leur identifiant, contrairement aux collections définies comme `type: 'data'`. + +#### `collection` + +**Disponible pour :** les collections utilisant `type: 'content'` ou `type: 'data'` +**Exemple de type :** `'blog' | 'authors' | ...` + +Le nom d'un dossier placé à la racine de `src/content/` et dans lequel se trouvent les entrées. Il s'agit du nom utilisé pour référencer la collection dans votre schéma et dans les fonctions de requête. + +#### `data` + +**Disponible pour :** les collections utilisant `type: 'content'` ou `type: 'data'` +**Type :** `CollectionSchema` + +Un objet de propriétés provenant du frontmatter et déduit de votre schéma de collection ([voir la référence `defineCollection()`](#definecollection)). La valeur par défaut est `any` si aucun schéma n'est configuré. + +#### `slug` + +**Disponible pour :** les collections utilisant `type: 'content'` seulement +**Exemple de type :** `'entry-1' | 'entry-2' | ...` + +Un slug d'URL préparé pour les documents Markdown ou MDX. La valeur par défaut est `id` sans l'extension de fichier, mais peut être remplacée en définissant [la propriété `slug`](/fr/guides/content-collections/#définition-dun-slug-personnalisé) dans le frontmatter d'un fichier. + +#### `body` + +**Disponible pour :** les collections utilisant `type: 'content'` seulement +**Type :** `string` + +Une chaîne de caractères contenant le corps brut et non compilé du document Markdown ou MDX. + +#### `render()` + +**Disponible pour :** les collections utilisant `type: 'content'` seulement +**Type :** `() => Promise` + +Une fonction pour compiler un document Markdown ou MDX donné à afficher. Cela renvoie les propriétés suivantes : + +- `` - Un composant utilisé pour restituer le contenu du document dans un fichier Astro. +- `headings` - Une liste générée de titres, [reflétant l'utilitaire `getHeadings()` d'Astro](/fr/guides/markdown-content/#propriétés-disponibles) sur les importations Markdown et MDX. +- `remarkPluginFrontmatter` - L'objet frontmatter modifié après [l'application de plugins Remark or Rehype](/fr/guides/markdown-content/#modification-programmatique-du-frontmatter). Définit sur le type `any`. + +```astro +--- +import { getEntryBySlug } from 'astro:content'; +const entry = await getEntryBySlug('blog', 'entry-1'); + +const { Content, headings, remarkPluginFrontmatter } = await entry.render(); +--- +``` + +[Consultez le guide Collections de contenu](/fr/guides/content-collections/#rendre-le-contenu-en-html) pour un exemple d'utilisation. + +### `CollectionKey` + +

+ +Une union de chaînes de caractères de tous les noms de collections définis dans votre fichier `src/content/config.*`. Ce type peut être utile lors de la définition d'une fonction générique qui accepte n'importe quel nom de collection. + +```ts +import { type CollectionKey, getCollection } from 'astro:content'; + +async function getCollection(collection: CollectionKey) { + return getCollection(collection); +} +``` + +### `ContentCollectionKey` + +

+ +Une union de chaînes de caractères de tous les noms des collections `type: 'content'` définies dans votre fichier `src/content/config.*`. + +### `DataCollectionKey` + +

+ +Une union de chaînes de caractères de tous les noms de la collection `type: 'data'` définie dans votre fichier `src/content/config.*`. + +### `SchemaContext` + +L'objet `context` que `defineCollection` utilise pour la forme de fonction du `schema`. Ce type peut être utile lors de la création de schémas réutilisables pour plusieurs collections. + +Il inclut la propriété suivante : + +- `image` - L'assistant de schéma `image()` qui vous permet [d'utiliser des images locales dans les collections de contenu](/fr/guides/images/#images-dans-les-collections-de-contenus) + +```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 }) + }), +}); +``` From 2583076f837e83f6402874334a0b85753d9f5d80 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 13:38:42 +0100 Subject: [PATCH 32/43] i18n(fr): create `reference/modules/astro-assets.mdx` (#9824) * i18n(fr): create `reference/modules/astro-assets.mdx` See #9687 and #9820 * remove extra space Co-authored-by: Thomas Bonnet --------- Co-authored-by: Thomas Bonnet Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../fr/reference/modules/astro-assets.mdx | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 src/content/docs/fr/reference/modules/astro-assets.mdx diff --git a/src/content/docs/fr/reference/modules/astro-assets.mdx b/src/content/docs/fr/reference/modules/astro-assets.mdx new file mode 100644 index 0000000000000..ef8915473c995 --- /dev/null +++ b/src/content/docs/fr/reference/modules/astro-assets.mdx @@ -0,0 +1,159 @@ +--- +title: Référence de l'API des ressources +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +Astro fournit des composants intégrés et des fonctions d'aide pour optimiser et afficher vos images. Pour des fonctionnalités et des exemples d'utilisation, [consultez notre guide d'images](/fr/guides/images/). + +## Importations depuis `astro:assets` + +```js +import { + Image, + Picture, + getImage, + } from 'astro:assets'; +``` + +### `` + +```astro title="src/components/MyComponent.astro" +--- +// importe le composant Image et l'image +import { Image } from 'astro:assets'; +import myImage from "../assets/mon_image.png"; // Image a une résolution de 1600x900 +--- + + +Une description de mon image. +``` + +```html + + +Une description de mon image. +``` +#### Propriétés + +- src (requis) +- alt (requis) +- width et height (requis pour les images dans `public/` et celles distantes) +- format +- quality +- densities +- widths + +En plus des propriétés ci-dessus, le composant `` accepte toutes les propriétés acceptées par la balise HTML ``. + +Pour en savoir plus, consultez le [Guide des images](/fr/guides/images/#image--astroassets). + +### `` + +

+ +Utilisez le composant Astro intégré `` pour afficher une image réactive avec plusieurs formats et/ou tailles. + +```astro title="src/pages/index.astro" +--- +import { Picture } from 'astro:assets'; +import myImage from "../assets/mon_image.png"; // La résolution de l'image est de 1600x900 +--- + + + +``` + +```html + + + + + Une description de mon image. + +``` + +Pour en savoir plus, consultez le [Guide des images](/fr/guides/images/#picture-). + +#### Propriétés + +`` accepte toutes les propriétés du composant `` en plus des suivantes : + +##### `formats` + +Un tableau de formats d'image à utiliser pour les balises ``. Par défaut, il est défini sur `['webp']`. + +##### `fallbackFormat` + +Format à utiliser comme valeur de repli pour la balise ``. La valeur par défaut est `.png` pour les images statiques, `.gif` pour les images animées et `.svg` pour les fichiers SVG. + +##### `pictureAttributes` + +Un objet d'attributs à ajouter à la balise ``. Utilisez cette propriété pour appliquer des attributs à l'élément externe `` lui-même. Les attributs appliqués directement au composant `` s'appliqueront à l'élément interne ``, à l'exception de ceux utilisés pour la transformation d'image. + +### `getImage()` + +

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

+ +:::caution +`getImage()` s'appuie sur des API serveur uniquement et interrompt la construction lorsqu'il est utilisé sur le client. +::: + +La fonction `getImage()` est prévue pour générer des images destinées à être utilisées ailleurs que directement en HTML, par exemple dans une [route d'API](/fr/guides/endpoints/#points-de-terminaison-du-serveur-routes-api). Elle vous permet également de créer votre propre composant `` personnalisé. + +`getImage()` prend un objet d'options avec les [mêmes propriétés que le composant Image](/fr/reference/components-reference/#propriétés) (à l'exception de `alt`). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +Elle renvoie un objet avec le type suivant : + +```ts +type GetImageResult = { + /* Attributs HTML supplémentaires nécessaires au rendu de l'image (largeur, hauteur, style, etc.) */ + attributes: Record; + /* Paramètres passés validés */ + options: ImageTransform; + /* Paramètres d'origine transmis */ + rawOptions: ImageTransform; + /* Chemin d'accès à l'image générée */ + src: string; + srcSet: { + /* Valeurs générées pour srcset, chaque entrée a une URL et un descripteur de taille */ + values: SrcSetValue[]; + /* Une valeur prête à être utilisée dans l'attribut `srcset` */ + attribute: string; + }; +} +``` From b32bde03a510fed4f3c055db9697ce3c2954bc11 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 13:46:06 +0100 Subject: [PATCH 33/43] i18n(fr): update `actions-returned-invalid-data-error.mdx` (#9832) See #9687 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- .../fr/reference/errors/actions-returned-invalid-data-error.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/fr/reference/errors/actions-returned-invalid-data-error.mdx b/src/content/docs/fr/reference/errors/actions-returned-invalid-data-error.mdx index ea4bb9f5df695..c9c55fa73bd29 100644 --- a/src/content/docs/fr/reference/errors/actions-returned-invalid-data-error.mdx +++ b/src/content/docs/fr/reference/errors/actions-returned-invalid-data-error.mdx @@ -10,4 +10,4 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ Le gestionnaire d'actions a renvoyé des données non valides. Les gestionnaires doivent renvoyer des types de données sérialisables et ne peuvent pas renvoyer un objet Response. **Voir aussi :** -- [Propriété `handler` dans la référence d'Actions](/fr/reference/api-reference/#propriété-handler) +- [Propriété `handler` dans la référence d'Actions](/fr/reference/modules/astro-actions/#propriété-handler) From 5ea394d2958962135b07246e1e7f061a8aea6789 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Mon, 28 Oct 2024 13:55:43 +0100 Subject: [PATCH 34/43] i18n(fr): update `tutorials/add-content-collections.mdx` (#9831) See #9687 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- src/content/docs/fr/tutorials/add-content-collections.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/fr/tutorials/add-content-collections.mdx b/src/content/docs/fr/tutorials/add-content-collections.mdx index 63f89816b5394..3c3c0b437c9ef 100644 --- a/src/content/docs/fr/tutorials/add-content-collections.mdx +++ b/src/content/docs/fr/tutorials/add-content-collections.mdx @@ -246,7 +246,7 @@ Les étapes ci-dessous vous montrent comment étendre le produit final du tutori ### Remplacer `Astro.glob()` avec `getCollection()` -11. Partout où vous avez une liste d'articles de blog, comme la page Blog du tutoriel (`src/pages/blog.astro/`), vous devrez remplacer `Astro.glob()` par [`getCollection()`](/fr/reference/api-reference/#getcollection) comme moyen d'extraire le contenu et les métadonnées de vos fichiers Markdown. +11. Partout où vous avez une liste d'articles de blog, comme la page Blog du tutoriel (`src/pages/blog.astro/`), vous devrez remplacer `Astro.glob()` par [`getCollection()`](/fr/reference/modules/astro-content/#getcollection) comme moyen d'extraire le contenu et les métadonnées de vos fichiers Markdown. ```astro title="src/pages/blog.astro" "post.data" "getCollection(\"posts\")" "/posts/${post.slug}/" del={7} ins={2,8} --- From 62896be0e8b5235a006248466fa9cb561a0fdf50 Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Mon, 28 Oct 2024 22:04:52 +0900 Subject: [PATCH 35/43] i18n(ja): Update middleware.mdx (#9841) * 0bad0edf9ee997a9be8ff4a4af3e4107a498a3e1 * 9052ff706e0b2eb6cfb1a2971fa53b05ebdd4156 * 58b9ed8bed27bd2f9e5decb9e4c3617f078d8b37 * 7cddce039c243322429462bf39f2599828ca6a26 * a47e02d6329e2ac5523ff5fa5098f031b8d7982a * a4fee213c6c5add423d089db2616bf57e6595f0a * Update src/content/docs/ja/guides/middleware.mdx Co-authored-by: ryu <114303361+ryuapp@users.noreply.github.com> --------- Co-authored-by: ryu <114303361+ryuapp@users.noreply.github.com> Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- src/content/docs/ja/guides/middleware.mdx | 84 +++++++++++++++++++++-- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/src/content/docs/ja/guides/middleware.mdx b/src/content/docs/ja/guides/middleware.mdx index d117b4d66bd55..1c187d5314115 100644 --- a/src/content/docs/ja/guides/middleware.mdx +++ b/src/content/docs/ja/guides/middleware.mdx @@ -4,22 +4,25 @@ description: Astroでのミドルウェアの使い方を学びます。 i18nReady: true --- import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; +import { Steps } from '@astrojs/starlight/components'; +import Since from '~/components/Since.astro'; -**ミドルウェア**により、リクエストとレスポンスをインターセプトし、ページやエンドポイントがレンダリングされる直前に動的に振る舞いを注入できます。こうしたレンダリングは、ページが事前レンダリングされる場合にはビルド時におこなわれますが、オンデマンドにレンダリングされるページの場合は、ルートへのリクエスト時におこなわれます。 +**ミドルウェア**により、リクエストとレスポンスをインターセプトし、ページやエンドポイントがレンダリングされる直前に動的に振る舞いを注入できます。こうしたレンダリングは、ページが事前レンダリングされる場合にはビルド時におこなわれますが、オンデマンドにレンダリングされるページの場合はルートへのリクエスト時におこなわれ、[クッキーやヘッダーなどの追加のSSR機能](/ja/guides/server-side-rendering/#オンデマンドレンダリングの機能)が利用できます。 また、ミドルウェアを使って、すべてのAstroコンポーネントとAPIエンドポイントで利用可能な`locals`オブジェクトを変更し、リクエスト固有の情報を各エンドポイントとページで設定・共有することもできます。このオブジェクトは、このミドルウェアがビルド時に実行される場合でも利用できます。 ## 基本的な使い方 + 1. `src/middleware.js|ts` というファイルを作成します。(あるいは、`src/middleware/index.js|ts` を作成しても構いません。) 2. このファイルの中で、[`context`オブジェクト](#contextオブジェクト)と`next()`関数を受け取る[`onRequest()`](/ja/reference/modules/astro-middleware/#onrequest)関数をエクスポートします。これをデフォルトエクスポートにしてはいけません。 ```js title="src/middleware.js" - export function onRequest ({ locals, request }, next) { + export function onRequest (context, next) { // リクエストからデータをインターセプトします // 必要に応じて、`locals`内のプロパティを改変します - locals.title = "新しいタイトル"; + context.locals.title = "新しいタイトル"; // Responseか`next()`の結果を返します return next(); @@ -35,6 +38,7 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';

{data.title}

この{data.property}はミドルウェアで設定しました。

``` +
### `context`オブジェクト @@ -55,11 +59,11 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; `locals`には、文字列、数値、さらには関数やマップといった複雑なデータ型など、どんな型のデータでも格納できます。 ```js title="src/middleware.js" -export function onRequest ({ locals, request }, next) { +export function onRequest (context, next) { // リクエストからデータをインターセプトします // 必要に応じて、`locals`内のプロパティを改変します - locals.user.name = "John Wick"; - locals.welcomeTitle = () => { + context.locals.user.name = "John Wick"; + context.locals.welcomeTitle = () => { return "おかえりなさい " + locals.user.name; }; @@ -137,7 +141,8 @@ export const onRequest = (context, next) => { `Astro.locals`内の情報に型を付け、`.astro`ファイルとミドルウェアの両コードで自動補完を有効化するには、`env.d.ts`ファイルでグローバル名前空間を宣言します。 ```ts title="src/env.d.ts" -/// +/// + declare namespace App { interface Locals { user: { @@ -193,6 +198,71 @@ authレスポンス validationレスポンス ``` +## リライト + +

+ +{/* TODO: routing.mdx の修正時に #rewrites を追加する */} +`APIContext`は、[Astro.rewrite](/ja/guides/routing/)と同じように動作する`rewrite()`メソッドを公開しています。 + +ページ閲覧者を新しいページにリダイレクトすることなく異なるページコンテンツを表示するには、ミドルウェア内で`context.rewrite()`を使用します。これにより新しいレンダリングフェーズがトリガーされ、ミドルウェアが再実行されます。 +```js title="src/middleware.js" +import { isLoggedIn } from "~/auth.js" +export function onRequest (context, next) { + if (!isLoggedIn(context)) { + // ユーザーがログインしていない場合、`/login`ルートをレンダリングするようにRequestを更新し、 + // ログイン成功後にユーザーをどこに送り返すかを示すヘッダーを追加します。 + // ミドルウェアは再実行されます。 + return context.rewrite(new Request("/login", { + headers: { + "x-redirect-to": context.url.pathname + } + })); + } + return next(); +}; +``` +また、`next()`関数にオプションのURLパスパラメータを渡すことで、新しいレンダリングフェーズを再トリガーすることなく、現在の`Request`を書き換えることができます。リライト先のパスは、文字列、URL、または`Request`として与えます。 +```js title="src/middleware.js" +import { isLoggedIn } from "~/auth.js" +export function onRequest (context, next) { + if (!isLoggedIn(context)) { + // ユーザーがログインしていない場合、`/login`ルートをレンダリングするようにRequestを更新し、 + // ログイン成功後にユーザーをどこに送り返すかを示すヘッダーを追加します。 + // 後続のミドルウェアに新しい`context`を返します。 + return next(new Request("/login", { + headers: { + "x-redirect-to": context.url.pathname + } + })); + } + return next(); +}; +``` +`next()`関数には、[Astro.rewrite()関数](/ja/reference/api-reference/#astrorewrite)と同じペイロードを渡せます。リライト先のパスは、文字列、URL、または`Request`として与えます。[sequence()](#ミドルウェアを連結する)により複数のミドルウェア関数を連結している場合、`next()`にパスを渡すと`Request`はその場で書き換えられ、ミドルウェアは再実行されません。チェーン内の次のミドルウェア関数は、更新された`context`をもつ新しい`Request`を受け取ります。 +```js title="src/middleware.js" +// 現在のURLは https://example.com/blog です + +// 最初のミドルウェア関数 +async function first(_, next) { + console.log(context.url.pathname) // これは"/blog"をログに出力します + // 新しいルートであるホームページにリライトします + // 次の関数に渡される、更新された`context`を返します + return next("/") +} + +// 現在のURLはまだ https://example.com/blog です + +// 2番目のミドルウェア関数 +async function second(context, next) { + // 更新された`context`を受け取ります + console.log(context.url.pathname) // これは"/"をログに出力します + return next() +} + +export const onRequest = sequence(first, second); +``` + ## エラーページ ミドルウェアは、オンデマンドレンダリングされるすべてのページに対して実行を試みます。これにはAstroのデフォルト(空白)の404ページや、カスタムの404ページが含まれます。ただし、そのコードが実行されるかどうかは[アダプター](/ja/guides/server-side-rendering/)によって決定されます。一部のアダプターは、プラットフォーム固有のエラーページを代わりに提供する場合があります。 From e86c8cd782dbfaf476c16e6e31f7631d5f76e5e7 Mon Sep 17 00:00:00 2001 From: Nin3 <30520689+Nin3lee@users.noreply.github.com> Date: Tue, 29 Oct 2024 11:14:14 +0800 Subject: [PATCH 36/43] i18n(zh-cn): Update `nav.ts` (#9862) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * i18n(zh-cn): Update `nav.ts` * `API 参考` => `Astro API 参考` --- src/i18n/zh-cn/nav.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/i18n/zh-cn/nav.ts b/src/i18n/zh-cn/nav.ts index a9f2d82f16386..af0f54321cf7f 100644 --- a/src/i18n/zh-cn/nav.ts +++ b/src/i18n/zh-cn/nav.ts @@ -61,14 +61,26 @@ export default NavDictionary({ 'guides/testing': '测试', 'guides/troubleshooting': '故障排除', + communityResources: '社区资源', + 'community-resources/content': '课程、指南和方案', + 'community-resources/talks': '演讲、访谈和直播', + reference: '参考', 'reference/configuration-reference': '配置', - 'reference/api-reference': 'Astro 运行时 API', 'reference/cli-reference': 'Astro 命令行', 'reference/directives-reference': '指令参考', 'reference/components-reference': '内置组件', 'guides/typescript': 'TypeScript 参考', 'reference/error-reference': '错误参考', + + 'api-reference': 'Astro API 参考', + 'reference/api-reference': 'Astro 运行时 API', + 'reference/modules/astro-actions': 'astro:actions', + 'reference/modules/astro-assets': 'astro:assets', + 'reference/modules/astro-content': 'astro:content', + 'reference/modules/astro-i18n': 'astro:i18n', + 'reference/modules/astro-middleware': 'astro:middleware', + 'reference/modules/astro-transitions': 'astro:transitions', dev: '其他开发 API', 'reference/integrations-reference': '集成 API', @@ -76,8 +88,4 @@ export default NavDictionary({ 'reference/image-service-reference': '图像服务 API', 'reference/dev-toolbar-app-reference': '开发工具栏应用 API', 'reference/container-reference': '容器 API(实验性)', - - communityResources: '社区资源', - 'community-resources/content': '课程、指南和方案', - 'community-resources/talks': '演讲、访谈和直播', }); From 8276ec8a5582f09f17f73e6f9eca5ceeff670a8e Mon Sep 17 00:00:00 2001 From: liruifengv Date: Tue, 29 Oct 2024 03:14:55 +0000 Subject: [PATCH 37/43] [ci] format --- src/i18n/zh-cn/nav.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/i18n/zh-cn/nav.ts b/src/i18n/zh-cn/nav.ts index af0f54321cf7f..4201d0acef16e 100644 --- a/src/i18n/zh-cn/nav.ts +++ b/src/i18n/zh-cn/nav.ts @@ -64,7 +64,7 @@ export default NavDictionary({ communityResources: '社区资源', 'community-resources/content': '课程、指南和方案', 'community-resources/talks': '演讲、访谈和直播', - + reference: '参考', 'reference/configuration-reference': '配置', 'reference/cli-reference': 'Astro 命令行', @@ -72,7 +72,7 @@ export default NavDictionary({ 'reference/components-reference': '内置组件', 'guides/typescript': 'TypeScript 参考', 'reference/error-reference': '错误参考', - + 'api-reference': 'Astro API 参考', 'reference/api-reference': 'Astro 运行时 API', 'reference/modules/astro-actions': 'astro:actions', From ec0f6ba2dae3a0414aea97a2d61e9ca7e93bbd05 Mon Sep 17 00:00:00 2001 From: viniciusdeliz Date: Tue, 29 Oct 2024 02:35:29 -0300 Subject: [PATCH 38/43] i18n(pt-BR): update link in `fleek.mdx` (#9861) Co-authored-by: liruifengv --- src/content/docs/pt-br/guides/deploy/fleek.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/pt-br/guides/deploy/fleek.mdx b/src/content/docs/pt-br/guides/deploy/fleek.mdx index 8cd651b5646ee..620647fe10190 100644 --- a/src/content/docs/pt-br/guides/deploy/fleek.mdx +++ b/src/content/docs/pt-br/guides/deploy/fleek.mdx @@ -75,4 +75,4 @@ Você pode publicar na Fleek através da interface do website ou usando a CLI Fl ## Saiba mais [Publique um site pela interface Fleek](https://fleek.xyz/docs/platform/deployments/) -[Publique um site pela CLI Fleek](https://fleek.xyz/docs/cli/sites/) +[Publique um site pela CLI Fleek](https://fleek.xyz/docs/cli/hosting/) From 754cbb6107dbf0ae2af10fe8ca4c841e8d3896ff Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 29 Oct 2024 12:51:24 -0300 Subject: [PATCH 39/43] reorg of images and assets guide and reference content (#9801) @lunaria-track:src/content/docs/en/**/*.mdx Co-authored-by: Fryuni <11063910+Fryuni@users.noreply.github.com> Co-authored-by: ArmandPhilippot <59021693+ArmandPhilippot@users.noreply.github.com> Co-authored-by: at-the-vr <88548999+at-the-vr@users.noreply.github.com> Co-authored-by: delucis <357379+delucis@users.noreply.github.com> --- src/content/docs/en/guides/images.mdx | 447 ++++-------------- .../guides/migrate-to-astro/from-gatsby.mdx | 4 +- .../guides/migrate-to-astro/from-nextjs.mdx | 4 +- .../guides/migrate-to-astro/from-nuxtjs.mdx | 4 +- src/content/docs/en/guides/upgrade-to/v3.mdx | 2 +- .../en/reference/components-reference.mdx | 131 +---- .../en/reference/errors/image-missing-alt.mdx | 4 +- .../errors/missing-image-dimension.mdx | 4 +- .../en/reference/errors/missing-sharp.mdx | 1 - .../en/reference/modules/astro-assets.mdx | 300 +++++++++++- .../docs/ru/reference/api-reference.mdx | 4 - .../ru/reference/errors/image-missing-alt.mdx | 4 +- .../errors/missing-image-dimension.mdx | 4 +- .../ru/reference/errors/missing-sharp.mdx | 1 - 14 files changed, 391 insertions(+), 523 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 7b1b0da800199..a126d37c82164 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -7,9 +7,12 @@ import Since from '~/components/Since.astro'; import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; import RecipeLinks from "~/components/RecipeLinks.astro"; import { Steps } from '@astrojs/starlight/components' +import ReadMore from '~/components/ReadMore.astro'; Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to from an external URL, or managed in a CMS or CDN! +See the full API reference for the [``](/en/reference/modules/astro-assets/#image-) and [``](/en/reference/modules/astro-assets/#picture-) components. + ## Where to store images ### `src/` vs `public/` @@ -22,18 +25,18 @@ Store your images in the `public/` folder if you want to avoid any processing or ### Remote images -You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. - -For extra protection when dealing with external sources, remote images will only be processed from [authorized image sources](#authorizing-remote-images) specified in your configuration. However, any remote images can be displayed. - -Astro can fetch your data remotely using APIs or display images from their full URL path. See our [CMS guides](/en/guides/cms/) for examples of integrating common services. +You can also choose to store your images remotely, in a [content management system (CMS)](/en/guides/cms/) or [digital asset management (DAM)](/en/guides/media/) platform. +Astro can fetch your data remotely using APIs or display images from their full URL path. + For extra protection when dealing with external sources, Astro's image components and helper function will only process (e.g. optimize, transform) images from [authorized image sources specified in your configuration](#authorizing-remote-images). Remote images from other sources will be displayed with no processing. ## Images in `.astro` files -In `.astro` files, **local images must be imported into the file in order to be used**. Remote and `public/` images do not require importing. +In `.astro` files, a local image must be imported from its relative path. This import provides the `src` value for your image. + +Remote and `public/` images do not require importing, and instead require a URL (full, or relative path on your site) for `src`. -Import and use Astro's built-in `` component for optimized images using `astro:assets`. Alternatively, Astro syntax supports writing an HTML `` tag directly, which skips image processing. +Import and use Astro's native [``](#display-optimized-images-with-the-image--component) and [``](#create-responsive-images-with-the-picture--component) components for optimized images. Astro syntax also supports [writing an HTML `` tag directly](#display-unprocessed-images-with-the-html-img-tag), which skips image processing. ```astro title="src/pages/blog/my-images.astro" --- @@ -49,20 +52,21 @@ import localBirdImage from '../../images/subfolder/localBirdImage.png'; A bird. ``` -To dynamically import images from the `src/` folder, see the following recipe: +See the full API reference for the [``](/en/reference/modules/astro-assets/#image-) and [``](/en/reference/modules/astro-assets/#picture-) components. -### `` (`astro:assets`) +### Display optimized images with the `` component -Use the built-in `` Astro component to display optimized versions of your local images and [configured remote images](#authorizing-remote-images). +Use the built-in `` Astro component to display optimized versions of: -Images in the `public/` folder, as well as remote images not specifically configured in your project, can also be used with the Image component, but will not be processed. +- your local images located within the `src/` folder +- [configured remote images](#authorizing-remote-images) from authorized sources -`` can transform a local or authorized remote image's dimensions, file type, and quality for control over your displayed image. The resulting `` tag includes `alt`, `loading`, and `decoding` attributes and infers image dimensions to avoid **Cumulative Layout Shift (CLS)**. +`` can transform a local or authorized remote image's dimensions, file type, and quality for control over your displayed image. The resulting `` tag includes `alt`, `loading`, and `decoding` attributes and infers image dimensions to avoid Cumulative Layout Shift (CLS). -:::tip[What is Cumulative Layout Shift?] -[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically setting the correct `width` and `height` for your local images. +:::note[What is Cumulative Layout Shift?] +[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically setting the correct `width` and `height` for your images. ::: ```astro title="src/components/MyComponent.astro" @@ -89,201 +93,11 @@ import myImage from '../assets/my_image.png'; // Image is 1600x900 /> ``` -#### Properties - -##### src (required) - -The format of the `src` value of your image file depends on where your image file is located: - -- **Local images in `src/`** - you must **also import the image** using a relative file path or configure and use an [import alias](/en/guides/imports/#aliases). Then use the import name as the `src` value: - - ```astro title="src/pages/index.astro" "myImportedImage" "{myImportedImage}" - --- - import { Image } from 'astro:assets'; - import myImportedImage from '../assets/my-local-image.png'; - --- - descriptive text - ``` - -- **Images in the `public/` folder** - use the image's **file path relative to the public folder**: - - ```astro title="src/pages/index.astro" '"/images/my-public-image.png"' - --- - import { Image } from 'astro:assets'; - --- - descriptive text - ``` - -- **Remote images** - use the image's **full URL** as the property value: - - ```astro title="src/pages/index.astro" '"https://example.com/remote-image.jpg"' - --- - import { Image } from 'astro:assets'; - --- - descriptive text - ``` - -##### alt (required) - -Use the required `alt` attribute to provide a string of [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. - -If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. +The `` component accepts [several component properties](/en/reference/modules/astro-assets/#image-properties) as well as any attributes accepted by the HTML `` tag. -##### width and height (required for images in `public/`) +The following example provides a `class` to the image component which will apply to the final `` element. -These properties define the dimensions to use for the image. - -When using images in their original aspect ratio, `width` and `height` are optional. These dimensions can be automatically inferred from image files located in `src/`. For remote images, add [the `inferSize` attribute set to `true`](#infersize) on the `` or `` component or use [`inferRemoteSize()` function](#inferremotesize). - -However, both of these properties are required for images stored in your `public/` folder as Astro is unable to analyze these files. - -##### densities - -

- -A list of pixel densities to generate for the image. - -If provided, this value will be used to generate a `srcset` attribute on the `` tag. Do not provide a value for `widths` when using this value. - -Densities that are equal to widths larger than the original image will be ignored to avoid upscaling the image. - -```astro title="src/components/MyComponent.astro" ---- -import { Image } from 'astro:assets'; -import myImage from '../assets/my_image.png'; ---- -A description of my image. -``` - -```html - -A description of my image. -``` - -##### widths - -

- -A list of widths to generate for the image. - -If provided, this value will be used to generate a `srcset` attribute on the `` tag. A [`sizes` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) must also be provided. - -Do not provide a value for `densities` when using this value. Only one of these two values can be used to generate a `srcset`. - -Widths that are larger than the original image will be ignored to avoid upscaling the image. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from '../assets/my_image.png'; // Image is 1600x900 ---- -A description of my image. -``` - -```html - -A description of my image. -``` - -##### format - -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used. - -By default, the `` component will produce a `.webp` file. - -##### quality - -`quality` is an optional property that can either be: -- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. -- a number from `0` to `100` (interpreted differently between formats). - -##### inferSize - -

- -Allows you to set the original `width` and `height` of a remote image automatically. - -By default, this value is set to `false` and you must manually specify both dimensions for your remote image. - -Add `inferSize` to the `` component (or `inferSize: true` to `getImage()`) to infer these values from the image content when fetched. This is helpful if you don't know the dimensions of the remote image, or if they might change: - -```astro mark="inferSize" ---- -import { Image } from 'astro:assets'; ---- -A cat sleeping in the sun. -``` - -`inferSize` can fetch the dimensions of a [remote image from a domain that has not been authorized](#authorizing-remote-images), however the image itself will remain unprocessed. - -###### inferRemoteSize() - -

- -A function to infer the dimensions of remote images. This can be used as an alternative to passing the `inferSize` property. - -```ts -import { inferRemoteSize } from 'astro:assets'; -const {width, height} = await inferRemoteSize("https://example.com/cat.png"); -``` - -##### Additional properties - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -For example, you can provide a `class` to the final `` element. - -```astro title="src/pages/index.astro" +```astro title="src/pages/index.astro" 'class="my-class"' --- import { Image } from 'astro:assets'; import myImage from '../assets/my_image.png'; @@ -293,7 +107,7 @@ import myImage from '../assets/my_image.png'; ``` -```html +```html 'class="my-class"' ``` -#### Setting Default Values - -Currently, there is no way to specify default values for all `` components. Required attributes should be set on each individual component. - -As an alternative, you can wrap these components in another Astro component for reuse. For example, you could create a component for your blog post images: - -```astro title="src/components/BlogPostImage.astro" ---- -import { Image } from 'astro:assets'; - -const { src, ...attrs } = Astro.props; ---- - - - -``` +:::tip +You can also use the `` component for images in the `public/` folder, or remote images not specifically configured in your project, even though these images will not be optimized or processed. The resulting image will be the same as using the HTML ``. -### `` +However, using the image component for all images provides a consistent authoring experience and prevents Cumulative Layout Shift (CLS) even for your unoptimized images. +::: +### Create responsive images with the `` component

-Use the built-in `` Astro component to display a responsive image with multiple formats and/or sizes. +Use the built-in `` Astro component to display a responsive image with multiple formats and/or sizes. ```astro title="src/pages/index.astro" --- @@ -360,65 +157,27 @@ import myImage from '../assets/my_image.png'; // Image is 1600x900 ``` -#### Properties +See details about [the `` component properties](/en/reference/modules/astro-assets/#picture-properties) in the `astro:assets` reference. -`` accepts all the properties of the `` component, plus the following: -##### `formats` +### Display unprocessed images with the HTML `` tag -An array of image formats to use for the `` tags. Entries will be added as `` elements in the order they are listed, and this order determines which format is displayed. For the best performance, list the most modern format first (e.g. `webp` or `avif`). By default, this is set to `['webp']`. +The [Astro template syntax](/en/basics/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. These images will not be processed and optimized. It accepts all HTML `` tag properties, and the only required property is `src`. -##### `fallbackFormat` +Local images must be imported from the relative path from the existing `.astro` file, or you can configure and use an [import alias](/en/guides/imports/#aliases). Then, you can access the image's `src` and other properties to use in the `` tag. -Format to use as a fallback value for the `` tag. - -Defaults to `.png` for static images (or `.jpg` if the image is a JPG), `.gif` for animated images, and `.svg` for SVG files. - -##### `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. - -```astro title="src/components/MyComponent.astro" ---- -import { Picture } from "astro:assets"; -import myImage from "../my_image.png"; // Image is 1600x900 ---- - - -``` +Imported image assets match the following signature: -```html - - - - A description of my image. - +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} ``` -### `` - -The [Astro template syntax](/en/basics/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. These images will not be processed and optimized. - -It accepts all HTML `` tag properties, and the only required property is `src`. - -#### Local images in `src/` - -Local images must be **imported from the relative path** from the existing `.astro` file, or configure and use an [import alias](/en/guides/imports/#aliases). Then, you can access the image's `src` and other properties to use in the `` tag. - -For example, use the image's own `height` and `width` properties to avoid CLS and improve Core Web Vitals. +The following example uses the image's own `height` and `width` properties to avoid Cumulative Layout Shift (CLS) and improve Core Web Vitals: ```astro title="src/pages/posts/post-1.astro" "myDog.width" "myDog.height" --- @@ -429,19 +188,8 @@ import myDog from '../../images/pets/local-dog.jpg'; A barking dog. ``` -Imported image assets match the following signature: - -```ts -interface ImageMetadata { - src: string; - width: number; - height: number; - format: string; -} -``` - #### Images in `public/` -For images located within `public/` use the image's **file path relative to the public folder** as the `src` value: +For images located within `public/` use the image's file path relative to the public folder as the `src` value: ```astro '"/images/public-cat.jpg"' A sleeping cat. @@ -449,7 +197,7 @@ For images located within `public/` use the image's **file path relative to the #### Remote images -For remote images, use the image's **full URL** as the `src` value: +For remote images, use the image's full URL as the `src` value: ```astro '"https://example.com/remote-cat.jpg"' A sleeping cat. @@ -457,13 +205,34 @@ For remote images, use the image's **full URL** as the `src` value: ### Choosing `` vs `` -The `` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS. +The `` component optimizes your image and infers width and height (for images it can process) based on the original aspect ratio to avoid CLS. It is the preferred way to use images in `.astro` files whenever possible. Use the HTML `` element when you cannot use the `` component, for example: - for unsupported image formats - when you do not want your image optimized by Astro - to access and change the `src` attribute dynamically client-side +### Setting Default Values + +Currently, there is no way to specify default values for all `` or `` components. Required attributes should be set on each individual component. + +As an alternative, you can wrap these components in another Astro component for reuse. For example, you could create a component for your blog post images that receives attributes as props and applies consistent styles to each image: + +```astro title="src/components/BlogPostImage.astro" +--- +import { Image } from 'astro:assets'; + +const { src, ...attrs } = Astro.props; +--- + + + +``` ### Authorizing remote images @@ -495,10 +264,12 @@ export default defineConfig({ ## Using Images from a CMS or CDN -Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. For image optimization with remote images, also [configure your authorized domains or URL patterns](#authorizing-remote-images). +Image CDNs work with [all Astro image options](#images-in-astro-files). Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. For image optimization with remote images, also [configure your authorized domains or URL patterns](#authorizing-remote-images). Alternatively, the CDN may provide its own SDKs to more easily integrate in an Astro project. For example, Cloudinary supports an [Astro SDK](https://astro.cloudinary.dev/) which allows you to easily drop in images with their `CldImage` component or a [Node.js SDK](https://cloudinary.com/documentation/node_integration) that can generate URLs to use with an `` tag in a Node.js environment. +See the full API reference for the [``](/en/reference/modules/astro-assets/#image-) and [``](/en/reference/modules/astro-assets/#picture-) components. + ## Images in Markdown files Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's [Image Service API](/en/reference/image-service-reference/) to optimize your local images stored in `src/`. Remote images and images stored in the `public/` folder are not optimized. @@ -521,13 +292,13 @@ Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax work ![Astro](https://example.com/images/remote-image.png) ``` -The `` tag is not supported for local images, and the `` component is unavailable in `.md` files. +The `` tag is not supported for local images, and the `` and `` components are unavailable in `.md` files. -If you require more control over your image attributes, we recommend using the `.mdx` file format, which allows you to include Astro's `` component or a JSX `` tag in addition to the Markdown syntax. Use the [MDX integration](/en/guides/integrations-guide/mdx/) to add support for MDX to Astro. +If you require more control over your image attributes, we recommend using [Astro's MDX integration](/en/guides/integrations-guide/mdx/) to add support for`.mdx` file format. MDX allows adding components to Markdown and there are additional [image options available in MDX](#images-in-mdx-files). ## Images in MDX files -You can use Astro's `` component and JSX `` tags in your `.mdx` files by importing both the component and your image. Use them just as they are [used in `.astro` files](#images-in-astro-files). +You can use Astro's `` and `` components in your `.mdx` files by importing both the component and your image. Use them just as they are [used in `.astro` files](#images-in-astro-files). The JSX `` tag is also supported for unprocessed images and [uses the same image import as the HTML `` tag](#display-unprocessed-images-with-the-html-img-tag). Additionally, there is support for [standard Markdown `![alt](src)` syntax](#images-in-markdown-files) with no import required. @@ -560,6 +331,8 @@ import rocket from '../assets/rocket.png'; ``` +See the full API reference for the [``](/en/reference/modules/astro-assets/#image-) and [``](/en/reference/modules/astro-assets/#picture-) components. + ## Images in content collections Images in content collections will be processed the same way they are in [Markdown](#images-in-markdown-files) and [MDX](#images-in-mdx-files) depending on which file type you are using. @@ -621,9 +394,26 @@ const allBlogPosts = await getCollection("blog"); ## Images in UI framework components -When adding images in a UI framework component, use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte). +The `` component, like any other Astro component, is unavailable inside UI framework components. + +But, you can pass the static content generated by `` to a framework component inside a `.astro` file as children or using a [named ``](/en/guides/framework-components/#can-i-use-astro-components-inside-my-framework-components): -Local images must **first be imported** to access their [image properties](#local-images-in-src) such as `src`. + +```astro title="src/components/ImageWrapper.astro" +--- +import ReactComponent from './ReactComponent.jsx'; +import { Image } from 'astro:assets'; +import stars from '~/stars/docline.png'; +--- + + + A starry night sky. + +``` + +You can also use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte). + +[Local images must first be imported](#display-unprocessed-images-with-the-html-img-tag) to access their image properties such as `src`. ```jsx title="src/components/ReactImage.jsx" import stars from "../assets/stars.png"; @@ -644,63 +434,14 @@ export default function ReactImage() { ``` -#### Passing the Image component - -The `` component, like any other Astro component, **is unavailable to UI framework components**. - -But, you can pass the static content generated by `` to a framework component inside a `.astro` file as children or using a [named ``](/en/guides/framework-components/#can-i-use-astro-components-inside-my-framework-components): - - -```astro title="src/components/ImageWrapper.astro" ---- -import ReactComponent from './ReactComponent.jsx'; -import { Image } from 'astro:assets'; -import stars from '~/stars/docline.png'; ---- - - - A starry night sky. - -``` - ## Generating images with `getImage()` -:::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). When you need options that the `` and `` components do not currently support, you can use the `getImage()` function to create your own custom `` component. -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. +See more in the [`getImage()` reference](/en/reference/modules/astro-assets/#getimage). -`getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`). - -```astro ---- -import { getImage } from "astro:assets"; -import myBackground from "../background.png"; - -const optimizedBackground = await getImage({src: myBackground, format: 'webp'}); ---- - -
-``` - -It returns an object with the following properties: - -```js -{ - rawOptions: {...}, // Original parameters passed - options: {...}, // Validated parameters passed - src: "...", // Path to the generated image - srcSet: { - values: [...], // Generated values for srcset, every entry has a url and a size descriptor - attribute: "", // Generated srcset attribute from the values - } - attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..) -} -``` - ## Alt Text Not all users can see images in the same way, so accessibility is an especially important concern when using images. Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. diff --git a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx index dc49d20ef5b59..1bdff9eef0436 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx @@ -320,7 +320,7 @@ See more about [Styling in Astro](/en/guides/styling/). ### Gatsby Image Plugin to Astro -Convert Gatsby's `` and `` components to [Astro's own image integration components](/en/guides/images/#image--astroassets), or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components. +Convert Gatsby's `` and `` components to [Astro's own image integration components](/en/guides/images/), or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components. ```astro title="src/pages/index.astro" --- @@ -331,7 +331,7 @@ import rocket from '../assets/rocket.png'; A rocketship in space. ``` -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Gatsby's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Gatsby's attributes. To continue using [images in Markdown (`.md`) files](/en/guides/images/#images-in-markdown-files) using standard Markdown syntax (`![]()`), you may need to update the link. Using the HTML `` tag directly is not supported in `.md` files for local images, and must be converted to Markdown syntax. diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx index 8fb638762a952..d1a962804d74a 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx @@ -422,9 +422,9 @@ See more about [Styling in Astro](/en/guides/styling/). ### Next Image Plugin to Astro -Convert any Next `` components to [Astro's own image component](/en/guides/images/#image--astroassets) in `.astro` or `.mdx` files, or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components. +Convert any Next `` components to [Astro's own image component](/en/guides/images/) in `.astro` or `.mdx` files, or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components. -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Next's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Next's attributes. ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx index b1396a9e9d385..a399b433b6f23 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx @@ -487,9 +487,9 @@ See more about [Styling in Astro](/en/guides/styling/). ### Nuxt Image Plugin to Astro -Convert any [Nuxt `` or `` components](https://image.nuxtjs.org/components/nuxt-img) to [Astro's own image component](/en/guides/images/#image--astroassets) in `.astro` or `.mdx` files, or to a [standard HTML ``](/en/guides/images/#images-in-ui-framework-components) or `` tag as appropriate in your Vue components. +Convert any [Nuxt `` or `` components](https://image.nuxtjs.org/components/nuxt-img) to [Astro's own image component](/en/guides/images/) in `.astro` or `.mdx` files, or to a [standard HTML ``](/en/guides/images/#images-in-ui-framework-components) or `` tag as appropriate in your Vue components. -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Nuxt's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Nuxt's attributes. ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 55fe269426ead..a2eeda10821aa 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -827,7 +827,7 @@ If you were using the image integration in Astro v2.x, complete the following st Change all `import` statements from `@astrojs/image/components` to `astro:assets` in order to use the new built-in `` component. - Remove any component attributes that are not [currently supported image asset properties](/en/guides/images/#properties). + Remove any component attributes that are not [currently supported image asset properties](/en/reference/modules/astro-assets/#image-properties). For example, `aspectRatio` is no longer supported, as it is now automatically inferred from the `width` and `height` attributes. diff --git a/src/content/docs/en/reference/components-reference.mdx b/src/content/docs/en/reference/components-reference.mdx index 20fae00a095f9..7e3e2322cad51 100644 --- a/src/content/docs/en/reference/components-reference.mdx +++ b/src/content/docs/en/reference/components-reference.mdx @@ -115,136 +115,7 @@ import { Prism } from '@astrojs/prism'; This component provides language-specific syntax highlighting for code blocks by applying Prism's CSS classes. Note that **you need to provide a Prism CSS stylesheet** (or bring your own) for syntax highlighting to appear! See the [Prism configuration section](/en/guides/markdown-content/#prism-configuration) for more details. -See the [list of languages supported by Prism](https://prismjs.com/#supported-languages) where you can find a language’s corresponding alias. And, you can also display your Astro code blocks with `lang="astro"`! - -## `` - -```astro title="src/components/MyComponent.astro" ---- -// import the Image component and the image -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - - -A description of my image. -``` - -```html - - -A description of my image. -``` -### Properties - -- src (required) -- alt (required) -- width and height (required for `public/` and remote images) -- format -- quality -- densities -- widths - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -See more in the [Images Guide](/en/guides/images/#image--astroassets). - -## `` - -

- -Use the built-in `` Astro component to display a responsive image with multiple formats and/or sizes. - -```astro title="src/pages/index.astro" ---- -import { Picture } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - - - -``` - -```html - - - - - A description of my image. - -``` - -See more in the [Images Guide](/en/guides/images/#picture-). - -### Properties - -`` accepts all the properties of the `` component, plus the following: - -#### `formats` - -An array of image formats to use for the `` tags. By default, this is set to `['webp']`. - -#### `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` - -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. - - -## `` - -A generic component used to render the content of a [content collection entry](/en/guides/content-collections/#what-are-content-collections). - -First, query one or more entries using `getCollection()` or `getEntry()`. Then, the `entry.render()` function can return the `` component for use in a `.astro` file template. - -```astro title="src/pages/render-example.astro" {4, 7} ---- -import { getEntry } from 'astro:content'; -const entry = await getEntry('blog', 'post-1'); -const { Content } = await entry.render(); ---- -

Published on: {entry.data.published.toDateString()}

- -``` - -## `` - -

- -Opt in to using view transitions on individual pages by importing and adding the `` routing component to `` on every desired page. - -```astro title="src/pages/index.astro" ins={2,7} ---- -import { ViewTransitions } from 'astro:transitions'; ---- - - - My Homepage - - - -

Welcome to my website!

- - -``` - -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. +See the [list of languages supported by Prism](https://prismjs.com/#supported-languages) where you can find a language’s corresponding alias. And, you can also display your Astro code blocks with `lang="astro"`. ## `` diff --git a/src/content/docs/en/reference/errors/image-missing-alt.mdx b/src/content/docs/en/reference/errors/image-missing-alt.mdx index 55d753d6a7b71..1c33c77fa7115 100644 --- a/src/content/docs/en/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/en/reference/errors/image-missing-alt.mdx @@ -22,7 +22,7 @@ If the image is merely decorative (i.e. doesn’t contribute to the understandin **See Also:** - [Images](/en/guides/images/) -- [Image component](/en/guides/images/#image--astroassets) --  [Image component#alt](/en/guides/images/#alt-required) +- [Image component](/en/reference/modules/astro-assets/#image-) +-  [Image component#alt](/en/reference/modules/astro-assets/#alt-required) diff --git a/src/content/docs/en/reference/errors/missing-image-dimension.mdx b/src/content/docs/en/reference/errors/missing-image-dimension.mdx index 1b7f30a4c74a1..8ee09b1113c3c 100644 --- a/src/content/docs/en/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/en/reference/errors/missing-image-dimension.mdx @@ -16,12 +16,12 @@ import DontEditWarning from '~/components/DontEditWarning.astro' > Missing width and height attributes for `IMAGE_URL`. When using remote images, both dimensions are required in order to avoid cumulative layout shift (CLS). ## What went wrong? -For remote images, `width` and `height` cannot automatically be inferred from the original file. To avoid cumulative layout shift (CLS), either specify these two properties, or set [`inferSize`](/en/guides/images/#infersize) to `true` to fetch a remote image's original dimensions. +For remote images, `width` and `height` cannot automatically be inferred from the original file. To avoid cumulative layout shift (CLS), either specify these two properties, or set [`inferSize`](/en/reference/modules/astro-assets/#infersize) to `true` to fetch a remote image's original dimensions. If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](/en/guides/imports/#other-assets). **See Also:** - [Images](/en/guides/images/) -- [Image component#width-and-height-required](/en/guides/images/#width-and-height-required-for-images-in-public) +- [Image component#width-and-height-required](/en/reference/modules/astro-assets/#width-and-height-required-for-images-in-public) diff --git a/src/content/docs/en/reference/errors/missing-sharp.mdx b/src/content/docs/en/reference/errors/missing-sharp.mdx index bd706ee0472fd..9fed3a6b7a09a 100644 --- a/src/content/docs/en/reference/errors/missing-sharp.mdx +++ b/src/content/docs/en/reference/errors/missing-sharp.mdx @@ -31,7 +31,6 @@ export default defineConfig({ **See Also:** - [Default Image Service](/en/guides/images/#default-image-service) -- [Image Component](/en/guides/images/#image--astroassets) - [Image Services API](/en/reference/image-service-reference/) diff --git a/src/content/docs/en/reference/modules/astro-assets.mdx b/src/content/docs/en/reference/modules/astro-assets.mdx index c041914953b16..79f36ed9122af 100644 --- a/src/content/docs/en/reference/modules/astro-assets.mdx +++ b/src/content/docs/en/reference/modules/astro-assets.mdx @@ -10,7 +10,7 @@ import ReadMore from '~/components/ReadMore.astro';

- Astro provides built-in components and helper functions for optimizing and displaying your images. For features and usage examples, [see our image guide](/en/guides/images/). +Astro provides built-in components and helper functions for optimizing and displaying your images. For features and usage examples, [see our image guide](/en/guides/images/). ## Imports from `astro:assets` @@ -19,6 +19,7 @@ import { Image, Picture, getImage, + inferRemoteSize, } from 'astro:assets'; ``` @@ -47,19 +48,222 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 alt="A description of my image." /> ``` -#### Properties -- src (required) -- alt (required) -- width and height (required for `public/` and remote images) -- format -- quality -- densities -- widths +#### Image properties -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. +The `` component accepts all properties accepted by the HTML `` tag in addition to the properties described below. -See more in the [Images Guide](/en/guides/images/#image--astroassets). +##### src (required) + +

+ +**Type:** `ImageMetadata | string | Promise<{ default: ImageMetadata }>` +

+ +The format of the `src` value of your image file depends on where your image file is located: + +- **Local images in `src/`** - you must **also import the image** using a relative file path or configure and use an [import alias](/en/guides/imports/#aliases). Then use the import name as the `src` value: + + ```astro title="src/pages/index.astro" "myImportedImage" "{myImportedImage}" + --- + import { Image } from 'astro:assets'; + import myImportedImage from '../assets/my-local-image.png'; + --- + descriptive text + ``` + +- **Images in the `public/` folder** - use the image's **file path relative to the public folder**: + + ```astro title="src/pages/index.astro" '"/images/my-public-image.png"' + --- + import { Image } from 'astro:assets'; + --- + descriptive text + ``` + +- **Remote images** - use the image's **full URL** as the property value: + + ```astro title="src/pages/index.astro" '"https://example.com/remote-image.jpg"' + --- + import { Image } from 'astro:assets'; + --- + descriptive text + ``` + +##### alt (required) + +

+ +**Type:** `string` +

+ +Use the required `alt` attribute to provide a string of [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. + +If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. + +##### width and height (required for images in `public/`) + +

+ +**Type:** `number | undefined` +

+ +These properties define the dimensions to use for the image. + +When using images in their original aspect ratio, `width` and `height` are optional. These dimensions can be automatically inferred from image files located in `src/`. For remote images, add [the `inferSize` attribute set to `true`](#infersize) on the `` or `` component or use [`inferRemoteSize()` function](#inferremotesize). + +However, both of these properties are required for images stored in your `public/` folder as Astro is unable to analyze these files. + +##### densities + +

+ +**Type:** ``(number | `${number}x`)[] | undefined``
+ +

+ +A list of pixel densities to generate for the image. + +If provided, this value will be used to generate a `srcset` attribute on the `` tag. Do not provide a value for `widths` when using this value. + +Densities that are equal to widths larger than the original image will be ignored to avoid upscaling the image. + +```astro title="src/components/MyComponent.astro" +--- +import { Image } from 'astro:assets'; +import myImage from '../assets/my_image.png'; +--- +A description of my image. +``` + +```html + +A description of my image. +``` + +##### widths + +

+ +**Type:** `number[] | undefined`
+ +

+ +A list of widths to generate for the image. + +If provided, this value will be used to generate a `srcset` attribute on the `` tag. A [`sizes` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) must also be provided. + +Do not provide a value for `densities` when using this value. Only one of these two values can be used to generate a `srcset`. + +Widths that are larger than the original image will be ignored to avoid upscaling the image. + +```astro +--- +import { Image } from 'astro:assets'; +import myImage from '../assets/my_image.png'; // Image is 1600x900 +--- +A description of my image. +``` + +```html + +A description of my image. +``` + +##### format + +

+ +**Type:** `ImageOutputFormat | undefined` +

+ +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used. + +By default, the `` component will produce a `.webp` file. + +##### quality + +

+ +**Type:** `ImageQuality | undefined` +

+ +`quality` is an optional property that can either be: +- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. +- a number from `0` to `100` (interpreted differently between formats). + +##### inferSize + +

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

+ +Allows you to set the original `width` and `height` of a remote image automatically. + +By default, this value is set to `false` and you must manually specify both dimensions for your remote image. + +Add `inferSize` to the `` component (or `inferSize: true` to `getImage()`) to infer these values from the image content when fetched. This is helpful if you don't know the dimensions of the remote image, or if they might change: + +```astro mark="inferSize" +--- +import { Image } from 'astro:assets'; +--- +A cat sleeping in the sun. +``` + +`inferSize` can fetch the dimensions of a [remote image from a domain that has not been authorized](/en/guides/images/#authorizing-remote-images), however the image itself will remain unprocessed. ### `` @@ -93,23 +297,66 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 ``` -See more in the [Images Guide](/en/guides/images/#picture-). - -#### Properties +#### Picture properties -`` accepts all the properties of the `` component, plus the following: +`` accepts all the properties of [the `` component](#image-properties), plus the following: ##### `formats` -An array of image formats to use for the `` tags. By default, this is set to `['webp']`. +

+ +**Type:** `ImageOutputFormat[]` +

+ +An array of image formats to use for the `` tags. Entries will be added as `` elements in the order they are listed, and this order determines which format is displayed. For the best performance, list the most modern format first (e.g. `webp` or `avif`). By default, this is set to `['webp']`. ##### `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. +

+ +**Type:** `ImageOutputFormat` +

+ +Format to use as a fallback value for the `` tag. Defaults to `.png` for static images (or `.jpg` if the image is a JPG), `.gif` for animated images, and `.svg` for SVG files. ##### `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. +

+ +**Type:** `HTMLAttributes<'picture'>` +

+ +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. + +```astro title="src/components/MyComponent.astro" +--- +import { Picture } from "astro:assets"; +import myImage from "../my_image.png"; // Image is 1600x900 +--- + + +``` + +```html + + + + A description of my image. + +``` ### `getImage()` @@ -124,7 +371,7 @@ An object of attributes to be added to the `` tag. Use this property to 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`). +`getImage()` takes an options object with the [same properties as the Image component](#image-properties) (except `alt`). ```astro --- @@ -157,3 +404,18 @@ type GetImageResult = { }; } ``` + +### inferRemoteSize() + +

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

+ +A function to infer the dimensions of remote images. This can be used as an alternative to passing the `inferSize` property. + +```ts +import { inferRemoteSize } from 'astro:assets'; +const {width, height} = await inferRemoteSize("https://example.com/cat.png"); +``` diff --git a/src/content/docs/ru/reference/api-reference.mdx b/src/content/docs/ru/reference/api-reference.mdx index 7928da5d011e3..149c82a996e4b 100644 --- a/src/content/docs/ru/reference/api-reference.mdx +++ b/src/content/docs/ru/reference/api-reference.mdx @@ -1780,8 +1780,6 @@ import myImage from "../assets/my_image.png"; // Изображение имее В дополнение к вышеперечисленным свойствам, компонент `` принимает все свойства, принимаемые тегом HTML ``. -Смотрите больше в [Путеводителе по изображениям](/ru/guides/images/#image--astroassets). - ### ``

@@ -1814,8 +1812,6 @@ import myImage from "../assets/my_image.png"; // Изображение имее
``` -Смотрите больше в [Путеводителе по изображениям](/ru/guides/images/#picture-). - #### Properties `` принимает все свойства компонента ``, плюс следующие: diff --git a/src/content/docs/ru/reference/errors/image-missing-alt.mdx b/src/content/docs/ru/reference/errors/image-missing-alt.mdx index 28d16cd2b0188..7f4df38a14314 100644 --- a/src/content/docs/ru/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/ru/reference/errors/image-missing-alt.mdx @@ -15,5 +15,5 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ **Смотрите также:** - [Изображения](/ru/guides/images/) -- [Компонент изображения](/ru/guides/images/#image--astroassets) -- [Компонент изображения#alt](/ru/guides/images/#alt-required) +- [Компонент изображения](/ru/reference/modules/astro-assets/#image-) +- [Компонент изображения#alt](/ru/reference/modules/astro-assets/#alt-required) diff --git a/src/content/docs/ru/reference/errors/missing-image-dimension.mdx b/src/content/docs/ru/reference/errors/missing-image-dimension.mdx index e22c7589f252c..b0c52db4228cc 100644 --- a/src/content/docs/ru/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/ru/reference/errors/missing-image-dimension.mdx @@ -8,12 +8,12 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ ## Что пошло не так? -Для внешних изображений `width` и `height` не могут быть автоматически определены из исходного файла. Чтобы избежать кумулятивного сдвига макета (CLS), либо укажите эти два свойства, либо установите [`inferSize`](/ru/guides/images/#infersize) в `true`, чтобы получить оригинальные размеры удаленного изображения. +Для внешних изображений `width` и `height` не могут быть автоматически определены из исходного файла. Чтобы избежать кумулятивного сдвига макета (CLS), либо укажите эти два свойства, либо установите [`inferSize`](/ru/reference/modules/astro-assets/#infersize) в `true`, чтобы получить оригинальные размеры удаленного изображения. Если ваше изображение находится в папке `src`, то вы, вероятно, хотели импортировать его. См. [руководство по импорту](/ru/guides/imports/#other-assets) для получения дополнительной информации. **Смотрите также:** - [Изображения](/ru/guides/images/) -- [Компонент изображения#width-and-height-required](/ru/guides/images/#width-and-height-required-for-images-in-public) +- [Компонент изображения#width-and-height-required](/ru/reference/modules/astro-assets/#width-and-height-required-for-images-in-public) diff --git a/src/content/docs/ru/reference/errors/missing-sharp.mdx b/src/content/docs/ru/reference/errors/missing-sharp.mdx index d37cd00fb0dc0..474208ae3d9ea 100644 --- a/src/content/docs/ru/reference/errors/missing-sharp.mdx +++ b/src/content/docs/ru/reference/errors/missing-sharp.mdx @@ -24,6 +24,5 @@ export default defineConfig({ **Смотрите также:** - [Служба изображений по умолчанию](/ru/guides/images/#default-image-service) -- [Компонент изображения](/ru/guides/images/#image--astroassets) - [API службы изображений](/ru/reference/image-service-reference/) From 92ae041063bd0dd7bab3e75339652db0316a8677 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Tue, 29 Oct 2024 17:03:06 +0100 Subject: [PATCH 40/43] i18n(fr): create `reference/modules/astro-middleware.mdx` (#9828) * i18n(fr): create `reference/modules/astro-middleware.mdx` See #9687 * translate comment Co-authored-by: Thomas Bonnet * translate missing sentence Co-authored-by: Thomas Bonnet --------- Co-authored-by: Thomas Bonnet Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> --- .../fr/reference/modules/astro-middleware.mdx | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/content/docs/fr/reference/modules/astro-middleware.mdx diff --git a/src/content/docs/fr/reference/modules/astro-middleware.mdx b/src/content/docs/fr/reference/modules/astro-middleware.mdx new file mode 100644 index 0000000000000..d799a66783b31 --- /dev/null +++ b/src/content/docs/fr/reference/modules/astro-middleware.mdx @@ -0,0 +1,122 @@ +--- +title: Référence de l'API Middleware +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 6 +--- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; + +

+ +Un middleware vous permet d'intercepter les requêtes et les réponses et d'injecter des comportements de manière dynamique chaque fois qu'une page ou un point de terminaison est sur le point d'être rendu. Pour les fonctionnalités et les exemples d'utilisation, [consultez notre guide Middleware](/fr/guides/middleware/). + +## Importations depuis `astro:middleware` + +```js +import { + sequence, + createContext, + trySerializeLocals, + defineMiddleware, + } from 'astro:middleware'; +``` + +### `defineMiddleware()` + +Vous pouvez importer et utiliser la fonction utilitaire `defineMiddleware()` pour bénéficier de la sûreté du typage : + +```ts +// src/middleware.ts +import { defineMiddleware } from "astro:middleware"; + +// `context` et `next` sont automatiquement saisis +export const onRequest = defineMiddleware((context, next) => { + +}); +``` + +### `sequence()` + +

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

+ +Une fonction qui accepte les fonctions middleware comme arguments et les exécutera dans l'ordre dans lequel elles sont transmises. + +```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`
+ +

+ +Une API de bas niveau pour créer un objet [`APIContext`](/fr/reference/api-reference/#contexte-du-point-de-terminaison) à transmettre à une fonction `onRequest()` du middleware Astro. + +Cette fonction peut être utilisée par les intégrations/adaptateurs pour exécuter par programmation le middleware Astro. + +### `trySerializeLocals()` + +

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

+ +Une API de bas niveau qui prend n'importe quelle valeur et tente d'en renvoyer une version sérialisée (une chaîne de caractères). Si la valeur ne peut pas être sérialisée, la fonction générera une erreur d'exécution. + +## Middleware exports + +Lors de la définition du middleware de votre projet dans `src/middleware.js`, il exporte les fonctions définies par l'utilisateur suivantes : + +### `onRequest()` + +**Type :** `(context: APIContext, next: MiddlewareNext) => Promise | Response | Promise | void` + +Une fonction exportée requise depuis `src/middleware.js` qui sera appelée avant le rendu de chaque page ou route API. Elle reçoit deux arguments : [context](#context) et [next()](#next). `onRequest()` doit renvoyer une réponse (`Response`) : soit directement, soit en appelant `next()`. + +```js title="src/middleware.js" +export function onRequest (context, next) { + // intercepte les données de réponse d'une requête + // éventuellement, transforme la réponse + // renvoie directement une réponse, ou le résultat de l'appel de `next()` + return next(); +}; +``` + +Votre fonction `onRequest()` sera appelée avec les arguments suivants : + +#### `context` + +

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

+ +Le premier argument de `onRequest()` est un objet de contexte. Il reflète de nombreuses propriétés globales d'`Astro`. + +Consultez [Contextes de point de terminaison](/fr/reference/api-reference/#contexte-du-point-de-terminaison) pour plus d'informations sur l'objet de contexte. + +#### `next()` + +

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

+ +Le deuxième argument de `onRequest()` est une fonction qui appelle tous les middlewares suivants de la chaîne et renvoie une `Response`. Par exemple, un autre middleware pourrait modifier le corps HTML d'une réponse et attendre le résultat de `next()` permettrait à votre middleware de répondre à ces modifications. + +Depuis Astro v4.13.0, `next()` accepte un paramètre de chemin d'URL facultatif sous la forme d'une chaîne de caractères, d'une `URL` ou d'un objet `Request` pour [réécrire](/fr/guides/routing/#réécritures) la requête actuelle sans déclencher une nouvelle phase de rendu. From 0532be62b3c65c3d71189920370c5a9d67cdccdd Mon Sep 17 00:00:00 2001 From: t0yohei <30691457+t0yohei@users.noreply.github.com> Date: Wed, 30 Oct 2024 01:16:33 +0900 Subject: [PATCH 41/43] i18n(ja): Add media.mdx (#9855) * i18n(ja): Add media.mdx * i18n(ja): Update hosted media and other translations --------- Co-authored-by: t0yohei Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: morinokami <7889778+morinokami@users.noreply.github.com> --- src/content/docs/ja/guides/media.mdx | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/content/docs/ja/guides/media.mdx diff --git a/src/content/docs/ja/guides/media.mdx b/src/content/docs/ja/guides/media.mdx new file mode 100644 index 0000000000000..b3a03f5e78a52 --- /dev/null +++ b/src/content/docs/ja/guides/media.mdx @@ -0,0 +1,39 @@ +--- +title: AstroでDAMを使う +description: デジタルアセットマネージャー(DAM)を使ってAstroに画像や動画を追加する方法 +i18nReady: true +--- +import MediaGuidesNav from '~/components/MediaGuidesNav.astro'; +import ReadMore from '~/components/ReadMore.astro'; +import Badge from "~/components/Badge.astro" + + +**Astroプロジェクトにヘッドレスデジタルアセットマネージャー(DAM)を接続する準備はできましたか?** このガイドに従って、ホステッドメディアシステム(hosted media systems)を組み込みましょう。 + +:::tip +DAMまたはホステッドメディアシステムをプロジェクトに接続するために、インテグレーションディレクトリで[コミュニティ製のインテグレーション](https://astro.build/integrations/)を探してみましょう。 +::: + +## ホステッドメディアガイド + +各ページの多くは**未完成**なので注意してください。未完成のページへの貢献をお待ちしています! + + + +## なぜ DAM やホステッドメディアを使うのか? + +DAM(デジタルアセットマネージャー)を使用することで、個人やチーム、組織は[CMS](/ja/guides/cms/)と同じように画像やビデオのアセットを一元管理することができます。 + +違いは管理するコンテンツの種類です。DAMは主に画像や動画、そして3Dモデルのようなその他のメディアアセット、またそれらのアセットに関連するメタデータを管理します。 + +これは、特に複数のウェブやモバイルプロパティ間でアセットを信頼できる唯一の情報源とする場合に便利です。このことは、複数のチームが同じアセットを使用する必要がある組織に属している場合や、PIM(商品情報マネージャー)のような他のコンテンツシステムに統合してアセットを製品に関連付ける場合に重要です。 + +## Astroと相性の良いホステッドメディアシステムやDAMは? + +CMSを使用するときと同じように、Astroはコンテンツの _表示_ を担うので、APIやSDKを介してアセットを取得し、やり取りできるヘッドレスDAMの使用をお勧めします。 + +CloudinaryのようないくつかのヘッドレスDAMはAstroの[インテグレーション](/ja/guides/integrations-guide/)を提供しており、アセットを簡単に取得し、ウェブサイトやアプリに表示することができます。 + +## ホステッドメディアシステムやDAMなしでAstroを使用できますか? + +はい!Astroにはリモート画像を参照するためのサポートを含んだ、[画像の保存](/ja/guides/images/#画像を保存する場所)方法が組み込まれています。 From a50bf4ca75610da2da2e3a50b0236bb190fe44b0 Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Tue, 29 Oct 2024 17:24:09 +0100 Subject: [PATCH 42/43] i18n(fr): update link in `guides/deploy/fleek.mdx` (#9856) See #9800 Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- src/content/docs/fr/guides/deploy/fleek.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/fr/guides/deploy/fleek.mdx b/src/content/docs/fr/guides/deploy/fleek.mdx index cb040209f92c1..60f8f3ad7a712 100644 --- a/src/content/docs/fr/guides/deploy/fleek.mdx +++ b/src/content/docs/fr/guides/deploy/fleek.mdx @@ -75,4 +75,4 @@ Vous pouvez déployer vers Fleek via l’interface utilisateur du site web ou en ## En savoir plus [Déployer votre site depuis l'interface utilisateur Fleek](https://fleek.xyz/docs/platform/deployments/) -[Déployer votre site depuis Fleek CLI](https://fleek.xyz/docs/cli/sites/) +[Déployer votre site depuis Fleek CLI](https://fleek.xyz/docs/cli/hosting/) From 1b254a36d2c0254d384ea511984fe7e156eb78da Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Tue, 29 Oct 2024 17:32:50 +0100 Subject: [PATCH 43/43] i18n(fr): update `guides/markdown-content.mdx` (#9834) * i18n(fr): update `guides/markdown-content.mdx` See #9687 * update anchor as well --------- Co-authored-by: Yan <61414485+yanthomasdev@users.noreply.github.com> Co-authored-by: thomasbnt <14293805+thomasbnt@users.noreply.github.com> --- src/content/docs/fr/guides/markdown-content.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/fr/guides/markdown-content.mdx b/src/content/docs/fr/guides/markdown-content.mdx index 12f601c4d8dd3..a4fbcf3fe36d3 100644 --- a/src/content/docs/fr/guides/markdown-content.mdx +++ b/src/content/docs/fr/guides/markdown-content.mdx @@ -61,7 +61,7 @@ const posts = Object.values(await import.meta.glob('../posts/*.md', { eager: tru Lorsque vous récupérez des données de vos collections via des fonctions d'aide, les propriétés de votre document Markdown sont disponibles dans un objet `data` (par exemple `post.data.title`). De plus, `body` contient le contenu brut, non compilé, sous forme de chaîne de caractères. -Voir le [Type des entrées de collection](/fr/reference/api-reference/#type-des-entrées-de-collection) complet. +Voir le [Type des entrées de collection](/fr/reference/modules/astro-content/#collectionentry) complet. #### Importation de Markdown