Skip to content

Commit

Permalink
post messages from iframe
Browse files Browse the repository at this point in the history
- fix user info opening
- remove iframe height checks by interval
- update height by mutation observer events
- rename events
  • Loading branch information
Pavel Mineev committed May 19, 2021
1 parent 6f10a5a commit c0ac2c9
Show file tree
Hide file tree
Showing 13 changed files with 137 additions and 163 deletions.
9 changes: 0 additions & 9 deletions frontend/app/common/user-info-settings.ts

This file was deleted.

6 changes: 3 additions & 3 deletions frontend/app/components/auth-panel/auth-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import b from 'bem-react-helper';
import { User, Sorting, Theme, PostInfo } from 'common/types';
import { IS_STORAGE_AVAILABLE, IS_THIRD_PARTY } from 'common/constants';
import { requestDeletion } from 'utils/email';
import { postMessage } from 'utils/postMessage';
import { postMessageToParent } from 'utils/postMessage';
import { getHandleClickProps } from 'common/accessibility';
import { StoreState } from 'store';
import { Dropdown, DropdownItem } from 'components/dropdown';
Expand Down Expand Up @@ -75,11 +75,11 @@ class AuthPanelComponent extends Component<Props, State> {
toggleUserInfoVisibility = () => {
const { user } = this.props;

if (user === null) {
if (!user) {
return;
}

postMessage({ isUserInfoShown: true, user });
postMessageToParent({ showUser: true, user });
};

renderAuthorized = (user: User) => {
Expand Down
35 changes: 14 additions & 21 deletions frontend/app/components/auth/auth.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import { parseMessage, postMessageToParent } from 'utils/postMessage';

function handleChangeIframeSize(element: HTMLElement) {
const { top } = element.getBoundingClientRect();
const height = window.scrollY + Math.abs(top) + element.scrollHeight + 20;
const height = Math.max(window.scrollY + Math.abs(top) + element.scrollHeight + 20, document.body.offsetHeight);

if (window.innerHeight > height) {
return;
}

document.body.style.setProperty('min-height', `${height}px`);
postMessageToParent({ height });
}

export function useDropdown(disableClosing?: boolean) {
Expand All @@ -19,28 +16,20 @@ export function useDropdown(disableClosing?: boolean) {
};

useEffect(() => {
if (!showDropdown) {
return;
}

const dropdownElement = rootRef.current;

handleChangeIframeSize(dropdownElement);
if (!showDropdown || !dropdownElement) {
return;
}

function handleMessageFromParent(evt: MessageEvent) {
if (typeof evt.data !== 'string' || disableClosing) {
const data = parseMessage(evt);

if (disableClosing && data.clickOutside) {
return;
}

try {
const data = JSON.parse(evt.data);

if (!data.clickOutside) {
return;
}

setShowDropdown(false);
} catch (e) {}
setShowDropdown(false);
}

function handleClickOutside(evt: MouseEvent) {
Expand All @@ -64,9 +53,13 @@ export function useDropdown(disableClosing?: boolean) {
const dropdownElement = rootRef.current;

if (!dropdownElement || !showDropdown) {
handleChangeIframeSize(document.body);

return;
}

handleChangeIframeSize(dropdownElement);

const observer = new MutationObserver(() => {
handleChangeIframeSize(dropdownElement);
});
Expand Down
35 changes: 15 additions & 20 deletions frontend/app/components/comment/comment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Avatar } from 'components/avatar';
import { Button } from 'components/button';
import { Countdown } from 'components/countdown';
import { getPreview, uploadImage } from 'common/api';
import { postMessage } from 'utils/postMessage';
import { postMessageToParent } from 'utils/postMessage';
import { FormattedMessage, useIntl, IntlShape, defineMessages } from 'react-intl';
import { getVoteMessage, VoteMessagesTypes } from './getVoteMessage';
import { getBlockingDurations } from './getBlockingDurations';
Expand Down Expand Up @@ -207,14 +207,7 @@ export class Comment extends Component<CommentProps, State> {
};

toggleUserInfoVisibility = () => {
if (!window.parent) {
return;
}

const { user } = this.props.data;
const data = JSON.stringify({ isUserInfoShown: true, user });

window.parent.postMessage(data, '*');
postMessageToParent({ showUser: true, user: this.props.data.user });
};

togglePin = () => {
Expand Down Expand Up @@ -353,21 +346,23 @@ export class Comment extends Component<CommentProps, State> {
this.props.setReplyEditState!({ id: this.props.data.id, state: CommentMode.None });
};

scrollToParent = (e: Event) => {
const {
data: { pid },
} = this.props;
scrollToParent = (evt: Event) => {
const { pid } = this.props.data;
const parentCommentNode = document.getElementById(`${COMMENT_NODE_CLASSNAME_PREFIX}${pid}`);

e.preventDefault();
evt.preventDefault();

const parentCommentNode = document.getElementById(`${COMMENT_NODE_CLASSNAME_PREFIX}${pid}`);
if (!parentCommentNode) {
return;
}

if (parentCommentNode) {
const top = parentCommentNode.getBoundingClientRect().top;
if (!postMessage({ scrollTo: top })) {
parentCommentNode.scrollIntoView();
}
const top = parentCommentNode.getBoundingClientRect().top;

if (postMessageToParent({ scrollTo: top })) {
return;
}

parentCommentNode.scrollIntoView();
};

copyComment = () => {
Expand Down
34 changes: 15 additions & 19 deletions frontend/app/components/dropdown/dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,25 +134,23 @@ export class Dropdown extends Component<Props, State> {
});
}

receiveMessage(event: MessageEvent<{ clickOutside?: boolean }>) {
try {
const data = parseMessage(event);
receiveMessage(evt: MessageEvent) {
const data = parseMessage(evt);

if (!data || !data.clickOutside || !this.state.isActive) {
return;
}
if (!data.clickOutside || !this.state.isActive) {
return;
}

this.setState(
{
contentTranslateX: 0,
isActive: false,
},
() => {
this.__onClose();
this.props.onClose && this.props.onClose(this.rootNode.current!);
}
);
} catch (e) {}
this.setState(
{
contentTranslateX: 0,
isActive: false,
},
() => {
this.__onClose();
this.props.onClose?.(this.rootNode.current!);
}
);
}

onOutsideClick(e: MouseEvent) {
Expand All @@ -171,13 +169,11 @@ export class Dropdown extends Component<Props, State> {

componentDidMount() {
document.addEventListener('click', this.onOutsideClick);

window.addEventListener('message', this.receiveMessage);
}

componentWillUnmount() {
document.removeEventListener('click', this.onOutsideClick);

window.removeEventListener('message', this.receiveMessage);
}

Expand Down
20 changes: 10 additions & 10 deletions frontend/app/components/root/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import { ConnectedComment as Comment } from 'components/comment/connected-commen
import { uploadImage, getPreview } from 'common/api';
import { isUserAnonymous } from 'utils/isUserAnonymous';
import { bindActions } from 'utils/actionBinder';
import { postMessage, parseMessage } from 'utils/postMessage';
import { postMessageToParent, parseMessage } from 'utils/postMessage';
import { useActions } from 'hooks/useAction';
import { setCollapse } from 'store/thread/actions';
import { logout } from 'components/auth/auth.api';
Expand Down Expand Up @@ -122,7 +122,7 @@ export class Root extends Component<Props, State> {
const userloading = this.props.fetchUser().finally(() => this.setState({ isUserLoading: false }));

Promise.all([userloading, this.props.fetchComments()]).finally(() => {
postMessage({ remarkIframeHeight: document.body.offsetHeight });
postMessageToParent({ height: document.body.offsetHeight });
setTimeout(this.checkUrlHash);
window.addEventListener('hashchange', this.checkUrlHash);
});
Expand Down Expand Up @@ -169,22 +169,22 @@ export class Root extends Component<Props, State> {
toMessage = (hash: string) => {
const comment = document.querySelector(hash);
if (comment) {
postMessage({ scrollTo: comment.getBoundingClientRect().top });
postMessageToParent({ scrollTo: comment.getBoundingClientRect().top });
comment.classList.add('comment_highlighting');
setTimeout(() => {
comment.classList.remove('comment_highlighting');
}, 5e3);
}
};

onMessage(event: MessageEvent<{ theme?: Theme }>) {
try {
const data = parseMessage(event);
onMessage(event: MessageEvent) {
const data = parseMessage(event);

if (data.theme && THEMES.includes(data.theme)) {
this.props.setTheme(data.theme);
}
} catch (e) {}
if (!data.theme || !THEMES.includes(data.theme)) {
return;
}

this.props.setTheme(data.theme);
}

onBlockedUsersShow = async () => {
Expand Down
13 changes: 7 additions & 6 deletions frontend/app/components/user-info/user-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { useIntl, defineMessages, FormattedMessage, IntlShape } from 'react-intl
import { StoreState } from 'store';
import { Comment } from 'common/types';
import { fetchInfo } from 'store/user-info/actions';
import { userInfo } from 'common/user-info-settings';
import { postMessage } from 'utils/postMessage';
import { parseQuery } from 'utils/parseQuery';
import { bindActions } from 'utils/actionBinder';
import { postMessageToParent } from 'utils/postMessage';
import { useActions } from 'hooks/useAction';
import { Avatar } from 'components/avatar';

Expand All @@ -23,6 +23,8 @@ const messages = defineMessages({
},
});

const user = parseQuery();

type Props = {
comments: Comment[] | null;
} & typeof boundActions & { intl: IntlShape };
Expand All @@ -38,7 +40,7 @@ class UserInfo extends Component<Props, State> {
componentWillMount(): void {
if (!this.props.comments && this.state.isLoading) {
this.props
.fetchInfo()
.fetchInfo(user.id)
.then(() => {
this.setState({ isLoading: false });
})
Expand All @@ -55,7 +57,6 @@ class UserInfo extends Component<Props, State> {
}

render(): JSX.Element | null {
const user = userInfo;
const { comments = [] } = this.props;
const { isLoading } = this.state;

Expand Down Expand Up @@ -87,12 +88,12 @@ class UserInfo extends Component<Props, State> {
static onKeyDown(e: KeyboardEvent): void {
// ESCAPE key pressed
if (e.keyCode === 27) {
postMessage({ isUserInfoShown: false });
postMessageToParent({ showUser: false });
}
}
}

const commentsSelector = (state: StoreState) => state.userComments[userInfo.id];
const commentsSelector = (state: StoreState) => state.userComments[user.id];

export const ConnectedUserInfo: FunctionComponent = () => {
const comments = useSelector(commentsSelector);
Expand Down
Loading

0 comments on commit c0ac2c9

Please sign in to comment.