@centroculturadigital-mx/svelte-themer
Version:
Styling your Svelte apps with CSS Variables, persisted.
832 lines (749 loc) • 26.1 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Themer = {}));
}(this, (function (exports) { 'use strict';
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 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 append(target, node) {
target.appendChild(node);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
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 children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.data !== data)
text.data = data;
}
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 setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
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 add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
dirty_components.length = 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;
flushing = false;
seen_callbacks.clear();
}
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 mount_component(component, target, anchor) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
// 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, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const prop_values = options.props || {};
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : []),
// everything else
callbacks: blank_object(),
dirty
};
let ready = false;
$$.ctx = instance
? instance(component, prop_values, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if ($$.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);
flush();
}
set_current_component(parent_component);
}
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() {
// overridden by instance, if it has props
}
}
const subscriber_queue = [];
/**
* 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 = [];
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 (let i = 0; i < subscribers.length; i += 1) {
const s = subscribers[i];
s[1]();
subscriber_queue.push(s, 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.push(subscriber);
if (subscribers.length === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
if (subscribers.length === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
const presets = [{
name: 'light',
properties: {
colors: {
text: '#282230',
background: '#f1f1f1',
primary: '#01796f',
primary_dark: '#016159',
secondary: '#562931',
},
fonts: {
families: {
primary: "https://fonts.googleapis.com/css2?family=Open+Sans&display=swap",
secondary: "https://fonts.googleapis.com/css2?family=Oswald&display=swap"
},
primary: "Oswald",
secondary: "Open Sans"
},
},
},
{
name: 'dark',
properties: {
colors: {
text: '#f1f1f1',
background: '#27323a',
primary: '#01978b',
primary_dark: '#00887c',
secondary: '#fe8690',
},
fonts: {
families: {
primary: "https://fonts.googleapis.com/css2?family=Open+Sans&display=swap",
secondary: "https://fonts.googleapis.com/css2?family=Oswald&display=swap"
},
primary: "Oswald",
secondary: "Open Sans"
},
},
},
{
name: 'forest',
properties: {
colors: {
background: '#3b6c4c',
text: '#f9f2cf',
primary: '#efdc7e',
primary_dark: '#e4d589',
secondary: '#4a875f',
},
fonts: {
families: {
primary: "https://fonts.googleapis.com/css2?family=Open+Sans&display=swap",
secondary: "https://fonts.googleapis.com/css2?family=Oswald&display=swap"
},
primary: "Oswald",
secondary: "Open Sans"
},
},
},
{
name: 'discord',
properties: {
colors: {
background: '#2C2F33',
text: '#FFFFFF',
primary: '#7289DA',
primary_dark: '#7289DA',
secondary: '#99AAB5',
},
fonts: {
families: {
primary: "https://fonts.googleapis.com/css2?family=Open+Sans&display=swap",
secondary: "https://fonts.googleapis.com/css2?family=Oswald&display=swap"
},
primary: "Oswald",
secondary: "Open Sans"
},
},
},
];
const getRootProperties = (object, prefix) => {
let properties = [];
let varString;
if (!prefix) {
prefix = `--theme`;
}
varString = prefix;
for (let [key, value] of Object.entries(object)) {
varString = `${varString}-${key}`;
if (typeof value === "object") {
properties = [...properties, ...getRootProperties(value, varString)];
} else {
properties.push([
varString, value
]);
}
varString = prefix;
}
return properties
};
const setRootProperties = (properties) => {
for (const property of properties) {
document.documentElement.style.setProperty(property[0], property[1]);
}
return
};
const setRootTypographies = (families) => {
return families;
};
const rootProperties = {
getRootProperties,
setRootProperties,
setRootTypographies
};
var rootProperties_1 = rootProperties;
/* src/ThemeWrapper.svelte generated by Svelte v3.22.2 */
function add_css() {
var style = element("style");
style.id = "svelte-1ccq932-style";
style.textContent = "html{background-color:var(--theme-colors-background);color:var(--theme-colors-text)}";
append(document.head, style);
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[13] = list[i];
child_ctx[15] = i;
return child_ctx;
}
// (111:2) {#each Object.values(links) as link, i}
function create_each_block(ctx) {
let link;
let link_href_value;
return {
c() {
link = element("link");
attr(link, "href", link_href_value = /*link*/ ctx[13]);
attr(link, "rel", "stylesheet");
attr(link, "type", "text/css");
},
m(target, anchor) {
insert(target, link, anchor);
},
p(ctx, dirty) {
if (dirty & /*links*/ 1 && link_href_value !== (link_href_value = /*link*/ ctx[13])) {
attr(link, "href", link_href_value);
}
},
d(detaching) {
if (detaching) detach(link);
}
};
}
function create_fragment(ctx) {
let each_1_anchor;
let t;
let current;
let each_value = Object.values(/*links*/ ctx[0]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
const default_slot_template = /*$$slots*/ ctx[12].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[11], null);
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
t = space();
if (default_slot) default_slot.c();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(document.head, null);
}
append(document.head, each_1_anchor);
insert(target, t, anchor);
if (default_slot) {
default_slot.m(target, anchor);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*Object, links*/ 1) {
each_value = Object.values(/*links*/ ctx[0]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (default_slot) {
if (default_slot.p && dirty & /*$$scope*/ 2048) {
default_slot.p(get_slot_context(default_slot_template, ctx, /*$$scope*/ ctx[11], null), get_slot_changes(default_slot_template, /*$$scope*/ ctx[11], dirty, null));
}
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
destroy_each(each_blocks, detaching);
detach(each_1_anchor);
if (detaching) detach(t);
if (default_slot) default_slot.d(detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { themes = [...presets] } = $$props;
let { storageKey = "__svelte-themer__theme" } = $$props;
const { getRootProperties, setRootProperties, setRootTypographies } = rootProperties_1;
// internal state, useful for quickly setting CSS vars without subscribing
let _current = themes[0].name;
// temporary
let _storage = {
// name of choice
n: themes[0].name
};
let { base = {
properties: { colors: { text: "#282230" } },
prefix: "base"
} } = $$props;
// utility to get current theme from name
const getCurrentTheme = name => themes.find(h => h.name === name);
// set up writeable store
let Theme = writable(getCurrentTheme(_current));
setContext("theme", {
theme: Theme,
toggle: () => {
// update internal state
let _currentIndex = themes.findIndex(h => h.name === _current);
_current = themes[_currentIndex === themes.length - 1
? 0
: _currentIndex += 1].name;
// update Theme store
Theme.update(t => ({ ...t, ...getCurrentTheme(_current) }));
// updatte cached theme choice
localStorage.setItem(storageKey, _current);
// update CSS vars
const properties = getRootProperties(getCurrentTheme(_current).properties);
setRootProperties(properties);
//
let typographies = getCurrentTheme(_current).fontFamilies;
$$invalidate(0, links = setRootTypographies(typographies));
}
});
let links = [];
onMount(() => {
let storedThemeChoice = localStorage.getItem(storageKey);
if (storedThemeChoice) {
// update Theme store with cached theme choice
if (!getCurrentTheme(storedThemeChoice)) ; else {
if (isNaN(parseInt(storedThemeChoice)) && getCurrentTheme(storedThemeChoice)) {
Theme.set(getCurrentTheme(storedThemeChoice)); // break
_current = storedThemeChoice;
}
}
} else {
// set default internal state if cached choice does not exist
localStorage.setItem(storageKey, _current);
}
// set CSS vars on mount
// setRootProperties(base)
const properties = getRootProperties(getCurrentTheme(_current).properties);
setRootProperties(properties);
//
const typographies = getCurrentTheme(_current).fontFamilies;
$$invalidate(0, links = setRootTypographies(typographies));
});
let { $$slots = {}, $$scope } = $$props;
$$self.$set = $$props => {
if ("themes" in $$props) $$invalidate(1, themes = $$props.themes);
if ("storageKey" in $$props) $$invalidate(2, storageKey = $$props.storageKey);
if ("base" in $$props) $$invalidate(3, base = $$props.base);
if ("$$scope" in $$props) $$invalidate(11, $$scope = $$props.$$scope);
};
return [
links,
themes,
storageKey,
base,
_current,
getRootProperties,
setRootProperties,
setRootTypographies,
_storage,
getCurrentTheme,
Theme,
$$scope,
$$slots
];
}
class ThemeWrapper extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1ccq932-style")) add_css();
init(this, options, instance, create_fragment, safe_not_equal, { themes: 1, storageKey: 2, base: 3 });
}
}
/* src/ThemeToggle.svelte generated by Svelte v3.22.2 */
function add_css$1() {
var style = element("style");
style.id = "svelte-13kmwkz-style";
style.textContent = "button.svelte-13kmwkz{border:none;padding:8px 12px;border-radius:3px;background-color:lightgrey;cursor:pointer;min-width:8ch;max-width:15ch;max-height:60px;color:var(--theme-base-text)}";
append(document.head, style);
}
function create_fragment$1(ctx) {
let button;
let t_value = /*$theme*/ ctx[0].name + "";
let t;
let dispose;
return {
c() {
button = element("button");
t = text(t_value);
attr(button, "class", "svelte-13kmwkz");
},
m(target, anchor, remount) {
insert(target, button, anchor);
append(button, t);
if (remount) dispose();
dispose = listen(button, "click", /*toggle*/ ctx[1]);
},
p(ctx, [dirty]) {
if (dirty & /*$theme*/ 1 && t_value !== (t_value = /*$theme*/ ctx[0].name + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(button);
dispose();
}
};
}
function instance$1($$self, $$props, $$invalidate) {
let $theme;
let { toggle, theme } = getContext("theme");
component_subscribe($$self, theme, value => $$invalidate(0, $theme = value));
return [$theme, toggle, theme];
}
class ThemeToggle extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-13kmwkz-style")) add_css$1();
init(this, options, instance$1, create_fragment$1, safe_not_equal, {});
}
}
exports.ThemeToggle = ThemeToggle;
exports.ThemeWrapper = ThemeWrapper;
Object.defineProperty(exports, '__esModule', { value: true });
})));