Skip to content

Commit

Permalink
url-state-provider: replace json-url with juri
Browse files Browse the repository at this point in the history
  • Loading branch information
andypf committed Aug 25, 2023
1 parent be2955b commit c896ff1
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 38 deletions.
8 changes: 8 additions & 0 deletions libs/url-state-provider/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
env: {
test: {
presets: ["@babel/preset-env"],
plugins: [["babel-plugin-transform-import-meta", { module: "ES6" }]],
},
},
}
6 changes: 6 additions & 0 deletions libs/url-state-provider/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
transform: { "\\.[jt]sx?$": "babel-jest" },
transformIgnorePatterns: [
"node_modules/(?!(query-string|decode-uri-component|split-on-first|filter-obj)/)",
],
}
15 changes: 6 additions & 9 deletions libs/url-state-provider/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "url-state-provider",
"version": "1.3.1",
"version": "1.3.2",
"description": "Save several paths in the url. This makes it possible to manage the status of several apps such as micro frontends with the help of URL.",
"source": "src/index.js",
"main": "build/cjs/index.js",
Expand All @@ -13,27 +13,24 @@
"devDependencies": {
"@babel/core": "^7.20.2",
"@babel/preset-env": "^7.20.2",
"@rollup/plugin-terser": "^0.1.0",
"babel-jest": "^29.3.1",
"babel-plugin-transform-import-meta": "^2.2.1",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"jest-esm-transformer": "^1.0.0",
"jsdom": "^18.0.0",
"juri-cutlery": "^1.0.0",
"lz-string": "^1.4.4",
"rollup": "^3.4.0",
"rollup-plugin-analyzer": "^4.0.0",
"rollup-plugin-delete": "^2.0.0",
"@jsonurl/jsonurl": "^1.1.7"
"rollup-plugin-delete": "^2.0.0"
},
"babel": {
"presets": [
"@babel/preset-env"
]
},
"jest": {
"verbose": true,
"transform": {
"\\.[jt]sx?$": "babel-jest"
}
"dependencies": {
"juri": "^1.0.3"
}
}
40 changes: 24 additions & 16 deletions libs/url-state-provider/src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import LZString from "lz-string"
import JsonURL from "@jsonurl/jsonurl"
import juriCutlery from "juri-cutlery"

var SEARCH_KEY = "__s"
const jsonURLSerializer = juriCutlery()
const SEARCH_KEY = "__s"
const regex = new RegExp(SEARCH_KEY + "=([^&]+)")

/**
* Variable where to host listeners for history changes
Expand All @@ -17,20 +19,17 @@ var onGlobalChangeListeners = []
*/
function encode(json, options = {}) {
try {
let urlState = JsonURL.stringify(json, {
AQF: true,
ignoreNullArrayMembers: true,
ignoreNullObjectMembers: true,
})
let urlState = jsonURLSerializer.encode(json)

if (options?.mode === "humanize") return urlState

if (urlState.length > 1800) {
urlState = LZString.compressToEncodedURIComponent(JSON.stringify(json))
}
//return LZString.compressToEncodedURIComponent(JSON.stringify(json))

return urlState
} catch (e) {
console.warn("URL State Provider: Could not encode data", data)
console.warn("URL State Provider: Could not encode data", json, e)
return ""
}
}
Expand All @@ -42,8 +41,8 @@ function encode(json, options = {}) {
*/
function decode(string) {
try {
// try to decode as jsonurl
let json = JsonURL.parse(encodeURIComponent(string), { AQF: true })
// try to decode using jsonURLSerializer
let json = jsonURLSerializer.decode(string)

// if parsed value is an object, return it
if (json && typeof json === "object") return json
Expand All @@ -67,10 +66,15 @@ function decode(string) {
* @returns json
*/
function URLToState() {
var currentUrl = new URL(window.location.href)
var urlStateParam = currentUrl.searchParams.get(SEARCH_KEY)
if (!urlStateParam) return {}
return decode(urlStateParam)
const match = window.location.href.match(regex)
if (!match) return {}
try {
// decodeURIComponent is needed to convert url encoded characters
return decode(decodeURIComponent(match[1]))
} catch (e) {
console.warn("URL State Provider: Could not decode string: ", match[1], e)
return {}
}
}

/**
Expand All @@ -90,9 +94,11 @@ function stateToQueryParam(state) {
*/
function stateToURL(state) {
var encodedState = encode(state)
// get current url
var newUrl = new URL(window.location.href)
// set new search params
newUrl.searchParams.set(SEARCH_KEY, encodedState)
//return newUrl.toString()
// return new url string, decodeURIComponent is needed to convert url encoded characters
return decodeURIComponent(newUrl.toString())
}

Expand All @@ -114,6 +120,8 @@ function currentState(stateID) {
function updateState(stateID, state, options = {}) {
// get current state from URL
const newState = URLToState()
// URLToState should return an object, if not return empty object
if ("string" === typeof newState) return {}
// change state, overwrite or merge if "merge" option is true
newState[stateID] = options?.merge
? { ...newState[stateID], ...state }
Expand Down
1 change: 0 additions & 1 deletion libs/url-state-provider/src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ describe("currentState", () => {

beforeAll(() => {
jest.resetModules()
delete window["__url_state_provider"]
window.location.href =
"http://localhost?test1=test1&__s=" + state + "&test2=test2"
})
Expand Down
32 changes: 20 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c896ff1

Please sign in to comment.