patch-settings

1.1.2 • Public • Published

Patch-settings

A module for managing settings in patch-* family apps. Settings are persisted to localStorage, and a couple of little methods are provided for gettings, settings, and observing!

You'll need to understand depject (a module for a different way of managing dependency injection), and for hte example below, depnest - a lazy way to write nested objects quickly.

Example

const nest = require('depject')
const { h } = require('mutant')
 
exports.gives = nest('app.page.settings')
 
exports.needs = nest({
  'settings.sync.get': 'first',
  'settings.sync.set': 'first'
}
 
exports.gives = (api) => {
  return nest('app.page.settings', settingsPage)
 
  function settingsPage (opts) => {
 
    const languages = [ 'en', 'es', 'de', 'zh' ]
    
    return h('div.page', [
      'Current language:',
      h('pre', api.settings.sync.get('language')),
 
      'Set your language:',
      languages.map( lang => {
        const setLang = () => api.settings.sync.set({ language: lang })
        return h('button', {'ev-click': setLang}, lang)
      })
 
    ])
 
  }
}

API

settings.sync.get

Called with no arguments, returns the whole settings object.

(path=string, fallback=anyValue)

Uses lodash/get pattern.

Example:

// settings = {
//   language: 'de',
//   colors {
//     primary: 'cyan'
//   }
// }
 
api.settings.sync.get('colors.primary',)
// => 'cyan'
 
api.settings.sync.get('colors.secondary')
// => undefined
 
api.settings.sync.get('colors.secondary', 'white')
// => 'white'

settings.sync.set

(newSettings=object)

Uses lodash.mergewith to recurssively merge newSettings into settings. Note if the value being merged is an Array, this merge is set to overwrite the current value (this is necessary otherwise merging short Arrays in leaves vestigal settings from previous long Arrays).

Example:

api.settings.sync.set({ 
  colors: {
    primary: 'pink',
    secondary: 'teal'
  }
})
// => undefined
 
api.settings.sync.get()
// settings = {
//   language: 'de',
//   colors {
//     primary: 'pink'
//     secondary: 'teal'
//   }
// }

settings.obs.get

(path=string, fallback=anyValue)

Similar to settings.sync.get, but returns a Mutant observeable. This can be given listeners which fire when part / all the state changes, or can be used when building views with Mutant.

You can also call .set(newValue) on the observable and the setting at the specified path will be updated.

const h = require('mutant/h')
const language = api.settings.obs.get('app.language')
 
h('select', {
  value: language,
  'ev-change' => (ev) => lanuage.set(ev.value)
}, [options])

Package Sidebar

Install

npm i patch-settings

Weekly Downloads

2

Version

1.1.2

License

AGPL-3.0

Unpacked Size

5.45 kB

Total Files

3

Last publish

Collaborators

  • dominictarr
  • mixmix
  • mmckegg