parent
10ef25eabb
commit
c970e9c015
18
.idea/code.iml
generated
Normal file
18
.idea/code.iml
generated
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/apps/daedalus_client/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/packages/daedalus/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/apps/app-playground/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/apps/app/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/apps/labrinth/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/apps/labrinth/tests" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/packages/app-lib/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
@ -33,6 +33,7 @@ pub enum ServerToClientMessage {
|
||||
UserOffline { id: UserId },
|
||||
FriendStatuses { statuses: Vec<UserStatus> },
|
||||
FriendRequest { from: UserId },
|
||||
FriendRequestRejected { from: UserId },
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@ -40,7 +41,7 @@ struct LauncherHeartbeatInit {
|
||||
code: String,
|
||||
}
|
||||
|
||||
#[get("launcher_heartbeat")]
|
||||
#[get("launcher_socket")]
|
||||
pub async fn ws_init(
|
||||
req: HttpRequest,
|
||||
pool: Data<PgPool>,
|
||||
@ -122,16 +123,12 @@ pub async fn ws_init(
|
||||
user.id,
|
||||
ServerToClientMessage::StatusUpdate { status },
|
||||
&pool,
|
||||
&redis,
|
||||
&db,
|
||||
Some(friends),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut stream = msg_stream
|
||||
.aggregate_continuations()
|
||||
// aggregate continuation frames up to 1MiB
|
||||
.max_continuation_size(2_usize.pow(20));
|
||||
let mut stream = msg_stream.aggregate_continuations();
|
||||
|
||||
actix_web::rt::spawn(async move {
|
||||
// receive messages from websocket
|
||||
@ -168,7 +165,6 @@ pub async fn ws_init(
|
||||
status: status.clone(),
|
||||
},
|
||||
&pool,
|
||||
&redis,
|
||||
&db,
|
||||
None,
|
||||
)
|
||||
@ -180,12 +176,23 @@ pub async fn ws_init(
|
||||
}
|
||||
|
||||
Ok(AggregatedMessage::Close(_)) => {
|
||||
let _ = close_socket(user.id, &pool, &redis, &db).await;
|
||||
let _ = close_socket(user.id, &pool, &db).await;
|
||||
}
|
||||
|
||||
Ok(AggregatedMessage::Ping(msg)) => {
|
||||
if let Some(mut socket) =
|
||||
db.auth_sockets.get_mut(&user.id.into())
|
||||
{
|
||||
let (_, socket) = socket.value_mut();
|
||||
let _ = socket.pong(&msg).await;
|
||||
}
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = close_socket(user.id, &pool, &db).await;
|
||||
});
|
||||
|
||||
Ok(res)
|
||||
@ -195,7 +202,6 @@ pub async fn broadcast_friends(
|
||||
user_id: UserId,
|
||||
message: ServerToClientMessage,
|
||||
pool: &PgPool,
|
||||
redis: &RedisPool,
|
||||
sockets: &ActiveSockets,
|
||||
friends: Option<Vec<FriendItem>>,
|
||||
) -> Result<(), crate::database::models::DatabaseError> {
|
||||
@ -218,17 +224,7 @@ pub async fn broadcast_friends(
|
||||
{
|
||||
let (_, socket) = socket.value_mut();
|
||||
|
||||
// TODO: bulk close sockets for better perf
|
||||
if socket.text(serde_json::to_string(&message)?).await.is_err()
|
||||
{
|
||||
Box::pin(close_socket(
|
||||
friend_id.into(),
|
||||
pool,
|
||||
redis,
|
||||
sockets,
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
let _ = socket.text(serde_json::to_string(&message)?).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -239,22 +235,20 @@ pub async fn broadcast_friends(
|
||||
pub async fn close_socket(
|
||||
id: UserId,
|
||||
pool: &PgPool,
|
||||
redis: &RedisPool,
|
||||
sockets: &ActiveSockets,
|
||||
) -> Result<(), crate::database::models::DatabaseError> {
|
||||
if let Some((_, (_, socket))) = sockets.auth_sockets.remove(&id) {
|
||||
let _ = socket.close(None).await;
|
||||
}
|
||||
|
||||
broadcast_friends(
|
||||
id,
|
||||
ServerToClientMessage::UserOffline { id },
|
||||
pool,
|
||||
redis,
|
||||
sockets,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -74,8 +74,6 @@ pub async fn add_friend(
|
||||
async fn send_friend_status(
|
||||
user_id: UserId,
|
||||
friend_id: UserId,
|
||||
pool: &PgPool,
|
||||
redis: &RedisPool,
|
||||
sockets: &ActiveSockets,
|
||||
) -> Result<(), ApiError> {
|
||||
if let Some(pair) = sockets.auth_sockets.get(&user_id.into()) {
|
||||
@ -85,45 +83,21 @@ pub async fn add_friend(
|
||||
{
|
||||
let (_, socket) = socket.value_mut();
|
||||
|
||||
if socket
|
||||
let _ = socket
|
||||
.text(serde_json::to_string(
|
||||
&ServerToClientMessage::StatusUpdate {
|
||||
status: friend_status.clone(),
|
||||
},
|
||||
)?)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
close_socket(
|
||||
friend_id.into(),
|
||||
pool,
|
||||
redis,
|
||||
sockets,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
send_friend_status(
|
||||
friend.user_id,
|
||||
friend.friend_id,
|
||||
&pool,
|
||||
&redis,
|
||||
&db,
|
||||
)
|
||||
.await?;
|
||||
send_friend_status(
|
||||
friend.friend_id,
|
||||
friend.user_id,
|
||||
&pool,
|
||||
&redis,
|
||||
&db,
|
||||
)
|
||||
.await?;
|
||||
send_friend_status(friend.user_id, friend.friend_id, &db).await?;
|
||||
send_friend_status(friend.friend_id, friend.user_id, &db).await?;
|
||||
} else {
|
||||
if friend.id == user.id.into() {
|
||||
return Err(ApiError::InvalidInput(
|
||||
@ -157,7 +131,7 @@ pub async fn add_friend(
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
close_socket(user.id, &pool, &redis, &db).await?;
|
||||
close_socket(user.id, &pool, &db).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -177,6 +151,7 @@ pub async fn remove_friend(
|
||||
pool: web::Data<PgPool>,
|
||||
redis: web::Data<RedisPool>,
|
||||
session_queue: web::Data<AuthQueue>,
|
||||
db: web::Data<ActiveSockets>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(
|
||||
&req,
|
||||
@ -202,6 +177,18 @@ pub async fn remove_friend(
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Some(mut socket) = db.auth_sockets.get_mut(&friend.id.into()) {
|
||||
let (_, socket) = socket.value_mut();
|
||||
|
||||
let _ = socket
|
||||
.text(serde_json::to_string(
|
||||
&ServerToClientMessage::FriendRequestRejected {
|
||||
from: user.id,
|
||||
},
|
||||
)?)
|
||||
.await;
|
||||
}
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
|
||||
@ -16,10 +16,10 @@ use reqwest::header::HeaderValue;
|
||||
use reqwest::Method;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
type WriteSocket =
|
||||
Arc<Mutex<Option<SplitSink<WebSocketStream<ConnectStream>, Message>>>>;
|
||||
Arc<RwLock<Option<SplitSink<WebSocketStream<ConnectStream>, Message>>>>;
|
||||
|
||||
pub struct FriendsSocket {
|
||||
write: WriteSocket,
|
||||
@ -67,7 +67,7 @@ impl Default for FriendsSocket {
|
||||
impl FriendsSocket {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
write: Arc::new(Mutex::new(None)),
|
||||
write: Arc::new(RwLock::new(None)),
|
||||
user_statuses: Arc::new(DashMap::new()),
|
||||
}
|
||||
}
|
||||
@ -83,7 +83,7 @@ impl FriendsSocket {
|
||||
|
||||
if let Some(credentials) = credentials {
|
||||
let mut request = format!(
|
||||
"{MODRINTH_SOCKET_URL}_internal/launcher_heartbeat?code={}",
|
||||
"{MODRINTH_SOCKET_URL}_internal/launcher_socket?code={}",
|
||||
credentials.session
|
||||
)
|
||||
.into_client_request()?;
|
||||
@ -105,7 +105,7 @@ impl FriendsSocket {
|
||||
let (write, read) = socket.split();
|
||||
|
||||
{
|
||||
let mut write_lock = self.write.lock().await;
|
||||
let mut write_lock = self.write.write().await;
|
||||
*write_lock = Some(write);
|
||||
}
|
||||
|
||||
@ -181,10 +181,8 @@ impl FriendsSocket {
|
||||
}
|
||||
}
|
||||
|
||||
let mut w = write_handle.lock().await;
|
||||
let mut w = write_handle.write().await;
|
||||
*w = None;
|
||||
|
||||
Self::reconnect_task();
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
@ -192,8 +190,6 @@ impl FriendsSocket {
|
||||
"Error connecting to friends socket: {e:?}"
|
||||
);
|
||||
|
||||
Self::reconnect_task();
|
||||
|
||||
return Err(crate::Error::from(e));
|
||||
}
|
||||
}
|
||||
@ -202,40 +198,42 @@ impl FriendsSocket {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reconnect_task() {
|
||||
tokio::task::spawn(async move {
|
||||
let res = async {
|
||||
pub async fn reconnect_task() -> crate::Result<()> {
|
||||
let state = crate::State::get().await?;
|
||||
|
||||
{
|
||||
if state.friends_socket.write.lock().await.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
tokio::task::spawn(async move {
|
||||
let mut last_connection = Utc::now();
|
||||
|
||||
state
|
||||
loop {
|
||||
let connected = {
|
||||
let read = state.friends_socket.write.read().await;
|
||||
read.is_some()
|
||||
};
|
||||
|
||||
if !connected
|
||||
&& Utc::now().signed_duration_since(last_connection)
|
||||
> chrono::Duration::seconds(30)
|
||||
{
|
||||
last_connection = Utc::now();
|
||||
let _ = state
|
||||
.friends_socket
|
||||
.connect(
|
||||
&state.pool,
|
||||
&state.api_semaphore,
|
||||
&state.process_manager,
|
||||
)
|
||||
.await?;
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok::<(), crate::Error>(())
|
||||
};
|
||||
|
||||
if let Err(e) = res.await {
|
||||
tracing::info!("Error reconnecting to friends socket: {e:?}");
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
FriendsSocket::reconnect_task();
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn disconnect(&self) -> crate::Result<()> {
|
||||
let mut write_lock = self.write.lock().await;
|
||||
let mut write_lock = self.write.write().await;
|
||||
if let Some(ref mut write_half) = *write_lock {
|
||||
write_half.close().await?;
|
||||
*write_lock = None;
|
||||
@ -247,7 +245,7 @@ impl FriendsSocket {
|
||||
&self,
|
||||
profile_name: Option<String>,
|
||||
) -> crate::Result<()> {
|
||||
let mut write_lock = self.write.lock().await;
|
||||
let mut write_lock = self.write.write().await;
|
||||
if let Some(ref mut write_half) = *write_lock {
|
||||
write_half
|
||||
.send(Message::Text(serde_json::to_string(
|
||||
|
||||
@ -87,6 +87,16 @@ impl State {
|
||||
if let Err(e) = res {
|
||||
tracing::error!("Error running discord RPC: {e}");
|
||||
}
|
||||
|
||||
let _ = state
|
||||
.friends_socket
|
||||
.connect(
|
||||
&state.pool,
|
||||
&state.api_semaphore,
|
||||
&state.process_manager,
|
||||
)
|
||||
.await;
|
||||
let _ = FriendsSocket::reconnect_task().await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
@ -138,9 +148,6 @@ impl State {
|
||||
let process_manager = ProcessManager::new();
|
||||
|
||||
let friends_socket = FriendsSocket::new();
|
||||
friends_socket
|
||||
.connect(&pool, &fetch_semaphore, &process_manager)
|
||||
.await?;
|
||||
|
||||
Ok(Arc::new(Self {
|
||||
directories,
|
||||
|
||||
@ -41,6 +41,9 @@ const props = withDefaults(
|
||||
{
|
||||
type: 'standard',
|
||||
openByDefault: false,
|
||||
buttonClass: null,
|
||||
contentClass: null,
|
||||
titleWrapperClass: null,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to: any
|
||||
}>()
|
||||
|
||||
|
||||
@ -70,7 +70,7 @@
|
||||
</ButtonStyled>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { CheckIcon, DropdownIcon, SearchIcon, XIcon } from '@modrinth/assets'
|
||||
import { CheckIcon, DropdownIcon, SearchIcon } from '@modrinth/assets'
|
||||
import { ButtonStyled, PopoutMenu, Button } from '../index'
|
||||
import { computed, ref } from 'vue'
|
||||
import ScrollablePanel from './ScrollablePanel.vue'
|
||||
@ -94,6 +94,7 @@ const props = withDefaults(
|
||||
direction: 'auto',
|
||||
displayName: (option: Option) => option as string,
|
||||
search: false,
|
||||
dropdownId: null,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@ -368,7 +368,6 @@ onMounted(() => {
|
||||
if (clipboardData.files && clipboardData.files.length > 0 && props.onImageUpload) {
|
||||
// If the user is pasting a file, upload it if there's an included handler and insert the link.
|
||||
uploadImagesFromList(clipboardData.files)
|
||||
|
||||
.then(function (url) {
|
||||
const selection = markdownCommands.yankSelection(view)
|
||||
const altText = selection || 'Replace this with a description'
|
||||
@ -654,7 +653,7 @@ function cleanUrl(input: string): string {
|
||||
// Attempt to validate and parse the URL
|
||||
try {
|
||||
url = new URL(input)
|
||||
} catch (e) {
|
||||
} catch {
|
||||
throw new Error('Invalid URL. Make sure the URL is well-formed.')
|
||||
}
|
||||
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
defineProps({
|
||||
sidebar: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
|
||||
@ -89,7 +89,7 @@ interface Item extends BaseOption {
|
||||
|
||||
type Option = Divider | Item
|
||||
|
||||
const props = withDefaults(
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
options: Option[]
|
||||
disabled?: boolean
|
||||
|
||||
@ -60,7 +60,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { GapIcon, ChevronLeftIcon, ChevronRightIcon } from '@modrinth/assets'
|
||||
import Button from './Button.vue'
|
||||
import ButtonStyled from './ButtonStyled.vue'
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { RadioButtonIcon, RadioButtonChecked } from '@modrinth/assets'
|
||||
import { ref } from 'vue'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
|
||||
@ -76,11 +76,19 @@ function onScroll({ target: { scrollTop, offsetHeight, scrollHeight } }) {
|
||||
}
|
||||
|
||||
&.bottom-fade {
|
||||
mask-image: linear-gradient(rgb(0 0 0 / 100%) calc(100% - var(--_fade-height)), transparent 100%);
|
||||
mask-image: linear-gradient(
|
||||
rgb(0 0 0 / 100%) calc(100% - var(--_fade-height)),
|
||||
transparent 100%
|
||||
);
|
||||
}
|
||||
|
||||
&.top-fade.bottom-fade {
|
||||
mask-image: linear-gradient(transparent, rgb(0 0 0 / 100%) var(--_fade-height), rgb(0 0 0 / 100%) calc(100% - var(--_fade-height)), transparent 100%);
|
||||
mask-image: linear-gradient(
|
||||
transparent,
|
||||
rgb(0 0 0 / 100%) var(--_fade-height),
|
||||
rgb(0 0 0 / 100%) calc(100% - var(--_fade-height)),
|
||||
transparent 100%
|
||||
);
|
||||
}
|
||||
}
|
||||
.scrollable-pane {
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
<template>
|
||||
<span
|
||||
class="inline-flex items-center gap-1 font-semibold text-secondary"
|
||||
>
|
||||
<span class="inline-flex items-center gap-1 font-semibold text-secondary">
|
||||
<component :is="icon" v-if="icon" :aria-hidden="true" class="shrink-0" />
|
||||
{{ formattedName }}
|
||||
</span>
|
||||
|
||||
@ -942,7 +942,6 @@ async function submitPayment() {
|
||||
|
||||
defineExpose({
|
||||
show: () => {
|
||||
|
||||
stripe = Stripe(props.publishableKey)
|
||||
|
||||
selectedPlan.value = 'yearly'
|
||||
|
||||
@ -3,21 +3,20 @@ import AutoLink from '../base/AutoLink.vue'
|
||||
import Avatar from '../base/Avatar.vue'
|
||||
import Checkbox from '../base/Checkbox.vue'
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
import { SlashIcon } from '@modrinth/assets'
|
||||
|
||||
import { ref } from 'vue'
|
||||
|
||||
export interface ContentCreator {
|
||||
name: string
|
||||
type: 'user' | 'organization'
|
||||
id: string
|
||||
link?: string | RouteLocationRaw
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
linkProps?: any
|
||||
}
|
||||
|
||||
export interface ContentProject {
|
||||
id: string
|
||||
link?: string | RouteLocationRaw
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
linkProps?: any
|
||||
}
|
||||
|
||||
@ -46,7 +45,7 @@ withDefaults(
|
||||
},
|
||||
)
|
||||
|
||||
const model = defineModel()
|
||||
const model = defineModel<boolean>()
|
||||
</script>
|
||||
<template>
|
||||
<div
|
||||
|
||||
@ -5,7 +5,6 @@ import Checkbox from '../base/Checkbox.vue'
|
||||
import ContentListItem from './ContentListItem.vue'
|
||||
import type { ContentItem } from './ContentListItem.vue'
|
||||
import { DropdownIcon } from '@modrinth/assets'
|
||||
// @ts-ignore
|
||||
import { RecycleScroller } from 'vue-virtual-scroller'
|
||||
|
||||
const props = withDefaults(
|
||||
|
||||
@ -69,6 +69,7 @@ const props = withDefaults(
|
||||
closeOnClickOutside: true,
|
||||
closeOnEsc: true,
|
||||
warnOnClose: false,
|
||||
header: null,
|
||||
onHide: () => {},
|
||||
onShow: () => {},
|
||||
},
|
||||
|
||||
@ -7,31 +7,29 @@ import { computed } from 'vue'
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
project: {
|
||||
body: string,
|
||||
color: number,
|
||||
body: string
|
||||
color: number
|
||||
}
|
||||
}>(),
|
||||
{
|
||||
},
|
||||
{},
|
||||
)
|
||||
|
||||
function clamp(value: number) {
|
||||
return Math.max(0, Math.min(255, value));
|
||||
return Math.max(0, Math.min(255, value))
|
||||
}
|
||||
|
||||
function toHex(value: number) {
|
||||
return clamp(value).toString(16).padStart(2, '0');
|
||||
return clamp(value).toString(16).padStart(2, '0')
|
||||
}
|
||||
|
||||
function decimalToHexColor(decimal: number) {
|
||||
const r = (decimal >> 16) & 255;
|
||||
const g = (decimal >> 8) & 255;
|
||||
const b = decimal & 255;
|
||||
const r = (decimal >> 16) & 255
|
||||
const g = (decimal >> 8) & 255
|
||||
const b = decimal & 255
|
||||
|
||||
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
|
||||
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
|
||||
}
|
||||
|
||||
|
||||
const color = computed(() => {
|
||||
return decimalToHexColor(props.project.color)
|
||||
})
|
||||
|
||||
@ -7,10 +7,7 @@
|
||||
{{ project.title }}
|
||||
</template>
|
||||
<template #title-suffix>
|
||||
<ProjectStatusBadge
|
||||
v-if="member || project.status !== 'approved'"
|
||||
:status="project.status"
|
||||
/>
|
||||
<ProjectStatusBadge v-if="member || project.status !== 'approved'" :status="project.status" />
|
||||
</template>
|
||||
<template #summary>
|
||||
{{ project.description }}
|
||||
@ -39,10 +36,7 @@
|
||||
<div class="hidden items-center gap-2 md:flex">
|
||||
<TagsIcon class="h-6 w-6 text-secondary" />
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<TagItem
|
||||
v-for="(category, index) in project.categories"
|
||||
:key="index"
|
||||
>
|
||||
<TagItem v-for="(category, index) in project.categories" :key="index">
|
||||
{{ formatCategory(category) }}
|
||||
</TagItem>
|
||||
</div>
|
||||
@ -55,7 +49,6 @@
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { DownloadIcon, HeartIcon, TagsIcon } from '@modrinth/assets'
|
||||
import Badge from '../base/SimpleBadge.vue'
|
||||
import Avatar from '../base/Avatar.vue'
|
||||
import ContentPageHeader from '../base/ContentPageHeader.vue'
|
||||
import { formatCategory, formatNumber, type Project } from '@modrinth/utils'
|
||||
|
||||
@ -2,14 +2,12 @@
|
||||
<div class="markdown-body" v-html="renderHighlightedString(description ?? '')" />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
|
||||
import { renderHighlightedString } from '@modrinth/utils'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
description: string,
|
||||
description: string
|
||||
}>(),
|
||||
{
|
||||
},
|
||||
{},
|
||||
)
|
||||
</script>
|
||||
|
||||
@ -87,11 +87,16 @@
|
||||
<div class="flex items-center">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<TagItem
|
||||
v-for="gameVersion in formatVersionsForDisplay(version.game_versions, gameVersions)"
|
||||
v-for="gameVersion in formatVersionsForDisplay(
|
||||
version.game_versions,
|
||||
gameVersions,
|
||||
)"
|
||||
:key="`version-tag-${gameVersion}`"
|
||||
v-tooltip="`Toggle filter for ${gameVersion}`"
|
||||
class="z-[1]"
|
||||
:action="() => versionFilters?.toggleFilters('gameVersion', version.game_versions)"
|
||||
:action="
|
||||
() => versionFilters?.toggleFilters('gameVersion', version.game_versions)
|
||||
"
|
||||
>
|
||||
{{ gameVersion }}
|
||||
</TagItem>
|
||||
@ -141,10 +146,7 @@
|
||||
<div class="flex items-start justify-end gap-1 sm:items-center z-[1]">
|
||||
<slot name="actions" :version="version"></slot>
|
||||
</div>
|
||||
<div
|
||||
v-if="showFiles"
|
||||
class="tag-list pointer-events-none relative z-[1] col-span-full"
|
||||
>
|
||||
<div v-if="showFiles" class="tag-list pointer-events-none relative z-[1] col-span-full">
|
||||
<div
|
||||
v-for="(file, fileIdx) in version.files"
|
||||
:key="`platform-tag-${fileIdx}`"
|
||||
@ -169,17 +171,16 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
formatBytes,
|
||||
formatCategory, formatNumber,
|
||||
formatCategory,
|
||||
formatNumber,
|
||||
formatVersionsForDisplay,
|
||||
type GameVersionTag, type PlatformTag, type Version
|
||||
type GameVersionTag,
|
||||
type PlatformTag,
|
||||
type Version,
|
||||
} from '@modrinth/utils'
|
||||
|
||||
import { commonMessages } from '../../utils/common-messages'
|
||||
import {
|
||||
CalendarIcon,
|
||||
DownloadIcon,
|
||||
StarIcon,
|
||||
} from '@modrinth/assets'
|
||||
import { CalendarIcon, DownloadIcon, StarIcon } from '@modrinth/assets'
|
||||
import { Pagination, VersionChannelIndicator, VersionFilterControl } from '../index'
|
||||
import { useVIntl } from '@vintl/vintl'
|
||||
import { type Ref, ref, computed } from 'vue'
|
||||
@ -196,18 +197,18 @@ type VersionWithDisplayUrlEnding = Version & {
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
baseId?: string,
|
||||
baseId?: string
|
||||
project: {
|
||||
project_type: string
|
||||
slug?: string
|
||||
id: string
|
||||
},
|
||||
versions: VersionWithDisplayUrlEnding[],
|
||||
showFiles?: boolean,
|
||||
currentMember?: boolean,
|
||||
loaders: PlatformTag[],
|
||||
gameVersions: GameVersionTag[],
|
||||
versionLink?: (version: Version) => string,
|
||||
}
|
||||
versions: VersionWithDisplayUrlEnding[]
|
||||
showFiles?: boolean
|
||||
currentMember?: boolean
|
||||
loaders: PlatformTag[]
|
||||
gameVersions: GameVersionTag[]
|
||||
versionLink?: (version: Version) => string
|
||||
}>(),
|
||||
{
|
||||
baseId: undefined,
|
||||
@ -217,23 +218,26 @@ const props = withDefaults(
|
||||
},
|
||||
)
|
||||
|
||||
const currentPage: Ref<number> = ref(1);
|
||||
const pageSize: Ref<number> = ref(20);
|
||||
const currentPage: Ref<number> = ref(1)
|
||||
const pageSize: Ref<number> = ref(20)
|
||||
const versionFilters: Ref<InstanceType<typeof VersionFilterControl> | null> = ref(null)
|
||||
|
||||
const selectedGameVersions: Ref<string[]> = computed(() => versionFilters.value?.selectedGameVersions ?? []);
|
||||
const selectedPlatforms: Ref<string[]> = computed(() => versionFilters.value?.selectedPlatforms ?? []);
|
||||
const selectedChannels: Ref<string[]> = computed(() => versionFilters.value?.selectedChannels ?? []);
|
||||
const selectedGameVersions: Ref<string[]> = computed(
|
||||
() => versionFilters.value?.selectedGameVersions ?? [],
|
||||
)
|
||||
const selectedPlatforms: Ref<string[]> = computed(
|
||||
() => versionFilters.value?.selectedPlatforms ?? [],
|
||||
)
|
||||
const selectedChannels: Ref<string[]> = computed(() => versionFilters.value?.selectedChannels ?? [])
|
||||
|
||||
const filteredVersions = computed(() => {
|
||||
return props.versions.filter(
|
||||
(version) =>
|
||||
hasAnySelected(version.game_versions, selectedGameVersions.value) &&
|
||||
hasAnySelected(version.loaders, selectedPlatforms.value) &&
|
||||
isAnySelected(version.version_type, selectedChannels.value)
|
||||
);
|
||||
});
|
||||
|
||||
isAnySelected(version.version_type, selectedChannels.value),
|
||||
)
|
||||
})
|
||||
|
||||
function hasAnySelected(values: string[], selected: string[]) {
|
||||
return selected.length === 0 || selected.some((value) => values.includes(value))
|
||||
@ -244,33 +248,37 @@ function isAnySelected(value: string, selected: string[]) {
|
||||
}
|
||||
|
||||
const currentVersions = computed(() =>
|
||||
filteredVersions.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value));
|
||||
filteredVersions.value.slice(
|
||||
(currentPage.value - 1) * pageSize.value,
|
||||
currentPage.value * pageSize.value,
|
||||
),
|
||||
)
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
if (route.query.page) {
|
||||
currentPage.value = Number(route.query.page) || 1;
|
||||
currentPage.value = Number(route.query.page) || 1
|
||||
}
|
||||
|
||||
function switchPage(page: number) {
|
||||
currentPage.value = page;
|
||||
currentPage.value = page
|
||||
|
||||
router.replace({
|
||||
query: {
|
||||
...route.query,
|
||||
page: currentPage.value !== 1 ? currentPage.value : undefined,
|
||||
},
|
||||
});
|
||||
})
|
||||
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
|
||||
function updateQuery(newQueries: Record<string, string | string[] | undefined | null>) {
|
||||
if (newQueries.page) {
|
||||
currentPage.value = Number(newQueries.page);
|
||||
currentPage.value = Number(newQueries.page)
|
||||
} else if (newQueries.page === undefined) {
|
||||
currentPage.value = 1;
|
||||
currentPage.value = 1
|
||||
}
|
||||
|
||||
router.replace({
|
||||
@ -278,9 +286,8 @@ function updateQuery(newQueries: Record<string, string | string[] | undefined |
|
||||
...route.query,
|
||||
...newQueries,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
<style scoped>
|
||||
.versions-grid-row {
|
||||
|
||||
@ -60,7 +60,10 @@
|
||||
<TagItem
|
||||
v-if="
|
||||
project.project_type !== 'datapack' &&
|
||||
project.client_side !== 'unsupported' && project.server_side !== 'unsupported' && project.client_side !== 'unknown' && project.server_side !== 'unknown'
|
||||
project.client_side !== 'unsupported' &&
|
||||
project.server_side !== 'unsupported' &&
|
||||
project.client_side !== 'unknown' &&
|
||||
project.server_side !== 'unknown'
|
||||
"
|
||||
>
|
||||
<MonitorSmartphoneIcon aria-hidden="true" />
|
||||
@ -88,6 +91,7 @@ defineProps<{
|
||||
loaders: string[]
|
||||
client_side: EnvironmentValue
|
||||
server_side: EnvironmentValue
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
versions: any[]
|
||||
}
|
||||
tags: {
|
||||
|
||||
@ -66,7 +66,7 @@
|
||||
<script setup lang="ts">
|
||||
import { BookTextIcon, CalendarIcon, ScaleIcon, VersionIcon, ExternalIcon } from '@modrinth/assets'
|
||||
import { useVIntl, defineMessages } from '@vintl/vintl'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
|
||||
@ -11,7 +11,8 @@ import {
|
||||
CalendarIcon,
|
||||
GlobeIcon,
|
||||
LinkIcon,
|
||||
UnknownIcon, XIcon
|
||||
UnknownIcon,
|
||||
XIcon,
|
||||
} from '@modrinth/assets'
|
||||
import { useVIntl, defineMessage, type MessageDescriptor } from '@vintl/vintl'
|
||||
import type { Component } from 'vue'
|
||||
@ -30,7 +31,7 @@ const metadata = computed(() => ({
|
||||
formattedName: formatMessage(statusMetadata[props.status]?.message ?? props.status),
|
||||
}))
|
||||
|
||||
const statusMetadata: Record<ProjectStatus, { icon?: Component, message: MessageDescriptor }> = {
|
||||
const statusMetadata: Record<ProjectStatus, { icon?: Component; message: MessageDescriptor }> = {
|
||||
approved: {
|
||||
icon: GlobeIcon,
|
||||
message: defineMessage({
|
||||
|
||||
@ -69,6 +69,7 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const filters = computed(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const filters: FilterType<any>[] = [
|
||||
{
|
||||
id: 'platform',
|
||||
|
||||
@ -4,8 +4,7 @@
|
||||
:class="`flex border-none cursor-pointer !w-full items-center gap-2 truncate rounded-xl px-2 py-2 [@media(hover:hover)]:py-1 text-sm font-semibold transition-all hover:text-contrast focus-visible:text-contrast active:scale-[0.98] ${included ? 'bg-brand-highlight text-contrast hover:brightness-125' : excluded ? 'bg-highlight-red text-contrast hover:brightness-125' : 'bg-transparent text-secondary hover:bg-button-bg focus-visible:bg-button-bg [&>svg.check-icon]:hover:text-brand [&>svg.check-icon]:focus-visible:text-brand'}`"
|
||||
@click="() => emit('toggle', option)"
|
||||
>
|
||||
<slot>
|
||||
</slot>
|
||||
<slot> </slot>
|
||||
<BanIcon
|
||||
v-if="excluded"
|
||||
:class="`filter-action-icon ml-auto h-4 w-4 shrink-0 transition-opacity group-hover:opacity-100 ${excluded ? '' : '[@media(hover:hover)]:opacity-0'}`"
|
||||
@ -17,8 +16,11 @@
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
<div v-if="supportsNegativeFilter && !excluded" class="w-px h-[1.75rem] bg-button-bg [@media(hover:hover)]:contents" :class="{ 'opacity-0': included }">
|
||||
</div>
|
||||
<div
|
||||
v-if="supportsNegativeFilter && !excluded"
|
||||
class="w-px h-[1.75rem] bg-button-bg [@media(hover:hover)]:contents"
|
||||
:class="{ 'opacity-0': included }"
|
||||
></div>
|
||||
<button
|
||||
v-if="supportsNegativeFilter && !excluded"
|
||||
v-tooltip="excluded ? 'Remove exclusion' : 'Exclude'"
|
||||
@ -34,14 +36,17 @@
|
||||
import { BanIcon, CheckIcon } from '@modrinth/assets'
|
||||
import type { FilterOption } from '../../utils/search'
|
||||
|
||||
withDefaults(defineProps<{
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
option: FilterOption
|
||||
included: boolean
|
||||
excluded: boolean
|
||||
supportsNegativeFilter?: boolean
|
||||
}>(), {
|
||||
}>(),
|
||||
{
|
||||
supportsNegativeFilter: false,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
toggle: [option: FilterOption]
|
||||
|
||||
@ -79,119 +79,119 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { FilterIcon, XCircleIcon, XIcon } from "@modrinth/assets";
|
||||
import { ManySelect, Checkbox } from "../index";
|
||||
import { type Version , formatCategory, type GameVersionTag } from '@modrinth/utils';
|
||||
import { ref, computed } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { FilterIcon, XCircleIcon, XIcon } from '@modrinth/assets'
|
||||
import { ManySelect, Checkbox } from '../index'
|
||||
import { type Version, formatCategory, type GameVersionTag } from '@modrinth/utils'
|
||||
import { ref, computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import TagItem from '../base/TagItem.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
versions: Version[]
|
||||
gameVersions: GameVersionTag[]
|
||||
baseId?: string
|
||||
}>();
|
||||
}>()
|
||||
|
||||
const emit = defineEmits(["update:query"]);
|
||||
const emit = defineEmits(['update:query'])
|
||||
|
||||
const allChannels = ref(["release", "beta", "alpha"]);
|
||||
const allChannels = ref(['release', 'beta', 'alpha'])
|
||||
|
||||
const route = useRoute();
|
||||
const route = useRoute()
|
||||
|
||||
const showSnapshots = ref(false);
|
||||
const showSnapshots = ref(false)
|
||||
|
||||
type FilterType = "channel" | "gameVersion" | "platform";
|
||||
type Filter = string;
|
||||
type FilterType = 'channel' | 'gameVersion' | 'platform'
|
||||
type Filter = string
|
||||
|
||||
const filterOptions = computed(() => {
|
||||
const filters: Record<FilterType, Filter[]> = {
|
||||
channel: [],
|
||||
gameVersion: [],
|
||||
platform: [],
|
||||
};
|
||||
}
|
||||
|
||||
const platformSet = new Set();
|
||||
const gameVersionSet = new Set();
|
||||
const channelSet = new Set();
|
||||
const platformSet = new Set()
|
||||
const gameVersionSet = new Set()
|
||||
const channelSet = new Set()
|
||||
|
||||
for (const version of props.versions) {
|
||||
for (const loader of version.loaders) {
|
||||
platformSet.add(loader);
|
||||
platformSet.add(loader)
|
||||
}
|
||||
for (const gameVersion of version.game_versions) {
|
||||
gameVersionSet.add(gameVersion);
|
||||
gameVersionSet.add(gameVersion)
|
||||
}
|
||||
channelSet.add(version.version_type);
|
||||
channelSet.add(version.version_type)
|
||||
}
|
||||
|
||||
if (channelSet.size > 0) {
|
||||
filters.channel = Array.from(channelSet) as Filter[];
|
||||
filters.channel.sort((a, b) => allChannels.value.indexOf(a) - allChannels.value.indexOf(b));
|
||||
filters.channel = Array.from(channelSet) as Filter[]
|
||||
filters.channel.sort((a, b) => allChannels.value.indexOf(a) - allChannels.value.indexOf(b))
|
||||
}
|
||||
if (gameVersionSet.size > 0) {
|
||||
const gameVersions = props.gameVersions.filter((x) => gameVersionSet.has(x.version));
|
||||
const gameVersions = props.gameVersions.filter((x) => gameVersionSet.has(x.version))
|
||||
|
||||
filters.gameVersion = gameVersions
|
||||
.filter((x) => (showSnapshots.value ? true : x.version_type === "release"))
|
||||
.map((x) => x.version);
|
||||
.filter((x) => (showSnapshots.value ? true : x.version_type === 'release'))
|
||||
.map((x) => x.version)
|
||||
}
|
||||
if (platformSet.size > 0) {
|
||||
filters.platform = Array.from(platformSet) as Filter[];
|
||||
filters.platform = Array.from(platformSet) as Filter[]
|
||||
}
|
||||
|
||||
return filters;
|
||||
});
|
||||
return filters
|
||||
})
|
||||
|
||||
const selectedChannels = ref<string[]>([]);
|
||||
const selectedGameVersions = ref<string[]>([]);
|
||||
const selectedPlatforms = ref<string[]>([]);
|
||||
const selectedChannels = ref<string[]>([])
|
||||
const selectedGameVersions = ref<string[]>([])
|
||||
const selectedPlatforms = ref<string[]>([])
|
||||
|
||||
selectedChannels.value = route.query.c ? getArrayOrString(route.query.c) : [];
|
||||
selectedGameVersions.value = route.query.g ? getArrayOrString(route.query.g) : [];
|
||||
selectedPlatforms.value = route.query.l ? getArrayOrString(route.query.l) : [];
|
||||
selectedChannels.value = route.query.c ? getArrayOrString(route.query.c) : []
|
||||
selectedGameVersions.value = route.query.g ? getArrayOrString(route.query.g) : []
|
||||
selectedPlatforms.value = route.query.l ? getArrayOrString(route.query.l) : []
|
||||
|
||||
async function toggleFilters(type: FilterType, filters: Filter[]) {
|
||||
for (const filter of filters) {
|
||||
await toggleFilter(type, filter, true);
|
||||
await toggleFilter(type, filter, true)
|
||||
}
|
||||
|
||||
updateFilters();
|
||||
updateFilters()
|
||||
}
|
||||
|
||||
async function toggleFilter(type: FilterType, filter: Filter, bulk = false) {
|
||||
if (type === "channel") {
|
||||
if (type === 'channel') {
|
||||
selectedChannels.value = selectedChannels.value.includes(filter)
|
||||
? selectedChannels.value.filter((x) => x !== filter)
|
||||
: [...selectedChannels.value, filter];
|
||||
} else if (type === "gameVersion") {
|
||||
: [...selectedChannels.value, filter]
|
||||
} else if (type === 'gameVersion') {
|
||||
selectedGameVersions.value = selectedGameVersions.value.includes(filter)
|
||||
? selectedGameVersions.value.filter((x) => x !== filter)
|
||||
: [...selectedGameVersions.value, filter];
|
||||
} else if (type === "platform") {
|
||||
: [...selectedGameVersions.value, filter]
|
||||
} else if (type === 'platform') {
|
||||
selectedPlatforms.value = selectedPlatforms.value.includes(filter)
|
||||
? selectedPlatforms.value.filter((x) => x !== filter)
|
||||
: [...selectedPlatforms.value, filter];
|
||||
: [...selectedPlatforms.value, filter]
|
||||
}
|
||||
if (!bulk) {
|
||||
updateFilters();
|
||||
updateFilters()
|
||||
}
|
||||
}
|
||||
|
||||
async function clearFilters() {
|
||||
selectedChannels.value = [];
|
||||
selectedGameVersions.value = [];
|
||||
selectedPlatforms.value = [];
|
||||
selectedChannels.value = []
|
||||
selectedGameVersions.value = []
|
||||
selectedPlatforms.value = []
|
||||
|
||||
updateFilters();
|
||||
updateFilters()
|
||||
}
|
||||
|
||||
function updateFilters() {
|
||||
emit("update:query", {
|
||||
emit('update:query', {
|
||||
c: selectedChannels.value,
|
||||
g: selectedGameVersions.value,
|
||||
l: selectedPlatforms.value,
|
||||
page: undefined,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
@ -200,13 +200,13 @@ defineExpose({
|
||||
selectedChannels,
|
||||
selectedGameVersions,
|
||||
selectedPlatforms,
|
||||
});
|
||||
})
|
||||
|
||||
function getArrayOrString(x: string | string[]): string[] {
|
||||
if (typeof x === "string") {
|
||||
return [x];
|
||||
if (typeof x === 'string') {
|
||||
return [x]
|
||||
} else {
|
||||
return x;
|
||||
return x
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@ -30,18 +30,18 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ButtonStyled, VersionChannelIndicator } from "../index";
|
||||
import { DownloadIcon, ExternalIcon } from "@modrinth/assets";
|
||||
import { computed } from "vue";
|
||||
import { ButtonStyled, VersionChannelIndicator } from '../index'
|
||||
import { DownloadIcon, ExternalIcon } from '@modrinth/assets'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
version: Version;
|
||||
}>();
|
||||
version: Version
|
||||
}>()
|
||||
|
||||
const downloadUrl = computed(() => {
|
||||
const primary: VersionFile = props.version.files.find((x) => x.primary) || props.version.files[0];
|
||||
return primary.url;
|
||||
});
|
||||
const primary: VersionFile = props.version.files.find((x) => x.primary) || props.version.files[0]
|
||||
return primary.url
|
||||
})
|
||||
|
||||
const emit = defineEmits(["onDownload", "onNavigate"]);
|
||||
const emit = defineEmits(['onDownload', 'onNavigate'])
|
||||
</script>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { type Ref , type Component, computed, readonly, ref } from 'vue';
|
||||
import { type Ref, type Component, computed, readonly, ref } from 'vue'
|
||||
import { type LocationQueryRaw, type LocationQueryValue, useRoute } from 'vue-router'
|
||||
import { defineMessage, useVIntl } from '@vintl/vintl'
|
||||
import { formatCategory, formatCategoryHeader, sortByNameOrNumber } from '@modrinth/utils'
|
||||
@ -8,40 +8,44 @@ type BaseOption = {
|
||||
id: string
|
||||
formatted_name?: string
|
||||
toggle_group?: string
|
||||
icon?: string | Component,
|
||||
query_value?: string,
|
||||
icon?: string | Component
|
||||
query_value?: string
|
||||
}
|
||||
|
||||
export type FilterOption = BaseOption & (
|
||||
{ method: 'or' | 'and', value: string, } |
|
||||
{ method: 'environment', environment: 'client' | 'server', }
|
||||
export type FilterOption = BaseOption &
|
||||
(
|
||||
| { method: 'or' | 'and'; value: string }
|
||||
| { method: 'environment'; environment: 'client' | 'server' }
|
||||
)
|
||||
|
||||
export type FilterType = {
|
||||
id: string,
|
||||
formatted_name: string,
|
||||
options: FilterOption[],
|
||||
supported_project_types: ProjectType[],
|
||||
query_param: string,
|
||||
id: string
|
||||
formatted_name: string
|
||||
options: FilterOption[]
|
||||
supported_project_types: ProjectType[]
|
||||
query_param: string
|
||||
supports_negative_filter: boolean
|
||||
toggle_groups?: {
|
||||
id: string,
|
||||
formatted_name: string,
|
||||
query_param?: string,
|
||||
}[],
|
||||
searchable: boolean,
|
||||
allows_custom_options?: 'and' | 'or',
|
||||
} & ({
|
||||
id: string
|
||||
formatted_name: string
|
||||
query_param?: string
|
||||
}[]
|
||||
searchable: boolean
|
||||
allows_custom_options?: 'and' | 'or'
|
||||
} & (
|
||||
| {
|
||||
display: 'all' | 'scrollable' | 'none'
|
||||
} | {
|
||||
display: 'expandable',
|
||||
}
|
||||
| {
|
||||
display: 'expandable'
|
||||
default_values: string[]
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
export type FilterValue = {
|
||||
type: string,
|
||||
option: string,
|
||||
negative?: boolean,
|
||||
type: string
|
||||
option: string
|
||||
negative?: boolean
|
||||
}
|
||||
|
||||
export interface GameVersion {
|
||||
@ -53,7 +57,14 @@ export interface GameVersion {
|
||||
|
||||
export type ProjectType = 'mod' | 'modpack' | 'resourcepack' | 'shader' | 'datapack' | 'plugin'
|
||||
|
||||
const ALL_PROJECT_TYPES: ProjectType[] = [ 'mod', 'modpack', 'resourcepack', 'shader', 'datapack', 'plugin' ]
|
||||
const ALL_PROJECT_TYPES: ProjectType[] = [
|
||||
'mod',
|
||||
'modpack',
|
||||
'resourcepack',
|
||||
'shader',
|
||||
'datapack',
|
||||
'plugin',
|
||||
]
|
||||
|
||||
export interface Platform {
|
||||
name: string
|
||||
@ -81,7 +92,11 @@ export interface SortType {
|
||||
name: string
|
||||
}
|
||||
|
||||
export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, providedFilters: Ref<FilterValue[]>) {
|
||||
export function useSearch(
|
||||
projectTypes: Ref<ProjectType[]>,
|
||||
tags: Ref<Tags>,
|
||||
providedFilters: Ref<FilterValue[]>,
|
||||
) {
|
||||
const query = ref('')
|
||||
const maxResults = ref(20)
|
||||
|
||||
@ -102,7 +117,7 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
const toggledGroups = ref<string[]>([])
|
||||
const overriddenProvidedFilterTypes = ref<string[]>([])
|
||||
|
||||
const { formatMessage } = useVIntl();
|
||||
const { formatMessage } = useVIntl()
|
||||
|
||||
const filters = computed(() => {
|
||||
const categoryFilters: Record<string, FilterType> = {}
|
||||
@ -112,12 +127,15 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
categoryFilters[filterTypeId] = {
|
||||
id: filterTypeId,
|
||||
formatted_name: formatCategoryHeader(category.header),
|
||||
supported_project_types: category.project_type === 'mod' ? ['mod', 'plugin', 'datapack'] : [category.project_type],
|
||||
supported_project_types:
|
||||
category.project_type === 'mod'
|
||||
? ['mod', 'plugin', 'datapack']
|
||||
: [category.project_type],
|
||||
display: 'all',
|
||||
query_param: category.header === 'resolutions' ? 'g' : 'f',
|
||||
supports_negative_filter: true,
|
||||
searchable: false,
|
||||
options: []
|
||||
options: [],
|
||||
}
|
||||
}
|
||||
categoryFilters[filterTypeId].options.push({
|
||||
@ -125,7 +143,7 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
formatted_name: formatCategory(category.name),
|
||||
icon: category.icon,
|
||||
value: `categories:${category.name}`,
|
||||
method: category.header === 'resolutions' ? 'or' : 'and'
|
||||
method: category.header === 'resolutions' ? 'or' : 'and',
|
||||
})
|
||||
}
|
||||
|
||||
@ -133,7 +151,9 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
...Object.values(categoryFilters),
|
||||
{
|
||||
id: 'environment',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.environment', defaultMessage: 'Environment' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.environment', defaultMessage: 'Environment' }),
|
||||
),
|
||||
supported_project_types: ['mod', 'modpack'],
|
||||
display: 'all',
|
||||
query_param: 'e',
|
||||
@ -142,23 +162,35 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
options: [
|
||||
{
|
||||
id: 'client',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.environment.client', defaultMessage: 'Client' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({
|
||||
id: 'search.filter_type.environment.client',
|
||||
defaultMessage: 'Client',
|
||||
}),
|
||||
),
|
||||
icon: ClientIcon,
|
||||
method: 'environment',
|
||||
environment: 'client',
|
||||
},
|
||||
{
|
||||
id: 'server',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.environment.server', defaultMessage: 'Server' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({
|
||||
id: 'search.filter_type.environment.server',
|
||||
defaultMessage: 'Server',
|
||||
}),
|
||||
),
|
||||
icon: ServerIcon,
|
||||
method: 'environment',
|
||||
environment: 'server',
|
||||
}
|
||||
]
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'game_version',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.game_version', defaultMessage: 'Game version' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.game_version', defaultMessage: 'Game version' }),
|
||||
),
|
||||
supported_project_types: ALL_PROJECT_TYPES,
|
||||
display: 'scrollable',
|
||||
query_param: 'v',
|
||||
@ -166,30 +198,43 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
toggle_groups: [
|
||||
{
|
||||
id: 'all_versions',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.game_version.all_versions', defaultMessage: 'Show all versions' })),
|
||||
query_param: 'h'
|
||||
}
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({
|
||||
id: 'search.filter_type.game_version.all_versions',
|
||||
defaultMessage: 'Show all versions',
|
||||
}),
|
||||
),
|
||||
query_param: 'h',
|
||||
},
|
||||
],
|
||||
searchable: true,
|
||||
options: tags.value.gameVersions.map(gameVersion =>
|
||||
({
|
||||
options: tags.value.gameVersions.map((gameVersion) => ({
|
||||
id: gameVersion.version,
|
||||
toggle_group: gameVersion.version_type !== 'release' ? 'all_versions' : undefined,
|
||||
value: `versions:${gameVersion.version}`,
|
||||
query_value: gameVersion.version,
|
||||
method: 'or'
|
||||
method: 'or',
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: 'mod_loader',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.mod_loader', defaultMessage: 'Loader' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.mod_loader', defaultMessage: 'Loader' }),
|
||||
),
|
||||
supported_project_types: ['mod'],
|
||||
display: 'expandable',
|
||||
query_param: 'g',
|
||||
supports_negative_filter: true,
|
||||
default_values: ['fabric', 'forge', 'neoforge', 'quilt'],
|
||||
searchable: false,
|
||||
options: tags.value.loaders.filter((loader) => loader.supported_project_types.includes('mod') && !loader.supported_project_types.includes('plugin') && !loader.supported_project_types.includes('datapack')).map(loader => {
|
||||
options: tags.value.loaders
|
||||
.filter(
|
||||
(loader) =>
|
||||
loader.supported_project_types.includes('mod') &&
|
||||
!loader.supported_project_types.includes('plugin') &&
|
||||
!loader.supported_project_types.includes('datapack'),
|
||||
)
|
||||
.map((loader) => {
|
||||
return {
|
||||
id: loader.name,
|
||||
formatted_name: formatCategory(loader.name),
|
||||
@ -201,13 +246,17 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
},
|
||||
{
|
||||
id: 'modpack_loader',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.modpack_loader', defaultMessage: 'Loader' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.modpack_loader', defaultMessage: 'Loader' }),
|
||||
),
|
||||
supported_project_types: ['modpack'],
|
||||
display: 'all',
|
||||
query_param: 'g',
|
||||
supports_negative_filter: true,
|
||||
searchable: false,
|
||||
options: tags.value.loaders.filter((loader) => loader.supported_project_types.includes('modpack')).map(loader => {
|
||||
options: tags.value.loaders
|
||||
.filter((loader) => loader.supported_project_types.includes('modpack'))
|
||||
.map((loader) => {
|
||||
return {
|
||||
id: loader.name,
|
||||
formatted_name: formatCategory(loader.name),
|
||||
@ -219,13 +268,21 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
},
|
||||
{
|
||||
id: 'plugin_loader',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.plugin_loader', defaultMessage: 'Loader' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.plugin_loader', defaultMessage: 'Loader' }),
|
||||
),
|
||||
supported_project_types: ['plugin'],
|
||||
display: 'all',
|
||||
query_param: 'g',
|
||||
supports_negative_filter: true,
|
||||
searchable: false,
|
||||
options: tags.value.loaders.filter((loader) => loader.supported_project_types.includes('plugin') && !['bungeecord', 'waterfall', 'velocity'].includes(loader.name)).map(loader => {
|
||||
options: tags.value.loaders
|
||||
.filter(
|
||||
(loader) =>
|
||||
loader.supported_project_types.includes('plugin') &&
|
||||
!['bungeecord', 'waterfall', 'velocity'].includes(loader.name),
|
||||
)
|
||||
.map((loader) => {
|
||||
return {
|
||||
id: loader.name,
|
||||
formatted_name: formatCategory(loader.name),
|
||||
@ -237,13 +294,17 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
},
|
||||
{
|
||||
id: 'plugin_platform',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.plugin_platform', defaultMessage: 'Platform' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.plugin_platform', defaultMessage: 'Platform' }),
|
||||
),
|
||||
supported_project_types: ['plugin'],
|
||||
display: 'all',
|
||||
query_param: 'g',
|
||||
supports_negative_filter: true,
|
||||
searchable: false,
|
||||
options: tags.value.loaders.filter((loader) => ['bungeecord', 'waterfall', 'velocity'].includes(loader.name)).map(loader => {
|
||||
options: tags.value.loaders
|
||||
.filter((loader) => ['bungeecord', 'waterfall', 'velocity'].includes(loader.name))
|
||||
.map((loader) => {
|
||||
return {
|
||||
id: loader.name,
|
||||
formatted_name: formatCategory(loader.name),
|
||||
@ -255,13 +316,17 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
},
|
||||
{
|
||||
id: 'shader_loader',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.shader_loader', defaultMessage: 'Loader' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.shader_loader', defaultMessage: 'Loader' }),
|
||||
),
|
||||
supported_project_types: ['shader'],
|
||||
display: 'all',
|
||||
query_param: 'g',
|
||||
supports_negative_filter: true,
|
||||
searchable: false,
|
||||
options: tags.value.loaders.filter((loader) => loader.supported_project_types.includes('shader')).map(loader => {
|
||||
options: tags.value.loaders
|
||||
.filter((loader) => loader.supported_project_types.includes('shader'))
|
||||
.map((loader) => {
|
||||
return {
|
||||
id: loader.name,
|
||||
formatted_name: formatCategory(loader.name),
|
||||
@ -273,7 +338,9 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
},
|
||||
{
|
||||
id: 'license',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.license', defaultMessage: 'License' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.license', defaultMessage: 'License' }),
|
||||
),
|
||||
supported_project_types: ['mod', 'modpack', 'resourcepack', 'shader', 'plugin', 'datapack'],
|
||||
query_param: 'l',
|
||||
supports_negative_filter: true,
|
||||
@ -282,42 +349,58 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
options: [
|
||||
{
|
||||
id: 'open_source',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.license.open_source', defaultMessage: 'Open source' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({
|
||||
id: 'search.filter_type.license.open_source',
|
||||
defaultMessage: 'Open source',
|
||||
}),
|
||||
),
|
||||
method: 'and',
|
||||
value: 'open_source:true',
|
||||
},
|
||||
]
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'project_id',
|
||||
formatted_name: formatMessage(defineMessage({ id: 'search.filter_type.project_id', defaultMessage: 'Project ID' })),
|
||||
formatted_name: formatMessage(
|
||||
defineMessage({ id: 'search.filter_type.project_id', defaultMessage: 'Project ID' }),
|
||||
),
|
||||
supported_project_types: ALL_PROJECT_TYPES,
|
||||
query_param: 'pid',
|
||||
supports_negative_filter: true,
|
||||
display: 'none',
|
||||
searchable: false,
|
||||
options: [],
|
||||
allows_custom_options: 'and'
|
||||
}
|
||||
allows_custom_options: 'and',
|
||||
},
|
||||
]
|
||||
|
||||
return filterTypes.filter(filterType => filterType.supported_project_types.some(projectType => projectTypes.value.includes(projectType)))
|
||||
return filterTypes.filter((filterType) =>
|
||||
filterType.supported_project_types.some((projectType) =>
|
||||
projectTypes.value.includes(projectType),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
const facets = computed(() => {
|
||||
const validProvidedFilters = providedFilters.value.filter(providedFilter => !overriddenProvidedFilterTypes.value.includes(providedFilter.type))
|
||||
const filteredFilters = currentFilters.value.filter((userFilter) => !validProvidedFilters.some(providedFilter => providedFilter.type === userFilter.type))
|
||||
const validProvidedFilters = providedFilters.value.filter(
|
||||
(providedFilter) => !overriddenProvidedFilterTypes.value.includes(providedFilter.type),
|
||||
)
|
||||
const filteredFilters = currentFilters.value.filter(
|
||||
(userFilter) =>
|
||||
!validProvidedFilters.some((providedFilter) => providedFilter.type === userFilter.type),
|
||||
)
|
||||
const filterValues = [...filteredFilters, ...validProvidedFilters]
|
||||
|
||||
const andFacets: string[][] = [];
|
||||
const orFacets: Record<string, string[]> = {};
|
||||
const andFacets: string[][] = []
|
||||
const orFacets: Record<string, string[]> = {}
|
||||
for (const filterValue of filterValues) {
|
||||
const type = filters.value.find(type => type.id === filterValue.type)
|
||||
const type = filters.value.find((type) => type.id === filterValue.type)
|
||||
if (!type) {
|
||||
console.error(`Filter type ${filterValue.type} not found`)
|
||||
continue
|
||||
}
|
||||
let option = type?.options.find(option => option.id === filterValue.option)
|
||||
let option = type?.options.find((option) => option.id === filterValue.option)
|
||||
if (!option && type.allows_custom_options) {
|
||||
option = {
|
||||
id: filterValue.option,
|
||||
@ -333,15 +416,15 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
|
||||
if (option.method === 'or' || option.method === 'and') {
|
||||
if (filterValue.negative) {
|
||||
andFacets.push([option.value.replace(':', '!=')]);
|
||||
andFacets.push([option.value.replace(':', '!=')])
|
||||
} else {
|
||||
if (option.method === 'or') {
|
||||
if (!orFacets[type.id]) {
|
||||
orFacets[type.id] = []
|
||||
}
|
||||
orFacets[type.id].push(option.value);
|
||||
orFacets[type.id].push(option.value)
|
||||
} else if (option.method === 'and') {
|
||||
andFacets.push([option.value]);
|
||||
andFacets.push([option.value])
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -353,10 +436,12 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
Add environment facets, separate from the rest because it oddly depends on the combination
|
||||
of filters selected to determine which facets to add.
|
||||
*/
|
||||
const client = currentFilters.value
|
||||
.some((filter) => filter.type === 'environment' && filter.option === 'client')
|
||||
const server = currentFilters.value
|
||||
.some((filter) => filter.type === 'environment' && filter.option === 'server')
|
||||
const client = currentFilters.value.some(
|
||||
(filter) => filter.type === 'environment' && filter.option === 'client',
|
||||
)
|
||||
const server = currentFilters.value.some(
|
||||
(filter) => filter.type === 'environment' && filter.option === 'server',
|
||||
)
|
||||
andFacets.push(...createEnvironmentFacets(client, server))
|
||||
|
||||
const projectType = projectTypes.value.map((projectType) => `project_type:${projectType}`)
|
||||
@ -371,95 +456,105 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
const params = [`limit=${maxResults.value}`, `index=${currentSortType.value.name}`]
|
||||
|
||||
if (query.value.length > 0) {
|
||||
params.push(`query=${encodeURIComponent(query.value)}`);
|
||||
params.push(`query=${encodeURIComponent(query.value)}`)
|
||||
}
|
||||
|
||||
params.push(`facets=${encodeURIComponent(JSON.stringify(facets.value))}`);
|
||||
params.push(`facets=${encodeURIComponent(JSON.stringify(facets.value))}`)
|
||||
|
||||
const offset = (currentPage.value - 1) * maxResults.value;
|
||||
const offset = (currentPage.value - 1) * maxResults.value
|
||||
if (currentPage.value !== 1) {
|
||||
params.push(`offset=${offset}`);
|
||||
params.push(`offset=${offset}`)
|
||||
}
|
||||
|
||||
return `?${params.join('&')}`;
|
||||
return `?${params.join('&')}`
|
||||
})
|
||||
|
||||
readQueryParams();
|
||||
readQueryParams()
|
||||
|
||||
function readQueryParams() {
|
||||
const readParams = new Set<string>();
|
||||
const readParams = new Set<string>()
|
||||
|
||||
// Load legacy params
|
||||
loadQueryParam(['l'], (openSource) => {
|
||||
if (openSource === 'true' && !currentFilters.value.some(filter => filter.type === 'license' && filter.option === 'open_source')) {
|
||||
if (
|
||||
openSource === 'true' &&
|
||||
!currentFilters.value.some(
|
||||
(filter) => filter.type === 'license' && filter.option === 'open_source',
|
||||
)
|
||||
) {
|
||||
currentFilters.value.push({
|
||||
type: 'license',
|
||||
option: 'open_source',
|
||||
negative: false,
|
||||
});
|
||||
readParams.add('l');
|
||||
})
|
||||
readParams.add('l')
|
||||
}
|
||||
});
|
||||
})
|
||||
loadQueryParam(['nf'], (filter) => {
|
||||
const set = typeof filter === 'string' ? new Set([filter]) : new Set(filter)
|
||||
|
||||
typesLoop: for (const type of filters.value) {
|
||||
for (const option of type.options) {
|
||||
const value = getOptionValue(option, false);
|
||||
if (set.has(value) && !currentFilters.value.some(filter => filter.type === type.id && filter.option === option.id)) {
|
||||
const value = getOptionValue(option, false)
|
||||
if (
|
||||
set.has(value) &&
|
||||
!currentFilters.value.some(
|
||||
(filter) => filter.type === type.id && filter.option === option.id,
|
||||
)
|
||||
) {
|
||||
currentFilters.value.push({
|
||||
type: type.id,
|
||||
option: option.id,
|
||||
negative: true,
|
||||
})
|
||||
readParams.add(type.query_param);
|
||||
readParams.add(type.query_param)
|
||||
|
||||
set.delete(value)
|
||||
|
||||
if (set.size === 0) {
|
||||
break typesLoop;
|
||||
break typesLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
loadQueryParam(['s'], (sort) => {
|
||||
currentSortType.value = sortTypes.find(sortType => sortType.name === sort) ?? sortTypes[0]
|
||||
readParams.add('s');
|
||||
currentSortType.value = sortTypes.find((sortType) => sortType.name === sort) ?? sortTypes[0]
|
||||
readParams.add('s')
|
||||
})
|
||||
loadQueryParam(['m'], (count) => {
|
||||
maxResults.value = Number(count)
|
||||
readParams.add('m');
|
||||
readParams.add('m')
|
||||
})
|
||||
loadQueryParam(['o'], (offset) => {
|
||||
currentPage.value = Math.ceil(Number(offset) / maxResults.value) + 1
|
||||
readParams.add('o');
|
||||
readParams.add('o')
|
||||
})
|
||||
loadQueryParam(['page'], (page) => {
|
||||
currentPage.value = Number(page)
|
||||
readParams.add('page');
|
||||
readParams.add('page')
|
||||
})
|
||||
|
||||
for (const key of Object.keys(route.query).filter(key => !readParams.has(key))) {
|
||||
const type = filters.value.find(type => type.query_param === key)
|
||||
for (const key of Object.keys(route.query).filter((key) => !readParams.has(key))) {
|
||||
const type = filters.value.find((type) => type.query_param === key)
|
||||
if (type) {
|
||||
const values = getParamValuesAsArray(route.query[key])
|
||||
|
||||
for (const value of values) {
|
||||
const negative = !value.includes(':') && value.includes('!=')
|
||||
const option = type.options.find(option => (getOptionValue(option, negative)) === value)
|
||||
const option = type.options.find((option) => getOptionValue(option, negative) === value)
|
||||
|
||||
if (!option && type.allows_custom_options) {
|
||||
currentFilters.value.push({
|
||||
type: type.id,
|
||||
option: value.replace('!=', ':'),
|
||||
negative: negative
|
||||
negative: negative,
|
||||
})
|
||||
} else if (option) {
|
||||
currentFilters.value.push({
|
||||
type: type.id,
|
||||
option: option.id,
|
||||
negative: negative
|
||||
negative: negative,
|
||||
})
|
||||
} else {
|
||||
console.error(`Unknown filter option: ${value}`)
|
||||
@ -472,17 +567,17 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
}
|
||||
|
||||
function createPageParams(): LocationQueryRaw {
|
||||
const items: Record<string, string[]> = {};
|
||||
const items: Record<string, string[]> = {}
|
||||
|
||||
if (query.value) {
|
||||
items.q = [query.value];
|
||||
items.q = [query.value]
|
||||
}
|
||||
|
||||
currentFilters.value.forEach(filterValue => {
|
||||
const type = filters.value.find(type => type.id === filterValue.type)
|
||||
currentFilters.value.forEach((filterValue) => {
|
||||
const type = filters.value.find((type) => type.id === filterValue.type)
|
||||
const option = type?.options.find((option) => option.id === filterValue.option)
|
||||
if (type && option) {
|
||||
const value = getOptionValue(option, filterValue.negative);
|
||||
const value = getOptionValue(option, filterValue.negative)
|
||||
if (items[type.query_param]) {
|
||||
items[type.query_param].push(value)
|
||||
} else {
|
||||
@ -491,36 +586,37 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
}
|
||||
})
|
||||
|
||||
toggledGroups.value.forEach(groupId => {
|
||||
toggledGroups.value.forEach((groupId) => {
|
||||
const group = filters.value
|
||||
.flatMap(filter => filter.toggle_groups)
|
||||
.find(group => group && group.id === groupId)
|
||||
.flatMap((filter) => filter.toggle_groups)
|
||||
.find((group) => group && group.id === groupId)
|
||||
|
||||
if (group && 'query_param' in group && group.query_param) {
|
||||
items[group.query_param] = [String(true)]
|
||||
}
|
||||
})
|
||||
|
||||
if (currentSortType.value.name !== "relevance") {
|
||||
items.s = [currentSortType.value.name];
|
||||
if (currentSortType.value.name !== 'relevance') {
|
||||
items.s = [currentSortType.value.name]
|
||||
}
|
||||
if (maxResults.value !== 20) {
|
||||
items.m = [String(maxResults.value)];
|
||||
items.m = [String(maxResults.value)]
|
||||
}
|
||||
if (currentPage.value > 1) {
|
||||
items.page = [String(currentPage.value)];
|
||||
items.page = [String(currentPage.value)]
|
||||
}
|
||||
|
||||
|
||||
return items;
|
||||
return items
|
||||
}
|
||||
|
||||
function createPageParamsString(pageParams: Record<string, string | string[] | boolean | number>) {
|
||||
let url = ``;
|
||||
function createPageParamsString(
|
||||
pageParams: Record<string, string | string[] | boolean | number>,
|
||||
) {
|
||||
let url = ``
|
||||
|
||||
Object.entries(pageParams).forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(value => {
|
||||
value.forEach((value) => {
|
||||
url = addQueryParam(url, key, value)
|
||||
})
|
||||
} else {
|
||||
@ -528,14 +624,17 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
}
|
||||
})
|
||||
|
||||
return url;
|
||||
return url
|
||||
}
|
||||
|
||||
function loadQueryParam(params: string[], provider: ((param: LocationQueryValue | LocationQueryValue[]) => void)) {
|
||||
function loadQueryParam(
|
||||
params: string[],
|
||||
provider: (param: LocationQueryValue | LocationQueryValue[]) => void,
|
||||
) {
|
||||
for (const param of params) {
|
||||
if (param in route.query) {
|
||||
provider(route.query[param]);
|
||||
return;
|
||||
provider(route.query[param])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -565,21 +664,21 @@ export function useSearch(projectTypes: Ref<ProjectType[]>, tags: Ref<Tags>, pro
|
||||
}
|
||||
|
||||
export function createEnvironmentFacets(client: boolean, server: boolean): string[][] {
|
||||
const facets: string[][] = [];
|
||||
const facets: string[][] = []
|
||||
if (client && server) {
|
||||
facets.push(["client_side:required"], ["server_side:required"])
|
||||
facets.push(['client_side:required'], ['server_side:required'])
|
||||
} else if (client) {
|
||||
facets.push(
|
||||
["client_side:optional", "client_side:required"],
|
||||
["server_side:optional", "server_side:unsupported"]
|
||||
);
|
||||
['client_side:optional', 'client_side:required'],
|
||||
['server_side:optional', 'server_side:unsupported'],
|
||||
)
|
||||
} else if (server) {
|
||||
facets.push(
|
||||
["client_side:optional", "client_side:unsupported"],
|
||||
["server_side:optional", "server_side:required"]
|
||||
);
|
||||
['client_side:optional', 'client_side:unsupported'],
|
||||
['server_side:optional', 'server_side:required'],
|
||||
)
|
||||
}
|
||||
return facets;
|
||||
return facets
|
||||
}
|
||||
|
||||
function getOptionValue(option: FilterOption, negative?: boolean): string {
|
||||
@ -603,6 +702,6 @@ function getParamValuesAsArray(x: LocationQueryValue | LocationQueryValue[]): st
|
||||
} else if (typeof x === 'string') {
|
||||
return [x]
|
||||
} else {
|
||||
return x.filter(x => x !== null)
|
||||
return x.filter((x) => x !== null)
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user