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

Proposal: presence #414

Merged
Merged
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
21 changes: 21 additions & 0 deletions packages/presence/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Solid Primitives Working Group

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
174 changes: 174 additions & 0 deletions packages/presence/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<p>
<img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=presence" alt="Solid Primitives presence">
</p>

# @solid-primitives/presence

[![turborepo](https://img.shields.io/badge/built%20with-turborepo-cc00ff.svg?style=for-the-badge&logo=turborepo)](https://turborepo.org/)
[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/presence?style=for-the-badge&label=size)](https://bundlephobia.com/package/@solid-primitives/presence)
[![version](https://img.shields.io/npm/v/@solid-primitives/presence?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/presence)
[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)

A small SolidJS utility to animate the presence of an element. Inspired by & directly forked from [`use-presence`](https://www.npmjs.com/package/use-presence).

### The problem

There are two problems that you have to solve when animating the presence of an element:

1. During enter animations, you have to render an initial state where the element is hidden and only after the latest state has propagated to the DOM, you can can animate the final state that the element should animate towards.
2. Exit animations are a bit tricky in SolidJS, since this typically means that a component unmounts. However when the component has already unmounted, you can't animate it anymore. A workaround is often to keep the element mounted, but that keeps unnecessary elements around and can hurt accessibility, as hidden interactive elements might still be focusable.

### This solution

This utility provides a lightweight solution where the animating element is only mounted the minimum of time, while making sure the animation is fully visible to the user. The rendering is left to the user to support all kinds of styling solutions.

## Installation

```bash
npm install @solid-primitives/presence
# or
yarn add @solid-primitives/presence
# or
pnpm add @solid-primitives/presence
```

## How to use it

### `createPresence` boolean example

```tsx
const FirstExample = () => {
const [showStuff, setShowStuff] = createSignal(true);
const { isVisible, isMounted } = createPresence(showStuff, {
transitionDuration: 500,
});

return (
<div
style={{
padding: "2em",
margin: "2em",
"border-radius": "2em",
"box-shadow": "-5px 0px 10px rgba(0, 0, 0, 0.2)",
}}
>
<button onclick={() => setShowStuff(!showStuff())}>{`${
showStuff() ? "Hide" : "Show"
} stuff`}</button>
<Show when={isMounted()}>
<div
style={{
transition: "all .5s ease",
opacity: isVisible() ? "1" : "0",
transform: isVisible() ? "translateX(0)" : "translateX(50px)",
}}
>
I am the stuff!
</div>
</Show>
</div>
);
};
```

### `createPresence` switching example

The first argument of `createPresence` is a signal accessor of arbitrary type. This allows you to use it with any kind of data, not just booleans. This is useful if you want to animate between different items. If you utilize the returned `mountedItem` property, you can get the data which should be currently mounted regardless of the animation state

```tsx
const SecondExample = () => {
const items = ["foo", "bar", "baz", "qux"];
const [activeItem, setActiveItem] = createSignal(items[0]);
const presence = createPresence(activeItem, {
transitionDuration: 500,
});

return (
<div
style={{
padding: "2em",
margin: "2em",
"border-radius": "2em",
"box-shadow": "-5px 0px 10px rgba(0, 0, 0, 0.2)",
}}
>
<For each={items}>
{item => (
<button onClick={() => setActiveItem(p => (p === item ? undefined : item))}>
{item}
</button>
)}
</For>
<Show when={presence.isMounted()}>
<div
style={{
transition: "all .5s linear",
...(presence.isEntering() && {
opacity: "0",
transform: "translateX(-25px)",
}),
...(presence.isExiting() && {
opacity: "0",
transform: "translateX(25px)",
}),
...(presence.isVisible() && {
opacity: "1",
transform: "translateX(0)",
}),
}}
>
{presence.mountedItem()}
</div>
</Show>
</div>
);
};
```

### `createPresence` options API

```ts
function createPresence<TItem>(
item: Accessor<TItem | undefined>,
options: Options,
): PresenceResult<TItem>;

type Options = {
/** Duration in milliseconds used both for enter and exit transitions. */
transitionDuration: MaybeAccessor<number>;
/** Duration in milliseconds used for enter transitions (overrides `transitionDuration` if provided). */
enterDuration: MaybeAccessor<number>;
/** Duration in milliseconds used for exit transitions (overrides `transitionDuration` if provided). */
exitDuration: MaybeAccessor<number>;
/** Opt-in to animating the entering of an element if `isVisible` is `true` during the initial mount. */
initialEnter?: boolean;
};

type PresenceResult<TItem> = {
/** Should the component be returned from render? */
isMounted: Accessor<boolean>;
/** The item that is currently mounted. */
mountedItem: Accessor<TItem | undefined>;
/** Should the component have its visible styles applied? */
isVisible: Accessor<boolean>;
/** Is the component either entering or exiting currently? */
isAnimating: Accessor<boolean>;
/** Is the component entering currently? */
isEntering: Accessor<boolean>;
/** Is the component exiting currently? */
isExiting: Accessor<boolean>;
};
```

## Demo

Demo can be seen [here](https://stackblitz.com/edit/presence-demo).

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)

## Related

- [`use-presence`](https://www.npmjs.com/package/use-presence)
- [`@solid-primitives/transition-group`](https://www.npmjs.com/package/@solid-primitives/transition-group)
35 changes: 35 additions & 0 deletions packages/presence/dev/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>Solid App</title>
<style>
html {
font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
}

body {
padding: 0;
margin: 0;
}

a,
button {
cursor: pointer;
}

* {
margin: 0;
}
</style>
</head>

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>

<script src="/index.tsx" type="module"></script>
</body>
</html>
104 changes: 104 additions & 0 deletions packages/presence/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { Component, For, Show, createSignal } from "solid-js";
import { render } from "solid-js/web";
import { createPresence } from "../src";
import "uno.css";

const App: Component = () => {
return (
<>
<FirstExample />
<SecondExample />
</>
);
};

const FirstExample = () => {
const [showStuff, setShowStuff] = createSignal(true);
const { isVisible, isMounted } = createPresence(showStuff, {
transitionDuration: 500,
});

return (
<div
style={{
padding: "2em",
margin: "2em",
"border-radius": "2em",
"box-shadow": "-5px 0px 10px rgba(0, 0, 0, 0.2)",
}}
>
<button onclick={() => setShowStuff(!showStuff())}>{`${
showStuff() ? "Hide" : "Show"
} stuff`}</button>
<Show when={isMounted()}>
<div
style={{
transition: "all .5s ease",
opacity: isVisible() ? "1" : "0",
transform: isVisible() ? "translateX(0)" : "translateX(50px)",
}}
>
I am the stuff!
</div>
</Show>
</div>
);
};

const SecondExample = () => {
const items = ["foo", "bar", "baz", "qux"];
const [item, setItem] = createSignal<(typeof items)[number] | undefined>(items[0]);
const { isMounted, mountedItem, isEntering, isVisible, isExiting } = createPresence(item, {
transitionDuration: 500,
});

return (
<div
style={{
padding: "2em",
margin: "2em",
"border-radius": "2em",
"box-shadow": "-5px 0px 10px rgba(0, 0, 0, 0.2)",
}}
>
<For each={items}>
{currItem => (
<button
onclick={() => {
if (item() === currItem) {
setItem(undefined);
} else {
setItem(currItem);
}
}}
>
{currItem}
</button>
)}
</For>
<Show when={isMounted()}>
<div
style={{
transition: "all .5s linear",
...(isEntering() && {
opacity: "0",
transform: "translateX(-25px)",
}),
...(isExiting() && {
opacity: "0",
transform: "translateX(25px)",
}),
...(isVisible() && {
opacity: "1",
transform: "translateX(0)",
}),
}}
>
{mountedItem()}
</div>
</Show>
</div>
);
};

render(() => <App />, document.getElementById("root")!);
2 changes: 2 additions & 0 deletions packages/presence/dev/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { viteConfig } from "../../../configs/vite.config";
export default viteConfig;
57 changes: 57 additions & 0 deletions packages/presence/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@solid-primitives/presence",
"version": "0.0.1",
"description": "Utility to animate the presence of an element based on the existence of data or lack thereof.",
"author": "Ethan Standel <[email protected]>",
"license": "MIT",
"homepage": "https://github.com/solidjs-community/solid-primitives/tree/main/packages/presence#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/solidjs-community/solid-primitives.git"
},
"primitive": {
"name": "presence",
"stage": 0,
"list": [
"createPresence"
],
"category": "Animation"
},
"files": [
"dist"
],
"private": false,
"sideEffects": false,
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"browser": {},
"exports": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": "./dist/index.cjs"
},
"keywords": [
"animation",
"animate",
"presence",
"transition"
],
"scripts": {
"dev": "vite serve dev",
"page": "vite build dev",
"build": "jiti ../../scripts/build.ts",
"test": "vitest -c ../../configs/vitest.config.ts",
"test:ssr": "pnpm run test --mode ssr"
},
"dependencies": {
"@solid-primitives/utils": "workspace:^"
},
"peerDependencies": {
"solid-js": "^1.6.12"
},
"typesVersions": {}
}
Loading