Merge pull request #1089 from jwhitmarsh/fix/1039

Refactor lets to consts
This commit is contained in:
SleeplessOne1917 2023-06-05 23:30:31 +00:00 committed by GitHub
commit 8181e4a1ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 734 additions and 727 deletions

View file

@ -37,7 +37,7 @@
"no-useless-constructor": 0, "no-useless-constructor": 0,
"no-useless-escape": 0, "no-useless-escape": 0,
"no-var": 0, "no-var": 0,
"prefer-const": 0, "prefer-const": 1,
"prefer-rest-params": 0, "prefer-rest-params": 0,
"quote-props": 0, "quote-props": 0,
"unicorn/filename-case": 0 "unicorn/filename-case": 0

View file

@ -213,15 +213,15 @@ server.listen(Number(port), hostname, () => {
function setForwardedHeaders(headers: IncomingHttpHeaders): { function setForwardedHeaders(headers: IncomingHttpHeaders): {
[key: string]: string; [key: string]: string;
} { } {
let out: { [key: string]: string } = {}; const out: { [key: string]: string } = {};
if (headers.host) { if (headers.host) {
out.host = headers.host; out.host = headers.host;
} }
let realIp = headers["x-real-ip"]; const realIp = headers["x-real-ip"];
if (realIp) { if (realIp) {
out["x-real-ip"] = realIp as string; out["x-real-ip"] = realIp as string;
} }
let forwardedFor = headers["x-forwarded-for"]; const forwardedFor = headers["x-forwarded-for"];
if (forwardedFor) { if (forwardedFor) {
out["x-forwarded-for"] = forwardedFor as string; out["x-forwarded-for"] = forwardedFor as string;
} }

View file

@ -80,7 +80,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
// Subscribe to jwt changes // Subscribe to jwt changes
if (isBrowser()) { if (isBrowser()) {
// On the first load, check the unreads // On the first load, check the unreads
let auth = myAuth(false); const auth = myAuth(false);
if (auth && UserService.Instance.myUserInfo) { if (auth && UserService.Instance.myUserInfo) {
this.requestNotificationPermission(); this.requestNotificationPermission();
WebSocketService.Instance.send( WebSocketService.Instance.send(
@ -438,13 +438,13 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
} }
get moderatesSomething(): boolean { get moderatesSomething(): boolean {
let mods = UserService.Instance.myUserInfo?.moderates; const mods = UserService.Instance.myUserInfo?.moderates;
let moderatesS = (mods && mods.length > 0) || false; const moderatesS = (mods && mods.length > 0) || false;
return amAdmin() || moderatesS; return amAdmin() || moderatesS;
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
if (msg.error == "not_logged_in") { if (msg.error == "not_logged_in") {
@ -453,7 +453,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
return; return;
} else if (msg.reconnect) { } else if (msg.reconnect) {
console.log(i18n.t("websocket_reconnected")); console.log(i18n.t("websocket_reconnected"));
let auth = myAuth(false); const auth = myAuth(false);
if (UserService.Instance.myUserInfo && auth) { if (UserService.Instance.myUserInfo && auth) {
WebSocketService.Instance.send( WebSocketService.Instance.send(
wsClient.userJoin({ wsClient.userJoin({
@ -463,13 +463,13 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
this.fetchUnreads(); this.fetchUnreads();
} }
} else if (op == UserOperation.GetUnreadCount) { } else if (op == UserOperation.GetUnreadCount) {
let data = wsJsonToRes<GetUnreadCountResponse>(msg); const data = wsJsonToRes<GetUnreadCountResponse>(msg);
this.setState({ this.setState({
unreadInboxCount: data.replies + data.mentions + data.private_messages, unreadInboxCount: data.replies + data.mentions + data.private_messages,
}); });
this.sendUnreadCount(); this.sendUnreadCount();
} else if (op == UserOperation.GetReportCount) { } else if (op == UserOperation.GetReportCount) {
let data = wsJsonToRes<GetReportCountResponse>(msg); const data = wsJsonToRes<GetReportCountResponse>(msg);
this.setState({ this.setState({
unreadReportCount: unreadReportCount:
data.post_reports + data.post_reports +
@ -478,13 +478,13 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
}); });
this.sendReportUnread(); this.sendReportUnread();
} else if (op == UserOperation.GetUnreadRegistrationApplicationCount) { } else if (op == UserOperation.GetUnreadRegistrationApplicationCount) {
let data = const data =
wsJsonToRes<GetUnreadRegistrationApplicationCountResponse>(msg); wsJsonToRes<GetUnreadRegistrationApplicationCountResponse>(msg);
this.setState({ unreadApplicationCount: data.registration_applications }); this.setState({ unreadApplicationCount: data.registration_applications });
this.sendApplicationUnread(); this.sendApplicationUnread();
} else if (op == UserOperation.CreateComment) { } else if (op == UserOperation.CreateComment) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if ( if (
mui && mui &&
data.recipient_ids.includes(mui.local_user_view.local_user.id) data.recipient_ids.includes(mui.local_user_view.local_user.id)
@ -496,7 +496,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
notifyComment(data.comment_view, this.context.router); notifyComment(data.comment_view, this.context.router);
} }
} else if (op == UserOperation.CreatePrivateMessage) { } else if (op == UserOperation.CreatePrivateMessage) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
if ( if (
data.private_message_view.recipient.id == data.private_message_view.recipient.id ==
@ -514,16 +514,16 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
fetchUnreads() { fetchUnreads() {
console.log("Fetching inbox unreads..."); console.log("Fetching inbox unreads...");
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let unreadForm: GetUnreadCount = { const unreadForm: GetUnreadCount = {
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.getUnreadCount(unreadForm)); WebSocketService.Instance.send(wsClient.getUnreadCount(unreadForm));
console.log("Fetching reports..."); console.log("Fetching reports...");
let reportCountForm: GetReportCount = { const reportCountForm: GetReportCount = {
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.getReportCount(reportCountForm)); WebSocketService.Instance.send(wsClient.getReportCount(reportCountForm));
@ -531,7 +531,7 @@ export class Navbar extends Component<NavbarProps, NavbarState> {
if (amAdmin()) { if (amAdmin()) {
console.log("Fetching applications..."); console.log("Fetching applications...");
let applicationCountForm: GetUnreadRegistrationApplicationCount = { const applicationCountForm: GetUnreadRegistrationApplicationCount = {
auth, auth,
}; };
WebSocketService.Instance.send( WebSocketService.Instance.send(

View file

@ -8,8 +8,8 @@ interface Props {
export class Theme extends Component<Props> { export class Theme extends Component<Props> {
render() { render() {
let user = UserService.Instance.myUserInfo; const user = UserService.Instance.myUserInfo;
let hasTheme = user?.local_user_view.local_user.theme !== "browser"; const hasTheme = user?.local_user_view.local_user.theme !== "browser";
if (user && hasTheme) { if (user && hasTheme) {
return ( return (

View file

@ -69,7 +69,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
} }
render() { render() {
let initialContent = const initialContent =
typeof this.props.node !== "number" typeof this.props.node !== "number"
? this.props.edit ? this.props.edit
? this.props.node.comment_view.comment.content ? this.props.node.comment_view.comment.content
@ -113,17 +113,17 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
formId: string; formId: string;
languageId?: number; languageId?: number;
}) { }) {
let content = msg.val; const content = msg.val;
let language_id = msg.languageId; const language_id = msg.languageId;
let node = this.props.node; const node = this.props.node;
this.setState({ formId: msg.formId }); this.setState({ formId: msg.formId });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (typeof node === "number") { if (typeof node === "number") {
let postId = node; const postId = node;
let form: CreateComment = { const form: CreateComment = {
content, content,
form_id: this.state.formId, form_id: this.state.formId,
post_id: postId, post_id: postId,
@ -133,7 +133,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
WebSocketService.Instance.send(wsClient.createComment(form)); WebSocketService.Instance.send(wsClient.createComment(form));
} else { } else {
if (this.props.edit) { if (this.props.edit) {
let form: EditComment = { const form: EditComment = {
content, content,
form_id: this.state.formId, form_id: this.state.formId,
comment_id: node.comment_view.comment.id, comment_id: node.comment_view.comment.id,
@ -142,7 +142,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
}; };
WebSocketService.Instance.send(wsClient.editComment(form)); WebSocketService.Instance.send(wsClient.editComment(form));
} else { } else {
let form: CreateComment = { const form: CreateComment = {
content, content,
form_id: this.state.formId, form_id: this.state.formId,
post_id: node.comment_view.post.id, post_id: node.comment_view.post.id,
@ -161,7 +161,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
// Only do the showing and hiding if logged in // Only do the showing and hiding if logged in
@ -170,7 +170,7 @@ export class CommentForm extends Component<CommentFormProps, CommentFormState> {
op == UserOperation.CreateComment || op == UserOperation.CreateComment ||
op == UserOperation.EditComment op == UserOperation.EditComment
) { ) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
// This only finishes this form, if the randomly generated form_id matches the one received // This only finishes this form, if the randomly generated form_id matches the one received
if (this.state.formId && this.state.formId == data.form_id) { if (this.state.formId && this.state.formId == data.form_id) {

View file

@ -147,7 +147,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
// TODO see if there's a better way to do this, and all willReceiveProps // TODO see if there's a better way to do this, and all willReceiveProps
componentWillReceiveProps(nextProps: CommentNodeProps) { componentWillReceiveProps(nextProps: CommentNodeProps) {
let cv = nextProps.node.comment_view; const cv = nextProps.node.comment_view;
this.setState({ this.setState({
my_vote: cv.my_vote, my_vote: cv.my_vote,
upvotes: cv.counts.upvotes, upvotes: cv.counts.upvotes,
@ -159,18 +159,18 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
render() { render() {
let node = this.props.node; const node = this.props.node;
let cv = this.props.node.comment_view; const cv = this.props.node.comment_view;
let purgeTypeText = const purgeTypeText =
this.state.purgeType == PurgeType.Comment this.state.purgeType == PurgeType.Comment
? i18n.t("purge_comment") ? i18n.t("purge_comment")
: `${i18n.t("purge")} ${cv.creator.name}`; : `${i18n.t("purge")} ${cv.creator.name}`;
let canMod_ = const canMod_ =
canMod(cv.creator.id, this.props.moderators, this.props.admins) && canMod(cv.creator.id, this.props.moderators, this.props.admins) &&
cv.community.local; cv.community.local;
let canModOnSelf = const canModOnSelf =
canMod( canMod(
cv.creator.id, cv.creator.id,
this.props.moderators, this.props.moderators,
@ -178,31 +178,31 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
UserService.Instance.myUserInfo, UserService.Instance.myUserInfo,
true true
) && cv.community.local; ) && cv.community.local;
let canAdmin_ = const canAdmin_ =
canAdmin(cv.creator.id, this.props.admins) && cv.community.local; canAdmin(cv.creator.id, this.props.admins) && cv.community.local;
let canAdminOnSelf = const canAdminOnSelf =
canAdmin( canAdmin(
cv.creator.id, cv.creator.id,
this.props.admins, this.props.admins,
UserService.Instance.myUserInfo, UserService.Instance.myUserInfo,
true true
) && cv.community.local; ) && cv.community.local;
let isMod_ = isMod(cv.creator.id, this.props.moderators); const isMod_ = isMod(cv.creator.id, this.props.moderators);
let isAdmin_ = const isAdmin_ =
isAdmin(cv.creator.id, this.props.admins) && cv.community.local; isAdmin(cv.creator.id, this.props.admins) && cv.community.local;
let amCommunityCreator_ = amCommunityCreator( const amCommunityCreator_ = amCommunityCreator(
cv.creator.id, cv.creator.id,
this.props.moderators this.props.moderators
); );
let borderColor = this.props.node.depth const borderColor = this.props.node.depth
? colorList[(this.props.node.depth - 1) % colorList.length] ? colorList[(this.props.node.depth - 1) % colorList.length]
: colorList[0]; : colorList[0];
let moreRepliesBorderColor = this.props.node.depth const moreRepliesBorderColor = this.props.node.depth
? colorList[this.props.node.depth % colorList.length] ? colorList[this.props.node.depth % colorList.length]
: colorList[0]; : colorList[0];
let showMoreChildren = const showMoreChildren =
this.props.viewType == CommentViewType.Tree && this.props.viewType == CommentViewType.Tree &&
!this.state.collapsed && !this.state.collapsed &&
node.children.length == 0 && node.children.length == 0 &&
@ -1035,7 +1035,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
get commentReplyOrMentionRead(): boolean { get commentReplyOrMentionRead(): boolean {
let cv = this.props.node.comment_view; const cv = this.props.node.comment_view;
if (this.isPersonMentionType(cv)) { if (this.isPersonMentionType(cv)) {
return cv.person_mention.read; return cv.person_mention.read;
@ -1047,12 +1047,12 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
linkBtn(small = false) { linkBtn(small = false) {
let cv = this.props.node.comment_view; const cv = this.props.node.comment_view;
let classnames = classNames("btn btn-link btn-animate text-muted", { const classnames = classNames("btn btn-link btn-animate text-muted", {
"btn-sm": small, "btn-sm": small,
}); });
let title = this.props.showContext const title = this.props.showContext
? i18n.t("show_context") ? i18n.t("show_context")
: i18n.t("link"); : i18n.t("link");
@ -1096,7 +1096,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
get commentUnlessRemoved(): string { get commentUnlessRemoved(): string {
let comment = this.props.node.comment_view.comment; const comment = this.props.node.comment_view.comment;
return comment.removed return comment.removed
? `*${i18n.t("removed")}*` ? `*${i18n.t("removed")}*`
: comment.deleted : comment.deleted
@ -1113,9 +1113,9 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleBlockUserClick(i: CommentNode) { handleBlockUserClick(i: CommentNode) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let blockUserForm: BlockPerson = { const blockUserForm: BlockPerson = {
person_id: i.props.node.comment_view.creator.id, person_id: i.props.node.comment_view.creator.id,
block: true, block: true,
auth, auth,
@ -1125,10 +1125,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleDeleteClick(i: CommentNode) { handleDeleteClick(i: CommentNode) {
let comment = i.props.node.comment_view.comment; const comment = i.props.node.comment_view.comment;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let deleteForm: DeleteComment = { const deleteForm: DeleteComment = {
comment_id: comment.id, comment_id: comment.id,
deleted: !comment.deleted, deleted: !comment.deleted,
auth, auth,
@ -1138,11 +1138,11 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleSaveCommentClick(i: CommentNode) { handleSaveCommentClick(i: CommentNode) {
let cv = i.props.node.comment_view; const cv = i.props.node.comment_view;
let save = cv.saved == undefined ? true : !cv.saved; const save = cv.saved == undefined ? true : !cv.saved;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: SaveComment = { const form: SaveComment = {
comment_id: cv.comment.id, comment_id: cv.comment.id,
save, save,
auth, auth,
@ -1160,8 +1160,8 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
handleCommentUpvote(event: any) { handleCommentUpvote(event: any) {
event.preventDefault(); event.preventDefault();
let myVote = this.state.my_vote; const myVote = this.state.my_vote;
let newVote = myVote == 1 ? 0 : 1; const newVote = myVote == 1 ? 0 : 1;
if (myVote == 1) { if (myVote == 1) {
this.setState({ this.setState({
@ -1183,9 +1183,9 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
this.setState({ my_vote: newVote }); this.setState({ my_vote: newVote });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: CreateCommentLike = { const form: CreateCommentLike = {
comment_id: this.props.node.comment_view.comment.id, comment_id: this.props.node.comment_view.comment.id,
score: newVote, score: newVote,
auth, auth,
@ -1197,8 +1197,8 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
handleCommentDownvote(event: any) { handleCommentDownvote(event: any) {
event.preventDefault(); event.preventDefault();
let myVote = this.state.my_vote; const myVote = this.state.my_vote;
let newVote = myVote == -1 ? 0 : -1; const newVote = myVote == -1 ? 0 : -1;
if (myVote == 1) { if (myVote == 1) {
this.setState({ this.setState({
@ -1220,9 +1220,9 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
this.setState({ my_vote: newVote }); this.setState({ my_vote: newVote });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: CreateCommentLike = { const form: CreateCommentLike = {
comment_id: this.props.node.comment_view.comment.id, comment_id: this.props.node.comment_view.comment.id,
score: newVote, score: newVote,
auth, auth,
@ -1242,11 +1242,11 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleReportSubmit(i: CommentNode) { handleReportSubmit(i: CommentNode) {
let comment = i.props.node.comment_view.comment; const comment = i.props.node.comment_view.comment;
let reason = i.state.reportReason; const reason = i.state.reportReason;
let auth = myAuth(); const auth = myAuth();
if (reason && auth) { if (reason && auth) {
let form: CreateCommentReport = { const form: CreateCommentReport = {
comment_id: comment.id, comment_id: comment.id,
reason, reason,
auth, auth,
@ -1272,10 +1272,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleModRemoveSubmit(i: CommentNode) { handleModRemoveSubmit(i: CommentNode) {
let comment = i.props.node.comment_view.comment; const comment = i.props.node.comment_view.comment;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: RemoveComment = { const form: RemoveComment = {
comment_id: comment.id, comment_id: comment.id,
removed: !comment.removed, removed: !comment.removed,
reason: i.state.removeReason, reason: i.state.removeReason,
@ -1288,10 +1288,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleDistinguishClick(i: CommentNode) { handleDistinguishClick(i: CommentNode) {
let comment = i.props.node.comment_view.comment; const comment = i.props.node.comment_view.comment;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: DistinguishComment = { const form: DistinguishComment = {
comment_id: comment.id, comment_id: comment.id,
distinguished: !comment.distinguished, distinguished: !comment.distinguished,
auth, auth,
@ -1314,17 +1314,17 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleMarkRead(i: CommentNode) { handleMarkRead(i: CommentNode) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (i.isPersonMentionType(i.props.node.comment_view)) { if (i.isPersonMentionType(i.props.node.comment_view)) {
let form: MarkPersonMentionAsRead = { const form: MarkPersonMentionAsRead = {
person_mention_id: i.props.node.comment_view.person_mention.id, person_mention_id: i.props.node.comment_view.person_mention.id,
read: !i.props.node.comment_view.person_mention.read, read: !i.props.node.comment_view.person_mention.read,
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.markPersonMentionAsRead(form)); WebSocketService.Instance.send(wsClient.markPersonMentionAsRead(form));
} else if (i.isCommentReplyType(i.props.node.comment_view)) { } else if (i.isCommentReplyType(i.props.node.comment_view)) {
let form: MarkCommentReplyAsRead = { const form: MarkCommentReplyAsRead = {
comment_reply_id: i.props.node.comment_view.comment_reply.id, comment_reply_id: i.props.node.comment_view.comment_reply.id,
read: !i.props.node.comment_view.comment_reply.read, read: !i.props.node.comment_view.comment_reply.read,
auth, auth,
@ -1371,16 +1371,16 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleModBanBothSubmit(i: CommentNode) { handleModBanBothSubmit(i: CommentNode) {
let cv = i.props.node.comment_view; const cv = i.props.node.comment_view;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (i.state.banType == BanType.Community) { if (i.state.banType == BanType.Community) {
// If its an unban, restore all their data // If its an unban, restore all their data
let ban = !cv.creator_banned_from_community; const ban = !cv.creator_banned_from_community;
if (ban == false) { if (ban == false) {
i.setState({ removeData: false }); i.setState({ removeData: false });
} }
let form: BanFromCommunity = { const form: BanFromCommunity = {
person_id: cv.creator.id, person_id: cv.creator.id,
community_id: cv.community.id, community_id: cv.community.id,
ban, ban,
@ -1392,11 +1392,11 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
WebSocketService.Instance.send(wsClient.banFromCommunity(form)); WebSocketService.Instance.send(wsClient.banFromCommunity(form));
} else { } else {
// If its an unban, restore all their data // If its an unban, restore all their data
let ban = !cv.creator.banned; const ban = !cv.creator.banned;
if (ban == false) { if (ban == false) {
i.setState({ removeData: false }); i.setState({ removeData: false });
} }
let form: BanPerson = { const form: BanPerson = {
person_id: cv.creator.id, person_id: cv.creator.id,
ban, ban,
remove_data: i.state.removeData, remove_data: i.state.removeData,
@ -1433,17 +1433,17 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
handlePurgeSubmit(i: CommentNode, event: any) { handlePurgeSubmit(i: CommentNode, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (i.state.purgeType == PurgeType.Person) { if (i.state.purgeType == PurgeType.Person) {
let form: PurgePerson = { const form: PurgePerson = {
person_id: i.props.node.comment_view.creator.id, person_id: i.props.node.comment_view.creator.id,
reason: i.state.purgeReason, reason: i.state.purgeReason,
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.purgePerson(form)); WebSocketService.Instance.send(wsClient.purgePerson(form));
} else if (i.state.purgeType == PurgeType.Comment) { } else if (i.state.purgeType == PurgeType.Comment) {
let form: PurgeComment = { const form: PurgeComment = {
comment_id: i.props.node.comment_view.comment.id, comment_id: i.props.node.comment_view.comment.id,
reason: i.state.purgeReason, reason: i.state.purgeReason,
auth, auth,
@ -1464,10 +1464,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleAddModToCommunity(i: CommentNode) { handleAddModToCommunity(i: CommentNode) {
let cv = i.props.node.comment_view; const cv = i.props.node.comment_view;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: AddModToCommunity = { const form: AddModToCommunity = {
person_id: cv.creator.id, person_id: cv.creator.id,
community_id: cv.community.id, community_id: cv.community.id,
added: !isMod(cv.creator.id, i.props.moderators), added: !isMod(cv.creator.id, i.props.moderators),
@ -1487,10 +1487,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleAddAdmin(i: CommentNode) { handleAddAdmin(i: CommentNode) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let creatorId = i.props.node.comment_view.creator.id; const creatorId = i.props.node.comment_view.creator.id;
let form: AddAdmin = { const form: AddAdmin = {
person_id: creatorId, person_id: creatorId,
added: !isAdmin(creatorId, i.props.admins), added: !isAdmin(creatorId, i.props.admins),
auth, auth,
@ -1509,10 +1509,10 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleTransferCommunity(i: CommentNode) { handleTransferCommunity(i: CommentNode) {
let cv = i.props.node.comment_view; const cv = i.props.node.comment_view;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: TransferCommunity = { const form: TransferCommunity = {
community_id: cv.community.id, community_id: cv.community.id,
person_id: cv.creator.id, person_id: cv.creator.id,
auth, auth,
@ -1531,8 +1531,8 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
get isCommentNew(): boolean { get isCommentNew(): boolean {
let now = moment.utc().subtract(10, "minutes"); const now = moment.utc().subtract(10, "minutes");
let then = moment.utc(this.props.node.comment_view.comment.published); const then = moment.utc(this.props.node.comment_view.comment.published);
return now.isBefore(then); return now.isBefore(then);
} }
@ -1551,7 +1551,7 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
handleFetchChildren(i: CommentNode) { handleFetchChildren(i: CommentNode) {
let form: GetComments = { const form: GetComments = {
post_id: i.props.node.comment_view.post.id, post_id: i.props.node.comment_view.post.id,
parent_id: i.props.node.comment_view.comment.id, parent_id: i.props.node.comment_view.comment.id,
max_depth: commentTreeMaxDepth, max_depth: commentTreeMaxDepth,
@ -1575,17 +1575,17 @@ export class CommentNode extends Component<CommentNodeProps, CommentNodeState> {
} }
get pointsTippy(): string { get pointsTippy(): string {
let points = i18n.t("number_of_points", { const points = i18n.t("number_of_points", {
count: Number(this.state.score), count: Number(this.state.score),
formattedCount: numToSI(this.state.score), formattedCount: numToSI(this.state.score),
}); });
let upvotes = i18n.t("number_of_upvotes", { const upvotes = i18n.t("number_of_upvotes", {
count: Number(this.state.upvotes), count: Number(this.state.upvotes),
formattedCount: numToSI(this.state.upvotes), formattedCount: numToSI(this.state.upvotes),
}); });
let downvotes = i18n.t("number_of_downvotes", { const downvotes = i18n.t("number_of_downvotes", {
count: Number(this.state.downvotes), count: Number(this.state.downvotes),
formattedCount: numToSI(this.state.downvotes), formattedCount: numToSI(this.state.downvotes),
}); });

View file

@ -28,7 +28,7 @@ export class CommentNodes extends Component<CommentNodesProps, any> {
} }
render() { render() {
let maxComments = this.props.maxCommentsShown ?? this.props.nodes.length; const maxComments = this.props.maxCommentsShown ?? this.props.nodes.length;
return ( return (
<div className="comments"> <div className="comments">

View file

@ -23,16 +23,16 @@ export class CommentReport extends Component<CommentReportProps, any> {
} }
render() { render() {
let r = this.props.report; const r = this.props.report;
let comment = r.comment; const comment = r.comment;
let tippyContent = i18n.t( const tippyContent = i18n.t(
r.comment_report.resolved ? "unresolve_report" : "resolve_report" r.comment_report.resolved ? "unresolve_report" : "resolve_report"
); );
// Set the original post data ( a troll could change it ) // Set the original post data ( a troll could change it )
comment.content = r.comment_report.original_comment_text; comment.content = r.comment_report.original_comment_text;
let comment_view: CommentView = { const comment_view: CommentView = {
comment, comment,
creator: r.comment_creator, creator: r.comment_creator,
post: r.post, post: r.post,
@ -45,7 +45,7 @@ export class CommentReport extends Component<CommentReportProps, any> {
my_vote: r.my_vote, my_vote: r.my_vote,
}; };
let node: CommentNodeI = { const node: CommentNodeI = {
comment_view, comment_view,
children: [], children: [],
depth: 0, depth: 0,
@ -102,9 +102,9 @@ export class CommentReport extends Component<CommentReportProps, any> {
} }
handleResolveReport(i: CommentReport) { handleResolveReport(i: CommentReport) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: ResolveCommentReport = { const form: ResolveCommentReport = {
report_id: i.props.report.comment_report.id, report_id: i.props.report.comment_report.id,
resolved: !i.props.report.comment_report.resolved, resolved: !i.props.report.comment_report.resolved,
auth, auth,

View file

@ -12,8 +12,8 @@ export class BannerIconHeader extends Component<BannerIconHeaderProps, any> {
} }
render() { render() {
let banner = this.props.banner; const banner = this.props.banner;
let icon = this.props.icon; const icon = this.props.icon;
return ( return (
<div className="position-relative mb-2"> <div className="position-relative mb-2">
{banner && <PictrsImage src={banner} banner alt="" />} {banner && <PictrsImage src={banner} banner alt="" />}

View file

@ -12,7 +12,7 @@ export class EmojiMart extends Component<EmojiMartProps> {
this.handleEmojiClick = this.handleEmojiClick.bind(this); this.handleEmojiClick = this.handleEmojiClick.bind(this);
} }
componentDidMount() { componentDidMount() {
let div: any = document.getElementById("emoji-picker"); const div: any = document.getElementById("emoji-picker");
if (div) { if (div) {
div.appendChild( div.appendChild(
getEmojiMart(this.handleEmojiClick, this.props.pickerOptions) getEmojiMart(this.handleEmojiClick, this.props.pickerOptions)

View file

@ -14,9 +14,9 @@ interface HtmlTagsProps {
/// Taken from https://metatags.io/ /// Taken from https://metatags.io/
export class HtmlTags extends Component<HtmlTagsProps, any> { export class HtmlTags extends Component<HtmlTagsProps, any> {
render() { render() {
let url = httpExternalPath(this.props.path); const url = httpExternalPath(this.props.path);
let desc = this.props.description; const desc = this.props.description;
let image = this.props.image; const image = this.props.image;
return ( return (
<Helmet title={this.props.title}> <Helmet title={this.props.title}>

View file

@ -31,12 +31,12 @@ export class LanguageSelect extends Component<LanguageSelectProps, any> {
// Necessary because there is no HTML way to set selected for multiple in value= // Necessary because there is no HTML way to set selected for multiple in value=
setSelectedValues() { setSelectedValues() {
let ids = this.props.selectedLanguageIds?.map(toString); const ids = this.props.selectedLanguageIds?.map(toString);
if (ids) { if (ids) {
let select = (document.getElementById(this.id) as HTMLSelectElement) const select = (document.getElementById(this.id) as HTMLSelectElement)
.options; .options;
for (let i = 0; i < select.length; i++) { for (let i = 0; i < select.length; i++) {
let o = select[i]; const o = select[i];
if (ids.includes(o.value)) { if (ids.includes(o.value)) {
o.selected = true; o.selected = true;
} }
@ -130,8 +130,8 @@ export class LanguageSelect extends Component<LanguageSelectProps, any> {
} }
handleLanguageChange(i: LanguageSelect, event: any) { handleLanguageChange(i: LanguageSelect, event: any) {
let options: HTMLOptionElement[] = Array.from(event.target.options); const options: HTMLOptionElement[] = Array.from(event.target.options);
let selected: number[] = options const selected: number[] = options
.filter(o => o.selected) .filter(o => o.selected)
.map(o => Number(o.value)); .map(o => Number(o.value));

View file

@ -85,7 +85,7 @@ export class MarkdownTextArea extends Component<
} }
componentDidMount() { componentDidMount() {
let textarea: any = document.getElementById(this.id); const textarea: any = document.getElementById(this.id);
if (textarea) { if (textarea) {
autosize(textarea); autosize(textarea);
this.tribute.attach(textarea); this.tribute.attach(textarea);
@ -132,7 +132,7 @@ export class MarkdownTextArea extends Component<
} }
render() { render() {
let languageId = this.state.languageId; const languageId = this.state.languageId;
return ( return (
<form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}> <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
@ -321,7 +321,7 @@ export class MarkdownTextArea extends Component<
handleEmoji(i: MarkdownTextArea, e: any) { handleEmoji(i: MarkdownTextArea, e: any) {
let value = e.native; let value = e.native;
if (value == null) { if (value == null) {
let emoji = customEmojisLookup.get(e.id)?.custom_emoji; const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
if (emoji) { if (emoji) {
value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`; value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
} }
@ -330,7 +330,7 @@ export class MarkdownTextArea extends Component<
content: `${i.state.content ?? ""} ${value} `, content: `${i.state.content ?? ""} ${value} `,
}); });
i.contentChange(); i.contentChange();
let textarea: any = document.getElementById(i.id); const textarea: any = document.getElementById(i.id);
autosize.update(textarea); autosize.update(textarea);
} }
@ -420,7 +420,7 @@ export class MarkdownTextArea extends Component<
contentChange() { contentChange() {
// Coerces the undefineds to empty strings, for replacing in the DB // Coerces the undefineds to empty strings, for replacing in the DB
let content = this.state.content ?? ""; const content = this.state.content ?? "";
this.props.onContentChange?.(content); this.props.onContentChange?.(content);
} }
@ -441,7 +441,7 @@ export class MarkdownTextArea extends Component<
handleSubmit(i: MarkdownTextArea, event: any) { handleSubmit(i: MarkdownTextArea, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ loading: true }); i.setState({ loading: true });
let msg = { const msg = {
val: i.state.content, val: i.state.content,
formId: i.formId, formId: i.formId,
languageId: i.state.languageId, languageId: i.state.languageId,
@ -589,7 +589,7 @@ export class MarkdownTextArea extends Component<
} }
simpleInsert(chars: string) { simpleInsert(chars: string) {
let content = this.state.content; const content = this.state.content;
if (!content) { if (!content) {
this.setState({ content: `${chars} ` }); this.setState({ content: `${chars} ` });
} else { } else {
@ -598,7 +598,7 @@ export class MarkdownTextArea extends Component<
}); });
} }
let textarea: any = document.getElementById(this.id); const textarea: any = document.getElementById(this.id);
textarea.focus(); textarea.focus();
setTimeout(() => { setTimeout(() => {
autosize.update(textarea); autosize.update(textarea);
@ -608,8 +608,8 @@ export class MarkdownTextArea extends Component<
handleInsertSpoiler(i: MarkdownTextArea, event: any) { handleInsertSpoiler(i: MarkdownTextArea, event: any) {
event.preventDefault(); event.preventDefault();
let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`; const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
let afterChars = "\n:::\n"; const afterChars = "\n:::\n";
i.simpleSurroundBeforeAfter(beforeChars, afterChars); i.simpleSurroundBeforeAfter(beforeChars, afterChars);
} }

View file

@ -15,13 +15,13 @@ export class MomentTime extends Component<MomentTimeProps, any> {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
let lang = getLanguages(); const lang = getLanguages();
moment.locale(lang); moment.locale(lang);
} }
createdAndModifiedTimes() { createdAndModifiedTimes() {
let updated = this.props.updated; const updated = this.props.updated;
let line = `${capitalizeFirstLetter(i18n.t("created"))}: ${this.format( let line = `${capitalizeFirstLetter(i18n.t("created"))}: ${this.format(
this.props.published this.props.published
)}`; )}`;
@ -45,7 +45,7 @@ export class MomentTime extends Component<MomentTimeProps, any> {
</span> </span>
); );
} else { } else {
let published = this.props.published; const published = this.props.published;
return ( return (
<span <span
className="pointer unselectable" className="pointer unselectable"

View file

@ -51,17 +51,17 @@ export class PictrsImage extends Component<PictrsImageProps, any> {
// sample url: // sample url:
// http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg // http://localhost:8535/pictrs/image/file.png?thumbnail=256&format=jpg
let split = this.props.src.split("/pictrs/image/"); const split = this.props.src.split("/pictrs/image/");
// If theres not multiple, then its not a pictrs image // If theres not multiple, then its not a pictrs image
if (split.length == 1) { if (split.length == 1) {
return this.props.src; return this.props.src;
} }
let host = split[0]; const host = split[0];
let path = split[1]; const path = split[1];
let params = { format }; const params = { format };
if (this.props.thumbnail) { if (this.props.thumbnail) {
params["thumbnail"] = thumbnailSize; params["thumbnail"] = thumbnailSize;
@ -69,8 +69,8 @@ export class PictrsImage extends Component<PictrsImageProps, any> {
params["thumbnail"] = iconThumbnailSize; params["thumbnail"] = iconThumbnailSize;
} }
let paramsStr = new URLSearchParams(params).toString(); const paramsStr = new URLSearchParams(params).toString();
let out = `${host}/pictrs/image/${path}?${paramsStr}`; const out = `${host}/pictrs/image/${path}?${paramsStr}`;
return out; return out;
} }

View file

@ -35,9 +35,9 @@ export class RegistrationApplication extends Component<
} }
render() { render() {
let a = this.props.application; const a = this.props.application;
let ra = this.props.application.registration_application; const ra = this.props.application.registration_application;
let accepted = a.creator_local_user.accepted_application; const accepted = a.creator_local_user.accepted_application;
return ( return (
<div> <div>
@ -116,10 +116,10 @@ export class RegistrationApplication extends Component<
} }
handleApprove(i: RegistrationApplication) { handleApprove(i: RegistrationApplication) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
i.setState({ denyExpanded: false }); i.setState({ denyExpanded: false });
let form: ApproveRegistrationApplication = { const form: ApproveRegistrationApplication = {
id: i.props.application.registration_application.id, id: i.props.application.registration_application.id,
approve: true, approve: true,
auth, auth,
@ -133,9 +133,9 @@ export class RegistrationApplication extends Component<
handleDeny(i: RegistrationApplication) { handleDeny(i: RegistrationApplication) {
if (i.state.denyExpanded) { if (i.state.denyExpanded) {
i.setState({ denyExpanded: false }); i.setState({ denyExpanded: false });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: ApproveRegistrationApplication = { const form: ApproveRegistrationApplication = {
id: i.props.application.registration_application.id, id: i.props.application.registration_application.id,
approve: false, approve: false,
deny_reason: i.state.denyReason, deny_reason: i.state.denyReason,

View file

@ -79,7 +79,7 @@ export class CommunityForm extends Component<
this.parseMessage = this.parseMessage.bind(this); this.parseMessage = this.parseMessage.bind(this);
this.subscription = wsSubscribe(this.parseMessage); this.subscription = wsSubscribe(this.parseMessage);
let cv = this.props.community_view; const cv = this.props.community_view;
if (cv) { if (cv) {
this.state = { this.state = {
@ -301,14 +301,14 @@ export class CommunityForm extends Component<
handleCreateCommunitySubmit(i: CommunityForm, event: any) { handleCreateCommunitySubmit(i: CommunityForm, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ loading: true }); i.setState({ loading: true });
let cForm = i.state.form; const cForm = i.state.form;
let auth = myAuth(); const auth = myAuth();
let cv = i.props.community_view; const cv = i.props.community_view;
if (auth) { if (auth) {
if (cv) { if (cv) {
let form: EditCommunity = { const form: EditCommunity = {
community_id: cv.community.id, community_id: cv.community.id,
title: cForm.title, title: cForm.title,
description: cForm.description, description: cForm.description,
@ -323,7 +323,7 @@ export class CommunityForm extends Component<
WebSocketService.Instance.send(wsClient.editCommunity(form)); WebSocketService.Instance.send(wsClient.editCommunity(form));
} else { } else {
if (cForm.title && cForm.name) { if (cForm.title && cForm.name) {
let form: CreateCommunity = { const form: CreateCommunity = {
name: cForm.name, name: cForm.name,
title: cForm.title, title: cForm.title,
description: cForm.description, description: cForm.description,
@ -390,7 +390,7 @@ export class CommunityForm extends Component<
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
// Errors handled by top level pages // Errors handled by top level pages
@ -398,15 +398,15 @@ export class CommunityForm extends Component<
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.CreateCommunity) { } else if (op == UserOperation.CreateCommunity) {
let data = wsJsonToRes<CommunityResponse>(msg); const data = wsJsonToRes<CommunityResponse>(msg);
this.props.onCreate?.(data.community_view); this.props.onCreate?.(data.community_view);
// Update myUserInfo // Update myUserInfo
let community = data.community_view.community; const community = data.community_view.community;
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
let person = mui.local_user_view.person; const person = mui.local_user_view.person;
mui.follows.push({ mui.follows.push({
community, community,
follower: person, follower: person,
@ -417,21 +417,21 @@ export class CommunityForm extends Component<
}); });
} }
} else if (op == UserOperation.EditCommunity) { } else if (op == UserOperation.EditCommunity) {
let data = wsJsonToRes<CommunityResponse>(msg); const data = wsJsonToRes<CommunityResponse>(msg);
this.setState({ loading: false }); this.setState({ loading: false });
this.props.onEdit?.(data.community_view); this.props.onEdit?.(data.community_view);
let community = data.community_view.community; const community = data.community_view.community;
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
let followFound = mui.follows.findIndex( const followFound = mui.follows.findIndex(
f => f.community.id == community.id f => f.community.id == community.id
); );
if (followFound) { if (followFound) {
mui.follows[followFound].community = community; mui.follows[followFound].community = community;
} }
let moderatesFound = mui.moderates.findIndex( const moderatesFound = mui.moderates.findIndex(
f => f.community.id == community.id f => f.community.id == community.id
); );
if (moderatesFound) { if (moderatesFound) {

View file

@ -18,22 +18,22 @@ export class CommunityLink extends Component<CommunityLinkProps, any> {
} }
render() { render() {
let community = this.props.community; const community = this.props.community;
let name_: string, title: string, link: string; let name_: string, title: string, link: string;
let local = community.local == null ? true : community.local; const local = community.local == null ? true : community.local;
if (local) { if (local) {
name_ = community.name; name_ = community.name;
title = community.title; title = community.title;
link = `/c/${community.name}`; link = `/c/${community.name}`;
} else { } else {
let domain = hostname(community.actor_id); const domain = hostname(community.actor_id);
name_ = `${community.name}@${domain}`; name_ = `${community.name}@${domain}`;
title = `${community.title}@${domain}`; title = `${community.title}@${domain}`;
link = !this.props.realLink ? `/c/${name_}` : community.actor_id; link = !this.props.realLink ? `/c/${name_}` : community.actor_id;
} }
let apubName = `!${name_}`; const apubName = `!${name_}`;
let displayName = this.props.useApubName ? apubName : title; const displayName = this.props.useApubName ? apubName : title;
return !this.props.realLink ? ( return !this.props.realLink ? (
<Link <Link
title={apubName} title={apubName}
@ -55,7 +55,7 @@ export class CommunityLink extends Component<CommunityLinkProps, any> {
} }
avatarAndName(displayName: string) { avatarAndName(displayName: string) {
let icon = this.props.community.icon; const icon = this.props.community.icon;
return ( return (
<> <>
{!this.props.hideAvatar && {!this.props.hideAvatar &&

View file

@ -124,8 +124,8 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
communityTitle() { communityTitle() {
let community = this.props.community_view.community; const community = this.props.community_view.community;
let subscribed = this.props.community_view.subscribed; const subscribed = this.props.community_view.subscribed;
return ( return (
<div> <div>
<h5 className="mb-0"> <h5 className="mb-0">
@ -178,8 +178,8 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
badges() { badges() {
let community_view = this.props.community_view; const community_view = this.props.community_view;
let counts = community_view.counts; const counts = community_view.counts;
return ( return (
<ul className="my-1 list-inline"> <ul className="my-1 list-inline">
<li className="list-inline-item badge badge-secondary"> <li className="list-inline-item badge badge-secondary">
@ -284,7 +284,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
createPost() { createPost() {
let cv = this.props.community_view; const cv = this.props.community_view;
return ( return (
<Link <Link
className={`btn btn-secondary btn-block mb-2 ${ className={`btn btn-secondary btn-block mb-2 ${
@ -298,7 +298,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
subscribe() { subscribe() {
let community_view = this.props.community_view; const community_view = this.props.community_view;
return ( return (
<div className="mb-2"> <div className="mb-2">
{community_view.subscribed == "NotSubscribed" && ( {community_view.subscribed == "NotSubscribed" && (
@ -314,8 +314,8 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
blockCommunity() { blockCommunity() {
let community_view = this.props.community_view; const community_view = this.props.community_view;
let blocked = this.props.community_view.blocked; const blocked = this.props.community_view.blocked;
return ( return (
<div className="mb-2"> <div className="mb-2">
@ -340,7 +340,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
description() { description() {
let desc = this.props.community_view.community.description; const desc = this.props.community_view.community.description;
return ( return (
desc && ( desc && (
<div className="md-div" dangerouslySetInnerHTML={mdToHtml(desc)} /> <div className="md-div" dangerouslySetInnerHTML={mdToHtml(desc)} />
@ -349,7 +349,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
adminButtons() { adminButtons() {
let community_view = this.props.community_view; const community_view = this.props.community_view;
return ( return (
<> <>
<ul className="list-inline mb-1 text-muted font-weight-bold"> <ul className="list-inline mb-1 text-muted font-weight-bold">
@ -536,9 +536,9 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleDeleteClick(i: Sidebar, event: any) { handleDeleteClick(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let deleteForm: DeleteCommunity = { const deleteForm: DeleteCommunity = {
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
deleted: !i.props.community_view.community.deleted, deleted: !i.props.community_view.community.deleted,
auth, auth,
@ -552,10 +552,10 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
handleLeaveModTeamClick(i: Sidebar) { handleLeaveModTeamClick(i: Sidebar) {
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
let auth = myAuth(); const auth = myAuth();
if (auth && mui) { if (auth && mui) {
let form: AddModToCommunity = { const form: AddModToCommunity = {
person_id: mui.local_user_view.person.id, person_id: mui.local_user_view.person.id,
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
added: false, added: false,
@ -572,10 +572,10 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleUnsubscribe(i: Sidebar, event: any) { handleUnsubscribe(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let community_id = i.props.community_view.community.id; const community_id = i.props.community_view.community.id;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: FollowCommunity = { const form: FollowCommunity = {
community_id, community_id,
follow: false, follow: false,
auth, auth,
@ -584,7 +584,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
// Update myUserInfo // Update myUserInfo
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
mui.follows = mui.follows.filter(i => i.community.id != community_id); mui.follows = mui.follows.filter(i => i.community.id != community_id);
} }
@ -592,10 +592,10 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleSubscribe(i: Sidebar, event: any) { handleSubscribe(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let community_id = i.props.community_view.community.id; const community_id = i.props.community_view.community.id;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: FollowCommunity = { const form: FollowCommunity = {
community_id, community_id,
follow: true, follow: true,
auth, auth,
@ -604,7 +604,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
} }
// Update myUserInfo // Update myUserInfo
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
mui.follows.push({ mui.follows.push({
community: i.props.community_view.community, community: i.props.community_view.community,
@ -635,9 +635,9 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleModRemoveSubmit(i: Sidebar, event: any) { handleModRemoveSubmit(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let removeForm: RemoveCommunity = { const removeForm: RemoveCommunity = {
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
removed: !i.props.community_view.community.removed, removed: !i.props.community_view.community.removed,
reason: i.state.removeReason, reason: i.state.removeReason,
@ -661,9 +661,9 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handlePurgeSubmit(i: Sidebar, event: any) { handlePurgeSubmit(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: PurgeCommunity = { const form: PurgeCommunity = {
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
reason: i.state.purgeReason, reason: i.state.purgeReason,
auth, auth,
@ -675,9 +675,9 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleBlock(i: Sidebar, event: any) { handleBlock(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let blockCommunityForm: BlockCommunity = { const blockCommunityForm: BlockCommunity = {
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
block: true, block: true,
auth, auth,
@ -690,9 +690,9 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
handleUnblock(i: Sidebar, event: any) { handleUnblock(i: Sidebar, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let blockCommunityForm: BlockCommunity = { const blockCommunityForm: BlockCommunity = {
community_id: i.props.community_view.community.id, community_id: i.props.community_view.community.id,
block: false, block: false,
auth, auth,

View file

@ -70,7 +70,7 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
loading: false, loading: false,
}; };
} else { } else {
let cAuth = myAuth(); const cAuth = myAuth();
if (cAuth) { if (cAuth) {
WebSocketService.Instance.send( WebSocketService.Instance.send(
wsClient.getBannedPersons({ wsClient.getBannedPersons({
@ -85,11 +85,11 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
let auth = req.auth; const auth = req.auth;
if (auth) { if (auth) {
let bannedPersonsForm: GetBannedPersons = { auth }; const bannedPersonsForm: GetBannedPersons = { auth };
promises.push(req.client.getBannedPersons(bannedPersonsForm)); promises.push(req.client.getBannedPersons(bannedPersonsForm));
promises.push(req.client.getFederatedInstances({ auth })); promises.push(req.client.getFederatedInstances({ auth }));
} }
@ -236,7 +236,7 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
} }
handleLeaveAdminTeam(i: AdminSettings) { handleLeaveAdminTeam(i: AdminSettings) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
i.setState({ leaveAdminTeamLoading: true }); i.setState({ leaveAdminTeamLoading: true });
WebSocketService.Instance.send(wsClient.leaveAdmin({ auth })); WebSocketService.Instance.send(wsClient.leaveAdmin({ auth }));
@ -244,7 +244,7 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -252,20 +252,20 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.EditSite) { } else if (op == UserOperation.EditSite) {
let data = wsJsonToRes<SiteResponse>(msg); const data = wsJsonToRes<SiteResponse>(msg);
this.setState(s => ((s.siteRes.site_view = data.site_view), s)); this.setState(s => ((s.siteRes.site_view = data.site_view), s));
toast(i18n.t("site_saved")); toast(i18n.t("site_saved"));
} else if (op == UserOperation.GetBannedPersons) { } else if (op == UserOperation.GetBannedPersons) {
let data = wsJsonToRes<BannedPersonsResponse>(msg); const data = wsJsonToRes<BannedPersonsResponse>(msg);
this.setState({ banned: data.banned, loading: false }); this.setState({ banned: data.banned, loading: false });
} else if (op == UserOperation.LeaveAdmin) { } else if (op == UserOperation.LeaveAdmin) {
let data = wsJsonToRes<GetSiteResponse>(msg); const data = wsJsonToRes<GetSiteResponse>(msg);
this.setState(s => ((s.siteRes.site_view = data.site_view), s)); this.setState(s => ((s.siteRes.site_view = data.site_view), s));
this.setState({ leaveAdminTeamLoading: false }); this.setState({ leaveAdminTeamLoading: false });
toast(i18n.t("left_admin_team")); toast(i18n.t("left_admin_team"));
this.context.router.history.push("/"); this.context.router.history.push("/");
} else if (op == UserOperation.GetFederatedInstances) { } else if (op == UserOperation.GetFederatedInstances) {
let data = wsJsonToRes<GetFederatedInstancesResponse>(msg); const data = wsJsonToRes<GetFederatedInstancesResponse>(msg);
this.setState({ instancesRes: data }); this.setState({ instancesRes: data });
} }
} }

View file

@ -325,10 +325,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
props: { form: EmojiForm; index: number }, props: { form: EmojiForm; index: number },
event: any event: any
) { ) {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
let item = { const item = {
...props.form.state.customEmojis[pagedIndex], ...props.form.state.customEmojis[pagedIndex],
category: event.target.value, category: event.target.value,
changed: true, changed: true,
@ -341,10 +341,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
props: { form: EmojiForm; index: number }, props: { form: EmojiForm; index: number },
event: any event: any
) { ) {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
let item = { const item = {
...props.form.state.customEmojis[pagedIndex], ...props.form.state.customEmojis[pagedIndex],
shortcode: event.target.value, shortcode: event.target.value,
changed: true, changed: true,
@ -357,10 +357,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
props: { form: EmojiForm; index: number; overrideValue: string | null }, props: { form: EmojiForm; index: number; overrideValue: string | null },
event: any event: any
) { ) {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
let item = { const item = {
...props.form.state.customEmojis[pagedIndex], ...props.form.state.customEmojis[pagedIndex],
image_url: props.overrideValue ?? event.target.value, image_url: props.overrideValue ?? event.target.value,
changed: true, changed: true,
@ -373,10 +373,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
props: { form: EmojiForm; index: number }, props: { form: EmojiForm; index: number },
event: any event: any
) { ) {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
let item = { const item = {
...props.form.state.customEmojis[pagedIndex], ...props.form.state.customEmojis[pagedIndex],
alt_text: event.target.value, alt_text: event.target.value,
changed: true, changed: true,
@ -389,10 +389,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
props: { form: EmojiForm; index: number }, props: { form: EmojiForm; index: number },
event: any event: any
) { ) {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
let item = { const item = {
...props.form.state.customEmojis[pagedIndex], ...props.form.state.customEmojis[pagedIndex],
keywords: event.target.value, keywords: event.target.value,
changed: true, changed: true,
@ -406,7 +406,7 @@ export class EmojiForm extends Component<any, EmojiFormState> {
index: number; index: number;
cv: CustomEmojiViewForm; cv: CustomEmojiViewForm;
}) { }) {
let pagedIndex = const pagedIndex =
(props.form.state.page - 1) * props.form.itemsPerPage + props.index; (props.form.state.page - 1) * props.form.itemsPerPage + props.index;
if (props.cv.id != 0) { if (props.cv.id != 0) {
const deleteForm: DeleteCustomEmoji = { const deleteForm: DeleteCustomEmoji = {
@ -415,7 +415,7 @@ export class EmojiForm extends Component<any, EmojiFormState> {
}; };
WebSocketService.Instance.send(wsClient.deleteCustomEmoji(deleteForm)); WebSocketService.Instance.send(wsClient.deleteCustomEmoji(deleteForm));
} else { } else {
let custom_emojis = [...props.form.state.customEmojis]; const custom_emojis = [...props.form.state.customEmojis];
custom_emojis.splice(Number(pagedIndex), 1); custom_emojis.splice(Number(pagedIndex), 1);
props.form.setState({ customEmojis: custom_emojis }); props.form.setState({ customEmojis: custom_emojis });
} }
@ -451,10 +451,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
handleAddEmojiClick(form: EmojiForm, event: any) { handleAddEmojiClick(form: EmojiForm, event: any) {
event.preventDefault(); event.preventDefault();
let custom_emojis = [...form.state.customEmojis]; const custom_emojis = [...form.state.customEmojis];
const page = const page =
1 + Math.floor(form.state.customEmojis.length / form.itemsPerPage); 1 + Math.floor(form.state.customEmojis.length / form.itemsPerPage);
let item: CustomEmojiViewForm = { const item: CustomEmojiViewForm = {
id: 0, id: 0,
shortcode: "", shortcode: "",
alt_text: "", alt_text: "",
@ -485,8 +485,8 @@ export class EmojiForm extends Component<any, EmojiFormState> {
pictrsDeleteToast(file.name, res.delete_url as string); pictrsDeleteToast(file.name, res.delete_url as string);
} else { } else {
toast(JSON.stringify(res), "danger"); toast(JSON.stringify(res), "danger");
let hash = res.files?.at(0)?.file; const hash = res.files?.at(0)?.file;
let url = `${res.url}/${hash}`; const url = `${res.url}/${hash}`;
props.form.handleEmojiImageUrlChange( props.form.handleEmojiImageUrlChange(
{ form: props.form, index: props.index, overrideValue: url }, { form: props.form, index: props.index, overrideValue: url },
event event
@ -508,7 +508,7 @@ export class EmojiForm extends Component<any, EmojiFormState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -516,11 +516,11 @@ export class EmojiForm extends Component<any, EmojiFormState> {
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.CreateCustomEmoji) { } else if (op == UserOperation.CreateCustomEmoji) {
let data = wsJsonToRes<CustomEmojiResponse>(msg); const data = wsJsonToRes<CustomEmojiResponse>(msg);
const custom_emoji_view = data.custom_emoji; const custom_emoji_view = data.custom_emoji;
updateEmojiDataModel(custom_emoji_view); updateEmojiDataModel(custom_emoji_view);
let currentEmojis = this.state.customEmojis; const currentEmojis = this.state.customEmojis;
let newEmojiIndex = currentEmojis.findIndex( const newEmojiIndex = currentEmojis.findIndex(
x => x.shortcode == custom_emoji_view.custom_emoji.shortcode x => x.shortcode == custom_emoji_view.custom_emoji.shortcode
); );
currentEmojis[newEmojiIndex].id = custom_emoji_view.custom_emoji.id; currentEmojis[newEmojiIndex].id = custom_emoji_view.custom_emoji.id;
@ -529,11 +529,11 @@ export class EmojiForm extends Component<any, EmojiFormState> {
toast(i18n.t("saved_emoji")); toast(i18n.t("saved_emoji"));
this.setState({ loading: false }); this.setState({ loading: false });
} else if (op == UserOperation.EditCustomEmoji) { } else if (op == UserOperation.EditCustomEmoji) {
let data = wsJsonToRes<CustomEmojiResponse>(msg); const data = wsJsonToRes<CustomEmojiResponse>(msg);
const custom_emoji_view = data.custom_emoji; const custom_emoji_view = data.custom_emoji;
updateEmojiDataModel(data.custom_emoji); updateEmojiDataModel(data.custom_emoji);
let currentEmojis = this.state.customEmojis; const currentEmojis = this.state.customEmojis;
let newEmojiIndex = currentEmojis.findIndex( const newEmojiIndex = currentEmojis.findIndex(
x => x.shortcode == custom_emoji_view.custom_emoji.shortcode x => x.shortcode == custom_emoji_view.custom_emoji.shortcode
); );
currentEmojis[newEmojiIndex].changed = false; currentEmojis[newEmojiIndex].changed = false;
@ -541,10 +541,10 @@ export class EmojiForm extends Component<any, EmojiFormState> {
toast(i18n.t("saved_emoji")); toast(i18n.t("saved_emoji"));
this.setState({ loading: false }); this.setState({ loading: false });
} else if (op == UserOperation.DeleteCustomEmoji) { } else if (op == UserOperation.DeleteCustomEmoji) {
let data = wsJsonToRes<DeleteCustomEmojiResponse>(msg); const data = wsJsonToRes<DeleteCustomEmojiResponse>(msg);
if (data.success) { if (data.success) {
removeFromEmojiDataModel(data.id); removeFromEmojiDataModel(data.id);
let custom_emojis = [ const custom_emojis = [
...this.state.customEmojis.filter(x => x.id != data.id), ...this.state.customEmojis.filter(x => x.id != data.id),
]; ];
this.setState({ customEmojis: custom_emojis }); this.setState({ customEmojis: custom_emojis });

View file

@ -55,7 +55,7 @@ export class Instances extends Component<any, InstancesState> {
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
promises.push(req.client.getFederatedInstances({})); promises.push(req.client.getFederatedInstances({}));
@ -73,7 +73,7 @@ export class Instances extends Component<any, InstancesState> {
} }
render() { render() {
let federated_instances = this.state.instancesRes?.federated_instances; const federated_instances = this.state.instancesRes?.federated_instances;
return federated_instances ? ( return federated_instances ? (
<div className="container-lg"> <div className="container-lg">
<HtmlTags <HtmlTags
@ -137,7 +137,7 @@ export class Instances extends Component<any, InstancesState> {
); );
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -145,7 +145,7 @@ export class Instances extends Component<any, InstancesState> {
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.GetFederatedInstances) { } else if (op == UserOperation.GetFederatedInstances) {
let data = wsJsonToRes<GetFederatedInstancesResponse>(msg); const data = wsJsonToRes<GetFederatedInstancesResponse>(msg);
this.setState({ loading: false, instancesRes: data }); this.setState({ loading: false, instancesRes: data });
} }
} }

View file

@ -23,7 +23,7 @@ export class Legal extends Component<any, LegalState> {
} }
render() { render() {
let legal = this.state.siteRes.site_view.local_site.legal_information; const legal = this.state.siteRes.site_view.local_site.legal_information;
return ( return (
<div className="container-lg"> <div className="container-lg">
<HtmlTags <HtmlTags

View file

@ -181,12 +181,12 @@ export class Login extends Component<any, State> {
handleLoginSubmit(i: Login, event: any) { handleLoginSubmit(i: Login, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ loginLoading: true }); i.setState({ loginLoading: true });
let lForm = i.state.form; const lForm = i.state.form;
let username_or_email = lForm.username_or_email; const username_or_email = lForm.username_or_email;
let password = lForm.password; const password = lForm.password;
let totp_2fa_token = lForm.totp_2fa_token; const totp_2fa_token = lForm.totp_2fa_token;
if (username_or_email && password) { if (username_or_email && password) {
let form: LoginI = { const form: LoginI = {
username_or_email, username_or_email,
password, password,
totp_2fa_token, totp_2fa_token,
@ -212,15 +212,15 @@ export class Login extends Component<any, State> {
handlePasswordReset(i: Login, event: any) { handlePasswordReset(i: Login, event: any) {
event.preventDefault(); event.preventDefault();
let email = i.state.form.username_or_email; const email = i.state.form.username_or_email;
if (email) { if (email) {
let resetForm: PasswordReset = { email }; const resetForm: PasswordReset = { email };
WebSocketService.Instance.send(wsClient.passwordReset(resetForm)); WebSocketService.Instance.send(wsClient.passwordReset(resetForm));
} }
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
// If the error comes back that the token is missing, show the TOTP field // If the error comes back that the token is missing, show the TOTP field
@ -235,14 +235,14 @@ export class Login extends Component<any, State> {
} }
} else { } else {
if (op == UserOperation.Login) { if (op == UserOperation.Login) {
let data = wsJsonToRes<LoginResponse>(msg); const data = wsJsonToRes<LoginResponse>(msg);
UserService.Instance.login(data); UserService.Instance.login(data);
this.props.history.push("/"); this.props.history.push("/");
location.reload(); location.reload();
} else if (op == UserOperation.PasswordReset) { } else if (op == UserOperation.PasswordReset) {
toast(i18n.t("reset_password_mail_sent")); toast(i18n.t("reset_password_mail_sent"));
} else if (op == UserOperation.GetSite) { } else if (op == UserOperation.GetSite) {
let data = wsJsonToRes<GetSiteResponse>(msg); const data = wsJsonToRes<GetSiteResponse>(msg);
this.setState({ siteRes: data }); this.setState({ siteRes: data });
} }
} }

View file

@ -173,9 +173,9 @@ export class Setup extends Component<any, State> {
event.preventDefault(); event.preventDefault();
i.setState({ userLoading: true }); i.setState({ userLoading: true });
event.preventDefault(); event.preventDefault();
let cForm = i.state.form; const cForm = i.state.form;
if (cForm.username && cForm.password && cForm.password_verify) { if (cForm.username && cForm.password && cForm.password_verify) {
let form: Register = { const form: Register = {
username: cForm.username, username: cForm.username,
password: cForm.password, password: cForm.password,
password_verify: cForm.password_verify, password_verify: cForm.password_verify,
@ -211,13 +211,13 @@ export class Setup extends Component<any, State> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
this.setState({ userLoading: false }); this.setState({ userLoading: false });
return; return;
} else if (op == UserOperation.Register) { } else if (op == UserOperation.Register) {
let data = wsJsonToRes<LoginResponse>(msg); const data = wsJsonToRes<LoginResponse>(msg);
this.setState({ userLoading: false }); this.setState({ userLoading: false });
UserService.Instance.login(data); UserService.Instance.login(data);
if (UserService.Instance.jwtInfo) { if (UserService.Instance.jwtInfo) {

View file

@ -109,7 +109,7 @@ export class Signup extends Component<any, State> {
} }
get documentTitle(): string { get documentTitle(): string {
let siteView = this.state.siteRes.site_view; const siteView = this.state.siteRes.site_view;
return `${this.titleName(siteView)} - ${siteView.site.name}`; return `${this.titleName(siteView)} - ${siteView.site.name}`;
} }
@ -140,7 +140,7 @@ export class Signup extends Component<any, State> {
} }
registerForm() { registerForm() {
let siteView = this.state.siteRes.site_view; const siteView = this.state.siteRes.site_view;
return ( return (
<form onSubmit={linkEvent(this, this.handleRegisterSubmit)}> <form onSubmit={linkEvent(this, this.handleRegisterSubmit)}>
<h5>{this.titleName(siteView)}</h5> <h5>{this.titleName(siteView)}</h5>
@ -371,7 +371,7 @@ export class Signup extends Component<any, State> {
} }
showCaptcha() { showCaptcha() {
let captchaRes = this.state.captcha?.ok; const captchaRes = this.state.captcha?.ok;
return captchaRes ? ( return captchaRes ? (
<div className="col-sm-4"> <div className="col-sm-4">
<> <>
@ -401,14 +401,14 @@ export class Signup extends Component<any, State> {
} }
get passwordStrength(): string | undefined { get passwordStrength(): string | undefined {
let password = this.state.form.password; const password = this.state.form.password;
return password return password
? passwordStrength(password, passwordStrengthOptions).value ? passwordStrength(password, passwordStrengthOptions).value
: undefined; : undefined;
} }
get passwordColorClass(): string { get passwordColorClass(): string {
let strength = this.passwordStrength; const strength = this.passwordStrength;
if (strength && ["weak", "medium"].includes(strength)) { if (strength && ["weak", "medium"].includes(strength)) {
return "text-warning"; return "text-warning";
@ -422,9 +422,9 @@ export class Signup extends Component<any, State> {
handleRegisterSubmit(i: Signup, event: any) { handleRegisterSubmit(i: Signup, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ registerLoading: true }); i.setState({ registerLoading: true });
let cForm = i.state.form; const cForm = i.state.form;
if (cForm.username && cForm.password && cForm.password_verify) { if (cForm.username && cForm.password && cForm.password_verify) {
let form: Register = { const form: Register = {
username: cForm.username, username: cForm.username,
password: cForm.password, password: cForm.password,
password_verify: cForm.password_verify, password_verify: cForm.password_verify,
@ -490,10 +490,10 @@ export class Signup extends Component<any, State> {
handleCaptchaPlay(i: Signup) { handleCaptchaPlay(i: Signup) {
// This was a bad bug, it should only build the new audio on a new file. // This was a bad bug, it should only build the new audio on a new file.
// Replays would stop prematurely if this was rebuilt every time. // Replays would stop prematurely if this was rebuilt every time.
let captchaRes = i.state.captcha?.ok; const captchaRes = i.state.captcha?.ok;
if (captchaRes) { if (captchaRes) {
if (!i.audio) { if (!i.audio) {
let base64 = `data:audio/wav;base64,${captchaRes.wav}`; const base64 = `data:audio/wav;base64,${captchaRes.wav}`;
i.audio = new Audio(base64); i.audio = new Audio(base64);
i.audio.play(); i.audio.play();
@ -514,7 +514,7 @@ export class Signup extends Component<any, State> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -524,7 +524,7 @@ export class Signup extends Component<any, State> {
return; return;
} else { } else {
if (op == UserOperation.Register) { if (op == UserOperation.Register) {
let data = wsJsonToRes<LoginResponse>(msg); const data = wsJsonToRes<LoginResponse>(msg);
// Only log them in if a jwt was set // Only log them in if a jwt was set
if (data.jwt) { if (data.jwt) {
UserService.Instance.login(data); UserService.Instance.login(data);
@ -540,7 +540,7 @@ export class Signup extends Component<any, State> {
this.props.history.push("/"); this.props.history.push("/");
} }
} else if (op == UserOperation.GetCaptcha) { } else if (op == UserOperation.GetCaptcha) {
let data = wsJsonToRes<GetCaptchaResponse>(msg); const data = wsJsonToRes<GetCaptchaResponse>(msg);
if (data.ok) { if (data.ok) {
this.setState({ captcha: data }); this.setState({ captcha: data });
this.setState(s => ((s.form.captcha_uuid = data.ok?.uuid), s)); this.setState(s => ((s.form.captcha_uuid = data.ok?.uuid), s));
@ -548,7 +548,7 @@ export class Signup extends Component<any, State> {
} else if (op == UserOperation.PasswordReset) { } else if (op == UserOperation.PasswordReset) {
toast(i18n.t("reset_password_mail_sent")); toast(i18n.t("reset_password_mail_sent"));
} else if (op == UserOperation.GetSite) { } else if (op == UserOperation.GetSite) {
let data = wsJsonToRes<GetSiteResponse>(msg); const data = wsJsonToRes<GetSiteResponse>(msg);
this.setState({ siteRes: data }); this.setState({ siteRes: data });
} }
} }

View file

@ -76,8 +76,8 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
this.handleDiscussionLanguageChange = this.handleDiscussionLanguageChange =
this.handleDiscussionLanguageChange.bind(this); this.handleDiscussionLanguageChange.bind(this);
let site = this.props.siteRes.site_view.site; const site = this.props.siteRes.site_view.site;
let ls = this.props.siteRes.site_view.local_site; const ls = this.props.siteRes.site_view.local_site;
this.state = { this.state = {
...this.state, ...this.state,
siteForm: { siteForm: {
@ -149,7 +149,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
} }
render() { render() {
let siteSetup = this.props.siteRes.site_view.local_site.site_setup; const siteSetup = this.props.siteRes.site_view.local_site.site_setup;
return ( return (
<> <>
<Prompt <Prompt
@ -747,13 +747,13 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
handleCreateSiteSubmit(i: SiteForm, event: any) { handleCreateSiteSubmit(i: SiteForm, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ loading: true }); i.setState({ loading: true });
let auth = myAuth() ?? "TODO"; const auth = myAuth() ?? "TODO";
i.setState(s => ((s.siteForm.auth = auth), s)); i.setState(s => ((s.siteForm.auth = auth), s));
if (i.props.siteRes.site_view.local_site.site_setup) { if (i.props.siteRes.site_view.local_site.site_setup) {
WebSocketService.Instance.send(wsClient.editSite(i.state.siteForm)); WebSocketService.Instance.send(wsClient.editSite(i.state.siteForm));
} else { } else {
let sForm = i.state.siteForm; const sForm = i.state.siteForm;
let form: CreateSite = { const form: CreateSite = {
name: sForm.name ?? "My site", name: sForm.name ?? "My site",
sidebar: sForm.sidebar, sidebar: sForm.sidebar,
description: sForm.description, description: sForm.description,
@ -841,7 +841,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
} }
handleTaglineChange(i: SiteForm, index: number, val: string) { handleTaglineChange(i: SiteForm, index: number, val: string) {
let taglines = i.state.siteForm.taglines; const taglines = i.state.siteForm.taglines;
if (taglines) { if (taglines) {
taglines[index] = val; taglines[index] = val;
i.setState(i.state); i.setState(i.state);
@ -854,7 +854,7 @@ export class SiteForm extends Component<SiteFormProps, SiteFormState> {
event: InfernoMouseEvent<HTMLButtonElement> event: InfernoMouseEvent<HTMLButtonElement>
) { ) {
event.preventDefault(); event.preventDefault();
let taglines = i.state.siteForm.taglines; const taglines = i.state.siteForm.taglines;
if (taglines) { if (taglines) {
taglines.splice(index, 1); taglines.splice(index, 1);
i.state.siteForm.taglines = undefined; i.state.siteForm.taglines = undefined;

View file

@ -67,7 +67,7 @@ export class SiteSidebar extends Component<SiteSidebarProps, SiteSidebarState> {
} }
siteInfo() { siteInfo() {
let site = this.props.site; const site = this.props.site;
return ( return (
<div> <div>
{site.description && <h6>{site.description}</h6>} {site.description && <h6>{site.description}</h6>}
@ -98,8 +98,8 @@ export class SiteSidebar extends Component<SiteSidebarProps, SiteSidebarState> {
} }
badges(siteAggregates: SiteAggregates) { badges(siteAggregates: SiteAggregates) {
let counts = siteAggregates; const counts = siteAggregates;
let online = this.props.online ?? 1; const online = this.props.online ?? 1;
return ( return (
<ul className="my-2 list-inline"> <ul className="my-2 list-inline">
<li className="list-inline-item badge badge-secondary"> <li className="list-inline-item badge badge-secondary">

View file

@ -131,7 +131,7 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
} }
handleTaglineChange(i: TaglineForm, index: number, val: string) { handleTaglineChange(i: TaglineForm, index: number, val: string) {
let taglines = i.state.siteForm.taglines; const taglines = i.state.siteForm.taglines;
if (taglines) { if (taglines) {
taglines[index] = val; taglines[index] = val;
i.setState(i.state); i.setState(i.state);
@ -143,7 +143,7 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
event: any event: any
) { ) {
event.preventDefault(); event.preventDefault();
let taglines = props.form.state.siteForm.taglines; const taglines = props.form.state.siteForm.taglines;
if (taglines) { if (taglines) {
taglines.splice(props.index, 1); taglines.splice(props.index, 1);
props.form.state.siteForm.taglines = undefined; props.form.state.siteForm.taglines = undefined;
@ -167,7 +167,7 @@ export class TaglineForm extends Component<TaglineFormProps, TaglineFormState> {
handleSaveClick(i: TaglineForm) { handleSaveClick(i: TaglineForm) {
i.setState({ loading: true }); i.setState({ loading: true });
let auth = myAuth() ?? "TODO"; const auth = myAuth() ?? "TODO";
i.setState(s => ((s.siteForm.auth = auth), s)); i.setState(s => ((s.siteForm.auth = auth), s));
WebSocketService.Instance.send(wsClient.editSite(i.state.siteForm)); WebSocketService.Instance.send(wsClient.editSite(i.state.siteForm));
i.setState({ ...i.state, editingRow: undefined }); i.setState({ ...i.state, editingRow: undefined });

View file

@ -141,7 +141,7 @@ export class Inbox extends Component<any, InboxState> {
} }
get documentTitle(): string { get documentTitle(): string {
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
return mui return mui
? `@${mui.local_user_view.person.name} ${i18n.t("inbox")} - ${ ? `@${mui.local_user_view.person.name} ${i18n.t("inbox")} - ${
this.state.siteRes.site_view.site.name this.state.siteRes.site_view.site.name
@ -150,8 +150,8 @@ export class Inbox extends Component<any, InboxState> {
} }
render() { render() {
let auth = myAuth(); const auth = myAuth();
let inboxRss = auth ? `/feeds/inbox/${auth}.xml` : undefined; const inboxRss = auth ? `/feeds/inbox/${auth}.xml` : undefined;
return ( return (
<div className="container-lg"> <div className="container-lg">
{this.state.loading ? ( {this.state.loading ? (
@ -343,13 +343,13 @@ export class Inbox extends Component<any, InboxState> {
} }
buildCombined(): ReplyType[] { buildCombined(): ReplyType[] {
let replies: ReplyType[] = this.state.replies.map(r => const replies: ReplyType[] = this.state.replies.map(r =>
this.replyToReplyType(r) this.replyToReplyType(r)
); );
let mentions: ReplyType[] = this.state.mentions.map(r => const mentions: ReplyType[] = this.state.mentions.map(r =>
this.mentionToReplyType(r) this.mentionToReplyType(r)
); );
let messages: ReplyType[] = this.state.messages.map(r => const messages: ReplyType[] = this.state.messages.map(r =>
this.messageToReplyType(r) this.messageToReplyType(r)
); );
@ -482,14 +482,14 @@ export class Inbox extends Component<any, InboxState> {
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
let sort: CommentSortType = "New"; const sort: CommentSortType = "New";
let auth = req.auth; const auth = req.auth;
if (auth) { if (auth) {
// It can be /u/me, or /username/1 // It can be /u/me, or /username/1
let repliesForm: GetReplies = { const repliesForm: GetReplies = {
sort: "New", sort: "New",
unread_only: true, unread_only: true,
page: 1, page: 1,
@ -498,7 +498,7 @@ export class Inbox extends Component<any, InboxState> {
}; };
promises.push(req.client.getReplies(repliesForm)); promises.push(req.client.getReplies(repliesForm));
let personMentionsForm: GetPersonMentions = { const personMentionsForm: GetPersonMentions = {
sort, sort,
unread_only: true, unread_only: true,
page: 1, page: 1,
@ -507,7 +507,7 @@ export class Inbox extends Component<any, InboxState> {
}; };
promises.push(req.client.getPersonMentions(personMentionsForm)); promises.push(req.client.getPersonMentions(personMentionsForm));
let privateMessagesForm: GetPrivateMessages = { const privateMessagesForm: GetPrivateMessages = {
unread_only: true, unread_only: true,
page: 1, page: 1,
limit: fetchLimit, limit: fetchLimit,
@ -520,14 +520,14 @@ export class Inbox extends Component<any, InboxState> {
} }
refetch() { refetch() {
let sort = this.state.sort; const sort = this.state.sort;
let unread_only = this.state.unreadOrAll == UnreadOrAll.Unread; const unread_only = this.state.unreadOrAll == UnreadOrAll.Unread;
let page = this.state.page; const page = this.state.page;
let limit = fetchLimit; const limit = fetchLimit;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let repliesForm: GetReplies = { const repliesForm: GetReplies = {
sort, sort,
unread_only, unread_only,
page, page,
@ -536,7 +536,7 @@ export class Inbox extends Component<any, InboxState> {
}; };
WebSocketService.Instance.send(wsClient.getReplies(repliesForm)); WebSocketService.Instance.send(wsClient.getReplies(repliesForm));
let personMentionsForm: GetPersonMentions = { const personMentionsForm: GetPersonMentions = {
sort, sort,
unread_only, unread_only,
page, page,
@ -547,7 +547,7 @@ export class Inbox extends Component<any, InboxState> {
wsClient.getPersonMentions(personMentionsForm) wsClient.getPersonMentions(personMentionsForm)
); );
let privateMessagesForm: GetPrivateMessages = { const privateMessagesForm: GetPrivateMessages = {
unread_only, unread_only,
page, page,
limit, limit,
@ -565,7 +565,7 @@ export class Inbox extends Component<any, InboxState> {
} }
markAllAsRead(i: Inbox) { markAllAsRead(i: Inbox) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
WebSocketService.Instance.send( WebSocketService.Instance.send(
wsClient.markAllAsRead({ wsClient.markAllAsRead({
@ -581,7 +581,7 @@ export class Inbox extends Component<any, InboxState> {
} }
sendUnreadCount(read: boolean) { sendUnreadCount(read: boolean) {
let urcs = UserService.Instance.unreadInboxCountSub; const urcs = UserService.Instance.unreadInboxCountSub;
if (read) { if (read) {
urcs.next(urcs.getValue() - 1); urcs.next(urcs.getValue() - 1);
} else { } else {
@ -590,7 +590,7 @@ export class Inbox extends Component<any, InboxState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -598,31 +598,31 @@ export class Inbox extends Component<any, InboxState> {
} else if (msg.reconnect) { } else if (msg.reconnect) {
this.refetch(); this.refetch();
} else if (op == UserOperation.GetReplies) { } else if (op == UserOperation.GetReplies) {
let data = wsJsonToRes<GetRepliesResponse>(msg); const data = wsJsonToRes<GetRepliesResponse>(msg);
this.setState({ replies: data.replies }); this.setState({ replies: data.replies });
this.setState({ combined: this.buildCombined(), loading: false }); this.setState({ combined: this.buildCombined(), loading: false });
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.GetPersonMentions) { } else if (op == UserOperation.GetPersonMentions) {
let data = wsJsonToRes<GetPersonMentionsResponse>(msg); const data = wsJsonToRes<GetPersonMentionsResponse>(msg);
this.setState({ mentions: data.mentions }); this.setState({ mentions: data.mentions });
this.setState({ combined: this.buildCombined() }); this.setState({ combined: this.buildCombined() });
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.GetPrivateMessages) { } else if (op == UserOperation.GetPrivateMessages) {
let data = wsJsonToRes<PrivateMessagesResponse>(msg); const data = wsJsonToRes<PrivateMessagesResponse>(msg);
this.setState({ messages: data.private_messages }); this.setState({ messages: data.private_messages });
this.setState({ combined: this.buildCombined() }); this.setState({ combined: this.buildCombined() });
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.EditPrivateMessage) { } else if (op == UserOperation.EditPrivateMessage) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
let found = this.state.messages.find( const found = this.state.messages.find(
m => m =>
m.private_message.id === data.private_message_view.private_message.id m.private_message.id === data.private_message_view.private_message.id
); );
if (found) { if (found) {
let combinedView = this.state.combined.find( const combinedView = this.state.combined.find(
i => i.id == data.private_message_view.private_message.id i => i.id == data.private_message_view.private_message.id
)?.view as PrivateMessageView | undefined; )?.view as PrivateMessageView | undefined;
if (combinedView) { if (combinedView) {
@ -634,13 +634,13 @@ export class Inbox extends Component<any, InboxState> {
} }
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.DeletePrivateMessage) { } else if (op == UserOperation.DeletePrivateMessage) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
let found = this.state.messages.find( const found = this.state.messages.find(
m => m =>
m.private_message.id === data.private_message_view.private_message.id m.private_message.id === data.private_message_view.private_message.id
); );
if (found) { if (found) {
let combinedView = this.state.combined.find( const combinedView = this.state.combined.find(
i => i.id == data.private_message_view.private_message.id i => i.id == data.private_message_view.private_message.id
)?.view as PrivateMessageView | undefined; )?.view as PrivateMessageView | undefined;
if (combinedView) { if (combinedView) {
@ -652,14 +652,14 @@ export class Inbox extends Component<any, InboxState> {
} }
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.MarkPrivateMessageAsRead) { } else if (op == UserOperation.MarkPrivateMessageAsRead) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
let found = this.state.messages.find( const found = this.state.messages.find(
m => m =>
m.private_message.id === data.private_message_view.private_message.id m.private_message.id === data.private_message_view.private_message.id
); );
if (found) { if (found) {
let combinedView = this.state.combined.find( const combinedView = this.state.combined.find(
i => i =>
i.id == data.private_message_view.private_message.id && i.id == data.private_message_view.private_message.id &&
i.type_ == ReplyEnum.Message i.type_ == ReplyEnum.Message
@ -700,18 +700,18 @@ export class Inbox extends Component<any, InboxState> {
op == UserOperation.DeleteComment || op == UserOperation.DeleteComment ||
op == UserOperation.RemoveComment op == UserOperation.RemoveComment
) { ) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
editCommentRes(data.comment_view, this.state.replies); editCommentRes(data.comment_view, this.state.replies);
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.MarkCommentReplyAsRead) { } else if (op == UserOperation.MarkCommentReplyAsRead) {
let data = wsJsonToRes<CommentReplyResponse>(msg); const data = wsJsonToRes<CommentReplyResponse>(msg);
let found = this.state.replies.find( const found = this.state.replies.find(
c => c.comment_reply.id == data.comment_reply_view.comment_reply.id c => c.comment_reply.id == data.comment_reply_view.comment_reply.id
); );
if (found) { if (found) {
let combinedView = this.state.combined.find( const combinedView = this.state.combined.find(
i => i =>
i.id == data.comment_reply_view.comment_reply.id && i.id == data.comment_reply_view.comment_reply.id &&
i.type_ == ReplyEnum.Reply i.type_ == ReplyEnum.Reply
@ -758,15 +758,15 @@ export class Inbox extends Component<any, InboxState> {
this.sendUnreadCount(data.comment_reply_view.comment_reply.read); this.sendUnreadCount(data.comment_reply_view.comment_reply.read);
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.MarkPersonMentionAsRead) { } else if (op == UserOperation.MarkPersonMentionAsRead) {
let data = wsJsonToRes<PersonMentionResponse>(msg); const data = wsJsonToRes<PersonMentionResponse>(msg);
// TODO this might not be correct, it might need to use the comment id // TODO this might not be correct, it might need to use the comment id
let found = this.state.mentions.find( const found = this.state.mentions.find(
c => c.person_mention.id == data.person_mention_view.person_mention.id c => c.person_mention.id == data.person_mention_view.person_mention.id
); );
if (found) { if (found) {
let combinedView = this.state.combined.find( const combinedView = this.state.combined.find(
i => i =>
i.id == data.person_mention_view.person_mention.id && i.id == data.person_mention_view.person_mention.id &&
i.type_ == ReplyEnum.Mention i.type_ == ReplyEnum.Mention
@ -814,8 +814,8 @@ export class Inbox extends Component<any, InboxState> {
this.sendUnreadCount(data.person_mention_view.person_mention.read); this.sendUnreadCount(data.person_mention_view.person_mention.read);
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.CreatePrivateMessage) { } else if (op == UserOperation.CreatePrivateMessage) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if ( if (
data.private_message_view.recipient.id == mui?.local_user_view.person.id data.private_message_view.recipient.id == mui?.local_user_view.person.id
) { ) {
@ -826,29 +826,29 @@ export class Inbox extends Component<any, InboxState> {
this.setState(this.state); this.setState(this.state);
} }
} else if (op == UserOperation.SaveComment) { } else if (op == UserOperation.SaveComment) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
saveCommentRes(data.comment_view, this.state.replies); saveCommentRes(data.comment_view, this.state.replies);
this.setState(this.state); this.setState(this.state);
setupTippy(); setupTippy();
} else if (op == UserOperation.CreateCommentLike) { } else if (op == UserOperation.CreateCommentLike) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
createCommentLikeRes(data.comment_view, this.state.replies); createCommentLikeRes(data.comment_view, this.state.replies);
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.BlockPerson) { } else if (op == UserOperation.BlockPerson) {
let data = wsJsonToRes<BlockPersonResponse>(msg); const data = wsJsonToRes<BlockPersonResponse>(msg);
updatePersonBlock(data); updatePersonBlock(data);
} else if (op == UserOperation.CreatePostReport) { } else if (op == UserOperation.CreatePostReport) {
let data = wsJsonToRes<PostReportResponse>(msg); const data = wsJsonToRes<PostReportResponse>(msg);
if (data) { if (data) {
toast(i18n.t("report_created")); toast(i18n.t("report_created"));
} }
} else if (op == UserOperation.CreateCommentReport) { } else if (op == UserOperation.CreateCommentReport) {
let data = wsJsonToRes<CommentReportResponse>(msg); const data = wsJsonToRes<CommentReportResponse>(msg);
if (data) { if (data) {
toast(i18n.t("report_created")); toast(i18n.t("report_created"));
} }
} else if (op == UserOperation.CreatePrivateMessageReport) { } else if (op == UserOperation.CreatePrivateMessageReport) {
let data = wsJsonToRes<PrivateMessageReportResponse>(msg); const data = wsJsonToRes<PrivateMessageReportResponse>(msg);
if (data) { if (data) {
toast(i18n.t("report_created")); toast(i18n.t("report_created"));
} }

View file

@ -143,11 +143,11 @@ export class PasswordChange extends Component<any, State> {
event.preventDefault(); event.preventDefault();
i.setState({ loading: true }); i.setState({ loading: true });
let password = i.state.form.password; const password = i.state.form.password;
let password_verify = i.state.form.password_verify; const password_verify = i.state.form.password_verify;
if (password && password_verify) { if (password && password_verify) {
let form: PasswordChangeAfterReset = { const form: PasswordChangeAfterReset = {
token: i.state.form.token, token: i.state.form.token,
password, password,
password_verify, password_verify,
@ -158,14 +158,14 @@ export class PasswordChange extends Component<any, State> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.PasswordChangeAfterReset) { } else if (op == UserOperation.PasswordChangeAfterReset) {
let data = wsJsonToRes<LoginResponse>(msg); const data = wsJsonToRes<LoginResponse>(msg);
UserService.Instance.login(data); UserService.Instance.login(data);
this.props.history.push("/"); this.props.history.push("/");
location.reload(); location.reload();

View file

@ -87,7 +87,7 @@ export class PersonDetails extends Component<PersonDetailsProps, any> {
renderItemType(i: ItemType) { renderItemType(i: ItemType) {
switch (i.type_) { switch (i.type_) {
case ItemEnum.Comment: { case ItemEnum.Comment: {
let c = i.view as CommentView; const c = i.view as CommentView;
return ( return (
<CommentNodes <CommentNodes
key={i.id} key={i.id}
@ -105,7 +105,7 @@ export class PersonDetails extends Component<PersonDetailsProps, any> {
); );
} }
case ItemEnum.Post: { case ItemEnum.Post: {
let p = i.view as PostView; const p = i.view as PostView;
return ( return (
<PostListing <PostListing
key={i.id} key={i.id}
@ -126,14 +126,14 @@ export class PersonDetails extends Component<PersonDetailsProps, any> {
overview() { overview() {
let id = 0; let id = 0;
let comments: ItemType[] = this.props.personRes.comments.map(r => ({ const comments: ItemType[] = this.props.personRes.comments.map(r => ({
id: id++, id: id++,
type_: ItemEnum.Comment, type_: ItemEnum.Comment,
view: r, view: r,
published: r.comment.published, published: r.comment.published,
score: r.counts.score, score: r.counts.score,
})); }));
let posts: ItemType[] = this.props.personRes.posts.map(r => ({ const posts: ItemType[] = this.props.personRes.posts.map(r => ({
id: id++, id: id++,
type_: ItemEnum.Post, type_: ItemEnum.Post,
view: r, view: r,
@ -141,7 +141,7 @@ export class PersonDetails extends Component<PersonDetailsProps, any> {
score: r.counts.score, score: r.counts.score,
})); }));
let combined = [...comments, ...posts]; const combined = [...comments, ...posts];
// Sort it // Sort it
if (this.props.sort === "New") { if (this.props.sort === "New") {

View file

@ -20,15 +20,15 @@ export class PersonListing extends Component<PersonListingProps, any> {
} }
render() { render() {
let person = this.props.person; const person = this.props.person;
let local = person.local; const local = person.local;
let apubName: string, link: string; let apubName: string, link: string;
if (local) { if (local) {
apubName = `@${person.name}`; apubName = `@${person.name}`;
link = `/u/${person.name}`; link = `/u/${person.name}`;
} else { } else {
let domain = hostname(person.actor_id); const domain = hostname(person.actor_id);
apubName = `@${person.name}@${domain}`; apubName = `@${person.name}@${domain}`;
link = !this.props.realLink link = !this.props.realLink
? `/u/${person.name}@${domain}` ? `/u/${person.name}@${domain}`
@ -70,7 +70,7 @@ export class PersonListing extends Component<PersonListingProps, any> {
} }
avatarAndName(displayName: string) { avatarAndName(displayName: string) {
let avatar = this.props.person.avatar; const avatar = this.props.person.avatar;
return ( return (
<> <>
{avatar && {avatar &&

View file

@ -86,7 +86,7 @@ export class RegistrationApplications extends Component<
} }
get documentTitle(): string { get documentTitle(): string {
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
return mui return mui
? `@${mui.local_user_view.person.name} ${i18n.t( ? `@${mui.local_user_view.person.name} ${i18n.t(
"registration_applications" "registration_applications"
@ -164,7 +164,7 @@ export class RegistrationApplications extends Component<
} }
applicationList() { applicationList() {
let res = this.state.listRegistrationApplicationsResponse; const res = this.state.listRegistrationApplicationsResponse;
return ( return (
res && ( res && (
<div> <div>
@ -193,11 +193,11 @@ export class RegistrationApplications extends Component<
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
let auth = req.auth; const auth = req.auth;
if (auth) { if (auth) {
let form: ListRegistrationApplications = { const form: ListRegistrationApplications = {
unread_only: true, unread_only: true,
page: 1, page: 1,
limit: fetchLimit, limit: fetchLimit,
@ -210,10 +210,10 @@ export class RegistrationApplications extends Component<
} }
refetch() { refetch() {
let unread_only = this.state.unreadOrAll == UnreadOrAll.Unread; const unread_only = this.state.unreadOrAll == UnreadOrAll.Unread;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: ListRegistrationApplications = { const form: ListRegistrationApplications = {
unread_only: unread_only, unread_only: unread_only,
page: this.state.page, page: this.state.page,
limit: fetchLimit, limit: fetchLimit,
@ -226,7 +226,7 @@ export class RegistrationApplications extends Component<
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -234,20 +234,20 @@ export class RegistrationApplications extends Component<
} else if (msg.reconnect) { } else if (msg.reconnect) {
this.refetch(); this.refetch();
} else if (op == UserOperation.ListRegistrationApplications) { } else if (op == UserOperation.ListRegistrationApplications) {
let data = wsJsonToRes<ListRegistrationApplicationsResponse>(msg); const data = wsJsonToRes<ListRegistrationApplicationsResponse>(msg);
this.setState({ this.setState({
listRegistrationApplicationsResponse: data, listRegistrationApplicationsResponse: data,
loading: false, loading: false,
}); });
window.scrollTo(0, 0); window.scrollTo(0, 0);
} else if (op == UserOperation.ApproveRegistrationApplication) { } else if (op == UserOperation.ApproveRegistrationApplication) {
let data = wsJsonToRes<RegistrationApplicationResponse>(msg); const data = wsJsonToRes<RegistrationApplicationResponse>(msg);
updateRegistrationApplicationRes( updateRegistrationApplicationRes(
data.registration_application, data.registration_application,
this.state.listRegistrationApplicationsResponse this.state.listRegistrationApplicationsResponse
?.registration_applications ?.registration_applications
); );
let uacs = UserService.Instance.unreadApplicationCountSub; const uacs = UserService.Instance.unreadApplicationCountSub;
// Minor bug, where if the application switches from deny to approve, the count will still go down // Minor bug, where if the application switches from deny to approve, the count will still go down
uacs.next(uacs.getValue() - 1); uacs.next(uacs.getValue() - 1);
this.setState(this.state); this.setState(this.state);

View file

@ -132,7 +132,7 @@ export class Reports extends Component<any, ReportsState> {
} }
get documentTitle(): string { get documentTitle(): string {
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
return mui return mui
? `@${mui.local_user_view.person.name} ${i18n.t("reports")} - ${ ? `@${mui.local_user_view.person.name} ${i18n.t("reports")} - ${
this.state.siteRes.site_view.site.name this.state.siteRes.site_view.site.name
@ -314,15 +314,15 @@ export class Reports extends Component<any, ReportsState> {
// .map(r => r.comment_reports) // .map(r => r.comment_reports)
// .unwrapOr([]) // .unwrapOr([])
// .map(r => this.commentReportToItemType(r)); // .map(r => this.commentReportToItemType(r));
let comments = const comments =
this.state.listCommentReportsResponse?.comment_reports.map( this.state.listCommentReportsResponse?.comment_reports.map(
this.commentReportToItemType this.commentReportToItemType
) ?? []; ) ?? [];
let posts = const posts =
this.state.listPostReportsResponse?.post_reports.map( this.state.listPostReportsResponse?.post_reports.map(
this.postReportToItemType this.postReportToItemType
) ?? []; ) ?? [];
let privateMessages = const privateMessages =
this.state.listPrivateMessageReportsResponse?.private_message_reports.map( this.state.listPrivateMessageReportsResponse?.private_message_reports.map(
this.privateMessageReportToItemType this.privateMessageReportToItemType
) ?? []; ) ?? [];
@ -366,7 +366,7 @@ export class Reports extends Component<any, ReportsState> {
} }
commentReports() { commentReports() {
let reports = this.state.listCommentReportsResponse?.comment_reports; const reports = this.state.listCommentReportsResponse?.comment_reports;
return ( return (
reports && ( reports && (
<div> <div>
@ -382,7 +382,7 @@ export class Reports extends Component<any, ReportsState> {
} }
postReports() { postReports() {
let reports = this.state.listPostReportsResponse?.post_reports; const reports = this.state.listPostReportsResponse?.post_reports;
return ( return (
reports && ( reports && (
<div> <div>
@ -398,7 +398,7 @@ export class Reports extends Component<any, ReportsState> {
} }
privateMessageReports() { privateMessageReports() {
let reports = const reports =
this.state.listPrivateMessageReportsResponse?.private_message_reports; this.state.listPrivateMessageReportsResponse?.private_message_reports;
return ( return (
reports && ( reports && (
@ -433,15 +433,15 @@ export class Reports extends Component<any, ReportsState> {
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
let unresolved_only = true; const unresolved_only = true;
let page = 1; const page = 1;
let limit = fetchLimit; const limit = fetchLimit;
let auth = req.auth; const auth = req.auth;
if (auth) { if (auth) {
let commentReportsForm: ListCommentReports = { const commentReportsForm: ListCommentReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -449,7 +449,7 @@ export class Reports extends Component<any, ReportsState> {
}; };
promises.push(req.client.listCommentReports(commentReportsForm)); promises.push(req.client.listCommentReports(commentReportsForm));
let postReportsForm: ListPostReports = { const postReportsForm: ListPostReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -458,7 +458,7 @@ export class Reports extends Component<any, ReportsState> {
promises.push(req.client.listPostReports(postReportsForm)); promises.push(req.client.listPostReports(postReportsForm));
if (amAdmin()) { if (amAdmin()) {
let privateMessageReportsForm: ListPrivateMessageReports = { const privateMessageReportsForm: ListPrivateMessageReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -474,12 +474,12 @@ export class Reports extends Component<any, ReportsState> {
} }
refetch() { refetch() {
let unresolved_only = this.state.unreadOrAll == UnreadOrAll.Unread; const unresolved_only = this.state.unreadOrAll == UnreadOrAll.Unread;
let page = this.state.page; const page = this.state.page;
let limit = fetchLimit; const limit = fetchLimit;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let commentReportsForm: ListCommentReports = { const commentReportsForm: ListCommentReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -489,7 +489,7 @@ export class Reports extends Component<any, ReportsState> {
wsClient.listCommentReports(commentReportsForm) wsClient.listCommentReports(commentReportsForm)
); );
let postReportsForm: ListPostReports = { const postReportsForm: ListPostReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -498,7 +498,7 @@ export class Reports extends Component<any, ReportsState> {
WebSocketService.Instance.send(wsClient.listPostReports(postReportsForm)); WebSocketService.Instance.send(wsClient.listPostReports(postReportsForm));
if (amAdmin()) { if (amAdmin()) {
let privateMessageReportsForm: ListPrivateMessageReports = { const privateMessageReportsForm: ListPrivateMessageReports = {
unresolved_only, unresolved_only,
page, page,
limit, limit,
@ -512,7 +512,7 @@ export class Reports extends Component<any, ReportsState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -520,33 +520,33 @@ export class Reports extends Component<any, ReportsState> {
} else if (msg.reconnect) { } else if (msg.reconnect) {
this.refetch(); this.refetch();
} else if (op == UserOperation.ListCommentReports) { } else if (op == UserOperation.ListCommentReports) {
let data = wsJsonToRes<ListCommentReportsResponse>(msg); const data = wsJsonToRes<ListCommentReportsResponse>(msg);
this.setState({ listCommentReportsResponse: data }); this.setState({ listCommentReportsResponse: data });
this.setState({ combined: this.buildCombined(), loading: false }); this.setState({ combined: this.buildCombined(), loading: false });
// this.sendUnreadCount(); // this.sendUnreadCount();
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.ListPostReports) { } else if (op == UserOperation.ListPostReports) {
let data = wsJsonToRes<ListPostReportsResponse>(msg); const data = wsJsonToRes<ListPostReportsResponse>(msg);
this.setState({ listPostReportsResponse: data }); this.setState({ listPostReportsResponse: data });
this.setState({ combined: this.buildCombined(), loading: false }); this.setState({ combined: this.buildCombined(), loading: false });
// this.sendUnreadCount(); // this.sendUnreadCount();
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.ListPrivateMessageReports) { } else if (op == UserOperation.ListPrivateMessageReports) {
let data = wsJsonToRes<ListPrivateMessageReportsResponse>(msg); const data = wsJsonToRes<ListPrivateMessageReportsResponse>(msg);
this.setState({ listPrivateMessageReportsResponse: data }); this.setState({ listPrivateMessageReportsResponse: data });
this.setState({ combined: this.buildCombined(), loading: false }); this.setState({ combined: this.buildCombined(), loading: false });
// this.sendUnreadCount(); // this.sendUnreadCount();
window.scrollTo(0, 0); window.scrollTo(0, 0);
setupTippy(); setupTippy();
} else if (op == UserOperation.ResolvePostReport) { } else if (op == UserOperation.ResolvePostReport) {
let data = wsJsonToRes<PostReportResponse>(msg); const data = wsJsonToRes<PostReportResponse>(msg);
updatePostReportRes( updatePostReportRes(
data.post_report_view, data.post_report_view,
this.state.listPostReportsResponse?.post_reports this.state.listPostReportsResponse?.post_reports
); );
let urcs = UserService.Instance.unreadReportCountSub; const urcs = UserService.Instance.unreadReportCountSub;
if (data.post_report_view.post_report.resolved) { if (data.post_report_view.post_report.resolved) {
urcs.next(urcs.getValue() - 1); urcs.next(urcs.getValue() - 1);
} else { } else {
@ -554,12 +554,12 @@ export class Reports extends Component<any, ReportsState> {
} }
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.ResolveCommentReport) { } else if (op == UserOperation.ResolveCommentReport) {
let data = wsJsonToRes<CommentReportResponse>(msg); const data = wsJsonToRes<CommentReportResponse>(msg);
updateCommentReportRes( updateCommentReportRes(
data.comment_report_view, data.comment_report_view,
this.state.listCommentReportsResponse?.comment_reports this.state.listCommentReportsResponse?.comment_reports
); );
let urcs = UserService.Instance.unreadReportCountSub; const urcs = UserService.Instance.unreadReportCountSub;
if (data.comment_report_view.comment_report.resolved) { if (data.comment_report_view.comment_report.resolved) {
urcs.next(urcs.getValue() - 1); urcs.next(urcs.getValue() - 1);
} else { } else {
@ -567,12 +567,12 @@ export class Reports extends Component<any, ReportsState> {
} }
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.ResolvePrivateMessageReport) { } else if (op == UserOperation.ResolvePrivateMessageReport) {
let data = wsJsonToRes<PrivateMessageReportResponse>(msg); const data = wsJsonToRes<PrivateMessageReportResponse>(msg);
updatePrivateMessageReportRes( updatePrivateMessageReportRes(
data.private_message_report_view, data.private_message_report_view,
this.state.listPrivateMessageReportsResponse?.private_message_reports this.state.listPrivateMessageReportsResponse?.private_message_reports
); );
let urcs = UserService.Instance.unreadReportCountSub; const urcs = UserService.Instance.unreadReportCountSub;
if (data.private_message_report_view.private_message_report.resolved) { if (data.private_message_report_view.private_message_report.resolved) {
urcs.next(urcs.getValue() - 1); urcs.next(urcs.getValue() - 1);
} else { } else {

View file

@ -476,7 +476,7 @@ export class Settings extends Component<any, SettingsState> {
} }
saveUserSettingsHtmlForm() { saveUserSettingsHtmlForm() {
let selectedLangs = this.state.saveUserSettingsForm.discussion_languages; const selectedLangs = this.state.saveUserSettingsForm.discussion_languages;
return ( return (
<> <>
@ -853,7 +853,7 @@ export class Settings extends Component<any, SettingsState> {
} }
totpSection() { totpSection() {
let totpUrl = const totpUrl =
UserService.Instance.myUserInfo?.local_user_view.local_user.totp_2fa_url; UserService.Instance.myUserInfo?.local_user_view.local_user.totp_2fa_url;
return ( return (
@ -998,7 +998,7 @@ export class Settings extends Component<any, SettingsState> {
handleShowAvatarsChange(i: Settings, event: any) { handleShowAvatarsChange(i: Settings, event: any) {
i.state.saveUserSettingsForm.show_avatars = event.target.checked; i.state.saveUserSettingsForm.show_avatars = event.target.checked;
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
mui.local_user_view.local_user.show_avatars = event.target.checked; mui.local_user_view.local_user.show_avatars = event.target.checked;
} }
@ -1027,7 +1027,7 @@ export class Settings extends Component<any, SettingsState> {
handleShowScoresChange(i: Settings, event: any) { handleShowScoresChange(i: Settings, event: any) {
i.state.saveUserSettingsForm.show_scores = event.target.checked; i.state.saveUserSettingsForm.show_scores = event.target.checked;
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
mui.local_user_view.local_user.show_scores = event.target.checked; mui.local_user_view.local_user.show_scores = event.target.checked;
} }
@ -1036,7 +1036,7 @@ export class Settings extends Component<any, SettingsState> {
handleGenerateTotp(i: Settings, event: any) { handleGenerateTotp(i: Settings, event: any) {
// Coerce false to undefined here, so it won't generate it. // Coerce false to undefined here, so it won't generate it.
let checked: boolean | undefined = event.target.checked || undefined; const checked: boolean | undefined = event.target.checked || undefined;
if (checked) { if (checked) {
toast(i18n.t("two_factor_setup_instructions")); toast(i18n.t("two_factor_setup_instructions"));
} }
@ -1046,7 +1046,7 @@ export class Settings extends Component<any, SettingsState> {
handleRemoveTotp(i: Settings, event: any) { handleRemoveTotp(i: Settings, event: any) {
// Coerce true to undefined here, so it won't generate it. // Coerce true to undefined here, so it won't generate it.
let checked: boolean | undefined = !event.target.checked && undefined; const checked: boolean | undefined = !event.target.checked && undefined;
i.state.saveUserSettingsForm.generate_totp_2fa = checked; i.state.saveUserSettingsForm.generate_totp_2fa = checked;
i.setState(i.state); i.setState(i.state);
} }
@ -1149,9 +1149,9 @@ export class Settings extends Component<any, SettingsState> {
handleSaveSettingsSubmit(i: Settings, event: any) { handleSaveSettingsSubmit(i: Settings, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ saveUserSettingsLoading: true }); i.setState({ saveUserSettingsLoading: true });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: SaveUserSettings = { ...i.state.saveUserSettingsForm, auth }; const form: SaveUserSettings = { ...i.state.saveUserSettingsForm, auth };
WebSocketService.Instance.send(wsClient.saveUserSettings(form)); WebSocketService.Instance.send(wsClient.saveUserSettings(form));
} }
} }
@ -1159,13 +1159,13 @@ export class Settings extends Component<any, SettingsState> {
handleChangePasswordSubmit(i: Settings, event: any) { handleChangePasswordSubmit(i: Settings, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ changePasswordLoading: true }); i.setState({ changePasswordLoading: true });
let auth = myAuth(); const auth = myAuth();
let pForm = i.state.changePasswordForm; const pForm = i.state.changePasswordForm;
let new_password = pForm.new_password; const new_password = pForm.new_password;
let new_password_verify = pForm.new_password_verify; const new_password_verify = pForm.new_password_verify;
let old_password = pForm.old_password; const old_password = pForm.old_password;
if (auth && new_password && old_password && new_password_verify) { if (auth && new_password && old_password && new_password_verify) {
let form: ChangePassword = { const form: ChangePassword = {
new_password, new_password,
new_password_verify, new_password_verify,
old_password, old_password,
@ -1189,10 +1189,10 @@ export class Settings extends Component<any, SettingsState> {
handleDeleteAccount(i: Settings, event: any) { handleDeleteAccount(i: Settings, event: any) {
event.preventDefault(); event.preventDefault();
i.setState({ deleteAccountLoading: true }); i.setState({ deleteAccountLoading: true });
let auth = myAuth(); const auth = myAuth();
let password = i.state.deleteAccountForm.password; const password = i.state.deleteAccountForm.password;
if (auth && password) { if (auth && password) {
let form: DeleteAccount = { const form: DeleteAccount = {
password, password,
auth, auth,
}; };
@ -1205,7 +1205,7 @@ export class Settings extends Component<any, SettingsState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
this.setState({ this.setState({
@ -1220,7 +1220,7 @@ export class Settings extends Component<any, SettingsState> {
toast(i18n.t("saved")); toast(i18n.t("saved"));
window.scrollTo(0, 0); window.scrollTo(0, 0);
} else if (op == UserOperation.ChangePassword) { } else if (op == UserOperation.ChangePassword) {
let data = wsJsonToRes<LoginResponse>(msg); const data = wsJsonToRes<LoginResponse>(msg);
UserService.Instance.login(data); UserService.Instance.login(data);
this.setState({ changePasswordLoading: false }); this.setState({ changePasswordLoading: false });
window.scrollTo(0, 0); window.scrollTo(0, 0);
@ -1233,16 +1233,16 @@ export class Settings extends Component<any, SettingsState> {
UserService.Instance.logout(); UserService.Instance.logout();
window.location.href = "/"; window.location.href = "/";
} else if (op == UserOperation.BlockPerson) { } else if (op == UserOperation.BlockPerson) {
let data = wsJsonToRes<BlockPersonResponse>(msg); const data = wsJsonToRes<BlockPersonResponse>(msg);
updatePersonBlock(data); updatePersonBlock(data);
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
this.setState({ personBlocks: mui.person_blocks }); this.setState({ personBlocks: mui.person_blocks });
} }
} else if (op == UserOperation.BlockCommunity) { } else if (op == UserOperation.BlockCommunity) {
let data = wsJsonToRes<BlockCommunityResponse>(msg); const data = wsJsonToRes<BlockCommunityResponse>(msg);
updateCommunityBlock(data); updateCommunityBlock(data);
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
if (mui) { if (mui) {
this.setState({ communityBlocks: mui.community_blocks }); this.setState({ communityBlocks: mui.community_blocks });
} }

View file

@ -76,7 +76,7 @@ export class VerifyEmail extends Component<any, State> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -84,7 +84,7 @@ export class VerifyEmail extends Component<any, State> {
this.props.history.push("/"); this.props.history.push("/");
return; return;
} else if (op == UserOperation.VerifyEmail) { } else if (op == UserOperation.VerifyEmail) {
let data = wsJsonToRes(msg); const data = wsJsonToRes(msg);
if (data) { if (data) {
toast(i18n.t("email_verified")); toast(i18n.t("email_verified"));
this.props.history.push("/login"); this.props.history.push("/login");

View file

@ -26,7 +26,7 @@ export class MetadataCard extends Component<
} }
render() { render() {
let post = this.props.post; const post = this.props.post;
return ( return (
<> <>
{!this.state.expanded && post.embed_title && post.url && ( {!this.state.expanded && post.embed_title && post.url && (

View file

@ -186,10 +186,10 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
render() { render() {
let firstLang = this.state.form.language_id; const firstLang = this.state.form.language_id;
let selectedLangs = firstLang ? Array.of(firstLang) : undefined; const selectedLangs = firstLang ? Array.of(firstLang) : undefined;
let url = this.state.form.url; const url = this.state.form.url;
return ( return (
<div> <div>
<Prompt <Prompt
@ -449,12 +449,12 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
i.setState(s => ((s.form.url = undefined), s)); i.setState(s => ((s.form.url = undefined), s));
} }
let pForm = i.state.form; const pForm = i.state.form;
let pv = i.props.post_view; const pv = i.props.post_view;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (pv) { if (pv) {
let form: EditPost = { const form: EditPost = {
name: pForm.name, name: pForm.name,
url: pForm.url, url: pForm.url,
body: pForm.body, body: pForm.body,
@ -466,7 +466,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
WebSocketService.Instance.send(wsClient.editPost(form)); WebSocketService.Instance.send(wsClient.editPost(form));
} else { } else {
if (pForm.name && pForm.community_id) { if (pForm.name && pForm.community_id) {
let form: CreatePost = { const form: CreatePost = {
name: pForm.name, name: pForm.name,
community_id: pForm.community_id, community_id: pForm.community_id,
url: pForm.url, url: pForm.url,
@ -483,14 +483,14 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
copySuggestedTitle(i: PostForm) { copySuggestedTitle(i: PostForm) {
let sTitle = i.state.suggestedTitle; const sTitle = i.state.suggestedTitle;
if (sTitle) { if (sTitle) {
i.setState( i.setState(
s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s) s => ((s.form.name = sTitle?.substring(0, MAX_POST_TITLE_LENGTH)), s)
); );
i.setState({ suggestedTitle: undefined }); i.setState({ suggestedTitle: undefined });
setTimeout(() => { setTimeout(() => {
let textarea: any = document.getElementById("post-title"); const textarea: any = document.getElementById("post-title");
autosize.update(textarea); autosize.update(textarea);
}, 10); }, 10);
} }
@ -502,9 +502,9 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
fetchPageTitle() { fetchPageTitle() {
let url = this.state.form.url; const url = this.state.form.url;
if (url && validURL(url)) { if (url && validURL(url)) {
let form: Search = { const form: Search = {
q: url, q: url,
type_: "Url", type_: "Url",
sort: "TopAll", sort: "TopAll",
@ -531,9 +531,9 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
fetchSimilarPosts() { fetchSimilarPosts() {
let q = this.state.form.name; const q = this.state.form.name;
if (q && q !== "") { if (q && q !== "") {
let form: Search = { const form: Search = {
q, q,
type_: "Posts", type_: "Posts",
sort: "TopAll", sort: "TopAll",
@ -580,7 +580,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
handleImageUploadPaste(i: PostForm, event: any) { handleImageUploadPaste(i: PostForm, event: any) {
let image = event.clipboardData.files[0]; const image = event.clipboardData.files[0];
if (image) { if (image) {
i.handleImageUpload(i, image); i.handleImageUpload(i, image);
} }
@ -649,8 +649,8 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let mui = UserService.Instance.myUserInfo; const mui = UserService.Instance.myUserInfo;
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
// Errors handled by top level pages // Errors handled by top level pages
@ -658,18 +658,18 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.CreatePost) { } else if (op == UserOperation.CreatePost) {
let data = wsJsonToRes<PostResponse>(msg); const data = wsJsonToRes<PostResponse>(msg);
if (data.post_view.creator.id == mui?.local_user_view.person.id) { if (data.post_view.creator.id == mui?.local_user_view.person.id) {
this.props.onCreate?.(data.post_view); this.props.onCreate?.(data.post_view);
} }
} else if (op == UserOperation.EditPost) { } else if (op == UserOperation.EditPost) {
let data = wsJsonToRes<PostResponse>(msg); const data = wsJsonToRes<PostResponse>(msg);
if (data.post_view.creator.id == mui?.local_user_view.person.id) { if (data.post_view.creator.id == mui?.local_user_view.person.id) {
this.setState({ loading: false }); this.setState({ loading: false });
this.props.onEdit?.(data.post_view); this.props.onEdit?.(data.post_view);
} }
} else if (op == UserOperation.Search) { } else if (op == UserOperation.Search) {
let data = wsJsonToRes<SearchResponse>(msg); const data = wsJsonToRes<SearchResponse>(msg);
if (data.type_ == "Posts") { if (data.type_ == "Posts") {
this.setState({ suggestedPosts: data.posts }); this.setState({ suggestedPosts: data.posts });

View file

@ -179,7 +179,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
body() { body() {
let body = this.props.post_view.post.body; const body = this.props.post_view.post.body;
return body ? ( return body ? (
<div className="col-12 card my-2 p-2"> <div className="col-12 card my-2 p-2">
{this.state.viewSource ? ( {this.state.viewSource ? (
@ -194,7 +194,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get img() { get img() {
let src = this.imageSrc; const src = this.imageSrc;
return src ? ( return src ? (
<> <>
<div className="offset-sm-3 my-2 d-none d-sm-block"> <div className="offset-sm-3 my-2 d-none d-sm-block">
@ -217,7 +217,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
imgThumb(src: string) { imgThumb(src: string) {
let post_view = this.props.post_view; const post_view = this.props.post_view;
return ( return (
<PictrsImage <PictrsImage
src={src} src={src}
@ -229,9 +229,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get imageSrc(): string | undefined { get imageSrc(): string | undefined {
let post = this.props.post_view.post; const post = this.props.post_view.post;
let url = post.url; const url = post.url;
let thumbnail = post.thumbnail_url; const thumbnail = post.thumbnail_url;
if (url && isImage(url)) { if (url && isImage(url)) {
if (url.includes("pictrs")) { if (url.includes("pictrs")) {
@ -249,9 +249,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
thumbnail() { thumbnail() {
let post = this.props.post_view.post; const post = this.props.post_view.post;
let url = post.url; const url = post.url;
let thumbnail = post.thumbnail_url; const thumbnail = post.thumbnail_url;
if (!this.props.hideImage && url && isImage(url) && this.imageSrc) { if (!this.props.hideImage && url && isImage(url) && this.imageSrc) {
return ( return (
@ -318,9 +318,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
createdLine() { createdLine() {
let post_view = this.props.post_view; const post_view = this.props.post_view;
let url = post_view.post.url; const url = post_view.post.url;
let body = post_view.post.body; const body = post_view.post.body;
return ( return (
<ul className="list-inline mb-1 text-muted small"> <ul className="list-inline mb-1 text-muted small">
<li className="list-inline-item"> <li className="list-inline-item">
@ -438,7 +438,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get postLink() { get postLink() {
let post = this.props.post_view.post; const post = this.props.post_view.post;
return ( return (
<Link <Link
className={`d-inline-block ${ className={`d-inline-block ${
@ -458,8 +458,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
postTitleLine() { postTitleLine() {
let post = this.props.post_view.post; const post = this.props.post_view.post;
let url = post.url; const url = post.url;
return ( return (
<div className="post-title overflow-hidden"> <div className="post-title overflow-hidden">
@ -550,7 +550,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
duplicatesLine() { duplicatesLine() {
let dupes = this.props.duplicates; const dupes = this.props.duplicates;
return dupes && dupes.length > 0 ? ( return dupes && dupes.length > 0 ? (
<ul className="list-inline mb-1 small text-muted"> <ul className="list-inline mb-1 small text-muted">
<> <>
@ -572,7 +572,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
commentsLine(mobile = false) { commentsLine(mobile = false) {
let post = this.props.post_view.post; const post = this.props.post_view.post;
return ( return (
<div className="d-flex justify-content-start flex-wrap text-muted font-weight-bold mb-1"> <div className="d-flex justify-content-start flex-wrap text-muted font-weight-bold mb-1">
@ -606,7 +606,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
postActions(mobile = false) { postActions(mobile = false) {
// Possible enhancement: Priority+ pattern instead of just hard coding which get hidden behind the show more button. // Possible enhancement: Priority+ pattern instead of just hard coding which get hidden behind the show more button.
// Possible enhancement: Make each button a component. // Possible enhancement: Make each button a component.
let post_view = this.props.post_view; const post_view = this.props.post_view;
return ( return (
<> <>
{this.saveButton} {this.saveButton}
@ -647,7 +647,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get commentsButton() { get commentsButton() {
let post_view = this.props.post_view; const post_view = this.props.post_view;
return ( return (
<button className="btn btn-link text-muted py-0 pl-0"> <button className="btn btn-link text-muted py-0 pl-0">
<Link <Link
@ -676,7 +676,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get unreadCount(): number | undefined { get unreadCount(): number | undefined {
let pv = this.props.post_view; const pv = this.props.post_view;
return pv.unread_comments == pv.counts.comments || pv.unread_comments == 0 return pv.unread_comments == pv.counts.comments || pv.unread_comments == 0
? undefined ? undefined
: pv.unread_comments; : pv.unread_comments;
@ -684,7 +684,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
get mobileVotes() { get mobileVotes() {
// TODO: make nicer // TODO: make nicer
let tippy = showScores() ? { "data-tippy-content": this.pointsTippy } : {}; const tippy = showScores()
? { "data-tippy-content": this.pointsTippy }
: {};
return ( return (
<> <>
<div> <div>
@ -730,8 +732,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get saveButton() { get saveButton() {
let saved = this.props.post_view.saved; const saved = this.props.post_view.saved;
let label = saved ? i18n.t("unsave") : i18n.t("save"); const label = saved ? i18n.t("unsave") : i18n.t("save");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-animate text-muted py-0"
@ -807,8 +809,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get deleteButton() { get deleteButton() {
let deleted = this.props.post_view.post.deleted; const deleted = this.props.post_view.post.deleted;
let label = !deleted ? i18n.t("delete") : i18n.t("restore"); const label = !deleted ? i18n.t("delete") : i18n.t("restore");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-animate text-muted py-0"
@ -856,8 +858,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get lockButton() { get lockButton() {
let locked = this.props.post_view.post.locked; const locked = this.props.post_view.post.locked;
let label = locked ? i18n.t("unlock") : i18n.t("lock"); const label = locked ? i18n.t("unlock") : i18n.t("lock");
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-animate text-muted py-0"
@ -919,7 +921,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get modRemoveButton() { get modRemoveButton() {
let removed = this.props.post_view.post.removed; const removed = this.props.post_view.post.removed;
return ( return (
<button <button
className="btn btn-link btn-animate text-muted py-0" className="btn btn-link btn-animate text-muted py-0"
@ -939,7 +941,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
*/ */
userActionsLine() { userActionsLine() {
// TODO: make nicer // TODO: make nicer
let post_view = this.props.post_view; const post_view = this.props.post_view;
return ( return (
this.state.showAdvanced && ( this.state.showAdvanced && (
<> <>
@ -1089,8 +1091,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
removeAndBanDialogs() { removeAndBanDialogs() {
let post = this.props.post_view; const post = this.props.post_view;
let purgeTypeText = const purgeTypeText =
this.state.purgeType == PurgeType.Post this.state.purgeType == PurgeType.Post
? i18n.t("purge_post") ? i18n.t("purge_post")
: `${i18n.t("purge")} ${post.creator.name}`; : `${i18n.t("purge")} ${post.creator.name}`;
@ -1245,7 +1247,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
mobileThumbnail() { mobileThumbnail() {
let post = this.props.post_view.post; const post = this.props.post_view.post;
return post.thumbnail_url || (post.url && isImage(post.url)) ? ( return post.thumbnail_url || (post.url && isImage(post.url)) ? (
<div className="row"> <div className="row">
<div className={`${this.state.imageExpanded ? "col-12" : "col-8"}`}> <div className={`${this.state.imageExpanded ? "col-12" : "col-8"}`}>
@ -1262,7 +1264,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
showMobilePreview() { showMobilePreview() {
let body = this.props.post_view.post.body; const body = this.props.post_view.post.body;
return !this.showBody && body ? ( return !this.showBody && body ? (
<div className="md-div mb-1 preview-lines">{body}</div> <div className="md-div mb-1 preview-lines">{body}</div>
) : ( ) : (
@ -1331,8 +1333,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
this.context.router.history.push(`/login`); this.context.router.history.push(`/login`);
} }
let myVote = this.state.my_vote; const myVote = this.state.my_vote;
let newVote = myVote == 1 ? 0 : 1; const newVote = myVote == 1 ? 0 : 1;
if (myVote == 1) { if (myVote == 1) {
this.setState({ this.setState({
@ -1354,9 +1356,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
this.setState({ my_vote: newVote }); this.setState({ my_vote: newVote });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: CreatePostLike = { const form: CreatePostLike = {
post_id: this.props.post_view.post.id, post_id: this.props.post_view.post.id,
score: newVote, score: newVote,
auth, auth,
@ -1374,8 +1376,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
this.context.router.history.push(`/login`); this.context.router.history.push(`/login`);
} }
let myVote = this.state.my_vote; const myVote = this.state.my_vote;
let newVote = myVote == -1 ? 0 : -1; const newVote = myVote == -1 ? 0 : -1;
if (myVote == 1) { if (myVote == 1) {
this.setState({ this.setState({
@ -1397,9 +1399,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
this.setState({ my_vote: newVote }); this.setState({ my_vote: newVote });
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: CreatePostLike = { const form: CreatePostLike = {
post_id: this.props.post_view.post.id, post_id: this.props.post_view.post.id,
score: newVote, score: newVote,
auth, auth,
@ -1443,10 +1445,10 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
handleReportSubmit(i: PostListing, event: any) { handleReportSubmit(i: PostListing, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
let reason = i.state.reportReason; const reason = i.state.reportReason;
if (auth && reason) { if (auth && reason) {
let form: CreatePostReport = { const form: CreatePostReport = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
reason, reason,
auth, auth,
@ -1458,9 +1460,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleBlockUserClick(i: PostListing) { handleBlockUserClick(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let blockUserForm: BlockPerson = { const blockUserForm: BlockPerson = {
person_id: i.props.post_view.creator.id, person_id: i.props.post_view.creator.id,
block: true, block: true,
auth, auth,
@ -1470,9 +1472,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleDeleteClick(i: PostListing) { handleDeleteClick(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let deleteForm: DeletePost = { const deleteForm: DeletePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
deleted: !i.props.post_view.post.deleted, deleted: !i.props.post_view.post.deleted,
auth, auth,
@ -1482,11 +1484,11 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleSavePostClick(i: PostListing) { handleSavePostClick(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let saved = const saved =
i.props.post_view.saved == undefined ? true : !i.props.post_view.saved; i.props.post_view.saved == undefined ? true : !i.props.post_view.saved;
let form: SavePost = { const form: SavePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
save: saved, save: saved,
auth, auth,
@ -1514,8 +1516,8 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
crossPostBody(): string | undefined { crossPostBody(): string | undefined {
let post = this.props.post_view.post; const post = this.props.post_view.post;
let body = post.body; const body = post.body;
return body return body
? `${i18n.t("cross_posted_from")} ${post.ap_id}\n\n${body.replace( ? `${i18n.t("cross_posted_from")} ${post.ap_id}\n\n${body.replace(
@ -1547,9 +1549,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
handleModRemoveSubmit(i: PostListing, event: any) { handleModRemoveSubmit(i: PostListing, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: RemovePost = { const form: RemovePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
removed: !i.props.post_view.post.removed, removed: !i.props.post_view.post.removed,
reason: i.state.removeReason, reason: i.state.removeReason,
@ -1561,9 +1563,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleModLock(i: PostListing) { handleModLock(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: LockPost = { const form: LockPost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
locked: !i.props.post_view.post.locked, locked: !i.props.post_view.post.locked,
auth, auth,
@ -1573,9 +1575,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleModFeaturePostLocal(i: PostListing) { handleModFeaturePostLocal(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: FeaturePost = { const form: FeaturePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
feature_type: "Local", feature_type: "Local",
featured: !i.props.post_view.post.featured_local, featured: !i.props.post_view.post.featured_local,
@ -1586,9 +1588,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleModFeaturePostCommunity(i: PostListing) { handleModFeaturePostCommunity(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: FeaturePost = { const form: FeaturePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
feature_type: "Community", feature_type: "Community",
featured: !i.props.post_view.post.featured_community, featured: !i.props.post_view.post.featured_community,
@ -1637,17 +1639,17 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
handlePurgeSubmit(i: PostListing, event: any) { handlePurgeSubmit(i: PostListing, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
if (i.state.purgeType == PurgeType.Person) { if (i.state.purgeType == PurgeType.Person) {
let form: PurgePerson = { const form: PurgePerson = {
person_id: i.props.post_view.creator.id, person_id: i.props.post_view.creator.id,
reason: i.state.purgeReason, reason: i.state.purgeReason,
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.purgePerson(form)); WebSocketService.Instance.send(wsClient.purgePerson(form));
} else if (i.state.purgeType == PurgeType.Post) { } else if (i.state.purgeType == PurgeType.Post) {
let form: PurgePost = { const form: PurgePost = {
post_id: i.props.post_view.post.id, post_id: i.props.post_view.post.id,
reason: i.state.purgeReason, reason: i.state.purgeReason,
auth, auth,
@ -1679,13 +1681,13 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
handleModBanBothSubmit(i: PostListing, event?: any) { handleModBanBothSubmit(i: PostListing, event?: any) {
if (event) event.preventDefault(); if (event) event.preventDefault();
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let ban = !i.props.post_view.creator_banned_from_community; const ban = !i.props.post_view.creator_banned_from_community;
let person_id = i.props.post_view.creator.id; const person_id = i.props.post_view.creator.id;
let remove_data = i.state.removeData; const remove_data = i.state.removeData;
let reason = i.state.banReason; const reason = i.state.banReason;
let expires = futureDaysToUnixTime(i.state.banExpireDays); const expires = futureDaysToUnixTime(i.state.banExpireDays);
if (i.state.banType == BanType.Community) { if (i.state.banType == BanType.Community) {
// If its an unban, restore all their data // If its an unban, restore all their data
@ -1693,7 +1695,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
i.setState({ removeData: false }); i.setState({ removeData: false });
} }
let form: BanFromCommunity = { const form: BanFromCommunity = {
person_id, person_id,
community_id: i.props.post_view.community.id, community_id: i.props.post_view.community.id,
ban, ban,
@ -1705,11 +1707,11 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
WebSocketService.Instance.send(wsClient.banFromCommunity(form)); WebSocketService.Instance.send(wsClient.banFromCommunity(form));
} else { } else {
// If its an unban, restore all their data // If its an unban, restore all their data
let ban = !i.props.post_view.creator.banned; const ban = !i.props.post_view.creator.banned;
if (ban == false) { if (ban == false) {
i.setState({ removeData: false }); i.setState({ removeData: false });
} }
let form: BanPerson = { const form: BanPerson = {
person_id, person_id,
ban, ban,
remove_data, remove_data,
@ -1725,9 +1727,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleAddModToCommunity(i: PostListing) { handleAddModToCommunity(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: AddModToCommunity = { const form: AddModToCommunity = {
person_id: i.props.post_view.creator.id, person_id: i.props.post_view.creator.id,
community_id: i.props.post_view.community.id, community_id: i.props.post_view.community.id,
added: !i.creatorIsMod_, added: !i.creatorIsMod_,
@ -1739,9 +1741,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleAddAdmin(i: PostListing) { handleAddAdmin(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: AddAdmin = { const form: AddAdmin = {
person_id: i.props.post_view.creator.id, person_id: i.props.post_view.creator.id,
added: !i.creatorIsAdmin_, added: !i.creatorIsAdmin_,
auth, auth,
@ -1760,9 +1762,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
handleTransferCommunity(i: PostListing) { handleTransferCommunity(i: PostListing) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: TransferCommunity = { const form: TransferCommunity = {
community_id: i.props.post_view.community.id, community_id: i.props.post_view.community.id,
person_id: i.props.post_view.creator.id, person_id: i.props.post_view.creator.id,
auth, auth,
@ -1809,17 +1811,17 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
} }
get pointsTippy(): string { get pointsTippy(): string {
let points = i18n.t("number_of_points", { const points = i18n.t("number_of_points", {
count: Number(this.state.score), count: Number(this.state.score),
formattedCount: Number(this.state.score), formattedCount: Number(this.state.score),
}); });
let upvotes = i18n.t("number_of_upvotes", { const upvotes = i18n.t("number_of_upvotes", {
count: Number(this.state.upvotes), count: Number(this.state.upvotes),
formattedCount: Number(this.state.upvotes), formattedCount: Number(this.state.upvotes),
}); });
let downvotes = i18n.t("number_of_downvotes", { const downvotes = i18n.t("number_of_downvotes", {
count: Number(this.state.downvotes), count: Number(this.state.downvotes),
formattedCount: Number(this.state.downvotes), formattedCount: Number(this.state.downvotes),
}); });

View file

@ -62,14 +62,14 @@ export class PostListings extends Component<PostListingsProps, any> {
removeDuplicates(): PostView[] { removeDuplicates(): PostView[] {
// Must use a spread to clone the props, because splice will fail below otherwise. // Must use a spread to clone the props, because splice will fail below otherwise.
let posts = [...this.props.posts]; const posts = [...this.props.posts];
// A map from post url to list of posts (dupes) // A map from post url to list of posts (dupes)
let urlMap = new Map<string, PostView[]>(); const urlMap = new Map<string, PostView[]>();
// Loop over the posts, find ones with same urls // Loop over the posts, find ones with same urls
for (let pv of posts) { for (const pv of posts) {
let url = pv.post.url; const url = pv.post.url;
if ( if (
!pv.post.deleted && !pv.post.deleted &&
!pv.post.removed && !pv.post.removed &&
@ -87,7 +87,7 @@ export class PostListings extends Component<PostListingsProps, any> {
// Sort by oldest // Sort by oldest
// Remove the ones that have no length // Remove the ones that have no length
for (let e of urlMap.entries()) { for (const e of urlMap.entries()) {
if (e[1].length == 1) { if (e[1].length == 1) {
urlMap.delete(e[0]); urlMap.delete(e[0]);
} else { } else {
@ -96,10 +96,10 @@ export class PostListings extends Component<PostListingsProps, any> {
} }
for (let i = 0; i < posts.length; i++) { for (let i = 0; i < posts.length; i++) {
let pv = posts[i]; const pv = posts[i];
let url = pv.post.url; const url = pv.post.url;
if (url) { if (url) {
let found = urlMap.get(url); const found = urlMap.get(url);
if (found) { if (found) {
// If its the oldest, add // If its the oldest, add
if (pv.post.id == found[0].post.id) { if (pv.post.id == found[0].post.id) {

View file

@ -18,10 +18,10 @@ export class PostReport extends Component<PostReportProps, any> {
} }
render() { render() {
let r = this.props.report; const r = this.props.report;
let resolver = r.resolver; const resolver = r.resolver;
let post = r.post; const post = r.post;
let tippyContent = i18n.t( const tippyContent = i18n.t(
r.post_report.resolved ? "unresolve_report" : "resolve_report" r.post_report.resolved ? "unresolve_report" : "resolve_report"
); );
@ -29,7 +29,7 @@ export class PostReport extends Component<PostReportProps, any> {
post.name = r.post_report.original_post_name; post.name = r.post_report.original_post_name;
post.url = r.post_report.original_post_url; post.url = r.post_report.original_post_url;
post.body = r.post_report.original_post_body; post.body = r.post_report.original_post_body;
let pv: PostView = { const pv: PostView = {
post, post,
creator: r.post_creator, creator: r.post_creator,
community: r.community, community: r.community,
@ -94,9 +94,9 @@ export class PostReport extends Component<PostReportProps, any> {
} }
handleResolveReport(i: PostReport) { handleResolveReport(i: PostReport) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: ResolvePostReport = { const form: ResolvePostReport = {
report_id: i.props.report.post_report.id, report_id: i.props.report.post_report.id,
resolved: !i.props.report.post_report.resolved, resolved: !i.props.report.post_report.resolved,
auth, auth,

View file

@ -161,15 +161,15 @@ export class Post extends Component<any, PostState> {
} }
fetchPost() { fetchPost() {
let auth = myAuth(false); const auth = myAuth(false);
let postForm: GetPost = { const postForm: GetPost = {
id: this.state.postId, id: this.state.postId,
comment_id: this.state.commentId, comment_id: this.state.commentId,
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.getPost(postForm)); WebSocketService.Instance.send(wsClient.getPost(postForm));
let commentsForm: GetComments = { const commentsForm: GetComments = {
post_id: this.state.postId, post_id: this.state.postId,
parent_id: this.state.commentId, parent_id: this.state.commentId,
max_depth: commentTreeMaxDepth, max_depth: commentTreeMaxDepth,
@ -182,9 +182,9 @@ export class Post extends Component<any, PostState> {
} }
fetchCrossPosts() { fetchCrossPosts() {
let q = this.state.postRes?.post_view.post.url; const q = this.state.postRes?.post_view.post.url;
if (q) { if (q) {
let form: Search = { const form: Search = {
q, q,
type_: "Url", type_: "Url",
sort: "TopAll", sort: "TopAll",
@ -198,18 +198,18 @@ export class Post extends Component<any, PostState> {
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let pathSplit = req.path.split("/"); const pathSplit = req.path.split("/");
let promises: Promise<any>[] = []; const promises: Promise<any>[] = [];
let pathType = pathSplit.at(1); const pathType = pathSplit.at(1);
let id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined; const id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined;
let auth = req.auth; const auth = req.auth;
let postForm: GetPost = { const postForm: GetPost = {
auth, auth,
}; };
let commentsForm: GetComments = { const commentsForm: GetComments = {
max_depth: commentTreeMaxDepth, max_depth: commentTreeMaxDepth,
sort: "Hot", sort: "Hot",
type_: "All", type_: "All",
@ -286,21 +286,21 @@ export class Post extends Component<any, PostState> {
}; };
get documentTitle(): string { get documentTitle(): string {
let name_ = this.state.postRes?.post_view.post.name; const name_ = this.state.postRes?.post_view.post.name;
let siteName = this.state.siteRes.site_view.site.name; const siteName = this.state.siteRes.site_view.site.name;
return name_ ? `${name_} - ${siteName}` : ""; return name_ ? `${name_} - ${siteName}` : "";
} }
get imageTag(): string | undefined { get imageTag(): string | undefined {
let post = this.state.postRes?.post_view.post; const post = this.state.postRes?.post_view.post;
let thumbnail = post?.thumbnail_url; const thumbnail = post?.thumbnail_url;
let url = post?.url; const url = post?.url;
return thumbnail || (url && isImage(url) ? url : undefined); return thumbnail || (url && isImage(url) ? url : undefined);
} }
render() { render() {
let res = this.state.postRes; const res = this.state.postRes;
let description = res?.post_view.post.body; const description = res?.post_view.post.body;
return ( return (
<div className="container-lg"> <div className="container-lg">
{this.state.loading ? ( {this.state.loading ? (
@ -445,8 +445,8 @@ export class Post extends Component<any, PostState> {
commentsFlat() { commentsFlat() {
// These are already sorted by new // These are already sorted by new
let commentsRes = this.state.commentsRes; const commentsRes = this.state.commentsRes;
let postRes = this.state.postRes; const postRes = this.state.postRes;
return ( return (
commentsRes && commentsRes &&
postRes && ( postRes && (
@ -470,7 +470,7 @@ export class Post extends Component<any, PostState> {
} }
sidebar() { sidebar() {
let res = this.state.postRes; const res = this.state.postRes;
return ( return (
res && ( res && (
<div className="mb-3"> <div className="mb-3">
@ -500,7 +500,7 @@ export class Post extends Component<any, PostState> {
} }
handleCommentViewTypeChange(i: Post, event: any) { handleCommentViewTypeChange(i: Post, event: any) {
let comments = i.state.commentsRes?.comments; const comments = i.state.commentsRes?.comments;
if (comments) { if (comments) {
i.setState({ i.setState({
commentViewType: Number(event.target.value), commentViewType: Number(event.target.value),
@ -515,14 +515,14 @@ export class Post extends Component<any, PostState> {
} }
handleViewPost(i: Post) { handleViewPost(i: Post) {
let id = i.state.postRes?.post_view.post.id; const id = i.state.postRes?.post_view.post.id;
if (id) { if (id) {
i.context.router.history.push(`/post/${id}`); i.context.router.history.push(`/post/${id}`);
} }
} }
handleViewContext(i: Post) { handleViewContext(i: Post) {
let parentId = getCommentParentId( const parentId = getCommentParentId(
i.state.commentsRes?.comments?.at(0)?.comment i.state.commentsRes?.comments?.at(0)?.comment
); );
if (parentId) { if (parentId) {
@ -531,10 +531,10 @@ export class Post extends Component<any, PostState> {
} }
commentsTree() { commentsTree() {
let res = this.state.postRes; const res = this.state.postRes;
let firstComment = this.state.commentTree.at(0)?.comment_view.comment; const firstComment = this.state.commentTree.at(0)?.comment_view.comment;
let depth = getDepthFromComment(firstComment); const depth = getDepthFromComment(firstComment);
let showContextButton = depth ? depth > 0 : false; const showContextButton = depth ? depth > 0 : false;
return ( return (
res && ( res && (
@ -574,13 +574,13 @@ export class Post extends Component<any, PostState> {
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
return; return;
} else if (msg.reconnect) { } else if (msg.reconnect) {
let post_id = this.state.postRes?.post_view.post.id; const post_id = this.state.postRes?.post_view.post.id;
if (post_id) { if (post_id) {
WebSocketService.Instance.send(wsClient.postJoin({ post_id })); WebSocketService.Instance.send(wsClient.postJoin({ post_id }));
WebSocketService.Instance.send( WebSocketService.Instance.send(
@ -591,7 +591,7 @@ export class Post extends Component<any, PostState> {
); );
} }
} else if (op == UserOperation.GetPost) { } else if (op == UserOperation.GetPost) {
let data = wsJsonToRes<GetPostResponse>(msg); const data = wsJsonToRes<GetPostResponse>(msg);
this.setState({ postRes: data }); this.setState({ postRes: data });
// join the rooms // join the rooms
@ -614,35 +614,35 @@ export class Post extends Component<any, PostState> {
this.scrollIntoCommentSection(); this.scrollIntoCommentSection();
} }
} else if (op == UserOperation.GetComments) { } else if (op == UserOperation.GetComments) {
let data = wsJsonToRes<GetCommentsResponse>(msg); const data = wsJsonToRes<GetCommentsResponse>(msg);
// This section sets the comments res // This section sets the comments res
let comments = this.state.commentsRes?.comments; const comments = this.state.commentsRes?.comments;
if (comments) { if (comments) {
// You might need to append here, since this could be building more comments from a tree fetch // You might need to append here, since this could be building more comments from a tree fetch
// Remove the first comment, since it is the parent // Remove the first comment, since it is the parent
let newComments = data.comments; const newComments = data.comments;
newComments.shift(); newComments.shift();
comments.push(...newComments); comments.push(...newComments);
} else { } else {
this.setState({ commentsRes: data }); this.setState({ commentsRes: data });
} }
let cComments = this.state.commentsRes?.comments ?? []; const cComments = this.state.commentsRes?.comments ?? [];
this.setState({ this.setState({
commentTree: buildCommentsTree(cComments, !!this.state.commentId), commentTree: buildCommentsTree(cComments, !!this.state.commentId),
loading: false, loading: false,
}); });
} else if (op == UserOperation.CreateComment) { } else if (op == UserOperation.CreateComment) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
// Don't get comments from the post room, if the creator is blocked // Don't get comments from the post room, if the creator is blocked
let creatorBlocked = UserService.Instance.myUserInfo?.person_blocks const creatorBlocked = UserService.Instance.myUserInfo?.person_blocks
.map(pb => pb.target.id) .map(pb => pb.target.id)
.includes(data.comment_view.creator.id); .includes(data.comment_view.creator.id);
// Necessary since it might be a user reply, which has the recipients, to avoid double // Necessary since it might be a user reply, which has the recipients, to avoid double
let postRes = this.state.postRes; const postRes = this.state.postRes;
let commentsRes = this.state.commentsRes; const commentsRes = this.state.commentsRes;
if ( if (
data.recipient_ids.length == 0 && data.recipient_ids.length == 0 &&
!creatorBlocked && !creatorBlocked &&
@ -666,21 +666,21 @@ export class Post extends Component<any, PostState> {
op == UserOperation.DeleteComment || op == UserOperation.DeleteComment ||
op == UserOperation.RemoveComment op == UserOperation.RemoveComment
) { ) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
editCommentRes(data.comment_view, this.state.commentsRes?.comments); editCommentRes(data.comment_view, this.state.commentsRes?.comments);
this.setState(this.state); this.setState(this.state);
setupTippy(); setupTippy();
} else if (op == UserOperation.SaveComment) { } else if (op == UserOperation.SaveComment) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
saveCommentRes(data.comment_view, this.state.commentsRes?.comments); saveCommentRes(data.comment_view, this.state.commentsRes?.comments);
this.setState(this.state); this.setState(this.state);
setupTippy(); setupTippy();
} else if (op == UserOperation.CreateCommentLike) { } else if (op == UserOperation.CreateCommentLike) {
let data = wsJsonToRes<CommentResponse>(msg); const data = wsJsonToRes<CommentResponse>(msg);
createCommentLikeRes(data.comment_view, this.state.commentsRes?.comments); createCommentLikeRes(data.comment_view, this.state.commentsRes?.comments);
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.CreatePostLike) { } else if (op == UserOperation.CreatePostLike) {
let data = wsJsonToRes<PostResponse>(msg); const data = wsJsonToRes<PostResponse>(msg);
createPostLikeRes(data.post_view, this.state.postRes?.post_view); createPostLikeRes(data.post_view, this.state.postRes?.post_view);
this.setState(this.state); this.setState(this.state);
} else if ( } else if (
@ -691,8 +691,8 @@ export class Post extends Component<any, PostState> {
op == UserOperation.FeaturePost || op == UserOperation.FeaturePost ||
op == UserOperation.SavePost op == UserOperation.SavePost
) { ) {
let data = wsJsonToRes<PostResponse>(msg); const data = wsJsonToRes<PostResponse>(msg);
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
res.post_view = data.post_view; res.post_view = data.post_view;
this.setState(this.state); this.setState(this.state);
@ -704,17 +704,17 @@ export class Post extends Component<any, PostState> {
op == UserOperation.RemoveCommunity || op == UserOperation.RemoveCommunity ||
op == UserOperation.FollowCommunity op == UserOperation.FollowCommunity
) { ) {
let data = wsJsonToRes<CommunityResponse>(msg); const data = wsJsonToRes<CommunityResponse>(msg);
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
res.community_view = data.community_view; res.community_view = data.community_view;
res.post_view.community = data.community_view.community; res.post_view.community = data.community_view.community;
this.setState(this.state); this.setState(this.state);
} }
} else if (op == UserOperation.BanFromCommunity) { } else if (op == UserOperation.BanFromCommunity) {
let data = wsJsonToRes<BanFromCommunityResponse>(msg); const data = wsJsonToRes<BanFromCommunityResponse>(msg);
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
if (res.post_view.creator.id == data.person_view.person.id) { if (res.post_view.creator.id == data.person_view.person.id) {
res.post_view.creator_banned_from_community = data.banned; res.post_view.creator_banned_from_community = data.banned;
@ -726,19 +726,19 @@ export class Post extends Component<any, PostState> {
.forEach(c => (c.creator_banned_from_community = data.banned)); .forEach(c => (c.creator_banned_from_community = data.banned));
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.AddModToCommunity) { } else if (op == UserOperation.AddModToCommunity) {
let data = wsJsonToRes<AddModToCommunityResponse>(msg); const data = wsJsonToRes<AddModToCommunityResponse>(msg);
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
res.moderators = data.moderators; res.moderators = data.moderators;
this.setState(this.state); this.setState(this.state);
} }
} else if (op == UserOperation.BanPerson) { } else if (op == UserOperation.BanPerson) {
let data = wsJsonToRes<BanPersonResponse>(msg); const data = wsJsonToRes<BanPersonResponse>(msg);
this.state.commentsRes?.comments this.state.commentsRes?.comments
.filter(c => c.creator.id == data.person_view.person.id) .filter(c => c.creator.id == data.person_view.person.id)
.forEach(c => (c.creator.banned = data.banned)); .forEach(c => (c.creator.banned = data.banned));
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
if (res.post_view.creator.id == data.person_view.person.id) { if (res.post_view.creator.id == data.person_view.person.id) {
res.post_view.creator.banned = data.banned; res.post_view.creator.banned = data.banned;
@ -746,20 +746,20 @@ export class Post extends Component<any, PostState> {
} }
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.AddAdmin) { } else if (op == UserOperation.AddAdmin) {
let data = wsJsonToRes<AddAdminResponse>(msg); const data = wsJsonToRes<AddAdminResponse>(msg);
this.setState(s => ((s.siteRes.admins = data.admins), s)); this.setState(s => ((s.siteRes.admins = data.admins), s));
} else if (op == UserOperation.Search) { } else if (op == UserOperation.Search) {
let data = wsJsonToRes<SearchResponse>(msg); const data = wsJsonToRes<SearchResponse>(msg);
let xPosts = data.posts.filter( const xPosts = data.posts.filter(
p => p.post.ap_id != this.state.postRes?.post_view.post.ap_id p => p.post.ap_id != this.state.postRes?.post_view.post.ap_id
); );
this.setState({ crossPosts: xPosts.length > 0 ? xPosts : undefined }); this.setState({ crossPosts: xPosts.length > 0 ? xPosts : undefined });
} else if (op == UserOperation.LeaveAdmin) { } else if (op == UserOperation.LeaveAdmin) {
let data = wsJsonToRes<GetSiteResponse>(msg); const data = wsJsonToRes<GetSiteResponse>(msg);
this.setState({ siteRes: data }); this.setState({ siteRes: data });
} else if (op == UserOperation.TransferCommunity) { } else if (op == UserOperation.TransferCommunity) {
let data = wsJsonToRes<GetCommunityResponse>(msg); const data = wsJsonToRes<GetCommunityResponse>(msg);
let res = this.state.postRes; const res = this.state.postRes;
if (res) { if (res) {
res.community_view = data.community_view; res.community_view = data.community_view;
res.post_view.community = data.community_view.community; res.post_view.community = data.community_view.community;
@ -767,15 +767,15 @@ export class Post extends Component<any, PostState> {
this.setState(this.state); this.setState(this.state);
} }
} else if (op == UserOperation.BlockPerson) { } else if (op == UserOperation.BlockPerson) {
let data = wsJsonToRes<BlockPersonResponse>(msg); const data = wsJsonToRes<BlockPersonResponse>(msg);
updatePersonBlock(data); updatePersonBlock(data);
} else if (op == UserOperation.CreatePostReport) { } else if (op == UserOperation.CreatePostReport) {
let data = wsJsonToRes<PostReportResponse>(msg); const data = wsJsonToRes<PostReportResponse>(msg);
if (data) { if (data) {
toast(i18n.t("report_created")); toast(i18n.t("report_created"));
} }
} else if (op == UserOperation.CreateCommentReport) { } else if (op == UserOperation.CreateCommentReport) {
let data = wsJsonToRes<CommentReportResponse>(msg); const data = wsJsonToRes<CommentReportResponse>(msg);
if (data) { if (data) {
toast(i18n.t("report_created")); toast(i18n.t("report_created"));
} }
@ -785,7 +785,7 @@ export class Post extends Component<any, PostState> {
op == UserOperation.PurgeComment || op == UserOperation.PurgeComment ||
op == UserOperation.PurgeCommunity op == UserOperation.PurgeCommunity
) { ) {
let data = wsJsonToRes<PurgeItemResponse>(msg); const data = wsJsonToRes<PurgeItemResponse>(msg);
if (data.success) { if (data.success) {
toast(i18n.t("purge_success")); toast(i18n.t("purge_success"));
this.context.router.history.push(`/`); this.context.router.history.push(`/`);

View file

@ -65,7 +65,7 @@ export class CreatePrivateMessage extends Component<
} }
fetchPersonDetails() { fetchPersonDetails() {
let form: GetPersonDetails = { const form: GetPersonDetails = {
person_id: this.state.recipient_id, person_id: this.state.recipient_id,
sort: "New", sort: "New",
saved_only: false, saved_only: false,
@ -75,8 +75,8 @@ export class CreatePrivateMessage extends Component<
} }
static fetchInitialData(req: InitialFetchRequest): Promise<any>[] { static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
let person_id = Number(req.path.split("/").pop()); const person_id = Number(req.path.split("/").pop());
let form: GetPersonDetails = { const form: GetPersonDetails = {
person_id, person_id,
sort: "New", sort: "New",
saved_only: false, saved_only: false,
@ -86,7 +86,7 @@ export class CreatePrivateMessage extends Component<
} }
get documentTitle(): string { get documentTitle(): string {
let name_ = this.state.recipientDetailsRes?.person_view.person.name; const name_ = this.state.recipientDetailsRes?.person_view.person.name;
return name_ ? `${i18n.t("create_private_message")} - ${name_}` : ""; return name_ ? `${i18n.t("create_private_message")} - ${name_}` : "";
} }
@ -97,7 +97,7 @@ export class CreatePrivateMessage extends Component<
} }
render() { render() {
let res = this.state.recipientDetailsRes; const res = this.state.recipientDetailsRes;
return ( return (
<div className="container-lg"> <div className="container-lg">
<HtmlTags <HtmlTags
@ -133,14 +133,14 @@ export class CreatePrivateMessage extends Component<
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
this.setState({ loading: false }); this.setState({ loading: false });
return; return;
} else if (op == UserOperation.GetPersonDetails) { } else if (op == UserOperation.GetPersonDetails) {
let data = wsJsonToRes<GetPersonDetailsResponse>(msg); const data = wsJsonToRes<GetPersonDetailsResponse>(msg);
this.setState({ recipientDetailsRes: data, loading: false }); this.setState({ recipientDetailsRes: data, loading: false });
} }
} }

View file

@ -183,19 +183,19 @@ export class PrivateMessageForm extends Component<
handlePrivateMessageSubmit(i: PrivateMessageForm, event: any) { handlePrivateMessageSubmit(i: PrivateMessageForm, event: any) {
event.preventDefault(); event.preventDefault();
let pm = i.props.privateMessageView; const pm = i.props.privateMessageView;
let auth = myAuth(); const auth = myAuth();
let content = i.state.content; const content = i.state.content;
if (auth && content) { if (auth && content) {
if (pm) { if (pm) {
let form: EditPrivateMessage = { const form: EditPrivateMessage = {
private_message_id: pm.private_message.id, private_message_id: pm.private_message.id,
content, content,
auth, auth,
}; };
WebSocketService.Instance.send(wsClient.editPrivateMessage(form)); WebSocketService.Instance.send(wsClient.editPrivateMessage(form));
} else { } else {
let form: CreatePrivateMessage = { const form: CreatePrivateMessage = {
content, content,
recipient_id: i.props.recipient.id, recipient_id: i.props.recipient.id,
auth, auth,
@ -224,7 +224,7 @@ export class PrivateMessageForm extends Component<
} }
parseMessage(msg: any) { parseMessage(msg: any) {
let op = wsUserOp(msg); const op = wsUserOp(msg);
console.log(msg); console.log(msg);
if (msg.error) { if (msg.error) {
toast(i18n.t(msg.error), "danger"); toast(i18n.t(msg.error), "danger");
@ -235,11 +235,11 @@ export class PrivateMessageForm extends Component<
op == UserOperation.DeletePrivateMessage || op == UserOperation.DeletePrivateMessage ||
op == UserOperation.MarkPrivateMessageAsRead op == UserOperation.MarkPrivateMessageAsRead
) { ) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
this.setState({ loading: false }); this.setState({ loading: false });
this.props.onEdit?.(data.private_message_view); this.props.onEdit?.(data.private_message_view);
} else if (op == UserOperation.CreatePrivateMessage) { } else if (op == UserOperation.CreatePrivateMessage) {
let data = wsJsonToRes<PrivateMessageResponse>(msg); const data = wsJsonToRes<PrivateMessageResponse>(msg);
this.props.onCreate?.(data.private_message_view); this.props.onCreate?.(data.private_message_view);
} }
} }

View file

@ -20,9 +20,9 @@ export class PrivateMessageReport extends Component<Props, any> {
} }
render() { render() {
let r = this.props.report; const r = this.props.report;
let pmr = r.private_message_report; const pmr = r.private_message_report;
let tippyContent = i18n.t( const tippyContent = i18n.t(
r.private_message_report.resolved ? "unresolve_report" : "resolve_report" r.private_message_report.resolved ? "unresolve_report" : "resolve_report"
); );
@ -78,10 +78,10 @@ export class PrivateMessageReport extends Component<Props, any> {
} }
handleResolveReport(i: PrivateMessageReport) { handleResolveReport(i: PrivateMessageReport) {
let pmr = i.props.report.private_message_report; const pmr = i.props.report.private_message_report;
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: ResolvePrivateMessageReport = { const form: ResolvePrivateMessageReport = {
report_id: pmr.id, report_id: pmr.id,
resolved: !pmr.resolved, resolved: !pmr.resolved,
auth, auth,

View file

@ -56,8 +56,8 @@ export class PrivateMessage extends Component<
} }
render() { render() {
let message_view = this.props.private_message_view; const message_view = this.props.private_message_view;
let otherPerson: Person = this.mine const otherPerson: Person = this.mine
? message_view.recipient ? message_view.recipient
: message_view.creator; : message_view.creator;
@ -261,7 +261,7 @@ export class PrivateMessage extends Component<
} }
get messageUnlessRemoved(): string { get messageUnlessRemoved(): string {
let message = this.props.private_message_view.private_message; const message = this.props.private_message_view.private_message;
return message.deleted ? `*${i18n.t("deleted")}*` : message.content; return message.deleted ? `*${i18n.t("deleted")}*` : message.content;
} }
@ -275,9 +275,9 @@ export class PrivateMessage extends Component<
} }
handleDeleteClick(i: PrivateMessage) { handleDeleteClick(i: PrivateMessage) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: DeletePrivateMessage = { const form: DeletePrivateMessage = {
private_message_id: i.props.private_message_view.private_message.id, private_message_id: i.props.private_message_view.private_message.id,
deleted: !i.props.private_message_view.private_message.deleted, deleted: !i.props.private_message_view.private_message.deleted,
auth, auth,
@ -291,9 +291,9 @@ export class PrivateMessage extends Component<
} }
handleMarkRead(i: PrivateMessage) { handleMarkRead(i: PrivateMessage) {
let auth = myAuth(); const auth = myAuth();
if (auth) { if (auth) {
let form: MarkPrivateMessageAsRead = { const form: MarkPrivateMessageAsRead = {
private_message_id: i.props.private_message_view.private_message.id, private_message_id: i.props.private_message_view.private_message.id,
read: !i.props.private_message_view.private_message.read, read: !i.props.private_message_view.private_message.read,
auth, auth,
@ -320,10 +320,10 @@ export class PrivateMessage extends Component<
handleReportSubmit(i: PrivateMessage, event: any) { handleReportSubmit(i: PrivateMessage, event: any) {
event.preventDefault(); event.preventDefault();
let auth = myAuth(); const auth = myAuth();
let reason = i.state.reportReason; const reason = i.state.reportReason;
if (auth && reason) { if (auth && reason) {
let form: CreatePrivateMessageReport = { const form: CreatePrivateMessageReport = {
private_message_id: i.props.private_message_view.private_message.id, private_message_id: i.props.private_message_view.private_message.id,
reason, reason,
auth, auth,

View file

@ -34,7 +34,7 @@ export class UserService {
} }
public login(res: LoginResponse) { public login(res: LoginResponse) {
let expires = new Date(); const expires = new Date();
expires.setDate(expires.getDate() + 365); expires.setDate(expires.getDate() + 365);
if (res.jwt) { if (res.jwt) {
toast(i18n.t("logged_in")); toast(i18n.t("logged_in"));
@ -56,11 +56,11 @@ export class UserService {
} }
public auth(throwErr = true): string | undefined { public auth(throwErr = true): string | undefined {
let jwt = this.jwtInfo?.jwt; const jwt = this.jwtInfo?.jwt;
if (jwt) { if (jwt) {
return jwt; return jwt;
} else { } else {
let msg = "No JWT cookie found"; const msg = "No JWT cookie found";
if (throwErr && isBrowser()) { if (throwErr && isBrowser()) {
console.error(msg); console.error(msg);
toast(i18n.t("not_logged_in"), "danger"); toast(i18n.t("not_logged_in"), "danger");
@ -71,7 +71,7 @@ export class UserService {
} }
private setJwtInfo() { private setJwtInfo() {
let jwt: string | undefined = IsomorphicCookie.load("jwt"); const jwt: string | undefined = IsomorphicCookie.load("jwt");
if (jwt) { if (jwt) {
this.jwtInfo = { jwt, claims: jwt_decode(jwt) }; this.jwtInfo = { jwt, claims: jwt_decode(jwt) };

View file

@ -30,7 +30,7 @@ export class WebSocketService {
console.log(`Connected to ${getWsUri()}`); console.log(`Connected to ${getWsUri()}`);
if (!firstConnect) { if (!firstConnect) {
let res = { const res = {
reconnect: true, reconnect: true,
}; };
obs.next(res); obs.next(res);

View file

@ -110,7 +110,7 @@ export interface ErrorPageData {
adminMatrixIds?: string[]; adminMatrixIds?: string[];
} }
let customEmojis: EmojiMartCategory[] = []; const customEmojis: EmojiMartCategory[] = [];
export let customEmojisLookup: Map<string, CustomEmojiView> = new Map< export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
string, string,
CustomEmojiView CustomEmojiView
@ -192,11 +192,11 @@ export function hotRankPost(post_view: PostView): number {
export function hotRank(score: number, timeStr: string): number { export function hotRank(score: number, timeStr: string): number {
// Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date const date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
let now: Date = new Date(); const now: Date = new Date();
let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5; const hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
let rank = const rank =
(10000 * Math.log10(Math.max(1, 3 + Number(score)))) / (10000 * Math.log10(Math.max(1, 3 + Number(score)))) /
Math.pow(hoursElapsed + 2, 1.8); Math.pow(hoursElapsed + 2, 1.8);
@ -243,7 +243,7 @@ export function canMod(
.concat(mods?.map(m => m.moderator.id) ?? []) ?? []; .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
if (myUserInfo) { if (myUserInfo) {
let myIndex = adminsThenMods.findIndex( const myIndex = adminsThenMods.findIndex(
id => id == myUserInfo.local_user_view.person.id id => id == myUserInfo.local_user_view.person.id
); );
if (myIndex == -1) { if (myIndex == -1) {
@ -294,7 +294,7 @@ export function amCommunityCreator(
mods?: CommunityModeratorView[], mods?: CommunityModeratorView[],
myUserInfo = UserService.Instance.myUserInfo myUserInfo = UserService.Instance.myUserInfo
): boolean { ): boolean {
let myId = myUserInfo?.local_user_view.person.id; const myId = myUserInfo?.local_user_view.person.id;
// Don't allow mod actions on yourself // Don't allow mod actions on yourself
return myId == mods?.at(0)?.moderator.id && myId != creator_id; return myId == mods?.at(0)?.moderator.id && myId != creator_id;
} }
@ -304,7 +304,7 @@ export function amSiteCreator(
admins?: PersonView[], admins?: PersonView[],
myUserInfo = UserService.Instance.myUserInfo myUserInfo = UserService.Instance.myUserInfo
): boolean { ): boolean {
let myId = myUserInfo?.local_user_view.person.id; const myId = myUserInfo?.local_user_view.person.id;
return myId == admins?.at(0)?.person.id && myId != creator_id; return myId == admins?.at(0)?.person.id && myId != creator_id;
} }
@ -331,12 +331,12 @@ export function validURL(str: string) {
} }
export function communityRSSUrl(actorId: string, sort: string): string { export function communityRSSUrl(actorId: string, sort: string): string {
let url = new URL(actorId); const url = new URL(actorId);
return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`; return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
} }
export function validEmail(email: string) { export function validEmail(email: string) {
let re = const re =
/^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/; /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
return re.test(String(email).toLowerCase()); return re.test(String(email).toLowerCase());
} }
@ -346,8 +346,8 @@ export function capitalizeFirstLetter(str: string): string {
} }
export async function getSiteMetadata(url: string) { export async function getSiteMetadata(url: string) {
let form: GetSiteMetadata = { url }; const form: GetSiteMetadata = { url };
let client = new LemmyHttp(getHttpBase()); const client = new LemmyHttp(getHttpBase());
return client.getSiteMetadata(form); return client.getSiteMetadata(form);
} }
@ -404,8 +404,8 @@ export function getLanguages(
override?: string, override?: string,
myUserInfo = UserService.Instance.myUserInfo myUserInfo = UserService.Instance.myUserInfo
): string[] { ): string[] {
let myLang = myUserInfo?.local_user_view.local_user.interface_language; const myLang = myUserInfo?.local_user_view.local_user.interface_language;
let lang = override || myLang || "browser"; const lang = override || myLang || "browser";
if (lang == "browser" && isBrowser()) { if (lang == "browser" && isBrowser()) {
return getBrowserLanguages(); return getBrowserLanguages();
@ -416,10 +416,10 @@ export function getLanguages(
function getBrowserLanguages(): string[] { function getBrowserLanguages(): string[] {
// Intersect lemmy's langs, with the browser langs // Intersect lemmy's langs, with the browser langs
let langs = languages ? languages.map(l => l.code) : ["en"]; const langs = languages ? languages.map(l => l.code) : ["en"];
// NOTE, mobile browsers seem to be missing this list, so append en // NOTE, mobile browsers seem to be missing this list, so append en
let allowedLangs = navigator.languages const allowedLangs = navigator.languages
.concat("en") .concat("en")
.filter(v => langs.includes(v)); .filter(v => langs.includes(v));
return allowedLangs; return allowedLangs;
@ -441,11 +441,11 @@ export async function setTheme(theme: string, forceReload = false) {
theme = "darkly"; theme = "darkly";
} }
let themeList = await fetchThemeList(); const themeList = await fetchThemeList();
// Unload all the other themes // Unload all the other themes
for (var i = 0; i < themeList.length; i++) { for (var i = 0; i < themeList.length; i++) {
let styleSheet = document.getElementById(themeList[i]); const styleSheet = document.getElementById(themeList[i]);
if (styleSheet) { if (styleSheet) {
styleSheet.setAttribute("disabled", "disabled"); styleSheet.setAttribute("disabled", "disabled");
} }
@ -457,7 +457,7 @@ export async function setTheme(theme: string, forceReload = false) {
document.getElementById("default-dark")?.setAttribute("disabled", "disabled"); document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
// Load the theme dynamically // Load the theme dynamically
let cssLoc = `/css/themes/${theme}.css`; const cssLoc = `/css/themes/${theme}.css`;
loadCss(theme, cssLoc); loadCss(theme, cssLoc);
document.getElementById(theme)?.removeAttribute("disabled"); document.getElementById(theme)?.removeAttribute("disabled");
@ -568,10 +568,10 @@ interface NotifyInfo {
export function messageToastify(info: NotifyInfo, router: any) { export function messageToastify(info: NotifyInfo, router: any) {
if (isBrowser()) { if (isBrowser()) {
let htmlBody = info.body ? md.render(info.body) : ""; const htmlBody = info.body ? md.render(info.body) : "";
let backgroundColor = `var(--light)`; const backgroundColor = `var(--light)`;
let toast = Toastify({ const toast = Toastify({
text: `${htmlBody}<br />${info.name}`, text: `${htmlBody}<br />${info.name}`,
avatar: info.icon, avatar: info.icon,
backgroundColor: backgroundColor, backgroundColor: backgroundColor,
@ -593,7 +593,7 @@ export function messageToastify(info: NotifyInfo, router: any) {
} }
export function notifyPost(post_view: PostView, router: any) { export function notifyPost(post_view: PostView, router: any) {
let info: NotifyInfo = { const info: NotifyInfo = {
name: post_view.community.name, name: post_view.community.name,
icon: post_view.community.icon, icon: post_view.community.icon,
link: `/post/${post_view.post.id}`, link: `/post/${post_view.post.id}`,
@ -603,7 +603,7 @@ export function notifyPost(post_view: PostView, router: any) {
} }
export function notifyComment(comment_view: CommentView, router: any) { export function notifyComment(comment_view: CommentView, router: any) {
let info: NotifyInfo = { const info: NotifyInfo = {
name: comment_view.creator.name, name: comment_view.creator.name,
icon: comment_view.creator.avatar, icon: comment_view.creator.avatar,
link: `/comment/${comment_view.comment.id}`, link: `/comment/${comment_view.comment.id}`,
@ -613,7 +613,7 @@ export function notifyComment(comment_view: CommentView, router: any) {
} }
export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) { export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
let info: NotifyInfo = { const info: NotifyInfo = {
name: pmv.creator.name, name: pmv.creator.name,
icon: pmv.creator.avatar, icon: pmv.creator.avatar,
link: `/inbox`, link: `/inbox`,
@ -649,11 +649,11 @@ export function setupTribute() {
{ {
trigger: ":", trigger: ":",
menuItemTemplate: (item: any) => { menuItemTemplate: (item: any) => {
let shortName = `:${item.original.key}:`; const shortName = `:${item.original.key}:`;
return `${item.original.val} ${shortName}`; return `${item.original.val} ${shortName}`;
}, },
selectTemplate: (item: any) => { selectTemplate: (item: any) => {
let customEmoji = customEmojisLookup.get( const customEmoji = customEmojisLookup.get(
item.original.key item.original.key
)?.custom_emoji; )?.custom_emoji;
if (customEmoji == undefined) return `${item.original.val}`; if (customEmoji == undefined) return `${item.original.val}`;
@ -680,7 +680,7 @@ export function setupTribute() {
{ {
trigger: "@", trigger: "@",
selectTemplate: (item: any) => { selectTemplate: (item: any) => {
let it: PersonTribute = item.original; const it: PersonTribute = item.original;
return `[${it.key}](${it.view.person.actor_id})`; return `[${it.key}](${it.view.person.actor_id})`;
}, },
values: debounce(async (text: string, cb: any) => { values: debounce(async (text: string, cb: any) => {
@ -697,7 +697,7 @@ export function setupTribute() {
{ {
trigger: "!", trigger: "!",
selectTemplate: (item: any) => { selectTemplate: (item: any) => {
let it: CommunityTribute = item.original; const it: CommunityTribute = item.original;
return `[${it.key}](${it.view.community.actor_id})`; return `[${it.key}](${it.view.community.actor_id})`;
}, },
values: debounce(async (text: string, cb: any) => { values: debounce(async (text: string, cb: any) => {
@ -714,7 +714,10 @@ export function setupTribute() {
} }
function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) { function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category); const groupedEmojis = groupBy(
custom_emoji_views,
x => x.custom_emoji.category
);
for (const [category, emojis] of Object.entries(groupedEmojis)) { for (const [category, emojis] of Object.entries(groupedEmojis)) {
customEmojis.push({ customEmojis.push({
id: category, id: category,
@ -739,7 +742,7 @@ export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
keywords: custom_emoji_view.keywords.map(x => x.keyword), keywords: custom_emoji_view.keywords.map(x => x.keyword),
skins: [{ src: custom_emoji_view.custom_emoji.image_url }], skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
}; };
let categoryIndex = customEmojis.findIndex( const categoryIndex = customEmojis.findIndex(
x => x.id == custom_emoji_view.custom_emoji.category x => x.id == custom_emoji_view.custom_emoji.category
); );
if (categoryIndex == -1) { if (categoryIndex == -1) {
@ -749,7 +752,7 @@ export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
emojis: [emoji], emojis: [emoji],
}); });
} else { } else {
let emojiIndex = customEmojis[categoryIndex].emojis.findIndex( const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
x => x.id == custom_emoji_view.custom_emoji.shortcode x => x.id == custom_emoji_view.custom_emoji.shortcode
); );
if (emojiIndex == -1) { if (emojiIndex == -1) {
@ -766,7 +769,7 @@ export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
export function removeFromEmojiDataModel(id: number) { export function removeFromEmojiDataModel(id: number) {
let view: CustomEmojiView | undefined; let view: CustomEmojiView | undefined;
for (let item of customEmojisLookup.values()) { for (const item of customEmojisLookup.values()) {
if (item.custom_emoji.id === id) { if (item.custom_emoji.id === id) {
view = item; view = item;
break; break;
@ -872,9 +875,9 @@ interface PersonTribute {
} }
async function personSearch(text: string): Promise<PersonTribute[]> { async function personSearch(text: string): Promise<PersonTribute[]> {
let users = (await fetchUsers(text)).users; const users = (await fetchUsers(text)).users;
let persons: PersonTribute[] = users.map(pv => { const persons: PersonTribute[] = users.map(pv => {
let tribute: PersonTribute = { const tribute: PersonTribute = {
key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`, key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
view: pv, view: pv,
}; };
@ -889,9 +892,9 @@ interface CommunityTribute {
} }
async function communitySearch(text: string): Promise<CommunityTribute[]> { async function communitySearch(text: string): Promise<CommunityTribute[]> {
let comms = (await fetchCommunities(text)).communities; const comms = (await fetchCommunities(text)).communities;
let communities: CommunityTribute[] = comms.map(cv => { const communities: CommunityTribute[] = comms.map(cv => {
let tribute: CommunityTribute = { const tribute: CommunityTribute = {
key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`, key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
view: cv, view: cv,
}; };
@ -907,17 +910,17 @@ export function getRecipientIdFromProps(props: any): number {
} }
export function getIdFromProps(props: any): number | undefined { export function getIdFromProps(props: any): number | undefined {
let id = props.match.params.post_id; const id = props.match.params.post_id;
return id ? Number(id) : undefined; return id ? Number(id) : undefined;
} }
export function getCommentIdFromProps(props: any): number | undefined { export function getCommentIdFromProps(props: any): number | undefined {
let id = props.match.params.comment_id; const id = props.match.params.comment_id;
return id ? Number(id) : undefined; return id ? Number(id) : undefined;
} }
export function editCommentRes(data: CommentView, comments?: CommentView[]) { export function editCommentRes(data: CommentView, comments?: CommentView[]) {
let found = comments?.find(c => c.comment.id == data.comment.id); const found = comments?.find(c => c.comment.id == data.comment.id);
if (found) { if (found) {
found.comment.content = data.comment.content; found.comment.content = data.comment.content;
found.comment.distinguished = data.comment.distinguished; found.comment.distinguished = data.comment.distinguished;
@ -931,7 +934,7 @@ export function editCommentRes(data: CommentView, comments?: CommentView[]) {
} }
export function saveCommentRes(data: CommentView, comments?: CommentView[]) { export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
let found = comments?.find(c => c.comment.id == data.comment.id); const found = comments?.find(c => c.comment.id == data.comment.id);
if (found) { if (found) {
found.saved = data.saved; found.saved = data.saved;
} }
@ -941,7 +944,7 @@ export function updatePersonBlock(
data: BlockPersonResponse, data: BlockPersonResponse,
myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
) { ) {
let mui = myUserInfo; const mui = myUserInfo;
if (mui) { if (mui) {
if (data.blocked) { if (data.blocked) {
mui.person_blocks.push({ mui.person_blocks.push({
@ -962,7 +965,7 @@ export function updateCommunityBlock(
data: BlockCommunityResponse, data: BlockCommunityResponse,
myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
) { ) {
let mui = myUserInfo; const mui = myUserInfo;
if (mui) { if (mui) {
if (data.blocked) { if (data.blocked) {
mui.community_blocks.push({ mui.community_blocks.push({
@ -983,7 +986,7 @@ export function createCommentLikeRes(
data: CommentView, data: CommentView,
comments?: CommentView[] comments?: CommentView[]
) { ) {
let found = comments?.find(c => c.comment.id === data.comment.id); const found = comments?.find(c => c.comment.id === data.comment.id);
if (found) { if (found) {
found.counts.score = data.counts.score; found.counts.score = data.counts.score;
found.counts.upvotes = data.counts.upvotes; found.counts.upvotes = data.counts.upvotes;
@ -995,7 +998,7 @@ export function createCommentLikeRes(
} }
export function createPostLikeFindRes(data: PostView, posts?: PostView[]) { export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
let found = posts?.find(p => p.post.id == data.post.id); const found = posts?.find(p => p.post.id == data.post.id);
if (found) { if (found) {
createPostLikeRes(data, found); createPostLikeRes(data, found);
} }
@ -1013,7 +1016,7 @@ export function createPostLikeRes(data: PostView, post_view?: PostView) {
} }
export function editPostFindRes(data: PostView, posts?: PostView[]) { export function editPostFindRes(data: PostView, posts?: PostView[]) {
let found = posts?.find(p => p.post.id == data.post.id); const found = posts?.find(p => p.post.id == data.post.id);
if (found) { if (found) {
editPostRes(data, found); editPostRes(data, found);
} }
@ -1039,7 +1042,7 @@ export function updatePostReportRes(
data: PostReportView, data: PostReportView,
reports?: PostReportView[] reports?: PostReportView[]
) { ) {
let found = reports?.find(p => p.post_report.id == data.post_report.id); const found = reports?.find(p => p.post_report.id == data.post_report.id);
if (found) { if (found) {
found.post_report = data.post_report; found.post_report = data.post_report;
} }
@ -1049,7 +1052,9 @@ export function updateCommentReportRes(
data: CommentReportView, data: CommentReportView,
reports?: CommentReportView[] reports?: CommentReportView[]
) { ) {
let found = reports?.find(c => c.comment_report.id == data.comment_report.id); const found = reports?.find(
c => c.comment_report.id == data.comment_report.id
);
if (found) { if (found) {
found.comment_report = data.comment_report; found.comment_report = data.comment_report;
} }
@ -1059,7 +1064,7 @@ export function updatePrivateMessageReportRes(
data: PrivateMessageReportView, data: PrivateMessageReportView,
reports?: PrivateMessageReportView[] reports?: PrivateMessageReportView[]
) { ) {
let found = reports?.find( const found = reports?.find(
c => c.private_message_report.id == data.private_message_report.id c => c.private_message_report.id == data.private_message_report.id
); );
if (found) { if (found) {
@ -1071,7 +1076,7 @@ export function updateRegistrationApplicationRes(
data: RegistrationApplicationView, data: RegistrationApplicationView,
applications?: RegistrationApplicationView[] applications?: RegistrationApplicationView[]
) { ) {
let found = applications?.find( const found = applications?.find(
ra => ra.registration_application.id == data.registration_application.id ra => ra.registration_application.id == data.registration_application.id
); );
if (found) { if (found) {
@ -1082,8 +1087,8 @@ export function updateRegistrationApplicationRes(
} }
export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] { export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
let nodes: CommentNodeI[] = []; const nodes: CommentNodeI[] = [];
for (let comment of comments) { for (const comment of comments) {
nodes.push({ comment_view: comment, children: [], depth: 0 }); nodes.push({ comment_view: comment, children: [], depth: 0 });
} }
return nodes; return nodes;
@ -1111,15 +1116,15 @@ export function buildCommentsTree(
comments: CommentView[], comments: CommentView[],
parentComment: boolean parentComment: boolean
): CommentNodeI[] { ): CommentNodeI[] {
let map = new Map<number, CommentNodeI>(); const map = new Map<number, CommentNodeI>();
let depthOffset = !parentComment const depthOffset = !parentComment
? 0 ? 0
: getDepthFromComment(comments[0].comment) ?? 0; : getDepthFromComment(comments[0].comment) ?? 0;
for (let comment_view of comments) { for (const comment_view of comments) {
let depthI = getDepthFromComment(comment_view.comment) ?? 0; const depthI = getDepthFromComment(comment_view.comment) ?? 0;
let depth = depthI ? depthI - depthOffset : 0; const depth = depthI ? depthI - depthOffset : 0;
let node: CommentNodeI = { const node: CommentNodeI = {
comment_view, comment_view,
children: [], children: [],
depth, depth,
@ -1127,22 +1132,22 @@ export function buildCommentsTree(
map.set(comment_view.comment.id, { ...node }); map.set(comment_view.comment.id, { ...node });
} }
let tree: CommentNodeI[] = []; const tree: CommentNodeI[] = [];
// if its a parent comment fetch, then push the first comment to the top node. // if its a parent comment fetch, then push the first comment to the top node.
if (parentComment) { if (parentComment) {
let cNode = map.get(comments[0].comment.id); const cNode = map.get(comments[0].comment.id);
if (cNode) { if (cNode) {
tree.push(cNode); tree.push(cNode);
} }
} }
for (let comment_view of comments) { for (const comment_view of comments) {
let child = map.get(comment_view.comment.id); const child = map.get(comment_view.comment.id);
if (child) { if (child) {
let parent_id = getCommentParentId(comment_view.comment); const parent_id = getCommentParentId(comment_view.comment);
if (parent_id) { if (parent_id) {
let parent = map.get(parent_id); const parent = map.get(parent_id);
// Necessary because blocked comment might not exist // Necessary because blocked comment might not exist
if (parent) { if (parent) {
parent.children.push(child); parent.children.push(child);
@ -1159,7 +1164,7 @@ export function buildCommentsTree(
} }
export function getCommentParentId(comment?: CommentI): number | undefined { export function getCommentParentId(comment?: CommentI): number | undefined {
let split = comment?.path.split("."); const split = comment?.path.split(".");
// remove the 0 // remove the 0
split?.shift(); split?.shift();
@ -1169,7 +1174,7 @@ export function getCommentParentId(comment?: CommentI): number | undefined {
} }
export function getDepthFromComment(comment?: CommentI): number | undefined { export function getDepthFromComment(comment?: CommentI): number | undefined {
let len = comment?.path.split(".").length; const len = comment?.path.split(".").length;
return len ? len - 2 : undefined; return len ? len - 2 : undefined;
} }
@ -1179,15 +1184,15 @@ export function insertCommentIntoTree(
parentComment: boolean parentComment: boolean
) { ) {
// Building a fake node to be used for later // Building a fake node to be used for later
let node: CommentNodeI = { const node: CommentNodeI = {
comment_view: cv, comment_view: cv,
children: [], children: [],
depth: 0, depth: 0,
}; };
let parentId = getCommentParentId(cv.comment); const parentId = getCommentParentId(cv.comment);
if (parentId) { if (parentId) {
let parent_comment = searchCommentTree(tree, parentId); const parent_comment = searchCommentTree(tree, parentId);
if (parent_comment) { if (parent_comment) {
node.depth = parent_comment.depth + 1; node.depth = parent_comment.depth + 1;
parent_comment.children.unshift(node); parent_comment.children.unshift(node);
@ -1201,13 +1206,13 @@ export function searchCommentTree(
tree: CommentNodeI[], tree: CommentNodeI[],
id: number id: number
): CommentNodeI | undefined { ): CommentNodeI | undefined {
for (let node of tree) { for (const node of tree) {
if (node.comment_view.comment.id === id) { if (node.comment_view.comment.id === id) {
return node; return node;
} }
for (const child of node.children) { for (const child of node.children) {
let res = searchCommentTree([child], id); const res = searchCommentTree([child], id);
if (res) { if (res) {
return res; return res;
@ -1232,7 +1237,7 @@ function hsl(num: number) {
} }
export function hostname(url: string): string { export function hostname(url: string): string {
let cUrl = new URL(url); const cUrl = new URL(url);
return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`; return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
} }
@ -1305,14 +1310,14 @@ moment.updateLocale("en", {
}); });
export function saveScrollPosition(context: any) { export function saveScrollPosition(context: any) {
let path: string = context.router.route.location.pathname; const path: string = context.router.route.location.pathname;
let y = window.scrollY; const y = window.scrollY;
sessionStorage.setItem(`scrollPosition_${path}`, y.toString()); sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
} }
export function restoreScrollPosition(context: any) { export function restoreScrollPosition(context: any) {
let path: string = context.router.route.location.pathname; const path: string = context.router.route.location.pathname;
let y = Number(sessionStorage.getItem(`scrollPosition_${path}`)); const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
window.scrollTo(0, y); window.scrollTo(0, y);
} }
@ -1347,7 +1352,7 @@ export function personToChoice(pvs: PersonView): Choice {
} }
export async function fetchCommunities(q: string) { export async function fetchCommunities(q: string) {
let form: Search = { const form: Search = {
q, q,
type_: "Communities", type_: "Communities",
sort: "TopAll", sort: "TopAll",
@ -1356,12 +1361,12 @@ export async function fetchCommunities(q: string) {
limit: fetchLimit, limit: fetchLimit,
auth: myAuth(false), auth: myAuth(false),
}; };
let client = new LemmyHttp(getHttpBase()); const client = new LemmyHttp(getHttpBase());
return client.search(form); return client.search(form);
} }
export async function fetchUsers(q: string) { export async function fetchUsers(q: string) {
let form: Search = { const form: Search = {
q, q,
type_: "Users", type_: "Users",
sort: "TopAll", sort: "TopAll",
@ -1370,7 +1375,7 @@ export async function fetchUsers(q: string) {
limit: fetchLimit, limit: fetchLimit,
auth: myAuth(false), auth: myAuth(false),
}; };
let client = new LemmyHttp(getHttpBase()); const client = new LemmyHttp(getHttpBase());
return client.search(form); return client.search(form);
} }
@ -1408,7 +1413,7 @@ export function numToSI(value: number): string {
} }
export function isBanned(ps: Person): boolean { export function isBanned(ps: Person): boolean {
let expires = ps.ban_expires; const expires = ps.ban_expires;
// Add Z to convert from UTC date // Add Z to convert from UTC date
// TODO this check probably isn't necessary anymore // TODO this check probably isn't necessary anymore
if (expires) { if (expires) {
@ -1478,8 +1483,8 @@ export function nsfwCheck(
pv: PostView, pv: PostView,
myUserInfo = UserService.Instance.myUserInfo myUserInfo = UserService.Instance.myUserInfo
): boolean { ): boolean {
let nsfw = pv.post.nsfw || pv.community.nsfw; const nsfw = pv.post.nsfw || pv.community.nsfw;
let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false; const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
return !nsfw || (nsfw && myShowNsfw); return !nsfw || (nsfw && myShowNsfw);
} }
@ -1503,10 +1508,10 @@ export function selectableLanguages(
showSite?: boolean, showSite?: boolean,
myUserInfo = UserService.Instance.myUserInfo myUserInfo = UserService.Instance.myUserInfo
): Language[] { ): Language[] {
let allLangIds = allLanguages.map(l => l.id); const allLangIds = allLanguages.map(l => l.id);
let myLangs = myUserInfo?.discussion_languages ?? allLangIds; let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
myLangs = myLangs.length == 0 ? allLangIds : myLangs; myLangs = myLangs.length == 0 ? allLangIds : myLangs;
let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages; const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
if (showAll) { if (showAll) {
return allLanguages; return allLanguages;