diff --git a/examples/lit/index.html b/examples/lit/index.html new file mode 100644 index 0000000000..a6998cdec5 --- /dev/null +++ b/examples/lit/index.html @@ -0,0 +1,24 @@ + + + + Lit • TodoMVC + + + + + + + +
+ +
+ + + + + + diff --git a/examples/lit/js/components/App.js b/examples/lit/js/components/App.js new file mode 100644 index 0000000000..e021e2c3fe --- /dev/null +++ b/examples/lit/js/components/App.js @@ -0,0 +1,76 @@ +import { connect } from 'pwa-helpers' +import { LitElement, html, css, unsafeCSS } from 'lit'; +import { when } from 'lit/directives/when.js'; + +import { store, getTodos } from '../store.js' +import './TodoForm.js'; +import './TodoList.js'; +import './Footer.js'; + +import { appCSSRules, baseCSSRules } from '../constant.js' + +export class TodoApp extends connect(store)(LitElement) { + static styles = [ + css`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => unsafeCSS(r)), + ...appCSSRules.map((r) => unsafeCSS(r)) + ] + + static getFilter () { + return location.hash.includes('#/') + ? location.hash.replace('#/', '') + : 'all' + } + + constructor (...args) { + super(...args) + + this.filter = TodoApp.getFilter() + window.addEventListener('hashchange', () => { + this.filter = TodoApp.getFilter() + this.requestUpdate() + }) + } + + stateChanged() { + this.requestUpdate() + } + + get todos () { + return getTodos(this.filter) + } + + get itemsLeft () { + const state = store.getState() + console.log('!!', state.todos); + return this.totalItems - state.completed.length + } + + get totalItems () { + const state = store.getState() + return Object.keys(state.todos).length + } + + render () { + return html` +
+
+

todos

+ +
+
+ +
+ ${when(this.totalItems > 0, () => html` + + + `)} +
+ ` + } +} +customElements.define('todo-app', TodoApp) + diff --git a/examples/lit/js/components/Footer.js b/examples/lit/js/components/Footer.js new file mode 100644 index 0000000000..0bdd5058c5 --- /dev/null +++ b/examples/lit/js/components/Footer.js @@ -0,0 +1,67 @@ +import { html, css, LitElement, unsafeCSS } from 'lit'; +import { classMap } from 'lit/directives/class-map.js'; +import { when } from 'lit/directives/when.js'; + +import { deleteCompleted } from '../store.js' +import { appCSSRules, baseCSSRules } from '../constant.js' + +function filterLink({ text, filter, selectedFilter }) { + return html`${text}`; +} + +export class Footer extends LitElement { + static properties = { + itemsLeft: { type: Number }, + totalItems: { type: Number }, + selectedFilter: { type: String } + } + + static styles = [ + css`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => unsafeCSS(r)), + ...appCSSRules.map((r) => unsafeCSS(r)) + ] + + render () { + return html` + ` + } +} +customElements.define('todo-footer', Footer) diff --git a/examples/lit/js/components/TodoForm.js b/examples/lit/js/components/TodoForm.js new file mode 100644 index 0000000000..eb176e6c26 --- /dev/null +++ b/examples/lit/js/components/TodoForm.js @@ -0,0 +1,36 @@ +import { html, css, LitElement, unsafeCSS } from 'lit' + +import { addTodoByText } from '../store.js' +import { appCSSRules, baseCSSRules } from '../constant.js' + +export class TodoForm extends LitElement { + static styles = [ + css`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => unsafeCSS(r)), + ...appCSSRules.map((r) => unsafeCSS(r)) + ] + + render () { + return html` +
+ +
+ `; + } + + handleSubmit (event) { + event.preventDefault() + if (event.target[0].value.length <= 0) { + return + } + + addTodoByText(event.target[0].value) + event.target[0].value = '' + } +} +customElements.define('todo-form', TodoForm) diff --git a/examples/lit/js/components/TodoItem.js b/examples/lit/js/components/TodoItem.js new file mode 100644 index 0000000000..fd09bd9565 --- /dev/null +++ b/examples/lit/js/components/TodoItem.js @@ -0,0 +1,97 @@ +import { connect } from 'pwa-helpers' +import { html, css, LitElement, unsafeCSS } from 'lit'; +import { classMap } from 'lit/directives/class-map.js'; + +import { store, setEdit, setTodo, toggleTodos, leaveEdit, deleteTodo } from '../store.js' +import { appCSSRules, baseCSSRules } from '../constant.js' + +const ESCAPE_KEY = 27; + +export class TodoItem extends connect(store)(LitElement) { + static properties = { + todo: { type: Object } + } + + static styles = [ + css` + :host(:focus) { box-shadow: none!important; } + .todo-list li:last-child { + border-bottom: 1px solid #ededed!important; + } + `, + ...baseCSSRules.map((r) => unsafeCSS(r)), + ...appCSSRules.map((r) => unsafeCSS(r)) + ] + + get isEditing () { + const state = store.getState() + return this.todo.id === state.editingTodo + } + + stateChanged() { + this.requestUpdate() + } + + beginEdit(event) { + setEdit(this.todo.id) + event.target.closest('li').lastElementChild[0].select() + } + + finishEdit(event) { + event.preventDefault() + + const text = event.target[0].value + setTodo({ ...this.todo, text }) + leaveEdit() + } + + abortEdit(event) { + event.target.value = this.todo.text + leaveEdit() + } + + captureEscape(event) { + if (event.which === ESCAPE_KEY) { + abortEdit(event) + } + } + + render() { + const itemClassList = { + todo: true, + completed: this.todo.completed, + editing: this.isEditing + } + return html` + + ` + } +} +customElements.define('todo-item', TodoItem) diff --git a/examples/lit/js/components/TodoList.js b/examples/lit/js/components/TodoList.js new file mode 100644 index 0000000000..2edf7f4a71 --- /dev/null +++ b/examples/lit/js/components/TodoList.js @@ -0,0 +1,40 @@ +import { html, css, LitElement, unsafeCSS } from "lit"; +import { when } from 'lit/directives/when.js'; +import { appCSSRules, baseCSSRules } from '../constant.js' + +import { markAll } from '../store.js' +import './TodoItem.js'; + +export class TodoList extends LitElement { + static properties = { + todos: { type: Object } + } + + static styles = [ + css`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => unsafeCSS(r)), + ...appCSSRules.map((r) => unsafeCSS(r)) + ] + + render () { + return html` + ${when(Object.keys(this.todos).length > 0, () => html` + + ` + )} + + ` + } +} +customElements.define('todo-list', TodoList) diff --git a/examples/lit/js/constant.js b/examples/lit/js/constant.js new file mode 100644 index 0000000000..2c86c0875b --- /dev/null +++ b/examples/lit/js/constant.js @@ -0,0 +1,13 @@ +const baseStyleSheet = [].slice + .call(document.styleSheets) + .find((file) => file.href && file.href.endsWith('todomvc-common/base.css')) +export const baseCSSRules = [].slice + .call(baseStyleSheet.cssRules) + .map(({ cssText }) => cssText) + +const appStyleSheet = [].slice + .call(document.styleSheets) + .find((file) => file.href && file.href.endsWith('todomvc-app-css/index.css')) +export const appCSSRules = [].slice + .call(appStyleSheet.cssRules) + .map(({ cssText }) => cssText) diff --git a/examples/lit/js/index.js b/examples/lit/js/index.js new file mode 100644 index 0000000000..1391931901 --- /dev/null +++ b/examples/lit/js/index.js @@ -0,0 +1 @@ +import './components/App.js' diff --git a/examples/lit/js/store.js b/examples/lit/js/store.js new file mode 100644 index 0000000000..08ba183810 --- /dev/null +++ b/examples/lit/js/store.js @@ -0,0 +1,122 @@ +import { createSlice, configureStore } from '@reduxjs/toolkit' + +const { actions: todoStoreActions, reducer: todoStoreReducer } = createSlice({ + name: 'todoStore', + initialState: { + todos: {}, + completed: [], + editingTodo: 0 + }, + reducers: { + setTodo: (state, { payload }) => { + state.todos[payload.id] = payload + }, + removeTodos: (state, { payload }) => { + payload.forEach((id) => ( + delete state.todos[id] + )) + }, + appendCompleted: (state, { payload }) => { + console.log('appendCompleted', payload) + state.completed.push(payload) + }, + removeCompleted: (state, { payload }) => { + state.completed.splice( + state.completed.findIndex((id) => id === payload), + 1 + ) + }, + clearCompleted: (state) => { + state.completed = [] + }, + setEdit: (state, { payload }) => { + state.editingTodo = payload + }, + leaveEdit: (state) => { + state.editingTodo = 0 + } + } +}) + +const store = configureStore({ + reducer: todoStoreReducer +}) + +const { + setTodo, removeTodos, appendCompleted, removeCompleted, + clearCompleted, setEdit, leaveEdit +} = todoStoreActions + +export const deleteTodo = (id) => { + store.dispatch(removeCompleted(id)) + store.dispatch(removeTodos([id])) +} + +export const deleteCompleted = () => { + const state = store.getState() + + store.dispatch(removeTodos(state.completed)) + store.dispatch(clearCompleted()) +} + +export const toggleTodos = (items) => { + const state = store.getState() + items.forEach((id) => { + let todo = state.todos[id] + let todoState = !todo.completed; + + todoState + ? store.dispatch(appendCompleted(id)) + : store.dispatch(removeCompleted(id)) + + store.dispatch(setTodo({ ...todo, completed: todoState })) + }) +} + +export const markAll = () => { + let state = store.getState() + let shouldMarkAll = state.completed.length === Object.keys(state.todos).length; + + if (shouldMarkAll) { + const items = Array.from(Object.keys(state.todos)); + return toggleTodos(items) + } + + const filterItems = (acc, item) => + item.completed ? acc : acc.concat(item.id); + + const items = Array.from(Object.values(state.todos)) + .reduce(filterItems, []); + + store.dispatch(toggleTodos(items)) +} + +export const addTodoByText = (text) => { + store.dispatch(setTodo({ + text, + completed: false, + id: Date.now() + })) +} + +export const getTodos = (filter) => { + let { todos } = store.getState() + console.log(11, store.getState()); + return Object.entries(todos).reduce((prev, [id, todo]) => { + if ( + !filter || + filter === 'all' || + (filter === 'active' && !todo.completed) || + (filter === 'completed' && todo.completed) + ) { + prev[id] = todo + return prev + } + + return prev + }, {}) +} + +export { + store, setTodo, appendCompleted, clearCompleted, setEdit, leaveEdit +} diff --git a/examples/lit/node_modules/todomvc-app-css/index.css b/examples/lit/node_modules/todomvc-app-css/index.css new file mode 100644 index 0000000000..d8be205ad4 --- /dev/null +++ b/examples/lit/node_modules/todomvc-app-css/index.css @@ -0,0 +1,376 @@ +html, +body { + margin: 0; + padding: 0; +} + +button { + margin: 0; + padding: 0; + border: 0; + background: none; + font-size: 100%; + vertical-align: baseline; + font-family: inherit; + font-weight: inherit; + color: inherit; + -webkit-appearance: none; + appearance: none; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +body { + font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif; + line-height: 1.4em; + background: #f5f5f5; + color: #4d4d4d; + min-width: 230px; + max-width: 550px; + margin: 0 auto; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + font-weight: 300; +} + +:focus { + outline: 0; +} + +.hidden { + display: none; +} + +.todoapp { + background: #fff; + margin: 130px 0 40px 0; + position: relative; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 25px 50px 0 rgba(0, 0, 0, 0.1); +} + +.todoapp input::-webkit-input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp input::-moz-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp input::input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp h1 { + position: absolute; + top: -155px; + width: 100%; + font-size: 100px; + font-weight: 100; + text-align: center; + color: rgba(175, 47, 47, 0.15); + -webkit-text-rendering: optimizeLegibility; + -moz-text-rendering: optimizeLegibility; + text-rendering: optimizeLegibility; +} + +.new-todo, +.edit { + position: relative; + margin: 0; + width: 100%; + font-size: 24px; + font-family: inherit; + font-weight: inherit; + line-height: 1.4em; + border: 0; + color: inherit; + padding: 6px; + border: 1px solid #999; + box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.new-todo { + padding: 16px 16px 16px 60px; + border: none; + background: rgba(0, 0, 0, 0.003); + box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); +} + +.main { + position: relative; + z-index: 2; + border-top: 1px solid #e6e6e6; +} + +.toggle-all { + text-align: center; + border: none; /* Mobile Safari */ + opacity: 0; + position: absolute; +} + +.toggle-all + label { + width: 60px; + height: 34px; + font-size: 0; + position: absolute; + top: -52px; + left: -13px; + -webkit-transform: rotate(90deg); + transform: rotate(90deg); +} + +.toggle-all + label:before { + content: '❯'; + font-size: 22px; + color: #e6e6e6; + padding: 10px 27px 10px 27px; +} + +.toggle-all:checked + label:before { + color: #737373; +} + +.todo-list { + margin: 0; + padding: 0; + list-style: none; +} + +.todo-list li { + position: relative; + font-size: 24px; + border-bottom: 1px solid #ededed; +} + +.todo-list li:last-child { + border-bottom: none; +} + +.todo-list li.editing { + border-bottom: none; + padding: 0; +} + +.todo-list li.editing .edit { + display: block; + width: 506px; + padding: 12px 16px; + margin: 0 0 0 43px; +} + +.todo-list li.editing .view { + display: none; +} + +.todo-list li .toggle { + text-align: center; + width: 40px; + /* auto, since non-WebKit browsers doesn't support input styling */ + height: auto; + position: absolute; + top: 0; + bottom: 0; + margin: auto 0; + border: none; /* Mobile Safari */ + -webkit-appearance: none; + appearance: none; +} + +.todo-list li .toggle { + opacity: 0; +} + +.todo-list li .toggle + label { + /* + Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433 + IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/ + */ + background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E'); + background-repeat: no-repeat; + background-position: center left; +} + +.todo-list li .toggle:checked + label { + background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E'); +} + +.todo-list li label { + word-break: break-all; + padding: 15px 15px 15px 60px; + display: block; + line-height: 1.2; + transition: color 0.4s; +} + +.todo-list li.completed label { + color: #d9d9d9; + text-decoration: line-through; +} + +.todo-list li .destroy { + display: none; + position: absolute; + top: 0; + right: 10px; + bottom: 0; + width: 40px; + height: 40px; + margin: auto 0; + font-size: 30px; + color: #cc9a9a; + margin-bottom: 11px; + transition: color 0.2s ease-out; +} + +.todo-list li .destroy:hover { + color: #af5b5e; +} + +.todo-list li .destroy:after { + content: '×'; +} + +.todo-list li:hover .destroy { + display: block; +} + +.todo-list li .edit { + display: none; +} + +.todo-list li.editing:last-child { + margin-bottom: -1px; +} + +.footer { + color: #777; + padding: 10px 15px; + height: 20px; + text-align: center; + border-top: 1px solid #e6e6e6; +} + +.footer:before { + content: ''; + position: absolute; + right: 0; + bottom: 0; + left: 0; + height: 50px; + overflow: hidden; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), + 0 8px 0 -3px #f6f6f6, + 0 9px 1px -3px rgba(0, 0, 0, 0.2), + 0 16px 0 -6px #f6f6f6, + 0 17px 2px -6px rgba(0, 0, 0, 0.2); +} + +.todo-count { + float: left; + text-align: left; +} + +.todo-count strong { + font-weight: 300; +} + +.filters { + margin: 0; + padding: 0; + list-style: none; + position: absolute; + right: 0; + left: 0; +} + +.filters li { + display: inline; +} + +.filters li a { + color: inherit; + margin: 3px; + padding: 3px 7px; + text-decoration: none; + border: 1px solid transparent; + border-radius: 3px; +} + +.filters li a:hover { + border-color: rgba(175, 47, 47, 0.1); +} + +.filters li a.selected { + border-color: rgba(175, 47, 47, 0.2); +} + +.clear-completed, +html .clear-completed:active { + float: right; + position: relative; + line-height: 20px; + text-decoration: none; + cursor: pointer; +} + +.clear-completed:hover { + text-decoration: underline; +} + +.info { + margin: 65px auto 0; + color: #bfbfbf; + font-size: 10px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-align: center; +} + +.info p { + line-height: 1; +} + +.info a { + color: inherit; + text-decoration: none; + font-weight: 400; +} + +.info a:hover { + text-decoration: underline; +} + +/* + Hack to remove background from Mobile Safari. + Can't use it globally since it destroys checkboxes in Firefox +*/ +@media screen and (-webkit-min-device-pixel-ratio:0) { + .toggle-all, + .todo-list li .toggle { + background: none; + } + + .todo-list li .toggle { + height: 40px; + } +} + +@media (max-width: 430px) { + .footer { + height: 50px; + } + + .filters { + bottom: 10px; + } +} diff --git a/examples/lit/node_modules/todomvc-common/base.css b/examples/lit/node_modules/todomvc-common/base.css new file mode 100644 index 0000000000..da65968a73 --- /dev/null +++ b/examples/lit/node_modules/todomvc-common/base.css @@ -0,0 +1,141 @@ +hr { + margin: 20px 0; + border: 0; + border-top: 1px dashed #c5c5c5; + border-bottom: 1px dashed #f7f7f7; +} + +.learn a { + font-weight: normal; + text-decoration: none; + color: #b83f45; +} + +.learn a:hover { + text-decoration: underline; + color: #787e7e; +} + +.learn h3, +.learn h4, +.learn h5 { + margin: 10px 0; + font-weight: 500; + line-height: 1.2; + color: #000; +} + +.learn h3 { + font-size: 24px; +} + +.learn h4 { + font-size: 18px; +} + +.learn h5 { + margin-bottom: 0; + font-size: 14px; +} + +.learn ul { + padding: 0; + margin: 0 0 30px 25px; +} + +.learn li { + line-height: 20px; +} + +.learn p { + font-size: 15px; + font-weight: 300; + line-height: 1.3; + margin-top: 0; + margin-bottom: 0; +} + +#issue-count { + display: none; +} + +.quote { + border: none; + margin: 20px 0 60px 0; +} + +.quote p { + font-style: italic; +} + +.quote p:before { + content: '“'; + font-size: 50px; + opacity: .15; + position: absolute; + top: -20px; + left: 3px; +} + +.quote p:after { + content: '”'; + font-size: 50px; + opacity: .15; + position: absolute; + bottom: -42px; + right: 3px; +} + +.quote footer { + position: absolute; + bottom: -40px; + right: 0; +} + +.quote footer img { + border-radius: 3px; +} + +.quote footer a { + margin-left: 5px; + vertical-align: middle; +} + +.speech-bubble { + position: relative; + padding: 10px; + background: rgba(0, 0, 0, .04); + border-radius: 5px; +} + +.speech-bubble:after { + content: ''; + position: absolute; + top: 100%; + right: 30px; + border: 13px solid transparent; + border-top-color: rgba(0, 0, 0, .04); +} + +.learn-bar > .learn { + position: absolute; + width: 272px; + top: 8px; + left: -300px; + padding: 10px; + border-radius: 5px; + background-color: rgba(255, 255, 255, .6); + transition-property: left; + transition-duration: 500ms; +} + +@media (min-width: 899px) { + .learn-bar { + width: auto; + padding-left: 300px; + } + + .learn-bar > .learn { + left: 8px; + } +} diff --git a/examples/lit/node_modules/todomvc-common/base.js b/examples/lit/node_modules/todomvc-common/base.js new file mode 100644 index 0000000000..44fb50c613 --- /dev/null +++ b/examples/lit/node_modules/todomvc-common/base.js @@ -0,0 +1,244 @@ +/* global _ */ +(function () { + 'use strict'; + + /* jshint ignore:start */ + // Underscore's Template Module + // Courtesy of underscorejs.org + var _ = (function (_) { + _.defaults = function (object) { + if (!object) { + return object; + } + for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { + var iterable = arguments[argsIndex]; + if (iterable) { + for (var key in iterable) { + if (object[key] == null) { + object[key] = iterable[key]; + } + } + } + } + return object; + } + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(text, data, settings) { + var render; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = new RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset) + .replace(escaper, function(match) { return '\\' + escapes[match]; }); + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } + if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } + if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + "return __p;\n"; + + try { + render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled function source as a convenience for precompilation. + template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; + + return template; + }; + + return _; + })({}); + + if (location.hostname === 'todomvc.com') { + window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script')); + } + /* jshint ignore:end */ + + function redirect() { + if (location.hostname === 'tastejs.github.io') { + location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com'); + } + } + + function findRoot() { + var base = location.href.indexOf('examples/'); + return location.href.substr(0, base); + } + + function getFile(file, callback) { + if (!location.host) { + return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.'); + } + + var xhr = new XMLHttpRequest(); + + xhr.open('GET', findRoot() + file, true); + xhr.send(); + + xhr.onload = function () { + if (xhr.status === 200 && callback) { + callback(xhr.responseText); + } + }; + } + + function Learn(learnJSON, config) { + if (!(this instanceof Learn)) { + return new Learn(learnJSON, config); + } + + var template, framework; + + if (typeof learnJSON !== 'object') { + try { + learnJSON = JSON.parse(learnJSON); + } catch (e) { + return; + } + } + + if (config) { + template = config.template; + framework = config.framework; + } + + if (!template && learnJSON.templates) { + template = learnJSON.templates.todomvc; + } + + if (!framework && document.querySelector('[data-framework]')) { + framework = document.querySelector('[data-framework]').dataset.framework; + } + + this.template = template; + + if (learnJSON.backend) { + this.frameworkJSON = learnJSON.backend; + this.frameworkJSON.issueLabel = framework; + this.append({ + backend: true + }); + } else if (learnJSON[framework]) { + this.frameworkJSON = learnJSON[framework]; + this.frameworkJSON.issueLabel = framework; + this.append(); + } + + this.fetchIssueCount(); + } + + Learn.prototype.append = function (opts) { + var aside = document.createElement('aside'); + aside.innerHTML = _.template(this.template, this.frameworkJSON); + aside.className = 'learn'; + + if (opts && opts.backend) { + // Remove demo link + var sourceLinks = aside.querySelector('.source-links'); + var heading = sourceLinks.firstElementChild; + var sourceLink = sourceLinks.lastElementChild; + // Correct link path + var href = sourceLink.getAttribute('href'); + sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http'))); + sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML; + } else { + // Localize demo links + var demoLinks = aside.querySelectorAll('.demo-link'); + Array.prototype.forEach.call(demoLinks, function (demoLink) { + if (demoLink.getAttribute('href').substr(0, 4) !== 'http') { + demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href')); + } + }); + } + + document.body.className = (document.body.className + ' learn-bar').trim(); + document.body.insertAdjacentHTML('afterBegin', aside.outerHTML); + }; + + Learn.prototype.fetchIssueCount = function () { + var issueLink = document.getElementById('issue-count-link'); + if (issueLink) { + var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos'); + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.onload = function (e) { + var parsedResponse = JSON.parse(e.target.responseText); + if (parsedResponse instanceof Array) { + var count = parsedResponse.length + if (count !== 0) { + issueLink.innerHTML = 'This app has ' + count + ' open issues'; + document.getElementById('issue-count').style.display = 'inline'; + } + } + }; + xhr.send(); + } + }; + + redirect(); + getFile('learn.json', Learn); +})(); diff --git a/examples/lit/out/index.js b/examples/lit/out/index.js new file mode 100644 index 0000000000..ba26907162 --- /dev/null +++ b/examples/lit/out/index.js @@ -0,0 +1,1810 @@ +/** +@license +Copyright (c) 2018 The Polymer Project Authors. All rights reserved. +This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt +The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt +The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt +Code distributed by Google as part of the polymer project is also +subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt +*/ +/** + This is a JavaScript mixin that you can use to connect a Custom Element base + class to a Redux store. The `stateChanged(state)` method will be called when + the state is updated. + + Example: + + import { connect } from 'pwa-helpers/connect-mixin.js'; + + class MyElement extends connect(store)(HTMLElement) { + stateChanged(state) { + this.textContent = state.data.count.toString(); + } + } +*/ +const connect = (store) => (baseElement) => class extends baseElement { + connectedCallback() { + if (super.connectedCallback) { + super.connectedCallback(); + } + this._storeUnsubscribe = store.subscribe(() => this.stateChanged(store.getState())); + this.stateChanged(store.getState()); + } + disconnectedCallback() { + this._storeUnsubscribe(); + if (super.disconnectedCallback) { + super.disconnectedCallback(); + } + } + /** + * The `stateChanged(state)` method will be called when the state is updated. + */ + stateChanged(_state) { } +}; + +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +const t$3=window.ShadowRoot&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,e$3=Symbol(),n$5=new WeakMap;class s$4{constructor(t,n,s){if(this._$cssResult$=!0,s!==e$3)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n;}get styleSheet(){let e=this.o;const s=this.t;if(t$3&&void 0===e){const t=void 0!==s&&1===s.length;t&&(e=n$5.get(s)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),t&&n$5.set(s,e));}return e}toString(){return this.cssText}}const o$5=t=>new s$4("string"==typeof t?t:t+"",void 0,e$3),r$3=(t,...n)=>{const o=1===t.length?t[0]:n.reduce(((e,n,s)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[s+1]),t[0]);return new s$4(o,t,e$3)},i$3=(e,n)=>{t$3?e.adoptedStyleSheets=n.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):n.forEach((t=>{const n=document.createElement("style"),s=window.litNonce;void 0!==s&&n.setAttribute("nonce",s),n.textContent=t.cssText,e.appendChild(n);}));},S$2=t$3?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return o$5(e)})(t):t; + +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */var s$3;const e$2=window.trustedTypes,r$2=e$2?e$2.emptyScript:"",h$2=window.reactiveElementPolyfillSupport,o$4={toAttribute(t,i){switch(i){case Boolean:t=t?r$2:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t);}return t},fromAttribute(t,i){let s=t;switch(i){case Boolean:s=null!==t;break;case Number:s=null===t?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t);}catch(t){s=null;}}return s}},n$4=(t,i)=>i!==t&&(i==i||t==t),l$3={attribute:!0,type:String,converter:o$4,reflect:!1,hasChanged:n$4};class a$2 extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u();}static addInitializer(t){var i;null!==(i=this.h)&&void 0!==i||(this.h=[]),this.h.push(t);}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((i,s)=>{const e=this._$Ep(s,i);void 0!==e&&(this._$Ev.set(e,s),t.push(e));})),t}static createProperty(t,i=l$3){if(i.state&&(i.attribute=!1),this.finalize(),this.elementProperties.set(t,i),!i.noAccessor&&!this.prototype.hasOwnProperty(t)){const s="symbol"==typeof t?Symbol():"__"+t,e=this.getPropertyDescriptor(t,s,i);void 0!==e&&Object.defineProperty(this.prototype,t,e);}}static getPropertyDescriptor(t,i,s){return {get(){return this[i]},set(e){const r=this[t];this[i]=e,this.requestUpdate(t,r,s);},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||l$3}static finalize(){if(this.hasOwnProperty("finalized"))return !1;this.finalized=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const t=this.properties,i=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const s of i)this.createProperty(s,t[s]);}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(i){const s=[];if(Array.isArray(i)){const e=new Set(i.flat(1/0).reverse());for(const i of e)s.unshift(S$2(i));}else void 0!==i&&s.push(S$2(i));return s}static _$Ep(t,i){const s=i.attribute;return !1===s?void 0:"string"==typeof s?s:"string"==typeof t?t.toLowerCase():void 0}u(){var t;this._$E_=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$Eg(),this.requestUpdate(),null===(t=this.constructor.h)||void 0===t||t.forEach((t=>t(this)));}addController(t){var i,s;(null!==(i=this._$ES)&&void 0!==i?i:this._$ES=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(s=t.hostConnected)||void 0===s||s.call(t));}removeController(t){var i;null===(i=this._$ES)||void 0===i||i.splice(this._$ES.indexOf(t)>>>0,1);}_$Eg(){this.constructor.elementProperties.forEach(((t,i)=>{this.hasOwnProperty(i)&&(this._$Ei.set(i,this[i]),delete this[i]);}));}createRenderRoot(){var t;const s=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return i$3(s,this.constructor.elementStyles),s}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostConnected)||void 0===i?void 0:i.call(t)}));}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostDisconnected)||void 0===i?void 0:i.call(t)}));}attributeChangedCallback(t,i,s){this._$AK(t,s);}_$EO(t,i,s=l$3){var e,r;const h=this.constructor._$Ep(t,s);if(void 0!==h&&!0===s.reflect){const n=(null!==(r=null===(e=s.converter)||void 0===e?void 0:e.toAttribute)&&void 0!==r?r:o$4.toAttribute)(i,s.type);this._$El=t,null==n?this.removeAttribute(h):this.setAttribute(h,n),this._$El=null;}}_$AK(t,i){var s,e;const r=this.constructor,h=r._$Ev.get(t);if(void 0!==h&&this._$El!==h){const t=r.getPropertyOptions(h),n=t.converter,l=null!==(e=null!==(s=null==n?void 0:n.fromAttribute)&&void 0!==s?s:"function"==typeof n?n:null)&&void 0!==e?e:o$4.fromAttribute;this._$El=h,this[h]=l(i,t.type),this._$El=null;}}requestUpdate(t,i,s){let e=!0;void 0!==t&&(((s=s||this.constructor.getPropertyOptions(t)).hasChanged||n$4)(this[t],i)?(this._$AL.has(t)||this._$AL.set(t,i),!0===s.reflect&&this._$El!==t&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(t,s))):e=!1),!this.isUpdatePending&&e&&(this._$E_=this._$Ej());}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_;}catch(t){Promise.reject(t);}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach(((t,i)=>this[i]=t)),this._$Ei=void 0);let i=!1;const s=this._$AL;try{i=this.shouldUpdate(s),i?(this.willUpdate(s),null===(t=this._$ES)||void 0===t||t.forEach((t=>{var i;return null===(i=t.hostUpdate)||void 0===i?void 0:i.call(t)})),this.update(s)):this._$Ek();}catch(t){throw i=!1,this._$Ek(),t}i&&this._$AE(s);}willUpdate(t){}_$AE(t){var i;null===(i=this._$ES)||void 0===i||i.forEach((t=>{var i;return null===(i=t.hostUpdated)||void 0===i?void 0:i.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t);}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1;}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return !0}update(t){void 0!==this._$EC&&(this._$EC.forEach(((t,i)=>this._$EO(i,this[i],t))),this._$EC=void 0),this._$Ek();}updated(t){}firstUpdated(t){}}a$2.finalized=!0,a$2.elementProperties=new Map,a$2.elementStyles=[],a$2.shadowRootOptions={mode:"open"},null==h$2||h$2({ReactiveElement:a$2}),(null!==(s$3=globalThis.reactiveElementVersions)&&void 0!==s$3?s$3:globalThis.reactiveElementVersions=[]).push("1.3.4"); + +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +var t$2;const i$2=globalThis.trustedTypes,s$2=i$2?i$2.createPolicy("lit-html",{createHTML:t=>t}):void 0,e$1=`lit$${(Math.random()+"").slice(9)}$`,o$3="?"+e$1,n$3=`<${o$3}>`,l$2=document,h$1=(t="")=>l$2.createComment(t),r$1=t=>null===t||"object"!=typeof t&&"function"!=typeof t,d$1=Array.isArray,u$1=t=>d$1(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]),c$1=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,v$1=/-->/g,a$1=/>/g,f$1=RegExp(">|[ \t\n\f\r](?:([^\\s\"'>=/]+)([ \t\n\f\r]*=[ \t\n\f\r]*(?:[^ \t\n\f\r\"'`<>=]|(\"|')|))|$)","g"),_$1=/'/g,g$1=/"/g,m$1=/^(?:script|style|textarea|title)$/i,p$1=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),$=p$1(1),b$1=Symbol.for("lit-noChange"),w$1=Symbol.for("lit-nothing"),x$1=new WeakMap,T=(t,i,s)=>{var e,o;const n=null!==(e=null==s?void 0:s.renderBefore)&&void 0!==e?e:i;let l=n._$litPart$;if(void 0===l){const t=null!==(o=null==s?void 0:s.renderBefore)&&void 0!==o?o:null;n._$litPart$=l=new N$1(i.insertBefore(h$1(),t),t,void 0,null!=s?s:{});}return l._$AI(t),l},A$1=l$2.createTreeWalker(l$2,129,null,!1),E$1=(t,i)=>{const o=t.length-1,l=[];let h,r=2===i?"":"",d=c$1;for(let i=0;i"===u[0]?(d=null!=h?h:c$1,p=-1):void 0===u[1]?p=-2:(p=d.lastIndex-u[2].length,o=u[1],d=void 0===u[3]?f$1:'"'===u[3]?g$1:_$1):d===g$1||d===_$1?d=f$1:d===v$1||d===a$1?d=c$1:(d=f$1,h=void 0);const y=d===f$1&&t[i+1].startsWith("/>")?" ":"";r+=d===c$1?s+n$3:p>=0?(l.push(o),s.slice(0,p)+"$lit$"+s.slice(p)+e$1+y):s+e$1+(-2===p?(l.push(void 0),i):y);}const u=r+(t[o]||"")+(2===i?"":"");if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return [void 0!==s$2?s$2.createHTML(u):u,l]};class C{constructor({strings:t,_$litType$:s},n){let l;this.parts=[];let r=0,d=0;const u=t.length-1,c=this.parts,[v,a]=E$1(t,s);if(this.el=C.createElement(v,n),A$1.currentNode=this.el.content,2===s){const t=this.el.content,i=t.firstChild;i.remove(),t.append(...i.childNodes);}for(;null!==(l=A$1.nextNode())&&c.length0){l.textContent=i$2?i$2.emptyScript:"";for(let i=0;i2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=w$1;}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,i=this,s,e){const o=this.strings;let n=!1;if(void 0===o)t=P$1(this,t,i,0),n=!r$1(t)||t!==this._$AH&&t!==b$1,n&&(this._$AH=t);else {const e=t;let l,h;for(t=o[0],l=0;l1?r-1:0),e=1;e3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o$1(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o$1(n)?n.get(r):n[r]}function f(n,r,t){var e=o$1(n);2===e?n.set(r,t):3===e?(n.delete(r),n.add(t)):n[r]=t;}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i$1(n,(function(n,r){return d(r,!0)}),!0),n)}function h(){n(2);}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function m(n,r){tn[n]||(tn[n]=r);}function _(){return U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r);}function O(n){g(n),n.p.forEach(S),n.p=null;}function g(n){n===U&&(U=n.l);}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.O=!0;}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.g||b("ES5").S(e,r,o),o?(i[Q].P&&(O(e),n(4)),t$1(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),O(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i$1(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o;i$1(3===e.i?new Set(o):o,(function(r,i){return A(n,e,o,r,i,t)})),x(n,o,!1),t&&n.u&&b("Patches").R(e,t,n.u,n.s);}return e.o}function A(e,i,o,a,c,s){if(c===o&&n(5),r(c)){var v=M(e,c,s&&i&&3!==i.i&&!u(i.D,a)?s.concat(a):void 0);if(f(o,a,v),!r(v))return;e.m=!1;}if(t$1(c)&&!y(c)){if(!e.h.F&&e._<1)return;M(e,c),i&&i.A.l||x(e,c);}}function x(n,r,t){void 0===t&&(t=!1),n.h.F&&n.m&&d(r,t);}function z(n,r){var t=n[Q];return (t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t);}}function k(n){n.P||(n.P=!0,n.l&&k(n.l));}function E(n){n.o||(n.o=l(n.t));}function R(n,r,t){var e=s(r)?b("MapSet").N(r,t):v(r)?b("MapSet").T(r,t):n.g?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,D:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return (t?t.A:_()).p.push(e),e}function D(e){return r(e)||n(22,e),function n(r){if(!t$1(r))return r;var e,u=r[Q],c=o$1(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=F(r,c),u.I=!1;}else e=F(r,c);return i$1(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t));})),3===c?new Set(e):e}(e)}function F(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}function N(){function t(n,r){var t=s[n];return t?t.enumerable=r:s[n]=t={configurable:!0,enumerable:r,get:function(){var r=this[Q];return f(r),en.get(r,n)},set:function(r){var t=this[Q];f(t),en.set(t,n,r);}},t}function e(n){for(var r=n.length-1;r>=0;r--){var t=n[r][Q];if(!t.P)switch(t.i){case 5:a(t)&&k(t);break;case 4:o(t)&&k(t);}}}function o(n){for(var r=n.t,t=n.k,e=nn(t),i=e.length-1;i>=0;i--){var o=e[i];if(o!==Q){var a=r[o];if(void 0===a&&!u(r,o))return !0;var f=t[o],s=f&&f[Q];if(s?s.t!==a:!c(f,a))return !0}}var v=!!r[Q];return e.length!==nn(r).length+(v?0:1)}function a(n){var r=n.k;if(r.length!==n.t.length)return !0;var t=Object.getOwnPropertyDescriptor(r,r.length-1);if(t&&!t.get)return !0;for(var e=0;e1?t-1:0),o=1;o1?t-1:0),o=1;o=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce;an.produceWithPatches.bind(an);an.setAutoFreeze.bind(an);an.setUseProxies.bind(an);an.applyPatches.bind(an);an.createDraft.bind(an);an.finishDraft.bind(an); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + + return target; +} + +// Inlined version of the `symbol-observable` polyfill +var $$observable = (function () { + return typeof Symbol === 'function' && Symbol.observable || '@@observable'; +})(); + +/** + * These are private action types reserved by Redux. + * For any unknown actions, you must return the current state. + * If the current state is undefined, you must return the initial state. + * Do not reference these action types directly in your code. + */ +var randomString = function randomString() { + return Math.random().toString(36).substring(7).split('').join('.'); +}; + +var ActionTypes = { + INIT: "@@redux/INIT" + randomString(), + REPLACE: "@@redux/REPLACE" + randomString(), + PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { + return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); + } +}; + +/** + * @param {any} obj The object to inspect. + * @returns {boolean} True if the argument appears to be a plain object. + */ +function isPlainObject$1(obj) { + if (typeof obj !== 'object' || obj === null) return false; + var proto = obj; + + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + + return Object.getPrototypeOf(obj) === proto; +} + +// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of +function miniKindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + var type = typeof val; + + switch (type) { + case 'boolean': + case 'string': + case 'number': + case 'symbol': + case 'function': + { + return type; + } + } + + if (Array.isArray(val)) return 'array'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + var constructorName = ctorName(val); + + switch (constructorName) { + case 'Symbol': + case 'Promise': + case 'WeakMap': + case 'WeakSet': + case 'Map': + case 'Set': + return constructorName; + } // other + + + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +} + +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} + +function isError(val) { + return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'; +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function'; +} + +function kindOf(val) { + var typeOfVal = typeof val; + + { + typeOfVal = miniKindOf(val); + } + + return typeOfVal; +} + +/** + * @deprecated + * + * **We recommend using the `configureStore` method + * of the `@reduxjs/toolkit` package**, which replaces `createStore`. + * + * Redux Toolkit is our recommended approach for writing Redux logic today, + * including store setup, reducers, data fetching, and more. + * + * **For more details, please read this Redux docs page:** + * **https://redux.js.org/introduction/why-rtk-is-redux-today** + * + * `configureStore` from Redux Toolkit is an improved version of `createStore` that + * simplifies setup and helps avoid common bugs. + * + * You should not be using the `redux` core package by itself today, except for learning purposes. + * The `createStore` method from the core `redux` package will not be removed, but we encourage + * all users to migrate to using Redux Toolkit for all Redux code. + * + * If you want to use `createStore` without this visual deprecation warning, use + * the `legacy_createStore` import instead: + * + * `import { legacy_createStore as createStore} from 'redux'` + * + */ + +function createStore(reducer, preloadedState, enhancer) { + var _ref2; + + if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { + throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.'); + } + + if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { + enhancer = preloadedState; + preloadedState = undefined; + } + + if (typeof enhancer !== 'undefined') { + if (typeof enhancer !== 'function') { + throw new Error("Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'"); + } + + return enhancer(createStore)(reducer, preloadedState); + } + + if (typeof reducer !== 'function') { + throw new Error("Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'"); + } + + var currentReducer = reducer; + var currentState = preloadedState; + var currentListeners = []; + var nextListeners = currentListeners; + var isDispatching = false; + /** + * This makes a shallow copy of currentListeners so we can use + * nextListeners as a temporary list while dispatching. + * + * This prevents any bugs around consumers calling + * subscribe/unsubscribe in the middle of a dispatch. + */ + + function ensureCanMutateNextListeners() { + if (nextListeners === currentListeners) { + nextListeners = currentListeners.slice(); + } + } + /** + * Reads the state tree managed by the store. + * + * @returns {any} The current state tree of your application. + */ + + + function getState() { + if (isDispatching) { + throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.'); + } + + return currentState; + } + /** + * Adds a change listener. It will be called any time an action is dispatched, + * and some part of the state tree may potentially have changed. You may then + * call `getState()` to read the current state tree inside the callback. + * + * You may call `dispatch()` from a change listener, with the following + * caveats: + * + * 1. The subscriptions are snapshotted just before every `dispatch()` call. + * If you subscribe or unsubscribe while the listeners are being invoked, this + * will not have any effect on the `dispatch()` that is currently in progress. + * However, the next `dispatch()` call, whether nested or not, will use a more + * recent snapshot of the subscription list. + * + * 2. The listener should not expect to see all state changes, as the state + * might have been updated multiple times during a nested `dispatch()` before + * the listener is called. It is, however, guaranteed that all subscribers + * registered before the `dispatch()` started will be called with the latest + * state by the time it exits. + * + * @param {Function} listener A callback to be invoked on every dispatch. + * @returns {Function} A function to remove this change listener. + */ + + + function subscribe(listener) { + if (typeof listener !== 'function') { + throw new Error("Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'"); + } + + if (isDispatching) { + throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.'); + } + + var isSubscribed = true; + ensureCanMutateNextListeners(); + nextListeners.push(listener); + return function unsubscribe() { + if (!isSubscribed) { + return; + } + + if (isDispatching) { + throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.'); + } + + isSubscribed = false; + ensureCanMutateNextListeners(); + var index = nextListeners.indexOf(listener); + nextListeners.splice(index, 1); + currentListeners = null; + }; + } + /** + * Dispatches an action. It is the only way to trigger a state change. + * + * The `reducer` function, used to create the store, will be called with the + * current state tree and the given `action`. Its return value will + * be considered the **next** state of the tree, and the change listeners + * will be notified. + * + * The base implementation only supports plain object actions. If you want to + * dispatch a Promise, an Observable, a thunk, or something else, you need to + * wrap your store creating function into the corresponding middleware. For + * example, see the documentation for the `redux-thunk` package. Even the + * middleware will eventually dispatch plain object actions using this method. + * + * @param {Object} action A plain object representing “what changed”. It is + * a good idea to keep actions serializable so you can record and replay user + * sessions, or use the time travelling `redux-devtools`. An action must have + * a `type` property which may not be `undefined`. It is a good idea to use + * string constants for action types. + * + * @returns {Object} For convenience, the same action object you dispatched. + * + * Note that, if you use a custom middleware, it may wrap `dispatch()` to + * return something else (for example, a Promise you can await). + */ + + + function dispatch(action) { + if (!isPlainObject$1(action)) { + throw new Error("Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples."); + } + + if (typeof action.type === 'undefined') { + throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'); + } + + if (isDispatching) { + throw new Error('Reducers may not dispatch actions.'); + } + + try { + isDispatching = true; + currentState = currentReducer(currentState, action); + } finally { + isDispatching = false; + } + + var listeners = currentListeners = nextListeners; + + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(); + } + + return action; + } + /** + * Replaces the reducer currently used by the store to calculate the state. + * + * You might need this if your app implements code splitting and you want to + * load some of the reducers dynamically. You might also need this if you + * implement a hot reloading mechanism for Redux. + * + * @param {Function} nextReducer The reducer for the store to use instead. + * @returns {void} + */ + + + function replaceReducer(nextReducer) { + if (typeof nextReducer !== 'function') { + throw new Error("Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer)); + } + + currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. + // Any reducers that existed in both the new and old rootReducer + // will receive the previous state. This effectively populates + // the new state tree with any relevant data from the old one. + + dispatch({ + type: ActionTypes.REPLACE + }); + } + /** + * Interoperability point for observable/reactive libraries. + * @returns {observable} A minimal observable of state changes. + * For more information, see the observable proposal: + * https://github.com/tc39/proposal-observable + */ + + + function observable() { + var _ref; + + var outerSubscribe = subscribe; + return _ref = { + /** + * The minimal observable subscription method. + * @param {Object} observer Any object that can be used as an observer. + * The observer object should have a `next` method. + * @returns {subscription} An object with an `unsubscribe` method that can + * be used to unsubscribe the observable from the store, and prevent further + * emission of values from the observable. + */ + subscribe: function subscribe(observer) { + if (typeof observer !== 'object' || observer === null) { + throw new Error("Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'"); + } + + function observeState() { + if (observer.next) { + observer.next(getState()); + } + } + + observeState(); + var unsubscribe = outerSubscribe(observeState); + return { + unsubscribe: unsubscribe + }; + } + }, _ref[$$observable] = function () { + return this; + }, _ref; + } // When a store is created, an "INIT" action is dispatched so that every + // reducer returns their initial state. This effectively populates + // the initial state tree. + + + dispatch({ + type: ActionTypes.INIT + }); + return _ref2 = { + dispatch: dispatch, + subscribe: subscribe, + getState: getState, + replaceReducer: replaceReducer + }, _ref2[$$observable] = observable, _ref2; +} + +/** + * Prints a warning in the console if it exists. + * + * @param {String} message The warning message. + * @returns {void} + */ +function warning(message) { + /* eslint-disable no-console */ + if (typeof console !== 'undefined' && typeof console.error === 'function') { + console.error(message); + } + /* eslint-enable no-console */ + + + try { + // This error was thrown as a convenience so that if you enable + // "break on all exceptions" in your console, + // it would pause the execution at this line. + throw new Error(message); + } catch (e) {} // eslint-disable-line no-empty + +} + +function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { + var reducerKeys = Object.keys(reducers); + var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; + + if (reducerKeys.length === 0) { + return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; + } + + if (!isPlainObject$1(inputState)) { + return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\""); + } + + var unexpectedKeys = Object.keys(inputState).filter(function (key) { + return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; + }); + unexpectedKeys.forEach(function (key) { + unexpectedKeyCache[key] = true; + }); + if (action && action.type === ActionTypes.REPLACE) return; + + if (unexpectedKeys.length > 0) { + return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored."); + } +} + +function assertReducerShape(reducers) { + Object.keys(reducers).forEach(function (key) { + var reducer = reducers[key]; + var initialState = reducer(undefined, { + type: ActionTypes.INIT + }); + + if (typeof initialState === 'undefined') { + throw new Error("The slice reducer for key \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined."); + } + + if (typeof reducer(undefined, { + type: ActionTypes.PROBE_UNKNOWN_ACTION() + }) === 'undefined') { + throw new Error("The slice reducer for key \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle '" + ActionTypes.INIT + "' or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null."); + } + }); +} +/** + * Turns an object whose values are different reducer functions, into a single + * reducer function. It will call every child reducer, and gather their results + * into a single state object, whose keys correspond to the keys of the passed + * reducer functions. + * + * @param {Object} reducers An object whose values correspond to different + * reducer functions that need to be combined into one. One handy way to obtain + * it is to use ES6 `import * as reducers` syntax. The reducers may never return + * undefined for any action. Instead, they should return their initial state + * if the state passed to them was undefined, and the current state for any + * unrecognized action. + * + * @returns {Function} A reducer function that invokes every reducer inside the + * passed object, and builds a state object with the same shape. + */ + + +function combineReducers(reducers) { + var reducerKeys = Object.keys(reducers); + var finalReducers = {}; + + for (var i = 0; i < reducerKeys.length; i++) { + var key = reducerKeys[i]; + + { + if (typeof reducers[key] === 'undefined') { + warning("No reducer provided for key \"" + key + "\""); + } + } + + if (typeof reducers[key] === 'function') { + finalReducers[key] = reducers[key]; + } + } + + var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same + // keys multiple times. + + var unexpectedKeyCache; + + { + unexpectedKeyCache = {}; + } + + var shapeAssertionError; + + try { + assertReducerShape(finalReducers); + } catch (e) { + shapeAssertionError = e; + } + + return function combination(state, action) { + if (state === void 0) { + state = {}; + } + + if (shapeAssertionError) { + throw shapeAssertionError; + } + + { + var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); + + if (warningMessage) { + warning(warningMessage); + } + } + + var hasChanged = false; + var nextState = {}; + + for (var _i = 0; _i < finalReducerKeys.length; _i++) { + var _key = finalReducerKeys[_i]; + var reducer = finalReducers[_key]; + var previousStateForKey = state[_key]; + var nextStateForKey = reducer(previousStateForKey, action); + + if (typeof nextStateForKey === 'undefined') { + var actionType = action && action.type; + throw new Error("When called with an action of type " + (actionType ? "\"" + String(actionType) + "\"" : '(unknown type)') + ", the slice reducer for key \"" + _key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined."); + } + + nextState[_key] = nextStateForKey; + hasChanged = hasChanged || nextStateForKey !== previousStateForKey; + } + + hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length; + return hasChanged ? nextState : state; + }; +} + +/** + * Composes single-argument functions from right to left. The rightmost + * function can take multiple arguments as it provides the signature for + * the resulting composite function. + * + * @param {...Function} funcs The functions to compose. + * @returns {Function} A function obtained by composing the argument functions + * from right to left. For example, compose(f, g, h) is identical to doing + * (...args) => f(g(h(...args))). + */ +function compose() { + for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { + funcs[_key] = arguments[_key]; + } + + if (funcs.length === 0) { + return function (arg) { + return arg; + }; + } + + if (funcs.length === 1) { + return funcs[0]; + } + + return funcs.reduce(function (a, b) { + return function () { + return a(b.apply(void 0, arguments)); + }; + }); +} + +/** + * Creates a store enhancer that applies middleware to the dispatch method + * of the Redux store. This is handy for a variety of tasks, such as expressing + * asynchronous actions in a concise manner, or logging every action payload. + * + * See `redux-thunk` package as an example of the Redux middleware. + * + * Because middleware is potentially asynchronous, this should be the first + * store enhancer in the composition chain. + * + * Note that each middleware will be given the `dispatch` and `getState` functions + * as named arguments. + * + * @param {...Function} middlewares The middleware chain to be applied. + * @returns {Function} A store enhancer applying the middleware. + */ + +function applyMiddleware() { + for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { + middlewares[_key] = arguments[_key]; + } + + return function (createStore) { + return function () { + var store = createStore.apply(void 0, arguments); + + var _dispatch = function dispatch() { + throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.'); + }; + + var middlewareAPI = { + getState: store.getState, + dispatch: function dispatch() { + return _dispatch.apply(void 0, arguments); + } + }; + var chain = middlewares.map(function (middleware) { + return middleware(middlewareAPI); + }); + _dispatch = compose.apply(void 0, chain)(store.dispatch); + return _objectSpread2(_objectSpread2({}, store), {}, { + dispatch: _dispatch + }); + }; + }; +} + +/* + * This is a dummy function to check if the function name has been altered by minification. + * If the function has been minified and NODE_ENV !== 'production', warn the user. + */ + +function isCrushed() {} + +if (typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { + warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.'); +} + +/** A function that accepts a potential "extra argument" value to be injected later, + * and returns an instance of the thunk middleware that uses that value + */ +function createThunkMiddleware(extraArgument) { + // Standard Redux middleware definition pattern: + // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware + var middleware = function middleware(_ref) { + var dispatch = _ref.dispatch, + getState = _ref.getState; + return function (next) { + return function (action) { + // The thunk middleware looks for any functions that were passed to `store.dispatch`. + // If this "action" is really a function, call it and return the result. + if (typeof action === 'function') { + // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg" + return action(dispatch, getState, extraArgument); + } // Otherwise, pass the action down the middleware chain as usual + + + return next(action); + }; + }; + }; + + return middleware; +} + +var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version +// with whatever "extra arg" they want to inject into their thunks + +thunk.withExtraArgument = createThunkMiddleware; +var thunkMiddleware = thunk; + +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +(undefined && undefined.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; +}; +var __defProp = Object.defineProperty; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; }; +var __spreadValues = function (a, b) { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) { + var prop = _c[_i]; + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () { + if (arguments.length === 0) + return void 0; + if (typeof arguments[0] === "object") + return compose; + return compose.apply(null, arguments); +}; +// src/isPlainObject.ts +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + var proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + var baseProto = proto; + while (Object.getPrototypeOf(baseProto) !== null) { + baseProto = Object.getPrototypeOf(baseProto); + } + return proto === baseProto; +} +function getTimeMeasureUtils(maxDelay, fnName) { + var elapsed = 0; + return { + measureTime: function (fn) { + var started = Date.now(); + try { + return fn(); + } + finally { + var finished = Date.now(); + elapsed += finished - started; + } + }, + warnIfExceeded: function () { + if (elapsed > maxDelay) { + console.warn(fnName + " took " + elapsed + "ms, which is more than the warning threshold of " + maxDelay + "ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that."); + } + } + }; +} +var MiddlewareArray = /** @class */ (function (_super) { + __extends(MiddlewareArray, _super); + function MiddlewareArray() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _this = _super.apply(this, args) || this; + Object.setPrototypeOf(_this, MiddlewareArray.prototype); + return _this; + } + Object.defineProperty(MiddlewareArray, Symbol.species, { + get: function () { + return MiddlewareArray; + }, + enumerable: false, + configurable: true + }); + MiddlewareArray.prototype.concat = function () { + var arr = []; + for (var _i = 0; _i < arguments.length; _i++) { + arr[_i] = arguments[_i]; + } + return _super.prototype.concat.apply(this, arr); + }; + MiddlewareArray.prototype.prepend = function () { + var arr = []; + for (var _i = 0; _i < arguments.length; _i++) { + arr[_i] = arguments[_i]; + } + if (arr.length === 1 && Array.isArray(arr[0])) { + return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))(); + } + return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))(); + }; + return MiddlewareArray; +}(Array)); +function freezeDraftable(val) { + return t$1(val) ? fn(val, function () { + }) : val; +} +var prefix = "Invariant failed"; +function invariant(condition, message) { + if (condition) { + return; + } + throw new Error(prefix + ": " + (message || "")); +} +function stringify(obj, serializer, indent, decycler) { + return JSON.stringify(obj, getSerialize(serializer, decycler), indent); +} +function getSerialize(serializer, decycler) { + var stack = [], keys = []; + if (!decycler) + decycler = function (_, value) { + if (stack[0] === value) + return "[Circular ~]"; + return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"; + }; + return function (key, value) { + if (stack.length > 0) { + var thisPos = stack.indexOf(this); + ~thisPos ? stack.splice(thisPos + 1) : stack.push(this); + ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key); + if (~stack.indexOf(value)) + value = decycler.call(this, key, value); + } + else + stack.push(value); + return serializer == null ? value : serializer.call(this, key, value); + }; +} +function isImmutableDefault(value) { + return typeof value !== "object" || value === null || typeof value === "undefined" || Object.isFrozen(value); +} +function trackForMutations(isImmutable, ignorePaths, obj) { + var trackedProperties = trackProperties(isImmutable, ignorePaths, obj); + return { + detectMutations: function () { + return detectMutations(isImmutable, ignorePaths, trackedProperties, obj); + } + }; +} +function trackProperties(isImmutable, ignorePaths, obj, path) { + if (ignorePaths === void 0) { ignorePaths = []; } + if (path === void 0) { path = ""; } + var tracked = { value: obj }; + if (!isImmutable(obj)) { + tracked.children = {}; + for (var key in obj) { + var childPath = path ? path + "." + key : key; + if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) { + continue; + } + tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath); + } + } + return tracked; +} +function detectMutations(isImmutable, ignorePaths, trackedProperty, obj, sameParentRef, path) { + if (ignorePaths === void 0) { ignorePaths = []; } + if (sameParentRef === void 0) { sameParentRef = false; } + if (path === void 0) { path = ""; } + var prevObj = trackedProperty ? trackedProperty.value : void 0; + var sameRef = prevObj === obj; + if (sameParentRef && !sameRef && !Number.isNaN(obj)) { + return { wasMutated: true, path: path }; + } + if (isImmutable(prevObj) || isImmutable(obj)) { + return { wasMutated: false }; + } + var keysToDetect = {}; + for (var key in trackedProperty.children) { + keysToDetect[key] = true; + } + for (var key in obj) { + keysToDetect[key] = true; + } + for (var key in keysToDetect) { + var childPath = path ? path + "." + key : key; + if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) { + continue; + } + var result = detectMutations(isImmutable, ignorePaths, trackedProperty.children[key], obj[key], sameRef, childPath); + if (result.wasMutated) { + return result; + } + } + return { wasMutated: false }; +} +function createImmutableStateInvariantMiddleware(options) { + if (options === void 0) { options = {}; } + var _c = options.isImmutable, isImmutable = _c === void 0 ? isImmutableDefault : _c, ignoredPaths = options.ignoredPaths, _d = options.warnAfter, warnAfter = _d === void 0 ? 32 : _d, ignore = options.ignore; + ignoredPaths = ignoredPaths || ignore; + var track = trackForMutations.bind(null, isImmutable, ignoredPaths); + return function (_c) { + var getState = _c.getState; + var state = getState(); + var tracker = track(state); + var result; + return function (next) { return function (action) { + var measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware"); + measureUtils.measureTime(function () { + state = getState(); + result = tracker.detectMutations(); + tracker = track(state); + invariant(!result.wasMutated, "A state mutation was detected between dispatches, in the path '" + (result.path || "") + "'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)"); + }); + var dispatchedAction = next(action); + measureUtils.measureTime(function () { + state = getState(); + result = tracker.detectMutations(); + tracker = track(state); + result.wasMutated && invariant(!result.wasMutated, "A state mutation was detected inside a dispatch, in the path: " + (result.path || "") + ". Take a look at the reducer(s) handling the action " + stringify(action) + ". (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)"); + }); + measureUtils.warnIfExceeded(); + return dispatchedAction; + }; }; + }; +} +// src/serializableStateInvariantMiddleware.ts +function isPlain(val) { + var type = typeof val; + return type === "undefined" || val === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val); +} +function findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths) { + if (path === void 0) { path = ""; } + if (isSerializable === void 0) { isSerializable = isPlain; } + if (ignoredPaths === void 0) { ignoredPaths = []; } + var foundNestedSerializable; + if (!isSerializable(value)) { + return { + keyPath: path || "", + value: value + }; + } + if (typeof value !== "object" || value === null) { + return false; + } + var entries = getEntries != null ? getEntries(value) : Object.entries(value); + var hasIgnoredPaths = ignoredPaths.length > 0; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _c = entries_1[_i], key = _c[0], nestedValue = _c[1]; + var nestedPath = path ? path + "." + key : key; + if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath) >= 0) { + continue; + } + if (!isSerializable(nestedValue)) { + return { + keyPath: nestedPath, + value: nestedValue + }; + } + if (typeof nestedValue === "object") { + foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths); + if (foundNestedSerializable) { + return foundNestedSerializable; + } + } + } + return false; +} +function createSerializableStateInvariantMiddleware(options) { + if (options === void 0) { options = {}; } + var _c = options.isSerializable, isSerializable = _c === void 0 ? isPlain : _c, getEntries = options.getEntries, _d = options.ignoredActions, ignoredActions = _d === void 0 ? [] : _d, _e = options.ignoredActionPaths, ignoredActionPaths = _e === void 0 ? ["meta.arg", "meta.baseQueryMeta"] : _e, _f = options.ignoredPaths, ignoredPaths = _f === void 0 ? [] : _f, _g = options.warnAfter, warnAfter = _g === void 0 ? 32 : _g, _h = options.ignoreState, ignoreState = _h === void 0 ? false : _h, _j = options.ignoreActions, ignoreActions = _j === void 0 ? false : _j; + return function (storeAPI) { return function (next) { return function (action) { + var result = next(action); + var measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware"); + if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) { + measureUtils.measureTime(function () { + var foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths); + if (foundActionNonSerializableValue) { + var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value; + console.error("A non-serializable value was detected in an action, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)"); + } + }); + } + if (!ignoreState) { + measureUtils.measureTime(function () { + var state = storeAPI.getState(); + var foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths); + if (foundStateNonSerializableValue) { + var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value; + console.error("A non-serializable value was detected in the state, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the reducer(s) handling this action type: " + action.type + ".\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)"); + } + }); + measureUtils.warnIfExceeded(); + } + return result; + }; }; }; +} +// src/getDefaultMiddleware.ts +function isBoolean(x) { + return typeof x === "boolean"; +} +function curryGetDefaultMiddleware() { + return function curriedGetDefaultMiddleware(options) { + return getDefaultMiddleware(options); + }; +} +function getDefaultMiddleware(options) { + if (options === void 0) { options = {}; } + var _c = options.thunk, thunk = _c === void 0 ? true : _c, _d = options.immutableCheck, immutableCheck = _d === void 0 ? true : _d, _e = options.serializableCheck, serializableCheck = _e === void 0 ? true : _e; + var middlewareArray = new MiddlewareArray(); + if (thunk) { + if (isBoolean(thunk)) { + middlewareArray.push(thunkMiddleware); + } + else { + middlewareArray.push(thunkMiddleware.withExtraArgument(thunk.extraArgument)); + } + } + { + if (immutableCheck) { + var immutableOptions = {}; + if (!isBoolean(immutableCheck)) { + immutableOptions = immutableCheck; + } + middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions)); + } + if (serializableCheck) { + var serializableOptions = {}; + if (!isBoolean(serializableCheck)) { + serializableOptions = serializableCheck; + } + middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions)); + } + } + return middlewareArray; +} +// src/configureStore.ts +var IS_PRODUCTION = "undefined" === "production"; +function configureStore(options) { + var curriedGetDefaultMiddleware = curryGetDefaultMiddleware(); + var _c = options || {}, _d = _c.reducer, reducer = _d === void 0 ? void 0 : _d, _e = _c.middleware, middleware = _e === void 0 ? curriedGetDefaultMiddleware() : _e, _f = _c.devTools, devTools = _f === void 0 ? true : _f, _g = _c.preloadedState, preloadedState = _g === void 0 ? void 0 : _g, _h = _c.enhancers, enhancers = _h === void 0 ? void 0 : _h; + var rootReducer; + if (typeof reducer === "function") { + rootReducer = reducer; + } + else if (isPlainObject(reducer)) { + rootReducer = combineReducers(reducer); + } + else { + throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers'); + } + var finalMiddleware = middleware; + if (typeof finalMiddleware === "function") { + finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware); + if (!Array.isArray(finalMiddleware)) { + throw new Error("when using a middleware builder function, an array of middleware must be returned"); + } + } + if (finalMiddleware.some(function (item) { return typeof item !== "function"; })) { + throw new Error("each middleware provided to configureStore must be a function"); + } + var middlewareEnhancer = applyMiddleware.apply(void 0, finalMiddleware); + var finalCompose = compose; + if (devTools) { + finalCompose = composeWithDevTools(__spreadValues({ + trace: !IS_PRODUCTION + }, typeof devTools === "object" && devTools)); + } + var storeEnhancers = [middlewareEnhancer]; + if (Array.isArray(enhancers)) { + storeEnhancers = __spreadArray([middlewareEnhancer], enhancers); + } + else if (typeof enhancers === "function") { + storeEnhancers = enhancers(storeEnhancers); + } + var composedEnhancer = finalCompose.apply(void 0, storeEnhancers); + return createStore(rootReducer, preloadedState, composedEnhancer); +} +// src/createAction.ts +function createAction(type, prepareAction) { + function actionCreator() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (prepareAction) { + var prepared = prepareAction.apply(void 0, args); + if (!prepared) { + throw new Error("prepareAction did not return an object"); + } + return __spreadValues(__spreadValues({ + type: type, + payload: prepared.payload + }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error }); + } + return { type: type, payload: args[0] }; + } + actionCreator.toString = function () { return "" + type; }; + actionCreator.type = type; + actionCreator.match = function (action) { return action.type === type; }; + return actionCreator; +} +// src/mapBuilders.ts +function executeReducerBuilderCallback(builderCallback) { + var actionsMap = {}; + var actionMatchers = []; + var defaultCaseReducer; + var builder = { + addCase: function (typeOrActionCreator, reducer) { + { + if (actionMatchers.length > 0) { + throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`"); + } + if (defaultCaseReducer) { + throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`"); + } + } + var type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type; + if (type in actionsMap) { + throw new Error("addCase cannot be called with two reducers for the same action type"); + } + actionsMap[type] = reducer; + return builder; + }, + addMatcher: function (matcher, reducer) { + { + if (defaultCaseReducer) { + throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`"); + } + } + actionMatchers.push({ matcher: matcher, reducer: reducer }); + return builder; + }, + addDefaultCase: function (reducer) { + { + if (defaultCaseReducer) { + throw new Error("`builder.addDefaultCase` can only be called once"); + } + } + defaultCaseReducer = reducer; + return builder; + } + }; + builderCallback(builder); + return [actionsMap, actionMatchers, defaultCaseReducer]; +} +// src/createReducer.ts +function isStateFunction(x) { + return typeof x === "function"; +} +function createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) { + if (actionMatchers === void 0) { actionMatchers = []; } + var _c = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2]; + var getInitialState; + if (isStateFunction(initialState)) { + getInitialState = function () { return freezeDraftable(initialState()); }; + } + else { + var frozenInitialState_1 = freezeDraftable(initialState); + getInitialState = function () { return frozenInitialState_1; }; + } + function reducer(state, action) { + if (state === void 0) { state = getInitialState(); } + var caseReducers = __spreadArray([ + actionsMap[action.type] + ], finalActionMatchers.filter(function (_c) { + var matcher = _c.matcher; + return matcher(action); + }).map(function (_c) { + var reducer2 = _c.reducer; + return reducer2; + })); + if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) { + caseReducers = [finalDefaultCaseReducer]; + } + return caseReducers.reduce(function (previousState, caseReducer) { + if (caseReducer) { + if (r(previousState)) { + var draft = previousState; + var result = caseReducer(draft, action); + if (typeof result === "undefined") { + return previousState; + } + return result; + } + else if (!t$1(previousState)) { + var result = caseReducer(previousState, action); + if (typeof result === "undefined") { + if (previousState === null) { + return previousState; + } + throw Error("A case reducer on a non-draftable value must not return undefined"); + } + return result; + } + else { + return fn(previousState, function (draft) { + return caseReducer(draft, action); + }); + } + } + return previousState; + }, state); + } + reducer.getInitialState = getInitialState; + return reducer; +} +// src/createSlice.ts +function getType2(slice, actionKey) { + return slice + "/" + actionKey; +} +function createSlice(options) { + var name = options.name; + if (!name) { + throw new Error("`name` is a required option for createSlice"); + } + if (typeof process !== "undefined" && "undefined" === "development") { + if (options.initialState === void 0) { + console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`"); + } + } + var initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState); + var reducers = options.reducers || {}; + var reducerNames = Object.keys(reducers); + var sliceCaseReducersByName = {}; + var sliceCaseReducersByType = {}; + var actionCreators = {}; + reducerNames.forEach(function (reducerName) { + var maybeReducerWithPrepare = reducers[reducerName]; + var type = getType2(name, reducerName); + var caseReducer; + var prepareCallback; + if ("reducer" in maybeReducerWithPrepare) { + caseReducer = maybeReducerWithPrepare.reducer; + prepareCallback = maybeReducerWithPrepare.prepare; + } + else { + caseReducer = maybeReducerWithPrepare; + } + sliceCaseReducersByName[reducerName] = caseReducer; + sliceCaseReducersByType[type] = caseReducer; + actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type); + }); + function buildReducer() { + var _c = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _d = _c[0], extraReducers = _d === void 0 ? {} : _d, _e = _c[1], actionMatchers = _e === void 0 ? [] : _e, _f = _c[2], defaultCaseReducer = _f === void 0 ? void 0 : _f; + var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType); + return createReducer(initialState, finalCaseReducers, actionMatchers, defaultCaseReducer); + } + var _reducer; + return { + name: name, + reducer: function (state, action) { + if (!_reducer) + _reducer = buildReducer(); + return _reducer(state, action); + }, + actions: actionCreators, + caseReducers: sliceCaseReducersByName, + getInitialState: function () { + if (!_reducer) + _reducer = buildReducer(); + return _reducer.getInitialState(); + } + }; +} +var alm = "listenerMiddleware"; +createAction(alm + "/add"); +createAction(alm + "/removeAll"); +createAction(alm + "/remove"); +// src/index.ts +N(); + +const { actions: todoStoreActions, reducer: todoStoreReducer } = createSlice({ + name: 'todoStore', + initialState: { + todos: {}, + completed: [], + editingTodo: 0 + }, + reducers: { + setTodo: (state, { payload }) => { + state.todos[payload.id] = payload; + }, + removeTodos: (state, { payload }) => { + payload.forEach((id) => ( + delete state.todos[id] + )); + }, + appendCompleted: (state, { payload }) => { + console.log('appendCompleted', payload); + state.completed.push(payload); + }, + removeCompleted: (state, { payload }) => { + state.completed.splice( + state.completed.findIndex((id) => id === payload), + 1 + ); + }, + clearCompleted: (state) => { + state.completed = []; + }, + setEdit: (state, { payload }) => { + state.editingTodo = payload; + }, + leaveEdit: (state) => { + state.editingTodo = 0; + } + } +}); + +const store = configureStore({ + reducer: todoStoreReducer +}); + +const { + setTodo, removeTodos, appendCompleted, removeCompleted, + clearCompleted, setEdit, leaveEdit +} = todoStoreActions; + +const deleteTodo = (id) => { + store.dispatch(removeCompleted(id)); + store.dispatch(removeTodos([id])); +}; + +const deleteCompleted = () => { + const state = store.getState(); + + store.dispatch(removeTodos(state.completed)); + store.dispatch(clearCompleted()); +}; + +const toggleTodos = (items) => { + const state = store.getState(); + items.forEach((id) => { + let todo = state.todos[id]; + let todoState = !todo.completed; + + todoState + ? store.dispatch(appendCompleted(id)) + : store.dispatch(removeCompleted(id)); + + store.dispatch(setTodo({ ...todo, completed: todoState })); + }); +}; + +const markAll = () => { + let state = store.getState(); + let shouldMarkAll = state.completed.length === Object.keys(state.todos).length; + + if (shouldMarkAll) { + const items = Array.from(Object.keys(state.todos)); + return toggleTodos(items) + } + + const filterItems = (acc, item) => + item.completed ? acc : acc.concat(item.id); + + const items = Array.from(Object.values(state.todos)) + .reduce(filterItems, []); + + store.dispatch(toggleTodos(items)); +}; + +const addTodoByText = (text) => { + store.dispatch(setTodo({ + text, + completed: false, + id: Date.now() + })); +}; + +const getTodos = (filter) => { + let { todos } = store.getState(); + console.log(11, store.getState()); + return Object.entries(todos).reduce((prev, [id, todo]) => { + if ( + !filter || + filter === 'all' || + (filter === 'active' && !todo.completed) || + (filter === 'completed' && todo.completed) + ) { + prev[id] = todo; + return prev + } + + return prev + }, {}) +}; + +const baseStyleSheet = [].slice + .call(document.styleSheets) + .find((file) => file.href && file.href.endsWith('todomvc-common/base.css')); +const baseCSSRules = [].slice + .call(baseStyleSheet.cssRules) + .map(({ cssText }) => cssText); + +const appStyleSheet = [].slice + .call(document.styleSheets) + .find((file) => file.href && file.href.endsWith('todomvc-app-css/index.css')); +const appCSSRules = [].slice + .call(appStyleSheet.cssRules) + .map(({ cssText }) => cssText); + +class TodoForm extends s$1 { + static styles = [ + r$3`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => o$5(r)), + ...appCSSRules.map((r) => o$5(r)) + ] + + render () { + return $` +
+ +
+ `; + } + + handleSubmit (event) { + event.preventDefault(); + if (event.target[0].value.length <= 0) { + return + } + + addTodoByText(event.target[0].value); + event.target[0].value = ''; + } +} +customElements.define('todo-form', TodoForm); + +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +const t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i;}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}} + +/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const o=e(class extends i{constructor(t$1){var i;if(super(t$1),t$1.type!==t.ATTRIBUTE||"class"!==t$1.name||(null===(i=t$1.strings)||void 0===i?void 0:i.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(t){return " "+Object.keys(t).filter((i=>t[i])).join(" ")+" "}update(i,[s]){var r,o;if(void 0===this.nt){this.nt=new Set,void 0!==i.strings&&(this.st=new Set(i.strings.join(" ").split(/\s/).filter((t=>""!==t))));for(const t in s)s[t]&&!(null===(r=this.st)||void 0===r?void 0:r.has(t))&&this.nt.add(t);return this.render(s)}const e=i.element.classList;this.nt.forEach((t=>{t in s||(e.remove(t),this.nt.delete(t));}));for(const t in s){const i=!!s[t];i===this.nt.has(t)||(null===(o=this.st)||void 0===o?void 0:o.has(t))||(i?(e.add(t),this.nt.add(t)):(e.remove(t),this.nt.delete(t)));}return b$1}}); + +const ESCAPE_KEY = 27; + +class TodoItem extends connect(store)(s$1) { + static properties = { + todo: { type: Object } + } + + static styles = [ + r$3` + :host(:focus) { box-shadow: none!important; } + .todo-list li:last-child { + border-bottom: 1px solid #ededed!important; + } + `, + ...baseCSSRules.map((r) => o$5(r)), + ...appCSSRules.map((r) => o$5(r)) + ] + + get isEditing () { + const state = store.getState(); + return this.todo.id === state.editingTodo + } + + stateChanged() { + this.requestUpdate(); + } + + beginEdit(event) { + setEdit(this.todo.id); + event.target.closest('li').lastElementChild[0].select(); + } + + finishEdit(event) { + event.preventDefault(); + + const text = event.target[0].value; + setTodo({ ...this.todo, text }); + leaveEdit(); + } + + abortEdit(event) { + event.target.value = this.todo.text; + leaveEdit(); + } + + captureEscape(event) { + if (event.which === ESCAPE_KEY) { + abortEdit(event); + } + } + + render() { + const itemClassList = { + todo: true, + completed: this.todo.completed, + editing: this.isEditing + }; + return $` +
    +
  • +
    + toggleTodos([this.todo.id])} + /> + + +
    +
    + +
    +
  • +
+ ` + } +} +customElements.define('todo-item', TodoItem); + +class TodoList extends s$1 { + static properties = { + todos: { type: Object } + } + + static styles = [ + r$3`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => o$5(r)), + ...appCSSRules.map((r) => o$5(r)) + ] + + render () { + return $` + ${n$1(Object.keys(this.todos).length > 0, () => $` + + ` + )} +
    + ${Object.values(this.todos).map((todo) => $` + + `)} +
+ ` + } +} +customElements.define('todo-list', TodoList); + +function filterLink({ text, filter, selectedFilter }) { + return $`${text}`; +} + +class Footer extends s$1 { + static properties = { + itemsLeft: { type: Number }, + totalItems: { type: Number }, + selectedFilter: { type: String } + } + + static styles = [ + r$3`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => o$5(r)), + ...appCSSRules.map((r) => o$5(r)) + ] + + render () { + return $` +
+ + ${this.itemsLeft} + items left + +
    +
  • + ${filterLink({ + text: 'All', + filter: 'all', + selectedFilter: this.selectedFilter + })} +
  • +
  • + ${filterLink({ + text: 'Active', + filter: 'active', + selectedFilter: this.selectedFilter + })} +
  • +
  • + ${filterLink({ + text: 'Completed', + filter: 'completed', + selectedFilter: this.selectedFilter + })} +
  • +
+ ${n$1(this.totalItems !== this.itemsLeft, () => ( + $` + ` + ))} +
` + } +} +customElements.define('todo-footer', Footer); + +class TodoApp extends connect(store)(s$1) { + static styles = [ + r$3`:host(:focus) { box-shadow: none!important }`, + ...baseCSSRules.map((r) => o$5(r)), + ...appCSSRules.map((r) => o$5(r)) + ] + + static getFilter () { + return location.hash.includes('#/') + ? location.hash.replace('#/', '') + : 'all' + } + + constructor (...args) { + super(...args); + + this.filter = TodoApp.getFilter(); + window.addEventListener('hashchange', () => { + this.filter = TodoApp.getFilter(); + this.requestUpdate(); + }); + } + + stateChanged() { + this.requestUpdate(); + } + + get todos () { + return getTodos(this.filter) + } + + get itemsLeft () { + const state = store.getState(); + console.log('!!', state.todos); + return this.totalItems - state.completed.length + } + + get totalItems () { + const state = store.getState(); + return Object.keys(state.todos).length + } + + render () { + return $` +
+
+

todos

+ +
+
+ +
+ ${n$1(this.totalItems > 0, () => $` + + + `)} +
+ ` + } +} +customElements.define('todo-app', TodoApp); +//# sourceMappingURL=index.js.map diff --git a/examples/lit/package.json b/examples/lit/package.json new file mode 100644 index 0000000000..3c0b12aaa6 --- /dev/null +++ b/examples/lit/package.json @@ -0,0 +1,21 @@ +{ + "private": true, + "type": "module", + "scripts": { + "clean": "rimraf out", + "compile": "rollup -c ./rollup.config.js", + "watch": "npm run clean && npm run compile -- --watch" + }, + "dependencies": { + "@reduxjs/toolkit": "^1.8.3", + "lit": "^2.2.8", + "pwa-helpers": "^0.9.1", + "todomvc-app-css": "^2.4.2", + "todomvc-common": "^1.0.5" + }, + "devDependencies": { + "@rollup/plugin-node-resolve": "^13.3.0", + "@rollup/plugin-replace": "^4.0.0", + "rollup": "^2.77.2" + } +} diff --git a/examples/lit/rollup.config.js b/examples/lit/rollup.config.js new file mode 100644 index 0000000000..5c2f36ccab --- /dev/null +++ b/examples/lit/rollup.config.js @@ -0,0 +1,22 @@ +import replace from '@rollup/plugin-replace' +import resolve from '@rollup/plugin-node-resolve' + +const extensions = ['.js'] + +export default { + input: 'js/index.js', + output: [{ + file: './out/index.js', + format: 'es', + sourcemap: true, + }], + plugins: [ + replace({ + preventAssignment: true, + values: { + 'process.env.NODE_ENV': `"${process.env.NODE_ENV}"` + } + }), + resolve({ extensions }) + ] +} diff --git a/index.html b/index.html index 9bff343ea4..91681bf986 100644 --- a/index.html +++ b/index.html @@ -117,6 +117,9 @@

Examples

  • Marionette.js
  • +
  • + Lit +
  • diff --git a/learn.json b/learn.json index aa64509afe..075de5fa30 100644 --- a/learn.json +++ b/learn.json @@ -1150,6 +1150,46 @@ }] }] }, + "lit": { + "name": "Lit", + "description": "Every Lit component is a native web component, with the superpower of interoperability.", + "homepage": "lit.dev", + "examples": [{ + "name": "Example", + "url": "examples/lit" + }], + "link_groups": [{ + "heading": "Official Resources", + "links": [{ + "name": "Documentation", + "url": "https://lit.dev/docs/" + }, { + "name": "Tutorials", + "url": "https://lit.dev/tutorials/" + }, { + "name": "Live examples", + "url": "https://lit.dev/playground/" + }, { + "name": "Lit Blog", + "url": "https://lit.dev/blog/" + }] + }, { + "heading": "Community", + "links": [{ + "name": "Lit Slack Workspace", + "url": "https://lit.dev/slack-invite/" + }, { + "name": "Twitter", + "url": "https://twitter.com/buildWithLit" + }, { + "name": "GitHub", + "url": "https://github.com/lit/lit/" + }, { + "name": "Stack Overflow", + "url": "https://stackoverflow.com/questions/tagged/lit+or+lit-html+or+lit-element" + }] + }] + }, "marionettejs": { "name": "Backbone.Marionette", "description": "Marionette simplifies your Backbone application code with robust views and architecture solutions.",