Patch: a micro language to make pretty deep links easy

May 27, 2024

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.

Example

This object:

{ "countries": [ "Canada", "France" ], "selection": "France" }

Becomes countries=Canada=France&selection=France (and vice versa).

How to use

  1. Include patch.js or just copy/paste the code:
<script src="patch.js"></script>
  1. Give your Javascript object to Patch, and it will give you the prettiest query string it can make:
window.location.hash = new Patch( { "countries": [ "Canada", "France" ], "selection": "France" } ).uriEncodedString
  1. Give Patch a query string, and it will give you back your Javascript object:
console.log(new Patch(window.location.hash).object)
*

Specification

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:

1. Spreadsheet Form

countries Canada France selection France

2. URI form

countries=Canada=France&selection=France

3. Object Form

{ "countries": ["Canada", "France"], "selection": ["France"], }

4. Matrix Form

[ ["countries", "Canada", "France"], ["selection", "France"], ]

Delimiters

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.

Spaces

Patch encodes spaces to + instead of %20 and uses the standard encoding of + to %2B.

URI Encoding

String inputs to the Patch constructor are assumed to be encoded and will be decoded before parsing. Similarly the string output is always encoded.

Scalar Types

Patch treats all scalars as strings. Do a just-in-time parse of numbers, booleans, or JSON values if needed.

*

Why Patch?

QueryStrings can be thought of as a domain specific language for describing this structure:

type QueryStrings = Omit<string, [RestrictedCharacters]> Map<QueryStrings, QueryStrings>

Some benefits of Patch

Live examples of Patch

History

I made Patch in 2020 for Our World in Data.

This is an updated fork.

View source