Better resolver, communities mostly done.

This commit is contained in:
Dessalines 2020-09-07 10:32:07 -05:00
parent 241ef72290
commit cde3c266f2
7 changed files with 82 additions and 95 deletions

View file

@ -10,7 +10,7 @@ import { IsoData } from '../shared/interfaces';
import { routes } from '../shared/routes'; import { routes } from '../shared/routes';
import IsomorphicCookie from 'isomorphic-cookie'; import IsomorphicCookie from 'isomorphic-cookie';
import { lemmyHttp, setAuth } from '../shared/utils'; import { lemmyHttp, setAuth } from '../shared/utils';
import { GetSiteForm } from 'lemmy-js-client'; import { GetSiteForm, GetSiteResponse } from 'lemmy-js-client';
const server = express(); const server = express();
const port = 1234; const port = 1234;
@ -38,15 +38,23 @@ server.get('/*', async (req, res) => {
} }
let resolver = await Promise.all(promises); let resolver = await Promise.all(promises);
let site: GetSiteResponse = resolver[0];
let routeData = resolver.slice(1, resolver.length);
let acceptLang = req.headers['accept-language'].split(',')[0];
let lang = !!site.my_user
? site.my_user.lang == 'browser'
? acceptLang
: 'en'
: acceptLang;
let isoData: IsoData = { let isoData: IsoData = {
path: req.path, path: req.path,
site: resolver[0], site,
routeData: resolver.slice(1, resolver.length), routeData,
lang,
}; };
console.log(activeRoute.path);
const wrapper = ( const wrapper = (
<StaticRouter location={req.url} context={isoData}> <StaticRouter location={req.url} context={isoData}>
<App site={isoData.site} /> <App site={isoData.site} />

View file

@ -1,7 +1,7 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Route, Switch } from 'inferno-router'; import { Route, Switch } from 'inferno-router';
/* import { Provider } from 'inferno-i18next'; */ import { Provider } from 'inferno-i18next';
/* import { i18n } from './i18next'; */ import { i18n } from '../i18next';
import { routes } from '../../shared/routes'; import { routes } from '../../shared/routes';
import { Navbar } from '../../shared/components/navbar'; import { Navbar } from '../../shared/components/navbar';
import { Footer } from '../../shared/components/footer'; import { Footer } from '../../shared/components/footer';
@ -18,10 +18,10 @@ export class App extends Component<AppProps, any> {
super(props, context); super(props, context);
} }
/* <Provider i18next={i18n}> */
render() { render() {
return ( return (
<> <>
<Provider i18next={i18n}>
<div> <div>
<Navbar site={this.props.site} /> <Navbar site={this.props.site} />
<div class="mt-4 p-0 fl-1"> <div class="mt-4 p-0 fl-1">
@ -40,6 +40,7 @@ export class App extends Component<AppProps, any> {
</div> </div>
<Footer /> <Footer />
</div> </div>
</Provider>
</> </>
); );
} }

View file

@ -1,7 +1,6 @@
import { Component, linkEvent } from 'inferno'; import { Component, linkEvent } from 'inferno';
import { Helmet } from 'inferno-helmet'; import { Helmet } from 'inferno-helmet';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
import { import {
UserOperation, UserOperation,
Community, Community,
@ -11,7 +10,6 @@ import {
ListCommunitiesForm, ListCommunitiesForm,
SortType, SortType,
WebSocketJsonResponse, WebSocketJsonResponse,
GetSiteResponse,
Site, Site,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
@ -22,10 +20,11 @@ import {
isBrowser, isBrowser,
lemmyHttp, lemmyHttp,
setAuth, setAuth,
setIsoData,
wsSubscribe,
} from '../utils'; } from '../utils';
import { CommunityLink } from './community-link'; import { CommunityLink } from './community-link';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
import { IsoData } from 'shared/interfaces';
const communityLimit = 100; const communityLimit = 100;
@ -42,36 +41,24 @@ interface CommunitiesProps {
export class Communities extends Component<any, CommunitiesState> { export class Communities extends Component<any, CommunitiesState> {
private subscription: Subscription; private subscription: Subscription;
private isoData = setIsoData(this.context);
private emptyState: CommunitiesState = { private emptyState: CommunitiesState = {
communities: [], communities: [],
loading: true, loading: true,
page: getPageFromProps(this.props), page: getPageFromProps(this.props),
site: undefined, site: this.isoData.site.site,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.state = this.emptyState; this.state = this.emptyState;
let isoData: IsoData; this.parseMessage = this.parseMessage.bind(this);
if (isBrowser()) { this.subscription = wsSubscribe(this.parseMessage);
this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
isoData = window.isoData;
} else {
isoData = this.context.router.staticContext;
}
this.state.site = isoData.site.site;
// Only fetch the data if coming from another route // Only fetch the data if coming from another route
if (isoData.path == this.context.router.route.match.path) { if (this.isoData.path == this.context.router.route.match.url) {
this.state.communities = isoData.routeData[0].communities; this.state.communities = this.isoData.routeData[0].communities;
this.state.loading = false; this.state.loading = false;
} else { } else {
this.refetch(); this.refetch();
@ -98,11 +85,7 @@ export class Communities extends Component<any, CommunitiesState> {
} }
get documentTitle(): string { get documentTitle(): string {
if (this.state.site) {
return `${i18n.t('communities')} - ${this.state.site.name}`; return `${i18n.t('communities')} - ${this.state.site.name}`;
} else {
return 'Lemmy';
}
} }
render() { render() {
@ -250,7 +233,7 @@ export class Communities extends Component<any, CommunitiesState> {
static fetchInitialData(auth: string, path: string): Promise<any>[] { static fetchInitialData(auth: string, path: string): Promise<any>[] {
let pathSplit = path.split('/'); let pathSplit = path.split('/');
let page = pathSplit[2] ? Number(pathSplit[2]) : 1; let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
let listCommunitiesForm: ListCommunitiesForm = { let listCommunitiesForm: ListCommunitiesForm = {
sort: SortType.TopAll, sort: SortType.TopAll,
limit: communityLimit, limit: communityLimit,
@ -282,10 +265,6 @@ export class Communities extends Component<any, CommunitiesState> {
found.subscribed = data.community.subscribed; found.subscribed = data.community.subscribed;
found.number_of_subscribers = data.community.number_of_subscribers; found.number_of_subscribers = data.community.number_of_subscribers;
this.setState(this.state); this.setState(this.state);
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
} }
} }
} }

View file

@ -46,7 +46,6 @@ interface NavbarState {
unreadCount: number; unreadCount: number;
searchParam: string; searchParam: string;
toggleSearch: boolean; toggleSearch: boolean;
siteRes: GetSiteResponse;
onSiteBanner?(url: string): any; onSiteBanner?(url: string): any;
} }
@ -62,7 +61,6 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
mentions: [], mentions: [],
messages: [], messages: [],
expanded: false, expanded: false,
siteRes: this.props.site, // TODO this could probably go away
searchParam: '', searchParam: '',
toggleSearch: false, toggleSearch: false,
}; };
@ -80,14 +78,15 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
() => console.log('complete') () => console.log('complete')
); );
// WebSocketService.Instance.getSite();
this.searchTextField = createRef(); this.searchTextField = createRef();
} }
// The login // The login
// TODO this needs some work
if (this.props.site.my_user) { if (this.props.site.my_user) {
console.log(this.props.site.my_user);
UserService.Instance.user = this.props.site.my_user; UserService.Instance.user = this.props.site.my_user;
// i18n.changeLanguage(getLanguage());
if (isBrowser()) { if (isBrowser()) {
WebSocketService.Instance.userJoin(); WebSocketService.Instance.userJoin();
@ -97,6 +96,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
this.fetchUnreads(); this.fetchUnreads();
// setTheme(data.my_user.theme, true); // setTheme(data.my_user.theme, true);
// i18n.changeLanguage(getLanguage()); // i18n.changeLanguage(getLanguage());
// i18n.changeLanguage('de');
} }
} }
} }
@ -113,7 +113,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
this.state.isLoggedIn = false; this.state.isLoggedIn = false;
} }
console.log('a new login'); console.log('a new login');
WebSocketService.Instance.getSite(); // WebSocketService.Instance.getSite();
this.setState(this.state); this.setState(this.state);
}); });
@ -184,19 +184,19 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
<nav class="navbar navbar-expand-lg navbar-light shadow-sm p-0 px-3"> <nav class="navbar navbar-expand-lg navbar-light shadow-sm p-0 px-3">
<div class="container"> <div class="container">
<Link <Link
title={this.state.siteRes.version} title={this.props.site.version}
className="d-flex align-items-center navbar-brand mr-md-3" className="d-flex align-items-center navbar-brand mr-md-3"
to="/" to="/"
> >
{this.state.siteRes.site.icon && showAvatars() && ( {this.props.site.site.icon && showAvatars() && (
<img <img
src={pictrsAvatarThumbnail(this.state.siteRes.site.icon)} src={pictrsAvatarThumbnail(this.props.site.site.icon)}
height="32" height="32"
width="32" width="32"
class="rounded-circle mr-2" class="rounded-circle mr-2"
/> />
)} )}
{this.state.siteRes.site.name} {this.props.site.site.name}
</Link> </Link>
{this.state.isLoggedIn && ( {this.state.isLoggedIn && (
<Link <Link
@ -441,29 +441,6 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
} }
} }
} }
// TODO all this needs to be moved
else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.siteRes = data;
// The login
if (data.my_user) {
UserService.Instance.user = data.my_user;
WebSocketService.Instance.userJoin();
// On the first load, check the unreads
if (this.state.isLoggedIn == false) {
this.requestNotificationPermission();
this.fetchUnreads();
setTheme(data.my_user.theme, true);
i18n.changeLanguage(getLanguage());
}
this.state.isLoggedIn = true;
}
this.setState(this.state);
}
} }
fetchUnreads() { fetchUnreads() {
@ -514,7 +491,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
get canAdmin(): boolean { get canAdmin(): boolean {
return ( return (
UserService.Instance.user && UserService.Instance.user &&
this.state.siteRes.admins this.props.site.admins
.map(a => a.id) .map(a => a.id)
.includes(UserService.Instance.user.id) .includes(UserService.Instance.user.id)
); );

View file

@ -93,11 +93,9 @@ export class Sponsors extends Component<any, SponsorsState> {
<div> <div>
<h5>{i18n.t('donate_to_lemmy')}</h5> <h5>{i18n.t('donate_to_lemmy')}</h5>
<p> <p>
{/* TODO
<T i18nKey="sponsor_message"> <T i18nKey="sponsor_message">
#<a href={repoUrl}>#</a> #<a href={repoUrl}>#</a>
</T> </T>
*/}
</p> </p>
<a class="btn btn-secondary" href="https://liberapay.com/Lemmy/"> <a class="btn btn-secondary" href="https://liberapay.com/Lemmy/">
{i18n.t('support_on_liberapay')} {i18n.t('support_on_liberapay')}

View file

@ -4,6 +4,8 @@ export interface IsoData {
path: string; path: string;
routeData: any[]; routeData: any[];
site: GetSiteResponse; site: GetSiteResponse;
// Lang and theme
lang: string;
// communities?: ListCommunitiesResponse; // communities?: ListCommunitiesResponse;
} }

View file

@ -47,7 +47,7 @@ import {
import { httpUri } from './env'; import { httpUri } from './env';
import { CommentSortType, DataType } from './interfaces'; import { CommentSortType, DataType, IsoData } from './interfaces';
import { UserService, WebSocketService } from './services'; import { UserService, WebSocketService } from './services';
// import Tribute from 'tributejs'; // import Tribute from 'tributejs';
@ -60,6 +60,8 @@ import emojiShortName from 'emoji-short-name';
import Toastify from 'toastify-js'; import Toastify from 'toastify-js';
import tippy from 'tippy.js'; import tippy from 'tippy.js';
import moment from 'moment'; import moment from 'moment';
import { Subscription } from 'rxjs';
import { retryWhen, delay, take } from 'rxjs/operators';
export const favIconUrl = '/static/assets/favicon.svg'; export const favIconUrl = '/static/assets/favicon.svg';
export const favIconPngUrl = '/static/assets/apple-touch-icon.png'; export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
@ -828,9 +830,7 @@ export function getSortTypeFromProps(props: any): SortType {
} }
export function getPageFromProps(props: any): number { export function getPageFromProps(props: any): number {
// TODO return props.match.params.page ? Number(props.match.params.page) : 1;
return 1;
// return props.match.params.page ? Number(props.match.params.page) : 1;
} }
export function editCommentRes(data: CommentResponse, comments: Comment[]) { export function editCommentRes(data: CommentResponse, comments: Comment[]) {
@ -1112,3 +1112,25 @@ export function setAuth(obj: any, auth: string) {
obj.auth = auth; obj.auth = auth;
} }
} }
export function setIsoData(context: any): IsoData {
if (isBrowser()) {
return window.isoData;
} else {
return context.router.staticContext;
}
}
export function wsSubscribe(parseMessage: any): Subscription {
if (isBrowser()) {
return WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
} else {
return null;
}
}