UNPKG

svelte-radio

Version:

Declarative Radio button group component for Svelte

960 lines (905 loc) 28.3 kB
function noop() { } function assign(tar, src) { // @ts-ignore for (const k in src) tar[k] = src[k]; return tar; } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === 'function'; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } function is_empty(obj) { return Object.keys(obj).length === 0; } function subscribe(store, ...callbacks) { if (store == null) { return noop; } const unsub = store.subscribe(...callbacks); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } function component_subscribe(component, store, callback) { component.$$.on_destroy.push(subscribe(store, callback)); } function create_slot(definition, ctx, $$scope, fn) { if (definition) { const slot_ctx = get_slot_context(definition, ctx, $$scope, fn); return definition[0](slot_ctx); } } function get_slot_context(definition, ctx, $$scope, fn) { return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx; } function get_slot_changes(definition, $$scope, dirty, fn) { if (definition[2] && fn) { const lets = definition[2](fn(dirty)); if ($$scope.dirty === undefined) { return lets; } if (typeof lets === 'object') { const merged = []; const len = Math.max($$scope.dirty.length, lets.length); for (let i = 0; i < len; i += 1) { merged[i] = $$scope.dirty[i] | lets[i]; } return merged; } return $$scope.dirty | lets; } return $$scope.dirty; } function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) { if (slot_changes) { const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); slot.p(slot_context, slot_changes); } } function get_all_dirty_from_scope($$scope) { if ($$scope.ctx.length > 32) { const dirty = []; const length = $$scope.ctx.length / 32; for (let i = 0; i < length; i++) { dirty[i] = -1; } return dirty; } return -1; } function exclude_internal_props(props) { const result = {}; for (const k in props) if (k[0] !== '$') result[k] = props[k]; return result; } function compute_rest_props(props, keys) { const rest = {}; keys = new Set(keys); for (const k in props) if (!keys.has(k) && k[0] !== '$') rest[k] = props[k]; return rest; } function append(target, node) { target.appendChild(node); } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { node.parentNode.removeChild(node); } function element(name) { return document.createElement(name); } function text(data) { return document.createTextNode(data); } function space() { return text(' '); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value); } function set_attributes(node, attributes) { // @ts-ignore const descriptors = Object.getOwnPropertyDescriptors(node.__proto__); for (const key in attributes) { if (attributes[key] == null) { node.removeAttribute(key); } else if (key === 'style') { node.style.cssText = attributes[key]; } else if (key === '__value') { node.value = node[key] = attributes[key]; } else if (descriptors[key] && descriptors[key].set) { node[key] = attributes[key]; } else { attr(node, key, attributes[key]); } } } function children(element) { return Array.from(element.childNodes); } function set_data(text, data) { data = '' + data; if (text.wholeText !== data) text.data = data; } function toggle_class(element, name, toggle) { element.classList[toggle ? 'add' : 'remove'](name); } function custom_event(type, detail, bubbles = false) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, bubbles, false, detail); return e; } let current_component; function set_current_component(component) { current_component = component; } function get_current_component() { if (!current_component) throw new Error('Function called outside component initialization'); return current_component; } function onMount(fn) { get_current_component().$$.on_mount.push(fn); } function afterUpdate(fn) { get_current_component().$$.after_update.push(fn); } function onDestroy(fn) { get_current_component().$$.on_destroy.push(fn); } function createEventDispatcher() { const component = get_current_component(); return (type, detail) => { const callbacks = component.$$.callbacks[type]; if (callbacks) { // TODO are there situations where events could be dispatched // in a server (non-DOM) environment? const event = custom_event(type, detail); callbacks.slice().forEach(fn => { fn.call(component, event); }); } }; } function setContext(key, context) { get_current_component().$$.context.set(key, context); } function getContext(key) { return get_current_component().$$.context.get(key); } // TODO figure out if we still want to support // shorthand events, or if we want to implement // a real bubbling mechanism function bubble(component, event) { const callbacks = component.$$.callbacks[event.type]; if (callbacks) { // @ts-ignore callbacks.slice().forEach(fn => fn.call(this, event)); } } const dirty_components = []; const binding_callbacks = []; const render_callbacks = []; const flush_callbacks = []; const resolved_promise = Promise.resolve(); let update_scheduled = false; function schedule_update() { if (!update_scheduled) { update_scheduled = true; resolved_promise.then(flush); } } function tick() { schedule_update(); return resolved_promise; } function add_render_callback(fn) { render_callbacks.push(fn); } // flush() calls callbacks in this order: // 1. All beforeUpdate callbacks, in order: parents before children // 2. All bind:this callbacks, in reverse order: children before parents. // 3. All afterUpdate callbacks, in order: parents before children. EXCEPT // for afterUpdates called during the initial onMount, which are called in // reverse order: children before parents. // Since callbacks might update component values, which could trigger another // call to flush(), the following steps guard against this: // 1. During beforeUpdate, any updated components will be added to the // dirty_components array and will cause a reentrant call to flush(). Because // the flush index is kept outside the function, the reentrant call will pick // up where the earlier call left off and go through all dirty components. The // current_component value is saved and restored so that the reentrant call will // not interfere with the "parent" flush() call. // 2. bind:this callbacks cannot trigger new flush() calls. // 3. During afterUpdate, any updated components will NOT have their afterUpdate // callback called a second time; the seen_callbacks set, outside the flush() // function, guarantees this behavior. const seen_callbacks = new Set(); let flushidx = 0; // Do *not* move this inside the flush() function function flush() { const saved_component = current_component; do { // first, call beforeUpdate functions // and update components while (flushidx < dirty_components.length) { const component = dirty_components[flushidx]; flushidx++; set_current_component(component); update(component.$$); } set_current_component(null); dirty_components.length = 0; flushidx = 0; while (binding_callbacks.length) binding_callbacks.pop()(); // then, once components are updated, call // afterUpdate functions. This may cause // subsequent updates... for (let i = 0; i < render_callbacks.length; i += 1) { const callback = render_callbacks[i]; if (!seen_callbacks.has(callback)) { // ...so guard against infinite loops seen_callbacks.add(callback); callback(); } } render_callbacks.length = 0; } while (dirty_components.length); while (flush_callbacks.length) { flush_callbacks.pop()(); } update_scheduled = false; seen_callbacks.clear(); set_current_component(saved_component); } function update($$) { if ($$.fragment !== null) { $$.update(); run_all($$.before_update); const dirty = $$.dirty; $$.dirty = [-1]; $$.fragment && $$.fragment.p($$.ctx, dirty); $$.after_update.forEach(add_render_callback); } } const outroing = new Set(); let outros; function transition_in(block, local) { if (block && block.i) { outroing.delete(block); block.i(local); } } function transition_out(block, local, detach, callback) { if (block && block.o) { if (outroing.has(block)) return; outroing.add(block); outros.c.push(() => { outroing.delete(block); if (callback) { if (detach) block.d(1); callback(); } }); block.o(local); } } function get_spread_update(levels, updates) { const update = {}; const to_null_out = {}; const accounted_for = { $$scope: 1 }; let i = levels.length; while (i--) { const o = levels[i]; const n = updates[i]; if (n) { for (const key in o) { if (!(key in n)) to_null_out[key] = 1; } for (const key in n) { if (!accounted_for[key]) { update[key] = n[key]; accounted_for[key] = 1; } } levels[i] = n; } else { for (const key in o) { accounted_for[key] = 1; } } } for (const key in to_null_out) { if (!(key in update)) update[key] = undefined; } return update; } function mount_component(component, target, anchor, customElement) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment && fragment.m(target, anchor); if (!customElement) { // onMount happens before the initial afterUpdate add_render_callback(() => { const new_on_destroy = on_mount.map(run).filter(is_function); if (on_destroy) { on_destroy.push(...new_on_destroy); } else { // Edge case - component was destroyed immediately, // most likely as a result of a binding initialising run_all(new_on_destroy); } component.$$.on_mount = []; }); } after_update.forEach(add_render_callback); } function destroy_component(component, detaching) { const $$ = component.$$; if ($$.fragment !== null) { run_all($$.on_destroy); $$.fragment && $$.fragment.d(detaching); // TODO null out other refs, including component.$$ (but need to // preserve final state?) $$.on_destroy = $$.fragment = null; $$.ctx = []; } } function make_dirty(component, i) { if (component.$$.dirty[0] === -1) { dirty_components.push(component); schedule_update(); component.$$.dirty.fill(0); } component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); } function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) { const parent_component = current_component; set_current_component(component); const $$ = component.$$ = { fragment: null, ctx: null, // state props, update: noop, not_equal, bound: blank_object(), // lifecycle on_mount: [], on_destroy: [], on_disconnect: [], before_update: [], after_update: [], context: new Map(options.context || (parent_component ? parent_component.$$.context : [])), // everything else callbacks: blank_object(), dirty, skip_bound: false, root: options.target || parent_component.$$.root }; append_styles && append_styles($$.root); let ready = false; $$.ctx = instance ? instance(component, options.props || {}, (i, ret, ...rest) => { const value = rest.length ? rest[0] : ret; if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { if (!$$.skip_bound && $$.bound[i]) $$.bound[i](value); if (ready) make_dirty(component, i); } return ret; }) : []; $$.update(); ready = true; run_all($$.before_update); // `false` as a special case of no DOM component $$.fragment = create_fragment ? create_fragment($$.ctx) : false; if (options.target) { if (options.hydrate) { const nodes = children(options.target); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment && $$.fragment.l(nodes); nodes.forEach(detach); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment && $$.fragment.c(); } if (options.intro) transition_in(component.$$.fragment); mount_component(component, options.target, options.anchor, options.customElement); flush(); } set_current_component(parent_component); } /** * Base class for Svelte components. Used when dev=false. */ class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } } /* src/Radio.svelte generated by Svelte v3.44.3 */ function create_fragment$1(ctx) { let div; let input; let t0; let label_1; let t1; let mounted; let dispose; let input_levels = [ /*$$restProps*/ ctx[4], { type: "radio" }, { id: /*id*/ ctx[1] }, { value: /*value*/ ctx[2] }, { checked: /*checked*/ ctx[0] } ]; let input_data = {}; for (let i = 0; i < input_levels.length; i += 1) { input_data = assign(input_data, input_levels[i]); } return { c() { div = element("div"); input = element("input"); t0 = space(); label_1 = element("label"); t1 = text(/*label*/ ctx[3]); set_attributes(input, input_data); attr(label_1, "for", /*id*/ ctx[1]); toggle_class(div, "svelte-radio", true); }, m(target, anchor) { insert(target, div, anchor); append(div, input); if (input.autofocus) input.focus(); append(div, t0); append(div, label_1); append(label_1, t1); if (!mounted) { dispose = [ listen(input, "focus", /*focus_handler*/ ctx[5]), listen(input, "blur", /*blur_handler*/ ctx[6]), listen(input, "change", /*change_handler*/ ctx[7]), listen(input, "change", /*change_handler_1*/ ctx[9]), listen(input, "keydown", /*keydown_handler*/ ctx[8]) ]; mounted = true; } }, p(ctx, [dirty]) { set_attributes(input, input_data = get_spread_update(input_levels, [ dirty & /*$$restProps*/ 16 && /*$$restProps*/ ctx[4], { type: "radio" }, dirty & /*id*/ 2 && { id: /*id*/ ctx[1] }, dirty & /*value*/ 4 && { value: /*value*/ ctx[2] }, dirty & /*checked*/ 1 && { checked: /*checked*/ ctx[0] } ])); if (dirty & /*label*/ 8) set_data(t1, /*label*/ ctx[3]); if (dirty & /*id*/ 2) { attr(label_1, "for", /*id*/ ctx[1]); } }, i: noop, o: noop, d(detaching) { if (detaching) detach(div); mounted = false; run_all(dispose); } }; } function instance$1($$self, $$props, $$invalidate) { const omit_props_names = ["id","value","label","checked"]; let $$restProps = compute_rest_props($$props, omit_props_names); let { id = "radio-" + Math.random().toString(36) } = $$props; let { value = "" } = $$props; let { label = "Radio button label" } = $$props; let { checked = false } = $$props; const ctx = getContext("RadioGroup"); let unsubscribe = undefined; onDestroy(() => { if (ctx) ctx.remove({ id }); if (unsubscribe) unsubscribe(); }); function focus_handler(event) { bubble.call(this, $$self, event); } function blur_handler(event) { bubble.call(this, $$self, event); } function change_handler(event) { bubble.call(this, $$self, event); } function keydown_handler(event) { bubble.call(this, $$self, event); } const change_handler_1 = ({ target }) => { $$invalidate(0, checked = target.checked); }; $$self.$$set = $$new_props => { $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)); $$invalidate(4, $$restProps = compute_rest_props($$props, omit_props_names)); if ('id' in $$new_props) $$invalidate(1, id = $$new_props.id); if ('value' in $$new_props) $$invalidate(2, value = $$new_props.value); if ('label' in $$new_props) $$invalidate(3, label = $$new_props.label); if ('checked' in $$new_props) $$invalidate(0, checked = $$new_props.checked); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*id, value, label, checked*/ 15) { if (ctx !== undefined) { ctx.add({ id, value, label, checked }); if (checked) ctx.toggle({ id }); unsubscribe = ctx.items.subscribe(value => { if (value[id] !== undefined) { $$invalidate(0, checked = value[id].checked); } }); } } }; return [ checked, id, value, label, $$restProps, focus_handler, blur_handler, change_handler, keydown_handler, change_handler_1 ]; } class Radio extends SvelteComponent { constructor(options) { super(); init(this, options, instance$1, create_fragment$1, safe_not_equal, { id: 1, value: 2, label: 3, checked: 0 }); } } var Radio$1 = Radio; const subscriber_queue = []; /** * Creates a `Readable` store that allows reading by subscription. * @param value initial value * @param {StartStopNotifier}start start and stop notifications for subscriptions */ function readable(value, start) { return { subscribe: writable(value, start).subscribe }; } /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ function writable(value, start = noop) { let stop; const subscribers = new Set(); function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (const subscriber of subscribers) { subscriber[1](); subscriber_queue.push(subscriber, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = noop) { const subscriber = [run, invalidate]; subscribers.add(subscriber); if (subscribers.size === 1) { stop = start(set) || noop; } run(value); return () => { subscribers.delete(subscriber); if (subscribers.size === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } function derived(stores, fn, initial_value) { const single = !Array.isArray(stores); const stores_array = single ? [stores] : stores; const auto = fn.length < 2; return readable(initial_value, (set) => { let inited = false; const values = []; let pending = 0; let cleanup = noop; const sync = () => { if (pending) { return; } cleanup(); const result = fn(single ? values[0] : values, set); if (auto) { set(result); } else { cleanup = is_function(result) ? result : noop; } }; const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => { values[i] = value; pending &= ~(1 << i); if (inited) { sync(); } }, () => { pending |= (1 << i); })); inited = true; sync(); return function stop() { run_all(unsubscribers); cleanup(); }; }); } /* src/RadioGroup.svelte generated by Svelte v3.44.3 */ const get_legend_slot_changes = dirty => ({}); const get_legend_slot_context = ctx => ({}); // (89:22) function fallback_block(ctx) { let legend_1; let t; return { c() { legend_1 = element("legend"); t = text(/*legend*/ ctx[0]); }, m(target, anchor) { insert(target, legend_1, anchor); append(legend_1, t); }, p(ctx, dirty) { if (dirty & /*legend*/ 1) set_data(t, /*legend*/ ctx[0]); }, d(detaching) { if (detaching) detach(legend_1); } }; } function create_fragment(ctx) { let fieldset; let t; let current; const legend_slot_template = /*#slots*/ ctx[7].legend; const legend_slot = create_slot(legend_slot_template, ctx, /*$$scope*/ ctx[6], get_legend_slot_context); const legend_slot_or_fallback = legend_slot || fallback_block(ctx); const default_slot_template = /*#slots*/ ctx[7].default; const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[6], null); let fieldset_levels = [/*$$restProps*/ ctx[4]]; let fieldset_data = {}; for (let i = 0; i < fieldset_levels.length; i += 1) { fieldset_data = assign(fieldset_data, fieldset_levels[i]); } return { c() { fieldset = element("fieldset"); if (legend_slot_or_fallback) legend_slot_or_fallback.c(); t = space(); if (default_slot) default_slot.c(); set_attributes(fieldset, fieldset_data); toggle_class(fieldset, "svelte-radio-group", true); }, m(target, anchor) { insert(target, fieldset, anchor); if (legend_slot_or_fallback) { legend_slot_or_fallback.m(fieldset, null); } append(fieldset, t); if (default_slot) { default_slot.m(fieldset, null); } current = true; }, p(ctx, [dirty]) { if (legend_slot) { if (legend_slot.p && (!current || dirty & /*$$scope*/ 64)) { update_slot_base( legend_slot, legend_slot_template, ctx, /*$$scope*/ ctx[6], !current ? get_all_dirty_from_scope(/*$$scope*/ ctx[6]) : get_slot_changes(legend_slot_template, /*$$scope*/ ctx[6], dirty, get_legend_slot_changes), get_legend_slot_context ); } } else { if (legend_slot_or_fallback && legend_slot_or_fallback.p && (!current || dirty & /*legend*/ 1)) { legend_slot_or_fallback.p(ctx, !current ? -1 : dirty); } } if (default_slot) { if (default_slot.p && (!current || dirty & /*$$scope*/ 64)) { update_slot_base( default_slot, default_slot_template, ctx, /*$$scope*/ ctx[6], !current ? get_all_dirty_from_scope(/*$$scope*/ ctx[6]) : get_slot_changes(default_slot_template, /*$$scope*/ ctx[6], dirty, null), null ); } } set_attributes(fieldset, fieldset_data = get_spread_update(fieldset_levels, [dirty & /*$$restProps*/ 16 && /*$$restProps*/ ctx[4]])); toggle_class(fieldset, "svelte-radio-group", true); }, i(local) { if (current) return; transition_in(legend_slot_or_fallback, local); transition_in(default_slot, local); current = true; }, o(local) { transition_out(legend_slot_or_fallback, local); transition_out(default_slot, local); current = false; }, d(detaching) { if (detaching) detach(fieldset); if (legend_slot_or_fallback) legend_slot_or_fallback.d(detaching); if (default_slot) default_slot.d(detaching); } }; } function instance($$self, $$props, $$invalidate) { const omit_props_names = ["legend","value"]; let $$restProps = compute_rest_props($$props, omit_props_names); let $state; let $flat; let $items; let { $$slots: slots = {}, $$scope } = $$props; let { legend = "Radio group legend" } = $$props; let { value = undefined } = $$props; const dispatch = createEventDispatcher(); const items = writable({}); component_subscribe($$self, items, value => $$invalidate(12, $items = value)); const flat = derived(items, _ => Object.values(_)); component_subscribe($$self, flat, value => $$invalidate(11, $flat = value)); const state = derived(flat, _ => _.map(({ checked }) => checked).join("")); component_subscribe($$self, state, value => $$invalidate(10, $state = value)); let prevState = undefined; let prevValue = value; function updateValues(item) { items.update(_ => { Object.keys(_).forEach(id => { _[id].checked = id === item.id; }); return _; }); } setContext("RadioGroup", { items, add: item => { items.update(_ => ({ ..._, [item.id]: item })); }, toggle: updateValues, remove: item => { items.update(_ => { delete _[item.id]; return _; }); } }); onMount(() => { if ($flat.filter(({ checked }) => checked).length === 0) { const item = $flat.filter(_ => _.value === value)[0] || $flat[0]; items.update(_ => { _[item.id].checked = true; return _; }); } }); afterUpdate(async () => { if (value !== prevValue) { prevValue = value; const selected = Object.values($items).filter(_ => _.value === value)[0]; if (selected !== undefined) updateValues(selected); } await tick(); if (prevState !== undefined && $state !== prevState) { const selected = $flat.filter(({ checked }) => checked)[0]; $$invalidate(5, value = selected.value); dispatch("change", { selected: { ...selected } }); } prevState = $state; }); $$self.$$set = $$new_props => { $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)); $$invalidate(4, $$restProps = compute_rest_props($$props, omit_props_names)); if ('legend' in $$new_props) $$invalidate(0, legend = $$new_props.legend); if ('value' in $$new_props) $$invalidate(5, value = $$new_props.value); if ('$$scope' in $$new_props) $$invalidate(6, $$scope = $$new_props.$$scope); }; return [legend, items, flat, state, $$restProps, value, $$scope, slots]; } class RadioGroup extends SvelteComponent { constructor(options) { super(); init(this, options, instance, create_fragment, safe_not_equal, { legend: 0, value: 5 }); } } var RadioGroup$1 = RadioGroup; export { Radio$1 as Radio, RadioGroup$1 as RadioGroup };