0.1.1 • Published 5 months ago

view-transitions-api-utils v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

view-transitions-api-utils

The simplest native method to achieve smooth element shared layout animations.

npm version npm downloads bundle JSDocs License

Install

pnpm add view-transitions-api-utils

Usage

Just set the CSS view-transition-name, leave the rest to document.startViewTransition().

import { startViewTransition } from 'view-transitions-api-utils';

await startViewTransition(() => {
  // updateDOM
}).finished;

React

import { useTransitionState } from 'view-transitions-api-utils/react';

const App = () => {
  const [showContent, setShowContent] = useTransitionState(false);

  return (
    <div onClick={() => setShowContent((show) => !show)}>
      <h1 style={{ viewTransitionName: 'title' }}>Title</h1>
      {showContent && <div style={{ height: 100, viewTransitionName: 'content' }}>Content</div>}
      <p style={{ viewTransitionName: 'tips' }}>Tips</p>
    </div>
  );
};

Vue

💡 You can encapsulate a hook yourself.

import { startViewTransition } from 'view-transitions-api-utils';

await startViewTransition(
  () => {
    // update state
    // for example: `count.value++`;
  },
  { flushSync: Vue.nextTick },
).finished;

Native demo

This code can be used to find a list on any website, select a sub-item from the list, and then execute it in the console to see the effect.

((el) => {
  // eslint-disable-next-line unicorn/no-array-for-each
  [...el.parentElement.children].forEach((item, index) => {
    item.style.viewTransitionName = `item${index}`;
  });

  document.startViewTransition(() => {
    el.style.display = el.style.display === 'none' ? '' : 'none';
  });
})($0);

Guide

https://developer.chrome.com/docs/web-platform/view-transitions

License

MIT License © 2023 u3u