Initial commit

This commit is contained in:
root committed 2026-04-29 10:03:27 +00:00
commit d1c730a53a
257 files changed
+19025

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
import { skbEndpoint } from "@/shared/api/wp-client";
export const submitContactForm = async (formData: FormData) => {
const response = await fetch(`${skbEndpoint}skbkit/v1/sendcontactform`, {
method: "POST",
body: formData,
});
if (!response.ok) throw new Error("Form submission failed");
return response;
};
@@ -0,0 +1,10 @@
import { useMutation } from "@tanstack/react-query";
import { submitContactForm } from "../api/post";
export const useContactForm = () => {
return useMutation({
mutationFn: submitContactForm,
onSuccess: () => console.log("Форма успешно отправлена"),
onError: (error: Error) => console.error("Ошибка отправки:", error),
});
};
+4
View File
@@ -0,0 +1,4 @@
export { useMedia } from "./media/hooks/useMedia";
export { usePostById } from "./posts/hooks/usePostById";
export { useNews } from "./news/hooks/useNews";
export { useContactForm } from "./contact/hooks/useContactForm";
+63
View File
@@ -0,0 +1,63 @@
import { wp } from "@/shared/api/wp-client";
import { WPv2 } from "@/shared/types/app";
export interface MediaItem {
id: number;
src: string;
category: string;
name: string;
team_name?: string;
team_job?: string;
}
function decodeHtml(html: string) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
return tempDiv.textContent || tempDiv.innerText || '';
}
/**
* Функция для получения всех медиафайлов с учетом пагинации
*/
export const fetchMedia = async (): Promise<MediaItem[]> => {
let page = 1;
let allMedia: MediaItem[] = [];
let hasMore = true;
while (hasMore) {
try {
// Запрашиваем медиа с указанной страницы
const media = (await wp.media().page(page)) as WPv2.MediaWithPaging;
console.log('unfilteredMedia', media);
// Преобразуем данные и добавляем в общий массив
const transformedMedia = media.map(({ id, source_url, alt_text, caption, title }) => {
const [category = "uncategorized", name = "unknown"] =
alt_text?.split("_") || [];
const newItem: MediaItem = { id, src: source_url, category, name };
if (category === "team") {
newItem.team_name = title.rendered;
newItem.team_job = decodeHtml(caption.rendered);
}
return newItem;
});
allMedia = [...allMedia, ...transformedMedia];
if (media._paging.totalPages === page) {
hasMore = false;
break;
}
page++;
} catch (error) {
hasMore = false;
console.error("Ошибка при загрузке медиа:", error);
}
}
console.log("media", allMedia);
return allMedia;
};
+10
View File
@@ -0,0 +1,10 @@
import { fetchMedia } from "@/modules/media/api/get";
import { useQuery } from "@tanstack/react-query";
export const useMedia = () => {
return useQuery({
queryKey: ["media"],
queryFn: fetchMedia,
staleTime: 1000 * 60 * 5, // 5 минут
});
};
+27
View File
@@ -0,0 +1,27 @@
import { skbEndpoint } from "@/shared/api/wp-client";
import { SKBKit } from "@/shared/types/app";
export const fetchNews = async <T = SKBKit.News[]>(params?: {
count?: number;
offset?: number;
}): Promise<SKBKit.ApiResponse<T>> => {
const url = new URL(`${skbEndpoint}skbkit/v1/getnews`);
if (params) {
if (params.count) url.searchParams.set("count", params.count.toString());
if (params.offset) url.searchParams.set("offset", params.offset.toString());
}
const response = await fetch(url.toString());
const data: T = await response.json();
return {
data,
headers: {
"x-wp-total": response.headers.get("x-wp-total") || "0",
"x-wp-totalpages": response.headers.get("x-wp-totalpages") || "0",
},
status: response.status,
statusText: response.statusText,
};
};
+11
View File
@@ -0,0 +1,11 @@
import { fetchNews } from "@/modules/news/api/get";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
export const useNews = (params?: { count?: number; offset?: number }) => {
return useQuery({
queryKey: ["news", params],
queryFn: () => fetchNews(params),
select: (news) => news.data,
placeholderData: keepPreviousData,
});
};
+17
View File
@@ -0,0 +1,17 @@
import { useQuery } from "@tanstack/react-query";
import { skbEndpoint } from "@/shared/api/wp-client";
import { SKBKit } from "@/shared/types/app";
export const fetchNewsById = async (id: string): Promise<SKBKit.News> => {
const response = await fetch(`${skbEndpoint}skbkit/v1/getnewsbyid?id=${id}`);
if (!response.ok) throw new Error("Ошибка при загрузке новости");
const data = await response.json();
return data;
};
export const useNewsById = (id: string) => {
return useQuery<SKBKit.News>({
queryKey: ["news", id],
queryFn: () => fetchNewsById(id),
enabled: !!id,
});
};
@@ -0,0 +1,29 @@
// posts/api/get.ts
import { wp } from "@/shared/api/wp-client";
import { parseContent } from "@/shared/api/parseContent";
import { App, WPv2 } from "@/shared/types/app";
export const fetchPostById = async (id: number): Promise<App.WpPostPage> => {
const [post, categories] = await Promise.all([
wp.posts().id(id).get() as Promise<WPv2.Post>,
wp.categories().get() as Promise<WPv2.Category[]>,
]);
const categoryMap = new Map<number, string>(
categories.map((c) => [c.id, c.name])
);
const postCategories = post.categories.map(
(id) => categoryMap.get(id) || ""
);
const result: App.WpPostPage = {
id: post.id,
title: post.title.rendered,
content: parseContent(post.content.rendered),
tag: post.tags[0],
categories: postCategories,
};
return result;
};
@@ -0,0 +1,49 @@
// posts/api/get/getPostProjects.ts
import { wp } from "@/shared/api/wp-client";
import { fetchMedia } from "@/modules/media/api/get";
import { App, WPv2 } from "@/shared/types/app";
export const fetchPostProjects = async (tag: number): Promise<App.Card[]> => {
const categories = await wp.categories().get() as WPv2.Category[];
const catId = categories.find(item => item.name === "projects")?.id || -1;
const isLabPage = tag !== -1; // Если передали тег, значит, это страница лаборатории
// Одновременно отфильтровать и по тегу, по категории WP не дает
// Если тега нет, проще взять категорию projects
// Если тег есть, надо искать по нему
const postsRequest = wp.posts();
if (isLabPage) {
postsRequest.tags(tag);
} else {
postsRequest.categories(catId);
}
const [posts, mediaLibrary] = await Promise.all([
postsRequest.get() as Promise<WPv2.Post[]>,
fetchMedia(),
]);
// При выборке по тегу подтянется еще и лаборатория, ее нужно убрать из массива
if (isLabPage) {
const labIndex = posts.findIndex((post) => {
return !post.categories.includes(catId);
});
posts.splice(labIndex, 1);
}
const result: App.Card[] = [];
for (const post of posts) {
const image = mediaLibrary.find((item) => item.id === post.featured_media);
const newPost: App.Card = {
id: post.id,
title: post.title.rendered,
preview: image?.src || "",
};
result.push(newPost);
}
return result;
};
+63
View File
@@ -0,0 +1,63 @@
// posts/api/get.ts
import { wp } from "@/shared/api/wp-client";
import { fetchMedia } from "@/modules/media/api/get";
import { App, WPv2 } from "@/shared/types/app";
import Parse from "html-react-parser";
import { parseContent } from "@/shared/api/parseContent";
export const fetchPosts = async (): Promise<App.PostsResult> => {
const [posts, categories, mediaLibrary] = await Promise.all([
wp.posts().param("per_page", 100).get() as Promise<WPv2.Post[]>,
wp.categories().get() as Promise<WPv2.Category[]>,
fetchMedia(),
]);
const categoryMap = new Map<number, string>(
categories.map((c) => [c.id, c.name])
);
const result: App.PostsResult = {
projects: {},
labs: {},
other: [],
};
for (const post of posts) {
const image = mediaLibrary.find((item) => item.id === post.featured_media);
const postCategories = post.categories.map(
(id) => categoryMap.get(id) || ""
);
const newPost: App.WpPost = {
id: post.id,
title: post.title.rendered,
};
if (postCategories.includes("projects")) {
const newProject: App.Card = {
...newPost,
preview: image?.src || "",
};
result.projects[post.id] = newProject;
} else if (postCategories.includes("labs")) {
//@ts-ignore
const excerptElement = Parse(post.excerpt.rendered)[0];
const newLab: App.LabCard = {
...newPost,
preview: image?.src || "",
previewText: (excerptElement as any)?.props?.children || "",
};
result.labs[post.id] = newLab;
} else {
const newWpPostPage: App.WpPostPage = {
...newPost,
content: parseContent(post.content.rendered),
tag: post.tags[0],
categories: postCategories,
};
result.other.push(newWpPostPage);
}
}
return result;
};
+12
View File
@@ -0,0 +1,12 @@
// posts/api/usePostById.ts
import { fetchPostById } from "@/modules/posts/api/get/fetchPostById";
import { useQuery } from "@tanstack/react-query";
import { App } from "@/shared/types/app";
export const usePostById = (id: number) => {
return useQuery<App.WpPostPage>({
queryKey: ["post", id],
queryFn: () => fetchPostById(id),
enabled: !!id,
});
};
@@ -0,0 +1,12 @@
// posts/api/useProjects.ts
import { fetchPostProjects } from "@/modules/posts/api/get/fetchPostProjects";
import { useQuery } from "@tanstack/react-query";
import { App } from "@/shared/types/app";
export const usePostProjects = (tag: number) => {
return useQuery<App.Card[]>({
queryKey: ["projects", tag],
queryFn: () => fetchPostProjects(tag),
enabled: !!tag,
});
};
+12
View File
@@ -0,0 +1,12 @@
// posts/api/usePosts.ts
import { fetchPosts } from "@/modules/posts/api/get/fetchPosts";
import { App } from "@/shared/types/app";
import { useQuery } from "@tanstack/react-query";
export const usePosts = () => {
return useQuery<App.PostsResult>({
queryKey: ["posts"],
queryFn: fetchPosts,
staleTime: 1000 * 60 * 5,
});
};