Skip to content

Commit

Permalink
Merge pull request #855 from City-of-Helsinki/UHF-9202_Ploughing_sche…
Browse files Browse the repository at this point in the history
…dule_search

UHF-9202: Ploughing schedule search
  • Loading branch information
xkhaven authored Dec 19, 2023
2 parents a5b3ee7 + a4c9b40 commit 8cfea20
Show file tree
Hide file tree
Showing 24 changed files with 553 additions and 5 deletions.
2 changes: 1 addition & 1 deletion dist/css/styles.min.css

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions dist/js/ploughing-schedule.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/js/school-search.min.js

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions hdbt.libraries.yml
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,13 @@ health-station-search:
dependencies:
- core/drupalSettings
- core/drupal

ploughing-schedule:
version: 1.0
js:
dist/js/ploughing-schedule.min.js: {
preprocess: false
}
dependencies:
- core/drupalSettings
- core/drupal
14 changes: 14 additions & 0 deletions hdbt.theme
Original file line number Diff line number Diff line change
Expand Up @@ -1770,3 +1770,17 @@ function hdbt_theme_suggestions_container_alter(array &$suggestions, array &$var
function hdbt_preprocess_views_exposed_form(array &$variables) {
$variables['#attached']['library'][] = 'hdbt/search-helper';
}

/**
* Implements hook_preprocess_HOOK().
*/
function hdbt_preprocess_paragraph__ploughing_schedule(array &$variables): void {
$variables['#attached']['library'][] = 'hdbt/ploughing-schedule';

$privacyUrl = helfi_eu_cookie_compliance_get_privacy_policy_url();

if ($privacyUrl instanceof Url) {
$privacyUrl->setAbsolute();
$variables['#attached']['drupalSettings']['helfi_react_search']['cookie_privacy_url'] = $privacyUrl->toString();
}
}
21 changes: 21 additions & 0 deletions src/js/react/apps/ploughing-schedule/components/ResultCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ForwardedRef, forwardRef } from 'react';

type CardProps = {
description: String;
lead?: String;
title: String;
}

const ResultCard = forwardRef(({description, lead, title}: CardProps, ref: ForwardedRef<HTMLDivElement>) => (
<div className='hdbt-search--ploughing-schedule__result-card' ref={ref}>
<h3 className='hdbt-search--ploughing-schedule__result-card--title hdbt-search--title'>{ title }</h3>
<div>
{ lead &&
<p>{lead}</p>
}
<p>{ description }</p>
</div>
</div>
));

export default ResultCard;
54 changes: 54 additions & 0 deletions src/js/react/apps/ploughing-schedule/components/ResultsList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { createRef } from 'react';
import { useAtomValue } from 'jotai';

import useScrollToResults from '@/react/common/hooks/useScrollToResults';
import LoadingOverlay from '@/react/common/LoadingOverlay';
import ResultsError from '@/react/common/ResultsError';
import ResultCard from './ResultCard';
import { paramsAtom } from '../store';
import getScheduleCard from '../helpers/GetScheduleCard';

type ResultsListProps = {
data: any;
error: string|Error;
isLoading: boolean;
isValidating: boolean;
}

const ResultsList = ({ data, error, isLoading, isValidating }: ResultsListProps) => {
const params = useAtomValue(paramsAtom);
const scrollTarget = createRef<HTMLDivElement>();
const choices = Boolean(Object.keys(params).length);
useScrollToResults(scrollTarget, choices);

if (isLoading || isValidating) {
return (
<div className='hdbt__loading-wrapper'>
<LoadingOverlay />
</div>
);
}

if (error) {
return (
<ResultsError
error={error}
ref={scrollTarget}
/>
);
}

const results = data.hits.hits;
const several = results.length > 1;

return (
<div className='hdbt-search--react__results'>
{ results.length
? <ResultCard {...getScheduleCard(results[0]._source.maintenance_class, several)} ref={scrollTarget} />
: <ResultCard {...getScheduleCard(0)} ref={scrollTarget} />
}
</div>
);
};

