Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/lib/utils/localstorage-writable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { browser } from '$app/environment'
import { type Updater, type Writable, get, writable } from 'svelte/store'

export type LocalStorageWritable<T> = Writable<T | null> & {
wipe: () => void
}

/**
* A standard svelte-compatible writable with persistent values backed up in localStorage
* @param localStorageKey The key used for local-storage
* @param defaultValue The default value in case there is none found in localstorage
* @returns A standard writable that persists all value changes to localstorage
*/
export const localStorageWritable = <T>(
localStorageKey: string,
defaultValue?: T
): LocalStorageWritable<T> => {
const storedValue = browser ? localStorage.getItem(localStorageKey) : null
const localStorageValue = (() => {
try {
return storedValue !== null ? JSON.parse(storedValue) : null
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@benjaminstrasser the check here is redundant.
JSON.parse(null) === null

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes you are correct! I caught that too. Problem is JSON.parse is typed as parse(value: string) and not parse(value: string | null) even though parse(null) === null.

See here: #81 (comment)

} catch {
return null
}
})()

const initialValue: T | null = localStorageValue ?? defaultValue ?? null

const { set, subscribe } = writable<T | null>(null)

const setAndStore = (value: T | null) => {
if (browser) {
localStorage.setItem(localStorageKey, JSON.stringify(value))
}

set(value)
}

const wipe = () => {
if (browser) {
localStorage.removeItem(localStorageKey)
}

set(null)
}

setAndStore(initialValue)

return {
subscribe,
set: setAndStore,
wipe,
update: (updater: Updater<T | null>) => setAndStore(updater(get({ subscribe })))
}
}
157 changes: 157 additions & 0 deletions src/lib/utils/localstorage-writable.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { localStorageWritable } from './localstorage-writable'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { get } from 'svelte/store'

const mockedBrowser = vi.hoisted(() => {
return vi.fn()
})

vi.mock('$app/environment', () => {
return {
get browser() {
return mockedBrowser()
}
}
})

const localStorageMockFactory = () => {
const store: Record<string, string> = {}

return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => {
store[key] = value
},
removeItem: (key: string) => {
delete store[key]
}
}
}

describe('localStorageWritable', () => {
beforeEach(() => {
mockedBrowser.mockReturnValue(true)
vi.stubGlobal('localStorage', localStorageMockFactory())
})

afterEach(() => {
vi.resetAllMocks()
})

it('should initialize with default value if no value in localStorage', () => {
const defaultValue = 'default'

const store = localStorageWritable('testKey', defaultValue)

expect(get(store)).toBe(defaultValue)
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(defaultValue))
})

it('should initialize with value from localStorage if present', () => {
localStorage.setItem('testKey', JSON.stringify('storedValue'))

const store = localStorageWritable('testKey')

expect(get(store)).toBe('storedValue')
})

it('should prioritize value from local storage over default', () => {
localStorage.setItem('testKey', JSON.stringify('storedValue'))

const store = localStorageWritable('testKey', 'defaultValue')

expect(get(store)).toBe('storedValue')
expect(localStorage.getItem('testKey')).toBe(JSON.stringify('storedValue'))
})

it('should store value in localStorage when set', () => {
const store = localStorageWritable('testKey')
store.set('newValue')

expect(localStorage.getItem('testKey')).toBe(JSON.stringify('newValue'))
expect(get(store)).toBe('newValue')
})

it('should remove value from localStorage when wipe is called', () => {
localStorage.setItem('testKey', JSON.stringify('storedValue'))

const store = localStorageWritable('testKey')
store.wipe()

expect(localStorage.getItem('testKey')).toBe(null)
expect(get(store)).toBe(null)
})

it('should update the value correctly using update method', () => {
const store = localStorageWritable<number>('testKey', 1)
store.update((n) => n! + 1)

expect(localStorage.getItem('testKey')).toBe(JSON.stringify(2))
expect(get(store)).toBe(2)
})

it('should initialize with default value if non-valid JSON is present in localStorage', () => {
localStorage.setItem('testKey', 'invalid-json')

const defaultValue = 'default'
const store = localStorageWritable('testKey', defaultValue)

expect(get(store)).toBe(defaultValue)
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(defaultValue))
})

it('should initialize with null if no default value and non-valid JSON is present in localStorage', () => {
localStorage.setItem('testKey', 'invalid-json')

const store = localStorageWritable('testKey')

expect(get(store)).toBe(null)
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(null))
})
})

describe('localStorageWritable with no browser', () => {
beforeEach(() => {
mockedBrowser.mockReturnValue(false)
vi.stubGlobal('localStorage', undefined)
})

afterEach(() => {
vi.resetAllMocks()
})

it('should initialize with default value', () => {
const defaultValue = 'default'
const store = localStorageWritable('testKey', defaultValue)

expect(get(store)).toBe(defaultValue)
})

it('should initialize with null', () => {
const store = localStorageWritable('testKey')

expect(get(store)).toBe(null)
})

it('should set value', () => {
const store = localStorageWritable('testKey')
store.set('newValue')

expect(get(store)).toBe('newValue')
})

it('should remove value', () => {
const store = localStorageWritable('testKey')
store.set('newValue')
store.wipe()

expect(get(store)).toBe(null)
})

it('should update the value correctly using update method', () => {
const store = localStorageWritable<number>('testKey', 1)
store.update((n) => n! + 1)

expect(get(store)).toBe(2)
})
})