Skip to content
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

feat(guff): add search bar #238

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
],
"import/no-unresolved": "off",
"import/prefer-default-export": "off",
"no-console": ["warn", { "allow": ["error"] }],
"no-console": ["warn", { "allow": ["error", "info"] }],
"no-nested-ternary": "off",
"no-param-reassign": ["error", { "props": false }],
"no-restricted-syntax": [
Expand Down
2 changes: 1 addition & 1 deletion .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"*.{js,jsx,ts,tsx}": "eslint",
"*.{js,json,jsx,scss,ts,tsx}": "prettier --write",
"*.{md,js,json,jsx,scss,ts,tsx}": "prettier --write",
"*.md": "markdownlint"
}
22 changes: 22 additions & 0 deletions guff/guff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { writeFileSync } from 'fs';
import type { Entry } from './models';
import { read } from './read';

const [_binary, _script, ...paths] = process.argv;

const database = paths.reduce<Entry[]>((accumulator, path) => {
if (path) {
const entry = read(path);
accumulator.push(...entry);
}
return accumulator;
}, []);

console.info(`Writing ${database.length} entries...`);

const json = process.env.GUFF_DEBUG
? JSON.stringify(database, null, 2)
: JSON.stringify(database);
writeFileSync('guff.json', json, 'utf8');

console.info(`Write successful!`);
11 changes: 11 additions & 0 deletions guff/models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface Entry {
kind: Kind | null;
headings: string[];
title: string;
}

export enum Kind {
ARTICLE,
PRIMER,
REPORT,
}
44 changes: 44 additions & 0 deletions guff/read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import matter from 'gray-matter';
import { Kind, type Entry } from './models';
import { walk } from './walk';

/** Regular expression to capture all headings in a Markdown buffer. */
const HEADING_RE = /^#{1,6} (?<text>.+)$/gm;

function assertKind(value: unknown): asserts value is Kind | undefined {
if (value && !Object.keys(Kind).includes(value)) {
throw new Error(`Unknown kind "${value}"`);
}
}

function assertTitle(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Missing title');
}
}

export const read = (root: string): Entry[] => {
const files = walk(root, { extension: '.md' });
console.info(`Parsing "${root}" (${files.length} files)...`);
return files.map((crumbs) => {
const path = join(root, ...crumbs);
const buffer = readFileSync(path, 'utf8');
const { content, data } = matter(buffer);
const { kind, title } = data;
try {
assertKind(kind);
assertTitle(title);
const matches = [...content.matchAll(HEADING_RE)];
const headings = matches.reduce<string[]>((accumulator, match) => {
const heading = match.groups?.text;
return heading ? [...accumulator, heading] : accumulator;
}, []);
return { kind: kind ?? null, headings, title };
} catch (error) {
const message = error instanceof Error ? error.message : `${error}`;
throw new Error(`${message} in "${path}"`);
}
});
};
13 changes: 13 additions & 0 deletions guff/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"baseUrl": ".",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"noUncheckedIndexedAccess": true,
"strict": true,
"target": "ESNext"
},
"include": ["**/*.ts"],
"ts-node": { "files": true }
}
3 changes: 3 additions & 0 deletions guff/typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
interface Array<T> {
includes(item: unknown, index?: number): item is T;
}
37 changes: 37 additions & 0 deletions guff/walk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { existsSync, readdirSync } from 'fs';
import { join, parse } from 'path';

interface WalkOptions {
depth?: number;
extension?: string;
}

/**
* Generator to walk through `directory` and yield all files.
* Return a tuple containing all successive parent folders followed by the file
* with their extension.
* When `extension` is specified, only return files that match.
* Prefer synchronous exploration since order matters.
*/
function* walkIterator(
directory: string,
options: WalkOptions = {},
accumulator: string[] = [],
): Generator<string[], void> {
const { depth, extension } = options;
if (accumulator.length === depth) return;
if (existsSync(directory)) {
for (const file of readdirSync(directory, { withFileTypes: true })) {
const { base, ext } = parse(file.name);
if (file.isDirectory()) {
const entry = join(directory, file.name);
yield* walkIterator(entry, options, [...accumulator, file.name]);
} else if (file.isFile() && (!extension || ext === extension)) {
yield [...accumulator, base];
}
}
}
}

