Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tutorialの一部翻訳 #39

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
title: Inspecting state
---

It's often useful to be able to track the value of a piece of state as it changes over time.
時間の経過とともに変化する状態の値を追跡できることは、多くの場合便利です。

Inside the `addNumber` function, we've added a `console.log` statement. But if you click the button and open the console drawer (using the button to the right of the URL bar), you'll see a warning, and a message saying the message could not be cloned.
今回は`addNumber` 関数内に `console.log` ステートメントを追加しました。ただし、ボタンをクリックした後にDevコンソールを開くと、警告と、メッセージを複製できなかったというメッセージが表示されます。

That's because `numbers` is a reactive [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). There are a couple of things we can do. Firstly, we can create a non-reactive _snapshot_ of the state with `$state.snapshot(...)`:
これは、`numbers` がリアクティブ [プロキシ](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Proxy) であるためです。できることはいくつかあります。まず、`$state.snapshot(...)` を使用して、状態の非リアクティブ _スナップショット_ を作成できます。

```js
/// file: App.svelte
Expand All @@ -16,7 +16,7 @@ function addNumber() {
}
```

Alternatively, we can use the `$inspect` rune to automatically log a snapshot of the state whenever it changes. This code will automatically be stripped out of your production build:
あるいは、`$inspect` ルーンを使用して、状態が変化するたびにそのスナップショットを自動的に記録することもできます。このコードは、プロダクションビルドから自動的に削除されます。

```js
/// file: App.svelte
Expand All @@ -28,7 +28,7 @@ function addNumber() {
+++$inspect(numbers);+++
```

You can customise how the information is displayed by using `$inspect(...).with(fn)` — for example, you can use `console.trace` to see where the state change originated from:
`$inspect(...).with(fn)` を使用すると、情報の表示方法をカスタマイズできます。たとえば、`console.trace` を使用して、状態の変化の発生元を確認できます。

```js
/// file: App.svelte
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
title: Effects
---

So far we've talked about reactivity in terms of state. But that's only half of the equation — state is only reactive if something is _reacting_ to it, otherwise it's just a sparkling variable.
これまで、状態の観点から反応性について説明してきました。しかし、それは物事のまだ半分( _half of the equation_ )に過ぎません。状態は、何かがそれに _反応している場合_ にのみ反応性があり、そうでない場合は単なる特殊な変数( _sparkling variable_ )です。

The thing that reacts is called an _effect_. You've already encountered effects — the ones that Svelte creates on your behalf to update the DOM in response to state changes — but you can also create your own with the `$effect` rune.
反応するものは _effect_ と呼ばれます。すでにエフェクト (状態の変化に応じて DOM を更新するために Svelte が作成するエフェクト) について説明しましたが、`$effect` ルーンを使用して独自のエフェクトを作成することもできます。

> [!NOTE] Most of the time, you shouldn't. `$effect` is best thought of as an escape hatch, rather than something to use frequently. If you can put your side effects in an [event handler](dom-events), for example, that's almost always preferable.
> [!NOTE] ほとんどの場合、`$effect` を使用するべきではありません。`$effect` は頻繁に使用するものではなく、困った時の最終手段として考えるのが最適です。たとえば、副作用( _side effects_ )を [イベント ハンドラー](dom-events) に配置できるのであれば、ほとんどの場合それが望ましいです。

Let's say we want to use `setInterval` to keep track of how long the component has been mounted. Create the effect:
`setInterval` を使用して、コンポーネントがマウントされている時間を追跡するとします。エフェクトを作成します。

```svelte
/// file: App.svelte
Expand All @@ -24,9 +24,9 @@ Let's say we want to use `setInterval` to keep track of how long the component h
</script>
```

Click the 'speed up' button a few times and notice that `elapsed` ticks up faster, because we're calling `setInterval` each time `interval` gets smaller.
speed upボタンを数回クリックすると、`interval` が小さくなるたびに `setInterval` が呼び出されるため、`elapsed` がより速く増加することがわかります。

If we then click the 'slow down' button... well, it doesn't work. That's because we're not clearing out the old intervals when the effect updates. We can fix that by returning a cleanup function:
次にslow downボタンをクリックしても、うまくいきません。これは、エフェクトの更新時に古い間隔をクリアしていないためです。クリーンアップ関数を返すことでこれを修正できます。

```js
/// file: App.svelte
Expand All @@ -41,8 +41,8 @@ $effect(() => {
});
```

The cleanup function is called immediately before the effect function re-runs when `interval` changes, and also when the component is destroyed.
クリーンアップ関数は、`interval` が変更されたとき、およびコンポーネントが破棄されたときに、エフェクト関数が再実行される直前に呼び出されます。

If the effect function doesn't read any state when it runs, it will only run once, when the component mounts.
エフェクト関数が実行時に状態を読み取らない場合は、コンポーネントがマウントされるときに 1 回だけ実行されます。

> [!NOTE] Effects do not run during server-side rendering.
> [!NOTE] サーバー側のレンダリング中は`$effect`は実行されません。
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: Universal reactivity
---

In the preceding exercises, we used runes to add reactivity inside components. But we can also use runes _outside_ components, for example to share some global state.
前の演習では、ルーンを使用してコンポーネント内にリアクティブ性を追加しました。ただし、たとえばグローバル状態を共有する場合など、コンポーネントの _外部_ でルーンを使用することもできます。

The `<Counter>` components in this exercise are all importing the `counter` object from `shared.js`. But it's a normal object, and as such nothing happens when you click the buttons. Wrap the object in `$state(...)`:
この演習の `<Counter>` コンポーネントはすべて、`shared.js` から `counter` オブジェクトをインポートします。ただし、これは通常のオブジェクトなので、ボタンをクリックしても何も起こりません。オブジェクトを `$state(...)` でラップします。

```js
/// file: shared.js
Expand All @@ -13,9 +13,9 @@ export const counter = +++$state({+++
+++})+++;
```

This causes an error, because you can't use runes in normal `.js` files, only `.svelte.js` files. Let's fix that — rename the file to `shared.svelte.js`.
ここでエラーが発生します。通常の `.js` ファイルではルーンを使用できず、`.svelte.js` ファイルでのみ使用できるためです。これを修正するには、ファイルの名前を `shared.svelte.js` に変更します。

Then, update the import declaration in `Counter.svelte`:
次に、`Counter.svelte` のインポート宣言を更新します。

```svelte
/// file: Counter.svelte
Expand All @@ -24,6 +24,6 @@ Then, update the import declaration in `Counter.svelte`:
</script>
```

Now, when you click any button, all three update simultaneously.
これで、いずれかのボタンをクリックすると、3 つすべてが同時に更新されます。

> [!NOTE] You cannot export a `$state` declaration from a module if the declaration is reassigned (rather than just mutated), because the importers would have no way to know about it.
> [!NOTE] 宣言が再割り当てされた場合(単に変更されるのではなく)、インポートする側がそれを知る方法がないため、モジュールから `$state` 宣言をエクスポートすることはできません。
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: Capturing
---

Normally, event handlers run during the [_bubbling_](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Event_bubbling) phase. Notice what happens if you type something into the `<input>` in this example — the inner handler runs first, as the event 'bubbles' from the target up to the document, followed by the outer handler.
通常、イベントハンドラーは [_バブリング_](https://developer.mozilla.org/ja/docs/Learn/JavaScript/Building_blocks/Event_bubbling) フェーズで実行されます。この例で `<input>` に何かを入力すると何が起こるかに注目してください。イベントが _target_ から _document_ まで「バブル」すると、最初に内部ハンドラーが実行され、その後に外部ハンドラーが実行されます。

Sometimes, you want handlers to run during the _capture_ phase instead. Add `capture` to the end of the event name:
場合によっては、代わりに _capture_ フェーズ中にハンドラを実行したいことがあります。イベント名の末尾に `capture` を追加します。

```svelte
/// file: App.svelte
Expand All @@ -13,4 +13,4 @@ Sometimes, you want handlers to run during the _capture_ phase instead. Add `cap
</div>
```

