Newer
Older
smart-home-server / webclient-vue / src / stores / favorites.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy 8 hours ago 964 bytes Scaffold Vue web client
import { defineStore } from "pinia";

const STORAGE_KEY = "sh_fav_areas";

function readFavorites() {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]").map(String);
  } catch (_) {
    return [];
  }
}

function writeFavorites(ids) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(ids.map(String)));
}

export const useFavoritesStore = defineStore("favorites", {
  state: () => ({
    ids: readFavorites(),
  }),

  actions: {
    has(id) {
      return this.ids.includes(String(id));
    },

    add(id) {
      const nextId = String(id);
      if (!this.ids.includes(nextId)) {
        this.ids.push(nextId);
        writeFavorites(this.ids);
      }
    },

    remove(id) {
      this.ids = this.ids.filter((item) => item !== String(id));
      writeFavorites(this.ids);
    },

    toggle(id) {
      if (this.has(id)) {
        this.remove(id);
        return false;
      }

      this.add(id);
      return true;
    },
  },
});