精简后的项目:仅保留 api/ui 源码、文档、构建依赖

This commit is contained in:
gallery
2026-09-11 16:11:09 +08:00
commit 490e85634e
457 changed files with 86862 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
import React from 'react'
import Loader from '../primitives/Loader'
type PaginateLoaderProps = {
active: boolean
text: string
}
const PaginateLoader = ({ active, text }: PaginateLoaderProps) => (
<Loader
active
message={text}
className={active ? 'opacity-100' : 'opacity-0'}
/>
)
export default PaginateLoader
+32
View File
@@ -0,0 +1,32 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: albumPathQuery
// ====================================================
export interface albumPathQuery_album_path {
__typename: 'Album'
id: string
title: string
}
export interface albumPathQuery_album {
__typename: 'Album'
id: string
path: albumPathQuery_album_path[]
}
export interface albumPathQuery {
/**
* Get album by id, user must own the album or be admin
* If valid tokenCredentials are provided, the album may be retrived without further authentication
*/
album: albumPathQuery_album
}
export interface albumPathQueryVariables {
id: string
}
+165
View File
@@ -0,0 +1,165 @@
import React from 'react'
import { authToken } from '../../helpers/authentication'
import { useTranslation } from 'react-i18next'
import { OrderDirection } from '../../__generated__/globalTypes'
import { MediaOrdering, SetOrderingFn } from '../../hooks/useOrderingParams'
import Checkbox from '../../primitives/form/Checkbox'
import { ReactComponent as SortingIcon } from './icons/sorting.svg'
import { ReactComponent as DirectionIcon } from './icons/direction-arrow.svg'
import Dropdown from '../../primitives/form/Dropdown'
import classNames from 'classnames'
export type SortingOptionValue = 'date_shot' | 'updated_at' | 'title' | 'type'
export type SortingOption = { value: SortingOptionValue; label: string }
export type FavoriteCheckboxProps = {
onlyFavorites: boolean
setOnlyFavorites(favorites: boolean): void
}
export const FavoritesCheckbox = ({
onlyFavorites,
setOnlyFavorites,
}: FavoriteCheckboxProps) => {
const { t } = useTranslation()
return (
<Checkbox
className="mb-1"
label={t('album_filter.only_favorites', 'Show only favorites')}
checked={onlyFavorites}
onChange={e => setOnlyFavorites(e.target.checked)}
/>
)
}
type SortingOptionsProps = {
ordering?: MediaOrdering
setOrdering?: SetOrderingFn
items?: SortingOption[]
}
const SortingOptions = ({
setOrdering,
ordering,
items,
}: SortingOptionsProps) => {
const { t } = useTranslation()
const changeOrderDirection = () => {
if (setOrdering && ordering) {
setOrdering({
orderDirection:
ordering.orderDirection === OrderDirection.ASC
? OrderDirection.DESC
: OrderDirection.ASC,
})
}
}
const changeOrderBy = (value: SortingOptionValue) => {
if (setOrdering) {
setOrdering({ orderBy: value })
}
}
const defaultOptions = React.useMemo(
() => [
{
value: 'date_shot',
label: t('album_filter.sorting_options.date_shot', 'Date shot'),
},
{
value: 'updated_at',
label: t('album_filter.sorting_options.date_imported', 'Date imported'),
},
{
value: 'title',
label: t('album_filter.sorting_options.title', 'Title'),
},
{
value: 'type',
label: t('album_filter.sorting_options.type', 'Kind'),
},
],
[t]
)
const sortingOptions = items ?? defaultOptions
return (
<fieldset>
<legend id="filter_group_sort-label" className="inline-block mb-1">
<SortingIcon
className="inline-block align-baseline mr-1 mt-1"
aria-hidden="true"
/>
<span>{t('album_filter.sort', 'Sort')}</span>
</legend>
<div>
<Dropdown
aria-labelledby="filter_group_sort-label"
setSelected={changeOrderBy}
value={ordering?.orderBy || undefined}
items={sortingOptions}
/>
<button
title={t('album_filter.sort_direction', 'Sort direction')}
aria-label={t('album_filter.sort_direction', 'Sort direction')}
aria-pressed={ordering?.orderDirection === OrderDirection.DESC}
className={classNames(
'bg-gray-50 h-[30px] align-top px-2 py-1 rounded ml-2 border border-gray-200 focus:outline-none focus:border-blue-300 text-[#8b8b8b] hover:bg-gray-100 hover:text-[#777]',
'dark:bg-dark-input-bg dark:border-dark-input-border dark:text-dark-input-text dark:focus:border-blue-300',
{ 'flip-y': ordering?.orderDirection === OrderDirection.ASC }
)}
onClick={changeOrderDirection}
>
<DirectionIcon />
<span className="sr-only">
{ordering?.orderDirection === OrderDirection.ASC
? t('album_filter.order_direction.ascending', 'Ascending')
: t('album_filter.order_direction.descending', 'Descending')}
</span>
</button>
</div>
</fieldset>
)
}
type AlbumFilterProps = {
onlyFavorites: boolean
setOnlyFavorites?(favorites: boolean): void
ordering?: MediaOrdering
setOrdering?: SetOrderingFn
sortingOptions?: SortingOption[]
}
const AlbumFilter = ({
onlyFavorites,
setOnlyFavorites,
setOrdering,
ordering,
sortingOptions,
}: AlbumFilterProps) => {
return (
<div className="flex items-end gap-4 flex-wrap mb-4">
{ordering && setOrdering ? (
<SortingOptions
ordering={ordering}
setOrdering={setOrdering}
items={sortingOptions}
/>
) : null}
{authToken() && setOnlyFavorites && (
<FavoritesCheckbox
onlyFavorites={onlyFavorites}
setOnlyFavorites={setOnlyFavorites}
/>
)}
</div>
)
}
export default AlbumFilter
+122
View File
@@ -0,0 +1,122 @@
import React, { useEffect, useContext } from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { SidebarContext } from '../sidebar/Sidebar'
import AlbumSidebar from '../sidebar/AlbumSidebar'
import { useLazyQuery, gql } from '@apollo/client'
import { authToken } from '../../helpers/authentication'
import { albumPathQuery } from './__generated__/albumPathQuery'
import useDelay from '../../hooks/useDelay'
import { ReactComponent as GearIcon } from './icons/gear.svg'
import { tailwindClassNames } from '../../helpers/utils'
import { buttonStyles } from '../../primitives/form/Input'
export const BreadcrumbList = styled.ol<{ hideLastArrow?: boolean }>`
&
${({ hideLastArrow }) =>
hideLastArrow ? 'li:not(:last-child)::after' : 'li::after'} {
content: '';
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='5px' height='6px' viewBox='0 0 5 6'%3E%3Cpolyline fill='none' stroke='%23979797' points='0.74 0.167710644 3.57228936 3 0.74 5.83228936' /%3E%3C/svg%3E");
width: 5px;
height: 6px;
display: inline-block;
margin: 6px;
vertical-align: middle;
}
`
const ALBUM_PATH_QUERY = gql`
query albumPathQuery($id: ID!) {
album(id: $id) {
id
path {
id
title
}
}
}
`
type AlbumTitleProps = {
album?: {
id: string
title: string
}
disableLink: boolean
}
const AlbumTitle = ({ album, disableLink = false }: AlbumTitleProps) => {
const [fetchPath, { data: pathData }] =
useLazyQuery<albumPathQuery>(ALBUM_PATH_QUERY)
const { updateSidebar } = useContext(SidebarContext)
useEffect(() => {
if (!album) return
if (authToken() && disableLink == true) {
fetchPath({
variables: {
id: album.id,
},
})
}
}, [album])
const delay = useDelay(200, [album])
if (!album) {
return (
<div
className={`flex mb-6 flex-col h-14 transition-opacity animate-pulse ${
delay ? 'opacity-100' : 'opacity-0'
}`}
>
<div className="w-32 h-4 bg-gray-100 mb-2 mt-1"></div>
<div className="w-72 h-6 bg-gray-100"></div>
</div>
)
}
let title = <span>{album.title}</span>
const path = pathData?.album.path || []
const breadcrumbSections = path
.slice()
.reverse()
.map(x => (
<li key={x.id} className="inline-block hover:underline">
<Link to={`/album/${x.id}`}>{x.title}</Link>
</li>
))
if (!disableLink) {
title = <Link to={`/album/${album.id}`}>{title}</Link>
}
return (
<div className="flex mb-6 items-end h-14">
<div className="min-w-0">
<nav aria-label="Album breadcrumb">
<BreadcrumbList>{breadcrumbSections}</BreadcrumbList>
</nav>
<h1 className="text-2xl truncate min-w-0">{title}</h1>
</div>
{authToken() && (
<button
title="Album options"
aria-label="Album options"
className={tailwindClassNames(buttonStyles({}), 'px-2 py-2 ml-2')}
onClick={() => {
updateSidebar(<AlbumSidebar albumId={album.id} />)
}}
>
<GearIcon />
</button>
)}
</div>
)
}
export default AlbumTitle
+35
View File
@@ -0,0 +1,35 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: albumPathQuery
// ====================================================
export interface albumPathQuery_album_path {
__typename: "Album";
id: string;
title: string;
}
export interface albumPathQuery_album {
__typename: "Album";
id: string;
/**
* A breadcrumb list of all parent albums down to this one
*/
path: albumPathQuery_album_path[];
}
export interface albumPathQuery {
/**
* Get album by id, user must own the album or be admin
* If valid tokenCredentials are provided, the album may be retrived without further authentication
*/
album: albumPathQuery_album;
}
export interface albumPathQueryVariables {
id: string;
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="13px" height="8px" viewBox="0 0 13 8" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<polyline fill="none" stroke="currentColor" stroke-width="1.5" points="1 7 6.5 1 12 7"></polyline>
</svg>

After

Width:  |  Height:  |  Size: 289 B

+7
View File
@@ -0,0 +1,7 @@
<svg
viewBox="0 0 15 15"
width="15px"
height="15px"
fill="currentColor">
<path d="M7.33333333,0 C8.069713,0 8.66666667,0.596953667 8.66666667,1.33333333 L8.66666667,1.39333333 C8.66841527,1.83176195 8.93035293,2.22728781 9.33333333,2.4 C9.74472671,2.5815643 10.2252088,2.49444392 10.5466667,2.18 L10.5866667,2.14 C10.8367577,1.88963061 11.176121,1.74895112 11.53,1.74895112 C11.883879,1.74895112 12.2232423,1.88963061 12.4733333,2.14 C12.7237027,2.39009101 12.8643822,2.72945434 12.8643822,3.08333333 C12.8643822,3.43721233 12.7237027,3.77657566 12.4733333,4.02666667 L12.4333333,4.06666667 C12.1188894,4.38812449 12.031769,4.86860662 12.2133333,5.28 L12.2133333,5.33333333 C12.3860455,5.73631374 12.7815714,5.9982514 13.22,6 L13.3333333,6 C14.069713,6 14.6666667,6.59695367 14.6666667,7.33333333 C14.6666667,8.069713 14.069713,8.66666667 13.3333333,8.66666667 L13.2733333,8.66666667 C12.8349047,8.66841527 12.4393789,8.93035293 12.2666667,9.33333333 C12.0851024,9.74472671 12.1722227,10.2252088 12.4866667,10.5466667 L12.5266667,10.5866667 C12.7770361,10.8367577 12.9177155,11.176121 12.9177155,11.53 C12.9177155,11.883879 12.7770361,12.2232423 12.5266667,12.4733333 C12.2765757,12.7237027 11.9372123,12.8643822 11.5833333,12.8643822 C11.2294543,12.8643822 10.890091,12.7237027 10.64,12.4733333 L10.6,12.4333333 C10.2785422,12.1188894 9.79806005,12.031769 9.38666667,12.2133333 C8.98368626,12.3860455 8.7217486,12.7815714 8.72,13.22 L8.72,13.3333333 C8.72,14.069713 8.12304633,14.6666667 7.38666667,14.6666667 C6.650287,14.6666667 6.05333333,14.069713 6.05333333,13.3333333 L6.05333333,13.2733333 C6.04277107,12.8217805 5.75724785,12.4225768 5.33333333,12.2666667 C4.92193995,12.0851024 4.44145782,12.1722227 4.12,12.4866667 L4.08,12.5266667 C3.82990899,12.7770361 3.49054566,12.9177155 3.13666667,12.9177155 C2.78278767,12.9177155 2.44342434,12.7770361 2.19333333,12.5266667 C1.94296394,12.2765757 1.80228446,11.9372123 1.80228446,11.5833333 C1.80228446,11.2294543 1.94296394,10.890091 2.19333333,10.64 L2.23333333,10.6 C2.54777725,10.2785422 2.63489764,9.79806005 2.45333333,9.38666667 C2.28062114,8.98368626 1.88509528,8.7217486 1.44666667,8.72 L1.33333333,8.72 C0.596953667,8.72 0,8.12304633 0,7.38666667 C0,6.650287 0.596953667,6.05333333 1.33333333,6.05333333 L1.39333333,6.05333333 C1.84488612,6.04277107 2.24408988,5.75724785 2.4,5.33333333 C2.5815643,4.92193995 2.49444392,4.44145782 2.18,4.12 L2.14,4.08 C1.88963061,3.82990899 1.74895112,3.49054566 1.74895112,3.13666667 C1.74895112,2.78278767 1.88963061,2.44342434 2.14,2.19333333 C2.39009101,1.94296394 2.72945434,1.80228446 3.08333333,1.80228446 C3.43721233,1.80228446 3.77657566,1.94296394 4.02666667,2.19333333 L4.06666667,2.23333333 C4.38812449,2.54777725 4.86860662,2.63489764 5.28,2.45333333 L5.33333333,2.45333333 C5.73631374,2.28062114 5.9982514,1.88509528 6,1.44666667 L6,1.33333333 C6,0.596953667 6.59695367,0 7.33333333,0 Z M7.33333333,5.33333333 C6.22876383,5.33333333 5.33333333,6.22876383 5.33333333,7.33333333 C5.33333333,8.43790283 6.22876383,9.33333333 7.33333333,9.33333333 C8.43790283,9.33333333 9.33333333,8.43790283 9.33333333,7.33333333 C9.33333333,6.22876383 8.43790283,5.33333333 7.33333333,5.33333333 Z" />
</svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="15px" height="13px" viewBox="0 0 15 13" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path fill="currentColor" d="M4,3.55271368e-14 L4.0278401,0.000770874105 C4.04128052,0.00151580687 4.05469661,0.00280063794 4.06805308,0.0046253673 L4,3.55271368e-14 C4.04183471,3.55271368e-14 4.08246942,0.00513782494 4.12130755,0.0148169071 C4.13326871,0.0178373169 4.14523456,0.0212920805 4.15708315,0.0252017355 C4.16997104,0.0294299553 4.18277427,0.034259294 4.19531518,0.0395860503 C4.20839103,0.0451160612 4.22150919,0.0513529918 4.23439118,0.0581928845 C4.23503401,0.0585723692 4.23566876,0.058911632 4.23630269,0.0592522225 L4.30644972,0.104852306 L4.30644972,0.104852306 L4.35355339,0.146446609 L7.85355339,3.64644661 C8.04881554,3.84170876 8.04881554,4.15829124 7.85355339,4.35355339 C7.67331141,4.53379537 7.38969588,4.54766014 7.19355028,4.39514769 L7.14644661,4.35355339 L4.5,1.707 L4.5,12 C4.5,12.2761424 4.27614237,12.5 4,12.5 C3.74358208,12.5 3.53224642,12.3069799 3.50336387,12.0583106 L3.5,12 L3.5,1.707 L0.853553391,4.35355339 C0.67331141,4.53379537 0.389695882,4.54766014 0.193550278,4.39514769 L0.146446609,4.35355339 C-0.0337953714,4.17331141 -0.0476601392,3.88969588 0.104852306,3.69355028 L0.146446609,3.64644661 L3.64644661,0.146446609 L3.65767597,0.135561002 C3.67134412,0.122717283 3.68573494,0.110633776 3.70078091,0.0993780001 L3.64644661,0.146446609 C3.67320128,0.11969194 3.70223365,0.0966031755 3.73291954,0.0771803148 C3.74617456,0.0688441438 3.75977662,0.0610999945 3.77375753,0.0539938991 C3.78609769,0.0476919126 3.79888567,0.0418687101 3.81184952,0.0366116524 C3.8234432,0.0319023624 3.83504722,0.0276848515 3.84684229,0.0238934918 C3.86557052,0.0179217879 3.88445336,0.0130756914 3.90351142,0.00934593934 C3.91016306,0.00799330119 3.91744282,0.00672777028 3.92477476,0.00562145489 C3.94767442,0.00222086491 3.97013713,0.000384038311 3.99261784,5.41592491e-05 L4,3.55271368e-14 Z M11,0 C11.2564179,0 11.4677536,0.193020095 11.4966361,0.441689437 L11.5,0.5 L11.499,10.792 L14.1464466,8.14644661 C14.3266886,7.96620463 14.6103041,7.95233986 14.8064497,8.10485231 L14.8535534,8.14644661 C15.0337954,8.32668859 15.0476601,8.61030412 14.8951477,8.80644972 L14.8535534,8.85355339 L11.3535534,12.3535534 L11.342324,12.364439 C11.3286559,12.3772827 11.3142651,12.3893662 11.2992191,12.400622 L11.3535534,12.3535534 C11.3267987,12.3803081 11.2977664,12.4033968 11.2670805,12.4228197 C11.2538254,12.4311559 11.2402234,12.4389 11.2262425,12.4460061 C11.2139023,12.4523081 11.2011143,12.4581313 11.1881505,12.4633883 C11.1765568,12.4680976 11.1649528,12.4723151 11.1531577,12.4761065 C11.1344295,12.4820782 11.1155466,12.4869243 11.0964886,12.4906541 C11.08887,12.4921969 11.0806073,12.4936082 11.0722781,12.4948142 C11.0526434,12.4976054 11.0335482,12.4992446 11.0144276,12.4997931 L11,12.5 L11,12.5 L10.9590982,12.4983345 C10.9507048,12.4976497 10.9423254,12.4967538 10.9339686,12.4956467 L11,12.5 C10.9581653,12.5 10.9175306,12.4948622 10.8786924,12.4851831 C10.8667313,12.4821627 10.8547654,12.4787079 10.8429168,12.4747983 C10.828989,12.4702266 10.8151853,12.4649672 10.8016896,12.4591301 C10.7896647,12.4539556 10.7775355,12.4481398 10.7656088,12.4418071 C10.74145,12.4289242 10.7184764,12.4141602 10.6968848,12.3976777 L10.6935503,12.3951477 L10.6464466,12.3535534 L7.14644661,8.85355339 C6.95118446,8.65829124 6.95118446,8.34170876 7.14644661,8.14644661 C7.32668859,7.96620463 7.61030412,7.95233986 7.80644972,8.10485231 L7.85355339,8.14644661 L10.499,10.792 L10.5,0.5 C10.5,0.223857625 10.7238576,0 11,0 Z"></path>
</svg>

After

Width:  |  Height:  |  Size: 3.6 KiB

@@ -0,0 +1,69 @@
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { ProtectedImage } from '../photoGallery/ProtectedMedia'
import { albumQuery_album_subAlbums } from '../../Pages/AlbumPage/__generated__/albumQuery'
interface AlbumBoxImageProps {
src?: string
}
const AlbumBoxImage = ({ src, ...props }: AlbumBoxImageProps) => {
const [loaded, setLoaded] = useState(false)
let image = null
if (src) {
image = (
<ProtectedImage
className="object-cover object-center w-full h-full rounded-lg"
{...props}
onLoad={() => setLoaded(true)}
src={src}
/>
)
}
let placeholder = null
if (!loaded) {
placeholder = (
<div className="bg-gray-100 dark:bg-[#191c1f] animate-pulse w-full h-full rounded-lg absolute top-0"></div>
)
}
return (
<div className="xs:w-[220px] xs:h-[220px] relative rounded-lg">
{image}
{placeholder}
</div>
)
}
type AlbumBoxProps = {
album?: albumQuery_album_subAlbums
customLink?: string
}
export const AlbumBox = ({ album, customLink, ...props }: AlbumBoxProps) => {
const wrapperClasses =
'inline-block text-center text-gray-900 dark:text-gray-200 mx-3 my-2 xs:h-60 xs:w-[220px]'
if (album) {
return (
<Link
to={customLink || `/album/${album.id}`}
className={wrapperClasses}
{...props}
>
<AlbumBoxImage src={album.thumbnail?.thumbnail?.url} />
<p className="whitespace-nowrap overflow-hidden overflow-ellipsis">
{album.title}
</p>
</Link>
)
}
return (
<div className={wrapperClasses} {...props}>
<AlbumBoxImage />
</div>
)
}
@@ -0,0 +1,33 @@
import React from 'react'
import { albumQuery_album_subAlbums } from '../../Pages/AlbumPage/__generated__/albumQuery'
import { AlbumBox } from './AlbumBox'
type AlbumBoxesProps = {
error?: Error
albums?: albumQuery_album_subAlbums[]
getCustomLink?(albumID: string): string
}
const AlbumBoxes = ({ error, albums, getCustomLink }: AlbumBoxesProps) => {
if (error) return <div>Error {error.message}</div>
let albumElements = []
if (albums !== undefined) {
albumElements = albums.map(album => (
<AlbumBox
key={album.id}
album={album}
customLink={getCustomLink ? getCustomLink(album.id) : undefined}
/>
))
} else {
for (let i = 0; i < 4; i++) {
albumElements.push(<AlbumBox key={i} />)
}
}
return <div className="-mx-3 my-6">{albumElements}</div>
}
export default AlbumBoxes
@@ -0,0 +1,124 @@
import React, { useEffect, useReducer } from 'react'
import AlbumTitle from '../album/AlbumTitle'
import MediaGallery, {
MEDIA_GALLERY_FRAGMENT,
} from '../photoGallery/MediaGallery'
import AlbumBoxes from './AlbumBoxes'
import AlbumFilter from '../album/AlbumFilter'
import {
mediaGalleryReducer,
urlPresentModeSetupHook,
} from '../photoGallery/mediaGalleryReducer'
import { MediaOrdering, SetOrderingFn } from '../../hooks/useOrderingParams'
import { gql } from '@apollo/client'
import { AlbumGalleryFields } from './__generated__/AlbumGalleryFields'
export const ALBUM_GALLERY_FRAGMENT = gql`
${MEDIA_GALLERY_FRAGMENT}
fragment AlbumGalleryFields on Album {
id
title
subAlbums(order: { order_by: "title", order_direction: $orderDirection }) {
id
title
thumbnail {
id
thumbnail {
url
}
}
}
media(
paginate: { limit: $limit, offset: $offset }
order: { order_by: $mediaOrderBy, order_direction: $orderDirection }
onlyFavorites: $onlyFavorites
) {
...MediaGalleryFields
}
}
`
type AlbumGalleryProps = {
album?: AlbumGalleryFields
loading?: boolean
customAlbumLink?(albumID: string): string
showFilter?: boolean
setOnlyFavorites?(favorites: boolean): void
setOrdering?: SetOrderingFn
ordering?: MediaOrdering
onlyFavorites?: boolean
onFavorite?(): void
}
const AlbumGallery = React.forwardRef(
(
{
album,
loading = false,
customAlbumLink,
showFilter = false,
setOnlyFavorites,
setOrdering,
ordering,
onlyFavorites = false,
}: AlbumGalleryProps,
ref: React.ForwardedRef<HTMLDivElement>
) => {
const [mediaState, dispatchMedia] = useReducer(mediaGalleryReducer, {
presenting: false,
activeIndex: -1,
media: album?.media || [],
})
useEffect(() => {
dispatchMedia({ type: 'replaceMedia', media: album?.media || [] })
}, [album?.media])
// urlPresentModeSetupHook({
// dispatchMedia,
// openPresentMode: event => {
// dispatchMedia({
// type: 'openPresentMode',
// activeIndex: event.state.activeIndex,
// })
// },
// })
let subAlbumElement = null
if (album) {
if (album.subAlbums.length > 0) {
subAlbumElement = (
<AlbumBoxes
albums={album.subAlbums}
getCustomLink={customAlbumLink}
/>
)
}
} else {
subAlbumElement = <AlbumBoxes />
}
return (
<div ref={ref}>
{showFilter && (
<AlbumFilter
onlyFavorites={onlyFavorites}
setOnlyFavorites={setOnlyFavorites}
setOrdering={setOrdering}
ordering={ordering}
/>
)}
<AlbumTitle album={album} disableLink />
{subAlbumElement}
<MediaGallery
loading={loading}
mediaState={mediaState}
dispatchMedia={dispatchMedia}
/>
</div>
)
}
)
export default AlbumGallery
@@ -0,0 +1,106 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { MediaType } from "./../../../__generated__/globalTypes";
// ====================================================
// GraphQL fragment: AlbumGalleryFields
// ====================================================
export interface AlbumGalleryFields_subAlbums_thumbnail_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface AlbumGalleryFields_subAlbums_thumbnail {
__typename: "Media";
id: string;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: AlbumGalleryFields_subAlbums_thumbnail_thumbnail | null;
}
export interface AlbumGalleryFields_subAlbums {
__typename: "Album";
id: string;
title: string;
/**
* An image in this album used for previewing this album
*/
thumbnail: AlbumGalleryFields_subAlbums_thumbnail | null;
}
export interface AlbumGalleryFields_media_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface AlbumGalleryFields_media_highRes {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface AlbumGalleryFields_media_videoWeb {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface AlbumGalleryFields_media {
__typename: "Media";
id: string;
type: MediaType;
/**
* A short string that can be used to generate a blured version of the media, to show while the original is loading
*/
blurhash: string | null;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: AlbumGalleryFields_media_thumbnail | null;
/**
* URL to display the photo in full resolution, will be null for videos
*/
highRes: AlbumGalleryFields_media_highRes | null;
/**
* URL to get the video in a web format that can be played in the browser, will be null for photos
*/
videoWeb: AlbumGalleryFields_media_videoWeb | null;
favorite: boolean;
}
export interface AlbumGalleryFields {
__typename: "Album";
id: string;
title: string;
/**
* The albums contained in this album
*/
subAlbums: AlbumGalleryFields_subAlbums[];
/**
* The media inside this album
*/
media: AlbumGalleryFields_media[];
}
@@ -0,0 +1,79 @@
import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { MediaType } from '../../__generated__/globalTypes'
import { MediaSidebarMedia } from '../sidebar/MediaSidebar/MediaSidebar'
import { sidebarMediaQuery_media_faces } from '../sidebar/MediaSidebar/__generated__/sidebarMediaQuery'
interface FaceBoxStyleProps {
$minY: number
$maxY: number
$minX: number
$maxX: number
}
const FaceBoxStyle = styled(Link)`
box-shadow: inset 0 0 2px 1px rgba(0, 0, 0, 0.3), 0 0 0 1px rgb(255, 255, 255);
border-radius: 50%;
position: absolute;
top: ${({ $minY }: FaceBoxStyleProps) => $minY * 100}%;
bottom: ${({ $maxY }: FaceBoxStyleProps) => (1 - $maxY) * 100}%;
left: ${({ $minX }: FaceBoxStyleProps) => $minX * 100}%;
right: ${({ $maxX }: FaceBoxStyleProps) => (1 - $maxX) * 100}%;
`
type FaceBoxProps = {
face: sidebarMediaQuery_media_faces
}
const FaceBox = ({ face /*media*/ }: FaceBoxProps) => {
return (
<FaceBoxStyle
to={`/people/${face.faceGroup.id}`}
$minX={face.rectangle.minX}
$maxX={face.rectangle.maxX}
$minY={face.rectangle.minY}
$maxY={face.rectangle.maxY}
></FaceBoxStyle>
)
}
const SidebarFacesOverlayWrapper = styled.div<{ width: number }>`
position: absolute;
width: ${({ width }) => width * 100}%;
left: ${({ width }) => (100 - width * 100) / 2}%;
height: 100%;
top: 0;
opacity: 0;
user-select: none;
transition: opacity ease 200ms;
&:hover {
opacity: 1;
}
`
type SidebarFaceOverlayProps = {
media: MediaSidebarMedia
}
export const SidebarFacesOverlay = ({ media }: SidebarFaceOverlayProps) => {
if (media.type != MediaType.Photo) return null
if (media.thumbnail == null) return null
const faceBoxes = media.faces?.map(face => (
<FaceBox key={face.id} face={face} />
))
let wrapperWidth = 1
if (media.thumbnail.width * 0.75 < media.thumbnail.height) {
wrapperWidth = (media.thumbnail.width * 0.75) / media.thumbnail.height
}
return (
<SidebarFacesOverlayWrapper width={wrapperWidth}>
{faceBoxes}
</SidebarFacesOverlayWrapper>
)
}
+31
View File
@@ -0,0 +1,31 @@
import React, { useContext } from 'react'
import SearchBar from './Searchbar'
import { authToken } from '../../helpers/authentication'
import { SidebarContext } from '../sidebar/Sidebar'
import classNames from 'classnames'
const Header = () => {
const { pinned } = useContext(SidebarContext)
return (
<div
className={classNames(
'sticky top-0 z-10 h-16 bg-dark-bg text-dark-text flex items-center justify-between pl-[14px] lg:pl-[281px] pr-4',
{ 'mr-[404px]': pinned }
)}
>
<h1 className="mr-4 lg:mr-8 flex-shrink-0 flex items-center">
<img
className="h-8"
style={{ height: '38px' }}
src={import.meta.env.BASE_URL + 'photoview-logo.svg'}
alt="logo"
/>
</h1>
{authToken() ? <SearchBar /> : null}
</div>
)
}
export default Header
+402
View File
@@ -0,0 +1,402 @@
import React, { useState, useRef, useEffect } from 'react'
import styled from 'styled-components'
import { useLazyQuery, gql } from '@apollo/client'
import { debounce, DebouncedFn } from '../../helpers/utils'
import { ProtectedImage } from '../photoGallery/ProtectedMedia'
import { NavLink, useNavigate, useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
searchQuery,
searchQuery_search_albums,
searchQuery_search_media,
} from './__generated__/searchQuery'
import classNames from 'classnames'
const SEARCH_QUERY = gql`
query searchQuery($query: String!) {
search(query: $query) {
query
albums {
id
title
thumbnail {
thumbnail {
url
}
}
}
media {
id
title
thumbnail {
url
}
album {
id
}
}
}
}
`
const SearchWrapper = styled.div.attrs({
className: 'w-full max-w-xs lg:relative',
})``
const SearchBar = () => {
const { t } = useTranslation()
const [fetchSearches, fetchResult] = useLazyQuery<searchQuery>(SEARCH_QUERY)
const [query, setQuery] = useState('')
const [fetched, setFetched] = useState(false)
const [expanded, setExpanded] = useState(false)
const inputEl = useRef<HTMLInputElement>(null)
type QueryFn = (query: string) => void
const debouncedFetch = useRef<null | DebouncedFn<QueryFn>>(null)
useEffect(() => {
debouncedFetch.current = debounce<QueryFn>(query => {
fetchSearches({ variables: { query } })
setFetched(true)
setExpanded(true)
}, 250)
return () => {
debouncedFetch.current?.cancel()
}
}, [])
const fetchEvent = (e: React.ChangeEvent<HTMLInputElement>) => {
e.persist()
setQuery(e.target.value)
if (e.target.value.trim() != '' && debouncedFetch.current) {
debouncedFetch.current(e.target.value.trim())
} else {
setFetched(false)
}
}
const location = useLocation()
useEffect(() => {
setExpanded(false)
setQuery('')
}, [location])
const [selectedItem, setSelectedItem] = useState<number | null>(null)
const searchData = fetchResult.data
let media = searchData?.search.media || []
let albums = searchData?.search.albums || []
albums = albums.slice(0, 5)
media = media.slice(0, 5)
const selectedItemId =
selectedItem !== null
? [...albums.map(x => x.id), ...media.map(x => x.id)][selectedItem]
: null
useEffect(() => {
const elem = inputEl.current
if (!elem) return
const focusEvent = () => {
setExpanded(true)
}
const blurEvent = () => {
setExpanded(false)
}
elem.addEventListener('focus', focusEvent)
elem.addEventListener('blur', blurEvent)
return () => {
elem.removeEventListener('focus', focusEvent)
elem.removeEventListener('blur', blurEvent)
}
}, [inputEl])
useEffect(() => {
setSelectedItem(null)
}, [searchData])
useEffect(() => {
const totalItems = albums.length + media.length
const keydownEvent = (event: KeyboardEvent) => {
if (!expanded) return
if (event.key == 'ArrowDown') {
event.preventDefault()
setSelectedItem(i => (i === null ? 0 : Math.min(totalItems - 1, i + 1)))
} else if (event.key == 'ArrowUp') {
event.preventDefault()
setSelectedItem(i => (i === null ? 0 : Math.max(0, i - 1)))
} else if (event.key == 'Escape') {
// setExpanded(false)
inputEl.current?.blur()
}
}
document.addEventListener('keydown', keydownEvent)
return () => {
document.removeEventListener('keydown', keydownEvent)
}
}, [searchData])
let results = null
if (query.trim().length > 0 && fetched) {
results = (
<SearchResults
albums={albums}
media={media}
query={fetchResult.data?.search.query || ''}
selectedItem={selectedItem}
setSelectedItem={setSelectedItem}
loading={fetchResult.loading}
expanded={expanded}
/>
)
}
return (
<SearchWrapper>
<input
ref={inputEl}
autoComplete="off"
aria-controls="search-results"
aria-haspopup="listbox"
aria-autocomplete="list"
aria-activedescendant={
selectedItemId ? `search-item-${selectedItemId}` : ''
}
aria-expanded={expanded}
className="w-full py-2 px-3 z-10 relative rounded-md bg-gray-50 focus:bg-white border border-gray-50 focus:border-blue-400 outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-50 dark:bg-dark-bg2 dark:border-dark-bg2 dark:focus:bg-[#2a2f35]"
type="search"
placeholder={t('header.search.placeholder', 'Search')}
onChange={fetchEvent}
value={query}
/>
{results}
</SearchWrapper>
)
}
const ResultTitle = styled.h1.attrs({
className:
'uppercase text-gray-700 dark:text-gray-200 text-sm font-semibold mt-4 mb-2 mx-1',
})``
type SearchResultsProps = {
albums: searchQuery_search_albums[]
media: searchQuery_search_media[]
loading: boolean
selectedItem: number | null
setSelectedItem: React.Dispatch<React.SetStateAction<number | null>>
query: string
expanded: boolean
}
const SearchResults = ({
albums,
media,
loading,
selectedItem,
setSelectedItem,
query,
expanded,
}: SearchResultsProps) => {
const { t } = useTranslation()
const albumElements = albums.map((album, i) => (
<AlbumRow
key={album.id}
query={query}
album={album}
selected={selectedItem == i}
setSelected={() => setSelectedItem(i)}
/>
))
const mediaElements = media.map((media, i) => (
<PhotoRow
key={media.id}
query={query}
media={media}
selected={selectedItem == i + albumElements.length}
setSelected={() => setSelectedItem(i + albumElements.length)}
/>
))
let message = null
if (loading) message = t('header.search.loading', 'Loading results...')
else if (media.length == 0 && albums.length == 0)
message = t('header.search.no_results', 'No results found')
if (message) message = <div className="mt-8 text-center">{message}</div>
return (
<div
id="search-results"
role="listbox"
className={classNames(
'absolute bg-white dark:bg-dark-bg left-0 right-0 top-[72px] overflow-y-auto h-[calc(100vh-152px)] border dark:border-dark-border px-4 z-0',
'lg:top-[40px] lg:shadow-md lg:rounded-b lg:max-h-[560px]',
{ hidden: !expanded }
)}
tabIndex={-1}
onMouseDown={e => {
// Prevent input blur event
e.preventDefault()
}}
>
{message}
{albumElements.length > 0 && (
<>
<ResultTitle>
{t('header.search.result_type.albums', 'Albums')}
</ResultTitle>
<ul aria-label="albums">{albumElements}</ul>
</>
)}
{mediaElements.length > 0 && (
<>
<ResultTitle>
{t('header.search.result_type.media', 'Media')}
</ResultTitle>
<ul aria-label="media">{mediaElements}</ul>
</>
)}
</div>
)
}
type SearchRowProps = {
id: string
link: string
preview: React.ReactNode
label: React.ReactNode
selected: boolean
setSelected(): void
}
const SearchRow = ({
id,
link,
preview,
label,
selected,
setSelected,
}: SearchRowProps) => {
const rowEl = useRef<HTMLLIElement>(null)
const navigate = useNavigate()
useEffect(() => {
const keydownEvent = (event: KeyboardEvent) => {
if (event.key == 'Enter') navigate(link)
}
document.addEventListener('keydown', keydownEvent)
return () => {
document.removeEventListener('keydown', keydownEvent)
}
})
if (selected) {
rowEl.current?.scrollIntoView({
block: 'nearest',
})
}
return (
<li
id={`search-item-${id}`}
ref={rowEl}
role="option"
aria-selected={selected}
onMouseOver={() => setSelected()}
className={classNames('rounded p-1 mt-1', {
'bg-gray-100 dark:bg-dark-bg2': selected,
})}
>
<NavLink to={link} className="flex items-center" tabIndex={-1}>
{preview}
<span className="flex-grow pl-2 text-sm">{label}</span>
</NavLink>
</li>
)
}
type PhotoRowArgs = {
query: string
media: searchQuery_search_media
selected: boolean
setSelected(): void
}
const PhotoRow = ({ query, media, selected, setSelected }: PhotoRowArgs) => (
<SearchRow
key={media.id}
id={media.id}
link={`/album/${media.album.id}`}
preview={
<ProtectedImage
src={media?.thumbnail?.url}
className="w-14 h-14 object-cover"
/>
}
label={searchHighlighted(query, media.title)}
selected={selected}
setSelected={setSelected}
/>
)
type AlbumRowArgs = {
query: string
album: searchQuery_search_albums
selected: boolean
setSelected(): void
}
const AlbumRow = ({ query, album, selected, setSelected }: AlbumRowArgs) => (
<SearchRow
key={album.id}
id={album.id}
link={`/album/${album.id}`}
preview={
<ProtectedImage
src={album?.thumbnail?.thumbnail?.url}
className="w-14 h-14 rounded object-cover"
/>
}
label={searchHighlighted(query, album.title)}
selected={selected}
setSelected={setSelected}
/>
)
const searchHighlighted = (query: string, text: string) => {
const i = text.toLowerCase().indexOf(query.toLowerCase())
if (i == -1) {
return text
}
const start = text.substring(0, i)
const middle = text.substring(i, i + query.length)
const end = text.substring(i + query.length)
return (
<span>
{start}
<span className="font-semibold whitespace-pre">{middle}</span>
{end}
</span>
)
}
export default SearchBar
+88
View File
@@ -0,0 +1,88 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: searchQuery
// ====================================================
export interface searchQuery_search_albums_thumbnail_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface searchQuery_search_albums_thumbnail {
__typename: "Media";
/**
* URL to display the media in a smaller resolution
*/
thumbnail: searchQuery_search_albums_thumbnail_thumbnail | null;
}
export interface searchQuery_search_albums {
__typename: "Album";
id: string;
title: string;
/**
* An image in this album used for previewing this album
*/
thumbnail: searchQuery_search_albums_thumbnail | null;
}
export interface searchQuery_search_media_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface searchQuery_search_media_album {
__typename: "Album";
id: string;
}
export interface searchQuery_search_media {
__typename: "Media";
id: string;
title: string;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: searchQuery_search_media_thumbnail | null;
/**
* The album that holds the media
*/
album: searchQuery_search_media_album;
}
export interface searchQuery_search {
__typename: "SearchResult";
/**
* The string that was searched for
*/
query: string;
/**
* A list of albums that matched the query
*/
albums: searchQuery_search_albums[];
/**
* A list of media that matched the query
*/
media: searchQuery_search_media[];
}
export interface searchQuery {
/**
* Perform a search query on the contents of the media library
*/
search: searchQuery_search;
}
export interface searchQueryVariables {
query: string;
}
+14
View File
@@ -0,0 +1,14 @@
import { render, screen } from '@testing-library/react'
import React from 'react'
import Layout from './Layout'
test('Layout component', () => {
render(
<Layout title="Test title">
<p>layout_content</p>
</Layout>
)
expect(screen.getByTestId('Layout')).toBeInTheDocument()
expect(screen.getByText('layout_content')).toBeInTheDocument()
})
+53
View File
@@ -0,0 +1,53 @@
import { gql } from '@apollo/client'
import React, { useContext } from 'react'
import { Helmet } from 'react-helmet'
import Header from '../header/Header'
import { Authorized } from '../routes/AuthorizedRoute'
import { Sidebar, SidebarContext } from '../sidebar/Sidebar'
import MainMenu from './MainMenu'
export const ADMIN_QUERY = gql`
query adminQuery {
myUser {
admin
}
}
`
type LayoutProps = {
children: React.ReactNode
title: string
}
const Layout = ({ children, title, ...otherProps }: LayoutProps) => {
const { pinned, content: sidebarContent } = useContext(SidebarContext)
return (
<>
<Helmet>
<title>
{title ? `${title} - Gallery.FuKun.Net` : `Gallery.FuKun.Net`}
</title>
</Helmet>
<div className="relative" {...otherProps} data-testid="Layout">
<Header />
<div className="">
<Authorized>
<MainMenu />
</Authorized>
<div
className={`mx-6 my-3 lg:mt-5 lg:mr-16 lg:ml-[292px] ${
pinned && sidebarContent ? 'lg:pr-[420px]' : ''
}`}
id="layout-content"
>
{children}
</div>
</div>
<Sidebar />
</div>
</>
)
}
export default Layout
@@ -0,0 +1,59 @@
import React from 'react'
import { MockedProvider } from '@apollo/client/testing'
import { render, screen } from '@testing-library/react'
import * as authentication from '../../helpers/authentication'
import { ADMIN_QUERY } from './Layout'
import { MemoryRouter } from 'react-router-dom'
import MainMenu, { MAPBOX_QUERY } from './MainMenu'
vi.mock('../../helpers/authentication.ts')
const authTokenMock = vi.mocked(authentication.authToken)
afterEach(() => {
authTokenMock.mockClear()
})
test('Layout sidebar component', async () => {
authTokenMock.mockImplementation(() => 'test-token')
const mockedGraphql = [
{
request: {
query: ADMIN_QUERY,
},
result: {
data: {
myUser: {
admin: true,
},
},
},
},
{
request: {
query: MAPBOX_QUERY,
},
result: {
data: {
mapboxToken: true,
},
},
},
]
render(
<MockedProvider mocks={mockedGraphql} addTypename={false}>
<MemoryRouter>
<MainMenu />
</MemoryRouter>
</MockedProvider>
)
expect(screen.getByText('Timeline')).toBeInTheDocument()
expect(screen.getByText('Albums')).toBeInTheDocument()
expect(await screen.findByText('Settings')).toBeInTheDocument()
expect(await screen.findByText('Places')).toBeInTheDocument()
})
+159
View File
@@ -0,0 +1,159 @@
import React from 'react'
import { NavLink } from 'react-router-dom'
import { useQuery, gql } from '@apollo/client'
import { authToken } from '../../helpers/authentication'
import { useTranslation } from 'react-i18next'
import { mapboxEnabledQuery } from '../../__generated__/mapboxEnabledQuery'
import { tailwindClassNames } from '../../helpers/utils'
import { faceDetectionEnabled } from './__generated__/faceDetectionEnabled'
export const MAPBOX_QUERY = gql`
query mapboxEnabledQuery {
mapboxToken
}
`
export const FACE_DETECTION_ENABLED_QUERY = gql`
query faceDetectionEnabled {
siteInfo {
faceDetectionEnabled
}
}
`
type MenuButtonProps = {
to: string
exact: boolean
label: string
background: string
activeClasses?: string
className?: string
icon?: React.ReactNode
}
const MenuButton = ({
to,
exact,
label,
background,
icon,
activeClasses,
className,
}: MenuButtonProps) => {
return (
<NavLink
to={to}
end={exact}
className={({ isActive }) =>
tailwindClassNames(
`rounded-lg my-2 outline-none`,
className,
{
activeClasses: isActive,
}
)
}
>
<li className="flex items-center">
<div
className={`w-12 h-12 p-1.5 lg:w-8 lg:h-8 lg:p-1 w-full h-full rounded-lg`}
style={{ backgroundColor: background }}
>
{icon}
</div>
<span className="hidden lg:block ml-2">{label}</span>
</li>
</NavLink>
)
}
const MenuSeparator = () => (
<hr className="hidden lg:block my-3 border-gray-200 dark:border-dark-border" />
)
export const MainMenu = () => {
const { t } = useTranslation()
const mapboxQuery = authToken()
? useQuery<mapboxEnabledQuery>(MAPBOX_QUERY)
: null
const faceDetectionEnabledQuery = authToken()
? useQuery<faceDetectionEnabled>(FACE_DETECTION_ENABLED_QUERY)
: null
const mapboxEnabled = !!mapboxQuery?.data?.mapboxToken
const faceDetectionEnabled =
!!faceDetectionEnabledQuery?.data?.siteInfo?.faceDetectionEnabled
return (
<div className="fixed w-full bottom-0 lg:bottom-auto lg:top-16 z-30 bg-dark-bg lg:w-[240px] lg:ml-0 lg:mr-5 flex-shrink-0">
<ul className="flex justify-around py-2 px-2 max-w-lg mx-auto lg:flex-col lg:p-0">
<MenuButton
to="/timeline"
exact
label={t('sidemenu.photos', 'Timeline')}
background="#000000"
activeClasses="bg-[#1a1a1a] dark:bg-[#1a1a1a]"
className="focus:ring-0 shadow-none"
icon={
<svg
viewBox="0 0 24 24"
fill="none"
stroke="white"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="3" y="3" width="18" height="18" rx="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<path d="m21 15-5-5L5 21" />
</svg>
}
/>
<MenuButton
to="/albums"
exact
label={t('sidemenu.albums', 'Albums')}
background="#000000"
activeClasses="bg-[#1a1a1a] dark:bg-[#1a1a1a]"
className="focus:ring-0 shadow-none"
icon={
<svg
viewBox="0 0 24 24"
fill="none"
stroke="white"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
</svg>
}
/>
<MenuButton
to="/settings"
exact
label={t('sidemenu.settings', 'Settings')}
background="#000000"
activeClasses="bg-[#1a1a1a] dark:bg-[#1a1a1a]"
className="focus:ring-0 shadow-none"
icon={
<svg
viewBox="0 0 24 24"
fill="none"
stroke="white"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
}
/>
</ul>
</div>
)
}
export default MainMenu
+23
View File
@@ -0,0 +1,23 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: adminQuery
// ====================================================
export interface adminQuery_myUser {
__typename: "User";
/**
* Whether or not the user has admin privileges
*/
admin: boolean;
}
export interface adminQuery {
/**
* Information about the currently logged in user
*/
myUser: adminQuery_myUser;
}
@@ -0,0 +1,20 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: faceDetectionEnabled
// ====================================================
export interface faceDetectionEnabled_siteInfo {
__typename: "SiteInfo";
/**
* Whether or not face detection is enabled and working
*/
faceDetectionEnabled: boolean;
}
export interface faceDetectionEnabled {
siteInfo: faceDetectionEnabled_siteInfo;
}
@@ -0,0 +1,15 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: mapboxEnabledQuery
// ====================================================
export interface mapboxEnabledQuery {
/**
* Get the mapbox api token, returns null if mapbox is not enabled
*/
mapboxToken: string | null;
}
@@ -0,0 +1,5 @@
<svg viewBox="0 0 24 24" fill="white">
<path
d="M6,16 L19,16 C19.5522847,16 20,16.4477153 20,17 L20,21 C20,21.5522847 19.5522847,22 19,22 L6,22 C4.8954305,22 4,21.1045695 4,20 L4,18 C4,16.8954305 4.8954305,16 6,16 Z" fillOpacity="0.75" />
<path d="M19,2 C19.5522847,2 20,2.44771525 20,3 L20,19 C20,19.5522847 19.5522847,20 19,20 L6,20 C4.8954305,20 4,19.1045695 4,18 L4,4 C4,2.8954305 4.8954305,2 6,2 L19,2 Z M14.4676845,9 L11.5079767,12.9536523 L9.50029382,10.8745763 L7,14 L18,14 L14.4676845,9 Z M10.75,9 C10.3357864,9 10,9.33578644 10,9.75 C10,10.1642136 10.3357864,10.5 10.75,10.5 C11.1642136,10.5 11.5,10.1642136 11.5,9.75 C11.5,9.33578644 11.1642136,9 10.75,9 Z" />
</svg>

After

Width:  |  Height:  |  Size: 686 B

@@ -0,0 +1,7 @@
<svg viewBox="0 0 24 24" fill="white">
<path
d="M12,15 C15.1826579,15 18.0180525,16.4868108 19.8494955,18.8037439 L20,19 C20,20.6568542 18.6568542,22 17,22 L7,22 C5.34314575,22 4,20.6568542 4,19 L4.15050454,18.8037439 C5.9819475,16.4868108 8.81734212,15 12,15 Z"
fillOpacity="0.75"
></path>
<circle cx="12" cy="11" r="6"></circle>
</svg>

After

Width:  |  Height:  |  Size: 351 B

@@ -0,0 +1,4 @@
<svg viewBox="0 0 24 24" fill="white">
<path d="M15.6971052,10 L23.9367603,21.526562 C23.6878671,22.9323278 22.4600272,24 20.982819,24 L5.851819,24 L15.6971052,10 Z" />
<path d="M5.59307375,14 L15.562,24 L2.982819,24 C1.43507633,24 0.161084327,22.8279341 -3.56225466e-14,21.3229592 L5.59307375,14 Z" fillOpacity="0.75"/>
</svg>

After

Width:  |  Height:  |  Size: 331 B

@@ -0,0 +1,8 @@
<svg viewBox="0 0 24 24" fill="white">
<path d="M3.4,3.34740684 C3.47896999,3.34740684 3.55617307,3.37078205 3.62188008,3.41458672 L9,7 L9,21 L3.4452998,17.2968665 C3.16710114,17.1114008 3,16.7991694 3,16.4648162 L3,3.74740684 C3,3.52649294 3.1790861,3.34740684 3.4,3.34740684 Z M15,3 L21.4961389,6.71207939 C21.8077139,6.89012225 22,7.22146569 22,7.58032254 L22,20.3107281 C22,20.531642 21.8209139,20.7107281 21.6,20.7107281 C21.5303892,20.7107281 21.4619835,20.692562 21.4015444,20.6580254 L15,17 L15,3 Z" />
<polygon
fillOpacity="0.75"
transform="translate(12, 12) scale(1, -1) translate(-12, -12)"
points="9 3 15 7 15 21 9 17"
/>
</svg>

After

Width:  |  Height:  |  Size: 658 B

@@ -0,0 +1,7 @@
<svg viewBox="0 0 24 24" fill="white">
<path
d="M13.4691754,16.7806702 L13,21 L11,21 L10.5318353,16.7809803 C10.9960818,16.9233714 11.4890921,17 12,17 C12.5112786,17 13.0046337,16.9232601 13.4691754,16.7806702 Z M16.4192861,14.3409153 L19.0710678,17.6568542 L17.6568542,19.0710678 L14.3409153,16.4192861 C15.2243208,15.9503691 15.9503691,15.2243208 16.4192861,14.3409153 Z M9.65908474,16.4192861 L6.34314575,19.0710678 L4.92893219,17.6568542 L7.5807139,14.3409153 C8.04963086,15.2243208 8.77567918,15.9503691 9.65908474,16.4192861 Z M7,12 C7,12.5112786 7.07673988,13.0046337 7.21932976,13.4691754 L3,13 L3,11 L7.21901966,10.5318353 C7.07662862,10.9960818 7,11.4890921 7,12 Z M16.7809803,10.5318353 L21,11 L21,13 L16.7806702,13.4691754 C16.9232601,13.0046337 17,12.5112786 17,12 C17,11.4890921 16.9233714,10.9960818 16.7809803,10.5318353 Z M6.34314575,4.92893219 L9.65908474,7.5807139 C8.77567918,8.04963086 8.04963086,8.77567918 7.5807139,9.65908474 L4.92893219,6.34314575 L6.34314575,4.92893219 Z M17.6568542,4.92893219 L19.0710678,6.34314575 L16.4192861,9.65908474 C15.9503691,8.77567918 15.2243208,8.04963086 14.3409153,7.5807139 L17.6568542,4.92893219 Z M13,3 L13.4691754,7.21932976 C13.0046337,7.07673988 12.5112786,7 12,7 C11.4890921,7 10.9960818,7.07662862 10.5318353,7.21901966 L11,3 L13,3 Z"
fillOpacity="0.76"
/>
<path d="M12,5 C15.8659932,5 19,8.13400675 19,12 C19,15.8659932 15.8659932,19 12,19 C8.13400675,19 5,15.8659932 5,12 C5,8.13400675 8.13400675,5 12,5 Z M12,8 C9.790861,8 8,9.790861 8,12 C8,14.209139 9.790861,16 12,16 C14.209139,16 16,14.209139 16,12 C16,9.790861 14.209139,8 12,8 Z" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

+83
View File
@@ -0,0 +1,83 @@
import React, { useState, useRef, useEffect } from 'react'
import { gql, useQuery } from '@apollo/client'
import type mapboxgl from 'mapbox-gl'
import styled from 'styled-components'
import 'mapbox-gl/dist/mapbox-gl.css'
import { mapboxToken } from './__generated__/mapboxToken'
import { isDarkMode } from '../../theme'
const MAPBOX_TOKEN_QUERY = gql`
query mapboxToken {
mapboxToken
myMediaGeoJson
}
`
const MapContainer = styled.div`
width: 100%;
height: 100%;
`
type MapboxMapProps = {
configureMapbox(map: mapboxgl.Map, mapboxLibrary: typeof mapboxgl): void
mapboxOptions?: Partial<mapboxgl.MapboxOptions>
}
const useMapboxMap = ({
configureMapbox,
mapboxOptions = undefined,
}: MapboxMapProps) => {
const [mapboxLibrary, setMapboxLibrary] = useState<typeof mapboxgl>()
const mapContainer = useRef<HTMLDivElement | null>(null)
const map = useRef<mapboxgl.Map | null>(null)
const { data: mapboxData } = useQuery<mapboxToken>(MAPBOX_TOKEN_QUERY, {
fetchPolicy: 'cache-first',
})
useEffect(() => {
async function loadMapboxLibrary() {
const mapbox = (await import('mapbox-gl')).default
setMapboxLibrary(mapbox)
}
loadMapboxLibrary()
}, [])
useEffect(() => {
if (
mapboxLibrary == null ||
mapContainer.current == null ||
mapboxData == null ||
map.current != null
) {
return
}
if (mapboxData.mapboxToken)
mapboxLibrary.accessToken = mapboxData.mapboxToken
map.current = new mapboxLibrary.Map({
container: mapContainer.current,
style: isDarkMode()
? 'mapbox://styles/mapbox/dark-v10'
: 'mapbox://styles/mapbox/streets-v11',
...mapboxOptions,
})
configureMapbox(map.current, mapboxLibrary)
map.current?.resize()
}, [mapContainer, mapboxLibrary, mapboxData])
map.current?.resize()
return {
mapContainer: <MapContainer ref={mapContainer}></MapContainer>,
mapboxMap: map.current,
mapboxLibrary,
mapboxToken: mapboxData?.mapboxToken || null,
}
}
export default useMapboxMap
+19
View File
@@ -0,0 +1,19 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: mapboxToken
// ====================================================
export interface mapboxToken {
/**
* Get the mapbox api token, returns null if mapbox is not enabled
*/
mapboxToken: string | null;
/**
* Get media owned by the logged in user, returned in GeoJson format
*/
myMediaGeoJson: Any;
}
@@ -0,0 +1,93 @@
import type mapboxgl from 'mapbox-gl'
import type geojson from 'geojson'
import React from 'react'
import ReactDOM from 'react-dom'
import MapClusterMarker from '../../Pages/PlacesPage/MapClusterMarker'
import { MediaMarker } from '../../Pages/PlacesPage/MapPresentMarker'
import { PlacesAction } from '../../Pages/PlacesPage/placesReducer'
const markers: { [key: string]: mapboxgl.Marker } = {}
let markersOnScreen: typeof markers = {}
type registerMediaMarkersArgs = {
map: mapboxgl.Map
mapboxLibrary: typeof mapboxgl
dispatchMarkerMedia: React.Dispatch<PlacesAction>
}
/**
* Add appropriate event handlers to the map, to render and update media markers
* Expects the provided mapbox map to contain geojson source of media
*/
export const registerMediaMarkers = (args: registerMediaMarkersArgs) => {
const updateMarkers = makeUpdateMarkers(args)
args.map.on('move', updateMarkers)
args.map.on('moveend', updateMarkers)
args.map.on('sourcedata', updateMarkers)
updateMarkers()
}
/**
* Make a function that can be passed to Mapbox to tell it how to render and update the image markers
*/
const makeUpdateMarkers =
({ map, mapboxLibrary, dispatchMarkerMedia }: registerMediaMarkersArgs) =>
() => {
const newMarkers: typeof markers = {}
const features = map.querySourceFeatures('media')
// for every media on the screen, create an HTML marker for it (if we didn't yet),
// and add it to the map if it's not there already
for (const feature of features) {
const point = feature.geometry as geojson.Point
const coords = point.coordinates as [number, number]
const props = feature.properties as MediaMarker
if (props == null) {
console.warn('WARN: geojson feature had no properties', feature)
continue
}
const id = props.cluster
? `cluster_${props.cluster_id}`
: `media_${props.media_id}`
let marker = markers[id]
if (!marker) {
const el = createClusterPopupElement(props, {
dispatchMarkerMedia,
})
marker = markers[id] = new mapboxLibrary.Marker({
element: el,
}).setLngLat(coords)
}
newMarkers[id] = marker
if (!markersOnScreen[id]) marker.addTo(map)
}
// for every marker we've added previously, remove those that are no longer visible
for (const id in markersOnScreen) {
if (!newMarkers[id]) markersOnScreen[id].remove()
}
markersOnScreen = newMarkers
}
function createClusterPopupElement(
geojsonProps: MediaMarker,
{
dispatchMarkerMedia,
}: {
dispatchMarkerMedia: React.Dispatch<PlacesAction>
}
) {
// setPresentMarker: React.Dispatch<React.SetStateAction<PresentMarker | null>>
const el = document.createElement('div')
ReactDOM.render(
<MapClusterMarker
marker={geojsonProps}
dispatchMarkerMedia={dispatchMarkerMedia}
/>,
el
)
return el
}
+33
View File
@@ -0,0 +1,33 @@
import React from 'react'
import { forwardRef } from 'react'
import { ReactComponent as DismissIcon } from './icons/dismissIcon.svg'
export type MessageProps = {
header: string
content?: string
children?: React.ReactNode
onDismiss?(): void
}
const Message = forwardRef(
(
{ onDismiss, header, children, content }: MessageProps,
ref: React.ForwardedRef<HTMLDivElement>
) => {
return (
<div
ref={ref}
className="bg-white dark:bg-dark-bg2 shadow-md border rounded p-2 h-[84px] relative"
>
<button onClick={onDismiss} className="absolute top-3 right-2">
<DismissIcon className="w-[10px] h-[10px] text-gray-700 dark:text-gray-200" />
</button>
<h1 className="font-semibold text-sm">{header}</h1>
<div className="text-sm">{content}</div>
{children}
</div>
)
}
)
export default Message
@@ -0,0 +1,30 @@
import React, { forwardRef } from 'react'
import MessagePlain, { MessageProps } from './Message'
type MessageProgressProps = MessageProps & {
percent?: number
}
const MessageProgress = forwardRef(
(
{ header, content, percent = 0, ...props }: MessageProgressProps,
ref: React.ForwardedRef<HTMLDivElement>
) => {
let color = '#dc2625'
if (percent > 33) color = '#fbbf24'
if (percent > 66) color = '#56e263'
return (
<MessagePlain header={header} content={content} {...props} ref={ref}>
<div className="absolute bottom-0 left-0 right-0 h-[3px] rounded-b overflow-hidden">
<div
className="h-full transition-all duration-200"
style={{ width: `${percent}%`, backgroundColor: color }}
></div>
</div>
</MessagePlain>
)
}
)
export default MessageProgress
+116
View File
@@ -0,0 +1,116 @@
import React, { useState } from 'react'
import styled from 'styled-components'
import { authToken } from '../../helpers/authentication'
import MessageProgress from './MessageProgress'
import MessagePlain from './Message'
import SubscriptionsHook, { Message } from './SubscriptionsHook'
import { NotificationType } from '../../__generated__/globalTypes'
const Container = styled.div`
position: fixed;
bottom: 20px;
right: 20px;
width: 500px;
@media (max-width: 1000px) {
display: none;
}
`
type MessageStateType = {
set: React.Dispatch<React.SetStateAction<Message[]>>
get: Message[]
add(message: Message): void
removeKey(key: string): void
}
export const MessageState: MessageStateType = {
set: fn => {
console.warn('set function is not defined yet, called with', fn)
},
get: [],
add: message => {
MessageState.set(messages => {
const newMessages = messages.filter(msg => msg.key != message.key)
newMessages.push(message)
return newMessages
})
},
removeKey: key => {
MessageState.set(messages => {
const newMessages = messages.filter(msg => msg.key != key)
return newMessages
})
},
}
const Messages = () => {
const [messages, setMessages] = useState<Message[]>([])
MessageState.set = setMessages
MessageState.get = messages
const getMessageElement = (message: Message): React.FunctionComponent => {
const dismissMessage = (message: Message) => {
message.onDismiss && message.onDismiss()
setMessages(messages => messages.filter(msg => msg.key != message.key))
}
switch (message.type) {
case NotificationType.Message:
return props => (
<MessagePlain
onDismiss={() => {
dismissMessage(message)
}}
{...message.props}
{...props}
/>
)
case NotificationType.Progress:
return props => (
<MessageProgress
onDismiss={() => {
dismissMessage(message)
}}
{...message.props}
{...props}
/>
)
default:
throw new Error(`Invalid message type: ${message.type}`)
}
}
// const transitions = useTransition(messages.slice().reverse(), x => x.key, {
// from: {
// opacity: 0,
// height: '0px',
// },
// enter: {
// opacity: 1,
// height: `100px`,
// },
// leave: { opacity: 0, height: '0px' },
// })
const messageElems = messages.map(msg => {
const Elem = getMessageElement(msg)
return (
<div key={msg.key}>
<Elem />
</div>
)
})
return (
<Container>
{messageElems}
{authToken() && (
<SubscriptionsHook messages={messages} setMessages={setMessages} />
)}
</Container>
)
}
export default Messages
@@ -0,0 +1,124 @@
import { notificationSubscription } from './__generated__/notificationSubscription'
import { useEffect } from 'react'
import { useSubscription, gql } from '@apollo/client'
import { authToken } from '../../helpers/authentication'
import { NotificationType } from '../../__generated__/globalTypes'
const NOTIFICATION_SUBSCRIPTION = gql`
subscription notificationSubscription {
notification {
key
type
header
content
progress
positive
negative
timeout
}
}
`
const messageTimeoutHandles = new Map<string, number>()
export interface Message {
key: string
type: NotificationType
timeout?: number
onDismiss?: () => void
props: {
header: string
content: string
negative?: boolean
positive?: boolean
percent?: number
}
}
type SubscriptionHookProps = {
messages: Message[]
setMessages: React.Dispatch<React.SetStateAction<Message[]>>
}
const SubscriptionsHook = ({
messages,
setMessages,
}: SubscriptionHookProps) => {
if (!authToken()) {
return null
}
const { data, error } = useSubscription<notificationSubscription>(
NOTIFICATION_SUBSCRIPTION
)
useEffect(() => {
if (error) {
setMessages(state => [
...state,
{
key: Math.random().toString(26),
type: NotificationType.Message,
props: {
header: 'Network error',
content: error.message,
negative: true,
},
},
])
}
if (!data) return
const newMessages = [...messages]
const msg = data.notification
if (msg.type == 'Close') {
setMessages(messages => messages.filter(m => m.key != msg.key))
return
}
const newNotification: Message = {
key: msg.key,
type: msg.type,
timeout: msg.timeout || undefined,
props: {
header: msg.header,
content: msg.content,
negative: msg.negative,
positive: msg.positive,
percent: msg.progress || undefined,
},
}
if (msg.timeout) {
// Clear old timeout, to replace it with the new one
if (messageTimeoutHandles.get(msg.key)) {
const timeoutHandle = messageTimeoutHandles.get(msg.key)
clearTimeout(timeoutHandle)
}
const timeoutHandle = setTimeout(() => {
setMessages(messages => messages.filter(m => m.key != msg.key))
}, msg.timeout) as unknown as number
messageTimeoutHandles.set(msg.key, timeoutHandle)
}
const notifyIndex = newMessages.findIndex(
msg => msg.key == newNotification.key
)
if (notifyIndex != -1) {
newMessages[notifyIndex] = newNotification
} else {
newMessages.push(newNotification)
}
setMessages(newMessages)
}, [data, error])
return null
}
export default SubscriptionsHook
@@ -0,0 +1,47 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { NotificationType } from "./../../../__generated__/globalTypes";
// ====================================================
// GraphQL subscription operation: notificationSubscription
// ====================================================
export interface notificationSubscription_notification {
__typename: "Notification";
/**
* A key used to identify the notification, new notification updates with the same key, should replace the old notifications
*/
key: string;
type: NotificationType;
/**
* The text for the title of the notification
*/
header: string;
/**
* The text for the body of the notification
*/
content: string;
/**
* A value between 0 and 1 when the notification type is `Progress`
*/
progress: number | null;
/**
* Whether or not the message of the notification is positive, the UI might reflect this with a green color
*/
positive: boolean;
/**
* Whether or not the message of the notification is negative, the UI might reflect this with a red color
*/
negative: boolean;
/**
* Time in milliseconds before the notification should close
*/
timeout: number | null;
}
export interface notificationSubscription {
notification: notificationSubscription_notification;
}
@@ -0,0 +1 @@
<svg viewBox="0 0 20 20"><g stroke="currentColor" stroke-width="3.5" fill="none" fill-rule="evenodd"><path d="m1.515 1.515 16.97 16.97M18.485 1.515l-16.97 16.97"/></g></svg>

After

Width:  |  Height:  |  Size: 173 B

@@ -0,0 +1,124 @@
import { render, screen } from '@testing-library/react'
import React from 'react'
import { MediaType } from '../../__generated__/globalTypes'
import MediaGallery from './MediaGallery'
import { MediaGalleryState } from './mediaGalleryReducer'
vi.mock('./photoGalleryMutations', () => ({
useMarkFavoriteMutation: () => [vi.fn()],
}))
test('photo gallery with media', () => {
const dispatchMedia = vi.fn()
const mediaState: MediaGalleryState = {
activeIndex: 0,
media: [
{
id: '165',
type: MediaType.Photo,
thumbnail: {
url: '/photo/thumbnail_3666760020_jpg_x76GG5pS.jpg',
width: 768,
height: 1024,
__typename: 'MediaURL',
},
highRes: null,
videoWeb: null,
blurhash: null,
favorite: false,
__typename: 'Media',
},
{
id: '122',
type: MediaType.Photo,
thumbnail: null,
highRes: null,
videoWeb: null,
blurhash: null,
favorite: false,
__typename: 'Media',
},
{
id: '98',
type: MediaType.Video,
thumbnail: null,
highRes: null,
videoWeb: null,
blurhash: null,
favorite: false,
__typename: 'Media',
},
],
presenting: false,
}
render(
<MediaGallery
dispatchMedia={dispatchMedia}
mediaState={mediaState}
loading={false}
/>
)
expect(
screen.getByTestId('photo-gallery-wrapper').querySelectorAll('img')
).toHaveLength(3)
})
describe('photo gallery presenting', () => {
const dispatchMedia = vi.fn()
test('not presenting', () => {
const mediaStateNoPresent: MediaGalleryState = {
activeIndex: -1,
media: [],
presenting: false,
}
render(
<MediaGallery
dispatchMedia={dispatchMedia}
loading={false}
mediaState={mediaStateNoPresent}
/>
)
expect(screen.queryByTestId('present-overlay')).not.toBeInTheDocument()
})
test('presenting', () => {
const mediaStatePresent: MediaGalleryState = {
activeIndex: 0,
media: [
{
id: '165',
type: MediaType.Photo,
thumbnail: {
url: '/photo/thumbnail_3666760020_jpg_x76GG5pS.jpg',
width: 768,
height: 1024,
__typename: 'MediaURL',
},
highRes: null,
videoWeb: null,
blurhash: null,
favorite: false,
__typename: 'Media',
},
],
presenting: true,
}
render(
<MediaGallery
dispatchMedia={dispatchMedia}
loading={false}
mediaState={mediaStatePresent}
/>
)
expect(screen.getByTestId('present-overlay')).toBeInTheDocument()
})
})
@@ -0,0 +1,126 @@
import React, { useContext } from 'react'
import styled from 'styled-components'
import { MediaThumbnail, MediaPlaceholder } from './MediaThumbnail'
import PresentView from './presentView/PresentView'
import {
openPresentModeAction,
PhotoGalleryAction,
MediaGalleryState,
} from './mediaGalleryReducer'
import {
toggleFavoriteAction,
useMarkFavoriteMutation,
} from './photoGalleryMutations'
import MediaSidebar from '../sidebar/MediaSidebar/MediaSidebar'
import { SidebarContext } from '../sidebar/Sidebar'
import { gql } from '@apollo/client'
const Gallery = styled.div`
display: flex;
flex-wrap: wrap;
align-items: center;
min-height: 200px;
position: relative;
margin: -4px;
@media (max-width: 1000px) {
/* Compensate for tab bar on mobile */
margin-bottom: 76px;
}
`
export const PhotoFiller = styled.div`
height: 200px;
flex-grow: 999999;
`
export const MEDIA_GALLERY_FRAGMENT = gql`
fragment MediaGalleryFields on Media {
id
type
blurhash
thumbnail {
url
width
height
}
highRes {
url
}
videoWeb {
url
}
favorite
}
`
type MediaGalleryProps = {
loading: boolean
mediaState: MediaGalleryState
dispatchMedia: React.Dispatch<PhotoGalleryAction>
}
const MediaGallery = ({ mediaState, dispatchMedia }: MediaGalleryProps) => {
const [markFavorite] = useMarkFavoriteMutation()
const { media, activeIndex, presenting } = mediaState
const { updateSidebar } = useContext(SidebarContext)
let mediaElements = []
if (media) {
mediaElements = media.map((media, index) => {
const active = activeIndex == index
return (
<MediaThumbnail
key={media.id}
media={media}
active={active}
selectImage={() => {
dispatchMedia({
type: 'selectImage',
index,
})
updateSidebar(<MediaSidebar media={mediaState.media[index]} />)
}}
clickFavorite={() => {
toggleFavoriteAction({
media,
markFavorite,
})
}}
clickPresent={() => {
dispatchMedia({
type: 'selectImage',
index,
})
updateSidebar(<MediaSidebar media={mediaState.media[index]} />)
}}
/>
)
})
} else {
for (let i = 0; i < 6; i++) {
mediaElements.push(<MediaPlaceholder key={i} />)
}
}
return (
<>
<Gallery data-testid="photo-gallery-wrapper">
{mediaElements}
<PhotoFiller />
</Gallery>
{/* PresentView disabled — click opens sidebar instead */}
{/* presenting && (
<PresentView
activeMedia={mediaState.media[mediaState.activeIndex]}
dispatchMedia={dispatchMedia}
/>
) */}
</>
)
}
export default MediaGallery
@@ -0,0 +1,220 @@
import React from 'react'
import styled from 'styled-components'
import { ProtectedImage } from './ProtectedMedia'
import { MediaType } from '../../__generated__/globalTypes'
import { ReactComponent as VideoThumbnailIconSVG } from './icons/videoThumbnailIcon.svg'
import { MediaGalleryFields } from './__generated__/MediaGalleryFields'
const MediaContainer = styled.div`
flex-grow: 1;
flex-basis: 0;
height: 200px;
margin: 4px 2px;
background-color: #eee;
position: relative;
overflow: hidden;
`
const StyledPhoto = styled(ProtectedImage)`
height: 200px;
min-width: 100%;
position: relative;
object-fit: cover;
transition: opacity 300ms;
`
type LazyPhotoProps = {
src?: string
blurhash: string | null
}
const LazyPhoto = (photoProps: LazyPhotoProps) => {
return <StyledPhoto {...photoProps} lazyLoading />
}
const PhotoOverlay = styled.div<{ active: boolean }>`
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
${({ active }) =>
active &&
`
outline: 4px solid rgba(65, 131, 196, 0.6);
outline-offset: -4px;
`}
`
const HoverIcon = styled.button`
font-size: 1.5em;
margin: 160px 10px 0 10px;
color: white;
text-shadow: 0 0 4px black;
opacity: 0;
position: relative;
border-radius: 50%;
width: 34px;
height: 34px;
${MediaContainer}:hover &, ${MediaContainer}:focus-within & {
opacity: 1 !important;
}
&:hover,
&:focus {
background-color: rgba(0, 0, 0, 0.4);
}
transition: opacity 100ms, background-color 100ms;
`
type FavoriteIconProps = {
favorite: boolean
onClick(e: React.MouseEvent<HTMLButtonElement, MouseEvent>): void
}
const FavoriteIcon = ({ favorite, onClick }: FavoriteIconProps) => {
return (
<HoverIcon
onClick={onClick}
style={{ opacity: favorite ? '0.75' : undefined }}
>
<svg
className="text-white m-auto mt-1"
width="19px"
height="17px"
viewBox="0 0 19 17"
version="1.1"
>
<path
d="M13.999086,1 C15.0573371,1 16.0710089,1.43342987 16.8190212,2.20112483 C17.5765039,2.97781012 18,4.03198704 18,5.13009709 C18,6.22820714 17.5765039,7.28238406 16.8188574,8.05923734 L16.8188574,8.05923734 L15.8553647,9.04761889 L9.49975689,15.5674041 L3.14414912,9.04761889 L2.18065643,8.05923735 C1.39216493,7.2503776 0.999999992,6.18971057 1,5.13009711 C1.00000001,4.07048366 1.39216496,3.00981663 2.18065647,2.20095689 C2.95931483,1.40218431 3.97927681,1.00049878 5.00042783,1.00049878 C6.02157882,1.00049878 7.04154078,1.4021843 7.82019912,2.20095684 L7.82019912,2.20095684 L9.4997569,3.92390079 L11.1794784,2.20078881 C11.9271631,1.43342987 12.9408349,1 13.999086,1 L13.999086,1 Z"
fill={favorite ? 'currentColor' : 'none'}
stroke="currentColor"
strokeWidth={favorite ? '0' : '2'}
></path>
</svg>
</HoverIcon>
)
}
type SidebarIconProps = {
onClick(e: React.MouseEvent<HTMLButtonElement, MouseEvent>): void
}
const SidebarIcon = ({ onClick }: SidebarIconProps) => (
<SidebarIconWrapper onClick={onClick}>
<svg
width="20px"
height="20px"
viewBox="0 0 20 20"
version="1.1"
className="m-auto"
>
<path
d="M10,0 C15.5228475,0 20,4.4771525 20,10 C20,15.5228475 15.5228475,20 10,20 C4.4771525,20 0,15.5228475 0,10 C0,4.4771525 4.4771525,0 10,0 Z M10,9 C9.44771525,9 9,9.44771525 9,10 L9,10 L9,14 L9.00672773,14.1166211 C9.06449284,14.6139598 9.48716416,15 10,15 C10.5522847,15 11,14.5522847 11,14 L11,14 L11,10 L10.9932723,9.88337887 C10.9355072,9.38604019 10.5128358,9 10,9 Z M10.01,5 L9.88337887,5.00672773 C9.38604019,5.06449284 9,5.48716416 9,6 C9,6.55228475 9.44771525,7 10,7 L10,7 L10.1266211,6.99327227 C10.6239598,6.93550716 11.01,6.51283584 11.01,6 C11.01,5.44771525 10.5622847,5 10.01,5 L10.01,5 Z"
fill="#FFFFFF"
></path>
</svg>
</SidebarIconWrapper>
)
const SidebarIconWrapper = styled(HoverIcon)`
margin: 10px !important;
position: absolute;
top: 0;
right: 0;
`
const VideoThumbnailIcon = styled(VideoThumbnailIconSVG)`
color: rgba(255, 255, 255, 0.8);
position: absolute;
left: calc(50% - 17.5px);
top: calc(50% - 22px);
`
type MediaThumbnailProps = {
media: MediaGalleryFields
active: boolean
selectImage(): void
clickPresent(): void
clickFavorite(): void
}
export const MediaThumbnail = ({
media,
active,
selectImage,
clickPresent,
clickFavorite,
}: MediaThumbnailProps) => {
let heartIcon = null
if (media.favorite !== undefined) {
heartIcon = (
<FavoriteIcon
favorite={media.favorite}
onClick={e => {
e.stopPropagation()
clickFavorite()
}}
/>
)
}
let videoIcon = null
if (media.type == MediaType.Video) {
videoIcon = <VideoThumbnailIcon />
}
let minWidth = 100
if (media.thumbnail) {
minWidth = Math.floor(
(media.thumbnail.width / media.thumbnail.height) * 200
)
}
return (
<MediaContainer
key={media.id}
style={{
cursor: 'pointer',
minWidth: `clamp(124px, ${minWidth}px, 100% - 8px)`,
}}
onClick={() => {
clickPresent()
}}
>
<div
style={{
// minWidth: `min(${minWidth}px, 100%)`,
minWidth: `${minWidth}px`,
height: `200px`,
}}
>
<LazyPhoto src={media.thumbnail?.url} blurhash={media.blurhash} />
</div>
<PhotoOverlay active={active}>
{videoIcon}
<SidebarIcon
onClick={e => {
e.stopPropagation()
selectImage()
}}
/>
{heartIcon}
</PhotoOverlay>
</MediaContainer>
)
}
export const MediaPlaceholder = styled.div`
flex-grow: 1;
height: 200px;
width: 300px;
margin: 4px 2px;
background-color: #eee;
position: relative;
`
@@ -0,0 +1,201 @@
import classNames from 'classnames'
import React, { DetailedHTMLProps, ImgHTMLAttributes } from 'react'
import { useRef } from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import { BlurhashCanvas } from 'react-blurhash'
import { isNil } from '../../helpers/utils'
const isNativeLazyLoadSupported = 'loading' in document.createElement('img')
const placeholder =
'data:image/gif;base64,R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
const getProtectedUrl = (url?: string) => {
if (url == undefined) return undefined
const imgUrl = new URL(url, location.origin)
const tokenRegex = location.pathname.match(/^\/share\/([\d\w]+)(\/?.*)$/)
if (tokenRegex) {
const token = tokenRegex[1]
imgUrl.searchParams.set('token', token)
}
return imgUrl.href
}
export interface ProtectedImageProps extends Omit<
DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>,
'src'
> {
src?: string
key?: string
lazyLoading?: boolean
blurhash?: string | null
}
/**
* An image that needs authorization to load
* Set lazyLoading to true if you want the image to be loaded once it enters the viewport
* Native lazy load via HTMLImageElement.loading attribute will be preferred if it is supported by the browser,
* otherwise IntersectionObserver will be used.
*/
export const ProtectedImage = ({
src,
lazyLoading,
blurhash,
...props
}: ProtectedImageProps) => {
const [loaded, setLoaded] = useState(false)
const url = getProtectedUrl(src) || placeholder
const didLoad = () => setLoaded(true)
if (!lazyLoading) {
return (
<img {...props} src={url} loading="eager" crossOrigin="use-credentials" />
)
}
if (!isNativeLazyLoadSupported) {
return <FallbackLazyloadedImage src={url} blurhash={blurhash} {...props} />
}
// load with native lazy loading
return (
<div className="w-full h-full">
<img
{...props}
src={url}
loading="lazy"
crossOrigin="use-credentials"
onLoad={didLoad}
/>
{blurhash && !loaded && (
<BlurhashCanvas
className="absolute w-full h-full top-0"
hash={blurhash}
/>
)}
</div>
)
}
interface FallbackLazyloadedImageProps extends Omit<
DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>,
'src'
> {
src?: string
blurhash?: string | null
}
const FallbackLazyloadedImage = ({
src,
blurhash,
className,
...props
}: FallbackLazyloadedImageProps) => {
const [inView, setInView] = useState(false)
const [loaded, setLoaded] = useState(false)
const imgRef = useRef<HTMLDivElement>(null)
const didLoad = () => setLoaded(true)
useEffect(() => {
const imgElm = imgRef.current
if (isNil(imgElm) || inView) return
if (window.IntersectionObserver === undefined) {
setInView(true)
return
}
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setInView(true)
observer.disconnect()
}
},
{
root: null,
threshold: 0,
}
)
observer.observe(imgElm)
return () => {
observer.disconnect()
}
}, [imgRef])
if (inView) {
return (
<div className={className}>
<img
className="w-full h-full"
{...props}
src={src}
onLoad={didLoad}
crossOrigin="use-credentials"
/>
{blurhash && !loaded && (
<BlurhashCanvas
className="absolute w-full h-full top-0"
hash={blurhash}
/>
)}
</div>
)
} else {
return (
<div ref={imgRef} className={classNames(className, 'bg-[#eee]')}>
{blurhash && (
<BlurhashCanvas
className="absolute w-full h-full top-0"
hash={blurhash}
/>
)}
</div>
)
}
}
export interface ProtectedVideoProps_Media {
__typename: 'Media'
id: string
thumbnail?: null | {
__typename: 'MediaURL'
url: string
}
videoWeb?: null | {
__typename: 'MediaURL'
url: string
}
}
export interface ProtectedVideoProps {
media: ProtectedVideoProps_Media
}
export const ProtectedVideo = ({ media, ...props }: ProtectedVideoProps) => {
if (isNil(media.videoWeb)) {
console.error('ProetctedVideo called with media.videoWeb = null')
return null
}
return (
<video
{...props}
controls
key={media.id}
crossOrigin="use-credentials"
poster={getProtectedUrl(media.thumbnail?.url)}
>
<source src={getProtectedUrl(media.videoWeb.url)} type="video/mp4" />
</video>
)
}
@@ -0,0 +1,65 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { MediaType } from "./../../../__generated__/globalTypes";
// ====================================================
// GraphQL fragment: MediaGalleryFields
// ====================================================
export interface MediaGalleryFields_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface MediaGalleryFields_highRes {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface MediaGalleryFields_videoWeb {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface MediaGalleryFields {
__typename: "Media";
id: string;
type: MediaType;
/**
* A short string that can be used to generate a blured version of the media, to show while the original is loading
*/
blurhash: string | null;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: MediaGalleryFields_thumbnail | null;
/**
* URL to display the photo in full resolution, will be null for videos
*/
highRes: MediaGalleryFields_highRes | null;
/**
* URL to get the video in a web format that can be played in the browser, will be null for photos
*/
videoWeb: MediaGalleryFields_videoWeb | null;
favorite: boolean;
}
@@ -0,0 +1,26 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: markMediaFavorite
// ====================================================
export interface markMediaFavorite_favoriteMedia {
__typename: "Media";
id: string;
favorite: boolean;
}
export interface markMediaFavorite {
/**
* Mark or unmark a media as being a favorite
*/
favoriteMedia: markMediaFavorite_favoriteMedia;
}
export interface markMediaFavoriteVariables {
mediaId: string;
favorite: boolean;
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="35px" height="44px" viewBox="0 0 35 44" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M3.07677855,0.965719632 L33.3619943,20.3146075 C34.2928109,20.9092959 34.5652967,22.145962 33.9706083,23.0767786 C33.814312,23.3214163 33.606632,23.5290962 33.3619943,23.6853925 L3.07677855,43.0342804 C2.14596197,43.6289687 0.909295855,43.356483 0.31460748,42.4256664 C0.10916386,42.1041025 4.6731219e-17,41.7304772 0,41.3488878 L0,2.65111215 C-1.3527075e-16,1.54654265 0.8954305,0.651112151 2,0.651112151 C2.38158936,0.651112151 2.75521463,0.760276012 3.07677855,0.965719632 Z" fill="currentColor"></path>
</svg>

After

Width:  |  Height:  |  Size: 708 B

@@ -0,0 +1,127 @@
import React, { useEffect } from 'react'
import { MediaGalleryFields } from './__generated__/MediaGalleryFields'
export interface MediaGalleryState {
presenting: boolean
activeIndex: number
media: MediaGalleryFields[]
}
export type GalleryAction =
| { type: 'nextImage' }
| { type: 'previousImage' }
| { type: 'closePresentMode' }
export type PhotoGalleryAction =
| GalleryAction
| { type: 'openPresentMode'; activeIndex: number }
| { type: 'selectImage'; index: number }
| { type: 'replaceMedia'; media: MediaGalleryFields[] }
export function mediaGalleryReducer(
state: MediaGalleryState,
action: PhotoGalleryAction
): MediaGalleryState {
switch (action.type) {
case 'nextImage':
return {
...state,
activeIndex: (state.activeIndex + 1) % state.media.length,
}
case 'previousImage':
if (state.activeIndex <= 0) {
return {
...state,
activeIndex: state.media.length - 1,
}
} else {
return {
...state,
activeIndex: state.activeIndex - 1,
}
}
case 'openPresentMode':
return {
...state,
presenting: true,
activeIndex: action.activeIndex,
}
case 'closePresentMode':
return {
...state,
presenting: false,
}
case 'selectImage':
return {
...state,
activeIndex: Math.max(
0,
Math.min(state.media.length - 1, action.index)
),
}
case 'replaceMedia':
return {
...state,
media: action.media,
activeIndex: -1,
presenting: false,
}
}
}
export interface MediaGalleryPopStateEvent extends PopStateEvent {
state: MediaGalleryState
}
export const urlPresentModeSetupHook = ({
dispatchMedia,
openPresentMode,
}: {
dispatchMedia: React.Dispatch<GalleryAction>
openPresentMode: (event: MediaGalleryPopStateEvent) => void
}) => {
useEffect(() => {
const urlChangeListener = (event: MediaGalleryPopStateEvent) => {
if (event.state.presenting === true) {
openPresentMode(event)
} else {
dispatchMedia({ type: 'closePresentMode' })
}
}
window.addEventListener('popstate', urlChangeListener)
history.replaceState({ presenting: false }, '')
return () => {
window.removeEventListener('popstate', urlChangeListener)
}
}, [])
}
export const openPresentModeAction = ({
dispatchMedia,
activeIndex,
}: {
dispatchMedia: React.Dispatch<PhotoGalleryAction>
activeIndex: number
}) => {
dispatchMedia({
type: 'openPresentMode',
activeIndex: activeIndex,
})
history.pushState({ presenting: true, activeIndex }, '')
}
export const closePresentModeAction = ({
dispatchMedia,
}: {
dispatchMedia: React.Dispatch<GalleryAction>
}) => {
dispatchMedia({
type: 'closePresentMode',
})
history.back()
}
@@ -0,0 +1,43 @@
import { MediaGalleryFields } from './__generated__/MediaGalleryFields'
import { gql, MutationFunction, useMutation } from '@apollo/client'
import {
markMediaFavorite,
markMediaFavoriteVariables,
} from './__generated__/markMediaFavorite'
const markFavoriteMutation = gql`
mutation markMediaFavorite($mediaId: ID!, $favorite: Boolean!) {
favoriteMedia(mediaId: $mediaId, favorite: $favorite) {
id
favorite
}
}
`
export const useMarkFavoriteMutation = () => {
return useMutation<markMediaFavorite, markMediaFavoriteVariables>(
markFavoriteMutation
)
}
export const toggleFavoriteAction = ({
media,
markFavorite,
}: {
media: MediaGalleryFields
markFavorite: MutationFunction<markMediaFavorite, markMediaFavoriteVariables>
}) => {
return markFavorite({
variables: {
mediaId: media.id,
favorite: !media.favorite,
},
optimisticResponse: {
favoriteMedia: {
id: media.id,
favorite: !media.favorite,
__typename: 'Media',
},
},
})
}
@@ -0,0 +1,113 @@
import { mediaGalleryReducer, MediaGalleryState } from './mediaGalleryReducer'
import { MediaType } from '../../__generated__/globalTypes'
describe('photo gallery reducer', () => {
const defaultState: MediaGalleryState = {
presenting: false,
activeIndex: 0,
media: [
{
__typename: 'Media',
id: '1',
highRes: null,
thumbnail: null,
blurhash: null,
type: MediaType.Photo,
},
{
__typename: 'Media',
id: '2',
highRes: null,
thumbnail: null,
blurhash: null,
type: MediaType.Photo,
},
{
__typename: 'Media',
id: '3',
highRes: null,
thumbnail: null,
blurhash: null,
type: MediaType.Photo,
},
],
}
test('next image', () => {
expect(mediaGalleryReducer(defaultState, { type: 'nextImage' })).toEqual({
...defaultState,
activeIndex: 1,
})
expect(
mediaGalleryReducer(
{ ...defaultState, activeIndex: 2 },
{ type: 'nextImage' }
)
).toEqual({
...defaultState,
activeIndex: 0,
})
})
test('previous image', () => {
expect(
mediaGalleryReducer(defaultState, { type: 'previousImage' })
).toEqual({
...defaultState,
activeIndex: 2,
})
expect(
mediaGalleryReducer(
{ ...defaultState, activeIndex: 2 },
{ type: 'previousImage' }
)
).toEqual({
...defaultState,
activeIndex: 1,
})
})
test('select image', () => {
expect(
mediaGalleryReducer(defaultState, { type: 'selectImage', index: 1 })
).toEqual({
...defaultState,
activeIndex: 1,
})
expect(
mediaGalleryReducer(defaultState, { type: 'selectImage', index: 100 })
).toEqual({
...defaultState,
activeIndex: 2,
})
expect(
mediaGalleryReducer(defaultState, { type: 'selectImage', index: -5 })
).toEqual({
...defaultState,
activeIndex: 0,
})
})
test('present mode', () => {
const openState = mediaGalleryReducer(defaultState, {
type: 'openPresentMode',
activeIndex: 10,
})
expect(openState).toEqual({
...defaultState,
presenting: true,
activeIndex: 10,
})
expect(
mediaGalleryReducer(openState, { type: 'closePresentMode' })
).toEqual({
...openState,
presenting: false,
})
})
})
@@ -0,0 +1,66 @@
import { render, screen } from '@testing-library/react'
import React from 'react'
import { MediaType } from '../../../__generated__/globalTypes'
import { MediaGalleryFields } from '../__generated__/MediaGalleryFields'
import PresentMedia from './PresentMedia'
test('render present image', () => {
const media: MediaGalleryFields = {
__typename: 'Media',
id: '123',
type: MediaType.Photo,
highRes: null,
blurhash: null,
videoWeb: null,
favorite: false,
thumbnail: {
__typename: 'MediaURL',
url: '/sample_image.jpg',
width: 300,
height: 200,
},
}
render(<PresentMedia media={media} />)
expect(screen.getByTestId('present-img-thumbnail')).toHaveAttribute(
'src',
'http://localhost:3000/sample_image.jpg'
)
expect(screen.getByTestId('present-img-highres')).toHaveStyle({
display: 'none',
})
})
test('render present video', () => {
const media: MediaGalleryFields = {
__typename: 'Media',
id: '123',
type: MediaType.Video,
highRes: null,
blurhash: null,
favorite: false,
videoWeb: {
__typename: 'MediaURL',
url: '/sample_video.mp4',
},
thumbnail: {
__typename: 'MediaURL',
url: '/sample_video_thumb.jpg',
width: 300,
height: 200,
},
}
render(<PresentMedia media={media} />)
expect(screen.getByTestId('present-video')).toHaveAttribute(
'poster',
'http://localhost:3000/sample_video_thumb.jpg'
)
expect(
screen.getByTestId('present-video').querySelector('source')
).toHaveAttribute('src', 'http://localhost:3000/sample_video.mp4')
})
@@ -0,0 +1,65 @@
import React from 'react'
import styled from 'styled-components'
import { MediaType } from '../../../__generated__/globalTypes'
import { exhaustiveCheck } from '../../../helpers/utils'
import { ProtectedImage, ProtectedVideo } from '../ProtectedMedia'
import { MediaGalleryFields } from '../__generated__/MediaGalleryFields'
const StyledPhoto = styled(ProtectedImage)`
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
object-fit: contain;
object-position: center;
`
const StyledVideo = styled(ProtectedVideo)`
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
`
type PresentMediaProps = {
media: MediaGalleryFields
imageLoaded?(): void
}
const PresentMedia = ({
media,
imageLoaded,
...otherProps
}: PresentMediaProps) => {
switch (media.type) {
case MediaType.Photo:
return (
<div {...otherProps}>
<StyledPhoto
key={`${media.id}-thumb`}
src={media.thumbnail?.url}
data-testid="present-img-thumbnail"
/>
<StyledPhoto
key={`${media.id}-highres`}
style={{ display: 'none' }}
src={media.highRes?.url}
data-testid="present-img-highres"
onLoad={e => {
const elem = e.target as HTMLImageElement
elem.style.display = 'initial'
imageLoaded && imageLoaded()
}}
/>
</div>
)
case MediaType.Video:
return <StyledVideo media={media} data-testid="present-video" />
}
exhaustiveCheck(media.type)
}
export default PresentMedia
@@ -0,0 +1,47 @@
import React from 'react'
import PresentNavigationOverlay from './PresentNavigationOverlay'
import { fireEvent, render, screen, act } from '@testing-library/react'
vi.useFakeTimers()
describe('PresentNavigationOverlay component', () => {
test('simple render', () => {
const dispatchMedia = vi.fn()
render(<PresentNavigationOverlay dispatchMedia={dispatchMedia} />)
expect(screen.getByLabelText('Previous image')).toBeInTheDocument()
expect(screen.getByLabelText('Next image')).toBeInTheDocument()
expect(screen.getByLabelText('Exit presentation mode')).toBeInTheDocument()
})
test('click buttons', () => {
const dispatchMedia = vi.fn()
render(<PresentNavigationOverlay dispatchMedia={dispatchMedia} />)
expect(dispatchMedia).not.toHaveBeenCalled()
fireEvent.click(screen.getByLabelText('Next image'))
expect(dispatchMedia).lastCalledWith({ type: 'nextImage' })
fireEvent.click(screen.getByLabelText('Previous image'))
expect(dispatchMedia).lastCalledWith({ type: 'previousImage' })
})
test('mouse move, show and hide', () => {
const dispatchMedia = vi.fn()
const { container } = render(
<PresentNavigationOverlay dispatchMedia={dispatchMedia} />
)
expect(screen.getByLabelText('Next image')).toHaveClass('hide')
fireEvent.mouseMove(container.firstChild!)
expect(screen.getByLabelText('Next image')).not.toHaveClass('hide')
act(() => {
vi.advanceTimersByTime(3000)
})
expect(screen.getByLabelText('Next image')).toHaveClass('hide')
})
})
@@ -0,0 +1,148 @@
import React, { useState, useRef, useEffect } from 'react'
import styled from 'styled-components'
import { debounce, DebouncedFn } from '../../../helpers/utils'
import { closePresentModeAction, GalleryAction } from '../mediaGalleryReducer'
import { useSwipeable } from 'react-swipeable'
import ExitIcon from './icons/Exit'
import NextIcon from './icons/Next'
import PrevIcon from './icons/Previous'
const StyledOverlayContainer = styled.div`
width: 100%;
height: 100%;
position: relative;
`
const OverlayButton = styled.button`
width: 64px;
height: 64px;
background: none;
border: none;
outline: none;
cursor: pointer;
position: absolute;
& svg {
width: 32px;
height: 32px;
overflow: visible !important;
}
& svg path {
stroke: rgba(255, 255, 255, 0.5);
transition-property: stroke, filter;
transition-duration: 140ms;
}
&:hover svg path {
stroke: rgba(255, 255, 255, 1);
filter: drop-shadow(0px 0px 2px rgba(0, 0, 0, 0.6));
}
&.hide svg path {
stroke: rgba(255, 255, 255, 0);
transition: stroke 300ms;
}
`
const ExitButton = styled(OverlayButton)`
left: 28px;
top: 28px;
`
const NavigationButton = styled(OverlayButton)<{ align: 'left' | 'right' }>`
height: 80%;
width: 20%;
top: 10%;
${({ align: float }) => (float == 'left' ? 'left: 0;' : null)}
${({ align: float }) => (float == 'right' ? 'right: 0;' : null)}
& svg {
margin: auto;
width: 48px;
height: 64px;
}
`
type PresentNavigationOverlayProps = {
children?: React.ReactChild
dispatchMedia: React.Dispatch<GalleryAction>
disableSaveCloseInHistory?: boolean
}
const PresentNavigationOverlay = ({
children,
dispatchMedia,
disableSaveCloseInHistory,
}: PresentNavigationOverlayProps) => {
const [hide, setHide] = useState(true)
const onMouseMove = useRef<null | DebouncedFn<() => void>>(null)
useEffect(() => {
onMouseMove.current = debounce(
() => {
setHide(hide => !hide)
},
2000,
true
)
return () => {
onMouseMove.current?.cancel()
}
}, [])
const handlers = useSwipeable({
onSwipedLeft: () => dispatchMedia({ type: 'nextImage' }),
onSwipedRight: () => dispatchMedia({ type: 'previousImage' }),
preventScrollOnSwipe: false,
trackMouse: false,
})
return (
<StyledOverlayContainer
data-testid="present-overlay"
onMouseMove={() => {
onMouseMove.current && onMouseMove.current()
}}
>
<div {...handlers}>
{children}
<NavigationButton
aria-label="Previous image"
className={hide ? 'hide' : undefined}
align="left"
onClick={() => dispatchMedia({ type: 'previousImage' })}
>
<PrevIcon />
</NavigationButton>
<NavigationButton
aria-label="Next image"
className={hide ? 'hide' : undefined}
align="right"
onClick={() => dispatchMedia({ type: 'nextImage' })}
>
<NextIcon />
</NavigationButton>
<ExitButton
aria-label="Exit presentation mode"
className={hide ? 'hide' : undefined}
onClick={() => {
if (disableSaveCloseInHistory === true) {
dispatchMedia({ type: 'closePresentMode' })
} else {
closePresentModeAction({ dispatchMedia })
}
}}
>
<ExitIcon />
</ExitButton>
</div>
</StyledOverlayContainer>
)
}
export default PresentNavigationOverlay
@@ -0,0 +1,83 @@
import React, { useEffect } from 'react'
import styled, { createGlobalStyle } from 'styled-components'
import PresentNavigationOverlay from './PresentNavigationOverlay'
import PresentMedia from './PresentMedia'
import { closePresentModeAction, GalleryAction } from '../mediaGalleryReducer'
import { MediaGalleryFields } from '../__generated__/MediaGalleryFields'
const StyledContainer = styled.div`
position: fixed;
width: 100vw;
height: 100vh;
background-color: black;
color: white;
top: 0;
left: 0;
z-index: 100;
`
const PreventScroll = createGlobalStyle`
* {
overflow: hidden !important;
}
`
type PresentViewProps = {
className?: string
imageLoaded?(): void
activeMedia: MediaGalleryFields
dispatchMedia: React.Dispatch<GalleryAction>
disableSaveCloseInHistory?: boolean
}
const PresentView = ({
className,
imageLoaded,
activeMedia,
dispatchMedia,
disableSaveCloseInHistory,
}: PresentViewProps) => {
useEffect(() => {
const keyDownEvent = (e: KeyboardEvent) => {
if (e.key == 'ArrowRight') {
e.stopPropagation()
dispatchMedia({ type: 'nextImage' })
}
if (e.key == 'ArrowLeft') {
e.stopPropagation()
dispatchMedia({ type: 'previousImage' })
}
if (e.key == 'Escape') {
e.stopPropagation()
if (disableSaveCloseInHistory === true) {
dispatchMedia({ type: 'closePresentMode' })
} else {
closePresentModeAction({ dispatchMedia })
}
}
}
document.addEventListener('keydown', keyDownEvent)
return function cleanup() {
document.removeEventListener('keydown', keyDownEvent)
}
})
return (
<StyledContainer className={className}>
<PreventScroll />
<PresentNavigationOverlay
dispatchMedia={dispatchMedia}
disableSaveCloseInHistory
>
<PresentMedia media={activeMedia} imageLoaded={imageLoaded} />
</PresentNavigationOverlay>
</StyledContainer>
)
}
export default PresentView
@@ -0,0 +1,23 @@
import * as React from 'react'
function SvgExit(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
viewBox="0 0 36 36"
fillRule="evenodd"
clipRule="evenodd"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit={1.5}
width="1em"
height="1em"
{...props}
>
<g fill="none" stroke="#000" strokeWidth={3}>
<path d="M2 2l32 32M2 34L34 2" />
</g>
</svg>
)
}
export default SvgExit
@@ -0,0 +1,21 @@
import * as React from 'react'
function SvgNext(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
viewBox="0 0 28 52"
fillRule="evenodd"
clipRule="evenodd"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit={1.5}
width="1em"
height="1em"
{...props}
>
<path d="M2 2l24 24L2 50" fill="none" stroke="#000" strokeWidth={3} />
</svg>
)
}
export default SvgNext
@@ -0,0 +1,21 @@
import * as React from 'react'
function SvgPrevious(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
viewBox="0 0 28 52"
fillRule="evenodd"
clipRule="evenodd"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit={1.5}
width="1em"
height="1em"
{...props}
>
<path d="M26 2L2 26l24 24" fill="none" stroke="#000" strokeWidth={3} />
</svg>
)
}
export default SvgPrevious
@@ -0,0 +1,134 @@
import React from 'react'
import AuthorizedRoute, { useIsAdmin } from './AuthorizedRoute'
import { render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import * as authentication from '../../helpers/authentication'
import { MockedProvider } from '@apollo/client/testing'
import { ADMIN_QUERY } from '../layout/Layout'
vi.mock('../../helpers/authentication.ts')
const authToken = vi.mocked(authentication.authToken)
describe('AuthorizedRoute component', () => {
const AuthorizedComponent = () => <div>authorized content</div>
test('not logged in', () => {
authToken.mockImplementation(() => null)
render(
<MemoryRouter initialEntries={['/authorized']}>
<Routes>
<Route index element={<div>redirect</div>} />
<Route
path="/authorized"
element={
<AuthorizedRoute>
<AuthorizedComponent />
</AuthorizedRoute>
}
/>
</Routes>
</MemoryRouter>
)
expect(screen.getByText('redirect')).toBeInTheDocument()
expect(screen.queryByText('authorized content')).toBeNull()
})
test('logged in', () => {
authToken.mockImplementation(() => 'token-here')
render(
<MemoryRouter initialEntries={['/authorized']}>
<Routes>
<Route index element={<div>redirect</div>} />
<Route
path="/authorized"
element={
<AuthorizedRoute>
<AuthorizedComponent />
</AuthorizedRoute>
}
/>
</Routes>
</MemoryRouter>
)
expect(screen.getByText('authorized content')).toBeInTheDocument()
expect(screen.queryByText('redirect')).toBeNull()
})
})
describe('useIsAdmin hook', () => {
const graphqlMock = (admin: boolean) => ({
request: {
query: ADMIN_QUERY,
},
result: {
data: {
myUser: {
admin,
},
},
},
})
test('not logged in', async () => {
authToken.mockImplementation(() => null)
const TestComponent = () => {
const isAdmin = useIsAdmin()
return isAdmin ? <div>is admin</div> : <div>not admin</div>
}
render(
<MockedProvider mocks={[graphqlMock(true)]}>
<TestComponent />
</MockedProvider>
)
await waitFor(() => {
expect(screen.getByText('not admin')).toBeInTheDocument()
})
})
test('not admin', async () => {
authToken.mockImplementation(() => 'token-here')
const TestComponent = () => {
const isAdmin = useIsAdmin()
return isAdmin ? <div>is admin</div> : <div>not admin</div>
}
render(
<MockedProvider mocks={[graphqlMock(false)]}>
<TestComponent />
</MockedProvider>
)
await waitFor(() => {
expect(screen.getByText('not admin')).toBeInTheDocument()
})
})
test('is admin', async () => {
authToken.mockImplementation(() => 'token-here')
const TestComponent = () => {
const isAdmin = useIsAdmin()
return isAdmin ? <div>is admin</div> : <div>not admin</div>
}
render(
<MockedProvider mocks={[graphqlMock(true)]}>
<TestComponent />
</MockedProvider>
)
await waitFor(() => {
expect(screen.getByText('is admin')).toBeInTheDocument()
})
})
})
@@ -0,0 +1,45 @@
import { useLazyQuery } from '@apollo/client'
import React, { useEffect } from 'react'
import { Navigate } from 'react-router-dom'
import { authToken } from '../../helpers/authentication'
import { adminQuery } from '../../__generated__/adminQuery'
import { ADMIN_QUERY } from '../layout/Layout'
export const useIsAdmin = () => {
const [fetchAdminQuery, { data, called }] =
useLazyQuery<adminQuery>(ADMIN_QUERY)
useEffect(() => {
if (authToken() && !called) {
fetchAdminQuery()
}
}, [authToken()])
if (!authToken()) {
return false
}
return data?.myUser?.admin
}
export const Authorized = ({ children }: { children: JSX.Element }) => {
const token = authToken()
return token ? children : null
}
interface AuthorizedRouteProps {
children: React.ReactNode
}
const AuthorizedRoute = ({ children }: AuthorizedRouteProps) => {
const token = authToken()
if (!token) {
return <Navigate to="/" />
}
return <>{children}</>
}
export default AuthorizedRoute
+41
View File
@@ -0,0 +1,41 @@
import React from 'react'
import Routes from './Routes'
import {
render,
screen,
waitForElementToBeRemoved,
} from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
vi.mock('../../Pages/LoginPage/LoginPage.tsx', () => () => (
<div>mocked login page</div>
))
describe('routes', () => {
// vitest does not support this yet
// https://github.com/vitest-dev/vitest/issues/960
test.skip('unauthorized root path should navigate to login page', async () => {
render(
<MemoryRouter initialEntries={['/']}>
<Routes />
</MemoryRouter>
)
await waitForElementToBeRemoved(() =>
screen.getByText('Loading', { exact: false })
)
expect(screen.getByText('mocked login page')).toBeInTheDocument()
})
test('invalid page should print a "not found" message', () => {
render(
<MemoryRouter initialEntries={['/random_non_existent_page']}>
<Routes />
</MemoryRouter>
)
expect(screen.getByText('Page not found')).toBeInTheDocument()
})
})
+157
View File
@@ -0,0 +1,157 @@
import React from 'react'
import {
Navigate,
useNavigate,
NavigateFunction,
Outlet,
useRoutes,
} from 'react-router-dom'
import Layout from '../layout/Layout'
import { authToken, clearTokenCookie } from '../../helpers/authentication'
import { TFunction, useTranslation } from 'react-i18next'
import Loader from '../../primitives/Loader'
import AuthorizedRoute from './AuthorizedRoute'
const AlbumsPage = React.lazy(
() => import('../../Pages/AllAlbumsPage/AlbumsPage')
)
const AlbumPage = React.lazy(() => import('../../Pages/AlbumPage/AlbumPage'))
const TimelinePage = React.lazy(
() => import('../../Pages/TimelinePage/TimelinePage')
)
const PlacesPage = React.lazy(() => import('../../Pages/PlacesPage/PlacesPage'))
const LoginPage = React.lazy(() => import('../../Pages/LoginPage/LoginPage'))
const InitialSetupPage = React.lazy(
() => import('../../Pages/LoginPage/InitialSetupPage')
)
const SharePageTokenRoute = React.lazy(() =>
import('../../Pages/SharePage/SharePage').then(x => ({
default: x.TokenRoute,
}))
)
const SettingsPage = React.lazy(
() => import('../../Pages/SettingsPage/SettingsPage')
)
const PeoplePage = React.lazy(() =>
import('../../Pages/PeoplePage/PeoplePage').then(x => ({
default: x.PeoplePage,
}))
)
const PersonPage = React.lazy(() =>
import('../../Pages/PeoplePage/PeoplePage').then(x => ({
default: x.PersonPage,
}))
)
const Routes = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const authorized = (element: React.ReactNode) => (
<AuthorizedRoute>{element}</AuthorizedRoute>
)
const routes = useRoutes([
{
index: true,
element: <IndexPage />,
},
{
path: '/login',
element: <LoginPage />,
},
{
path: '/logout',
element: <LogoutPage navigate={navigate} />,
},
{
path: '/initialSetup',
element: <InitialSetupPage />,
},
{
path: '/share/:token/*',
element: <SharePageTokenRoute />,
},
{
path: '/albums',
element: authorized(<AlbumsPage />),
},
{
path: '/album/:id',
element: authorized(<AlbumPage />),
},
{
path: '/timeline',
element: authorized(<TimelinePage />),
},
{
path: '/places',
element: authorized(<PlacesPage />),
},
{
path: '/settings',
element: authorized(<SettingsPage />),
},
{
path: '/people',
element: authorized(<Outlet />),
children: [
{
path: ':person',
element: <PersonPage />,
},
{
index: true,
element: <PeoplePage />,
},
],
},
{
// for backwards-compatibility
path: '/photos',
element: <Navigate to="/timeline" />,
},
{
path: '*',
element: <NotFoundPage t={t} />,
},
])
return (
<React.Suspense
fallback={
<Layout title={t('general.loading.page', 'Loading page')}>
<Loader message={t('general.loading.page', 'Loading page')} active />
</Layout>
}
>
{routes}
</React.Suspense>
)
}
const IndexPage = () => {
const token = authToken()
const dest = token ? '/timeline' : '/login'
return <Navigate to={dest} />
}
export const NotFoundPage = ({ t }: { t: TFunction }) => {
return <div>{t('routes.page_not_found', 'Page not found')}</div>
}
const LogoutPage = ({ navigate }: { navigate: NavigateFunction }) => {
clearTokenCookie()
navigate('/')
return null
}
export default Routes
+161
View File
@@ -0,0 +1,161 @@
import React, { useState, useEffect } from 'react'
import { useMutation, gql } from '@apollo/client'
import { useTranslation } from 'react-i18next'
import { SidebarSection, SidebarSectionTitle } from './SidebarComponents'
import {
setAlbumCover,
setAlbumCoverVariables,
} from './__generated__/setAlbumCover'
import {
resetAlbumCover,
resetAlbumCoverVariables,
} from './__generated__/resetAlbumCover'
import { authToken } from '../../helpers/authentication'
const RESET_ALBUM_COVER_MUTATION = gql`
mutation resetAlbumCover($albumID: ID!) {
resetAlbumCover(albumID: $albumID) {
id
thumbnail {
id
thumbnail {
url
}
}
}
}
`
const SET_ALBUM_COVER_MUTATION = gql`
mutation setAlbumCover($coverID: ID!) {
setAlbumCover(coverID: $coverID) {
id
thumbnail {
id
thumbnail {
url
}
}
}
}
`
type SidebarPhotoCoverProps = {
cover_id: string
}
export const SidebarPhotoCover = ({ cover_id }: SidebarPhotoCoverProps) => {
const { t } = useTranslation()
const [setAlbumCover] = useMutation<setAlbumCover, setAlbumCoverVariables>(
SET_ALBUM_COVER_MUTATION,
{
variables: {
coverID: cover_id,
},
}
)
const [buttonDisabled, setButtonDisabled] = useState(false)
useEffect(() => {
setButtonDisabled(false)
}, [cover_id])
// hide when not authenticated
if (!authToken()) {
return null
}
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.album.album_cover', 'Album cover')}
</SidebarSectionTitle>
<div>
<table className="border-collapse w-full">
<tfoot>
<tr className="text-left border-gray-100 dark:border-dark-border2 border-b border-t">
<td colSpan={2} className="pl-4 py-2">
<button
className="disabled:opacity-50 text-green-500 font-bold uppercase text-xs"
disabled={buttonDisabled}
onClick={() => {
setButtonDisabled(true),
setAlbumCover({
variables: {
coverID: cover_id,
},
})
}}
>
<span>
{t('sidebar.album.set_cover', 'Set as album cover photo')}
</span>
</button>
</td>
</tr>
</tfoot>
</table>
</div>
</SidebarSection>
)
}
type SidebarAlbumCoverProps = {
id: string
}
export const SidebarAlbumCover = ({ id }: SidebarAlbumCoverProps) => {
const { t } = useTranslation()
const [resetAlbumCover] = useMutation<
resetAlbumCover,
resetAlbumCoverVariables
>(RESET_ALBUM_COVER_MUTATION, {
variables: {
albumID: id,
},
})
const [buttonDisabled, setButtonDisabled] = useState(false)
useEffect(() => {
setButtonDisabled(false)
}, [id])
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.album.album_cover', 'Album cover')}
</SidebarSectionTitle>
<div>
<table className="border-collapse w-full">
<tfoot>
<tr className="text-left border-gray-100 dark:border-dark-border2 border-b border-t">
<td colSpan={2} className="pl-4 py-2">
<button
className="disabled:opacity-50 text-red-500 font-bold uppercase text-xs"
disabled={buttonDisabled}
onClick={() => {
setButtonDisabled(true),
resetAlbumCover({
variables: {
albumID: id,
},
})
}}
>
<span>
{t('sidebar.album.reset_cover', 'Reset cover photo')}
</span>
</button>
</td>
</tr>
</tfoot>
</table>
</div>
</SidebarSection>
)
}
@@ -0,0 +1,61 @@
import React from 'react'
import { useQuery, gql } from '@apollo/client'
import { SidebarAlbumShare } from './Sharing'
import { useTranslation } from 'react-i18next'
import SidebarHeader from './SidebarHeader'
import {
getAlbumSidebar,
getAlbumSidebarVariables,
} from './__generated__/getAlbumSidebar'
import { SidebarAlbumCover } from './AlbumCovers'
import SidebarAlbumDownload from './SidebarDownloadAlbum'
const albumQuery = gql`
query getAlbumSidebar($id: ID!) {
album(id: $id) {
id
title
}
}
`
type AlbumSidebarProps = {
albumId: string
}
const AlbumSidebar = ({ albumId }: AlbumSidebarProps) => {
const { t } = useTranslation()
const { loading, error, data } = useQuery<
getAlbumSidebar,
getAlbumSidebarVariables
>(albumQuery, {
variables: { id: albumId },
})
if (loading) return <div>{t('general.loading.default', 'Loading...')}</div>
if (error) return <div>{error.message}</div>
return (
<div>
{/* <p>{t('sidebar.album.title', 'Album options')}</p> */}
<SidebarHeader
title={
data?.album.title ??
t('sidebar.album.title_placeholder', 'Album title')
}
/>
<div className="mt-8">
{/* <h1 className="text-3xl font-semibold">{data.album.title}</h1> */}
<SidebarAlbumShare id={albumId} />
</div>
<div className="mt-8">
<SidebarAlbumCover id={albumId} />
</div>
<div className="mt-8">
<SidebarAlbumDownload albumID={albumId} />
</div>
</div>
)
}
export default AlbumSidebar
@@ -0,0 +1,85 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import { MockedProvider } from '@apollo/client/testing'
import MediaSidebar, { MediaSidebarMedia } from './MediaSidebar'
import { MediaType } from '../../../__generated__/globalTypes'
import { MemoryRouter } from 'react-router'
import * as authentication from '../../../helpers/authentication'
vi.mock('../../../helpers/authentication.ts')
const authToken = vi.mocked(authentication.authToken)
describe('MediaSidebar', () => {
const media: MediaSidebarMedia = {
__typename: 'Media',
id: '6867',
title: '122A6069.jpg',
type: MediaType.Photo,
thumbnail: {
__typename: 'MediaURL',
url: '/photo/thumbnail.jpg',
width: 1024,
height: 839,
},
highRes: {
__typename: 'MediaURL',
url: '/photo/highres.jpg',
width: 5322,
height: 4362,
},
videoWeb: null,
album: {
__typename: 'Album',
id: '2294',
title: 'album_name',
},
}
test('render sample image, unauthorized', () => {
authToken.mockImplementation(() => null)
render(
<MockedProvider mocks={[]} addTypename={false}>
<MemoryRouter>
<MediaSidebar media={media} />
</MemoryRouter>
</MockedProvider>
)
expect(screen.getByText('122A6069.jpg')).toBeInTheDocument()
expect(screen.getByRole('img')).toHaveAttribute(
'src',
'http://localhost:3000/photo/highres.jpg'
)
expect(
screen.queryByText('Set as album cover photo')
).not.toBeInTheDocument()
expect(screen.queryByText('Sharing options')).not.toBeInTheDocument()
})
test('render sample image, authorized', () => {
authToken.mockImplementation(() => 'token-here')
render(
<MockedProvider mocks={[]} addTypename={false}>
<MemoryRouter>
<MediaSidebar media={media} />
</MemoryRouter>
</MockedProvider>
)
expect(screen.getByText('122A6069.jpg')).toBeInTheDocument()
expect(screen.getByRole('img')).toHaveAttribute(
'src',
'http://localhost:3000/photo/highres.jpg'
)
expect(screen.getByText('Set as album cover photo')).toBeInTheDocument()
expect(screen.getByText('Album path')).toBeInTheDocument()
screen.debug()
})
})
@@ -0,0 +1,308 @@
import { gql, useLazyQuery } from '@apollo/client'
import React, { useEffect, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { authToken } from '../../../helpers/authentication'
import { isNil } from '../../../helpers/utils'
import { MediaType } from '../../../__generated__/globalTypes'
import { SidebarFacesOverlay } from '../../facesOverlay/FacesOverlay'
import { SidebarContext } from '../Sidebar'
import {
ProtectedImage,
ProtectedVideo,
ProtectedVideoProps_Media,
} from '../../photoGallery/ProtectedMedia'
import { SidebarPhotoCover } from '../AlbumCovers'
import { SidebarPhotoShare } from '../Sharing'
import SidebarMediaDownload from '../SidebarDownloadMedia'
import SidebarHeader from '../SidebarHeader'
import { sidebarDownloadQuery_media_downloads } from '../__generated__/sidebarDownloadQuery'
import ExifDetails from './MediaSidebarExif'
import MediaSidebarPeople from './MediaSidebarPeople'
import MediaSidebarMap from './MediaSidebarMap'
import {
sidebarMediaQuery,
sidebarMediaQueryVariables,
sidebarMediaQuery_media_album_path,
sidebarMediaQuery_media_exif,
sidebarMediaQuery_media_faces,
sidebarMediaQuery_media_thumbnail,
sidebarMediaQuery_media_videoMetadata,
} from './__generated__/sidebarMediaQuery'
import { BreadcrumbList } from '../../album/AlbumTitle'
export const SIDEBAR_MEDIA_QUERY = gql`
query sidebarMediaQuery($id: ID!) {
media(id: $id) {
id
title
type
highRes {
url
width
height
}
thumbnail {
url
width
height
}
videoWeb {
url
width
height
}
videoMetadata {
id
width
height
duration
codec
framerate
bitrate
colorProfile
audio
}
exif {
id
description
camera
maker
lens
dateShot
exposure
aperture
iso
focalLength
flash
exposureProgram
coordinates {
latitude
longitude
}
}
album {
id
title
path {
id
title
}
}
faces {
id
rectangle {
minX
maxX
minY
maxY
}
faceGroup {
id
label
imageFaceCount
}
media {
id
title
thumbnail {
url
width
height
}
}
}
}
}
`
const PreviewImage = styled(ProtectedImage)`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
object-fit: contain;
`
const PreviewVideo = styled(ProtectedVideo)`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
`
interface PreviewMediaPropsMedia extends ProtectedVideoProps_Media {
type: MediaType
}
type PreviewMediaProps = {
media: PreviewMediaPropsMedia
previewImage?: {
url: string
}
}
const PreviewMedia = ({ media, previewImage }: PreviewMediaProps) => {
if (media.type === MediaType.Photo) {
return <PreviewImage src={previewImage?.url} />
}
if (media.type === MediaType.Video) {
return <PreviewVideo media={media} />
}
return <div>ERROR: Unknown media type: {media.type}</div>
}
type SidebarContentProps = {
media: MediaSidebarMedia
hidePreview?: boolean
}
const SidebarContent = ({ media, hidePreview }: SidebarContentProps) => {
const { updateSidebar } = useContext(SidebarContext)
const { t } = useTranslation()
let previewImage = null
if (media.highRes) previewImage = media.highRes
else if (media.thumbnail) previewImage = media.thumbnail
const imageAspect =
previewImage?.width && previewImage?.height
? previewImage.height / previewImage.width
: 3 / 2
let sidebarMap = null
const mediaCoordinates = media.exif?.coordinates
if (mediaCoordinates) {
sidebarMap = <MediaSidebarMap coordinates={mediaCoordinates} />
}
let albumPath = null
const mediaAlbum = media.album
if (!isNil(mediaAlbum)) {
console.log('PATH reversed', mediaAlbum.path ?? [])
const pathElms = [
...[...(mediaAlbum.path ?? [])].reverse(),
mediaAlbum,
].map(album => (
<li key={album.id} className="inline-block hover:underline">
<Link
className="text-blue-900 dark:text-blue-200 hover:underline"
to={`/album/${album.id}`}
onClick={() => updateSidebar(null)}
>
{album.title}
</Link>
</li>
))
albumPath = (
<div className="mx-4 my-4">
<h2 className="uppercase text-xs text-gray-900 dark:text-gray-300 font-semibold">
{t('sidebar.media.album_path', 'Album path')}
</h2>
<BreadcrumbList hideLastArrow={true}>{pathElms}</BreadcrumbList>
</div>
)
}
return (
<div>
<SidebarHeader title={media.title ?? 'Loading...'} />
<div className="lg:mx-4">
{!hidePreview && (
<div
className="w-full h-0 relative"
style={{ paddingTop: `${Math.min(imageAspect, 0.75) * 100}%` }}
>
<PreviewMedia
previewImage={previewImage || undefined}
media={media}
/>
<SidebarFacesOverlay media={media} />
</div>
)}
</div>
<ExifDetails media={media} />
{albumPath}
<MediaSidebarPeople media={media} />
{sidebarMap}
<SidebarMediaDownload media={media} />
<SidebarPhotoShare id={media.id} />
<div className="mt-8">
<SidebarPhotoCover cover_id={media.id} />
</div>
</div>
)
}
export interface MediaSidebarMedia {
__typename: 'Media'
id: string
title?: string
type: MediaType
highRes?: null | {
__typename: 'MediaURL'
url: string
width?: number
height?: number
}
thumbnail?: sidebarMediaQuery_media_thumbnail | null
videoWeb?: null | {
__typename: 'MediaURL'
url: string
width?: number
height?: number
}
videoMetadata?: sidebarMediaQuery_media_videoMetadata | null
exif?: sidebarMediaQuery_media_exif | null
faces?: sidebarMediaQuery_media_faces[]
downloads?: sidebarDownloadQuery_media_downloads[]
album?: {
__typename: 'Album'
id: string
title: string
path?: sidebarMediaQuery_media_album_path[]
}
}
type MediaSidebarType = {
media: MediaSidebarMedia
hidePreview?: boolean
}
const MediaSidebar = ({ media, hidePreview }: MediaSidebarType) => {
const [loadMedia, { loading, error, data }] = useLazyQuery<
sidebarMediaQuery,
sidebarMediaQueryVariables
>(SIDEBAR_MEDIA_QUERY)
useEffect(() => {
if (media != null && authToken()) {
loadMedia({
variables: {
id: media.id,
},
})
}
}, [media])
if (!media) return null
if (!authToken()) {
return <SidebarContent media={media} hidePreview={hidePreview} />
}
if (error) return <div>{error.message}</div>
if (loading || data == null) {
return <SidebarContent media={media} hidePreview={hidePreview} />
}
return <SidebarContent media={data.media} hidePreview={hidePreview} />
}
export default MediaSidebar
@@ -0,0 +1,553 @@
import { vi } from 'vitest'
// Mock react-i18next following the project pattern
const mockUseTranslation = vi.fn()
vi.mock('react-i18next', () => ({
useTranslation: mockUseTranslation,
}))
mockUseTranslation.mockReturnValue({
t: (key: string, defaultValue: string) => defaultValue,
i18n: { language: 'en' },
})
import React from 'react'
import { render, screen } from '@testing-library/react'
import ExifDetails from './MediaSidebarExif'
import { MediaSidebarMedia } from './MediaSidebar'
import { MediaType } from '../../../__generated__/globalTypes'
describe('ExifDetails', () => {
test('without EXIF information', () => {
const media: MediaSidebarMedia = {
id: '1730',
title: 'media_name.jpg',
type: MediaType.Photo,
exif: {
id: '0',
description: null,
camera: null,
maker: null,
lens: null,
dateShot: null,
exposure: null,
aperture: null,
iso: null,
focalLength: null,
flash: null,
exposureProgram: null,
coordinates: null,
__typename: 'MediaEXIF',
},
__typename: 'Media',
}
render(<ExifDetails media={media} />)
expect(screen.queryByText('Description')).not.toBeInTheDocument()
expect(screen.queryByText('Camera')).not.toBeInTheDocument()
expect(screen.queryByText('Maker')).not.toBeInTheDocument()
expect(screen.queryByText('Lens')).not.toBeInTheDocument()
expect(screen.queryByText('Program')).not.toBeInTheDocument()
expect(screen.queryByText('Date shot')).not.toBeInTheDocument()
expect(screen.queryByText('Exposure')).not.toBeInTheDocument()
expect(screen.queryByText('Aperture')).not.toBeInTheDocument()
expect(screen.queryByText('ISO')).not.toBeInTheDocument()
expect(screen.queryByText('Focal length')).not.toBeInTheDocument()
expect(screen.queryByText('Flash')).not.toBeInTheDocument()
expect(screen.queryByText('Coordinates')).not.toBeInTheDocument()
})
test('with EXIF information', () => {
const media: MediaSidebarMedia = {
id: '1730',
title: 'media_name.jpg',
type: MediaType.Photo,
exif: {
id: '1666',
description: 'Media description',
camera: 'Canon EOS R',
maker: 'Canon',
lens: 'TAMRON SP 24-70mm F/2.8',
dateShot: '2021-01-23T20:50:18Z',
exposure: 0.016666666666666666,
aperture: 2.8,
iso: 100,
focalLength: 24,
flash: 9,
exposureProgram: 3,
coordinates: {
__typename: 'Coordinates',
latitude: 41.40338,
longitude: 2.17403,
},
__typename: 'MediaEXIF',
},
__typename: 'Media',
}
render(<ExifDetails media={media} />)
expect(screen.getByText('Description')).toBeInTheDocument()
expect(screen.getByText('Camera')).toBeInTheDocument()
expect(screen.getByText('Canon EOS R')).toBeInTheDocument()
expect(screen.getByText('Maker')).toBeInTheDocument()
expect(screen.getByText('Canon')).toBeInTheDocument()
expect(screen.getByText('Lens')).toBeInTheDocument()
expect(screen.getByText('TAMRON SP 24-70mm F/2.8')).toBeInTheDocument()
expect(screen.getByText('Date shot')).toBeInTheDocument()
expect(screen.getByText('Exposure')).toBeInTheDocument()
expect(screen.getByText('1/60')).toBeInTheDocument()
expect(screen.getByText('Program')).toBeInTheDocument()
expect(screen.getByText('Aperture priority')).toBeInTheDocument()
expect(screen.getByText('Aperture')).toBeInTheDocument()
expect(screen.getByText('f/2.8')).toBeInTheDocument()
expect(screen.getByText('ISO')).toBeInTheDocument()
expect(screen.getByText('100')).toBeInTheDocument()
expect(screen.getByText('Focal length')).toBeInTheDocument()
expect(screen.getByText('24mm')).toBeInTheDocument()
expect(screen.getByText('Flash')).toBeInTheDocument()
expect(screen.getByText('On, Fired')).toBeInTheDocument()
expect(screen.getByText('Coordinates')).toBeInTheDocument()
expect(screen.getByText('41.40338, 2.17403')).toBeInTheDocument()
})
})
describe('ExifDetails dateShot formatting', () => {
const createMediaWithDateShot = (dateShot: string): MediaSidebarMedia => ({
id: '1730',
title: 'media_name.jpg',
type: MediaType.Photo,
exif: {
id: '1666',
description: null,
camera: null,
maker: null,
lens: null,
dateShot,
exposure: null,
aperture: null,
iso: null,
focalLength: null,
flash: null,
exposureProgram: null,
coordinates: null,
__typename: 'MediaEXIF',
},
__typename: 'Media',
})
describe('RFC3339 with timezone offset', () => {
test('formats RFC3339 with positive timezone offset', () => {
const media = createMediaWithDateShot('2023-07-15T14:30:45+02:00')
render(<ExifDetails media={media} />)
expect(screen.getByText('Date shot')).toBeInTheDocument()
// Should show medium date format, time, and timezone offset WITHOUT abbreviation
expect(screen.getByText(/Jul 15, 2023.*2:30:45 PM.*\+02:00$/)).toBeInTheDocument()
})
test('formats RFC3339 with negative timezone offset', () => {
const media = createMediaWithDateShot('2023-12-15T10:15:30-08:00')
render(<ExifDetails media={media} />)
expect(screen.getByText(/Dec 15, 2023.*10:15:30 AM.*-08:00$/)).toBeInTheDocument()
})
test('formats RFC3339 with fractional timezone offset', () => {
const media = createMediaWithDateShot('2023-06-01T16:45:12+05:30')
render(<ExifDetails media={media} />)
// India Standard Time with +05:30 offset, no abbreviation
expect(screen.getByText(/Jun 1, 2023.*4:45:12 PM.*\+05:30$/)).toBeInTheDocument()
})
test('formats RFC3339 UTC with Z suffix', () => {
const media = createMediaWithDateShot('2023-05-10T12:00:00Z')
render(<ExifDetails media={media} />)
// Should show UTC offset but no abbreviation
expect(screen.getByText(/May 10, 2023.*12:00:00 PM.*\+00:00$/)).toBeInTheDocument()
})
test('formats RFC3339 with +0000 format', () => {
const media = createMediaWithDateShot('2023-01-01T12:00:00+0000')
render(<ExifDetails media={media} />)
// Should detect +0000 as timezone and show +00:00 offset
expect(screen.getByText(/Jan 1, 2023.*12:00:00 PM.*\+00:00$/)).toBeInTheDocument()
})
})
describe('RFC3339 without timezone - no offset should be shown', () => {
test('formats RFC3339 without timezone shows only date and time', () => {
const media = createMediaWithDateShot('2023-08-25T18:45:30')
render(<ExifDetails media={media} />)
expect(screen.getByText('Date shot')).toBeInTheDocument()
// Should show only date and time, no timezone info
expect(screen.getByText(/^Aug 25, 2023 6:45:30 PM$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
})
test('formats RFC3339 with milliseconds but no timezone', () => {
const media = createMediaWithDateShot('2023-03-20T09:30:15.123')
render(<ExifDetails media={media} />)
// Should show only date and time, no timezone info
expect(screen.getByText(/^Mar 20, 2023 9:30:15 AM$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
})
test('handles trimming of whitespace in dateShot', () => {
const media = createMediaWithDateShot(' 2023-04-10T15:20:00 ')
render(<ExifDetails media={media} />)
// Should trim whitespace and format correctly without timezone
expect(screen.getByText(/^Apr 10, 2023 3:20:00 PM$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
})
})
describe('Translation language-based formatting', () => {
const mockUseTranslationWithLanguage = (language: string) => {
mockUseTranslation.mockReturnValue({
t: (key: string, defaultValue: string) => defaultValue,
i18n: { language },
})
}
afterEach(() => {
mockUseTranslation.mockReturnValue({
t: (key: string, defaultValue: string) => defaultValue,
i18n: { language: 'en' },
})
})
test('uses English (en) translation language', () => {
mockUseTranslationWithLanguage('en')
const mediaWithTz = createMediaWithDateShot('2023-11-05T15:20:10+01:00')
const { rerender } = render(<ExifDetails media={mediaWithTz} />)
// English locale DATE_MED format with timezone
expect(screen.getByText(/Nov 5, 2023.*3:20:10 PM.*\+01:00$/)).toBeInTheDocument()
// Test without timezone - should use English formatting but no timezone
const mediaNoTz = createMediaWithDateShot('2023-11-05T15:20:10')
rerender(<ExifDetails media={mediaNoTz} />)
expect(screen.getByText(/^Nov 5, 2023 3:20:10 PM$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
})
test('uses German (de) translation language', () => {
mockUseTranslationWithLanguage('de')
const mediaWithTz = createMediaWithDateShot('2023-11-05T15:20:10+01:00')
const { rerender } = render(<ExifDetails media={mediaWithTz} />)
// German locale DATE_MED format with timezone
expect(screen.getByText(/5\. Nov\. 2023.*15:20:10.*\+01:00$/)).toBeInTheDocument()
// Test without timezone - should use German formatting but no timezone
const mediaNoTz = createMediaWithDateShot('2023-11-05T15:20:10')
rerender(<ExifDetails media={mediaNoTz} />)
expect(screen.getByText(/^5\. Nov\. 2023 15:20:10$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
})
test('uses French (fr) translation language', () => {
mockUseTranslationWithLanguage('fr')
const mediaWithTz = createMediaWithDateShot('2023-12-25T20:45:30+01:00')
const { rerender } = render(<ExifDetails media={mediaWithTz} />)
// French DATE_MED format with timezone
expect(screen.getByText(/25 déc\. 2023.*20:45:30.*\+01:00$/)).toBeInTheDocument()
// Test without timezone
const mediaNoTz = createMediaWithDateShot('2023-12-25T20:45:30')
rerender(<ExifDetails media={mediaNoTz} />)
expect(screen.getByText(/^25 déc\. 2023 20:45:30$/)).toBeInTheDocument()
})
test('uses Spanish (es) translation language', () => {
mockUseTranslationWithLanguage('es')
const media = createMediaWithDateShot('2023-07-20T14:15:30-05:00')
render(<ExifDetails media={media} />)
// Spanish locale formatting with timezone
expect(screen.getByText(/20 jul 2023.*14:15:30.*-05:00$/)).toBeInTheDocument()
})
test('uses Danish (da) translation language', () => {
mockUseTranslationWithLanguage('da')
const media = createMediaWithDateShot('2023-06-15T12:30:45+02:00')
render(<ExifDetails media={media} />)
// Danish locale formatting with timezone
expect(screen.getByText(/15\. jun\. 2023 12\.30\.45 \+02:00$/)).toBeInTheDocument()
})
test('uses Italian (it) translation language', () => {
mockUseTranslationWithLanguage('it')
const media = createMediaWithDateShot('2023-09-10T11:20:15+02:00')
render(<ExifDetails media={media} />)
// Italian locale formatting with timezone
expect(screen.getByText(/10 set 2023.*11:20:15.*\+02:00$/)).toBeInTheDocument()
})
test('uses Portuguese (pt) translation language', () => {
mockUseTranslationWithLanguage('pt')
const media = createMediaWithDateShot('2023-09-10T11:20:15-03:00')
render(<ExifDetails media={media} />)
// Portuguese locale formatting with timezone
expect(screen.getByText(/10 de set\. de 2023.*11:20:15.*-03:00$/)).toBeInTheDocument()
})
test('uses Polish (pl) translation language', () => {
mockUseTranslationWithLanguage('pl')
const media = createMediaWithDateShot('2023-08-12T16:00:00+02:00')
render(<ExifDetails media={media} />)
// Polish locale formatting with timezone
expect(screen.getByText(/12 sie 2023.*16:00:00.*\+02:00$/)).toBeInTheDocument()
})
test('uses Ukrainian (uk) translation language', () => {
mockUseTranslationWithLanguage('uk')
const media = createMediaWithDateShot('2023-08-12T16:00:00+03:00')
render(<ExifDetails media={media} />)
// Ukrainian locale formatting with timezone
expect(screen.getByText(/12 серп\. 2023.*16:00:00.*\+03:00$/)).toBeInTheDocument()
})
test('uses Swedish (sv) translation language', () => {
mockUseTranslationWithLanguage('sv')
const media = createMediaWithDateShot('2023-05-15T14:30:00+02:00')
render(<ExifDetails media={media} />)
// Swedish locale formatting with timezone
expect(screen.getByText(/15 maj 2023.*14:30:00.*\+02:00$/)).toBeInTheDocument()
})
test('uses Japanese (ja) translation language', () => {
mockUseTranslationWithLanguage('ja')
const media = createMediaWithDateShot('2023-04-12T08:15:45-07:00')
render(<ExifDetails media={media} />)
// Japanese locale formatting with timezone
expect(screen.getByText(/2023年4月12日.*8:15:45.*-07:00$/)).toBeInTheDocument()
})
test('uses Basque (eu) translation language', () => {
mockUseTranslationWithLanguage('eu')
const media = createMediaWithDateShot('2023-03-20T10:30:00+01:00')
render(<ExifDetails media={media} />)
// Basque locale formatting with timezone
expect(screen.getByText(/2023.*mar.*20.*10:30:00.*\+01:00$/)).toBeInTheDocument()
})
test('handles invalid translation language gracefully', () => {
mockUseTranslationWithLanguage('invalid-locale')
const media = createMediaWithDateShot('2023-05-15T14:30:00+01:00')
render(<ExifDetails media={media} />)
// Should fall back gracefully and still format the date
expect(screen.getByText('Date shot')).toBeInTheDocument()
expect(screen.getByText(/May 15, 2023.*2:30:00 PM.*\+01:00$/)).toBeInTheDocument()
})
test('handles empty string translation language', () => {
mockUseTranslationWithLanguage('')
const media = createMediaWithDateShot('2023-01-15T12:00:00-05:00')
render(<ExifDetails media={media} />)
// Should handle empty string gracefully
expect(screen.getByText('Date shot')).toBeInTheDocument()
expect(screen.getByText(/Jan 15, 2023.*12:00:00 PM.*-05:00$/)).toBeInTheDocument()
})
test('uses Russian (ru) translation language', () => {
mockUseTranslationWithLanguage('ru')
const media = createMediaWithDateShot('2023-02-23T12:15:30+03:00')
render(<ExifDetails media={media} />)
// Russian locale formatting with timezone
expect(screen.getByText(/23 февр\. 2023.*12:15:30.*\+03:00$/)).toBeInTheDocument()
})
test('uses Traditional Chinese Hong Kong (zh-HK) translation language', () => {
mockUseTranslationWithLanguage('zh-HK')
const media = createMediaWithDateShot('2023-10-01T15:30:00+08:00')
render(<ExifDetails media={media} />)
// Traditional Chinese HK locale formatting with timezone
expect(screen.getByText(/2023年10月1日 下午3:30:00 \+08:00$/)).toBeInTheDocument()
})
test('uses Traditional Chinese Taiwan (zh-TW) translation language', () => {
mockUseTranslationWithLanguage('zh-TW')
const media = createMediaWithDateShot('2023-10-10T16:45:00+08:00')
render(<ExifDetails media={media} />)
// Traditional Chinese TW locale formatting with timezone
expect(screen.getByText(/2023年10月10日 下午4:45:00 \+08:00$/)).toBeInTheDocument()
})
test('uses Simplified Chinese (zh-CN) translation language', () => {
mockUseTranslationWithLanguage('zh-CN')
const media = createMediaWithDateShot('2023-10-01T15:30:00+08:00')
render(<ExifDetails media={media} />)
// Simplified Chinese locale formatting with timezone
expect(screen.getByText(/2023年10月1日.*15:30:00.*\+08:00$/)).toBeInTheDocument()
})
test('uses Turkish (tr) translation language', () => {
mockUseTranslationWithLanguage('tr')
const media = createMediaWithDateShot('2023-05-19T13:45:25+03:00')
render(<ExifDetails media={media} />)
// Turkish locale formatting with timezone
expect(screen.getByText(/19 May 2023.*13:45:25.*\+03:00$/)).toBeInTheDocument()
})
})
describe('Timezone detection edge cases', () => {
test('detects various timezone formats correctly with regex', () => {
const testCases = [
{ input: '2023-01-01T12:00:00+0000', shouldHaveTz: true }, // +HHMM format
{ input: '2023-01-01T12:00:00-05:00', shouldHaveTz: true }, // -HH:MM format
{ input: '2023-01-01T12:00:00Z', shouldHaveTz: true }, // Z format
{ input: '2023-01-01T12:00:00z', shouldHaveTz: true }, // lowercase z
{ input: '2023-01-01T12:00:00+1400', shouldHaveTz: true }, // +HHMM max offset
{ input: '2023-01-01T12:00:00', shouldHaveTz: false }, // No timezone
{ input: '2023-01-01T12:00:00.123', shouldHaveTz: false }, // Milliseconds, no timezone
{ input: '2023-01-01T12:00:00.456789', shouldHaveTz: false }, // Microseconds, no timezone
]
testCases.forEach(({ input, shouldHaveTz }, index) => {
const media = createMediaWithDateShot(input)
const { rerender } = render(<ExifDetails media={media} />)
if (shouldHaveTz) {
expect(screen.getByText(/[+-]\d{2}:\d{2}$/)).toBeInTheDocument()
} else {
expect(screen.getByText(/^\w+ \d+, \d+ \d+:\d+:\d+ [AP]M$/)).toBeInTheDocument()
expect(screen.queryByText(/[+-]\d{2}:\d{2}/)).not.toBeInTheDocument()
}
if (index < testCases.length - 1) {
rerender(<div />)
}
})
})
test('handles edge case timezone offsets', () => {
const testCases = [
{ input: '2023-01-01T12:00:00+14:00', expected: /Jan 1, 2023.*12:00:00 PM.*\+14:00$/ }, // Max positive
{ input: '2023-01-01T12:00:00-12:00', expected: /Jan 1, 2023.*12:00:00 PM.*-12:00$/ }, // Max negative
{ input: '2023-01-01T12:00:00+05:45', expected: /Jan 1, 2023.*12:00:00 PM.*\+05:45$/ }, // Nepal time
{ input: '2023-01-01T12:00:00+09:30', expected: /Jan 1, 2023.*12:00:00 PM.*\+09:30$/ }, // Adelaide
]
testCases.forEach(({ input, expected }, index) => {
const media = createMediaWithDateShot(input)
const { rerender } = render(<ExifDetails media={media} />)
expect(screen.getByText(expected)).toBeInTheDocument()
if (index < testCases.length - 1) {
rerender(<div />)
}
})
})
})
describe('Error handling and robustness', () => {
test('handles invalid dateShot gracefully', () => {
const media = createMediaWithDateShot('invalid-date-string')
render(<ExifDetails media={media} />)
// Should display the original invalid string when parsing fails
expect(screen.getByText('invalid-date-string')).toBeInTheDocument()
})
test('handles malformed but parseable dates', () => {
// Test dates that might be malformed but still parseable
const testCases = [
'2023-02-29T10:00:00', // Invalid leap year date
'2023-13-01T10:00:00', // Invalid month
'2023-01-32T10:00:00', // Invalid day
]
testCases.forEach((input, index) => {
const media = createMediaWithDateShot(input)
const { rerender } = render(<ExifDetails media={media} />)
// Should show original string if invalid
expect(screen.getByText('Date shot')).toBeInTheDocument()
expect(screen.getByText(input)).toBeInTheDocument()
if (index < testCases.length - 1) {
rerender(<div />)
}
})
})
})
describe('Format consistency validation', () => {
test('always follows consistent format structure', () => {
const testCases = [
{ input: '2023-04-10T15:20:25-07:00', pattern: /^Apr 10, 2023 3:20:25 PM -07:00$/ },
{ input: '2023-04-10T15:20:25', pattern: /^Apr 10, 2023 3:20:25 PM$/ },
{ input: '2023-04-10T15:20:25Z', pattern: /^Apr 10, 2023 3:20:25 PM \+00:00$/ },
]
testCases.forEach(({ input, pattern }, index) => {
const media = createMediaWithDateShot(input)
const { rerender } = render(<ExifDetails media={media} />)
expect(screen.getByText(pattern)).toBeInTheDocument()
if (index < testCases.length - 1) {
rerender(<div />)
}
})
})
})
})
@@ -0,0 +1,242 @@
import React from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
import { isNil } from '../../../helpers/utils'
import { TranslationFn } from '../../../localization'
import SidebarItem from '../SidebarItem'
import { MediaSidebarMedia } from './MediaSidebar'
import { DateTime } from 'luxon'
const MetadataInfoContainer = styled.div`
margin-bottom: 1.5rem;
`
type ExifDetailsProps = {
media?: MediaSidebarMedia
}
const ExifDetails = ({ media }: ExifDetailsProps) => {
const { t, i18n } = useTranslation()
let exifItems: JSX.Element[] = []
const exifName = exifNameLookup(t)
if (media?.exif) {
const mediaExif = media?.exif as unknown as {
[key: string]: string | number | null
}
const exifKeys = Object.keys(exifName).filter(
x => mediaExif[x] !== null && x != '__typename'
)
const exif = exifKeys.reduce((prev, curr) => {
const value = mediaExif[curr]
if (isNil(value)) return prev
return {
...prev,
[curr]: value,
}
}, {} as { [key: string]: string | number })
if (exif.dateShot && String(exif.dateShot).trim().length > 0) {
exif.dateShot = String(exif.dateShot).trim();
const dateString = String(exif.dateShot);
// Parse as ISO (RFC3339 is a subset of ISO8601)
const dt = DateTime.fromISO(dateString, { setZone: true });
if (dt.isValid) {
// Format date and time parts in user's translation locale, but as "naive" (no shifting)
const dtLocalized = dt.setLocale(i18n.language);
const localeDate = dtLocalized.toLocaleString(DateTime.DATE_MED);
const localeTime = dtLocalized.toLocaleString(DateTime.TIME_WITH_SECONDS);
// Check if the original string contains timezone information
const hasTimezone = /(?:[zZ]|[+-]\d{2}:\d{2}|[+-]\d{4})$/.test(dateString);
if (hasTimezone) {
// Get the offset in ±HH:MM
const offset = dt.toFormat('ZZ');
exif.dateShot = `${localeDate} ${localeTime} ${offset}`;
} else {
// No timezone in original - show only date and time
exif.dateShot = `${localeDate} ${localeTime}`;
}
}
}
if (typeof exif.exposure === 'number' && exif.exposure !== 0) {
exif.exposure = `1/${Math.round(1 / exif.exposure)}`
}
const coords = media.exif.coordinates
if (!isNil(coords)) {
exif.coordinates =
`${Math.round(coords.latitude * 1000000) / 1000000}, ${Math.round(coords.longitude * 1000000) / 1000000}`
}
const exposurePrograms = exposureProgramsLookup(t)
if (
typeof exif.exposureProgram === 'number' &&
exposurePrograms[exif.exposureProgram]
) {
exif.exposureProgram = exposurePrograms[exif.exposureProgram]
} else if (exif.exposureProgram !== 0) {
delete exif.exposureProgram
}
if (!isNil(exif.aperture)) {
exif.aperture = `f/${exif.aperture}`
}
if (!isNil(exif.focalLength)) {
exif.focalLength = `${exif.focalLength}mm`
}
const flash = flashLookup(t)
if (typeof exif.flash === 'number' && flash[exif.flash]) {
exif.flash = flash[exif.flash]
}
exifItems = exifKeys.map(key => (
<SidebarItem key={key} name={exifName[key]} value={exif[key] as string} />
))
}
let videoMetadataItems: JSX.Element[] = []
if (media?.videoMetadata) {
const videoMetadata = media.videoMetadata as unknown as {
[key: string]: string | number | null
}
let metadata = Object.keys(videoMetadata)
.filter(x => !['id', '__typename', 'width', 'height'].includes(x))
.reduce((prev, curr) => {
const value = videoMetadata[curr]
if (isNil(value)) return prev
return {
...prev,
[curr]: value,
}
}, {} as { [key: string]: string | number })
metadata = {
dimensions: `${media.videoMetadata.width}x${media.videoMetadata.height}`,
...metadata,
}
videoMetadataItems = Object.keys(metadata).map(key => (
<SidebarItem key={key} name={key} value={metadata[key] as string} />
))
}
return (
<div>
<MetadataInfoContainer>{videoMetadataItems}</MetadataInfoContainer>
<MetadataInfoContainer>{exifItems}</MetadataInfoContainer>
</div>
)
}
const exifNameLookup = (t: TranslationFn): { [key: string]: string } => ({
description: t('sidebar.media.exif.description', 'Description'),
camera: t('sidebar.media.exif.name.camera', 'Camera'),
maker: t('sidebar.media.exif.name.maker', 'Maker'),
lens: t('sidebar.media.exif.name.lens', 'Lens'),
exposureProgram: t('sidebar.media.exif.name.exposure_program', 'Program'),
dateShot: t('sidebar.media.exif.name.date_shot', 'Date shot'),
exposure: t('sidebar.media.exif.name.exposure', 'Exposure'),
aperture: t('sidebar.media.exif.name.aperture', 'Aperture'),
iso: t('sidebar.media.exif.name.iso', 'ISO'),
focalLength: t('sidebar.media.exif.name.focal_length', 'Focal length'),
flash: t('sidebar.media.exif.name.flash', 'Flash'),
coordinates: t('sidebar.media.exif.name.coordinates', 'Coordinates'),
})
// From https://exiftool.org/TagNames/EXIF.html
const exposureProgramsLookup = (
t: TranslationFn
): { [key: number]: string } => ({
0: t('sidebar.media.exif.exposure_program.not_defined', 'Not defined'),
1: t('sidebar.media.exif.exposure_program.manual', 'Manual'),
2: t('sidebar.media.exif.exposure_program.normal_program', 'Normal program'),
3: t(
'sidebar.media.exif.exposure_program.aperture_priority',
'Aperture priority'
),
4: t(
'sidebar.media.exif.exposure_program.shutter_priority',
'Shutter priority'
),
5: t(
'sidebar.media.exif.exposure_program.creative_program',
'Creative program'
),
6: t('sidebar.media.exif.exposure_program.action_program', 'Action program'),
7: t('sidebar.media.exif.exposure_program.portrait_mode', 'Portrait mode'),
8: t('sidebar.media.exif.exposure_program.landscape_mode', 'Landscape mode'),
9: t('sidebar.media.exif.exposure_program.bulb', 'Bulb'),
})
// From https://exiftool.org/TagNames/EXIF.html#Flash
const flashLookup = (t: TranslationFn): { [key: number]: string } => {
const values = {
no_flash: t('sidebar.media.exif.flash.no_flash', 'No Flash'),
fired: t('sidebar.media.exif.flash.fired', 'Fired'),
did_not_fire: t('sidebar.media.exif.flash.did_not_fire', 'Did not fire'),
on: t('sidebar.media.exif.flash.on', 'On'),
off: t('sidebar.media.exif.flash.off', 'Off'),
auto: t('sidebar.media.exif.flash.auto', 'Auto'),
return_not_detected: t(
'sidebar.media.exif.flash.return_not_detected',
'Return not detected'
),
return_detected: t(
'sidebar.media.exif.flash.return_detected',
'Return detected'
),
no_flash_function: t(
'sidebar.media.exif.flash.no_flash_function',
'No flash function'
),
red_eye_reduction: t(
'sidebar.media.exif.flash.red_eye_reduction',
'Red-eye reduction'
),
}
return {
0x0: values['no_flash'],
0x1: values['fired'],
0x5: `${values['fired']}, ${values['return_not_detected']}`,
0x7: `${values['fired']}, ${values['return_detected']}`,
0x8: `${values['on']}, ${values['did_not_fire']}`,
0x9: `${values['on']}, ${values['fired']}`,
0xd: `${values['on']}, ${values['return_not_detected']}`,
0xf: `${values['on']}, ${values['return_detected']}`,
0x10: `${values['off']}, ${values['did_not_fire']}`,
0x14: `${values['off']}, ${values['did_not_fire']}, ${values['return_not_detected']}`,
0x18: `${values['auto']}, ${values['did_not_fire']}`,
0x19: `${values['auto']}, ${values['fired']}`,
0x1d: `${values['auto']}, ${values['fired']}, ${values['return_not_detected']}`,
0x1f: `${values['auto']}, ${values['fired']}, ${values['return_detected']}`,
0x20: `${values['no_flash_function']}`,
0x30: `${values['off']}, ${values['no_flash_function']}`,
0x41: `${values['fired']}, ${values['red_eye_reduction']}`,
0x45: `${values['fired']}, ${values['red_eye_reduction']}, ${values['return_not_detected']}`,
0x47: `${values['fired']}, ${values['red_eye_reduction']}, ${values['return_detected']}`,
0x49: `${values['on']}, ${values['red_eye_reduction']}`,
0x4d: `${values['on']}, ${values['red_eye_reduction']}, ${values['return_not_detected']}`,
0x4f: `${values['on']}, ${values['red_eye_reduction']}, ${values['return_detected']}`,
0x50: `${values['off']}, ${values['red_eye_reduction']}`,
0x58: `${values['auto']}, ${values['did_not_fire']}, ${values['red_eye_reduction']}`,
0x59: `${values['auto']}, ${values['fired']}, ${values['red_eye_reduction']}`,
0x5d: `${values['auto']}, ${values['red_eye_reduction']}, ${values['return_not_detected']}`,
0x5f: `${values['auto']}, ${values['red_eye_reduction']}, ${values['return_detected']}`,
}
}
export default ExifDetails
@@ -0,0 +1,56 @@
import React from 'react'
import { useTranslation } from 'react-i18next'
import { isNil } from '../../../helpers/utils'
import useMapboxMap from '../../mapbox/MapboxMap'
import { SidebarSection, SidebarSectionTitle } from '../SidebarComponents'
import { sidebarMediaQuery_media_exif_coordinates } from './__generated__/sidebarMediaQuery'
type MediaSidebarMapProps = {
coordinates: sidebarMediaQuery_media_exif_coordinates
}
const MediaSidebarMap = ({ coordinates }: MediaSidebarMapProps) => {
const { t } = useTranslation()
const { mapContainer, mapboxToken } = useMapboxMap({
mapboxOptions: {
interactive: false,
zoom: 12,
center: {
lat: coordinates.latitude,
lng: coordinates.longitude,
},
},
configureMapbox: (map, mapboxLibrary) => {
// todo
map.addControl(
new mapboxLibrary.NavigationControl({ showCompass: false })
)
const centerMarker = new mapboxLibrary.Marker({
color: 'red',
scale: 0.8,
})
centerMarker.setLngLat({
lat: coordinates.latitude,
lng: coordinates.longitude,
})
centerMarker.addTo(map)
},
})
if (isNil(mapboxToken)) {
return null
}
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.location.title', 'Location')}
</SidebarSectionTitle>
<div className="w-full h-64">{mapContainer}</div>
</SidebarSection>
)
}
export default MediaSidebarMap
@@ -0,0 +1,218 @@
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from 'react-router-dom'
import FaceCircleImage from '../../../Pages/PeoplePage/FaceCircleImage'
import { SidebarSection, SidebarSectionTitle } from '../SidebarComponents'
import { MediaSidebarMedia, SIDEBAR_MEDIA_QUERY } from './MediaSidebar'
import { sidebarMediaQuery_media_faces } from './__generated__/sidebarMediaQuery'
import { ReactComponent as PeopleDotsIcon } from './icons/peopleDotsIcon.svg'
import { Menu } from '@headlessui/react'
import { Button } from '../../../primitives/form/Input'
import { ArrowPopoverPanel } from '../Sharing'
import { isNil, tailwindClassNames } from '../../../helpers/utils'
import MergeFaceGroupsModal, {
MergeFaceGroupsModalState,
} from '../../../Pages/PeoplePage/SingleFaceGroup/MergeFaceGroupsModal'
import { useDetachImageFaces } from '../../../Pages/PeoplePage/SingleFaceGroup/DetachImageFacesModal'
import MoveImageFacesModal from '../../../Pages/PeoplePage/SingleFaceGroup/MoveImageFacesModal'
import { FaceDetails } from '../../../Pages/PeoplePage/PeoplePage'
type PersonMoreMenuItemProps = {
label: string
className?: string
onClick(): void
}
const PersonMoreMenuItem = ({
label,
className,
onClick,
}: PersonMoreMenuItemProps) => {
return (
<Menu.Item>
{({ active }) => (
<button
onClick={onClick}
className={tailwindClassNames(
`whitespace-normal w-full block py-1 cursor-pointer ${
active ? 'bg-gray-50 text-black' : 'text-gray-700'
}`,
className
)}
>
{label}
</button>
)}
</Menu.Item>
)
}
type PersonMoreMenuProps = {
face: sidebarMediaQuery_media_faces
setChangeLabel: React.Dispatch<React.SetStateAction<boolean>>
className?: string
menuFlipped: boolean
}
const PersonMoreMenu = ({
menuFlipped,
face,
setChangeLabel,
className,
}: PersonMoreMenuProps) => {
const { t } = useTranslation()
const [mergeModalState, setMergeModalState] = useState(
MergeFaceGroupsModalState.Closed
)
const [moveModalOpen, setMoveModalOpen] = useState(false)
const refetchQueries = [
{
query: SIDEBAR_MEDIA_QUERY,
variables: {
id: face.media.id,
},
},
]
const navigate = useNavigate()
const detachImageFaceMutation = useDetachImageFaces({
refetchQueries,
})
const modals = (
<>
<MergeFaceGroupsModal
preselectedDestinationFaceGroup={face.faceGroup}
state={mergeModalState}
setState={setMergeModalState}
refetchQueries={refetchQueries}
/>
<MoveImageFacesModal
faceGroup={{ imageFaces: [], ...face.faceGroup }}
open={moveModalOpen}
setOpen={setMoveModalOpen}
preselectedImageFaces={[face]}
/>
</>
)
const detachImageFace = () => {
if (
!confirm(
t(
'sidebar.people.confirm_image_detach',
'Are you sure you want to detach this image?'
)
)
)
return
detachImageFaceMutation([face]).then(({ data }) => {
if (isNil(data)) throw new Error('Expected data not to be null')
navigate(`/people/${data.detachImageFaces.id}`)
})
}
return (
<>
<Menu
as="div"
className={tailwindClassNames('relative inline-block', className)}
>
<Menu.Button as={Button} className="px-1.5 py-1.5 align-middle ml-1">
<PeopleDotsIcon className="text-gray-500" />
</Menu.Button>
<Menu.Items className="">
<ArrowPopoverPanel width={120} flipped={menuFlipped}>
<PersonMoreMenuItem
onClick={() => setChangeLabel(true)}
className="border-b"
label={t('people_page.action_label.change_label', 'Change label')}
/>
<PersonMoreMenuItem
onClick={() =>
setMergeModalState(MergeFaceGroupsModalState.SelectDestination)
}
className="border-b"
label={t('sidebar.people.action_label.merge_face', 'Merge face')}
/>
<PersonMoreMenuItem
onClick={() => detachImageFace()}
className="border-b"
label={t(
'sidebar.people.action_label.detach_image',
'Detach image'
)}
/>
<PersonMoreMenuItem
onClick={() => setMoveModalOpen(true)}
label={t('sidebar.people.action_label.move_face', 'Move face')}
/>
</ArrowPopoverPanel>
</Menu.Items>
</Menu>
{modals}
</>
)
}
type MediaSidebarFaceProps = {
face: sidebarMediaQuery_media_faces
menuFlipped: boolean
}
const MediaSidebarPerson = ({ face, menuFlipped }: MediaSidebarFaceProps) => {
const [changeLabel, setChangeLabel] = useState(false)
return (
<li className="flex flex-col items-center">
<Link to={`/people/${face.faceGroup.id}`}>
<FaceCircleImage imageFace={face} selectable={true} size="92px" />
</Link>
<div className="mt-1 whitespace-nowrap">
<FaceDetails
className="text-sm max-w-[80px] align-middle"
textFieldClassName="w-[100px]"
group={face.faceGroup}
editLabel={changeLabel}
setEditLabel={setChangeLabel}
/>
{!changeLabel && (
<PersonMoreMenu
menuFlipped={menuFlipped}
className="pl-0.5"
face={face}
setChangeLabel={setChangeLabel}
/>
)}
</div>
</li>
)
}
type MediaSidebarFacesProps = {
media: MediaSidebarMedia
}
const MediaSidebarPeople = ({ media }: MediaSidebarFacesProps) => {
const { t } = useTranslation()
const faceElms = (media.faces ?? []).map((face, i) => (
<MediaSidebarPerson key={face.id} face={face} menuFlipped={i % 3 == 0} />
))
if (faceElms.length == 0) return null
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.people.title', 'People')}
</SidebarSectionTitle>
<ul className="grid grid-cols-3 gap-4 px-4">{faceElms}</ul>
</SidebarSection>
)
}
export default MediaSidebarPeople
@@ -0,0 +1,257 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
import { MediaType } from "./../../../../__generated__/globalTypes";
// ====================================================
// GraphQL query operation: sidebarMediaQuery
// ====================================================
export interface sidebarMediaQuery_media_highRes {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface sidebarMediaQuery_media_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface sidebarMediaQuery_media_videoWeb {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface sidebarMediaQuery_media_videoMetadata {
__typename: "VideoMetadata";
id: string;
width: number;
height: number;
duration: number;
codec: string | null;
framerate: number | null;
bitrate: string | null;
colorProfile: string | null;
audio: string | null;
}
export interface sidebarMediaQuery_media_exif_coordinates {
__typename: "Coordinates";
/**
* GPS latitude in degrees
*/
latitude: number;
/**
* GPS longitude in degrees
*/
longitude: number;
}
export interface sidebarMediaQuery_media_exif {
__typename: "MediaEXIF";
id: string;
/**
* The description of the image
*/
description: string | null;
/**
* The model name of the camera
*/
camera: string | null;
/**
* The maker of the camera
*/
maker: string | null;
/**
* The name of the lens
*/
lens: string | null;
/**
* The date when the photo is shot
*/
dateShot: string | null;
/**
* The exposure time of the image
*/
exposure: number | null;
/**
* The aperature stops of the image
*/
aperture: number | null;
/**
* The ISO setting of the image
*/
iso: number | null;
/**
* The focal length of the lens, when the image was taken
*/
focalLength: number | null;
/**
* A formatted description of the flash settings, when the image was taken
*/
flash: number | null;
/**
* An index describing the mode for adjusting the exposure of the image
*/
exposureProgram: number | null;
/**
* GPS coordinates of where the image was taken
*/
coordinates: sidebarMediaQuery_media_exif_coordinates | null;
}
export interface sidebarMediaQuery_media_album_path {
__typename: "Album";
id: string;
title: string;
}
export interface sidebarMediaQuery_media_album {
__typename: "Album";
id: string;
title: string;
/**
* A breadcrumb list of all parent albums down to this one
*/
path: sidebarMediaQuery_media_album_path[];
}
export interface sidebarMediaQuery_media_faces_rectangle {
__typename: "FaceRectangle";
minX: number;
maxX: number;
minY: number;
maxY: number;
}
export interface sidebarMediaQuery_media_faces_faceGroup {
__typename: "FaceGroup";
id: string;
/**
* The name of the person
*/
label: string | null;
/**
* The total number of images in this collection
*/
imageFaceCount: number;
}
export interface sidebarMediaQuery_media_faces_media_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
}
export interface sidebarMediaQuery_media_faces_media {
__typename: "Media";
id: string;
title: string;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: sidebarMediaQuery_media_faces_media_thumbnail | null;
}
export interface sidebarMediaQuery_media_faces {
__typename: "ImageFace";
id: string;
/**
* A bounding box of where on the image the face is present
*/
rectangle: sidebarMediaQuery_media_faces_rectangle;
/**
* The `FaceGroup` that contains this `ImageFace`
*/
faceGroup: sidebarMediaQuery_media_faces_faceGroup;
/**
* A reference to the image the face appears on
*/
media: sidebarMediaQuery_media_faces_media;
}
export interface sidebarMediaQuery_media {
__typename: "Media";
id: string;
title: string;
type: MediaType;
/**
* URL to display the photo in full resolution, will be null for videos
*/
highRes: sidebarMediaQuery_media_highRes | null;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: sidebarMediaQuery_media_thumbnail | null;
/**
* URL to get the video in a web format that can be played in the browser, will be null for photos
*/
videoWeb: sidebarMediaQuery_media_videoWeb | null;
videoMetadata: sidebarMediaQuery_media_videoMetadata | null;
exif: sidebarMediaQuery_media_exif | null;
/**
* The album that holds the media
*/
album: sidebarMediaQuery_media_album;
/**
* A list of faces present on the image
*/
faces: sidebarMediaQuery_media_faces[];
}
export interface sidebarMediaQuery {
/**
* Get media by id, user must own the media or be admin.
* If valid tokenCredentials are provided, the media may be retrived without further authentication
*/
media: sidebarMediaQuery_media;
}
export interface sidebarMediaQueryVariables {
id: string;
}
@@ -0,0 +1,3 @@
<svg width="12px" height="3px" viewBox="0 0 8 2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M1,0 C1.55228475,0 2,0.44771525 2,1 C2,1.55228475 1.55228475,2 1,2 C0.44771525,2 0,1.55228475 0,1 C0,0.44771525 0.44771525,0 1,0 Z M4,0 C4.55228475,0 5,0.44771525 5,1 C5,1.55228475 4.55228475,2 4,2 C3.44771525,2 3,1.55228475 3,1 C3,0.44771525 3.44771525,0 4,0 Z M7,0 C7.55228475,0 8,0.44771525 8,1 C8,1.55228475 7.55228475,2 7,2 C6.44771525,2 6,1.55228475 6,1 C6,0.44771525 6.44771525,0 7,0 Z" fill="currentColor"></path>
</svg>

After

Width:  |  Height:  |  Size: 583 B

+146
View File
@@ -0,0 +1,146 @@
import { vi, describe, test, expect } from 'vitest'
import React from 'react'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { MockedProvider } from '@apollo/client/testing'
import { SidebarAlbumShare, SET_EXPIRE_MUTATION, SHARE_ALBUM_QUERY } from './Sharing'
// =========================================================
// Key modification: Mock this layer directly to bypass js-cookie.
// This prevents the test runner from reading the authentication.ts file,
// avoiding the "Failed to load js-cookie" error.
// =========================================================
vi.mock('../../helpers/authentication', () => ({
authToken: () => 'mock_token',
getSharePassword: () => 'mock_pass',
saveSharePassword: vi.fn(),
clearSharePassword: vi.fn(),
}))
// Mock the translation module to prevent interference
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, fallback: string) => fallback,
i18n: { language: 'en' },
}),
}))
const MOCK_ALBUM_ID = 'album-123'
const MOCK_TOKEN = 'token-abc'
const mockShareNoExpire = {
id: 'share-1',
token: MOCK_TOKEN,
hasPassword: false,
expire: null,
__typename: 'ShareToken'
}
const mockShareWithExpire = {
...mockShareNoExpire,
expire: '2025-01-01T00:00:00Z'
}
const getSharesQueryMock = {
request: {
query: SHARE_ALBUM_QUERY,
variables: { id: MOCK_ALBUM_ID },
},
result: {
data: {
album: {
id: MOCK_ALBUM_ID,
__typename: 'Album',
shares: [mockShareNoExpire],
},
},
},
}
const setExpireMutationMock = {
request: {
query: SET_EXPIRE_MUTATION,
variables: {
token: MOCK_TOKEN,
expire: expect.stringContaining('2026-10-01'),
},
},
result: {
data: {
setExpireShareToken: {
token: MOCK_TOKEN,
__typename: 'ShareToken',
},
},
},
}
const clearExpireMutationMock = {
request: {
query: SET_EXPIRE_MUTATION,
variables: {
token: MOCK_TOKEN,
expire: null,
},
},
result: {
data: {
setExpireShareToken: {
token: MOCK_TOKEN,
__typename: 'ShareToken',
},
},
},
}
describe('Sidebar Sharing Expiration', () => {
test('User can open popover, enable expiration, set date, and save', async () => {
render(
<MockedProvider mocks={[getSharesQueryMock, setExpireMutationMock]} addTypename={false}>
<SidebarAlbumShare id={MOCK_ALBUM_ID} />
</MockedProvider>
)
await waitFor(() => expect(screen.getByText(/Public Link/i)).toBeInTheDocument())
const moreBtn = screen.getByTitle('More')
fireEvent.click(moreBtn)
const checkbox = await screen.findByLabelText(/Expiration date/i)
fireEvent.click(checkbox)
const inputs = screen.getAllByRole('textbox')
// Filter for the enabled input field (the password field is disabled by default)
const dateInput = inputs.find(input => !input.hasAttribute('disabled'))
if (!dateInput) {
throw new Error('Could not find the enabled date input field')
}
// Interact with the input
fireEvent.change(dateInput, { target: { value: '2026-10-01' } })
fireEvent.keyDown(dateInput, { key: 'Enter', code: 'Enter', charCode: 13 })
})
test('User can clear the expiration date by unchecking the box', async () => {
const mockWithExpireData = JSON.parse(JSON.stringify(getSharesQueryMock))
mockWithExpireData.result.data.album.shares = [mockShareWithExpire]
render(
<MockedProvider mocks={[mockWithExpireData, clearExpireMutationMock]} addTypename={false}>
<SidebarAlbumShare id={MOCK_ALBUM_ID} />
</MockedProvider>
)
await waitFor(() => expect(screen.getByText(/Public Link/i)).toBeInTheDocument())
fireEvent.click(screen.getByTitle('More'))
const checkbox = await screen.findByLabelText(/Expiration date/i)
expect(checkbox).toBeChecked()
fireEvent.click(checkbox)
await waitFor(() => expect(checkbox).not.toBeChecked())
})
})
+604
View File
@@ -0,0 +1,604 @@
import React, { useEffect, useState } from 'react'
import {
useMutation,
useQuery,
gql,
useLazyQuery,
DocumentNode,
} from '@apollo/client'
import copy from 'copy-to-clipboard'
import { useTranslation } from 'react-i18next'
import { Popover } from '@headlessui/react'
import {
sidebareDeleteShare,
sidebareDeleteShareVariables,
} from './__generated__/sidebareDeleteShare'
import {
sidebarPhotoAddShare,
sidebarPhotoAddShareVariables,
} from './__generated__/sidebarPhotoAddShare'
import {
sidebarAlbumAddShare,
sidebarAlbumAddShareVariables,
} from './__generated__/sidebarAlbumAddShare'
import {
sidebarGetPhotoShares,
sidebarGetPhotoSharesVariables,
sidebarGetPhotoShares_media_shares,
} from './__generated__/sidebarGetPhotoShares'
import {
sidebarGetAlbumShares,
sidebarGetAlbumSharesVariables,
sidebarGetAlbumShares_album_shares,
} from './__generated__/sidebarGetAlbumShares'
import { authToken } from '../../helpers/authentication'
import { SidebarSection, SidebarSectionTitle } from './SidebarComponents'
import { ReactComponent as LinkIcon } from './icons/shareLinkIcon.svg'
import { ReactComponent as CopyIcon } from './icons/shareCopyIcon.svg'
import { ReactComponent as DeleteIcon } from './icons/shareDeleteIcon.svg'
import { ReactComponent as MoreIcon } from './icons/shareMoreIcon.svg'
import { ReactComponent as AddIcon } from './icons/shareAddIcon.svg'
import Checkbox from '../../primitives/form/Checkbox'
import { TextField } from '../../primitives/form/Input'
import styled from 'styled-components'
import {
sidebarProtectShare,
sidebarProtectShareVariables,
} from './__generated__/sidebarProtectShare'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from 'dayjs'
const SHARE_PHOTO_QUERY = gql`
query sidebarGetPhotoShares($id: ID!) {
media(id: $id) {
id
shares {
id
token
hasPassword
expire
}
}
}
`
export const SHARE_ALBUM_QUERY = gql`
query sidebarGetAlbumShares($id: ID!) {
album(id: $id) {
id
shares {
id
token
hasPassword
expire
}
}
}
`
const ADD_MEDIA_SHARE_MUTATION = gql`
mutation sidebarPhotoAddShare($id: ID!, $password: String, $expire: Time) {
shareMedia(mediaId: $id, password: $password, expire: $expire) {
token
}
}
`
const ADD_ALBUM_SHARE_MUTATION = gql`
mutation sidebarAlbumAddShare($id: ID!, $password: String, $expire: Time) {
shareAlbum(albumId: $id, password: $password, expire: $expire) {
token
}
}
`
const PROTECT_SHARE_MUTATION = gql`
mutation sidebarProtectShare($token: String!, $password: String) {
protectShareToken(token: $token, password: $password) {
token
hasPassword
}
}
`
export const SET_EXPIRE_MUTATION = gql`
mutation sidebarSetExpireShare($token: String!, $expire: Time){
setExpireShareToken(token: $token, expire: $expire){
token
}
}
`
const DELETE_SHARE_MUTATION = gql`
mutation sidebareDeleteShare($token: String!) {
deleteShareToken(token: $token) {
token
}
}
`
export const ArrowPopoverPanel = styled.div.attrs({
className:
'absolute -top-3 bg-white dark:bg-dark-bg rounded shadow-md border border-gray-200 dark:border-dark-border z-10',
}) <{ width: number; flipped?: boolean }>`
width: ${({ width }) => width}px;
${({ flipped }) =>
flipped
? `
left: 32px;
`
: `
right: 24px;
`}
&::after {
content: '';
position: absolute;
top: 18px;
width: 8px;
height: 14px;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 14'%3E%3Cpolyline stroke-width='1' stroke='%23E2E2E2' fill='%23FFFFFF' points='1 0 7 7 1 14'%3E%3C/polyline%3E%3C/svg%3E");
${({ flipped }) =>
flipped
? `
left: -7px;
transform: rotate(180deg);
`
: `
right: -7px;
`}
}
`
type MorePopoverSectionPasswordProps = {
share: sidebarGetAlbumShares_album_shares
query: DocumentNode
id: string
}
const MorePopoverSectionPassword = ({
share,
query,
id,
}: MorePopoverSectionPasswordProps) => {
const [addingPassword, setAddingPassword] = useState(false)
const activated = addingPassword || share.hasPassword
const [passwordInputValue, setPasswordInputValue] = useState(
share.hasPassword ? '**********' : ''
)
const [passwordHidden, setPasswordHidden] = useState(share.hasPassword)
const [setPassword, { loading: setPasswordLoading }] = useMutation<
sidebarProtectShare,
sidebarProtectShareVariables
>(PROTECT_SHARE_MUTATION, {
refetchQueries: [{ query: query, variables: { id } }],
onCompleted: data => {
hidePassword(data.protectShareToken.hasPassword)
},
// refetchQueries: [{ query: query, variables: { id } }],
variables: {
token: share.token,
},
})
const hidePassword = (hide: boolean) => {
if (hide) {
setPasswordInputValue('**********')
}
if (passwordHidden && !hide) {
setPasswordInputValue('')
}
setPasswordHidden(hide)
}
const checkboxChange = () => {
const enable = !activated
setAddingPassword(enable)
if (!enable) {
setPassword({
variables: {
token: share.token,
password: null,
},
})
setPasswordInputValue('')
}
}
const updatePasswordAction = () => {
if (!passwordHidden && passwordInputValue != '') {
setPassword({
variables: {
token: share.token,
password: passwordInputValue,
},
})
}
}
return (
<div className="px-4 py-2">
<Checkbox
label="Password protected"
checked={activated}
onChange={checkboxChange}
/>
<TextField
disabled={!activated}
type={passwordHidden ? 'password' : 'text'}
value={passwordInputValue}
className="w-full"
wrapperClassName="mt-2"
onKeyDown={event => {
if (
event.shiftKey ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.key == 'Enter' ||
event.key == 'Tab' ||
event.key == 'Escape'
) {
return
}
hidePassword(false)
}}
onChange={event => {
setPasswordInputValue(event.target.value)
}}
action={updatePasswordAction}
loading={setPasswordLoading}
/>
</div>
)
}
type MorePopoverSectionExpirationProps = {
share: sidebarGetAlbumShares_album_shares
id: string
query: DocumentNode
}
const MorePopoverSectionExpiration = ({
share,
id,
query,
}: MorePopoverSectionExpirationProps) => {
// Verify whether the backend response includes an expiration time
// Set it to true if share.expire exists; otherwise,set it to false
const [enabled, setEnabled] = useState(!!share.expire)
useEffect(() => {
setEnabled(!!share.expire)
setDate(share.expire ? new Date(share.expire) : null)
}, [share.expire])
const { t, i18n } = useTranslation()
const dateFormatterOptions: Intl.DateTimeFormatOptions = {
year: 'numeric',
month: 'long',
day: 'numeric',
}
const dateFormatter = new Intl.DateTimeFormat(
i18n.language,
dateFormatterOptions
)
const oldExpireDate = share.expire
? dateFormatter.format(new Date(share.expire.slice(0, 19).replace(' ', 'T')))
: '';
const [date, setDate] = useState<Date | null>(
share.expire ? new Date(share.expire) : null
)
const [setExpire, { loading }] = useMutation(SET_EXPIRE_MUTATION, {
refetchQueries: [{ query, variables: { id } }],
})
const submit = () => {
if (!date && enabled) return
const formatDate = date ? dayjs(date).endOf('day').format('YYYY-MM-DDTHH:mm:ss')+'Z' : null
//Save the local time while treating it as UTC.
setExpire({
variables: {
token: share.token,
expire: formatDate,
},
})
}
return (
<div className="px-4 py-2">
<Checkbox
label={t('sidebar.sharing.expiration_date', 'Expiration date')}
checked={enabled}
onChange={() => {
const next = !enabled
setEnabled(next)
if (!next) {
// If the checkbox is unchecked,set the expiration time to null.
setDate(null)
setExpire({
variables: {
token: share.token,
expire: null,
},
})
}
}}
/>
{enabled && (
<div className="mt-2 w-full">
<DatePicker
selected={date}
onChange={setDate}
minDate={new Date()}
placeholderText={oldExpireDate}
value={oldExpireDate}
customInput={
<TextField
fullWidth
action={submit}
loading={loading}
/>
}
/>
</div>
)}
</div>
)
}
type MorePopoverProps = {
id: string
query: DocumentNode
share: sidebarGetAlbumShares_album_shares
}
const MorePopover = ({ id, share, query }: MorePopoverProps) => {
const { t } = useTranslation()
return (
<Popover className="relative">
<Popover.Button
className="align-middle p-1 ml-2"
title={t('sidebar.sharing.more', 'More')}
>
<MoreIcon />
</Popover.Button>
<Popover.Panel>
<ArrowPopoverPanel width={260}>
<MorePopoverSectionPassword id={id} share={share} query={query} />
<MorePopoverSectionExpiration id={id} share={share} query={query} />
</ArrowPopoverPanel>
</Popover.Panel>
</Popover>
)
}
type SidebarShareAlbumProps = {
id: string
}
export const SidebarAlbumShare = ({ id }: SidebarShareAlbumProps) => {
const { t } = useTranslation()
const {
loading: queryLoading,
error: sharesError,
data: sharesData,
} = useQuery<sidebarGetAlbumShares, sidebarGetAlbumSharesVariables>(
SHARE_ALBUM_QUERY,
{ variables: { id } }
)
const [shareAlbum, { loading: mutationLoading }] = useMutation<
sidebarAlbumAddShare,
sidebarAlbumAddShareVariables
>(ADD_ALBUM_SHARE_MUTATION, {
refetchQueries: [{ query: SHARE_ALBUM_QUERY, variables: { id } }],
})
const loading = queryLoading || mutationLoading
if (sharesError) {
return <div>Error: {sharesError.message}</div>
}
if (loading) {
return <div>{t('general.loading.shares', 'Loading shares...')}</div>
}
return (
<SidebarShare
id={id}
isPhoto={false}
loading={loading}
shares={sharesData?.album.shares}
shareItem={shareAlbum}
/>
)
}
type SidebarSharePhotoProps = {
id: string
}
export const SidebarPhotoShare = ({ id }: SidebarSharePhotoProps) => {
const { t } = useTranslation()
const [
loadShares,
{ loading: queryLoading, error: sharesError, data: sharesData },
] = useLazyQuery<sidebarGetPhotoShares, sidebarGetPhotoSharesVariables>(
SHARE_PHOTO_QUERY
)
const [sharePhoto, { loading: mutationLoading }] = useMutation<
sidebarPhotoAddShare,
sidebarPhotoAddShareVariables
>(ADD_MEDIA_SHARE_MUTATION, {
refetchQueries: [{ query: SHARE_PHOTO_QUERY, variables: { id } }],
})
useEffect(() => {
if (authToken()) {
loadShares({
variables: {
id,
},
})
}
}, [])
const loading = queryLoading || mutationLoading
if (sharesError) {
return <div>Error: {sharesError.message}</div>
}
if (loading) {
return <div>{t('general.loading.shares', 'Loading shares...')}</div>
}
return (
<SidebarShare
id={id}
isPhoto={true}
loading={loading}
shares={sharesData?.media.shares}
shareItem={sharePhoto}
/>
)
}
type SidebarShareProps = {
id: string
isPhoto: boolean
loading: boolean
shares?: sidebarGetPhotoShares_media_shares[]
shareItem: (item: { variables: { id: string } }) => Promise<unknown>
}
const SidebarShare = ({
loading,
shares,
isPhoto,
id,
shareItem,
}: SidebarShareProps) => {
const { t } = useTranslation()
const query = isPhoto ? SHARE_PHOTO_QUERY : SHARE_ALBUM_QUERY
const [deleteShare] = useMutation<
sidebareDeleteShare,
sidebareDeleteShareVariables
>(DELETE_SHARE_MUTATION, {
refetchQueries: [{ query: query, variables: { id } }],
})
if (shares === undefined) {
return null
}
const optionsRows = shares.map(share => (
<tr
key={share.token}
className="border-gray-100 dark:border-dark-border2 border-b border-t"
>
<td className="pl-4 py-2 w-full">
<span className="text-[#585858] dark:text-[#C0C3C4] mr-2">
<LinkIcon className="inline-block mr-2" />
<span className="text-xs uppercase font-bold">
{t('sidebar.sharing.public_link', 'Public Link') + ' '}
</span>
</span>
<span className="text-sm">{share.token}</span>
</td>
<td className="pr-6 py-2 whitespace-nowrap text-[#5C6A7F] dark:text-[#7599ca] flex">
<button
className="align-middle p-1 ml-2"
title={t('sidebar.sharing.copy_link', 'Copy Link')}
onClick={() => {
copy(`${location.origin}/share/${share.token}`)
}}
>
<CopyIcon />
</button>
<button
onClick={() => {
deleteShare({ variables: { token: share.token } })
}}
className="align-middle p-1 ml-2 hover:text-red-600 focus:text-red-600"
title={t('sidebar.sharing.delete', 'Delete')}
>
<DeleteIcon />
</button>
<MorePopover share={share} id={id} query={query} />
{/* <ShareItemMoreDropdown share={share} id={id} isPhoto={isPhoto} /> */}
</td>
</tr>
))
if (optionsRows.length == 0) {
optionsRows.push(
<tr
key="no-shares"
className="border-gray-100 dark:border-dark-border2 border-b border-t"
>
<td
colSpan={2}
className="pl-4 py-2 italic text-gray-600 dark:text-gray-300"
>
{t('sidebar.sharing.no_shares_found', 'No shares found')}
</td>
</tr>
)
}
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.sharing.title', 'Sharing options')}
</SidebarSectionTitle>
<div>
<table className="border-collapse w-full">
<tbody>{optionsRows}</tbody>
<tfoot>
<tr className="text-left border-gray-100 dark:border-dark-border2 border-b border-t">
<td colSpan={2} className="pl-4 py-2">
<button
className="text-green-500 font-bold uppercase text-xs"
disabled={loading}
onClick={() => {
shareItem({
variables: {
id,
},
})
}}
>
<AddIcon className="inline-block mr-2" />
<span>{t('sidebar.sharing.add_share', 'Add shares')}</span>
</button>
</td>
</tr>
</tfoot>
</table>
</div>
</SidebarSection>
)
}
+111
View File
@@ -0,0 +1,111 @@
import React, { createContext, useContext, useEffect, useState } from 'react'
export type UpdateSidebarFn = (content: React.ReactNode) => void
export type SidebarPinnedFn = (pin: boolean) => void
interface SidebarContextType {
updateSidebar: UpdateSidebarFn
setPinned: SidebarPinnedFn
content: React.ReactNode
pinned: boolean
}
export const SidebarContext = createContext<SidebarContextType>({
updateSidebar: content => {
console.warn(
'SidebarContext: updateSidebar was called before initialized',
content
)
},
setPinned: content => {
console.warn(
'SidebarContext: setPinned was called before initialized',
content
)
},
content: null,
pinned: false,
})
SidebarContext.displayName = 'SidebarContext'
type SidebarProviderProps = {
children: React.ReactChild | React.ReactChild[]
}
export const SidebarProvider = ({ children }: SidebarProviderProps) => {
const [state, setState] = useState<{
content: React.ReactNode | null
pinned: boolean
}>({
content: null,
pinned: false,
})
const updateSidebar = (content: React.ReactNode | null) => {
if (content) {
setState(state => ({ ...state, content }))
} else {
setState(state => ({ ...state, content: null, pinned: false }))
}
}
const setPinned = (pinned: boolean) => {
setState(state => ({ ...state, pinned }))
}
return (
<SidebarContext.Provider
value={{
updateSidebar,
setPinned,
content: state.content,
pinned: state.pinned,
}}
>
{children}
</SidebarContext.Provider>
)
}
export const Sidebar = () => {
const { content, pinned, updateSidebar } = useContext(SidebarContext)
useEffect(() => {
const body = document.body
if (content == null) {
body.classList.remove('overflow-y-hidden')
body.classList.remove('lg:overflow-y-auto')
} else {
body.classList.add('overflow-y-hidden')
body.classList.add('lg:overflow-y-auto')
}
return () => {
body.classList.remove('overflow-y-hidden')
body.classList.remove('lg:overflow-y-auto')
}
})
return (
<>
{/* Backdrop — tap to close (mobile only) */}
{content && !pinned && (
<div
className="fixed inset-0 bg-black/50 z-30 lg:hidden"
onClick={() => updateSidebar(null)}
/>
)}
<div
className={`fixed top-16 bg-white dark:bg-dark-bg2 dark:border-dark-border2 bottom-0 w-full overflow-y-auto transform transition-transform motion-reduce:transition-none ${
content == null && !pinned ? 'translate-x-full' : 'translate-x-0'
} ${
pinned ? 'lg:border-l' : 'lg:shadow-separator'
} lg:w-[420px] lg:right-0 lg:top-0 lg:z-40`}
>
{content}
<div className="h-24"></div>
</div>
</>
)
}
@@ -0,0 +1,7 @@
import styled from 'styled-components'
export const SidebarSection = styled.div.attrs({ className: 'mb-8' })``
export const SidebarSectionTitle = styled.h2.attrs({
className: 'text-xl mb-2 mx-4',
})``
@@ -0,0 +1,85 @@
import React from 'react'
import { useTranslation } from 'react-i18next'
import { API_ENDPOINT } from '../../apolloClient'
import { SidebarSection, SidebarSectionTitle } from './SidebarComponents'
import SidebarTable from './SidebarTable'
type SidebarAlbumDownladProps = {
albumID: string
}
const SidebarAlbumDownload = ({ albumID }: SidebarAlbumDownladProps) => {
const { t } = useTranslation()
const downloads = [
{
title: t('sidebar.album.download.thumbnails.title', 'Thumbnails'),
description: t(
'sidebar.album.download.thumbnails.description',
'Low resolution images, no videos'
),
purpose: 'thumbnail,video-thumbnail',
},
{
title: t(
'sidebar.album.download.high-resolutions.title',
'High resolutions'
),
description: t(
'sidebar.album.download.high-resolutions.description',
'High resolution jpegs of RAW images'
),
purpose: 'high-res',
},
{
title: t('sidebar.album.download.originals.title', 'Originals'),
description: t(
'sidebar.album.download.originals.description',
'The original images and videos'
),
purpose: 'original',
},
{
title: t('sidebar.album.download.web-videos.title', 'Converted videos'),
description: t(
'sidebar.album.download.web-videos.description',
'Videos that have been optimized for web'
),
purpose: 'video-web',
},
]
const downloadRows = downloads.map(x => (
<SidebarTable.Row
key={x.purpose}
onClick={() =>
(location.href = `${API_ENDPOINT}/download/album/${albumID}/${x.purpose}`)
}
tabIndex={0}
>
<td className="pl-4 py-2">{`${x.title}`}</td>
<td className="pr-4 py-2 text-sm text-gray-800 dark:text-gray-400 italic">{`${x.description}`}</td>
</SidebarTable.Row>
))
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.download.title', 'Download')}
</SidebarSectionTitle>
<SidebarTable.Table>
<SidebarTable.Head>
<SidebarTable.HeadRow>
<th className="px-4 py-2" colSpan={2}>
{t('sidebar.download.table_columns.name', 'Name')}
</th>
</SidebarTable.HeadRow>
</SidebarTable.Head>
<tbody>{downloadRows}</tbody>
</SidebarTable.Table>
</SidebarSection>
)
}
export default SidebarAlbumDownload
@@ -0,0 +1,295 @@
import { gql, useLazyQuery } from '@apollo/client'
import { useTranslation } from 'react-i18next'
import { NotificationType } from '../../__generated__/globalTypes'
import { authToken } from '../../helpers/authentication'
import { TranslationFn } from '../../localization'
import { MessageState } from '../messages/Messages'
import { MediaSidebarMedia } from './MediaSidebar/MediaSidebar'
import React from 'react'
import { SidebarSection, SidebarSectionTitle } from './SidebarComponents'
import SidebarTable from './SidebarTable'
import {
sidebarDownloadQuery,
sidebarDownloadQueryVariables,
sidebarDownloadQuery_media_downloads,
} from './__generated__/sidebarDownloadQuery'
export const SIDEBAR_DOWNLOAD_QUERY = gql`
query sidebarDownloadQuery($mediaId: ID!) {
media(id: $mediaId) {
id
downloads {
title
mediaUrl {
url
width
height
fileSize
}
}
}
}
`
const formatBytes = (t: TranslationFn) => (bytes: number) => {
if (bytes == 0)
return t('sidebar.download.filesize.byte', '{{count}} Byte', { count: 0 })
const i = Math.floor(Math.log(bytes) / Math.log(1024))
const count = Math.round(bytes / Math.pow(1024, i))
switch (i) {
case 0:
// i18next-extract-mark-plural-next-line
return t('sidebar.download.filesize.byte', '{{count}} Byte', { count })
case 1:
return t('sidebar.download.filesize.kilo_byte', '{{count}} KB', { count })
case 2:
return t('sidebar.download.filesize.mega_byte', '{{count}} MB', { count })
case 3:
return t('sidebar.download.filesize.giga_byte', '{{count}} GB', { count })
case 4:
return t('sidebar.download.filesize.tera_byte', '{{count}} TB', { count })
default:
throw new Error(`invalid byte value: ${bytes}`)
}
}
const downloadMedia = (t: TranslationFn) => async (url: string) => {
const imgUrl = new URL(
`${import.meta.env.BASE_URL}${url}`.replace(/\/\//g, '/'),
location.origin
)
if (authToken() == null) {
// Get share token if not authorized
const token = location.pathname.match(/^\/share\/([\d\w]+)(\/?.*)$/)
if (token) {
imgUrl.searchParams.set('token', token[1])
}
}
const response = await fetch(imgUrl.href, {
credentials: 'include',
})
let blob = null
if (response.headers.has('content-length')) {
blob = await downloadMediaShowProgress(t)(response)
} else {
blob = await response.blob()
}
if (blob == null) {
console.log('Blob is null canceling')
return
}
const filenameMatch = url.match(/[^/]*$/)
if (filenameMatch == null) {
console.error('Could not extract filename', url)
return
}
const filename = filenameMatch[0]
downloadBlob(blob, filename)
}
const downloadMediaShowProgress =
(t: TranslationFn) => async (response: Response) => {
const totalBytes = Number(response.headers.get('content-length'))
const reader = response.body?.getReader()
const data = new Uint8Array(totalBytes)
if (reader == null) {
throw new Error('Download reader is null')
}
let canceled = false
const onDismiss = () => {
canceled = true
reader.cancel('Download canceled by user')
}
const notifyKey = Math.random().toString(26)
MessageState.add({
key: notifyKey,
type: NotificationType.Progress,
onDismiss,
props: {
header: 'Downloading photo',
content: `Starting download`,
percent: 0,
},
})
let receivedBytes = 0
let result
do {
result = await reader.read()
if (canceled) break
if (result.value) data.set(result.value, receivedBytes)
receivedBytes += result.value ? result.value.length : 0
MessageState.add({
key: notifyKey,
type: NotificationType.Progress,
onDismiss,
props: {
header: 'Downloading photo',
percent: (receivedBytes / totalBytes) * 100,
content: `${formatBytes(t)(receivedBytes)} of ${formatBytes(t)(
totalBytes
)} bytes downloaded`,
},
})
} while (!result.done)
if (canceled) {
return
}
MessageState.add({
key: notifyKey,
type: NotificationType.Progress,
props: {
header: 'Downloading photo completed',
content: `The photo has been downloaded`,
percent: 100,
positive: true,
},
})
setTimeout(() => {
MessageState.removeKey(notifyKey)
}, 2000)
const content = new Blob([data.buffer], {
type: response.headers.get('content-type') || undefined,
})
return content
}
const downloadBlob = (blob: Blob, filename: string) => {
const objectUrl = window.URL.createObjectURL(blob)
const anchor = document.createElement('a')
document.body.appendChild(anchor)
anchor.href = objectUrl
anchor.download = filename
anchor.click()
anchor.remove()
window.URL.revokeObjectURL(objectUrl)
}
type SidebarDownloadTableRow = {
title: string
url: string
width: number
height: number
fileSize: number
}
type SidebarDownloadTableProps = {
rows: SidebarDownloadTableRow[]
}
const SidebarDownloadTable = ({ rows }: SidebarDownloadTableProps) => {
const { t } = useTranslation()
const extractExtension = (url: string) => {
const urlMatch = url.split(/[#?]/)
if (urlMatch == null) return
return urlMatch[0].split('.').pop()?.trim().toLowerCase()
}
const download = downloadMedia(t)
const bytes = formatBytes(t)
const downloadRows = rows.map(x => (
<SidebarTable.Row key={x.url} onClick={() => download(x.url)} tabIndex={0}>
<td className="pl-4 py-2">{`${x.title}`}</td>
<td className="py-2">{`${x.width} x ${x.height}`}</td>
<td className="py-2">{`${bytes(x.fileSize)}`}</td>
<td className="pr-4 py-2">{extractExtension(x.url)}</td>
</SidebarTable.Row>
))
return (
<SidebarTable.Table>
<SidebarTable.Head>
<SidebarTable.HeadRow>
<th className="w-2/6 pl-4 py-2">
{t('sidebar.download.table_columns.name', 'Name')}
</th>
<th className="w-2/6 py-2">
{t('sidebar.download.table_columns.dimensions', 'Dimensions')}
</th>
<th className="w-1/6 py-2">
{t('sidebar.download.table_columns.file_size', 'Size')}
</th>
<th className="w-1/6 pr-4 py-2">
{t('sidebar.download.table_columns.file_type', 'Type')}
</th>
</SidebarTable.HeadRow>
</SidebarTable.Head>
<tbody>{downloadRows}</tbody>
</SidebarTable.Table>
)
}
type SidebarMediaDownladProps = {
media: MediaSidebarMedia
}
const SidebarMediaDownload = ({ media }: SidebarMediaDownladProps) => {
const { t } = useTranslation()
if (!media || !media.id) return null
const [loadPhotoDownloads, { called, loading, data }] = useLazyQuery<
sidebarDownloadQuery,
sidebarDownloadQueryVariables
>(SIDEBAR_DOWNLOAD_QUERY, { variables: { mediaId: media.id } })
let downloads: sidebarDownloadQuery_media_downloads[] = []
if (called) {
if (!loading) {
downloads = (data && data.media.downloads) || []
}
} else {
if (!media.downloads) {
loadPhotoDownloads()
} else {
downloads = media.downloads
}
}
const downloadRows = downloads.map<SidebarDownloadTableRow>(x => ({
title: x.title,
url: x.mediaUrl.url,
width: x.mediaUrl.width,
height: x.mediaUrl.height,
fileSize: x.mediaUrl.fileSize,
}))
return (
<SidebarSection>
<SidebarSectionTitle>
{t('sidebar.download.title', 'Download')}
</SidebarSectionTitle>
<SidebarDownloadTable rows={downloadRows} />
</SidebarSection>
)
}
export default SidebarMediaDownload
@@ -0,0 +1,38 @@
import React, { useContext } from 'react'
import { ReactComponent as CloseIcon } from './icons/closeSidebarIcon.svg'
import { ReactComponent as PinIconOutline } from './icons/pinSidebarIconOutline.svg'
import { ReactComponent as PinIconFilled } from './icons/pinSidebarIconFilled.svg'
import { SidebarContext } from './Sidebar'
type SidebarHeaderProps = {
title: string
}
const SidebarHeader = ({ title }: SidebarHeaderProps) => {
const { updateSidebar, setPinned, pinned } = useContext(SidebarContext)
const PinIcon = pinned ? PinIconFilled : PinIconOutline
return (
<div className="m-2 flex items-center">
<button
className={`${pinned ? 'lg:hidden' : ''}`}
title="Close sidebar"
onClick={() => updateSidebar(null)}
>
<CloseIcon className="m-2 text-[#1F2021] dark:text-[#abadaf]" />
</button>
<span className="flex-grow -mt-1 ml-2">{title}</span>
<button
className="hidden lg:block"
title="Pin sidebar"
onClick={() => setPinned(!pinned)}
>
<PinIcon className="m-2 text-[#1F2021] dark:text-[#abadaf]" />
</button>
</div>
)
}
export default SidebarHeader
+25
View File
@@ -0,0 +1,25 @@
import React from 'react'
type SidebarItemProps = {
name: string
value: string
}
const SidebarItem = ({ name, value }: SidebarItemProps) => (
<div className="flex items-baseline mb-1">
<div
className="w-[110px] flex-shrink-0 font-semibold text-sm text-gray-500 dark:text-gray-400 text-right pr-2 truncate"
title={name}
>
{name}
</div>
<div
className="flex-1 text-base break-words min-w-0"
style={{ overflowWrap: 'break-word', wordBreak: 'break-word' }}
>
{value}
</div>
</div>
)
export default SidebarItem
@@ -0,0 +1,24 @@
import styled from 'styled-components'
const Table = styled.table.attrs({ className: 'table-fixed w-full' })``
const Head = styled.thead.attrs({
className: 'bg-[#f9f9fb] dark:bg-[#2B3037]',
})``
const HeadRow = styled.tr.attrs({
className:
'text-left uppercase text-xs border-gray-100 dark:border-dark-border2 border-b border-t',
})``
const Row = styled.tr.attrs({
className:
'cursor-pointer border-gray-100 dark:border-dark-border2 border-b hover:bg-gray-50 focus:bg-gray-50 dark:hover:bg-[#3c4759] dark:focus:bg-[#3c4759]',
})``
export default {
Table,
Head,
HeadRow,
Row,
}
@@ -0,0 +1,26 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: getAlbumSidebar
// ====================================================
export interface getAlbumSidebar_album {
__typename: "Album";
id: string;
title: string;
}
export interface getAlbumSidebar {
/**
* Get album by id, user must own the album or be admin
* If valid tokenCredentials are provided, the album may be retrived without further authentication
*/
album: getAlbumSidebar_album;
}
export interface getAlbumSidebarVariables {
id: string;
}
@@ -0,0 +1,45 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: resetAlbumCover
// ====================================================
export interface resetAlbumCover_resetAlbumCover_thumbnail_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface resetAlbumCover_resetAlbumCover_thumbnail {
__typename: "Media";
id: string;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: resetAlbumCover_resetAlbumCover_thumbnail_thumbnail | null;
}
export interface resetAlbumCover_resetAlbumCover {
__typename: "Album";
id: string;
/**
* An image in this album used for previewing this album
*/
thumbnail: resetAlbumCover_resetAlbumCover_thumbnail | null;
}
export interface resetAlbumCover {
/**
* Reset the assigned cover photo for an album
*/
resetAlbumCover: resetAlbumCover_resetAlbumCover;
}
export interface resetAlbumCoverVariables {
albumID: string;
}
+45
View File
@@ -0,0 +1,45 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: setAlbumCover
// ====================================================
export interface setAlbumCover_setAlbumCover_thumbnail_thumbnail {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
}
export interface setAlbumCover_setAlbumCover_thumbnail {
__typename: "Media";
id: string;
/**
* URL to display the media in a smaller resolution
*/
thumbnail: setAlbumCover_setAlbumCover_thumbnail_thumbnail | null;
}
export interface setAlbumCover_setAlbumCover {
__typename: "Album";
id: string;
/**
* An image in this album used for previewing this album
*/
thumbnail: setAlbumCover_setAlbumCover_thumbnail | null;
}
export interface setAlbumCover {
/**
* Assign a cover photo to an album
*/
setAlbumCover: setAlbumCover_setAlbumCover;
}
export interface setAlbumCoverVariables {
coverID: string;
}
@@ -0,0 +1,26 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: sidebarAlbumAddShare
// ====================================================
export interface sidebarAlbumAddShare_shareAlbum {
__typename: "ShareToken";
token: string;
}
export interface sidebarAlbumAddShare {
/**
* Generate share token for album
*/
shareAlbum: sidebarAlbumAddShare_shareAlbum;
}
export interface sidebarAlbumAddShareVariables {
id: string;
password?: string | null;
expire?: Time | null;
}
@@ -0,0 +1,58 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: sidebarDownloadQuery
// ====================================================
export interface sidebarDownloadQuery_media_downloads_mediaUrl {
__typename: "MediaURL";
/**
* URL for previewing the image
*/
url: string;
/**
* Width of the image in pixels
*/
width: number;
/**
* Height of the image in pixels
*/
height: number;
/**
* The file size of the resource in bytes
*/
fileSize: number;
}
export interface sidebarDownloadQuery_media_downloads {
__typename: "MediaDownload";
/**
* A description of the role of the media file
*/
title: string;
mediaUrl: sidebarDownloadQuery_media_downloads_mediaUrl;
}
export interface sidebarDownloadQuery_media {
__typename: "Media";
id: string;
/**
* A list of different versions of files for this media that can be downloaded by the user
*/
downloads: sidebarDownloadQuery_media_downloads[];
}
export interface sidebarDownloadQuery {
/**
* Get media by id, user must own the media or be admin.
* If valid tokenCredentials are provided, the media may be retrived without further authentication
*/
media: sidebarDownloadQuery_media;
}
export interface sidebarDownloadQueryVariables {
mediaId: string;
}
@@ -0,0 +1,43 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: sidebarGetAlbumShares
// ====================================================
export interface sidebarGetAlbumShares_album_shares {
__typename: "ShareToken";
id: string;
token: string;
/**
* Whether or not a password is needed to access the share
*/
hasPassword: boolean;
/**
* Optional expire date
*/
expire: Time | null;
}
export interface sidebarGetAlbumShares_album {
__typename: "Album";
id: string;
/**
* A list of share tokens pointing to this album, owned by the logged in user
*/
shares: sidebarGetAlbumShares_album_shares[];
}
export interface sidebarGetAlbumShares {
/**
* Get album by id, user must own the album or be admin
* If valid tokenCredentials are provided, the album may be retrived without further authentication
*/
album: sidebarGetAlbumShares_album;
}
export interface sidebarGetAlbumSharesVariables {
id: string;
}
@@ -0,0 +1,43 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: sidebarGetPhotoShares
// ====================================================
export interface sidebarGetPhotoShares_media_shares {
__typename: "ShareToken";
id: string;
token: string;
/**
* Whether or not a password is needed to access the share
*/
hasPassword: boolean;
/**
* Optional expire date
*/
expire: Time | null;
}
export interface sidebarGetPhotoShares_media {
__typename: "Media";
id: string;
/**
* A list of share tokens pointing to this media, owned byt the logged in user
*/
shares: sidebarGetPhotoShares_media_shares[];
}
export interface sidebarGetPhotoShares {
/**
* Get media by id, user must own the media or be admin.
* If valid tokenCredentials are provided, the media may be retrived without further authentication
*/
media: sidebarGetPhotoShares_media;
}
export interface sidebarGetPhotoSharesVariables {
id: string;
}
@@ -0,0 +1,26 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: sidebarPhotoAddShare
// ====================================================
export interface sidebarPhotoAddShare_shareMedia {
__typename: "ShareToken";
token: string;
}
export interface sidebarPhotoAddShare {
/**
* Generate share token for media
*/
shareMedia: sidebarPhotoAddShare_shareMedia;
}
export interface sidebarPhotoAddShareVariables {
id: string;
password?: string | null;
expire?: Time | null;
}
@@ -0,0 +1,29 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: sidebarProtectShare
// ====================================================
export interface sidebarProtectShare_protectShareToken {
__typename: "ShareToken";
token: string;
/**
* Whether or not a password is needed to access the share
*/
hasPassword: boolean;
}
export interface sidebarProtectShare {
/**
* Set a password for a token, if null is passed for the password argument, the password will be cleared
*/
protectShareToken: sidebarProtectShare_protectShareToken;
}
export interface sidebarProtectShareVariables {
token: string;
password?: string | null;
}
@@ -0,0 +1,25 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: sidebarSetExpierShare
// ====================================================
export interface sidebarSetExpierShare_setExpireShareToken {
__typename: "ShareToken";
token: string;
}
export interface sidebarSetExpierShare {
/**
* Set a Expiration Time for a token
*/
setExpireShareToken: sidebarSetExpierShare_setExpireShareToken;
}
export interface sidebarSetExpierShareVariables {
token: string;
expire?: Time | null;
}
@@ -0,0 +1,24 @@
/* tslint:disable */
/* eslint-disable */
// @generated
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL mutation operation: sidebareDeleteShare
// ====================================================
export interface sidebareDeleteShare_deleteShareToken {
__typename: "ShareToken";
token: string;
}
export interface sidebareDeleteShare {
/**
* Delete a share token by it's token value
*/
deleteShareToken: sidebareDeleteShare_deleteShareToken;
}
export interface sidebareDeleteShareVariables {
token: string;
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="12px" height="12px" viewBox="0 0 12 12" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path stroke="none" stroke-width="1" fill="none" d="M1,11 L11,1 M11,11 L1,1" stroke="currentColor" stroke-width="2"></path>
</svg>

After

Width:  |  Height:  |  Size: 316 B

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="17px" viewBox="0 0 16 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(8, 8.5) rotate(-330) translate(-8, -8.5) translate(4, 2)" stroke="currentColor" fill="currentColor">
<path d="M6.76850191,0.434840963 C6.04896114,1.86467297 5.79279384,3.20120746 6,4.44444444 C6.17989677,5.52382504 6.63266329,6.48919052 7.35829958,7.34054088 C7.50158762,7.50867286 7.48146228,7.76112984 7.31333862,7.90442763 C7.24096223,7.96611661 7.14897427,8 7.053875,8 L0.922873286,8 C0.701919553,8.00007212 0.522801161,7.82095373 0.522801161,7.59999999 C0.522801161,7.50599929 0.555900634,7.41500023 0.616293108,7.34296634 C1.36567981,6.44912577 1.82691544,5.48295181 2,4.44444444 C2.19754347,3.25918364 1.93688287,1.92116674 1.21801821,0.430393743 C1.14595115,0.281147735 1.2086138,0.10177184 1.35789863,0.0297852978 C1.39855358,0.0101811032 1.44310701,8.29112604e-18 1.4882418,0 L6.50055336,0 C6.666219,3.58349532e-05 6.80051754,0.134334371 6.80051754,0.300000012 C6.80051754,0.346829895 6.78955305,0.393009303 6.76850191,0.434840963 Z" stroke-linejoin="round"></path>
<line x1="4" y1="8" x2="4" y2="13" stroke-linecap="round"></line>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="17px" viewBox="0 0 16 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g transform="translate(8, 8.5) rotate(-330) translate(-8, -8.5) translate(4, 2)" stroke="currentColor">
<path d="M6.76850191,0.434840963 C6.04896114,1.86467297 5.79279384,3.20120746 6,4.44444444 C6.17989677,5.52382504 6.63266329,6.48919052 7.35829958,7.34054088 C7.50158762,7.50867286 7.48146228,7.76112984 7.31333862,7.90442763 C7.24096223,7.96611661 7.14897427,8 7.053875,8 L0.922873286,8 C0.701919553,8.00007212 0.522801161,7.82095373 0.522801161,7.59999999 C0.522801161,7.50599929 0.555900634,7.41500023 0.616293108,7.34296634 C1.36567981,6.44912577 1.82691544,5.48295181 2,4.44444444 C2.19754347,3.25918364 1.93688287,1.92116674 1.21801821,0.430393743 C1.14595115,0.281147735 1.2086138,0.10177184 1.35789863,0.0297852978 C1.39855358,0.0101811032 1.44310701,8.29112604e-18 1.4882418,0 L6.50055336,0 C6.666219,3.58349532e-05 6.80051754,0.134334371 6.80051754,0.300000012 C6.80051754,0.346829895 6.78955305,0.393009303 6.76850191,0.434840963 Z" stroke-linejoin="round"></path>
<line x1="4" y1="8" x2="4" y2="13" stroke-linecap="round"></line>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="12px" height="12px" viewBox="0 0 12 12" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M5.66666667,1 L5.66666667,10.3333333 M1,5.66666667 L10.3333333,5.66666667" fill="none" stroke="currentColor" stroke-width="1.5"></path>
</svg>

After

Width:  |  Height:  |  Size: 337 B

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="14px" height="14px" viewBox="0 0 14 14" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path stroke="none" d="M12.0909091,4.45454545 C13.1452709,4.45454545 14,5.30927457 14,6.36363636 L14,6.36363636 L14,12.0909091 C14,13.1452709 13.1452709,14 12.0909091,14 L12.0909091,14 L6.36363636,14 C5.30927457,14 4.45454545,13.1452709 4.45454545,12.0909091 L4.45454545,12.0909091 L4.45454545,6.36363636 C4.45454545,5.30927457 5.30927457,4.45454545 6.36363636,4.45454545 L6.36363636,4.45454545 Z M12.0909091,5.72727273 L6.36363636,5.72727273 C6.01218243,5.72727273 5.72727273,6.01218243 5.72727273,6.36363636 L5.72727273,6.36363636 L5.72727273,12.0909091 C5.72727273,12.442363 6.01218243,12.7272727 6.36363636,12.7272727 L6.36363636,12.7272727 L12.0909091,12.7272727 C12.442363,12.7272727 12.7272727,12.442363 12.7272727,12.0909091 L12.7272727,12.0909091 L12.7272727,6.36363636 C12.7272727,6.01218243 12.442363,5.72727273 12.0909091,5.72727273 L12.0909091,5.72727273 Z M7.63636364,0 C8.65306965,0 9.48414783,0.79476725 9.54221374,1.79691732 L9.54545455,1.90909091 L9.54545455,2.54545455 C9.54545455,2.89690848 9.26054484,3.18181818 8.90909091,3.18181818 C8.58274083,3.18181818 8.31376817,2.93615624 8.27700856,2.61966799 L8.27272727,2.54545455 L8.27272727,1.90909091 C8.27272727,1.58274083 8.02706533,1.31376817 7.71057708,1.27700856 L7.63636364,1.27272727 L1.90909091,1.27272727 C1.58274083,1.27272727 1.31376817,1.51838921 1.27700856,1.83487747 L1.27272727,1.90909091 L1.27272727,7.63636364 C1.27272727,7.96271372 1.51838921,8.23168637 1.83487747,8.26844599 L1.90909091,8.27272727 L2.54545455,8.27272727 C2.89690848,8.27272727 3.18181818,8.55763698 3.18181818,8.90909091 C3.18181818,9.23544099 2.93615624,9.50441365 2.61966799,9.54117326 L2.54545455,9.54545455 L1.90909091,9.54545455 C0.892384892,9.54545455 0.0613067131,8.7506873 0.0032408049,7.74853723 L0,7.63636364 L0,1.90909091 C0,0.892384892 0.79476725,0.0613067131 1.79691732,0.0032408049 L1.90909091,0 L7.63636364,0 Z" fill="currentColor" fill-rule="nonzero"></path>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="13px" height="14px" viewBox="0 0 13 14" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path stroke="none" d="M7.63636364,0 C8.65306965,0 9.48414783,0.79476725 9.54221374,1.79691732 L9.54545455,1.90909091 L9.545,2.545 L12.0909091,2.54545455 C12.442363,2.54545455 12.7272727,2.83036425 12.7272727,3.18181818 C12.7272727,3.50816826 12.4816108,3.77714092 12.1651225,3.81390053 L12.0909091,3.81818182 L11.454,3.818 L11.4545455,12.0909091 C11.4545455,13.1076151 10.6597782,13.9386933 9.65762814,13.9967592 L9.54545455,14 L3.18181818,14 C2.16511217,14 1.33403399,13.2052327 1.27596808,12.2030827 L1.27272727,12.0909091 L1.272,3.818 L0.636363636,3.81818182 C0.284909705,3.81818182 2.27373675e-13,3.53327211 2.27373675e-13,3.18181818 C2.27373675e-13,2.8554681 0.245661939,2.58649544 0.562150193,2.54973583 L0.636363636,2.54545455 L3.181,2.545 L3.18181818,1.90909091 C3.18181818,0.892384892 3.97658543,0.0613067131 4.9787355,0.0032408049 L5.09090909,0 L7.63636364,0 Z M10.181,3.818 L2.545,3.818 L2.54545455,12.0909091 C2.54545455,12.4172592 2.79111648,12.6862318 3.10760474,12.7229914 L3.18181818,12.7272727 L9.54545455,12.7272727 C9.87180462,12.7272727 10.1407773,12.4816108 10.1775369,12.1651225 L10.1818182,12.0909091 L10.181,3.818 Z M5.09090909,5.72727273 C5.41725917,5.72727273 5.68623183,5.97293467 5.72299144,6.28942292 L5.72727273,6.36363636 L5.72727273,10.1818182 C5.72727273,10.5332721 5.44236302,10.8181818 5.09090909,10.8181818 C4.76455901,10.8181818 4.49558635,10.5725199 4.45882674,10.2560316 L4.45454545,10.1818182 L4.45454545,6.36363636 C4.45454545,6.01218243 4.73945516,5.72727273 5.09090909,5.72727273 Z M7.63636364,5.72727273 C7.96271372,5.72727273 8.23168637,5.97293467 8.26844599,6.28942292 L8.27272727,6.36363636 L8.27272727,10.1818182 C8.27272727,10.5332721 7.98781757,10.8181818 7.63636364,10.8181818 C7.31001356,10.8181818 7.0410409,10.5725199 7.00428128,10.2560316 L7,10.1818182 L7,6.36363636 C7,6.01218243 7.2849097,5.72727273 7.63636364,5.72727273 Z M7.63636364,1.27272727 L5.09090909,1.27272727 C4.76455901,1.27272727 4.49558635,1.51838921 4.45882674,1.83487747 L4.45454545,1.90909091 L4.454,2.545 L8.272,2.545 L8.27272727,1.90909091 C8.27272727,1.58274083 8.02706533,1.31376817 7.71057708,1.27700856 L7.63636364,1.27272727 Z" fill="currentColor" fill-rule="nonzero"></path>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="12px" height="14px" viewBox="0 0 12 12" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path stroke="none" stroke-width="1" fill="none" d="M5.01241676,3.99743718 L5.2123926,4.0051107 C6.08060614,4.06729045 6.87900923,4.50349496 7.40038252,5.20051071 C7.56578589,5.42163587 7.52061445,5.73497915 7.29948929,5.90038252 C7.07836413,6.06578589 6.76502085,6.02061445 6.59961748,5.79948929 C6.25203528,5.33481212 5.71976656,5.04400912 5.14095753,5.00255596 C4.62002941,4.96524811 4.10763194,5.1332244 3.71124008,5.46642286 L3.58355339,5.58355339 L2.0896441,7.0773559 C1.33169968,7.86211367 1.34253936,9.10952545 2.11400695,9.88099305 C2.84487099,10.6118571 4.00289823,10.6600523 4.78475751,10.0238225 L4.91144661,9.91144661 L5.76644661,9.05644661 C5.96170876,8.86118446 6.27829124,8.86118446 6.47355339,9.05644661 C6.64711974,9.23001296 6.66640489,9.49943736 6.53140884,9.6943055 L6.47355339,9.76355339 L5.6123559,10.6246441 C4.43521924,11.7615607 2.56410157,11.7453012 1.40690017,10.5880998 C0.295986831,9.47718649 0.236565536,7.70832791 1.24484904,6.52165836 L1.37644661,6.37644661 L2.87638252,4.87651071 C3.44442608,4.30826116 4.21444071,3.99361146 5.01241676,3.99743718 Z M10.5930998,1.41190017 C11.7040132,2.52281351 11.7634345,4.29167209 10.755151,5.47834164 L10.6235534,5.62355339 L9.12361748,7.12348929 C8.50823696,7.73909297 7.65582094,8.05706905 6.7876074,7.9948893 C5.91939386,7.93270955 5.12099077,7.49650504 4.59961748,6.79948929 C4.43421411,6.57836413 4.47938555,6.26502085 4.70051071,6.09961748 C4.92163587,5.93421411 5.23497915,5.97938555 5.40038252,6.20051071 C5.74796472,6.66518788 6.28023344,6.95599088 6.85904247,6.99744404 C7.37997059,7.03475189 7.89236806,6.8667756 8.28875992,6.53357714 L8.41644661,6.41644661 L9.9103559,4.9226441 C10.6683003,4.13788633 10.6574606,2.89047455 9.88599305,2.11900695 C9.15512901,1.38814291 7.99710177,1.3399477 7.21436478,1.97705267 L7.08752112,2.08958265 L6.22752112,2.94458265 C6.03169053,3.13927469 5.71510939,3.13835172 5.52041735,2.94252112 C5.34735776,2.76844949 5.32885818,2.49897001 5.46442178,2.30449627 L5.52247888,2.23541735 L6.3876441,1.3753559 C7.56478076,0.238439269 9.43589843,0.254698775 10.5930998,1.41190017 Z" fill="currentColor" fill-rule="nonzero"></path>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="10px" height="14px" viewBox="0 0 10 2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path stroke="none" stroke-width="1" fill="none" d="M0.646446609,0.646446609 C1.13807119,0.5 1.26307119,0.555964406 1.35355339,0.646446609 C1.44403559,0.736928813 1.5,0.861928813 1.5,1 C1.5,1.13807119 1.44403559,1.26307119 1.35355339,1.35355339 C1.26307119,1.44403559 1.13807119,1.5 1,1.5 C0.861928813,1.5 0.736928813,1.44403559 0.646446609,1.35355339 C0.555964406,1.26307119 0.5,1.13807119 0.5,1 C0.5,0.861928813 0.555964406,0.736928813 0.646446609,0.646446609 Z M4.64644661,0.646446609 C5.13807119,0.5 5.26307119,0.555964406 5.35355339,0.646446609 C5.44403559,0.736928813 5.5,0.861928813 5.5,1 C5.5,1.13807119 5.44403559,1.26307119 5.35355339,1.35355339 C5.26307119,1.44403559 5.13807119,1.5 5,1.5 C4.86192881,1.5 4.73692881,1.44403559 4.64644661,1.35355339 C4.55596441,1.26307119 4.5,1.13807119 4.5,1 C4.5,0.861928813 4.55596441,0.736928813 4.64644661,0.646446609 Z M8.64644661,0.646446609 C9.13807119,0.5 9.26307119,0.555964406 9.35355339,0.646446609 C9.44403559,0.736928813 9.5,0.861928813 9.5,1 C9.5,1.13807119 9.44403559,1.26307119 9.35355339,1.35355339 C9.26307119,1.44403559 9.13807119,1.5 9,1.5 C8.86192881,1.5 8.73692881,1.44403559 8.64644661,1.35355339 C8.55596441,1.26307119 8.5,1.13807119 8.5,1 C8.5,0.861928813 8.55596441,0.736928813 8.64644661,0.646446609 Z" stroke="currentColor"></path>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1,108 @@
import { useQuery } from '@apollo/client'
import gql from 'graphql-tag'
import React from 'react'
import { useTranslation } from 'react-i18next'
import Dropdown, { DropdownItem } from '../../primitives/form/Dropdown'
import { FavoriteCheckboxProps, FavoritesCheckbox } from '../album/AlbumFilter'
import { ReactComponent as DateIcon } from './icons/date.svg'
import { earliestMedia } from './__generated__/earliestMedia'
const EARLIEST_MEDIA_QUERY = gql`
query earliestMedia {
myMedia(
order: { order_by: "date_shot", order_direction: ASC }
paginate: { limit: 1 }
) {
id
date
}
}
`
type DateSelectorProps = {
filterDate: string | null
setFilterDate(date: string | null): void
}
const DateSelector = ({ filterDate, setFilterDate }: DateSelectorProps) => {
const { t } = useTranslation()
const { data, loading } = useQuery<earliestMedia>(EARLIEST_MEDIA_QUERY)
let items: DropdownItem[] = [
{
value: 'all',
label: t('timeline_filter.date.dropdown_all', 'From today'),
},
]
if (data) {
if (data.myMedia.length != 0) {
const dateStr = data.myMedia[0].date
const date = new Date(dateStr)
const now = new Date()
const currentYear = now.getFullYear()
const earliestYear = date.getFullYear()
const years: number[] = []
for (let i = currentYear - 1; i >= earliestYear; i--) {
years.push(i)
}
const yearItems = years.map<DropdownItem>(x => ({
value: `${x}`,
label: t('timeline_filter.date.dropdown_year', '{{year}} and earlier', {
year: x,
}),
}))
items = [...items, ...yearItems]
}
}
return (
<fieldset>
<legend id="filter_group_date-label" className="inline-block mb-1">
<DateIcon
className="inline-block align-baseline mr-1"
aria-hidden="true"
/>
<span>{t('timeline_filter.date.label', 'Date')}</span>
</legend>
<div>
<Dropdown
aria-labelledby="filter_group_date-label"
setSelected={date =>
date == 'all' ? setFilterDate(null) : setFilterDate(date)
}
value={filterDate || 'all'}
items={items}
disabled={loading}
/>
</div>
</fieldset>
)
}
type TimelineFiltersProps = DateSelectorProps & FavoriteCheckboxProps
const TimelineFilters = ({
onlyFavorites,
setOnlyFavorites,
filterDate,
setFilterDate,
}: TimelineFiltersProps) => {
return null
// return (
// <div className="flex items-end gap-4 flex-wrap mb-4">
// <DateSelector filterDate={filterDate} setFilterDate={setFilterDate} />
// <FavoritesCheckbox
// onlyFavorites={onlyFavorites}
// setOnlyFavorites={setOnlyFavorites}
// />
// </div>
// )
}
export default TimelineFilters
@@ -0,0 +1,37 @@
import { MockedProvider } from '@apollo/client/testing'
import { render, screen } from '@testing-library/react'
import React from 'react'
import { MemoryRouter } from 'react-router-dom'
import TimelineGallery, { MY_TIMELINE_QUERY } from './TimelineGallery'
import { timelineData } from './timelineTestData'
vi.mock('../../hooks/useScrollPagination')
test('timeline with media', async () => {
const graphqlMocks = [
{
request: {
query: MY_TIMELINE_QUERY,
variables: { onlyFavorites: false, offset: 0, limit: 200 },
},
result: {
data: {
myTimeline: timelineData,
},
},
},
]
render(
<MemoryRouter initialEntries={['/timeline']}>
<MockedProvider mocks={graphqlMocks}>
<TimelineGallery />
</MockedProvider>
</MemoryRouter>
)
expect(screen.queryByLabelText('Show only favorites')).toBeInTheDocument()
expect(await screen.findAllByRole('link')).toHaveLength(4)
expect(await screen.findAllByRole('img')).toHaveLength(5)
})
@@ -0,0 +1,188 @@
import React, { useRef, useEffect, useReducer } from 'react'
import { useQuery, gql } from '@apollo/client'
import TimelineGroupDate from './TimelineGroupDate'
import PresentView from '../photoGallery/presentView/PresentView'
import useURLParameters from '../../hooks/useURLParameters'
import useScrollPagination from '../../hooks/useScrollPagination'
import PaginateLoader from '../PaginateLoader'
import { useTranslation } from 'react-i18next'
import {
myTimeline,
myTimelineVariables,
myTimeline_myTimeline,
} from './__generated__/myTimeline'
import {
getActiveTimelineImage as getActiveTimelineMedia,
timelineGalleryReducer,
} from './timelineGalleryReducer'
import { urlPresentModeSetupHook } from '../photoGallery/mediaGalleryReducer'
import TimelineFilters from './TimelineFilters'
import client from '../../apolloClient'
export const MY_TIMELINE_QUERY = gql`
query myTimeline(
$onlyFavorites: Boolean
$limit: Int
$offset: Int
$fromDate: Time
) {
myTimeline(
onlyFavorites: $onlyFavorites
fromDate: $fromDate
paginate: { limit: $limit, offset: $offset }
) {
id
title
type
blurhash
thumbnail {
url
width
height
}
highRes {
url
width
height
}
videoWeb {
url
}
favorite
album {
id
title
}
date
}
}
`
export type TimelineGroup = {
date: string
albums: TimelineGroupAlbum[]
}
export type TimelineGroupAlbum = {
id: string
title: string
media: myTimeline_myTimeline[]
}
const TimelineGallery = () => {
const { t } = useTranslation()
const { getParam, setParam } = useURLParameters()
const onlyFavorites = getParam('favorites') == '1' ? true : false
const setOnlyFavorites = (favorites: boolean) =>
setParam('favorites', favorites ? '1' : null)
const filterDate = getParam('date')
const setFilterDate = (x: string) => setParam('date', x)
const favoritesNeedsRefresh = useRef(false)
const [mediaState, dispatchMedia] = useReducer(timelineGalleryReducer, {
presenting: false,
timelineGroups: [],
activeIndex: {
date: -1,
album: -1,
media: -1,
},
})
const { data, error, loading, refetch, fetchMore } = useQuery<
myTimeline,
myTimelineVariables
>(MY_TIMELINE_QUERY, {
variables: {
onlyFavorites,
fromDate: filterDate
? `${parseInt(filterDate) + 1}-01-01T00:00:00Z`
: undefined,
offset: 0,
limit: 200,
},
})
const { containerElem, finished: finishedLoadingMore } =
useScrollPagination<myTimeline>({
loading,
fetchMore,
data,
getItems: data => data.myTimeline,
})
useEffect(() => {
dispatchMedia({
type: 'replaceTimelineGroups',
timeline: data?.myTimeline || [],
})
}, [data])
useEffect(() => {
; (async () => {
await client.resetStore()
await refetch({
onlyFavorites,
fromDate: filterDate
? `${parseInt(filterDate) + 1}-01-01T00:00:00Z`
: undefined,
offset: 0,
limit: 200,
})
})()
}, [filterDate])
// urlPresentModeSetupHook({
// dispatchMedia,
// openPresentMode: (_event) => {
// dispatchMedia({
// type: 'openPresentMode',
// activeIndex: mediaState.activeIndex,
// })
// },
// })
useEffect(() => {
favoritesNeedsRefresh.current = false
refetch({
onlyFavorites: onlyFavorites,
})
}, [onlyFavorites])
if (error) {
return <div>{error.message}</div>
}
const timelineGroups = mediaState.timelineGroups.map((_, i) => (
<TimelineGroupDate
key={i}
groupIndex={i}
mediaState={mediaState}
dispatchMedia={dispatchMedia}
/>
))
return (
<div className="overflow-x-hidden">
<TimelineFilters
onlyFavorites={onlyFavorites}
setOnlyFavorites={setOnlyFavorites}
filterDate={filterDate}
setFilterDate={setFilterDate}
/>
<div className="-mx-3 flex flex-wrap" ref={containerElem}>
{timelineGroups}
</div>
<PaginateLoader
active={!finishedLoadingMore && !loading}
text={t('general.loading.paginate.media', 'Loading more media')}
/>
</div>
)
}
export default TimelineGallery

Some files were not shown because too many files have changed in this diff Show More