Patch is a tiny Javascript class (1k compressed) with zero dependencies that makes pretty deep links easy.
Patch can be used with both:
Patch handles encoding and decoding for you, and makes your deep links pretty, so you don't have to think about it.
This object:
{
"countries": [
"Canada",
"France"
],
"selection": "France"
}
Becomes countries=Canada=France&selection=France
(and vice versa).
<script src="patch.js"></script>
window.location.hash = new Patch(
{
"countries": [
"Canada",
"France"
],
"selection": "France"
}
).uriEncodedString
console.log(new Patch(window.location.hash).object)
They key idea of Patch is to think of your query params as a spreadsheet.
Then Patch encodes and decodes that spreadsheet.
A Patch object has 4 forms:
countries Canada France
selection France
countries=Canada=France&selection=France
{
"countries": ["Canada", "France"],
"selection": ["France"],
}
[
["countries", "Canada", "France"],
["selection", "France"],
]
Patch requires 2 delimiters, one for separating "rows" and one for separating "columns".
The default is &
for rows and =
for columns.
You can change these to suit your own needs.
Patch encodes spaces to +
instead of %20
and uses the standard encoding of +
to %2B
.
String inputs to the Patch constructor are assumed to be encoded and will be decoded before parsing. Similarly the string output is always encoded.
Patch treats all scalars as strings. Do a just-in-time parse of numbers, booleans, or JSON values if needed.
QueryStrings can be thought of as a domain specific language for describing this structure:
type QueryStrings = Omit<string, [RestrictedCharacters]>
Map<QueryStrings, QueryStrings>
I made Patch in 2020 for Our World in Data.
This is an updated fork.