export default ResultsList;
80 changes: 80 additions & 0 deletions src/js/react/apps/ploughing-schedule/containers/FormContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Button, SearchInput } from 'hds-react';
import { useAtomValue, useSetAtom } from 'jotai';
import { useState } from 'react';

import configurationsAtom, { paramsAtom } from '../store';
import SearchParams from '../types/SearchParams';
import getSuggestionsQuery from '../helpers/GetSuggestionsQuery';

type SuggestionItemType = {
value: string;
};

const FormContainer = () => {
const setParams = useSetAtom(paramsAtom);
const [keyword, setKeyword] = useState('');
const { baseUrl, index } = useAtomValue(configurationsAtom);

const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const params: SearchParams = {};
params.keyword = keyword;
setParams(params);
};

const getSuggestions = (searchString: string) => new Promise<SuggestionItemType[]>((resolve, reject) => {
const suggestions = fetch(`${baseUrl}/${index}/_search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: getSuggestionsQuery(searchString),
})
.then(res => res.json())
.then(data => {
const streetNames: any[] = data?.hits?.hits.map((hit: any) => ({ value: hit.fields.street_name[0] }));

// Remove street name duplicates.
return streetNames.filter((item, indx, self) =>
indx === self.findIndex((curr) => curr.value === item.value)
);
})
.catch(error => {
console.warn(error);
return [];
});

resolve(suggestions);
});

return (
<form className='hdbt-search--react__form-container' onSubmit={onSubmit}>
<h2 className='hdbt-search--react__form-title'>
{Drupal.t('See the ploughing schedule', {}, {context: 'Ploughing schedule: Form title / submit'})}
</h2>
<p className='hdbt-search--react__form-description'>
{Drupal.t(
'Enter the name of your street to see an estimate of the street\'s ploughing schedule.',
{},
{context: 'Ploughing schedule: Form description'}
)}
</p>
<SearchInput
className='hdbt-search__filter'
hideSearchButton
label={Drupal.t('Street name', {}, {context: 'Ploughing schedule: Input label'})}
suggestionLabelField='value'
getSuggestions={getSuggestions}
onSubmit={value => setKeyword(value)}
onChange={(value) => setKeyword(value)}
visibleSuggestions={5}
placeholder={Drupal.t('For example, Mannerheimintie', {}, {context: 'Ploughing schedule: Input placeholder'})}
/>
<Button className='hdbt-search--react__submit-button hdbt-search--ploughing-schedule__submit-button' type='submit'>
{Drupal.t('See the ploughing schedule', {}, {context: 'Ploughing schedule: Form title / submit'})}
</Button>
</form>
);
};

export default FormContainer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useAtomValue } from 'jotai';

import { paramsAtom } from '../store';
import UseQuery from '../hooks/UseQuery';
import ResultsList from '../components/ResultsList';

const ResultsContainer = () => {
const params = useAtomValue(paramsAtom);
const { data, error, isLoading, isValidating } = UseQuery(params);

return (
<ResultsList {...{data, error, isLoading, isValidating}} />
);
};

export default ResultsContainer;
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Suspense } from 'react';
import { useAtomValue } from 'jotai';

import LoadingOverlay from '@/react/common/LoadingOverlay';
import FormContainer from './FormContainer';
import ResultsContainer from './ResultsContainer';
import { paramsAtom } from '../store';

const SearchContainer = () => {
const params = useAtomValue(paramsAtom);

return (
<Suspense fallback={
<div className='hdbt__loading-wrapper'>
<LoadingOverlay />
</div>
}>
<div>
<FormContainer />
{ params.keyword ? <ResultsContainer /> : '' }
</div>
</Suspense>
);
};

export default SearchContainer;
24 changes: 24 additions & 0 deletions src/js/react/apps/ploughing-schedule/helpers/GetQueryString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import BooleanQuery from '@/types/BooleanQuery';

const getQueryString = (keyword: string) => {
const query: BooleanQuery = {
bool: {
must: [
{
match: { street_name: keyword }
}
]
}
};

const sort = [{ length:'desc' }];

const queryString = JSON.stringify({
query,
sort
});

return queryString;
};

export default getQueryString;
27 changes: 27 additions & 0 deletions src/js/react/apps/ploughing-schedule/helpers/GetScheduleCard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const htmlParser = require('html-react-parser');

const getScheduleCard = (maintenanceClass: number, several?: boolean) => {
if (maintenanceClass > 0) {
const schedules: any = [];
schedules[1] = Drupal.t('<strong>We will plough the street by 7.00</strong>, if it has snowed in the evening or during the early hours of the night. If it snows between 4.00 and 18.00, we will plough the street within three hours of the end of the snowfall. Ploughing may be delayed if it snows a lot and for an extended period.', {}, {context: 'Ploughing schedule: Class 1'});
schedules[2] = Drupal.t('<strong>We will plough the street by 7.00</strong>, if it has snowed in the evening or during the early hours of the night. If it snows between 4.00 and 17.00, we will plough the street within four hours of the end of the snowfall. Ploughing may be delayed if it snows a lot and for an extended period.', {}, {context: 'Ploughing schedule: Class 2'});
schedules[3] = Drupal.t('<strong>We will plough the street within three business days</strong>. Ploughing may be delayed if it snows a lot and for an extended period.', {}, {context: 'Ploughing schedule: Class 3'});

const leadText: string = Drupal.t('The estimated ploughing schedules for the different parts of the street differ from each other. Below is the ploughing schedule for the longest part of the street.', {}, {context: 'Ploughing schedule: Multiple streets'});

return {
'title': Drupal.t('Estimated ploughing schedule', {}, {context: 'Ploughing schedule: Result title'}),
'description': htmlParser(schedules[maintenanceClass]),
'lead': several ? leadText : ''
};
}

return {
'title': Drupal.t('No results', {}, {context: 'No search results'}),
'description': Drupal.t('No results were found for the criteria you entered. Try changing your search criteria.',
{},
{ context: 'React search: no search results' })
};
};

export default getScheduleCard;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const getSuggestionsQuery = (keyword: string) => {

const query = {
match_phrase_prefix: {
street_name: {
query: keyword
}
}
};

const fields = [
'id',
'street_name'
];

const _source = 'false';

const queryString = JSON.stringify({
query,
fields,
_source
});

return queryString;
};

export default getSuggestionsQuery;
39 changes: 39 additions & 0 deletions src/js/react/apps/ploughing-schedule/hooks/UseQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import useSWR from 'swr';
import { useAtomValue } from 'jotai';

import SearchParams from '../types/SearchParams';
import configurationsAtom from '../store';
import getQueryString from '../helpers/GetQueryString';

const UseQuery = (params: SearchParams) => {
const { baseUrl, index } = useAtomValue(configurationsAtom);

const fetcher = async () => {
const { keyword } = params;

if (!keyword) {
return;
}

return fetch(`${baseUrl}/${index}/_search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: getQueryString(keyword),
}).then((res) => res.json());
};

const { data, error, isLoading, isValidating } = useSWR(`_${ Object.values(params).toString()}`, fetcher, {
revalidateOnFocus: false
});

return {
data,
error,
isLoading,
isValidating
};
};

export default UseQuery;
27 changes: 27 additions & 0 deletions src/js/react/apps/ploughing-schedule/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import React from 'react';
import ReactDOM from 'react-dom';

import initSentry from '@/react/common/helpers/Sentry';
import SearchContainer from './containers/SearchContainer';

initSentry();

const ROOT_ID = 'helfi-ploughing-schedule';

const start = () => {
const rootElement: HTMLElement | null = document.getElementById(ROOT_ID);

if (!rootElement) {
console.warn('Root id missing for Ploughing schedule app', { ROOT_ID });
return;
}

ReactDOM.render(
<React.StrictMode>
<SearchContainer />
</React.StrictMode>,
rootElement,
);
};

document.addEventListener('DOMContentLoaded', start);
Loading

0 comments on commit 8cfea20

Please sign in to comment.