Source: stores/visited.js

/*
 * Copyright © 2025 The CTAN Team and individual authors
 *
 * This file is distributed under the 3-clause BSD license.
 * See file LICENSE for details.
 */
import { defineStore } from 'pinia'

/**
 * This is the store for recently visited pages of the CTAN portal.
 *
 * @author Gerd Neugebauer <gene@ctan.org>
 */
export const useVisitedStore = defineStore('visited', {
  /**
   * Map describing the recently visited package and pages.
   */
  state: () => ({
    /*
     * @param history the history of previously visited items
     */
    history: undefined,
    /*
     * @param pkg the key of the recently visited package
     */
    pkg: null
  }),

  actions: {
    /**
     * Add the item.
     */
    add (item) {
      if (this.history === undefined) {
        this.init()
      }
      const previous = this.history[item]
      const now = Date.now()
      const epoch = now - 1000 * 60 * 60 * 24 * 14
      
      for (const [key, value] of Object.entries(this.history)) {
        if (value < epoch) {
          delete this.history[key]
        }
      }
      this.history[item] = now
      window.localStorage.setItem('ctan.visited', JSON.stringify(this.history))

      if (item.startsWith('/pkg/')) {
        this.pkg = item.substring(5)
      }
      return previous
    },

    /**
     * Get all history items.
     */
    all () {
      this.init()
      return this.history
    },

    /**
     * Remove all items.
     */
    clear () {
      this.history = {}
      window.localStorage.setItem('ctan.visited', JSON.stringify(this.history))
    },


    /**
     * Load from local storage.
     */
    init () {
      this.history = window.localStorage.getItem('ctan.visited')
        ? JSON.parse(window.localStorage.getItem('ctan.visited'))
        : {}
    },

    /**
     * Check whether an URL has been visited before.
     */
    hasSeen (id) {
      if (this.history === undefined) {
        this.init()
      }
      return this.history[id]
    },

    /**
     * Remove a item.
     */
    remove (id) {
      if (this.history === undefined) {
        this.init()
      }

      for (const [key, value] of Object.entries(this.history)) {
        if (key === id) {
          delete this.history[key]
        }
      }
      window.localStorage.setItem('ctan.visited', JSON.stringify(this.history))
    }
  }
})