1 import { Component, linkEvent, createRef, RefObject } from 'inferno';
2 import { Link } from 'inferno-router';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import { WebSocketService, UserService } from '../services';
11 GetUserMentionsResponse,
12 GetPrivateMessagesForm,
13 PrivateMessagesResponse,
21 PrivateMessageResponse,
22 WebSocketJsonResponse,
24 } from '../interfaces';
27 pictrsAvatarThumbnail,
35 import { version } from '../version';
36 import { i18n } from '../i18next';
38 interface NavbarState {
41 replies: Array<Comment>;
42 mentions: Array<Comment>;
43 messages: Array<PrivateMessage>;
46 admins: Array<UserView>;
48 toggleSearch: boolean;
51 export class Navbar extends Component<any, NavbarState> {
52 private wsSub: Subscription;
53 private userSub: Subscription;
54 private searchTextField: RefObject<HTMLInputElement>;
55 emptyState: NavbarState = {
56 isLoggedIn: UserService.Instance.user !== undefined,
68 constructor(props: any, context: any) {
69 super(props, context);
70 this.state = this.emptyState;
72 // Subscribe to user changes
73 this.userSub = UserService.Instance.sub.subscribe(user => {
74 this.state.isLoggedIn = user.user !== undefined;
75 if (this.state.isLoggedIn) {
76 this.state.unreadCount = user.user.unreadCount;
77 this.requestNotificationPermission();
79 this.setState(this.state);
82 this.wsSub = WebSocketService.Instance.subject
83 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
85 msg => this.parseMessage(msg),
86 err => console.error(err),
87 () => console.log('complete')
90 if (this.state.isLoggedIn) {
91 this.requestNotificationPermission();
92 // TODO couldn't get re-logging in to re-fetch unreads
96 WebSocketService.Instance.getSite();
98 this.searchTextField = createRef();
101 handleSearchParam(i: Navbar, event: any) {
102 i.state.searchParam = event.target.value;
107 const searchParam = this.state.searchParam;
108 this.setState({ searchParam: '' });
109 this.setState({ toggleSearch: false });
110 if (searchParam === '') {
111 this.context.router.history.push(`/search/`);
113 this.context.router.history.push(
114 `/search/q/${searchParam}/type/all/sort/topall/page/1`
119 handleSearchSubmit(i: Navbar, event: any) {
120 event.preventDefault();
124 handleSearchBtn(i: Navbar, event: any) {
125 event.preventDefault();
126 i.setState({ toggleSearch: true });
128 i.searchTextField.current.focus();
129 const offsetWidth = i.searchTextField.current.offsetWidth;
130 if (i.state.searchParam && offsetWidth > 100) {
135 handleSearchBlur(i: Navbar, event: any) {
136 if (!(event.relatedTarget && event.relatedTarget.name !== 'search-btn')) {
137 i.state.toggleSearch = false;
143 return this.navbar();
146 componentWillUnmount() {
147 this.wsSub.unsubscribe();
148 this.userSub.unsubscribe();
151 // TODO class active corresponding to current page
154 <nav class="container-fluid navbar navbar-expand-md navbar-light shadow p-0 px-3">
155 <Link title={version} class="navbar-brand" to="/">
156 {this.state.siteName}
158 {this.state.isLoggedIn && (
160 class="ml-auto p-0 navbar-toggler nav-link"
162 title={i18n.t('inbox')}
165 <use xlinkHref="#icon-bell"></use>
167 {this.state.unreadCount > 0 && (
168 <span class="ml-1 badge badge-light">
169 {this.state.unreadCount}
175 class="navbar-toggler"
178 onClick={linkEvent(this, this.expandNavbar)}
179 data-tippy-content={i18n.t('expand_here')}
181 <span class="navbar-toggler-icon"></span>
184 className={`${!this.state.expanded && 'collapse'} navbar-collapse`}
186 <ul class="navbar-nav mr-auto">
187 <li class="nav-item">
191 title={i18n.t('communities')}
193 {i18n.t('communities')}
196 <li class="nav-item">
200 pathname: '/create_post',
201 state: { prevPath: this.currentLocation },
203 title={i18n.t('create_post')}
205 {i18n.t('create_post')}
208 <li class="nav-item">
211 to="/create_community"
212 title={i18n.t('create_community')}
214 {i18n.t('create_community')}
217 <li className="nav-item">
221 title={i18n.t('donate_to_lemmy')}
224 <use xlinkHref="#icon-coffee"></use>
229 {!this.context.router.history.location.pathname.match(
232 <div class="nav-item my-2">
235 onSubmit={linkEvent(this, this.handleSearchSubmit)}
238 class={`form-control mr-0 search-input ${
239 this.state.toggleSearch ? 'show-input' : 'hide-input'
241 onInput={linkEvent(this, this.handleSearchParam)}
242 value={this.state.searchParam}
243 ref={this.searchTextField}
245 placeholder={i18n.t('search')}
246 onBlur={linkEvent(this, this.handleSearchBlur)}
250 onClick={linkEvent(this, this.handleSearchBtn)}
252 style="color: var(--gray)"
255 <use xlinkHref="#icon-search"></use>
261 <ul class="navbar-nav my-2">
263 <li className="nav-item">
267 title={i18n.t('admin_settings')}
270 <use xlinkHref="#icon-settings"></use>
275 {this.state.isLoggedIn ? (
277 <li className="nav-item">
278 <Link class="nav-link" to="/inbox" title={i18n.t('inbox')}>
280 <use xlinkHref="#icon-bell"></use>
282 {this.state.unreadCount > 0 && (
283 <span class="ml-1 badge badge-light">
284 {this.state.unreadCount}
289 <li className="nav-item">
292 to={`/u/${UserService.Instance.user.username}`}
293 title={i18n.t('settings')}
296 {UserService.Instance.user.avatar && showAvatars() && (
298 src={pictrsAvatarThumbnail(
299 UserService.Instance.user.avatar
303 class="rounded-circle mr-2"
306 {UserService.Instance.user.username}
315 title={i18n.t('login_sign_up')}
317 {i18n.t('login_sign_up')}
326 expandNavbar(i: Navbar) {
327 i.state.expanded = !i.state.expanded;
331 parseMessage(msg: WebSocketJsonResponse) {
332 let res = wsJsonToRes(msg);
334 if (msg.error == 'not_logged_in') {
335 UserService.Instance.logout();
339 } else if (msg.reconnect) {
341 } else if (res.op == UserOperation.GetReplies) {
342 let data = res.data as GetRepliesResponse;
343 let unreadReplies = data.replies.filter(r => !r.read);
345 this.state.replies = unreadReplies;
346 this.state.unreadCount = this.calculateUnreadCount();
347 this.setState(this.state);
348 this.sendUnreadCount();
349 } else if (res.op == UserOperation.GetUserMentions) {
350 let data = res.data as GetUserMentionsResponse;
351 let unreadMentions = data.mentions.filter(r => !r.read);
353 this.state.mentions = unreadMentions;
354 this.state.unreadCount = this.calculateUnreadCount();
355 this.setState(this.state);
356 this.sendUnreadCount();
357 } else if (res.op == UserOperation.GetPrivateMessages) {
358 let data = res.data as PrivateMessagesResponse;
359 let unreadMessages = data.messages.filter(r => !r.read);
361 this.state.messages = unreadMessages;
362 this.state.unreadCount = this.calculateUnreadCount();
363 this.setState(this.state);
364 this.sendUnreadCount();
365 } else if (res.op == UserOperation.CreateComment) {
366 let data = res.data as CommentResponse;
368 if (this.state.isLoggedIn) {
369 if (data.recipient_ids.includes(UserService.Instance.user.id)) {
370 this.state.replies.push(data.comment);
371 this.state.unreadCount++;
372 this.setState(this.state);
373 this.sendUnreadCount();
374 this.notify(data.comment);
377 } else if (res.op == UserOperation.CreatePrivateMessage) {
378 let data = res.data as PrivateMessageResponse;
380 if (this.state.isLoggedIn) {
381 if (data.message.recipient_id == UserService.Instance.user.id) {
382 this.state.messages.push(data.message);
383 this.state.unreadCount++;
384 this.setState(this.state);
385 this.sendUnreadCount();
386 this.notify(data.message);
389 } else if (res.op == UserOperation.GetSite) {
390 let data = res.data as GetSiteResponse;
392 if (data.site && !this.state.siteName) {
393 this.state.siteName = data.site.name;
394 this.state.admins = data.admins;
395 WebSocketService.Instance.site = data.site;
396 WebSocketService.Instance.admins = data.admins;
398 this.setState(this.state);
404 if (this.state.isLoggedIn) {
405 let repliesForm: GetRepliesForm = {
406 sort: SortType[SortType.New],
412 let userMentionsForm: GetUserMentionsForm = {
413 sort: SortType[SortType.New],
419 let privateMessagesForm: GetPrivateMessagesForm = {
425 if (this.currentLocation !== '/inbox') {
426 WebSocketService.Instance.getReplies(repliesForm);
427 WebSocketService.Instance.getUserMentions(userMentionsForm);
428 WebSocketService.Instance.getPrivateMessages(privateMessagesForm);
433 get currentLocation() {
434 return this.context.router.history.location.pathname;
438 UserService.Instance.user.unreadCount = this.state.unreadCount;
439 UserService.Instance.sub.next({
440 user: UserService.Instance.user,
444 calculateUnreadCount(): number {
446 this.state.replies.filter(r => !r.read).length +
447 this.state.mentions.filter(r => !r.read).length +
448 this.state.messages.filter(r => !r.read).length
452 get canAdmin(): boolean {
454 UserService.Instance.user &&
455 this.state.admins.map(a => a.id).includes(UserService.Instance.user.id)
459 requestNotificationPermission() {
460 if (UserService.Instance.user) {
461 document.addEventListener('DOMContentLoaded', function () {
463 toast(i18n.t('notifications_error'), 'danger');
467 if (Notification.permission !== 'granted')
468 Notification.requestPermission();
473 notify(reply: Comment | PrivateMessage) {
474 let creator_name = reply.creator_name;
475 let creator_avatar = reply.creator_avatar
476 ? reply.creator_avatar
477 : `${window.location.protocol}//${window.location.host}/static/assets/apple-touch-icon.png`;
478 let link = isCommentType(reply)
479 ? `/post/${reply.post_id}/comment/${reply.id}`
481 let htmlBody = md.render(reply.content);
482 let body = reply.content; // Unfortunately the notifications API can't do html
492 if (Notification.permission !== 'granted') Notification.requestPermission();
494 var notification = new Notification(reply.creator_name, {
495 icon: creator_avatar,
499 notification.onclick = () => {
500 event.preventDefault();
501 this.context.router.history.push(link);