chore: init monorepo

This commit is contained in:
2025-06-21 12:42:09 +03:00
commit 1874ae3ac1
103 changed files with 23946 additions and 0 deletions
+115
View File
@@ -0,0 +1,115 @@
import { Routes, Route, useNavigate, useLocation } from "react-router";
//
import MainPage from "./pages/MainPage";
import SearchPage from "./pages/SearchPage";
import PageBody from "./pages/PageBody";
import BookPage from "./pages/BookPage";
import AccountPage from "./pages/account/AccountPage";
import AuthPage from "./pages/AuthPage";
//
import {
argbFromHex,
themeFromSourceColor,
applyTheme,
} from "@material/material-color-utilities";
import axios from "axios";
import { useEffect, useState } from "react";
import Reader from "./pages/Reader";
import Offline from "./pages/Offline";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import NotFound from "./pages/NotFound";
import Collections from "./pages/account/Collections";
import Main from "./pages/account/Main";
import CollectionPage from "./pages/account/CollectionPage";
import OOBE from "./pages/OOBE/OOBE";
import OOBEWelcome from "./pages/OOBE/OOBEWelcome";
import OOBECreateUser from "./pages/OOBE/OOBECreateUser";
import UploadBook from "./pages/account/UploadBook";
import ShelvePage from "./pages/account/ShelvePage";
const PWAPage = () => {
const navigate = useNavigate();
useEffect(() => {
let lastReadBook = localStorage.getItem("lastReadBook");
if (lastReadBook !== null) {
navigate(`/reader/${lastReadBook}`);
} else {
navigate("/account");
}
});
return <></>;
};
function App() {
const [checked, setChecked] = useState(false);
const theme = themeFromSourceColor(argbFromHex("ffddaf"));
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
applyTheme(theme, { target: document.body, dark: systemDark });
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
axios
.get("/ping", { timeout: 5000 })
.then(() => {
window.onLine = true;
setChecked(true);
})
.catch((error) => {
if (error.response === undefined) {
window.onLine = false;
} else {
if (error.response.status === 401) {
window.onLine = true;
if (
location.pathname !== "/login" &&
!location.pathname.startsWith("/oobe")
) {
console.log("redir");
navigate(`/login?to=${location.pathname}`);
}
} else {
window.onLine = false;
}
}
setChecked(true);
});
}, []);
if (!checked) {
return <span>проверка соединения с сервером...</span>;
}
return (
<>
<ToastContainer theme={systemDark ? "dark" : "light"} autoClose={2000} />
<Routes>
<Route path="/login" element={<AuthPage />} />
<Route path="/pwa" element={<PWAPage />} />
<Route path="/oobe" element={<OOBE />}>
<Route index element={<OOBEWelcome />} />
<Route path="create-user" element={<OOBECreateUser />} />
</Route>
{/*<Route index element={<MainPage/>} />*/}
<Route element={<PageBody />}>
<Route path="/" element={<AccountPage />}>
<Route index element={<Main />} />
<Route path="collections" element={<Collections />} />
<Route path="collection/:id" element={<CollectionPage />} />
<Route path="shelve" element={<ShelvePage />} />
<Route path="settings" element={<p>404</p>} />
<Route path="upload" element={<UploadBook />} />
</Route>
<Route path="/search" element={<SearchPage />} />
<Route path="/book/:id" element={<BookPage />} />
<Route path="/reader/:id" element={<Reader />} />
<Route path="/offline" element={<Offline />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</>
);
}
export default App;
+87
View File
@@ -0,0 +1,87 @@
import axios from "axios";
import { useEffect, useState } from "react";
import BookCard from "./bookCard/BookCard";
import LinearProgress from "../md-components/LinearProgress";
import IconButton from "../md-components/IconButton";
import Icon from "../md-components/Icon";
const Pagination = ({ offset, setOffset, perPage, total }) => {
return (
<div
style={{
display: "flex",
alignItems: "center",
gap: "10px",
width: "100%",
justifyContent: "center",
}}
>
<IconButton
disabled={offset - perPage < 0}
onClick={() => setOffset((prev) => prev - perPage)}
>
<Icon>arrow_back</Icon>
</IconButton>
<span>
{total > 0 ? offset + 1 : 0}-
{offset + perPage > total ? total : offset + perPage}
{" из " /* если убрать ковычки - не будет пробеловё*/}
{total}
</span>
<IconButton
disabled={offset + perPage + 1 > total}
onClick={() => setOffset((prev) => prev + perPage)}
>
<Icon>arrow_forward</Icon>
</IconButton>
</div>
);
};
const SearchResults = ({ query, author, collection }) => {
const [searchResults, setSearchResults] = useState(false);
const [offset, setOffset] = useState(0);
useEffect(() => {
setSearchResults(false);
axios
.get("/search", {
params: {
q: query,
author: author,
collection: collection,
offset: offset,
limit: 8,
},
})
.then((res) => setSearchResults(res.data));
}, [offset]);
if (!searchResults) {
return <LinearProgress indeterminate style={{ width: "100%" }} />;
}
if (searchResults.count === 0) {
return <p style={{ marginLeft: 20 }}>ничего не найдено</p>;
}
return (
<>
<div className="results_container">
{searchResults.books.map((book) => (
<BookCard
key={book.id}
id={book.id}
title={book.title}
authors={book.authors}
filetype={book.filetype}
/>
))}
</div>
<Pagination
offset={offset}
setOffset={setOffset}
perPage={10}
total={searchResults.count}
/>
</>
);
};
export default SearchResults;
@@ -0,0 +1,174 @@
import "./bookCard.css";
import axios from "axios";
import Skeleton from "react-loading-skeleton";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import IconButton from "../../md-components/IconButton";
import Icon from "../../md-components/Icon";
function personToString(person) {
let tmpString;
if (person.lastName) {
tmpString = person.lastName;
} else {
tmpString = person.firstName;
}
if (person.middleName) {
tmpString += " " + person.middleName[0] + ".";
}
if (person.lastName && person.firstName) {
tmpString += " " + person.firstName[0] + ".";
}
return tmpString;
}
function authorsString(authors) {
let authorsStr = authors
.slice(0, 2)
.map((author) => personToString(author))
.join(", ");
if (authors.length > 2) {
authorsStr += " и др.";
}
return authorsStr;
}
const BookCard = ({
id,
title,
authors,
reader,
offline,
fromSearch,
collectionDelId,
fixed,
filetype,
}) => {
const [loaded, setLoaded] = useState(false);
const [bookImgSrc, setBookImgSrc] = useState("");
async function loadImgFromCache() {
if (window.caches === undefined) {
setBookImgSrc(axios.defaults.baseURL + "/book/" + id + "/cover");
return;
}
let cache = await window.caches.open("bookCovers");
let img = await cache.match(`/api/book/${id}/cover`);
if (img === undefined) {
if (window.onLine) {
setBookImgSrc(axios.defaults.baseURL + "/book/" + id + "/cover");
return;
} else {
setBookImgSrc("/favicon.png");
return;
}
}
let blob = await img.blob();
setBookImgSrc(URL.createObjectURL(blob));
}
useEffect(() => {
loadImgFromCache();
}, []);
return (
<Link
className={"book_card" + (fixed ? " fixed" : "")}
to={
!offline && !window.onLine
? false
: reader === undefined
? `/book/${id}${fromSearch ? "?from_search=" + fromSearch : ""}`
: `/reader/${id}`
}
style={{
color: "black",
textDecoration: "none",
}}
>
{!offline && !window.onLine ? (
<div className="book_card_deactivate"></div>
) : (
<md-ripple></md-ripple>
)}
<div
style={{
width: "100%",
overflow: "hidden",
backgroundImage: "url(" + bookImgSrc + ")",
backgroundSize: "100%",
}}
className="book_card_image"
>
<div
style={{
position: "absolute",
left: 5,
top: 5,
zIndex: 1,
background: "var(--md-sys-color-inverse-primary)",
padding: 5,
borderRadius: 10,
}}
>
<b>{filetype}</b>
</div>
{/* {
collectionDelId ?
<div className="book_actions">
<IconButton onClick={() => {
axios.post("/collection/"+collectionDelId, {book_id: String(id)})
}}>
<Icon>delete</Icon>
</IconButton>
</div> : <></>
} */}
<div
style={{
display: "flex",
alignItems: "center",
height: "100%",
backdropFilter: "blur(5px)",
}}
>
{loaded ? (
<></>
) : (
<Skeleton
style={{
width: 240,
height: 380,
lineHeight: "revert",
}}
/>
)}
<img
onLoad={() => setLoaded(true)}
style={{
pointerEvents: "none",
boxShadow: "0px 0px 20px gray",
width: "100%",
}}
src={bookImgSrc}
/>
</div>
</div>
<div
style={{
padding: "10px 0px",
}}
>
<span className="h-fit line-clamp-2 break-words">
<b>{title}</b>
</span>
<span
style={{
color: "gray",
}}
>
{authorsString(authors)}
</span>
</div>
</Link>
);
};
export default BookCard;
@@ -0,0 +1,63 @@
.book_card {
display: flex;
border-radius: 17px;
/* border: 2px solid var(--md-sys-color-outline); */
overflow: hidden;
flex-direction: column;
width: 180px;
position: relative;
user-select: none;
cursor: pointer;
padding: 10px 10px 0 10px;
}
.book_card_deactivate {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
z-index: 1;
cursor: not-allowed;
}
md-ripple {
z-index: 2;
}
.book_card_image {
height: 280px;
border-radius: 12px;
position: relative;
}
.book_actions {
position: absolute;
height: 100%;
width: 100%;
justify-content: center;
align-items: center;
z-index: 2;
opacity: 0;
display: flex;
transition: all 0.1s;
}
.book_actions:hover {
opacity: 1;
/* background: #ffffff55; */
}
@media screen and (max-width: 120px) {
.book_card:not(.fixed) {
width: calc(33% - 9px);
}
}
@media screen and (max-width: 500px) {
.book_card:not(.fixed) {
width: calc(50% - 25px);
}
.book_card_image:not(.fixed) {
height: 260px;
}
}
@media screen and (max-width: 450px) {
.book_card {
font-size: 14px;
}
}
@@ -0,0 +1,74 @@
import Skeleton from 'react-loading-skeleton'
import "./contents.css"
const Contents = ({data, readerRef, readerHeight, currentPage, setCurrentPage}) => {
const Chapter = ({title, id, subId}) => {
if (!readerRef.current) return
let totalSections = readerRef.current.getElementsByTagName("section")
if (totalSections[id] === undefined) return
let anchorOffset = totalSections[id].offsetTop
let nextAnchorOffset
if (totalSections[id+1] != undefined) {
nextAnchorOffset = totalSections[id+1].offsetTop
}
let anchorPage = Math.ceil(anchorOffset / readerHeight)
let nextAnchorPage
if (nextAnchorOffset) {
nextAnchorPage = Math.ceil(nextAnchorOffset / readerHeight)
}
return <div
className={subId !== undefined ? "contents__chapter sub" : "contents__chapter"}
onClick={() => {
setCurrentPage(anchorPage)
}}
style={{
backgroundColor: currentPage >= anchorPage && currentPage < nextAnchorPage || currentPage == anchorPage ? "var(--md-sys-color-primary-container)" : ""
}}
>
<md-ripple></md-ripple>
{title}
</div>
}
if (!readerRef.current || readerRef.current.getElementsByTagName("section").length === 0) {
return <div className="contents">
<span className="contents__scroll">
<div className="contents__chapter" style={{background: "var(--md-sys-color-primary-container)"}}>
<md-ripple></md-ripple>
<Skeleton width={200}/>
</div>
<div className="contents__chapter">
<md-ripple></md-ripple>
<Skeleton width={130}/>
</div>
<div className="contents__chapter">
<md-ripple></md-ripple>
<Skeleton width={180}/>
</div>
</span>
</div>
}
let anchors = data.map(chapter => {
let chapters = []
if (chapter.title === "") return false
chapters.push(<Chapter title={chapter.title} id={chapter.id} key={chapter.id}/>)
if (chapter.subChapters) {
chapter.subChapters.map(subchapter => {
if (subchapter.title === "") return false
chapters.push(<Chapter title={subchapter.title} id={subchapter.id} subId={subchapter.id} key={subchapter.id}/>)
})
}
return chapters
}).filter(val => val !== false)
if (anchors.length === 0) {
return <></>
}
return <div className="contents">
<span className="contents__scroll">
{
anchors
}
</span>
</div>
}
export default Contents
@@ -0,0 +1,30 @@
.contents {
width: fit-content;
height: calc(100vh - 60px);
overflow: hidden;
}
.contents__scroll {
display: block;
height: calc(100vh - 80px);
overflow-x: hidden;
padding: 10px;
}
.contents__chapter {
border-radius: 15px;
/*height: 50px;*/
width: 220px;
position: relative;
display: flex;
align-items: center;
user-select: none;
padding-left: 20px;
margin: 5px;
cursor: pointer;
padding: 15px;
}
.contents__chapter.sub {
width: 205px;
padding-left: 20px;
margin-left: 20px;
}
+281
View File
@@ -0,0 +1,281 @@
const curVersion = 1
export function initDB() {
return new Promise(resolve => {
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onupgradeneeded = () => {
console.log("init db!")
let db = openRequest.result;
if (!db.objectStoreNames.contains('books')) {
db.createObjectStore('books', {keyPath: 'id'});
}
if (!db.objectStoreNames.contains('reader')) {
db.createObjectStore('reader', {keyPath: 'id'});
}
resolve(true)
};
openRequest.onsuccess = () => {
resolve(true)
}
})
}
export function addBook(id, bookInfo, contents) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("books", "readwrite")
let books = transaction.objectStore("books")
books.add({
id: id,
...bookInfo,
contents: contents
})
resolve(true)
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function removeBook(id) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("books", "readwrite")
let books = transaction.objectStore("books")
books.delete(id)
resolve(true)
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function getBook(id) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("books")
let books = transaction.objectStore("books")
let req = books.get(id)
req.onsuccess = () => {
if (req.result !== undefined) {
resolve(req.result)
} else {
resolve(undefined)
}
};
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function getAllBooks() {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("books")
let books = transaction.objectStore("books")
let req = books.getAll()
req.onsuccess = () => {
if (req.result !== undefined) {
resolve(req.result)
} else {
resolve(undefined)
}
};
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function getAllReadBooks() {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader")
let reader = transaction.objectStore("reader")
let req = reader.getAll()
req.onsuccess = () => {
if (req.result !== undefined) {
resolve(req.result)
} else {
resolve(undefined)
}
};
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function getReadBook(id) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader")
let reader = transaction.objectStore("reader")
let req = reader.get(id)
req.onsuccess = () => {
if (req.result !== undefined) {
resolve(req.result)
} else {
resolve(undefined)
}
};
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function updateReadBook(id, progress) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader", "readwrite")
let reader = transaction.objectStore("reader")
let prev = reader.get(id)
prev.onsuccess = () => {
reader.put({
id: id,
...prev.result,
progress: progress,
lastRead: Math.floor(Date.now() / 1000)
})
resolve(true)
}
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function putReadBook(id, onBookshelf, bookInfo) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader", "readwrite")
let reader = transaction.objectStore("reader")
let prev = reader.get(id)
prev.onsuccess = () => {
reader.put({
id: id,
...prev.result,
onBookshelf: onBookshelf,
bookInfo: onBookshelf ? {
title: bookInfo.title,
authors: bookInfo.authors,
} : {}
})
resolve(true)
}
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function saveReadBook(id, offline) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader", "readwrite")
let reader = transaction.objectStore("reader")
let prev = reader.get(id)
prev.onsuccess = () => {
reader.put({
id: id,
...prev.result,
offline: offline,
})
resolve(true)
}
};
openRequest.onerror = () => {
resolve(false)
}
})
}
export function syncReadBook(syncData) {
return new Promise(async resolve => {
await initDB()
let openRequest = indexedDB.open("YaBL", curVersion);
openRequest.onsuccess = () => {
let db = openRequest.result;
db.onversionchange = () => {
db.close();
alert("База данных устарела, пожалуйста, перезагрузите страницу.")
};
let transaction = db.transaction("reader", "readwrite")
let reader = transaction.objectStore("reader")
reader.clear()
if (syncData === null) {resolve(true); return}
for (let book of syncData) {
reader.add(book)
}
resolve(true)
};
openRequest.onerror = () => {
resolve(false)
}
})
}
+72
View File
@@ -0,0 +1,72 @@
:root {
--md-sys-color-primary: olive;
--md-sys-color-secondary: tomato;
--md-ref-typeface-brand: "MiSans Regular";
--md-ref-typeface-plain: "MiSans Regular";
font-family: "MiSans Regular";
}
md-icon {
--md-icon-font: "Material Symbols Rounded";
font-variation-settings: "FILL" 1, "wght" 400, "GRAD" 0, "opsz" 24;
}
@font-face {
font-family: "Material Symbols Rounded";
font-style: normal;
font-weight: 400;
src: url(/material-icons-rounded.woff2) format("woff2");
font-display: swap;
}
@font-face {
font-display: swap;
font-family: "MiSans Regular";
font-style: normal;
font-weight: 400;
src: url(/moscowsansregular.woff2) format("woff2");
}
body {
margin: 0;
background: var(--md-sys-color-background);
--md-sys-color-surface-container-high: var(--md-sys-color-surface-variant);
--md-sys-color-surface-container-highest: var(--md-sys-color-surface-variant);
--md-sys-color-surface-container: var(--md-sys-color-surface-variant);
}
span,
p,
td,
h1,
h2,
h3,
b,
v,
cite,
/* md-icon, */
input {
color: var(--md-sys-color-on-background);
}
#root {
min-height: 100vh;
}
@font-face {
font-family: "Material Symbols Rounded Filled";
font-style: normal;
font-weight: 400;
src: url(/material-icons-filled.woff) format("woff");
}
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background-color: rgba(155, 155, 155);
border-radius: 20px;
border: transparent;
}
@layer theme, base, components, utilities;
@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/utilities.css" layer(utilities);
+18
View File
@@ -0,0 +1,18 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import "react-loading-skeleton/dist/skeleton.css";
import { BrowserRouter } from "react-router-dom";
import axios from "axios";
import { registerSW } from "virtual:pwa-register";
registerSW({ immediate: true });
axios.defaults.baseURL = "/api";
ReactDOM.createRoot(document.getElementById("root")).render(
<BrowserRouter>
<App />
</BrowserRouter>
);
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdAssistChip } from "@material/web/chips/assist-chip";
const AssistChip = createComponent({
tagName: "md-assist-chip",
elementClass: MdAssistChip,
react: React,
events: {
onClick: "click"
}
});
export default AssistChip
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdChipSet } from "@material/web/chips/chip-set";
const ChipSet = createComponent({
tagName: "md-chip-set",
elementClass: MdChipSet,
react: React,
events: {
onClick: "click"
}
});
export default ChipSet
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdIconButton } from "@material/web/iconbutton/icon-button";
const DefaultIconButton = createComponent({
tagName: "md-icon-button",
elementClass: MdIconButton,
react: React,
events: {
onClick: "click"
}
});
export default DefaultIconButton
+15
View File
@@ -0,0 +1,15 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdDialog } from "@material/web/dialog/dialog";
const Dialog = createComponent({
tagName: "md-dialog",
elementClass: MdDialog,
react: React,
events: {
onClick: "click",
onClose: "close"
}
});
export default Dialog
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdFilledButton } from "@material/web/button/filled-button";
const FilledButton = createComponent({
tagName: "md-filled-button",
elementClass: MdFilledButton,
react: React,
events: {
onClick: "click"
}
});
export default FilledButton
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdIcon } from "@material/web/icon/icon";
const Icon = createComponent({
tagName: "md-icon",
elementClass: MdIcon,
react: React,
events: {
onClick: "click"
}
});
export default Icon
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdFilledTonalIconButton } from "@material/web/iconbutton/filled-tonal-icon-button";
const IconButton = createComponent({
tagName: "md-filled-tonal-icon-button",
elementClass: MdFilledTonalIconButton,
react: React,
events: {
onClick: "click"
}
});
export default IconButton
+15
View File
@@ -0,0 +1,15 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdInputChip } from "@material/web/chips/input-chip";
const InputChip = createComponent({
tagName: "md-input-chip",
elementClass: MdInputChip,
react: React,
events: {
onClick: "click",
onRemove: "remove"
}
});
export default InputChip
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdLinearProgress } from "@material/web/progress/linear-progress";
const LinearProgress = createComponent({
tagName: "md-linear-progress",
elementClass: MdLinearProgress,
react: React,
events: {
onClick: "click"
}
});
export default LinearProgress
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdList } from "@material/web/list/list";
const List = createComponent({
tagName: "md-list",
elementClass: MdList,
react: React,
events: {
onClick: "click"
}
});
export default List
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdListItem } from "@material/web/list/list-item";
const ListItem = createComponent({
tagName: "md-list-item",
elementClass: MdListItem,
react: React,
events: {
onClick: "click"
}
});
export default ListItem
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdMenu } from "@material/web/menu/menu";
const Menu = createComponent({
tagName: "md-menu",
elementClass: MdMenu,
react: React,
events: {
onClick: "click"
}
});
export default Menu
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdMenuItem } from "@material/web/menu/menu-item";
const MenuItem = createComponent({
tagName: "md-menu-item",
elementClass: MdMenuItem,
react: React,
events: {
onClick: "click"
}
});
export default MenuItem
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdOutlinedButton } from "@material/web/button/outlined-button";
const OutlinedButton = createComponent({
tagName: "md-outlined-button",
elementClass: MdOutlinedButton,
react: React,
events: {
onClick: "click"
}
});
export default OutlinedButton
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdOutlinedIconButton } from "@material/web/iconbutton/outlined-icon-button";
const OutlinedIconButton = createComponent({
tagName: "md-outlined-icon-button",
elementClass: MdOutlinedIconButton,
react: React,
events: {
onClick: "click"
}
});
export default OutlinedIconButton
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdPrimaryTab } from "@material/web/tabs/primary-tab";
const PrimaryTab = createComponent({
tagName: "md-primary-tab",
elementClass: MdPrimaryTab,
react: React,
events: {
onClick: "click"
}
});
export default PrimaryTab
+15
View File
@@ -0,0 +1,15 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdTabs } from "@material/web/tabs/tabs";
const Tabs = createComponent({
tagName: "md-tabs",
elementClass: MdTabs,
react: React,
events: {
onClick: "click",
onChange: "change"
}
});
export default Tabs
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdTextButton } from "@material/web/button/text-button";
const TextButton = createComponent({
tagName: "md-text-button",
elementClass: MdTextButton,
react: React,
events: {
onClick: "click"
}
});
export default TextButton
+14
View File
@@ -0,0 +1,14 @@
import React from "react";
import { createComponent } from "@lit/react";
import { MdOutlinedTextField } from "@material/web/textfield/outlined-text-field";
const TextField = createComponent({
tagName: "md-outlined-text-field",
elementClass: MdOutlinedTextField,
react: React,
events: {
onClick: "click"
}
});
export default TextField
+88
View File
@@ -0,0 +1,88 @@
import { useRef, useState } from "react"
import FilledButton from "../md-components/FilledButton"
import TextField from "../md-components/TextField"
import axios from "axios"
import { useNavigate } from "react-router"
import { toast } from "react-toastify"
import { useSearchParams } from "react-router-dom"
const AuthPage = () => {
const widthStyle = {width: "100%"}
const [login, setLogin] = useState("")
const [password, setPassword] = useState("")
const submitRef = useRef()
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const [searchParams] = useSearchParams()
function makeLogin() {
if (loading) return
setLoading(true)
axios.post("/auth", {login: login, password: password})
.then(() => {
axios.get("/user")
.then(res => {localStorage.setItem("userInfo", JSON.stringify(res.data))})
if (searchParams.get("to") !== null) {
navigate(searchParams.get("to"))
} else {
navigate("/")
}
})
.catch(() => {toast.error("Неверный логин или пароль!");setLoading(false)})
}
function handleSubmit(e) {
if(e.key==="Enter"){
submitRef.current.click()
}
}
return <div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
minHeight: "100vh",
flexDirection: "column",
gap: "15px",
margin: "0 15px"
}}>
<h2>Вход</h2>
<form onSubmit={(e) => {e.preventDefault();makeLogin()}}
id="form-id"
style={{
display: "flex",
flexDirection: "column",
gap: "15px",
width: "100%",
maxWidth: "400px",
alignItems: "center",
}}>
<TextField
style={widthStyle}
label="Логин"
required
onInput={e => setLogin(e.target.value.toLowerCase())}
value={login}
onKeyDown={handleSubmit}
disabled={loading}
/>
<TextField
style={widthStyle}
label="Пароль"
required
type="password"
onInput={e => setPassword(e.target.value)}
value={password}
onKeyDown={handleSubmit}
disable={loading}
/>
<FilledButton
type="submit"
style={widthStyle}
ref={submitRef}
disabled={loading}
>Войти</FilledButton>
</form>
</div>
}
export default AuthPage
+76
View File
@@ -0,0 +1,76 @@
.book_container {
display: flex;
justify-content: center;
gap: 40px;
margin-top: 20px;
}
.book_cover {
border-radius: 25px;
max-width: 400px;
align-self: flex-start;
object-fit: contain;
}
.book_info {
display: flex;
flex-direction: column;
max-width: 580px;
width: 100%;
}
.buttons_container {
display: flex;
gap: 25px;
margin: 20px 0;
}
.action_button {
flex-basis: 33%;
}
.info_table td:last-child {
font-weight: bold;
}
.m3infoTable h3 {
font-size: 14px;
margin: 0;
/* font-family: monospace; */
/* font-weight: bolder; */
}
.m3infoTable span {
display: block;
font-family: monospace;
margin-bottom: 5px;
font-size: 18px;
}
@media screen and (max-width: calc(640px + 400px)) { /* мини картинка */
.book_cover {
max-width: 200px;
}
}
@media screen and (max-width: calc(640px + 200px)) { /* телефонный вид */
.book_cover {
max-width: calc(100% - 15px);
max-height: 300px;
align-self: center;
}
.book_container {
flex-direction: column;
}
.book_info {
max-width: 100%;
}
}
@media screen and (max-width: 600px) { /* кнопки в столбик */
.buttons_container {
flex-direction: column;
gap: 10px;
}
.action_button {
flex-basis: auto;
}
}
+464
View File
@@ -0,0 +1,464 @@
import { useNavigate, useParams } from "react-router";
import "@material/web/chips/assist-chip";
import "@material/web/chips/chip-set";
import ChipSet from "../md-components/ChipSet";
import AssistChip from "../md-components/AssistChip";
import { useEffect, useRef, useState } from "react";
import FilledButton from "../md-components/FilledButton";
import Dialog from "../md-components/Dialog";
import OutlinedButton from "../md-components/OutlinedButton";
import Icon from "../md-components/Icon";
import "./BookPage.css";
import Skeleton from "react-loading-skeleton";
import axios from "axios";
import DOMPurify from "dompurify";
import { Link } from "react-router-dom";
import { getBook } from "../db";
import { translit } from "../translit";
import { toast } from "react-toastify";
import IconButton from "../md-components/IconButton";
import NotFound from "./NotFound";
import MenuItem from "../md-components/MenuItem";
import Menu from "../md-components/Menu";
import List from "../md-components/List";
import ListItem from "../md-components/ListItem";
import TextField from "../md-components/TextField";
const InfoRow = ({ field, name }) => {
if (!field) return;
let result = field;
if (result instanceof Object) {
result = field.map((obj) => obj.name);
}
if (result instanceof Array) {
result = result.join(", ");
}
return (
<tr>
<td>{name}</td>
<td>{result}</td>
</tr>
);
};
const BookPage = () => {
const { id } = useParams();
const [bookInfo, setBookInfo] = useState(false);
const [bookImgSrc, setBookImgSrc] = useState();
const [openShare, setOpenShare] = useState(false);
const [openInfo, setOpenInfo] = useState(false);
const [allCollections, setAllCollections] = useState([]);
const [collectionsFilter, setCollectionsFilter] = useState([]);
const [downloading, setDownloading] = useState(false);
const navigate = useNavigate();
async function loadImgFromCache() {
if (window.caches === undefined) {
setBookImgSrc(axios.defaults.baseURL + "/book/" + id + "/cover");
return;
}
let cache = await window.caches.open("bookCovers");
let img = await cache.match(`/api/book/${id}/cover`);
if (img === undefined) {
setBookImgSrc(axios.defaults.baseURL + "/book/" + id + "/cover");
return;
}
let blob = await img.blob();
setBookImgSrc(URL.createObjectURL(blob));
}
const loadBookInfo = async (soft) => {
if (!soft) {
setBookInfo(false);
}
loadImgFromCache();
let localBook = await getBook(id);
if (window.onLine && !localBook) {
axios
.get("/book/" + id)
.then((res) => setBookInfo(res.data))
.catch(() => setBookInfo(404));
axios.get("/collection").then((res) => setAllCollections(res.data));
} else if (localBook) {
setBookInfo(localBook);
} else {
navigate("/offline");
}
};
const updateCollections = (id) => {
setAllCollections((a) =>
a.map((c) => {
if (c.id !== id) return c;
c.hasBook = !c.hasBook;
return c;
})
);
};
useEffect(() => {
loadBookInfo();
}, []);
useEffect(() => {
// первоначальная загрузка наличия книги в списках (ааа какой же костыль)
if (bookInfo.collections) {
setAllCollections((a) =>
a.map((c) => {
if (bookInfo.collections.filter((o) => o.id === c.id).length > 0) {
c.hasBook = true;
} else {
c.hasBook = false;
}
return c;
})
);
}
}, [bookInfo]);
async function getBookBlob() {
return (await axios.get(`/book/${id}/download`, { responseType: "blob" }))
.data;
}
function getBookFilename() {
if (bookInfo.authors === null) {
return `${translit(bookInfo.title)}.${bookInfo.filetype}`;
} else {
return `${translit(bookInfo.authors[0].name)}_-_${translit(
bookInfo.title
)}.${bookInfo.filetype}`;
}
}
async function downloadBook() {
setDownloading(true);
let a = document.createElement("a");
let bookBlob = await getBookBlob();
document.body.appendChild(a);
a.style = "display: none";
let blobURL = URL.createObjectURL(bookBlob);
a.href = blobURL;
a.download = getBookFilename();
a.click();
window.URL.revokeObjectURL(blobURL);
setDownloading(false);
}
const selectLinkRef = useRef();
const collectionDialogRef = useRef();
function share() {
setOpenShare(true);
}
if (bookInfo == 404) {
return <NotFound />;
}
return (
<div className="book_container">
<Dialog open={openShare} onClose={() => setOpenShare(false)}>
<div slot="headline">Поделиться</div>
<div slot="content">
<div
style={{
background: "var(--md-sys-color-inverse-on-surface)",
color: "white",
padding: "10px",
borderRadius: "25px",
display: "flex",
alignItems: "center",
gap: "15px",
}}
>
<span
ref={selectLinkRef}
style={{ wordBreak: "break-all", textAlign: "center" }}
>
{window.location.protocol +
"//" +
window.location.host +
window.location.pathname}
</span>
<div style={{ width: "40px", height: "40px" }}>
<IconButton
onClick={async () => {
let range = document.createRange();
range.selectNode(selectLinkRef.current);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
await navigator.clipboard.writeText(sel.toString());
toast.success("скопировано");
}}
disabled={navigator.clipboard === undefined}
>
<Icon>link</Icon>
</IconButton>
</div>
</div>
{navigator.share === undefined ? (
<p style={{ color: "#ff3333" }}>
Ваш браузер не поддерживает{" "}
<a
href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share"
style={{ color: "#ff3333" }}
>
share api
</a>
</p>
) : (
<></>
)}
</div>
<div slot="actions">
<OutlinedButton onClick={() => setOpenShare(false)}>
закрыть
</OutlinedButton>
{/* FileShare - до лучших времен
<OutlinedIconButton
disabled={navigator.share === undefined}
onClick={async () => {
let bookBlob = await getBookBlob()
console.log(bookBlob)
navigator.share({
files: [
new File(
[bookBlob],
"test.fb2",
{
type: "application/pdf"
}
)
],
text: "YaBL - " + bookInfo.title,
title: 'some_title',
url: 'some_url'
})
}}
>
<Icon>attach_file</Icon>
</OutlinedIconButton> */}
<FilledButton
onClick={() => {
setOpenShare(false);
navigator.share({
url: "",
title: "YaBL - " + bookInfo.title,
});
}}
disabled={navigator.share === undefined}
autoFocus
>
<Icon slot="icon">share</Icon>
поделиться
</FilledButton>
</div>
</Dialog>
<Dialog open={openInfo} onClose={() => setOpenInfo(false)}>
<div slot="headline">Информация</div>
<div slot="content" className="m3infoTable">
<h3>Вес файла</h3>
<span>{(bookInfo.size / 1024 / 1024).toFixed(2)} Мб</span>
<h3>Файл</h3>
<span>{bookInfo.filename}</span>
<h3>Хеш (xxh64)</h3>
<span>{bookInfo.hash || "отсутствует"}</span>
<h3>Архив</h3>
<span>{bookInfo.bookcase}</span>
</div>
<div slot="actions">
<FilledButton onClick={() => setOpenInfo(false)}>
закрыть
</FilledButton>
</div>
</Dialog>
<Dialog ref={collectionDialogRef}>
<div slot="headline">Коллекции</div>
<div slot="content">
<TextField onInput={(e) => setCollectionsFilter(e.target.value)}>
<Icon slot="leading-icon">search</Icon>
</TextField>
<br />
<br />
<div style={{ height: 300 }}>
<List
style={{
borderRadius: 12,
overflowX: "hidden",
height: "calc(100% - 10px)",
}}
>
{allCollections
.filter((coll) => coll.name.includes(collectionsFilter))
.map((coll) => (
<ListItem
key={coll.id}
type="button"
onClick={() => {
axios
.post("/collection/" + coll.id, { book_id: id })
.then(() => updateCollections(coll.id));
}}
>
{coll.name}
{coll.hasBook ? <Icon slot="end">check</Icon> : <></>}
</ListItem>
))}
</List>
</div>
</div>
<div slot="actions">
<FilledButton onClick={() => collectionDialogRef.current.close()}>
закрыть
</FilledButton>
</div>
</Dialog>
<img className="book_cover" src={bookImgSrc} />
<div className="book_info">
<span
className="break-words"
style={{
fontSize: "35px",
}}
>
{bookInfo.title || <Skeleton width={200} />}
</span>
<span>
{bookInfo.authors ? (
bookInfo.authors
.map((author) => (
<Link
to={`/search?author=${author.id}&offset=0&limit=10`}
style={{ color: "var(--md-sys-color-on-background)" }}
>
{author.name}
</Link>
))
.reduce((prev, curr) => [prev, ", ", curr])
) : bookInfo.authors === null ? (
<span>Автор неизвестен</span>
) : (
<Skeleton width={300} />
)}
</span>
<ChipSet
style={{
margin: "10px 0",
}}
>
{bookInfo.genres !== undefined ? (
bookInfo.genres !== null ? (
bookInfo.genres.map((value) => (
<AssistChip label={value.name} key={value.id} />
))
) : (
<></>
)
) : (
[150, 100, 200].map((w, key) => (
<Skeleton width={w} height={32} key={key} />
))
)}
</ChipSet>
<div className="buttons_container">
<FilledButton
style={{ width: "100%" }}
disabled={!window.onLine || downloading}
onClick={downloadBook}
className="action_button"
>
{downloading ? (
<>
<div slot="icon" class="flex justify-center items-center">
<div class="w-3 border-t-transparent rounded-full h-3 border-2 animate-spin"></div>
</div>
<>Загрузка...</>
</>
) : (
<>
<Icon slot="icon" style={{ marginTop: "2px" }}>
download
</Icon>
<>Скачать .{bookInfo.filetype}</>
</>
)}
</FilledButton>
<Link to={"/reader/" + id} className="action_button">
<OutlinedButton style={{ width: "100%" }}>
<Icon slot="icon" style={{ marginTop: "2px" }}>
chrome_reader_mode
</Icon>
Читать онлайн
</OutlinedButton>
</Link>
<OutlinedButton
disabled={!window.onLine}
className="action_button"
onClick={() => collectionDialogRef.current.show()}
>
<Icon
slot="icon"
style={{
marginTop: "2px",
}}
>
collections_bookmark
</Icon>
В коллекцию
</OutlinedButton>
</div>
{bookInfo.description !== "" ? (
<span>
<b>Описание</b>
</span>
) : (
<></>
)}
{bookInfo.description !== undefined || bookInfo.description !== "" ? (
<div
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(bookInfo.description),
}}
/>
) : (
<Skeleton count={10} />
)}
<div style={{ height: "20px" }} />
<span>
<b>Информация</b>
</span>
<div style={{ height: "20px" }} />
{bookInfo ? (
<table className="info_table">
<tbody>
<InfoRow field={bookInfo.lang} name={"Язык"} />
<InfoRow field={bookInfo.translators} name={"Переводчики"} />
<InfoRow field={bookInfo.sequence} name={"Серия"} />
<InfoRow field={bookInfo.src_lang} name={"Язык оригинала"} />
<InfoRow field={bookInfo.isbn} name={"ISBN"} />
<InfoRow field={bookInfo.publisher} name={"Издатель"} />
<InfoRow field={bookInfo.year} name={"Год выхода"} />
<InfoRow field={bookInfo.downloads} name={"Загрузки"} />
</tbody>
</table>
) : (
<Skeleton count={5} />
)}
<div
style={{
marginTop: "25px",
display: "flex",
justifyContent: "center",
flexDirection: "row",
alignItems: "center",
gap: "15px",
}}
>
<IconButton onClick={() => setOpenInfo(true)}>
<Icon>info</Icon>
</IconButton>
<IconButton onClick={() => share()}>
<Icon>share</Icon>
</IconButton>
<IconButton onClick={() => toast.info("coming soon...")}>
<Icon>flag</Icon>
</IconButton>
</div>
</div>
</div>
);
};
export default BookPage;
+21
View File
@@ -0,0 +1,21 @@
import { useEffect } from "react"
import SearchHeader from "./SearchHeader"
const MainPage = () => {
useEffect(() => {
})
return <div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
minHeight: "100vh",
width: "calc(100% - 30px)",
margin: "0 15px",
}}>
<SearchHeader/>
</div>
}
export default MainPage
+24
View File
@@ -0,0 +1,24 @@
import { Link } from "react-router-dom"
import FilledButton from "../md-components/FilledButton"
import Icon from "../md-components/Icon"
const NotFound = () => {
return <div style={{
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
gap: "40px"
}}>
<h1 style={{margin: 0}}>404</h1>
<Icon style={{fontSize: "100px", height: "100px", width: "100px", color: "var(--md-sys-color-on-background)"}}>search_off</Icon>
<Link to={"/"}>
<FilledButton>
<Icon slot="icon">search</Icon>
Найти что-нибудь еще
</FilledButton>
</Link>
</div>
}
export default NotFound
+13
View File
@@ -0,0 +1,13 @@
import { Outlet } from "react-router";
function OOBE() {
return (
<div className="flex items-center h-screen justify-center flex-col p-3">
<div className="flex flex-col bg-(--md-sys-color-surface-variant) p-8 rounded-3xl w-full max-w-180 min-h-100 justify-between items-center">
<Outlet />
</div>
</div>
);
}
export default OOBE;
@@ -0,0 +1,96 @@
import { Link, useNavigate } from "react-router";
import TextField from "../../md-components/TextField";
import FilledButton from "../../md-components/FilledButton";
import { useRef, useState } from "react";
import axios from "axios";
import { toast } from "react-toastify";
function OOBECreateUser() {
const submitRef = useRef();
const [processing, setProcessing] = useState(false);
function handleSubmit(e) {
if (e.key === "Enter") {
submitRef.current.click();
}
}
const navigate = useNavigate();
function createUser(name, username, password) {
axios
.post("/oobe/create-user", {
name: name,
username: username,
password: password,
})
.then(() => {
toast(`happy reading ${name}!`);
axios
.post("/auth", { login: username, password: password })
.then(() => {
axios.get("/user").then((res) => {
localStorage.setItem("userInfo", JSON.stringify(res.data));
});
navigate("/");
})
.catch(() => {
toast.error("Что то пошло не так...");
setProcessing(false);
});
})
.catch((error) => {
if (error.response.status === 403) {
toast.error("OOBE уже завершен, невозможно создать пользователя");
} else {
toast.error("Ошибка при создании пользователя");
}
setProcessing(false);
});
}
return (
<>
<h1 className="font-bold text-2xl mb-6">Создать пользователя</h1>
<div className="mb-0">
<span>Введите данные для администратора библиотеки</span>
<form
onSubmit={(e) => {
e.preventDefault();
if (processing) return;
setProcessing(true);
createUser(
e.target.name.value,
e.target.username.value,
e.target.password.value
);
}}
className="flex flex-col gap-3 py-4 items-center"
>
<TextField label="Имя" id="name" onKeyDown={handleSubmit} required />
<TextField
label="Логин"
type="username"
id="username"
onKeyDown={handleSubmit}
required
/>
<TextField
label="Пароль"
type="password"
id="password"
onKeyDown={handleSubmit}
required
/>
<FilledButton
className="w-50"
type="submit"
ref={submitRef}
disabled={processing}
>
{processing ? "Создание..." : "Создать"}
</FilledButton>
</form>
</div>
<span className="text-center mt-4">v2.0-beta</span>
</>
);
}
export default OOBECreateUser;
+19
View File
@@ -0,0 +1,19 @@
import { Link } from "react-router";
import FilledButton from "../../md-components/FilledButton";
function OOBEWelcome() {
return (
<>
<h1 className="font-bold text-2xl mb-6">Добро пожаловать!</h1>
<div className="mb-6">
<span>Настройте библиотеку под себя</span>
</div>
<Link to={"/oobe/create-user"} viewTransition>
<FilledButton className="w-50">К настройке</FilledButton>
</Link>
<span className="text-center">v2.0-beta</span>
</>
);
}
export default OOBEWelcome;
+24
View File
@@ -0,0 +1,24 @@
import { Link } from "react-router-dom"
import FilledButton from "../md-components/FilledButton"
import Icon from "../md-components/Icon"
const Offline = () => {
return <div style={{
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
gap: "40px"
}}>
<h1 style={{margin: 0}}>Нет сети</h1>
<Icon style={{fontSize: "80px", height: "80px", width: "80px", color: "var(--md-sys-color-on-background)"}}>cloud_off</Icon>
<Link to={"/account"}>
<FilledButton>
<Icon slot="icon">local_library</Icon>
В локальную библиотеку
</FilledButton>
</Link>
</div>
}
export default Offline
+43
View File
@@ -0,0 +1,43 @@
import { Outlet } from "react-router"
import SearchHeader from "./SearchHeader"
import Icon from "../md-components/Icon"
const PageBody = () => {
return <>
{/* {
window.location.protocol !== "https:" ?
<div style={{
background: "#F80000",
height: 22,
width: "100%",
// marginTop: "-15px",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}>
<Icon style={{color: "white", fontSize: 16}}>warning</Icon>
<span style={{fontSize: 14}}>Сайт использует протокол HTTP, часть функционала недоступна</span>
</div>
: <></>
} */}
<div style={{
display: "flex",
justifyContent: "center",
}}>
<div style={{
display: "flex",
width: "calc(100% - 20px)",
maxWidth: "1300px",
flexDirection: "column",
padding: "10px",
gap: "10px",
minHeight: "calc(100vh - 20px)"
}}>
<SearchHeader/>
<Outlet/>
</div>
</div>
</>
}
export default PageBody
+186
View File
@@ -0,0 +1,186 @@
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router";
import "./reader.css";
import OutlinedButton from "../md-components/OutlinedButton";
import FilledButton from "../md-components/FilledButton";
import Contents from "../components/contents/Contents";
import Icon from "../md-components/Icon";
import { Link } from "react-router-dom";
import Skeleton from "react-loading-skeleton";
import LinearProgress from "../md-components/LinearProgress";
import {
addBook,
getBook,
getReadBook,
putReadBook,
removeBook,
saveReadBook,
updateReadBook,
} from "../db";
import IconButton from "../md-components/IconButton";
import ReaderFB2 from "./ReaderFB2";
const Reader = () => {
const { id } = useParams();
const navigate = useNavigate();
const [isLocal, setIsLocal] = useState(false);
const [onBookshelf, setOnBookshelf] = useState(false);
const [bookInfo, setBookInfo] = useState(false);
const [contents, setContents] = useState([]);
const [saving, setSaving] = useState(false);
const [shelving, setShelving] = useState(false);
const [pdfURL, setPdfURL] = useState(false);
async function loadBook() {
let readBook = await getReadBook(id);
if (readBook) {
setOnBookshelf(readBook.onBookshelf === true);
}
let caches = undefined;
let localFile = undefined;
if (window.caches !== undefined) {
caches = await window.caches.open("books");
localFile = await caches.match(`/api/book/${id}/reader`);
}
let localBook = await getBook(id);
if (localBook !== undefined && localFile !== undefined) {
setIsLocal(true);
setContents(localBook.contents);
setBookInfo(localBook);
let blob = await localFile.blob();
let pdfBlob = new Blob([blob], { type: "application/pdf" });
console.log(pdfBlob);
setPdfURL(URL.createObjectURL(pdfBlob));
} else {
if (!window.onLine) {
localStorage.removeItem("lastReadBook");
navigate("/offline");
}
setIsLocal(false);
axios
.get(`/book/${id}`)
.then((res) => setBookInfo(res.data))
.catch(() => navigate("/notfound"));
axios.get(`/book/${id}/contents`).then((res) => setContents(res.data));
setPdfURL(`/api/book/${id}/reader`);
}
console.log(bookInfo);
localStorage.setItem("lastReadBook", id);
}
useEffect(() => {
loadBook();
}, [id]);
async function saveBook() {
setSaving(true);
let caches = await window.caches.open("books");
await caches.add(`/api/book/${id}/reader`);
await addBook(id, bookInfo, contents);
await saveReadBook(id, true);
setIsLocal(true);
setSaving(false);
console.log("save");
}
async function deleteBook() {
let caches = await window.caches.open("books");
await caches.delete(`/api/book/${id}/reader`);
await removeBook(id);
await saveReadBook(id, false);
setIsLocal(false);
}
return (
<>
<h1 style={{ display: "flex", marginBottom: 0, gap: "10px" }}>
<span className="truncate">
{bookInfo.title || (
<Skeleton width={300} style={{ display: "inline-block" }} />
)}{" "}
</span>
{isLocal ? (
<Icon style={{ lineHeight: "38px", height: "100%" }}>cloud_off</Icon>
) : (
<></>
)}
</h1>
<span>
{bookInfo.authors ? (
bookInfo.authors
.map((author) => (
<Link
to={"/search?author=" + author.id}
style={{ color: "var(--md-sys-color-on-background)" }}
>
{author.name}
</Link>
))
.reduce((prev, curr) => [prev, ", ", curr])
) : bookInfo.authors === null ? (
<span>Автор неизвестен</span>
) : (
<Skeleton width={350} />
)}
</span>
<div style={{ display: "flex", gap: "10px" }} className="flex mt-4">
<Link to={`/book/${id}`} className="reader_action_button">
<FilledButton style={{ width: "100%" }}>
<Icon slot="icon">info</Icon>
Информация
</FilledButton>
</Link>
{isLocal ? (
<OutlinedButton onClick={deleteBook} className="reader_action_button">
<Icon slot="icon">delete</Icon>
Удалить с устройства
</OutlinedButton>
) : (
<OutlinedButton
onClick={saveBook}
className="reader_action_button"
disabled={window.caches === undefined || saving}
>
<Icon slot="icon">cloud</Icon>
{saving ? "Сохранение..." : "Сохранить локально"}
</OutlinedButton>
)}
{/* <OutlinedButton
className="reader_action_button"
onClick={async () => {
setShelving(true);
let caches = await window.caches.open("bookCovers");
if (onBookshelf) {
await caches.delete(`/api/book/${id}/cover`);
} else {
await caches.add(`/api/book/${id}/cover`);
}
putReadBook(id, !onBookshelf, bookInfo);
setOnBookshelf(!onBookshelf);
setShelving(false);
}}
disabled={shelving}
>
<Icon slot="icon">book</Icon>
{shelving
? "Сохранение..."
: onBookshelf
? "Убрать с полки"
: "На полку"}
</OutlinedButton> */}
</div>
{bookInfo.filetype === "fb2" ? (
<ReaderFB2 />
) : pdfURL ? (
<embed className="h-[calc(100vh-15px)]" src={pdfURL}></embed>
) : (
<>
<LinearProgress indeterminate />
<span>Загрузка...</span>
</>
)}
</>
);
};
export default Reader;
+257
View File
@@ -0,0 +1,257 @@
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router";
import "./reader.css";
import OutlinedButton from "../md-components/OutlinedButton";
import FilledButton from "../md-components/FilledButton";
import Contents from "../components/contents/Contents";
import Icon from "../md-components/Icon";
import { Link } from "react-router-dom";
import Skeleton from "react-loading-skeleton";
import LinearProgress from "../md-components/LinearProgress";
import {
addBook,
getBook,
getReadBook,
putReadBook,
removeBook,
saveReadBook,
updateReadBook,
} from "../db";
import IconButton from "../md-components/IconButton";
const ReaderFB2 = () => {
const { id } = useParams();
const readerRef = useRef();
const containerRef = useRef();
const progressRef = useRef();
const contentsRef = useRef();
const contentsBackdropRef = useRef();
const navigate = useNavigate();
const [totalHeight, setTotalHeight] = useState(0);
const [currentHeight, setCurrentHeight] = useState(0);
const [readerHeight, setReaderHeight] = useState(0);
const [totalPages, setTotalPages] = useState(1);
const [currentPage, setCurrentPage] = useState(0);
const [isLocal, setIsLocal] = useState(false);
const [onBookshelf, setOnBookshelf] = useState(false);
const [bookInfo, setBookInfo] = useState({ title: "" });
const [contents, setContents] = useState([]);
function nextPage() {
setCurrentPage((prev) => {
if (totalPages - prev < 1) {
return prev;
}
return prev + 1;
});
}
function prevPage() {
setCurrentPage((prev) => {
if (prev <= 1) {
return prev;
}
return prev - 1;
});
}
const leftRef = useRef();
const rightRef = useRef();
function keyboardPagination(e) {
if (!(leftRef.current && rightRef.current)) {
console.log("harakiri");
document.removeEventListener("keydown", keyboardPagination, false);
return;
}
if (e.key === "ArrowRight") {
rightRef.current.click();
}
if (e.key === "ArrowLeft") {
leftRef.current.click();
}
}
useEffect(() => {
if (!(leftRef.current && rightRef.current)) return;
console.log("add listener");
document.addEventListener("keydown", keyboardPagination, false);
}, [leftRef, rightRef]);
function toggleFloatingContents() {
if (!contentsRef.current || !contentsBackdropRef.current) return;
contentsRef.current.classList.toggle("show");
contentsBackdropRef.current.classList.toggle("show");
}
useEffect(() => {
if (currentPage === 0) return;
if (readerHeight === totalHeight) return;
setCurrentHeight(readerHeight * (currentPage - 1));
readerRef.current.scrollTop = readerHeight * (currentPage - 1);
progressRef.current.style.width = `${(currentPage / totalPages) * 100}%`;
//console.log(readerHeight * (currentPage-1) / totalHeight, "update read book", currentPage)
//console.log(readerHeight, currentPage, totalHeight)
updateReadBook(id, (readerHeight * (currentPage - 1)) / totalHeight);
}, [currentPage]);
async function loadBook() {
let readBook = await getReadBook(id);
if (readBook) {
setOnBookshelf(readBook.onBookshelf === true);
}
let caches = undefined;
let localHTML = undefined;
if (window.caches !== undefined) {
caches = await window.caches.open("books");
localHTML = await caches.match(`/api/book/${id}/reader`);
}
let localBook = await getBook(id);
let innerHTML = "";
if (localBook !== undefined && localHTML !== undefined) {
setIsLocal(true);
setBookInfo(localBook);
setContents(localBook.contents);
await localHTML.text().then((html) => {
innerHTML = html;
});
} else {
if (!window.onLine) {
localStorage.removeItem("lastReadBook");
navigate("/offline");
}
setIsLocal(false);
axios
.get(`/book/${id}`)
.then((res) => setBookInfo(res.data))
.catch(() => navigate("/notfound"));
axios.get(`/book/${id}/contents`).then((res) => setContents(res.data));
await axios.get(`/book/${id}/reader`).then((res) => {
innerHTML = res.data;
});
}
localStorage.setItem("lastReadBook", id);
readerRef.current.innerHTML =
innerHTML +
"<br>".repeat(Math.floor(containerRef.current.clientHeight / 23) * 2); // заполнение двух страниц пустотой для возможности прокрутки не до конца
resizingReader(true);
}
async function resizingReader(firstLoad) {
if (!readerRef.current) return;
if (readerRef.current.scrollHeight === 0) return;
let progressRatio;
if (firstLoad) {
let readBook = await getReadBook(id);
if (readBook === undefined) {
progressRatio = 0;
updateReadBook(id, 0);
} else {
progressRatio = readBook.progress;
}
}
readerRef.current.style.height = `${
Math.floor(containerRef.current.clientHeight / 23) * 23 - 23
}px`; // подгоняем блок контента под окно ридера, и не забывает учитывать прогресс
setTotalHeight(readerRef.current.scrollHeight);
setReaderHeight(readerRef.current.clientHeight);
setTotalPages(
Math.ceil(
readerRef.current.scrollHeight / readerRef.current.clientHeight
) - 2
);
setCurrentPage(
Math.ceil(
Math.floor(progressRatio * readerRef.current.scrollHeight) /
readerRef.current.clientHeight
) + 1
);
}
useEffect(() => {
if (!readerRef.current) return;
loadBook();
}, [id]);
// изменение размера изображений для соответствия с шириной строки (23px)
useEffect(() => {
if (!readerRef.current) return;
let images = Array.from(readerRef.current.getElementsByTagName("img"));
images.map((img) => {
img.height = Math.floor(img.height / 23) * 23;
});
}, [totalHeight]);
return (
<>
<div
className="reader_contents_backdrop"
ref={contentsBackdropRef}
onClick={toggleFloatingContents}
></div>
<div className="reader_contents" ref={contentsRef}>
<Contents
data={contents}
readerRef={readerRef}
readerHeight={readerHeight}
currentPage={currentPage}
setCurrentPage={setCurrentPage}
/>
</div>
<div style={{ display: "flex", gap: "10px" }} className="mb-4">
{!(contents.length === 1 && contents[0].title === "") &&
contents.length !== 0 ? (
<OutlinedButton
className="contents_button reader_action_button"
onClick={toggleFloatingContents}
>
<Icon slot="icon">article</Icon>
Содержание
</OutlinedButton>
) : (
<></>
)}
</div>
<div className="reader_container" ref={containerRef}>
<div className="book_content" ref={readerRef} id="reader">
<LinearProgress indeterminate />
<br />
<Skeleton
count={
containerRef.current
? Math.floor(containerRef.current.clientHeight / 23) - 2
: 0
}
/>
</div>
<div className="reader_progress" ref={progressRef}></div>
</div>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "20px",
}}
>
<IconButton
onClick={prevPage}
disabled={currentHeight === 0}
ref={leftRef}
>
<Icon>arrow_back</Icon>
</IconButton>
<span>
{currentPage} из {totalPages}
</span>
<IconButton
onClick={nextPage}
disabled={totalPages - currentPage < 1}
ref={rightRef}
>
<Icon>arrow_forward</Icon>
</IconButton>
</div>
</>
);
};
export default ReaderFB2;
+36
View File
@@ -0,0 +1,36 @@
import Search from "../search/Search"
import Icon from "../md-components/Icon"
import IconButton from "../md-components/IconButton"
import { Link } from "react-router-dom"
const SearchHeader = () => {
return (
<div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "100%"
}}>
<Link to={"/"}>
<img
width={48}
src="/favicon.png"
/>
</Link>
<Search/>
{/* <Link to={"/account"}>
<IconButton
style={{
"--md-filled-tonal-icon-button-container-height": "48px",
"--md-filled-tonal-icon-button-container-width": "48px"
}}
>
<Icon>person</Icon>
</IconButton>
</Link> */}
</div>
)
}
export default SearchHeader
+11
View File
@@ -0,0 +1,11 @@
.results_container {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
@media screen and (max-width: 820px) {
.results_container {
gap: 10px;
}
}
+121
View File
@@ -0,0 +1,121 @@
import { useNavigate, useSearchParams } from "react-router-dom";
import BookCard from "../components/bookCard/BookCard";
import { useEffect, useState } from "react";
import "@material/web/progress/linear-progress";
import LinearProgress from "../md-components/LinearProgress";
import "./SearchPage.css";
import axios from "axios";
import IconButton from "../md-components/IconButton";
import Icon from "../md-components/Icon";
const Pagination = ({ total }) => {
const [searchParams, setSearchParams] = useSearchParams();
const [perPage, setPerPage] = useState(10);
return (
<div
style={{
display: "flex",
alignItems: "center",
gap: "10px",
width: "100%",
justifyContent: "center",
}}
>
<IconButton
disabled={Number(searchParams.get("offset")) - perPage < 0}
onClick={() => {
searchParams.set(
"offset",
Number(searchParams.get("offset")) - perPage
);
setSearchParams(searchParams);
}}
>
<Icon>arrow_back</Icon>
</IconButton>
<span>
{Number(searchParams.get("offset")) + 1}-
{Number(searchParams.get("offset")) + perPage > total
? total
: Number(searchParams.get("offset")) + perPage}
{" из "}
{total}
</span>
<IconButton
disabled={Number(searchParams.get("offset")) + perPage + 1 > total}
onClick={() => {
searchParams.set(
"offset",
Number(searchParams.get("offset")) + perPage
);
setSearchParams(searchParams);
}}
>
<Icon>arrow_forward</Icon>
</IconButton>
</div>
);
};
const SearchPage = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [result, setResult] = useState(false);
const navigate = useNavigate();
const loadResults = async () => {
setResult(false);
axios
.get("/search", {
params: Object.fromEntries(searchParams.entries()),
})
.then((res) => setResult(res.data));
};
useEffect(() => {
if (!window.onLine) navigate("/offline");
if (
searchParams.get("offset") === null ||
searchParams.get("limit") === null
) {
searchParams.set("offset", "0");
searchParams.set("limit", "10");
window.history.replaceState(
null,
"",
`/search?${searchParams.toString()}`
);
setSearchParams(searchParams);
}
loadResults();
}, [searchParams]);
if (!result) {
return <LinearProgress />;
}
return (
<>
{
<span>
Найдено <b>{result.count}</b> за <b>{result.time}</b> с. 🚀
</span>
}
<div className="results_container">
{result.books === null ? (
<p>Ничего не найдено 🙁</p>
) : (
result.books.map((value) => (
<BookCard
key={value.id}
id={value.id}
authors={value.authors}
title={value.title}
fromSearch={searchParams.get("q")}
filetype={value.filetype}
/>
))
)}
<Pagination total={result.count} />
</div>
</>
);
};
export default SearchPage;
@@ -0,0 +1,63 @@
.account_buttons_container {
display: flex;
gap: 25px;
margin: 20px 0;
}
.main_down_menu {
display: none;
position: fixed;
bottom: 0;
width: 100%;
justify-content: space-around;
background-color: var(--md-sys-color-background);
padding: 10px 0;
z-index: 4;
}
.main_down_menu_item {
display: flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: var(--md-sys-color-on-surface);
gap: 2px;
font-size: 14px;
user-select: none;
}
.main_down_menu_item .icon {
width: 65px;
position: relative;
padding: 3px 0;
display: flex;
justify-content: center;
border-radius: 20px;
}
.main_down_menu_item .icon.active {
background: var(--md-sys-color-primary-container);
}
.main_page_container {
display: flex;
gap: 50px;
}
@media screen and (max-width: 470px) { /* кнопки в столбик */
.account_buttons_container {
flex-direction: column;
gap: 10px;
}
.account_action_button {
flex-basis: auto;
}
}
@media screen and (max-width: 1160px) {
.main_page_container {
gap: 0;
margin-bottom: 71px;
}
.main_side_menu {
display: none !important;
}
.main_down_menu {
display: flex;
}
}
+119
View File
@@ -0,0 +1,119 @@
import { Outlet, useLocation } from "react-router";
import List from "../../md-components/List";
import ListItem from "../../md-components/ListItem";
import { Link } from "react-router-dom";
import Icon from "../../md-components/Icon";
const AccountPage = () => {
const location = useLocation();
const menuRoutes = [
{
name: "Главная",
path: "/",
icon: "home",
},
{
name: "Коллекции",
path: "/collections",
icon: "collections_bookmark",
},
{
name: "Полка",
path: "/shelve",
icon: "shelves",
},
{
name: "Загрузить книгу",
path: "/upload",
icon: "upload",
},
// {
// name: "Настройки",
// path: "/settings",
// icon: "settings",
// },
// {
// name: "Безопасность",
// path: "/security",
// icon: "security",
// },
// {
// name: "Администрирование",
// path: "/admin",
// icon: "admin_panel_settings",
// },
];
return (
<>
<div className="main_page_container">
<div
style={{
display: "flex",
flexDirection: "column",
paddingTop: 50,
color: "white",
}}
>
<List
style={{
border: "0px solid gray",
borderRadius: 15,
padding: 10,
gap: 10,
width: 240,
}}
className="main_side_menu"
>
{menuRoutes.map((route) => (
<Link
to={route.path}
style={{ textDecoration: "none" }}
key={route.path}
>
<ListItem
type="button"
style={{
borderRadius: 15,
background:
location.pathname == route.path
? "var(--md-sys-color-primary-container)"
: "",
}}
onClick={() => {} /*navigate(route.path)*/}
>
<Icon slot="start">{route.icon}</Icon>
{route.name}
</ListItem>
</Link>
))}
</List>
</div>
<div style={{ paddingTop: 20, width: "100%" }}>
<Outlet />
</div>
</div>
<div className="main_down_menu">
{menuRoutes.map((route, i) => (
<Link
className="main_down_menu_item"
to={route.path}
id={"route" + i}
key={i}
>
<div
className={
"icon " + (location.pathname == route.path ? "active" : "")
}
>
<md-ripple for={"route" + i} />
<Icon>{route.icon}</Icon>
</div>
<span>{route.name}</span>
</Link>
))}
</div>
</>
);
};
export default AccountPage;
@@ -0,0 +1,30 @@
import { useParams } from "react-router"
import SearchResults from "../../components/SearchResults"
import DefaultIconButton from "../../md-components/DefaultIconButton"
import Icon from "../../md-components/Icon"
import { Link } from "react-router-dom"
import { useEffect, useState } from "react"
import axios from "axios"
const CollectionPage = () => {
const [ collectionInfo, setCollectionInfo ] = useState(false)
const { id } = useParams()
useEffect(() => {
axios.get("/collection/"+id).then(res=>setCollectionInfo(res.data))
}, [])
return <>
<div style={{display: "flex", alignItems: "center", gap: 15}}>
<Link to={"/collections"}>
<DefaultIconButton>
<Icon>chevron_left</Icon>
</DefaultIconButton>
</Link>
<h3 style={{margin: 0}}>{collectionInfo.name}</h3>
</div>
<SearchResults
collection={id}
/>
</>
}
export default CollectionPage
@@ -0,0 +1,19 @@
.scroll_container {
width: calc(205px * 4);
overflow-x: auto !important;
scrollbar-width: none;
}
.slider_button {
position: absolute;
z-index: 3;
}
@media screen and (max-width: 1160px) {
.scroll_container {
/* width: calc(205px * 2 + 80px); */
width: calc(100vw - 30px);
}
.slider_button {
display: none;
}
}
@@ -0,0 +1,167 @@
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import BookCard from "../../components/bookCard/BookCard";
import LinearProgress from "../../md-components/LinearProgress";
import Icon from "../../md-components/Icon";
import { Link } from "react-router-dom";
import IconButton from "../../md-components/IconButton";
import "./CollectionSlider.css";
import DefaultIconButton from "../../md-components/DefaultIconButton";
const CollectionSlider = ({ id, name, onDelete }) => {
const [collectionInfo, setCollectionInfo] = useState(false);
const [collectionBooks, setCollectionBooks] = useState(false);
const [curPage, setCurPage] = useState(0);
const scrollRef = useRef();
const loadCollectionInfo = () => {
setCollectionInfo(false);
axios.get("/collection/" + id).then((res) => setCollectionInfo(res.data));
axios
.get("/search", { params: { collection: id, offset: 0, limit: 9 } })
.then((res) => setCollectionBooks(res.data.books));
};
useEffect(() => loadCollectionInfo(), [id]);
// до лучших времен
// useEffect(() => {
// if (scrollRef.current !== undefined) {
// console.log('add listener')
// scrollRef.current.addEventListener("scroll", e => console.log(e.target.scrollLeft))
// }
// }, [scrollRef])
useEffect(() => {
if (scrollRef.current == undefined) return;
scrollRef.current.scrollLeft = 205 * 4 * curPage;
}, [curPage]);
if (!collectionInfo || !collectionBooks) {
return (
<>
<br />
<LinearProgress indeterminate style={{ width: "100%" }} />
</>
);
}
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
return (
<>
<div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
<DefaultIconButton
onClick={() => onDelete(collectionInfo.creator.id === userInfo.id)}
>
<Icon>
{collectionInfo.creator.id === userInfo.id
? "delete"
: "bookmark_remove"}
</Icon>
</DefaultIconButton>
<Link to={"/collection/" + id} style={{ textDecoration: "none" }}>
<h3 style={{ display: "flex", width: "fit-content" }}>
{name}
<Icon>chevron_right</Icon>
</h3>
</Link>
</div>
<div
style={{
position: "relative",
width: "fit-content",
}}
>
<IconButton
className="slider_button"
onClick={() => setCurPage((p) => p - 1)}
style={{
left: -15,
top: 135,
opacity: curPage === 0 ? 0 : 1,
transition: "all 0.2s",
}}
disabled={curPage === 0}
>
<Icon>chevron_left</Icon>
</IconButton>
{collectionBooks.length === 0 ? (
<span style={{ marginLeft: 25 }}>
добавьте первую книгу в коллекцию
</span>
) : (
<></>
)}
<div
ref={scrollRef}
style={{
translate: "all 1s",
scrollBehavior: "smooth",
}}
className="scroll_container"
>
<div
style={{
display: "flex",
gap: 5,
width:
collectionBooks.length > 8
? 205 * 8
: 205 * collectionBooks.length,
}}
>
{collectionBooks.slice(0, 7).map((book) => (
<BookCard
key={book.id}
id={book.id}
title={book.title}
authors={book.authors}
collectionDelId={id}
fixed
filetype={book.filetype}
/>
))}
{collectionBooks.length > 8 ? (
<Link to={"/collection/" + id} style={{ textDecoration: "none" }}>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: 280,
width: 180,
margin: 10,
borderRadius: 12,
background: "var(--md-sys-color-primary-container)",
color: "var(--md-sys-color-on-primary-container)",
position: "relative",
userSelect: "none",
}}
>
<md-ripple />
<span>Еще</span>
<Icon>chevron_right</Icon>
</div>
</Link>
) : (
<></>
)}
</div>
</div>
<IconButton
className="slider_button"
onClick={() => setCurPage((p) => p + 1)}
style={{
right: -15,
top: 135,
opacity: (curPage === 0) & (collectionBooks.length > 4) ? 1 : 0,
transition: "all 0.2s",
}}
disabled={(curPage !== 0) | (collectionBooks.length < 4)}
>
<Icon>chevron_right</Icon>
</IconButton>
</div>
</>
);
};
export default CollectionSlider;
+158
View File
@@ -0,0 +1,158 @@
import axios from "axios";
import { useCallback, useEffect, useRef, useState } from "react";
import Icon from "../../md-components/Icon";
import LinearProgress from "../../md-components/LinearProgress";
import Dialog from "../../md-components/Dialog";
import FilledButton from "../../md-components/FilledButton";
import TextButton from "../../md-components/TextButton";
import TextField from "../../md-components/TextField";
import CollectionSlider from "./CollectionSlider";
const Collections = () => {
const [currentCollectionTab, setCurrentCollectionTab] = useState(0);
const [collectionPermDel, setCollectionPermDel] = useState(false);
const [collectionTabs, setCollectionTabs] = useState(false);
const [limit, setLimit] = useState(3);
const createDialogRef = useRef();
const deleteDialogRef = useRef();
const newCollectionNameRef = useRef();
const deleteAction = (indx, permDel) => {
setCurrentCollectionTab(indx);
setCollectionPermDel(permDel);
deleteDialogRef.current.show();
};
const deleteCollection = (id) => {
axios.delete("/collection/" + id).then(() => deleteFromList(id));
};
const removeCollection = (id) => {
axios.delete("/user/collection/" + id).then(() => deleteFromList(id));
};
const deleteFromList = useCallback(
(delId) =>
setCollectionTabs((old) => old.filter((tab) => tab.id !== delId)),
[]
);
const addToList = (newColl) => setCollectionTabs((old) => [...old, newColl]);
const createNewCollection = (name) => {
axios
.put("/collection", { name: name })
.then((res) => addToList({ id: res.data.id, name: name }));
};
const loadCollectionsList = () => {
setCollectionTabs(false);
axios.get("/collection").then((res) => {
setCollectionTabs(res.data);
});
};
useEffect(() => loadCollectionsList(), []);
if (!window.onLine) {
return <span>Недоступно оффлайн</span>;
}
if (collectionTabs === false) {
return <LinearProgress indeterminate style={{ width: "100%" }} />;
}
return (
<>
{collectionTabs.slice(0, limit).map((tab, i) => (
<div className="mb-4">
<CollectionSlider
key={tab.id}
id={tab.id}
name={tab.name}
onDelete={(permDel) => deleteAction(i, permDel)}
/>
</div>
))}
{collectionTabs.length > limit ? (
<TextButton onClick={() => setLimit((pr) => (pr += 10))}>
<Icon slot="icon">keyboard_arrow_down</Icon> загрузить еще
</TextButton>
) : (
<></>
)}
<TextButton
onClick={() => {
newCollectionNameRef.current.value = "";
createDialogRef.current.show();
}}
>
<Icon slot="icon">add</Icon> создать коллекцию
</TextButton>
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: 5,
}}
>
{/* {
collectionInfo ? collectionInfo.books.map(book => <BookCard key={book.id}
id={book.id}
title={book.title}
authors={book.authors}
/>) : <LinearProgress indeterminate style={{width: "100%"}}/>
} */}
</div>
<Dialog ref={createDialogRef}>
<div slot="headline">Новая коллекция</div>
<div slot="content">
<TextField ref={newCollectionNameRef} label="Название" required />
</div>
<div slot="actions">
<TextButton onClick={() => createDialogRef.current.close()}>
отмена
</TextButton>
<FilledButton
onClick={() => {
if (newCollectionNameRef.current.reportValidity()) {
createNewCollection(newCollectionNameRef.current.value);
createDialogRef.current.close();
}
}}
>
создать
</FilledButton>
</div>
</Dialog>
<Dialog ref={deleteDialogRef}>
<div slot="headline">Удаление</div>
<div slot="content" className="">
<p>
Вы потеряете весь список собранных книг в коллекции "
<b>
{collectionTabs[currentCollectionTab]
? collectionTabs[currentCollectionTab].name
: ""}
</b>
" без возможности восстановления
</p>
<p>Уверены что хотите продолжить?</p>
</div>
<div slot="actions">
<TextButton onClick={() => deleteDialogRef.current.close()}>
отмена
</TextButton>
<FilledButton
onClick={() => {
let colId = collectionTabs[currentCollectionTab].id;
collectionPermDel
? deleteCollection(colId)
: removeCollection(colId);
deleteDialogRef.current.close();
}}
//style={{"--md-filled-button-container-color": "red", "--md-filled-button-label-text-color": "white"}}
>
уверен
</FilledButton>
</div>
</Dialog>
</>
);
};
export default Collections;
+195
View File
@@ -0,0 +1,195 @@
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import Skeleton from "react-loading-skeleton";
import BookCard from "../../components/bookCard/BookCard";
import Icon from "../../md-components/Icon";
import {
getAllReadBooks,
getBook,
putReadBook,
saveReadBook,
syncReadBook,
} from "../../db";
import { toast } from "react-toastify";
import OutlinedButton from "../../md-components/OutlinedButton";
import "./AccountPage.css";
import FilledButton from "../../md-components/FilledButton";
import { useNavigate } from "react-router";
const Main = () => {
const navigate = useNavigate();
const [accountInfo, setAccountInfo] = useState(false);
const [bookshelf, setBookshelf] = useState([]);
async function loadAccount() {
if (window.onLine) {
axios.get("/user").then((res) => setAccountInfo(res.data));
}
}
useEffect(() => {
if (accountInfo !== false) return;
loadAccount();
updateBookshelf();
}, [accountInfo]);
async function updateBookshelf() {
let caches = await window.caches.open("bookCovers");
let reader = await getAllReadBooks();
if (bookshelf.length !== 0) return;
reader
.filter((book) => book.onBookshelf)
.map(async (value) => {
let newBook;
if (value.offline === undefined) {
let localBook = await getBook(value.id);
if (localBook !== undefined) {
await saveReadBook(value.id, true);
} else {
await saveReadBook(value.id, false);
}
}
if (window.onLine) {
if (
(await caches.match(`/api/book/${value.id}/cover`)) === undefined
) {
await caches.add(`/api/book/${value.id}/cover`);
}
}
if (value.bookInfo === undefined) {
if (window.onLine) {
let bookInfo = (await axios.get("/book/" + value.id)).data;
await putReadBook(value.id, true, bookInfo);
newBook = (
<BookCard
key={value.id}
id={value.id}
authors={bookInfo.authors}
title={bookInfo.title}
reader={true}
offline={value.offline}
/>
);
} else {
newBook = (
<BookCard
key={value.id}
id={value.id}
authors={[]}
title={"Подключитесь к интернету"}
reader={true}
offline={false}
/>
);
}
} else {
newBook = (
<BookCard
key={value.id}
id={value.id}
authors={value.bookInfo.authors}
title={value.bookInfo.title}
reader={true}
offline={value.offline}
/>
);
}
setBookshelf((prev) => [...prev, newBook]);
});
}
return (
<>
{/* <IconButton onClick={() => {
setAccountInfo(false)
}}><Icon>refresh</Icon></IconButton> */}
{window.onLine ? (
<h2>Здравствуйте, {accountInfo.name || <Skeleton width={150} />}</h2>
) : (
<h2>
Офлайн режим{" "}
<Icon style={{ lineHeight: "30px", height: "100%" }}>cloud_off</Icon>
</h2>
)}
<FilledButton
className="w-26"
//style={{"--md-filled-button-container-color": "var(--md-sys-color-error)"}}
onClick={() => {
document.cookie = "token=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
navigate("/login");
}}
>
выйти
</FilledButton>
{/* <h3>Синхронизация</h3>
<div className="account_buttons_container">
<OutlinedButton
className="account_action_button"
disabled={!window.onLine}
onClick={async () => {
axios.put("/user/reader", await getAllReadBooks()).then((res) => {
if (res.status === 200) {
toast.success("Успешно!");
} else {
toast.error("Что то пошло не так");
}
});
}}
>
<Icon slot="icon">upload</Icon>
Загрузить на сервер
</OutlinedButton>
<OutlinedButton
className="account_action_button"
disabled={!window.onLine}
onClick={async () => {
axios.get("/user/reader").then(async (res) => {
if (res.status === 200) {
await window.caches.delete("bookCovers");
await syncReadBook(res.data);
updateBookshelf();
toast.success("Успешно!");
} else {
toast.error("Что то пошло не так");
}
});
}}
>
<Icon slot="icon">download</Icon>
Получить с сервера
</OutlinedButton>
</div> */}
{/*<h3>Избранное</h3>
<div className="results_container">
{
window.ononline ?
accountInfo.favorites === undefined ?
<Skeleton/>
:
accountInfo.favorites === null || accountInfo.favorites.length === 0 ?
<p>Нет избранных книг 💔</p>
:
accountInfo.favorites.map(value => <BookCard
key={value.id}
id={value.id}
authors={value.authors}
title={value.title}
/>)
: <p>Невозможно загрузить избранное в офлайн режиме ✈️</p>
}
</div>*/}
{/* todo */}
{/* <h3>Продолжить чтение</h3>
<div className="results_container">
{
bookshelf === false ?
<Skeleton/>
:
bookshelf.length === 0 ?
<p>Вы еще ничего не добавляли на полку</p>
:
bookshelf
}
</div> */}
</>
);
};
export default Main;
+36
View File
@@ -0,0 +1,36 @@
import { useEffect, useState } from "react";
import { getAllBooks } from "../../db";
import BookCard from "../../components/bookCard/BookCard";
function ShelvePage() {
const [allBooks, setAllBooks] = useState([]);
async function loadBooks() {
let allBooks = await getAllBooks();
setAllBooks(allBooks);
}
useEffect(() => {
loadBooks();
}, []);
return (
<>
<h2>Книги, доступные оффлайн</h2>
<div className="flex flex-wrap">
{allBooks.length === 0 ? (
<span>Тут ничего нет</span>
) : (
allBooks.map((book) => (
<BookCard
key={book.id}
id={book.id}
authors={book.authors ? book.authors : []}
title={book.title}
filetype={book.filetype}
offline
/>
))
)}
</div>
</>
);
}
export default ShelvePage;
+140
View File
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState } from "react";
import FilledButton from "../../md-components/FilledButton";
import Icon from "../../md-components/Icon";
import IconButton from "../../md-components/IconButton";
import axios from "axios";
import { toast } from "react-toastify";
function UploadBook() {
const fileSelectorRef = useRef();
const [uploadedFiles, setUploadedFiles] = useState([]);
const [uploadStatuses, setUploadStatuses] = useState([]);
const [isDragging, setIsDragging] = useState(false);
const [uploading, setUploading] = useState(false);
const handleFileChange = (e) => {
const files = Array.from(e.target.files);
setUploadedFiles((prev) => [...prev, ...files]);
};
const handleDrop = (e) => {
e.preventDefault();
setIsDragging(false);
const droppedFiles = Array.from(e.dataTransfer.files);
setUploadedFiles((prev) => [...prev, ...droppedFiles]);
};
const handleDragOver = (e) => {
e.preventDefault();
setIsDragging(true);
};
const handleDragLeave = () => {
setIsDragging(false);
};
useEffect(
() => setUploadStatuses(uploadedFiles.map(() => 0)),
[uploadedFiles]
);
const handleUpload = async () => {
setUploading(true);
console.log(uploading);
if (uploadedFiles.length === 0) {
alert("Нечего грузить, капитан.");
return;
}
for (const [i, file] of uploadedFiles.entries()) {
const formData = new FormData();
formData.append("files", file);
try {
console.log(uploadedFiles);
const res = await axios.post("/book/upload", formData);
console.log(res);
if (res.status === 200) {
// toast("Залили! 🧃");
setUploadStatuses((prev) => ({ ...prev, [i]: 1 }));
console.log(uploadStatuses);
} else {
toast("Ошибка на сервере, go дебажить.");
}
} catch (err) {
console.error("Ошибка:", err);
toast("Шатался интернет или сервер умер.");
}
}
setUploading(false);
setUploadedFiles([]);
};
if (!window.onLine) {
return <span>Недоступно оффлайн</span>;
}
return (
<div className="flex flex-col items-center justify-center h-screen">
<h1 className="text-2xl font-bold mb-4">Загрузка литературы</h1>
<div
className={`flex items-center justify-around w-full max-w-lg h-50 mb-4 rounded-xl flex-col gap-1 px-4 border-2 border-dashed transition-colors duration-200 cursor-pointer border-(--md-sys-color-outline) ${
isDragging
? "bg-(--md-sys-color-surface-variant)"
: "bg-(--md-sys-color-inverse-on-surface)"
}`}
onClick={() => fileSelectorRef.current.click()}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
>
<>
<span className="font-bold">Перетащи файл сюда или кликни</span>
<IconButton className="w-24 h-24">
<Icon className="text-6xl w-24 h-24">upload_file</Icon>
</IconButton>
<span className="text-sm">Поддерживается .fb2 и .pdf</span>
</>
<input
type="file"
multiple
accept=".fb2,.pdf"
ref={fileSelectorRef}
className="hidden"
onChange={handleFileChange}
/>
</div>
<div className="w-full max-w-lg bg-(--md-sys-color-surface-variant) flex p-[18px] rounded-2xl flex-col max-h-60 overflow-scroll gap-3 mb-4">
{uploadedFiles.length === 0 ? <span>Нечего загружать</span> : <></>}
{uploadedFiles.map((file, i) => (
<div className="flex justify-between" key={i}>
<span className="truncate w-[calc(100%-42px)] inline-block">
{file.name}
</span>
{uploading ? (
<Icon className="text-(--md-sys-color-on-surface)">
{uploadStatuses[i] === 0
? "sync"
: uploadStatuses[i] === -1
? "error"
: "check_circle"}
</Icon>
) : (
<IconButton
onClick={() =>
setUploadedFiles((prev) => prev.filter((_, io) => io !== i))
}
>
<Icon>remove</Icon>
</IconButton>
)}
</div>
))}
</div>
<FilledButton onClick={handleUpload} disabled={uploading}>
Загрузить
</FilledButton>
</div>
);
}
export default UploadBook;
+137
View File
@@ -0,0 +1,137 @@
.book_content h2 {
text-align: center;
margin: 0;
font-size: 23px;
margin: 23px;
}
.book_content emphasis {
font-style: italic;
}
.book_content epigraph {
display: block;
font-style: italic;
background-color: var(--md-sys-color-inverse-on-surface);
margin: calc(23px/2);
padding: calc(23px/2);
border-radius: 10px;
}
.book_content epigraph b {
margin-left: 15px;
display: block;
}
.book_content poem {
display: block;
margin: 23px 25px;
}
.book_content poem v {
display: block;
text-indent: 25px;
}
.book_content p {
margin: 0;
text-indent: 25px;
}
.book_content sub {
line-height: 23px;
}
.reader_container {
position: relative;
height: calc(100vh - 30px - 40px);
border: 1px solid gray;
/*border-bottom: 0;*/
border-radius: 15px 15px 0 0;
overflow: hidden;
display: flex;
align-items: center;
}
.book_content {
overflow:hidden;
line-height: 23px;
padding: 0 23px;
width: 100%;
color: var(--md-sys-color-on-background);
}
.book_content a {
color: var(--md-sys-color-on-background);
}
.book_img {
display: block;
margin: 0 auto;
max-width: 100%;
}
.reader_progress {
position: absolute;
bottom: 0;
height: 5px;
background-color: var(--md-sys-color-primary);
transition: all 0.5s;
}
.reader_contents {
position: fixed;
top: 25px;
left: 10px;
overflow: hidden;
transition: 0.5s;
transform: translateX(0);
background: var(--md-sys-color-background);
z-index: 1;
border-radius: 15px;
border: 1px solid var(--md-sys-color-outline);
}
.contents_button {
display: none;
}
.reader_contents_backdrop {
visibility: hidden;
pointer-events: none;
opacity: 0;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: var(--md-sys-color-outline-variant);
z-index: 1;
transition: 0.5s;
}
.reader_contents_backdrop.show {
visibility: visible;
opacity: 0.4;
pointer-events: all;
}
code {
line-height: 23px;
}
.reader_buttons_container {
display: flex;
gap: 25px;
margin: 20px 0;
}
@media screen and (max-width: 1880px) {
.reader_contents {
transform: translateX(calc(-100% - 15px));
border: none;
}
.reader_contents.show {
transform: translateX(15px);
box-shadow: 0px 0px 35px -15px var(--md-sys-color-shadow);
}
.contents_button {
display: block;
}
}
@media screen and (max-width: 750px) { /* кнопки в столбик */
.reader_buttons_container {
flex-direction: column;
gap: 10px;
}
.reader_action_button {
flex-basis: auto;
}
}
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useState } from "react"
import './search.css'
import { useNavigate } from "react-router"
import { useSearchParams } from "react-router-dom"
import FilledButton from "../md-components/FilledButton"
import Icon from "../md-components/Icon"
import InputChip from "../md-components/InputChip"
import axios from "axios"
const Search = () => {
const [searchParams, setSearchParams] = useSearchParams()
const searchText = searchParams.get("q")
const fromSearch = searchParams.get("from_search")
const authorId = searchParams.get("author")
const navigate = useNavigate()
const [value, setValue] = useState(searchText === null ? "" : searchText)
const [authorInfo, setAuthorInfo] = useState({name: "..."})
useEffect(() => {
if (!authorId) return
axios.get("/author/"+authorId)
.then(res => setAuthorInfo(res.data))
}, [authorId])
useEffect(() => {
if (searchText === null) {
if (fromSearch !== null) {
setValue(fromSearch)
} else {
setValue("")
}
} else {
setValue(searchText)
}
}, [searchParams])
function search() {
if (!searchParams.has("q") && !searchParams.has("author")) {
navigate(`/search?q=${value}&offset=0&limit=10`)
} else {
if (value === '' && authorId) {
searchParams.delete("q")
} else {
searchParams.set("q", value)
}
searchParams.set("offset", "0")
setSearchParams(searchParams)
}
}
function removeAuthorFilter() {
// remove author filter
searchParams.delete("author")
searchParams.set("q", value)
setSearchParams(searchParams)
}
return (
<div className="search_container">
<div className="text-field-block">
{
authorId ?
<div>
<InputChip
className="search_mobile_chip"
onRemove={removeAuthorFilter}
removable
removeOnly
>
<Icon slot="icon">person</Icon>
</InputChip>
<InputChip
className="search_chip"
label={authorInfo.name}
onRemove={removeAuthorFilter}
removable
removeOnly
/>
</div>
: <></>
}
<input
className="text-field"
placeholder={authorId ? 'поиск по автору' : 'поиск на YaBL'}
onChange={e => setValue(e.target.value)}
value={value}
onKeyDown={e => {
if (e.key === "Enter") search()
if (e.key === "Backspace" && e.target.selectionStart === 0 && e.target.selectionEnd === 0 && searchParams.has("author")) removeAuthorFilter()
}}
/>
</div>
<FilledButton
className="search_button"
onClick={search}
>
<span className="search_button_text">Поиск</span>
<Icon className="search_button_icon">search</Icon>
</FilledButton>
</div>
)
}
export default Search
+79
View File
@@ -0,0 +1,79 @@
.text-field-block {
max-width: 500px;
width: calc(100% - 130px);
height: 46px;
border: 1px solid gray;
padding-left: 15px;
border-right: 0;
border-radius: 9999px 0 0 9999px;
box-sizing: border-box;
background: var(--md-sys-color-surface);
display: flex;
overflow: hidden;
align-items: center;
gap: 10px;
}
.text-field {
border: 0;
margin: 0;
padding: 0;
width: 100%;
font-size: 16px;
padding: 16px 0;
background: var(--md-sys-color-surface);
color: var(--md-sys-color-on-surface);
outline: 0;
}
.text-field-box:focus {
outline: 0;
border-width: 2px;
padding: 15px;
}
.search_button {
height: 46px;
width: 130px;
border: 0;
--_container-shape-start-start: 0;
--_container-shape-end-start: 0;
}
.search_button span {
color: var(--md-sys-color-on-primary);
}
.search_button_icon {
display: none;
}
.search_container {
max-width: 630px;
width: 100%;
white-space: nowrap;
padding: 0 20px;
display: flex;
}
.search_mobile_chip {
display: none;
}
@media screen and (max-width: 600px) {
.search_button {
width: fit-content;
padding: 15px;
}
.search_button_text {
display: none;
}
.search_button_icon {
display: block;
}
.text-field-block {
width: calc(100% - 0px);
}
.search_container {
padding: 0 10px;
}
.search_chip {
display: none;
}
.search_mobile_chip {
display: block;
}
}
+13
View File
@@ -0,0 +1,13 @@
const converter = {
'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd',
'е': 'e', 'ё': 'e', 'ж': 'zh', 'з': 'z', 'и': 'i',
'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n',
'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't',
'у': 'u', 'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch',
'ш': 'sh', 'щ': 'sch', 'ь': '', 'ы': 'y', 'ъ': '',
'э': 'e', 'ю': 'yu', 'я': 'ya', ' ': "_",
};
// TODO: if language not cyrillic or latin (ex chinese), may cause errors, but mne pofig
export function translit(word){
return word.toLowerCase().split("").map(letter => converter[letter] === undefined ? letter : converter[letter]).join("")
}