Skip to content

Commit

Permalink
Simply facet refinements and states
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed May 2, 2024
1 parent 019e9df commit f87d1a9
Show file tree
Hide file tree
Showing 6 changed files with 631 additions and 486 deletions.
Binary file modified algolia-search/.yarn/install-state.gz
Binary file not shown.
18 changes: 9 additions & 9 deletions algolia-search/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,24 @@
"dev": "webpack serve --env dev"
},
"dependencies": {
"algoliasearch": "^4.22.1",
"preact": "^10.19.7",
"react-instantsearch": "^7.7.2",
"styled-components": "^6.1.8"
"algoliasearch": "^4.23.3",
"preact": "^10.21.0",
"react-instantsearch": "^7.7.3",
"styled-components": "^6.1.9"
},
"devDependencies": {
"@babel/core": "^7.24.1",
"@babel/preset-env": "^7.24.1",
"@babel/core": "^7.24.5",
"@babel/preset-env": "^7.24.5",
"@babel/preset-react": "^7.24.1",
"@babel/preset-typescript": "^7.24.1",
"@types/webpack": "^5.28.5",
"babel-loader": "^9.1.3",
"css-loader": "^6.10.0",
"dotenv-webpack": "^8.0.1",
"css-loader": "^6.11.0",
"dotenv-webpack": "^8.1.0",
"html-webpack-plugin": "^5.6.0",
"preact-island": "^1.1.2",
"terser-webpack-plugin": "^5.3.10",
"webpack": "^5.90.3",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
},
Expand Down
13 changes: 11 additions & 2 deletions algolia-search/src/algolia-search.island.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,16 @@ const CustomHits = (props) => {

const Search = () => {
const currentSearchParams = new URLSearchParams(window.location.search)
const initialSearch = currentSearchParams.get('key');

const initialUiState = {};

if (currentSearchParams.get('key')) {
initialUiState.query = currentSearchParams.get('key');
}
if (currentSearchParams.get("page-type")) {
initialUiState.refinementList = {basic_page_type: currentSearchParams.get("page-type").split(',')}
}

const searchIndex = window.drupalSettings?.stanfordAlgolia.index || process.env.ALGOLIA_INDEX;

return (
Expand All @@ -64,7 +73,7 @@ const Search = () => {
searchClient={searchClient}
indexName={searchIndex}
initialUiState={{
[searchIndex]: {query: initialSearch},
[searchIndex]: initialUiState,
}}
>
<Container>
Expand Down
106 changes: 0 additions & 106 deletions algolia-search/src/facets.tsx

This file was deleted.

113 changes: 28 additions & 85 deletions algolia-search/src/search-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,89 +4,49 @@ import {
useRefinementList,
useSearchBox
} from "react-instantsearch";
import {useEffect, useRef, useState} from "preact/compat";
import {useEffect, useRef} from "preact/compat";

const SearchForm = (props) => {
const ref = useRef(false)
const windowSearchParams = new URLSearchParams(window.location.search)

const {query, refine} = useSearchBox(props);
const {items: pageTypeRefinements, refine: refineNewsType} = useRefinementList({attribute: "basic_page_type"});
const [chosenBasicPageTypes, setChosenNewsTypes] = useState<string[]>(windowSearchParams.get('basic-page-type')?.split(',') || []);
const {status} = useInstantSearch();
const {items: pageTypeRefinements, refine: refinePageTypes} = useRefinementList({attribute: "basic_page_type"});
const inputRef = useRef<HTMLInputElement>(null);
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
e.stopPropagation();
refine(inputRef.current?.value);
const addRefinements = chosenBasicPageTypes.filter(basicPageType => !pageTypeRefinements.find(item => item.value === basicPageType).isRefined);
const removeRefinements = pageTypeRefinements.filter(refinement => refinement.isRefined && !chosenBasicPageTypes.includes(refinement.value)).map(refinement => refinement.value);
[...addRefinements, ...removeRefinements].map(basicPageType => refineNewsType(basicPageType));
const searchParams = new URLSearchParams(window.location.search);
inputRef.current?.value.length > 0 ? searchParams.set('key', inputRef.current?.value) : searchParams.delete('key');
chosenBasicPageTypes.length > 0 ? searchParams.set('basic-page-type', chosenBasicPageTypes.join(',')) : searchParams.delete('basic-page-type');
window.history.replaceState(null, '', `?${searchParams.toString()}`);
}

const handleFormReset = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
e.stopPropagation();
refine('');
inputRef.current.value = '';
inputRef.current?.focus();
pageTypeRefinements.filter(refinement => refinement.isRefined).map(refinement => refineNewsType(refinement.value));
setChosenNewsTypes([]);
useEffect(() => {
const searchParams = new URLSearchParams(window.location.search);
searchParams.delete('key');
searchParams.delete('basic-page-type');
window.history.replaceState(null, '', `?${searchParams.toString()}`);
}
const handleChange = (item, e) => {
setChosenNewsTypes(prevTypes => {
const pageTypes = [...prevTypes];
if (e.currentTarget.checked) {
pageTypes.push(item.value);
} else {
pageTypes.splice(prevTypes.findIndex(value => value === item.value), 1)
}
return pageTypes;
});
e.preventDefault();
e.stopPropagation();
refine(inputRef.current?.value);

const addRefinements = chosenBasicPageTypes.filter(basicPageType => !pageTypeRefinements.find(it => it.value === basicPageType).isRefined)
const removeRefinements = pageTypeRefinements.filter(refinement => refinement.isRefined && !chosenBasicPageTypes.includes(refinement.value)).map(refinement => refinement.value);
searchParams.delete("key")
searchParams.delete("page-type")

[...addRefinements, ...removeRefinements].map(basicPageType => refineNewsType(basicPageType))
if (query) searchParams.set("key", query);
const pageTypes = pageTypeRefinements.filter(item => item.isRefined).map(item => item.value);

const searchParams = new URLSearchParams(window.location.search)
inputRef.current?.value.length > 0 ? searchParams.set('key', inputRef.current?.value): searchParams.delete('key');
chosenBasicPageTypes.length > 0 ? searchParams.set('basic-page-type', chosenBasicPageTypes.join(',')) : searchParams.delete('basic-page-type')
if (pageTypes.length >= 1) searchParams.set("page-type", pageTypes.join(','))

window.history.replaceState(null, '', `?${searchParams.toString()}`)
}
useEffect(() => {
if (ref.current) return
ref.current = true;
chosenBasicPageTypes.map(basicPageType => refineNewsType(basicPageType));
}, [ref, chosenBasicPageTypes])
window.history.replaceState(null, '', `?${searchParams.toString()}`);
}, [query, pageTypeRefinements])

return (
<form
action=""
role="search"
noValidate
onSubmit={handleFormSubmit}
onReset={handleFormReset}
style={{marginBottom: "20px"}}
onSubmit={(e) => {
e.preventDefault();
refine(inputRef.current.value)
}}
onReset={(e) => {
inputRef.current.value = ""
refine("");
pageTypeRefinements.map(refinementItem => {
if (refinementItem.isRefined) refinePageTypes(refinementItem.value)
})
}}
>
<div className="lg:w-2/3 mx-auto mb-20 flex gap-5 items-center">
<div>
<label htmlFor="keyword-search-algolia">
Keywords<span className="visually-hidden">&nbsp;Search</span>
</label>
<input
id="keyword-search-algolia"
className="flex-grow border-0 border-b border-black-30 text-m2"
ref={inputRef}
autoComplete="on"
autoCorrect="on"
Expand All @@ -95,7 +55,6 @@ const SearchForm = (props) => {
maxLength={128}
type="search"
defaultValue={query}
autoFocus
/>

<div style={{display: "flex", gap: "1rem", marginTop: "1rem"}}>
Expand All @@ -111,15 +70,15 @@ const SearchForm = (props) => {
<legend>Basic Page Types</legend>

<ul style={{listStyle: "none", paddingLeft: "0", marginInline: "0"}}>
{pageTypeRefinements.sort((a, b) => a.count < b.count ? 1 : (a.count === b.count ? (a.value < b.value ? -1 : 1) : -1)).map((item, i) =>
{pageTypeRefinements.map((item, i) =>
<li key={i}>
<label style={{
'margin-top': '1rem'
}}>
<input
type="checkbox"
checked={chosenBasicPageTypes.findIndex(value => value === item.value) >= 0}
onChange={(e) => handleChange(item, e)}
onChange={() => refinePageTypes(item.value)}
checked={item.isRefined}
style={{
border: 'black',
width: '12px',
Expand All @@ -128,8 +87,8 @@ const SearchForm = (props) => {
clip: 'unset',
overflow: 'unset',
position: 'relative',
'clip-path': 'unset',
"marginRight": "3"
clipPath: 'unset',
marginRight: "3"
}}
/>
{item.value} ({item.count})
Expand All @@ -138,12 +97,6 @@ const SearchForm = (props) => {
)}
</ul>
</fieldset>
<fieldset>
<legend>Subject</legend>
<ul style={{listStyle: "none"}}>

</ul>
</fieldset>
</div>
</form>
);
Expand Down Expand Up @@ -171,14 +124,4 @@ const CustomCurrentRefinements = (props) => {
);
}


const StatusMessage = ({status, query}) => {
let message = status === 'loading' ? 'Loading' : null;
if (status != 'loading' && query) {
message = `Showing results for "${query}"`
}
return (
<div className="visually-hidden" aria-live="polite" aria-atomic>{message}</div>
)
}
export default SearchForm;
Loading

0 comments on commit f87d1a9

Please sign in to comment.