User can select from/to years when searching files. Indexing doc and docx files.

This commit is contained in:
Roland 2024-03-06 17:41:04 -07:00
parent 758ff8e810
commit 00fe799b8f
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
40 changed files with 880 additions and 159 deletions

View file

@ -10,7 +10,7 @@ import {MoreRoute} from "./components/Apps";
import {InventoryRoute} from "./components/Inventory";
import {ArchiveRoute} from "./components/Archive";
import {FilesRoute} from "./components/Files";
import {StatusProvider} from "./hooks/customHooks";
import {QueryProvider, StatusProvider} from "./hooks/customHooks";
import {MapRoute} from "./components/Map";
import {MediaContextProvider, mediaStyles, StatusContext, ThemeContext} from "./contexts/contexts";
import {Header, ThemeProvider} from "./components/Theme";
@ -61,17 +61,19 @@ function HelpPage() {
}
function Root() {
return <ThemeProvider>
<TagsProvider>
<FilePreviewProvider>
<header>
<NavBar/>
</header>
<Outlet/>
<Footer/>
</FilePreviewProvider>
</TagsProvider>
</ThemeProvider>
return <QueryProvider>
<ThemeProvider>
<TagsProvider>
<FilePreviewProvider>
<header>
<NavBar/>
</header>
<Outlet/>
<Footer/>
</FilePreviewProvider>
</TagsProvider>
</ThemeProvider>
</QueryProvider>
}
const router = createBrowserRouter(createRoutesFromElements(<Route

View file

@ -26,7 +26,7 @@ import {SearchView, useSearch, useSearchSuggestions} from "./components/Search";
import {KiwixRestartMessage, OutdatedZimsMessage} from "./components/Zim";
import {useWROLMode} from "./hooks/customHooks";
import {FileSearchFilterButton} from "./components/Files";
import {FilePreviewContext} from "./components/FilePreview";
import {dateRangeIsEmpty, DateSelectorButton} from "./components/DatesSelector";
function FlagsMessages({flags}) {
const {settings, fetchSettings} = React.useContext(SettingsContext);
@ -170,11 +170,11 @@ export function DashboardPage() {
loading,
setSearchStr: setSuggestionSearchStr,
setSearchTags,
months, setMonths,
dateRange, setDateRange,
} = useSearchSuggestions(searchStr, activeTags);
const {status} = useContext(StatusContext);
const {setPreviewFile} = React.useContext(FilePreviewContext);
React.useEffect(() => {
setSuggestionSearchStr(localSearchStr);
}, [localSearchStr]);
@ -231,24 +231,53 @@ export function DashboardPage() {
<Media at='mobile'>
<Grid>
<Grid.Row columns={2}>
<Grid.Column width={13}>
{getSearchResultsInput({size: 'large'})}
<Grid.Column width={12}>
{getSearchResultsInput()}
</Grid.Column>
<Grid.Column width={3} textAlign='right'>
<FileSearchFilterButton size='large'/>
<Grid.Column width={1} textAlign='right' style={{padding: 0}}>
<DateSelectorButton onMonthsChange={setMonths} defaultMonthsSelected={months}
defaultDateRange={dateRange}
onDateRangeChange={setDateRange}/>
</Grid.Column>
<Grid.Column width={1} textAlign='right'>
<FileSearchFilterButton/>
</Grid.Column>
</Grid.Row>
</Grid>
</Media>
<Media greaterThanOrEqual='tablet'>
<Media at='tablet'>
<Grid>
<Grid.Row columns={2}>
<Grid.Column mobile={14}>
{getSearchResultsInput({size: 'big'})}
<Grid.Column textAlign='right' width={2}>
<DateSelectorButton onMonthsChange={setMonths} defaultMonthsSelected={months}
defaultDateRange={dateRange}
onDateRangeChange={setDateRange}
buttonProps={{size: 'big'}}/>
</Grid.Column>
<Grid.Column textAlign='right' width={2}>
<FileSearchFilterButton size='big'/>
</Grid.Column>
<Grid.Column mobile={12}>
{getSearchResultsInput({size: 'big'})}
</Grid.Column>
</Grid.Row>
</Grid>
</Media>
<Media greaterThanOrEqual='computer'>
<Grid>
<Grid.Row columns={2}>
<Grid.Column textAlign='right' width={1}>
<DateSelectorButton onMonthsChange={setMonths} defaultMonthsSelected={months}
defaultDateRange={dateRange}
onDateRangeChange={setDateRange}
buttonProps={{size: 'big'}}/>
</Grid.Column>
<Grid.Column textAlign='right' width={1}>
<FileSearchFilterButton size='big'/>
</Grid.Column>
<Grid.Column mobile={14}>
{getSearchResultsInput({size: 'big'})}
</Grid.Column>
</Grid.Row>
</Grid>
</Media>

View file

@ -1,5 +1,6 @@
import {API_URI, ARCHIVES_API, DEFAULT_LIMIT, emptyToNull, OTP_API, VIDEOS_API, ZIM_API} from "./components/Common";
import {toast} from "react-semantic-toasts-2";
import _ from "lodash";
function timeoutPromise(ms, promise) {
// Create a timeout wrapper around a promise. If the timeout is reached, throw an error. Otherwise, return
@ -545,7 +546,7 @@ export async function deleteDownload(downloadId) {
}
}
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline) {
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear) {
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit)};
if (mimetypes) {
body['mimetypes'] = mimetypes;
@ -559,7 +560,16 @@ export async function filesSearch(offset, limit, searchStr, mimetypes, model, ta
if (headline) {
body['headline'] = true;
}
console.debug('searching files', body);
if (!_.isEmpty(months)) {
body['months'] = months.map(i => parseInt(i));
}
if (fromYear) {
body['from_year'] = fromYear;
}
if (toYear) {
body['to_year'] = toYear;
}
console.info('searching files', body);
const response = await apiPost(`${API_URI}/files/search`, body);
if (response.status === 200) {
@ -1050,8 +1060,14 @@ export async function fetchDecoded(vinNumber) {
}
}
export async function searchSuggestions(search_str, tagNames, mimetypes) {
const body = {search_str: search_str, tag_names: tagNames, mimetypes: mimetypes};
export async function searchSuggestions(search_str, tagNames, mimetypes, months, dateRange) {
months = months ? months.map(i => parseInt(i)) : [];
const body = {search_str, tag_names: tagNames, mimetypes, months};
if (dateRange) {
body['from_year'] = dateRange[0];
body['to_year'] = dateRange[1];
}
const response = await apiPost(`${API_URI}/search_suggestions`, body);
if (response.ok) {
const content = await response.json();

View file

@ -1657,7 +1657,22 @@ export function getParentDirectory(filePath) {
export function MultilineText({text, ...props}) {
return <div {...props}>
{text.split('\n').map((line, index, array) =>
index === array.length - 1 ? line : <p>{line}</p>
index === array.length - 1 ? line : <p key={index}>{line}</p>
)}
</div>
}
export const monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];

View file

@ -0,0 +1,230 @@
import React from "react";
import {Button, Form, FormField, Modal, ModalActions, ModalContent, ModalHeader, Segment} from "./Theme";
import {Checkbox, Dropdown} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {monthNames} from "./Common";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
export const dateRangeIsEmpty = (dateRange) => {
return dateRange[0] === null && dateRange[1] === null;
}
function MonthsForm({monthsSelected, setMonthsSelected}) {
monthsSelected = monthsSelected.map(i => parseInt(i));
const handleWinter = (e) => {
if (e) e.preventDefault();
setMonthsSelected([12, 1, 2]);
}
const handleSpring = (e) => {
if (e) e.preventDefault();
setMonthsSelected([3, 4, 5]);
}
const handleSummer = (e) => {
if (e) e.preventDefault();
setMonthsSelected([6, 7, 8]);
}
const handleFall = (e) => {
if (e) e.preventDefault();
setMonthsSelected([9, 10, 11]);
}
const monthCheckbox = (label) => {
// "January" == 1, etc.
const idx = monthNames.indexOf(label) + 1;
const isChecked = monthsSelected.indexOf(idx) >= 0;
return <Checkbox
label={label}
checked={isChecked}
size='large'
onChange={(e, {checked}) => {
// Add or remove month index if the respective checkbox is checked.
if (checked) {
setMonthsSelected([...monthsSelected, idx]);
} else {
setMonthsSelected(monthsSelected.filter(i => i !== idx));
}
}}
/>
}
return <Form>
<Grid>
<Grid.Row columns={3}>
<Grid.Column>{monthCheckbox('January')}</Grid.Column>
<Grid.Column>{monthCheckbox('February')}</Grid.Column>
<Grid.Column>{monthCheckbox('March')}</Grid.Column>
</Grid.Row>
<Grid.Row columns={3}>
<Grid.Column>{monthCheckbox('April')}</Grid.Column>
<Grid.Column>{monthCheckbox('May')}</Grid.Column>
<Grid.Column>{monthCheckbox('June')}</Grid.Column>
</Grid.Row>
<Grid.Row columns={3}>
<Grid.Column>{monthCheckbox('July')}</Grid.Column>
<Grid.Column>{monthCheckbox('August')}</Grid.Column>
<Grid.Column>{monthCheckbox('September')}</Grid.Column>
</Grid.Row>
<Grid.Row columns={3}>
<Grid.Column>{monthCheckbox('October')}</Grid.Column>
<Grid.Column>{monthCheckbox('November')}</Grid.Column>
<Grid.Column>{monthCheckbox('December')}</Grid.Column>
</Grid.Row>
<Grid.Row columns={4}>
<Grid.Column><Button onClick={handleWinter} color='blue' size='small'>Winter</Button></Grid.Column>
<Grid.Column><Button onClick={handleSpring} color='green' size='small'>Spring</Button></Grid.Column>
<Grid.Column><Button onClick={handleSummer} color='yellow' size='small'>Summer</Button></Grid.Column>
<Grid.Column><Button onClick={handleFall} color='red' size='small'>Fall</Button></Grid.Column>
</Grid.Row>
</Grid>
</Form>
}
function DateRangeForm({dateRange, setDateRange}) {
const currentYear = (new Date()).getFullYear();
const [error, setError] = React.useState('');
let yearRange = [];
for (let i = 1970; i <= currentYear; i++) {
yearRange = [...yearRange, {
key: i,
text: i,
value: i,
}];
}
const handleFromYear = (e, {value}) => {
const toYear = dateRange[1] || currentYear;
setDateRange([value, toYear]);
}
const handleToYear = (e, {value}) => {
setDateRange([dateRange[0], value]);
}
React.useEffect(() => {
if (dateRange[0] > dateRange[1]) {
setError('From Year must be greater than To Year');
} else {
setError('');
}
}, [dateRange])
const errorMessage = error && <Message error content={error}/>;
return <React.Fragment>
<Form>
<Grid>
<Grid.Row columns={2}>
<Grid.Column>
<FormField>
<label>From Year</label>
<Dropdown search scrolling fluid
options={yearRange}
value={dateRange[0]}
onChange={handleFromYear}
error={!!error}
/>
</FormField>
</Grid.Column>
<Grid.Column>
<FormField>
<label>To Year</label>
<Dropdown search scrolling fluid
options={yearRange.reverse()}
value={dateRange[1]}
onChange={handleToYear}
error={!!error}
/>
</FormField>
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
{errorMessage}
</React.Fragment>
}
export function DateSelectorButton({
onMonthsChange,
onDateRangeChange,
defaultMonthsSelected,
defaultDateRange,
buttonProps
}) {
const emptyDateRange = [null, null];
const [open, setOpen] = React.useState(false);
const [monthsSelected, setMonthsSelected] = React.useState(defaultMonthsSelected || []);
const [dateRange, setDateRange] = React.useState(defaultDateRange || emptyDateRange);
const [color, setColor] = React.useState('grey');
React.useEffect(() => {
if (monthsSelected.length > 0 || (!dateRangeIsEmpty(dateRange))) {
setColor('violet');
} else {
setColor('grey');
}
}, [JSON.stringify(dateRange), JSON.stringify(monthsSelected)]);
const handleOpen = (e) => {
if (e) e.preventDefault();
setOpen(true);
}
const handleClose = (e) => {
if (e) e.preventDefault();
setOpen(false);
// Only submit selection when user has closed selector.
if (onDateRangeChange && dateRange[0] <= dateRange[1]) {
onDateRangeChange(dateRange);
} else if (onDateRangeChange && dateRangeIsEmpty(dateRange)) {
//Clear the date range.
onDateRangeChange(dateRange);
}
if (onMonthsChange) {
onMonthsChange(monthsSelected);
}
}
const localOnSetDateRange = (newDateRange) => {
setDateRange(newDateRange);
}
const handleClear = (e) => {
if (e) e.preventDefault();
setDateRange(emptyDateRange);
setMonthsSelected([]);
}
return <React.Fragment>
<Button
icon='calendar alternate'
onClick={handleOpen}
color={color}
{...buttonProps}
/>
<Modal closeIcon
open={open}
onClose={handleClose}
size='tiny'
>
<ModalHeader>Filter by Date</ModalHeader>
<ModalContent>
<Segment>
<DateRangeForm dateRange={dateRange} setDateRange={localOnSetDateRange}/>
</Segment>
<Segment>
<MonthsForm monthsSelected={monthsSelected} setMonthsSelected={setMonthsSelected}/>
</Segment>
</ModalContent>
<ModalActions>
<Button onClick={handleClear} secondary>Clear</Button>
<Button onClick={handleClose}>Close</Button>
</ModalActions>
</Modal>
</React.Fragment>
}

View file

@ -194,7 +194,7 @@ export function FilePreviewProvider({children}) {
if (previewQuery && !previewFile) {
initPreviewFile();
}
}, []);
}, [previewQuery]);
const localFetchFile = async () => {
// Get the file again with its Tags.

View file

@ -32,9 +32,9 @@ import {
useTitle
} from "./Common";
import {
useAllQuery,
useFilesProgressInterval,
usePages,
useQuery,
useSearchFiles,
useSearchFilter,
useSearchView,
@ -149,7 +149,7 @@ function FileCard({file}) {
</ExternalCardLink>
</CardHeader>
{author && <b {...s}>{author}</b>}
<p>{isoDatetimeToString(file.modified)}</p>
<p>{isoDatetimeToString(file.published_datetime) || isoDatetimeToString(file.modified)}</p>
<p>{size}</p>
</CardContent>
</Card>
@ -403,6 +403,9 @@ export function SearchFilter({filters = [], modalHeader, size = 'medium'}) {
</Form.Field>
);
// Use violet color when filter has been applied.
const buttonColor = filter ? 'violet' : 'grey';
if (filters && filters.length > 0) {
return <>
<Modal open={open} onOpen={() => handleOpen()} onClose={() => setOpen(false)} closeIcon>
@ -420,7 +423,7 @@ export function SearchFilter({filters = [], modalHeader, size = 'medium'}) {
<Button
icon='filter'
onClick={handleOpen}
primary={!!filter}
color={buttonColor}
size={size}
/>
</>
@ -430,12 +433,11 @@ export function SearchFilter({filters = [], modalHeader, size = 'medium'}) {
}
export function TagsQuerySelector({onChange}) {
// Creates dropdown that the User can use to manipulate the tag query.
const {searchParams, updateQuery} = useQuery();
const activeTags = searchParams.getAll('tag');
// Creates modal that the User can use to manipulate the tag query.
const [activeTags, setActiveTags] = useAllQuery('tag');
const localOnChange = (tagNames) => {
updateQuery({'tag': tagNames});
setActiveTags(tagNames);
if (onChange) {
onChange(tagNames);
}

View file

@ -1,7 +1,7 @@
import React, {useState} from "react";
import {createSearchParams, Route, Routes, useNavigate} from "react-router-dom";
import {Route, Routes, useNavigate} from "react-router-dom";
import {FilesSearchView} from "./Files";
import {useLatestRequest, usePages, useQuery, useSearchFilter} from "../hooks/customHooks";
import {useLatestRequest, usePages, useSearchDateRange, useSearchFilter, useSearchMonths} from "../hooks/customHooks";
import {ZimSearchView} from "./Zim";
import {searchEstimateZims, searchSuggestions} from "../api";
import {filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common";
@ -9,6 +9,7 @@ import _ from "lodash";
import {TagsContext} from "../Tags";
import {Button as SButton, Header as SHeader, Label} from "semantic-ui-react";
import {Modal, ModalContent} from "./Theme";
import {QueryContext} from "../contexts/contexts";
const SUGGESTED_APPS = [
{location: '/admin', title: 'Downloads', description: 'View and control your downloads'},
@ -37,7 +38,9 @@ const SUGGESTED_APPS = [
export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false, model) => {
const navigate = useNavigate();
const {searchParams, updateQuery} = useQuery();
const {months, setMonths} = useSearchMonths();
const {dateRange, setDateRange} = useSearchDateRange();
const {searchParams, updateQuery, getLocationStr} = React.useContext(QueryContext);
// `searchStr` means actually fetch the files/zims.
const searchStr = searchParams.get('q');
// User can search only by Tags, `searchStr` not required.
@ -53,11 +56,8 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
if (filter) {
searchQuery['filter'] = filter;
}
navigate({
pathname: '/search',
// Start new search at offset 0.
search: createSearchParams(searchQuery).toString(),
});
const location = getLocationStr(searchQuery, '/search');
navigate(location);
}
const clearSearch = () => {
@ -90,6 +90,8 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
setSearchStr,
clearSearch,
setTags,
months, setMonths,
dateRange, setDateRange,
}
}
@ -101,6 +103,8 @@ export function useSuggestions(searchStr, tagNames, filter) {
zimsEstimates: [],
}
const [suggestions, setSuggestions] = React.useState(defaultSuggestions);
const {months} = useSearchMonths();
const {dateRange} = useSearchDateRange();
// fileGroups/channels/domains.
const {data, sendRequest, loading} = useLatestRequest(500);
// Zims are slow, so they are separate.
@ -109,10 +113,17 @@ export function useSuggestions(searchStr, tagNames, filter) {
React.useEffect(() => {
if ((searchStr && searchStr.length > 0) || (tagNames && tagNames.length > 0)) {
const mimetypes = filterToMimetypes(filter);
sendRequest(async () => await searchSuggestions(searchStr, tagNames, mimetypes));
sendRequest(async () => await searchSuggestions(searchStr, tagNames, mimetypes, months, dateRange));
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
}
}, [searchStr, sendRequest, sendZimRequest, JSON.stringify(tagNames)]);
}, [
searchStr,
sendRequest,
sendZimRequest,
JSON.stringify(tagNames),
JSON.stringify(months),
JSON.stringify(dateRange),
]);
React.useEffect(() => {
if (!_.isEmpty(data)) {
@ -141,8 +152,10 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) {
const [searchStr, setSearchStr] = React.useState(defaultSearchStr || '');
const [searchTags, setSearchTags] = React.useState(defaultTagNames);
const {SingleTag, fuzzyMatchTagsByName} = React.useContext(TagsContext);
const {months, setMonths} = useSearchMonths();
const {dateRange, setDateRange} = useSearchDateRange();
const {suggestions, loading} = useSuggestions(searchStr, searchTags, filter);
const {getLocationStr} = useQuery();
const {getLocationStr} = React.useContext(QueryContext);
// The results that will be displayed by <Search>.
const [suggestionsResults, setSuggestionsResults] = useState({});
@ -275,12 +288,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames) {
suggestions,
suggestionsResults,
suggestionsSums,
searchStr,
setSearchStr,
searchStr, setSearchStr,
setSearchTags,
months, setMonths,
handleResultSelect,
resultRenderer,
loading,
dateRange, setDateRange,
}
}

View file

@ -52,7 +52,7 @@ import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {Button, Card, Header, Loader, Placeholder, Segment, Statistic, StatisticGroup} from "./Theme";
import {deleteVideos} from "../api";
import {Media, ThemeContext} from "../contexts/contexts";
import {Media, QueryContext, ThemeContext} from "../contexts/contexts";
import _ from "lodash";
export function VideoWrapper() {
@ -69,7 +69,7 @@ export function VideoWrapper() {
function VideosPage() {
const {channelId} = useParams();
const {searchParams} = useQuery();
const {searchParams} = React.useContext(QueryContext);
const [selectedVideos, setSelectedVideos] = useState([]);
let searchOrder = defaultVideoOrder;

View file

@ -13,6 +13,13 @@ export const SettingsContext = React.createContext({
fetchSettings: null,
});
export const QueryContext = React.createContext({
searchParams: null,
setSearchParams: null,
updateQuery: null,
getLocationStr: null,
})
export const AppMedia = createMedia({
breakpoints: {
mobile: 0, tablet: 700, computer: 1024,

View file

@ -15,7 +15,6 @@ import {
getSettings,
getStatistics,
getStatus,
getThrottleStatus,
getVideo,
getVideosStatistics,
searchArchives,
@ -28,7 +27,7 @@ import {
} from "../api";
import {createSearchParams, useLocation, useSearchParams} from "react-router-dom";
import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common";
import {SettingsContext, StatusContext} from "../contexts/contexts";
import {QueryContext, SettingsContext, StatusContext} from "../contexts/contexts";
import {toast} from "react-semantic-toasts-2";
import {useSearch} from "../components/Search";
import _ from "lodash";
@ -103,63 +102,95 @@ export const useLatestRequest = (delay = 300, defaultLoading = false) => {
return {data, sendRequest, loading};
};
const getSearchParamCopy = (searchParams) => {
let copy = {};
if (searchParams) {
Array.from(searchParams.keys()).forEach(key => {
const value = searchParams.getAll(key)
copy[key] = value.length === 1 ? value[0] : value;
})
}
copy = removeEmptyValues(copy);
return copy;
}
export const useQuery = () => {
const removeEmptyValues = (obj) => {
Object.entries(obj).forEach(([k, v]) => {
// Clear any empty values.
if (v === null || v === undefined || (Array.isArray(v) && v.length === 0)) {
delete obj[k];
}
});
return obj
}
export const useQuery = (defaultParams) => {
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const [state, setState] = React.useState(defaultParams || getSearchParamCopy(searchParams));
const setQuery = (obj, replace = true) => {
console.debug(`setQuery`, obj);
setSearchParams(createSearchParams(obj), {replace: replace});
}
const getQuery = (obj) => {
const newQuery = {};
for (const entry of searchParams.entries()) {
newQuery[entry[0]] = entry[1];
React.useEffect(() => {
// Copy the state into the URL.
setSearchParams(state);
if (!_.isEmpty(state)) {
console.debug('Changing URL params', state);
}
Object.entries(obj).forEach(([key, value]) => {
if (value === undefined || value === null || value === '') {
delete newQuery[key];
} else {
newQuery[key] = value;
}
})
return newQuery;
}
}, [state]);
const updateQuery = (obj) => {
const newQuery = getQuery(obj);
setQuery(newQuery);
}
React.useEffect(() => {
// Keep URL and state in sync.
setState(getSearchParamCopy(searchParams));
}, [searchParams]);
const updateQuery = (newParams, replace = false) => {
// Update the old state with the new values.
setState(oldState => {
if (replace) {
// Ignore oldState because all values are going to be replaced.
return removeEmptyValues(newParams);
} else {
return removeEmptyValues({...oldState, ...newParams});
}
});
};
const getLocationStr = (newSearchParams, pathname) => {
// Get the current location, but with new params appended.
const newQuery = createSearchParams(getQuery(newSearchParams));
newSearchParams = {...state, ...newSearchParams};
const newQuery = createSearchParams(newSearchParams);
return `${pathname || location.pathname}?${newQuery.toString()}`
}
return {searchParams, setSearchParams, setQuery, updateQuery, getLocationStr}
return {searchParams, updateQuery, getLocationStr}
}
export const QueryProvider = (props) => {
const value = useQuery();
return <QueryContext.Provider value={value}>
{props.children}
</QueryContext.Provider>
}
export const useOneQuery = (name) => {
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const value = searchParams.get(name);
const setValue = (newValue) => {
console.debug(`useOneQuery setValue=${newValue}`);
updateQuery({[name]: newValue});
const setValue = (newValue, replace = false) => {
updateQuery({[name]: newValue}, replace);
}
return [value, setValue]
}
export const useAllQuery = (name) => {
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const value = searchParams.getAll(name);
const setValue = (newValue) => {
updateQuery({[name]: newValue});
const setValue = (newValue, replace = false) => {
updateQuery({[name]: newValue}, replace);
}
return [value, setValue]
@ -212,7 +243,7 @@ export const useArchive = (archiveId) => {
}
export const usePages = (defaultLimit = 24, totalPages = 0) => {
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const offset = searchParams.get('o') || 0;
const limit = parseInt(searchParams.get('l') || defaultLimit || 24);
const [activePage, setActivePage] = useState(calculatePage(offset, limit));
@ -232,7 +263,7 @@ export const usePages = (defaultLimit = 24, totalPages = 0) => {
const setTotal = (total) => {
const newTotalPages = calculateTotalPages(total, limit);
console.log('newTotalPages', newTotalPages);
console.debug('newTotalPages', newTotalPages);
setTotalPages(newTotalPages);
}
@ -245,7 +276,7 @@ export const usePages = (defaultLimit = 24, totalPages = 0) => {
export const useSearchArchives = (defaultLimit) => {
const {domain} = useSearchDomain();
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const searchStr = searchParams.get('q') || '';
const order = searchParams.get('order');
const activeTags = searchParams.getAll('tag');
@ -304,7 +335,7 @@ export const useSearchArchives = (defaultLimit) => {
}
export const useSearchVideos = (defaultLimit, channelId, order_by) => {
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
const searchStr = searchParams.get('q') || '';
const order = searchParams.get('order') || order_by;
@ -473,7 +504,9 @@ export const useSearchFiles = (defaultLimit = 48, emptySearch = false, model) =>
searchStr,
filter,
model: model_,
setSearchStr
setSearchStr,
months,
dateRange,
} = useSearch(defaultLimit, emptySearch, model);
const {view} = useSearchView();
@ -486,9 +519,16 @@ export const useSearchFiles = (defaultLimit = 48, emptySearch = false, model) =>
}
const mimetypes = filterToMimetypes(filter);
setSearchFiles(null);
let fromYear;
let toYear;
if (dateRange) {
fromYear = dateRange[0];
toYear = dateRange[1];
}
try {
let [file_groups, total] = await filesSearch(
pages.offset, pages.limit, searchStr, mimetypes, model || model_, activeTags, headline);
pages.offset, pages.limit, searchStr, mimetypes, model || model_, activeTags, headline,
months, fromYear, toYear);
setSearchFiles(file_groups);
pages.setTotal(total);
} catch (e) {
@ -514,7 +554,17 @@ export const useSearchFiles = (defaultLimit = 48, emptySearch = false, model) =>
}
// Handle when this is unmounted.
return () => debouncedLocalSearchFiles.cancel();
}, [searchStr, pages.effect, filter, model, model_, JSON.stringify(activeTags), headline]);
}, [
searchStr,
pages.effect,
filter,
model,
model_,
JSON.stringify(activeTags),
headline,
JSON.stringify(months),
JSON.stringify(dateRange),
]);
return {
searchFiles,
@ -933,6 +983,33 @@ export const useSearchOrder = () => {
return {sort, setSort}
}
export const useSearchMonths = () => {
const {searchParams, updateQuery} = React.useContext(QueryContext);
const months = searchParams.getAll('month');
const setMonths = (newMonths) => {
// Set new months, go back to first page.
updateQuery({'month': newMonths, 'o': 0});
}
return {months, setMonths}
}
export const useSearchDateRange = () => {
const {searchParams, updateQuery} = React.useContext(QueryContext);
let fromDate = searchParams.get('fromDate');
let toDate = searchParams.get('toDate');
fromDate = fromDate ? parseInt(fromDate) : null;
toDate = toDate ? parseInt(toDate) : null;
const setDateRange = ([newFromDate, newToDate]) => {
// Set new date range, go back to first page.
updateQuery({fromDate: newFromDate, toDate: newToDate, 'o': 0});
}
return {dateRange: [fromDate, toDate], setDateRange}
}
export const useUploadFile = () => {
const [files, setFiles] = useState([]);
const [progresses, setProgresses] = useState({});
@ -983,7 +1060,7 @@ export const useUploadFile = () => {
handleProgress(file.name, chunkNum, totalChunks, 'pending', file.type);
const expectedChunk = data['expected_chunk'];
if (xhr.status === 416) {
console.log(`Server requested a different chunk ${chunkNum}`);
console.warn(`Server requested a different chunk ${chunkNum}`);
await uploadChunk(file, expectedChunk, chunkSize, totalChunks, tries + 1, maxTries);
} else {
console.debug(`Uploading of chunk ${chunkNum} succeeded, got request for chunk ${chunkNum}`);
@ -992,7 +1069,7 @@ export const useUploadFile = () => {
}
} else if (xhr.status === 201) {
handleProgress(file.name, totalChunks, totalChunks, 'complete', file.type);
console.log(`Uploading of ${file.path} completed.`);
console.info(`Uploading of ${file.path} completed.`);
} else if (xhr.status === 400) {
handleProgress(file.name, totalChunks, totalChunks, 'conflicting', file.type);
const data = JSON.parse(xhr.responseText);
@ -1046,7 +1123,7 @@ export const useUploadFile = () => {
export const useSearchZims = (defaultLimit) => {
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
const {searchParams, updateQuery} = useQuery();
const {searchParams, updateQuery} = React.useContext(QueryContext);
const searchStr = searchParams.get('q') || '';
const [zims, setZims] = useState(null);