mirror of
https://github.com/ItzCrazyKns/Perplexica.git
synced 2025-04-30 16:22:29 +00:00
Compare commits
8 Commits
1862491496
...
admin-pass
Author | SHA1 | Date | |
---|---|---|---|
|
a401e67d87 | ||
|
d95849e538 | ||
|
ec5e5b3893 | ||
|
639fbd7a15 | ||
|
a88104434d | ||
|
a1e0d368c6 | ||
|
5779701b7d | ||
|
fdfe8d1f41 |
@ -1,6 +1,10 @@
|
||||
[GENERAL]
|
||||
PORT = 3001 # Port to run the server on
|
||||
SIMILARITY_MEASURE = "cosine" # "cosine" or "dot"
|
||||
CONFIG_PASSWORD = "lorem_ipsum" # Password to access config
|
||||
DISCOVER_ENABLED = true
|
||||
LIBRARY_ENABLED = true
|
||||
COPILOT_ENABLED = true
|
||||
KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m")
|
||||
|
||||
[MODELS.OPENAI]
|
||||
@ -18,6 +22,7 @@ API_KEY = ""
|
||||
[MODELS.CUSTOM_OPENAI]
|
||||
API_KEY = ""
|
||||
API_URL = ""
|
||||
MODEL_NAME = ""
|
||||
|
||||
[MODELS.OLLAMA]
|
||||
API_URL = "" # Ollama API URL - http://host.docker.internal:11434
|
||||
|
@ -8,6 +8,10 @@ interface Config {
|
||||
GENERAL: {
|
||||
PORT: number;
|
||||
SIMILARITY_MEASURE: string;
|
||||
CONFIG_PASSWORD: string;
|
||||
DISCOVER_ENABLED: boolean;
|
||||
LIBRARY_ENABLED: boolean;
|
||||
COPILOT_ENABLED: boolean;
|
||||
KEEP_ALIVE: string;
|
||||
};
|
||||
MODELS: {
|
||||
@ -51,6 +55,14 @@ export const getPort = () => loadConfig().GENERAL.PORT;
|
||||
export const getSimilarityMeasure = () =>
|
||||
loadConfig().GENERAL.SIMILARITY_MEASURE;
|
||||
|
||||
export const getConfigPassword = () => loadConfig().GENERAL.CONFIG_PASSWORD;
|
||||
|
||||
export const isDiscoverEnabled = () => loadConfig().GENERAL.DISCOVER_ENABLED;
|
||||
|
||||
export const isLibraryEnabled = () => loadConfig().GENERAL.LIBRARY_ENABLED;
|
||||
|
||||
export const isCopilotEnabled = () => loadConfig().GENERAL.COPILOT_ENABLED;
|
||||
|
||||
export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE;
|
||||
|
||||
export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY;
|
||||
|
@ -10,6 +10,10 @@ import {
|
||||
getGeminiApiKey,
|
||||
getOpenaiApiKey,
|
||||
updateConfig,
|
||||
getConfigPassword,
|
||||
isLibraryEnabled,
|
||||
isCopilotEnabled,
|
||||
isDiscoverEnabled,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiModelName,
|
||||
@ -18,8 +22,16 @@ import logger from '../utils/logger';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', async (_, res) => {
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const authHeader = req.headers['authorization']?.split(' ')[1];
|
||||
const password = getConfigPassword();
|
||||
|
||||
if (authHeader !== password) {
|
||||
res.status(401).json({ message: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
const config = {};
|
||||
|
||||
const [chatModelProviders, embeddingModelProviders] = await Promise.all([
|
||||
@ -69,9 +81,22 @@ router.get('/', async (_, res) => {
|
||||
});
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
const authHeader = req.headers['authorization']?.split(' ')[1];
|
||||
const password = getConfigPassword();
|
||||
|
||||
if (authHeader !== password) {
|
||||
res.status(401).json({ message: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
const config = req.body;
|
||||
|
||||
const updatedConfig = {
|
||||
GENERAL: {
|
||||
DISCOVER_ENABLED: config.isDiscoverEnabled,
|
||||
LIBRARY_ENABLED: config.isLibraryEnabled,
|
||||
COPILOT_ENABLED: config.isCopilotEnabled,
|
||||
},
|
||||
MODELS: {
|
||||
OPENAI: {
|
||||
API_KEY: config.openaiApiKey,
|
||||
@ -101,4 +126,14 @@ router.post('/', async (req, res) => {
|
||||
res.status(200).json({ message: 'Config updated' });
|
||||
});
|
||||
|
||||
router.get('/preferences', (_, res) => {
|
||||
const preferences = {
|
||||
isLibraryEnabled: isLibraryEnabled(),
|
||||
isCopilotEnabled: isCopilotEnabled(),
|
||||
isDiscoverEnabled: isDiscoverEnabled(),
|
||||
};
|
||||
|
||||
res.status(200).json(preferences);
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
@ -9,10 +9,33 @@ const router = express.Router();
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const [chatModelProviders, embeddingModelProviders] = await Promise.all([
|
||||
getAvailableChatModelProviders(),
|
||||
getAvailableEmbeddingModelProviders(),
|
||||
]);
|
||||
const [chatModelProvidersRaw, embeddingModelProvidersRaw] =
|
||||
await Promise.all([
|
||||
getAvailableChatModelProviders(),
|
||||
getAvailableEmbeddingModelProviders(),
|
||||
]);
|
||||
|
||||
const chatModelProviders = {};
|
||||
|
||||
const chatModelProvidersKeys = Object.keys(chatModelProvidersRaw);
|
||||
chatModelProvidersKeys.forEach((provider) => {
|
||||
chatModelProviders[provider] = {};
|
||||
const models = Object.keys(chatModelProvidersRaw[provider]);
|
||||
models.forEach((model) => {
|
||||
chatModelProviders[provider][model] = {};
|
||||
});
|
||||
});
|
||||
|
||||
const embeddingModelProviders = {};
|
||||
|
||||
const embeddingModelProvidersKeys = Object.keys(embeddingModelProvidersRaw);
|
||||
embeddingModelProvidersKeys.forEach((provider) => {
|
||||
embeddingModelProviders[provider] = {};
|
||||
const models = Object.keys(embeddingModelProvidersRaw[provider]);
|
||||
models.forEach((model) => {
|
||||
embeddingModelProviders[provider][model] = {};
|
||||
});
|
||||
});
|
||||
|
||||
Object.keys(chatModelProviders).forEach((provider) => {
|
||||
Object.keys(chatModelProviders[provider]).forEach((model) => {
|
||||
|
@ -5,8 +5,9 @@ import type { Embeddings } from '@langchain/core/embeddings';
|
||||
import logger from '../utils/logger';
|
||||
import db from '../db';
|
||||
import { chats, messages as messagesSchema } from '../db/schema';
|
||||
import { eq, asc, gt, and } from 'drizzle-orm';
|
||||
import { eq, gt, and } from 'drizzle-orm';
|
||||
import crypto from 'crypto';
|
||||
import { isLibraryEnabled } from '../config';
|
||||
import { getFileDetails } from '../utils/files';
|
||||
import MetaSearchAgent, {
|
||||
MetaSearchAgentType,
|
||||
@ -94,6 +95,8 @@ const handleEmitterEvents = (
|
||||
let recievedMessage = '';
|
||||
let sources = [];
|
||||
|
||||
const libraryEnabled = isLibraryEnabled();
|
||||
|
||||
emitter.on('data', (data) => {
|
||||
const parsedData = JSON.parse(data);
|
||||
if (parsedData.type === 'response') {
|
||||
@ -119,18 +122,20 @@ const handleEmitterEvents = (
|
||||
emitter.on('end', () => {
|
||||
ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId }));
|
||||
|
||||
db.insert(messagesSchema)
|
||||
.values({
|
||||
content: recievedMessage,
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
role: 'assistant',
|
||||
metadata: JSON.stringify({
|
||||
createdAt: new Date(),
|
||||
...(sources && sources.length > 0 && { sources }),
|
||||
}),
|
||||
})
|
||||
.execute();
|
||||
if (libraryEnabled) {
|
||||
db.insert(messagesSchema)
|
||||
.values({
|
||||
content: recievedMessage,
|
||||
chatId: chatId,
|
||||
messageId: messageId,
|
||||
role: 'assistant',
|
||||
metadata: JSON.stringify({
|
||||
createdAt: new Date(),
|
||||
...(sources && sources.length > 0 && { sources }),
|
||||
}),
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
emitter.on('error', (data) => {
|
||||
const parsedData = JSON.parse(data);
|
||||
@ -188,6 +193,8 @@ export const handleMessage = async (
|
||||
const handler: MetaSearchAgentType =
|
||||
searchHandlers[parsedWSMessage.focusMode];
|
||||
|
||||
const libraryEnabled = isLibraryEnabled();
|
||||
|
||||
if (handler) {
|
||||
try {
|
||||
const emitter = await handler.searchAndAnswer(
|
||||
@ -201,50 +208,52 @@ export const handleMessage = async (
|
||||
|
||||
handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId);
|
||||
|
||||
const chat = await db.query.chats.findFirst({
|
||||
where: eq(chats.id, parsedMessage.chatId),
|
||||
});
|
||||
if (libraryEnabled) {
|
||||
const chat = await db.query.chats.findFirst({
|
||||
where: eq(chats.id, parsedMessage.chatId),
|
||||
});
|
||||
|
||||
if (!chat) {
|
||||
await db
|
||||
.insert(chats)
|
||||
.values({
|
||||
id: parsedMessage.chatId,
|
||||
title: parsedMessage.content,
|
||||
createdAt: new Date().toString(),
|
||||
focusMode: parsedWSMessage.focusMode,
|
||||
files: parsedWSMessage.files.map(getFileDetails),
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
if (!chat) {
|
||||
await db
|
||||
.insert(chats)
|
||||
.values({
|
||||
id: parsedMessage.chatId,
|
||||
title: parsedMessage.content,
|
||||
createdAt: new Date().toString(),
|
||||
focusMode: parsedWSMessage.focusMode,
|
||||
files: parsedWSMessage.files.map(getFileDetails),
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
|
||||
const messageExists = await db.query.messages.findFirst({
|
||||
where: eq(messagesSchema.messageId, humanMessageId),
|
||||
});
|
||||
const messageExists = await db.query.messages.findFirst({
|
||||
where: eq(messagesSchema.messageId, humanMessageId),
|
||||
});
|
||||
|
||||
if (!messageExists) {
|
||||
await db
|
||||
.insert(messagesSchema)
|
||||
.values({
|
||||
content: parsedMessage.content,
|
||||
chatId: parsedMessage.chatId,
|
||||
messageId: humanMessageId,
|
||||
role: 'user',
|
||||
metadata: JSON.stringify({
|
||||
createdAt: new Date(),
|
||||
}),
|
||||
})
|
||||
.execute();
|
||||
} else {
|
||||
await db
|
||||
.delete(messagesSchema)
|
||||
.where(
|
||||
and(
|
||||
gt(messagesSchema.id, messageExists.id),
|
||||
eq(messagesSchema.chatId, parsedMessage.chatId),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
if (!messageExists) {
|
||||
await db
|
||||
.insert(messagesSchema)
|
||||
.values({
|
||||
content: parsedMessage.content,
|
||||
chatId: parsedMessage.chatId,
|
||||
messageId: humanMessageId,
|
||||
role: 'user',
|
||||
metadata: JSON.stringify({
|
||||
createdAt: new Date(),
|
||||
}),
|
||||
})
|
||||
.execute();
|
||||
} else {
|
||||
await db
|
||||
.delete(messagesSchema)
|
||||
.where(
|
||||
and(
|
||||
gt(messagesSchema.id, messageExists.id),
|
||||
eq(messagesSchema.chatId, parsedMessage.chatId),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
|
@ -5,7 +5,31 @@ export const metadata: Metadata = {
|
||||
title: 'Library - Perplexica',
|
||||
};
|
||||
|
||||
const Layout = ({ children }: { children: React.ReactNode }) => {
|
||||
const Layout = async ({ children }: { children: React.ReactNode }) => {
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
const { isLibraryEnabled } = data;
|
||||
|
||||
if (!isLibraryEnabled) {
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-center min-h-screen w-full">
|
||||
<p className="text-lg dark:text-white/70 text-black/70">
|
||||
Library is disabled
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <div>{children}</div>;
|
||||
};
|
||||
|
||||
|
@ -1,8 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import DeleteChat from '@/components/DeleteChat';
|
||||
import { cn, formatTimeDifference } from '@/lib/utils';
|
||||
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react';
|
||||
import { formatTimeDifference } from '@/lib/utils';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { BookOpenText, ClockIcon } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
|
@ -112,6 +112,83 @@ const Page = () => {
|
||||
const [automaticImageSearch, setAutomaticImageSearch] = useState(false);
|
||||
const [automaticVideoSearch, setAutomaticVideoSearch] = useState(false);
|
||||
const [savingStates, setSavingStates] = useState<Record<string, boolean>>({});
|
||||
|
||||
const [password, setPassword] = useState('');
|
||||
const [passwordSubmitted, setPasswordSubmitted] = useState(false);
|
||||
const [isPasswordValid, setIsPasswordValid] = useState(true);
|
||||
|
||||
const handlePasswordSubmit = async () => {
|
||||
setIsLoading(true);
|
||||
setPasswordSubmitted(true);
|
||||
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${password}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
setIsPasswordValid(false);
|
||||
setPasswordSubmitted(false);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
} else {
|
||||
setIsPasswordValid(true);
|
||||
}
|
||||
|
||||
const data = (await res.json()) as SettingsType;
|
||||
setConfig(data);
|
||||
|
||||
const chatModelProvidersKeys = Object.keys(data.chatModelProviders || {});
|
||||
const embeddingModelProvidersKeys = Object.keys(
|
||||
data.embeddingModelProviders || {},
|
||||
);
|
||||
|
||||
const defaultChatModelProvider =
|
||||
chatModelProvidersKeys.length > 0 ? chatModelProvidersKeys[0] : '';
|
||||
const defaultEmbeddingModelProvider =
|
||||
embeddingModelProvidersKeys.length > 0
|
||||
? embeddingModelProvidersKeys[0]
|
||||
: '';
|
||||
|
||||
const chatModelProvider =
|
||||
localStorage.getItem('chatModelProvider') ||
|
||||
defaultChatModelProvider ||
|
||||
'';
|
||||
const chatModel =
|
||||
localStorage.getItem('chatModel') ||
|
||||
(data.chatModelProviders &&
|
||||
data.chatModelProviders[chatModelProvider]?.length > 0
|
||||
? data.chatModelProviders[chatModelProvider][0].name
|
||||
: undefined) ||
|
||||
'';
|
||||
const embeddingModelProvider =
|
||||
localStorage.getItem('embeddingModelProvider') ||
|
||||
defaultEmbeddingModelProvider ||
|
||||
'';
|
||||
const embeddingModel =
|
||||
localStorage.getItem('embeddingModel') ||
|
||||
(data.embeddingModelProviders &&
|
||||
data.embeddingModelProviders[embeddingModelProvider]?.[0].name) ||
|
||||
'';
|
||||
|
||||
setSelectedChatModelProvider(chatModelProvider);
|
||||
setSelectedChatModel(chatModel);
|
||||
setSelectedEmbeddingModelProvider(embeddingModelProvider);
|
||||
setSelectedEmbeddingModel(embeddingModel);
|
||||
setChatModels(data.chatModelProviders || {});
|
||||
setEmbeddingModels(data.embeddingModelProviders || {});
|
||||
|
||||
setAutomaticImageSearch(
|
||||
localStorage.getItem('autoImageSearch') === 'true',
|
||||
);
|
||||
setAutomaticVideoSearch(
|
||||
localStorage.getItem('autoVideoSearch') === 'true',
|
||||
);
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchConfig = async () => {
|
||||
@ -119,6 +196,7 @@ const Page = () => {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${password}`,
|
||||
},
|
||||
});
|
||||
|
||||
@ -193,11 +271,16 @@ const Page = () => {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${password}`,
|
||||
},
|
||||
body: JSON.stringify(updatedConfig),
|
||||
},
|
||||
);
|
||||
|
||||
if (response.status === 401) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to update config');
|
||||
}
|
||||
@ -211,6 +294,7 @@ const Page = () => {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${password}`,
|
||||
},
|
||||
});
|
||||
|
||||
@ -376,6 +460,33 @@ const Page = () => {
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : !passwordSubmitted ? (
|
||||
<div className="flex flex-col max-w-md mx-auto mt-10 p-6 bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 rounded-2xl">
|
||||
<h2 className="text-sm text-black/80 dark:text-white/80">
|
||||
Enter the password to access the settings
|
||||
</h2>
|
||||
<div className="flex flex-col">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
className="mt-4"
|
||||
disabled={isLoading}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{!isPasswordValid && (
|
||||
<p className="text-xs text-red-500 mt-2">
|
||||
Password is incorrect
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
onClick={handlePasswordSubmit}
|
||||
disabled={isLoading}
|
||||
className="bg-[#24A0ED] flex flex-row items-center text-xs mt-4 text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full px-4 py-2"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
config && (
|
||||
<div className="flex flex-col space-y-6 pb-28 lg:pb-8">
|
||||
|
@ -1,5 +1,6 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Switch } from '@headlessui/react';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const CopilotToggle = ({
|
||||
copilotEnabled,
|
||||
@ -8,11 +9,33 @@ const CopilotToggle = ({
|
||||
copilotEnabled: boolean;
|
||||
setCopilotEnabled: (enabled: boolean) => void;
|
||||
}) => {
|
||||
const fetchAndSetCopilotEnabled = async () => {
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const preferences = await res.json();
|
||||
|
||||
setCopilotEnabled(preferences.isCopilotEnabled);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchAndSetCopilotEnabled();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer">
|
||||
<Switch
|
||||
checked={copilotEnabled}
|
||||
onChange={setCopilotEnabled}
|
||||
disabled={true}
|
||||
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full"
|
||||
>
|
||||
<span className="sr-only">Copilot</span>
|
||||
|
@ -4,9 +4,15 @@ import { cn } from '@/lib/utils';
|
||||
import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useSelectedLayoutSegments } from 'next/navigation';
|
||||
import React, { useState, type ReactNode } from 'react';
|
||||
import React, { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import Layout from './Layout';
|
||||
|
||||
export type Preferences = {
|
||||
isLibraryEnabled: boolean;
|
||||
isDiscoverEnabled: boolean;
|
||||
isCopilotEnabled: boolean;
|
||||
};
|
||||
|
||||
const VerticalIconContainer = ({ children }: { children: ReactNode }) => {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-y-3 w-full">{children}</div>
|
||||
@ -17,6 +23,31 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
|
||||
const segments = useSelectedLayoutSegments();
|
||||
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||
const [preferences, setPreferences] = useState<Preferences | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPreferences = async () => {
|
||||
setLoading(true);
|
||||
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
setPreferences(data);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
fetchPreferences();
|
||||
}, []);
|
||||
|
||||
const navLinks = [
|
||||
{
|
||||
@ -24,22 +55,44 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
|
||||
href: '/',
|
||||
active: segments.length === 0 || segments.includes('c'),
|
||||
label: 'Home',
|
||||
show: true,
|
||||
},
|
||||
{
|
||||
icon: Search,
|
||||
href: '/discover',
|
||||
active: segments.includes('discover'),
|
||||
label: 'Discover',
|
||||
show: preferences?.isDiscoverEnabled,
|
||||
},
|
||||
{
|
||||
icon: BookOpenText,
|
||||
href: '/library',
|
||||
active: segments.includes('library'),
|
||||
label: 'Library',
|
||||
show: preferences?.isLibraryEnabled,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
return loading ? (
|
||||
<div className="flex flex-row items-center justify-center h-full">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col">
|
||||
<div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8">
|
||||
@ -47,23 +100,26 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
|
||||
<SquarePen className="cursor-pointer" />
|
||||
</a>
|
||||
<VerticalIconContainer>
|
||||
{navLinks.map((link, i) => (
|
||||
<Link
|
||||
key={i}
|
||||
href={link.href}
|
||||
className={cn(
|
||||
'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg',
|
||||
link.active
|
||||
? 'text-black dark:text-white'
|
||||
: 'text-black/70 dark:text-white/70',
|
||||
)}
|
||||
>
|
||||
<link.icon />
|
||||
{link.active && (
|
||||
<div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" />
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
{navLinks.map(
|
||||
(link, i) =>
|
||||
link.show === true && (
|
||||
<Link
|
||||
key={i}
|
||||
href={link.href}
|
||||
className={cn(
|
||||
'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg',
|
||||
link.active
|
||||
? 'text-black dark:text-white'
|
||||
: 'text-black/70 dark:text-white/70',
|
||||
)}
|
||||
>
|
||||
<link.icon />
|
||||
{link.active && (
|
||||
<div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" />
|
||||
)}
|
||||
</Link>
|
||||
),
|
||||
)}
|
||||
</VerticalIconContainer>
|
||||
|
||||
<Link href="/settings">
|
||||
|
Reference in New Issue
Block a user