Skip to content

Add Match component and package #760

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

Open
wants to merge 12 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
21 changes: 21 additions & 0 deletions packages/match/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.
132 changes: 132 additions & 0 deletions packages/match/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<p>
<img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=match" alt="Solid Primitives match">
</p>

# @solid-primitives/match

[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/match?style=for-the-badge&label=size)](https://bundlephobia.com/package/@solid-primitives/match)
[![version](https://img.shields.io/npm/v/@solid-primitives/match?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/match)
[![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)

Control-flow components for matching discriminated union (tagged union) members and union literals.

## Installation

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

## `MatchTag`

Control-flow component for matching discriminated union (tagged union) members.

### How to use it

```tsx
type MyUnion = {
type: "foo",
foo: "foo-value",
} | {
type: "bar",
bar: "bar-value",
}

const [value, setValue] = createSignal<MyUnion>({type: "foo", foo: "foo-value"})

<MatchTag on={value()} case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}} />
```

### Changing the tag key

The default tag key is `"type"`, but it can be changed with the `tag` prop:

```tsx
type MyUnion = {
kind: "foo",
foo: "foo-value",
} | {
kind: "bar",
bar: "bar-value",
}

<MatchTag on={value()} tag="kind" case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}} />
```

### Partial matching

Use the `partial` prop to only handle some of the union members:

```tsx
<MatchTag partial on={value()} case={{
foo: v => <>{v().foo}</>,
// bar case is not handled
}} />
```

### Fallback

Provide a fallback element when no match is found or the value is `null`/`undefined`:

```tsx
<MatchTag on={value()} case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}} fallback={<div>No match found</div>} />
```

## `MatchValue`

Control-flow component for matching union literals.

### How to use it

```tsx
type MyUnion = "foo" | "bar";

const [value, setValue] = createSignal<MyUnion>("foo");

<MatchValue on={value()} case={{
foo: () => <p>foo</p>,
bar: () => <p>bar</p>,
}} />
```

### Partial matching

Use the `partial` prop to only handle some of the union members:

```tsx
<MatchValue partial on={value()} case={{
foo: () => <p>foo</p>,
// bar case is not handled
}} />
```

### Fallback

Provide a fallback element when no match is found or the value is `null`/`undefined`:

```tsx
<MatchValue on={value()} case={{
foo: () => <p>foo</p>,
bar: () => <p>bar</p>,
}} fallback={<div>No match found</div>} />
```

## Demo

[Deployed example](https://primitives.solidjs.community/playground/match) | [Source code](https://github.com/solidjs-community/solid-primitives/tree/main/packages/match/dev)

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)
114 changes: 114 additions & 0 deletions packages/match/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { Component, createSignal } from "solid-js";
import { MatchTag, MatchValue } from "../src/index.js";

type AnimalDog = {type: 'dog', breed: string};
type AnimalCat = {type: 'cat', lives: number};
type AnimalBird = {type: 'bird', canFly: boolean};

type Animal = AnimalDog | AnimalCat | AnimalBird;

const DogDisplay: Component<{ animal: AnimalDog }> = (props) => (
<div class="text-center">
<div class="text-2xl mb-2">🐕</div>
<div class="text-sm">Breed: {props.animal.breed}</div>
</div>
);

const CatDisplay: Component<{ animal: AnimalCat }> = (props) => (
<div class="text-center">
<div class="text-2xl mb-2">🐱</div>
<div class="text-sm">Lives: {props.animal.lives}</div>
</div>
);

const BirdDisplay: Component<{ animal: AnimalBird }> = (props) => (
<div class="text-center">
<div class="text-2xl mb-2">🐦</div>
<div class="text-sm">
{props.animal.canFly ? 'Can fly' : 'Cannot fly'}
</div>
</div>
);

const FallbackDisplay: Component = () => (
<div class="text-center">
<div class="text-2xl mb-2">❓</div>
<div>Fallback content</div>
</div>
);

const App: Component = () => {
const [animal, setAnimal] = createSignal<Animal | null>(null);

const animals: (Animal | null)[] = [
null,
{ type: 'dog', breed: 'Golden Retriever' },
{ type: 'cat', lives: 9 },
{ type: 'bird', canFly: true },
];

return (
<div class="min-h-screen p-8">
<div class="max-w-4xl mx-auto space-y-8">
<div class="text-center">
<h1 class="text-3xl font-bold mb-2">Match Component Demo</h1>
<p>Control-flow component for matching discriminated union members</p>
</div>

<div class="border border-gray-500 border-2 rounded-lg p-6">
<label class="block text-sm font-medium mb-2">
Select an animal:
</label>
<select
class="w-full p-2 border border-gray-500 border-2 rounded-md"
onChange={e => {setAnimal(animals[parseInt(e.target.value)]!)}}
>
<option value="0">None (null)</option>
<option value="1">Dog</option>
<option value="2">Cat</option>
<option value="3">Bird</option>
</select>
</div>

<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="border border-gray-500 border-2 rounded-lg p-6">
<h2 class="text-xl font-semibold mb-1">Complete Match</h2>
<p class="text-sm mb-4">Handles all union members with fallback</p>
<div class="border border-gray-500 border-2 rounded p-4 min-h-[100px] flex items-center justify-center">
<MatchTag on={animal()} case={{
dog: v => <DogDisplay animal={v()} />,
cat: v => <CatDisplay animal={v()} />,
bird: v => <BirdDisplay animal={v()} />,
}} fallback={<FallbackDisplay />} />
</div>
</div>

<div class="border border-gray-500 border-2 rounded-lg p-6">
<h2 class="text-xl font-semibold mb-1">Partial Match</h2>
<p class="text-sm mb-4">Only handles dogs and cats</p>
<div class="border border-gray-500 border-2 rounded p-4 min-h-[100px] flex items-center justify-center">
<MatchTag partial on={animal()} case={{
dog: v => <DogDisplay animal={v()} />,
cat: v => <CatDisplay animal={v()} />,
}} fallback={<FallbackDisplay />} />
</div>
</div>
</div>

<div class="mt-8 border border-gray-500 border-2 rounded-lg p-6">
<h2 class="text-xl font-semibold mb-1">Value Match</h2>
<p class="text-sm mb-4">Match on union literals</p>
<div class="border border-gray-500 border-2 rounded p-4 min-h-[100px] flex items-center justify-center">
<MatchValue on={animal()?.type} case={{
dog: () => <p>🐕</p>,
cat: () => <p>🐱</p>,
bird: () => <p>🐦</p>,
}} fallback={<FallbackDisplay />} />
</div>
</div>
</div>
</div>
);
};

export default App;
59 changes: 59 additions & 0 deletions packages/match/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
{
"name": "@solid-primitives/match",
"version": "0.0.100",
"description": "A template primitive example.",
"author": "Damian Tarnawski <[email protected]>",
"contributors": [],
"license": "MIT",
"homepage": "https://primitives.solidjs.community/package/match",
"repository": {
"type": "git",
"url": "git+https://github.com/solidjs-community/solid-primitives.git"
},
"bugs": {
"url": "https://github.com/solidjs-community/solid-primitives/issues"
},
"primitive": {
"name": "match",
"stage": 0,
"list": [
"Match"
],
"category": "Control Flow"
},
"keywords": [
"solid",
"primitives",
"union"
],
"private": false,
"sideEffects": false,
"files": [
"dist"
],
"type": "module",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"browser": {},
"exports": {
"@solid-primitives/source": "./src/index.ts",
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"typesVersions": {},
"scripts": {
"dev": "node --import=@nothing-but/node-resolve-ts --experimental-transform-types ../../scripts/dev.ts",
"build": "node --import=@nothing-but/node-resolve-ts --experimental-transform-types ../../scripts/build.ts",
"vitest": "vitest -c ../../configs/vitest.config.ts",
"test": "pnpm run vitest",
"test:ssr": "pnpm run vitest --mode ssr"
},
"peerDependencies": {
"solid-js": "^1.6.12"
},
"devDependencies": {
"solid-js": "^1.9.7"
}
}
Loading
Loading