8000 feat: better search results by jcserv · Pull Request #70 · jcserv/portfolio · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: better search results #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/assets/socials.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { File, Github, Linkedin } from "lucide-react";

export const getSocials = (className: string) => [
{
label: "Github",
icon: (
<Github
aria-label="Github Profile"
className={className}
/>
),
url: "https://github.com/jcserv",
},
{
label: "LinkedIn",
icon: (
<Linkedin
aria-label="LinkedIn Profile"
className={className}
/>
),
url: "https://linkedin.com/in/jarrod-servilla",
},
{
label: "Resume",
icon: (
<File
aria-label="Jarrod Servilla's Resume"
className={className}
/>
),
url: "/resume.pdf",
},
]
174 changes: 68 additions & 106 deletions src/components/CommandBar.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
import React from "react";
import Fuse, { FuseResult, FuseResultMatch } from "fuse.js";
import { Briefcase, DoorOpen, User, Wand } from "lucide-react";
import Fuse, { FuseResult } from "fuse.js";
import {
Briefcase,
CloudCog,
DoorOpen,
Hammer,
User,
Wand,
} from "lucide-react";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command";
import { Button } from "@/components/ui/button";
import { Section } from "@/components/SearchResult";
import { useActiveExp } from "@/context/ActiveExpProvider";
import { cn, scrollToSection } from "@/lib/utils";
import { experienceToContent } from "@/types/experience";
import { projectsToContent } from "@/types/project";
import experience from "@/assets/experience.json";
import projects from "@/assets/projects.json";
import { getSocials } from "@/assets/socials";
import { SearchItem } from "@/types/searchItem";


type SectionCommand = {
label: string;
content: string[];
value: string;
icon: JSX.Element;
shortcut: string;
};

