npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

synced-web-settings

v1.1.0

Published

Tiny package to make syncing settings with browser storage easier.

Downloads

7

Readme

synced-web-settings

Tiny package to make syncing settings with browser storage easier.

Overview

Instead of this:

// getting value
let someString = localStorage.getItem("setting:someString");

// setting value
someString = "new value!";
localStorage.setItem("setting:someString", someString);

Do this:

// getting value
repo.settings.someString;

// setting value
repo.settings.someString = "new value!"; 

Supported types include: string, boolean, number, bigint, any objects compatible with JSON.parse()/JSON.stringify(), and any other objects you want (as long as you write a custom serializer).

You can also subscribe to setting updates:

// the subscribe() function knows what your settings are for type safety
repo.subscriptions.subscribe("someBool", (value) => {
  doStuffWithBoolean(value);
});

When setting up a repo, you can choose between localStorage, sessionStorage, or any other storage container that implements the Storage type.

Advantages over using storage directly:

  • ✅ Easier to read & write
  • ✅ No manual type conversion
  • ✅ Intellisense & type safety for setting names & values
  • ✅ Default values when not present in storage container
  • ✅ Callbacks/subscriptions when settings change

Usage

Creating a Settings Repository

Create a SettingsRespository and define your settings:

import { SettingsRespository, StoredBoolean } from "synced-web-settings";

const repo = new SettingsRespository({
  prefix: "setting:", // optional; gets appended to setting name for key
  storage: localStorage, // can be anything that implements Storage
  settings: {
    someBoolean: { // name can be whatever you want
      type: StoredBoolean, // reference to class that handles proxying
      defaultValue: false, // value to use when setting not yet set
      callbacks: [ // these all get called when the setting changes
        (value) => doStuffWithBoolean(value),
      ]
    },
    // add as many settings as you'd like
  }
});

Settings can use any subclass of StoredSetting. There are 5 predefined implementations you can use:

  • StoredBoolean
  • StoredNumber
  • StoredBigint
  • StoredString
  • StoredJson

Note that StoredJson is only compatible with objects that can work with JSON.parse() and JSON.stringify(), which means objects with circular references or containing bigints are not allowed. For more complex data types such as these, you can create your own implementation of StoredSetting, like:

class StoredThing extends StoredSetting<YourType> {
  constructor(
    defaultValue: YourType,
    callbacks?: readonly OnChangeCallback<YourType>[]
  ) {
    super(defaultValue, callbacks);
  }

  protected _decode(value: string): YourType {
    // parse string as a YourType
  }

  protected _encode(value: YourType): string {
    // convert YourType to a string
  }
}

Getting Your Settings Type

There is no need to write an interface for your settings and use it as a generic in the SettingsRespository constructor. There is some TypeScript magic going on behind the scenes so you can simply do this:

const repo = new SettingsRespository({
  storage: localStorage,
  settings: {
    someBoolean: {
      type: StoredBoolean,
      defaultValue: false
    },
    someNumber: {
      type: StoredNumber,
      defaultValue: 0
    },
  }
});

type MyWebsiteSettings = typeof repo.settings;

/*
  Equivalent to:

  interface MyWebsiteSettings {
    someBoolean: boolean;
    someNumber: number;
  }
*/

Using Settings

Using settings is as simple as using an object, because that's literally all it is. Just get, set, and delete properties as you would on a normal object, and they will instantly sync with the storage container you chose.

const someBool = repo.settings.someBool; // reads from storage
repo.settings.someBool = true; // writes "true" to storage
delete repo.settings.someBool; // removes someBool setting from storage

Subscribe to Setting Updates

To receive updates when a setting has changed, create a subscription:

// the subscribe() function knows what your settings are for type safety, and
// returns a function that will cancel the subscription when called
const unsub = repo.subscriptions.subscribe("someBool", (value) => {
  doStuffWithBoolean(value);
});

// when you're ready to terminate the subscription, call unsub()
unsub();

As shorthand for multiple subscriptions that are related, use a batch:

const unsub = repo.subscriptions.batchSubscribe(
  someBool: (value) => {
    // do stuff with the boolean
  },
  someNum: (value) => {
    // do stuff with the number
  }
);

// unsubscribes all of the above at once
unsub();