mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
Trip members can rate a place 1-5 stars; the place shows the average, with a who-voted custom tooltip and a star-sort toggle in the places sidebar. Saved collection places are ratable too (plus a min-rating filter), and ratings travel with a place copied between a trip and a collection — carrying only the votes of users who belong to both sides. Adds a full Collections MCP surface (list/get, CRUD lists + places, status, rate_collection_place, labels, sharing, copy-to-trip) under a new collections:read/collections:write scope, plus rate_place for trip places; rating aggregates flow through the existing place outputs. Mobile trip + collection place sheets gain the rating row. New UI strings translated across all 22 locales.
This commit is contained in:
@@ -404,6 +404,10 @@ export const placesApi = {
|
||||
fd.append('image', file)
|
||||
return postMultipart<{ place: Place }>(`/trips/${tripId}/places/${id}/image`, fd)
|
||||
},
|
||||
rate: (tripId: number | string, id: number | string, rating: number | null): Promise<{ place: Place }> =>
|
||||
rating === null
|
||||
? apiClient.delete(`/trips/${tripId}/places/${id}/rating`).then(r => r.data)
|
||||
: apiClient.put(`/trips/${tripId}/places/${id}/rating`, { rating }).then(r => r.data),
|
||||
importGpx: (tripId: number | string, file: File, opts?: { waypoints?: boolean; routes?: boolean; tracks?: boolean }) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
|
||||
@@ -74,6 +74,10 @@ export const collectionsApi = {
|
||||
postMultipart(`${base}/places/${pid}/image`, formData),
|
||||
setStatus: (pid: number, status: CollectionStatus): Promise<CollectionPlace> =>
|
||||
ax.post(`${base}/places/${pid}/status`, { status }).then((r: AxiosResponse) => r.data),
|
||||
ratePlace: (pid: number, rating: number | null): Promise<CollectionPlace> =>
|
||||
rating === null
|
||||
? ax.delete(`${base}/places/${pid}/rating`).then((r: AxiosResponse) => r.data)
|
||||
: ax.put(`${base}/places/${pid}/rating`, { rating }).then((r: AxiosResponse) => r.data),
|
||||
deletePlace: (pid: number): Promise<unknown> =>
|
||||
ax.delete(`${base}/places/${pid}`).then((r: AxiosResponse) => r.data),
|
||||
deleteMany: (ids: number[]): Promise<unknown> =>
|
||||
|
||||
@@ -7,6 +7,7 @@ describe('SCOPE_GROUPS', () => {
|
||||
const expected = [
|
||||
'trips:read', 'trips:write', 'trips:delete', 'trips:share',
|
||||
'places:read', 'places:write',
|
||||
'collections:read', 'collections:write',
|
||||
'atlas:read', 'atlas:write',
|
||||
'packing:read', 'packing:write',
|
||||
'todos:read', 'todos:write',
|
||||
@@ -16,6 +17,7 @@ describe('SCOPE_GROUPS', () => {
|
||||
'notifications:read', 'notifications:write',
|
||||
'vacay:read', 'vacay:write',
|
||||
'geo:read', 'weather:read',
|
||||
'journey:read', 'journey:write', 'journey:share',
|
||||
]
|
||||
for (const scope of expected) {
|
||||
expect(SCOPE_GROUPS).toHaveProperty(scope)
|
||||
@@ -32,8 +34,8 @@ describe('SCOPE_GROUPS', () => {
|
||||
})
|
||||
|
||||
describe('ALL_SCOPES', () => {
|
||||
it('FE-OAUTH-SCOPES-003: contains exactly 27 scopes', () => {
|
||||
expect(ALL_SCOPES).toHaveLength(27)
|
||||
it('FE-OAUTH-SCOPES-003: contains exactly 29 scopes', () => {
|
||||
expect(ALL_SCOPES).toHaveLength(29)
|
||||
})
|
||||
|
||||
it('FE-OAUTH-SCOPES-004: matches Object.keys(SCOPE_GROUPS)', () => {
|
||||
|
||||
@@ -20,6 +20,8 @@ export const SCOPE_GROUPS: Record<string, ScopeKeys> = {
|
||||
'trips:share': { labelKey: 'oauth.scope.trips:share.label', descriptionKey: 'oauth.scope.trips:share.description', groupKey: 'oauth.scope.group.trips' },
|
||||
'places:read': { labelKey: 'oauth.scope.places:read.label', descriptionKey: 'oauth.scope.places:read.description', groupKey: 'oauth.scope.group.places' },
|
||||
'places:write': { labelKey: 'oauth.scope.places:write.label', descriptionKey: 'oauth.scope.places:write.description', groupKey: 'oauth.scope.group.places' },
|
||||
'collections:read': { labelKey: 'oauth.scope.collections:read.label', descriptionKey: 'oauth.scope.collections:read.description', groupKey: 'oauth.scope.group.collections' },
|
||||
'collections:write': { labelKey: 'oauth.scope.collections:write.label', descriptionKey: 'oauth.scope.collections:write.description', groupKey: 'oauth.scope.group.collections' },
|
||||
'atlas:read': { labelKey: 'oauth.scope.atlas:read.label', descriptionKey: 'oauth.scope.atlas:read.description', groupKey: 'oauth.scope.group.atlas' },
|
||||
'atlas:write': { labelKey: 'oauth.scope.atlas:write.label', descriptionKey: 'oauth.scope.atlas:write.description', groupKey: 'oauth.scope.group.atlas' },
|
||||
'packing:read': { labelKey: 'oauth.scope.packing:read.label', descriptionKey: 'oauth.scope.packing:read.description', groupKey: 'oauth.scope.group.packing' },
|
||||
|
||||
@@ -27,8 +27,10 @@ function makeProps(overrides: Partial<HarnessProps> = {}): HarnessProps {
|
||||
counts: { all: 3, idea: 1, want: 1, visited: 1 },
|
||||
categoryFilter: 'all',
|
||||
categoryOptions: CATEGORY_OPTIONS,
|
||||
ratingFilter: 'all',
|
||||
onStatusFilter: vi.fn(),
|
||||
onCategoryFilter: vi.fn(),
|
||||
onRatingFilter: vi.fn(),
|
||||
showLabels: false,
|
||||
labelOptions: [],
|
||||
labelFilter: [],
|
||||
@@ -49,9 +51,9 @@ beforeEach(() => {
|
||||
describe('CollectionFilterBar', () => {
|
||||
it('FE-COMP-COLFILTERBAR-001: renders the status dropdown showing the current "All" filter', () => {
|
||||
render(<Harness {...makeProps()} />);
|
||||
// Both dropdown triggers currently read "All" (status=all, category=all).
|
||||
// With a category present there are exactly two "All" triggers: status + category.
|
||||
expect(screen.getAllByRole('button', { name: 'All' })).toHaveLength(2);
|
||||
// Three dropdown triggers read "All" (status=all, category=all, rating=all):
|
||||
// status + category + the #1435 rating filter.
|
||||
expect(screen.getAllByRole('button', { name: 'All' })).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLFILTERBAR-002: opening the status dropdown reveals the status options', async () => {
|
||||
@@ -84,15 +86,15 @@ describe('CollectionFilterBar', () => {
|
||||
|
||||
it('FE-COMP-COLFILTERBAR-004: the category dropdown is present when categoryOptions is non-empty', () => {
|
||||
render(<Harness {...makeProps()} />);
|
||||
// Two dropdown triggers = status + category.
|
||||
// Three dropdown triggers = status + category + rating.
|
||||
const triggers = screen.getAllByRole('button', { name: 'All' });
|
||||
expect(triggers).toHaveLength(2);
|
||||
expect(triggers).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLFILTERBAR-005: the category dropdown is hidden when categoryOptions is empty', () => {
|
||||
render(<Harness {...makeProps({ categoryOptions: [] })} />);
|
||||
// Only the status dropdown remains.
|
||||
expect(screen.getAllByRole('button', { name: 'All' })).toHaveLength(1);
|
||||
// The status + rating dropdowns remain (the rating filter always shows).
|
||||
expect(screen.getAllByRole('button', { name: 'All' })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-COLFILTERBAR-006: clicking a category option calls onCategoryFilter with the category id', async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { ChevronDown, Check, Layers, Tag, Tags, CheckSquare } from 'lucide-react'
|
||||
import { ChevronDown, Check, Layers, Tag, Tags, CheckSquare, Star } from 'lucide-react'
|
||||
import type { StatusFilter } from '../../store/collectionStore'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
@@ -67,8 +67,10 @@ interface CollectionFilterBarProps {
|
||||
counts: Record<StatusFilter, number>
|
||||
categoryFilter: number | 'all'
|
||||
categoryOptions: CategoryOption[]
|
||||
ratingFilter: number | 'all'
|
||||
onStatusFilter: (f: StatusFilter) => void
|
||||
onCategoryFilter: (f: number | 'all') => void
|
||||
onRatingFilter: (f: number | 'all') => void
|
||||
// Per-collection labels (hidden on the "All saved" union).
|
||||
showLabels: boolean
|
||||
labelOptions: LabelOption[]
|
||||
@@ -88,7 +90,7 @@ interface CollectionFilterBarProps {
|
||||
* Custom compact dropdowns so they barely take any space.
|
||||
*/
|
||||
export default function CollectionFilterBar({
|
||||
statusFilter, counts, categoryFilter, categoryOptions, onStatusFilter, onCategoryFilter,
|
||||
statusFilter, counts, categoryFilter, categoryOptions, ratingFilter, onStatusFilter, onCategoryFilter, onRatingFilter,
|
||||
showLabels, labelOptions, labelFilter, onLabelFilter, canManageLabels, onManageLabels,
|
||||
showSelect, selectMode, onToggleSelect, t,
|
||||
}: CollectionFilterBarProps): React.ReactElement {
|
||||
@@ -109,12 +111,23 @@ export default function CollectionFilterBar({
|
||||
}),
|
||||
]
|
||||
|
||||
// Minimum-average-rating filter (#1435): All, then ≥5…≥1 stars.
|
||||
const ratingOpts: Opt[] = [
|
||||
{ key: 'all', label: t('common.all') },
|
||||
...[5, 4, 3, 2, 1].map(n => ({
|
||||
key: n,
|
||||
label: `${n}+`,
|
||||
icon: <Star size={13} color="#facc15" fill="#facc15" />,
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="col-filterbar">
|
||||
<Dropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
|
||||
{categoryOptions.length > 0 && (
|
||||
<Dropdown current={categoryFilter} options={catOpts} onSelect={k => onCategoryFilter(k as number | 'all')} lead={<Tag size={13} />} />
|
||||
)}
|
||||
<Dropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
|
||||
{showSelect && (
|
||||
<button type="button" onClick={onToggleSelect} className={`col-filter-btn col-filter-select${selectMode ? ' open' : ''}`} aria-pressed={selectMode}>
|
||||
<CheckSquare size={14} /> <span className="col-filter-lbl">{t('collections.select')}</span>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import { STATUS_META, STATUS_ORDER, normalizeLinkUrl } from '../../pages/collections/collectionsModel'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import PlaceRating from '../shared/StarRating'
|
||||
import { normalizeImageFile } from '../../utils/convertHeic'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
|
||||
@@ -35,6 +36,8 @@ interface CollectionPlaceDetailProps {
|
||||
onUploadImage?: (file: File) => Promise<void>
|
||||
onCopyToTrip: () => void
|
||||
onRemove: () => void
|
||||
/** Cast/clear the current user's star vote (#1435); every member may vote. */
|
||||
onRate?: (rating: number | null) => Promise<void> | void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
@@ -62,7 +65,7 @@ function StatusSegment({ status, onSet, t }: { status: CollectionStatus; onSet:
|
||||
* is an always-live segmented control (auto-saves).
|
||||
*/
|
||||
export default function CollectionPlaceDetail({
|
||||
place, canEdit, canDelete, categories, labels, anchorRect, onClose, onSetStatus, onSave, onUploadImage, onCopyToTrip, onRemove, t,
|
||||
place, canEdit, canDelete, categories, labels, anchorRect, onClose, onSetStatus, onSave, onUploadImage, onCopyToTrip, onRemove, onRate, t,
|
||||
}: CollectionPlaceDetailProps): React.ReactElement {
|
||||
const toast = useToast()
|
||||
const [editing, setEditing] = useState(false)
|
||||
@@ -208,6 +211,13 @@ export default function CollectionPlaceDetail({
|
||||
{/* Status — live for editors, read-only for viewers */}
|
||||
<StatusSegment status={place.status} onSet={canEdit ? onSetStatus : () => {}} t={t} />
|
||||
|
||||
{/* Collaborative rating (#1435) — every member votes; the average shows. */}
|
||||
{onRate && (
|
||||
<div style={{ padding: '2px 0' }}>
|
||||
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={onRate} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing ? (
|
||||
<div className="col-detail-edit">
|
||||
{/* Category */}
|
||||
|
||||
@@ -7,6 +7,7 @@ import remarkBreaks from 'remark-breaks'
|
||||
import { X, Clock, MapPin, ExternalLink, Phone, Banknote, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy } from 'lucide-react'
|
||||
import PlaceAvatar from '../shared/PlaceAvatar'
|
||||
import PlaceAvatarUpload from '../shared/PlaceAvatarUpload'
|
||||
import PlaceRating from '../shared/StarRating'
|
||||
import GuestBadge from '../shared/GuestBadge'
|
||||
import StatusBadge from '../Collections/StatusBadge'
|
||||
import { mapsApi, pluginsApi } from '../../api/client'
|
||||
@@ -131,6 +132,8 @@ interface PlaceInspectorProps {
|
||||
onUpdatePlace?: (placeId: number, data: Partial<Place>) => void
|
||||
/** Upload a custom thumbnail (#1136); enables the click-to-change avatar in trip mode. */
|
||||
onUploadImage?: (placeId: number, file: File) => Promise<void>
|
||||
/** Cast/clear the current user's star vote (#1435); enables the rating row. */
|
||||
onRate?: (placeId: number, rating: number | null) => Promise<void> | void
|
||||
leftWidth?: number
|
||||
rightWidth?: number
|
||||
// ── Collection-mode props ──
|
||||
@@ -144,7 +147,7 @@ export default function PlaceInspector({
|
||||
place, categories, mode = 'trip', days = [], selectedDayId = null, selectedAssignmentId = null,
|
||||
assignments = {}, reservations = [],
|
||||
onClose, onEdit, onDelete, onAssignToDay, onRemoveAssignment,
|
||||
files = [], onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace, onUploadImage,
|
||||
files = [], onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace, onUploadImage, onRate,
|
||||
leftWidth = 0, rightWidth = 0,
|
||||
collectionStatus, onCopyToTrip, onSetStatus, onRemoveFromList,
|
||||
}: PlaceInspectorProps) {
|
||||
@@ -341,6 +344,17 @@ export default function PlaceInspector({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Collaborative rating (#1435) — every member's own vote, shown as the average. */}
|
||||
{mode === 'trip' && onRate && (
|
||||
<div className="bg-surface-hover" style={{ borderRadius: 10, padding: '8px 12px' }}>
|
||||
<PlaceRating
|
||||
ratings={place.ratings ?? []}
|
||||
ratingAvg={place.rating_avg}
|
||||
onRate={rating => onRate(place.id, rating)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Telefon */}
|
||||
{(place.phone || googleDetails?.phone) && (
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Search, Plus, X, Upload, ChevronDown, Check, MapPin } from 'lucide-react'
|
||||
import { Search, Plus, X, Upload, ChevronDown, Check, MapPin, Star } from 'lucide-react'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import Tooltip from '../shared/Tooltip'
|
||||
import type { SidebarState } from './usePlacesSidebar'
|
||||
@@ -25,6 +25,7 @@ export function PlacesHeader(S: SidebarState) {
|
||||
places, categories, categoryFilters, search, setSearch, plannedIds, hasTracks,
|
||||
filter, setFilter, setSelectedIds, selectMode, setSelectMode,
|
||||
catDropOpen, setCatDropOpen, toggleCategoryFilter, setCategoryFilters,
|
||||
ratingSort, setRatingSort,
|
||||
} = S
|
||||
return (
|
||||
<div className="border-b border-edge-faint" style={{ padding: '14px 16px 10px', flexShrink: 0 }}>
|
||||
@@ -165,6 +166,25 @@ export function PlacesHeader(S: SidebarState) {
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
|
||||
<ChevronDown size={12} className="text-content-faint" style={{ flexShrink: 0, transform: catDropOpen ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }} />
|
||||
</button>
|
||||
{/* Star sort (#1435): order the list by average rating, best first. */}
|
||||
<Tooltip label={t('places.sortByRating')} placement="bottom">
|
||||
<button
|
||||
onClick={() => setRatingSort(v => !v)}
|
||||
aria-label={t('places.sortByRating')}
|
||||
aria-pressed={ratingSort}
|
||||
className={ratingSort ? 'text-accent' : 'text-content-faint'}
|
||||
style={{
|
||||
width: 30, flexShrink: 0, borderRadius: 8,
|
||||
border: `1px solid ${ratingSort ? 'var(--accent)' : 'var(--border-primary)'}`,
|
||||
background: ratingSort ? 'color-mix(in srgb, var(--accent) 14%, transparent)' : 'var(--bg-card)',
|
||||
cursor: 'pointer', fontFamily: 'inherit', padding: 0,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
transition: 'background 0.18s, color 0.18s, border-color 0.18s',
|
||||
}}
|
||||
>
|
||||
<Star size={13} strokeWidth={2.2} fill={ratingSort ? 'currentColor' : 'none'} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{canEditPlaces && (
|
||||
<Tooltip label={t('common.select')} placement="bottom">
|
||||
<button
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react'
|
||||
import { Plus, Check, Route } from 'lucide-react'
|
||||
import { Plus, Check, Route, Star } from 'lucide-react'
|
||||
import PlaceAvatar from '../shared/PlaceAvatar'
|
||||
import { getCategoryIcon } from '../shared/categoryIcons'
|
||||
import type { Place, Category } from '../../types'
|
||||
@@ -89,6 +89,13 @@ export const MemoPlaceRow = React.memo(function MemoPlaceRow({
|
||||
<span className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.2 }}>
|
||||
{place.name}
|
||||
</span>
|
||||
{/* Average member rating (#1435). */}
|
||||
{(place.rating_count ?? 0) > 0 && place.rating_avg != null && (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, flexShrink: 0, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-secondary)', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<Star size={9} color="#facc15" fill="#facc15" />
|
||||
{(Math.round(place.rating_avg * 10) / 10).toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(place.description || place.address || cat?.name) && (
|
||||
<div style={{ marginTop: 2 }}>
|
||||
|
||||
@@ -155,6 +155,8 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
const categoryFilters = useTripStore((s) => s.placesCategoryFilter)
|
||||
const setCategoryFilters = useTripStore((s) => s.setPlacesCategoryFilter)
|
||||
const [selectMode, setSelectMode] = useState(false)
|
||||
// Star sort (#1435): list-only toggle, so it stays local (the map keeps its order).
|
||||
const [ratingSort, setRatingSort] = useState(false)
|
||||
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
|
||||
const [pendingDeleteIds, setPendingDeleteIds] = useState<number[] | null>(null)
|
||||
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
|
||||
@@ -196,18 +198,26 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
Object.values(assignments).flatMap(da => da.map(a => a.place?.id).filter(Boolean))
|
||||
), [assignments])
|
||||
|
||||
const filtered = useMemo(() => places.filter(p => {
|
||||
if (filter === 'unplanned' && plannedIds.has(p.id)) return false
|
||||
if (filter === 'tracks' && !p.route_geometry) return false
|
||||
if (categoryFilters.size > 0) {
|
||||
if (p.category_id == null) {
|
||||
if (!categoryFilters.has('uncategorized')) return false
|
||||
} else if (!categoryFilters.has(String(p.category_id))) return false
|
||||
const filtered = useMemo(() => {
|
||||
const list = places.filter(p => {
|
||||
if (filter === 'unplanned' && plannedIds.has(p.id)) return false
|
||||
if (filter === 'tracks' && !p.route_geometry) return false
|
||||
if (categoryFilters.size > 0) {
|
||||
if (p.category_id == null) {
|
||||
if (!categoryFilters.has('uncategorized')) return false
|
||||
} else if (!categoryFilters.has(String(p.category_id))) return false
|
||||
}
|
||||
if (search && !p.name.toLowerCase().includes(search.toLowerCase()) &&
|
||||
!(p.address || '').toLowerCase().includes(search.toLowerCase())) return false
|
||||
return true
|
||||
})
|
||||
// Star sort (#1435): highest average first, unrated places at the end;
|
||||
// ties keep the list's original order (stable sort).
|
||||
if (ratingSort) {
|
||||
return [...list].sort((a, b) => (b.rating_avg ?? -1) - (a.rating_avg ?? -1))
|
||||
}
|
||||
if (search && !p.name.toLowerCase().includes(search.toLowerCase()) &&
|
||||
!(p.address || '').toLowerCase().includes(search.toLowerCase())) return false
|
||||
return true
|
||||
}), [places, filter, categoryFilters, search, plannedIds])
|
||||
return list
|
||||
}, [places, filter, categoryFilters, search, plannedIds, ratingSort])
|
||||
|
||||
const registerPlaceRow = useCallback((placeId: number, element: HTMLDivElement | null) => {
|
||||
if (element) {
|
||||
@@ -267,6 +277,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
listImportEnrich, setListImportEnrich, canEnrichImport,
|
||||
availableListImportProviders, hasMultipleListImportProviders, handleListImport,
|
||||
search, setSearch, filter, setFilter, categoryFilters, setCategoryFilters,
|
||||
ratingSort, setRatingSort,
|
||||
selectMode, setSelectMode, selectedIds, setSelectedIds, pendingDeleteIds, setPendingDeleteIds,
|
||||
categoryPickerOpen, setCategoryPickerOpen,
|
||||
saveToListOpen, setSaveToListOpen, collectionsEnabled, tripId,
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import React, { useState } from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import { Star } from 'lucide-react'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import type { PlaceRatingVote } from '@trek/shared'
|
||||
|
||||
const STAR_FILL = '#facc15'
|
||||
|
||||
interface StarsProps {
|
||||
/** Value the stars visualize (average for display, own vote while hovering). */
|
||||
value: number
|
||||
size?: number
|
||||
/** Interactive mode: hover previews, click casts/clears the own vote. */
|
||||
onRate?: (rating: number | null) => void
|
||||
myRating?: number | null
|
||||
ariaLabel?: string
|
||||
}
|
||||
|
||||
/** Five stars with fractional fill; interactive when onRate is set (#1435).
|
||||
* Clicking the star matching the own vote clears it. */
|
||||
export function Stars({ value, size = 15, onRate, myRating = null, ariaLabel }: StarsProps) {
|
||||
const [hover, setHover] = useState<number | null>(null)
|
||||
const shown = hover ?? value
|
||||
|
||||
return (
|
||||
<div
|
||||
role={onRate ? 'radiogroup' : undefined}
|
||||
aria-label={ariaLabel}
|
||||
style={{ display: 'inline-flex', gap: 2, cursor: onRate ? 'pointer' : 'default' }}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
>
|
||||
{[1, 2, 3, 4, 5].map(i => {
|
||||
// Fractional fill for averages: full below, empty above, clipped between.
|
||||
const fill = Math.max(0, Math.min(1, shown - (i - 1)))
|
||||
const star = (
|
||||
<span key={i} style={{ position: 'relative', display: 'inline-flex', width: size, height: size }}>
|
||||
<Star size={size} color={STAR_FILL} fill="none" style={{ position: 'absolute', inset: 0 }} />
|
||||
{fill > 0 && (
|
||||
<span style={{ position: 'absolute', inset: 0, width: `${fill * 100}%`, overflow: 'hidden' }}>
|
||||
<Star size={size} color={STAR_FILL} fill={STAR_FILL} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
if (!onRate) return star
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={myRating === i}
|
||||
aria-label={`${i}`}
|
||||
onMouseEnter={() => setHover(i)}
|
||||
onFocus={() => setHover(i)}
|
||||
onBlur={() => setHover(null)}
|
||||
onClick={() => onRate(myRating === i ? null : i)}
|
||||
style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'inline-flex' }}
|
||||
>
|
||||
{star}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface PlaceRatingProps {
|
||||
ratings: PlaceRatingVote[]
|
||||
ratingAvg: number | null | undefined
|
||||
onRate?: (rating: number | null) => void
|
||||
size?: number
|
||||
/** Hide the voter avatar strip (compact mobile rows). */
|
||||
compact?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The collaborative rating row (#1435): interactive stars (hover previews the
|
||||
* own vote, the average fill shows otherwise), the numeric average, and the
|
||||
* voter avatars. Hovering reveals a custom tooltip listing every voter with
|
||||
* their stars.
|
||||
*/
|
||||
export default function PlaceRating({ ratings, ratingAvg, onRate, size = 16, compact = false }: PlaceRatingProps) {
|
||||
const { t } = useTranslation()
|
||||
const currentUserId = useAuthStore(s => s.user?.id)
|
||||
const [tip, setTip] = useState<{ top: number; left: number } | null>(null)
|
||||
const myRating = ratings.find(r => r.user_id === currentUserId)?.rating ?? null
|
||||
const avg = ratingAvg ?? null
|
||||
|
||||
const showTip = (e: React.MouseEvent) => {
|
||||
if (ratings.length === 0) return
|
||||
const r = e.currentTarget.getBoundingClientRect()
|
||||
setTip({ top: r.top, left: r.left + r.width / 2 })
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, minHeight: size + 4 }}
|
||||
onMouseEnter={showTip}
|
||||
onMouseLeave={() => setTip(null)}
|
||||
>
|
||||
<Stars value={avg ?? 0} size={size} onRate={onRate} myRating={myRating} ariaLabel={t('places.yourRating')} />
|
||||
{avg !== null ? (
|
||||
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', fontVariantNumeric: 'tabular-nums' }}>
|
||||
{(Math.round(avg * 10) / 10).toLocaleString()} <span style={{ fontWeight: 400, color: 'var(--text-faint)' }}>({ratings.length})</span>
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{t('places.notRated')}</span>
|
||||
)}
|
||||
|
||||
{/* Who voted — avatar strip. */}
|
||||
{!compact && ratings.length > 0 && (
|
||||
<span style={{ display: 'inline-flex', marginLeft: 'auto' }}>
|
||||
{ratings.slice(0, 6).map((r, i) => (
|
||||
<span key={r.user_id} className="bg-surface-tertiary text-content-muted" style={{
|
||||
width: 18, height: 18, borderRadius: '50%', overflow: 'hidden', flexShrink: 0,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: 'calc(8px * var(--fs-scale-caption, 1))', fontWeight: 700,
|
||||
marginLeft: i ? -5 : 0, border: '1.5px solid var(--bg-elevated, #fff)',
|
||||
}}>
|
||||
{r.avatar ? <img src={avatarSrc(r.avatar)!} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : r.username?.[0]?.toUpperCase()}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Custom voter tooltip — fixed at the root so nothing clips it. */}
|
||||
{tip && ratings.length > 0 && ReactDOM.createPortal(
|
||||
<div
|
||||
role="tooltip"
|
||||
className="bg-surface-card text-content border border-edge-faint"
|
||||
style={{
|
||||
position: 'fixed', top: tip.top - 8, left: tip.left, transform: 'translate(-50%, -100%)',
|
||||
zIndex: 100000, pointerEvents: 'none', borderRadius: 10, padding: '8px 11px', minWidth: 140,
|
||||
boxShadow: '0 4px 16px rgba(0,0,0,0.15)', fontFamily: 'var(--font-system)',
|
||||
}}
|
||||
>
|
||||
{ratings.map(r => (
|
||||
<div key={r.user_id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '2px 0' }}>
|
||||
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.username}{r.user_id === currentUserId ? ` (${t('vacay.you')})` : ''}
|
||||
</span>
|
||||
<Stars value={r.rating} size={11} />
|
||||
</div>
|
||||
))}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { normalizeImageFile } from '../../../utils/convertHeic'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import { normalizeLinkUrl, STATUS_ORDER } from '../../../pages/collections/collectionsModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import PlaceRating from '../../../components/shared/StarRating'
|
||||
import MCollCategoryPicker from './MCollCategoryPicker'
|
||||
import MCollLinksEditor from './MCollLinksEditor'
|
||||
import { STATUS_SPEC } from './collectionsMobileModel'
|
||||
@@ -38,6 +39,8 @@ interface MCollPlaceSheetProps {
|
||||
onUploadImage?: (file: File) => Promise<void>
|
||||
onCopyToTrip: () => void
|
||||
onRemove: () => void
|
||||
/** Cast/clear the current user's star vote (#1435); every member may vote. */
|
||||
onRate?: (rating: number | null) => Promise<void> | void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
@@ -48,7 +51,7 @@ interface MCollPlaceSheetProps {
|
||||
* description / links.
|
||||
*/
|
||||
export default function MCollPlaceSheet({
|
||||
place, canEdit, canDelete, categories, labels, onClose, onSetStatus, onSave, onUploadImage, onCopyToTrip, onRemove, t,
|
||||
place, canEdit, canDelete, categories, labels, onClose, onSetStatus, onSave, onUploadImage, onCopyToTrip, onRemove, onRate, t,
|
||||
}: MCollPlaceSheetProps) {
|
||||
const toast = useToast()
|
||||
const imageInputRef = useRef<HTMLInputElement | null>(null)
|
||||
@@ -231,6 +234,13 @@ export default function MCollPlaceSheet({
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Collaborative rating (#1435) — tap a star to cast/clear your vote. */}
|
||||
{onRate && (
|
||||
<div className="mt-3">
|
||||
<PlaceRating ratings={held.ratings ?? []} ratingAvg={held.rating_avg} onRate={onRate} size={18} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing ? (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('common.name').toUpperCase()}</Eyebrow>
|
||||
|
||||
@@ -84,13 +84,14 @@ export default function MCollections() {
|
||||
setLabelDrop(false)
|
||||
}, [c.activeId])
|
||||
|
||||
// The mobile toolbar has no category filter control, but the shared hook
|
||||
// still applies one set on desktop — keep it cleared so resizing to phone
|
||||
// doesn't silently filter the list and map.
|
||||
const { categoryFilter, setCategoryFilter } = c
|
||||
// The mobile toolbar has no category or rating filter control, but the shared
|
||||
// hook still applies whatever was set on desktop — keep both cleared so
|
||||
// resizing to phone doesn't silently filter the list and map (#1435).
|
||||
const { categoryFilter, setCategoryFilter, ratingFilter, setRatingFilter } = c
|
||||
useEffect(() => {
|
||||
if (categoryFilter !== 'all') setCategoryFilter('all')
|
||||
}, [categoryFilter, setCategoryFilter])
|
||||
if (ratingFilter !== 'all') setRatingFilter('all')
|
||||
}, [categoryFilter, setCategoryFilter, ratingFilter, setRatingFilter])
|
||||
|
||||
const title = c.isAllSaved ? t('collections.allSaved') : (c.activeCollection?.name ?? t('collections.title'))
|
||||
const isRealList = !c.isAllSaved && typeof c.activeId === 'number'
|
||||
@@ -456,6 +457,7 @@ export default function MCollections() {
|
||||
onUploadImage={file => c.uploadPlaceImage(c.selectedPlace!.id, file)}
|
||||
onCopyToTrip={c.openCopyForSelectedPlace}
|
||||
onRemove={c.handleDetailRemove}
|
||||
onRate={r => c.handleRatePlace(c.selectedPlace!.id, r)}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useSaveToCollectionStore } from '../../../../store/saveToCollectionStore'
|
||||
import { collectionTargetFromPlace } from '../lib/collectionTarget'
|
||||
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
|
||||
import PlaceRating from '../../../../components/shared/StarRating'
|
||||
import { avatarSrc } from '../../../../utils/avatarSrc'
|
||||
import { openFile } from '../../../../utils/fileDownload'
|
||||
import { getGoogleMapsUrlForPlace } from '../../../../components/Planner/placeGoogleMaps'
|
||||
@@ -168,6 +169,16 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
openSavePicker(collectionTargetFromPlace(place))
|
||||
}
|
||||
|
||||
// Collaborative rating (#1435): every trip member casts their own star vote.
|
||||
const handleRate = async (rating: number | null) => {
|
||||
if (!place) return
|
||||
try {
|
||||
await planner.tripActions.ratePlace(planner.tripId, place.id, rating)
|
||||
} catch (err: unknown) {
|
||||
planner.toast.error(err instanceof Error ? err.message : t('common.unknownError'))
|
||||
}
|
||||
}
|
||||
|
||||
const showOnMap = () => {
|
||||
close()
|
||||
if (shell.trTab !== 'plan') shell.setTrTab('plan')
|
||||
@@ -259,6 +270,11 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* Collaborative rating (#1435) — tap a star to cast/clear your vote. */}
|
||||
<div className={`mt-[10px] rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
|
||||
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={handleRate} size={18} />
|
||||
</div>
|
||||
|
||||
{place.description && (
|
||||
<div className={`mt-[10px] rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
|
||||
<div className="font-geist text-[0.75rem] leading-[1.5] text-m-muted">{place.description}</div>
|
||||
|
||||
@@ -102,8 +102,10 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
counts={c.counts}
|
||||
categoryFilter={c.categoryFilter}
|
||||
categoryOptions={c.categoryOptions}
|
||||
ratingFilter={c.ratingFilter}
|
||||
onStatusFilter={c.setStatusFilter}
|
||||
onCategoryFilter={c.setCategoryFilter}
|
||||
onRatingFilter={c.setRatingFilter}
|
||||
showLabels={isRealList}
|
||||
labelOptions={c.labelOptions}
|
||||
labelFilter={c.labelFilter}
|
||||
@@ -298,6 +300,7 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
onUploadImage={file => c.uploadPlaceImage(c.selectedPlace!.id, file)}
|
||||
onCopyToTrip={c.openCopyForSelectedPlace}
|
||||
onRemove={c.handleDetailRemove}
|
||||
onRate={r => c.handleRatePlace(c.selectedPlace!.id, r)}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -573,6 +573,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
}}
|
||||
onUpdatePlace={async (placeId, data) => { try { await tripActions.updatePlace(tripId, placeId, data) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
onUploadImage={async (placeId, file) => { await tripActions.uploadPlaceImage(tripId, placeId, file) }}
|
||||
onRate={async (placeId, rating) => { try { await tripActions.ratePlace(tripId, placeId, rating) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
leftWidth={(isMobile || window.innerWidth < 900) ? 0 : (leftCollapsed ? 0 : leftWidth)}
|
||||
rightWidth={(isMobile || window.innerWidth < 900) ? 0 : (rightCollapsed ? 0 : rightWidth)}
|
||||
/>
|
||||
@@ -612,6 +613,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
}}
|
||||
onUpdatePlace={async (placeId, data) => { try { await tripActions.updatePlace(tripId, placeId, data) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
onUploadImage={async (placeId, file) => { await tripActions.uploadPlaceImage(tripId, placeId, file) }}
|
||||
onRate={async (placeId, rating) => { try { await tripActions.ratePlace(tripId, placeId, rating) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } }}
|
||||
leftWidth={0}
|
||||
rightWidth={0}
|
||||
/>
|
||||
|
||||
@@ -35,6 +35,7 @@ interface PlaceLike {
|
||||
sort_order?: number;
|
||||
created_at?: string;
|
||||
label_ids?: number[];
|
||||
rating_avg?: number | null;
|
||||
}
|
||||
function cp(overrides: PlaceLike): CollectionPlace {
|
||||
return {
|
||||
@@ -80,6 +81,25 @@ describe('collectionsModel', () => {
|
||||
expect(out.map(p => p.id)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
it('FE-COLLECTIONS-MODEL-036: rating filter keeps places whose average is >= the floor (#1435)', () => {
|
||||
const places = [
|
||||
cp({ id: 1, name: 'A', status: 'idea', rating_avg: 4.5 }),
|
||||
cp({ id: 2, name: 'B', status: 'idea', rating_avg: 3 }),
|
||||
cp({ id: 3, name: 'C', status: 'idea', rating_avg: null }), // unrated → excluded by a floor
|
||||
cp({ id: 4, name: 'D', status: 'idea' }), // unrated (undefined) → excluded
|
||||
];
|
||||
const out = filterPlaces(places, 'all', '', 'all', [], 4);
|
||||
expect(out.map(p => p.id)).toEqual([1]);
|
||||
});
|
||||
|
||||
it("FE-COLLECTIONS-MODEL-037: rating filter 'all' keeps unrated places too", () => {
|
||||
const places = [
|
||||
cp({ id: 1, name: 'A', status: 'idea', rating_avg: 5 }),
|
||||
cp({ id: 2, name: 'B', status: 'idea', rating_avg: null }),
|
||||
];
|
||||
expect(filterPlaces(places, 'all', '', 'all', [], 'all')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-COLLECTIONS-MODEL-004: search matches place name (case-insensitive)', () => {
|
||||
const places = [
|
||||
cp({ id: 1, name: 'Eiffel Tower', status: 'idea' }),
|
||||
|
||||
@@ -54,12 +54,15 @@ export function filterPlaces(
|
||||
search: string,
|
||||
categoryFilter: number | 'all' = 'all',
|
||||
labelFilter: number[] = [],
|
||||
ratingFilter: number | 'all' = 'all',
|
||||
): CollectionPlace[] {
|
||||
const q = search.trim().toLowerCase()
|
||||
return places.filter(p => {
|
||||
if (!p) return false
|
||||
if (statusFilter !== 'all' && p.status !== statusFilter) return false
|
||||
if (categoryFilter !== 'all' && (p.category_id ?? null) !== categoryFilter) return false
|
||||
// Minimum-average-stars filter (#1435): unrated places drop out once a floor is set.
|
||||
if (ratingFilter !== 'all' && (p.rating_avg == null || p.rating_avg < ratingFilter)) return false
|
||||
if (labelFilter.length && !labelFilter.some(id => (p.label_ids ?? []).includes(id))) return false
|
||||
if (!q) return true
|
||||
return (
|
||||
|
||||
@@ -50,15 +50,15 @@ export function useCollections() {
|
||||
const store = useCollectionStore()
|
||||
const {
|
||||
collections, activeId, places, members, labels, incomingInvites,
|
||||
view, statusFilter, categoryFilter, labelFilter, search, selectedPlaceId, selectMode, selectedIds,
|
||||
view, statusFilter, categoryFilter, ratingFilter, labelFilter, search, selectedPlaceId, selectMode, selectedIds,
|
||||
loading, placesLoading,
|
||||
loadAll, setActive, refreshActive, loadCollection,
|
||||
deleteCollection,
|
||||
setStatus, updatePlace, uploadPlaceImage, deletePlace, deleteMany, copyToTrip, clearSelection,
|
||||
setStatus, updatePlace, uploadPlaceImage, ratePlace, deletePlace, deleteMany, copyToTrip, clearSelection,
|
||||
moveToList, duplicateToList, setSelectedIds,
|
||||
createLabel, updateLabel, deleteLabel, assignLabels,
|
||||
acceptInvite, declineInvite,
|
||||
setView, setStatusFilter, setCategoryFilter, setLabelFilter, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
||||
setView, setStatusFilter, setCategoryFilter, setRatingFilter, setLabelFilter, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
||||
} = store
|
||||
|
||||
// ── Page-local UI state ─────────────────────────────────────────────
|
||||
@@ -167,8 +167,8 @@ export function useCollections() {
|
||||
|
||||
// Labels are per-collection, so never apply them on the "All saved" union.
|
||||
const visiblePlaces = useMemo(
|
||||
() => sortPlaces(filterPlaces(places, statusFilter, search, categoryFilter, isAllSaved ? [] : labelFilter)),
|
||||
[places, statusFilter, search, categoryFilter, isAllSaved, labelFilter],
|
||||
() => sortPlaces(filterPlaces(places, statusFilter, search, categoryFilter, isAllSaved ? [] : labelFilter, ratingFilter)),
|
||||
[places, statusFilter, search, categoryFilter, isAllSaved, labelFilter, ratingFilter],
|
||||
)
|
||||
// Categories actually present in this list, for the category filter dropdown.
|
||||
const categoryOptions = useMemo(() => presentCategories(places), [places])
|
||||
@@ -221,6 +221,14 @@ export function useCollections() {
|
||||
}
|
||||
}, [deletePlace, toast, t])
|
||||
|
||||
const handleRatePlace = useCallback(async (placeId: number, rating: number | null) => {
|
||||
try {
|
||||
await ratePlace(placeId, rating)
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
}, [ratePlace, toast, t])
|
||||
|
||||
const handleDeleteSelected = useCallback(async () => {
|
||||
if (selectedIds.length === 0) return
|
||||
try {
|
||||
@@ -378,11 +386,11 @@ export function useCollections() {
|
||||
myRole, canEdit, canDelete,
|
||||
canShare, shareMemberCount,
|
||||
activeId, places, visiblePlaces, mappable, members, incomingInvites, counts,
|
||||
view, statusFilter, categoryFilter, categoryOptions, search, selectedPlaceId, selectMode, selectedIds,
|
||||
view, statusFilter, categoryFilter, categoryOptions, ratingFilter, search, selectedPlaceId, selectMode, selectedIds,
|
||||
labels, labelFilter, labelOptions,
|
||||
loading, placesLoading,
|
||||
// store setters
|
||||
setView, setStatusFilter, setCategoryFilter, setLabelFilter, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
||||
setView, setStatusFilter, setCategoryFilter, setRatingFilter, setLabelFilter, setSearch, setSelectedPlaceId, setSelectMode, toggleSelect,
|
||||
updatePlace, uploadPlaceImage,
|
||||
// labels
|
||||
showLabelManager, setShowLabelManager, labelPickerOpen, setLabelPickerOpen,
|
||||
@@ -399,7 +407,7 @@ export function useCollections() {
|
||||
copyIds, openCopyForSelectedPlace, openCopyForSelection, closeCopy, handleCopyToTrip,
|
||||
// handlers
|
||||
handleSelectList, handleDeleteList,
|
||||
handleStatusChange, handleDeletePlace, handleDeleteSelected,
|
||||
handleStatusChange, handleRatePlace, handleDeletePlace, handleDeleteSelected,
|
||||
handleAcceptInvite, handleDeclineInvite,
|
||||
allVisibleSelected, handleSelectAll,
|
||||
listPickerMode, setListPickerMode, handleMoveToList, handleDuplicateToList,
|
||||
|
||||
@@ -34,6 +34,7 @@ interface CollectionState {
|
||||
view: CollectionView
|
||||
statusFilter: StatusFilter
|
||||
categoryFilter: number | 'all'
|
||||
ratingFilter: number | 'all'
|
||||
labelFilter: number[]
|
||||
search: string
|
||||
selectedPlaceId: number | null
|
||||
@@ -56,6 +57,7 @@ interface CollectionState {
|
||||
setStatus: (placeId: number, status: CollectionStatus) => Promise<void>
|
||||
updatePlace: (placeId: number, body: CollectionPlaceUpdateRequest) => Promise<void>
|
||||
uploadPlaceImage: (placeId: number, file: File) => Promise<void>
|
||||
ratePlace: (placeId: number, rating: number | null) => Promise<void>
|
||||
deletePlace: (placeId: number) => Promise<void>
|
||||
deleteMany: (ids: number[]) => Promise<void>
|
||||
copyToTrip: (tripId: number, placeIds: number[], force?: boolean) => Promise<{ copied: number; skipped: { id: number; name: string }[] }>
|
||||
@@ -78,6 +80,7 @@ interface CollectionState {
|
||||
setView: (view: CollectionView) => void
|
||||
setStatusFilter: (filter: StatusFilter) => void
|
||||
setCategoryFilter: (filter: number | 'all') => void
|
||||
setRatingFilter: (filter: number | 'all') => void
|
||||
setLabelFilter: (labelIds: number[]) => void
|
||||
setSearch: (search: string) => void
|
||||
setSelectedPlaceId: (id: number | null) => void
|
||||
@@ -97,6 +100,7 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
|
||||
view: 'list',
|
||||
statusFilter: 'all',
|
||||
categoryFilter: 'all',
|
||||
ratingFilter: 'all',
|
||||
labelFilter: [],
|
||||
search: '',
|
||||
selectedPlaceId: null,
|
||||
@@ -238,6 +242,11 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
|
||||
if (updated) set({ places: get().places.map(p => (p.id === placeId ? updated : p)) })
|
||||
},
|
||||
|
||||
ratePlace: async (placeId: number, rating: number | null) => {
|
||||
const updated = await collectionsApi.ratePlace(placeId, rating)
|
||||
if (updated) set({ places: get().places.map(p => (p.id === placeId ? updated : p)) })
|
||||
},
|
||||
|
||||
deletePlace: async (placeId: number) => {
|
||||
set({ places: get().places.filter(p => p.id !== placeId) })
|
||||
await collectionsApi.deletePlace(placeId)
|
||||
@@ -383,6 +392,7 @@ export const useCollectionStore = create<CollectionState>((set, get) => ({
|
||||
setView: (view: CollectionView) => set({ view }),
|
||||
setStatusFilter: (filter: StatusFilter) => set({ statusFilter: filter }),
|
||||
setCategoryFilter: (filter: number | 'all') => set({ categoryFilter: filter }),
|
||||
setRatingFilter: (filter: number | 'all') => set({ ratingFilter: filter }),
|
||||
setLabelFilter: (labelIds: number[]) => set({ labelFilter: labelIds }),
|
||||
setSearch: (search: string) => set({ search }),
|
||||
setSelectedPlaceId: (id: number | null) => set({ selectedPlaceId: id }),
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface PlacesSlice {
|
||||
addPlace: (tripId: number | string, placeData: Partial<Place> & { name: string }) => Promise<Place>
|
||||
updatePlace: (tripId: number | string, placeId: number, placeData: Partial<Place>) => Promise<Place>
|
||||
uploadPlaceImage: (tripId: number | string, placeId: number, file: File) => Promise<Place>
|
||||
ratePlace: (tripId: number | string, placeId: number, rating: number | null) => Promise<Place>
|
||||
deletePlace: (tripId: number | string, placeId: number) => Promise<void>
|
||||
deletePlacesMany: (tripId: number | string, placeIds: number[]) => Promise<void>
|
||||
updatePlacesMany: (tripId: number | string, placeIds: number[], patch: Partial<Place>) => Promise<void>
|
||||
@@ -81,6 +82,18 @@ export const createPlacesSlice = (set: SetState, get: GetState): PlacesSlice =>
|
||||
}
|
||||
},
|
||||
|
||||
ratePlace: async (tripId, placeId, rating) => {
|
||||
// Casts (or clears, rating null) the current user's own star vote (#1435)
|
||||
// and applies the returned place with the fresh average.
|
||||
try {
|
||||
const data = await placesApi.rate(tripId, placeId, rating)
|
||||
applyUpdatedPlace(set, placeId, data.place)
|
||||
return data.place
|
||||
} catch (err: unknown) {
|
||||
throw new Error(getApiErrorMessage(err, 'Error rating place'))
|
||||
}
|
||||
},
|
||||
|
||||
deletePlace: async (tripId, placeId) => {
|
||||
try {
|
||||
await placeRepo.delete(tripId, placeId)
|
||||
|
||||
Reference in New Issue
Block a user