Split SharePopover component

This commit is contained in:
Tom Moor committed 2024-01-01 23:52:36 -05:00
1 parent 6fd9cea27d
commit a4c581e9ad
6 files changed
+272 -243

No files matched your search

-1
View File
@@ -352,7 +352,6 @@ export const shareDocument = createAction({
share={share}
sharedParent={sharedParent}
onRequestClose={stores.dialogs.closeAllModals}
hideTitle
visible
/>
),
+245
View File
@@ -0,0 +1,245 @@
import invariant from "invariant";
import debounce from "lodash/debounce";
import isEmpty from "lodash/isEmpty";
import { observer } from "mobx-react";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import { s } from "@shared/styles";
import { dateLocale, dateToRelative } from "@shared/utils/date";
import { SHARE_URL_SLUG_REGEX } from "@shared/utils/urlHelpers";
import Document from "~/models/Document";
import Share from "~/models/Share";
import Button from "~/components/Button";
import CopyToClipboard from "~/components/CopyToClipboard";
import Flex from "~/components/Flex";
import Input, { NativeInput } from "~/components/Input";
import Notice from "~/components/Notice";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import env from "~/env";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import { Label } from "../Labeled";
type Props = {
/** The document to share. */
document: Document;
/** The existing share model, if any. */
share: Share | null | undefined;
/** The existing share parent model, if any. */
sharedParent: Share | null | undefined;
/** Ref to the Copy Link button */
copyButtonRef?: React.RefObject<HTMLButtonElement>;
};
function PublicAccess({ document, share, sharedParent, copyButtonRef }: Props) {
const { shares } = useStores();
const { t } = useTranslation();
const [slugValidationError, setSlugValidationError] = React.useState("");
const [urlSlug, setUrlSlug] = React.useState("");
const can = usePolicy(share);
const documentAbilities = usePolicy(document);
const collectionSharingDisabled = document.collection?.sharing === false;
const canPublish = can.update && documentAbilities.share;
const handlePublishedChange = React.useCallback(
async (event) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
try {
await share.save({
published: event.currentTarget.checked,
});
} catch (err) {
toast.error(err.message);
}
},
[document.id, shares]
);
const handleChildDocumentsChange = React.useCallback(
async (event) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
try {
await share.save({
includeChildDocuments: event.currentTarget.checked,
});
} catch (err) {
toast.error(err.message);
}
},
[document.id, shares]
);
const handleCopied = React.useCallback(() => {
toast.message(t("Share link copied"));
}, [t]);
const handleUrlSlugChange = React.useMemo(
() =>
debounce(async (ev) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
const val = ev.target.value;
setUrlSlug(val);
if (val && !SHARE_URL_SLUG_REGEX.test(val)) {
setSlugValidationError(
t("Only lowercase letters, digits and dashes allowed")
);
} else {
setSlugValidationError("");
if (share.urlId !== val) {
try {
await share.save({
urlId: isEmpty(val) ? null : val,
});
} catch (err) {
if (err.message.includes("must be unique")) {
setSlugValidationError(
t("Sorry, this link has already been used")
);
}
}
}
}
}, 500),
[t, document.id, shares]
);
const userLocale = useUserLocale();
const locale = userLocale ? dateLocale(userLocale) : undefined;
const shareUrl = sharedParent?.url
? `${sharedParent.url}${document.url}`
: share?.url ?? "";
const documentTitle = sharedParent?.documentTitle;
return (
<>
{sharedParent && !document.isDraft && (
<NoticeWrapper>
<Notice>
<Trans>
This document is shared because the parent{" "}
<StyledLink to={`/doc/${sharedParent.documentId}`}>
{documentTitle}
</StyledLink>{" "}
is publicly shared.
</Trans>
</Notice>
</NoticeWrapper>
)}
{collectionSharingDisabled ? (
<Switch
label={t("Publish to internet")}
note={t("Public sharing is disabled in this collection")}
checked={false}
disabled
/>
) : (
!sharedParent?.published && (
<>
<Switch
id="published"
label={t("Publish to internet")}
note={
<>
{t("Allow anyone with the link to view this document")}
{share?.published && share?.lastAccessedAt && (
<>
.{" "}
{t("The shared link was last accessed {{ timeAgo }}.", {
timeAgo: dateToRelative(
Date.parse(share?.lastAccessedAt),
{
addSuffix: true,
locale,
}
),
})}
</>
)}
</>
}
onChange={handlePublishedChange}
checked={share?.published ?? false}
disabled={!canPublish}
/>
{share?.published && (
<>
{!document.isDraft && (
<Switch
id="includeChildDocuments"
note={t(
"Documents nested under this document will be shared"
)}
label={t("Share child documents")}
onChange={handleChildDocumentsChange}
checked={share ? share.includeChildDocuments : false}
disabled={!share}
/>
)}
<Flex align="center" justify="space-between" gap={8}>
<Flex column>
<StyledLabel>{t("Custom link")}</StyledLabel>
<Text type="secondary" size="small">
{env.URL.replace(/https?:\/\//, "")}/s/
</Text>
</Flex>
<CustomSlugInput
type="text"
placeholder="a-unique-link"
onChange={handleUrlSlugChange}
error={slugValidationError}
defaultValue={urlSlug}
/>
</Flex>
</>
)}
</>
)
)}
<Flex justify="flex-end" style={{ marginBottom: 8 }}>
<CopyToClipboard text={shareUrl} onCopy={handleCopied}>
<Button
type="submit"
disabled={!share || slugValidationError}
ref={copyButtonRef}
>
{t("Copy link")}
</Button>
</CopyToClipboard>
</Flex>
</>
);
}
const CustomSlugInput = styled(Input)`
${NativeInput} {
padding: 4px 8px;
}
`;
const StyledLabel = styled(Label)`
padding-bottom: 0;
`;
const StyledLink = styled(Link)`
color: ${s("textSecondary")};
text-decoration: underline;
`;
const NoticeWrapper = styled.div`
margin: 20px 0;
`;
export default observer(PublicAccess);
+17 -236
View File
@@ -1,37 +1,21 @@
import invariant from "invariant";
import debounce from "lodash/debounce";
import isEmpty from "lodash/isEmpty";
import { observer } from "mobx-react";
import { QuestionMarkIcon, TeamIcon } from "outline-icons";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { Link } from "react-router-dom";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { CollectionPermission } from "@shared/types";
import { dateLocale, dateToRelative } from "@shared/utils/date";
import { SHARE_URL_SLUG_REGEX } from "@shared/utils/urlHelpers";
import Document from "~/models/Document";
import Share from "~/models/Share";
import Button from "~/components/Button";
import CopyToClipboard from "~/components/CopyToClipboard";
import Flex from "~/components/Flex";
import Input, { NativeInput } from "~/components/Input";
import Notice from "~/components/Notice";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import env from "~/env";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useKeyDown from "~/hooks/useKeyDown";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import CollectionIcon from "../Icons/CollectionIcon";
import { Label } from "../Labeled";
import Item from "../List/Item";
import Tooltip from "../Tooltip";
import DocumentMembersList from "./DocumentMemberList";
import PublicAccess from "./PublicAccess";
type Props = {
/** The document to share. */
@@ -40,8 +24,6 @@ type Props = {
share: Share | null | undefined;
/** The existing share parent model, if any. */
sharedParent: Share | null | undefined;
/** Whether to hide the title. */
hideTitle?: boolean;
/** Callback fired when the popover requests to be closed. */
onRequestClose: () => void;
/** Whether the popover is visible. */
@@ -57,22 +39,9 @@ function SharePopover({
}: Props) {
const team = useCurrentTeam();
const { t } = useTranslation();
const { shares, collections } = useStores();
const [expandedOptions, setExpandedOptions] = React.useState(false);
const [slugValidationError, setSlugValidationError] = React.useState("");
const [urlSlug, setUrlSlug] = React.useState("");
const timeout = React.useRef<ReturnType<typeof setTimeout>>();
const buttonRef = React.useRef<HTMLButtonElement>(null);
const can = usePolicy(share);
const documentAbilities = usePolicy(document);
const collection = document.collectionId
? collections.get(document.collectionId)
: undefined;
const canPublish =
can.update &&
team.sharing &&
(!document.collectionId || collection?.sharing) &&
documentAbilities.share;
const collection = document.collection;
React.useEffect(() => {
if (!visible && expandedOptions) {
@@ -86,121 +55,8 @@ function SharePopover({
void document.share();
buttonRef.current?.focus();
}
return () => (timeout.current ? clearTimeout(timeout.current) : undefined);
}, [document, visible]);
React.useEffect(() => {
if (!visible) {
setUrlSlug(share?.urlId || "");
setSlugValidationError("");
}
}, [share, visible]);
const handlePublishedChange = React.useCallback(
async (event) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
try {
await share.save({
published: event.currentTarget.checked,
});
} catch (err) {
toast.error(err.message);
}
},
[document.id, shares]
);
const handleChildDocumentsChange = React.useCallback(
async (event) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
try {
await share.save({
includeChildDocuments: event.currentTarget.checked,
});
} catch (err) {
toast.error(err.message);
}
},
[document.id, shares]
);
const handleCopied = React.useCallback(() => {
timeout.current = setTimeout(() => {
onRequestClose();
toast.message(t("Share link copied"));
}, 250);
}, [t, onRequestClose]);
const handleUrlSlugChange = React.useMemo(
() =>
debounce(async (ev) => {
const share = shares.getByDocumentId(document.id);
invariant(share, "Share must exist");
const val = ev.target.value;
setUrlSlug(val);
if (val && !SHARE_URL_SLUG_REGEX.test(val)) {
setSlugValidationError(
t("Only lowercase letters, digits and dashes allowed")
);
} else {
setSlugValidationError("");
if (share.urlId !== val) {
try {
await share.save({
urlId: isEmpty(val) ? null : val,
});
} catch (err) {
if (err.message.includes("must be unique")) {
setSlugValidationError(
t("Sorry, this link has already been used")
);
}
}
}
}
}, 500),
[t, document.id, shares]
);
const PublishToInternet = () => (
<Switch
id="published"
label={t("Publish to internet")}
note={
<>
{t("Allow anyone with the link to view this document")}
{share?.lastAccessedAt && (
<>
.{" "}
{t("The shared link was last accessed {{ timeAgo }}.", {
timeAgo: dateToRelative(Date.parse(share?.lastAccessedAt), {
addSuffix: true,
locale,
}),
})}
</>
)}
</>
}
onChange={handlePublishedChange}
checked={share ? share.published : false}
disabled={!share}
/>
);
const userLocale = useUserLocale();
const locale = userLocale ? dateLocale(userLocale) : undefined;
const shareUrl = sharedParent?.url
? `${sharedParent.url}${document.url}`
: share?.url ?? "";
const documentTitle = sharedParent?.documentTitle;
return (
<>
<Heading>{t("People with access")}</Heading>
@@ -208,7 +64,7 @@ function SharePopover({
{collection?.permission ? (
<Item
image={<TeamIcon />}
title="All workspace members"
title={t("All workspace members")}
actions={
<CollectionAccess>
{collection?.permission === CollectionPermission.ReadWrite
@@ -222,7 +78,7 @@ function SharePopover({
) : collection ? (
<Item
image={<CollectionIcon collection={collection} />}
title="Collection members"
title={t("Collection members")}
actions={<CollectionAccess>{t("Can view")}</CollectionAccess>}
border={false}
small
@@ -230,75 +86,19 @@ function SharePopover({
) : null}
</DocumentMembersList>
<Separator />
<Heading>{t("Public access")}</Heading>
{team.sharing && visible && (
<>
<Separator />
<Heading>{t("Public access")}</Heading>
<>
{sharedParent && !document.isDraft && (
<NoticeWrapper>
<Notice>
<Trans>
This document is shared because the parent{" "}
<StyledLink to={`/doc/${sharedParent.documentId}`}>
{documentTitle}
</StyledLink>{" "}
is publicly shared.
</Trans>
</Notice>
</NoticeWrapper>
)}
{!sharedParent?.published && <PublishToInternet />}
{share?.published && (
<>
{!sharedParent?.published && (
<>
{canPublish && !document.isDraft && (
<Switch
id="includeChildDocuments"
note={t(
"Documents nested under this document will be shared"
)}
label={t("Share child documents")}
onChange={handleChildDocumentsChange}
checked={share ? share.includeChildDocuments : false}
disabled={!share}
/>
)}
<Flex align="center" justify="space-between" gap={8}>
<Flex column>
<StyledLabel>{t("Custom link")}</StyledLabel>
<Text type="secondary" size="small">
{env.URL.replace(/https?:\/\//, "")}/s/
</Text>
</Flex>
<CustomSlugInput
type="text"
placeholder="a-unique-link"
onChange={handleUrlSlugChange}
error={slugValidationError}
defaultValue={urlSlug}
/>
</Flex>
</>
)}
<Flex justify="flex-end" style={{ marginBottom: 8 }}>
<CopyToClipboard text={shareUrl} onCopy={handleCopied}>
<Button
type="submit"
disabled={!share || slugValidationError}
ref={buttonRef}
>
{t("Copy link")}
</Button>
</CopyToClipboard>
</Flex>
</>
)}
</>
<PublicAccess
document={document}
share={share}
sharedParent={sharedParent}
copyButtonRef={buttonRef}
/>
</>
)}
</>
);
}
@@ -317,21 +117,6 @@ const CollectionAccess = ({ children }: { children: React.ReactNode }) => {
);
};
const CustomSlugInput = styled(Input)`
${NativeInput} {
padding: 4px 8px;
}
`;
const StyledLabel = styled(Label)`
padding-bottom: 0;
`;
const StyledLink = styled(Link)`
color: ${s("textSecondary")};
text-decoration: underline;
`;
const Heading = styled(Text).attrs({ size: "large", weight: "bold" })`
display: flex;
align-items: center;
@@ -339,10 +124,6 @@ const Heading = styled(Text).attrs({ size: "large", weight: "bold" })`
margin-top: 12px;
`;
const NoticeWrapper = styled.div`
margin: 20px 0;
`;
const Separator = styled.div`
height: 1px;
margin: 16px 0;
+1 -1
View File
@@ -244,7 +244,7 @@ function DocumentHeader({
/>
</Action>
)}
{!isEditing && !isRevision && !isMobile && can.share && (
{!isEditing && !isRevision && !isMobile && can.update && (
<Action>
<ShareButton document={document} />
</Action>
@@ -23,7 +23,8 @@ function ShareButton({ document }: Props) {
const sharedParent = shares.getByDocumentParents(document.id);
const domain = share?.domain || sharedParent?.domain;
const isPubliclyShared =
team.sharing &&
team.sharing !== false &&
document.collection?.sharing !== false &&
(share?.published || (sharedParent?.published && !document.isDraft));
const popover = usePopoverState({
+7 -4
View File
@@ -250,16 +250,19 @@
"Share link copied": "Share link copied",
"Only lowercase letters, digits and dashes allowed": "Only lowercase letters, digits and dashes allowed",
"Sorry, this link has already been used": "Sorry, this link has already been used",
"This document is shared because the parent <2>{documentTitle}</2> is publicly shared.": "This document is shared because the parent <2>{documentTitle}</2> is publicly shared.",
"Publish to internet": "Publish to internet",
"Public sharing is disabled in this collection": "Public sharing is disabled in this collection",
"Allow anyone with the link to view this document": "Allow anyone with the link to view this document",
"The shared link was last accessed {{ timeAgo }}.": "The shared link was last accessed {{ timeAgo }}.",
"People with access": "People with access",
"Can view": "Can view",
"Public access": "Public access",
"This document is shared because the parent <2>{documentTitle}</2> is publicly shared.": "This document is shared because the parent <2>{documentTitle}</2> is publicly shared.",
"Documents nested under this document will be shared": "Documents nested under this document will be shared",
"Share child documents": "Share child documents",
"Custom link": "Custom link",
"People with access": "People with access",
"All workspace members": "All workspace members",
"Can view": "Can view",
"Collection members": "Collection members",
"Public access": "Public access",
"Access inherited from collection": "Access inherited from collection",
"Logo": "Logo",
"Move document": "Move document",