Compare commits

..

2 Commits

Author SHA1 Message Date
Tom Moor 8e9beac59f test 2023-08-08 23:12:41 -04:00
Tom Moor a0f7c76405 Add support for SSL in development 2023-08-08 22:46:31 -04:00
494 changed files with 6140 additions and 9871 deletions
+14 -16
View File
@@ -36,20 +36,20 @@ jobs:
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: install-deps
command: yarn install --frozen-lockfile --cache-folder ~/.cache/yarn
command: yarn install --frozen-lockfile
- save_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
paths:
- ~/.cache/yarn
- ./node_modules
lint:
<<: *defaults
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: lint
command: yarn lint
@@ -58,7 +58,7 @@ jobs:
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: typescript
command: yarn tsc
@@ -67,7 +67,7 @@ jobs:
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: test
command: yarn test:app
@@ -76,25 +76,22 @@ jobs:
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: test
command: yarn test:shared
test-server:
<<: *defaults
parallelism: 3
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: migrate
command: ./node_modules/.bin/sequelize db:migrate --url $DATABASE_URL_TEST
- run:
name: test
command: |
TESTFILES=$(circleci tests glob "server/**/*.test.ts" | circleci tests split)
yarn test $TESTFILES
command: yarn test:server --forceExit
bundle-size:
<<: *defaults
environment:
@@ -102,7 +99,7 @@ jobs:
steps:
- checkout
- restore_cache:
key: yarn-cache-{{ checksum "yarn.lock" }}
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: build-vite
command: yarn vite:build
@@ -169,8 +166,9 @@ workflows:
- build
- bundle-size:
requires:
- build
- types
- test-app
- test-shared
- test-server
build-docker:
jobs:
+2 -2
View File
@@ -183,5 +183,5 @@ RATE_LIMITER_REQUESTS=1000
RATE_LIMITER_DURATION_WINDOW=60
# Iframely API config
# IFRAMELY_URL=
# IFRAMELY_API_KEY=
IFRAMELY_URL=
IFRAMELY_API_KEY=
+1 -2
View File
@@ -21,7 +21,7 @@
"eslint-plugin-import",
"eslint-plugin-node",
"eslint-plugin-react",
"eslint-plugin-lodash"
"import"
],
"rules": {
"eqeqeq": 2,
@@ -55,7 +55,6 @@
],
"padding-line-between-statements": ["error", { "blankLine": "always", "prev": "*", "next": "export" }],
"lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
"lodash/import-scope": ["warn", "method"],
"import/no-named-as-default": "off",
"import/no-named-as-default-member": "off",
"import/newline-after-import": 2,
+2 -5
View File
@@ -1,7 +1,5 @@
{
"workerIdleMemoryLimit": "0.75",
"maxWorkers": 2,
"maxConcurrency": 1,
"projects": [
{
"displayName": "server",
@@ -15,9 +13,8 @@
"<rootDir>/server/test/env.ts"
],
"setupFilesAfterEnv": ["<rootDir>/server/test/setup.ts"],
"globalSetup": "<rootDir>/server/test/globalSetup.ts",
"globalTeardown": "<rootDir>/server/test/globalTeardown.ts",
"testEnvironment": "node"
"testEnvironment": "node",
"runner": "@getoutline/jest-runner-serial"
},
{
"displayName": "app",
+2 -2
View File
@@ -3,7 +3,7 @@ Business Source License 1.1
Parameters
Licensor: General Outline, Inc.
Licensed Work: Outline 0.71.0
Licensed Work: Outline 0.64.0
The Licensed Work is (c) 2020 General Outline, Inc.
Additional Use Grant: You may make use of the Licensed Work, provided that
you may not use the Licensed Work for a Document
@@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that
Licensed Work by creating teams and documents
controlled by such third parties.
Change Date: 2027-08-18
Change Date: 2026-05-23
Change License: Apache License, Version 2.0
+2 -2
View File
@@ -11,14 +11,14 @@ test:
docker-compose up -d redis postgres s3
yarn sequelize db:drop --env=test
yarn sequelize db:create --env=test
NODE_ENV=test yarn sequelize db:migrate --env=test
yarn sequelize db:migrate --env=test
yarn test
watch:
docker-compose up -d redis postgres s3
yarn sequelize db:drop --env=test
yarn sequelize db:create --env=test
NODE_ENV=test yarn sequelize db:migrate --env=test
yarn sequelize db:migrate --env=test
yarn test:watch
destroy:
+1 -5
View File
@@ -96,10 +96,6 @@ Or to run migrations on test database:
yarn sequelize db:migrate --env test
```
# Activity
![Alt](https://repobeats.axiom.co/api/embed/ff2e4e6918afff1acf9deb72d1ba6b071d586178.svg "Repobeats analytics image")
# License
## License
Outline is [BSL 1.1 licensed](LICENSE).
+1 -1
View File
@@ -14,7 +14,6 @@ import {
BrowserIcon,
} from "outline-icons";
import * as React from "react";
import { isMac } from "@shared/utils/browser";
import {
developersUrl,
changelogUrl,
@@ -27,6 +26,7 @@ import KeyboardShortcuts from "~/scenes/KeyboardShortcuts";
import { createAction } from "~/actions";
import { NavigationSection, RecentSearchesSection } from "~/actions/sections";
import Desktop from "~/utils/Desktop";
import { isMac } from "~/utils/browser";
import history from "~/utils/history";
import isCloudHosted from "~/utils/isCloudHosted";
import {
+1 -1
View File
@@ -1,4 +1,4 @@
import flattenDeep from "lodash/flattenDeep";
import { flattenDeep } from "lodash";
import * as React from "react";
import { Optional } from "utility-types";
import { v4 as uuidv4 } from "uuid";
+1 -1
View File
@@ -1,6 +1,6 @@
/* eslint-disable prefer-rest-params */
/* global ga */
import escape from "lodash/escape";
import { escape } from "lodash";
import * as React from "react";
import { IntegrationService } from "@shared/types";
import env from "~/env";
+1 -4
View File
@@ -1,7 +1,4 @@
import filter from "lodash/filter";
import isEqual from "lodash/isEqual";
import sortBy from "lodash/sortBy";
import uniq from "lodash/uniq";
import { sortBy, filter, uniq, isEqual } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
+2 -7
View File
@@ -7,7 +7,6 @@ import ConfirmationDialog from "~/components/ConfirmationDialog";
import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import { homePath } from "~/utils/routeHelpers";
type Props = {
@@ -18,20 +17,16 @@ type Props = {
function CollectionDeleteDialog({ collection, onSubmit }: Props) {
const team = useCurrentTeam();
const { ui } = useStores();
const { showToast } = useToasts();
const history = useHistory();
const { t } = useTranslation();
const handleSubmit = async () => {
const redirect = collection.id === ui.activeCollectionId;
await collection.delete();
onSubmit();
if (redirect) {
history.push(homePath());
}
await collection.delete();
onSubmit();
showToast(t("Collection deleted"), { type: "success" });
};
return (
+5 -38
View File
@@ -14,48 +14,15 @@ function ConnectionStatus() {
const theme = useTheme();
const { t } = useTranslation();
const codeToMessage = {
1009: {
title: t("Document is too large"),
body: t(
"This document has reached the maximum size and can no longer be edited"
),
},
4401: {
title: t("Authentication failed"),
body: t("Please try logging out and back in again"),
},
4403: {
title: t("Authorization failed"),
body: t("You may have lost access to this document, try reloading"),
},
4503: {
title: t("Too many users connected to document"),
body: t("Your edits will sync once other users leave the document"),
},
};
const message = ui.multiplayerErrorCode
? codeToMessage[ui.multiplayerErrorCode]
: undefined;
return ui.multiplayerStatus === "connecting" ||
ui.multiplayerStatus === "disconnected" ? (
<Tooltip
tooltip={
message ? (
<Centered>
<strong>{message.title}</strong>
<br />
{message.body}
</Centered>
) : (
<Centered>
<strong>{t("Server connection lost")}</strong>
<br />
{t("Edits you make will sync once youre online")}
</Centered>
)
<Centered>
<strong>{t("Server connection lost")}</strong>
<br />
{t("Edits you make will sync once youre online")}
</Centered>
}
placement="bottom"
>
+2 -5
View File
@@ -9,7 +9,6 @@ type Props = Omit<React.HTMLAttributes<HTMLSpanElement>, "ref" | "onChange"> & {
readOnly?: boolean;
onClick?: React.MouseEventHandler<HTMLDivElement>;
onChange?: (text: string) => void;
onFocus?: React.FocusEventHandler<HTMLSpanElement> | undefined;
onBlur?: React.FocusEventHandler<HTMLSpanElement> | undefined;
onInput?: React.FormEventHandler<HTMLSpanElement> | undefined;
onKeyDown?: React.KeyboardEventHandler<HTMLSpanElement> | undefined;
@@ -36,7 +35,6 @@ const ContentEditable = React.forwardRef(function _ContentEditable(
disabled,
onChange,
onInput,
onFocus,
onBlur,
onKeyDown,
value,
@@ -145,13 +143,11 @@ const ContentEditable = React.forwardRef(function _ContentEditable(
);
return (
<div className={className} dir={dir} onClick={onClick} tabIndex={-1}>
{children}
<div className={className} dir={dir} onClick={onClick}>
<Content
ref={contentRef}
contentEditable={!disabled && !readOnly}
onInput={wrappedEvent(onInput)}
onFocus={wrappedEvent(onFocus)}
onBlur={wrappedEvent(onBlur)}
onKeyDown={wrappedEvent(onKeyDown)}
onPaste={handlePaste}
@@ -162,6 +158,7 @@ const ContentEditable = React.forwardRef(function _ContentEditable(
>
{innerValue}
</Content>
{children}
</div>
);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { mergeRefs } from "react-merge-refs";
import { MenuItem as BaseMenuItem } from "reakit/Menu";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import MenuIconWrapper from "./MenuIconWrapper";
import MenuIconWrapper from "../MenuIconWrapper";
type Props = {
id?: string;
+1 -1
View File
@@ -9,8 +9,8 @@ import {
MenuStateReturn,
} from "reakit/Menu";
import styled, { useTheme } from "styled-components";
import MenuIconWrapper from "~/components/ContextMenu/MenuIconWrapper";
import Flex from "~/components/Flex";
import MenuIconWrapper from "~/components/MenuIconWrapper";
import { actionToMenuItem } from "~/actions";
import useActionContext from "~/hooks/useActionContext";
import {
+60 -83
View File
@@ -57,6 +57,11 @@ const ContextMenu: React.FC<Props> = ({
...rest
}: Props) => {
const previousVisible = usePrevious(rest.visible);
const maxHeight = useMenuHeight({
visible: rest.visible,
elementRef: rest.unstable_disclosureRef,
});
const backgroundRef = React.useRef<HTMLDivElement>(null);
const { ui } = useStores();
const { t } = useTranslation();
const { setIsMenuOpen } = useMenuContext();
@@ -94,6 +99,21 @@ const ContextMenu: React.FC<Props> = ({
t,
]);
// We must manually manage scroll lock for iOS support so that the scrollable
// element can be passed into body-scroll-lock. See:
// https://github.com/ariakit/ariakit/issues/469
React.useEffect(() => {
const scrollElement = backgroundRef.current;
if (rest.visible && scrollElement && !isSubMenu) {
disableBodyScroll(scrollElement, {
reserveScrollBarGap: true,
});
}
return () => {
scrollElement && !isSubMenu && enableBodyScroll(scrollElement);
};
}, [isSubMenu, rest.visible]);
// Perf win don't render anything until the menu has been opened
if (!rest.visible && !previousVisible) {
return null;
@@ -104,94 +124,51 @@ const ContextMenu: React.FC<Props> = ({
return (
<>
<Menu hideOnClickOutside={!isMobile} preventBodyScroll={false} {...rest}>
{(props) => (
<InnerContextMenu
// eslint-disable-next-line @typescript-eslint/no-explicit-any
menuProps={props as any}
{...rest}
isSubMenu={isSubMenu}
>
{children}
</InnerContextMenu>
)}
{(props) => {
// kind of hacky, but this is an effective way of telling which way
// the menu will _actually_ be placed when taking into account screen
// positioning.
const topAnchor = props.style?.top === "0";
// @ts-expect-error ts-migrate(2339) FIXME: Property 'placement' does not exist on type 'Extra... Remove this comment to see the full error message
const rightAnchor = props.placement === "bottom-end";
return (
<>
{isMobile && (
<Backdrop
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
rest.hide?.();
}}
/>
)}
<Position {...props}>
<Background
dir="auto"
topAnchor={topAnchor}
rightAnchor={rightAnchor}
ref={backgroundRef}
hiddenScrollbars
style={
topAnchor
? {
maxHeight,
}
: undefined
}
>
{rest.visible || rest.animating ? children : null}
</Background>
</Position>
</>
);
}}
</Menu>
</>
);
};
type InnerContextMenuProps = MenuStateReturn & {
isSubMenu: boolean;
menuProps: { style?: React.CSSProperties; placement: string };
children: React.ReactNode;
};
/**
* Inner context menu allows deferring expensive window measurement hooks etc
* until the menu is actually opened.
*/
const InnerContextMenu = (props: InnerContextMenuProps) => {
const { menuProps } = props;
// kind of hacky, but this is an effective way of telling which way
// the menu will _actually_ be placed when taking into account screen
// positioning.
const topAnchor = menuProps.style?.top === "0";
const rightAnchor = menuProps.placement === "bottom-end";
const backgroundRef = React.useRef<HTMLDivElement>(null);
const isMobile = useMobile();
const maxHeight = useMenuHeight({
visible: props.visible,
elementRef: props.unstable_disclosureRef,
});
// We must manually manage scroll lock for iOS support so that the scrollable
// element can be passed into body-scroll-lock. See:
// https://github.com/ariakit/ariakit/issues/469
React.useEffect(() => {
const scrollElement = backgroundRef.current;
if (props.visible && scrollElement && !props.isSubMenu) {
disableBodyScroll(scrollElement, {
reserveScrollBarGap: true,
});
}
return () => {
scrollElement && !props.isSubMenu && enableBodyScroll(scrollElement);
};
}, [props.isSubMenu, props.visible]);
return (
<>
{isMobile && (
<Backdrop
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
props.hide?.();
}}
/>
)}
<Position {...menuProps}>
<Background
dir="auto"
topAnchor={topAnchor}
rightAnchor={rightAnchor}
ref={backgroundRef}
hiddenScrollbars
style={
topAnchor && !isMobile
? {
maxHeight,
}
: undefined
}
>
{props.visible || props.animating ? props.children : null}
</Background>
</Position>
</>
);
};
export default ContextMenu;
export const Backdrop = styled.div`
+1 -8
View File
@@ -15,7 +15,6 @@ import {
templatesPath,
trashPath,
} from "~/utils/routeHelpers";
import EmojiIcon from "./Icons/EmojiIcon";
type Props = {
children?: React.ReactNode;
@@ -106,13 +105,7 @@ const DocumentBreadcrumb: React.FC<Props> = ({
path.forEach((node: NavigationNode) => {
output.push({
type: "route",
title: node.emoji ? (
<>
<EmojiIcon emoji={node.emoji} /> {node.title}
</>
) : (
node.title
),
title: node.title,
to: node.url,
});
});
+3 -3
View File
@@ -111,7 +111,7 @@ function DocumentCard(props: Props) {
{document.emoji ? (
<Squircle color={theme.slateLight}>
<EmojiIcon emoji={document.emoji} size={24} />
<EmojiIcon emoji={document.emoji} size={26} />
</Squircle>
) : (
<Squircle color={collection?.color}>
@@ -279,8 +279,8 @@ const Heading = styled.h3`
overflow: hidden;
color: ${s("text")};
font-family: ${s("fontFamily")};
font-weight: 500;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
`;
export default observer(DocumentCard);
-18
View File
@@ -1,6 +1,5 @@
import * as React from "react";
import { Editor } from "~/editor";
import useIdle from "~/hooks/useIdle";
export type DocumentContextValue = {
/** The current editor instance for this document. */
@@ -17,21 +16,4 @@ const DocumentContext = React.createContext<DocumentContextValue>({
export const useDocumentContext = () => React.useContext(DocumentContext);
const activityEvents = [
"click",
"mousemove",
"DOMMouseScroll",
"mousewheel",
"mousedown",
"touchstart",
"touchmove",
"focus",
];
export const useEditingFocus = () => {
const { editor } = useDocumentContext();
const isIdle = useIdle(3000, activityEvents);
return isIdle && !!editor?.view.hasFocus();
};
export default DocumentContext;
+75 -81
View File
@@ -1,10 +1,5 @@
import FuzzySearch from "fuzzy-search";
import concat from "lodash/concat";
import difference from "lodash/difference";
import fill from "lodash/fill";
import filter from "lodash/filter";
import includes from "lodash/includes";
import map from "lodash/map";
import { includes, difference, concat, filter, map, fill } from "lodash";
import { observer } from "mobx-react";
import { StarredIcon, DocumentIcon } from "outline-icons";
import * as React from "react";
@@ -15,6 +10,7 @@ import scrollIntoView from "smooth-scroll-into-view-if-needed";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { NavigationNode } from "@shared/types";
import parseTitle from "@shared/utils/parseTitle";
import DocumentExplorerNode from "~/components/DocumentExplorerNode";
import DocumentExplorerSearchResult from "~/components/DocumentExplorerSearchResult";
import Flex from "~/components/Flex";
@@ -204,86 +200,84 @@ function DocumentExplorer({ onSubmit, onSelect, items }: Props) {
}
};
const ListItem = observer(
({
index,
data,
style,
}: {
index: number;
data: NavigationNode[];
style: React.CSSProperties;
}) => {
const node = data[index];
const isCollection = node.type === "collection";
let icon, title: string, emoji: string | undefined, path;
const ListItem = ({
index,
data,
style,
}: {
index: number;
data: NavigationNode[];
style: React.CSSProperties;
}) => {
const node = data[index];
const isCollection = node.type === "collection";
let icon, title, path;
if (isCollection) {
const col = collections.get(node.collectionId as string);
icon = col && (
<CollectionIcon collection={col} expanded={isExpanded(index)} />
);
title = node.title;
if (isCollection) {
const col = collections.get(node.collectionId as string);
icon = col && (
<CollectionIcon collection={col} expanded={isExpanded(index)} />
);
title = node.title;
} else {
const doc = documents.get(node.id);
const { strippedTitle, emoji } = parseTitle(node.title);
title = strippedTitle;
if (emoji) {
icon = <EmojiIcon emoji={emoji} />;
} else if (doc?.isStarred) {
icon = <StarredIcon color={theme.yellow} />;
} else {
const doc = documents.get(node.id);
emoji = doc?.emoji ?? node.emoji;
title = doc?.title ?? node.title;
if (emoji) {
icon = <EmojiIcon emoji={emoji} />;
} else if (doc?.isStarred) {
icon = <StarredIcon color={theme.yellow} />;
} else {
icon = <DocumentIcon color={theme.textSecondary} />;
}
path = ancestors(node)
.map((a) => a.title)
.join(" / ");
icon = <DocumentIcon color={theme.textSecondary} />;
}
return searchTerm ? (
<DocumentExplorerSearchResult
selected={isSelected(index)}
active={activeNode === index}
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => toggleSelect(index)}
icon={icon}
title={title}
path={path}
/>
) : (
<DocumentExplorerNode
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => toggleSelect(index)}
onDisclosureClick={(ev) => {
ev.stopPropagation();
toggleCollapse(index);
}}
selected={isSelected(index)}
active={activeNode === index}
expanded={isExpanded(index)}
icon={icon}
title={title}
depth={node.depth as number}
hasChildren={hasChildren(index)}
ref={itemRefs[index]}
/>
);
path = ancestors(node)
.map((a) => parseTitle(a.title).strippedTitle)
.join(" / ");
}
);
return searchTerm ? (
<DocumentExplorerSearchResult
selected={isSelected(index)}
active={activeNode === index}
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => toggleSelect(index)}
icon={icon}
title={title}
path={path}
/>
) : (
<DocumentExplorerNode
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => toggleSelect(index)}
onDisclosureClick={(ev) => {
ev.stopPropagation();
toggleCollapse(index);
}}
selected={isSelected(index)}
active={activeNode === index}
expanded={isExpanded(index)}
icon={icon}
title={title}
depth={node.depth as number}
hasChildren={hasChildren(index)}
ref={itemRefs[index]}
/>
);
};
const focusSearchInput = () => {
inputSearchRef.current?.focus();
+2 -9
View File
@@ -24,7 +24,6 @@ import usePolicy from "~/hooks/usePolicy";
import DocumentMenu from "~/menus/DocumentMenu";
import { hover } from "~/styles";
import { newDocumentPath } from "~/utils/routeHelpers";
import EmojiIcon from "./Icons/EmojiIcon";
type Props = {
document: Document;
@@ -93,12 +92,6 @@ function DocumentListItem(
>
<Content>
<Heading dir={document.dir}>
{document.emoji && (
<>
<EmojiIcon emoji={document.emoji} size={24} />
&nbsp;
</>
)}
<Title
text={document.titleWithDefault}
highlight={highlight}
@@ -269,8 +262,8 @@ const Heading = styled.h3<{ rtl?: boolean }>`
margin-bottom: 0.25em;
white-space: nowrap;
color: ${s("text")};
font-family: ${s("fontFamily")};
font-weight: 500;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
`;
const StarPositioner = styled(Flex)`
+1 -1
View File
@@ -1,4 +1,4 @@
import sortBy from "lodash/sortBy";
import { sortBy } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
+2 -6
View File
@@ -1,6 +1,4 @@
import deburr from "lodash/deburr";
import difference from "lodash/difference";
import sortBy from "lodash/sortBy";
import { deburr, difference, sortBy } from "lodash";
import { observer } from "mobx-react";
import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model";
import { TextSelection } from "prosemirror-state";
@@ -48,7 +46,6 @@ export type Props = Optional<
> & {
shareId?: string | undefined;
embedsDisabled?: boolean;
previewsDisabled?: boolean;
onHeadingsChange?: (headings: Heading[]) => void;
onSynced?: () => Promise<void>;
onPublish?: (event: React.MouseEvent) => any;
@@ -63,7 +60,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
onHeadingsChange,
onCreateCommentMark,
onDeleteCommentMark,
previewsDisabled,
} = props;
const userLocale = useUserLocale();
const locale = dateLocale(userLocale);
@@ -341,7 +337,7 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
userPreferences={preferences}
dictionary={dictionary}
{...props}
onHoverLink={previewsDisabled ? undefined : handleLinkActive}
onHoverLink={handleLinkActive}
onClickLink={handleClickLink}
onSearchLink={handleSearchLink}
onChange={handleChange}
-23
View File
@@ -1,23 +0,0 @@
import styled from "styled-components";
import Button from "~/components/Button";
import { hover } from "~/styles";
import Flex from "../Flex";
export const EmojiButton = styled(Button)`
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
&: ${hover},
&:active,
&[aria-expanded= "true"] {
opacity: 1 !important;
}
`;
export const Emoji = styled(Flex)<{ size?: number }>`
line-height: 1.6;
${(props) => (props.size ? `font-size: ${props.size}px` : "")}
`;
-269
View File
@@ -1,269 +0,0 @@
import data from "@emoji-mart/data";
import Picker from "@emoji-mart/react";
import { SmileyIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { usePopoverState, PopoverDisclosure } from "reakit/Popover";
import styled, { useTheme } from "styled-components";
import { depths, s } from "@shared/styles";
import { toRGB } from "@shared/utils/color";
import Button from "~/components/Button";
import Popover from "~/components/Popover";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import { Emoji, EmojiButton } from "./components";
/* Locales supported by emoji-mart */
const supportedLocales = [
"en",
"ar",
"be",
"cs",
"de",
"es",
"fa",
"fi",
"fr",
"hi",
"it",
"ja",
"kr",
"nl",
"pl",
"pt",
"ru",
"sa",
"tr",
"uk",
"vi",
"zh",
];
/**
* React hook to derive emoji picker's theme from UI theme
*
* @returns {string} Theme to use for emoji picker
*/
function usePickerTheme(): string {
const { ui } = useStores();
const { theme } = ui;
if (theme === "system") {
return "auto";
}
return theme;
}
type Props = {
/** The selected emoji, if any */
value?: string | null;
/** Callback when an emoji is selected */
onChange: (emoji: string | null) => void | Promise<void>;
/** Callback when the picker is opened */
onOpen?: () => void;
/** Callback when the picker is closed */
onClose?: () => void;
/** Callback when the picker is clicked outside of */
onClickOutside: () => void;
/** Whether to auto focus the search input on open */
autoFocus?: boolean;
/** Class name to apply to the trigger button */
className?: string;
};
function EmojiPicker({
value,
onOpen,
onClose,
onChange,
onClickOutside,
autoFocus,
className,
}: Props) {
const { t } = useTranslation();
const pickerTheme = usePickerTheme();
const theme = useTheme();
const locale = useUserLocale(true) ?? "en";
const popover = usePopoverState({
placement: "bottom-start",
modal: true,
unstable_offset: [0, 0],
});
const [emojisPerLine, setEmojisPerLine] = React.useState(9);
const pickerRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
if (popover.visible) {
onOpen?.();
} else {
onClose?.();
}
}, [popover.visible, onOpen, onClose]);
React.useEffect(() => {
if (popover.visible && pickerRef.current) {
// 28 is picker's observed width when perLine is set to 0
// and 36 is the default emojiButtonSize
// Ref: https://github.com/missive/emoji-mart#options--props
setEmojisPerLine(Math.floor((pickerRef.current.clientWidth - 28) / 36));
}
}, [popover.visible]);
const handleEmojiChange = React.useCallback(
async (emoji) => {
popover.hide();
await onChange(emoji ? emoji.native : null);
},
[popover, onChange]
);
const handleClick = React.useCallback(
(ev: React.MouseEvent) => {
ev.stopPropagation();
if (popover.visible) {
popover.hide();
} else {
popover.show();
}
},
[popover]
);
const handleClickOutside = React.useCallback(() => {
// It was observed that onClickOutside got triggered
// even when the picker wasn't open or opened at all.
// Hence, this guard here...
if (popover.visible) {
onClickOutside();
}
}, [popover.visible, onClickOutside]);
// Auto focus search input when picker is opened
React.useLayoutEffect(() => {
if (autoFocus && popover.visible) {
requestAnimationFrame(() => {
const searchInput = pickerRef.current
?.querySelector("em-emoji-picker")
?.shadowRoot?.querySelector(
"input[type=search]"
) as HTMLInputElement | null;
searchInput?.focus();
});
}
}, [autoFocus, popover.visible]);
return (
<>
<PopoverDisclosure {...popover}>
{(props) => (
<EmojiButton
{...props}
className={className}
onClick={handleClick}
icon={
value ? (
<Emoji size={32} align="center" justify="center">
{value}
</Emoji>
) : (
<StyledSmileyIcon size={32} color={theme.textTertiary} />
)
}
neutral
borderOnHover
/>
)}
</PopoverDisclosure>
<PickerPopover
{...popover}
tabIndex={0}
// This prevents picker from closing when any of its
// children are focused, e.g, clicking on search bar or
// a click on skin tone button
onClick={(e) => e.stopPropagation()}
width={352}
aria-label={t("Emoji Picker")}
>
{popover.visible && (
<>
{value && (
<RemoveButton neutral onClick={() => handleEmojiChange(null)}>
{t("Remove")}
</RemoveButton>
)}
<PickerStyles ref={pickerRef}>
<Picker
// https://github.com/missive/emoji-mart/issues/800
locale={
locale === "ko"
? "kr"
: supportedLocales.includes(locale)
? locale
: "en"
}
data={data}
onEmojiSelect={handleEmojiChange}
theme={pickerTheme}
previewPosition="none"
perLine={emojisPerLine}
onClickOutside={handleClickOutside}
/>
</PickerStyles>
</>
)}
</PickerPopover>
</>
);
}
const StyledSmileyIcon = styled(SmileyIcon)`
flex-shrink: 0;
@media print {
display: none;
}
`;
const RemoveButton = styled(Button)`
margin-left: -12px;
margin-bottom: 8px;
border-radius: 6px;
height: 24px;
font-size: 13px;
> :first-child {
min-height: unset;
line-height: unset;
}
`;
const PickerPopover = styled(Popover)`
z-index: ${depths.popover};
> :first-child {
padding-top: 8px;
padding-bottom: 0;
max-height: 488px;
overflow: unset;
}
`;
const PickerStyles = styled.div`
margin-left: -24px;
margin-right: -24px;
em-emoji-picker {
--shadow: none;
--font-family: ${s("fontFamily")};
--rgb-background: ${(props) => toRGB(props.theme.menuBackground)};
--rgb-accent: ${(props) => toRGB(props.theme.accent)};
--border-radius: 6px;
margin-left: auto;
margin-right: auto;
min-height: 443px;
}
`;
export default EmojiPicker;
+1 -1
View File
@@ -80,7 +80,7 @@ const Note = styled(Text)`
margin-bottom: 0;
line-height: 1.2em;
font-size: 14px;
font-weight: 500;
font-weight: 400;
color: ${s("textTertiary")};
`;
+3 -5
View File
@@ -1,4 +1,4 @@
import throttle from "lodash/throttle";
import { throttle } from "lodash";
import { observer } from "mobx-react";
import { MenuIcon } from "outline-icons";
import { transparentize } from "polished";
@@ -6,7 +6,6 @@ import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
import { supportsPassiveListener } from "@shared/utils/browser";
import Button from "~/components/Button";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
@@ -15,16 +14,16 @@ import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
import { draggableOnDesktop, fadeOnDesktopBackgrounded } from "~/styles";
import Desktop from "~/utils/Desktop";
import { supportsPassiveListener } from "~/utils/browser";
type Props = {
left?: React.ReactNode;
title: React.ReactNode;
actions?: React.ReactNode;
hasSidebar?: boolean;
className?: string;
};
function Header({ left, title, actions, hasSidebar, className }: Props) {
function Header({ left, title, actions, hasSidebar }: Props) {
const { ui } = useStores();
const isMobile = useMobile();
const hasMobileSidebar = hasSidebar && isMobile;
@@ -55,7 +54,6 @@ function Header({ left, title, actions, hasSidebar, className }: Props) {
<Wrapper
align="center"
shrink={false}
className={className}
$passThrough={passThrough}
$insetTitleAdjust={ui.sidebarIsClosed && Desktop.hasInsetTitlebar()}
>
+1 -1
View File
@@ -1,4 +1,4 @@
import escapeRegExp from "lodash/escapeRegExp";
import { escapeRegExp } from "lodash";
import * as React from "react";
import replace from "string-replace-to-array";
import styled from "styled-components";
+1 -1
View File
@@ -4,7 +4,7 @@ import styled, { css } from "styled-components";
import { s } from "@shared/styles";
import Text from "~/components/Text";
export const CARD_MARGIN = 10;
export const CARD_MARGIN = 16;
const NUMBER_OF_LINES = 10;
+33 -65
View File
@@ -2,7 +2,7 @@ import { m } from "framer-motion";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
import { depths } from "@shared/styles";
import { depths, s } from "@shared/styles";
import { UnfurlType } from "@shared/types";
import LoadingIndicator from "~/components/LoadingIndicator";
import useEventListener from "~/hooks/useEventListener";
@@ -17,7 +17,7 @@ import HoverPreviewDocument from "./HoverPreviewDocument";
import HoverPreviewLink from "./HoverPreviewLink";
import HoverPreviewMention from "./HoverPreviewMention";
const DELAY_OPEN = 500;
const DELAY_OPEN = 300;
const DELAY_CLOSE = 600;
type Props = {
@@ -27,14 +27,6 @@ type Props = {
onClose: () => void;
};
enum Direction {
UP,
DOWN,
}
const POINTER_HEIGHT = 22;
const POINTER_WIDTH = 22;
function HoverPreviewInternal({ element, onClose }: Props) {
const url = element.href || element.dataset.url;
const [isVisible, setVisible] = React.useState(false);
@@ -44,46 +36,31 @@ function HoverPreviewInternal({ element, onClose }: Props) {
const stores = useStores();
const [cardLeft, setCardLeft] = React.useState(0);
const [cardTop, setCardTop] = React.useState(0);
const [pointerLeft, setPointerLeft] = React.useState(0);
const [pointerTop, setPointerTop] = React.useState(0);
const [pointerDir, setPointerDir] = React.useState(Direction.UP);
const [pointerOffset, setPointerOffset] = React.useState(0);
React.useLayoutEffect(() => {
if (isVisible && cardRef.current) {
const elem = element.getBoundingClientRect();
const card = cardRef.current.getBoundingClientRect();
let cTop = elem.bottom + window.scrollY + CARD_MARGIN;
let pTop = -POINTER_HEIGHT;
let pDir = Direction.UP;
if (cTop + card.height > window.innerHeight + window.scrollY) {
// shift card upwards if it goes out of screen
const bottom = elem.top + window.scrollY;
cTop = bottom - card.height;
// shift a little further to leave some margin between card and element boundary
cTop -= CARD_MARGIN;
// pointer should be shifted downwards to align with card's bottom
pTop = card.height;
pDir = Direction.DOWN;
}
setCardTop(cTop);
setPointerTop(pTop);
setPointerDir(pDir);
const top = elem.bottom + window.scrollY;
setCardTop(top);
let cLeft = elem.left;
let pLeft = elem.width / 2;
if (cLeft + card.width > window.innerWidth) {
let left = elem.left;
let pointerOffset = elem.width / 2;
if (left + card.width > window.innerWidth) {
// shift card leftwards by the amount it went out of screen
let shiftBy = cLeft + card.width - window.innerWidth;
// shift a little further to leave some margin between card and window boundary
let shiftBy = left + card.width - window.innerWidth;
// shift a littler further to leave some margin between card and window boundary
shiftBy += CARD_MARGIN;
cLeft -= shiftBy;
left -= shiftBy;
// shift pointer rightwards by same amount so as to position it back correctly
pLeft += shiftBy;
pointerOffset += shiftBy;
}
setCardLeft(cLeft);
setPointerLeft(pLeft);
setCardLeft(left);
setPointerOffset(pointerOffset);
}
}, [isVisible, element]);
@@ -126,18 +103,18 @@ function HoverPreviewInternal({ element, onClose }: Props) {
useKeyDown("Escape", closePreview);
useEventListener("scroll", closePreview, window, { capture: true });
const stopCloseTimer = React.useCallback(() => {
const stopCloseTimer = () => {
if (timerClose.current) {
clearTimeout(timerClose.current);
timerClose.current = undefined;
}
}, []);
};
const startOpenTimer = React.useCallback(() => {
const startOpenTimer = () => {
if (!timerOpen.current) {
timerOpen.current = setTimeout(() => setVisible(true), DELAY_OPEN);
}
}, []);
};
const startCloseTimer = React.useCallback(() => {
stopOpenTimer();
@@ -172,7 +149,7 @@ function HoverPreviewInternal({ element, onClose }: Props) {
stopCloseTimer();
};
}, [element, startCloseTimer, data, startOpenTimer, stopCloseTimer]);
}, [element, startCloseTimer, data]);
if (loading) {
return <LoadingIndicator />;
@@ -216,11 +193,7 @@ function HoverPreviewInternal({ element, onClose }: Props) {
description={data.description}
/>
)}
<Pointer
top={pointerTop}
left={pointerLeft}
direction={pointerDir}
/>
<Pointer offset={pointerOffset} />
</Animate>
) : null}
</Position>
@@ -244,6 +217,7 @@ const Animate = styled(m.div)`
`;
const Position = styled.div<{ fixed?: boolean; top?: number; left?: number }>`
margin-top: 10px;
position: ${({ fixed }) => (fixed ? "fixed" : "absolute")};
z-index: ${depths.hoverPreview};
display: flex;
@@ -253,11 +227,11 @@ const Position = styled.div<{ fixed?: boolean; top?: number; left?: number }>`
${({ left }) => (left !== undefined ? `left: ${left}px` : "")};
`;
const Pointer = styled.div<{ top: number; left: number; direction: Direction }>`
top: ${(props) => props.top}px;
left: ${(props) => props.left}px;
width: ${POINTER_WIDTH}px;
height: ${POINTER_HEIGHT}px;
const Pointer = styled.div<{ offset: number }>`
top: -22px;
left: ${(props) => props.offset}px;
width: 22px;
height: 22px;
position: absolute;
transform: translateX(-50%);
pointer-events: none;
@@ -267,26 +241,20 @@ const Pointer = styled.div<{ top: number; left: number; direction: Direction }>`
content: "";
display: inline-block;
position: absolute;
${({ direction }) => (direction === Direction.UP ? "bottom: 0" : "top: 0")};
${({ direction }) => (direction === Direction.UP ? "right: 0" : "left: 0")};
bottom: 0;
right: 0;
}
&:before {
border: 8px solid transparent;
${({ direction, theme }) =>
direction === Direction.UP
? `border-bottom-color: ${theme.menuBorder || "rgba(0, 0, 0, 0.1)"}`
: `border-top-color: ${theme.menuBorder || "rgba(0, 0, 0, 0.1)"}`};
${({ direction }) =>
direction === Direction.UP ? "right: -1px" : "left: -1px"};
border-bottom-color: ${(props) =>
props.theme.menuBorder || "rgba(0, 0, 0, 0.1)"};
right: -1px;
}
&:after {
border: 7px solid transparent;
${({ direction, theme }) =>
direction === Direction.UP
? `border-bottom-color: ${theme.menuBackground}`
: `border-top-color: ${theme.menuBackground}`};
border-bottom-color: ${s("menuBackground")};
}
`;
@@ -26,9 +26,9 @@ const HoverPreviewLink = React.forwardRef(function _HoverPreviewLink(
) {
return (
<Preview as="a" href={url} target="_blank" rel="noopener noreferrer">
<Flex column ref={ref}>
<Flex column>
{thumbnailUrl ? <Thumbnail src={thumbnailUrl} alt={""} /> : null}
<Card>
<Card ref={ref}>
<CardContent>
<Flex column>
<Title>{title}</Title>
+1 -1
View File
@@ -29,5 +29,5 @@ const Span = styled.span<{ $size: number }>`
width: ${(props) => props.$size}px;
height: ${(props) => props.$size}px;
text-indent: -0.15em;
font-size: ${(props) => props.$size - 10}px;
font-size: 14px;
`;
+1 -1
View File
@@ -18,7 +18,7 @@ export default function InputSelectPermission(
const handleChange = React.useCallback(
(value) => {
if (value === "no_access") {
value = null;
value = "";
}
onChange?.(value);
+1 -1
View File
@@ -1,4 +1,4 @@
import find from "lodash/find";
import { find } from "lodash";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import styled from "styled-components";
+1 -1
View File
@@ -1,4 +1,4 @@
import times from "lodash/times";
import { times } from "lodash";
import * as React from "react";
import styled from "styled-components";
import Fade from "~/components/Fade";
@@ -1,12 +1,11 @@
import styled from "styled-components";
import { s } from "@shared/styles";
const MenuIconWrapper = styled.span`
width: 24px;
height: 24px;
margin-right: 6px;
margin-left: -4px;
color: ${s("textSecondary")};
color: ${({ theme }) => theme.textSecondary};
`;
export default MenuIconWrapper;
+5 -3
View File
@@ -94,9 +94,11 @@ const Modal: React.FC<Props> = ({
{title}
</Text>
)}
<NudeButton onClick={onRequestClose}>
<CloseIcon />
</NudeButton>
<Text as="span" size="large">
<NudeButton onClick={onRequestClose}>
<CloseIcon />
</NudeButton>
</Text>
</Header>
</Centered>
</Small>
@@ -1,18 +1,19 @@
import { observer } from "mobx-react";
import { SubscribeIcon } from "outline-icons";
import * as React from "react";
import styled from "styled-components";
import styled, { useTheme } from "styled-components";
import { s } from "@shared/styles";
import useStores from "~/hooks/useStores";
import Relative from "../Sidebar/components/Relative";
const NotificationIcon = () => {
const { notifications } = useStores();
const theme = useTheme();
const count = notifications.approximateUnreadCount;
return (
<Relative style={{ height: 24 }}>
<SubscribeIcon />
<SubscribeIcon color={theme.textTertiary} />
{count > 0 && <Badge />}
</Relative>
);
@@ -64,7 +64,6 @@ function NotificationListItem({ notification, onNavigate }: Props) {
{notification.comment && (
<StyledCommentEditor
defaultValue={toJS(notification.comment.data)}
previewsDisabled
/>
)}
</Flex>
+1 -1
View File
@@ -1,4 +1,4 @@
import isEqual from "lodash/isEqual";
import { isEqual } from "lodash";
import { observable, action } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
+1 -1
View File
@@ -1,4 +1,4 @@
import debounce from "lodash/debounce";
import { debounce } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
+13 -29
View File
@@ -1,11 +1,5 @@
import { observer } from "mobx-react";
import {
EditIcon,
SearchIcon,
ShapesIcon,
HomeIcon,
SidebarIcon,
} from "outline-icons";
import { EditIcon, SearchIcon, ShapesIcon, HomeIcon } from "outline-icons";
import * as React from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
@@ -20,7 +14,7 @@ import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import OrganizationMenu from "~/menus/OrganizationMenu";
import { metaDisplay } from "~/utils/keyboard";
import Desktop from "~/utils/Desktop";
import {
homePath,
draftsPath,
@@ -28,23 +22,21 @@ import {
searchPath,
} from "~/utils/routeHelpers";
import TeamLogo from "../TeamLogo";
import Tooltip from "../Tooltip";
import Sidebar from "./Sidebar";
import ArchiveLink from "./components/ArchiveLink";
import Collections from "./components/Collections";
import DragPlaceholder from "./components/DragPlaceholder";
import HeaderButton, { HeaderButtonProps } from "./components/HeaderButton";
import HistoryNavigation from "./components/HistoryNavigation";
import Section from "./components/Section";
import SidebarAction from "./components/SidebarAction";
import SidebarButton, { SidebarButtonProps } from "./components/SidebarButton";
import SidebarLink from "./components/SidebarLink";
import Starred from "./components/Starred";
import ToggleButton from "./components/ToggleButton";
import TrashLink from "./components/TrashLink";
function AppSidebar() {
const { t } = useTranslation();
const { documents, ui } = useStores();
const { documents } = useStores();
const team = useCurrentTeam();
const user = useCurrentUser();
const can = usePolicy(team);
@@ -73,31 +65,23 @@ function AppSidebar() {
<DragPlaceholder />
<OrganizationMenu>
{(props: SidebarButtonProps) => (
<SidebarButton
{(props: HeaderButtonProps) => (
<HeaderButton
{...props}
title={team.name}
image={
<TeamLogo
model={team}
size={24}
size={Desktop.hasInsetTitlebar() ? 24 : 32}
alt={t("Logo")}
style={{ marginLeft: 4 }}
/>
}
>
<Tooltip
tooltip={t("Toggle sidebar")}
shortcut={`${metaDisplay}+.`}
delay={500}
>
<ToggleButton
position="bottom"
image={<SidebarIcon />}
onClick={ui.toggleCollapsedSidebar}
/>
</Tooltip>
</SidebarButton>
style={
// Move the logo over to align with smaller size
Desktop.hasInsetTitlebar() ? { paddingLeft: 8 } : undefined
}
showDisclosure
/>
)}
</OrganizationMenu>
<Scrollable flex shadow>
+1 -2
View File
@@ -120,7 +120,7 @@ const Position = styled(Flex)`
const Sidebar = styled(m.div)<{
$border?: boolean;
}>`
display: block;
display: flex;
flex-shrink: 0;
background: ${s("background")};
max-width: 80%;
@@ -129,7 +129,6 @@ const Sidebar = styled(m.div)<{
z-index: 1;
${breakpoint("mobile", "tablet")`
display: flex;
position: absolute;
top: 0;
right: 0;
+7 -22
View File
@@ -1,6 +1,6 @@
import groupBy from "lodash/groupBy";
import { groupBy } from "lodash";
import { observer } from "mobx-react";
import { BackIcon, SidebarIcon } from "outline-icons";
import { BackIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
@@ -8,21 +8,17 @@ import styled from "styled-components";
import Flex from "~/components/Flex";
import Scrollable from "~/components/Scrollable";
import useSettingsConfig from "~/hooks/useSettingsConfig";
import useStores from "~/hooks/useStores";
import Desktop from "~/utils/Desktop";
import isCloudHosted from "~/utils/isCloudHosted";
import { metaDisplay } from "~/utils/keyboard";
import Tooltip from "../Tooltip";
import Sidebar from "./Sidebar";
import Header from "./components/Header";
import HeaderButton from "./components/HeaderButton";
import HistoryNavigation from "./components/HistoryNavigation";
import Section from "./components/Section";
import SidebarButton from "./components/SidebarButton";
import SidebarLink from "./components/SidebarLink";
import ToggleButton from "./components/ToggleButton";
import Version from "./components/Version";
function SettingsSidebar() {
const { ui } = useStores();
const { t } = useTranslation();
const history = useHistory();
const configs = useSettingsConfig();
@@ -35,23 +31,12 @@ function SettingsSidebar() {
return (
<Sidebar>
<HistoryNavigation />
<SidebarButton
<HeaderButton
title={t("Return to App")}
image={<StyledBackIcon />}
onClick={returnToApp}
>
<Tooltip
tooltip={t("Toggle sidebar")}
shortcut={`${metaDisplay}+.`}
delay={500}
>
<ToggleButton
position="bottom"
image={<SidebarIcon />}
onClick={ui.toggleCollapsedSidebar}
/>
</Tooltip>
</SidebarButton>
minHeight={Desktop.hasInsetTitlebar() ? undefined : 48}
/>
<Flex auto column>
<Scrollable shadow>
+2 -2
View File
@@ -11,9 +11,9 @@ import { homePath, sharedDocumentPath } from "~/utils/routeHelpers";
import { useTeamContext } from "../TeamContext";
import TeamLogo from "../TeamLogo";
import Sidebar from "./Sidebar";
import HeaderButton from "./components/HeaderButton";
import Section from "./components/Section";
import DocumentLink from "./components/SharedDocumentLink";
import SidebarButton from "./components/SidebarButton";
type Props = {
rootNode: NavigationNode;
@@ -28,7 +28,7 @@ function SharedSidebar({ rootNode, shareId }: Props) {
return (
<Sidebar>
{team && (
<SidebarButton
<HeaderButton
title={team.name}
image={<TeamLogo model={team} size={32} alt={t("Logo")} />}
onClick={() =>
+64 -66
View File
@@ -1,8 +1,9 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Portal } from "react-portal";
import { useLocation } from "react-router-dom";
import styled, { css, useTheme } from "styled-components";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
import Flex from "~/components/Flex";
@@ -10,29 +11,29 @@ import useMenuContext from "~/hooks/useMenuContext";
import usePrevious from "~/hooks/usePrevious";
import useStores from "~/hooks/useStores";
import AccountMenu from "~/menus/AccountMenu";
import { fadeOnDesktopBackgrounded } from "~/styles";
import { draggableOnDesktop, fadeOnDesktopBackgrounded } from "~/styles";
import { fadeIn } from "~/styles/animations";
import Desktop from "~/utils/Desktop";
import Avatar from "../Avatar";
import NotificationIcon from "../Notifications/NotificationIcon";
import NotificationsPopover from "../Notifications/NotificationsPopover";
import HeaderButton, { HeaderButtonProps } from "./components/HeaderButton";
import ResizeBorder from "./components/ResizeBorder";
import SidebarButton, { SidebarButtonProps } from "./components/SidebarButton";
import ToggleButton from "./components/ToggleButton";
import Toggle, { ToggleButton, Positioner } from "./components/Toggle";
const ANIMATION_MS = 250;
type Props = {
children: React.ReactNode;
className?: string;
};
const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
{ children, className }: Props,
{ children }: Props,
ref: React.RefObject<HTMLDivElement>
) {
const [isCollapsing, setCollapsing] = React.useState(false);
const theme = useTheme();
const { t } = useTranslation();
const { ui, auth } = useStores();
const location = useLocation();
const previousLocation = usePrevious(location);
@@ -45,7 +46,6 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
const setWidth = ui.setSidebarWidth;
const [offset, setOffset] = React.useState(0);
const [isHovering, setHovering] = React.useState(false);
const [isAnimating, setAnimating] = React.useState(false);
const [isResizing, setResizing] = React.useState(false);
const isSmallerThanMinimum = width < minWidth;
@@ -99,22 +99,6 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
[width]
);
const handlePointerMove = React.useCallback(() => {
setHovering(true);
}, []);
const handlePointerLeave = React.useCallback(
(ev) => {
setHovering(
ev.pageX < width &&
ev.pageX > 0 &&
ev.pageY < window.innerHeight &&
ev.pageY > 0
);
},
[width]
);
React.useEffect(() => {
if (isAnimating) {
setTimeout(() => setAnimating(false), ANIMATION_MS);
@@ -163,19 +147,23 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
[width]
);
const toggleStyle = React.useMemo(
() => ({
right: "auto",
marginLeft: `${collapsed ? theme.sidebarCollapsedWidth : width}px`,
}),
[width, theme.sidebarCollapsedWidth, collapsed]
);
return (
<>
<Container
ref={ref}
style={style}
$isHovering={isHovering}
$isAnimating={isAnimating}
$isSmallerThanMinimum={isSmallerThanMinimum}
$mobileSidebarVisible={ui.mobileSidebarVisible}
$collapsed={collapsed}
className={className}
onPointerMove={handlePointerMove}
onPointerLeave={handlePointerLeave}
column
>
{ui.mobileSidebarVisible && (
@@ -187,32 +175,26 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
{user && (
<AccountMenu>
{(props: SidebarButtonProps) => (
<SidebarButton
{(props: HeaderButtonProps) => (
<HeaderButton
{...props}
showMoreMenu
title={user.name}
position="bottom"
image={
<Avatar
<StyledAvatar
alt={user.name}
model={user}
size={24}
showBorder={false}
style={{ marginLeft: 4 }}
/>
}
>
<NotificationsPopover>
{(rest: SidebarButtonProps) => (
<SidebarButton
{...rest}
position="bottom"
image={<NotificationIcon />}
/>
{(rest: HeaderButtonProps) => (
<HeaderButton {...rest} image={<NotificationIcon />} />
)}
</NotificationsPopover>
</SidebarButton>
</HeaderButton>
)}
</AccountMenu>
)}
@@ -220,11 +202,28 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
onMouseDown={handleMouseDown}
onDoubleClick={ui.sidebarIsClosed ? undefined : handleReset}
/>
{ui.sidebarIsClosed && (
<Toggle
onClick={ui.toggleCollapsedSidebar}
direction={"right"}
aria-label={t("Expand")}
/>
)}
</Container>
<Toggle
style={toggleStyle}
onClick={ui.toggleCollapsedSidebar}
direction={ui.sidebarIsClosed ? "right" : "left"}
aria-label={ui.sidebarIsClosed ? t("Expand") : t("Collapse")}
/>
</>
);
});
const StyledAvatar = styled(Avatar)`
margin-left: 4px;
`;
const Backdrop = styled.a`
animation: ${fadeIn} 250ms ease-in-out;
position: fixed;
@@ -241,33 +240,16 @@ type ContainerProps = {
$mobileSidebarVisible: boolean;
$isAnimating: boolean;
$isSmallerThanMinimum: boolean;
$isHovering: boolean;
$collapsed: boolean;
};
const hoverStyles = (props: ContainerProps) => `
transform: none;
box-shadow: ${
props.$collapsed
? "rgba(0, 0, 0, 0.2) 1px 0 4px"
: props.$isSmallerThanMinimum
? "rgba(0, 0, 0, 0.1) inset -1px 0 2px"
: "none"
};
${ToggleButton} {
opacity: 1;
}
`;
const Container = styled(Flex)<ContainerProps>`
position: fixed;
top: 0;
bottom: 0;
width: 100%;
background: ${s("sidebarBackground")};
transition: box-shadow 100ms ease-in-out, opacity 100ms ease-in-out,
transform 100ms ease-out,
transition: box-shadow 100ms ease-in-out, transform 100ms ease-out,
${s("backgroundTransition")}
${(props: ContainerProps) =>
props.$isAnimating ? `,width ${ANIMATION_MS}ms ease-out` : ""};
@@ -277,17 +259,19 @@ const Container = styled(Flex)<ContainerProps>`
z-index: ${depths.sidebar};
max-width: 80%;
min-width: 280px;
padding-top: ${Desktop.hasInsetTitlebar() ? 36 : 0}px;
${draggableOnDesktop()}
${fadeOnDesktopBackgrounded()}
${Positioner} {
display: none;
}
@media print {
display: none;
transform: none;
}
& > div {
opacity: ${(props) => (props.$collapsed && !props.$isHovering ? "0" : "1")};
}
${breakpoint("tablet")`
margin: 0;
min-width: 0;
@@ -296,14 +280,28 @@ const Container = styled(Flex)<ContainerProps>`
? `calc(-100% + ${Desktop.hasInsetTitlebar() ? 8 : 16}px)`
: 0});
${(props: ContainerProps) => props.$isHovering && css(hoverStyles)}
&:hover,
&:focus-within {
${hoverStyles}
transform: none;
box-shadow: ${(props: ContainerProps) =>
props.$collapsed
? "rgba(0, 0, 0, 0.2) 1px 0 4px"
: props.$isSmallerThanMinimum
? "rgba(0, 0, 0, 0.1) inset -1px 0 2px"
: "none"};
& > div {
${Positioner} {
display: block;
}
${ToggleButton} {
opacity: 1;
}
}
}
&:not(:hover):not(:focus-within) > div {
opacity: ${(props: ContainerProps) => (props.$collapsed ? "0" : "1")};
transition: opacity 100ms ease-in-out;
}
`};
`;
@@ -324,7 +324,6 @@ function InnerDocumentLink(
starred: inStarredSection,
},
}}
emoji={document?.emoji || node.emoji}
label={
<EditableTitle
title={title}
@@ -0,0 +1,102 @@
import { ExpandedIcon, MoreIcon } from "outline-icons";
import * as React from "react";
import styled from "styled-components";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
import { undraggableOnDesktop } from "~/styles";
export type HeaderButtonProps = React.ComponentProps<typeof Button> & {
title: React.ReactNode;
image: React.ReactNode;
minHeight?: number;
rounded?: boolean;
showDisclosure?: boolean;
showMoreMenu?: boolean;
onClick: React.MouseEventHandler<HTMLButtonElement>;
children?: React.ReactNode;
};
const HeaderButton = React.forwardRef<HTMLButtonElement, HeaderButtonProps>(
function _HeaderButton(
{
showDisclosure,
showMoreMenu,
image,
title,
minHeight = 0,
children,
...rest
}: HeaderButtonProps,
ref
) {
return (
<Flex justify="space-between" align="center" shrink={false}>
<Button
{...rest}
minHeight={minHeight}
as="button"
ref={ref}
role="button"
>
<Title gap={8} align="center">
{image}
{title}
</Title>
{showDisclosure && <ExpandedIcon />}
{showMoreMenu && <MoreIcon />}
</Button>
{children}
</Flex>
);
}
);
const Title = styled(Flex)`
color: ${s("text")};
flex-shrink: 1;
flex-grow: 1;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
`;
const Button = styled(Flex)<{ minHeight: number }>`
flex: 1;
color: ${s("textTertiary")};
align-items: center;
padding: 8px 4px;
font-size: 15px;
font-weight: 500;
border-radius: 4px;
margin: 8px 0;
border: 0;
background: none;
flex-shrink: 0;
min-height: ${(props) => props.minHeight}px;
-webkit-appearance: none;
text-decoration: none;
text-align: left;
overflow: hidden;
user-select: none;
cursor: var(--pointer);
${undraggableOnDesktop()}
&:active,
&:hover,
&[aria-expanded="true"] {
color: ${s("sidebarText")};
transition: background 100ms ease-in-out;
background: ${s("sidebarActiveBackground")};
}
&:last-child {
margin-right: 8px;
}
&:first-child {
margin-left: 8px;
}
`;
export default HeaderButton;
@@ -3,12 +3,12 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { isMac } from "@shared/utils/browser";
import Flex from "~/components/Flex";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import useKeyDown from "~/hooks/useKeyDown";
import Desktop from "~/utils/Desktop";
import { isMac } from "~/utils/browser";
function HistoryNavigation(props: React.ComponentProps<typeof Flex>) {
const { t } = useTranslation();
@@ -1,4 +1,3 @@
import includes from "lodash/includes";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -7,14 +6,14 @@ import Collection from "~/models/Collection";
import Document from "~/models/Document";
import useStores from "~/hooks/useStores";
import { sharedDocumentPath } from "~/utils/routeHelpers";
import { descendants } from "~/utils/tree";
import Disclosure from "./Disclosure";
import SidebarLink from "./SidebarLink";
type Props = {
node: NavigationNode;
collection?: Collection;
activeDocumentId?: string;
activeDocument?: Document;
activeDocumentId: string | undefined;
activeDocument: Document | undefined;
isDraft?: boolean;
depth: number;
index: number;
@@ -42,19 +41,10 @@ function DocumentLink(
const hasChildDocuments =
!!node.children.length || activeDocument?.parentDocumentId === node.id;
const document = documents.get(node.id);
const showChildren = React.useMemo(
() =>
!!(
hasChildDocuments &&
((activeDocumentId &&
includes(
descendants(node).map((n) => n.id),
activeDocumentId
)) ||
isActiveDocument ||
depth <= 1)
),
[hasChildDocuments, activeDocumentId, isActiveDocument, depth, node]
() => !!hasChildDocuments,
[hasChildDocuments]
);
const [expanded, setExpanded] = React.useState(showChildren);
@@ -65,6 +55,12 @@ function DocumentLink(
}
}, [showChildren]);
React.useEffect(() => {
if (isActiveDocument) {
setExpanded(true);
}
}, [isActiveDocument]);
const handleDisclosureClick = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
@@ -109,10 +105,14 @@ function DocumentLink(
title: node.title,
},
}}
expanded={hasChildDocuments && depth !== 0 ? expanded : undefined}
onDisclosureClick={handleDisclosureClick}
emoji={node.emoji}
label={title}
label={
<>
{hasChildDocuments && depth !== 0 && (
<Disclosure expanded={expanded} onClick={handleDisclosureClick} />
)}
{title}
</>
}
depth={depth}
exact={false}
scrollIntoViewIfNeeded={!document?.isStarred}
@@ -1,120 +0,0 @@
import { MoreIcon } from "outline-icons";
import * as React from "react";
import styled from "styled-components";
import { extraArea, s } from "@shared/styles";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
import { draggableOnDesktop, undraggableOnDesktop } from "~/styles";
import Desktop from "~/utils/Desktop";
export type SidebarButtonProps = React.ComponentProps<typeof Button> & {
position: "top" | "bottom";
title: React.ReactNode;
image: React.ReactNode;
showMoreMenu?: boolean;
onClick: React.MouseEventHandler<HTMLButtonElement>;
children?: React.ReactNode;
};
const SidebarButton = React.forwardRef<HTMLButtonElement, SidebarButtonProps>(
function _SidebarButton(
{
position = "top",
showMoreMenu,
image,
title,
children,
...rest
}: SidebarButtonProps,
ref
) {
return (
<Container
justify="space-between"
align="center"
shrink={false}
$position={position}
>
<Button
{...rest}
$position={position}
as="button"
ref={ref}
role="button"
>
<Content gap={8} align="center">
{image}
{title && <Title as="span">{title}</Title>}
</Content>
{showMoreMenu && <StyledMoreIcon />}
</Button>
{children}
</Container>
);
}
);
const StyledMoreIcon = styled(MoreIcon)`
flex-shrink: 0;
`;
const Container = styled(Flex)<{ $position: "top" | "bottom" }>`
padding-top: ${(props) =>
props.$position === "top" && Desktop.hasInsetTitlebar() ? 36 : 0}px;
${draggableOnDesktop()}
`;
const Title = styled(Text)`
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const Content = styled(Flex)`
flex-shrink: 1;
flex-grow: 1;
`;
const Button = styled(Flex)<{
$position: "top" | "bottom";
}>`
flex: 1;
color: ${s("textTertiary")};
align-items: center;
padding: 4px;
font-size: 15px;
font-weight: 500;
border-radius: 4px;
border: 0;
margin: ${(props) => (props.$position === "top" ? 16 : 8)}px 0;
background: none;
flex-shrink: 0;
-webkit-appearance: none;
text-decoration: none;
text-align: left;
user-select: none;
cursor: var(--pointer);
position: relative;
${undraggableOnDesktop()}
${extraArea(4)}
&:active,
&:hover,
&[aria-expanded="true"] {
color: ${s("sidebarText")};
transition: background 100ms ease-in-out;
background: ${s("sidebarActiveBackground")};
}
&:last-child {
margin-right: 8px;
}
&:first-child {
margin-left: 8px;
}
`;
export default SidebarButton;
@@ -5,7 +5,6 @@ import breakpoint from "styled-components-breakpoint";
import { s } from "@shared/styles";
import { NavigationNode } from "@shared/types";
import EventBoundary from "~/components/EventBoundary";
import EmojiIcon from "~/components/Icons/EmojiIcon";
import NudeButton from "~/components/NudeButton";
import useUnmount from "~/hooks/useUnmount";
import { undraggableOnDesktop } from "~/styles";
@@ -26,7 +25,6 @@ type Props = Omit<NavLinkProps, "to"> & {
onClickIntent?: () => void;
onDisclosureClick?: React.MouseEventHandler<HTMLButtonElement>;
icon?: React.ReactNode;
emoji?: string | null;
label?: React.ReactNode;
menu?: React.ReactNode;
showActions?: boolean;
@@ -50,7 +48,6 @@ function SidebarLink(
onClick,
onClickIntent,
to,
emoji,
label,
active,
isActiveDrop,
@@ -139,7 +136,6 @@ function SidebarLink(
/>
)}
{icon && <IconWrapper>{icon}</IconWrapper>}
{emoji && <EmojiIcon emoji={emoji} />}
<Label>{label}</Label>
</Content>
</Link>
@@ -156,7 +152,6 @@ const Content = styled.span`
${Disclosure} {
margin-top: 2px;
margin-left: 2px;
}
`;
@@ -297,7 +292,7 @@ const Label = styled.div`
position: relative;
width: 100%;
max-height: 4.8em;
line-height: 24px;
line-height: 1.6;
* {
unicode-bidi: plaintext;
@@ -8,6 +8,7 @@ import { useDrag, useDrop } from "react-dnd";
import { getEmptyImage } from "react-dnd-html5-backend";
import { useLocation } from "react-router-dom";
import styled, { useTheme } from "styled-components";
import parseTitle from "@shared/utils/parseTitle";
import Star from "~/models/Star";
import Fade from "~/components/Fade";
import CollectionIcon from "~/components/Icons/CollectionIcon";
@@ -41,10 +42,14 @@ function useLabelAndIcon({ documentId, collectionId }: Star) {
if (documentId) {
const document = documents.get(documentId);
if (document) {
const { emoji } = parseTitle(document?.title);
return {
label: document.titleWithDefault,
icon: document.emoji ? (
<EmojiIcon emoji={document.emoji} />
label: emoji
? document.title.replace(emoji, "")
: document.titleWithDefault,
icon: emoji ? (
<EmojiIcon emoji={emoji} />
) : (
<StarredIcon color={theme.yellow} />
),
@@ -143,10 +148,6 @@ function StarredLink({ star }: Props) {
return null;
}
const { emoji } = document;
const label = emoji
? document.title.replace(emoji, "")
: document.titleWithDefault;
const collection = document.collectionId
? collections.get(document.collectionId)
: undefined;
@@ -0,0 +1,106 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { s } from "@shared/styles";
import Arrow from "~/components/Arrow";
import useEventListener from "~/hooks/useEventListener";
type Props = {
direction: "left" | "right";
style?: React.CSSProperties;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
};
const Toggle = React.forwardRef<HTMLButtonElement, Props>(function Toggle_(
{ direction = "left", onClick, style }: Props,
ref
) {
const { t } = useTranslation();
const [hovering, setHovering] = React.useState(false);
const positionRef = React.useRef<HTMLDivElement>(null);
// Not using CSS hover here so that we can disable pointer events on this
// div and allow click through to the editor elements behind.
useEventListener("mousemove", (event: MouseEvent) => {
if (!positionRef.current) {
return;
}
const bound = positionRef.current.getBoundingClientRect();
const withinBounds =
event.clientX >= bound.left && event.clientX <= bound.right;
if (withinBounds !== hovering) {
setHovering(withinBounds);
}
});
return (
<Positioner style={style} ref={positionRef} $hovering={hovering}>
<ToggleButton
ref={ref}
$direction={direction}
onClick={onClick}
aria-label={t("Toggle sidebar")}
>
<Arrow />
</ToggleButton>
</Positioner>
);
});
export const ToggleButton = styled.button<{ $direction?: "left" | "right" }>`
opacity: 0;
background: none;
transition: opacity 100ms ease-in-out;
transform: translateY(-50%)
scaleX(${(props) => (props.$direction === "left" ? 1 : -1)});
position: fixed;
top: 50vh;
padding: 8px;
border: 0;
pointer-events: none;
color: ${s("divider")};
&:active {
color: ${s("sidebarText")};
}
${breakpoint("tablet")`
pointer-events: all;
cursor: var(--pointer);
`}
@media (hover: none) {
opacity: 1;
}
`;
export const Positioner = styled.div<{ $hovering: boolean }>`
display: none;
z-index: 2;
position: absolute;
top: 0;
bottom: 0;
right: -30px;
width: 30px;
pointer-events: none;
&:focus-within ${ToggleButton} {
opacity: 1;
}
${(props) =>
props.$hovering &&
css`
${ToggleButton} {
opacity: 1;
}
`}
${breakpoint("tablet")`
display: block;
`}
`;
export default Toggle;
@@ -1,15 +0,0 @@
import styled from "styled-components";
import { hover } from "~/styles";
import SidebarButton from "./SidebarButton";
const ToggleButton = styled(SidebarButton)`
opacity: 0;
transition: opacity 100ms ease-in-out;
&:${hover},
&:active {
opacity: 1;
}
`;
export default ToggleButton;
+2 -13
View File
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import { StarredIcon, UnstarredIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { useTheme } from "styled-components";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
@@ -15,18 +14,12 @@ import { hover } from "~/styles";
import NudeButton from "./NudeButton";
type Props = {
/** Target collection */
collection?: Collection;
/** Target document */
document?: Document;
/** Size of the star */
size?: number;
/** Color override for the star */
color?: string;
};
function Star({ size, document, collection, color, ...rest }: Props) {
const { t } = useTranslation();
function Star({ size, document, collection, ...rest }: Props) {
const theme = useTheme();
const context = useActionContext({
activeDocumentId: document?.id,
@@ -43,10 +36,6 @@ function Star({ size, document, collection, color, ...rest }: Props) {
<NudeButton
context={context}
hideOnActionDisabled
tooltip={{
tooltip: target.isStarred ? t("Unstar document") : t("Star document"),
delay: 500,
}}
action={
collection
? collection.isStarred
@@ -66,7 +55,7 @@ function Star({ size, document, collection, color, ...rest }: Props) {
) : (
<AnimatedStar
size={size}
color={color ?? theme.textTertiary}
color={theme.textTertiary}
as={UnstarredIcon}
/>
)}
+1 -1
View File
@@ -1,4 +1,4 @@
import isEqual from "lodash/isEqual";
import { isEqual } from "lodash";
import { observer } from "mobx-react";
import { CollapsedIcon } from "outline-icons";
import * as React from "react";
+1 -2
View File
@@ -4,8 +4,7 @@ import Avatar from "./Avatar";
const TeamLogo = styled(Avatar)`
border-radius: 4px;
box-shadow: inset 0 0 0 1px ${s("divider")};
border: 0;
border: 1px solid ${s("divider")};
`;
export default TeamLogo;
+8 -13
View File
@@ -1,4 +1,4 @@
import styled, { css } from "styled-components";
import styled from "styled-components";
type Props = {
type?: "secondary" | "tertiary" | "danger";
@@ -14,7 +14,7 @@ type Props = {
*/
const Text = styled.p<Props>`
margin-top: 0;
text-align: ${(props) => (props.dir ? props.dir : "inherit")};
text-align: ${(props) => (props.dir ? props.dir : "initial")};
color: ${(props) =>
props.type === "secondary"
? props.theme.textSecondary
@@ -31,17 +31,12 @@ const Text = styled.p<Props>`
: props.size === "xsmall"
? "13px"
: "inherit"};
${(props) =>
props.weight &&
css`
font-weight: ${props.weight === "bold"
? 500
: props.weight === "normal"
? 400
: "inherit"};
`}
font-weight: ${(props) =>
props.weight === "bold"
? 500
: props.weight === "normal"
? "normal"
: "inherit"};
white-space: normal;
user-select: ${(props) => (props.selectable ? "text" : "none")};
`;
+2 -3
View File
@@ -1,6 +1,5 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import { UserRole } from "@shared/types";
import User from "~/models/User";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import Input from "~/components/Input";
@@ -16,7 +15,7 @@ export function UserChangeToViewerDialog({ user, onSubmit }: Props) {
const { users } = useStores();
const handleSubmit = async () => {
await users.demote(user, UserRole.Viewer);
await users.demote(user, "viewer");
onSubmit();
};
@@ -42,7 +41,7 @@ export function UserChangeToMemberDialog({ user, onSubmit }: Props) {
const { users } = useStores();
const handleSubmit = async () => {
await users.demote(user, UserRole.Member);
await users.demote(user, "member");
onSubmit();
};
+1 -1
View File
@@ -1,5 +1,5 @@
import invariant from "invariant";
import find from "lodash/find";
import { find } from "lodash";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
+15 -20
View File
@@ -1,7 +1,5 @@
import data, { type Emoji as TEmoji, EmojiMartData } from "@emoji-mart/data";
import FuzzySearch from "fuzzy-search";
import capitalize from "lodash/capitalize";
import snakeCase from "lodash/snakeCase";
import gemojies from "gemoji";
import React from "react";
import EmojiMenuItem from "./EmojiMenuItem";
import SuggestionsMenu, {
@@ -16,14 +14,14 @@ type Emoji = {
attrs: { markup: string; "data-name": string };
};
const searcher = new FuzzySearch<TEmoji>(
Object.values((data as EmojiMartData).emojis),
["keywords"],
{
caseSensitive: true,
sort: true,
}
);
const searcher = new FuzzySearch<{
names: string[];
description: string;
emoji: string;
}>(gemojies, ["names"], {
caseSensitive: true,
sort: true,
});
type Props = Omit<
SuggestionsMenuProps<Emoji>,
@@ -36,17 +34,14 @@ const EmojiMenu = (props: Props) => {
const items = React.useMemo(() => {
const n = search.toLowerCase();
const result = searcher.search(n).map((item) => {
// We snake_case the shortcode for backwards compatability with gemoji to
// avoid multiple formats being written into documents.
const shortcode = snakeCase(item.id);
const emoji = item.skins[0].native;
const description = item.description;
const name = item.names[0];
return {
...item,
name: "emoji",
title: emoji,
description: capitalize(item.name.toLowerCase()),
emoji,
attrs: { markup: shortcode, "data-name": shortcode },
title: name,
description,
attrs: { markup: name, "data-name": name },
};
});
+1 -3
View File
@@ -9,7 +9,6 @@ import { Portal } from "~/components/Portal";
import useComponentSize from "~/hooks/useComponentSize";
import useEventListener from "~/hooks/useEventListener";
import useMediaQuery from "~/hooks/useMediaQuery";
import useMobile from "~/hooks/useMobile";
import useViewportHeight from "~/hooks/useViewportHeight";
import Logger from "~/utils/Logger";
import { useEditor } from "./EditorContext";
@@ -41,7 +40,6 @@ function usePosition({
const { selection } = view.state;
const { width: menuWidth, height: menuHeight } = useComponentSize(menuRef);
const viewportHeight = useViewportHeight();
const isMobile = useMobile();
const isTouchDevice = useMediaQuery("(hover: none) and (pointer: coarse)");
if (!active || !menuWidth || !menuHeight || !menuRef.current) {
@@ -50,7 +48,7 @@ function usePosition({
// If we're on a mobile device then stick the floating toolbar to the bottom
// of the screen above the virtual keyboard.
if (isTouchDevice && isMobile && viewportHeight) {
if (isTouchDevice && viewportHeight) {
return {
left: 0,
right: 0,
+2 -2
View File
@@ -1,4 +1,4 @@
import some from "lodash/some";
import { some } from "lodash";
import { EditorState, NodeSelection, TextSelection } from "prosemirror-state";
import * as React from "react";
import createAndInsertLink from "@shared/editor/commands/createAndInsertLink";
@@ -231,7 +231,7 @@ export default function SelectionToolbar(props: Props) {
} else if (rowIndex !== undefined) {
items = getTableRowMenuItems(state, rowIndex, dictionary);
} else if (isImageSelection) {
items = readOnly ? [] : getImageMenuItems(state, dictionary);
items = getImageMenuItems(state, dictionary);
} else if (isDividerSelection) {
items = getDividerMenuItems(state, dictionary);
} else if (readOnly) {
+1 -1
View File
@@ -1,5 +1,5 @@
import commandScore from "command-score";
import capitalize from "lodash/capitalize";
import { capitalize } from "lodash";
import * as React from "react";
import { Trans } from "react-i18next";
import { VisuallyHidden } from "reakit/VisuallyHidden";
-6
View File
@@ -8,10 +8,4 @@ declare global {
const env = window.env;
if (!env) {
throw new Error(
"Config could not be be parsed. \nSee: https://docs.getoutline.com/s/hosting/doc/troubleshooting-HXckrzCqDJ#h-config-could-not-be-parsed"
);
}
export default env;
+1 -1
View File
@@ -1,5 +1,5 @@
import { useRegisterActions } from "kbar";
import flattenDeep from "lodash/flattenDeep";
import { flattenDeep } from "lodash";
import { useLocation } from "react-router-dom";
import { actionToKBar } from "~/actions";
import { Action } from "~/types";
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react";
export default function useDebouncedCallback<T>(
callback: (...params: T[]) => unknown,
wait: number
) {
// track args & timeout handle between calls
const argsRef = React.useRef<T[]>();
const timeout = React.useRef<ReturnType<typeof setTimeout>>();
function cleanup() {
if (timeout.current) {
clearTimeout(timeout.current);
}
}
// make sure our timeout gets cleared if consuming component gets unmounted
React.useEffect(() => cleanup, []);
return function (...args: T[]) {
argsRef.current = args;
cleanup();
timeout.current = setTimeout(() => {
if (argsRef.current) {
callback(...argsRef.current);
}
}, wait);
};
}
+1 -1
View File
@@ -1,4 +1,4 @@
import find from "lodash/find";
import { find } from "lodash";
import * as React from "react";
import embeds, { EmbedDescriptor } from "@shared/editor/embeds";
import { IntegrationType } from "@shared/types";
+37
View File
@@ -0,0 +1,37 @@
import * as React from "react";
type Options = {
fontSize?: string;
lineHeight?: string;
};
/**
* Measures the width of an emoji character
*
* @param emoji The emoji to measure
* @param options Options to pass to the measurement element
* @returns The width of the emoji in pixels
*/
export default function useEmojiWidth(
emoji: string | undefined,
{ fontSize = "2.25em", lineHeight = "1.25" }: Options
) {
return React.useMemo(() => {
const element = window.document.createElement("span");
if (!emoji) {
return 0;
}
element.innerText = `${emoji}\u00A0`;
element.style.visibility = "hidden";
element.style.position = "absolute";
element.style.left = "-9999px";
element.style.lineHeight = lineHeight;
element.style.fontSize = fontSize;
element.style.width = "max-content";
window.document.body?.appendChild(element);
const width = window.getComputedStyle(element).width;
window.document.body?.removeChild(element);
return parseInt(width, 10);
}, [emoji, fontSize, lineHeight]);
}
+6 -10
View File
@@ -1,4 +1,4 @@
import throttle from "lodash/throttle";
import { throttle } from "lodash";
import * as React from "react";
import { Minute } from "@shared/utils/time";
@@ -17,14 +17,10 @@ const activityEvents = [
/**
* Hook to detect user idle state.
*
* @param timeToIdle The time in ms until idle
* @param events The events to listen to
* @param {number} timeToIdle
* @returns boolean if the user is idle
*/
export default function useIdle(
timeToIdle: number = 3 * Minute,
events = activityEvents
) {
export default function useIdle(timeToIdle: number = 3 * Minute) {
const [isIdle, setIsIdle] = React.useState(false);
const timeout = React.useRef<ReturnType<typeof setTimeout>>();
@@ -44,15 +40,15 @@ export default function useIdle(
onActivity();
}, 1000);
events.forEach((eventName) =>
activityEvents.forEach((eventName) =>
window.addEventListener(eventName, handleUserActivityEvent)
);
return () => {
events.forEach((eventName) =>
activityEvents.forEach((eventName) =>
window.removeEventListener(eventName, handleUserActivityEvent)
);
};
}, [events, onActivity]);
}, [onActivity]);
return isIdle;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import noop from "lodash/noop";
import { noop } from "lodash";
import React from "react";
type MenuContextType = {
+1 -1
View File
@@ -1,4 +1,4 @@
import throttle from "lodash/throttle";
import { throttle } from "lodash";
import * as React from "react";
import useEventListener from "./useEventListener";
import useIsMounted from "./useIsMounted";
-31
View File
@@ -1,31 +0,0 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import { QueryNotices } from "@shared/types";
import useQuery from "./useQuery";
import useToasts from "./useToasts";
/**
* Display a toast message based on a notice in the query string. This is usually
* used when redirecting from an external source to the client, such as OAuth,
* or emails.
*/
export default function useQueryNotices() {
const query = useQuery();
const { t } = useTranslation();
const { showToast } = useToasts();
const notice = query.get("notice") as QueryNotices;
React.useEffect(() => {
switch (notice) {
case QueryNotices.UnsubscribeDocument: {
showToast(
t("Unsubscribed from document", {
type: "success",
})
);
break;
}
default:
}
}, [t, showToast, notice]);
}
-40
View File
@@ -1,40 +0,0 @@
import throttle from "lodash/throttle";
import * as React from "react";
import useUnmount from "./useUnmount";
interface ThrottleSettings {
leading?: boolean | undefined;
trailing?: boolean | undefined;
}
const defaultOptions: ThrottleSettings = {
leading: false,
trailing: true,
};
/**
* A hook that returns a throttled callback function.
*
* @param fn The function to throttle
* @param wait The time in ms to wait before calling the function
* @param dependencies The dependencies to watch for changes
* @param options The throttle options
*/
export default function useThrottledCallback<T extends (...args: any[]) => any>(
fn: T,
wait = 250,
dependencies: React.DependencyList = [],
options: ThrottleSettings = defaultOptions
) {
const handler = React.useMemo(
() => throttle<T>(fn, wait, options),
// eslint-disable-next-line react-hooks/exhaustive-deps
dependencies
);
useUnmount(() => {
handler.cancel();
});
return handler;
}
+3 -10
View File
@@ -1,18 +1,11 @@
import useStores from "./useStores";
/**
* Returns the user's locale, or undefined if the user is not logged in.
*
* @param languageCode Whether to only return the language code
* @returns The user's locale, or undefined if the user is not logged in
*/
export default function useUserLocale(languageCode?: boolean) {
export default function useUserLocale() {
const { auth } = useStores();
if (!auth.user?.language) {
if (!auth.user || !auth.user.language) {
return undefined;
}
const { language } = auth.user;
return languageCode ? language.split("_")[0] : language;
return auth.user.language;
}
+2 -2
View File
@@ -1,8 +1,8 @@
// Based on https://github.com/rehooks/window-scroll-position which is no longer
// maintained.
import throttle from "lodash/throttle";
import { throttle } from "lodash";
import { useState, useEffect } from "react";
import { supportsPassiveListener } from "@shared/utils/browser";
import { supportsPassiveListener } from "~/utils/browser";
const getPosition = () => ({
x: window.pageXOffset,
+12 -15
View File
@@ -1,6 +1,6 @@
import * as React from "react";
import useDebouncedCallback from "./useDebouncedCallback";
import useEventListener from "./useEventListener";
import useThrottledCallback from "./useThrottledCallback";
/**
* A debounced hook that listens to the window resize event and returns the
@@ -14,25 +14,22 @@ export default function useWindowSize() {
height: window.innerHeight,
});
const handleResize = useThrottledCallback(() => {
setWindowSize((state) => {
if (
window.innerWidth === state.width &&
window.innerHeight === state.height
) {
return state;
}
return { width: window.innerWidth, height: window.innerHeight };
});
const handleResize = useDebouncedCallback(() => {
if (
window.innerWidth !== windowSize.width ||
window.innerHeight !== windowSize.height
) {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
}, 100);
useEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
React.useEffect(() => {
handleResize();
}, [handleResize]);
handleResize();
return windowSize;
}
+3 -3
View File
@@ -40,7 +40,7 @@ import {
openDocumentComments,
} from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
import useCurrentUser from "~/hooks/useCurrentUser";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useMobile from "~/hooks/useMobile";
import usePolicy from "~/hooks/usePolicy";
import useRequest from "~/hooks/useRequest";
@@ -73,7 +73,7 @@ function DocumentMenu({
onOpen,
onClose,
}: Props) {
const user = useCurrentUser();
const team = useCurrentTeam();
const { policies, collections, documents, subscriptions } = useStores();
const { showToast } = useToasts();
const menu = useMenuState({
@@ -263,7 +263,7 @@ function DocumentMenu({
type: "route",
title: t("Edit"),
to: documentEditPath(document),
visible: !!can.update && user.separateEditMode,
visible: !!can.update && !team.seamlessEditing,
icon: <EditIcon />,
},
{
+1 -1
View File
@@ -1,4 +1,4 @@
import pick from "lodash/pick";
import { pick } from "lodash";
import { set, observable } from "mobx";
import Logger from "~/utils/Logger";
import { getFieldsForModel } from "./decorators/Field";
+1 -1
View File
@@ -1,4 +1,4 @@
import trim from "lodash/trim";
import { trim } from "lodash";
import { action, computed, observable, reaction, runInAction } from "mobx";
import {
CollectionPermission,
+8 -8
View File
@@ -1,9 +1,10 @@
import { addDays, differenceInDays } from "date-fns";
import floor from "lodash/floor";
import { floor } from "lodash";
import { action, autorun, computed, observable, set } from "mobx";
import { ExportContentType } from "@shared/types";
import type { NavigationNode } from "@shared/types";
import Storage from "@shared/utils/Storage";
import parseTitle from "@shared/utils/parseTitle";
import { isRTL } from "@shared/utils/rtl";
import DocumentsStore from "~/stores/DocumentsStore";
import User from "~/models/User";
@@ -67,13 +68,6 @@ export default class Document extends ParanoidModel {
@observable
title: string;
/**
* An emoji to use as the document icon.
*/
@Field
@observable
emoji: string | undefined | null;
/**
* Whether this is a template.
*/
@@ -133,6 +127,12 @@ export default class Document extends ParanoidModel {
revision: number;
@computed
get emoji() {
const { emoji } = parseTitle(this.title);
return emoji;
}
/**
* Returns the direction of the document text, either "rtl" or "ltr"
*/
-3
View File
@@ -14,9 +14,6 @@ class Revision extends BaseModel {
/** Markdown string of the content when revision was created */
text: string;
/** The emoji of the document when the revision was created */
emoji: string | null;
/** HTML string representing the revision as a diff from the previous version */
html: string;
+13 -8
View File
@@ -81,6 +81,17 @@ class Team extends BaseModel {
return this.name ? this.name[0] : "?";
}
/**
* Returns whether this team is using a separate editing mode behind an "Edit"
* button rather than seamless always-editing.
*
* @returns True if editing mode is seamless (no button)
*/
@computed
get seamlessEditing(): boolean {
return !!this.getPreference(TeamPreference.SeamlessEdit);
}
/**
* Returns the value of the provided preference.
*
@@ -88,15 +99,9 @@ class Team extends BaseModel {
* @returns The preference value if set, else the default value
*/
getPreference<T extends keyof TeamPreferences>(
key: T,
defaultValue?: TeamPreferences[T]
key: T
): TeamPreferences[T] | false {
return (
this.preferences?.[key] ??
TeamPreferenceDefaults[key] ??
defaultValue ??
false
);
return this.preferences?.[key] ?? TeamPreferenceDefaults[key] ?? false;
}
/**
+7 -25
View File
@@ -5,12 +5,10 @@ import { UserPreferenceDefaults } from "@shared/constants";
import {
NotificationEventDefaults,
NotificationEventType,
TeamPreference,
UserPreference,
UserPreferences,
UserRole,
} from "@shared/types";
import type { NotificationSettings } from "@shared/types";
import type { Role, NotificationSettings } from "@shared/types";
import { client } from "~/utils/ApiClient";
import ParanoidModel from "./ParanoidModel";
import Field from "./decorators/Field";
@@ -76,30 +74,16 @@ class User extends ParanoidModel {
}
@computed
get role(): UserRole {
get role(): Role {
if (this.isAdmin) {
return UserRole.Admin;
return "admin";
} else if (this.isViewer) {
return UserRole.Viewer;
return "viewer";
} else {
return UserRole.Member;
return "member";
}
}
/**
* Returns whether this user is using a separate editing mode behind an "Edit"
* button rather than seamless always-editing.
*
* @returns True if editing mode is seamless (no button)
*/
@computed
get separateEditMode(): boolean {
return !this.getPreference(
UserPreference.SeamlessEdit,
this.store.rootStore.auth.team.getPreference(TeamPreference.SeamlessEdit)
);
}
/**
* Returns the current preference for the given notification event type taking
* into account the default system value.
@@ -145,10 +129,8 @@ class User extends ParanoidModel {
* @param key The UserPreference key to retrieve
* @returns The value
*/
getPreference(key: UserPreference, defaultValue = false): boolean {
return (
this.preferences?.[key] ?? UserPreferenceDefaults[key] ?? defaultValue
);
getPreference(key: UserPreference): boolean {
return this.preferences?.[key] ?? UserPreferenceDefaults[key] ?? false;
}
/**
-3
View File
@@ -4,7 +4,6 @@ import DesktopRedirect from "~/scenes/DesktopRedirect";
import DelayedMount from "~/components/DelayedMount";
import FullscreenLoading from "~/components/FullscreenLoading";
import Route from "~/components/ProfiledRoute";
import useQueryNotices from "~/hooks/useQueryNotices";
import lazyWithRetry from "~/utils/lazyWithRetry";
import { matchDocumentSlug as slug } from "~/utils/routeHelpers";
@@ -15,8 +14,6 @@ const Login = lazyWithRetry(() => import("~/scenes/Login"));
const Logout = lazyWithRetry(() => import("~/scenes/Logout"));
export default function Routes() {
useQueryNotices();
return (
<React.Suspense
fallback={
+31 -2
View File
@@ -26,6 +26,7 @@ import PaginatedDocumentList from "~/components/PaginatedDocumentList";
import PinnedDocuments from "~/components/PinnedDocuments";
import PlaceholderText from "~/components/PlaceholderText";
import Scene from "~/components/Scene";
import Star, { AnimatedStar } from "~/components/Star";
import Tab from "~/components/Tab";
import Tabs from "~/components/Tabs";
import Tooltip from "~/components/Tooltip";
@@ -156,7 +157,7 @@ function CollectionScene() {
<Empty collection={collection} />
) : (
<>
<HeadingWithIcon>
<HeadingWithIcon $isStarred={collection.isStarred}>
<HeadingIcon collection={collection} size={40} expanded />
{collection.name}
{collection.isPrivate && (
@@ -169,6 +170,7 @@ function CollectionScene() {
<Badge>{t("Private")}</Badge>
</Tooltip>
)}
<StarButton collection={collection} size={32} />
</HeadingWithIcon>
<CollectionDescription collection={collection} />
@@ -283,15 +285,42 @@ function CollectionScene() {
);
}
const StarButton = styled(Star)`
position: relative;
top: 0;
left: 10px;
overflow: hidden;
width: 24px;
svg {
position: relative;
left: -4px;
}
`;
const Documents = styled.div`
position: relative;
background: ${s("background")};
`;
const HeadingWithIcon = styled(Heading)`
const HeadingWithIcon = styled(Heading)<{ $isStarred: boolean }>`
display: flex;
align-items: center;
${AnimatedStar} {
opacity: ${(props) => (props.$isStarred ? "1 !important" : 0)};
}
&:hover {
${AnimatedStar} {
opacity: 0.5;
&:hover {
opacity: 1;
}
}
}
${breakpoint("tablet")`
margin-left: -40px;
`};
+1 -1
View File
@@ -1,4 +1,4 @@
import sortBy from "lodash/sortBy";
import { sortBy } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
+1 -2
View File
@@ -1,4 +1,4 @@
import intersection from "lodash/intersection";
import { intersection } from "lodash";
import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
@@ -56,7 +56,6 @@ class CollectionNew extends React.Component<Props> {
icon: this.icon,
color: this.color,
permission: this.permission,
documents: [],
},
this.props.collections
);
@@ -1,4 +1,4 @@
import debounce from "lodash/debounce";
import { debounce } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -13,8 +13,8 @@ import PaginatedList from "~/components/PaginatedList";
import Text from "~/components/Text";
import useBoolean from "~/hooks/useBoolean";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useDebouncedCallback from "~/hooks/useDebouncedCallback";
import useStores from "~/hooks/useStores";
import useThrottledCallback from "~/hooks/useThrottledCallback";
import useToasts from "~/hooks/useToasts";
import MemberListItem from "./components/MemberListItem";
@@ -31,7 +31,12 @@ function AddPeopleToCollection({ collection }: Props) {
useBoolean();
const [query, setQuery] = React.useState("");
const debouncedFetch = useThrottledCallback(
const handleFilter = (ev: React.ChangeEvent<HTMLInputElement>) => {
setQuery(ev.target.value);
debouncedFetch(ev.target.value);
};
const debouncedFetch = useDebouncedCallback(
(query) =>
users.fetchPage({
query,
@@ -39,11 +44,6 @@ function AddPeopleToCollection({ collection }: Props) {
250
);
const handleFilter = (ev: React.ChangeEvent<HTMLInputElement>) => {
setQuery(ev.target.value);
void debouncedFetch(ev.target.value);
};
const handleAddUser = async (user: User) => {
try {
await memberships.create({
@@ -1,4 +1,4 @@
import throttle from "lodash/throttle";
import { throttle } from "lodash";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -72,7 +72,7 @@ function DataLoader({ match, children }: Props) {
? documents.getSharedTree(document.id)
: undefined;
const isEditRoute = match.path === matchDocumentEdit;
const isEditing = isEditRoute || !auth.user?.separateEditMode;
const isEditing = isEditRoute || !!auth.team?.seamlessEditing;
const can = usePolicy(document?.id);
const location = useLocation<LocationState>();
+8 -14
View File
@@ -1,4 +1,4 @@
import debounce from "lodash/debounce";
import { debounce } from "lodash";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
import { AllSelection } from "prosemirror-state";
@@ -354,7 +354,7 @@ class DocumentScene extends React.Component<Props> {
this.isUploading = false;
};
handleChange = (getEditorText: () => string) => {
onChange = (getEditorText: () => string) => {
const { document } = this.props;
this.getEditorText = getEditorText;
@@ -369,19 +369,13 @@ class DocumentScene extends React.Component<Props> {
this.headings = headings;
};
handleChangeTitle = action((value: string) => {
onChangeTitle = action((value: string) => {
this.title = value;
this.props.document.title = value;
this.updateIsDirty();
void this.autosave();
});
handleChangeEmoji = action((value: string) => {
this.props.document.emoji = value;
this.updateIsDirty();
void this.autosave();
});
goBack = () => {
if (!this.props.readOnly) {
this.props.history.push(this.props.document.url);
@@ -391,7 +385,7 @@ class DocumentScene extends React.Component<Props> {
render() {
const { document, revision, readOnly, abilities, auth, ui, shareId, t } =
this.props;
const { team, user } = auth;
const team = auth.team;
const isShare = !!shareId;
const embedsDisabled =
(team && team.documentEmbeds === false) || document.embedsDisabled;
@@ -463,7 +457,7 @@ class DocumentScene extends React.Component<Props> {
revision={revision}
shareId={shareId}
isDraft={document.isDraft}
isEditing={!readOnly && !!user?.separateEditMode}
isEditing={!readOnly && !team?.seamlessEditing}
isSaving={this.isSaving}
isPublishing={this.isPublishing}
publishingIsDisabled={
@@ -488,6 +482,7 @@ class DocumentScene extends React.Component<Props> {
<Flex auto={!readOnly} reverse>
{revision ? (
<RevisionViewer
isDraft={document.isDraft}
document={document}
revision={revision}
id={revision.id}
@@ -511,9 +506,8 @@ class DocumentScene extends React.Component<Props> {
onFileUploadStop={this.onFileUploadStop}
onSearchLink={this.props.onSearchLink}
onCreateLink={this.props.onCreateLink}
onChangeTitle={this.handleChangeTitle}
onChangeEmoji={this.handleChangeEmoji}
onChange={this.handleChange}
onChangeTitle={this.onChangeTitle}
onChange={this.onChange}
onHeadingsChange={this.onHeadingsChange}
onSave={this.onSave}
onPublish={this.onPublish}
@@ -1,356 +0,0 @@
import { observer } from "mobx-react";
import { Slice } from "prosemirror-model";
import { Selection } from "prosemirror-state";
import { __parseFromClipboard } from "prosemirror-view";
import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import isMarkdown from "@shared/editor/lib/isMarkdown";
import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize";
import { extraArea, s } from "@shared/styles";
import { light } from "@shared/styles/theme";
import {
getCurrentDateAsString,
getCurrentDateTimeAsString,
getCurrentTimeAsString,
} from "@shared/utils/date";
import { DocumentValidation } from "@shared/validations";
import ContentEditable, { RefHandle } from "~/components/ContentEditable";
import { useDocumentContext } from "~/components/DocumentContext";
import { Emoji, EmojiButton } from "~/components/EmojiPicker/components";
import Flex from "~/components/Flex";
import useBoolean from "~/hooks/useBoolean";
import usePolicy from "~/hooks/usePolicy";
import { isModKey } from "~/utils/keyboard";
const EmojiPicker = React.lazy(() => import("~/components/EmojiPicker"));
type Props = {
/** ID of the associated document */
documentId: string;
/** Document to display */
title: string;
/** Emoji to display */
emoji?: string | null;
/** Placeholder to display when the document has no title */
placeholder?: string;
/** Should the title be editable, policies will also be considered separately */
readOnly?: boolean;
/** Callback called on any edits to text */
onChangeTitle?: (text: string) => void;
/** Callback called when the user selects an emoji */
onChangeEmoji?: (emoji: string | null) => void;
/** Callback called when the user expects to move to the "next" input */
onGoToNextInput?: (insertParagraph?: boolean) => void;
/** Callback called when the user expects to save (CMD+S) */
onSave?: (options: { publish?: boolean; done?: boolean }) => void;
/** Callback called when focus leaves the input */
onBlur?: React.FocusEventHandler<HTMLSpanElement>;
};
const lineHeight = "1.25";
const fontSize = "2.25em";
const DocumentTitle = React.forwardRef(function _DocumentTitle(
{
documentId,
title,
emoji,
readOnly,
onChangeTitle,
onChangeEmoji,
onSave,
onGoToNextInput,
onBlur,
placeholder,
}: Props,
externalRef: React.RefObject<RefHandle>
) {
const ref = React.useRef<RefHandle>(null);
const [emojiPickerIsOpen, handleOpen, handleClose] = useBoolean();
const { editor } = useDocumentContext();
const can = usePolicy(documentId);
const handleClick = React.useCallback(() => {
ref.current?.focus();
}, [ref]);
const restoreFocus = React.useCallback(() => {
ref.current?.focusAtEnd();
}, [ref]);
const handleBlur = React.useCallback(
(ev: React.FocusEvent<HTMLSpanElement>) => {
// Do nothing and simply return if the related target is the parent
// or a sibling of the current target element(the <span>
// containing document title)
if (
ev.currentTarget.parentElement === ev.relatedTarget ||
(ev.relatedTarget &&
ev.currentTarget.parentElement === ev.relatedTarget.parentElement)
) {
return;
}
if (onBlur) {
onBlur(ev);
}
},
[onBlur]
);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent) => {
if (event.nativeEvent.isComposing) {
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (isModKey(event)) {
onSave?.({
done: true,
});
return;
}
onGoToNextInput?.(true);
return;
}
if (event.key === "Tab" || event.key === "ArrowDown") {
event.preventDefault();
onGoToNextInput?.();
return;
}
if (event.key === "p" && isModKey(event) && event.shiftKey) {
event.preventDefault();
onSave?.({
publish: true,
done: true,
});
return;
}
if (event.key === "s" && isModKey(event)) {
event.preventDefault();
onSave?.({});
return;
}
},
[onGoToNextInput, onSave]
);
const handleChange = React.useCallback(
(value: string) => {
let title = value;
if (/\/date\s$/.test(value)) {
title = getCurrentDateAsString();
ref?.current?.focusAtEnd();
} else if (/\/time$/.test(value)) {
title = getCurrentTimeAsString();
ref?.current?.focusAtEnd();
} else if (/\/datetime$/.test(value)) {
title = getCurrentDateTimeAsString();
ref?.current?.focusAtEnd();
}
onChangeTitle?.(title);
},
[ref, onChangeTitle]
);
// Custom paste handling so that if a multiple lines are pasted we
// only take the first line and insert the rest directly into the editor.
const handlePaste = React.useCallback(
(event: React.ClipboardEvent) => {
event.preventDefault();
const text = event.clipboardData.getData("text/plain");
const html = event.clipboardData.getData("text/html");
const [firstLine, ...rest] = text.split(`\n`);
const content = rest.join(`\n`).trim();
window.document.execCommand(
"insertText",
false,
firstLine.replace(/^#+\s?/, "")
);
if (editor && content) {
const { view, pasteParser } = editor;
let slice;
if (isMarkdown(text)) {
const paste = pasteParser.parse(normalizePastedMarkdown(content));
if (paste) {
slice = paste.slice(0);
}
} else {
const defaultSlice = __parseFromClipboard(
view,
text,
html,
false,
view.state.selection.$from
);
// remove first node from slice
slice = defaultSlice.content.firstChild
? new Slice(
defaultSlice.content.cut(
defaultSlice.content.firstChild.nodeSize
),
defaultSlice.openStart,
defaultSlice.openEnd
)
: defaultSlice;
}
if (slice) {
view.dispatch(
view.state.tr
.setSelection(Selection.atStart(view.state.doc))
.replaceSelection(slice)
);
}
}
},
[editor]
);
const handleEmojiChange = React.useCallback(
async (value: string | null) => {
// Restore focus on title
restoreFocus();
if (emoji !== value) {
onChangeEmoji?.(value);
}
},
[emoji, onChangeEmoji, restoreFocus]
);
const dir = ref.current?.getComputedDirection();
const emojiIcon = <Emoji size={32}>{emoji}</Emoji>;
return (
<Title
onClick={handleClick}
onChange={handleChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onBlur={handleBlur}
placeholder={placeholder}
value={title}
$emojiPickerIsOpen={emojiPickerIsOpen}
$containsEmoji={!!emoji}
autoFocus={!document.title}
maxLength={DocumentValidation.maxTitleLength}
readOnly={readOnly}
dir="auto"
ref={mergeRefs([ref, externalRef])}
>
{can.update && !readOnly ? (
<EmojiWrapper align="center" justify="center" dir={dir}>
<React.Suspense fallback={emojiIcon}>
<StyledEmojiPicker
value={emoji}
onChange={handleEmojiChange}
onOpen={handleOpen}
onClose={handleClose}
onClickOutside={restoreFocus}
autoFocus
/>
</React.Suspense>
</EmojiWrapper>
) : emoji ? (
<EmojiWrapper align="center" justify="center" dir={dir}>
{emojiIcon}
</EmojiWrapper>
) : null}
</Title>
);
});
const StyledEmojiPicker = styled(EmojiPicker)`
${extraArea(8)}
`;
const EmojiWrapper = styled(Flex)<{ dir?: string }>`
position: absolute;
top: 8px;
${(props) => (props.dir === "rtl" ? "right: -40px" : "left: -40px")};
height: 32px;
width: 32px;
`;
type TitleProps = {
$containsEmoji: boolean;
$emojiPickerIsOpen: boolean;
};
const Title = styled(ContentEditable)<TitleProps>`
position: relative;
line-height: ${lineHeight};
margin-top: 1em;
margin-bottom: 0.5em;
margin-left: ${(props) =>
props.$containsEmoji || props.$emojiPickerIsOpen ? "40px" : "0px"};
font-size: ${fontSize};
font-weight: 500;
border: 0;
padding: 0;
cursor: ${(props) => (props.readOnly ? "default" : "text")};
> span {
outline: none;
}
&::placeholder {
color: ${s("placeholder")};
-webkit-text-fill-color: ${s("placeholder")};
}
&:focus-within,
&:focus {
margin-left: 40px;
${EmojiButton} {
opacity: 1 !important;
}
}
${EmojiButton} {
opacity: ${(props: TitleProps) =>
props.$containsEmoji ? "1 !important" : 0};
}
${breakpoint("tablet")`
margin-left: 0;
&:focus-within,
&:focus {
margin-left: 0;
}
&:hover {
${EmojiButton} {
opacity: 0.5;
&:hover {
opacity: 1;
}
}
}`};
@media print {
color: ${light.text};
-webkit-text-fill-color: ${light.text};
background: none;
}
`;
export default observer(DocumentTitle);
@@ -0,0 +1,278 @@
import { observer } from "mobx-react";
import { Slice } from "prosemirror-model";
import { Selection } from "prosemirror-state";
import { __parseFromClipboard } from "prosemirror-view";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import isMarkdown from "@shared/editor/lib/isMarkdown";
import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize";
import { s } from "@shared/styles";
import { light } from "@shared/styles/theme";
import {
getCurrentDateAsString,
getCurrentDateTimeAsString,
getCurrentTimeAsString,
} from "@shared/utils/date";
import { DocumentValidation } from "@shared/validations";
import Document from "~/models/Document";
import ContentEditable, { RefHandle } from "~/components/ContentEditable";
import { useDocumentContext } from "~/components/DocumentContext";
import Star, { AnimatedStar } from "~/components/Star";
import useEmojiWidth from "~/hooks/useEmojiWidth";
import { isModKey } from "~/utils/keyboard";
type Props = {
document: Document;
/** Placeholder to display when the document has no title */
placeholder: string;
/** Should the title be editable, policies will also be considered separately */
readOnly?: boolean;
/** Whether the title show the option to star, policies will also be considered separately (defaults to true) */
starrable?: boolean;
/** Callback called on any edits to text */
onChange: (text: string) => void;
/** Callback called when the user expects to move to the "next" input */
onGoToNextInput: (insertParagraph?: boolean) => void;
/** Callback called when the user expects to save (CMD+S) */
onSave?: (options: { publish?: boolean; done?: boolean }) => void;
/** Callback called when focus leaves the input */
onBlur?: React.FocusEventHandler<HTMLSpanElement>;
};
const lineHeight = "1.25";
const fontSize = "2.25em";
const EditableTitle = React.forwardRef(
(
{
document,
readOnly,
onChange,
onSave,
onGoToNextInput,
onBlur,
starrable,
placeholder,
}: Props,
ref: React.RefObject<RefHandle>
) => {
const { editor } = useDocumentContext();
const handleClick = React.useCallback(() => {
ref.current?.focus();
}, [ref]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent) => {
if (event.nativeEvent.isComposing) {
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (isModKey(event)) {
onSave?.({
done: true,
});
return;
}
onGoToNextInput(true);
return;
}
if (event.key === "Tab" || event.key === "ArrowDown") {
event.preventDefault();
onGoToNextInput();
return;
}
if (event.key === "p" && isModKey(event) && event.shiftKey) {
event.preventDefault();
onSave?.({
publish: true,
done: true,
});
return;
}
if (event.key === "s" && isModKey(event)) {
event.preventDefault();
onSave?.({});
return;
}
},
[onGoToNextInput, onSave]
);
const handleChange = React.useCallback(
(text: string) => {
if (/\/date\s$/.test(text)) {
onChange(getCurrentDateAsString());
ref.current?.focusAtEnd();
} else if (/\/time$/.test(text)) {
onChange(getCurrentTimeAsString());
ref.current?.focusAtEnd();
} else if (/\/datetime$/.test(text)) {
onChange(getCurrentDateTimeAsString());
ref.current?.focusAtEnd();
} else {
onChange(text);
}
},
[ref, onChange]
);
// Custom paste handling so that if a multiple lines are pasted we
// only take the first line and insert the rest directly into the editor.
const handlePaste = React.useCallback(
(event: React.ClipboardEvent) => {
event.preventDefault();
const text = event.clipboardData.getData("text/plain");
const html = event.clipboardData.getData("text/html");
const [firstLine, ...rest] = text.split(`\n`);
const content = rest.join(`\n`).trim();
window.document.execCommand(
"insertText",
false,
firstLine.replace(/^#+\s?/, "")
);
if (editor && content) {
const { view, pasteParser } = editor;
let slice;
if (isMarkdown(text)) {
const paste = pasteParser.parse(normalizePastedMarkdown(content));
if (paste) {
slice = paste.slice(0);
}
} else {
const defaultSlice = __parseFromClipboard(
view,
text,
html,
false,
view.state.selection.$from
);
// remove first node from slice
slice = defaultSlice.content.firstChild
? new Slice(
defaultSlice.content.cut(
defaultSlice.content.firstChild.nodeSize
),
defaultSlice.openStart,
defaultSlice.openEnd
)
: defaultSlice;
}
if (slice) {
view.dispatch(
view.state.tr
.setSelection(Selection.atStart(view.state.doc))
.replaceSelection(slice)
);
}
}
},
[editor]
);
const emojiWidth = useEmojiWidth(document.emoji, {
fontSize,
lineHeight,
});
const value =
!document.title && readOnly ? document.titleWithDefault : document.title;
return (
<Title
onClick={handleClick}
onChange={handleChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onBlur={onBlur}
placeholder={placeholder}
value={value}
$emojiWidth={emojiWidth}
$isStarred={document.isStarred}
autoFocus={!document.title}
maxLength={DocumentValidation.maxTitleLength}
readOnly={readOnly}
dir="auto"
ref={ref}
>
{starrable !== false && <StarButton document={document} size={32} />}
</Title>
);
}
);
const StarButton = styled(Star)`
position: relative;
top: 4px;
left: 10px;
overflow: hidden;
width: 24px;
svg {
position: relative;
left: -4px;
}
`;
type TitleProps = {
$isStarred: boolean;
$emojiWidth: number;
};
const Title = styled(ContentEditable)<TitleProps>`
line-height: ${lineHeight};
margin-top: 1em;
margin-bottom: 0.5em;
font-size: ${fontSize};
font-weight: 500;
border: 0;
padding: 0;
cursor: ${(props) => (props.readOnly ? "default" : "text")};
> span {
outline: none;
}
&::placeholder {
color: ${s("placeholder")};
-webkit-text-fill-color: ${s("placeholder")};
}
${breakpoint("tablet")`
margin-left: ${(props: TitleProps) => -props.$emojiWidth}px;
`};
${AnimatedStar} {
opacity: ${(props) => (props.$isStarred ? "1 !important" : 0)};
}
&:hover {
${AnimatedStar} {
opacity: 0.5;
&:hover {
opacity: 1;
}
}
}
@media print {
color: ${light.text};
-webkit-text-fill-color: ${light.text};
background: none;
}
`;
export default observer(EditableTitle);
+6 -14
View File
@@ -22,13 +22,12 @@ import {
import { useDocumentContext } from "../../../components/DocumentContext";
import MultiplayerEditor from "./AsyncMultiplayerEditor";
import DocumentMeta from "./DocumentMeta";
import DocumentTitle from "./DocumentTitle";
import EditableTitle from "./EditableTitle";
const extensions = withComments(richExtensions);
type Props = Omit<EditorProps, "extensions" | "editorStyle"> & {
onChangeTitle: (title: string) => void;
onChangeEmoji: (emoji: string | null) => void;
onChangeTitle: (text: string) => void;
id: string;
document: Document;
isDraft: boolean;
@@ -57,7 +56,6 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
const {
document,
onChangeTitle,
onChangeEmoji,
isDraft,
shareId,
readOnly,
@@ -153,20 +151,14 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
return (
<Flex auto column>
<DocumentTitle
<EditableTitle
ref={titleRef}
readOnly={readOnly}
documentId={document.id}
title={
!document.title && readOnly
? document.titleWithDefault
: document.title
}
emoji={document.emoji}
onChangeTitle={onChangeTitle}
onChangeEmoji={onChangeEmoji}
document={document}
onGoToNextInput={handleGoToNextInput}
onChange={onChangeTitle}
onBlur={handleBlur}
starrable={!shareId}
placeholder={t("Untitled")}
/>
{!shareId && (
+64 -89
View File
@@ -10,7 +10,7 @@ import {
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled, { useTheme } from "styled-components";
import styled from "styled-components";
import { NavigationNode } from "@shared/types";
import { Theme } from "~/stores/UiStore";
import Document from "~/models/Document";
@@ -20,10 +20,7 @@ import Badge from "~/components/Badge";
import Button from "~/components/Button";
import Collaborators from "~/components/Collaborators";
import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import { useEditingFocus } from "~/components/DocumentContext";
import Header from "~/components/Header";
import EmojiIcon from "~/components/Icons/EmojiIcon";
import Star from "~/components/Star";
import Tooltip from "~/components/Tooltip";
import { publishDocument } from "~/actions/definitions/documents";
import { restoreRevision } from "~/actions/definitions/revisions";
@@ -84,12 +81,10 @@ function DocumentHeader({
}: Props) {
const { t } = useTranslation();
const { ui, auth } = useStores();
const theme = useTheme();
const { resolvedTheme } = ui;
const { team, user } = auth;
const { team } = auth;
const isMobile = useMobile();
const isRevision = !!revision;
const isEditingFocus = useEditingFocus();
// We cache this value for as long as the component is mounted so that if you
// apply a template there is still the option to replace it until the user
@@ -109,6 +104,7 @@ function DocumentHeader({
const { isDeleted, isTemplate } = document;
const can = usePolicy(document?.id);
const canToggleEmbeds = team?.documentEmbeds;
const canEdit = can.update && !isEditing;
const toc = (
<Tooltip
tooltip={ui.tocVisible ? t("Hide contents") : t("Show contents")}
@@ -142,7 +138,7 @@ function DocumentHeader({
to={documentEditPath(document)}
neutral
>
{isMobile ? null : t("Edit")}
{t("Edit")}
</Button>
</Tooltip>
</Action>
@@ -170,8 +166,7 @@ function DocumentHeader({
if (shareId) {
return (
<StyledHeader
$hidden={isEditingFocus}
<Header
title={document.title}
hasSidebar={!!sharedTree}
left={
@@ -190,7 +185,7 @@ function DocumentHeader({
actions={
<>
{appearanceAction}
{can.update && !isEditing ? editAction : <div />}
{canEdit ? editAction : <div />}
</>
}
/>
@@ -199,25 +194,17 @@ function DocumentHeader({
return (
<>
<StyledHeader
$hidden={isEditingFocus}
<Header
hasSidebar
left={
isMobile ? (
<TableOfContentsMenu headings={headings} />
) : (
<DocumentBreadcrumb document={document}>
{toc} <Star document={document} color={theme.textSecondary} />
</DocumentBreadcrumb>
<DocumentBreadcrumb document={document}>{toc}</DocumentBreadcrumb>
)
}
title={
<>
{document.emoji && (
<>
<EmojiIcon size={24} emoji={document.emoji} />{" "}
</>
)}
{document.title}{" "}
{document.isArchived && (
<ArchivedBadge>{t("Archived")}</ArchivedBadge>
@@ -228,11 +215,11 @@ function DocumentHeader({
<>
<ObservingBanner />
{!isPublishing && isSaving && user?.separateEditMode && (
{!isPublishing && isSaving && !team?.seamlessEditing && (
<Status>{t("Saving")}</Status>
)}
{!isDeleted && !isRevision && <Collaborators document={document} />}
{(isEditing || !user?.separateEditMode) && !isTemplate && isNew && (
{(isEditing || team?.seamlessEditing) && !isTemplate && isNew && (
<Action>
<TemplatesMenu
document={document}
@@ -263,56 +250,45 @@ function DocumentHeader({
disabled={savingIsDisabled}
neutral={isDraft}
>
{isDraft ? t("Save draft") : t("Done editing")}
{isDraft ? t("Save Draft") : t("Done Editing")}
</Button>
</Tooltip>
</Action>
</>
)}
{can.update &&
!isEditing &&
user?.separateEditMode &&
!isRevision &&
editAction}
{can.update &&
can.createChildDocument &&
!isRevision &&
!isMobile && (
<Action>
<NewChildDocumentMenu
document={document}
label={(props) => (
<Tooltip
tooltip={t("New document")}
shortcut="n"
delay={500}
placement="bottom"
>
<Button icon={<PlusIcon />} {...props} neutral>
{t("New doc")}
</Button>
</Tooltip>
)}
/>
</Action>
)}
{can.update &&
!isEditing &&
isTemplate &&
!isDraft &&
!isRevision && (
<Action>
<Button
icon={<PlusIcon />}
as={Link}
to={newDocumentPath(document.collectionId, {
templateId: document.id,
})}
>
{t("New from template")}
</Button>
</Action>
)}
{canEdit && !team?.seamlessEditing && !isRevision && editAction}
{canEdit && can.createChildDocument && !isRevision && !isMobile && (
<Action>
<NewChildDocumentMenu
document={document}
label={(props) => (
<Tooltip
tooltip={t("New document")}
shortcut="n"
delay={500}
placement="bottom"
>
<Button icon={<PlusIcon />} {...props} neutral>
{t("New doc")}
</Button>
</Tooltip>
)}
/>
</Action>
)}
{canEdit && isTemplate && !isDraft && !isRevision && (
<Action>
<Button
icon={<PlusIcon />}
as={Link}
to={newDocumentPath(document.collectionId, {
templateId: document.id,
})}
>
{t("New from template")}
</Button>
</Action>
)}
{revision && revision.createdAt !== document.updatedAt && (
<Action>
<Tooltip
@@ -342,23 +318,27 @@ function DocumentHeader({
{document.collectionId ? t("Publish") : `${t("Publish")}`}
</Button>
</Action>
{!isDeleted && <Separator />}
<Action>
<DocumentMenu
document={document}
isRevision={isRevision}
label={(props) => (
<Button
icon={<MoreIcon />}
{...props}
borderOnHover
neutral
{!isEditing && (
<>
{!isDeleted && <Separator />}
<Action>
<DocumentMenu
document={document}
isRevision={isRevision}
label={(props) => (
<Button
icon={<MoreIcon />}
{...props}
borderOnHover
neutral
/>
)}
showToggleEmbeds={canToggleEmbeds}
showDisplayOptions
/>
)}
showToggleEmbeds={canToggleEmbeds}
showDisplayOptions
/>
</Action>
</Action>
</>
)}
</>
}
/>
@@ -366,11 +346,6 @@ function DocumentHeader({
);
}
const StyledHeader = styled(Header)<{ $hidden: boolean }>`
transition: opacity 500ms ease-in-out;
${(props) => props.$hidden && "opacity: 0;"}
`;
const ArchivedBadge = styled(Badge)`
position: absolute;
`;
@@ -1,43 +1,44 @@
import { observer } from "mobx-react";
import { KeyboardIcon } 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 KeyboardShortcuts from "~/scenes/KeyboardShortcuts";
import { useEditingFocus } from "~/components/DocumentContext";
import Guide from "~/components/Guide";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import useStores from "~/hooks/useStores";
import useBoolean from "~/hooks/useBoolean";
function KeyboardShortcutsButton() {
const { t } = useTranslation();
const { dialogs } = useStores();
const isEditingFocus = useEditingFocus();
const handleOpenKeyboardShortcuts = () => {
dialogs.openGuide({
title: t("Keyboard shortcuts"),
content: <KeyboardShortcuts />,
});
};
const [
keyboardShortcutsOpen,
handleOpenKeyboardShortcuts,
handleCloseKeyboardShortcuts,
] = useBoolean();
return (
<Tooltip tooltip={t("Keyboard shortcuts")} shortcut="?" delay={500}>
<Button onClick={handleOpenKeyboardShortcuts} $hidden={isEditingFocus}>
<KeyboardIcon />
</Button>
</Tooltip>
<>
<Guide
isOpen={keyboardShortcutsOpen}
onRequestClose={handleCloseKeyboardShortcuts}
title={t("Keyboard shortcuts")}
>
<KeyboardShortcuts />
</Guide>
<Tooltip tooltip={t("Keyboard shortcuts")} shortcut="?" delay={500}>
<Button onClick={handleOpenKeyboardShortcuts}>
<KeyboardIcon />
</Button>
</Tooltip>
</>
);
}
const Button = styled(NudeButton)<{ $hidden: boolean }>`
const Button = styled(NudeButton)`
display: none;
position: fixed;
bottom: 0;
margin: 24px;
transition: opacity 500ms ease-in-out;
${(props) => props.$hidden && "opacity: 0;"}
${breakpoint("tablet")`
display: block;
@@ -48,4 +49,4 @@ const Button = styled(NudeButton)<{ $hidden: boolean }>`
}
`;
export default observer(KeyboardShortcutsButton);
export default KeyboardShortcutsButton;

Some files were not shown because too many files have changed in this diff Show More