Skip to content

Commit

Permalink
Merge branch 'v3-upgrade-guide' into cookies-updates
Browse files Browse the repository at this point in the history
  • Loading branch information
TheOtterlord committed Aug 22, 2023
2 parents a9f72f6 + 20f3664 commit bae891d
Show file tree
Hide file tree
Showing 16 changed files with 631 additions and 59 deletions.
44 changes: 24 additions & 20 deletions src/content/docs/es/reference/image-service-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ Ambos tipos de serivicios pueden proporcionar `getHTMLAttributes()` para determi
Un servicio externo apunta a una URL remota para ser usada como el atributo `src` de la etiqueta `<img>`. Esta URL remota es responsable de descargar, transformar y devolver la imagen.

```js
import type { ExternalImageService } from "astro";
import type { ExternalImageService, ImageTransform, AstroConfig } from "astro";

const service: ExternalImageService = {
validateOptions(options: ImageTransform, serviceConfig: Record<string, any>) {
validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']) {
const serviceConfig = imageConfig.service.config;
// Aplica el ancho máximo establecido por el usuario.
if (options.width > serviceConfig.maxWidth) {
console.warn(`El ancho de la imagen ${options.width} excede el ancho máximo ${serviceConfig.maxWidth}. Se utilizará el ancho máximo como alternativa.`);
Expand All @@ -43,10 +44,10 @@ const service: ExternalImageService = {

return options;
},
getURL(options, serviceConfig) {
getURL(options, imageConfig) {
return `https://mysupercdn.com/${options.src}?q=${options.quality}&w=${options.width}&h=${options.height}`;
},
getHTMLAttributes(options, serviceConfig) {
getHTMLAttributes(options, imageConfig) {
const { src, format, quality, ...attributes } = options;
return {
...attributes,
Expand All @@ -65,9 +66,10 @@ export default service;
Para crear tu propio servicio local, puedes apuntar al [endpoint integrado](https://github.com/withastro/astro/blob/main/packages/astro/src/assets/image-endpoint.ts) (`/_image`) o puedes crear tu propio endpoint que pueda llamar a los métodos del servicio.
```js
import type { LocalImageService } from "astro";
import type { LocalImageService, AstroConfig } from "astro";

const service: LocalImageService = {
getURL(options: ImageTransform, serviceConfig: Record<string, any>) {
getURL(options: ImageTransform, imageConfig: AstroConfig['image']) {
const searchParams = new URLSearchParams();
searchParams.append('href', typeof options.src === "string" ? options.src : options.src.src);
options.width && searchParams.append('w', options.width.toString());
Expand All @@ -78,7 +80,7 @@ const service: LocalImageService = {
// O usa el endpoint integrado, el cual llamará a tus funciones parseURL y transform:
// return `/_image?${searchParams}`;
},
parseURL(url: URL, serviceConfig) {
parseURL(url: URL, imageConfig) {
return {
src: params.get('href')!,
width: params.has('w') ? parseInt(params.get('w')!) : undefined,
Expand All @@ -87,14 +89,14 @@ const service: LocalImageService = {
quality: params.get('q'),
};
},
transform(buffer: Buffer, options: { src: string, [key: string]: any }, serviceConfig): { data: Buffer, format: OutputFormat } {
transform(buffer: Buffer, options: { src: string, [key: string]: any }, imageConfig): { data: Buffer, format: OutputFormat } {
const { buffer } = mySuperLibraryThatEncodesImages(options);
return {
data: buffer,
format: options.format,
};
},
getHTMLAttributes(options, serviceConfig) {
getHTMLAttributes(options, imageConfig) {
let targetWidth = options.width;
let targetHeight = options.height;
if (typeof options.src === "object") {
Expand Down Expand Up @@ -125,20 +127,22 @@ En el tiempo de compilación para sitios estáticos y rutas pre-renderizadas, ta
En el modo de desarrollo y el modo SSR, Astro no sabe de antemano qué imágenes deben ser optimizadas. Astro usa un endpoint GET (por defecto, `/_image`) para procesar las imágenes en tiempo de ejecución. `<Image />` y `getImage()` pasan sus opciones a `getURL()`, que devolverá la URL del endpoint. Luego, el endpoint llama a `parseURL()` y pasa las propiedades resultantes a `transform()`.
#### getConfiguredImageService y imageServiceConfig
#### getConfiguredImageService & imageConfig
Si implementas tu propio endpoint como un endpoint de Astro, puedes usar `getConfiguredImageService` y `imageConfg` para llamar a los métodos `parseURL` y `transform` de tu servicio y proporcionar la configuración de la imagen.
Si implementas tu propio endpoint como un endpoint de Astro, puedes usar `getConfiguredImageService` y `imageServiceConfig` para llamar a los métodos `parseURL` y `transform` de tu servicio y proporcionar el objeto de configuración del servicio.
Para acceder a la configuración del servicio de imágenes ([`image.service.config`](/es/reference/configuration-reference/#imageservice-experimental)), puedes usar `imageConfig.service.config`.
```ts title="src/api/my_custom_endpoint_that_transforms_images.ts"
import type { APIRoute } from "astro";
import { getConfiguredImageService, imageServiceConfig } from 'astro:assets';
import { getConfiguredImageService, imageConfig } from 'astro:assets';

export const get: APIRoute = async ({ request }) => {
const imageService = await getConfiguredImageService();

const imageTransform = imageService.parseURL(new URL(request.url), imageServiceConfig);
const imageTransform = imageService.parseURL(new URL(request.url), imageConfig);
// ... busca la imagen de imageTransform.src y guárdala en inputBuffer
const { data, format } = await imageService.transform(inputBuffer, imageTransform, imageServiceConfig);
const { data, format } = await imageService.transform(inputBuffer, imageTransform, imageConfig);
return new Response(data, {
status: 200,
headers: {
Expand All @@ -158,7 +162,7 @@ export const get: APIRoute = async ({ request }) => {
**Requerido para servicios locales y externos**
`getURL(options: ImageTransform, imageServiceConfig: Record<string, any>): string`
`getURL(options: ImageTransform, imageConfig: AstroConfig['image']): string`
Para servicios locales, este hook devuelve la URL del endpoint que genera tu imagen (en SSR y modo de desarrollo). No se usa durante la compilación. El endpoint local al que apunta `getURL()` puede llamar tanto a `parseURL()` como a `transform()`.
Expand All @@ -169,7 +173,7 @@ Para ambos tipos de servicios, `options` son las propiedades pasadas por el usua
```ts
export type ImageTransform = {
// Imágenes importadas ESM | rutas de imágenes remotas/públicas
src: ImageAsset | string;
src: ImageMetadata | string;
width?: number;
height?: number;
quality?: ImageQuality;
Expand All @@ -184,15 +188,15 @@ export type ImageTransform = {
**Requerido para servicios locales; no disponible para servicios externos**
`parseURL(url: URL, imageServiceConfig: Record<string, any>): { src: string, [key: string]: any}`
`parseURL(url: URL, imageConfig: AstroConfig['image']): { src: string, [key: string]: any}`
Este hook analiza las URL generadas por `getURL()` en un objeto con las diferentes propiedades que se utilizarán en `transform` (en SSR y modo de desarrollo). No se usa durante la compilación.
### `transform()`
**Requerido para servicios locales; no disponible para servicios externos**
`transform(buffer: Buffer, options: { src: string, [key: string]: any }, imageServiceConfig: Record<string, any>): { data: Buffer, format: OutputFormat }`
`transform(buffer: Buffer, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']): { data: Buffer, format: OutputFormat }`
Este hook transforma y devuelve la imagen y se llama durante la compilación para crear los archivos de activos finales.
Expand All @@ -202,15 +206,15 @@ Debes devolver un `format` para asegurarte de que se sirve el tipo MIME adecuado
**Opcional para ambos servicios locales y externos**
`getHTMLAttributes(options: ImageTransform, imageServiceConfig: Record<string, any>): Record<string, any>`
`getHTMLAttributes(options: ImageTransform, imageConfig: AstroConfig['image']): Record<string, any>`
Este hook devuelve todos los atributos adicionales utilizados para renderizar la imagen como HTML, basados en los parámetros pasados por el usuario (`options`).
### `validateOptions()`
**Opcional para ambos servicios locales y externos**
`validateOptions(options: ImageTransform, imageServiceConfig: Record<string, any>): ImageTransform`
`validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']): ImageTransform`
Este hook te permite validar y aumentar las opciones pasadas por el usuario. Esto es útil para establecer opciones predeterminadas, o para decirle al usuario que un parámetro es obligatorio.
Expand Down
176 changes: 176 additions & 0 deletions src/content/docs/ja/core-concepts/astro-syntax.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
---
title: Astroの構文
description: .astroコンポーネント構文の紹介。
i18nReady: true
---

**HTMLを知っていれば、最初のAstroコンポーネントを書くには十分です。**

Astroコンポーネントの構文はHTMLのスーパーセットです。この構文は[HTMLやJSXを書いたことのある人にとって親しみやすいように設計され](#astroとjsxの違い)、コンポーネントやJavaScriptの式がサポートされています。

## JSXライクな式

Astroコンポーネントのフロントマターのコードフェンス(`---`)の間に、JavaScriptのローカル変数を定義できます。そして、JSXライクな式を使って、変数をコンポーネントのHTMLテンプレートに注入できます。

:::note[動的 vs リアクティブ]
この方法により、フロントマターで計算された**動的**な値をテンプレートに含めることができます。しかし、一度含められたこれらの値は**リアクティブ**ではなく、変化することはありません。Astroコンポーネントは、レンダリングの際に一度だけ実行されるテンプレートです。

以下で[AstroとJSXの違い](#astroとjsxの違い)に関する例をいくつか紹介します。
:::

### 変数

ローカル変数は、波括弧の構文を使ってHTMLに追加できます。

```astro title="src/components/Variables.astro" "{name}"
---
const name = "Astro";
---
<div>
<h1>Hello {name}!</h1> <!-- <h1>Hello Astro!</h1> を出力 -->
</div>
```

### 動的属性

ローカル変数を波括弧で囲むことで、HTML要素とコンポーネントの両方に属性値を渡せます。

```astro title="src/components/DynamicAttributes.astro" "{name}" "${name}"
---
const name = "Astro";
---
<h1 class={name}>属性を式で指定できます</h1>
<MyComponent templateLiteralNameAttribute={`私の名前は${name}です`} />
```

:::caution
HTML属性は文字列に変換されるため、関数やオブジェクトをHTML要素に渡すことはできません。たとえば、Astroコンポーネント内のHTML要素にイベントハンドラを割り当てることはできません。

```astro
---
// dont-do-this.astro
function handleClick () {
console.log("ボタンがクリックされました!");
}
---
<!-- ❌ これは動作しません! ❌ -->
<button onClick={handleClick}>クリックしても何も起こりません!</button>
```

代わりに、通常のJavaScriptと同じように、クライアントサイドスクリプトを使用してイベントハンドラを追加します。

```astro
---
// do-this-instead.astro
---
<button id="button">クリックしてください</button>
<script>
function handleClick () {
console.log("ボタンがクリックされました!");
}
document.getElementById("button").addEventListener("click", handleClick);
</script>
```
:::

### 動的HTML

ローカル変数をJSXのような関数で使用して、動的に生成されるHTML要素を作成できます。

```astro title="src/components/DynamicHtml.astro" "{item}"
---
const items = ["犬", "猫", "カモノハシ"];
---
<ul>
{items.map((item) => (
<li>{item}</li>
))}
</ul>
```

Astroは、JSXと同様に論理演算子と三項演算子を使用して、HTMLを条件に応じて表示できます。

```astro title="src/components/ConditionalHtml.astro" "visible"
---
const visible = true;
---
{visible && <p>表示!</p>}
{visible ? <p>表示!</p> : <p>あるいはこちらを表示!</p>}
```

### 動的タグ

HTMLタグ名またはインポートされたコンポーネントを変数に設定することで、動的タグも使用できます。

```astro title="src/components/DynamicTags.astro" /Element|(?<!My)Component/
---
import MyComponent from "./MyComponent.astro";
const Element = 'div'
const Component = MyComponent;
---
<Element>Hello!</Element> <!-- <div>Hello!</div> としてレンダリングされます -->
<Component /> <!-- <MyComponent /> としてレンダリングされます -->
```

動的タグを使用する場合は、以下の点に注意してください。

- **変数名は大文字で始める必要があります。** たとえば、`element`ではなく`Element`を使用します。そうしないと、Astroは変数名をそのままHTMLタグとしてレンダリングしようとします。

- **ハイドレーションディレクティブは使えません。**[`client:*`ハイドレーションディレクティブ](/ja/core-concepts/framework-components/#インタラクティブなコンポーネント)を使用する場合、Astroはバンドルする対象のコンポーネントを知る必要がありますが、動的タグパターンではこれが機能しなくなるためです。

### フラグメント

Astroでは、`<Fragment> </Fragment>`または短縮形の`<> </>`を使用できます。

フラグメントは、次の例のように、[`set:*`ディレクティブ](/ja/reference/directives-reference/#sethtml)を使用する際にラッパー要素を避けるために役立ちます。

```astro title="src/components/SetHtml.astro" "Fragment"
---
const htmlString = '<p>生のHTMLコンテンツ</p>';
---
<Fragment set:html={htmlString} />
```

### AstroとJSXの違い

Astroコンポーネントの構文はHTMLのスーパーセットです。HTMLやJSXを書いたことのある人にとって親しみやすいように設計されてはいますが、`.astro`ファイルとJSXの間にはいくつかの重要な違いがあります。

#### 属性

Astroでは、JSXで使用されている`camelCase`ではなく、すべてのHTML属性に標準の`kebab-case`形式を使用します。これは、Reactではサポートされていない`class`でも同様です。

```jsx del={1} ins={2} title="example.astro"
<div className="box" dataValue="3" />
<div class="box" data-value="3" />
```

#### 複数の要素

Astroコンポーネントテンプレートは複数の要素をレンダリングできます。その際、JavaScriptやJSXとは異なり、全体を単一の`<div>``<>`で囲む必要はありません。

```astro title="src/components/RootElements.astro"
---
// 複数の要素を含むテンプレート
---
<p>全体をコンテナ要素で囲む必要はありません。</p>
<p>Astroではテンプレート内に複数のルート要素を置けます。</p>
```

#### コメント

Astroでは、標準のHTMLコメントまたはJavaScriptスタイルのコメントを使用できます。

```astro title="example.astro"
---
---
<!-- .astroファイルでは、HTMLのコメント構文が使えます -->
{/* JSのコメント構文も有効です */}
```

:::caution
HTMLスタイルのコメントはブラウザのDOMに含まれますが、JSのコメントはスキップされます。TODOメッセージやその他の開発専用の説明を残したい場合は、JavaScriptスタイルのコメントを使用することをお勧めします。
:::


2 changes: 1 addition & 1 deletion src/content/docs/ja/guides/troubleshooting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Astroテンプレートにインポートして使用しているコンポーネ
それから、import文を確認してください。

- インポートのリンク先が違っていませんか?(importパスを確認してください)
- インポートしたコンポーネントと同じ名前になっていますか?(コンポーネント名と、[`.Astro`構文にしたがっていること](/ja/core-concepts/astro-syntax/#differences-between-astro-and-jsx)を確認してください。)
- インポートしたコンポーネントと同じ名前になっていますか?(コンポーネント名と、[`.Astro`構文にしたがっていること](/ja/core-concepts/astro-syntax/#astroとjsxの違い)を確認してください。)
- インポート時に拡張子が含まれていますか?(インポートしたファイルに拡張子が含まれているか確認してください。例: `.Astro``.md``.vue``.svelte`。 注: `.js(x)``.ts(x)`のファイルのみ、拡張子は必要ありません。)

### コンポーネントがインタラクティブでない
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
title: Astro.clientAddress is not available in current adapter.
i18nReady: true
githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts
---

> **ClientAddressNotAvailable**: `Astro.clientAddress``ADAPTER_NAME`アダプターでは利用できません。アダプターにサポートを追加するためにIssueを作成してください。
## 何が問題か?

使用しているアダプターは、`Astro.clientAddress`をサポートしていません。

**以下も参照してください:**
- [公式インテグレーション](/ja/guides/integrations-guide/#公式インテグレーション)
- [Astro.clientAddress](/ja/reference/api-reference/#astroclientaddress)


Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
title: No static path found for requested path.
i18nReady: true
githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts
---

> **NoMatchingStaticPathFound**: `getStaticPaths()`のルーティングパターンがマッチしましたが、リクエストされたパス`PATH_NAME`に対応する静的パスが見つかりませんでした。
## 何が問題か?

[動的ルーティング](/ja/core-concepts/routing/#動的ルーティング)がマッチしましたが、リクエストされたパラメーターに対応するパスが見つかりませんでした。これは多くの場合、生成されたパスまたはリクエストされたパスのどちらかにタイポがあることが原因です。

**以下も参照してください:**
- [getStaticPaths()](/ja/reference/api-reference/#getstaticpaths)


Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: Invalid type returned by Astro page.
i18nReady: true
githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts
---

> ルーティングで`RETURNED_VALUE`が返されました。AstroファイルからはResponseのみ返せます。
## 何が問題か?

Astroファイル内で返せるのは[Response](https://developer.mozilla.org/ja/docs/Web/API/Response)のインスタンスのみです。

```astro title="pages/login.astro"
---
return new Response(null, {
status: 404,
statusText: 'Not found'
});
// または、リダイレクトの場合、Astro.redirectもResponseのインスタンスを返します
return Astro.redirect('/login');
---
```

**以下も参照してください:**
- [Response](/ja/guides/server-side-rendering/#response)


Loading

0 comments on commit bae891d

Please sign in to comment.