1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538 | import React, {
useState,
useMemo,
useCallback,
useEffect,
useRef,
} from 'react';
import styled from 'styled-components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faPlay,
faThList,
faTh,
faSearch,
faImage,
} from '@fortawesome/free-solid-svg-icons';
import { Episode } from '../../index';
interface Props {
animeId: string | undefined;
episodes: Episode[];
selectedEpisodeId: string;
onEpisodeSelect: (id: string) => void;
maxListHeight: string;
}
// Styled components for the episode list
const ListContainer = styled.div<{ $maxHeight: string }>`
background-color: var(--global-secondary-bg);
color: var(--global-text);
border-radius: var(--global-border-radius);
overflow: hidden;
flex-grow: 1;
display: flex;
flex-direction: column;
max-height: ${({ $maxHeight }) => $maxHeight};
@media (max-width: 1000px) {
max-height: 18rem;
}
@media (max-width: 500px) {
max-height: ${({ $maxHeight }) => $maxHeight};
}
`;
const EpisodeGrid = styled.div<{ $isRowLayout: boolean }>`
display: grid;
grid-template-columns: ${({ $isRowLayout }) =>
$isRowLayout ? '1fr' : 'repeat(auto-fill, minmax(4rem, 1fr))'};
gap: 0.29rem;
padding: 0.4rem;
overflow-y: auto;
flex-grow: 1;
`;
const EpisodeImage = styled.img`
max-width: 250px;
max-height: 150px;
height: auto;
margin-top: 0.5rem;
border-radius: var(--global-border-radius);
@media (max-width: 500px) {
max-width: 125px;
max-height: 80px;
}
`;
const ListItem = styled.button<{
$isSelected: boolean;
$isRowLayout: boolean;
$isWatched: boolean;
}>`
transition:
padding 0.3s ease-in-out,
transform 0.3s ease-in-out;
animation: popIn 0.3s ease-in-out;
background-color: ${({ $isSelected, $isWatched }) =>
$isSelected
? $isWatched
? 'var(--primary-accent)' // Selected and watched
: 'var(--primary-accent-bg)' // Selected but not watched
: $isWatched
? 'var(--primary-accent-bg); filter: brightness(0.8);' // Not selected but watched
: 'var(--global-tertiary-bg)'};
border: none;
border-radius: var(--global-border-radius);
color: ${({ $isSelected, $isWatched }) =>
$isSelected
? $isWatched
? 'var(--global-text)' // Selected and watched
: 'var(--global-text)' // Selected but not watched
: $isWatched
? 'var(--primary-accent); filter: brightness(0.8);' // Not selected but watched
: 'grey'}; // Not selected and not watched
padding: ${({ $isRowLayout }) =>
$isRowLayout ? '0.6rem 0.5rem' : '0.4rem 0'};
text-align: ${({ $isRowLayout }) => ($isRowLayout ? 'left' : 'center')};
cursor: pointer;
justify-content: ${({ $isRowLayout }) =>
$isRowLayout ? 'space-between' : 'center'};
align-items: center;
&:hover,
&:active,
&:focus {
${({ $isSelected, $isWatched }) =>
$isSelected
? $isWatched
? 'filter: brightness(1.1)' // Selected and watched
: 'filter: brightness(1.1)' // Selected but not watched
: $isWatched
? 'filter: brightness(1.1)' // Not selected but watched
: 'background-color: var(--global-button-hover-bg); filter: brightness(1.05); color: #FFFFFF'};
padding-left: ${({ $isRowLayout }) => ($isRowLayout ? '1rem' : '')};
}
`;
const ControlsContainer = styled.div`
display: flex;
align-items: center;
background-color: var(--global-secondary-bg);
border-bottom: 1px solid var(--global-shadow);
padding: 0.25rem 0;
`;
const SelectInterval = styled.select`
padding: 0.5rem;
background-color: var(--global-secondary-bg);
color: var(--global-text);
border: none;
border-radius: var(--global-border-radius);
`;
const LayoutToggle = styled.button`
background-color: var(--global-secondary-bg);
border: 1px solid var(--global-shadow);
padding: 0.5rem;
margin-right: 0.5rem;
cursor: pointer;
color: var(--global-text);
border-radius: var(--global-border-radius);
transition:
background-color 0.15s,
color 0.15s;
&:hover,
&:active,
&:focus {
background-color: var(--global-button-hover-bg);
}
`;
const SearchContainer = styled.div`
display: flex;
align-items: center;
background-color: var(--global-secondary-bg);
border: 1px solid var(--global-shadow);
padding: 0.5rem;
gap: 0.25rem;
margin: 0 0.5rem;
border-radius: var(--global-border-radius);
transition:
background-color 0.15s,
color 0.15s;
&:hover,
&:active,
&:focus {
background-color: var(--global-button-hover-bg);
}
`;
const SearchInput = styled.input`
border: none;
background-color: transparent;
color: var(--global-text);
outline: none;
width: 100%;
&::placeholder {
color: var(--global-placeholder);
}
`;
const Icon = styled.div`
color: var(--global-text);
opacity: 0.5;
font-size: 0.8rem;
transition: opacity 0.2s;
@media (max-width: 768px) {
display: none; /* Hide on mobile */
}
`;
const EpisodeNumber = styled.span``;
const EpisodeTitle = styled.span`
padding: 0.5rem;
`;
// The updated EpisodeList component
export const EpisodeList: React.FC<Props> = ({
animeId,
episodes,
selectedEpisodeId,
onEpisodeSelect,
maxListHeight,
}) => {
// State for interval, layout, user layout preference, search term, and watched episodes
const episodeGridRef = useRef<HTMLDivElement>(null);
const episodeRefs = useRef<{ [key: string]: HTMLButtonElement | null }>({});
const [interval, setInterval] = useState<[number, number]>([0, 99]);
const [isRowLayout, setIsRowLayout] = useState(true);
const [userLayoutPreference, setUserLayoutPreference] = useState<
boolean | null
>(null);
const [searchTerm, setSearchTerm] = useState('');
const [watchedEpisodes, setWatchedEpisodes] = useState<Episode[]>([]);
const defaultLayoutMode = episodes.every((episode) => episode.title)
? 'list'
: 'grid';
const [displayMode, setDisplayMode] = useState<'list' | 'grid' | 'imageList'>(
() => {
const savedMode = animeId
? localStorage.getItem(`listLayout-[${animeId}]`)
: null;
return (savedMode as 'list' | 'grid' | 'imageList') || defaultLayoutMode;
},
);
const [selectionInitiatedByUser, setSelectionInitiatedByUser] =
useState(false);
// Update local storage when watched episodes change
useEffect(() => {
if (animeId && watchedEpisodes.length > 0) {
localStorage.setItem(
`watched-episodes-${animeId}`,
JSON.stringify(watchedEpisodes),
);
}
}, [animeId, watchedEpisodes]);
// Load watched episodes from local storage when animeId changes
useEffect(() => {
if (animeId) {
localStorage.setItem(`listLayout-[${animeId}]`, displayMode);
const watched = localStorage.getItem('watched-episodes');
if (watched) {
const watchedEpisodesObject = JSON.parse(watched);
const watchedEpisodesForAnime = watchedEpisodesObject[animeId];
if (watchedEpisodesForAnime) {
setWatchedEpisodes(watchedEpisodesForAnime);
}
}
}
}, [animeId]);
// Function to handle episode selection
// Function to mark an episode as watched
const markEpisodeAsWatched = useCallback(
(id: string) => {
if (animeId) {
setWatchedEpisodes((prevWatchedEpisodes) => {
const updatedWatchedEpisodes = [...prevWatchedEpisodes];
const selectedEpisodeIndex = updatedWatchedEpisodes.findIndex(
(episode) => episode.id === id,
);
if (selectedEpisodeIndex === -1) {
const selectedEpisode = episodes.find(
(episode) => episode.id === id,
);
if (selectedEpisode) {
updatedWatchedEpisodes.push(selectedEpisode);
// Update the watched episodes object in local storage
localStorage.setItem(
'watched-episodes',
JSON.stringify({
...JSON.parse(
localStorage.getItem('watched-episodes') || '{}',
),
[animeId]: updatedWatchedEpisodes,
}),
);
return updatedWatchedEpisodes;
}
}
return prevWatchedEpisodes;
});
}
},
[episodes, animeId],
);
const handleEpisodeSelect = useCallback(
(id: string) => {
setSelectionInitiatedByUser(true);
markEpisodeAsWatched(id); // Mark the episode as watched
onEpisodeSelect(id);
},
[onEpisodeSelect, markEpisodeAsWatched],
);
// Update watched episodes when a new episode is selected or visited
useEffect(() => {
if (selectedEpisodeId && !selectionInitiatedByUser) {
markEpisodeAsWatched(selectedEpisodeId);
}
}, [selectedEpisodeId, selectionInitiatedByUser, markEpisodeAsWatched]);
// Generate interval options
const intervalOptions = useMemo(() => {
return episodes.reduce<{ start: number; end: number }[]>(
(options, _, index) => {
if (index % 100 === 0) {
const start = index;
const end = Math.min(index + 99, episodes.length - 1);
options.push({ start, end });
}
return options;
},
[],
);
}, [episodes]);
// Handle interval change
const handleIntervalChange = useCallback(
(e: React.ChangeEvent<HTMLSelectElement>) => {
const [start, end] = e.target.value.split('-').map(Number);
setInterval([start, end]);
},
[],
);
// Toggle layout preference
const toggleLayoutPreference = useCallback(() => {
setDisplayMode((prevMode) => {
const nextMode =
prevMode === 'list'
? 'grid'
: prevMode === 'grid'
? 'imageList'
: 'list';
if (animeId) {
localStorage.setItem(`listLayout-[${animeId}]`, nextMode);
}
return nextMode;
});
}, [animeId]);
// Filter episodes based on search input
const filteredEpisodes = useMemo(() => {
const searchQuery = searchTerm.toLowerCase();
return episodes.filter(
(episode) =>
episode.title?.toLowerCase().includes(searchQuery) ||
episode.number.toString().includes(searchQuery),
);
}, [episodes, searchTerm]);
// Apply the interval to the filtered episodes
const displayedEpisodes = useMemo(() => {
if (!searchTerm) {
// If there's no search term, apply interval to all episodes
return episodes.slice(interval[0], interval[1] + 1);
}
// If there is a search term, display filtered episodes without applying interval
return filteredEpisodes;
}, [episodes, filteredEpisodes, interval, searchTerm]);
// Determine layout based on episodes and user preference
useEffect(() => {
const allTitlesNull = episodes.every((episode) => episode.title === null);
const defaultLayout = episodes.length <= 26 && !allTitlesNull;
setIsRowLayout(
userLayoutPreference !== null ? userLayoutPreference : defaultLayout,
);
// Find the selected episode
if (!selectionInitiatedByUser) {
const selectedEpisode = episodes.find(
(episode) => episode.id === selectedEpisodeId,
);
if (selectedEpisode) {
// Find the interval containing the selected episode
for (let i = 0; i < intervalOptions.length; i++) {
const { start, end } = intervalOptions[i];
if (
selectedEpisode.number >= start + 1 &&
selectedEpisode.number <= end + 1
) {
setInterval([start, end]);
break;
}
}
}
}
}, [
episodes,
userLayoutPreference,
selectedEpisodeId,
intervalOptions,
selectionInitiatedByUser,
]);
useEffect(() => {
const timer = setTimeout(() => {
if (
selectedEpisodeId &&
episodeRefs.current[selectedEpisodeId] &&
episodeGridRef.current &&
!selectionInitiatedByUser
) {
const episodeElement = episodeRefs.current[selectedEpisodeId];
const container = episodeGridRef.current;
// Ensure episodeElement is not null before proceeding
if (episodeElement && container) {
// Calculate episode's top position relative to the container
const episodeTop =
episodeElement.getBoundingClientRect().top -
container.getBoundingClientRect().top;
// Calculate the desired scroll position to center the episode in the container
const episodeHeight = episodeElement.offsetHeight;
const containerHeight = container.offsetHeight;
const desiredScrollPosition =
episodeTop + episodeHeight / 2 - containerHeight / 2;
container.scrollTo({
top: desiredScrollPosition,
behavior: 'smooth',
});
setSelectionInitiatedByUser(false);
}
}
}, 100); // A delay ensures the layout has stabilized, especially after dynamic content loading.
return () => clearTimeout(timer);
}, [selectedEpisodeId, episodes, displayMode, selectionInitiatedByUser]);
// Render the EpisodeList component
return (
<ListContainer $maxHeight={maxListHeight}>
<ControlsContainer>
<SelectInterval
onChange={handleIntervalChange}
value={`${interval[0]}-${interval[1]}`}
>
{intervalOptions.map(({ start, end }, index) => (
<option key={index} value={`${start}-${end}`}>
Episodes {start + 1} - {end + 1}
</option>
))}
</SelectInterval>
<SearchContainer>
<Icon>
<FontAwesomeIcon icon={faSearch} />
</Icon>
<SearchInput
type='text'
placeholder='Search episodes...'
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</SearchContainer>
<LayoutToggle onClick={toggleLayoutPreference}>
{displayMode === 'list' && <FontAwesomeIcon icon={faThList} />}
{displayMode === 'grid' && <FontAwesomeIcon icon={faTh} />}
{displayMode === 'imageList' && <FontAwesomeIcon icon={faImage} />}
</LayoutToggle>
</ControlsContainer>
<EpisodeGrid
key={`episode-grid-${displayMode}`}
$isRowLayout={displayMode === 'list' || displayMode === 'imageList'}
ref={episodeGridRef}
>
{displayedEpisodes.map((episode) => {
const $isSelected = episode.id === selectedEpisodeId;
const $isWatched = watchedEpisodes.some((e) => e.id === episode.id);
return (
<ListItem
key={episode.id}
$isSelected={$isSelected}
$isRowLayout={
displayMode === 'list' || displayMode === 'imageList'
}
$isWatched={$isWatched}
onClick={() => handleEpisodeSelect(episode.id)}
aria-selected={$isSelected}
ref={(el) => (episodeRefs.current[episode.id] = el)} // Reference to each episode's button
>
{displayMode === 'imageList' ? (
<>
<div>
<EpisodeNumber>{episode.number}. </EpisodeNumber>
<EpisodeTitle>{episode.title}</EpisodeTitle>
</div>
<EpisodeImage
src={episode.image}
alt={`Episode ${episode.number} - ${episode.title}`}
/>
</>
) : displayMode === 'grid' ? (
<>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
{$isSelected ? (
<FontAwesomeIcon icon={faPlay} />
) : (
<EpisodeNumber>{episode.number}</EpisodeNumber>
)}
</div>
</>
) : (
// Render for 'list' layout
<>
<EpisodeNumber>{episode.number}. </EpisodeNumber>
<EpisodeTitle>{episode.title}</EpisodeTitle>
{$isSelected && <FontAwesomeIcon icon={faPlay} />}
</>
)}
</ListItem>
);
})}
</EpisodeGrid>
</ListContainer>
);
};
|