0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Svelte5でFullScreen切り替えUを作ったよ

Posted at

10月下旬にSvelte5がリリースされて、旧来のSvelte4とは書きっぷりがだいぶ進化したよね。

Svelte4の「絶対に素のJSの書きっぷりに抑える」という路線も頑な意志を感じられて好きだったけど、実際仕事で使うならSvelte5のRunesをはじめとする重大なアップデートはすごく良い印象を持ってる。

今回、自分がSvelte5をキャッチアップするためにFullScreen切り替えコンポーネントを作ったから、せっかくだからソースコードを紹介するね。

FullScreen切り替えUI

RunesはSvelteの印象を大きく変えたなーと思ってる。

次のコード中でいうところの、 $state$props がRunesだね。Svelte4なら let xxxState = somethingexport let xxxxProp って書いていたけれど、あえて素のJSらしさを幾らか捨てて、他のフロントエンドフレームワークのように専用の書き方を用意してきたんだなーって感じたよ。

FullScreenControl.svelte
<script lang="ts">
  import { onMount, type Snippet } from "svelte";

  const {
    enterFullScreenLabel,
    exitFullScreenLabel,
  }: {
    enterFullScreenLabel: Snippet;
    exitFullScreenLabel: Snippet;
  } = $props();

  let isFullscreen = $state(false);

  onMount(() => {
    isFullscreen = document.fullscreenElement !== null;
  });

  const handleOnClick = () => {
    if (document.fullscreenElement) {
      document.exitFullscreen();
      isFullscreen = false;
      return;
    }
    document.body.requestFullscreen();
    isFullscreen = true;
  };
</script>

<button
  title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
  aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
  onclick={handleOnClick}
>
  {#if isFullscreen}
    {@render exitFullScreenLabel()}
  {:else}
    {@render enterFullScreenLabel()}
  {/if}
</button>

あとslotを非推奨にして、@render というより強力な機能を登場させたのも印象的だね。上記でも使っていて、親クラスから渡される snippet を描画するようにしているんだ。

Usage

実装したフルスクリーン切り替えUIコンポーネントを使う時は次のようにするよ。子要素として記述したsnippetは暗黙的に親コンポーネントのpropsに渡される仕様だね。slot時代のイメージから容易に移行できるようにあえてこの書き方をしているけど、snippetは他にも渡し方がある。詳しくは公式ドキュメントを読んでね。

<FullScreenControl>
  {#snippet exitFullScreenLabel()}
    <ArrowsPointingIn />
  {/snippet}
  {#snippet enterFullScreenLabel()}
    <ArrowsPointingOut />
  {/snippet}
</FullScreenControl>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?