all repos — h3 @ 9f72a6511e88ebaaa0c5ba1a5d04baff0d788990

A tiny, extremely minimalist JavaScript microframework.

example/assets/js/modules.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
const app = (store) => {
  store.on("app/load", () => {
    const storedData = localStorage.getItem("h3_todo_list");
    const { todos, settings } = storedData ? JSON.parse(storedData) : {todos: [], settings: {}};
    return { todos, settings };
  });
  store.on("app/save", (state, data) => {
    localStorage.setItem(
      "h3_todo_list",
      JSON.stringify({ todos: state.todos, settings: state.settings })
    );
  });
};

const settings = (store) => {
  let removeSubscription;
  store.on("$init", () => ({ settings: {} }));
  store.on("settings/set", (state, data) => {
    if (data.logging) {
      removeSubscription = store.on("$log", (state, data) => console.log(data));
    } else {
      removeSubscription && removeSubscription();
    }
    return { settings: data };
  });
};

const todos = (store) => {
  store.on("$init", () => ({ todos: [], filteredTodos: [], filter: "" }));
  store.on("todos/add", (state, data) => {
    let todos = state.todos;
    todos.unshift({
      key: data.key,
      text: data.text,
    });
    return { todos };
  });
  store.on("todos/remove", (state, data) => {
    const todos = state.todos.filter(({ key }) => key !== data.key);
    return { todos };
  });
  store.on("todos/toggle", (state, data) => {
    const todos = state.todos;
    const todo = state.todos.find((t) => t.key === data.key);
    todo.done = !todo.done;
    return { todos };
  });
  store.on("todos/filter", (state, filter) => {
    const todos = state.todos;
    const filteredTodos = todos.filter(({ text }) => text.match(filter));
    return { filteredTodos, filter };
  });
};

const error = (store) => {
  store.on("$init", () => ({ displayEmptyTodoError: false }));
  store.on("error/clear", (state) => ({ displayEmptyTodoError: false }));
  store.on("error/set", (state) => ({ displayEmptyTodoError: true }));
};

const pages = (store) => {
  store.on("$init", () => ({ pagesize: 10, page: 1 }));
  store.on("pages/set", (state, page) => ({ page }));
};

export default [app, todos, error, pages, settings];