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,
20 PrivateMessageResponse,
21 WebSocketJsonResponse,
22 } from '../interfaces';
25 pictrsAvatarThumbnail,
33 import { i18n } from '../i18next';
35 interface NavbarState {
38 replies: Array<Comment>;
39 mentions: Array<Comment>;
40 messages: Array<PrivateMessage>;
44 admins: Array<UserView>;
46 toggleSearch: boolean;
49 export class Navbar extends Component<any, NavbarState> {
50 private wsSub: Subscription;
51 private userSub: Subscription;
52 private searchTextField: RefObject<HTMLInputElement>;
53 emptyState: NavbarState = {
54 isLoggedIn: UserService.Instance.user !== undefined,
67 constructor(props: any, context: any) {
68 super(props, context);
69 this.state = this.emptyState;
71 // Subscribe to user changes
72 this.userSub = UserService.Instance.sub.subscribe(user => {
73 this.state.isLoggedIn = user.user !== undefined;
74 if (this.state.isLoggedIn) {
75 this.state.unreadCount = user.user.unreadCount;
76 this.requestNotificationPermission();
78 this.setState(this.state);
81 this.wsSub = WebSocketService.Instance.subject
82 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
84 msg => this.parseMessage(msg),
85 err => console.error(err),
86 () => console.log('complete')
89 if (this.state.isLoggedIn) {
90 this.requestNotificationPermission();
91 // TODO couldn't get re-logging in to re-fetch unreads
95 WebSocketService.Instance.getSite();
97 this.searchTextField = createRef();
100 handleSearchParam(i: Navbar, event: any) {
101 i.state.searchParam = event.target.value;
106 const searchParam = this.state.searchParam;
107 this.setState({ searchParam: '' });
108 this.setState({ toggleSearch: false });
109 if (searchParam === '') {
110 this.context.router.history.push(`/search/`);
112 this.context.router.history.push(
113 `/search/q/${searchParam}/type/all/sort/topall/page/1`
118 handleSearchSubmit(i: Navbar, event: any) {
119 event.preventDefault();
123 handleSearchBtn(i: Navbar, event: any) {
124 event.preventDefault();
125 i.setState({ toggleSearch: true });
127 i.searchTextField.current.focus();
128 const offsetWidth = i.searchTextField.current.offsetWidth;
129 if (i.state.searchParam && offsetWidth > 100) {
134 handleSearchBlur(i: Navbar, event: any) {
135 if (!(event.relatedTarget && event.relatedTarget.name !== 'search-btn')) {
136 i.state.toggleSearch = false;
142 return this.navbar();
145 componentWillUnmount() {
146 this.wsSub.unsubscribe();
147 this.userSub.unsubscribe();
150 // TODO class active corresponding to current page
153 <nav class="navbar navbar-expand-lg navbar-light shadow-sm p-0 px-3">
154 <div class="container">
155 <Link title={this.state.version} class="navbar-brand" to="/">
156 {this.state.siteName}
158 {this.state.isLoggedIn && (
160 class="ml-auto p-0 navbar-toggler nav-link border-0"
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 border-0"
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 my-2 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(
234 onSubmit={linkEvent(this, this.handleSearchSubmit)}
237 class={`form-control mr-0 search-input ${
238 this.state.toggleSearch ? 'show-input' : 'hide-input'
240 onInput={linkEvent(this, this.handleSearchParam)}
241 value={this.state.searchParam}
242 ref={this.searchTextField}
244 placeholder={i18n.t('search')}
245 onBlur={linkEvent(this, this.handleSearchBlur)}
249 onClick={linkEvent(this, this.handleSearchBtn)}
251 style="color: var(--gray)"
254 <use xlinkHref="#icon-search"></use>
259 <ul class="navbar-nav my-2">
261 <li className="nav-item">
265 title={i18n.t('admin_settings')}
268 <use xlinkHref="#icon-settings"></use>
274 {this.state.isLoggedIn ? (
276 <ul class="navbar-nav my-2">
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}
290 <ul class="navbar-nav">
291 <li className="nav-item">
294 to={`/u/${UserService.Instance.user.username}`}
295 title={i18n.t('settings')}
298 {UserService.Instance.user.avatar && showAvatars() && (
300 src={pictrsAvatarThumbnail(
301 UserService.Instance.user.avatar
305 class="rounded-circle mr-2"
308 {UserService.Instance.user.username}
315 <ul class="navbar-nav my-2">
316 <li className="nav-item">
318 class="btn btn-success"
320 title={i18n.t('login_sign_up')}
322 {i18n.t('login_sign_up')}
333 expandNavbar(i: Navbar) {
334 i.state.expanded = !i.state.expanded;
338 parseMessage(msg: WebSocketJsonResponse) {
339 let res = wsJsonToRes(msg);
341 if (msg.error == 'not_logged_in') {
342 UserService.Instance.logout();
346 } else if (msg.reconnect) {
348 } else if (res.op == UserOperation.GetReplies) {
349 let data = res.data as GetRepliesResponse;
350 let unreadReplies = data.replies.filter(r => !r.read);
352 this.state.replies = unreadReplies;
353 this.state.unreadCount = this.calculateUnreadCount();
354 this.setState(this.state);
355 this.sendUnreadCount();
356 } else if (res.op == UserOperation.GetUserMentions) {
357 let data = res.data as GetUserMentionsResponse;
358 let unreadMentions = data.mentions.filter(r => !r.read);
360 this.state.mentions = unreadMentions;
361 this.state.unreadCount = this.calculateUnreadCount();
362 this.setState(this.state);
363 this.sendUnreadCount();
364 } else if (res.op == UserOperation.GetPrivateMessages) {
365 let data = res.data as PrivateMessagesResponse;
366 let unreadMessages = data.messages.filter(r => !r.read);
368 this.state.messages = unreadMessages;
369 this.state.unreadCount = this.calculateUnreadCount();
370 this.setState(this.state);
371 this.sendUnreadCount();
372 } else if (res.op == UserOperation.CreateComment) {
373 let data = res.data as CommentResponse;
375 if (this.state.isLoggedIn) {
376 if (data.recipient_ids.includes(UserService.Instance.user.id)) {
377 this.state.replies.push(data.comment);
378 this.state.unreadCount++;
379 this.setState(this.state);
380 this.sendUnreadCount();
381 this.notify(data.comment);
384 } else if (res.op == UserOperation.CreatePrivateMessage) {
385 let data = res.data as PrivateMessageResponse;
387 if (this.state.isLoggedIn) {
388 if (data.message.recipient_id == UserService.Instance.user.id) {
389 this.state.messages.push(data.message);
390 this.state.unreadCount++;
391 this.setState(this.state);
392 this.sendUnreadCount();
393 this.notify(data.message);
396 } else if (res.op == UserOperation.GetSite) {
397 let data = res.data as GetSiteResponse;
399 if (data.site && !this.state.siteName) {
400 this.state.siteName = data.site.name;
401 this.state.version = data.version;
402 this.state.admins = data.admins;
403 this.setState(this.state);
409 if (this.state.isLoggedIn) {
410 let repliesForm: GetRepliesForm = {
411 sort: SortType[SortType.New],
417 let userMentionsForm: GetUserMentionsForm = {
418 sort: SortType[SortType.New],
424 let privateMessagesForm: GetPrivateMessagesForm = {
430 if (this.currentLocation !== '/inbox') {
431 WebSocketService.Instance.getReplies(repliesForm);
432 WebSocketService.Instance.getUserMentions(userMentionsForm);
433 WebSocketService.Instance.getPrivateMessages(privateMessagesForm);
438 get currentLocation() {
439 return this.context.router.history.location.pathname;
443 UserService.Instance.user.unreadCount = this.state.unreadCount;
444 UserService.Instance.sub.next({
445 user: UserService.Instance.user,
449 calculateUnreadCount(): number {
451 this.state.replies.filter(r => !r.read).length +
452 this.state.mentions.filter(r => !r.read).length +
453 this.state.messages.filter(r => !r.read).length
457 get canAdmin(): boolean {
459 UserService.Instance.user &&
460 this.state.admins.map(a => a.id).includes(UserService.Instance.user.id)
464 requestNotificationPermission() {
465 if (UserService.Instance.user) {
466 document.addEventListener('DOMContentLoaded', function () {
468 toast(i18n.t('notifications_error'), 'danger');
472 if (Notification.permission !== 'granted')
473 Notification.requestPermission();
478 notify(reply: Comment | PrivateMessage) {
479 let creator_name = reply.creator_name;
480 let creator_avatar = reply.creator_avatar
481 ? reply.creator_avatar
482 : `${window.location.protocol}//${window.location.host}/static/assets/apple-touch-icon.png`;
483 let link = isCommentType(reply)
484 ? `/post/${reply.post_id}/comment/${reply.id}`
486 let htmlBody = md.render(reply.content);
487 let body = reply.content; // Unfortunately the notifications API can't do html
497 if (Notification.permission !== 'granted') Notification.requestPermission();
499 var notification = new Notification(reply.creator_name, {
500 icon: creator_avatar,
504 notification.onclick = () => {
505 event.preventDefault();
506 this.context.router.history.push(link);