const sections: SectionCommand[] = [
const sections: SearchItem[] = [
{
label: "Landing",
content: [],
Expand All @@ -41,46 +39,88 @@ const sections: SectionCommand[] = [
"I studied computer science at the University of Toronto",
"working at dbt Labs as a Software Engineer, working on dbt Explorer.",
"I've worked at SailPoint, Citigroup, and Citylitics.",
"Certifications: AWS Certified Developer, DataDog Fundamentals, PagerDuty Incident Responder, dbt Fundamentals"
"Certifications: AWS Certified Developer, DataDog Fundamentals, PagerDuty Incident Responder, dbt Fundamentals",
],
value: "about",
icon: <User className="mr-2 h-4 w-4" />,
shortcut: "F2",
},
{
label: "Experience",
content: experienceToContent(experience),
content: [],
value: "experience",
icon: <Briefcase className="mr-2 h-4 w-4" />,
shortcut: "F3",
},
{
label: "Projects",
content: projectsToContent(projects),
content: [],
value: "projects",
icon: <Wand className="mr-2 h-4 w-4" />,
shortcut: "F4",
},
];

const projs: SearchItem[] = projects.slice(0, 4).map((proj, index) => {
return {
label: "Projects",
content: [proj.description],
value: `project-${index}`,
icon: <Hammer className="mr-2 h-4 w-4" />,
};
});

const socs: SearchItem[] = getSocials("mr-2 h-4 w-4").map((soc, index) => {
return {
label: soc.label,
content: [],
value: `social-${index}`,
icon: soc.icon,
customOnSelect: () => {
window.open(soc.url, "_blank");
},
};
});

// TODO: Add ability to ask natural language questions
export const CommandBar: React.FC = () => {
const [open, setOpen] = React.useState(false);
const [query, setQuery] = React.useState("");
const { setActiveExp } = useActiveExp();

// TODO: Include other search items like Github, LinkedIn, etc.
// TODO: Include experience and project content in search that links to the respective sections with ?activeTab=<x>
const [searchResults, setSearchResults] = React.useState<
FuseResult<SectionCommand>[]
FuseResult<SearchItem>[]
>([]);

const fuse = new Fuse(sections, {
includeScore: true,
includeMatches: true,
ignoreFieldNorm: true,
keys: ["label", "content"],
const experiences: SearchItem[] = experience.map((exp, index) => {
return {
label: "Experience",
content: [exp.workplace, ...exp.description],
value: `experience-${index}`,
icon: <CloudCog className="mr-2 h-4 w-4" />,
customOnSelect: () => {
scrollToSection("experience");
setActiveExp(`${index}`);
},
};
});

const searchInput = React.useMemo(() => {
return sections.concat(experiences).concat(projs).concat(socs);
}, [sections, experiences, projs, socs]);

const fuse = new Fuse(
searchInput,
{
includeScore: true,
includeMatches: true,
ignoreFieldNorm: true,
shouldSort: true,
minMatchCharLength: 3,
keys: ["label", "content"],
}
);

React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
Expand All @@ -102,7 +142,7 @@ export const CommandBar: React.FC = () => {
}, []);

React.useEffect(() => {
const results = fuse.search(query);
const results = fuse.search(query).filter((result) => result.score! < 0.6);
setSearchResults(results);
}, [query]);

Expand Down Expand Up @@ -160,81 +200,3 @@ export const CommandBar: React.FC = () => {
</>
);
};

type SectionProps = SectionCommand & {
matches?: readonly FuseResultMatch[] | undefined;
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
};

const Section: React.FC<SectionProps> = ({
label,
value,
icon,
shortcut,
matches,
setOpen,
}: SectionProps) => (
<CommandItem
value={value}
=> {
scrollToSection(value);
setTimeout(() => setOpen(false), 450);
}}
>
{icon}
<div className="flex flex-col">
<span>{label}</span>
{(matches ?? []).length > 0 && (
<span className="flex items-center gap-2 text-sm text-muted-foreground truncate">
Includes:
{matches?.slice(0, 1).map((match, idx) => {
const getNWords = (str: string, n: number, fromEnd = false) => {
if (!str) return "";
const words = str.trim().split(/\s+/);
const selectedWords = fromEnd
? words.slice(Math.max(words.length - n, 0))
: words.slice(0, n);
return selectedWords.join(" ");
};

// The best match will be the one with the greatest difference
const bestMatch = match.indices.reduce((acc, curr) => {
const matchLength = curr[1] - curr[0];
return matchLength > acc[1] - acc[0] ? curr : acc;
});

const beforeMatch = match.value?.slice(0, bestMatch[0]) || "";
const highlightedMatch =
match.value?.slice(bestMatch[0], bestMatch[1] + 1) || "";
const afterMatch = match.value?.slice(bestMatch[1] + 1) || "";

// Get 3 words before and after
const truncatedBefore = getNWords(beforeMatch, 3, true);
const truncatedAfter = getNWords(afterMatch, 3);

return (
<span key={idx} className="flex items-center gap-1 truncate">
{truncatedBefore && (
<span>
{beforeMatch.length > truncatedBefore.length ? "..." : ""}
{truncatedBefore}
</span>
)}
<span className="bg-yellow-200 text-black px-1 rounded">
{highlightedMatch}
</span>
{truncatedAfter && (
<span>
{truncatedAfter}
{afterMatch.length > truncatedAfter.length ? "..." : ""}
</span>
)}
</span>
);
})}
</span>
)}
</div>
<CommandShortcut>{shortcut}</CommandShortcut>
</CommandItem>
);
90 changes: 90 additions & 0 deletions src/components/SearchResult.tsx
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import React from "react";
import { FuseResultMatch } from "fuse.js";
import { CommandItem, CommandShortcut } from "@/components/ui/command";
import { scrollToSection } from "@/lib/utils";
import { SearchItem } from "@/types/searchItem";

type SectionProps = SearchItem & {
matches?: readonly FuseResultMatch[] | undefined;
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
};

export const Section: React.FC<SectionProps> = ({
label,
value,
icon,
shortcut,
matches,
setOpen,
customOnSelect,
}: SectionProps) => (
<CommandItem
value={value}
=> {
if (customOnSelect) {
customOnSelect();
setTimeout(() => setOpen(false), 450);
return;
}

scrollToSection(value);
setTimeout(() => setOpen(false), 450);
}}
>
{icon}
<div className="flex flex-col">
<span>{label}</span>
{(matches ?? []).length > 0 && (
<span className="flex items-center gap-2 text-sm text-muted-foreground truncate">
Includes:
{matches?.slice(0, 1).map((match, idx) => {
const getNWords = (str: string, n: number, fromEnd = false) => {
if (!str) return "";
const words = str.trim().split(/\s+/);
const selectedWords = fromEnd
? words.slice(Math.max(words.length - n, 0))
: words.slice(0, n);
return selectedWords.join(" ");
};

// The best match will be the one with the greatest difference
const bestMatch = match.indices.reduce((acc, curr) => {
const matchLength = curr[1] - curr[0];
return matchLength > acc[1] - acc[0] ? curr : acc;
});

const beforeMatch = match.value?.slice(0, bestMatch[0]) || "";
const highlightedMatch =
match.value?.slice(bestMatch[0], bestMatch[1] + 1) || "";
const afterMatch = match.value?.slice(bestMatch[1] + 1) || "";

// Get 3 words before and after
const truncatedBefore = getNWords(beforeMatch, 3, true);
const truncatedAfter = getNWords(afterMatch, 3);

return (
<span key={idx} className="flex items-center gap-1 truncate">
{truncatedBefore && (
<span>
{beforeMatch.length > truncatedBefore.length ? "..." : ""}
{truncatedBefore}
</span>
)}
<span className="bg-yellow-200 text-black px-1 rounded">
{highlightedMatch}
</span>
{truncatedAfter && (
<span>
{truncatedAfter}
{afterMatch.length > truncatedAfter.length ? "..." : ""}
</span>
)}
</span>
);
})}
</span>
)}
</div>
{shortcut && <CommandShortcut>{shortcut}</CommandShortcut>}
</CommandItem>
);
Loading
Loading
0