Now, the relative order is reversed. If both capturing and non-capturing handlers exist for a given event, the capturing handlers will run first.
現在、相対的な順序は逆になっています。特定のイベントに対してキャプチャハンドラーと非キャプチャハンドラーの両方が存在する場合、キャプチャハンドラーが最初に実行されます。
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Component events
---

You can pass event handlers to components like any other prop. In `Stepper.svelte`, add `increment` and `decrement` props...
他のプロパティと同様に、イベント ハンドラーをコンポーネントに渡すことができます。`Stepper.svelte` で、`increment` および `decrement` プロパティを追加します...

```svelte
/// file: Stepper.svelte
Expand All @@ -11,15 +11,15 @@ You can pass event handlers to components like any other prop. In `Stepper.svelt
</script>
```

...and wire them up:
...そしてこのように接続します。:

```svelte
/// file: Stepper.svelte
<button +++onclick={decrement}+++>-1</button>
<button +++onclick={increment}+++>+1</button>
```

In `App.svelte`, define the handlers:
`App.svelte` 内で、ハンドラーの内容を定義します。

```svelte
<Stepper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Spreading events
---

We can also [spread](spread-props) event handlers directly onto elements. Here, we've defined an `onclick` handler in `App.svelte` — all we need to do is pass the props to the `<button>` in `BigRedButton.svelte`:
また、イベント ハンドラーを要素に直接 [_spread_](spread-props) することもできます。ここでは、`App.svelte` で `onclick` ハンドラーを定義しました。必要なのは、`BigRedButton.svelte` `<button>` にプロパティを渡すだけです。

