Merge branch 'router-upgrade' of github.com:Discours/discoursio-webapp into router-upgrade

This commit is contained in:
Untone 2024-07-12 14:18:28 +03:00
commit 65798a7f60
4 changed files with 71 additions and 41 deletions

View File

@ -9,7 +9,8 @@ export default defineConfig({
ssr: true, ssr: true,
server: { server: {
preset: isVercel ? 'vercel_edge' : isBun ? 'bun' : 'node', preset: isVercel ? 'vercel_edge' : isBun ? 'bun' : 'node',
port: 3000 port: 3000,
https: true
}, },
devOverlay: true, devOverlay: true,
build: { build: {
@ -43,6 +44,9 @@ export default defineConfig({
build: { build: {
chunkSizeWarningLimit: 1024, chunkSizeWarningLimit: 1024,
target: 'esnext' target: 'esnext'
},
server: {
https: true
} }
} }
} as SolidStartInlineConfig) } as SolidStartInlineConfig)

View File

@ -11,6 +11,7 @@ import { LocalizeProvider } from './context/localize'
import { SessionProvider } from './context/session' import { SessionProvider } from './context/session'
import { TopicsProvider } from './context/topics' import { TopicsProvider } from './context/topics'
import { UIProvider } from './context/ui' // snackbar included import { UIProvider } from './context/ui' // snackbar included
import { AuthorsProvider } from './context/authors'
import '~/styles/app.scss' import '~/styles/app.scss'
export const Providers = (props: { children?: JSX.Element }) => { export const Providers = (props: { children?: JSX.Element }) => {
@ -24,7 +25,9 @@ export const Providers = (props: { children?: JSX.Element }) => {
<Meta name="viewport" content="width=device-width, initial-scale=1" /> <Meta name="viewport" content="width=device-width, initial-scale=1" />
<UIProvider> <UIProvider>
<EditorProvider> <EditorProvider>
<Suspense fallback={<Loading />}>{props.children}</Suspense> <AuthorsProvider>
<Suspense fallback={<Loading />}>{props.children}</Suspense>
</AuthorsProvider>
</EditorProvider> </EditorProvider>
</UIProvider> </UIProvider>
</MetaProvider> </MetaProvider>

View File

@ -21,44 +21,64 @@ type Props = {
authorsByShouts?: Author[] authorsByShouts?: Author[]
isLoaded: boolean isLoaded: boolean
} }
export const AUTHORS_PER_PAGE = 20 export const AUTHORS_PER_PAGE = 20
export const ABC = { export const ABC = {
ru: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ#', ru: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ#',
en: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#' en: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'
} }
// useAuthors sorted from context, set filter/sort
export const AllAuthors = (props: Props) => { export const AllAuthors = (props: Props) => {
const { t, lang } = useLocalize() const { t, lang } = useLocalize()
const alphabet = createMemo(() => ABC[lang()] || ABC['ru']) const alphabet = createMemo(() => ABC[lang()] || ABC['ru'])
const [searchParams, changeSearchParams] = useSearchParams<{ by?: string }>() const [searchParams, changeSearchParams] = useSearchParams<{ by?: string }>()
const { authorsSorted, setAuthorsSort, loadAuthors } = useAuthors() const { authorsSorted, setAuthorsSort, loadAuthors } = useAuthors()
const authors = createMemo(() => props.authors || authorsSorted())
const [loading, setLoading] = createSignal<boolean>(false) const [loading, setLoading] = createSignal<boolean>(false)
const [currentAuthors, setCurrentAuthors] = createSignal<Author[]>([])
// UPDATE Fetch authors initially and when searchParams.by changes
createEffect(() => {
fetchAuthors(searchParams.by || 'name', 0)
})
const authors = createMemo(() => {
let sortedAuthors = [...(props.authors || authorsSorted())] // Clone the array to avoid mutating the original
console.log('Before Sorting:', sortedAuthors.slice(0, 5)) // Log the first 5 authors for comparison
if (searchParams.by === 'name') {
sortedAuthors = sortedAuthors.sort((a, b) => a.name.localeCompare(b.name))
console.log('Sorted by Name:', sortedAuthors.slice(0, 5))
} else if (searchParams.by === 'shouts') {
sortedAuthors = sortedAuthors.sort((a, b) => (b.stat?.shouts || 0) - (a.stat?.shouts || 0))
console.log('Sorted by Shouts:', sortedAuthors.slice(0, 5))
} else if (searchParams.by === 'followers') {
sortedAuthors = sortedAuthors.sort((a, b) => (b.stat?.followers || 0) - (a.stat?.followers || 0));
console.log('Sorted by Followers:', sortedAuthors.slice(0, 5));
}
console.log('After Sorting:', sortedAuthors.slice(0, 5))
return sortedAuthors
})
// Log authors data and searchParams for debugging
createEffect(() => {
console.log('Authors:', props.authors.slice(0, 5)) // Log the first 5 authors
console.log('Sorted Authors:', authors().slice(0, 5)) // Log the first 5 sorted authors
console.log('Search Params "by":', searchParams.by)
})
// filter // filter
const [searchQuery, setSearchQuery] = createSignal('') const [searchQuery, setSearchQuery] = createSignal('')
const [filteredAuthors, setFilteredAuthors] = createSignal<Author[]>([]) const [filteredAuthors, setFilteredAuthors] = createSignal<Author[]>([])
createEffect( createEffect(() =>
() => authors() && setFilteredAuthors(dummyFilter(authors(), searchQuery(), lang()) as Author[])
authors() &&
setFilteredAuthors((_prev: Author[]) => dummyFilter(authors(), searchQuery(), lang()) as Author[])
) )
// sort by
onMount(() => !searchParams?.by && changeSearchParams({ by: 'name' }))
createEffect(on(() => searchParams?.by || 'name', setAuthorsSort || ((_) => null), {}))
// store by first char // store by first char
const byLetterFiltered = createMemo<{ [letter: string]: Author[] }>(() => { const byLetterFiltered = createMemo<{ [letter: string]: Author[] }>(() => {
if (!(filteredAuthors()?.length > 0)) return {} if (!(filteredAuthors()?.length > 0)) return {}
console.debug('[components.AllAuthors] update byLetterFiltered', filteredAuthors()?.length) console.debug('[components.AllAuthors] update byLetterFiltered', filteredAuthors()?.length)
return ( return filteredAuthors().reduce(
filteredAuthors()?.reduce( (acc, author: Author) => authorLetterReduce(acc, author, lang()),
(acc, author: Author) => authorLetterReduce(acc, author, lang()), {} as { [letter: string]: Author[] }
{} as { [letter: string]: Author[] }
) || {}
) )
}) })
@ -81,21 +101,25 @@ export const AllAuthors = (props: Props) => {
limit: AUTHORS_PER_PAGE, limit: AUTHORS_PER_PAGE,
offset offset
}) })
// UPDATE authors to currentAuthors state
setCurrentAuthors((prev) => [...prev, ...authorsSorted()])
} catch (error) { } catch (error) {
console.error('[components.AuthorsList] error fetching authors:', error) console.error('[components.AuthorsList] error fetching authors:', error)
} finally { } finally {
setLoading(false) setLoading(false)
} }
} }
const [currentPage, setCurrentPage] = createSignal<{ followers: number; shouts: number }>({ const [currentPage, setCurrentPage] = createSignal<{ followers: number; shouts: number }>({
followers: 0, followers: 0,
shouts: 0 shouts: 0
}) })
const loadMoreAuthors = () => { const loadMoreAuthors = () => {
const by = searchParams?.by as 'followers' | 'shouts' | undefined const by = searchParams?.by as 'followers' | 'shouts' | undefined;
if (!by) return if (!by) return;
const nextPage = currentPage()[by] + 1 const nextPage = currentPage()[by] + 1;
fetchAuthors(by, nextPage).then(() => setCurrentPage({ ...currentPage(), [by]: nextPage })) fetchAuthors(by, nextPage).then(() => setCurrentPage({ ...currentPage(), [by]: nextPage }));
} }
const TabNavigator = () => ( const TabNavigator = () => (
@ -109,21 +133,21 @@ export const AllAuthors = (props: Props) => {
['view-switcher__item--selected']: !searchParams?.by || searchParams?.by === 'shouts' ['view-switcher__item--selected']: !searchParams?.by || searchParams?.by === 'shouts'
})} })}
> >
<a href="/author?by=shouts">{t('By shouts')}</a> <a href="#" onClick={() => changeSearchParams({ by: 'shouts' })}>{t('By shouts')}</a>
</li> </li>
<li <li
class={clsx({ class={clsx({
['view-switcher__item--selected']: searchParams?.by === 'followers' ['view-switcher__item--selected']: searchParams?.by === 'followers'
})} })}
> >
<a href="/author?by=followers">{t('By popularity')}</a> <a href="#" onClick={() => changeSearchParams({ by: 'followers' })}>{t('By popularity')}</a>
</li> </li>
<li <li
class={clsx({ class={clsx({
['view-switcher__item--selected']: searchParams?.by === 'name' ['view-switcher__item--selected']: searchParams?.by === 'name'
})} })}
> >
<a href="/author?by=name">{t('By name')}</a> <a href="#" onClick={() => changeSearchParams({ by: 'name' })}>{t('By name')}</a>
</li> </li>
<Show when={searchParams?.by === 'name'}> <Show when={searchParams?.by === 'name'}>
<li class="view-switcher__search"> <li class="view-switcher__search">
@ -193,7 +217,7 @@ export const AllAuthors = (props: Props) => {
const AuthorsSortedList = () => ( const AuthorsSortedList = () => (
<div class={clsx(stylesAuthorList.AuthorsList)}> <div class={clsx(stylesAuthorList.AuthorsList)}>
<For each={authorsSorted?.()}> <For each={authors()}>
{(author) => ( {(author) => (
<div class="row"> <div class="row">
<div class="col-lg-20 col-xl-18"> <div class="col-lg-20 col-xl-18">
@ -205,7 +229,7 @@ export const AllAuthors = (props: Props) => {
<div class="row"> <div class="row">
<div class="col-lg-20 col-xl-18"> <div class="col-lg-20 col-xl-18">
<div class={stylesAuthorList.action}> <div class={stylesAuthorList.action}>
<Show when={!loading() && ((authorsSorted?.() || []).length || 0) > 0}> <Show when={!loading() && ((authors() || []).length || 0) > 0}>
<Button value={t('Load more')} onClick={loadMoreAuthors} aria-live="polite" /> <Button value={t('Load more')} onClick={loadMoreAuthors} aria-live="polite" />
</Show> </Show>
<Show when={loading()}> <Show when={loading()}>
@ -221,7 +245,6 @@ export const AllAuthors = (props: Props) => {
<Show when={props.isLoaded} fallback={<Loading />}> <Show when={props.isLoaded} fallback={<Loading />}>
<div class="offset-md-5"> <div class="offset-md-5">
<TabNavigator /> <TabNavigator />
<Show when={searchParams?.by === 'name'} fallback={<AuthorsSortedList />}> <Show when={searchParams?.by === 'name'} fallback={<AuthorsSortedList />}>
<AbcNavigator /> <AbcNavigator />
<AbcAuthorsList /> <AbcAuthorsList />

View File

@ -56,7 +56,7 @@ export const AuthorsProvider = (props: { children: JSX.Element }) => {
const [authorsSorted, setAuthorsSorted] = createSignal<Author[]>([]) const [authorsSorted, setAuthorsSorted] = createSignal<Author[]>([])
const [sortBy, setSortBy] = createSignal<SortFunction<Author>>() const [sortBy, setSortBy] = createSignal<SortFunction<Author>>()
const { feedByAuthor } = useFeed() const { feedByAuthor } = useFeed()
const setAuthorsSort = (stat: string) => setSortBy((_) => byStat(stat) as SortFunction<Author>) const setAuthorsSort = (stat: string) => setSortBy(() => byStat(stat) as SortFunction<Author>)
// Эффект для отслеживания изменений сигнала sortBy и обновления authorsSorted // Эффект для отслеживания изменений сигнала sortBy и обновления authorsSorted
createEffect( createEffect(
@ -64,7 +64,7 @@ export const AuthorsProvider = (props: { children: JSX.Element }) => {
[sortBy, authorsEntities], [sortBy, authorsEntities],
([sortfn, authorsdict]) => { ([sortfn, authorsdict]) => {
if (sortfn) { if (sortfn) {
setAuthorsSorted?.([...filterAndSort(Object.values(authorsdict), sortfn)]) setAuthorsSorted([...filterAndSort(Object.values(authorsdict), sortfn)])
} }
}, },
{ defer: true } { defer: true }
@ -101,6 +101,17 @@ export const AuthorsProvider = (props: { children: JSX.Element }) => {
} }
} }
const loadAuthorsPaginated = async (args: QueryLoad_Authors_ByArgs): Promise<void> => {
try {
const fetcher = await loadAuthors(args)
const data = await fetcher()
if (data) addAuthors(data as Author[])
} catch (error) {
console.error('Error loading authors:', error)
throw error
}
}
const topAuthors = createMemo(() => { const topAuthors = createMemo(() => {
const articlesByAuthorMap = feedByAuthor?.() || {} const articlesByAuthorMap = feedByAuthor?.() || {}
@ -125,17 +136,6 @@ export const AuthorsProvider = (props: { children: JSX.Element }) => {
return sortedTopAuthors return sortedTopAuthors
}) })
const loadAuthorsPaginated = async (args: QueryLoad_Authors_ByArgs): Promise<void> => {
try {
const fetcher = await loadAuthors(args)
const data = await fetcher()
if (data) addAuthors(data as Author[])
} catch (error) {
console.error('Error loading authors:', error)
throw error
}
}
const authorsByTopic = createMemo(() => { const authorsByTopic = createMemo(() => {
const articlesByAuthorMap = feedByAuthor?.() || {} const articlesByAuthorMap = feedByAuthor?.() || {}
const result: { [topicSlug: string]: Author[] } = {} const result: { [topicSlug: string]: Author[] } = {}