|
| 1 | +/** |
| 2 | + * Code from https://github.com/developit/linkstate/blob/f744563a7f7eaf5e9c3126403492474cbdb68027/src/index.js |
| 3 | + * Unmodified from the original |
| 4 | + * |
| 5 | + * Copyright (c) 2017 Jason Miller under the MIT License (MIT) |
| 6 | + * |
| 7 | + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: |
| 8 | + * |
| 9 | + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. |
| 10 | + * |
| 11 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 12 | + */ |
| 13 | + |
| 14 | +import delve from 'dlv'; |
| 15 | + |
| 16 | +/** @typedef {import('preact').AnyComponent} Component */ |
| 17 | + |
| 18 | +/** Create an Event handler function that sets a given state property. |
| 19 | + * @param {Component} component The component whose state should be updated |
| 20 | + * @param {string} key A dot-notated key path to update in the component's state |
| 21 | + * @param {string} eventPath A dot-notated key path to the value that should be retrieved from the Event or component |
| 22 | + * @returns {function} linkedStateHandler |
| 23 | + */ |
| 24 | +export default function linkState(component, key, eventPath) { |
| 25 | + let path = key.split('.'), |
| 26 | + cache = component.__lsc || (component.__lsc = {}); |
| 27 | + |
| 28 | + return cache[key+eventPath] || (cache[key+eventPath] = function(e) { |
| 29 | + let t = e && e.target || this, |
| 30 | + state = {}, |
| 31 | + obj = state, |
| 32 | + v = typeof eventPath==='string' ? delve(e, eventPath) : (t && t.nodeName) ? (t.type.match(/^che|rad/) ? t.checked : t.value) : e, |
| 33 | + i = 0; |
| 34 | + for ( ; i<path.length-1; i++) { |
| 35 | + obj = obj[path[i]] || (obj[path[i]] = !i && component.state[path[i]] || {}); |
| 36 | + } |
| 37 | + obj[path[i]] = v; |
| 38 | + component.setState(state); |
| 39 | + }); |
| 40 | +} |
0 commit comments