Somewhat working webpack. Sponsors and communities pages done.

This commit is contained in:
Dessalines 2020-09-06 22:41:46 -05:00
parent 2eee936026
commit 241ef72290
22 changed files with 4604 additions and 1396 deletions

20
.babelrc Normal file
View file

@ -0,0 +1,20 @@
{
"compact": false,
"presets": [
[
"@babel/preset-env",
{
"loose": true,
"targets": {
"browsers": ["ie >= 11", "safari > 10"]
}
}
],
["@babel/typescript", {"isTSX": true, "allExtensions": true}]
],
"plugins": [
"@babel/plugin-transform-runtime",
["babel-plugin-inferno", { "imports": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }],
]
}

View file

@ -1,3 +1,3 @@
fuse.ts
generate_translations.js generate_translations.js
webpack.config.js
src/api_tests src/api_tests

8
Dockerfile Normal file
View file

@ -0,0 +1,8 @@
FROM node:14
WORKDIR /usr/src/app_name
COPY . .
RUN yarn
RUN yarn build:server
RUN yarn build:client
EXPOSE 1234
CMD yarn serve

82
fuse.ts
View file

@ -1,82 +0,0 @@
import { CSSPlugin, FuseBox, FuseBoxOptions, Sparky } from 'fuse-box';
import path = require('path');
import TsTransformClasscat from 'ts-transform-classcat';
import TsTransformInferno from 'ts-transform-inferno';
/**
* Some of FuseBoxOptions overrides by ts config (module, target, etc)
* https://fuse-box.org/page/working-with-targets
*/
let fuse: FuseBox;
const fuseOptions: FuseBoxOptions = {
homeDir: './src',
output: 'dist/$name.js',
sourceMaps: { inline: false, vendor: false },
/**
* Custom TypeScript Transformers (compile Inferno tsx to ts)
*/
transformers: {
before: [TsTransformClasscat(), TsTransformInferno()],
},
};
const fuseClientOptions: FuseBoxOptions = {
...fuseOptions,
plugins: [
/**
* https://fuse-box.org/page/css-resource-plugin
* Compile Sass {SassPlugin()}
* Make .css files modules-like (allow import them like modules) {CSSModules}
* Make .css files modules like and allow import it from node_modules too {CSSResourcePlugin}
* Use them all and bundle with {CSSPlugin}
* */
CSSPlugin(),
],
};
const fuseServerOptions: FuseBoxOptions = {
...fuseOptions,
};
Sparky.task('clean', () => {
/**Clean distribute (dist) folder */
Sparky.src('dist/').clean('dist/');
});
Sparky.task('config', () => {
fuse = FuseBox.init(fuseOptions);
fuse.dev();
});
Sparky.task('test', ['&clean', '&config'], () => {
fuse.bundle('client/bundle').test('[**/**.test.tsx]', null);
});
Sparky.task('client', () => {
fuse.opts = fuseClientOptions;
fuse
.bundle('client/bundle')
.target('browser@esnext')
.watch('client/**')
.hmr()
.instructions('> client/index.tsx');
});
Sparky.task('copy-assets', () =>
Sparky.src('**/**.*', { base: 'src/assets' }).dest('dist/assets')
);
Sparky.task('server', () => {
/**Workaround. Should be fixed */
fuse.opts = fuseServerOptions;
fuse
.bundle('server/bundle')
.watch('**')
.target('server@esnext')
.instructions('> [server/index.tsx]')
.completed(proc => {
proc.require({
// tslint:disable-next-line:no-shadowed-variable
close: ({ FuseBox }) => FuseBox.import(FuseBox.mainFile).shutdown(),
});
});
});
Sparky.task(
'dev',
['&clean', '&config', '&client', '&server', '&copy-assets'],
() => {
fuse.run();
}
);

View file

