wip: search modal (link, category, or Google) with keybinds

This commit is contained in:
Sonny
2023-04-24 01:37:55 +02:00
parent d055387363
commit 43c7aab885
11 changed files with 595 additions and 46 deletions

View File

@@ -0,0 +1,32 @@
import { ReactNode } from "react";
import { createPortal } from "react-dom";
import styles from "./modal.module.scss";
interface ModalProps {
close?: (...args: any) => void | Promise<void>;
title?: string;
children: ReactNode;
showCloseBtn?: boolean;
}
export default function Modal({
close,
title,
children,
showCloseBtn = true,
}: ModalProps) {
return createPortal(
<div className={styles["modal-wrapper"]}>
<div className={styles["modal-container"]}>
<div className={styles["modal-header"]}>
<h3>{title}</h3>
{showCloseBtn && <button onClick={close}>close</button>}
</div>
<div className={styles["modal-body"]}>{children}</div>
</div>
</div>,
document.body
);
}

View File

@@ -0,0 +1,22 @@
@import "../../styles/colors.scss";
.modal-wrapper {
z-index: 9999;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba($black, 0.5);
backdrop-filter: blur(0.25em);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.modal-container {
background: $light-grey;
min-height: 250px;
min-width: 250px;
}

View File

@@ -0,0 +1,183 @@
import LinkTag from "next/link";
import { ReactNode, useCallback, useMemo, useState } from "react";
import { FcGoogle } from "react-icons/fc";
import useAutoFocus from "../../hooks/useAutoFocus";
import FormLayout from "../FormLayout";
import LinkFavicon from "../Links/LinkFavicon";
import Modal from "../Modal/Modal";
import TextBox from "../TextBox";
import { Category, ItemComplete, Link } from "../../types";
import styles from "./search.module.scss";
export default function SearchModal({
close,
handleSelectCategory,
categories,
favorites,
items,
}: {
close: any;
handleSelectCategory: (category: Category) => void;
categories: Category[];
favorites: Link[];
items: ItemComplete[];
}) {
const autoFocusRef = useAutoFocus();
const [search, setSearch] = useState<string>("");
const canSubmit = useMemo<boolean>(() => search.length > 0, [search]);
const itemsCompletion = useMemo(() => {
if (search.length === 0) {
return [];
}
return items.filter((item) =>
item.name.toLocaleLowerCase().includes(search.toLocaleLowerCase().trim())
);
}, [items, search]);
const handleSubmit = useCallback(
(event) => {
event.preventDefault();
setSearch("");
if (itemsCompletion.length > 0) {
const firstItem = itemsCompletion[0];
if (firstItem.type === "link") {
window.open(firstItem.url);
} else {
const category = categories.find((c) => c.id === firstItem.id);
console.log(category);
if (category) {
handleSelectCategory(category);
}
}
} else {
window.open(`https://google.com/search?q=${encodeURI(search.trim())}`);
}
close();
},
[categories, close, handleSelectCategory, itemsCompletion, search]
);
return (
<Modal title="Rechercher" close={close}>
<FormLayout
title="Search"
canSubmit={canSubmit}
handleSubmit={handleSubmit}
>
<TextBox
name="search"
onChangeCallback={(value) => setSearch(value)}
value={search}
placeholder="Rechercher"
innerRef={autoFocusRef}
fieldClass={styles["search-input-field"]}
/>
{search.length === 0 && favorites.length > 0 && (
<ListItemComponent
items={favorites.map((favorite) => ({
id: favorite.id,
name: favorite.name,
url: favorite.url,
type: "link",
}))}
noItem={<p>ajouter un favoris</p>}
/>
)}
{search.length > 0 && (
<ListItemComponent
items={itemsCompletion.map((item) => ({
id: item.id,
name: item.name,
url: item.url,
type: item.type,
}))}
noItem={
<i
style={{
display: "flex",
alignItems: "center",
gap: ".25em",
}}
>
Recherche avec{" "}
<span style={{ display: "flex", alignItems: "center" }}>
<FcGoogle size={24} />
oogle
</span>
</i>
}
/>
)}
</FormLayout>
</Modal>
);
}
function ListItemComponent({
items,
noItem,
}: {
items: ItemComplete[];
noItem?: ReactNode;
}) {
return (
<ul
style={{
margin: "1em 0",
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "1em",
flexWrap: "wrap",
}}
>
{items.length > 0 ? (
items.map((item) => (
<ItemComponent
item={{
id: item.id,
name: item.name,
url: item.url,
type: item.type,
}}
key={item.type + "-" + item.id}
/>
))
) : noItem ? (
noItem
) : (
<i>no item found</i>
)}
</ul>
);
}
function ItemComponent({ item }: { item: ItemComplete }) {
const { name, type, url } = item;
return (
<li>
<LinkTag
href={url}
style={{
display: "flex",
flexDirection: "column",
}}
target="_blank"
rel="no-referrer"
>
{type === "link" ? (
<LinkFavicon url={item.url} noMargin />
) : (
<span>category</span>
)}
<span>{name}</span>
</LinkTag>
</li>
);
}

View File

@@ -0,0 +1,7 @@
.search-input-field {
& input {
border-radius: 1.5em;
padding: 1em;
border: 1px solid transparent;
}
}

View File

@@ -50,14 +50,20 @@ function MenuControls({
}) {
return (
<div className={styles["menu-controls"]}>
<div className="action">
<LinkTag href={"/search"}>Rechercher</LinkTag>
<kbd>S</kbd>
</div>
<div className="action">
<LinkTag href={"/category/create"}>Créer categorie</LinkTag>
<LinkTag href={"/category/create"}>
Créer categorie <kbd>C</kbd>
</LinkTag>
<kbd>C</kbd>
</div>
<div className="action">
<LinkTag href={`/link/create?categoryId=${categoryActive.id}`}>
Créer lien
Créer lien <kbd>L</kbd>
</LinkTag>
<kbd>L</kbd>
</div>
</div>
);
}

18
hooks/useModal.tsx Normal file
View File

@@ -0,0 +1,18 @@
import { useState } from "react";
const useModal = () => {
const [isShowing, setIsShowing] = useState<boolean>(false);
const toggle = () => setIsShowing((value) => !value);
const open = () => setIsShowing(true);
const close = () => setIsShowing(false);
return {
isShowing,
toggle,
open,
close,
};
};
export default useModal;

16
package-lock.json generated
View File

@@ -9,7 +9,6 @@
"@prisma/client": "^4.12.0",
"@svgr/webpack": "^7.0.0",
"axios": "^1.3.5",
"hotkeys-js": "^3.10.2",
"next": "^13.3.0",
"next-auth": "^4.22.0",
"next-seo": "^6.0.0",
@@ -17,6 +16,7 @@
"nprogress": "^0.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hotkeys-hook": "^4.4.0",
"react-icons": "^4.8.0",
"react-select": "^5.7.2",
"sass": "^1.62.0",
@@ -4571,11 +4571,6 @@
"react-is": "^16.7.0"
}
},
"node_modules/hotkeys-js": {
"version": "3.10.2",
"resolved": "https://registry.npmjs.org/hotkeys-js/-/hotkeys-js-3.10.2.tgz",
"integrity": "sha512-Z6vLmJTYzkbZZXlBkhrYB962Q/rZGc/WHQiyEGu9ZZVF7bAeFDjjDa31grWREuw9Ygb4zmlov2bTkPYqj0aFnQ=="
},
"node_modules/ignore": {
"version": "5.2.4",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz",
@@ -5753,6 +5748,15 @@
"react": "^18.2.0"
}
},
"node_modules/react-hotkeys-hook": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/react-hotkeys-hook/-/react-hotkeys-hook-4.4.0.tgz",
"integrity": "sha512-wOaCWLwgT/f895CMJrR9hmzVf+gfL8IpjWDXWXKngBp9i6Xqzf0tvLv4VI8l3Vlsg/cc4C/Iik3Ck76L/Hj0tw==",
"peerDependencies": {
"react": ">=16.8.1",
"react-dom": ">=16.8.1"
}
},
"node_modules/react-icons": {
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/react-icons/-/react-icons-4.8.0.tgz",

View File

@@ -11,7 +11,6 @@
"@prisma/client": "^4.12.0",
"@svgr/webpack": "^7.0.0",
"axios": "^1.3.5",
"hotkeys-js": "^3.10.2",
"next": "^13.3.0",
"next-auth": "^4.22.0",
"next-seo": "^6.0.0",
@@ -19,6 +18,7 @@
"nprogress": "^0.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hotkeys-hook": "^4.4.0",
"react-icons": "^4.8.0",
"react-select": "^5.7.2",
"sass": "^1.62.0",

View File

@@ -1,22 +1,33 @@
import hotkeys from "hotkeys-js";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useState } from "react";
import { useHotkeys } from "react-hotkeys-hook";
import useModal from "../hooks/useModal";
import Links from "../components/Links/Links";
import SearchModal from "../components/SearchModal/SearchModal";
import SideMenu from "../components/SideMenu/SideMenu";
import { Category, Link } from "../types";
import { Category, ItemComplete, Link } from "../types";
import { prisma } from "../utils/back";
import { BuildCategory } from "../utils/front";
const OPEN_SEARCH_KEY = "s";
const CLOSE_SEARCH_KEY = "escape";
const OPEN_CREATE_LINK_KEY = "l";
const OPEN_CREATE_CATEGORY_KEY = "c";
interface HomeProps {
categories: Category[];
favorites: Link[];
items: ItemComplete[];
currentCategory: Category | undefined;
}
function Home({ categories, favorites, currentCategory }: HomeProps) {
function Home({ categories, favorites, currentCategory, items }: HomeProps) {
const router = useRouter();
const modal = useModal();
const [categoryActive, setCategoryActive] = useState<Category | null>(
currentCategory || categories?.[0]
@@ -32,22 +43,32 @@ function Home({ categories, favorites, currentCategory }: HomeProps) {
);
};
const openSearchModal = useCallback(
(event) => {
event.preventDefault();
modal.open();
},
[modal]
);
const closeSearchModal = useCallback(() => modal.close(), [modal]);
const gotoCreateLink = useCallback(() => {
router.push(`/link/create?categoryId=${categoryActive.id}`);
}, [categoryActive.id, router]);
const gotoCreateCategory = useCallback(() => {
router.push("/category/create");
}, [router]);
useEffect(() => {
hotkeys("l", gotoCreateLink);
hotkeys("c", gotoCreateCategory);
useHotkeys(OPEN_SEARCH_KEY, openSearchModal, { enabled: !modal.isShowing });
useHotkeys(CLOSE_SEARCH_KEY, closeSearchModal, { enabled: modal.isShowing });
return () => {
hotkeys.unbind("l", gotoCreateLink);
hotkeys.unbind("c", gotoCreateCategory);
};
}, [gotoCreateCategory, gotoCreateLink]);
useHotkeys(OPEN_CREATE_LINK_KEY, gotoCreateLink, {
enabled: !modal.isShowing,
});
useHotkeys(OPEN_CREATE_CATEGORY_KEY, gotoCreateCategory, {
enabled: !modal.isShowing,
});
return (
<div className="App">
@@ -58,6 +79,15 @@ function Home({ categories, favorites, currentCategory }: HomeProps) {
categoryActive={categoryActive}
/>
<Links category={categoryActive} />
{modal.isShowing && (
<SearchModal
close={modal.close}
categories={categories}
favorites={favorites}
items={items}
handleSelectCategory={handleSelectCategory}
/>
)}
</div>
);
}
@@ -69,10 +99,31 @@ export async function getServerSideProps({ query }) {
include: { links: true },
});
const items = [] as ItemComplete[];
const favorites = [] as Link[];
const categories = categoriesDB.map((categoryDB) => {
const category = BuildCategory(categoryDB);
category.links.map((link) => (link.favorite ? favorites.push(link) : null));
category.links.map((link) => {
if (link.favorite) {
favorites.push(link);
}
items.push({
id: link.id,
name: link.name,
url: link.url,
type: "link",
});
});
items.push({
id: category.id,
name: category.name,
url: `/?categoryId=${category.id}`,
type: "category",
});
return category;
});
@@ -92,6 +143,7 @@ export async function getServerSideProps({ query }) {
props: {
categories: JSON.parse(JSON.stringify(categories)),
favorites: JSON.parse(JSON.stringify(favorites)),
items: JSON.parse(JSON.stringify(items)),
currentCategory: currentCategory
? JSON.parse(JSON.stringify(currentCategory))
: null,

218
pages/search.tsx Normal file
View File

@@ -0,0 +1,218 @@
import LinkTag from "next/link";
import { useRouter } from "next/router";
import { ReactNode, useCallback, useMemo, useState } from "react";
import { FcGoogle } from "react-icons/fc";
import FormLayout from "../components/FormLayout";
import TextBox from "../components/TextBox";
import useAutoFocus from "../hooks/useAutoFocus";
import LinkFavicon from "../components/Links/LinkFavicon";
import { Link } from "../types";
import { prisma } from "../utils/back";
import { BuildCategory } from "../utils/front";
import styles from "../styles/search.module.scss";
interface ItemComplete {
id: number;
name: string;
url: string;
type: "category" | "link";
}
interface SearchPageProps {
favorites: Link[];
items: ItemComplete[];
}
export default function SearchPage({ favorites, items }: SearchPageProps) {
const router = useRouter();
const autoFocusRef = useAutoFocus();
const [search, setSearch] = useState<string>("");
const canSubmit = useMemo<boolean>(() => search.length > 0, [search]);
const itemsCompletion = useMemo(
() =>
search.length > 0
? items.filter((item) =>
item.name
.toLocaleLowerCase()
.includes(search.toLocaleLowerCase().trim())
)
: [],
[items, search]
);
console.log("itemsCompletion", itemsCompletion);
const handleSubmit = useCallback(
(event) => {
event.preventDefault();
setSearch("");
if (itemsCompletion.length > 0) {
const firstItem = itemsCompletion[0];
if (firstItem.type === "link") {
window.open(firstItem.url);
} else {
router.push(firstItem.url);
}
} else {
window.open(`https://google.com/search?q=${encodeURI(search.trim())}`);
}
},
[itemsCompletion, router, search]
);
return (
<>
<FormLayout
title="Search"
canSubmit={canSubmit}
handleSubmit={handleSubmit}
>
<TextBox
name="search"
onChangeCallback={(value) => setSearch(value)}
value={search}
placeholder="Rechercher"
innerRef={autoFocusRef}
fieldClass={styles["search-input-field"]}
/>
{search.length === 0 && favorites.length > 0 && (
<ListItemComponent
items={favorites.map((favorite) => ({
id: favorite.id,
name: favorite.name,
url: favorite.url,
type: "link",
}))}
noItem={<p>ajouter un favoris</p>}
/>
)}
{search.length > 0 && (
<ListItemComponent
items={itemsCompletion.map((item) => ({
id: item.id,
name: item.name,
url: item.url,
type: item.type,
}))}
noItem={
<i
style={{ display: "flex", alignItems: "center", gap: ".25em" }}
>
Recherche avec{" "}
<span style={{ display: "flex", alignItems: "center" }}>
<FcGoogle size={24} />
oogle
</span>
</i>
}
/>
)}
</FormLayout>
</>
);
}
function ListItemComponent({
items,
noItem,
}: {
items: ItemComplete[];
noItem?: ReactNode;
}) {
return (
<ul
style={{
margin: "1em 0",
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "1em",
}}
>
{items.length > 0 ? (
items.map((item) => (
<ItemComponent
item={{
id: item.id,
name: item.name,
url: item.url,
type: item.type,
}}
key={item.type + "-" + item.id}
/>
))
) : noItem ? (
noItem
) : (
<i>no item found</i>
)}
</ul>
);
}
function ItemComponent({ item }: { item: ItemComplete }) {
const { name, type, url } = item;
return (
<li>
<LinkTag
href={url}
style={{
display: "flex",
flexDirection: "column",
}}
>
{type === "link" ? (
<LinkFavicon url={item.url} noMargin />
) : (
<span>category</span>
)}
<span>{name}</span>
</LinkTag>
</li>
);
}
export async function getServerSideProps() {
const categoriesDB = await prisma.category.findMany({
include: { links: true },
});
const items = [] as ItemComplete[];
const favorites = [] as Link[];
categoriesDB.forEach((categoryDB) => {
const category = BuildCategory(categoryDB);
category.links.map((link) => {
if (link.favorite) {
favorites.push(link);
}
items.push({
id: link.id,
name: link.name,
url: link.url,
type: "link",
});
});
items.push({
id: category.id,
name: category.name,
url: `/?categoryId=${category.id}`,
type: "category",
});
});
return {
props: {
favorites: JSON.parse(JSON.stringify(favorites)),
items: JSON.parse(JSON.stringify(items)),
},
};
}

9
types.d.ts vendored
View File

@@ -18,7 +18,7 @@ export interface Link {
category: {
id: number;
name: string;
}
};
nextLinkId: number;
favorite: boolean;
@@ -26,3 +26,10 @@ export interface Link {
createdAt: Date;
updatedAt: Date;
}
export interface ItemComplete {
id: number;
name: string;
url: string;
type: "category" | "link";
}