feat(utils): add URL read/write helpers for filter state
This commit is contained in:
@@ -61,4 +61,36 @@ describe('changeColor', () => {
|
||||
it('returns text.secondary for null', () => {
|
||||
expect(changeColor(null)).toBe('text.secondary')
|
||||
})
|
||||
})
|
||||
|
||||
import { readFiltersFromUrl, writeFiltersToUrl } from '../utils/url.js'
|
||||
|
||||
describe('readFiltersFromUrl', () => {
|
||||
it('returns defaults when search is empty', () => {
|
||||
window.history.replaceState(null, '', '/?')
|
||||
expect(readFiltersFromUrl()).toEqual({ q: '', faction: '', dir: '' })
|
||||
})
|
||||
it('reads q, faction, dir from query string', () => {
|
||||
window.history.replaceState(null, '', '/?q=foo&faction=space-marines&dir=up')
|
||||
expect(readFiltersFromUrl()).toEqual({ q: 'foo', faction: 'space-marines', dir: 'up' })
|
||||
})
|
||||
it('returns empty strings for missing keys', () => {
|
||||
window.history.replaceState(null, '', '/?q=foo')
|
||||
expect(readFiltersFromUrl()).toEqual({ q: 'foo', faction: '', dir: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeFiltersToUrl', () => {
|
||||
it('writes all three params', () => {
|
||||
writeFiltersToUrl({ q: 'foo', faction: 'space-marines', dir: 'up' })
|
||||
expect(window.location.search).toBe('?q=foo&faction=space-marines&dir=up')
|
||||
})
|
||||
it('clears the query string when all are empty', () => {
|
||||
writeFiltersToUrl({ q: '', faction: '', dir: '' })
|
||||
expect(window.location.search).toBe('')
|
||||
})
|
||||
it('writes only the present keys (others stay empty)', () => {
|
||||
writeFiltersToUrl({ q: 'foo', faction: '', dir: '' })
|
||||
expect(window.location.search).toBe('?q=foo')
|
||||
})
|
||||
})
|
||||
18
react-app/src/utils/url.js
vendored
Normal file
18
react-app/src/utils/url.js
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
export function readFiltersFromUrl() {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
return {
|
||||
q: params.get('q') || '',
|
||||
faction: params.get('faction') || '',
|
||||
dir: params.get('dir') || '',
|
||||
}
|
||||
}
|
||||
|
||||
export function writeFiltersToUrl({ q, faction, dir }) {
|
||||
const params = new URLSearchParams()
|
||||
if (q) params.set('q', q)
|
||||
if (faction) params.set('faction', faction)
|
||||
if (dir) params.set('dir', dir)
|
||||
const qs = params.toString()
|
||||
const newUrl = qs ? `?${qs}` : window.location.pathname
|
||||
window.history.replaceState(null, '', newUrl)
|
||||
}
|
||||
Reference in New Issue
Block a user