@ -4,16 +4,19 @@
"author": "Dessalines <tyhou13@gmx.com>", "author": "Dessalines <tyhou13@gmx.com>",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"scripts": { "scripts": {
"build": "yarn run build:server && yarn run build:client",
"build:client": "webpack --env.platform=client",
"build:server": "webpack --env.platform=server",
"clean": "yarn run rimraf dist",
"dev": "nodemon --watch ./src/shared/components -e ts,tsx,css,scss --exec yarn run start",
"lint": "tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx src", "lint": "tsc --noEmit && eslint --report-unused-disable-directives --ext .js,.ts,.tsx src",
"prebuild": "node generate_translations.js", "prebuild": "yarn clean && node generate_translations.js",
"prestart": "node generate_translations.js", "serve": "node dist/js/server.js",
"start": "set NODE_ENV=development && node -r ts-node/register --inspect fuse.ts dev", "start": "yarn run build && yarn run serve"
"test": "node -r ts-node/register --inspect fuse.ts test"
}, },
"repository": "https://github.com/LemmyNet/lemmy-isomorphic-ui", "repository": "https://github.com/LemmyNet/lemmy-isomorphic-ui",
"dependencies": { "dependencies": {
"@types/autosize": "^3.0.6", "@typescript-eslint/parser": "^4.0.1",
"@types/node-fetch": "^2.5.7",
"autosize": "^4.0.2", "autosize": "^4.0.2",
"choices.js": "^9.0.1", "choices.js": "^9.0.1",
"cookie-parser": "^1.4.3", "cookie-parser": "^1.4.3",
@ -41,40 +44,57 @@
"reconnecting-websocket": "^4.4.0", "reconnecting-websocket": "^4.4.0",
"rxjs": "^6.5.5", "rxjs": "^6.5.5",
"serialize-javascript": "^4.0.0", "serialize-javascript": "^4.0.0",
"terser": "^4.6.11",
"tippy.js": "^6.1.1", "tippy.js": "^6.1.1",
"toastify-js": "^1.7.0", "toastify-js": "^1.7.0",
"tributejs": "^5.1.3", "tributejs": "^5.1.3",
"ws": "^7.3.1" "ws": "^7.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.5.5",
"@babel/plugin-transform-runtime": "^7.11.5",
"@babel/plugin-transform-typescript": "^7.11.0",
"@babel/preset-env": "7.11.5",
"@babel/preset-typescript": "^7.3.3",
"@types/autosize": "^3.0.6",
"@types/cookie-parser": "^1.4.1", "@types/cookie-parser": "^1.4.1",
"@types/enzyme": "^3.1.10", "@types/enzyme": "^3.1.10",
"@types/express": "^4.11.1", "@types/express": "^4.11.1",
"@types/jest": "^26.0.10", "@types/jest": "^26.0.10",
"@types/node": "^14.6.0", "@types/node": "^14.6.0",
"@types/node-fetch": "^2.5.7",
"@types/serialize-javascript": "^4.0.0", "@types/serialize-javascript": "^4.0.0",
"autoprefixer": "^9.8.6",
"babel-loader": "^8.0.6",
"babel-plugin-inferno": "^6",
"bootstrap": "^4.5.2",
"classcat": "^4.1.0", "classcat": "^4.1.0",
"enzyme": "^3.3.0", "clean-webpack-plugin": "^3.0.0",
"enzyme-adapter-inferno": "^1.3.0", "css-loader": "^4.2.2",
"eslint": "^7.5.0", "eslint": "^7.5.0",
"eslint-plugin-jane": "^8.0.4", "eslint-plugin-jane": "^8.0.4",
"fuse-box": "3.7.1",
"fuse-test-runner": "^1.0.16",
"husky": "^4.2.5", "husky": "^4.2.5",
"inferno-devtools": "^7.4.3",
"inferno-test-utils": "^7.4.3",
"jest": "^26.4.2", "jest": "^26.4.2",
"jsdom": "16.4.0",
"jsdom-global": "3.0.2",
"lemmy-js-client": "^1.0.8", "lemmy-js-client": "^1.0.8",
"lint-staged": "^10.1.3", "lint-staged": "^10.1.3",
"mini-css-extract-plugin": "^0.11.0",
"node-sass": "^4.12.0",
"nodemon": "^2.0.4",
"postcss-loader": "^3.0.0",
"precss": "^4.0.0",
"prettier": "^2.0.4", "prettier": "^2.0.4",
"rimraf": "^3.0.2",
"sass-loader": "^10.0.1",
"sortpack": "^2.1.4", "sortpack": "^2.1.4",
"style-loader": "^1.2.1",
"terser": "^4.6.11",
"ts-node": "^9.0.0", "ts-node": "^9.0.0",
"ts-transform-classcat": "^1.0.0", "ts-transform-classcat": "^1.0.0",
"ts-transform-inferno": "^4.0.3", "ts-transform-inferno": "^4.0.3",
"typescript": "^4.0.2" "typescript": "^4.0.2",
"webpack": "4.44.1",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "3.11.0",
"webpack-node-externals": "^2.5.2"
}, },
"engines": { "engines": {
"node": ">=8.9.0" "node": ">=8.9.0"

View file

@ -1,21 +1,11 @@
import { Component } from 'inferno';
import { hydrate } from 'inferno-hydrate'; import { hydrate } from 'inferno-hydrate';
import { BrowserRouter } from 'inferno-router'; import { BrowserRouter } from 'inferno-router';
import { App } from '../shared/components/app'; import { App } from '../shared/components/app';
/* import { initDevTools } from 'inferno-devtools'; */
declare global {
interface Window {
isoData: {
name: string;
};
}
}
const wrapper = ( const wrapper = (
<BrowserRouter> <BrowserRouter>
<App /> <App site={window.isoData.site} />
</BrowserRouter> </BrowserRouter>
); );
/* initDevTools(); */
hydrate(wrapper, document.getElementById('root')); hydrate(wrapper, document.getElementById('root'));

View file

@ -1,35 +1,55 @@
import cookieParser = require('cookie-parser'); // import cookieParser = require('cookie-parser');
import serialize from 'serialize-javascript'; import serialize from 'serialize-javascript';
import express from 'express'; import express from 'express';
import { StaticRouter } from 'inferno-router'; import { StaticRouter } from 'inferno-router';
import { renderToString } from 'inferno-server'; import { renderToString } from 'inferno-server';
import { matchPath } from 'inferno-router'; import { matchPath } from 'inferno-router';
import path = require('path'); import path from 'path';
import { App } from '../shared/components/app'; import { App } from '../shared/components/app';
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 { GetSiteForm } from 'lemmy-js-client';
const server = express(); const server = express();
const port = 1234; const port = 1234;
server.use(express.json()); server.use(express.json());
server.use(express.urlencoded({ extended: false })); server.use(express.urlencoded({ extended: false }));
server.use('/assets', express.static(path.resolve('./dist/assets'))); server.use('/assets', express.static(path.resolve('./src/assets')));
server.use('/static', express.static(path.resolve('./dist/client'))); server.use('/static', express.static(path.resolve('./dist')));
server.use(cookieParser()); // server.use(cookieParser());
server.get('/*', (req, res) => { server.get('/*', async (req, res) => {
const activeRoute = routes.find(route => matchPath(req.url, route)) || {}; const activeRoute = routes.find(route => matchPath(req.url, route)) || {};
console.log(activeRoute);
const context = {} as any; const context = {} as any;
const isoData = {
name: 'fishing sux',
};
let auth: string = IsomorphicCookie.load('jwt', req); let auth: string = IsomorphicCookie.load('jwt', req);
let getSiteForm: GetSiteForm = {};
setAuth(getSiteForm, auth);
let promises: Promise<any>[] = [];
let siteData = lemmyHttp.getSite(getSiteForm);
promises.push(siteData);
if (activeRoute.fetchInitialData) {
promises.push(...activeRoute.fetchInitialData(auth, req.path));
}
let resolver = await Promise.all(promises);
let isoData: IsoData = {
path: req.path,
site: resolver[0],
routeData: resolver.slice(1, resolver.length),
};
console.log(activeRoute.path);
const wrapper = ( const wrapper = (
<StaticRouter location={req.url} context={context}> <StaticRouter location={req.url} context={isoData}>
<App /> <App site={isoData.site} />
</StaticRouter> </StaticRouter>
); );
if (context.url) { if (context.url) {
@ -49,24 +69,15 @@ server.get('/*', (req, res) => {
<!-- Icons --> <!-- Icons -->
<link rel="shortcut icon" type="image/svg+xml" href="/assets/favicon.svg" /> <link rel="shortcut icon" type="image/svg+xml" href="/assets/favicon.svg" />
<link rel="apple-touch-icon" href="/assets/apple-touch-icon.png" /> <!-- <link rel="apple-touch-icon" href="/assets/apple-touch-icon.png" /> -->
<!-- Styles --> <!-- Styles -->
<link rel="stylesheet" type="text/css" href="/assets/css/tribute.css" /> <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
<link rel="stylesheet" type="text/css" href="/assets/css/toastify.css" />
<link rel="stylesheet" type="text/css" href="/assets/css/choices.min.css" />
<link rel="stylesheet" type="text/css" href="/assets/css/tippy.css" />
<link rel="stylesheet" type="text/css" href="/assets/css/themes/litely.min.css" id="default-light" media="(prefers-color-scheme: light)" />
<link rel="stylesheet" type="text/css" href="/assets/css/themes/darkly.min.css" id="default-dark" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: dark)" />
<link rel="stylesheet" type="text/css" href="/assets/css/main.css" />
<!-- Scripts -->
<script async src="/assets/libs/sortable/sortable.min.js"></script>
</head> </head>
<body> <body>
<div id='root'>${renderToString(wrapper)}</div> <div id='root'>${renderToString(wrapper)}</div>
<script src='./static/bundle.js'></script> <script src='/static/js/client.js'></script>
</body> </body>
</html> </html>
`); `);

View file

@ -6,19 +6,24 @@ 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';
import { Symbols } from '../../shared/components/symbols'; import { Symbols } from '../../shared/components/symbols';
import { GetSiteResponse } from 'lemmy-js-client';
import './styles.scss';
export class App extends Component<any, any> { export interface AppProps {
site: GetSiteResponse;
}
export class App extends Component<AppProps, any> {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
} }
/* <Provider i18next={i18n}> */
render() { render() {
return ( return (
<> <>
<h1>Hi there!</h1>
{/* <Provider i18next={i18n}> */}
<div> <div>
<Navbar /> <Navbar site={this.props.site} />
<div class="mt-4 p-0 fl-1"> <div class="mt-4 p-0 fl-1">
<Switch> <Switch>
{routes.map(({ path, exact, component: C, ...rest }) => ( {routes.map(({ path, exact, component: C, ...rest }) => (
@ -35,7 +40,6 @@ export class App extends Component<any, any> {
</div> </div>
<Footer /> <Footer />
</div> </div>
{/* </Provider> */}
</> </>
); );
} }

View file

@ -15,11 +15,17 @@ import {
Site, Site,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { wsJsonToRes, toast, getPageFromProps } from '../utils'; import {
wsJsonToRes,
toast,
getPageFromProps,
isBrowser,
lemmyHttp,
setAuth,
} 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';
declare const Sortable: any;
const communityLimit = 100; const communityLimit = 100;
@ -46,20 +52,36 @@ export class Communities extends Component<any, CommunitiesState> {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.state = this.emptyState; this.state = this.emptyState;
this.subscription = WebSocketService.Instance.subject let isoData: IsoData;
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe(
msg => this.parseMessage(msg),
err => console.error(err),
() => console.log('complete')
);
this.refetch(); if (isBrowser()) {
WebSocketService.Instance.getSite(); 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
if (isoData.path == this.context.router.route.match.path) {
this.state.communities = isoData.routeData[0].communities;
this.state.loading = false;
} else {
this.refetch();
}
} }
componentWillUnmount() { componentWillUnmount() {
this.subscription.unsubscribe(); if (isBrowser()) {
this.subscription.unsubscribe();
}
} }
static getDerivedStateFromProps(props: any): CommunitiesProps { static getDerivedStateFromProps(props: any): CommunitiesProps {
@ -226,6 +248,19 @@ export class Communities extends Component<any, CommunitiesState> {
WebSocketService.Instance.listCommunities(listCommunitiesForm); WebSocketService.Instance.listCommunities(listCommunitiesForm);
} }
static fetchInitialData(auth: string, path: string): Promise<any>[] {
let pathSplit = path.split('/');
let page = pathSplit[2] ? Number(pathSplit[2]) : 1;
let listCommunitiesForm: ListCommunitiesForm = {
sort: SortType.TopAll,
limit: communityLimit,
page,
};
setAuth(listCommunitiesForm, auth);
return [lemmyHttp.listCommunities(listCommunitiesForm)];
}
parseMessage(msg: WebSocketJsonResponse) { parseMessage(msg: WebSocketJsonResponse) {
console.log(msg); console.log(msg);
let res = wsJsonToRes(msg); let res = wsJsonToRes(msg);
@ -241,8 +276,6 @@ export class Communities extends Component<any, CommunitiesState> {
this.state.loading = false; this.state.loading = false;
window.scrollTo(0, 0); window.scrollTo(0, 0);
this.setState(this.state); this.setState(this.state);
let table = document.querySelector('#community_table');
Sortable.initTable(table);
} else if (res.op == UserOperation.FollowCommunity) { } else if (res.op == UserOperation.FollowCommunity) {
let data = res.data as CommunityResponse; let data = res.data as CommunityResponse;
let found = this.state.communities.find(c => c.id == data.community.id); let found = this.state.communities.find(c => c.id == data.community.id);

View file

@ -48,28 +48,28 @@ export class Footer extends Component<any, FooterState> {
<li class="nav-item"> <li class="nav-item">
<span class="navbar-text">{this.state.version}</span> <span class="navbar-text">{this.state.version}</span>
</li> </li>
<li class="nav-item"> <li className="nav-item">
<Link class="nav-link" to="/modlog"> <Link className="nav-link" to="/modlog">
{i18n.t('modlog')} {i18n.t('modlog')}
</Link> </Link>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<Link class="nav-link" to="/instances"> <Link className="nav-link" to="/instances">
{i18n.t('instances')} {i18n.t('instances')}
</Link> </Link>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href={'/docs/index.html'}> <a className="nav-link" href={'/docs/index.html'}>
{i18n.t('docs')} {i18n.t('docs')}
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<Link class="nav-link" to="/sponsors"> <Link className="nav-link" to="/sponsors">
{i18n.t('donate')} {i18n.t('donate')}
</Link> </Link>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href={repoUrl}> <a className="nav-link" href={repoUrl}>
{i18n.t('code')} {i18n.t('code')}
</a> </a>
</li> </li>

View file

@ -33,6 +33,10 @@ import {
} from '../utils'; } from '../utils';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
interface NavbarProps {
site: GetSiteResponse;
}
interface NavbarState { interface NavbarState {
isLoggedIn: boolean; isLoggedIn: boolean;
expanded: boolean; expanded: boolean;
@ -42,51 +46,25 @@ interface NavbarState {
unreadCount: number; unreadCount: number;
searchParam: string; searchParam: string;
toggleSearch: boolean; toggleSearch: boolean;
siteLoading: boolean;
siteRes: GetSiteResponse; siteRes: GetSiteResponse;
onSiteBanner?(url: string): any; onSiteBanner?(url: string): any;
} }
export class Navbar extends Component<any, NavbarState> { export class Navbar extends Component<NavbarProps, NavbarState> {
private wsSub: Subscription; private wsSub: Subscription;
private userSub: Subscription; private userSub: Subscription;
private unreadCountSub: Subscription; private unreadCountSub: Subscription;
private searchTextField: RefObject<HTMLInputElement>; private searchTextField: RefObject<HTMLInputElement>;
emptyState: NavbarState = { emptyState: NavbarState = {
isLoggedIn: false, isLoggedIn: !!this.props.site.my_user,
unreadCount: 0, unreadCount: 0,
replies: [], replies: [],
mentions: [], mentions: [],
messages: [], messages: [],
expanded: false, expanded: false,
siteRes: { siteRes: this.props.site, // TODO this could probably go away
site: {
id: null,
name: null,
creator_id: null,
creator_name: null,
published: null,
number_of_users: null,
number_of_posts: null,
number_of_comments: null,
number_of_communities: null,
enable_downvotes: null,
open_registration: null,
enable_nsfw: null,
icon: null,
banner: null,
creator_preferred_username: null,
},
my_user: null,
admins: [],
banned: [],
online: null,
version: null,
federated_instances: null,
},
searchParam: '', searchParam: '',
toggleSearch: false, toggleSearch: false,
siteLoading: true,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -102,15 +80,31 @@ export class Navbar extends Component<any, NavbarState> {
() => console.log('complete') () => console.log('complete')
); );
WebSocketService.Instance.getSite(); // WebSocketService.Instance.getSite();
this.searchTextField = createRef(); this.searchTextField = createRef();
} }
// The login
if (this.props.site.my_user) {
UserService.Instance.user = this.props.site.my_user;
if (isBrowser()) {
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());
}
}
}
} }
componentDidMount() { componentDidMount() {
// Subscribe to jwt changes
if (isBrowser()) { if (isBrowser()) {
// Subscribe to jwt changes
this.userSub = UserService.Instance.jwtSub.subscribe(res => { this.userSub = UserService.Instance.jwtSub.subscribe(res => {
// A login // A login
if (res !== undefined) { if (res !== undefined) {
@ -118,6 +112,7 @@ export class Navbar extends Component<any, NavbarState> {
} else { } else {
this.state.isLoggedIn = false; this.state.isLoggedIn = false;
} }
console.log('a new login');
WebSocketService.Instance.getSite(); WebSocketService.Instance.getSite();
this.setState(this.state); this.setState(this.state);
}); });
@ -137,16 +132,16 @@ export class Navbar extends Component<any, NavbarState> {
} }
updateUrl() { updateUrl() {
/* const searchParam = this.state.searchParam; */ const searchParam = this.state.searchParam;
/* this.setState({ searchParam: '' }); */ this.setState({ searchParam: '' });
/* this.setState({ toggleSearch: false }); */ this.setState({ toggleSearch: false });
/* if (searchParam === '') { */ if (searchParam === '') {
/* this.context.router.history.push(`/search/`); */ this.context.router.history.push(`/search/`);
/* } else { */ } else {
/* this.context.router.history.push( */ this.context.router.history.push(
/* `/search/q/${searchParam}/type/All/sort/TopAll/page/1` */ `/search/q/${searchParam}/type/All/sort/TopAll/page/1`
/* ); */ );
/* } */ }
} }
handleSearchSubmit(i: Navbar, event: any) { handleSearchSubmit(i: Navbar, event: any) {
@ -185,37 +180,27 @@ export class Navbar extends Component<any, NavbarState> {
// TODO class active corresponding to current page // TODO class active corresponding to current page
navbar() { navbar() {
let user = UserService.Instance.user; let user = UserService.Instance.user;
let expandedClass = `${!this.state.expanded && 'collapse'} navbar-collapse`;
return ( return (
<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">
{!this.state.siteLoading ? ( <Link
<Link title={this.state.siteRes.version}
title={this.state.siteRes.version} className="d-flex align-items-center navbar-brand mr-md-3"
class="d-flex align-items-center navbar-brand mr-md-3" to="/"
to="/" >
> {this.state.siteRes.site.icon && showAvatars() && (
{this.state.siteRes.site.icon && showAvatars() && ( <img
<img src={pictrsAvatarThumbnail(this.state.siteRes.site.icon)}
src={pictrsAvatarThumbnail(this.state.siteRes.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.state.siteRes.site.name} </Link>
</Link>
) : (
<div class="navbar-item">
<svg class="icon icon-spinner spin">
<use xlinkHref="#icon-spinner"></use>
</svg>
</div>
)}
{this.state.isLoggedIn && ( {this.state.isLoggedIn && (
<Link <Link
class="ml-auto p-0 navbar-toggler nav-link border-0" className="ml-auto p-0 navbar-toggler nav-link border-0"
to="/inbox" to="/inbox"
title={i18n.t('inbox')} title={i18n.t('inbox')}
> >
@ -238,161 +223,155 @@ export class Navbar extends Component<any, NavbarState> {
> >
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
{/* TODO this isn't working <div
className={`${!this.state.expanded && 'collapse' className={`${!this.state.expanded && 'collapse'} navbar-collapse`}
} navbar-collapse`} >
*/} <ul class="navbar-nav my-2 mr-auto">
{!this.state.siteLoading && ( <li class="nav-item">
<div class="navbar-collapse"> <Link
<ul class="navbar-nav my-2 mr-auto"> className="nav-link"
<li class="nav-item"> to="/communities"
<Link title={i18n.t('communities')}
class="nav-link" >
to="/communities" {i18n.t('communities')}
title={i18n.t('communities')} </Link>
> </li>
{i18n.t('communities')} <li class="nav-item">
</Link> <Link
</li> className="nav-link"
<li class="nav-item"> to={{
<Link pathname: '/create_post',
class="nav-link" state: { prevPath: this.currentLocation },
to={{ }}
pathname: '/create_post', title={i18n.t('create_post')}
state: { prevPath: this.currentLocation }, >
}} {i18n.t('create_post')}
title={i18n.t('create_post')} </Link>
> </li>
{i18n.t('create_post')} <li class="nav-item">
</Link> <Link
</li> className="nav-link"
<li class="nav-item"> to="/create_community"
<Link title={i18n.t('create_community')}
class="nav-link" >
to="/create_community" {i18n.t('create_community')}
title={i18n.t('create_community')} </Link>
> </li>
{i18n.t('create_community')} <li className="nav-item">
</Link> <Link
</li> className="nav-link"
to="/sponsors"
title={i18n.t('donate_to_lemmy')}
>
<svg class="icon">
<use xlinkHref="#icon-coffee"></use>
</svg>
</Link>
</li>
</ul>
<ul class="navbar-nav my-2">
{this.canAdmin && (
<li className="nav-item"> <li className="nav-item">
<Link <Link
class="nav-link" className="nav-link"
to="/sponsors" to={`/admin`}
title={i18n.t('donate_to_lemmy')} title={i18n.t('admin_settings')}
> >
<svg class="icon"> <svg class="icon">
<use xlinkHref="#icon-coffee"></use> <use xlinkHref="#icon-settings"></use>
</svg> </svg>
</Link> </Link>
</li> </li>
</ul> )}
<ul class="navbar-nav my-2"> </ul>
{this.canAdmin && ( {!this.context.router.history.location.pathname.match(
/^\/search/
) && (
<form
class="form-inline"
onSubmit={linkEvent(this, this.handleSearchSubmit)}
>
<input
class={`form-control mr-0 search-input ${
this.state.toggleSearch ? 'show-input' : 'hide-input'
}`}
onInput={linkEvent(this, this.handleSearchParam)}
value={this.state.searchParam}
ref={this.searchTextField}
type="text"
placeholder={i18n.t('search')}
onBlur={linkEvent(this, this.handleSearchBlur)}
></input>
<button
name="search-btn"
onClick={linkEvent(this, this.handleSearchBtn)}
class="px-1 btn btn-link"
style="color: var(--gray)"
>
<svg class="icon">
<use xlinkHref="#icon-search"></use>
</svg>
</button>
</form>
)}
{this.state.isLoggedIn ? (
<>
<ul class="navbar-nav my-2">
<li className="nav-item"> <li className="nav-item">
<Link <Link
class="nav-link" className="nav-link"
to={`/admin`} to="/inbox"
title={i18n.t('admin_settings')} title={i18n.t('inbox')}
> >
<svg class="icon"> <svg class="icon">
<use xlinkHref="#icon-settings"></use> <use xlinkHref="#icon-bell"></use>
</svg> </svg>
</Link> {this.state.unreadCount > 0 && (
</li> <span class="ml-1 badge badge-light">
)} {this.state.unreadCount}
</ul>
{!this.context.router.history.location.pathname.match(
/^\/search/
) && (
<form
class="form-inline"
onSubmit={linkEvent(this, this.handleSearchSubmit)}
>
{/* TODO No idea why, but this class here fails
class={`form-control mr-0 search-input ${
this.state.toggleSearch ? 'show-input' : 'hide-input'
}`}
*/}
<input
onInput={linkEvent(this, this.handleSearchParam)}
value={this.state.searchParam}
type="text"
placeholder={i18n.t('search')}
onBlur={linkEvent(this, this.handleSearchBlur)}
></input>
<button
name="search-btn"
onClick={linkEvent(this, this.handleSearchBtn)}
class="px-1 btn btn-link"
style="color: var(--gray)"
>
<svg class="icon">
<use xlinkHref="#icon-search"></use>
</svg>
</button>
</form>
)}
{this.state.isLoggedIn ? (
<>
<ul class="navbar-nav my-2">
<li className="nav-item">
<Link
class="nav-link"
to="/inbox"
title={i18n.t('inbox')}
>
<svg class="icon">
<use xlinkHref="#icon-bell"></use>
</svg>
{this.state.unreadCount > 0 && (
<span class="ml-1 badge badge-light">
{this.state.unreadCount}
</span>
)}
</Link>
</li>
</ul>
<ul class="navbar-nav">
<li className="nav-item">
<Link
class="nav-link"
to={`/u/${user.name}`}
title={i18n.t('settings')}
>
<span>
{user.avatar && showAvatars() && (
<img
src={pictrsAvatarThumbnail(user.avatar)}
height="32"
width="32"
class="rounded-circle mr-2"
/>
)}
{user.preferred_username
? user.preferred_username
: user.name}
</span> </span>
</Link> )}
</li>
</ul>
</>
) : (
<ul class="navbar-nav my-2">
<li className="ml-2 nav-item">
<Link
class="btn btn-success"
to="/login"
title={i18n.t('login_sign_up')}
>
{i18n.t('login_sign_up')}
</Link> </Link>
</li> </li>
</ul> </ul>
)} <ul class="navbar-nav">
</div> <li className="nav-item">
)} <Link
className="nav-link"
to={`/u/${user.name}`}
title={i18n.t('settings')}
>
<span>
{user.avatar && showAvatars() && (
<img
src={pictrsAvatarThumbnail(user.avatar)}
height="32"
width="32"
class="rounded-circle mr-2"
/>
)}
{user.preferred_username
? user.preferred_username
: user.name}
</span>
</Link>
</li>
</ul>
</>
) : (
<ul class="navbar-nav my-2">
<li className="ml-2 nav-item">
<Link
className="btn btn-success"
to="/login"
title={i18n.t('login_sign_up')}
>
{i18n.t('login_sign_up')}
</Link>
</li>
</ul>
)}
</div>
</div> </div>
</nav> </nav>
); );
@ -405,7 +384,6 @@ export class Navbar extends Component<any, NavbarState> {
parseMessage(msg: WebSocketJsonResponse) { parseMessage(msg: WebSocketJsonResponse) {
let res = wsJsonToRes(msg); let res = wsJsonToRes(msg);
console.log(res);
if (msg.error) { if (msg.error) {
if (msg.error == 'not_logged_in') { if (msg.error == 'not_logged_in') {
UserService.Instance.logout(); UserService.Instance.logout();
@ -462,7 +440,10 @@ export class Navbar extends Component<any, NavbarState> {
notifyPrivateMessage(data.message, this.context.router); notifyPrivateMessage(data.message, this.context.router);
} }
} }
} else if (res.op == UserOperation.GetSite) { }
// TODO all this needs to be moved
else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse; let data = res.data as GetSiteResponse;
this.state.siteRes = data; this.state.siteRes = data;
@ -480,10 +461,9 @@ export class Navbar extends Component<any, NavbarState> {
} }
this.state.isLoggedIn = true; this.state.isLoggedIn = true;
} }
}
this.state.siteLoading = false; this.setState(this.state);
this.setState(this.state); }
} }
fetchUnreads() { fetchUnreads() {

View file

@ -1,17 +1,10 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { Helmet } from 'inferno-helmet'; import { Helmet } from 'inferno-helmet';
import { Subscription } from 'rxjs'; import { Site } from 'lemmy-js-client';
import { retryWhen, delay, take } from 'rxjs/operators';
import { WebSocketService } from '../services';
import {
GetSiteResponse,
Site,
WebSocketJsonResponse,
UserOperation,
} from 'lemmy-js-client';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
import { T } from 'inferno-i18next'; import { T } from 'inferno-i18next';
import { repoUrl, wsJsonToRes, toast } from '../utils'; import { repoUrl, isBrowser } from '../utils';
import { IsoData } from 'shared/interfaces';
interface SilverUser { interface SilverUser {
name: string; name: string;
@ -51,30 +44,27 @@ interface SponsorsState {
} }
export class Sponsors extends Component<any, SponsorsState> { export class Sponsors extends Component<any, SponsorsState> {
private subscription: Subscription;
private emptyState: SponsorsState = { private emptyState: SponsorsState = {
site: undefined, site: undefined,
}; };
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
this.state = this.emptyState; this.state = this.emptyState;
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')
);
WebSocketService.Instance.getSite(); let isoData: IsoData;
if (isBrowser()) {
isoData = window.isoData;
} else {
isoData = this.context.router.staticContext;
}
this.state.site = isoData.site.site;
} }
componentDidMount() { componentDidMount() {
window.scrollTo(0, 0); if (isBrowser()) {
} window.scrollTo(0, 0);
}
componentWillUnmount() {
this.subscription.unsubscribe();
} }
get documentTitle(): string { get documentTitle(): string {
@ -103,9 +93,11 @@ 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')}
@ -195,17 +187,4 @@ export class Sponsors extends Component<any, SponsorsState> {
</div> </div>
); );
} }
parseMessage(msg: WebSocketJsonResponse) {
console.log(msg);
let res = wsJsonToRes(msg);
if (msg.error) {
toast(i18n.t(msg.error), 'danger');
return;
} else if (res.op == UserOperation.GetSite) {
let data = res.data as GetSiteResponse;
this.state.site = data.site;
this.setState(this.state);
}
}
} }

View file

@ -0,0 +1,23 @@
// import '../../assets/css/themes/darkly.min.css';
@import '../../assets/css/tribute.css';
@import '../../assets/css/toastify.css';
@import '../../assets/css/choices.min.css';
@import '../../assets/css/tippy.css';
@import '../../assets/css/main.css';
// Bootstrap theme
@import "../../assets/css/themes/_variables.darkly.scss";
@import "../../../node_modules/bootstrap/scss/bootstrap";
// // Required
// @import "../../../node_modules/bootstrap/scss/functions";
// @import "../../../node_modules/bootstrap/scss/variables";
// @import "../../../node_modules/bootstrap/scss/mixins";
// // Optional
// @import "../../../node_modules/bootstrap/scss/reboot";
// @import "../../../node_modules/bootstrap/scss/type";
// @import "../../../node_modules/bootstrap/scss/images";
// @import "../../../node_modules/bootstrap/scss/code";
// @import "../../../node_modules/bootstrap/scss/grid";

View file

@ -13,3 +13,4 @@ const host = '192.168.50.60';
const port = 8536; const port = 8536;
const endpoint = `${host}:${port}`; const endpoint = `${host}:${port}`;
export const wsUri = `ws://${endpoint}/api/v1/ws`; export const wsUri = `ws://${endpoint}/api/v1/ws`;
export const httpUri = `http://${endpoint}/api/v1`;

View file

@ -1,3 +1,18 @@
import { GetSiteResponse } from 'lemmy-js-client';
export interface IsoData {
path: string;
routeData: any[];
site: GetSiteResponse;
// communities?: ListCommunitiesResponse;
}
declare global {
interface Window {
isoData: IsoData;
}
}
export enum CommentSortType { export enum CommentSortType {
Hot, Hot,
Top, Top,

View file

@ -1,8 +1,5 @@
import { BrowserRouter, Route, Switch } from 'inferno-router';
import { IRouteProps } from 'inferno-router/dist/Route'; import { IRouteProps } from 'inferno-router/dist/Route';
import { Main } from './components/main'; import { Main } from './components/main';
import { Navbar } from './components/navbar';
import { Footer } from './components/footer';
import { Login } from './components/login'; import { Login } from './components/login';
import { CreatePost } from './components/create-post'; import { CreatePost } from './components/create-post';
import { CreateCommunity } from './components/create-community'; import { CreateCommunity } from './components/create-community';
@ -20,7 +17,11 @@ import { Search } from './components/search';
import { Sponsors } from './components/sponsors'; import { Sponsors } from './components/sponsors';
import { Instances } from './components/instances'; import { Instances } from './components/instances';
export const routes: IRouteProps[] = [ interface IRoutePropsWithFetch extends IRouteProps {
fetchInitialData?(auth: string, path: string): Promise<any>[];
}
export const routes: IRoutePropsWithFetch[] = [
{ exact: true, path: `/`, component: Main }, { exact: true, path: `/`, component: Main },
{ {
path: `/home/data_type/:data_type/listing_type/:listing_type/sort/:sort/page/:page`, path: `/home/data_type/:data_type/listing_type/:listing_type/sort/:sort/page/:page`,
@ -36,8 +37,13 @@ export const routes: IRouteProps[] = [
{ {
path: `/communities/page/:page`, path: `/communities/page/:page`,
component: Communities, component: Communities,
fetchInitialData: (auth, path) => Communities.fetchInitialData(auth, path),
},
{
path: `/communities`,
component: Communities,
fetchInitialData: (auth, path) => Communities.fetchInitialData(auth, path),
}, },
{ path: `/communities`, component: Communities },
{ {
path: `/post/:id/comment/:comment_id`, path: `/post/:id/comment/:comment_id`,
component: Post, component: Post,

View file

@ -24,7 +24,7 @@ export class UserService {
if (jwt) { if (jwt) {
this.setClaims(jwt); this.setClaims(jwt);
} else { } else {
setTheme(); // setTheme();
console.log('No JWT cookie found.'); console.log('No JWT cookie found.');
} }
} }
@ -39,7 +39,7 @@ export class UserService {
this.claims = undefined; this.claims = undefined;
this.user = undefined; this.user = undefined;
IsomorphicCookie.remove('jwt'); IsomorphicCookie.remove('jwt');
setTheme(); // setTheme();
this.jwtSub.next(); this.jwtSub.next();
console.log('Logged out.'); console.log('Logged out.');
} }

View file

@ -393,7 +393,7 @@ export class WebSocketService {
this.ws.send(this.client.saveSiteConfig(form)); this.ws.send(this.client.saveSiteConfig(form));
} }
private setAuth(obj: any, throwErr: boolean = true) { public setAuth(obj: any, throwErr: boolean = true) {
obj.auth = UserService.Instance.auth; obj.auth = UserService.Instance.auth;
if (obj.auth == null && throwErr) { if (obj.auth == null && throwErr) {
toast(i18n.t('not_logged_in'), 'danger'); toast(i18n.t('not_logged_in'), 'danger');

View file

@ -42,8 +42,11 @@ import {
SearchResponse, SearchResponse,
CommentResponse, CommentResponse,
PostResponse, PostResponse,
LemmyHttp,
} from 'lemmy-js-client'; } from 'lemmy-js-client';
import { httpUri } from './env';
import { CommentSortType, DataType } from './interfaces'; import { CommentSortType, DataType } from './interfaces';
import { UserService, WebSocketService } from './services'; import { UserService, WebSocketService } from './services';
@ -74,6 +77,8 @@ export const postRefetchSeconds: number = 60 * 1000;
export const fetchLimit: number = 20; export const fetchLimit: number = 20;
export const mentionDropdownFetchLimit = 10; export const mentionDropdownFetchLimit = 10;
export const lemmyHttp = new LemmyHttp(httpUri);
export const languages = [ export const languages = [
{ code: 'ca', name: 'Català' }, { code: 'ca', name: 'Català' },
{ code: 'en', name: 'English' }, { code: 'en', name: 'English' },
@ -450,18 +455,18 @@ export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
// } // }
} }
export function loadCss(id: string, loc: string) { // export function loadCss(id: string, loc: string) {
if (!document.getElementById(id)) { // if (!document.getElementById(id)) {
var head = document.getElementsByTagName('head')[0]; // var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link'); // var link = document.createElement('link');
link.id = id; // link.id = id;
link.rel = 'stylesheet'; // link.rel = 'stylesheet';
link.type = 'text/css'; // link.type = 'text/css';
link.href = loc; // link.href = loc;
link.media = 'all'; // link.media = 'all';
head.appendChild(link); // head.appendChild(link);
} // }
} // }
export function objectFlip(obj: any) { export function objectFlip(obj: any) {
const ret = {}; const ret = {};
@ -828,10 +833,7 @@ export function getPageFromProps(props: any): number {
// return props.match.params.page ? Number(props.match.params.page) : 1; // return props.match.params.page ? Number(props.match.params.page) : 1;
} }
export function editCommentRes( export function editCommentRes(data: CommentResponse, comments: Comment[]) {
data: CommentResponse,
comments: Comment[]
) {
let found = comments.find(c => c.id == data.comment.id); let found = comments.find(c => c.id == data.comment.id);
if (found) { if (found) {
found.content = data.comment.content; found.content = data.comment.content;
@ -844,10 +846,7 @@ export function editCommentRes(
} }
} }
export function saveCommentRes( export function saveCommentRes(data: CommentResponse, comments: Comment[]) {
data: CommentResponse,
comments: Comment[]
) {
let found = comments.find(c => c.id == data.comment.id); let found = comments.find(c => c.id == data.comment.id);
if (found) { if (found) {
found.saved = data.comment.saved; found.saved = data.comment.saved;
@ -907,9 +906,7 @@ export function editPostRes(data: PostResponse, post: Post) {
} }
} }
export function commentsToFlatNodes( export function commentsToFlatNodes(comments: Comment[]): CommentNodeI[] {
comments: Comment[]
): CommentNodeI[] {
let nodes: CommentNodeI[] = []; let nodes: CommentNodeI[] = [];
for (let comment of comments) { for (let comment of comments) {
nodes.push({ comment: comment }); nodes.push({ comment: comment });
@ -1109,3 +1106,9 @@ export function siteBannerCss(banner: string): string {
export function isBrowser() { export function isBrowser() {
return typeof window !== 'undefined'; return typeof window !== 'undefined';
} }
export function setAuth(obj: any, auth: string) {
if (auth) {
obj.auth = auth;
}
}

View file

@ -1,14 +1,27 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "commonjs", "pretty": true,
"target": "esnext", "target": "esnext",
"sourceMap": true, "module": "esnext",
"inlineSources": true, "allowSyntheticDefaultImports": true,
"jsx": "preserve", "preserveConstEnums": true,
"importHelpers": true, "sourceMap": true,
"emitDecoratorMetadata": true, "moduleResolution": "node",
"experimentalDecorators": true, "lib": ["es2017", "dom"],
"esModuleInterop": true "types": [
}, "inferno"
"exclude": ["node_modules", "fuse.ts"] ],
"jsx": "preserve",
"noUnusedLocals": true,
"baseUrl": "./src",
"noEmit": true,
"skipLibCheck": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": [
"src/**/*",
"node_modules/inferno/dist/index.d.ts"
]
} }

70
webpack.config.js Normal file
View file

@ -0,0 +1,70 @@
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const nodeExternals = require('webpack-node-externals');
const path = require('path');
module.exports = function (env, _) {
const base = {
// mode: "production",
mode: 'development',
entry: './src/server/index.tsx', // Point to main file
output: {
path: path.resolve(process.cwd(), 'dist'),
filename: 'js/server.js',
publicPath: '/',
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
performance: {
hints: false,
},
module: {
rules: [
{
test: /\.(scss|css)$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader', // Run post css actions
options: {
plugins: function () {
// post css plugins, can be exported to postcss.config.js
return [require('precss'), require('autoprefixer')];
},
},
},
'sass-loader',
],
},
{
test: /\.(js|jsx|tsx|ts)$/, // All ts and tsx files will be process by
loaders: 'babel-loader', // first babel-loader, then ts-loader
exclude: /node_modules/, // ignore node_modules
},
],
},
devServer: {
host: '0.0.0.0',
contentBase: 'src/',
historyApiFallback: true,
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles/styles.css',
}),
],
};
// server-specific configuration
if (env.platform === 'server') {
base.target = 'node';
base.externals = [nodeExternals()];
}
// client-specific configurations
if (env.platform === 'client') {
base.entry = './src/client/index.tsx';
base.output.filename = 'js/client.js';
}
return base;
};

5002
yarn.lock

File diff suppressed because it is too large Load diff