Merge remote-tracking branch 'origin/main' into tommoor/gmail-threading-fix

# Conflicts:
#	server/emails/templates/BaseEmail.tsx
This commit is contained in:
Tom Moor committed 2026-10-21 00:03:12 -04:00
commit 144f1d91df
140 files changed
+3861 -1445

No files matched your search

+6 -1
View File
@@ -1,5 +1,6 @@
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
@@ -10,6 +11,10 @@ export const Action = styled(Flex)`
font-size: 15px;
flex-shrink: 0;
${breakpoint("mobile", "tablet")`
height: ${MOBILE_TOUCH_TARGET}px;
`};
&:empty {
display: none;
}
+25 -2
View File
@@ -3,6 +3,8 @@ import { DisclosureIcon } from "outline-icons";
import { darken, lighten, transparentize } from "polished";
import * as React from "react";
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import type { Props as ActionButtonProps } from "~/components/ActionButton";
import ActionButton from "~/components/ActionButton";
@@ -36,6 +38,12 @@ const RealButton = styled(ActionButton)<RealProps>`
transition: background 200ms ease-out;
${undraggableOnDesktop()}
${breakpoint("mobile", "tablet")`
height: ${MOBILE_TOUCH_TARGET}px;
border-radius: ${MOBILE_TOUCH_TARGET / 2}px;
font-size: 16px;
`};
&::-moz-focus-inner {
padding: 0;
border: 0;
@@ -126,11 +134,13 @@ const Label = styled.span<{ hasIcon?: boolean }>`
${(props) => props.hasIcon && "padding-inline-start: 4px;"};
`;
export const Inner = styled.span<{
interface InnerProps {
disclosure?: boolean;
hasIcon?: boolean;
hasText?: boolean;
}>`
}
export const Inner = styled.span<InnerProps>`
display: flex;
padding: 0 8px;
padding-inline-end: ${(props) => (props.disclosure ? 2 : 8)}px;
@@ -141,6 +151,18 @@ export const Inner = styled.span<{
${(props) => props.hasIcon && props.hasText && "padding-inline-start: 4px;"};
${(props) => props.hasIcon && !props.hasText && "padding: 0 4px;"};
${breakpoint("mobile", "tablet")`
min-height: ${MOBILE_TOUCH_TARGET}px;
padding: 0 16px;
padding-inline-end: ${(props: InnerProps) => (props.disclosure ? 8 : 16)}px;
${(props: InnerProps) =>
props.hasIcon && props.hasText && "padding-inline-start: 12px;"};
${(props: InnerProps) =>
props.hasIcon &&
!props.hasText &&
`padding: 0 ${(MOBILE_TOUCH_TARGET - 24) / 2}px;`};
`};
`;
export type Props<T> = ActionButtonProps & {
@@ -192,6 +214,7 @@ function Button<T extends React.ElementType = "button">(
$danger={danger}
$fullwidth={fullwidth}
$borderOnHover={borderOnHover}
data-variant={danger ? "danger" : neutral ? "neutral" : "primary"}
{...rest}
>
<Inner hasIcon={hasIcon} hasText={hasText} disclosure={disclosure}>
+1 -1
View File
@@ -1,6 +1,6 @@
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
type Props = {
+9 -14
View File
@@ -17,12 +17,12 @@ const Circle = ({
}) => {
const radius = offset * 0.7;
const circumference = 2 * Math.PI * radius;
let strokePercentage;
let strokeDashoffset = 0;
if (percentage) {
if (percentage !== undefined) {
// because the circle is so small, anything greater than 85% appears like 100%
percentage = percentage > 85 && percentage < 100 ? 85 : percentage;
strokePercentage = ((100 - percentage) * circumference) / 100;
const visible = percentage > 85 && percentage < 100 ? 85 : percentage;
strokeDashoffset = ((100 - visible) * circumference) / 100;
}
return (
@@ -31,13 +31,14 @@ const Circle = ({
cx={offset}
cy={offset}
fill="none"
stroke={strokePercentage !== circumference ? color : ""}
stroke={color}
strokeWidth={2.5}
strokeDasharray={circumference}
strokeDashoffset={percentage ? strokePercentage : 0}
strokeLinecap="round"
style={{
transition: "stroke-dashoffset 0.6s ease 0s",
strokeDashoffset: `${strokeDashoffset}px`,
opacity: percentage === 0 ? 0 : 1,
transition: "stroke-dashoffset 0.6s ease, opacity 0.6s ease",
}}
/>
);
@@ -76,13 +77,7 @@ const CircularProgressBar = ({
>
<g transform={`rotate(-90 ${offset} ${offset})`}>
<Circle color={theme.progressBarBackground} offset={offset} />
{percentage > 0 && (
<Circle
color={theme.accent}
percentage={percentage}
offset={offset}
/>
)}
<Circle color={theme.accent} percentage={percentage} offset={offset} />
</g>
</SVG>
);
+20 -5
View File
@@ -1,7 +1,9 @@
import { filter, isEqual, orderBy, uniq } from "es-toolkit/compat";
import { observer } from "mobx-react";
import styled from "styled-components";
import { useState, useMemo, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import type Document from "~/models/Document";
import type User from "~/models/User";
import type { AvatarProps } from "~/components/Avatar";
@@ -15,8 +17,12 @@ import {
PopoverContent,
} from "~/components/primitives/Popover";
import useCurrentUser from "~/hooks/useCurrentUser";
import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
/** Space after the avatars on mobile, matching the inset of a 24px icon in a touch target. */
const MobileIconInset = (MOBILE_TOUCH_TARGET - 24) / 2;
type Props = {
/** The document to display live collaborators for */
document: Document;
@@ -31,6 +37,8 @@ type Props = {
function Collaborators(props: Props) {
const { limit = 6 } = props;
const { t } = useTranslation();
const isMobile = useMobile();
const size = isMobile ? AvatarSize.XLarge : AvatarSize.Large;
const user = useCurrentUser();
const currentUserId = user?.id;
const [requestedUserIds, setRequestedUserIds] = useState<string[]>([]);
@@ -163,21 +171,23 @@ function Collaborators(props: Props) {
return null;
}
const facepileWidth = Math.min(collaborators.length, limit) * size;
return (
<Popover>
<PopoverTrigger>
<NudeButton
width={Math.min(collaborators.length, limit) * AvatarSize.Large}
height={AvatarSize.Large}
<FacepileButton
width={isMobile ? facepileWidth + MobileIconInset : facepileWidth}
height={isMobile ? MOBILE_TOUCH_TARGET : size}
>
<Facepile
size={AvatarSize.Large}
size={size}
limit={limit}
overflow={Math.max(0, collaborators.length - limit)}
users={collaborators}
renderAvatar={renderAvatar}
/>
</NudeButton>
</FacepileButton>
</PopoverTrigger>
<PopoverContent aria-label={t("Viewers")} side="bottom" align="end">
<DocumentViews document={document} />
@@ -186,4 +196,9 @@ function Collaborators(props: Props) {
);
}
const FacepileButton = styled(NudeButton)`
display: inline-flex;
align-items: center;
`;
export default observer(Collaborators);
+1 -1
View File
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import SearchActions from "~/components/SearchActions";
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import CommandBarResults from "./CommandBarResults";
@@ -15,7 +15,7 @@ import { useTranslation } from "react-i18next";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList as List } from "react-window";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import Icon from "@shared/components/Icon";
import type { NavigationNode } from "@shared/types";
import { isModKey } from "@shared/utils/keyboard";
@@ -2,7 +2,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s, ellipsis } from "@shared/styles";
import Flex from "~/components/Flex";
import Disclosure from "~/components/Sidebar/components/Disclosure";
+1 -1
View File
@@ -5,7 +5,7 @@ import { mergeRefs } from "react-merge-refs";
import { Link } from "react-router-dom";
import { CheckmarkIcon, DocumentIcon } from "outline-icons";
import styled, { css, useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import EventBoundary from "@shared/components/EventBoundary";
import Icon from "@shared/components/Icon";
import { s, hover } from "@shared/styles";
+1 -1
View File
@@ -63,7 +63,7 @@ function Facepile({
model,
size,
style: {
marginRight: lastChild ? 0 : -4,
marginRight: lastChild ? 0 : -Math.round(size / 7),
...(lastChild || filtered.length === 1
? {}
: { clipPath: `url(#${clipPathId(size)})` }),
+12
View File
@@ -3,6 +3,8 @@ import { CheckmarkIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import type { FetchPageParams } from "~/stores/base/Store";
import Button, { Inner } from "~/components/Button";
@@ -359,6 +361,16 @@ export const StyledButton = styled(Button)`
line-height: 28px;
min-height: auto;
}
${breakpoint("mobile", "tablet")`
&& {
height: ${MOBILE_TOUCH_TARGET}px;
}
&& ${Inner} {
min-height: ${MOBILE_TOUCH_TARGET}px;
}
`};
`;
export default FilterOptions;
+108 -6
View File
@@ -6,11 +6,12 @@ import { transparentize } from "polished";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { mergeRefs } from "react-merge-refs";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import styled, { css } from "styled-components";
import type { DefaultTheme } from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import useMeasure from "react-use-measure";
import { HEADER_HEIGHT } from "@shared/constants";
import { depths, s } from "@shared/styles";
import { HEADER_HEIGHT, MOBILE_TOUCH_TARGET } from "@shared/constants";
import { depths, hover, s } from "@shared/styles";
import { metaDisplay } from "@shared/utils/keyboard";
import Button from "~/components/Button";
import Fade from "~/components/Fade";
@@ -164,6 +165,26 @@ function Header({ left, title, actions, hasSidebar, className, ref }: Props) {
);
}
/** Height of the fade at the bottom of the mobile header background. */
const HeaderFadeHeight = 64;
/** Eased mask stops for the header fade, so it has no visible start or end. */
const headerFadeStops = [1, 0.85, 0.5, 0.15, 0]
.map(
(opacity, index, stops) =>
`rgb(0 0 0 / ${opacity}) calc(100% - ${HeaderFadeHeight * (1 - index / (stops.length - 1))}px)`
)
.join(", ");
/** Raised capsule that holds header buttons on mobile, like an iOS toolbar. */
const mobilePill = css`
background: ${s("menuBackground")};
box-shadow:
0 0 0 1px ${s("divider")},
0 4px 12px rgb(0 0 0 / 8%);
border-radius: ${MOBILE_TOUCH_TARGET / 2}px;
`;
const Breadcrumbs = styled("div")`
flex-grow: 1;
flex-basis: 0;
@@ -172,6 +193,20 @@ const Breadcrumbs = styled("div")`
padding-inline: 0 8px;
display: flex;
${breakpoint("mobile", "tablet")`
gap: 8px;
&& [data-variant] {
${mobilePill}
}
&& [data-variant]:${hover}:not(:disabled),
&& [data-variant][aria-expanded="true"] {
${mobilePill}
background: ${s("buttonNeutralBackground")};
}
`};
${breakpoint("tablet")`
min-width: auto;
`};
@@ -185,6 +220,45 @@ const Actions = styled(Flex)`
gap: 8px;
margin-inline-start: 8px;
${breakpoint("mobile", "tablet")`
flex: 0 0 auto;
gap: 0;
margin-inline-start: auto;
&:not(:empty) {
${mobilePill}
padding-inline: 10px;
}
/* Touch targets overlap so icons sit closer than their 44px hit areas. */
& > * {
margin-inline: -4px;
}
&& [data-variant] {
background: transparent;
box-shadow: none;
}
&& [data-variant="primary"] {
color: ${s("accent")};
}
&& [data-variant="primary"]:disabled {
color: ${s("textTertiary")};
svg {
fill: currentColor;
}
}
&& [data-variant]:${hover}:not(:disabled),
&& [data-variant][aria-expanded="true"] {
background: ${s("buttonNeutralBackground")};
box-shadow: none;
}
`};
${breakpoint("tablet")`
position: unset;
`};
@@ -224,7 +298,7 @@ const Wrapper = styled(Flex)<WrapperProps>`
backdrop-filter: blur(20px);
`};
padding: 12px 16px;
padding: 6px 16px;
padding-inline-end: ${endPadding(16)};
transform: translate3d(0, 0, 0);
min-height: ${HEADER_HEIGHT}px;
@@ -249,6 +323,35 @@ const Wrapper = styled(Flex)<WrapperProps>`
display: none;
}
${breakpoint("mobile", "tablet")`
${(props: WrapperProps & { theme: DefaultTheme }) =>
!props.$passThrough &&
`
background: transparent;
backdrop-filter: none;
/* The blurred background extends past the header and fades out, so content blends under it. */
&::before {
content: "";
position: absolute;
inset: 0 0 -${HeaderFadeHeight / 2}px;
z-index: -1;
pointer-events: none;
background: ${transparentize(0.2, props.theme.background)};
backdrop-filter: blur(20px);
mask-image: linear-gradient(to bottom, ${headerFadeStops});
}
/* A stuck tab bar continues the header, so the header is solid above it. */
body:has([data-sticky-tabs][data-stuck]) &::before {
inset: 0;
background: ${props.theme.background};
backdrop-filter: none;
mask-image: none;
}
`}
`};
${breakpoint("tablet")`
padding: 12px;
padding-inline-end: ${endPadding(12)};
@@ -282,7 +385,6 @@ const Title = styled("div")`
`;
const MobileMenuButton = styled(Button)`
margin-right: 8px;
pointer-events: auto;
@media print {
+1 -1
View File
@@ -1,5 +1,5 @@
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
import NudeButton from "~/components/NudeButton";
+10 -2
View File
@@ -1,13 +1,21 @@
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { IconTitleWrapper } from "@shared/components/Icon";
const Heading = styled.h1<{ as?: string; centered?: boolean }>`
display: flex;
align-items: center;
user-select: none;
${(props) => (props.as ? "" : "margin-top: 8vh; font-weight: 600;")}
${(props) => (props.as ? "" : "margin-top: 16px; font-weight: 600;")}
${(props) => (props.centered ? "text-align: center;" : "")}
/* On mobile the title icon sits above the title, so leave room for it. */
${breakpoint("mobile", "tablet")`
&:has(> ${IconTitleWrapper}) {
margin-top: 60px;
}
`};
${breakpoint("tablet")`
${(props: { as?: string }) => (props.as ? "" : "margin-top: 6vh;")}
`};
+1 -1
View File
@@ -5,7 +5,7 @@ import Dropzone from "react-dropzone";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import {
DropzoneContainer,
dropzoneIcon,
+8 -1
View File
@@ -2,7 +2,8 @@ import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s, ellipsis } from "@shared/styles";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
@@ -75,6 +76,7 @@ export const NativeInput = styled.input<{
${breakpoint("mobile", "tablet")`
font-size: 16px;
height: ${MOBILE_TOUCH_TARGET - 2}px;
`};
`;
@@ -121,6 +123,11 @@ export const Outline = styled(Flex)<{
: props.theme.inputBorder};
border-radius: ${(props) => (props.$round ? "16px" : "4px")};
font-weight: normal;
${breakpoint("mobile", "tablet")`
${(props: { $round?: boolean }) =>
props.$round && `border-radius: ${MOBILE_TOUCH_TARGET / 2}px;`}
`};
align-items: center;
overflow: hidden;
background: ${s("background")};
+3 -1
View File
@@ -4,7 +4,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import { metaDisplay, shortcutSeparator } from "@shared/utils/keyboard";
import useBoolean from "~/hooks/useBoolean";
@@ -122,6 +122,8 @@ const InputMaxWidth = styled(Input).attrs({ round: true })`
/* On mobile the input grows to fill the header, so add a gap before the
* adjacent action button (e.g. "New doc"). */
${breakpoint("mobile", "tablet")`
flex: 1;
min-width: 0;
margin-inline-end: 8px;
`}
`;
+1 -1
View File
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import type { DefaultTheme } from "styled-components";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
import { LoadingIndicatorBar } from "~/components/LoadingIndicator";
+1 -1
View File
@@ -226,7 +226,7 @@ function MobileDropdown({
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
>
<DrawerTitle>{ariaLabel}</DrawerTitle>
<DrawerTitle hidden>{ariaLabel}</DrawerTitle>
<StyledScrollable hiddenScrollbars>
{content}
{!submenuName ? append : null}
+1 -1
View File
@@ -4,7 +4,7 @@ import { CloseIcon, BackIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s, borderRadius } from "@shared/styles";
import Flex from "~/components/Flex";
import NudeButton from "~/components/NudeButton";
+1 -1
View File
@@ -21,7 +21,7 @@ import { CollapseIcon } from "outline-icons";
import { useState, useRef, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s, hover, hideScrollbars } from "@shared/styles";
import type Pin from "~/models/Pin";
import DocumentCard from "~/components/DocumentCard";
+6 -1
View File
@@ -1,4 +1,5 @@
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import DelayedMount from "~/components/DelayedMount";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
@@ -54,6 +55,10 @@ export default function PlaceholderDocument({
const Wrapper = styled(Fade)`
display: block;
margin: 6vh 0;
margin: 0 0 6vh;
padding: 12px 0;
${breakpoint("tablet")`
margin-top: 6vh;
`};
`;
+1 -1
View File
@@ -3,7 +3,7 @@ import { m } from "framer-motion";
import { observer } from "mobx-react";
import * as React from "react";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import ErrorBoundary from "~/components/ErrorBoundary";
import ResizeBorder from "~/components/Sidebar/components/ResizeBorder";
+79 -17
View File
@@ -3,7 +3,7 @@ import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import { useHistory } from "react-router-dom";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { Avatar } from "~/components/Avatar";
import Flex from "~/components/Flex";
@@ -12,9 +12,10 @@ import useEventListener from "~/hooks/useEventListener";
import useMobile from "~/hooks/useMobile";
import { useResizeHandle } from "~/hooks/useResizeHandle";
import useStores from "~/hooks/useStores";
import { useSwipeToDismiss } from "~/hooks/useSwipeToDismiss";
import AccountMenu from "~/menus/AccountMenu";
import { fadeOnDesktopBackgrounded } from "~/styles";
import { fadeIn } from "~/styles/animations";
import { drawerTransition } from "~/styles/animations";
import Desktop from "~/utils/Desktop";
import NotificationIcon from "../Notifications/NotificationIcon";
import NotificationsPopover from "../Notifications/NotificationsPopover";
@@ -71,6 +72,7 @@ function Sidebar({
const isSmallerThanMinimum = width < minWidth;
const hoverTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
const internalRef = React.useRef<HTMLDivElement | null>(null);
const backdropRef = React.useRef<HTMLAnchorElement | null>(null);
const mergedRef = React.useMemo(() => mergeRefs([internalRef, ref]), [ref]);
const measure = React.useCallback(
@@ -258,16 +260,17 @@ function Sidebar({
[ui, history]
);
// On mobile the width comes from the viewport, not the resizable desktop width.
const style = React.useMemo(
() => ({
width: `${width}px`,
}),
[width]
() => (isMobile ? undefined : { width: `${width}px` }),
[isMobile, width]
);
const handleCloseSidebar = () => {
ui.toggleMobileSidebar();
};
useSwipeToDismiss(internalRef, backdropRef, {
enabled: isMobile && ui.mobileSidebarVisible,
side: direction === "rtl" ? "right" : "left",
onDismiss: ui.hideMobileSidebar,
});
return (
<TooltipProvider>
@@ -316,18 +319,24 @@ function Sidebar({
</SidebarButton>
</AccountMenu>
)}
<ResizeBorder
onMouseDown={handleMouseDown}
onDoubleClick={sidebarIsClosed ? undefined : handleReset}
/>
{!isMobile && (
<ResizeBorder
onMouseDown={handleMouseDown}
onDoubleClick={sidebarIsClosed ? undefined : handleReset}
/>
)}
</Container>
{ui.mobileSidebarVisible && <Backdrop onClick={handleCloseSidebar} />}
<Backdrop
ref={backdropRef}
$visible={ui.mobileSidebarVisible}
onClick={ui.hideMobileSidebar}
aria-hidden
/>
</TooltipProvider>
);
}
const Backdrop = styled.a`
animation: ${fadeIn} 250ms ease-in-out;
const Backdrop = styled.a<{ $visible: boolean }>`
position: fixed;
top: 0;
left: 0;
@@ -336,6 +345,13 @@ const Backdrop = styled.a`
cursor: default;
z-index: ${depths.mobileSidebar - 1};
background: ${s("backdrop")};
opacity: ${(props) => (props.$visible ? 1 : 0)};
pointer-events: ${(props) => (props.$visible ? "auto" : "none")};
transition: opacity ${drawerTransition};
${breakpoint("tablet")`
display: none;
`};
`;
type ContainerProps = {
@@ -372,7 +388,7 @@ const Container = styled(Flex)<ContainerProps>`
background: ${s("sidebarBackground")};
transition:
box-shadow 150ms ease-in-out,
transform 250ms cubic-bezier(0.34, 1.15, 0.64, 1)
transform ${drawerTransition}
${(props: ContainerProps) =>
props.$isAnimating ? `, width ${ANIMATION_MS}ms ease-out` : ""};
transform: translateX(
@@ -382,8 +398,54 @@ const Container = styled(Flex)<ContainerProps>`
max-width: 80%;
min-width: 280px;
padding-inline-start: var(--sal);
padding-bottom: var(--sab, 0px);
${fadeOnDesktopBackgrounded()}
${breakpoint("mobile", "tablet")`
/* Leaves a strip of the page visible to tap and close, as in Material navigation drawers. */
width: calc(100% - 56px);
max-width: 360px;
min-width: 0;
border-start-end-radius: 8px;
border-end-end-radius: 8px;
/* The negative spread keeps the shadow off the edge side, so a stretch cannot reveal it. */
box-shadow: ${(props: ContainerProps) =>
props.$mobileSidebarVisible
? "12px 0 24px -12px rgb(0 0 0 / 16%)"
: "none"};
[dir="rtl"] & {
box-shadow: ${(props: ContainerProps) =>
props.$mobileSidebarVisible
? "-12px 0 24px -12px rgb(0 0 0 / 16%)"
: "none"};
}
@supports (corner-shape: superellipse(2)) {
border-start-end-radius: 14px;
border-end-end-radius: 14px;
corner-shape: superellipse(2);
}
/* Fills the space behind the edge when the sidebar is stretched past open,
overlapping by a pixel so no seam shows at fractional offsets. */
&::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
inset-inline-end: calc(100% - 1px);
width: 100%;
background: inherit;
}
/* Horizontal gestures drag the sidebar closed, scroll containers inside reset the value. */
&,
& * {
touch-action: pan-y pinch-zoom;
}
`};
[dir="rtl"] & {
transform: translateX(
${(props) => (props.$mobileSidebarVisible ? 0 : "100%")}
@@ -92,7 +92,7 @@ function HistoryNavigation(props: React.ComponentProps<typeof Flex>) {
const Navigation = styled(Flex)`
position: absolute;
inset-inline-end: 12px;
top: 20px;
top: 17px;
button {
cursor: default;
@@ -8,9 +8,11 @@ import { UserPreference } from "@shared/types";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import { DocumentValidation } from "@shared/validations";
import { createAction } from "~/actions";
import { sortCollection } from "~/actions/definitions/collections";
import { DocumentSection } from "~/actions/sections";
import EditableTitle, { type RefHandle } from "~/components/EditableTitle";
import Flex from "~/components/Flex";
import { ActionContextProvider } from "~/hooks/useActionContext";
import useBoolean from "~/hooks/useBoolean";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
@@ -59,7 +61,15 @@ export const PersonalDocs = observer(function PersonalDocs() {
}),
[canCreate, setIsAddingNew]
);
const headerActions = useMemo(() => [newDocAction], [newDocAction]);
const hasCollection = !!collection;
const headerActions = useMemo(
() => (hasCollection ? [newDocAction, sortCollection] : [newDocAction]),
[hasCollection, newDocAction]
);
const activeModels = useMemo(
() => (collection ? [collection] : undefined),
[collection]
);
const handleNewDoc = useCallback(
async (title: string) => {
@@ -143,30 +153,32 @@ export const PersonalDocs = observer(function PersonalDocs() {
return (
<SidebarContext.Provider value="personal">
<Flex column>
<Header
id="personal"
title={t("Personal")}
actions={canCreate ? headerActions : undefined}
primaryAction={canCreate ? newDocAction : undefined}
>
<Relative>
{collection ? (
<CollectionLinkChildren
collection={collection}
expanded
childDepth={0}
prefetchDocument={documents.prefetchDocument}
>
{newDocRow}
</CollectionLinkChildren>
) : (
newDocRow
)}
<SidebarAction action={newDocAction} depth={0} />
</Relative>
</Header>
</Flex>
<ActionContextProvider value={{ activeModels }}>
<Flex column>
<Header
id="personal"
title={t("Personal")}
actions={headerActions}
primaryAction={canCreate ? newDocAction : undefined}
>
<Relative>
{collection ? (
<CollectionLinkChildren
collection={collection}
expanded
childDepth={0}
prefetchDocument={documents.prefetchDocument}
>
{newDocRow}
</CollectionLinkChildren>
) : (
newDocRow
)}
<SidebarAction action={newDocAction} depth={0} />
</Relative>
</Header>
</Flex>
</ActionContextProvider>
</SidebarContext.Provider>
);
});
@@ -2,7 +2,7 @@ import { MoreIcon } from "outline-icons";
import { observer } from "mobx-react";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { extraArea, hover, s } from "@shared/styles";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
@@ -1,7 +1,7 @@
import type { LocationDescriptor } from "history";
import * as React from "react";
import styled, { useTheme, css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { ellipsis, hover, s } from "@shared/styles";
import { isMobile } from "@shared/utils/browser";
import { UnreadBadge } from "~/components/UnreadBadge";
+26 -16
View File
@@ -2,6 +2,7 @@ import * as RadixSwitch from "@radix-ui/react-switch";
import { darken } from "polished";
import * as React from "react";
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import { LabelText } from "~/components/Input";
import Text from "~/components/Text";
@@ -67,7 +68,7 @@ function Switch({
className={label ? undefined : className}
{...props}
>
<StyledSwitchThumb width={width} height={height} />
<StyledSwitchThumb />
</StyledSwitchRoot>
);
@@ -128,15 +129,16 @@ const Label = styled.label<{
const HOVER_EXTRA = 3;
const StyledSwitchThumb = styled(RadixSwitch.Thumb)<{
width: number;
height: number;
}>`
/** Minimum switch size on mobile, so that small switches stay usable by touch. */
const MOBILE_MIN_WIDTH = 32;
const MOBILE_MIN_HEIGHT = 18;
const StyledSwitchThumb = styled(RadixSwitch.Thumb)`
display: block;
width: ${(props) => props.height - 8}px;
height: ${(props) => props.height - 8}px;
width: calc(var(--switch-height) - 8px);
height: calc(var(--switch-height) - 8px);
background-color: white;
border-radius: ${(props) => (props.height - 8) / 2}px;
border-radius: calc((var(--switch-height) - 8px) / 2);
transition:
transform 0.2s,
width 0.2s;
@@ -144,11 +146,11 @@ const StyledSwitchThumb = styled(RadixSwitch.Thumb)<{
will-change: transform, width;
&[data-state="checked"] {
transform: translateX(${(props) => props.width - props.height}px);
transform: translateX(calc(var(--switch-width) - var(--switch-height)));
}
[dir="rtl"] &[data-state="checked"] {
transform: translateX(${(props) => -(props.width - props.height)}px);
transform: translateX(calc(var(--switch-height) - var(--switch-width)));
}
`;
@@ -156,17 +158,25 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{
width: number;
height: number;
}>`
--switch-width: ${(props) => Math.max(props.width, MOBILE_MIN_WIDTH)}px;
--switch-height: ${(props) => Math.max(props.height, MOBILE_MIN_HEIGHT)}px;
position: relative;
width: ${(props) => props.width}px;
height: ${(props) => props.height}px;
width: var(--switch-width);
height: var(--switch-height);
background-color: ${(props) => props.theme.slate};
border-radius: ${(props) => props.height}px;
border-radius: var(--switch-height);
border: none;
cursor: var(--pointer);
transition: background-color 0.2s;
padding: 0 4px;
flex-shrink: 0;
${(props) => breakpoint("tablet")`
--switch-width: ${props.width}px;
--switch-height: ${props.height}px;
`}
&:focus {
box-shadow: 0 0 1px ${s("accent")};
outline: none;
@@ -190,12 +200,12 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{
}
&:hover:not(:disabled) ${StyledSwitchThumb} {
width: ${(props) => props.height - 8 + HOVER_EXTRA}px;
width: calc(var(--switch-height) - 8px + ${HOVER_EXTRA}px);
}
&:hover:not(:disabled)[data-state="checked"] ${StyledSwitchThumb} {
transform: translateX(
${(props) => props.width - props.height - HOVER_EXTRA}px
calc(var(--switch-width) - var(--switch-height) - ${HOVER_EXTRA}px)
);
}
@@ -203,7 +213,7 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{
&:hover:not(:disabled)[data-state="checked"]
${StyledSwitchThumb} {
transform: translateX(
${(props) => -(props.width - props.height - HOVER_EXTRA)}px
calc(var(--switch-height) - var(--switch-width) + ${HOVER_EXTRA}px)
);
}
`;
+7
View File
@@ -19,6 +19,8 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { Waypoint } from "react-waypoint";
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { HEADER_HEIGHT as APP_HEADER_HEIGHT } from "@shared/constants";
import { s } from "@shared/styles";
import DelayedMount from "~/components/DelayedMount";
import Empty from "~/components/Empty";
@@ -717,6 +719,11 @@ const THead = styled.div<{ $topPos: number }>`
border-bottom: 1px solid
${(props) => transparentize(0.3, props.theme.divider)};
background: ${s("background")};
${breakpoint("mobile", "tablet")`
top: ${({ $topPos }: { $topPos: number }) =>
`${Math.min($topPos, APP_HEADER_HEIGHT)}px`};
`};
`;
const TBody = styled.div<{ $height: number }>`
+4 -1
View File
@@ -5,7 +5,8 @@ import { isEqual } from "es-toolkit/compat";
import queryString from "query-string";
import * as React from "react";
import styled, { css, useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s, hover } from "@shared/styles";
import NavLink from "~/components/NavLink";
@@ -60,9 +61,11 @@ const tabStyles = css`
cursor: var(--pointer);
user-select: none;
padding: 12px 0;
min-height: ${MOBILE_TOUCH_TARGET}px;
${breakpoint("tablet")`
padding: 6px 0;
min-height: 0;
`};
`;
+26 -2
View File
@@ -44,9 +44,12 @@ const Nav = styled.nav<{ $shadowVisible?: boolean }>`
// When sticky we need extra background coverage around the sides otherwise
// items that scroll past can "stick out" the sides of the heading
/** Offset from the top of the viewport at which the tab bar sticks. */
const StickyTop = 54;
const Sticky = styled.div`
position: sticky;
top: 54px;
top: ${StickyTop}px;
margin: 0 -8px;
padding: 0 8px;
background: ${s("background")};
@@ -76,6 +79,7 @@ export const TabsGroup: React.FC<Props> = ({ children }: Props) => {
export const Tabs: React.FC<Props> = ({ children }: Props) => {
const ref = React.useRef<HTMLElement>(null);
const stickyRef = React.useRef<HTMLDivElement>(null);
const [shadowVisible, setShadow] = React.useState(false);
const { width } = useWindowSize();
@@ -97,9 +101,29 @@ export const Tabs: React.FC<Props> = ({ children }: Props) => {
updateShadows();
}, [width, updateShadows]);
// Mark the tab bar while it is stuck so the header above can style itself to match.
React.useEffect(() => {
const sticky = stickyRef.current;
if (!sticky) {
return;
}
const observer = new IntersectionObserver(
([entry]) => {
sticky.toggleAttribute(
"data-stuck",
entry.intersectionRatio < 1 &&
entry.boundingClientRect.top <= StickyTop + 1
);
},
{ threshold: 1, rootMargin: `-${StickyTop + 1}px 0px 0px 0px` }
);
observer.observe(sticky);
return () => observer.disconnect();
}, []);
return (
<TabsGroup>
<Sticky>
<Sticky ref={stickyRef} data-sticky-tabs>
<Nav ref={ref} onScroll={updateShadows} $shadowVisible={shadowVisible}>
{children}
</Nav>
+3 -1
View File
@@ -108,7 +108,9 @@ const StyledContent = styled(m.div)`
const StyledInnerContent = styled(Flex)`
padding: 6px;
padding-bottom: calc(6px + var(--sab, 0px));
/* The safe area inset is zero unless the viewport uses viewport-fit=cover. */
padding-bottom: max(24px, calc(6px + var(--sab, 0px)));
height: 100%;
`;
@@ -4,7 +4,7 @@
import { CheckmarkIcon } from "outline-icons";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import Button, { Inner } from "~/components/Button";
import Flex from "~/components/Flex";
@@ -2,7 +2,7 @@ import { ExpandedIcon } from "outline-icons";
import { ellipsis } from "polished";
import { Link } from "react-router-dom";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s, borderRadius } from "@shared/styles";
import Scrollable from "~/components/Scrollable";
import { fadeAndScaleIn } from "~/styles/animations";
+44
View File
@@ -0,0 +1,44 @@
import { DoneIcon, InfoIcon, StarredIcon, WarningIcon } from "outline-icons";
import styled from "styled-components";
import { NoticeTypes } from "@shared/editor/nodes/Notice";
import { s } from "@shared/styles";
interface Props {
/** The style of the notice. */
type: NoticeTypes;
}
/**
* Renders the icon for a notice style, colored to match the notice in the editor.
*
* @param props the component props.
* @returns the icon element.
*/
export function NoticeIcon({ type }: Props) {
switch (type) {
case NoticeTypes.Success:
return <SuccessIcon />;
case NoticeTypes.Warning:
return <NoticeWarningIcon />;
case NoticeTypes.Tip:
return <TipIcon />;
default:
return <NoticeInfoIcon />;
}
}
const NoticeInfoIcon = styled(InfoIcon)`
color: ${s("noticeInfoText")};
`;
const SuccessIcon = styled(DoneIcon)`
color: ${s("noticeSuccessText")};
`;
const NoticeWarningIcon = styled(WarningIcon)`
color: ${s("noticeWarningText")};
`;
const TipIcon = styled(StarredIcon)`
color: ${s("noticeTipText")};
`;
+1 -1
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import * as Toolbar from "@radix-ui/react-toolbar";
import { closeHistory } from "@shared/editor/lib/closeHistory";
import { MenuItemGroup, type MenuItem } from "@shared/editor/types";
+10 -12
View File
@@ -13,13 +13,9 @@ import {
TableIcon,
TodoListIcon,
ImageIcon,
StarredIcon,
WarningIcon,
InfoIcon,
AttachmentIcon,
CalendarIcon,
MathIcon,
DoneIcon,
EmbedIcon,
CollapseIcon,
} from "outline-icons";
@@ -28,10 +24,12 @@ import styled from "styled-components";
import { v4 as uuidv4 } from "uuid";
import type { TFunction } from "i18next";
import Image from "@shared/editor/components/Img";
import { NoticeTypes } from "@shared/editor/nodes/Notice";
import type { MenuItem } from "@shared/editor/types";
import { MentionType } from "@shared/types";
import { toISODate } from "@shared/utils/date";
import { metaDisplay } from "@shared/utils/keyboard";
import { NoticeIcon } from "~/editor/components/NoticeIcon";
import Desktop from "~/utils/Desktop";
const Img = styled(Image)`
@@ -243,30 +241,30 @@ export default function blockMenuItems(
{
name: "container_notice",
title: t("Info notice"),
icon: <InfoIcon />,
icon: <NoticeIcon type={NoticeTypes.Info} />,
keywords: "card callout hint information note",
attrs: { style: "info" },
attrs: { style: NoticeTypes.Info },
},
{
name: "container_notice",
title: t("Success notice"),
icon: <DoneIcon />,
icon: <NoticeIcon type={NoticeTypes.Success} />,
keywords: "card callout hint",
attrs: { style: "success" },
attrs: { style: NoticeTypes.Success },
},
{
name: "container_notice",
title: t("Warning notice"),
icon: <WarningIcon />,
icon: <NoticeIcon type={NoticeTypes.Warning} />,
keywords: "card callout hint error caution danger alert",
attrs: { style: "warning" },
attrs: { style: NoticeTypes.Warning },
},
{
name: "container_notice",
title: t("Tip notice"),
icon: <StarredIcon />,
icon: <NoticeIcon type={NoticeTypes.Tip} />,
keywords: "card callout hint suggestion",
attrs: { style: "tip" },
attrs: { style: NoticeTypes.Tip },
},
{
name: "separator",
+6 -11
View File
@@ -1,14 +1,9 @@
import { t } from "i18next";
import {
DoneIcon,
ExpandedIcon,
InfoIcon,
StarredIcon,
WarningIcon,
} from "outline-icons";
import { ExpandedIcon } from "outline-icons";
import { NoticeTypes } from "@shared/editor/nodes/Notice";
import { findParentNode } from "@shared/editor/queries/findParentNode";
import type { MenuItem, SelectionContext } from "@shared/editor/types";
import { NoticeIcon } from "~/editor/components/NoticeIcon";
/**
* Returns menu items for the notice/callout selection toolbar.
@@ -39,25 +34,25 @@ export default function noticeMenuItems(ctx: SelectionContext): MenuItem[] {
children: [
{
name: NoticeTypes.Info,
icon: <InfoIcon />,
icon: <NoticeIcon type={NoticeTypes.Info} />,
label: t("Info notice"),
active: () => currentStyle === NoticeTypes.Info,
},
{
name: NoticeTypes.Success,
icon: <DoneIcon />,
icon: <NoticeIcon type={NoticeTypes.Success} />,
label: t("Success notice"),
active: () => currentStyle === NoticeTypes.Success,
},
{
name: NoticeTypes.Warning,
icon: <WarningIcon />,
icon: <NoticeIcon type={NoticeTypes.Warning} />,
label: t("Warning notice"),
active: () => currentStyle === NoticeTypes.Warning,
},
{
name: NoticeTypes.Tip,
icon: <StarredIcon />,
icon: <NoticeIcon type={NoticeTypes.Tip} />,
label: t("Tip notice"),
active: () => currentStyle === NoticeTypes.Tip,
},
+1
View File
@@ -31,6 +31,7 @@ export default function tableMenuItems(ctx: SelectionContext): MenuItem[] {
label: isFullWidth ? t("Default width") : t("Full width"),
icon: <AlignFullWidthIcon />,
attrs: isFullWidth ? { layout: null } : { layout: TableLayout.fullWidth },
visible: !ctx.isInNotice,
},
{
name: "distributeColumns",
+14
View File
@@ -90,4 +90,18 @@ describe("DragTarget#hasOwnControls", () => {
const paragraph = new DragTarget(0, document.createElement("div"), "block");
expect(paragraph.hasOwnControls(state)).toBe(false);
});
it("returns true for an empty paragraph that holds the selection", () => {
const emptyDoc = doc([p("one"), p("")]);
const state = createEditorStateWithSelection(emptyDoc, 6);
const paragraph = new DragTarget(5, document.createElement("div"), "block");
expect(paragraph.hasOwnControls(state)).toBe(true);
});
it("returns false for an empty paragraph without the selection", () => {
const emptyDoc = doc([p("one"), p("")]);
const state = createEditorStateWithSelection(emptyDoc, 2);
const paragraph = new DragTarget(5, document.createElement("div"), "block");
expect(paragraph.hasOwnControls(state)).toBe(false);
});
});
+15 -5
View File
@@ -200,18 +200,28 @@ export class DragTarget {
/**
* Whether the editor shows its own controls for this block, which would
* overlap the drag handle, e.g. a table that holds the selection.
* overlap the drag handle, e.g. a table that holds the selection or an
* empty paragraph that shows the block menu trigger.
*
* @param state - the editor state.
* @returns true if the drag handle should be hidden for this block.
*/
public hasOwnControls(state: EditorState): boolean {
const node = state.doc.nodeAt(this.pos);
if (node?.type.name !== "table") {
return false;
const { $from, from, to } = state.selection;
switch (node?.type.name) {
case "table":
return from > this.pos && to < this.pos + node.nodeSize;
case "paragraph":
return (
node.content.size === 0 &&
$from.depth === 1 &&
$from.before() === this.pos
);
default:
return false;
}
const { from, to } = state.selection;
return from > this.pos && to < this.pos + node.nodeSize;
}
/**
+175
View File
@@ -0,0 +1,175 @@
import { useEffect } from "react";
import type { RefObject } from "react";
interface Options {
/** Whether the panel is open and can be swiped away. */
enabled: boolean;
/** The screen edge that the panel is attached to. */
side: "left" | "right";
/** Called when a swipe passes the dismiss threshold. */
onDismiss: () => void;
}
/** Distance in pixels a pointer must move before the gesture is a drag or a scroll. */
const DragSlop = 8;
/** Release speed in px/ms above which the panel is dismissed, matches vaul. */
const VelocityThreshold = 0.4;
/** Fraction of the panel width past which the panel is dismissed, matches vaul. */
const CloseThreshold = 0.25;
/** Rubber band resistance for a drag away from the edge, matches vaul. */
const dampen = (value: number) => Math.max(8 * (Math.log(value + 1) - 2), 0);
/**
* Lets the user drag an edge-attached panel toward its edge to dismiss it, with
* the same thresholds as the vaul drawer. The panel follows the pointer, and on
* release it either dismisses or springs back using the CSS transition of the
* panel. A vertical gesture is left to the browser so that the panel can scroll.
*
* @param panelRef ref to the panel element that moves.
* @param overlayRef ref to an optional backdrop that fades as the panel moves.
* @param options the swipe options.
*/
export function useSwipeToDismiss(
panelRef: RefObject<HTMLElement | null>,
overlayRef: RefObject<HTMLElement | null>,
{ enabled, side, onDismiss }: Options
) {
useEffect(() => {
const panel = panelRef.current;
if (!enabled || !panel) {
return;
}
const overlay = overlayRef.current;
const sign = side === "left" ? -1 : 1;
let start: { x: number; y: number; time: number } | null = null;
let isDragging = false;
let width = 0;
let distance = 0;
const setStyles = (
transition: string,
transform: string,
opacity: string
) => {
panel.style.transition = transition;
panel.style.transform = transform;
if (overlay) {
overlay.style.transition = transition;
overlay.style.opacity = opacity;
}
};
const suppressClick = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
const handlePointerDown = (event: PointerEvent) => {
if (!event.isPrimary || event.button !== 0) {
return;
}
start = { x: event.clientX, y: event.clientY, time: event.timeStamp };
isDragging = false;
distance = 0;
};
const handlePointerMove = (event: PointerEvent) => {
if (!start || !event.isPrimary) {
return;
}
const dx = event.clientX - start.x;
const dy = event.clientY - start.y;
if (!isDragging) {
if (Math.abs(dx) < DragSlop && Math.abs(dy) < DragSlop) {
return;
}
// A mostly vertical gesture is a scroll, so leave it to the browser.
if (Math.abs(dy) >= Math.abs(dx)) {
start = null;
return;
}
isDragging = true;
width = panel.getBoundingClientRect().width;
panel.setPointerCapture(event.pointerId);
}
// A drag away from the edge stretches with resistance. Whole pixels
// stop a visible line where the panel meets its fill.
const dragged = dx * sign;
distance = Math.round(
dragged >= 0 ? Math.min(dragged, width) : -dampen(-dragged)
);
setStyles(
"none",
`translateX(${distance * sign}px)`,
String(1 - Math.max(distance, 0) / width)
);
};
const handlePointerUp = (event: PointerEvent) => {
if (!event.isPrimary) {
return;
}
if (!start || !isDragging) {
start = null;
return;
}
const velocity =
Math.abs(event.clientX - start.x) /
Math.max(event.timeStamp - start.time, 1);
start = null;
isDragging = false;
// The pointer moved, so the click that follows is not a tap.
panel.addEventListener("click", suppressClick, {
capture: true,
once: true,
});
setTimeout(() => {
panel.removeEventListener("click", suppressClick, { capture: true });
}, 0);
if (
distance > 0 &&
(velocity > VelocityThreshold || distance >= width * CloseThreshold)
) {
// Hold the closed position until the closed styles apply, then the
// cleanup below removes the inline styles.
setStyles("", `translateX(${sign * 100}%)`, "0");
onDismiss();
return;
}
setStyles("", "", "");
};
const handlePointerCancel = (event: PointerEvent) => {
if (!event.isPrimary) {
return;
}
if (isDragging) {
setStyles("", "", "");
}
start = null;
isDragging = false;
};
panel.addEventListener("pointerdown", handlePointerDown);
panel.addEventListener("pointermove", handlePointerMove);
panel.addEventListener("pointerup", handlePointerUp);
panel.addEventListener("pointercancel", handlePointerCancel);
return () => {
panel.removeEventListener("pointerdown", handlePointerDown);
panel.removeEventListener("pointermove", handlePointerMove);
panel.removeEventListener("pointerup", handlePointerUp);
panel.removeEventListener("pointercancel", handlePointerCancel);
setStyles("", "", "");
};
}, [panelRef, overlayRef, enabled, side, onDismiss]);
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import { SubscriptionType, UserPreference } from "@shared/types";
import type Document from "~/models/Document";
+5 -1
View File
@@ -98,7 +98,11 @@ function TableOfContentsMenu() {
const rootAction = useMenuAction(actions);
return (
<DropdownMenu action={rootAction} ariaLabel={t("Table of contents")}>
<DropdownMenu
action={rootAction}
align="end"
ariaLabel={t("Table of contents")}
>
<Button
icon={<TableOfContentsIcon />}
aria-label={t("Table of contents")}
@@ -3,7 +3,7 @@ import { GlobeIcon, PadlockIcon, TeamIcon } from "outline-icons";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { flattenTree } from "@shared/utils/tree";
import type Collection from "~/models/Collection";
import Flex from "~/components/Flex";
+1 -1
View File
@@ -1,5 +1,5 @@
import { IconTitleWrapper } from "@shared/components/Icon";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { first } from "es-toolkit/compat";
import { Suspense, useCallback } from "react";
import styled from "styled-components";
@@ -5,7 +5,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import scrollIntoView from "scroll-into-view-if-needed";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s, hover } from "@shared/styles";
import type { ProsemirrorData } from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
@@ -7,7 +7,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import EventBoundary from "@shared/components/EventBoundary";
import { s, hover } from "@shared/styles";
import type { ProsemirrorData } from "@shared/types";
@@ -2,7 +2,7 @@ import { observer } from "mobx-react";
import { DisconnectedIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import {
AuthenticationFailed,
AuthorizationFailed,
+1 -1
View File
@@ -4,7 +4,7 @@ import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { EmojiText } from "@shared/components/EmojiText";
import { HeadingPrefixHelper } from "@shared/editor/extensions/HeadingPrefix";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
+2 -2
View File
@@ -7,7 +7,7 @@ import { useTranslation } from "react-i18next";
import { Prompt, matchPath, useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { s } from "@shared/styles";
import type { NavigationNode } from "@shared/types";
@@ -591,7 +591,7 @@ const EditorContainer = styled.div<EditorContainerProps>`
// A notice above the editor already provides the space from the header
&:has(> ${DocumentNotice}) {
--document-title-margin-top: 0;
--document-title-margin-top: 0px;
}
${breakpoint("tablet")`
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
@@ -5,7 +5,7 @@ import { __parseFromClipboard } from "prosemirror-view";
import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import Icon, { IconTitleWrapper } from "@shared/components/Icon";
import isMarkdown from "@shared/editor/lib/isMarkdown";
import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize";
@@ -292,7 +292,10 @@ const StyledIconPicker = styled(IconPicker)`
const Title = styled(ContentEditable)<TitleProps>`
position: relative;
line-height: ${lineHeight};
margin-top: var(--document-title-margin-top, 8vh);
margin-top: ${(props) =>
props.$containsIcon || !props.readOnly
? "calc(var(--document-title-margin-top, 16px) + 44px)"
: "var(--document-title-margin-top, 16px)"};
margin-bottom: 0.5em;
font-size: ${fontSize};
font-weight: 600;
+6 -3
View File
@@ -170,9 +170,7 @@ function DocumentHeader({
$hidden={isEditingFocus}
hasSidebar
left={
isMobile ? (
<TableOfContentsMenu />
) : (
isMobile ? null : (
<DocumentBreadcrumb document={document}>
{toc}{" "}
<StarAction>
@@ -282,6 +280,11 @@ function DocumentHeader({
</Button>
</Action>
)}
{isMobile && (
<Action>
<TableOfContentsMenu />
</Action>
)}
<Action>
<DocumentMenu
document={document}
@@ -3,7 +3,7 @@ import { CheckmarkIcon, DocumentIcon, PlusIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import EventBoundary from "@shared/components/EventBoundary";
import Icon from "@shared/components/Icon";
import { s, hover, ellipsis } from "@shared/styles";
@@ -126,11 +126,7 @@ function SharedDocumentHeader({ document }: Props) {
}
hasSidebar={hasSidebar}
left={
isMobile ? (
hasHeadings ? (
<TableOfContentsMenu />
) : null
) : hasSidebar ? (
isMobile ? null : hasSidebar ? (
<PublicBreadcrumb
documentId={document.id}
shareId={shareId}
@@ -145,6 +141,11 @@ function SharedDocumentHeader({ document }: Props) {
actions={
<>
<SearchHighlightChip />
{hasHeadings && isMobile && (
<Action>
<TableOfContentsMenu />
</Action>
)}
{hasHeadings && !isMobile && !tocInLeft && <Action>{toc}</Action>}
{allowSubscriptions !== false && env.EMAIL_ENABLED && (
<SubscribeAction shareId={shareId} documentId={document.id} />
@@ -1,7 +1,7 @@
import { WarningIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { DocumentValidation } from "@shared/validations";
import type Document from "~/models/Document";
import Fade from "~/components/Fade";
+37 -23
View File
@@ -338,35 +338,49 @@ export function useDocumentSave({
}, [readOnly, updateIsDirty]);
// Auto-delete/auto-save on unmount + debounce cleanup
useEffect(
() => () => {
const isMountedRef = useRef(false);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
autosave.cancel();
// Read the editor now, as it may be destroyed by the time the check runs.
// oxlint-disable-next-line react-hooks/exhaustive-deps
const currentDoc = editorRef.current?.view.state.doc;
const isEditorEmpty =
!currentDoc || ProsemirrorHelper.isEmpty(currentDoc);
const currentTitle = titleRef.current;
if (
shouldAutoDeleteDraftOnUnmount({
isEditorEmpty,
title: titleRef.current,
createdById: document.createdBy?.id,
currentUserId: auth.user?.id,
isDraft: document.isDraft,
isActive: document.isActive,
hasEmptyTitle: document.hasEmptyTitle,
isPersistedOnce: document.isPersistedOnce,
})
) {
void document.delete();
} else if (document.isDirty()) {
void document.save(undefined, {
autosave: true,
});
}
},
// Defer the check so that a StrictMode remount does not count as an unmount.
queueMicrotask(() => {
if (isMountedRef.current) {
return;
}
if (
shouldAutoDeleteDraftOnUnmount({
isEditorEmpty,
title: currentTitle,
createdById: document.createdBy?.id,
currentUserId: auth.user?.id,
isDraft: document.isDraft,
isActive: document.isActive,
hasEmptyTitle: document.hasEmptyTitle,
isPersistedOnce: document.isPersistedOnce,
})
) {
void document.delete();
} else if (document.isDirty()) {
void document.save(undefined, {
autosave: true,
});
}
});
};
// oxlint-disable-next-line react-hooks/exhaustive-deps
[]
);
}, []);
return {
isUploading,
@@ -7,6 +7,7 @@ import { CSRF } from "@shared/constants";
import { Client } from "@shared/types";
import { errToString } from "@shared/utils/error";
import ButtonLarge from "~/components/ButtonLarge";
import ButtonLink from "~/components/ButtonLink";
import PluginIcon from "~/components/PluginIcon";
import useQuery from "~/hooks/useQuery";
import { client } from "~/utils/ApiClient";
@@ -51,9 +52,11 @@ function flattenFormFields(
* Renders the "Continue with Passkey" login option and runs the WebAuthn
* authentication ceremony.
*
* In the desktop app the ceremony cannot run inside Electron's Chromium, so the
* flow is opened in the system browser and the resulting session is returned to
* the app via the outline:// deep link, mirroring the SSO desktop flow.
* In the desktop app the ceremony runs inside the app when it supports a
* platform authenticator. Otherwise, or if the user chooses a passkey that is
* not stored in the app, the flow is opened in the system browser and the
* resulting session is returned to the app via the outline:// deep link,
* mirroring the SSO desktop flow.
*/
export function PasskeyAuthenticationProvider(props: Props) {
const { t } = useTranslation();
@@ -65,6 +68,13 @@ export function PasskeyAuthenticationProvider(props: Props) {
);
const [isAuthenticating, setIsAuthenticating] = React.useState(false);
const [hasError, setHasError] = React.useState(false);
const [isSupportedInApp, setIsSupportedInApp] = React.useState(false);
React.useEffect(() => {
if (Desktop.isElectron()) {
void Desktop.isPasskeySupported().then(setIsSupportedInApp);
}
}, []);
// True when this page was opened in the system browser from the desktop app
// to complete a passkey login (see the /auth/passkey route). In that case the
@@ -128,14 +138,19 @@ export function PasskeyAuthenticationProvider(props: Props) {
}
}, [isDesktopRedirect, runAuthentication]);
// Opens the flow in the system browser, which returns to the app via the
// outline:// deep link like SSO login.
const openInBrowser = () => {
window.location.href = `/auth/passkey?client=${Client.Desktop}`;
};
const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
event.preventDefault();
// The WebAuthn ceremony cannot run inside Electron's Chromium as it lacks
// platform authenticator support. Open the flow in the system browser,
// which returns to the app via the outline:// deep link like SSO login.
if (Desktop.isElectron()) {
window.location.href = `/auth/passkey?client=${Client.Desktop}`;
// Older desktop apps and devices without a platform authenticator cannot
// run the WebAuthn ceremony inside the app.
if (Desktop.isElectron() && !isSupportedInApp) {
openInBrowser();
return;
}
@@ -172,6 +187,11 @@ export function PasskeyAuthenticationProvider(props: Props) {
</ButtonLarge>
)}
</Form>
{isSupportedInApp && hasError && (
<Fallback type="button" onClick={openInBrowser}>
{t("Use a passkey from your browser")}
</Fallback>
)}
</Wrapper>
);
}
@@ -180,6 +200,12 @@ const Wrapper = styled.div`
width: 100%;
`;
const Fallback = styled(ButtonLink)`
display: block;
margin: 12px auto 0;
font-size: 14px;
`;
const Form = styled.form`
width: 100%;
display: flex;
+1 -1
View File
@@ -6,7 +6,7 @@ import { useTranslation } from "react-i18next";
import { useHistory, useLocation, useRouteMatch } from "react-router-dom";
import { Waypoint } from "react-waypoint";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { Pagination } from "@shared/constants";
import type { Filter } from "@shared/helpers/FilterHelper";
import { DURATION_BY_DATE_FILTER } from "@shared/helpers/FilterHelper";
+42 -28
View File
@@ -36,7 +36,7 @@ function Notifications() {
const options = [
{
event: NotificationEventType.PublishDocument,
events: [NotificationEventType.PublishDocument],
icon: <PublishIcon />,
title: t("Document published"),
description: t(
@@ -44,7 +44,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.UpdateDocument,
events: [NotificationEventType.UpdateDocument],
icon: <EditIcon />,
title: t("Document updated"),
description: t(
@@ -52,7 +52,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.CreateComment,
events: [NotificationEventType.CreateComment],
icon: <CommentIcon />,
title: t("Comment posted"),
description: t(
@@ -60,7 +60,10 @@ function Notifications() {
),
},
{
event: NotificationEventType.MentionedInComment,
events: [
NotificationEventType.MentionedInComment,
NotificationEventType.MentionedInDocument,
],
icon: <EmailIcon />,
title: t("Mentioned"),
description: t(
@@ -68,7 +71,10 @@ function Notifications() {
),
},
{
event: NotificationEventType.GroupMentionedInDocument,
events: [
NotificationEventType.GroupMentionedInDocument,
NotificationEventType.GroupMentionedInComment,
],
icon: <GroupIcon />,
title: t("Group mentions"),
description: t(
@@ -76,7 +82,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.ResolveComment,
events: [NotificationEventType.ResolveComment],
icon: <DoneIcon />,
title: t("Resolved"),
description: t(
@@ -84,7 +90,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.ReactionsCreate,
events: [NotificationEventType.ReactionsCreate],
icon: <SmileyIcon />,
title: t("Reaction added"),
description: t(
@@ -92,7 +98,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.CreateCollection,
events: [NotificationEventType.CreateCollection],
icon: <CollectionIcon />,
title: t("Collection created"),
description: t(
@@ -100,7 +106,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.InviteAccepted,
events: [NotificationEventType.InviteAccepted],
icon: <UserIcon />,
title: t("Invite accepted"),
description: t(
@@ -108,7 +114,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.AddUserToDocument,
events: [NotificationEventType.AddUserToDocument],
icon: <DocumentIcon />,
title: t("Invited to document"),
description: t(
@@ -116,7 +122,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.AddUserToCollection,
events: [NotificationEventType.AddUserToCollection],
icon: <CollectionIcon />,
title: t("Invited to collection"),
description: t(
@@ -124,7 +130,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.AddUserToGroup,
events: [NotificationEventType.AddUserToGroup],
icon: <GroupIcon />,
title: t("Group membership"),
description: t(
@@ -132,7 +138,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.ExportCompleted,
events: [NotificationEventType.ExportCompleted],
icon: <CheckboxIcon checked />,
title: t("Export completed"),
description: t(
@@ -140,7 +146,7 @@ function Notifications() {
),
},
{
event: NotificationEventType.RequestDocumentAccess,
events: [NotificationEventType.RequestDocumentAccess],
icon: <CheckboxIcon checked />,
title: t("Document access requested"),
description: t(
@@ -150,14 +156,14 @@ function Notifications() {
{
visible: isCloudHosted,
icon: <AcademicCapIcon />,
event: NotificationEventType.Onboarding,
events: [NotificationEventType.Onboarding],
title: t("Getting started"),
description: t("Tips on getting started with features and functionality"),
},
{
visible: isCloudHosted,
icon: <StarredIcon />,
event: NotificationEventType.Features,
events: [NotificationEventType.Features],
title: t("New features"),
description: t("Receive an email when new features of note are added"),
},
@@ -170,8 +176,11 @@ function Notifications() {
}, 500);
const handleChange = React.useCallback(
(eventType: NotificationEventType) => async (checked: boolean) => {
await user.setNotificationEventType(eventType, checked);
(eventTypes: NotificationEventType[]) => async (checked: boolean) => {
// Sequential, as each request saves the full settings object.
for (const eventType of eventTypes) {
await user.setNotificationEventType(eventType, checked);
}
showSuccessMessage();
},
[user, showSuccessMessage]
@@ -182,7 +191,9 @@ function Notifications() {
runInAction(() => {
const updated = { ...user.notificationSettings };
for (const option of visibleOptions) {
updated[option.event] = checked;
for (const eventType of option.events) {
updated[eventType] = checked;
}
}
user.notificationSettings = updated;
});
@@ -197,7 +208,7 @@ function Notifications() {
);
const allEnabled = visibleOptions.every((o) =>
user.subscribedToEventType(o.event)
o.events.every((eventType) => user.subscribedToEventType(eventType))
);
const showSuccessNotice = window.location.search === "?success";
@@ -231,14 +242,17 @@ function Notifications() {
</SettingRow>
{options.map((option) => {
const setting = user.subscribedToEventType(option.event);
const [name] = option.events;
const checked = option.events.every((eventType) =>
user.subscribedToEventType(eventType)
);
return (
<SettingRow
key={option.event}
key={name}
visible={option.visible}
label={option.title}
name={option.event}
name={name}
description={
<Text size="small" type="secondary">
{option.description}
@@ -247,11 +261,11 @@ function Notifications() {
compact
>
<Switch
key={option.event}
id={option.event}
name={option.event}
checked={!!setting}
onChange={handleChange(option.event)}
key={name}
id={name}
name={name}
checked={checked}
onChange={handleChange(option.events)}
/>
</SettingRow>
);
+9 -2
View File
@@ -7,6 +7,7 @@ import { Trans, useTranslation } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import type { Filter } from "@shared/helpers/FilterHelper";
import type UsersStore from "~/stores/UsersStore";
import { queriedUsers } from "~/stores/UsersStore";
@@ -155,7 +156,7 @@ function Users() {
</Trans>
</Text>
<StickyFilters justify="space-between">
<HStack>
<FilterGroup>
<InputSearch
short
value={query}
@@ -170,7 +171,7 @@ function Users() {
activeKey={role ?? ""}
onSelect={handleRoleFilter}
/>
</HStack>
</FilterGroup>
<ExportCSV reqParams={reqParams} />
</StickyFilters>
<ConditionalFade animate={!data}>
@@ -268,6 +269,12 @@ function getFilteredUsers({
return filteredUsers;
}
const FilterGroup = styled(HStack)`
${breakpoint("mobile", "tablet")`
display: contents;
`};
`;
const LargeUserStatusFilter = styled(UserStatusFilter)`
height: 32px;
`;
+1 -1
View File
@@ -1,6 +1,6 @@
import { transparentize } from "polished";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { s } from "@shared/styles";
import { HStack } from "~/components/primitives/HStack";
+24 -1
View File
@@ -1,7 +1,7 @@
import { transparentize } from "polished";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
@@ -27,6 +27,29 @@ const Row = styled(Flex)<{ $border?: boolean; $compact?: boolean }>`
&:last-child {
border-bottom: 0;
}
${breakpoint("mobile", "tablet")`
&:has([role="switch"]) {
gap: 16px;
> :first-child {
min-width: 0;
}
> :last-child {
flex: 0 0 auto;
}
}
&:not(:has([role="switch"])) {
flex-direction: column;
gap: 12px;
> :last-child > * {
align-self: stretch;
}
}
`};
`;
const Column = styled.div`
@@ -1,6 +1,8 @@
import styled from "styled-components";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { HEADER_HEIGHT } from "~/components/Header";
import { Wrapper as InputWrapper } from "~/components/Input";
import { HStack } from "~/components/primitives/HStack";
export const FILTER_HEIGHT = 40;
@@ -11,4 +13,17 @@ export const StickyFilters = styled(HStack)`
top: ${HEADER_HEIGHT}px;
z-index: ${depths.header};
background: ${s("background")};
${breakpoint("mobile", "tablet")`
position: static;
height: auto;
flex-wrap: wrap;
justify-content: flex-start;
padding-block: 8px;
${InputWrapper} {
flex: 1 1 100%;
max-width: none;
}
`};
`;
+1 -1
View File
@@ -3,7 +3,7 @@ import { EditIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { IconTitleWrapper } from "@shared/components/Icon";
import useShare from "@shared/hooks/useShare";
import type CollectionModel from "~/models/Collection";
+5
View File
@@ -148,3 +148,8 @@ export const pulse = keyframes`
* The duration of the sidebar appearing animation in ms
*/
export const sidebarAppearDuration = 600;
/**
* The duration and easing of the vaul drawer, shared so that panels move the same way.
*/
export const drawerTransition = "500ms cubic-bezier(0.32, 0.72, 0, 1)";
-2
View File
@@ -6,8 +6,6 @@ declare module "emoji-mart";
declare module "string-replace-to-array";
declare module "styled-components-breakpoint";
declare module "command-score";
declare module "*.png" {
+6
View File
@@ -72,6 +72,12 @@ declare global {
*/
loadAuthConfig: (host: string) => Promise<{ providers: unknown[] }>;
/**
* Returns true when passkeys can be created and used inside the app, rather
* than in the system browser. Not present in older desktop apps.
*/
isPasskeySupported?: () => Promise<boolean>;
/**
* Clears the desktop configuration, removing any custom hosts. Intended
* for debugging use.
+18
View File
@@ -39,6 +39,24 @@ export default class Desktop {
return navigator?.userAgent?.includes("Electron");
}
/**
* Returns true when the desktop app can run the WebAuthn ceremony itself. This
* requires a desktop app that has configured a platform authenticator, and a
* device that supports it.
*
* @returns a promise that resolves to true if passkeys work inside the app.
*/
static async isPasskeySupported(): Promise<boolean> {
try {
if (!(await this.bridge?.isPasskeySupported?.())) {
return false;
}
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
} catch (_err) {
return false;
}
}
/**
* The bridge provides secure access to API's in desktop wrapper.
*/
+230 -30
View File
@@ -1,8 +1,18 @@
/* oxlint-disable no-console */
/* oxlint-disable typescript/no-require-imports */
/* oxlint-disable no-undef */
const { exec } = require("child_process");
const { readdirSync, existsSync } = require("fs");
const { exec, spawn } = require("child_process");
const {
copyFileSync,
existsSync,
mkdirSync,
readdirSync,
rmSync,
statSync,
watch,
} = require("fs");
const { writeFile } = require("fs/promises");
const path = require("path");
const getDirectories = (source) =>
readdirSync(source, { withFileTypes: true })
@@ -38,34 +48,12 @@ async function build() {
const d = getDirectories("./plugins");
// Compile server and shared
// Compile server, shared and plugins in a single SWC process, as process
// startup costs far more than the compilation itself.
console.log("Compiling…");
const swc = (src, out) =>
execAsync(
`yarn swc "${src}" -d "${out}" --strip-leading-paths --extensions .ts,.tsx --ignore "**/*.test.ts,**/*.test.tsx,**/__mocks__/**" --quiet`
);
await Promise.all([
swc("./server", "./build/server"),
swc("./shared", "./build/shared"),
]);
// SWC's --strip-leading-paths removes only the topmost path segment, so a
// `plugins/<name>/server` input keeps `<name>/server/…` and lands correctly
// under a `./build/plugins` output directory.
for (const plugin of d) {
const hasServer = existsSync(`./plugins/${plugin}/server`);
if (hasServer) {
await swc(`./plugins/${plugin}/server`, "./build/plugins");
}
const hasShared = existsSync(`./plugins/${plugin}/shared`);
if (hasShared) {
await swc(`./plugins/${plugin}/shared`, "./build/plugins");
}
}
await execAsync(
`node_modules/.bin/swc ./server ./shared ./plugins -d ./build --extensions .ts,.tsx --ignore "**/*.test.ts,**/*.test.tsx,**/__mocks__/**,plugins/*/client/**" --quiet`
);
// Copy static files
console.log("Copying static files…");
@@ -91,4 +79,216 @@ async function build() {
console.log("Done!");
}
void build();
/**
* Whether a source file is compiled into the server build.
* @param file {string} path relative to the project root.
* @return {boolean}
*/
function isCompiled(file) {
return (
/\.tsx?$/.test(file) &&
!/\.test\.tsx?$/.test(file) &&
!file.split(path.sep).includes("__mocks__") &&
!/^plugins[\\/][^\\/]+[\\/]client[\\/]/.test(file)
);
}
/**
* The build output path of a source file.
* @param file {string} path relative to the project root.
* @return {string | undefined} the output path, or undefined if the file is not
* part of the build.
*/
function getDest(file) {
if (isCompiled(file)) {
return path.join("build", file.replace(/\.tsx?$/, ".js"));
}
if (
/^plugins[\\/][^\\/]+[\\/]plugin\.json$/.test(file) ||
/^shared[\\/]i18n[\\/]locales[\\/]/.test(file)
) {
return path.join("build", file);
}
return undefined;
}
/**
* Builds, then watches the source directories and updates the output of each
* changed, added or removed file. A full build runs again after a failed one.
* When a command is passed it is run, and restarted after each change that
* affects the server.
* @param command {string[]} the command and arguments to run, may be empty.
*/
async function watchSources(command) {
const swc = require("@swc/core");
const timers = new Map();
let child;
let restartTimer;
let isBuilt = false;
let isBuilding = false;
let isBuildPending = false;
const startServer = () => {
// Run in a new process group so the forked service processes are stopped
// together with the master.
child = spawn(command[0], command.slice(1), {
stdio: "inherit",
detached: true,
});
child.once("exit", (code, signal) => {
child = undefined;
if (signal !== "SIGKILL") {
console.log(
`Server exited with ${signal ?? code}, waiting for changes…`
);
}
});
};
const stopServer = (callback) => {
if (!child) {
callback?.();
return;
}
if (callback) {
child.once("exit", callback);
}
process.kill(-child.pid, "SIGKILL");
};
const restartServer = () => {
if (!command.length || !isBuilt) {
return;
}
clearTimeout(restartTimer);
restartTimer = setTimeout(() => {
console.log("Restarting…");
stopServer(startServer);
}, 100);
};
const fullBuild = async () => {
if (isBuilding) {
isBuildPending = true;
return;
}
isBuilding = true;
try {
await build();
isBuilt = true;
} catch (err) {
console.error(err.message ?? err);
console.log("Build failed, waiting for changes…");
} finally {
isBuilding = false;
}
if (isBuildPending) {
isBuildPending = false;
await fullBuild();
} else if (isBuilt && command.length) {
startServer();
}
};
const updateFile = async (file) => {
const dest = getDest(file);
if (!dest) {
return false;
}
if (!isCompiled(file)) {
mkdirSync(path.dirname(dest), { recursive: true });
copyFileSync(file, dest);
console.log(`Copied ${file}`);
return true;
}
const start = performance.now();
try {
const { code } = await swc.transformFile(file);
mkdirSync(path.dirname(dest), { recursive: true });
await writeFile(dest, code);
console.log(
`Compiled ${file} (${(performance.now() - start).toFixed(1)}ms)`
);
return true;
} catch (err) {
console.error(err.message ?? err);
return false;
}
};
const handleChange = async (file) => {
const stats = statSync(file, { throwIfNoEntry: false });
let isChanged = false;
if (!stats) {
// The path of a removed directory maps directly to its output.
const dest = getDest(file) ?? path.join("build", file);
if (existsSync(dest)) {
rmSync(dest, { recursive: true, force: true });
isChanged = true;
}
} else if (stats.isDirectory()) {
// A directory that was moved in does not emit events for its files.
for (const entry of readdirSync(file, { recursive: true })) {
isChanged = (await updateFile(path.join(file, entry))) || isChanged;
}
} else {
isChanged = await updateFile(file);
}
// The editor and components are mostly used by the client, so changes
// there are picked up on the next restart.
if (isChanged && !/^shared[\\/](editor|components)[\\/]/.test(file)) {
restartServer();
}
};
for (const dir of ["server", "shared", "plugins"]) {
watch(dir, { recursive: true }, (_event, filename) => {
if (!filename) {
return;
}
if (!isBuilt) {
void fullBuild();
return;
}
// Editors can emit several events for one save, so debounce each file.
const file = path.join(dir, filename);
clearTimeout(timers.get(file));
timers.set(
file,
setTimeout(() => {
timers.delete(file);
void handleChange(file);
}, 50)
);
});
}
watch(".", (_event, filename) => {
if (/^\.env(\.local|\.development)?$/.test(filename ?? "")) {
restartServer();
}
});
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, () => stopServer(() => process.exit(0)));
}
await fullBuild();
console.log("Watching for changes…");
}
if (process.argv.includes("--watch")) {
// Arguments after "--" are the command to run, e.g. the server.
const separator = process.argv.indexOf("--");
const command = separator === -1 ? [] : process.argv.slice(separator + 1);
void watchSources(command);
} else {
void build();
}
+27 -29
View File
@@ -11,7 +11,7 @@
"build": "yarn clean && yarn vite:build && yarn build:i18n && yarn build:server",
"start": "node ./build/server/index.js",
"dev": "NODE_ENV=development yarn concurrently -n api,collaboration -c \"blue,magenta\" \"node --inspect=0.0.0.0 build/server/index.js --services=cron,collaboration,websockets,admin,web,worker\"",
"dev:backend": "NODE_ENV=development nodemon --quiet --exec \"yarn build:server && yarn dev\" -e js,ts,tsx --watch server --watch shared --watch plugins --watch .env --watch .env.local --watch .env.development --ignore \"shared/components/**/*.tsx?\" --ignore \"plugins/client/**/*.tsx?\" --ignore \"**/*.test.ts\" --ignore data/ --ignore build/ --ignore app/ --ignore \"shared/editor/**\" --ignore server/migrations",
"dev:backend": "NODE_ENV=development node ./build.js --watch -- node --inspect=0.0.0.0 build/server/index.js --services=cron,collaboration,websockets,admin,web,worker",
"dev:watch": "NODE_ENV=development yarn concurrently -n backend,frontend \"yarn dev:backend\" \"yarn vite:dev\"",
"lint": "oxlint --type-aware app server shared plugins",
"lint:changed": "git diff --name-only --diff-filter=ACMRTUXB | grep -E '\\.(js|jsx|ts|tsx)$' | xargs -r oxlint",
@@ -52,12 +52,12 @@
"> 0.25%, not dead"
],
"dependencies": {
"@aws-sdk/client-s3": "^3.1149.0",
"@aws-sdk/client-s3": "^3.1152.0",
"@aws-sdk/cloudfront-signer": "^3.1149.0",
"@aws-sdk/lib-storage": "^3.1149.0",
"@aws-sdk/s3-presigned-post": "^3.1149.0",
"@aws-sdk/s3-request-presigner": "^3.1149.0",
"@aws-sdk/signature-v4-crt": "^3.1149.0",
"@aws-sdk/lib-storage": "^3.1152.0",
"@aws-sdk/s3-presigned-post": "^3.1152.0",
"@aws-sdk/s3-request-presigner": "^3.1152.0",
"@aws-sdk/signature-v4-crt": "^3.1152.0",
"@benrbray/prosemirror-math": "^0.2.2",
"@bull-board/api": "^6.21.3",
"@bull-board/koa": "^6.21.3",
@@ -85,7 +85,7 @@
"@koa/router": "^15.7.0",
"@koa/send": "^6.0.0",
"@linear/sdk": "^97.0.0",
"@modelcontextprotocol/sdk": "^1.31.0",
"@modelcontextprotocol/sdk": "^1.32.1",
"@noble/hashes": "^2.4.0",
"@node-oauth/oauth2-server": "^5.3.0",
"@notionhq/client": "^2.3.0",
@@ -93,21 +93,21 @@
"@octokit/webhooks-types": "^7.6.1",
"@outlinewiki/koa-passport": "^4.2.1",
"@outlinewiki/passport-azure-ad-oauth2": "^0.1.0",
"@radix-ui/react-collapsible": "^1.1.21",
"@radix-ui/react-context-menu": "^2.3.8",
"@radix-ui/react-dialog": "^1.2.0",
"@radix-ui/react-direction": "^1.1.5",
"@radix-ui/react-dropdown-menu": "^2.1.25",
"@radix-ui/react-hover-card": "^1.1.24",
"@radix-ui/react-one-time-password-field": "^0.1.17",
"@radix-ui/react-popover": "^1.2.0",
"@radix-ui/react-select": "^2.3.8",
"@radix-ui/react-slot": "^1.4.0",
"@radix-ui/react-switch": "^1.3.8",
"@radix-ui/react-tabs": "^1.1.22",
"@radix-ui/react-toolbar": "^1.1.20",
"@radix-ui/react-tooltip": "^1.3.0",
"@radix-ui/react-visually-hidden": "^1.2.12",
"@radix-ui/react-collapsible": "^1.2.1",
"@radix-ui/react-context-menu": "^2.4.1",
"@radix-ui/react-dialog": "^1.3.1",
"@radix-ui/react-direction": "^1.2.0",
"@radix-ui/react-dropdown-menu": "^2.2.1",
"@radix-ui/react-hover-card": "^1.2.1",
"@radix-ui/react-one-time-password-field": "^0.2.1",
"@radix-ui/react-popover": "^1.3.1",
"@radix-ui/react-select": "^2.4.1",
"@radix-ui/react-slot": "^1.5.0",
"@radix-ui/react-switch": "^1.4.1",
"@radix-ui/react-tabs": "^1.2.1",
"@radix-ui/react-toolbar": "^1.2.1",
"@radix-ui/react-tooltip": "^1.4.1",
"@radix-ui/react-visually-hidden": "^1.2.13",
"@sentry/node": "^10.76.2",
"@sentry/react": "^10.76.2",
"@simplewebauthn/browser": "^13.3.0",
@@ -121,7 +121,7 @@
"addressparser": "^1.0.1",
"async-sema": "^3.1.1",
"bull": "^4.16.5",
"chrono-node": "^2.10.1",
"chrono-node": "^2.10.3",
"class-validator": "^0.15.1",
"command-score": "^0.1.2",
"compressorjs": "^1.3.0",
@@ -153,8 +153,8 @@
"http-errors": "2.0.1",
"https-proxy-agent": "^7.0.6",
"i18next": "^22.5.1",
"i18next-fs-backend": "^2.6.8",
"i18next-http-backend": "^3.0.6",
"i18next-fs-backend": "^2.6.9",
"i18next-http-backend": "^4.0.3",
"invariant": "^2.2.4",
"ioredis": "^5.11.1",
"ipaddr.js": "^2.4.0",
@@ -177,7 +177,7 @@
"lib0": "^0.2.99",
"mailparser": "^3.9.28",
"mammoth": "^1.11.0",
"markdown-it": "^14.3.2",
"markdown-it": "^14.3.3",
"markdown-it-container": "^3.0.0",
"markdown-it-emoji": "^3.0.0",
"mime-types": "^3.0.2",
@@ -258,7 +258,6 @@
"stoppable": "^1.1.0",
"string-replace-to-array": "^2.1.1",
"styled-components": "^6.5.3",
"styled-components-breakpoint": "^2.1.1",
"styled-normalize": "^8.1.1",
"throng": "^5.0.0",
"tiny-cookie": "^2.5.1",
@@ -270,7 +269,7 @@
"uuid": "^11.1.1",
"validator": "13.15.35",
"vaul": "^1.1.2",
"vite": "^8.3.2",
"vite": "^8.3.3",
"vite-plugin-pwa": "1.3.0",
"winston": "^3.17.0",
"ws": "^7.5.13",
@@ -345,7 +344,6 @@
"ioredis-mock": "^8.13.1",
"lint-staged": "^16.4.0",
"msw": "^2.15.0",
"nodemon": "^3.1.14",
"oxfmt": "0.72.0",
"oxlint": "1.81.0",
"oxlint-tsgolint": "7.0.2001",
+19 -1
View File
@@ -21,6 +21,7 @@ import usePolicy from "~/hooks/usePolicy";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import Notice from "~/components/Notice";
import DelayedMount from "~/components/DelayedMount";
import Desktop from "~/utils/Desktop";
type Passkey = {
id: string;
@@ -38,6 +39,9 @@ function PasskeysSettings() {
const [passkeys, setPasskeys] = React.useState<Passkey[]>([]);
const [isLoading, setIsLoading] = React.useState(true);
const [isRegistering, setIsRegistering] = React.useState(false);
const [isSupported, setIsSupported] = React.useState<boolean | undefined>(
() => (Desktop.isElectron() ? undefined : true)
);
const team = useCurrentTeam();
const can = usePolicy(team);
@@ -57,6 +61,12 @@ function PasskeysSettings() {
void loadPasskeys();
}, [loadPasskeys]);
React.useEffect(() => {
if (Desktop.isElectron()) {
void Desktop.isPasskeySupported().then(setIsSupported);
}
}, []);
const handleRegister = async () => {
setIsRegistering(true);
try {
@@ -139,7 +149,7 @@ function PasskeysSettings() {
<Action>
<Button
onClick={handleRegister}
disabled={isRegistering || !can.createUserPasskey}
disabled={isRegistering || !isSupported || !can.createUserPasskey}
icon={<PlusIcon />}
>
{isRegistering ? `${t("Registering")}…` : `${t("Add passkey")}…`}
@@ -165,6 +175,14 @@ function PasskeysSettings() {
</Notice>
)}
{isSupported === false && (
<Notice>
{t(
"Passkeys cannot be added in the desktop app on this device. Use a web browser to add a passkey."
)}
</Notice>
)}
{isLoading ? (
<DelayedMount>
<PlaceholderList count={5} />
+23 -1
View File
@@ -1,7 +1,12 @@
import { buildApiKey, buildTeam, buildUser } from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import type { APIContext } from "@server/types";
import { getExpectedOrigin, getPasskeyLoginRedirect } from "./passkeys";
import { PasskeyBrand } from "@shared/utils/passkeys";
import {
getExpectedOrigin,
getPasskeyLoginRedirect,
isUniqueAuthenticator,
} from "./passkeys";
const server = getTestServer();
@@ -118,6 +123,23 @@ describe("getPasskeyLoginRedirect", () => {
});
});
describe("isUniqueAuthenticator", () => {
it("should be true for a known authenticator", () => {
expect(isUniqueAuthenticator(PasskeyBrand.OnePassword)).toBe(true);
});
it("should be false for the Chromium authenticator", () => {
expect(isUniqueAuthenticator(PasskeyBrand.ChromiumBrowser)).toBe(false);
});
it("should be false for a missing or zero AAGUID", () => {
expect(isUniqueAuthenticator(undefined)).toBe(false);
expect(isUniqueAuthenticator("00000000-0000-0000-0000-000000000000")).toBe(
false
);
});
});
describe("#passkeys.generateRegistrationOptions", () => {
it("should return registration options for a session", async () => {
const team = await buildTeam({ passkeysEnabled: true });
+15 -3
View File
@@ -19,7 +19,7 @@ import { AuthenticationType } from "@server/types";
import Logger from "@server/logging/Logger";
import Redis from "@server/storage/redis";
import { signIn } from "@server/utils/authentication";
import { generatePasskeyName } from "@shared/utils/passkeys";
import { generatePasskeyName, PasskeyBrand } from "@shared/utils/passkeys";
import * as T from "./schema";
import { Client } from "@shared/types";
import { Minute } from "@shared/utils/time";
@@ -90,6 +90,19 @@ const getRegistrationChallengeKey = (userId: string): string =>
const getAuthenticationChallengeKey = (challengeId: string): string =>
`passkey:auth-challenge:${challengeId}`;
/**
* Returns true if a user may only register one passkey from the authenticator
* with the given AAGUID. The Chromium Touch ID authenticator, which is also used
* by the desktop app, reports the same AAGUID on every device, so it is excluded.
*
* @param aaguid - the authenticator AAGUID from the registration response.
* @returns true if a second passkey from the authenticator should be rejected.
*/
export const isUniqueAuthenticator = (aaguid: string | undefined): boolean =>
!!aaguid &&
aaguid !== "00000000-0000-0000-0000-000000000000" &&
aaguid !== PasskeyBrand.ChromiumBrowser;
router.post(
"passkeys.generateRegistrationOptions",
auth({ type: AuthenticationType.APP }),
@@ -167,7 +180,6 @@ router.post(
}
const { verified, registrationInfo } = verification;
const ZERO_AAGUID = "00000000-0000-0000-0000-000000000000";
if (verified && registrationInfo) {
const { credential, aaguid } = registrationInfo;
@@ -198,7 +210,7 @@ router.post(
});
} else {
// Check if user already has a passkey from the same authenticator
if (aaguid && aaguid !== ZERO_AAGUID) {
if (isUniqueAuthenticator(aaguid)) {
const duplicateDevice = await UserPasskey.findOne({
where: { userId: user.id, aaguid },
});
@@ -26,8 +26,6 @@ export default class SlackProcessor extends BaseProcessor {
switch (event.name) {
case "documents.publish":
case "revisions.create":
// wait a few seconds to give the document summary chance to be generated
await sleep(5000);
return this.documentUpdated(event);
case "integrations.create":
@@ -85,11 +83,9 @@ export default class SlackProcessor extends BaseProcessor {
if (event.name === "documents.publish" && event.data?.source === "import") {
return;
}
const [document, team] = await Promise.all([
Document.findByPk(event.documentId),
Team.findByPk(event.teamId),
]);
if (!document || !team) {
const document = await Document.findByPk(event.documentId);
if (!document) {
return;
}
@@ -124,10 +120,22 @@ export default class SlackProcessor extends BaseProcessor {
if (!integration) {
return;
}
let text = `${document.updatedBy.name} updated "${document.displayTitle}"`;
// wait a few seconds to give the document summary chance to be generated
await sleep(5000);
const [latest, team] = await Promise.all([
Document.findByPk(event.documentId),
Team.findByPk(event.teamId),
]);
if (!latest?.publishedAt || !team) {
return;
}
let text = `${latest.updatedBy.name} updated "${latest.displayTitle}"`;
if (event.name === "documents.publish") {
text = `${document.createdBy.name} published "${document.displayTitle}"`;
text = `${latest.createdBy.name} published "${latest.displayTitle}"`;
}
await fetch(integration.settings.url, {
@@ -138,7 +146,7 @@ export default class SlackProcessor extends BaseProcessor {
body: JSON.stringify({
text,
attachments: [
presentMessageAttachment(document, team, document.collection),
presentMessageAttachment(latest, team, latest.collection),
],
}),
});
@@ -6,16 +6,22 @@ import {
type StrictRequest,
} from "msw";
import { server } from "@server/test/msw";
import { WebhookDelivery } from "@server/models";
import { Revision, WebhookDelivery } from "@server/models";
import {
buildCollection,
buildComment,
buildDocument,
buildPersonalCollection,
buildUser,
buildWebhookDelivery,
buildWebhookSubscription,
} from "@server/test/factories";
import type { DocumentEvent, UserEvent } from "@server/types";
import type {
CommentEvent,
DocumentEvent,
RevisionEvent,
UserEvent,
} from "@server/types";
import DeliverWebhookTask, {
isExpectedNetworkError,
} from "./DeliverWebhookTask";
@@ -160,6 +166,89 @@ describe("DeliverWebhookTask", () => {
);
});
test("should include the document collectionId in comment events", async () => {
const user = await buildUser();
const subscription = await buildWebhookSubscription({
teamId: user.teamId,
createdById: user.id,
url: "http://example.com",
events: ["*"],
});
const collection = await buildCollection({
teamId: user.teamId,
userId: user.id,
});
const document = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
});
const comment = await buildComment({
userId: user.id,
documentId: document.id,
});
const captured = captureWebhook("http://example.com");
const event: CommentEvent = {
name: "comments.create",
modelId: comment.id,
documentId: document.id,
teamId: user.teamId,
actorId: user.id,
ip,
};
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event,
});
expect(captured.length).toBe(1);
const parsedBody = JSON.parse(captured[0].body);
expect(parsedBody.payload.id).toBe(comment.id);
expect(parsedBody.payload.model.collectionId).toBe(collection.id);
expect(parsedBody.payload.model.documentId).toBe(document.id);
});
test("should include the document collectionId in revision events", async () => {
const user = await buildUser();
const subscription = await buildWebhookSubscription({
teamId: user.teamId,
createdById: user.id,
url: "http://example.com",
events: ["*"],
});
const collection = await buildCollection({
teamId: user.teamId,
userId: user.id,
});
const document = await buildDocument({
teamId: user.teamId,
userId: user.id,
collectionId: collection.id,
});
const revision = await Revision.buildFromDocument(document).save();
const captured = captureWebhook("http://example.com");
const event: RevisionEvent = {
name: "revisions.create",
modelId: revision.id,
documentId: document.id,
teamId: user.teamId,
actorId: user.id,
ip,
};
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event,
});
expect(captured.length).toBe(1);
const parsedBody = JSON.parse(captured[0].body);
expect(parsedBody.payload.id).toBe(revision.id);
expect(parsedBody.payload.model.collectionId).toBe(collection.id);
expect(parsedBody.payload.model.documentId).toBe(document.id);
});
test("should hit the subscription url when the eventing model doesn't exist", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
@@ -432,15 +432,26 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
subscription: WebhookSubscription,
event: CommentEvent
): Promise<void> {
const model = await Comment.findByPk(event.modelId, {
paranoid: false,
});
const [model, document] = await Promise.all([
Comment.findByPk(event.modelId, {
paranoid: false,
}),
Document.unscoped().findOne({
attributes: ["collectionId"],
where: { id: event.documentId },
paranoid: false,
}),
]);
await this.sendWebhook({
event,
subscription,
payload: {
id: event.modelId,
model: model && presentComment(model),
model: model && {
...presentComment(model),
collectionId: document?.collectionId ?? null,
},
},
});
}
@@ -744,7 +755,9 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
Revision.findByPk(event.modelId, {
paranoid: false,
}),
Document.findByPk(event.documentId, {
Document.unscoped().findOne({
attributes: ["collectionId"],
where: { id: event.documentId },
paranoid: false,
}),
]);
+9 -5
View File
@@ -139,11 +139,15 @@ export async function authorizeDocumentPublish(
});
}
if (document.parentDocumentId) {
const parentDocument = await Document.findByPk(document.parentDocumentId, {
userId: user.id,
transaction,
});
const parentDocument = document.parentDocumentId
? await Document.findByPk(document.parentDocumentId, {
userId: user.id,
transaction,
})
: null;
// The parent only grants access when it is in the destination collection.
if (parentDocument && parentDocument.collectionId === collection?.id) {
authorize(user, "createChildDocument", parentDocument, { collection });
} else {
authorize(user, "createDocument", collection);
+29 -7
View File
@@ -29,6 +29,10 @@ type SendMailOptions = {
previewText?: string;
/** The plain-text version of the email body. */
text: string;
/** The language of the email in BCP47 format, e.g. "en-US". */
lang?: string;
/** The text direction of the email. */
dir?: "ltr" | "rtl";
/** The React element rendered to produce the HTML body. */
component: React.JSX.Element;
/** Additional CSS to inject into the head of the email. */
@@ -172,6 +176,8 @@ export class Mailer {
data.component,
{
title: data.subject,
lang: data.lang,
dir: data.dir ?? "ltr",
headCSS: [baseStyles, data.headCSS].join(" "),
} as Oy.RenderOptions,
this.template
@@ -188,16 +194,14 @@ export class Mailer {
references: data.references,
inReplyTo: data.references?.at(-1),
subject: data.subject,
headers: this.tagHeaders(data.tags),
headers: {
...this.tagHeaders(data.tags),
...this.unsubscribeHeaders(data.unsubscribeUrl),
},
html,
text: data.text,
list: data.unsubscribeUrl
? {
unsubscribe: {
url: data.unsubscribeUrl,
comment: "Unsubscribe from these emails",
},
}
? { unsubscribe: data.unsubscribeUrl }
: undefined,
attachments: env.isCloudHosted
? undefined
@@ -263,6 +267,24 @@ export class Mailer {
return undefined;
}
/**
* Builds the headers that allow mail clients to unsubscribe with one click,
* as described in RFC 8058. The List-Unsubscribe header itself is set by the
* `list` option.
*
* @param unsubscribeUrl The URL that accepts a POST to unsubscribe.
* @returns A map of headers to set on the message, or undefined.
*/
private unsubscribeHeaders(
unsubscribeUrl?: string
): Record<string, string> | undefined {
if (!unsubscribeUrl) {
return undefined;
}
return { "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" };
}
/** The configured SMTP host and service name, for provider detection. */
private get provider(): string {
return `${env.SMTP_HOST ?? ""} ${env.SMTP_SERVICE ?? ""}`;
+34 -6
View File
@@ -9,9 +9,9 @@ import { toError } from "@shared/utils/error";
import { randomString } from "@shared/random";
import { TeamPreference } from "@shared/types";
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
import { isRTLLanguage } from "@shared/utils/rtl";
import { Day } from "@shared/utils/time";
import mailer from "@server/emails/mailer";
import { BodyNoticeContext } from "@server/emails/templates/components/Body";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import Metrics from "@server/logging/Metrics";
@@ -23,6 +23,8 @@ import { TextHelper } from "@server/models/helpers/TextHelper";
import { taskQueue } from "@server/queues";
import { TaskPriority } from "@server/queues/tasks/base/BaseTask";
import type { NotificationMetadata } from "@server/types";
import { BodyNoticeContext } from "./components/Body";
import { DirectionContext } from "./components/Direction";
export enum EmailMessageCategory {
Authentication = "authentication",
@@ -158,6 +160,9 @@ export default abstract class BaseEmail<
? this.t("This notification was delayed and may be out of date.")
: undefined;
const lang = this.locale;
const dir = isRTLLanguage(lang) ? "rtl" : "ltr";
try {
const text = this.renderAsText(data);
await mailer.sendMail({
@@ -168,11 +173,15 @@ export default abstract class BaseEmail<
messageId,
references,
previewText: this.preview(data),
lang,
dir,
component: (
<BodyNoticeContext.Provider value={delayedNotice}>
{this.render(data)}
{notification ? this.pixel(notification) : null}
</BodyNoticeContext.Provider>
<DirectionContext.Provider value={dir}>
<BodyNoticeContext.Provider value={delayedNotice}>
{this.render(data)}
{notification ? this.pixel(notification) : null}
</BodyNoticeContext.Provider>
</DirectionContext.Provider>
),
text: delayedNotice ? `${delayedNotice}\n\n${text}` : text,
headCSS: this.headCSS?.(data),
@@ -233,6 +242,11 @@ export default abstract class BaseEmail<
return <img src={notification.pixelUrl} alt="" width="1" height="1" />;
}
/** The receiving user's language in BCP47 format. */
private get locale() {
return unicodeCLDRtoBCP47(this.props.language ?? env.DEFAULT_LANGUAGE);
}
/**
* Translate a string using the receiving user's language preference.
*
@@ -243,10 +257,24 @@ export default abstract class BaseEmail<
protected t(key: string, options?: Record<string, unknown>): string {
return i18nT(key, {
...options,
lng: unicodeCLDRtoBCP47(this.props.language ?? env.DEFAULT_LANGUAGE),
lng: this.locale,
}) as string;
}
/**
* Join a list of items into a single string using the receiving user's
* language preference, e.g. "A, B and C".
*
* @param items The items to join.
* @returns The joined string.
*/
protected formatList(items: string[]): string {
return new Intl.ListFormat(this.locale, {
style: "long",
type: "conjunction",
}).format(items);
}
/**
* Returns the subject of the email.
*
@@ -1,11 +1,13 @@
import * as React from "react";
import { CollectionPermission } from "@shared/types";
import { CollectionPermission, NotificationEventType } from "@shared/types";
import { Collection, UserMembership } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import type { EmailProps } from "./BaseEmail";
import BaseEmail, { EmailMessageCategory } from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
import EmailTemplate from "./components/EmailLayout";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
@@ -53,6 +55,13 @@ export default class CollectionSharedEmail extends BaseEmail<
return { collection, membership };
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.AddUserToCollection
);
}
protected subject({ actorName, collection }: Props) {
return this.t(
"{{ actorName }} invited you to the “{{ collectionName }}” collection",
@@ -111,6 +120,11 @@ ${this.t("View Collection")}: ${teamUrl}${collection.path}
<Button href={collectionUrl}>{this.t("View Collection")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={this.unsubscribeUrl(props)}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
@@ -1,14 +1,18 @@
import * as React from "react";
import { NotificationEventType } from "@shared/types";
import { Document, User } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import type { EmailProps } from "./BaseEmail";
import BaseEmail, { EmailMessageCategory } from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
import EmailTemplate from "./components/EmailLayout";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
type InputProps = EmailProps & {
userId: string;
documentId: string;
actorId: string;
teamUrl: string;
@@ -46,12 +50,24 @@ export default class DocumentAccessRequestEmail extends BaseEmail<
return { document, actor };
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.RequestDocumentAccess
);
}
protected subject({ actor, document }: Props) {
return `${actor.name} is requesting access to “${document.displayTitle}”`;
return this.t(
"{{ actorName }} is requesting access to “{{ documentTitle }}”",
{ actorName: actor.name, documentTitle: document.displayTitle }
);
}
protected preview({ actor }: Props): string {
return `${actor.name} is requesting access to a document`;
return this.t("{{ actorName }} is requesting access to a document", {
actorName: actor.name,
});
}
protected fromName({ actor }: Props) {
@@ -60,9 +76,9 @@ export default class DocumentAccessRequestEmail extends BaseEmail<
protected renderAsText({ actor, teamUrl, document }: Props): string {
return `
${actor.name} is requesting access to “${document.displayTitle}”.
${this.t("{{ actorName }} is requesting access to “{{ documentTitle }}”.", { actorName: actor.name, documentTitle: document.displayTitle })}
Open the document to share it with them: ${teamUrl}${document.path}
${this.t("Open the document to share it with them")}: ${teamUrl}${document.path}
`;
}
@@ -73,21 +89,29 @@ Open the document to share it with them: ${teamUrl}${document.path}
return (
<EmailTemplate
previewText={this.preview(props)}
goToAction={{ url: documentUrl, name: "View Document" }}
goToAction={{ url: documentUrl, name: this.t("View Document") }}
>
<Header />
<Body>
<Heading>{document.displayTitle}</Heading>
<p>
{actor.name} is requesting access to the{" "}
<a href={documentUrl}>{document.displayTitle}</a> document.
{this.t("{{ actorName }} is requesting access to the", {
actorName: actor.name,
})}{" "}
<a href={documentUrl}>{document.displayTitle}</a>{" "}
{this.t("document")}.
</p>
<p>Open the document to share it with them.</p>
<p>{this.t("Open the document to share it with them")}.</p>
<p>
<Button href={documentUrl}>View Document</Button>
<Button href={documentUrl}>{this.t("View Document")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={this.unsubscribeUrl(props)}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
@@ -1,8 +1,9 @@
import { differenceBy } from "es-toolkit/compat";
import * as React from "react";
import { MentionType } from "@shared/types";
import { MentionType, NotificationEventType } from "@shared/types";
import { Document, Revision } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import { can } from "@server/policies";
import type { EmailProps } from "./BaseEmail";
@@ -12,6 +13,7 @@ import Button from "./components/Button";
import Diff from "./components/Diff";
import EmailTemplate from "./components/EmailLayout";
import EmptySpace from "./components/EmptySpace";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
@@ -92,6 +94,13 @@ export default class DocumentMentionedEmail extends BaseEmail<
return { document, body };
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.MentionedInDocument
);
}
protected subject({ document }: Props) {
return this.t(`Mentioned you in “{{ documentTitle }}”`, {
documentTitle: document.displayTitle,
@@ -157,6 +166,11 @@ ${this.t("Open Document")}: ${teamUrl}${document.url}
<Button href={documentLink}>{this.t("Open Document")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={this.unsubscribeUrl(props)}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
@@ -0,0 +1,95 @@
import { NotificationEventType } from "@shared/types";
import { createContext } from "@server/context";
import mailer from "@server/emails/mailer";
import env from "@server/env";
import { Revision } from "@server/models";
import { buildDocument, buildTeam, buildUser } from "@server/test/factories";
import { initI18n } from "@server/utils/i18n";
import DocumentPublishedOrUpdatedEmail from "./DocumentPublishedOrUpdatedEmail";
describe("DocumentPublishedOrUpdatedEmail", () => {
beforeAll(async () => {
await initI18n();
});
afterEach(() => {
vi.restoreAllMocks();
});
async function sendEmail(
eventType:
| NotificationEventType.PublishDocument
| NotificationEventType.UpdateDocument,
collaboratorCount: number,
{ withActorId = true } = {}
) {
const spy = vi.spyOn(mailer, "sendMail").mockResolvedValue(undefined);
const team = await buildTeam();
const [actor, ...others] = await Promise.all(
Array.from({ length: collaboratorCount }, (_, index) =>
buildUser({ teamId: team.id, name: `User ${index + 1}` })
)
);
const recipient = await buildUser({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: actor.id,
lastModifiedById: actor.id,
});
const revision = await Revision.createFromDocument(
createContext({ user: actor }),
document,
[actor.id, ...others.map((user) => user.id)]
);
await new DocumentPublishedOrUpdatedEmail({
to: recipient.email,
userId: recipient.id,
eventType,
revisionId: revision.id,
documentId: document.id,
teamUrl: team.url,
actorId: withActorId ? actor.id : undefined,
actorName: actor.name,
}).send();
expect(spy).toHaveBeenCalledTimes(1);
return spy.mock.calls[0][0];
}
it("should name the actor when they are the only collaborator", async () => {
const mail = await sendEmail(NotificationEventType.UpdateDocument, 1);
expect(mail.previewText).toEqual("User 1 updated a document");
expect(mail.text).toContain("User 1 updated the document");
});
it("should list every collaborator on an update", async () => {
const mail = await sendEmail(NotificationEventType.UpdateDocument, 3);
expect(mail.previewText).toEqual(
"User 1, User 2, and User 3 updated a document"
);
expect(mail.text).toContain("User 1, User 2, and User 3 updated the");
});
it("should send from the actor only", async () => {
const mail = await sendEmail(NotificationEventType.UpdateDocument, 2);
expect(mail.from.name).toEqual(`User 1 via ${env.APP_NAME}`);
});
it("should name only the actor on publish", async () => {
const mail = await sendEmail(NotificationEventType.PublishDocument, 2);
expect(mail.previewText).toEqual("User 1 published a document");
});
it("should name only the actor when the actor ID is missing", async () => {
const mail = await sendEmail(NotificationEventType.UpdateDocument, 2, {
withActorId: false,
});
expect(mail.previewText).toEqual("User 1 updated a document");
});
});
@@ -24,6 +24,7 @@ type InputProps = EmailProps & {
userId: string;
documentId: string;
revisionId?: string;
actorId?: string;
actorName: string;
eventType:
| NotificationEventType.PublishDocument
@@ -36,6 +37,10 @@ type BeforeSend = {
collection: Collection | null;
unsubscribeUrl: string;
body: string | undefined;
/** Names of everyone who contributed to the revision, actor first. */
actorNames: string;
/** The number of contributors named in actorNames. */
actorCount: number;
};
type Props = InputProps & BeforeSend;
@@ -61,32 +66,28 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail<
return false;
}
const [collection, team] = await Promise.all([
const [collection, team, revision] = await Promise.all([
document.$get("collection"),
document.$get("team"),
revisionId ? Revision.findByPk(revisionId) : null,
]);
let body;
if (revisionId && team?.getPreference(TeamPreference.PreviewsInEmails)) {
if (revision && team?.getPreference(TeamPreference.PreviewsInEmails)) {
body = await CacheHelper.getDataOrSet<string>(
`diff:${revisionId}`,
`diff:${revision.id}`,
async () => {
// generate the diff html for the email
const revision = await Revision.findByPk(revisionId);
const before = await revision.before();
const content = await DocumentHelper.toEmailDiff(before, revision, {
includeTitle: false,
centered: false,
signedUrls: 4 * Day.seconds,
baseUrl: props.teamUrl,
});
if (revision) {
const before = await revision.before();
const content = await DocumentHelper.toEmailDiff(before, revision, {
includeTitle: false,
centered: false,
signedUrls: 4 * Day.seconds,
baseUrl: props.teamUrl,
});
// inline all css so that it works in as many email providers as possible.
return content ? await HTMLHelper.inlineCSS(content) : undefined;
}
return;
// inline all css so that it works in as many email providers as possible.
return content ? await HTMLHelper.inlineCSS(content) : undefined;
},
30,
10000
@@ -97,6 +98,7 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail<
document,
collection,
body,
...(await this.actorNames(props, revision)),
unsubscribeUrl: this.unsubscribeUrl(props),
};
}
@@ -123,9 +125,10 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail<
});
}
protected preview({ actorName, eventType }: Props): string {
protected preview({ actorNames, actorCount, eventType }: Props): string {
return this.t("{{ actorName }} {{ eventName }} a document", {
actorName,
actorName: actorNames,
count: actorCount,
eventName: this.eventName(eventType),
});
}
@@ -144,7 +147,8 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail<
}
protected renderAsText({
actorName,
actorNames,
actorCount,
teamUrl,
document,
collection,
@@ -155,7 +159,7 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail<
return `
${this.t("“{{ documentTitle }}” {{ eventName }}", { documentTitle: document.displayTitle, eventName })}
${this.t("{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”", { actorName, eventName, documentTitle: document.displayTitle })}${
${this.t("{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”", { actorName: actorNames, count: actorCount, eventName, documentTitle: document.displayTitle })}${
collection?.name
? `, ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}`
: ""
@@ -168,7 +172,8 @@ ${this.t("Open Document")}: ${teamUrl}${document.url}
protected render(props: Props) {
const {
document,
actorName,
actorNames,
actorCount,
collection,
eventType,
teamUrl,
@@ -194,7 +199,8 @@ ${this.t("Open Document")}: ${teamUrl}${document.url}
</Heading>
<p>
{this.t("{{ actorName }} {{ eventName }} the document", {
actorName,
actorName: actorNames,
count: actorCount,
eventName,
})}{" "}
<a href={documentLink}>{document.displayTitle}</a>
@@ -240,4 +246,35 @@ ${this.t("Open Document")}: ${teamUrl}${document.url}
</EmailTemplate>
);
}
/**
* Returns the names of everyone who contributed to an update, with the actor
* first, joined into a single string.
*
* @param props The email props.
* @param revision The revision that triggered the email, if any.
* @returns The joined names and the number of contributors.
*/
private async actorNames(
{ actorId, actorName, eventType }: InputProps,
revision: Revision | null
) {
if (
!actorId ||
!revision ||
eventType !== NotificationEventType.UpdateDocument
) {
return { actorNames: actorName, actorCount: 1 };
}
const collaborators = await revision.collaborators;
const names = [
actorName,
...collaborators
.filter((user) => user && user.id !== actorId)
.map((user) => user.name),
];
return { actorNames: this.formatList(names), actorCount: names.length };
}
}
@@ -1,11 +1,13 @@
import * as React from "react";
import { DocumentPermission } from "@shared/types";
import { DocumentPermission, NotificationEventType } from "@shared/types";
import { Document, GroupMembership, UserMembership } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import type { EmailProps } from "./BaseEmail";
import BaseEmail, { EmailMessageCategory } from "./BaseEmail";
import Body from "./components/Body";
import Button from "./components/Button";
import EmailTemplate from "./components/EmailLayout";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
@@ -56,6 +58,13 @@ export default class DocumentSharedEmail extends BaseEmail<
return { document, membership };
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.AddUserToDocument
);
}
protected subject({ actorName, document }: Props) {
return this.t(`{{ actorName }} shared “{{ documentTitle }}” with you`, {
actorName,
@@ -109,6 +118,11 @@ ${this.t("View Document")}: ${teamUrl}${document.path}
<Button href={documentUrl}>{this.t("View Document")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={this.unsubscribeUrl(props)}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
@@ -1,8 +1,9 @@
import { differenceBy } from "es-toolkit/compat";
import * as React from "react";
import { MentionType } from "@shared/types";
import { MentionType, NotificationEventType } from "@shared/types";
import { Document, Revision, Group } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import { can } from "@server/policies";
import type { EmailProps } from "./BaseEmail";
@@ -12,10 +13,12 @@ import Button from "./components/Button";
import Diff from "./components/Diff";
import EmailTemplate from "./components/EmailLayout";
import EmptySpace from "./components/EmptySpace";
import Footer from "./components/Footer";
import Header from "./components/Header";
import Heading from "./components/Heading";
type InputProps = EmailProps & {
userId: string;
documentId: string;
revisionId: string | undefined;
actorName: string;
@@ -98,6 +101,13 @@ export default class GroupDocumentMentionedEmail extends BaseEmail<
return { document, body, groupName: group.name };
}
protected unsubscribeUrl({ userId }: InputProps) {
return NotificationSettingsHelper.unsubscribeUrl(
userId,
NotificationEventType.GroupMentionedInDocument
);
}
protected subject({ document, groupName }: Props) {
return this.t(
`The {{ groupName }} group was mentioned in “{{ documentTitle }}”`,
@@ -174,6 +184,11 @@ ${this.t("Open Document")}: ${teamUrl}${document.url}
<Button href={documentLink}>{this.t("Open Document")}</Button>
</p>
</Body>
<Footer
unsubscribeUrl={this.unsubscribeUrl(props)}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
</EmailTemplate>
);
}
@@ -0,0 +1,167 @@
import { renderToStaticMarkup } from "react-dom/server";
import { CollectionPermission, DocumentPermission } from "@shared/types";
import mailer from "@server/emails/mailer";
import { UserMembership } from "@server/models";
import {
buildCollection,
buildDocument,
buildGroup,
buildUser,
} from "@server/test/factories";
import CollectionSharedEmail from "./CollectionSharedEmail";
import DocumentAccessRequestEmail from "./DocumentAccessRequestEmail";
import DocumentMentionedEmail from "./DocumentMentionedEmail";
import DocumentSharedEmail from "./DocumentSharedEmail";
import GroupDocumentMentionedEmail from "./GroupDocumentMentionedEmail";
const teamUrl = "https://example.outline.dev";
describe("notification emails", () => {
beforeEach(() => {
vi.spyOn(mailer, "sendMail").mockResolvedValue();
});
afterEach(() => {
vi.restoreAllMocks();
});
const expectUnsubscribe = (eventType: string, userId: string) => {
expect(mailer.sendMail).toHaveBeenCalledTimes(1);
const options = vi.mocked(mailer.sendMail).mock.calls[0][0];
expect(options.unsubscribeUrl).toContain(`userId=${userId}`);
expect(options.unsubscribeUrl).toContain(`eventType=${eventType}`);
};
it("should include an unsubscribe link in DocumentMentionedEmail", async () => {
const user = await buildUser();
const document = await buildDocument({ teamId: user.teamId });
await new DocumentMentionedEmail({
to: user.email,
userId: user.id,
documentId: document.id,
revisionId: undefined,
actorName: "Actor",
teamUrl,
}).send();
expectUnsubscribe("documents.mentioned", user.id);
});
it("should include an unsubscribe link in GroupDocumentMentionedEmail", async () => {
const user = await buildUser();
const group = await buildGroup({ teamId: user.teamId });
const document = await buildDocument({ teamId: user.teamId });
await new GroupDocumentMentionedEmail({
to: user.email,
userId: user.id,
documentId: document.id,
revisionId: undefined,
groupId: group.id,
actorName: "Actor",
teamUrl,
}).send();
expectUnsubscribe("documents.group_mentioned", user.id);
});
it("should include an unsubscribe link in DocumentSharedEmail", async () => {
const user = await buildUser();
const document = await buildDocument({ teamId: user.teamId });
const membership = await UserMembership.create({
userId: user.id,
documentId: document.id,
createdById: document.createdById,
permission: DocumentPermission.Read,
});
await new DocumentSharedEmail({
to: user.email,
userId: user.id,
documentId: document.id,
membershipId: membership.id,
actorName: "Actor",
teamUrl,
}).send();
expectUnsubscribe("documents.add_user", user.id);
});
it("should include an unsubscribe link in CollectionSharedEmail", async () => {
const user = await buildUser();
const collection = await buildCollection({ teamId: user.teamId });
await UserMembership.create({
userId: user.id,
collectionId: collection.id,
createdById: collection.createdById,
permission: CollectionPermission.Read,
});
await new CollectionSharedEmail({
to: user.email,
userId: user.id,
collectionId: collection.id,
actorName: "Actor",
teamUrl,
}).send();
expectUnsubscribe("collections.add_user", user.id);
});
it("should include an unsubscribe link in DocumentAccessRequestEmail", async () => {
const user = await buildUser();
const actor = await buildUser({ teamId: user.teamId });
const document = await buildDocument({ teamId: user.teamId });
await new DocumentAccessRequestEmail({
to: user.email,
userId: user.id,
documentId: document.id,
actorId: actor.id,
teamUrl,
}).send();
expectUnsubscribe("access_requests.create", user.id);
});
it("should set the language and direction for RTL languages", async () => {
const user = await buildUser({ language: "he_IL" });
const actor = await buildUser({ teamId: user.teamId });
const document = await buildDocument({ teamId: user.teamId });
await new DocumentAccessRequestEmail({
to: user.email,
language: user.language,
userId: user.id,
documentId: document.id,
actorId: actor.id,
teamUrl,
}).send();
const options = vi.mocked(mailer.sendMail).mock.calls[0][0];
expect(options.lang).toEqual("he-IL");
expect(options.dir).toEqual("rtl");
expect(renderToStaticMarkup(options.component)).toContain('align="right"');
});
it("should set the language and direction for LTR languages", async () => {
const user = await buildUser({ language: "en_US" });
const document = await buildDocument({ teamId: user.teamId });
await new DocumentMentionedEmail({
to: user.email,
language: user.language,
userId: user.id,
documentId: document.id,
revisionId: undefined,
actorName: "Actor",
teamUrl,
}).send();
const options = vi.mocked(mailer.sendMail).mock.calls[0][0];
expect(options.lang).toEqual("en-US");
expect(options.dir).toEqual("ltr");
expect(renderToStaticMarkup(options.component)).toContain('align="left"');
});
});
@@ -0,0 +1,4 @@
import * as React from "react";
/** The text direction of the email that is being rendered. */
export const DirectionContext = React.createContext<"ltr" | "rtl">("ltr");
@@ -1,6 +1,7 @@
import { Table, TBody, TR, TD } from "oy-vey";
import * as React from "react";
import theme from "@shared/styles/theme";
import { DirectionContext } from "./Direction";
const EmailLayout: React.FC<
React.PropsWithChildren<{
@@ -9,6 +10,7 @@ const EmailLayout: React.FC<
goToAction?: { url: string; name: string };
}>
> = ({ previewText, bgcolor = "#FFFFFF", goToAction, children }) => {
const dir = React.useContext(DirectionContext);
let markup;
if (goToAction) {
markup = JSON.stringify({
@@ -60,7 +62,7 @@ const EmailLayout: React.FC<
<Table width="550">
<TBody>
<TR>
<TD align="left">{children}</TD>
<TD align={dir === "rtl" ? "right" : "left"}>{children}</TD>
</TR>
</TBody>
</Table>
@@ -3,6 +3,7 @@ import * as React from "react";
import theme from "@shared/styles/theme";
import { UrlHelper } from "@shared/utils/UrlHelper";
import env from "@server/env";
import { DirectionContext } from "./Direction";
type Props = {
unsubscribeUrl?: string;
@@ -17,11 +18,12 @@ export const Link = ({
href: string;
children: React.ReactNode;
}) => {
const dir = React.useContext(DirectionContext);
const linkStyle = {
color: theme.slate,
fontWeight: 500,
textDecoration: "none",
marginRight: "10px",
[dir === "rtl" ? "marginLeft" : "marginRight"]: "10px",
};
return (
+3
View File
@@ -57,6 +57,9 @@ export function createMcpServer(
},
},
instructions,
// Tool arguments are flat, so a large element count is never legitimate.
maxToolInputElements: 1000,
}
);
+26
View File
@@ -69,6 +69,7 @@ import GroupUser from "./GroupUser";
import Import from "./Import";
import Relationship from "./Relationship";
import Revision from "./Revision";
import Share from "./Share";
import Star from "./Star";
import Team from "./Team";
import User from "./User";
@@ -1314,6 +1315,17 @@ class Document extends ArchivableModel<
this.collectionId = collectionId;
}
// A parent outside the destination collection is stale, so publish at the root.
if (this.parentDocumentId && this.collectionId) {
const parentDocument = await Document.unscoped().findByPk(
this.parentDocumentId,
{ attributes: ["collectionId"], transaction }
);
if (parentDocument?.collectionId !== this.collectionId) {
this.parentDocumentId = null;
}
}
if (this.collectionId) {
const collection = await Collection.findByPk(this.collectionId, {
includeDocumentStructure: true,
@@ -1424,6 +1436,20 @@ class Document extends ArchivableModel<
if (options.detach) {
this.collectionId = null;
this.parentDocumentId = null;
}
// Withdrawing the document also disables its public share links.
const shares = await Share.findAll({
where: {
documentId: this.id,
published: true,
revokedAt: { [Op.is]: null },
},
transaction,
});
for (const share of shares) {
await share.updateWithCtx(ctx, { published: false });
}
return this.saveWithCtx(ctx, undefined, { name: "unpublish" });
+7 -2
View File
@@ -1,4 +1,5 @@
import type { InferAttributes, InferCreationAttributes } from "sequelize";
import { sortBy } from "es-toolkit/compat";
import { Op } from "sequelize";
import {
AllowNull,
@@ -123,7 +124,8 @@ class Revision extends ParanoidModel<
collaboratorIds: string[];
/**
* Get the collaborators for this revision.
* Get the collaborators for this revision, with the author first and the
* others in the order they were recorded.
*/
get collaborators() {
const otherCollaboratorIds = (this.collaboratorIds ?? []).filter(
@@ -141,7 +143,10 @@ class Revision extends ParanoidModel<
},
},
paranoid: false,
}).then((others) => [this.user, ...others]);
}).then((others) => [
this.user,
...sortBy(others, [(user) => otherCollaboratorIds.indexOf(user.id)]),
]);
}
// hooks
@@ -1369,6 +1369,54 @@ Second notes.`
);
});
it("should resolve anchors for a heading that ends in a number", async () => {
const document = await buildDocument({
text: `## Setup
First setup.
## Setup
Second setup.
## Setup 1
Third setup.`,
});
expect(DocumentHelper.getAnchorContent(document, "h-setup-1")).toBe(
`## Setup
Second setup.`
);
expect(DocumentHelper.getAnchorContent(document, "h-setup-1-1")).toBe(
`## Setup 1
Third setup.`
);
});
it("should count nested headings when numbering duplicates", async () => {
const document = await buildDocument({
text: `> ## Notes
>
> Quoted notes.
## Notes
Top-level notes.`,
});
expect(
DocumentHelper.getAnchorContent(document, "h-notes")
).toBeUndefined();
expect(DocumentHelper.getAnchorContent(document, "h-notes-1")).toBe(
`## Notes
Top-level notes.`
);
});
it("should return undefined when no heading matches", async () => {
const document = await buildDocument({
text: `## Installation
+19 -25
View File
@@ -8,7 +8,7 @@ import {
ChangesetHelper,
type ExtendedChange,
} from "@shared/editor/lib/ChangesetHelper";
import headingToSlug from "@shared/editor/lib/headingToSlug";
import { HeadingSlugger } from "@shared/editor/lib/headingToSlug";
import textBetween from "@shared/editor/lib/textBetween";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import type { NavigationNode, ProsemirrorData } from "@shared/types";
@@ -267,40 +267,34 @@ export class DocumentHelper {
const node = DocumentHelper.toProsemirror(document);
// Headings are always top-level nodes, so iterating the document's direct
// children is sufficient to locate the section.
const children: Node[] = [];
node.content.forEach((child) => children.push(child));
const previouslySeen: Record<string, number> = {};
// Nested headings (eg. in tables) affect the numbering of duplicates, so
// every heading is visited, but a section can only start at a top-level one.
const slugger = new HeadingSlugger();
let startIndex = -1;
let level = 0;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.type.name !== "heading") {
continue;
node.forEach((child, _offset, index) => {
if (startIndex !== -1) {
return;
}
// Calculate the heading id using the same de-duplication logic as the
// editor so that anchors to repeated headings resolve correctly.
const slug = headingToSlug(child);
const headingId =
previouslySeen[slug] > 0
? headingToSlug(child, previouslySeen[slug])
: slug;
previouslySeen[slug] =
previouslySeen[slug] !== undefined ? previouslySeen[slug] + 1 : 1;
if (startIndex === -1 && headingId === id) {
startIndex = i;
level = child.attrs.level;
if (child.type.name === "heading") {
if (slugger.slug(child) === id) {
startIndex = index;
}
return;
}
}
child.descendants((nested) => {
if (nested.type.name === "heading") {
slugger.slug(nested);
}
});
});
if (startIndex === -1) {
return undefined;
}
const level = children[startIndex].attrs.level;
const sectionNodes: Node[] = [children[startIndex]];
for (let i = startIndex + 1; i < children.length; i++) {
@@ -47,6 +47,7 @@ export default class EmailsProcessor extends BaseProcessor {
revisionId: notification.revisionId,
documentId: notification.documentId,
teamUrl: notification.team.url,
actorId: notification.actorId,
actorName: notification.actor.name,
},
{ notificationId }
@@ -94,6 +95,7 @@ export default class EmailsProcessor extends BaseProcessor {
{
to: notification.user.email,
language: notification.user.language,
userId: notification.userId,
documentId: notification.documentId,
revisionId: notification.revisionId,
groupId: notification.groupId,
@@ -215,6 +217,8 @@ export default class EmailsProcessor extends BaseProcessor {
await new DocumentAccessRequestEmail(
{
to: notification.user.email,
language: notification.user.language,
userId: notification.userId,
documentId: notification.documentId,
actorId: notification.actorId,
teamUrl: notification.team.url,
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more