Various commenting improvements (#4938)

* fix: New threads attached to previous as replies

* fix: Cannot use floating toolbar properly in comments

* perf: Avoid re-writing history on click in editor

* fix: Comment on text selection

* fix: 'Copy link' on comments uses wrong hostname

* Show comment buttons on input focus rather than non-empty input
Increase maximum sidebar size

* Allow opening comments from document menu

* fix: Clicking comment menu should not focus thread
This commit is contained in:
Tom Moor
2023-02-26 14:19:12 -05:00
committed by GitHub
parent b813f20f8f
commit 08df14618c
16 changed files with 219 additions and 141 deletions

View File

@@ -22,9 +22,10 @@ import {
LightBulbIcon,
UnpublishIcon,
PublishIcon,
CommentIcon,
} from "outline-icons";
import * as React from "react";
import { ExportContentType } from "@shared/types";
import { ExportContentType, TeamPreference } from "@shared/types";
import { getEventFiles } from "@shared/utils/files";
import DocumentDelete from "~/scenes/DocumentDelete";
import DocumentMove from "~/scenes/DocumentMove";
@@ -466,7 +467,7 @@ export const printDocument = createAction({
icon: <PrintIcon />,
visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print),
perform: async () => {
window.print();
queueMicrotask(window.print);
},
});
@@ -708,6 +709,29 @@ export const permanentlyDeleteDocument = createAction({
},
});
export const openDocumentComments = createAction({
name: ({ t }) => t("Comments"),
analyticsName: "Open comments",
section: DocumentSection,
icon: <CommentIcon />,
visible: ({ activeDocumentId, stores }) => {
const can = stores.policies.abilities(activeDocumentId ?? "");
return (
!!activeDocumentId &&
can.read &&
!can.restore &&
!!stores.auth.team?.getPreference(TeamPreference.Commenting)
);
},
perform: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return;
}
stores.ui.toggleComments();
},
});
export const openDocumentHistory = createAction({
name: ({ t }) => t("History"),
analyticsName: "Open document history",
@@ -771,6 +795,7 @@ export const rootDocumentActions = [
printDocument,
pinDocumentToCollection,
pinDocumentToHome,
openDocumentComments,
openDocumentHistory,
openDocumentInsights,
];

View File

@@ -21,7 +21,6 @@ import HoverPreview from "~/components/HoverPreview";
import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
import useDictionary from "~/hooks/useDictionary";
import useEmbeds from "~/hooks/useEmbeds";
import useFocusedComment from "~/hooks/useFocusedComment";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import { NotFoundError } from "~/utils/errors";
@@ -61,7 +60,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
onDeleteCommentMark,
} = props;
const { auth, comments, documents } = useStores();
const focusedComment = useFocusedComment();
const { showToast } = useToasts();
const dictionary = useDictionary();
const embeds = useEmbeds(!shareId);
@@ -343,7 +341,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
onChange={handleChange}
placeholder={props.placeholder || ""}
defaultValue={props.defaultValue || ""}
focusedCommentId={focusedComment?.id}
/>
{props.bottomPadding && !props.readOnly && (
<ClickablePadding

18
app/components/Portal.tsx Normal file
View File

@@ -0,0 +1,18 @@
import * as React from "react";
import { Portal as ReactPortal } from "react-portal";
/**
* A React context that provides a dom node for portals to be rendered into.
*/
export const PortalContext = React.createContext<
HTMLElement | null | undefined
>(undefined);
/**
* A portal component that uses context to render into a different dom node
* or the root of body if no context is available.
*/
export function Portal(props: { children: React.ReactNode }) {
const node = React.useContext(PortalContext);
return <ReactPortal node={node}>{props.children}</ReactPortal>;
}

View File

@@ -3,7 +3,6 @@ import { findDomRefAtPos, findParentNode } from "prosemirror-utils";
import { EditorView } from "prosemirror-view";
import * as React from "react";
import { Trans } from "react-i18next";
import { Portal } from "react-portal";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import styled from "styled-components";
import insertFiles from "@shared/editor/commands/insertFiles";
@@ -14,6 +13,7 @@ import { MenuItem } from "@shared/editor/types";
import { depths } from "@shared/styles";
import { getEventFiles } from "@shared/utils/files";
import { AttachmentValidation } from "@shared/validations";
import { Portal } from "~/components/Portal";
import Scrollable from "~/components/Scrollable";
import { Dictionary } from "~/hooks/useDictionary";
import Input from "./Input";
@@ -406,7 +406,16 @@ class CommandMenu<T extends MenuItem> extends React.Component<Props<T>, State> {
const { top, bottom, right } = paragraph.node.getBoundingClientRect();
const margin = 24;
let leftPos = left + window.scrollX;
const offsetParent = ref?.offsetParent
? ref.offsetParent.getBoundingClientRect()
: ({
width: 0,
height: 0,
top: 0,
left: 0,
} as DOMRect);
let leftPos = left - offsetParent.left;
if (props.rtl && ref) {
leftPos = right - ref.scrollWidth;
}
@@ -414,14 +423,14 @@ class CommandMenu<T extends MenuItem> extends React.Component<Props<T>, State> {
if (startPos.top - offsetHeight > margin) {
return {
left: leftPos,
top: undefined,
bottom: window.innerHeight - top - window.scrollY,
top: top - offsetParent.top - offsetHeight,
bottom: undefined,
isAbove: false,
};
} else {
return {
left: leftPos,
top: bottom + window.scrollY,
top: bottom - offsetParent.top,
bottom: undefined,
isAbove: true,
};

View File

@@ -1,9 +1,9 @@
import { NodeSelection } from "prosemirror-state";
import { CellSelection } from "prosemirror-tables";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
import { depths } from "@shared/styles";
import { Portal } from "~/components/Portal";
import useComponentSize from "~/hooks/useComponentSize";
import useEventListener from "~/hooks/useEventListener";
import useMediaQuery from "~/hooks/useMediaQuery";
@@ -80,6 +80,15 @@ function usePosition({
right: Math.max(fromPos.right, toPos.right),
};
const offsetParent = menuRef.current.offsetParent
? menuRef.current.offsetParent.getBoundingClientRect()
: ({
width: 0,
height: 0,
top: 0,
left: 0,
} as DOMRect);
// tables are an oddity, and need their own positioning logic
const isColSelection =
selection instanceof CellSelection &&
@@ -116,8 +125,8 @@ function usePosition({
const { left, top, width } = imageElement.getBoundingClientRect();
return {
left: Math.round(left + width / 2 + window.scrollX - menuWidth / 2),
top: Math.round(top + window.scrollY - menuHeight),
left: Math.round(left + width / 2 - menuWidth / 2 - offsetParent.left),
top: Math.round(top - menuHeight - offsetParent.top),
offset: 0,
visible: true,
};
@@ -145,8 +154,8 @@ function usePosition({
// of the selection still
const offset = left - (centerOfSelection - menuWidth / 2);
return {
left: Math.round(left + window.scrollX),
top: Math.round(top + window.scrollY),
left: Math.round(left - offsetParent.left),
top: Math.round(top - offsetParent.top),
offset: Math.round(offset),
visible: true,
};

View File

@@ -2,7 +2,9 @@ import styled from "styled-components";
type Props = { active?: boolean; disabled?: boolean };
export default styled.button<Props>`
export default styled.button.attrs((props) => ({
type: props.type || "button",
}))<Props>`
display: inline-block;
flex: 0;
width: 24px;

View File

@@ -32,6 +32,7 @@ import { UserPreferences } from "@shared/types";
import ProsemirrorHelper from "@shared/utils/ProsemirrorHelper";
import EventEmitter from "@shared/utils/events";
import Flex from "~/components/Flex";
import { PortalContext } from "~/components/Portal";
import { Dictionary } from "~/hooks/useDictionary";
import Logger from "~/utils/Logger";
import BlockMenu from "./components/BlockMenu";
@@ -178,7 +179,8 @@ export class Editor extends React.PureComponent<
isBlurred: boolean;
extensions: ExtensionManager;
element = React.createRef<HTMLDivElement>();
elementRef = React.createRef<HTMLDivElement>();
wrapperRef = React.createRef<HTMLDivElement>();
view: EditorView;
schema: Schema;
serializer: MarkdownSerializer;
@@ -435,7 +437,7 @@ export class Editor extends React.PureComponent<
}
private createView() {
if (!this.element.current) {
if (!this.elementRef.current) {
throw new Error("createView called before ref available");
}
@@ -448,7 +450,7 @@ export class Editor extends React.PureComponent<
};
const self = this; // eslint-disable-line
const view = new EditorView(this.element.current, {
const view = new EditorView(this.elementRef.current, {
handleDOMEvents: {
blur: this.handleEditorBlur,
focus: this.handleEditorFocus,
@@ -521,13 +523,13 @@ export class Editor extends React.PureComponent<
};
private calculateDir = () => {
if (!this.element.current) {
if (!this.elementRef.current) {
return;
}
const isRTL =
this.props.dir === "rtl" ||
getComputedStyle(this.element.current).direction === "rtl";
getComputedStyle(this.elementRef.current).direction === "rtl";
if (this.state.isRTL !== isRTL) {
this.setState({ isRTL });
@@ -718,75 +720,78 @@ export class Editor extends React.PureComponent<
const { isRTL } = this.state;
return (
<EditorContext.Provider value={this}>
<Flex
onKeyDown={onKeyDown}
style={style}
className={className}
align="flex-start"
justify="center"
column
>
<EditorContainer
dir={dir}
rtl={isRTL}
grow={grow}
readOnly={readOnly}
readOnlyWriteCheckboxes={readOnlyWriteCheckboxes}
focusedCommentId={this.props.focusedCommentId}
ref={this.element}
/>
{!readOnly && this.view && (
<>
<SelectionToolbar
view={this.view}
dictionary={dictionary}
commands={this.commands}
rtl={isRTL}
isTemplate={this.props.template === true}
onOpen={this.handleOpenSelectionMenu}
onClose={this.handleCloseSelectionMenu}
onSearchLink={this.props.onSearchLink}
onClickLink={this.props.onClickLink}
onCreateLink={this.props.onCreateLink}
onShowToast={this.props.onShowToast}
/>
<LinkToolbar
isActive={this.state.linkMenuOpen}
onCreateLink={this.props.onCreateLink}
onSearchLink={this.props.onSearchLink}
onClickLink={this.props.onClickLink}
onClose={this.handleCloseLinkMenu}
/>
<EmojiMenu
view={this.view}
commands={this.commands}
dictionary={dictionary}
rtl={isRTL}
onShowToast={this.props.onShowToast}
isActive={this.state.emojiMenuOpen}
search={this.state.blockMenuSearch}
onClose={this.handleCloseEmojiMenu}
/>
<BlockMenu
view={this.view}
commands={this.commands}
dictionary={dictionary}
rtl={isRTL}
isActive={this.state.blockMenuOpen}
search={this.state.blockMenuSearch}
onClose={this.handleCloseBlockMenu}
uploadFile={this.props.uploadFile}
onLinkToolbarOpen={this.handleOpenLinkMenu}
onFileUploadStart={this.props.onFileUploadStart}
onFileUploadStop={this.props.onFileUploadStop}
onShowToast={this.props.onShowToast}
embeds={this.props.embeds}
/>
</>
)}
</Flex>
</EditorContext.Provider>
<PortalContext.Provider value={this.wrapperRef.current}>
<EditorContext.Provider value={this}>
<Flex
ref={this.wrapperRef}
onKeyDown={onKeyDown}
style={style}
className={className}
align="flex-start"
justify="center"
column
>
<EditorContainer
dir={dir}
rtl={isRTL}
grow={grow}
readOnly={readOnly}
readOnlyWriteCheckboxes={readOnlyWriteCheckboxes}
focusedCommentId={this.props.focusedCommentId}
ref={this.elementRef}
/>
{!readOnly && this.view && (
<>
<SelectionToolbar
view={this.view}
dictionary={dictionary}
commands={this.commands}
rtl={isRTL}
isTemplate={this.props.template === true}
onOpen={this.handleOpenSelectionMenu}
onClose={this.handleCloseSelectionMenu}
onSearchLink={this.props.onSearchLink}
onClickLink={this.props.onClickLink}
onCreateLink={this.props.onCreateLink}
onShowToast={this.props.onShowToast}
/>
<LinkToolbar
isActive={this.state.linkMenuOpen}
onCreateLink={this.props.onCreateLink}
onSearchLink={this.props.onSearchLink}
onClickLink={this.props.onClickLink}
onClose={this.handleCloseLinkMenu}
/>
<EmojiMenu
view={this.view}
commands={this.commands}
dictionary={dictionary}
rtl={isRTL}
onShowToast={this.props.onShowToast}
isActive={this.state.emojiMenuOpen}
search={this.state.blockMenuSearch}
onClose={this.handleCloseEmojiMenu}
/>
<BlockMenu
view={this.view}
commands={this.commands}
dictionary={dictionary}
rtl={isRTL}
isActive={this.state.blockMenuOpen}
search={this.state.blockMenuSearch}
onClose={this.handleCloseBlockMenu}
uploadFile={this.props.uploadFile}
onLinkToolbarOpen={this.handleOpenLinkMenu}
onFileUploadStart={this.props.onFileUploadStart}
onFileUploadStop={this.props.onFileUploadStop}
onShowToast={this.props.onShowToast}
embeds={this.props.embeds}
/>
</>
)}
</Flex>
</EditorContext.Provider>
</PortalContext.Provider>
);
}
}

View File

@@ -9,6 +9,7 @@ import ContextMenu from "~/components/ContextMenu";
import MenuItem from "~/components/ContextMenu/MenuItem";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Separator from "~/components/ContextMenu/Separator";
import EventBoundary from "~/components/EventBoundary";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
@@ -52,11 +53,14 @@ function CommentMenu({ comment, onEdit, onDelete, className }: Props) {
return (
<>
<OverflowMenuButton
aria-label={t("Show menu")}
className={className}
{...menu}
/>
<EventBoundary>
<OverflowMenuButton
aria-label={t("Show menu")}
className={className}
{...menu}
/>
</EventBoundary>
<ContextMenu {...menu} aria-label={t("Comment options")}>
{can.update && (
<MenuItem {...menu} onClick={onEdit}>

View File

@@ -1,10 +1,5 @@
import { observer } from "mobx-react";
import {
EditIcon,
PrintIcon,
NewDocumentIcon,
RestoreIcon,
} from "outline-icons";
import { EditIcon, NewDocumentIcon, RestoreIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
@@ -40,6 +35,8 @@ import {
openDocumentInsights,
publishDocument,
unpublishDocument,
printDocument,
openDocumentComments,
} from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
@@ -125,11 +122,6 @@ function DocumentMenu({
[showToast, t, document]
);
const handlePrint = React.useCallback(() => {
menu.hide();
window.print();
}, [menu]);
const collection = collections.get(document.collectionId);
const can = usePolicy(document);
const restoreItems = React.useMemo(
@@ -291,16 +283,11 @@ function DocumentMenu({
{
type: "separator",
},
actionToMenuItem(downloadDocument, context),
actionToMenuItem(openDocumentComments, context),
actionToMenuItem(openDocumentHistory, context),
actionToMenuItem(openDocumentInsights, context),
{
type: "button",
title: t("Print"),
onClick: handlePrint,
visible: !!showDisplayOptions,
icon: <PrintIcon />,
},
actionToMenuItem(downloadDocument, context),
actionToMenuItem(printDocument, context),
{
type: "separator",
},

View File

@@ -22,7 +22,7 @@ type Props = {
/** The document that the comment will be associated with */
documentId: string;
/** The comment thread that the comment will be associated with */
thread: Comment;
thread?: Comment;
/** Placeholder text to display in the editor */
placeholder?: string;
/** Whether to focus the editor on mount */
@@ -59,20 +59,22 @@ function CommentForm({
}: Props) {
const { editor } = useDocumentContext();
const [data, setData] = usePersistedState<Record<string, any> | undefined>(
`draft-${documentId}-${thread.id}`,
`draft-${documentId}-${thread?.id ?? "new"}`,
undefined
);
const formRef = React.useRef<HTMLFormElement>(null);
const editorRef = React.useRef<SharedEditor>(null);
const [forceRender, setForceRender] = React.useState(0);
const [inputFocused, setInputFocused] = React.useState(false);
const { t } = useTranslation();
const { showToast } = useToasts();
const { comments } = useStores();
const user = useCurrentUser();
const isEmpty = editorRef.current?.isEmpty() ?? true;
useOnClickOutside(formRef, () => {
if (isEmpty && thread.isNew) {
const isEmpty = editorRef.current?.isEmpty() ?? true;
if (isEmpty && thread?.isNew) {
if (thread.id) {
editor?.removeComment(thread.id);
}
@@ -86,19 +88,29 @@ function CommentForm({
setData(undefined);
setForceRender((s) => ++s);
thread
const comment =
thread ??
new Comment(
{
documentId,
data,
},
comments
);
comment
.save({
documentId,
data,
})
.catch(() => {
thread.isNew = true;
comment.isNew = true;
showToast(t("Error creating comment"), { type: "error" });
});
// optimistically update the comment model
thread.isNew = false;
thread.createdBy = user;
comment.isNew = false;
comment.createdBy = user;
});
const handleCreateReply = async (event: React.FormEvent) => {
@@ -145,6 +157,16 @@ function CommentForm({
setForceRender((s) => ++s);
};
const handleFocus = () => {
onFocus?.();
setInputFocused(true);
};
const handleBlur = () => {
onBlur?.();
setInputFocused(false);
};
// Focus the editor when it's a new comment just mounted, after a delay as the
// editor is mounted within a fade transition.
React.useEffect(() => {
@@ -199,21 +221,23 @@ function CommentForm({
ref={editorRef}
onChange={handleChange}
onSave={handleSave}
onFocus={onFocus}
onBlur={onBlur}
onFocus={handleFocus}
onBlur={handleBlur}
maxLength={CommentValidation.maxLength}
placeholder={
placeholder ||
// isNew is only the case for comments that exist in draft state,
// they are marks in the document, but not yet saved to the db.
(thread.isNew ? `${t("Add a comment")}` : `${t("Add a reply")}`)
(thread?.isNew
? `${t("Add a comment")}`
: `${t("Add a reply")}`)
}
/>
{!isEmpty && (
{inputFocused && (
<Flex justify={dir === "rtl" ? "flex-end" : "flex-start"} gap={8}>
<ButtonSmall type="submit" borderOnHover>
{thread.isNew ? t("Post") : t("Reply")}
{thread && !thread.isNew ? t("Reply") : t("Post")}
</ButtonSmall>
<ButtonSmall onClick={handleCancel} neutral borderOnHover>
{t("Cancel")}

View File

@@ -4,7 +4,6 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { useRouteMatch } from "react-router-dom";
import styled from "styled-components";
import Comment from "~/models/Comment";
import Empty from "~/components/Empty";
import Flex from "~/components/Flex";
import useCurrentUser from "~/hooks/useCurrentUser";
@@ -16,7 +15,6 @@ import Sidebar from "./SidebarLayout";
function Comments() {
const { ui, comments, documents } = useStores();
const [newComment] = React.useState(new Comment({}, comments));
const { t } = useTranslation();
const user = useCurrentUser();
const match = useRouteMatch<{ documentSlug: string }>();
@@ -54,9 +52,7 @@ function Comments() {
<AnimatePresence initial={false}>
{!focusedComment && (
<NewCommentForm
key="new-comment-form"
documentId={document.id}
thread={newComment}
placeholder={`${t("Add a comment")}`}
autoFocus={false}
dir={document.dir}

View File

@@ -10,6 +10,7 @@ import Document from "~/models/Document";
import { RefHandle } from "~/components/ContentEditable";
import Editor, { Props as EditorProps } from "~/components/Editor";
import Flex from "~/components/Flex";
import useFocusedComment from "~/hooks/useFocusedComment";
import useStores from "~/hooks/useStores";
import {
documentHistoryUrl,
@@ -43,6 +44,7 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
const titleRef = React.useRef<RefHandle>(null);
const { t } = useTranslation();
const match = useRouteMatch();
const focusedComment = useFocusedComment();
const { ui, comments, auth } = useStores();
const { user, team } = auth;
const history = useHistory();
@@ -91,13 +93,13 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
pathname: window.location.pathname.replace(/\/history$/, ""),
state: { commentId },
});
} else {
} else if (focusedComment) {
history.replace({
pathname: window.location.pathname,
});
}
},
[ui, history]
[ui, focusedComment, history]
);
// Create a Comment model in local store when a comment mark is created, this
@@ -177,6 +179,7 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
readOnly={readOnly}
shareId={shareId}
userId={user?.id}
focusedCommentId={focusedComment?.id}
onClickCommentMark={handleClickComment}
onCreateCommentMark={
team?.getPreference(TeamPreference.Commenting)

View File

@@ -83,7 +83,7 @@ function Insights() {
</Text>
</Content>
<Content column>
<Heading>{t("Collaborators")}</Heading>
<Heading>{t("Contributors")}</Heading>
<Text type="secondary" size="small">
{t(`Created`)} <Time dateTime={document.createdAt} addSuffix />.
<br />
@@ -92,7 +92,7 @@ function Insights() {
</Text>
<ListSpacing>
<PaginatedList
aria-label={t("Collaborators")}
aria-label={t("Contributors")}
items={document.collaborators}
renderItem={(model: User) => (
<ListItem

View File

@@ -2,7 +2,6 @@ import queryString from "query-string";
import Collection from "~/models/Collection";
import Comment from "~/models/Comment";
import Document from "~/models/Document";
import env from "~/env";
export function homePath(): string {
return "/home";
@@ -138,7 +137,7 @@ export function notFoundUrl(): string {
}
export function urlify(path: string): string {
return `${env.URL}${path}`;
return `${window.location.host}${path}`;
}
export const matchDocumentSlug =

View File

@@ -52,6 +52,7 @@
"Delete {{ documentName }}": "Delete {{ documentName }}",
"Permanently delete": "Permanently delete",
"Permanently delete {{ documentName }}": "Permanently delete {{ documentName }}",
"Comments": "Comments",
"History": "History",
"Insights": "Insights",
"Home": "Home",
@@ -436,10 +437,9 @@
"Error creating comment": "Error creating comment",
"Add a comment": "Add a comment",
"Add a reply": "Add a reply",
"Post": "Post",
"Reply": "Reply",
"Post": "Post",
"Cancel": "Cancel",
"Comments": "Comments",
"No comments yet": "No comments yet",
"Error updating comment": "Error updating comment",
"Document updated by {{userName}}": "Document updated by {{userName}}",
@@ -476,7 +476,7 @@
"{{ count }} words selected_plural": "{{ count }} words selected",
"{{ count }} characters selected": "{{ count }} character selected",
"{{ count }} characters selected_plural": "{{ count }} characters selected",
"Collaborators": "Collaborators",
"Contributors": "Contributors",
"Created": "Created",
"Last updated": "Last updated",
"Creator": "Creator",

View File

@@ -50,7 +50,7 @@ const spacing = {
sidebarWidth: 260,
sidebarCollapsedWidth: 16,
sidebarMinWidth: 200,
sidebarMaxWidth: 400,
sidebarMaxWidth: 600,
};
const buildBaseTheme = (input: Partial<Colors>) => {