Viewing File: /home/maglabs/marco/wp-content/plugins/extendify/src/Assist/state/KnowledgeBase.js

import apiFetch from '@wordpress/api-fetch';
import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';

const path = '/extendify/v1/assist/support-articles-data';
const storage = {
	getItem: async () => await apiFetch({ path }),
	setItem: async (_name, state) =>
		await apiFetch({ path, method: 'POST', data: { state } }),
};

const key = 'extendify-assist-knowledge-base';
const startingState = {
	articles: [],
	recentArticles: [],
	viewedArticles: [],
	activeCategory: null,
	searchTerm: '',
	// initialize the state with default values
	...((window.extAssistData.userData.supportArticlesData?.data || {})?.state ??
		{}),
};

const state = (set) => ({
	...startingState,
	pushArticle(article) {
		const { slug, title } = article;
		set((state) => {
			const lastViewedAt = new Date().toISOString();
			const firstViewedAt = lastViewedAt;
			const viewed = state.viewedArticles.find((a) => a.slug === slug);

			return {
				articles: [article, ...state.articles],
				recentArticles: [article, ...state.recentArticles.slice(0, 9)],
				viewedArticles: [
					// Remove the article if it's already in the list
					...state.viewedArticles.filter((a) => a.slug !== slug),
					// Either add the article or update the count
					viewed
						? { ...viewed, count: viewed.count + 1, lastViewedAt }
						: {
								slug,
								title,
								firstViewedAt,
								lastViewedAt,
								count: 1,
						  },
				],
			};
		});
	},
	popArticle() {
		set((state) => ({ articles: state.articles.slice(1) }));
	},
	clearArticles() {
		set({ articles: [] });
	},
	setActiveCategory(slug) {
		set({ activeCategory: slug });
	},
	reset() {
		set({ articles: [], activeCategory: null, searchTerm: '' });
	},
	updateTitle(slug, title) {
		// We don't always know the title until after we fetch the article data
		set((state) => ({
			articles: state.articles.map((article) => {
				if (article.slug === slug) {
					article.title = title;
				}
				return article;
			}),
		}));
	},
	clearSearchTerm() {
		set({ searchTerm: '' });
	},
	setSearchTerm(term) {
		set({ searchTerm: term });
	},
});

export const useKnowledgeBaseStore = create(
	persist(devtools(state, { name: 'Extendify Assist Knowledge Base' }), {
		name: key,
		storage: createJSONStorage(() => storage),
		skipHydration: true,
		partialize: (state) => {
			delete state.articles;
			delete state.activeCategory;
			delete state.searchTerm;
			return state;
		},
	}),
);
Back to Directory File Manager