Skip to content
Snippets Groups Projects
projects.js 1.28 KiB
import { writable } from 'svelte/store';

//TODO project url and so
function getStoredProjects() {
  if (typeof window !== 'undefined') { 
    const storedProjects = localStorage.getItem('userProjects');
    return storedProjects ? JSON.parse(storedProjects) : [];
  }
  return [];
}

const initialProjects = getStoredProjects();

export const userProjects = writable(initialProjects);

if (typeof window !== 'undefined') {
  userProjects.subscribe(projects => {
    localStorage.setItem('userProjects', JSON.stringify(projects));
  });
}


/**
 * @param {string} name 
 */
export function addProject(name) {
  userProjects.update(projects => {
    const maxId = projects.reduce((/** @type {number} */ max, /** @type {{ id: number; }} */ project) => project.id > max ? project.id : max, 0);
    const newProject = { id: maxId + 1, name };

    return [...projects, newProject];
  });
}

/**
 * @param {string} name 
 */
export function removeProject(name) {
  userProjects.update(projects => {
    return projects.filter((/** @type {{ name: string; }} */ project) => project.name !== name);
  });
}

/**
 * @param {number} id 
 */
export function removeProjectbyId(id) {
  userProjects.update(projects => {
    return projects.filter((/** @type {{ id: number; }} */ project) => project.id !== id);
  });
}