```svelte
/// file: BigRedButton.svelte
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@
title: Raw state
---

In previous exercises, we learned that state is [deeply reactive](deep-state) — if you (for example) change a property of an object, or push to an array, it will cause the UI to update. This works by creating a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) that intercepts reads and writes.
前回の演習では、状態が [深く反応する](deep-state) ことを学びました。つまり、(たとえば) オブジェクトのプロパティを変更したり、配列にプッシュしたりすると、UI が更新されます。これは、読み取りと書き込みをインターセプトする [プロキシ](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Proxy) を作成することで機能します。

Occasionally, that's not what you want. If you're not changing individual properties, or if it's important to maintain referential equality, then you can use _raw state_ instead.
場合によっては、それが望ましくないこともあります。個々のプロパティを変更しない場合、または参照の等価性を維持することが重要である場合は、代わりに _raw state_ を使用できます。

In this example, we have a chart of Svelte's steadily increasing stock price. We want the chart to update when new data comes in, which we could achieve by turning `data` into state...
この例では、Svelte の株価が着実に上昇しているグラフがあります。新しいデータが入ったときにグラフを更新したいのですが、これは `data` state に変換することで実現できます...

```js
/// file: App.svelte
let data = +++$state(poll())+++;
```

...but there's no need to make it deeply reactive when it will be discarded a few milliseconds later. Instead, use `$state.raw`:
...しかし、数ミリ秒後に破棄されるのであれば、それを深く反応させる必要はありません。代わりに、`$state.raw` を使用します。

```js
/// file: App.svelte
let data = +++$state.raw(poll())+++;
```

> [!NOTE] Mutating raw state will have no direct effect. In general, mutating non-reactive state is strongly discouraged.
> [!NOTE] _raw state_ を変更してもエフェクトは反応しません。一般に非反応状態を変更することは強く推奨されません。
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: Reactive classes
---

It's not just variables that can be made reactive — in Svelte, we can also make properties of classes reactive.
リアクティブにできるのは変数だけではありません。Svelte では、クラスのプロパティもリアクティブにできます。

Let's make the `width` and `height` properties of our `Box` class reactive:
`Box` クラスの `width` プロパティと `height` プロパティをリアクティブにしてみましょう。

```js
/// file: App.svelte
Expand All @@ -17,9 +17,9 @@ class Box {
}
```

Now, when we interact with the range inputs or click the 'embiggen' button, the box reacts.
ここで、範囲入力を操作したり、「embiggen」ボタンをクリックすると、ボックスが反応します。

We can also use `$derived`, so that `box.area` updates reactively:
`$derived` を使用すると、`box.area` がリアクティブに更新されるようになります。

```js
/// file: App.svelte
Expand All @@ -32,4 +32,4 @@ class Box {
}
```

> [!NOTE] In addition to `$state` and `$derived`, you can use `$state.raw` and `$derived.by` to define reactive fields.
> [!NOTE] `$state` `$derived` に加えて、`$state.raw` `$derived.by` を使用してリアクティブフィールドを定義することもできます。
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: Getters and setters
---

Classes are particularly useful when you need to validate data. In the case of this `Box` class, it shouldn't be possible to keep embiggening past the maximum allowed by the sliders, but that's exactly what happens.
クラスは、データを検証する必要がある場合に特に便利です。この `Box` クラスの場合、スライダーで許可されている最大値を超えて拡大し続けることはできないはずですが、実際には起ってしまっています。

We can fix that by replacing `width` and `height` with _getters_ and _setters_, otherwise known as _accessors_. First, convert them to [private properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties):
これを修正するには、`width` `height` を _getter_ と _setter_ (別名 _accessors_) に置き換えます。まず、これらを [プライベート プロパティ](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/Private_properties) に変換します。

```js
/// file: App.svelte
Expand All @@ -22,7 +22,7 @@ class Box {
}
```

Then, create some getters and setters:
次に、いくつかのゲッターとセッターを作成します。

```js
/// file: App.svelte
Expand Down Expand Up @@ -52,7 +52,7 @@ class Box {
}
```

Finally, add the validation to the setters:
最後に、セッターに検証を追加します。

```js
/// file: App.svelte
Expand All @@ -65,4 +65,4 @@ set height(value) {
}
```

It's now impossible to increase the box size past safe limits, whether through the `bind:value` on the range inputs, or the `embiggen` method, no matter how hard you press the button.
ボタンをどれだけ無理やり押しても、範囲入力の `bind:value` `embiggen` メソッドを介して、ボックスのサイズを限度を超えて増やすことはできなくなりました。
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title: Reactive built-ins
---

Svelte ships with several reactive classes that you can use in place of JavaScript built-in objects — namely `Map`, `Set`, `Date`, `URL` and `URLSearchParams`.
Svelte には、JavaScript 組み込みオブジェクトの代わりに使用できるいくつかのリアクティブ クラス (`Map``Set``Date``URL``URLSearchParams`) が付属しています。

In this exercise, we _could_ declare `date` using `$state(new Date())` and reassign it inside the `setInterval`. But a nicer alternative is to use `SvelteDate` from [`svelte/reactivity`](/docs/svelte/svelte-reactivity):
この演習では、`$state(new Date())` を使用して `date` を宣言し、`setInterval` 内で再割り当てします。ただし、より適切な代替案は、[`svelte/reactivity`](/docs/svelte/svelte-reactivity) の `SvelteDate` を使用することです。

```svelte
/// file: App.svelte
Expand Down
Loading