text
stringlengths 2
104M
| meta
dict |
---|---|
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-08-decreaseApproval.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('decreaseApproval should throw if contract is paused', async () => {
const initialAmount = 1000;
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.decreaseApproval(address1, initialAmount, { from: ownerAddress }),
'Pausable: paused'
);
});
it('decreaseApproval success', async () => {
const initialAmount = 1000;
const expectedAmount = 500;
await contractInstance.approve(address1, initialAmount, { from: ownerAddress });
const resultBeforeDecrease = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
const resultDecrease = await contractInstance.decreaseApproval(address1, 500, { from: ownerAddress });
const resultAfterDecrease = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
assert.equal(initialAmount, resultBeforeDecrease.toNumber(), 'wrong result berore increase');
assert.equal(expectedAmount, resultAfterDecrease.toNumber(), 'wrong result after increase');
Assert.eventEmitted(resultDecrease, 'Approval');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
contract('ERC20-01-constructor.test.js', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
it('set name', async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
const result = await contractInstance.name();
assert.equal(tokenName, result, 'name is wrong');
});
it('set symbol', async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
const result = await contractInstance.symbol();
assert.equal(tokenSymbol, result, 'symbol is wrong');
});
it('set decimals', async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
const result = await contractInstance.decimals();
assert.equal(tokenDecimals, result, 'decimals is wrong');
});
it('set totalSupply', async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
const result = await contractInstance.totalSupply();
assert.equal(tokenTotalSupply, result, 'totalSupply is wrong');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-04-transferFrom.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
const address2 = accounts[2];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('transferFrom should throw if contract is paused', async () => {
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.transferFrom(ownerAddress, address2, 1000, { from: address1 }),
'Pausable: paused'
);
});
it('transferFrom should throw if from address is not valid', async () => {
await Assert.reverts(
contractInstance.transferFrom('0x0000000000000000000000000000000000000000', address1, 1000, { from: ownerAddress }),
'ERC20: from address is not valid'
);
});
it('transferFrom should throw if to address is not valid', async () => {
await Assert.reverts(
contractInstance.transferFrom(address1, '0x0000000000000000000000000000000000000000', 1000, { from: ownerAddress }),
'ERC20: to address is not valid'
);
});
it('transferFrom should throw if balance is insufficient', async () => {
await Assert.reverts(
contractInstance.transferFrom(address1, address2, 1000, { from: address1 }),
'ERC20: insufficient balance'
);
});
it('transferFrom should throw if sender is not approved', async () => {
await Assert.reverts(
contractInstance.transferFrom(ownerAddress, address1, 1000, { from: address1 }),
'ERC20: transfer from value not allowed'
);
});
it('transferFrom should throw if approval is not enoughth', async () => {
await contractInstance.approve(address1, 999, { from: ownerAddress });
await Assert.reverts(
contractInstance.transferFrom(ownerAddress, address2, 1000, { from: address1 }),
'ERC20: transfer from value not allowed'
);
});
it('transferFrom success', async () => {
await contractInstance.approve(address1, 1000, { from: ownerAddress });
const result = await contractInstance.transferFrom(ownerAddress, address2, 1000, { from: address1 });
const expectedBalance = 1000;
const resultBalanceOf = await contractInstance.balanceOf(address2, { from: address1 });
Assert.eventEmitted(result, 'Transfer');
assert.equal(expectedBalance, resultBalanceOf, 'wrong balance');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-06-allowance.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('allowance should throw if contract is paused', async () => {
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.allowance(ownerAddress, address1, { from: ownerAddress }),
'Pausable: paused'
);
});
it('not allowance', async () => {
const result = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
assert.equal(0, result.toNumber(), 'wrong result');
});
it('allowance', async () => {
const expectedAmount = 1000;
await contractInstance.approve(address1, expectedAmount, { from: ownerAddress });
const result = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
assert.equal(expectedAmount, result.toNumber(), 'wrong result');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-02-transfer.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('transfer should throw if contract is paused', async () => {
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.transfer(address1, 1000, { from: ownerAddress }),
'Pausable: paused'
);
});
it('transfer should throw if to address is not valid', async () => {
await Assert.reverts(
contractInstance.transfer('0x0000000000000000000000000000000000000000', 1000, { from: ownerAddress }),
'ERC20: to address is not valid'
);
});
it('transfer should throw if balance is insufficient', async () => {
await Assert.reverts(
contractInstance.transfer(ownerAddress, 1000, { from: address1 }),
'ERC20: insufficient balance'
);
});
it('transfer success', async () => {
const result = await contractInstance.transfer(address1, 1000, { from: ownerAddress });
const expectedBalance = 1000;
const resultBalanceOf = await contractInstance.balanceOf(address1, { from: address1 });
Assert.eventEmitted(result, 'Transfer');
assert.equal(expectedBalance, resultBalanceOf, 'wrong balance');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-09-mintTo.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('mintTo should throw if contract is paused', async () => {
const mintValue = 1000;
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.mintTo(address1, mintValue, { from: address1 }),
'Pausable: paused'
);
});
it('mintTo should throw if to address is invalid', async () => {
await Assert.reverts(
contractInstance.mintTo('0x0000000000000000000000000000000000000000', 1000, { from: ownerAddress }),
'ERC20: to address is not valid'
);
});
it('mintTo should throw if account is not a minter', async () => {
const mintValue = 1000;
await Assert.reverts(
contractInstance.mintTo(address1, mintValue, { from: address1 }),
'Ownable: caller is not the owner'
);
});
it('mintTo success', async () => {
const mintValue = 1000;
const resultBeforeMint = await contractInstance.totalSupply();
const mint = await contractInstance.mintTo(address1, mintValue, { from: ownerAddress });
const expectedTotalSupply = resultBeforeMint.toNumber() + mintValue;
const resultAfterMint = await contractInstance.totalSupply();
const resultBalanceOf = await contractInstance.balanceOf(address1, { from: address1 });
assert.equal(expectedTotalSupply, resultAfterMint, 'wrong totalSupply after');
assert.equal(mintValue, resultBalanceOf, 'wrong balance');
Assert.eventEmitted(mint, 'Transfer');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-11-burn.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('burn should throw if contract is paused', async () => {
const burnValue = 1000;
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.burn(burnValue, { from: address1 }),
'Pausable: paused'
);
});
it('burn should throw if balance is insufficient', async () => {
await Assert.reverts(
contractInstance.burn(1000, { from: address1 }),
'ERC20: insufficient balance'
);
});
it('burn success', async () => {
const mintValue = 1000;
const burnValue = 500;
const expectedBalance = 500;
await contractInstance.mintTo(address1, mintValue, { from: ownerAddress });
const burn = await contractInstance.burn(burnValue, { from: address1 });
const expectedTotalSupply = (tokenTotalSupply + mintValue) - burnValue;
const resultAfterBurn = await contractInstance.totalSupply();
const resultBalanceOf = await contractInstance.balanceOf(address1, { from: address1 });
assert.equal(expectedTotalSupply, resultAfterBurn, 'wrong totalSupply after');
assert.equal(expectedBalance, resultBalanceOf, 'wrong balance');
Assert.eventEmitted(burn, 'Transfer');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-07-increaseApproval.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('increaseApproval should throw if contract is paused', async () => {
const initialAmount = 1000;
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.increaseApproval(address1, initialAmount, { from: ownerAddress }),
'Pausable: paused'
);
});
it('increaseApproval success', async () => {
const initialAmount = 1000;
const expectedAmount = 2000;
await contractInstance.approve(address1, initialAmount, { from: ownerAddress });
const resultBeforeIncrease = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
const resultIncrease = await contractInstance.increaseApproval(address1, initialAmount, { from: ownerAddress });
const resultAfterIncrease = await contractInstance.allowance(ownerAddress, address1, { from: ownerAddress });
assert.equal(initialAmount, resultBeforeIncrease.toNumber(), 'wrong result berore increase');
assert.equal(expectedAmount, resultAfterIncrease.toNumber(), 'wrong result after increase');
Assert.eventEmitted(resultIncrease, 'Approval');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
const Assert = require('truffle-assertions');
contract('ERC20-04-transferFrom.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
const address1 = accounts[1];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('approve should throw if contract is paused', async () => {
await contractInstance.pause({ from: ownerAddress });
await Assert.reverts(
contractInstance.approve(address1, 1000, { from: ownerAddress }),
'Pausable: paused'
);
});
it('approve success', async () => {
const result = await contractInstance.approve(address1, 1000, { from: ownerAddress });
Assert.eventEmitted(result, 'Approval');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Artifact = artifacts.require('../contracts/ERC20');
contract('ERC20-03-balanceOf.test', (accounts) => {
const tokenName = 'token';
const tokenSymbol = 'TKN';
const tokenDecimals = 18;
const tokenTotalSupply = 1000000;
let contractInstance;
const ownerAddress = accounts[0];
before(() => {
web3.eth.defaultAccount = ownerAddress;
});
beforeEach(async () => {
contractInstance = await Artifact.new(tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
});
it('balanceOf success', async () => {
const result = await contractInstance.balanceOf(ownerAddress, { from: ownerAddress });
assert.equal(result.toNumber(), tokenTotalSupply, 'balance is wrong');
});
}); | {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Migrations = artifacts.require("ERC20");
require('dotenv').config();
console.log(process.env.TOKEN_NAME);
const tokenName = process.env.TOKEN_NAME;
const tokenSymbol = process.env.TOKEN_SYMBOL;
const tokenDecimals = process.env.TOKEN_DECIMALS;
const tokenTotalSupply = process.env.TOKEN_TOTALSUPLY;
module.exports = function (deployer) {
deployer.deploy(Migrations, tokenName, tokenSymbol, tokenDecimals, tokenTotalSupply);
};
| {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
const Migrations = artifacts.require("Migrations");
module.exports = function(deployer) {
deployer.deploy(Migrations);
};
| {
"repo_name": "freitasgouvea/token-erc-20",
"stars": "43",
"repo_language": "JavaScript",
"file_name": "1_initial_migration.js",
"mime_type": "text/plain"
} |
**Data Structures**
Requirements:
- access point values (coordinates)
- find neighbours
- within a certain radius “r”
- the “k” nearest neighbours
Storing Values
- values per element
- unique index for every point,
*Octrees*
Hierarchical spatial data structure
- divide-and-conquer
- binary subdivision
each node contains:
- dimensions
[xmin,xmax] x [ymin,ymax] x [zmin,zmax]
- pointers to eight children
- empty for leaf-nodes
- unique label
| {
"repo_name": "mmolero/awesome-point-cloud-processing",
"stars": "650",
"repo_language": "None",
"file_name": "README.md",
"mime_type": "text/plain"
} |
# awesome-point-cloud-processing
A curated list of awesome Point Cloud Processing Resources, Libraries, Software. Inspired by [awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
**Please feel free to add more resources (pull requests)**
## Tutorials
[Data Structures for Large 3D Point Cloud Processing](http://www7.informatik.uni-wuerzburg.de/mitarbeiter/nuechter/tutorial2014). Data Structures for Large 3D Point Cloud Processing Tutorial at the 13th International Conference on Intelligent Autonomous Systems
[INF555 Geometric Modeling: Digital Representation
and Analysis of Shapes: lecture 7](http://www.enseignement.polytechnique.fr/informatique/INF555/Slides/lecture7.pdf).
[3D Deep Learning on Point Cloud Data](http://graphics.stanford.edu/courses/cs468-17-spring/LectureSlides/L16%20-%203d%20deep%20learning%20on%20point%20cloud%20(analysis)%20and%20joint%20embedding.pdf)
## Libraries
- [**PCL - Point Cloud Library**](http://pointclouds.org/) is a standalone, large scale, open project for 2D/3D image and point cloud processing.
- [**3DTK - The 3D Toolkit**](http://slam6d.sourceforge.net/) provides algorithms and methods to process 3D point clouds.
- [**PDAL - Point Data Abstraction Library**](http://www.pdal.io/) is a C++/Python BSD library for translating and manipulating point cloud data.
- [**libLAS**](http://liblas.org/) is a C/C++ library for reading and writing the very common LAS LiDAR format (Legacy. Replaced by PDAL).
- [**entwine**](https://github.com/connormanning/entwine/) is a data organization library for massive point clouds, designed to conquer datasets of hundreds of billions of points as well as desktop-scale point clouds.
- [**PotreeConverter**](https://github.com/potree/PotreeConverter) is another data organisation library, generating data for use in the Potree web viewer.
- [**lidR**](https://github.com/Jean-Romain/lidR) R package for Airborne LiDAR Data Manipulation and Visualization for Forestry Applications.
- [**pypcd**](https://github.com/dimatura/pypcd) Python module to read and write point clouds stored in the PCD file format, used by the Point Cloud Library.
- [**Open3D**](https://github.com/intel-isl/Open3D) is an open-source library that supports rapid development of software that deals with 3D data. It has Python and C++ frontends.
- [**cilantro**](https://github.com/kzampog/cilantro) A Lean and Efficient Library for Point Cloud Data Processing (C++).
- [**PyVista**](https://github.com/pyvista/pyvista/) 3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit(VTK).
- [**pyntcloud**](https://github.com/daavoo/pyntcloud) is a Python library for working with 3D point clouds.
- [**pylas**](https://github.com/tmontaigu/pylas) Reading Las (lidar) in Python.
- [**PyTorch**](https://github.com/rusty1s/pytorch_geometric) PyTorch Geometric (PyG) is a geometric deep learning extension library for PyTorch.
## Software (Open Source)
- [**Paraview**](http://www.paraview.org/). Open-source, multi-platform data analysis and visualization application.
- [**MeshLab**](http://meshlab.sourceforge.net/). Open source, portable, and extensible system for the processing and editing of unstructured 3D triangular meshes
- [**CloudCompare**](http://www.danielgm.net/cc/). 3D point cloud and mesh processing software
Open Source Project
- [**OpenFlipper**](http://www.openflipper.org/). An Open Source Geometry Processing and Rendering Framework
- [**PotreeDesktop**](https://github.com/potree/PotreeDesktop). A desktop/portable version of the web-based point cloud viewer [**Potree**](https://github.com/potree/potree)
- [**3d-annotation-tool**](https://github.com/StrayRobots/3d-annotation-tool). A lightweight desktop application to annotate pointclouds for machine learning.
## Servers
- [**LOPoCS**](https://oslandia.github.io/lopocs/) is a point cloud server written in Python
- [**Greyhound**](https://github.com/hobu/greyhound) is a server designed to deliver points from Entwine octrees
## Web-based point cloud viewers
- [**Potree**](https://github.com/potree/potree) is a web-based octree viewer written in Javascript.
## Conferences
- [**International LiDAR Mapping Forum**](https://www.lidarmap.org/) International LiDAR Mapping Forum (ILMF)
- [**3D-ARCH**](http://www.3d-arch.org/) is a series of international workshops to discuss steps and processes for smart 3D reconstruction, modelling, accessing and understanding of digital environments from multiple data sources.
- [**Geo Business**](https://www.geobusinessshow.com/programme/) Geospatial event with many 3D Point clound and LiDAR presentations.
- [**LiDAR Comex**](https://lidarcomex.com/) The Lidar Commercial Expo.
## Community
- [**Laser Scanning Forum**](https://www.laserscanningforum.com/forum/) Laser Scanning Forum
- [**PCL Discord**](https://discord.com/invite/JFFMAXS) Point Cloud Library (PCL) Discord channel.
## Papers
[awesome-point-cloud-analysis](https://github.com/Yochengliu/awesome-point-cloud-analysis) for anyone who wants to do research about 3D point cloud.
[Efficient Processing of Large 3D Point Clouds](https://www.researchgate.net/publication/233792575_Efficient_Processing_of_Large_3D_Point_Clouds) Jan Elseberg, Dorit Borrmann, Andreas N̈uchtre, Proceedings of the XXIII International Symposium on Information, Communication and Automation Technologies (ICAT '11), 2011
[Data Structure for Efficient Processing in 3-D](http://www.roboticsproceedings.org/rss01/p48.pdf) Jean-François Lalonde, Nicolas Vandapel and Martial Hebert, Robotics: Science and Systems I, 2005
[An out-of-core octree for massive point cloud processing](http://rs.tudelft.nl/~rlindenbergh/workshop/WenzelIQmulus.pdf) K. Wenzel, M. Rothermel, D. Fritsch, N. Haala, Workshop on Processing Large Geospatial Data 2014
## News
[LiDAR News](https://lidarnews.com/) About 3D laser scanning and lidar, along with a number of related technologies such as unmanned aerial systems – UASs and photogrammetry.
[LiDAR Mag](https://lidarmag.com/) Magazine about LiDARs.
[Wired](https://www.wired.com/tag/lidar/) The WIRED conversation illuminates how technology is changing every aspect of our lives—from culture to business, science to design.
[GIM International](https://www.gim-international.com/news/lidar) GIM International is the independent and high-quality information source for everything the global geomatics industry has to offer.
| {
"repo_name": "mmolero/awesome-point-cloud-processing",
"stars": "650",
"repo_language": "None",
"file_name": "README.md",
"mime_type": "text/plain"
} |
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
# v2.0.4 (Sun Aug 13 2023)
#### ⚠️ Pushed to `main`
- misc(build): smaller tsup external ([@JesusTheHun](https://github.com/JesusTheHun))
- misc: add package/ to gitignore ([@JesusTheHun](https://github.com/JesusTheHun))
- Merge branch 'fix/runtime-package.json' ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(panel): catch failed npmjs requests ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(panel): get version from package.json at runtime ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v2.0.3 (Fri Aug 11 2023)
#### ⚠️ Pushed to `main`
- fix(panel): duplicate event key when hmr triggers ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v2.0.2 (Fri Aug 04 2023)
#### ⚠️ Pushed to `main`
- test(event): the suffix of the first event is now 1 ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(event): duplicate event key when hmr triggers before any new event ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(panel): use template literal for styled components ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v2.0.1 (Fri Aug 04 2023)
#### ⚠️ Pushed to `main`
- feat(panel): add banner when a new version is available ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(panel): update panel registration title to return a ReactElement ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(npm): add required package at build time to dev deps ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(helper): remove forgotten log statement ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v1.0.2 (Thu Jun 01 2023)
#### ⚠️ Pushed to `main`
- feat(readme): add table of available parameters ([@JesusTheHun](https://github.com/JesusTheHun))
- feat(readme): changelog ([@JesusTheHun](https://github.com/JesusTheHun))
- feat(decorator): add support for route id ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v1.0.1 (Tue May 23 2023)
#### ⚠️ Pushed to `main`
- feat(npm): bump react-inspector version ([@JesusTheHun](https://github.com/JesusTheHun))
- feat(npm): update dependencies ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.6 (Wed May 03 2023)
#### ⚠️ Pushed to `main`
- fix(router): rebuild router only after story args changed ([@JesusTheHun](https://github.com/JesusTheHun))
- feat(decorator): add support for shouldRevalidate function ([@JesusTheHun](https://github.com/JesusTheHun))
- fix(controls): router not reloading component after change through SB controls ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.5 (Fri Mar 24 2023)
#### ⚠️ Pushed to `main`
- fix: reloading component should not trigger a console warning ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.4 (Mon Mar 20 2023)
#### ⚠️ Pushed to `main`
- fix: log of action with file upload ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.3 (Mon Mar 20 2023)
#### ⚠️ Pushed to `main`
- fix: story decorator not passing errorElement to the wrapping component ([@JesusTheHun](https://github.com/JesusTheHun))
- fix: story decorator not passing routeHandle to the wraping component ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.2 (Sun Mar 19 2023)
#### ⚠️ Pushed to `main`
- feat: add support for route handle ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.3.1 (Wed Mar 15 2023)
#### ⚠️ Pushed to `main`
- fix(ts): restore ts rootDir to src ([@JesusTheHun](https://github.com/JesusTheHun))
- misc(npm): bump version ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.2.2 (Mon Mar 13 2023)
#### ⚠️ Pushed to `main`
- feat(readme): add data router information ([@JesusTheHun](https://github.com/JesusTheHun))
- feat(ci): add tests to CI steps ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: ts strict ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: ci ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: log route loader ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: log route outlet action ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: log route action ([@JesusTheHun](https://github.com/JesusTheHun))
- fix: faulty router initialization ([@JesusTheHun](https://github.com/JesusTheHun))
- wip: tests ([@JesusTheHun](https://github.com/JesusTheHun))
- wip: impl ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.15 (Tue Aug 30 2022)
#### ⚠️ Pushed to `main`
- fix: event order ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: support for descendant routes ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.14 (Fri Aug 19 2022)
#### ⚠️ Pushed to `main`
- feat: support for easy outlet ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.13 (Tue Aug 02 2022)
#### ⚠️ Pushed to `main`
- fix: query string question mark inconsistencies ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.12 (Tue Aug 02 2022)
#### ⚠️ Pushed to `main`
- test: add basic nested routing stories ([@JesusTheHun](https://github.com/JesusTheHun))
- change(event): remove matchedRoutes prop as the fix cannot be delivered before the next react-router version ([@JesusTheHun](https://github.com/JesusTheHun))
- fix: double parsing of route pattern ([@JesusTheHun](https://github.com/JesusTheHun))
- readme: add tiny contribution guideline ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.11 (Fri Jul 29 2022)
#### ⚠️ Pushed to `main`
- readme: add doc about location state ([@JesusTheHun](https://github.com/JesusTheHun))
- test: add stories to test location state ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: add support for location state ([@JesusTheHun](https://github.com/JesusTheHun))
- misc: improve event properties order & consistency ([@JesusTheHun](https://github.com/JesusTheHun))
- misc: set node version to 16.15.1 ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.10 (Thu Jun 23 2022)
#### ⚠️ Pushed to `main`
- fix: react-inspector is core dep not devDep ([@JesusTheHun](https://github.com/JesusTheHun))
- readme: add compatibility mentions ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.9 (Wed Jun 22 2022)
#### ⚠️ Pushed to `main`
- patch addon to support both React 17 & 18 ([@JesusTheHun](https://github.com/JesusTheHun))
- bump to node version 16 ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: add support for React 18 ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.8 (Mon Jun 06 2022)
#### ⚠️ Pushed to `main`
- attempt to fix badges in storybook catalog ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.7 (Wed May 11 2022)
#### ⚠️ Pushed to `main`
- fix: double initial rendering navigation event ([@JesusTheHun](https://github.com/JesusTheHun))
- misc: better event name ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: initial rendering no longer increment the counter in the panel title ([@JesusTheHun](https://github.com/JesusTheHun))
- feat: use header component to test router decorator ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.6 (Wed May 11 2022)
#### ⚠️ Pushed to `main`
- fix: remove default preview decorator ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.5 (Wed May 11 2022)
#### ⚠️ Pushed to `main`
- export withRouter decorator ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.4 (Wed May 11 2022)
#### ⚠️ Pushed to `main`
- readme: improve overall documentation ([@JesusTheHun](https://github.com/JesusTheHun))
- readme: improve the getting started section ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
---
# v0.1.1 (Wed May 11 2022)
#### ⚠️ Pushed to `main`
- add some badges ([@JesusTheHun](https://github.com/JesusTheHun))
- change license to Unlicense ([@JesusTheHun](https://github.com/JesusTheHun))
- fix: wrong storybook catalog icon ([@JesusTheHun](https://github.com/JesusTheHun))
#### Authors: 1
- Jesus The Hun ([@JesusTheHun](https://github.com/JesusTheHun))
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
# Upgrade from v1 to v2
The `v2` makes a clear distinction between routing declaration and the browser location.
Here is a simplified view of the two APIs :
```tsx
// v1
type ReactRouterAddonStoryParameters = {
routeId: string;
routePath: string;
routeParams: {};
routeState: any;
routeHandle: any;
searchParams: {};
outlet: React.ReactNode | OutletProps;
browserPath: string;
loader: LoaderFunction;
action: ActionFunction;
errorElement: React.ReactNode;
hydrationData: HydrationState;
shouldRevalidate: ShouldRevalidateFunction;
};
// v2
type ReactRouterAddonStoryParameters = {
hydrationData: HydrationState;
location: {
path: string | Function;
pathParams: {};
searchParams: {};
hash: string;
state: any;
};
routing: string | RouteObject | RouteObject[]; // <= You can now use react-router native configuration
};
```
Before
```tsx
export const UserProfile = {
render: <UserProfile />,
parameters: {
reactRouter: {
routePath: '/users/:userId',
routeParams: { userId: '42' },
},
},
};
```
New version, verbose
```tsx
export const UserProfile = {
render: <UserProfile />,
parameters: {
// Note the helper function 👇 that provide auto-completion and type safety
reactRouter: reactRouterParameters({
location: {
path: '/users/:userId',
pathParams: { userId: 42 },
},
routing: [
{
path: '/users/:userId',
},
],
}),
},
};
```
To limit the verbosity, you can do two things :
1. `routing` : if you only want to set the path of the story you can use a `string`. Also, if you have a single route, you can pass an object instead of an array of object.
2. `location` : you can omit `location.path` if the path you want is the joined `path`s defined in your `routing`.
New version, using shorthands
```tsx
export const UserProfile = {
render: <UserProfile />,
parameters: {
// Note the helper function 👇 that provide auto-completion and type safety
reactRouter: reactRouterParameters({
location: {
pathParams: { userId: 42 },
},
routing: '/users/:userId',
}),
},
};
```
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
restoreMocks: true,
unstubEnvs: true,
unstubGlobals: true,
setupFiles: ['./src/setupTests.ts'],
threads: true,
testTimeout: 20000,
},
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
## V1 Documentation - Legacy
Only supports for Storybook 7
## Getting Started
Install the package
```
yarn add -D storybook-addon-react-router-v6
```
Add it to your storybook configuration:
```js
// .storybook/main.ts
module.exports = {
addons: ['storybook-addon-react-router-v6'],
};
```
## How to use it as a component decorator
To add the router to all the stories of a component, simply add it to the `decorators` array.
Note that the `parameters.reactRouter` property is optional, by default the router will render the component at `/`.
```tsx
import { withRouter } from 'storybook-addon-react-router-v6';
export default {
title: 'User Profile',
component: UserProfile,
decorators: [withRouter],
parameters: {
reactRouter: {
routePath: '/users/:userId',
routeParams: { userId: '42' },
},
},
};
export const Example = () => <UserProfile />;
```
## Usage at the story level
If you want to change the router config just for one story you can do the following :
```tsx
import { withRouter } from 'storybook-addon-react-router-v6';
export default {
title: 'User Profile',
component: UserProfile,
decorators: [withRouter],
};
export const Example = () => <UserProfile />;
Example.story = {
parameters: {
reactRouter: {
routePath: '/users/:userId',
routeParams: { userId: '42' },
routeHandle: 'Profile',
searchParams: { tab: 'activityLog' },
routeState: { fromPage: 'homePage' },
},
},
};
```
## Define a global default
If you want you can wrap all your stories inside a router by adding the decorator in your `preview.js` file.
```ts
// preview.js
export const decorators = [withRouter];
// you can also define global defaults parameters
export const parameters = {
reactRouter: {
// ...
},
};
```
## Data Router
If you use the data routers of `react-router 6.4+`, such as `<BrowserRouter />`, you can use the following properties :
```js
export const Example = () => <Articles />;
Example.story = {
parameters: {
reactRouter: {
routePath: '/articles',
loader: fetchArticlesFunction,
action: articlesActionFunction,
errorElement: <FancyErrorComponent />,
},
},
};
```
## Outlet
If your component renders an outlet, you can set the `outlet` property :
```js
export const Example = () => <Articles />;
Example.story = {
parameters: {
reactRouter: {
routePath: '/articles',
outlet: {
element: <Article />,
handle: 'Article',
path: ':articleId',
loader: yourLoaderFunction,
action: yourActionFunction,
errorElement: <FancyErrorComponent />,
},
// Or simply
outlet: <MostRecentArticles />,
},
},
};
```
## Descendant Routes
`<Route>` can be nested to handle layouts & outlets.
But components can also render a `<Routes>` component with its set of `<Route>`, leading to a deep nesting called `Descendant Routes`.
In this case, in order for the whole component tree to render in your story with matching params, you will need to set the `browserPath` property :
```js
export default {
title: 'Descendant Routes',
component: SettingsPage, // this component renders a <Routes> with several <Route> with path like `billing` or `privacy`
decorators: [withRouter],
};
Default.story = {
parameters: {
reactRouter: {
browserPath: '/billing',
},
},
};
// If you want to render at a specific path, like `/settings`, React Router requires that you add a trailing wildcard
SpecificPath.story = {
parameters: {
reactRouter: {
routePath: '/settings/*',
browserPath: '/settings/billing',
},
},
};
```
## Dedicated panel
Navigation events, loader and actions are logged, for you to better understand the lifecycle of your components.

## Available Parameters
Every parameter is optional. In most cases they follow the same type used by Route Router itself, sometimes they offer a sugar syntax.
| Parameter | Type | Description |
| ---------------- | ------------------------------------------------------------------- | ------------------------------------------------------------- |
| routePath | `string` | i.e: `/users/:userId` |
| routeParams | `Record<string, string>` | i.e: `{ userId: "777" }` |
| routeState | `any` | Available through `useLocation()` |
| routeHandle | `any` | Available through `useMatches()` |
| searchParams | `string[][] \| Record<string, string> \| string \| URLSearchParams` | Location query string `useSearchParams()` |
| outlet | `React.ReactNode \| OutletProps` | Outlet rendered by the route. See type `OutletProps` below. |
| browserPath | `string` | Useful when you have [descendant routes](#descendant-routes). |
| loader | `LoaderFunction` | |
| action | `ActionFunction` | |
| errorElement | `React.ReactNode \| null` | |
| hydrationData | `HydrationState` | |
| shouldRevalidate | `ShouldRevalidateFunction` | |
| routeId | `string` | Available through `useMatches()` |
```ts
type OutletProps = {
element: React.ReactNode;
path?: string;
handle?: unknown;
loader?: LoaderFunction;
action?: ActionFunction;
errorElement?: React.ReactNode | null;
};
```
## Compatibility
✅ Storybook 7.0
✅ React 16
✅ React 17
✅ React 18
If you face an issue with any version, open an issue.
## Contribution
Contributions are welcome.
Before writing any code, file an issue to showcase the bug or the use case for the feature you want to see in this addon.
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
export * from './dist/manager';
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { defineConfig } from 'tsup';
export default defineConfig((options) => ({
entry: ['src/index.ts', 'src/manager.tsx'],
splitting: false,
minify: !options.watch,
format: ['cjs', 'esm'],
dts: {
resolve: true,
},
treeshake: true,
sourcemap: true,
clean: true,
platform: 'browser',
esbuildOptions(options) {
options.conditions = ['module'];
options.external = ['./package.json'];
},
}));
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
# Storybook Addon React Router v6
[](https://storybook.js.org)
[](https://www.npmjs.com/package/storybook-addon-react-router-v6)
[](https://github.com/JesusTheHun/storybook-addon-react-router-v6/actions/workflows/release.yml)

> Use React Router v6 in your stories.
## New major version
The new version brings more **flexibility**, **type safety** and helper functions !
The upgrade is quite simple. An [upgrade guide](UPGRADE_V1_V2.md) is available.
### Deprecated parameters
The parameters you used with the previous version are now deprecated but they still work.
The old documentation remains accessible : [v1 documentation](DOCUMENTATION_V1.md).
## Getting Started
Install the package
```
yarn add -D storybook-addon-react-router-v6
```
Add it to your storybook configuration:
```js
// .storybook/main.ts
export default {
addons: ['storybook-addon-react-router-v6'],
} satisfies StorybookConfig;
```
## Decorate all stories of a component
To add the router to all the stories of a component, simply add it to the `decorators` array.
Note that `parameters.reactRouter` is optional, by default the router will render the component at `/`.
```tsx
import { withRouter } from 'storybook-addon-react-router-v6';
export default {
title: 'User Profile',
render: () => <UserProfile />,
decorators: [withRouter],
parameters: {
reactRouter: reactRouterParameters({
location: {
pathParams: { userId: '42' },
},
routing: { path: '/users/:userId' },
}),
},
};
```
## Decorate a specific story
To change the config for a single story, you can do the following :
```tsx
import { withRouter } from 'storybook-addon-react-router-v6';
export default {
title: 'User Profile',
render: () => <UserProfile />,
decorators: [withRouter],
};
export const FromHomePage = {
parameters: {
reactRouter: reactRouterParameters({
location: {
pathParams: { userId: '42' },
searchParams: { tab: 'activityLog' },
state: { fromPage: 'homePage' },
},
routing: {
path: '/users/:userId',
handle: 'Profile',
},
}),
},
};
```
## Decorate all stories, globally
To wrap all your project's stories inside a router by adding the decorator in your `preview.js` file.
```ts
// .storybook/preview.js
export default {
decorators: [withRouter],
parameters: {
reactRouter: reactRouterParameters({ ... }),
}
} satisfies Preview;
```
## Location
To specify anything related to the browser location, use the `location` property.
```tsx
type LocationParameters = {
path?: string | ((inferredPath: string, pathParams: Record<string, string>) => string | undefined);
pathParams?: PathParams;
searchParams?: ConstructorParameters<typeof URLSearchParams>[0];
hash?: string;
state?: unknown;
};
```
### Inferred path
If `location.path` is not provided, the browser pathname will be generated using the joined `path`s from the `routing` property and the `pathParams`.
### Path as a function
You can provide a function to `path`.
It will receive the joined `path`s from the routing property and the `pathParams` as parameters.
If the function returns a `string`, is will be used _as is_. It's up to you to call `generatePath` from `react-router` if you need to.
If the function returns `undefined`, it will fallback to the default behavior, just like if you didn't provide any value for `location.path`.
## Routing
You can set `routing` to anything accepted by `createBrowserRouter`.
To make your life easier, `storybook-addon-react-router-v6` comes with some routing helpers :
```tsx
export const MyStory = {
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet(<MyOutlet />),
}),
},
};
```
### Routing Helpers
The following helpers are available out of the box :
```ts
reactRouterOutlet(); // Render a single outlet
reactRouterOutlets(); // Render multiple outlets
reactRouterNestedOutlets(); // Render multiple outlets nested one into another
reactRouterNestedAncestors(); // Render the story as an outlet of nested outlets
```
You can also create your own helper and use the exported type `RoutingHelper` to assist you :
```ts
import { RoutingHelper } from 'storybook-addon-react-router-v6';
const myCustomHelper: RoutingHelper = () => {
// Routing creation logic
};
```
`RouterRoute` is basically the native `RouteObject` from `react-router`; augmented with `{ useStoryElement?: boolean }`.
If you want to accept a JSX and turn it into a `RouterRoute`, you can use the exported function `castRouterRoute`.
### Use the story as the route element
Just set `{ useStoryElement: true }` in the routing config object.
## Dedicated panel
Navigation events, loader and actions are logged, for you to better understand the lifecycle of your components.

## Compatibility
This package aims to support `Storybook > 7` and `React > 16`.
✅ Storybook 7.0
✅ React 16
✅ React 17
✅ React 18
If you have an issue with any version, open an issue.
## Contribution
Contributions are welcome.
Before writing any code, file an issue to showcase the bug or the use case for the feature you want to see in this addon.
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
name: Release
on: [push]
jobs:
release:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, 'ci skip') && !contains(github.event.head_commit.message, 'skip ci')"
steps:
- uses: actions/checkout@v3
- name: Prepare repository
run: git fetch --unshallow --tags
- name: Use Node.js 18.x
uses: actions/setup-node@v1
with:
node-version: 18.x
- name: Install dependencies
uses: bahmutov/npm-install@v1
- name: Tests
run: yarn test:ci
- name: Create Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
yarn release
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { withRouter } from './features/decorator/withRouter';
import { reactRouterParameters } from './features/decorator/utils/routesHelpers/reactRouterParameters';
import { reactRouterOutlet } from './features/decorator/utils/routesHelpers/reactRouterOutlet';
import { reactRouterOutlets } from './features/decorator/utils/routesHelpers/reactRouterOutlets';
import { reactRouterNestedOutlets } from './features/decorator/utils/routesHelpers/reactRouterNestedOutlets';
import { reactRouterNestedAncestors } from './features/decorator/utils/routesHelpers/reactRouterNestedAncestors';
import { castRouterRoute } from './features/decorator/utils/castRouterRoute';
import type { ReactRouterAddonStoryParameters } from './features/decorator/components/ReactRouterDecorator';
import type {
RouteDefinition,
NonIndexRouteDefinition,
NonIndexRouteDefinitionObject,
RouteDefinitionObject,
RouterRoute,
RoutingHelper,
} from './features/decorator/types';
export {
withRouter,
reactRouterParameters,
reactRouterOutlet,
reactRouterOutlets,
reactRouterNestedOutlets,
reactRouterNestedAncestors,
castRouterRoute,
};
export type {
RouterRoute,
ReactRouterAddonStoryParameters,
RouteDefinition,
NonIndexRouteDefinition,
NonIndexRouteDefinitionObject,
RouteDefinitionObject,
RoutingHelper,
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React, { PropsWithChildren } from 'react';
export type FCC<T = unknown> = React.FC<PropsWithChildren<T>>;
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
// @ts-ignore
import packageJson from '../package.json';
export const ADDON_ID = 'storybook/react-router-v6';
export const PANEL_ID = `${ADDON_ID}/panel`;
export const PARAM_KEY = `reactRouter`;
export const EVENTS = {
CLEAR: `${ADDON_ID}/clear`,
NAVIGATION: `${ADDON_ID}/navigation`,
STORY_LOADED: `${ADDON_ID}/story-loaded`,
ROUTE_MATCHES: `${ADDON_ID}/route-matches`,
ACTION_INVOKED: `${ADDON_ID}/action_invoked`,
ACTION_SETTLED: `${ADDON_ID}/action_settled`,
LOADER_INVOKED: `${ADDON_ID}/loader_invoked`,
LOADER_SETTLED: `${ADDON_ID}/loader_settled`,
} as const;
export const ADDON_VERSION = packageJson.version;
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { addons, types } from '@storybook/manager-api';
import React from 'react';
import { ADDON_ID, PANEL_ID, PARAM_KEY } from './constants';
import { Panel } from './features/panel/components/Panel';
import { PanelTitle } from './features/panel/components/PanelTitle';
addons.register(ADDON_ID, (api) => {
addons.add(PANEL_ID, {
type: types.PANEL,
paramKey: PARAM_KEY,
title: <PanelTitle />,
match: ({ viewMode }) => viewMode === 'story',
render: ({ active }) => <Panel active={active || false} api={api} key={ADDON_ID} />,
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import '@testing-library/jest-dom';
import { vi, expect, beforeEach } from 'vitest';
import matchers from '@testing-library/jest-dom/matchers';
import { fetch, Request, Response } from '@remix-run/web-fetch';
import { mockLocalStorage } from './utils/test-utils';
expect.extend(matchers);
beforeEach(() => {
mockLocalStorage();
vi.stubGlobal('fetch', fetch);
vi.stubGlobal('Request', Request);
vi.stubGlobal('Response', Response);
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { makeDecorator } from '@storybook/preview-api';
import React from 'react';
import { PARAM_KEY } from '../../constants';
import { ReactRouterDecorator, ReactRouterDecoratorProps } from './components/ReactRouterDecorator';
import { castParametersV2 } from './utils/castParametersV2';
export const withRouter = makeDecorator({
name: 'withRouter',
parameterName: PARAM_KEY,
wrapper: (getStory, context, { parameters }) => {
const v2parameters = castParametersV2(parameters);
return (
<ReactRouterDecorator
renderStory={getStory as unknown as ReactRouterDecoratorProps['renderStory']}
storyContext={context as ReactRouterDecoratorProps['storyContext']}
parameters={v2parameters}
/>
);
},
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { HydrationState } from '@remix-run/router';
import React from 'react';
import { LazyRouteFunction, RouteObject } from 'react-router';
import { Overwrite, PromiseType } from 'utility-types';
import { Merge } from '../../utils/type-utils';
export type RouterParameters = {
hydrationData?: HydrationState;
routing?: string | RouterRoute | [RouterRoute, ...RouterRoute[]];
};
export type LocationParameters<PathParams extends Record<string, string | number> = Record<string, string | number>> = {
path?: string | ((inferredPath: string, pathParams: PathParams) => string | undefined);
pathParams?: PathParams;
searchParams?: ConstructorParameters<typeof URLSearchParams>[0];
hash?: string;
state?: unknown;
};
export type NavigationHistoryEntry = LocationParameters & {
isInitialLocation?: boolean;
};
export type RouterRoute = Overwrite<RouteObject, { children?: RouterRoute[] }> & StoryRouteIdentifier;
export type RouteDefinition = React.ReactElement | RouteDefinitionObject;
export type NonIndexRouteDefinition = React.ReactElement | NonIndexRouteDefinitionObject;
export type RouteDefinitionObject = Merge<Omit<RouteObject, 'children'> & StoryRouteIdentifier>;
export type NonIndexRouteDefinitionObject = RouteDefinitionObject & { index?: false };
export type StoryRouteIdentifier = { useStoryElement?: boolean };
type Params<Path extends string> = Record<string, never> extends RouteParamsFromPath<Path>
? { path?: Path }
: { path: Path; params: RouteParamsFromPath<Path> };
type PushRouteParam<
Segment extends string | undefined,
RouteParams extends Record<string, unknown> | unknown
> = Segment extends `:${infer ParamName}` ? { [key in ParamName | keyof RouteParams]: string } : RouteParams;
export type RouteParamsFromPath<Path extends string | undefined> =
Path extends `${infer CurrentSegment}/${infer RemainingPath}`
? PushRouteParam<CurrentSegment, RouteParamsFromPath<RemainingPath>>
: PushRouteParam<Path, unknown>;
type LazyReturnType<T extends RouteDefinitionObject> = T extends {
lazy?: infer Lazy extends LazyRouteFunction<RouteObject>;
}
? PromiseType<ReturnType<Lazy>>
: never;
export type RoutingHelper = (...args: never[]) => [RouterRoute, ...RouterRoute[]];
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { DeepRouteMatchesContext } from '../components/DeepRouteMatches';
export const useDeepRouteMatches = () => {
return React.useContext(DeepRouteMatchesContext);
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { addons } from '@storybook/preview-api';
import { useCallback } from 'react';
import { LoaderFunction, LoaderFunctionArgs } from 'react-router';
import { EVENTS } from '../../../constants';
import { useDataEventBuilder } from './useDataEventBuilder';
export function useLoaderDecorator() {
const channel = addons.getChannel();
const createEventData = useDataEventBuilder();
return useCallback(
(loader: LoaderFunction) =>
async function (loaderArgs: LoaderFunctionArgs) {
if (loader === undefined) return;
channel.emit(EVENTS.LOADER_INVOKED, await createEventData(EVENTS.LOADER_INVOKED, loaderArgs));
const loaderResult = await loader(loaderArgs);
channel.emit(EVENTS.LOADER_SETTLED, await createEventData(EVENTS.LOADER_SETTLED, loaderResult));
return loaderResult;
},
[channel, createEventData]
);
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { ActionFunctionArgs } from '@remix-run/router/utils';
import { addons } from '@storybook/preview-api';
import { useCallback } from 'react';
import { ActionFunction } from 'react-router';
import { EVENTS } from '../../../constants';
import { useDataEventBuilder } from './useDataEventBuilder';
export function useActionDecorator() {
const channel = addons.getChannel();
const createEventData = useDataEventBuilder();
return useCallback(
(action: ActionFunction) =>
async function (actionArgs: ActionFunctionArgs) {
if (action === undefined) return;
channel.emit(EVENTS.ACTION_INVOKED, await createEventData(EVENTS.ACTION_INVOKED, actionArgs));
const actionResult = await action(actionArgs);
channel.emit(EVENTS.ACTION_SETTLED, await createEventData(EVENTS.ACTION_SETTLED, actionResult));
return actionResult;
},
[channel, createEventData]
);
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import type { RouterDataEvent, DataEventArgs, RouterDataEventName } from '../../panel/types';
import { useCallback, useRef } from 'react';
import { EVENTS } from '../../../constants';
import { getHumanReadableBody } from '../utils/getHumanReadableBody';
export const useDataEventBuilder = () => {
const eventCount = useRef(0);
return useCallback(
async (
eventName: RouterDataEventName,
eventArgs?: DataEventArgs[keyof DataEventArgs]
): Promise<RouterDataEvent> => {
eventCount.current++;
const key = `${eventName}_${eventCount.current}`;
switch (eventName) {
case EVENTS.ACTION_INVOKED: {
const { request, params, context } = eventArgs as DataEventArgs[typeof eventName];
const requestData = {
url: request.url,
method: request.method,
body: await getHumanReadableBody(request),
};
const data = { params, request: requestData, context };
return { key, type: eventName, data };
}
case EVENTS.ACTION_SETTLED: {
return { key, type: eventName, data: eventArgs };
}
case EVENTS.LOADER_INVOKED: {
const { request, params, context } = eventArgs as DataEventArgs[typeof eventName];
const requestData = {
url: request.url,
method: request.method,
body: await getHumanReadableBody(request),
};
const data = { params, request: requestData, context };
return { key, type: eventName, data };
}
case EVENTS.LOADER_SETTLED: {
return { key, type: eventName, data: eventArgs };
}
}
},
[]
);
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { useRef } from 'react';
import { useLocation, useNavigationType, useParams, useSearchParams } from 'react-router-dom';
import { ValuesType } from 'utility-types';
import { EVENTS } from '../../../constants';
import type { RouterNavigationEvent, RouterNavigationEventName, RouteMatchesData } from '../../panel/types';
import { searchParamsToRecord } from '../utils/searchParamsToRecord';
import { useCurrentUrl } from './useCurrentUrl';
import { useDeepRouteMatches } from './useDeepRouteMatches';
export const useNavigationEventBuilder = () => {
const eventCount = useRef(0);
const location = useLocation();
const params = useParams();
const [search] = useSearchParams();
const navigationType = useNavigationType();
const matches = useDeepRouteMatches();
const searchParams = searchParamsToRecord(search);
const currentUrl = useCurrentUrl();
const matchesData: RouteMatchesData = matches.map((routeMatch) => {
const match: ValuesType<RouteMatchesData> = {
path: routeMatch.route.path,
};
if (Object.keys(routeMatch.params).length > 0) {
match.params = routeMatch.params;
}
return match;
});
const locationData = {
url: currentUrl,
path: location.pathname,
routeParams: params,
searchParams,
hash: location.hash,
routeState: location.state,
routeMatches: matchesData,
};
return (eventName: RouterNavigationEventName): RouterNavigationEvent => {
eventCount.current++;
const key = `${eventName}_${eventCount.current}`;
switch (eventName) {
case EVENTS.STORY_LOADED: {
return { key, type: eventName, data: locationData };
}
case EVENTS.NAVIGATION: {
return { key, type: eventName, data: { ...locationData, navigationType } };
}
case EVENTS.ROUTE_MATCHES: {
return { key, type: eventName, data: { matches: matchesData } };
}
}
};
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { useState } from 'react';
import { UNSAFE_RouteContext } from 'react-router';
import { RouteMatch } from 'react-router-dom';
type Ctx = {
_currentValue?: { matches: RouteMatch[] };
};
export function useRouteContextMatches() {
const [deepRouteMatches, setDeepRouteMatches] = useState<RouteMatch[]>([]);
const RouteContext = UNSAFE_RouteContext as unknown as { Provider: { _context: Ctx } };
RouteContext.Provider._context = new Proxy(RouteContext.Provider._context ?? {}, {
set(target: Ctx, p: keyof Ctx, v: Ctx[keyof Ctx]) {
if (p === '_currentValue') {
if (v !== undefined) {
setDeepRouteMatches((currentMatches) => {
if (v.matches.length > currentMatches.length) {
return v.matches;
}
return currentMatches;
});
}
}
return Reflect.set(target, p, v);
},
});
return deepRouteMatches;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { useLocation } from 'react-router-dom';
export const useCurrentUrl = () => {
const location = useLocation();
return `${location.pathname}${location.search}${location.hash}`;
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { useCallback } from 'react';
import { RouterRoute } from '../types';
import { useActionDecorator } from './useActionDecorator';
import { useLoaderDecorator } from './useLoaderDecorator';
export function useRouteObjectsDecorator() {
const decorateAction = useActionDecorator();
const decorateLoader = useLoaderDecorator();
const decorateRouteObjects = useCallback(
<T extends RouterRoute[]>(routeDefinitions: T) => {
return routeDefinitions.map((routeDefinition) => {
const { action, loader, children } = routeDefinition;
const augmentedRouteDefinition = { ...routeDefinition };
if (action) {
augmentedRouteDefinition.action = decorateAction(action);
}
if (loader) {
augmentedRouteDefinition.loader = decorateLoader(loader);
}
if (children) {
augmentedRouteDefinition.children = decorateRouteObjects(children);
}
return augmentedRouteDefinition;
});
},
[decorateAction, decorateLoader]
);
return decorateRouteObjects;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { addons } from '@storybook/preview-api';
import React, { useRef } from 'react';
import { RouteMatch, useLocation } from 'react-router-dom';
import { EVENTS } from '../../../constants';
import { FCC } from '../../../fixes';
import { useDeepRouteMatches } from '../hooks/useDeepRouteMatches';
import { useNavigationEventBuilder } from '../hooks/useNavigationEventBuilder';
export const RouterLogger: FCC = ({ children }) => {
const channel = addons.getChannel();
const location = useLocation();
const matches = useDeepRouteMatches();
const buildEventData = useNavigationEventBuilder();
const storyLoadedEmittedLocationKeyRef = useRef<string>();
const lastNavigationEventLocationKeyRef = useRef<string>();
const lastRouteMatchesRef = useRef<RouteMatch[]>();
const storyLoaded = storyLoadedEmittedLocationKeyRef.current !== undefined;
const shouldEmitNavigationEvents = storyLoaded && location.key !== storyLoadedEmittedLocationKeyRef.current;
if (shouldEmitNavigationEvents && lastNavigationEventLocationKeyRef.current !== location.key) {
channel.emit(EVENTS.NAVIGATION, buildEventData(EVENTS.NAVIGATION));
lastNavigationEventLocationKeyRef.current = location.key;
}
if (shouldEmitNavigationEvents && matches.length > 0 && matches !== lastRouteMatchesRef.current) {
channel.emit(EVENTS.ROUTE_MATCHES, buildEventData(EVENTS.ROUTE_MATCHES));
}
if (!storyLoaded && matches.length > 0) {
channel.emit(EVENTS.STORY_LOADED, buildEventData(EVENTS.STORY_LOADED));
storyLoadedEmittedLocationKeyRef.current = location.key;
lastRouteMatchesRef.current = matches;
}
lastRouteMatchesRef.current = matches;
return <>{children}</>;
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React, { useCallback, useMemo } from 'react';
import { RouteObject } from 'react-router';
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
import { useRouteObjectsDecorator } from '../hooks/useRouteObjectsDecorator';
import { injectStory } from '../utils/InjectStory';
import { normalizeHistory } from '../utils/normalizeHistory';
import { normalizeRouting } from '../utils/normalizeRouting';
import { ReactRouterAddonStoryParameters, ReactRouterDecoratorProps } from './ReactRouterDecorator';
import { RouterLogger } from './RouterLogger';
export type StoryRouterProps = {
renderStory: ReactRouterDecoratorProps['renderStory'];
storyContext: ReactRouterDecoratorProps['storyContext'];
storyParameters: ReactRouterAddonStoryParameters;
};
export function StoryRouter(props: StoryRouterProps) {
const { renderStory, storyContext, storyParameters = {} } = props;
const { hydrationData, routing, navigationHistory, location } = storyParameters;
const decorateRouteObjects = useRouteObjectsDecorator();
const StoryComponent = useCallback(
({ storyContext }: Pick<StoryRouterProps, 'storyContext'>) => renderStory(storyContext),
[renderStory]
);
const memoryRouter = useMemo(() => {
const normalizedRoutes = normalizeRouting(routing);
const decoratedRoutes = decorateRouteObjects(normalizedRoutes);
const injectedRoutes = injectStory(
decoratedRoutes,
<RouterLogger>
<StoryComponent storyContext={storyContext} />
</RouterLogger>
);
const { initialEntries, initialIndex } = normalizeHistory({ navigationHistory, location, routes: injectedRoutes });
return createMemoryRouter(injectedRoutes as RouteObject[], {
initialEntries,
initialIndex,
hydrationData,
});
}, [StoryComponent, decorateRouteObjects, hydrationData, location, navigationHistory, routing, storyContext]);
return <RouterProvider router={memoryRouter} fallbackElement={<Fallback />} />;
}
function Fallback() {
return <p>Performing initial data load</p>;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { beforeEach, describe, it, vi } from 'vitest';
import { composeStories } from '@storybook/react';
import { render, screen, waitFor } from '@testing-library/react';
import { EVENTS } from '../../../constants';
import { addons } from '@storybook/preview-api';
import * as NestingStories from '../../../stories/v2/DescendantRoutes.stories';
import * as ActionStories from '../../../stories/v2/DataRouter/Action.stories';
import * as LoaderStories from '../../../stories/v2/DataRouter/Loader.stories';
import Channel from '@storybook/channels';
import { SpyInstance } from '@vitest/spy';
import userEvent from '@testing-library/user-event';
type LocalTestContext = {
emitSpy: SpyInstance;
};
describe('RouterLogger', () => {
beforeEach<LocalTestContext>((context) => {
const transport = {
setHandler: vi.fn(),
send: vi.fn(),
};
const channelMock = new Channel({ transport });
context.emitSpy = vi.spyOn(channelMock, 'emit');
addons.setChannel(channelMock);
});
it<LocalTestContext>('should log when the story loads', async (context) => {
const { DescendantRoutesTwoRouteMatch } = composeStories(NestingStories);
render(<DescendantRoutesTwoRouteMatch />);
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.STORY_LOADED, {
type: EVENTS.STORY_LOADED,
key: `${EVENTS.STORY_LOADED}_1`,
data: {
url: '/library/13/777',
path: '/library/13/777',
routeParams: { '*': '13/777' },
searchParams: {},
routeMatches: [
{ path: '/library/*', params: { '*': '13/777' } },
{ path: ':collectionId/*', params: { '*': '777', 'collectionId': '13' } },
{ path: ':bookId', params: { '*': '777', 'collectionId': '13', 'bookId': '777' } },
],
hash: '',
routeState: null,
},
});
});
});
it<LocalTestContext>('should log navigation when a link is clicked', async (context) => {
const { DescendantRoutesOneIndex } = composeStories(NestingStories);
render(<DescendantRoutesOneIndex />);
const user = userEvent.setup();
await user.click(screen.getByRole('link', { name: 'Explore collection 13' }));
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.NAVIGATION, {
type: EVENTS.NAVIGATION,
key: expect.stringContaining(EVENTS.NAVIGATION),
data: {
navigationType: 'PUSH',
url: '/library/13',
path: '/library/13',
routeParams: { '*': '13' },
searchParams: {},
routeMatches: [
{ path: '/library/*', params: { '*': '' } },
{ path: undefined, params: { '*': '' } },
],
hash: '',
routeState: null,
},
});
});
});
it<LocalTestContext>('should log new route match when nested Routes is mounted', async (context) => {
const { DescendantRoutesOneIndex } = composeStories(NestingStories);
render(<DescendantRoutesOneIndex />);
const user = userEvent.setup();
await user.click(screen.getByRole('link', { name: 'Explore collection 13' }));
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.ROUTE_MATCHES, {
type: EVENTS.ROUTE_MATCHES,
key: expect.stringContaining(EVENTS.ROUTE_MATCHES),
data: {
matches: [
{ path: '/library/*', params: { '*': '13' } },
{ path: ':collectionId/*', params: { '*': '', 'collectionId': '13' } },
{ path: undefined, params: { '*': '', 'collectionId': '13' } },
],
},
});
});
});
it<LocalTestContext>('should log data router action when triggered', async (context) => {
const { TextFormData } = composeStories(ActionStories);
render(<TextFormData />);
context.emitSpy.mockClear();
const user = userEvent.setup();
await user.click(screen.getByRole('button'));
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(
EVENTS.ACTION_INVOKED,
expect.objectContaining({
type: EVENTS.ACTION_INVOKED,
key: expect.stringContaining(EVENTS.ACTION_INVOKED),
data: expect.objectContaining({
request: {
url: 'http://localhost/',
method: 'POST',
body: {
foo: 'bar',
},
},
}),
})
);
});
});
it<LocalTestContext>('should log file info when route action is triggered', async (context) => {
const { FileFormData } = composeStories(ActionStories);
render(<FileFormData />);
const file = new File(['hello'], 'hello.txt', { type: 'plain/text' });
const input = screen.getByLabelText(/file/i) as HTMLInputElement;
const user = userEvent.setup();
await user.upload(input, file);
await user.click(screen.getByRole('button'));
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.ACTION_INVOKED, {
type: EVENTS.ACTION_INVOKED,
key: expect.stringContaining(EVENTS.ACTION_INVOKED),
data: expect.objectContaining({
request: {
url: 'http://localhost/',
method: 'POST',
body: {
myFile: expect.objectContaining({}),
},
},
}),
});
});
});
it<LocalTestContext>('should log when data router action settled', async (context) => {
const { TextFormData } = composeStories(ActionStories);
render(<TextFormData />);
const user = userEvent.setup();
await user.click(screen.getByRole('button'));
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.ACTION_SETTLED, {
type: EVENTS.ACTION_SETTLED,
key: expect.stringContaining(EVENTS.ACTION_SETTLED),
data: { result: 42 },
});
});
});
it<LocalTestContext>('should log data router loader when triggered', async (context) => {
const { RouteAndOutletLoader } = composeStories(LoaderStories);
render(<RouteAndOutletLoader />);
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.LOADER_INVOKED, {
type: EVENTS.LOADER_INVOKED,
key: expect.stringContaining(EVENTS.LOADER_INVOKED),
data: expect.objectContaining({
request: expect.anything(),
}),
});
});
});
it<LocalTestContext>('should log when data router loader settled', async (context) => {
const { RouteAndOutletLoader } = composeStories(LoaderStories);
render(<RouteAndOutletLoader />);
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.LOADER_SETTLED, {
type: EVENTS.LOADER_SETTLED,
key: expect.stringContaining(EVENTS.LOADER_SETTLED),
data: { foo: 'Data loaded' },
});
});
await waitFor(() => {
expect(context.emitSpy).toHaveBeenCalledWith(EVENTS.LOADER_SETTLED, {
type: EVENTS.LOADER_SETTLED,
key: expect.stringContaining(EVENTS.LOADER_SETTLED),
data: { foo: 'Outlet data loaded' },
});
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { RouteMatch } from 'react-router-dom';
export const DeepRouteMatchesContext = React.createContext<RouteMatch[]>([]);
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { useRouteContextMatches } from '../hooks/useRouteContextMatches';
import { LocationParameters, NavigationHistoryEntry, RouterParameters } from '../types';
import { DeepRouteMatchesContext } from './DeepRouteMatches';
import { StoryRouter } from './StoryRouter';
export type ReactRouterDecoratorProps = {
renderStory: (context: unknown) => React.ReactElement;
storyContext: unknown;
parameters: ReactRouterAddonStoryParameters;
};
export type ReactRouterAddonStoryParameters =
| (RouterParameters & {
location?: LocationParameters;
navigationHistory?: never;
})
| (RouterParameters & {
location?: never;
navigationHistory: [NavigationHistoryEntry, ...NavigationHistoryEntry[]];
});
export const ReactRouterDecorator: React.FC<ReactRouterDecoratorProps> = ({
renderStory,
storyContext,
parameters,
}) => {
const deepRouteMatches = useRouteContextMatches();
return (
<DeepRouteMatchesContext.Provider value={deepRouteMatches}>
<StoryRouter renderStory={renderStory} storyContext={storyContext} storyParameters={parameters} />
</DeepRouteMatchesContext.Provider>
);
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { hasOwnProperty } from '../../../utils/misc';
export function isValidReactNode(e: unknown): e is React.ReactNode {
if (React.isValidElement(e)) return true;
switch (true) {
case React.isValidElement(e):
case typeof e === 'string':
case typeof e === 'number':
case typeof e === 'boolean':
case e === null:
case e === undefined:
case e instanceof Object && hasOwnProperty(e, Symbol.iterator):
return true;
}
return false;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { describe, expect, it } from 'vitest';
import { searchParamsToRecord } from './searchParamsToRecord';
describe('searchParamsToRecord', () => {
it('should have a property for each search param', () => {
const searchParams = new URLSearchParams({
foo: 'bar',
yaz: 'yoz',
});
expect(searchParamsToRecord(searchParams)).toEqual({
foo: 'bar',
yaz: 'yoz',
});
});
it('should merge values of the same param into an array', () => {
const searchParamsTwoValues = new URLSearchParams({
foo: 'bar',
yaz: 'yoz',
});
searchParamsTwoValues.append('foo', 'baz');
expect(searchParamsToRecord(searchParamsTwoValues)).toEqual({
foo: ['bar', 'baz'],
yaz: 'yoz',
});
const searchParamsThreeValues = new URLSearchParams({
foo: 'bar',
yaz: 'yoz',
});
searchParamsThreeValues.append('foo', 'baz');
searchParamsThreeValues.append('foo', 'buz');
expect(searchParamsToRecord(searchParamsThreeValues)).toEqual({
foo: ['bar', 'baz', 'buz'],
yaz: 'yoz',
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
export function searchParamsToRecord(searchParams: URLSearchParams) {
const result: Record<string, string | string[]> = {};
searchParams.forEach((value, key) => {
const currentValue = result[key];
if (typeof currentValue === 'string') {
result[key] = [currentValue, value];
return;
}
if (Array.isArray(currentValue)) {
result[key] = [...currentValue, value];
return;
}
result[key] = value;
});
return result;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { FileSummary, getFormDataSummary } from './getFormDataSummary';
export async function getHumanReadableBody(request: Request) {
const requestClone = request.clone();
const contentTypeHeader = requestClone.headers.get('content-type') || '';
let humanReadableBody: string | Record<string, string | FileSummary> | undefined = undefined;
switch (true) {
case contentTypeHeader.startsWith('text'):
humanReadableBody = await requestClone.text();
break;
case contentTypeHeader.startsWith('application/json'):
humanReadableBody = await requestClone.json();
break;
case contentTypeHeader.startsWith('multipart/form-data'):
case contentTypeHeader.startsWith('application/x-www-form-urlencoded'): {
humanReadableBody = getFormDataSummary(await requestClone.formData());
break;
}
}
return humanReadableBody;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
export type FileSummary = { filename: string; filesize: number; filetype: string };
export function getFormDataSummary(formData: FormData): Record<string, string | FileSummary> {
const data: Record<string, string | FileSummary> = {};
formData.forEach((value, key) => {
if (value instanceof File) {
data[key] = {
filename: value.name,
filesize: value.size,
filetype: value.type,
};
return;
}
data[key] = value;
});
return data;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { generatePath, InitialEntry } from '@remix-run/router';
import { ReactRouterAddonStoryParameters } from '../components/ReactRouterDecorator';
import { RouterRoute } from '../types';
export type NormalizedHistoryParameters = Pick<ReactRouterAddonStoryParameters, 'navigationHistory' | 'location'> & {
routes: RouterRoute[];
};
export function normalizeHistory({ navigationHistory, location, routes }: NormalizedHistoryParameters) {
if (navigationHistory !== undefined) {
const initialEntries: InitialEntry[] = [];
let initialIndex;
const compactNavigationHistory = Object.values(navigationHistory);
for (let i = 0; i < compactNavigationHistory.length; i++) {
const { path: userPath, pathParams, searchParams, hash, state, isInitialLocation } = compactNavigationHistory[i];
if (isInitialLocation) initialIndex = i;
const inferredPath = inferLocationPathFromRoutes(routes);
const computedPath = typeof userPath === 'function' ? userPath(inferredPath, pathParams ?? {}) : userPath;
const path = computedPath ?? inferredPath;
initialEntries.push({
pathname: generatePath(path ?? '/', pathParams),
search: new URLSearchParams(searchParams).toString(),
hash,
state,
});
}
initialIndex ??= initialEntries.length - 1;
return {
initialEntries,
initialIndex,
};
}
const { path: userPath, pathParams, searchParams, hash, state } = location ?? {};
const inferredPath = inferLocationPathFromRoutes(routes);
const computedPath = typeof userPath === 'function' ? userPath(inferredPath, pathParams ?? {}) : userPath;
const path = computedPath ?? inferredPath;
const initialIndex = 0;
const initialEntries: InitialEntry[] = [
{
pathname: generatePath(path, pathParams),
search: new URLSearchParams(searchParams).toString(),
hash,
state,
},
];
return {
initialEntries,
initialIndex,
};
}
export function inferLocationPathFromRoutes(routes: RouterRoute[] = [], basePath = '/'): string {
if (routes.length !== 1) return basePath;
const obviousRoute = routes[0];
const pathToObviousRoute = appendPathSegment(basePath, obviousRoute.path);
if (obviousRoute.children === undefined || obviousRoute.children.length === 0) return pathToObviousRoute;
return inferLocationPathFromRoutes(obviousRoute.children, pathToObviousRoute);
}
export function appendPathSegment(basePath: string, pathSegment = '') {
const blankValues = ['', '/'];
const basePathParts = basePath.split('/').filter((s) => !blankValues.includes(s));
const pathSegmentParts = pathSegment.split('/').filter((s) => !blankValues.includes(s));
const parts = [...basePathParts, ...pathSegmentParts];
return '/' + parts.join('/');
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { describe, it } from 'vitest';
import { injectStory } from './InjectStory';
import { isValidReactNode } from './isValidReactNode';
describe('injectStory', () => {
it('should return an empty array if routes is an empty array', () => {
const result = injectStory([], <h1>StoryComponent</h1>);
expect(result).toEqual([]);
});
it('should return the same routes array if no route has useStoryElement property', () => {
const routes = [
{ path: '/', element: <div /> },
{ path: '/about', element: <div /> },
];
const result = injectStory(routes, <h1>StoryComponent</h1>);
expect(result).toEqual(routes);
expect(result).not.toBe(routes);
});
it('should return the same route array if no route has children property', () => {
const routes = [
{ path: '/', element: <div /> },
{ path: '/about', element: <div /> },
];
const result = injectStory(routes, <h1>StoryComponent</h1>);
expect(result).toEqual(routes);
});
it('should inject the story in the story route object', () => {
const routes = [
{ path: '/', element: <div /> },
{ path: '/about', useStoryElement: true },
];
const result = injectStory(routes, <h1>StoryComponent</h1>);
expect(result).toEqual([
{ path: '/', element: <div /> },
expect.objectContaining({ path: '/about', useStoryElement: true }),
]);
expect(isValidReactNode(result[1].element)).toBeTruthy();
expect(result[1]).not.toBe(routes[1]);
});
it('should inject the story when the story route is deep', () => {
const routes = [
{
path: '/',
element: <div />,
children: [
{ path: '/child1', element: <div /> },
{ path: '/child2', useStoryElement: true },
],
},
];
const result = injectStory(routes, <h1>StoryComponent</h1>);
expect(result).toEqual([
{
path: '/',
element: <div />,
children: [
{ path: '/child1', element: <div /> },
expect.objectContaining({ path: '/child2', useStoryElement: true }),
],
},
]);
expect(isValidReactNode(result[0].children?.[1].element)).toBeTruthy();
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { RouteDefinition, RouterRoute } from '../types';
import { isValidReactNode } from './isValidReactNode';
export function castRouterRoute(definition: RouteDefinition): RouterRoute {
if (isValidReactNode(definition)) {
return { element: definition };
}
return definition;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { RouteObject } from 'react-router';
import { describe, it } from 'vitest';
import { appendPathSegment, inferLocationPathFromRoutes } from './normalizeHistory';
describe('normalizeHistory', () => {
describe('inferLocationPathFromRoutes', () => {
it('should return "/" if no routes is given', () => {
const result = inferLocationPathFromRoutes();
expect(result).toEqual('/');
});
it('should return the root path if a single route is given', () => {
const routes = [{ path: '/parent/child' }];
const result = inferLocationPathFromRoutes(routes);
expect(result).toEqual('/parent/child');
});
it('should return the root path if no default route is found', () => {
const routes = [{ path: '/parent1' }, { path: '/parent2' }];
const result = inferLocationPathFromRoutes(routes);
expect(result).toEqual('/');
});
it('should return the parent path if there is an index route', () => {
const routes: RouteObject[] = [
{
path: '/parent',
children: [{ index: true }, { path: '/child' }],
},
];
const result = inferLocationPathFromRoutes(routes);
expect(result).toEqual('/parent');
});
it('should return the joined path if each route has a single child', () => {
const routes = [{ path: '/parent', children: [{ path: '/child' }] }];
const result = inferLocationPathFromRoutes(routes);
expect(result).toEqual('/parent/child');
});
});
describe('appendPathSegment', () => {
it('should return "/" if both the basePath and the segmentPath are empty', () => {
expect(appendPathSegment('', '')).toEqual('/');
});
it('should return the basePath if there is no path to append', () => {
expect(appendPathSegment('/', '')).toEqual('/');
expect(appendPathSegment('/test', '')).toEqual('/test');
});
it('should insert a slash before the pathSegment if missing', () => {
expect(appendPathSegment('/test', 'path')).toEqual('/test/path');
expect(appendPathSegment('/test', '/path')).toEqual('/test/path');
});
it('should remove the slash after the basePath if present', () => {
expect(appendPathSegment('/test/', 'path')).toEqual('/test/path');
expect(appendPathSegment('/test/', '/path')).toEqual('/test/path');
});
it('should add a heading slash to the basePath if missing', () => {
expect(appendPathSegment('test', 'path')).toEqual('/test/path');
expect(appendPathSegment('test', '/path')).toEqual('/test/path');
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { isValidReactNode } from './isValidReactNode';
describe('isValidReactNode', () => {
it('should return true when a JSX element is given', () => {
expect(isValidReactNode(<div />)).toBe(true);
});
it('should return true when `null` is given', () => {
expect(isValidReactNode(null)).toBe(true);
});
it('should return true when `undefined` is given', () => {
expect(isValidReactNode(undefined)).toBe(true);
});
it('should return true when a string is given', () => {
expect(isValidReactNode('hello')).toBe(true);
});
it('should return true when a number is given', () => {
expect(isValidReactNode(42)).toBe(true);
});
it('should return true when a React.Fragment is given', () => {
expect(isValidReactNode(<></>)).toBe(true);
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { castArray } from '../../../utils/misc';
import { ReactRouterAddonStoryParameters } from '../components/ReactRouterDecorator';
import { RouterRoute } from '../types';
export function normalizeRouting(routing: ReactRouterAddonStoryParameters['routing']): [RouterRoute, ...RouterRoute[]] {
if (routing === undefined) {
return [{ path: '/' }];
}
if (typeof routing === 'string') {
return [{ path: routing }];
}
routing = castArray(routing);
if (routing.length === 1) {
routing[0].path ??= '/';
}
return routing;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
/* eslint-disable @typescript-eslint/no-explicit-any */
import { hasOwnProperty } from '../../../utils/misc';
import { ReactRouterAddonStoryParameters } from '../components/ReactRouterDecorator';
import { LocationParameters, RouterRoute } from '../types';
import { castRouterRoute } from './castRouterRoute';
export function castParametersV2(parameters: Record<string, unknown> = {}): ReactRouterAddonStoryParameters {
const exclusiveV2properties = ['location', 'navigationHistory', 'routing'];
const isV2 = Object.keys(parameters ?? {}).some((prop) => exclusiveV2properties.includes(prop));
if (isV2) return parameters;
const v2params = {
routing: {} as RouterRoute,
location: {} as LocationParameters,
hydrationData: undefined,
} satisfies ReactRouterAddonStoryParameters;
// <!> The order is important <!>
if (hasOwnProperty(parameters, 'routePath')) {
v2params.location.path = parameters.routePath as any;
v2params.routing.path = parameters.routePath as any;
}
if (hasOwnProperty(parameters, 'routeParams')) v2params.location.pathParams = parameters.routeParams as any;
if (hasOwnProperty(parameters, 'routeState')) v2params.location.state = parameters.routeState as any;
if (hasOwnProperty(parameters, 'routeHandle')) v2params.routing.handle = parameters.routeHandle as any;
if (hasOwnProperty(parameters, 'searchParams')) v2params.location.searchParams = parameters.searchParams as any;
if (hasOwnProperty(parameters, 'browserPath')) v2params.location.path = parameters.browserPath as any;
if (hasOwnProperty(parameters, 'loader')) v2params.routing.loader = parameters.loader as any;
if (hasOwnProperty(parameters, 'action')) v2params.routing.action = parameters.action as any;
if (hasOwnProperty(parameters, 'errorElement')) v2params.routing.errorElement = parameters.errorElement as any;
if (hasOwnProperty(parameters, 'hydrationData')) v2params.hydrationData = parameters.hydrationData as any;
if (hasOwnProperty(parameters, 'shouldRevalidate'))
v2params.routing.shouldRevalidate = parameters.shouldRevalidate as any;
if (hasOwnProperty(parameters, 'routeId')) v2params.routing.id = parameters.routeId as any;
if (hasOwnProperty(parameters, 'outlet')) {
const outlet = castRouterRoute(parameters.outlet as any);
outlet.path ??= '';
v2params.routing.children = [outlet];
}
v2params.routing.useStoryElement = true;
return v2params;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { RouterRoute } from '../types';
export function injectStory(routes: RouterRoute[], StoryComponent: React.ReactElement): RouterRoute[] {
// Single route, no children
if (routes.length === 1 && (routes[0].children === undefined || routes[0].children.length === 0)) {
return [{ ...routes[0], element: StoryComponent }];
}
const storyRouteIndex = routes.findIndex((route) => route.useStoryElement);
if (storyRouteIndex !== -1) {
const localRoutes = Array.from(routes);
localRoutes.splice(storyRouteIndex, 1, {
...routes[storyRouteIndex],
element: StoryComponent,
});
return localRoutes;
}
return routes.map((route) => {
if (!route.children) return route;
return {
...route,
children: injectStory(route.children, StoryComponent),
};
});
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { FormData } from '@remix-run/web-fetch';
import { describe, expect, it } from 'vitest';
import { getFormDataSummary } from './getFormDataSummary';
describe('getFormDataSummary', () => {
it('should return a record with an entry for each form data string value', () => {
const formData = new FormData();
formData.append('foo', 'bar');
formData.append('fuu', 'baz');
const summary = getFormDataSummary(formData);
expect(summary).toEqual({
foo: 'bar',
fuu: 'baz',
});
});
it('should return an object describing the file', () => {
const formData = new FormData();
formData.append('myFile', new File(['somecontent'], 'myFile.txt', { type: 'text/plain' }));
const summary = getFormDataSummary(formData);
expect(summary).toEqual({
myFile: {
filename: 'myFile.txt',
filetype: 'text/plain',
filesize: 11,
},
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { describe, expect, test } from 'vitest';
import { reactRouterOutlet } from './reactRouterOutlet';
import { reactRouterParameters } from './reactRouterParameters';
describe('reactRouterParameters', () => {
function MyComponent() {
return null;
}
test.skip('should look nice', () => {
reactRouterParameters({
routing: reactRouterOutlet(<MyComponent />),
location: { hash: 'title1' },
});
});
test('it should return the given parameter', () => {
const parameters = { routing: { path: '/users' } };
expect(reactRouterParameters(parameters)).toBe(parameters);
});
test.skip('a typescript error should show up if the api v1 is used', () => {
reactRouterParameters({
// @ts-expect-error test
routePath: 'apiV1',
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { castArray, hasOwnProperty, invariant } from '../../../../utils/misc';
import {
NonIndexRouteDefinition,
NonIndexRouteDefinitionObject,
RouteDefinitionObject,
RouterRoute,
} from '../../types';
import { castRouterRoute } from '../castRouterRoute';
/**
* Render the story as the outlet of an ancestor.
* You can specify multiple ancestors to create a deep nesting.
* Outlets are nested in a visual/JSX order : the first element of the array will be the root, the last will be
* the direct parent of the story
*/
export function reactRouterNestedAncestors(
ancestors: NonIndexRouteDefinition | NonIndexRouteDefinition[]
): [RouterRoute];
export function reactRouterNestedAncestors(
story: Omit<RouteDefinitionObject, 'element'>,
ancestors: NonIndexRouteDefinition | NonIndexRouteDefinition[]
): [RouterRoute];
export function reactRouterNestedAncestors(
...args:
| [NonIndexRouteDefinition | NonIndexRouteDefinition[]]
| [Omit<RouteDefinitionObject, 'element'>, NonIndexRouteDefinition | NonIndexRouteDefinition[]]
): [RouterRoute] {
const story = (args.length === 1 ? {} : args[0]) as RouteDefinitionObject;
const ancestors = castArray(args.length === 1 ? args[0] : args[1]);
invariant(
!hasOwnProperty(story, 'element'),
'The story definition cannot contain the `element` property because the story element will be used'
);
const ancestorsRoot: RouterRoute = { path: '/' };
let lastAncestor = ancestorsRoot;
console.log('ancestorsRoot', ancestorsRoot);
for (let i = 0; i < ancestors.length; i++) {
const ancestor = ancestors[i];
const ancestorDefinitionObjet = castRouterRoute(ancestor) as NonIndexRouteDefinitionObject;
ancestorDefinitionObjet.path ??= '';
lastAncestor.children = [ancestorDefinitionObjet];
lastAncestor = ancestorDefinitionObjet;
}
lastAncestor.children = [
{
...story,
index: true,
useStoryElement: true,
},
];
return [ancestorsRoot];
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { RouteObject } from 'react-router';
import { hasOwnProperty, invariant } from '../../../../utils/misc';
import { NonIndexRouteDefinition, NonIndexRouteDefinitionObject, RouteDefinition, RouterRoute } from '../../types';
import { castRouterRoute } from '../castRouterRoute';
/**
* Render the story with multiple outlets nested one into the previous.
* Use this function when your story component renders an outlet that itself can have outlet and so forth.
* Outlets are nested in a visual/JSX order : the first element of the array will be the root, the last will be
* the direct parent of the story
* @see withOutlet
* @see withOutlets
*/
export function reactRouterNestedOutlets(outlets: [...RouteDefinition[], NonIndexRouteDefinition]): [RouterRoute];
export function reactRouterNestedOutlets(
story: Omit<NonIndexRouteDefinitionObject, 'element'>,
outlets: [...RouteDefinition[], NonIndexRouteDefinition]
): [RouterRoute];
export function reactRouterNestedOutlets(
...args: [RouteDefinition[]] | [Omit<NonIndexRouteDefinitionObject, 'element'>, RouteDefinition[]]
): [RouterRoute] {
const story = (args.length === 1 ? {} : args[0]) as NonIndexRouteDefinitionObject;
const outlets = args.length === 1 ? args[0] : args[1];
invariant(
!hasOwnProperty(story, 'element'),
'The story definition cannot contain the `element` property because the story element will be used'
);
const outletsRoot: RouteObject = {};
let lastOutlet = outletsRoot;
outlets.forEach((outlet) => {
const outletDefinitionObjet = castRouterRoute(outlet) as NonIndexRouteDefinitionObject;
outletDefinitionObjet.path ??= '';
lastOutlet.children = [outletDefinitionObjet];
lastOutlet = outletDefinitionObjet;
}, outletsRoot);
return [
{
...story,
useStoryElement: true,
children: [outletsRoot],
},
];
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { hasOwnProperty, invariant } from '../../../../utils/misc';
import { NonIndexRouteDefinitionObject, RouteDefinition, RouterRoute } from '../../types';
import { castRouterRoute } from '../castRouterRoute';
/**
* Render the story with a single outlet
* @see withOutlets
* @see withNestedOutlets
*/
export function reactRouterOutlet(outlet: RouteDefinition): [RouterRoute];
export function reactRouterOutlet(
story: Omit<NonIndexRouteDefinitionObject, 'element'>,
outlet: RouteDefinition
): [RouterRoute];
export function reactRouterOutlet(...args: RouteDefinition[]): [RouterRoute] {
const story = (args.length === 1 ? {} : args[0]) as NonIndexRouteDefinitionObject;
const outlet = args.length === 1 ? args[0] : args[1];
invariant(
!hasOwnProperty(story, 'element'),
'The story definition cannot contain the `element` property because the story element will be used'
);
const outletDefinitionObject = castRouterRoute(outlet);
outletDefinitionObject.index = true;
return [
{
...story,
useStoryElement: true,
children: [outletDefinitionObject],
},
];
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { RouteObject } from 'react-router';
import { hasOwnProperty, invariant } from '../../../../utils/misc';
import {
NonIndexRouteDefinition,
NonIndexRouteDefinitionObject,
RouteDefinitionObject,
RouterRoute,
} from '../../types';
/**
* Render the story with multiple possible outlets.
* Use this function when your story component can navigate and you want a different outlet depending on the path.
* @see withOutlet
* @see withNestedOutlets
*/
export function reactRouterOutlets(outlets: RouteDefinitionObject[]): [RouterRoute];
export function reactRouterOutlets(
story: Omit<NonIndexRouteDefinitionObject, 'element'>,
outlets: RouteDefinitionObject[]
): [RouterRoute];
export function reactRouterOutlets(
...args: [RouteDefinitionObject[]] | [NonIndexRouteDefinition, RouteDefinitionObject[]]
): [RouterRoute] {
const story = (args.length === 1 ? {} : args[0]) as NonIndexRouteDefinitionObject;
const outlets = args.length === 1 ? args[0] : args[1];
invariant(
!hasOwnProperty(story, 'element'),
'The story definition cannot contain the `element` property because the story element will be used'
);
return [
{
...story,
useStoryElement: true,
children: outlets,
},
];
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { ReactRouterAddonStoryParameters } from '../../components/ReactRouterDecorator';
export function reactRouterParameters(params: ReactRouterAddonStoryParameters) {
return params;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { ActionFunctionArgs, LoaderFunctionArgs, NavigationType, RouteMatch, useParams } from 'react-router-dom';
import { PromiseType } from 'utility-types';
import { EVENTS } from '../../constants';
import { getHumanReadableBody } from '../decorator/utils/getHumanReadableBody';
export type AddonEvents = typeof EVENTS;
///////////////////
// Router Events //
///////////////////
export type RouterEvents = Omit<AddonEvents, 'CLEAR' | 'NEW_VERSION'>;
export type RouterNavigationEventKey = 'NAVIGATION' | 'STORY_LOADED' | 'ROUTE_MATCHES';
export type RouterDataEventKey = 'ACTION_INVOKED' | 'ACTION_SETTLED' | 'LOADER_INVOKED' | 'LOADER_SETTLED';
export type RouterNavigationEventName = RouterEvents[RouterNavigationEventKey];
export type RouterDataEventName = RouterEvents[RouterDataEventKey];
export type RouterNavigationEvents = Pick<RouterEvents, RouterNavigationEventKey>;
export type RouterDataEvents = Pick<RouterEvents, RouterDataEventKey>;
export type RouterEventData = RouterLocationEventData & RouterDataEventData;
export type RouterEvent = {
[Key in keyof RouterEvents]: {
key: string;
type: RouterEvents[Key];
data: RouterEventData[RouterEvents[Key]];
};
}[keyof RouterEvents];
export type RouterNavigationEvent = Extract<RouterEvent, { type: RouterNavigationEventName }>;
export type RouterDataEvent = Extract<RouterEvent, { type: RouterDataEventName }>;
export type RouteMatchesData = Array<{ path: RouteMatch['route']['path']; params?: RouteMatch['params'] }>;
export type RouterStoryLoadedEventData = {
url: string;
path: string;
hash: string;
routeParams: ReturnType<typeof useParams>;
routeState: unknown;
searchParams: Record<string, string | string[]>;
routeMatches: RouteMatchesData;
};
export type RouterNavigationEventData = {
url: string;
navigationType: NavigationType;
path: string;
hash: string;
routeParams: ReturnType<typeof useParams>;
searchParams: Record<string, string | string[]>;
routeState: unknown;
routeMatches: RouteMatchesData;
};
export type RouterRouteMatchesEventData = {
matches: RouteMatchesData;
};
export type DataEventArgs = {
[EVENTS.ACTION_INVOKED]: ActionFunctionArgs;
[EVENTS.ACTION_SETTLED]: unknown;
[EVENTS.LOADER_INVOKED]: LoaderFunctionArgs;
[EVENTS.LOADER_SETTLED]: unknown;
};
export type RequestSummary = {
url: ActionFunctionArgs['request']['url'];
method: ActionFunctionArgs['request']['method'];
body: PromiseType<ReturnType<typeof getHumanReadableBody>>;
};
export type RouterDataEventData = {
[EVENTS.ACTION_INVOKED]: Pick<ActionFunctionArgs, 'params' | 'context'> & {
request: RequestSummary;
};
[EVENTS.ACTION_SETTLED]: DataEventArgs[RouterDataEvents['ACTION_SETTLED']];
[EVENTS.LOADER_INVOKED]: Pick<LoaderFunctionArgs, 'params' | 'context'> & {
request: RequestSummary;
};
[EVENTS.LOADER_SETTLED]: DataEventArgs[RouterDataEvents['LOADER_SETTLED']];
};
export type RouterLocationEventData = {
[EVENTS.NAVIGATION]: RouterNavigationEventData;
[EVENTS.STORY_LOADED]: RouterStoryLoadedEventData;
[EVENTS.ROUTE_MATCHES]: RouterRouteMatchesEventData;
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { compareVersions } from 'compare-versions';
import { useEffect, useState } from 'react';
import { ADDON_VERSION } from '../../../constants';
export function useAddonVersions() {
const [version, setVersion] = useState<string>();
useEffect(() => {
if (version !== undefined) return;
const abortController = new AbortController();
fetch(`https://registry.npmjs.org/storybook-addon-react-router-v6/latest`, { signal: abortController.signal })
.then((b) => b.json())
.then((json) => setVersion(json.version))
// eslint-disable-next-line @typescript-eslint/no-empty-function
.catch(() => {});
return () => abortController.abort();
}, [version]);
const newVersionAvailable = version === undefined ? undefined : compareVersions(version, ADDON_VERSION) === 1;
return {
currentAddonVersion: ADDON_VERSION,
latestAddonVersion: version,
addonUpdateAvailable: newVersionAvailable,
};
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { ActionBar, ScrollArea } from '@storybook/components';
import { styled } from '@storybook/theming';
import React, { Fragment, PropsWithChildren } from 'react';
import { EVENTS } from '../../../constants';
import { FCC } from '../../../fixes';
import { RouterEvent, RouterEvents } from '../types';
import { InspectorContainer } from './InspectorContainer';
import { RouterEventDisplayWrapper } from './RouterEventDisplayWrapper';
import { ThemedInspector } from './ThemedInspector';
export type PanelContentProps = {
routerEvents: Array<RouterEvent>;
onClear: () => void;
};
export type ScrollAreaProps = PropsWithChildren<{
horizontal?: boolean;
vertical?: boolean;
className?: string;
title: string;
}>;
const PatchedScrollArea = ScrollArea as FCC<ScrollAreaProps>;
export const PanelContent: FCC<PanelContentProps> = ({ routerEvents, onClear }) => {
return (
<Fragment>
<Wrapper title="reactRouterLogger">
{routerEvents.map((event, i) => {
return (
<RouterEventDisplayWrapper key={i}>
<InspectorContainer>
<ThemedInspector
name={humanReadableEventNames[event.type]}
data={event.data}
showNonenumerable={false}
sortObjectKeys={false}
expandPaths={[
'$.routeParams',
'$.searchParams',
'$.routeMatches.*',
'$.routeMatches.*.*',
'$.matches',
'$.matches.*',
'$.matches.*.*',
]}
/>
</InspectorContainer>
</RouterEventDisplayWrapper>
);
})}
</Wrapper>
<ActionBar actionItems={[{ title: 'Clear', onClick: onClear }]} />
</Fragment>
);
};
export const humanReadableEventNames: Record<RouterEvents[keyof RouterEvents], string> = {
[EVENTS.NAVIGATION]: 'Navigate',
[EVENTS.STORY_LOADED]: 'Story rendered',
[EVENTS.ROUTE_MATCHES]: 'New route matches',
[EVENTS.ACTION_INVOKED]: 'Action invoked',
[EVENTS.ACTION_SETTLED]: 'Action settled',
[EVENTS.LOADER_INVOKED]: 'Loader invoked',
[EVENTS.LOADER_SETTLED]: 'Loader settled',
};
export const Wrapper = styled(({ children, title }: ScrollAreaProps) => (
<PatchedScrollArea horizontal vertical title={title}>
{children}
</PatchedScrollArea>
))({
margin: 0,
padding: '10px 5px 20px',
});
Wrapper.displayName = 'Wrapper';
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { styled } from '@storybook/theming';
export const RouterEventDisplayWrapper = styled.div({
display: 'flex',
padding: 0,
borderLeft: '5px solid transparent',
borderBottom: '1px solid transparent',
transition: 'all 0.1s',
alignItems: 'flex-start',
whiteSpace: 'pre',
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { AddonPanel } from '@storybook/components';
import { STORY_CHANGED } from '@storybook/core-events';
import { API, useChannel } from '@storybook/manager-api';
import React, { useState } from 'react';
import { EVENTS } from '../../../constants';
import { useAddonVersions } from '../hooks/useAddonVersions';
import { RouterEvent } from '../types';
import { InformationBanner } from './InformationBanner';
import { PanelContent } from './PanelContent';
interface PanelProps {
active: boolean;
api: API;
}
export const Panel: React.FC<PanelProps> = (props) => {
const [navigationEvents, setNavigationEvents] = useState<RouterEvent[]>([]);
const { latestAddonVersion, addonUpdateAvailable } = useAddonVersions();
const pushEvent = (event: RouterEvent) => {
setNavigationEvents((prev) => [...prev, event]);
};
useChannel({
[EVENTS.ROUTE_MATCHES]: pushEvent,
[EVENTS.NAVIGATION]: pushEvent,
[EVENTS.STORY_LOADED]: pushEvent,
[EVENTS.ACTION_INVOKED]: pushEvent,
[EVENTS.ACTION_SETTLED]: pushEvent,
[EVENTS.LOADER_INVOKED]: pushEvent,
[EVENTS.LOADER_SETTLED]: pushEvent,
[STORY_CHANGED]: () => setNavigationEvents([]),
});
const clear = () => {
props.api.emit(EVENTS.CLEAR);
setNavigationEvents([]);
};
return (
<AddonPanel {...props}>
{addonUpdateAvailable && (
<InformationBanner>
Version {latestAddonVersion} is now available !{' '}
<a
href={`https://github.com/JesusTheHun/storybook-addon-react-router-v6/releases/tag/v${latestAddonVersion}`}
>
Changelog
</a>
.
</InformationBanner>
)}
<PanelContent routerEvents={navigationEvents} onClear={clear} />
</AddonPanel>
);
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { styled } from '@storybook/theming';
export const InformationBanner = styled.p`
background: #ffebba;
padding: 5px;
margin-top: 0;
`;
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { styled } from '@storybook/theming';
export const InspectorContainer = styled.div({
flex: 1,
padding: '0 0 0 5px',
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import type { Theme } from '@storybook/theming';
import { withTheme } from '@storybook/theming';
import { ObjectInspector } from 'react-inspector';
interface InspectorProps {
theme: Theme;
sortObjectKeys?: boolean;
showNonenumerable?: boolean;
name: any;
data: any;
depth?: number;
expandPaths?: string | string[];
}
export const ThemedInspector = withTheme(({ theme, ...props }: InspectorProps) => (
<ObjectInspector theme={theme.addonActionsTheme || 'chromeLight'} {...props} />
));
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { STORY_CHANGED } from '@storybook/core-events';
import { ManagerContext } from '@storybook/manager-api';
import React, { useContext, useEffect, useState } from 'react';
import { EVENTS } from '../../../constants';
import { useAddonVersions } from '../hooks/useAddonVersions';
export function PanelTitle() {
const { api } = useContext(ManagerContext);
const { addonUpdateAvailable } = useAddonVersions();
const [badgeCount, setBadgeCount] = useState(0);
const incrementBadgeCount = () => setBadgeCount((previous) => previous + 1);
const clearBadgeCount = () => setBadgeCount(0);
useEffect(() => {
api.on(STORY_CHANGED, clearBadgeCount);
api.on(EVENTS.ROUTE_MATCHES, incrementBadgeCount);
api.on(EVENTS.NAVIGATION, incrementBadgeCount);
api.on(EVENTS.ACTION_INVOKED, incrementBadgeCount);
api.on(EVENTS.ACTION_SETTLED, incrementBadgeCount);
api.on(EVENTS.LOADER_INVOKED, incrementBadgeCount);
api.on(EVENTS.LOADER_SETTLED, incrementBadgeCount);
api.on(EVENTS.CLEAR, clearBadgeCount);
return () => {
api.off(STORY_CHANGED, clearBadgeCount);
api.off(EVENTS.ROUTE_MATCHES, incrementBadgeCount);
api.off(EVENTS.NAVIGATION, incrementBadgeCount);
api.off(EVENTS.ACTION_INVOKED, incrementBadgeCount);
api.off(EVENTS.ACTION_SETTLED, incrementBadgeCount);
api.off(EVENTS.LOADER_INVOKED, incrementBadgeCount);
api.off(EVENTS.LOADER_SETTLED, incrementBadgeCount);
api.off(EVENTS.CLEAR, clearBadgeCount);
};
}, [api]);
const suffixes: string[] = [];
if (addonUpdateAvailable) suffixes.push('⚡️');
if (badgeCount) suffixes.push(`(${badgeCount})`);
return <>React Router {suffixes.join(' ')}</>;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { describe, test } from 'vitest';
import { expectTypeOf } from 'expect-type';
import { RouteParamsFromPath } from '../features/decorator/types';
describe('Types - Utils', () => {
describe('RouteParamsFromPath', () => {
test('returns an empty object when no param is expected', () => {
expectTypeOf<RouteParamsFromPath<'/users'>>().toEqualTypeOf<unknown>();
expectTypeOf<RouteParamsFromPath<'users'>>().toEqualTypeOf<unknown>();
});
test('returns an object with the expected route params', () => {
expectTypeOf<RouteParamsFromPath<'/users/:userId'>>().toEqualTypeOf<{ userId: string }>();
expectTypeOf<RouteParamsFromPath<'/:dashboard'>>().toEqualTypeOf<{ dashboard: string }>();
expectTypeOf<RouteParamsFromPath<'/users/:userId/:tabId'>>().toEqualTypeOf<{
userId: string;
tabId: string;
}>();
expectTypeOf<RouteParamsFromPath<'/users/:userId/tabs'>>().toEqualTypeOf<{ userId: string }>();
expectTypeOf<RouteParamsFromPath<'/users/:userId/tabs/:tabId'>>().toEqualTypeOf<{
userId: string;
tabId: string;
}>();
expectTypeOf<RouteParamsFromPath<'users/:userId'>>().toEqualTypeOf<{ userId: string }>();
expectTypeOf<RouteParamsFromPath<':userId'>>().toEqualTypeOf<{ userId: string }>();
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { expectTypeOf } from 'expect-type';
import { describe, expect, it } from 'vitest';
import { castArray } from './misc';
describe('Utils - Misc', () => {
describe('castArray', () => {
it('should cast a non-array `undefined` to an array containing a single value, `undefined`', () => {
expect(castArray(undefined)).toEqual([undefined]);
});
it('should return an empty array if called with no argument', () => {
expect(castArray()).toEqual([]);
});
it('should cast a non-array value to an array containing only the value', () => {
expect(castArray('a')).toEqual(['a']);
});
it('should return the same object ref is the value is already an array', () => {
const arr = ['a', 'b'];
expect(castArray(arr)).toBe(arr);
});
it('should preserve the type of a non-array value', () => {
expectTypeOf(castArray('a')).toEqualTypeOf<[string]>();
expectTypeOf(castArray('a' as const)).toEqualTypeOf<['a']>();
});
it('should preserve the type of the element of an array value', () => {
expectTypeOf(castArray(['a', 'b'])).toEqualTypeOf<string[]>();
expectTypeOf(castArray([777, 'a', 'b'])).toEqualTypeOf<Array<number | string>>();
expectTypeOf(castArray(['a', 'b'] as const)).toEqualTypeOf<readonly ['a', 'b']>();
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { vi } from 'vitest';
type Vi = typeof vi;
export class LocalStorage {
store!: Record<string, string>;
constructor(vi: Vi) {
Object.defineProperty(this, 'store', {
enumerable: false,
writable: true,
value: {},
});
Object.defineProperty(this, 'getItem', {
enumerable: false,
value: vi.fn((key: string) => (this.store[key] !== undefined ? this.store[key] : null)),
});
Object.defineProperty(this, 'setItem', {
enumerable: false,
// not mentioned in the spec, but we must always coerce to a string
value: vi.fn((key: string, val = '') => {
this.store[key] = val + '';
}),
});
Object.defineProperty(this, 'removeItem', {
enumerable: false,
value: vi.fn((key: string) => {
delete this.store[key];
}),
});
Object.defineProperty(this, 'clear', {
enumerable: false,
value: vi.fn(() => {
Object.keys(this.store).map((key: string) => delete this.store[key]);
}),
});
Object.defineProperty(this, 'toString', {
enumerable: false,
value: vi.fn(() => {
return '[object Storage]';
}),
});
Object.defineProperty(this, 'key', {
enumerable: false,
value: vi.fn((idx) => Object.keys(this.store)[idx] || null),
});
} // end constructor
get length() {
return Object.keys(this.store).length;
}
// for backwards compatibility
get __STORE__() {
return this.store;
}
}
export function mockLocalStorage(): void {
if (!(window.localStorage instanceof LocalStorage)) {
vi.stubGlobal('localStorage', new LocalStorage(vi));
vi.stubGlobal('sessionStorage', new LocalStorage(vi));
}
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
export type RequireOne<T, Key = keyof T> = Exclude<
{
[K in keyof T]: K extends Key ? Omit<T, K> & Required<Pick<T, K>> : never;
}[keyof T],
undefined
>;
export type If<T, Then, Else> = T extends true ? Then : Else;
export type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void
? I
: never;
export type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
export type Merge<T, Deep = false> = {
[K in keyof T]: Deep extends true ? (T extends object ? Merge<T[K], true> : T[K]) : T[K];
// eslint-disable-next-line @typescript-eslint/ban-types
} & {};
export type ToArray<T> = T extends ReadonlyArray<unknown> ? T : [T];
export type AssertKey<T, K extends PropertyKey> = IsUnion<T> extends true
? Extract<T, { [key in K]: unknown }> extends Extract<T, { [key in K]: infer Value }>
? T & Record<K, Value>
: T
: T & Record<K, unknown>;
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { AssertKey, ToArray } from './type-utils';
export type Deferred<T> = {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: unknown) => void;
};
export function defer<T = void>(): Deferred<T> {
const deferred: Partial<Deferred<T>> = {};
deferred.promise = new Promise<T>((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred as Deferred<T>;
}
export function hasOwnProperty<T extends object, K extends PropertyKey>(obj: T, prop: K): obj is AssertKey<T, K> {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
export function invariant(value: boolean, message?: string): asserts value;
export function invariant<T>(value: T | null | undefined, message?: string): asserts value is T;
export function invariant(value: any, message?: string) {
if (value === false || value === null || typeof value === 'undefined') {
console.warn('Test invariant failed:', message);
throw new Error(message);
}
}
export function castArray(): [];
export function castArray<T>(value: T): ToArray<T>;
export function castArray<T>(value?: T) {
if (arguments.length === 0) {
return [];
}
return (Array.isArray(value) ? value : [value]) as ToArray<T>;
}
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { Outlet, useLocation, useMatches, useParams, useSearchParams } from 'react-router-dom';
import { withRouter } from '../../features/decorator/withRouter';
export default {
title: 'v1/Basics',
decorators: [withRouter],
};
export const RenderChildren = {
render: () => <h1>Hi</h1>,
};
export const RenderChildrenWithStoryArgs = {
render: ({ id }: { id: string }) => <h1>{id}</h1>,
args: {
id: '42',
},
};
function ShowPath() {
const location = useLocation();
return <p>{location.pathname}</p>;
}
export const SpecificPath = {
render: () => <ShowPath />,
parameters: {
reactRouter: {
routePath: '/foo',
},
},
};
function ShowRouteParams() {
const routeParams = useParams();
return <p>{JSON.stringify(routeParams)}</p>;
}
export const RouteParams = {
render: () => <ShowRouteParams />,
parameters: {
reactRouter: {
routePath: '/book/:id', // TODO edit appendPathSegment to handle this case ; the slash in the middle is wrongfully removed
routeParams: { id: '42' },
},
},
};
function ShowSearchParams() {
const [searchParams] = useSearchParams();
return <p>{JSON.stringify(Object.fromEntries(searchParams.entries()))}</p>;
}
export const SearchParams = {
render: () => <ShowSearchParams />,
parameters: {
reactRouter: {
searchParams: { page: '42' },
},
},
};
function ShowHandles() {
const matches = useMatches();
return <p>{JSON.stringify(matches.map((m) => m.handle))}</p>;
}
export const MatchesHandles = {
render: () => <ShowHandles />,
parameters: {
reactRouter: {
routeHandle: 'Hi',
},
},
};
export const MatchesHandlesInsideOutlet = {
render: () => <ShowHandles />,
parameters: {
reactRouter: {
routeHandle: 'Hi',
outlet: {
handle: 'Yall',
element: <ShowHandles />,
},
},
},
};
export const OutletJSX = {
render: () => <Outlet />,
parameters: {
reactRouter: {
outlet: <h1>I'm an outlet</h1>,
},
},
};
export const OutletConfigObject = {
render: () => <Outlet />,
parameters: {
reactRouter: {
outlet: {
element: <h1>I'm an outlet defined with a config object</h1>,
},
},
},
};
function ShowRouteId() {
const matches = useMatches();
return <p>{JSON.stringify(matches.map((m) => m.id))}</p>;
}
export const RouteId = {
render: () => <ShowRouteId />,
parameters: {
reactRouter: {
routeId: 'SomeRouteId',
},
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { composeStories } from '@storybook/react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { invariant } from '../../utils/misc';
import * as BasicStories from './Basics.stories';
import * as ActionStories from './DataRouter/Action.stories';
import * as ComplexStories from './DataRouter/Complex.stories';
import * as LoaderStories from './DataRouter/Loader.stories';
import * as NestingStories from './Nesting.stories';
describe('StoryRouteTree', () => {
describe('Basics', () => {
const {
RenderChildren,
RenderChildrenWithStoryArgs,
OutletJSX,
OutletConfigObject,
SpecificPath,
RouteParams,
MatchesHandles,
MatchesHandlesInsideOutlet,
SearchParams,
RouteId,
} = composeStories(BasicStories);
it('should render child component', () => {
render(<RenderChildren />);
expect(screen.getByRole('heading', { name: 'Hi' })).toBeInTheDocument();
});
it('should render child component with story args', () => {
render(<RenderChildrenWithStoryArgs />);
expect(screen.getByRole('heading', { name: '42' })).toBeInTheDocument();
});
it('should render component at the specified path', async () => {
render(<SpecificPath />);
expect(screen.getByText('/foo')).toBeInTheDocument();
});
it('should render component with the specified route params', async () => {
render(<RouteParams />);
expect(screen.getByText('{"id":"42"}')).toBeInTheDocument();
});
it('should render component with the specified search params', async () => {
render(<SearchParams />);
expect(screen.getByText('{"page":"42"}')).toBeInTheDocument();
});
it('should render component with the specified route handle', async () => {
render(<MatchesHandles />);
expect(screen.getByText('["Hi"]')).toBeInTheDocument();
});
it('should render component and its outlet with the specified route handles', async () => {
render(<MatchesHandlesInsideOutlet />);
expect(screen.getByText('["Hi","Yall"]')).toBeInTheDocument();
});
it('should render outlet component', () => {
render(<OutletJSX />);
expect(screen.getByRole('heading', { name: "I'm an outlet" })).toBeInTheDocument();
});
it('should render outlet component defined with config object', () => {
render(<OutletConfigObject />);
expect(screen.getByRole('heading', { name: "I'm an outlet defined with a config object" })).toBeInTheDocument();
});
it('should render route with the assigned id', () => {
render(<RouteId />);
expect(screen.getByText('["SomeRouteId"]')).toBeInTheDocument();
});
});
describe('Nesting', () => {
const { IndexAtRoot, MatchingRoute, MatchingNestedRoute } = composeStories(NestingStories);
it('should render the index route when on root path', async () => {
render(<IndexAtRoot />);
expect(screen.queryByRole('link', { name: 'Navigate to listing' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Navigate to details' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Listing id: 13', level: 1 })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Details id: 37', level: 2 })).not.toBeInTheDocument();
});
it('should navigate appropriately when clicking a link', async () => {
render(<IndexAtRoot />);
expect(screen.queryByRole('link', { name: 'Navigate to listing' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Navigate to details' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Listing id: 13', level: 1 })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Details id: 37', level: 2 })).not.toBeInTheDocument();
const user = userEvent.setup();
await user.click(screen.getByRole('link', { name: 'Navigate to listing' }));
expect(screen.queryByRole('link', { name: 'Navigate to listing' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Navigate to details' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Listing id: 13', level: 1 })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Details id: 37', level: 2 })).not.toBeInTheDocument();
});
it('should render the matching route with bound params when on sub-path', () => {
render(<MatchingRoute />);
expect(screen.queryByRole('link', { name: 'Navigate to listing' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Navigate to details' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Listing id: 13', level: 1 })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Details id: 37', level: 2 })).not.toBeInTheDocument();
});
it('should render the matching route with bound params when on sub-sub-path', () => {
render(<MatchingNestedRoute />);
expect(screen.queryByRole('link', { name: 'Navigate to listing' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Navigate to details' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Listing id: 13', level: 1 })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Details id: 37', level: 2 })).toBeInTheDocument();
});
});
describe('Loader', () => {
const { RouteLoader, RouteAndOutletLoader, ErrorBoundary } = composeStories(LoaderStories);
it('should render component with route loader', async () => {
render(<RouteLoader />);
await waitFor(() => expect(screen.getByRole('heading', { name: 'Data loaded' })).toBeInTheDocument(), {
timeout: 1000,
});
});
it('should render component with route loader and outlet loader', async () => {
render(<RouteAndOutletLoader />);
await waitFor(() => expect(screen.getByRole('heading', { level: 1, name: 'Data loaded' })).toBeInTheDocument(), {
timeout: 1000,
});
await waitFor(
() => expect(screen.getByRole('heading', { level: 2, name: 'Outlet data loaded' })).toBeInTheDocument(),
{ timeout: 1000 }
);
});
it('should render the error boundary if the route loader fails', async () => {
render(<ErrorBoundary />);
await waitFor(() =>
expect(screen.queryByRole('heading', { name: 'Fancy error component : Meh.', level: 1 })).toBeInTheDocument()
);
});
it('should not revalidate the route data', async () => {
const { RouteShouldNotRevalidate } = composeStories(LoaderStories);
invariant(RouteShouldNotRevalidate.parameters);
const loader = vi.fn(() => 'Yo');
RouteShouldNotRevalidate.parameters.reactRouter.loader = loader;
render(<RouteShouldNotRevalidate />);
await waitFor(() => expect(loader).toHaveBeenCalledOnce());
const user = userEvent.setup();
await user.click(screen.getByRole('link'));
screen.getByText('?foo=bar');
expect(loader).toHaveBeenCalledOnce();
});
});
describe('Action', () => {
const { TextFormData, FileFormData } = composeStories(ActionStories);
it('should handle route action with text form', async () => {
const action = vi.fn();
invariant(TextFormData.parameters);
TextFormData.parameters.reactRouter.action = action;
render(<TextFormData />);
const user = userEvent.setup();
await user.click(screen.getByRole('button'));
expect(action).toHaveBeenCalledOnce();
expect(action.mock.lastCall?.[0].request).toBeInstanceOf(Request);
const formData = await (action.mock.lastCall?.[0].request as Request).formData();
const pojoFormData = Object.fromEntries(formData.entries());
expect(pojoFormData).toEqual({ foo: 'bar' });
});
it('should handle route action with file form', async () => {
const action = vi.fn();
invariant(FileFormData.parameters);
FileFormData.parameters.reactRouter.action = action;
const file = new File(['hello'], 'hello.txt', { type: 'plain/text' });
render(<FileFormData />);
const input = screen.getByLabelText(/file/i) as HTMLInputElement;
const user = userEvent.setup();
await user.upload(input, file);
await user.click(screen.getByRole('button'));
expect(input.files).toHaveLength(1);
expect(input.files?.item(0)).toStrictEqual(file);
expect(action).toHaveBeenCalledOnce();
expect(action.mock.lastCall?.[0].request).toBeInstanceOf(Request);
const request = action.mock.lastCall?.[0].request as Request;
const formData = await request.formData();
const pojoFormData = Object.fromEntries(formData.entries());
expect(pojoFormData).toHaveProperty('myFile');
});
});
describe('Complex', () => {
const { TodoListScenario } = composeStories(ComplexStories);
it('should render route with actions properly', async () => {
render(<TodoListScenario />);
await waitFor(() => expect(screen.queryByRole('heading', { level: 1, name: 'Todos' })).toBeInTheDocument(), {
timeout: 1000,
});
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { Link, Route, Routes, useParams } from 'react-router-dom';
import { withRouter } from '../../features/decorator/withRouter';
export default {
title: 'v1/Nesting',
decorators: [withRouter],
};
function NestedRoutes() {
return (
<Routes>
<Route index element={<Link to="13">Navigate to listing</Link>} />
<Route path=":id/*" element={<Listing />} />
</Routes>
);
}
function Listing() {
const params = useParams();
return (
<div>
<h1>Listing id: {params.id}</h1>
<Routes>
<Route index element={<Link to="FixedId">Navigate to details</Link>} />
<Route path=":subId" element={<SubListingDetailPage />} />
</Routes>
</div>
);
}
function SubListingDetailPage() {
const params = useParams();
return <h2>Details id: {params.subId}</h2>;
}
export const IndexAtRoot = {
render: () => <NestedRoutes />,
parameters: {
reactRouter: {
routePath: '/listing/*',
browserPath: '/listing',
},
},
};
function NestedRoutesWithProp({ foo = 1 }: { foo?: number }) {
return (
<Routes>
<Route
index
element={
<div>
<h1>Story arg : {foo}</h1>
<Link to={`${foo}`}>Navigate to listing</Link>
</div>
}
/>
<Route
path=":id/*"
element={
<div>
<h2>Story arg : {foo}</h2>
<Listing />
</div>
}
/>
</Routes>
);
}
export const IndexAtRootWithStoryArgs = {
render: ({ foo }: { foo: number }) => <NestedRoutesWithProp foo={foo} />,
parameters: {
reactRouter: {
routePath: '/listing/*',
browserPath: '/listing',
},
},
args: {
foo: 42,
},
};
export const MatchingRoute = {
render: () => <NestedRoutes />,
parameters: {
reactRouter: {
routePath: '/listing/*',
browserPath: '/listing/13',
},
},
};
export const MatchingNestedRoute = {
render: () => <NestedRoutes />,
parameters: {
reactRouter: {
routePath: '/listing/*',
browserPath: '/listing/13/37',
},
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
/**
* Credits : https://github.com/remix-run/react-router
* reactrouter.com
*/
import React from 'react';
import {
ActionFunctionArgs,
Form,
Link,
LoaderFunctionArgs,
Outlet,
useFetcher,
useLoaderData,
useNavigation,
useParams,
} from 'react-router-dom';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v1/Complex',
decorators: [withRouter],
};
function sleep(n = 500) {
return new Promise((r) => setTimeout(r, n));
}
interface Todos {
[key: string]: string;
}
const TODOS_KEY = 'todos';
const uuid = () => Math.random().toString(36).substr(2, 9);
function saveTodos(todos: Todos): void {
return localStorage.setItem(TODOS_KEY, JSON.stringify(todos));
}
function initializeTodos(): Todos {
const todos: Todos = new Array(3)
.fill(null)
.reduce((acc, _, index) => Object.assign(acc, { [uuid()]: `Seeded Todo #${index + 1}` }), {});
saveTodos(todos);
return todos;
}
function getTodos(): Todos {
const todosFromStorage = localStorage.getItem(TODOS_KEY);
if (todosFromStorage === null) {
return initializeTodos();
}
return JSON.parse(todosFromStorage);
}
function addTodo(todo: string): void {
const newTodos = { ...getTodos() };
newTodos[uuid()] = todo;
saveTodos(newTodos);
}
function deleteTodo(id: string): void {
const newTodos = { ...getTodos() };
delete newTodos[id];
saveTodos(newTodos);
}
async function todoListAction({ request }: ActionFunctionArgs) {
await sleep();
const formData = await request.formData();
// Deletion via fetcher
if (formData.get('action') === 'delete') {
const id = formData.get('todoId');
if (typeof id === 'string') {
deleteTodo(id);
return { ok: true };
}
}
// Addition via <Form>
const todo = formData.get('todo');
if (typeof todo === 'string') {
addTodo(todo);
}
return new Response(null, {
status: 302,
headers: { Location: '/todos' },
});
}
async function todoListLoader(): Promise<Todos> {
await sleep(100);
return getTodos();
}
function TodosList() {
const todos = useLoaderData() as Todos;
const navigation = useNavigation();
const formRef = React.useRef<HTMLFormElement>(null);
// If we add and then we delete - this will keep isAdding=true until the
// fetcher completes it's revalidation
const [isAdding, setIsAdding] = React.useState(false);
React.useEffect(() => {
if (navigation.formData?.get('action') === 'add') {
setIsAdding(true);
} else if (navigation.state === 'idle') {
setIsAdding(false);
formRef.current?.reset();
}
}, [navigation]);
const items = Object.entries(todos).map(([id, todo]) => (
<li key={id}>
<TodoListItem id={id} todo={todo} />
</li>
));
return (
<>
<h1>Todos</h1>
<ul>
<li>
<Link to="/todos/junk">Click to trigger error</Link>
</li>
{items}
</ul>
<Form method="post" ref={formRef}>
<input type="hidden" name="action" value="add" />
<input name="todo"></input>
<button type="submit" disabled={isAdding}>
{isAdding ? 'Adding...' : 'Add'}
</button>
</Form>
<Outlet />
</>
);
}
interface TodoItemProps {
id: string;
todo: string;
}
function TodoListItem({ id, todo }: TodoItemProps) {
const fetcher = useFetcher();
const isDeleting = fetcher.formData != null;
return (
<>
<Link to={id}>{todo}</Link>
<fetcher.Form method="post">
<input type="hidden" name="action" value="delete" />
<button type="submit" name="todoId" value={id} disabled={isDeleting}>
{isDeleting ? 'Deleting...' : 'Delete'}
</button>
</fetcher.Form>
</>
);
}
function Todo() {
const params = useParams();
const todo = useLoaderData() as string;
return (
<>
<h2>Todo:</h2>
<p>id: {params.id}</p>
<p>title: {todo}</p>
</>
);
}
async function todoLoader({ params }: LoaderFunctionArgs) {
await sleep();
const todos = getTodos();
if (!params.id) throw new Error('Expected params.id');
const todo = todos[params.id];
if (!todo) throw new Error(`Uh oh, I couldn't find a todo with id "${params.id}"`);
return todo;
}
export const TodoListScenario = {
render: () => <TodosList />,
parameters: {
reactRouter: {
routePath: '/todos',
loader: todoListLoader,
action: todoListAction,
outlet: {
path: ':id',
element: <Todo />,
loader: todoLoader,
},
},
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { useFetcher } from 'react-router-dom';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v1/Action',
decorators: [withRouter],
};
function TinyForm() {
const fetcher = useFetcher();
return (
<div>
<fetcher.Form method="post">
<input type="hidden" name="foo" value="bar" />
<button type="submit">Submit</button>
</fetcher.Form>
</div>
);
}
export const TextFormData = {
render: () => <TinyForm />,
parameters: {
reactRouter: {
action: async () => ({ result: 42 }),
},
},
};
function FileForm() {
const fetcher = useFetcher();
return (
<div>
<fetcher.Form method="post" encType="multipart/form-data">
<label htmlFor="file-uploader">Upload file:</label>
<input id="file-uploader" type="file" name="myFile" />
<button type="submit">Submit</button>
</fetcher.Form>
</div>
);
}
export const FileFormData = {
render: () => <FileForm />,
parameters: {
reactRouter: {
action: async () => ({ result: 'file saved' }),
},
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { Link, Outlet, useLoaderData, useLocation, useRouteError } from 'react-router-dom';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v1/Loader',
decorators: [withRouter],
};
function sleep(n = 500) {
return new Promise((r) => setTimeout(r, n));
}
function loader(response: unknown) {
return async () => sleep(100).then(() => ({ foo: response }));
}
function DataLoader() {
const data = useLoaderData() as { foo: string };
return <h1>{data.foo}</h1>;
}
export const RouteLoader = {
render: () => <DataLoader />,
parameters: {
reactRouter: {
loader: loader('Data loaded'),
},
},
};
function DataLoaderWithOutlet() {
const data = useLoaderData() as { foo: string };
return (
<div>
<h1>{data.foo}</h1>
<Outlet />
</div>
);
}
function DataLoaderOutlet() {
const data = useLoaderData() as { foo: string };
return (
<div>
<h2>{data.foo}</h2>
</div>
);
}
export const RouteAndOutletLoader = {
render: () => <DataLoaderWithOutlet />,
parameters: {
reactRouter: {
loader: loader('Data loaded'),
outlet: {
element: <DataLoaderOutlet />,
loader: loader('Outlet data loaded'),
},
},
},
};
function AddSearchParam() {
const location = useLocation();
return (
<div>
{location.search}
<div>
<Link to={{ search: '?foo=bar' }}>Add Search Param</Link>
</div>
</div>
);
}
export const RouteShouldNotRevalidate = {
render: () => <AddSearchParam />,
parameters: {
reactRouter: {
loader: loader('Should not appear again after search param is added'),
shouldRevalidate: () => false,
},
},
};
function DataErrorBoundary() {
const error = useRouteError() as Error;
return <h1>Fancy error component : {error.message}</h1>;
}
async function failingLoader() {
throw new Error('Meh.');
}
export const ErrorBoundary = {
render: () => <DataLoader />,
parameters: {
reactRouter: {
loader: failingLoader,
errorElement: <DataErrorBoundary />,
},
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { generatePath } from '@remix-run/router';
import React, { useState } from 'react';
import { Link, Outlet, useLocation, useMatches, useParams, useSearchParams } from 'react-router-dom';
import { reactRouterNestedAncestors } from '../../features/decorator/utils/routesHelpers/reactRouterNestedAncestors';
import { reactRouterNestedOutlets } from '../../features/decorator/utils/routesHelpers/reactRouterNestedOutlets';
import { reactRouterOutlet } from '../../features/decorator/utils/routesHelpers/reactRouterOutlet';
import { reactRouterOutlets } from '../../features/decorator/utils/routesHelpers/reactRouterOutlets';
import { reactRouterParameters } from '../../features/decorator/utils/routesHelpers/reactRouterParameters';
import { withRouter } from '../../features/decorator/withRouter';
export default {
title: 'v2/Basics',
decorators: [withRouter],
};
export const ZeroConfig = {
render: () => <h1>Hi</h1>,
};
export const PreserveComponentState = {
render: ({ id }: { id: string }) => {
const [count, setCount] = useState(0);
return (
<div>
<h1>{id}</h1>
<button onClick={() => setCount((count) => count + 1)}>Increase</button>
<div role={'status'}>{count}</div>
</div>
);
},
args: {
id: '42',
},
};
export const LocationPath = {
render: () => {
const location = useLocation();
return <p>{location.pathname}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
location: {
path: '/books',
},
routing: { path: '/books' },
}),
},
};
export const LocationPathFromFunctionStringResult = {
render: () => {
const location = useLocation();
return <p>{location.pathname}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
location: {
path: (inferredPath, pathParams) => {
return generatePath(inferredPath, pathParams);
},
pathParams: { bookId: 777 },
},
routing: { path: '/books/:bookId' },
}),
},
};
export const LocationPathFromFunctionUndefinedResult = {
render: () => {
const location = useLocation();
return <p>{location.pathname}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
location: {
path: () => undefined,
},
routing: { path: '/books' },
}),
},
};
export const LocationPathBestGuess = {
render: () => (
<div>
<h1>Story</h1>
The outlet should be shown below.
<Outlet />
</div>
),
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet(
{
path: 'books',
},
{
path: 'summary',
element: <h2>I'm the outlet</h2>,
}
),
}),
},
};
export const LocationPathParams = {
render: () => {
const routeParams = useParams();
return <p>{JSON.stringify(routeParams)}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
location: {
path: '/book/:bookId',
pathParams: {
bookId: '42',
},
},
routing: {
path: '/book/:bookId',
},
}),
},
};
export const LocationSearchParams = {
render: () => {
const [searchParams] = useSearchParams();
return <p>{JSON.stringify(Object.fromEntries(searchParams.entries()))}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
location: {
searchParams: { page: '42' },
},
}),
},
};
export const RoutingString = {
render: () => {
const location = useLocation();
return <p>{location.pathname}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
routing: '/books',
}),
},
};
export const RoutingHandles = {
render: () => {
const matches = useMatches();
return <p>{JSON.stringify(matches.map((m) => m.handle))}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet(
{ handle: 'Handle part 1 out of 2' },
{
handle: 'Handle part 2 out of 2',
element: <p>I'm the outlet.</p>,
}
),
}),
},
};
export const RoutingOutletJSX = {
render: () => <Outlet />,
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet(<h1>I'm an outlet defined by a JSX element</h1>),
}),
},
};
export const RoutingOutletConfigObject = {
render: () => <Outlet />,
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet({
element: <h1>I'm an outlet defined with a config object</h1>,
}),
}),
},
};
export const RoutingOutlets = {
render: () => {
const location = useLocation();
return (
<section>
<h1>Story</h1>
<h2>Current URL : {location.pathname}</h2>
<p>Go to :</p>
<ul>
<li>
<Link to={'/'}>Index</Link>
</li>
<li>
<Link to={'one'}>One</Link>
</li>
<li>
<Link to={'two'}>Two</Link>
</li>
</ul>
<Outlet />
</section>
);
},
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlets([
{
path: '',
element: <p>Outlet Index</p>,
},
{
path: 'one',
element: <p>Outlet One</p>,
},
{
path: 'two',
element: <p>Outlet Two</p>,
},
]),
}),
},
};
export const RoutingNestedOutlets = {
render: () => (
<section>
<h1>Story</h1>
<Outlet />
</section>
),
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterNestedOutlets([
<>
<p>Outlet level 1</p>
<Outlet />
</>,
<>
<p>Outlet level 2</p>
<Outlet />
</>,
<>
<p>Outlet level 3</p>
<Outlet />
</>,
]),
}),
},
};
export const RoutingNestedAncestors = {
render: () => (
<section>
<h1>Story</h1>
</section>
),
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterNestedAncestors([
<>
<p>Ancestor level 1</p>
<Outlet />
</>,
<>
<p>Ancestor level 2</p>
<Outlet />
</>,
<>
<p>Ancestor level 3</p>
<Outlet />
</>,
]),
}),
},
};
export const RoutingRouteId = {
render: () => {
const matches = useMatches();
return <p>{JSON.stringify(matches.map((m) => m.id))}</p>;
},
parameters: {
reactRouter: reactRouterParameters({
routing: {
id: 'SomeRouteId',
},
}),
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import { composeStories } from '@storybook/react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { invariant } from '../../utils/misc';
import * as BasicStories from './Basics.stories';
import * as ActionStories from './DataRouter/Action.stories';
import * as ComplexStories from './DataRouter/Complex.stories';
import * as LoaderStories from './DataRouter/Loader.stories';
import * as DescendantRoutesStories from './DescendantRoutes.stories';
describe('StoryRouteTree', () => {
describe('Basics', () => {
const {
ZeroConfig,
PreserveComponentState,
LocationPath,
LocationPathFromFunctionStringResult,
LocationPathFromFunctionUndefinedResult,
LocationPathParams,
LocationPathBestGuess,
LocationSearchParams,
RoutingString,
RoutingRouteId,
RoutingHandles,
RoutingOutletJSX,
RoutingOutletConfigObject,
RoutingOutlets,
RoutingNestedOutlets,
RoutingNestedAncestors,
} = composeStories(BasicStories);
it('should render the story with zero config', () => {
render(<ZeroConfig />);
expect(screen.getByRole('heading', { name: 'Hi' })).toBeInTheDocument();
});
it('should preserve the state of the component when its updated locally or when the story args are changed', async () => {
const { rerender } = render(<PreserveComponentState />);
const user = userEvent.setup();
await user.click(screen.getByRole('button'));
expect(screen.getByRole('heading', { name: '42' })).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('1');
PreserveComponentState.args.id = '43';
rerender(<PreserveComponentState />);
expect(screen.getByRole('heading', { name: '43' })).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('1');
});
it('should render component at the specified path', async () => {
render(<LocationPath />);
expect(screen.getByText('/books')).toBeInTheDocument();
});
it('should render component at the path return by the function', async () => {
render(<LocationPathFromFunctionStringResult />);
expect(screen.getByText('/books/777')).toBeInTheDocument();
});
it('should render component at the inferred path if the function returns undefined', async () => {
render(<LocationPathFromFunctionUndefinedResult />);
expect(screen.getByText('/books')).toBeInTheDocument();
});
it('should render component with the specified route params', async () => {
render(<LocationPathParams />);
expect(screen.getByText('{"bookId":"42"}')).toBeInTheDocument();
});
it('should guess the location path and render the component tree', () => {
render(<LocationPathBestGuess />);
expect(screen.getByRole('heading', { level: 2, name: "I'm the outlet" })).toBeInTheDocument();
});
it('should render component with the specified search params', async () => {
render(<LocationSearchParams />);
expect(screen.getByText('{"page":"42"}')).toBeInTheDocument();
});
it('should render route with the assigned id', () => {
render(<RoutingRouteId />);
expect(screen.getByText('["SomeRouteId"]')).toBeInTheDocument();
});
it('should render component with the specified route handle', async () => {
render(<RoutingString />);
expect(screen.getByText('/books')).toBeInTheDocument();
});
it('should render component with the specified route handle', async () => {
render(<RoutingHandles />);
expect(screen.getByText('["Handle part 1 out of 2","Handle part 2 out of 2"]')).toBeInTheDocument();
});
it('should render outlet component defined by a JSX element', () => {
render(<RoutingOutletJSX />);
expect(screen.getByRole('heading', { name: "I'm an outlet defined by a JSX element" })).toBeInTheDocument();
});
it('should render outlet component defined with config object', () => {
render(<RoutingOutletConfigObject />);
expect(screen.getByRole('heading', { name: "I'm an outlet defined with a config object" })).toBeInTheDocument();
});
it('should render the component tree and the matching outlet if many are set', async () => {
render(<RoutingOutlets />);
expect(screen.getByText('Outlet Index')).toBeInTheDocument();
const user = userEvent.setup();
await user.click(screen.getByRole('link', { name: 'One' }));
expect(screen.getByText('Outlet One')).toBeInTheDocument();
});
it('should render all the nested outlets when there is only one per level ', () => {
render(<RoutingNestedOutlets />);
expect(screen.getByText('Story')).toBeInTheDocument();
expect(screen.getByText('Outlet level 1')).toBeInTheDocument();
expect(screen.getByText('Outlet level 2')).toBeInTheDocument();
expect(screen.getByText('Outlet level 3')).toBeInTheDocument();
});
it('should render all the nested ancestors when there is only one per level ', () => {
render(<RoutingNestedAncestors />);
expect(screen.getByText('Ancestor level 1')).toBeInTheDocument();
expect(screen.getByText('Ancestor level 2')).toBeInTheDocument();
expect(screen.getByText('Ancestor level 3')).toBeInTheDocument();
expect(screen.getByText('Story')).toBeInTheDocument();
});
});
describe('DescendantRoutes', () => {
const { DescendantRoutesOneIndex, DescendantRoutesOneRouteMatch, DescendantRoutesTwoRouteMatch } =
composeStories(DescendantRoutesStories);
it('should render the index route when on root path', async () => {
render(<DescendantRoutesOneIndex />);
expect(screen.queryByRole('heading', { name: 'Library Index' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Explore collection 13' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Pick a book at random' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Collection: 13' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Book id: 777' })).not.toBeInTheDocument();
});
it('should navigate appropriately when clicking a link', async () => {
render(<DescendantRoutesOneIndex />);
const user = userEvent.setup();
await user.click(screen.getByRole('link', { name: 'Explore collection 13' }));
expect(screen.queryByRole('heading', { name: 'Library Index' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Explore collection 13' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Collection: 13' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Pick a book at random' })).toBeInTheDocument();
});
it('should render the nested matching route when accessed directly by location pathname', () => {
render(<DescendantRoutesOneRouteMatch />);
expect(screen.queryByRole('heading', { name: 'Library Index' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Explore collection 13' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Collection: 13' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Pick a book at random' })).toBeInTheDocument();
});
it('should render the deeply nested matching route when accessed directly by location pathname', () => {
render(<DescendantRoutesTwoRouteMatch />);
expect(screen.queryByRole('heading', { name: 'Library Index' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Explore collection 13' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Pick a book at random' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Collection: 13' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Book id: 777' })).toBeInTheDocument();
});
});
describe('Loader', () => {
const { RouteLoader, RouteAndOutletLoader, ErrorBoundary } = composeStories(LoaderStories);
it('should render component with route loader', async () => {
render(<RouteLoader />);
await waitFor(() => expect(screen.getByRole('heading', { name: 'Data loaded' })).toBeInTheDocument(), {
timeout: 1000,
});
});
it('should render component with route loader and outlet loader', async () => {
render(<RouteAndOutletLoader />);
await waitFor(() => expect(screen.getByRole('heading', { level: 1, name: 'Data loaded' })).toBeInTheDocument(), {
timeout: 1000,
});
await waitFor(
() => expect(screen.getByRole('heading', { level: 2, name: 'Outlet data loaded' })).toBeInTheDocument(),
{ timeout: 1000 }
);
});
it('should render the error boundary if the route loader fails', async () => {
render(<ErrorBoundary />);
await waitFor(() =>
expect(screen.queryByRole('heading', { name: 'Fancy error component : Meh.', level: 1 })).toBeInTheDocument()
);
});
it('should not revalidate the route data', async () => {
const { RouteShouldNotRevalidate } = composeStories(LoaderStories);
invariant(RouteShouldNotRevalidate.parameters);
const loader = vi.fn(() => 'Yo');
RouteShouldNotRevalidate.parameters.reactRouter.routing.loader = loader;
render(<RouteShouldNotRevalidate />);
await waitFor(() => expect(loader).toHaveBeenCalledOnce());
const user = userEvent.setup();
await user.click(screen.getByRole('link'));
screen.getByText('?foo=bar');
expect(loader).toHaveBeenCalledOnce();
});
});
describe('Action', () => {
const { TextFormData, FileFormData } = composeStories(ActionStories);
it('should handle route action with text form', async () => {
const action = vi.fn();
invariant(TextFormData.parameters);
TextFormData.parameters.reactRouter.routing.action = action;
render(<TextFormData />);
const user = userEvent.setup();
await user.click(screen.getByRole('button'));
expect(action).toHaveBeenCalledOnce();
expect(action.mock.lastCall?.[0].request).toBeInstanceOf(Request);
const formData = await (action.mock.lastCall?.[0].request as Request).formData();
const pojoFormData = Object.fromEntries(formData.entries());
expect(pojoFormData).toEqual({ foo: 'bar' });
});
it('should handle route action with file form', async () => {
const action = vi.fn();
invariant(FileFormData.parameters);
FileFormData.parameters.reactRouter.routing.action = action;
const file = new File(['hello'], 'hello.txt', { type: 'plain/text' });
render(<FileFormData />);
const input = screen.getByLabelText(/file/i) as HTMLInputElement;
const user = userEvent.setup();
await user.upload(input, file);
await user.click(screen.getByRole('button'));
expect(input.files).toHaveLength(1);
expect(input.files?.item(0)).toStrictEqual(file);
expect(action).toHaveBeenCalledOnce();
expect(action.mock.lastCall?.[0].request).toBeInstanceOf(Request);
const request = action.mock.lastCall?.[0].request as Request;
const formData = await request.formData();
const pojoFormData = Object.fromEntries(formData.entries());
expect(pojoFormData).toHaveProperty('myFile');
});
});
describe('Complex', () => {
const { TodoListScenario } = composeStories(ComplexStories);
it('should render route with actions properly', async () => {
render(<TodoListScenario />);
await waitFor(() => expect(screen.queryByRole('heading', { level: 1, name: 'Todos' })).toBeInTheDocument(), {
timeout: 1000,
});
});
});
});
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { Link, Route, Routes, useParams } from 'react-router-dom';
import { reactRouterParameters } from '../../features/decorator/utils/routesHelpers/reactRouterParameters';
import { withRouter } from '../../features/decorator/withRouter';
export default {
title: 'v2/DescendantRoutes',
decorators: [withRouter],
};
function LibraryComponent() {
return (
<div>
<Link to={''} relative={'route'}>
Get back to the Library
</Link>
<p>Below is the Library {`<Routes />`}</p>
<Routes>
<Route index element={<LibraryIndexComponent />} />
<Route path=":collectionId/*" element={<CollectionComponent />} />
</Routes>
</div>
);
}
function CollectionComponent() {
const params = useParams();
return (
<div>
<h2>Collection: {params.collectionId}</h2>
<p>Below is the Collection {`<Routes />`}</p>
<Routes>
<Route index element={<CollectionIndexComponent />} />
<Route path="partnerBookId" element={<BookDetailsComponent />} />
<Route path=":bookId" element={<BookDetailsComponent />} />
</Routes>
</div>
);
}
function LibraryIndexComponent() {
return (
<div>
<h2>Library Index</h2>
<ul>
<li>
<Link to="13">Explore collection 13</Link>
</li>
<li>
<Link to="14">Explore collection 14</Link>
</li>
</ul>
</div>
);
}
function CollectionIndexComponent() {
return (
<div>
<ul>
<li>
<Link to="partnerBookId">See our partner's book</Link>
</li>
<li>
<Link to="777">Pick a book at random</Link>
</li>
</ul>
</div>
);
}
function BookDetailsComponent() {
const params = useParams();
const isPartnerBook = params.bookId === undefined;
return (
<div>
{isPartnerBook && <h3>Our partner book</h3>}
{!isPartnerBook && <h3>Book id: {params.bookId}</h3>}
<p>What a wonderful book !</p>
</div>
);
}
export const DescendantRoutesOneIndex = {
render: () => <LibraryComponent />,
parameters: {
reactRouter: reactRouterParameters({
location: { path: '/library' },
routing: { path: '/library/*' },
}),
},
};
export const DescendantRoutesOneRouteMatch = {
render: () => <LibraryComponent />,
parameters: {
reactRouter: reactRouterParameters({
routing: { path: '/library/*' },
location: { path: '/library/13' },
}),
},
};
export const DescendantRoutesTwoRouteMatch = {
render: () => <LibraryComponent />,
parameters: {
reactRouter: reactRouterParameters({
routing: { path: '/library/*' },
location: { path: '/library/13/777' },
}),
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
/**
* Credits : https://github.com/remix-run/react-router
* reactrouter.com
*/
import React from 'react';
import {
ActionFunctionArgs,
Form,
Link,
LoaderFunctionArgs,
Outlet,
useFetcher,
useLoaderData,
useNavigation,
useParams,
} from 'react-router-dom';
import { reactRouterOutlet } from '../../../features/decorator/utils/routesHelpers/reactRouterOutlet';
import { reactRouterParameters } from '../../../features/decorator/utils/routesHelpers/reactRouterParameters';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v2/Complex',
decorators: [withRouter],
};
function sleep(n = 500) {
return new Promise((r) => setTimeout(r, n));
}
interface Todos {
[key: string]: string;
}
const TODOS_KEY = 'todos';
const uuid = () => Math.random().toString(36).substr(2, 9);
function saveTodos(todos: Todos): void {
return localStorage.setItem(TODOS_KEY, JSON.stringify(todos));
}
function initializeTodos(): Todos {
const todos: Todos = new Array(3)
.fill(null)
.reduce((acc, _, index) => Object.assign(acc, { [uuid()]: `Seeded Todo #${index + 1}` }), {});
saveTodos(todos);
return todos;
}
function getTodos(): Todos {
const todosFromStorage = localStorage.getItem(TODOS_KEY);
if (todosFromStorage === null) {
return initializeTodos();
}
return JSON.parse(todosFromStorage);
}
function addTodo(todo: string): void {
const newTodos = { ...getTodos() };
newTodos[uuid()] = todo;
saveTodos(newTodos);
}
function deleteTodo(id: string): void {
const newTodos = { ...getTodos() };
delete newTodos[id];
saveTodos(newTodos);
}
async function todoListAction({ request }: ActionFunctionArgs) {
await sleep();
const formData = await request.formData();
// Deletion via fetcher
if (formData.get('action') === 'delete') {
const id = formData.get('todoId');
if (typeof id === 'string') {
deleteTodo(id);
return { ok: true };
}
}
// Addition via <Form>
const todo = formData.get('todo');
if (typeof todo === 'string') {
addTodo(todo);
}
return new Response(null, {
status: 302,
headers: { Location: '/todos' },
});
}
async function todoListLoader(): Promise<Todos> {
await sleep(100);
return getTodos();
}
function TodosList() {
const todos = useLoaderData() as Todos;
const navigation = useNavigation();
const formRef = React.useRef<HTMLFormElement>(null);
// If we add and then we delete - this will keep isAdding=true until the
// fetcher completes it's revalidation
const [isAdding, setIsAdding] = React.useState(false);
React.useEffect(() => {
if (navigation.formData?.get('action') === 'add') {
setIsAdding(true);
} else if (navigation.state === 'idle') {
setIsAdding(false);
formRef.current?.reset();
}
}, [navigation]);
const items = Object.entries(todos).map(([id, todo]) => (
<li key={id}>
<TodoListItem id={id} todo={todo} />
</li>
));
return (
<>
<h1>Todos</h1>
<ul>
<li>
<Link to="/todos/junk">Click to trigger error</Link>
</li>
{items}
</ul>
<Form method="post" ref={formRef}>
<input type="hidden" name="action" value="add" />
<input name="todo"></input>
<button type="submit" disabled={isAdding}>
{isAdding ? 'Adding...' : 'Add'}
</button>
</Form>
<Outlet />
</>
);
}
interface TodoItemProps {
id: string;
todo: string;
}
function TodoListItem({ id, todo }: TodoItemProps) {
const fetcher = useFetcher();
const isDeleting = fetcher.formData != null;
return (
<>
<Link to={id}>{todo}</Link>
<fetcher.Form method="post">
<input type="hidden" name="action" value="delete" />
<button type="submit" name="todoId" value={id} disabled={isDeleting}>
{isDeleting ? 'Deleting...' : 'Delete'}
</button>
</fetcher.Form>
</>
);
}
function Todo() {
const params = useParams();
const todo = useLoaderData() as string;
return (
<>
<h2>Todo:</h2>
<p>id: {params.id}</p>
<p>title: {todo}</p>
</>
);
}
async function todoLoader({ params }: LoaderFunctionArgs) {
await sleep();
const todos = getTodos();
if (!params.id) throw new Error('Expected params.id');
const todo = todos[params.id];
if (!todo) throw new Error(`Uh oh, I couldn't find a todo with id "${params.id}"`);
return todo;
}
export const TodoListScenario = {
render: () => <TodosList />,
parameters: {
reactRouter: reactRouterParameters({
location: { path: '/todos' },
routing: reactRouterOutlet(
{
path: '/todos',
loader: todoListLoader,
action: todoListAction,
},
{
path: ':id',
element: <Todo />,
loader: todoLoader,
}
),
}),
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { useFetcher } from 'react-router-dom';
import { reactRouterParameters } from '../../../features/decorator/utils/routesHelpers/reactRouterParameters';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v2/Action',
decorators: [withRouter],
};
function TextForm() {
const fetcher = useFetcher();
return (
<div>
<fetcher.Form method="post">
<input type="hidden" name="foo" value="bar" />
<button type="submit">Submit</button>
</fetcher.Form>
</div>
);
}
export const TextFormData = {
render: () => <TextForm />,
parameters: {
reactRouter: reactRouterParameters({
routing: { action: async () => ({ result: 42 }) },
}),
},
};
function FileForm() {
const fetcher = useFetcher();
return (
<div>
<fetcher.Form method="post" encType="multipart/form-data">
<label htmlFor="file-uploader">Upload file:</label>
<input id="file-uploader" type="file" name="myFile" />
<button type="submit">Submit</button>
</fetcher.Form>
</div>
);
}
export const FileFormData = {
render: () => <FileForm />,
parameters: {
reactRouter: reactRouterParameters({
routing: { action: async () => ({ result: 'file saved' }) },
}),
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import React from 'react';
import { Link, Outlet, useLoaderData, useLocation, useRouteError } from 'react-router-dom';
import { reactRouterOutlet } from '../../../features/decorator/utils/routesHelpers/reactRouterOutlet';
import { reactRouterParameters } from '../../../features/decorator/utils/routesHelpers/reactRouterParameters';
import { withRouter } from '../../../features/decorator/withRouter';
export default {
title: 'v2/Loader',
decorators: [withRouter],
};
function sleep(n = 500) {
return new Promise((r) => setTimeout(r, n));
}
function loader(response: unknown) {
return async () => sleep(100).then(() => ({ foo: response }));
}
function DataLoader() {
const data = useLoaderData() as { foo: string };
return <h1>{data.foo}</h1>;
}
export const RouteLoader = {
render: () => <DataLoader />,
parameters: {
reactRouter: reactRouterParameters({
routing: { loader: loader('Data loaded') },
}),
},
};
function DataLoaderWithOutlet() {
const data = useLoaderData() as { foo: string };
return (
<div>
<h1>{data.foo}</h1>
<Outlet />
</div>
);
}
function DataLoaderOutlet() {
const data = useLoaderData() as { foo: string };
return (
<div>
<h2>{data.foo}</h2>
</div>
);
}
export const RouteAndOutletLoader = {
render: () => <DataLoaderWithOutlet />,
parameters: {
reactRouter: reactRouterParameters({
routing: reactRouterOutlet(
{
loader: loader('Data loaded'),
},
{
index: true,
element: <DataLoaderOutlet />,
loader: loader('Outlet data loaded'),
}
),
}),
},
};
export const RouteShouldNotRevalidate = {
render: () => {
const location = useLocation();
return (
<div>
{location.search}
<div>
<Link to={{ search: '?foo=bar' }}>Add Search Param</Link>
</div>
</div>
);
},
parameters: {
reactRouter: reactRouterParameters({
routing: {
loader: loader('Should not appear again after search param is added'),
shouldRevalidate: () => false,
},
}),
},
};
function DataErrorBoundary() {
const error = useRouteError() as Error;
return <h1>Fancy error component : {error.message}</h1>;
}
async function failingLoader() {
throw new Error('Meh.');
}
export const ErrorBoundary = {
render: () => <DataLoader />,
parameters: {
reactRouter: reactRouterParameters({
routing: {
loader: failingLoader,
errorElement: <DataErrorBoundary />,
},
}),
},
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable no-console */
const prompts = require('prompts');
const dedent = require('ts-dedent').default;
const path = require('path');
const fs = require('fs');
const { execSync } = require('child_process');
// CLI questions
const questions = [
{
type: 'text',
name: 'authorName',
initial: '',
message: 'What is the package author name?*',
validate: (name) => (name === '' ? "Name can't be empty" : true),
},
{
type: 'text',
name: 'authorEmail',
initial: '',
message: 'What is the package author email?',
},
{
type: 'text',
name: 'packageName',
message: 'What is the addon package name (eg: storybook-addon-something)?*',
validate: (name) => (name === '' ? "Package name can't be empty" : true),
},
{
type: 'text',
name: 'displayName',
message: 'What is the addon display name (this will be used in the addon catalog)?*',
validate: (name) =>
name === ''
? "Display name can't be empty. For more info, see: https://storybook.js.org/docs/react/addons/addon-catalog#addon-metadata"
: true,
},
{
type: 'text',
name: 'addonDescription',
initial: '',
message: 'Write a short description of the addon*',
validate: (name) => (name === '' ? "Description can't be empty" : true),
},
{
type: 'text',
name: 'repoUrl',
message: 'Git repo URL for your addon package (https://github.com/...)*',
validate: (url) => (url === '' ? "URL can't be empty" : true),
},
{
type: 'text',
name: 'addonIcon',
initial: 'https://user-images.githubusercontent.com/321738/63501763-88dbf600-c4cc-11e9-96cd-94adadc2fd72.png',
message: 'URL of your addon icon',
},
{
type: 'list',
name: 'keywords',
initial: ['storybook-addons'],
message: 'Enter addon keywords (comma separated)',
separator: ',',
format: (keywords) =>
keywords
.concat(['storybook-addons'])
.map((k) => `"${k}"`)
.join(', '),
},
{
type: 'list',
name: 'supportedFrameworks',
initial: 'react, vue, angular, web-components, ember, html, svelte, preact, react-native',
message: 'List of frameworks you support (comma separated)?',
separator: ',',
format: (frameworks) => frameworks.map((k) => `"${k}"`).join(', '),
},
];
const REPLACE_TEMPLATES = {
packageName: 'storybook-addon-kit',
addonDescription: 'everything you need to build a Storybook addon',
packageAuthor: 'package-author',
repoUrl: 'https://github.com/storybookjs/storybook-addon-kit',
keywords: `"storybook-addons"`,
displayName: 'Addon Kit',
supportedFrameworks: `"supported-frameworks"`,
};
const bold = (message) => `\u001b[1m${message}\u001b[22m`;
const magenta = (message) => `\u001b[35m${message}\u001b[39m`;
const blue = (message) => `\u001b[34m${message}\u001b[39m`;
const main = async () => {
console.log(
bold(
magenta(
dedent`
Welcome to Storybook addon-kit!
Please answer the following questions while we prepare this project for you:\n
`
)
)
);
const {
authorName,
authorEmail,
packageName,
addonDescription,
repoUrl,
displayName,
keywords,
supportedFrameworks,
} = await prompts(questions);
if (!authorName || !packageName) {
console.log(
`\nProcess canceled by the user. Feel free to run ${bold(
'yarn postinstall'
)} to execute the installation steps again!`
);
process.exit(0);
}
const authorField = authorName + (authorEmail ? ` <${authorEmail}>` : '');
const packageJson = path.resolve(__dirname, `../package.json`);
console.log(`\n👷 Updating package.json...`);
let packageJsonContents = fs.readFileSync(packageJson, 'utf-8');
packageJsonContents = packageJsonContents
.replace(REPLACE_TEMPLATES.packageName, packageName)
.replace(REPLACE_TEMPLATES.addonDescription, addonDescription)
.replace(REPLACE_TEMPLATES.packageAuthor, authorField)
.replace(REPLACE_TEMPLATES.keywords, keywords)
.replace(REPLACE_TEMPLATES.repoUrl, repoUrl)
.replace(REPLACE_TEMPLATES.displayName, displayName)
.replace(REPLACE_TEMPLATES.supportedFrameworks, supportedFrameworks)
.replace(' "postinstall": "node scripts/welcome.js",\n', '');
fs.writeFileSync(packageJson, packageJsonContents);
console.log('📝 Updating the README...');
const readme = path.resolve(__dirname, `../README.md`);
let readmeContents = fs.readFileSync(readme, 'utf-8');
const regex = /<\!-- README START -->([\s\S]*)<\!-- README END -->/g;
readmeContents = readmeContents.replace(
regex,
dedent`
# Storybook Addon ${displayName}
${addonDescription}
`
);
fs.writeFileSync(readme, readmeContents);
console.log(`📦 Creating a commit...`);
execSync('git add . && git commit -m "project setup" --no-verify');
console.log(
dedent`\n
🚀 All done! Run \`yarn start\` test to get started.
Thanks for using this template, ${authorName.split(' ')[0]}! ❤️
Feel free to open issues in case there are bugs/feature requests at:
${bold(blue('https://github.com/storybookjs/addon-kit'))}\n
`
);
};
main().catch((e) => console.log(`Something went wrong: ${e}`));
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
#!/usr/bin/env zx
// Copy TS files and delete src
await $`cp -r ./src ./srcTS`;
await $`rm -rf ./src`;
await $`mkdir ./src`;
// Convert TS code to JS
await $`babel --no-babelrc --presets @babel/preset-typescript ./srcTS -d ./src --extensions \".js,.jsx,.ts,.tsx\" --ignore "./srcTS/typings.d.ts"`;
// Format the newly created .js files
await $`prettier --write ./src`;
// Add in minimal files required for the TS build setup
await $`touch ./src/dummy.ts`;
await $`printf "export {};" >> ./src/dummy.ts`;
await $`touch ./src/typings.d.ts`;
await $`printf 'declare module "global";' >> ./src/typings.d.ts`;
// Clean up
await $`rm -rf ./srcTS`;
console.log(
chalk.green.bold`
TypeScript Ejection complete!`,
chalk.green`
Addon code converted with JS. The TypeScript build setup is still available in case you want to adopt TypeScript in the future.
`
);
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
#!/usr/bin/env zx
const packageJson = require('../package.json');
const boxen = require('boxen');
const dedent = require('dedent');
const name = packageJson.name;
const displayName = packageJson.storybook.displayName;
let exitCode = 0;
$.verbose = false;
/**
* Check that meta data has been updated
*/
if (name.includes('addon-kit') || displayName.includes('Addon Kit')) {
console.error(
boxen(
dedent`
${chalk.red.bold('Missing metadata')}
${chalk.red(dedent`Your package name and/or displayName includes default values from the Addon Kit.
The addon gallery filters out all such addons.
Please configure appropriate metadata before publishing your addon. For more info, see:
https://storybook.js.org/docs/react/addons/addon-catalog#addon-metadata`)}`,
{ padding: 1, borderColor: 'red' }
)
);
exitCode = 1;
}
/**
* Check that README has been updated
*/
const readmeTestStrings =
'# Storybook Addon Kit|Click the \\*\\*Use this template\\*\\* button to get started.|https://user-images.githubusercontent.com/42671/106809879-35b32000-663a-11eb-9cdc-89f178b5273f.gif';
if ((await $`cat README.md | grep -E ${readmeTestStrings}`.exitCode) == 0) {
console.error(
boxen(
dedent`
${chalk.red.bold('README not updated')}
${chalk.red(dedent`You are using the default README.md file that comes with the addon kit.
Please update it to provide info on what your addon does and how to use it.`)}
`,
{ padding: 1, borderColor: 'red' }
)
);
exitCode = 1;
}
process.exit(exitCode);
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
<script>
window.global = window;
</script>
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
import type { StorybookConfig } from '@storybook/react-vite';
const config: StorybookConfig = {
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
stories: ['../src/stories/**/*.stories.@(ts|tsx)'],
addons: ['./local-preset.js'],
};
export default config;
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
function managerEntries(entry = []) {
return [...entry, require.resolve('../dist/manager.mjs')];
}
module.exports = {
managerEntries,
};
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
| {
"repo_name": "JesusTheHun/storybook-addon-react-router-v6",
"stars": "30",
"repo_language": "TypeScript",
"file_name": "pre-commit",
"mime_type": "text/plain"
} |
while getopts "ifc" opt; do
case $opt in
i)
convert promo/icon.png -resize 16x16 extension/icons/16.png
cp extension/icons/16.png docs/favicon.png
convert promo/icon.png -resize 24x24 extension/icons/24.png
convert promo/icon.png -resize 32x32 extension/icons/32.png
convert promo/icon.png -resize 48x48 extension/icons/48.png
convert promo/icon.png -resize 128x128 extension/icons/128.png
;;
f)
cp manifests/firefoxManifest.json extension/manifest.json
exit
;;
c)
cp manifests/chromeManifest.json extension/manifest.json
exit
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
cp manifests/firefoxManifest.json extension/manifest.json
(cd extension && zip -r ../firefox.zip .)
cp manifests/chromeManifest.json extension/manifest.json
(cd extension && zip -r ../chrome.zip .)
| {
"repo_name": "corollari/ankiTab",
"stars": "168",
"repo_language": "JavaScript",
"file_name": "config.js",
"mime_type": "text/plain"
} |
[link-cws]: https://chrome.google.com/webstore/detail/ankitab/ihoaepdiibjbifnhcjoaddgcnfgjmjdk "Version published on Chrome Web Store"
[link-amo]: https://addons.mozilla.org/en-US/firefox/addon/ankitab/ "Version published on Mozilla Add-ons"
<h1 align="center">
<img src="https://raw.githubusercontent.com/corollari/ankiTab/master/promo/icon.png" width="64"></a>
<br>
AnkiTab
<br>
</h1>
<h4 align="center">Browser extension that replaces the new tab page with <a href="https://apps.ankiweb.net/" target="_blank">Anki</a> flashcards</h4>
<p align="center">
<a href="#install">Install</a> •
<a href="#build">Build</a> •
<a href="#credits">Credits</a> •
<a href="#to-do">TO-DO</a> •
<a href="#license">License</a>
</p>

## Install
- [**Chrome** extension][link-cws] [<img valign="middle" src="https://img.shields.io/chrome-web-store/v/ihoaepdiibjbifnhcjoaddgcnfgjmjdk.svg?label=%20">][link-cws]
- [**Firefox** add-on](https://github.com/corollari/ankiTab/issues/3)
## Build
##### Setup:
```bash
git clone https://github.com/corollari/ankiTab.git
cd ankiTab
```
##### Build .zip packages for Firefox and Chrome:
```bash
bash build.sh
```
##### Prepare the extension to be loaded unpacked into Firefox:
```bash
bash build.sh -f
```
##### Prepare the extension to be loaded unpacked into Chrome:
```bash
bash build.sh -c
```
##### Build the images (only necessary after changing the icon):
```bash
bash build.sh -i
```
## Credits
The main icon used in the extension comes from [Open Iconic](https://useiconic.com/open).
## TO-DO
- [ ] Use a standalone web version of Anki instead of relying on AnkiConnect
## License
The Unlicense
| {
"repo_name": "corollari/ankiTab",
"stars": "168",
"repo_language": "JavaScript",
"file_name": "config.js",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>New Tab</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../extension/libs/bootstrap.css">
<base href=".">
</head>
<body>
<div class="container">
<h1>AnkiTab</h1>
</div>
</body>
</html>
| {
"repo_name": "corollari/ankiTab",
"stars": "168",
"repo_language": "JavaScript",
"file_name": "config.js",
"mime_type": "text/plain"
} |
chrome.browserAction.onClicked.addListener(function (tab) { //Fired when the user clicks the extension's icon
chrome.tabs.create({ url: "about://newtab" });
//chrome.tabs.create({ url: "app/index.html" });
});
chrome.runtime.onInstalled.addListener(function() {
let defaults={
interleavingTrigger: 1,
lastDeck:"",
interleavingDisabled:false,
betaEnabled:false,
deckNames:[],
excludedDecks:[],
emptyDecks:[]
};
chrome.storage.local.get(Object.keys(defaults), function(result) {
for(let s in result){
delete defaults[s];
}
chrome.storage.local.set(defaults, function() {}); //Set missing default values
});
});
chrome.runtime.setUninstallURL("https://goo.gl/forms/QsvZzGcRfQTPZ66E2");
| {
"repo_name": "corollari/ankiTab",
"stars": "168",
"repo_language": "JavaScript",
"file_name": "config.js",
"mime_type": "text/plain"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.