it-tools/src/tools/tools.store.ts

64 lines
2.1 KiB
TypeScript
Raw Normal View History

import { type MaybeRef, get, useStorage } from '@vueuse/core';
import { defineStore } from 'pinia';
import type { Ref } from 'vue';
2023-11-01 15:38:19 +01:00
import _ from 'lodash';
import type { Tool, ToolCategory, ToolWithCategory } from './tools.types';
import { toolsWithCategory } from './index';
2023-11-01 15:38:19 +01:00
export const useToolStore = defineStore('tools', () => {
const favoriteToolsName = useStorage('favoriteToolsName', []) as Ref<string[]>;
const { t } = useI18n();
2023-11-01 15:38:19 +01:00
const tools = computed<ToolWithCategory[]>(() => toolsWithCategory.map((tool) => {
const toolI18nKey = tool.path.replace(/\//g, '');
2023-11-01 15:38:19 +01:00
return ({
...tool,
path: tool.path,
2023-11-01 15:38:19 +01:00
name: t(`tools.${toolI18nKey}.title`, tool.name),
description: t(`tools.${toolI18nKey}.description`, tool.description),
category: t(`tools.categories.${tool.category.toLowerCase()}`, tool.category),
});
}));
2023-11-01 15:38:19 +01:00
const toolsByCategory = computed<ToolCategory[]>(() => {
return _.chain(tools.value)
.groupBy('category')
.map((components, name, path) => ({
2023-11-01 15:38:19 +01:00
name,
path,
2023-11-01 15:38:19 +01:00
components,
}))
.value();
});
const favoriteTools = computed(() => {
return favoriteToolsName.value
.map(favoriteName => tools.value.find(({ name, path }) => name === favoriteName || path === favoriteName))
2023-11-01 15:38:19 +01:00
.filter(Boolean) as ToolWithCategory[]; // cast because .filter(Boolean) does not remove undefined from type
});
return {
tools,
favoriteTools,
toolsByCategory,
newTools: computed(() => tools.value.filter(({ isNew }) => isNew)),
addToolToFavorites({ tool }: { tool: MaybeRef<Tool> }) {
const toolPath = get(tool).path;
if (toolPath) {
favoriteToolsName.value.push(toolPath);
}
},
removeToolFromFavorites({ tool }: { tool: MaybeRef<Tool> }) {
favoriteToolsName.value = favoriteToolsName.value.filter(name => get(tool).name !== name && get(tool).path !== name);
},
isToolFavorite({ tool }: { tool: MaybeRef<Tool> }) {
return favoriteToolsName.value.includes(get(tool).name)
|| favoriteToolsName.value.includes(get(tool).path);
},
2023-11-01 15:38:19 +01:00
};
});