export const walk = (directory: string, options?: WalkOptions): string[][] =>
Array.from(walkIterator(directory, options));
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
"scripts": {
"build": "concurrently 'next build' 'yarn scryfall' --names 'next,scryfall' --prefix-colors auto --kill-others --success first",
"dev": "concurrently 'next dev' 'yarn scryfall:dev' --names 'next,scryfall' --prefix-colors auto",
"lint": "concurrently 'yarn:lint:*' --names --prefix-colors auto --success all",
"guff": "ts-node ./guff/guff.ts markdown/articles/ markdown/chapters/",
"guff:watch": "find guff/* | entr yarn guff",
"lint": "concurrently 'yarn:lint:*' --prefix-colors auto --success all",
"lint:code": "eslint .",
"lint:format": "prettier --check --loglevel warn markdown/ puzzles/ scryfall/ src/",
"lint:format": "prettier --check --loglevel warn guff/ markdown/ puzzles/ scryfall/ src/",
"lint:prune": "ts-prune --error",
"lint:typings": "tsc",
"lint:wiki": "markdownlint markdown/",
Expand Down Expand Up @@ -40,6 +42,7 @@
"plaiceholder": "3.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hotkeys-hook": "4.4.1",
"react-intersection-observer": "9.5.2",
"react-markdown": "8.0.7",
"react-syntax-highlighter": "15.5.0",
Expand All @@ -51,6 +54,7 @@
"remark-toc": "8.0.1",
"sharp": "0.32.5",
"simple-icons": "9.10.0",
"ts-node": "10.9.1",
"unified": "10.1.2",
"unist-util-select": "5.0.0",
"unist-util-visit": "5.0.0"
Expand Down
2 changes: 2 additions & 0 deletions src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Icon from '@mdi/react';
import { AppBar, Box, IconButton, Toolbar } from '@mui/material';
import { alpha, useTheme } from '@mui/material/styles';
import { Progress } from '@/components/Progress/Progress';
import { Search } from '@/components/Search/Search';

interface Props {
isMobile: boolean;
Expand Down Expand Up @@ -38,6 +39,7 @@ export const Header: FunctionComponent<Props> = ({
<Icon path={mdiMenu} size={1} />
</IconButton>
)}
<Search />
</Toolbar>
</AppBar>
<Box role="presentation" sx={({ mixins }) => mixins.toolbar} />
Expand Down
1 change: 0 additions & 1 deletion src/components/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ export const Layout: FunctionComponent<Props> = ({
withProgress={withProgress}
/>
<Sidebar
category={router.query.category && (router.query.category as string)}
menu={menu}
isClear={isClear}
isMobile={!isDesktop}
Expand Down
59 changes: 59 additions & 0 deletions src/components/Search/Search.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {
useEffect,
useRef,
useState,
type ChangeEvent,
type FunctionComponent,
} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { InputBase, Typography } from '@mui/material';
import { useDebounce } from '@/hooks/useDebounce';

export const Search: FunctionComponent = () => {
const root = useRef<HTMLInputElement>(null);
const [input, setInput] = useState('');
const query = useDebounce(input, 200);

useEffect(() => {}, [query]);

useHotkeys(
'/',
(event) => {
event.preventDefault(); // NOTE Prevents typing the `/`
root.current?.focus();
root.current?.select();
},
[root.current],
);

const onChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
setInput(target.value);
};

return (
<InputBase
fullWidth
inputProps={{ 'aria-label': 'search', ref: root }}
onChange={onChange}
placeholder="Search"
startAdornment={
<Typography
sx={{
backgroundColor: 'action.focus',
border: 1,
borderColor: 'divider',
borderRadius: '4px',
color: 'text.secondary',
fontFamily: 'monospace',
mr: 1,
px: 0.5,
}}
variant="caption"
>
/
</Typography>
}
value={input}
/>
);
};
4 changes: 1 addition & 3 deletions src/components/Sidebar/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { darkTheme } from '@/theme/theme';
import type { MenuEntry } from '@/tools/markdown/types';

interface Props {
category: string | undefined;
isClear: boolean;
isMobile?: boolean;
isOpen?: boolean;
Expand All @@ -29,7 +28,6 @@ interface Props {
}

export const Sidebar: FunctionComponent<Props> = ({
category,
isClear,
isMobile = false,
isOpen,
Expand Down Expand Up @@ -80,7 +78,7 @@ export const Sidebar: FunctionComponent<Props> = ({
/>
</List>
<Divider />
<SidebarRosetta sx={{ my: 2 }} category={category} />
<SidebarRosetta sx={{ my: 2 }} />
</Box>
);

Expand Down
9 changes: 5 additions & 4 deletions src/components/Sidebar/SidebarRosetta.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import type { FunctionComponent } from 'react';
import { useRouter } from 'next/router';
import { useEffect, useState, type FunctionComponent } from 'react';
import {
Table,
TableBody,
Expand All @@ -14,11 +14,12 @@ import { getRosetta } from '@/tools/game/getRosetta';
import type { Rosetta } from '@/tools/game/getRosetta';

interface Props {
category: string | undefined;
sx?: SxProps<Theme>;
}

export const SidebarRosetta: FunctionComponent<Props> = ({ category, sx }) => {
export const SidebarRosetta: FunctionComponent<Props> = ({ sx }) => {
const { query } = useRouter();
const category = query.category && (query.category as string);
const [rosetta, setRosetta] = useState<Rosetta>([]);

useEffect(() => {
Expand Down
12 changes: 12 additions & 0 deletions src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useEffect, useState } from 'react';

export const useDebounce = <T>(input: T, delay: number): T => {
const [output, setOutput] = useState<T>(input);

useEffect(() => {
const timer = setTimeout(() => setOutput(input), delay);
return () => clearTimeout(timer);
}, [input, delay]);

return output;
};
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@
"target": "es5"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"exclude": ["guff/", "node_modules/"]
}
Loading