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: frontend categories #614

Merged
merged 4 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 src/lib/components/results/general/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* @property {string} query
* @property {string} category
* @property {number} currentPage
* @property {ResultType[]} results
* @property {WebResultType[]} results
*/

/** @type {Props} */
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/results/general/single.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

/**
* @typedef {object} Props
* @property {ResultType} result
* @property {WebResultType} result
*/

/** @type {Props} */
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/results/images/main.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
* @property {string} query
* @property {string} category
* @property {number} currentPage
* @property {ResultType[]} results
* @property {ResultType | undefined} imagePreview
* @property {ImagesResultType[]} results
* @property {ImagesResultType | undefined} imagePreview
*/

/** @type {Props} */
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/results/images/preview.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

/**
* @typedef {object} Props
* @property {ResultType} result
* @property {ResultType | undefined} imagePreview
* @property {ImagesResultType} result
* @property {ImagesResultType | undefined} imagePreview
*/

/** @type {Props} */
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/results/images/single.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

/**
* @typedef {object} Props
* @property {ResultType} result
* @property {ResultType | undefined} imagePreview
* @property {ImagesResultType} result
* @property {ImagesResultType | undefined} imagePreview
*/

/** @type {Props} */
Expand Down
26 changes: 19 additions & 7 deletions src/lib/components/results/infiniteloading/main.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
<script>
import { concatSearchParams } from '$lib/functions/api/concatparams';
import { fetchAdditionalResults } from '$lib/functions/api/additionalresults';
import { fetchResults } from '$lib/functions/api/fetchapi';
import {
fetchAdditionalWebResults,
fetchAdditionalImagesResults
} from '$lib/functions/api/additionalresults';
import { fetchWebResults, fetchImagesResults } from '$lib/functions/api/fetchapi';
import { assertImagesResultType } from '$lib/types/search/assert';
import { getCategoryConfigBase64 } from '$lib/functions/categories/convert';

/**
* @typedef {object} Props
* @property {string} query
* @property {string} category
* @property {number} currentPage
* @property {ResultType[]} results
* @property {WebResultType[] | ImagesResultType[]} results
*/

/** @type {Props} */
Expand All @@ -20,21 +25,28 @@
event.preventDefault();
const params = concatSearchParams([
['q', query],
['category', category],
['category', getCategoryConfigBase64(category)],
['start', nextPage.toString()]
]);
const newResults = await fetchAdditionalResults(results, params);
const newResults = assertImagesResultType(results, category)
? await fetchAdditionalImagesResults(results, params)
: await fetchAdditionalWebResults(results, params);
results = newResults;
nextPage = nextPage + 1;
}

async function preloadResults() {
const params = concatSearchParams([
['q', query],
['category', category],
['category', getCategoryConfigBase64(category)],
['start', nextPage.toString()]
]);
await fetchResults(params);

if (assertImagesResultType(results, category)) {
await fetchImagesResults(params);
} else {
await fetchWebResults(params);
}
}
</script>

Expand Down
10 changes: 5 additions & 5 deletions src/lib/components/searchbox/main.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script>
import { CategoryEnum } from '$lib/types/search/category';
import { CategoryEnum } from '$lib/types/search/categoryenum';
import { getQueryWithoutCategory } from '$lib/functions/query/category';
import { fetchSuggestions } from '$lib/functions/api/fetchapi';
import { fetchSuggestionsResults } from '$lib/functions/api/fetchapi';

/**
* @typedef {object} Props
Expand All @@ -15,7 +15,7 @@
let {
homepage = false,
query = '',
category = CategoryEnum.GENERAL,
category = CategoryEnum.WEB,
aleksasiriski marked this conversation as resolved.
Show resolved Hide resolved
// @ts-ignore
loading = $bindable(false)
} = $props();
Expand All @@ -36,7 +36,7 @@
// Whether to show suggestions or not.
let shouldShowSuggs = $state(homepage);

/** @type {SuggestionType[]} */
/** @type {SuggestionsResultType[]} */
let suggestions = $state([]);

// Determines if the suggestions can be shown.
Expand All @@ -47,7 +47,7 @@
if (getQueryWithoutCategory(currQuery) === '') {
suggestions = [];
} else if (currentIndex === -1) {
fetchSuggestions(getQueryWithoutCategory(currQuery)).then((resp) => {
fetchSuggestionsResults(getQueryWithoutCategory(currQuery)).then((resp) => {
const maxSize = 10;
if (resp.suggestions.length > maxSize)
resp.suggestions.splice(maxSize, resp.suggestions.length - maxSize);
Expand Down
44 changes: 39 additions & 5 deletions src/lib/functions/api/additionalresults.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,47 @@
import { fetchResults } from './fetchapi';
import { fetchWebResults, fetchImagesResults } from './fetchapi';

/**
* Fetches additional results from the API and combines with the old results.
* @param {ResultType[]} oldResults
* @param {WebResultType[]} oldResults
* @param {URLSearchParams} params
* @returns {Promise<ResultType[]>}
* @returns {Promise<WebResultType[]>}
*/
export async function fetchAdditionalResults(oldResults, params) {
const resp = await fetchResults(params);
export async function fetchAdditionalWebResults(oldResults, params) {
const resp = await fetchWebResults(params);
const newResults = resp.results;

// Get the last rank from old results.
const lastRank = oldResults[oldResults.length - 1].rank;

// Make the new results start from the last rank of the old results.
for (const result of newResults) {
result.rank += lastRank;
}

// Combine the old results with the new results (removing duplicates).
const combinedResults = oldResults.concat(
newResults.filter(
(newResult) => !oldResults.some((oldResult) => oldResult.url === newResult.url)
)
);

// Make all ranks consecutive.
// Starting from the appended results, because the old results already have consecutive ranks.
for (let i = lastRank; i < combinedResults.length; i++) {
combinedResults[i].rank = i + 1;
}

return combinedResults;
}

/**
* Fetches additional results from the API and combines with the old results.
* @param {ImagesResultType[]} oldResults
* @param {URLSearchParams} params
* @returns {Promise<ImagesResultType[]>}
*/
export async function fetchAdditionalImagesResults(oldResults, params) {
const resp = await fetchImagesResults(params);
const newResults = resp.results;

// Get the last rank from old results.
Expand Down
2 changes: 1 addition & 1 deletion src/lib/functions/api/createurl.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { error } from '@sveltejs/kit';
* @param {URLSearchParams} [params]
* @returns {URL}
*/
export function createApiUrl(path = '', params = new URLSearchParams()) {
export function createApiUrl(path = '/', params = new URLSearchParams()) {
const apiUri = env.PUBLIC_API_URI;
if (!apiUri) {
// Internal Server Error.
Expand Down
40 changes: 26 additions & 14 deletions src/lib/functions/api/fetchapi.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getSuggestionsCategoryConfigBase64 } from '../categories/convert';
import { concatSearchParams } from './concatparams';
import { fetchAPI } from './fetchapigeneric';

Expand All @@ -7,41 +8,52 @@ import { fetchAPI } from './fetchapigeneric';
* @returns {Promise<CurrenciesResponseType>}
*/
export async function fetchCurrencies(fetcher = fetch) {
return await fetchAPI(fetcher, 'currencies');
return await fetchAPI(fetcher, '/exchange/currencies');
}

// /**
// * Fetches /exchange with params from the API.
// * @param {URLSearchParams} params
// * @param {typeof fetch} [fetcher]
// * @returns {Promise<ExchangeResponseType>}
// */
// export async function fetchExchange(params, fetcher = fetch) {
// return await fetchAPI(fetcher, '/exchange', params);
// }

/**
* Fetches /exchange with params from the API.
* Fetches /search/web with params from the API.
* @param {URLSearchParams} params
* @param {typeof fetch} [fetcher]
* @returns {Promise<ExchangeResponseType>}
* @returns {Promise<WebResultsResponseType>}
*/
export async function fetchExchange(params, fetcher = fetch) {
return await fetchAPI(fetcher, 'exchange', params);
export async function fetchWebResults(params, fetcher = fetch) {
return await fetchAPI(fetcher, '/search/web', params);
}

/**
* Fetches /search with params from the API.
* Fetches /search/images with params from the API.
* @param {URLSearchParams} params
* @param {typeof fetch} [fetcher]
* @returns {Promise<ResultsResponseType>}
* @returns {Promise<ImagesResultsResponseType>}
*/
export async function fetchResults(params, fetcher = fetch) {
return await fetchAPI(fetcher, 'search', params);
export async function fetchImagesResults(params, fetcher = fetch) {
return await fetchAPI(fetcher, '/search/images', params);
}

/**
* Fetches /suggestions with query from the API.
* Fetches /search/suggestions with query from the API.
* @param {string} query
* @param {typeof fetch} [fetcher]
* @returns {Promise<SuggestionsResponseType>}
* @returns {Promise<SuggestionsResultsResponseType>}
*/
export async function fetchSuggestions(query, fetcher = fetch) {
export async function fetchSuggestionsResults(query, fetcher = fetch) {
/** @type {URLSearchParams} */
const params = concatSearchParams([
['q', query],
['output', 'json']
['output', 'json'],
['category', getSuggestionsCategoryConfigBase64()]
]);

return await fetchAPI(fetcher, 'suggestions', params);
return await fetchAPI(fetcher, '/search/suggestions', params);
}
2 changes: 1 addition & 1 deletion src/lib/functions/api/fetchapiversion.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function fetchVersion(fetcher = fetch) {
/** @type {URL} */
let apiUrl;
try {
apiUrl = createApiUrl('versionz');
apiUrl = createApiUrl('/versionz');
} catch (err) {
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err}`);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/functions/api/proxyimage.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function proxyImageLink(url, hash, timestamp) {
/** @type {URL} */
let apiUrl;
try {
apiUrl = createApiUrl('proxy', params);
apiUrl = createApiUrl('/imageproxy', params);
} catch (err) {
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err}`);
Expand All @@ -45,7 +45,7 @@ export function proxyFaviconLink(fqdn, hash, timestamp) {
/** @type {URL} */
let apiUrl;
try {
apiUrl = createApiUrl('proxy', params);
apiUrl = createApiUrl('/imageproxy', params);
} catch (err) {
// Internal Server Error.
throw error(500, `Failed to create API URL: ${err}`);
Expand Down
34 changes: 34 additions & 0 deletions src/lib/functions/categories/convert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { CategoryEnum } from '$lib/types/search/categoryenum';
import { imagesCategory } from './images';
import { scienceCategory } from './science';
import { suggestionsCategory } from './suggestions';
import { thoroughCategory } from './thorough';
import { webCategory } from './web';

/**
* Returns the category config in Base64 format.
* @param {CategoryEnum} category - The category string to map.
* @returns {string} The category config.
*/
export function getCategoryConfigBase64(category) {
switch (category) {
case CategoryEnum.WEB:
return btoa(JSON.stringify(webCategory));
case CategoryEnum.IMAGES:
return btoa(JSON.stringify(imagesCategory));
case CategoryEnum.SCIENCE:
return btoa(JSON.stringify(scienceCategory));
case CategoryEnum.THOROUGH:
return btoa(JSON.stringify(thoroughCategory));
default:
throw new Error(`Invalid category: ${category}`);
}
}

/**
* Return the suggestions category config in Base64 format.
* @returns {string} The suggestions category config.
*/
export function getSuggestionsCategoryConfigBase64() {
return btoa(JSON.stringify(suggestionsCategory));
}
47 changes: 47 additions & 0 deletions src/lib/functions/categories/images.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Images category config.
* @type {CategoryType}
*/
export const imagesCategory = {
engines: {
bing: {
enabled: true,
required: false,
requiredbyorigin: true,
preferred: false,
preferredbyorigin: false
},
google: {
enabled: true,
required: false,
requiredbyorigin: true,
preferred: false,
preferredbyorigin: false
}
},
ranking: {
rankexp: 0.5,
rankmul: 1,
rankconst: 0,
rankscoremul: 1,
rankscoreadd: 0,
timesreturnedmul: 1,
timesreturnedadd: 0,
timesreturnedscoremul: 1,
timesreturnedscoreadd: 0,
engines: {
bing: {
mul: 1,
add: 0
},
google: {
mul: 1,
add: 0
}
}
},
timings: {
preferredtimeout: '500',
hardtimeout: '1500'
}
};
Loading