From 8b0b383e9ec1326efbc4c3c3f742f0b01732a0d2 Mon Sep 17 00:00:00 2001 From: Saumya Pandey Date: Sat, 5 Mar 2022 23:00:41 +0530 Subject: [PATCH 001/187] fix: don't hide sidebar when menu is open (#3203) --- app/components/ContextMenu/index.tsx | 23 ++++++++++++++++++++- app/components/Layout.tsx | 3 ++- app/components/Sidebar/Sidebar.tsx | 4 +++- app/hooks/useMenuContext.tsx | 31 ++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 app/hooks/useMenuContext.tsx diff --git a/app/components/ContextMenu/index.tsx b/app/components/ContextMenu/index.tsx index 9d2612219e..3c1f713581 100644 --- a/app/components/ContextMenu/index.tsx +++ b/app/components/ContextMenu/index.tsx @@ -1,10 +1,13 @@ import * as React from "react"; +import { useTranslation } from "react-i18next"; import { Portal } from "react-portal"; import { Menu } from "reakit/Menu"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import useMenuContext from "~/hooks/useMenuContext"; import useMenuHeight from "~/hooks/useMenuHeight"; import usePrevious from "~/hooks/usePrevious"; +import useStores from "~/hooks/useStores"; import { fadeIn, fadeAndSlideUp, @@ -50,20 +53,38 @@ export default function ContextMenu({ const previousVisible = usePrevious(rest.visible); const maxHeight = useMenuHeight(rest.visible, rest.unstable_disclosureRef); const backgroundRef = React.useRef(null); + const { ui } = useStores(); + const { t } = useTranslation(); + const { setIsMenuOpen } = useMenuContext(); React.useEffect(() => { if (rest.visible && !previousVisible) { if (onOpen) { onOpen(); } + if (rest["aria-label"] !== t("Submenu")) { + setIsMenuOpen(true); + } } if (!rest.visible && previousVisible) { if (onClose) { onClose(); } + if (rest["aria-label"] !== t("Submenu")) { + setIsMenuOpen(false); + } } - }, [onOpen, onClose, previousVisible, rest.visible]); + }, [ + onOpen, + onClose, + previousVisible, + rest.visible, + ui.sidebarCollapsed, + setIsMenuOpen, + rest, + t, + ]); // Perf win – don't render anything until the menu has been opened if (!rest.visible && !previousVisible) { diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx index 0436993512..a0f6303e2b 100644 --- a/app/components/Layout.tsx +++ b/app/components/Layout.tsx @@ -8,6 +8,7 @@ import { LoadingIndicatorBar } from "~/components/LoadingIndicator"; import SkipNavContent from "~/components/SkipNavContent"; import SkipNavLink from "~/components/SkipNavLink"; import useKeyDown from "~/hooks/useKeyDown"; +import { MenuProvider } from "~/hooks/useMenuContext"; import useStores from "~/hooks/useStores"; import { isModKey } from "~/utils/keyboard"; @@ -40,7 +41,7 @@ function Layout({ title, children, sidebar, rightRail }: Props) { {ui.progressBarVisible && } - {sidebar} + {sidebar} ( const { ui } = useStores(); const location = useLocation(); const previousLocation = usePrevious(location); + const { isMenuOpen } = useMenuContext(); const width = ui.sidebarWidth; - const collapsed = ui.isEditing || ui.sidebarCollapsed; + const collapsed = (ui.isEditing || ui.sidebarCollapsed) && !isMenuOpen; const maxWidth = theme.sidebarMaxWidth; const minWidth = theme.sidebarMinWidth + 16; // padding diff --git a/app/hooks/useMenuContext.tsx b/app/hooks/useMenuContext.tsx new file mode 100644 index 0000000000..7df90f7c1f --- /dev/null +++ b/app/hooks/useMenuContext.tsx @@ -0,0 +1,31 @@ +import { noop } from "lodash"; +import React from "react"; + +type MenuContextType = { + isMenuOpen: boolean; + setIsMenuOpen: React.Dispatch>; +}; + +const MenuContext = React.createContext(null); + +export const MenuProvider: React.FC = ({ children }) => { + const [isMenuOpen, setIsMenuOpen] = React.useState(false); + const memoized = React.useMemo( + () => ({ + isMenuOpen, + setIsMenuOpen, + }), + [isMenuOpen, setIsMenuOpen] + ); + + return ( + {children} + ); +}; + +const useMenuContext: () => MenuContextType = () => { + const value = React.useContext(MenuContext); + return value ? value : { isMenuOpen: false, setIsMenuOpen: noop }; +}; + +export default useMenuContext; From 631d600920702c8426ca3cc2c5ab8c9858c5590e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Mar 2022 13:58:58 -0800 Subject: [PATCH 002/187] feat: File attachments (#3031) * stash * refactor, working in non-collab + collab editor * attachment styling * Avoid crypto require in browser * AttachmentIcon, handling unknown types * Do not allow attachment creation for file sizes over limit * Allow image as file attachment * Upload placeholder styling * lint * Refactor: Do not use placeholder for file attachmentuploads * Add loading spinner * fix: Extra paragraphs around attachments on insert * Bump editor * fix build error * Remove attachment placeholder when upload fails * Remove unused styles * fix: Attachments on shared pages * Merge fixes --- app/components/Editor.tsx | 13 +- app/editor/components/CommandMenu.tsx | 49 +++-- app/editor/components/LinkEditor.tsx | 2 +- app/editor/components/LinkToolbar.tsx | 2 +- app/editor/components/SelectionToolbar.tsx | 2 +- app/editor/index.tsx | 33 +-- app/editor/menus/block.ts | 13 +- app/hooks/useDictionary.ts | 3 +- app/models/FileOperation.ts | 9 +- app/scenes/Document/components/Document.tsx | 8 +- app/scenes/Settings/Import.tsx | 2 +- .../Settings/components/ImageUpload.tsx | 2 +- app/utils/{uploadFile.ts => files.ts} | 35 +++- package.json | 2 + server/editor/index.ts | 2 + server/editor/renderToHtml.ts | 2 + server/models/User.ts | 6 +- server/presenters/document.ts | 8 +- server/presenters/env.ts | 1 + server/routes/api/attachments.ts | 23 +- server/utils/color.ts | 19 -- server/utils/parseAttachmentIds.ts | 10 +- server/utils/s3.ts | 11 +- shared/editor/commands/createAndInsertLink.ts | 2 +- shared/editor/commands/insertFiles.ts | 197 ++++++++++++------ shared/editor/components/DisabledEmbed.tsx | 20 ++ shared/editor/components/FileExtension.tsx | 42 ++++ .../editor/{embeds => }/components/Frame.tsx | 0 .../editor/{embeds => }/components/Image.tsx | 2 +- shared/editor/components/Widget.tsx | 98 +++++++++ shared/editor/embeds/Abstract.tsx | 2 +- shared/editor/embeds/Airtable.tsx | 2 +- shared/editor/embeds/Bilibili.tsx | 2 +- shared/editor/embeds/Cawemo.tsx | 2 +- shared/editor/embeds/ClickUp.tsx | 2 +- shared/editor/embeds/Codepen.tsx | 2 +- shared/editor/embeds/DBDiagram.tsx | 2 +- shared/editor/embeds/Descript.tsx | 2 +- shared/editor/embeds/Diagrams.tsx | 4 +- shared/editor/embeds/Figma.tsx | 2 +- shared/editor/embeds/Framer.tsx | 2 +- shared/editor/embeds/GoogleCalendar.tsx | 2 +- shared/editor/embeds/GoogleDataStudio.tsx | 4 +- shared/editor/embeds/GoogleDocs.tsx | 4 +- shared/editor/embeds/GoogleDrawings.tsx | 4 +- shared/editor/embeds/GoogleDrive.tsx | 4 +- shared/editor/embeds/GoogleSheets.tsx | 4 +- shared/editor/embeds/GoogleSlides.tsx | 4 +- shared/editor/embeds/InVision.tsx | 2 +- shared/editor/embeds/Loom.tsx | 2 +- shared/editor/embeds/Lucidchart.tsx | 2 +- shared/editor/embeds/Marvel.tsx | 2 +- shared/editor/embeds/Mindmeister.tsx | 2 +- shared/editor/embeds/Miro.tsx | 2 +- shared/editor/embeds/ModeAnalytics.tsx | 2 +- shared/editor/embeds/Pitch.tsx | 2 +- shared/editor/embeds/Prezi.tsx | 2 +- shared/editor/embeds/Spotify.tsx | 2 +- shared/editor/embeds/Trello.tsx | 2 +- shared/editor/embeds/Typeform.tsx | 2 +- shared/editor/embeds/Vimeo.tsx | 2 +- shared/editor/embeds/Whimsical.tsx | 2 +- shared/editor/embeds/YouTube.tsx | 2 +- shared/editor/embeds/components/Simple.tsx | 71 ------- shared/editor/embeds/index.tsx | 2 +- ...adPlaceholder.ts => uploadPlaceholder.tsx} | 29 ++- shared/editor/nodes/Attachment.tsx | 114 ++++++++++ shared/editor/nodes/CodeFence.ts | 10 +- shared/editor/nodes/Embed.tsx | 4 +- shared/editor/nodes/Heading.ts | 10 +- shared/editor/nodes/Image.tsx | 29 ++- shared/editor/queries/findAttachmentById.ts | 23 ++ shared/editor/rules/attachments.ts | 82 ++++++++ shared/editor/rules/embeds.ts | 5 +- shared/editor/version.ts | 2 +- shared/env.ts | 5 + shared/i18n/locales/en_US/translation.json | 3 +- shared/types.ts | 1 + shared/utils/color.ts | 31 ++- shared/utils/files.test.ts | 13 ++ shared/utils/files.ts | 21 ++ yarn.lock | 15 ++ 82 files changed, 846 insertions(+), 322 deletions(-) rename app/utils/{uploadFile.ts => files.ts} (56%) delete mode 100644 server/utils/color.ts create mode 100644 shared/editor/components/DisabledEmbed.tsx create mode 100644 shared/editor/components/FileExtension.tsx rename shared/editor/{embeds => }/components/Frame.tsx (100%) rename shared/editor/{embeds => }/components/Image.tsx (84%) create mode 100644 shared/editor/components/Widget.tsx delete mode 100644 shared/editor/embeds/components/Simple.tsx rename shared/editor/lib/{uploadPlaceholder.ts => uploadPlaceholder.tsx} (67%) create mode 100644 shared/editor/nodes/Attachment.tsx create mode 100644 shared/editor/queries/findAttachmentById.ts create mode 100644 shared/editor/rules/attachments.ts create mode 100644 shared/env.ts create mode 100644 shared/utils/files.test.ts create mode 100644 shared/utils/files.ts diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index 22406cf6b4..63d2fe9e01 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -6,9 +6,9 @@ import ErrorBoundary from "~/components/ErrorBoundary"; import { Props as EditorProps } from "~/editor"; import useDictionary from "~/hooks/useDictionary"; import useToasts from "~/hooks/useToasts"; +import { uploadFile } from "~/utils/files"; import history from "~/utils/history"; import { isModKey } from "~/utils/keyboard"; -import { uploadFile } from "~/utils/uploadFile"; import { isHash } from "~/utils/urls"; const SharedEditor = React.lazy( @@ -21,7 +21,12 @@ const SharedEditor = React.lazy( export type Props = Optional< EditorProps, - "placeholder" | "defaultValue" | "onClickLink" | "embeds" | "dictionary" + | "placeholder" + | "defaultValue" + | "onClickLink" + | "embeds" + | "dictionary" + | "onShowToast" > & { shareId?: string | undefined; embedsDisabled?: boolean; @@ -35,7 +40,7 @@ function Editor(props: Props, ref: React.Ref) { const { showToast } = useToasts(); const dictionary = useDictionary(); - const onUploadImage = React.useCallback( + const onUploadFile = React.useCallback( async (file: File) => { const result = await uploadFile(file, { documentId: id, @@ -90,7 +95,7 @@ function Editor(props: Props, ref: React.Ref) { = { dictionary: Dictionary; view: EditorView; search: string; - uploadImage?: (file: File) => Promise; - onImageUploadStart?: () => void; - onImageUploadStop?: () => void; - onShowToast?: (message: string, id: string) => void; + uploadFile?: (file: File) => Promise; + onFileUploadStart?: () => void; + onFileUploadStop?: () => void; + onShowToast: (message: string, id: string) => void; onLinkToolbarOpen?: () => void; onClose: () => void; onClearSearch: () => void; @@ -178,7 +178,9 @@ class CommandMenu extends React.Component, State> { insertItem = (item: any) => { switch (item.name) { case "image": - return this.triggerImagePick(); + return this.triggerFilePick("image/*"); + case "attachment": + return this.triggerFilePick("*"); case "embed": return this.triggerLinkInput(item); case "link": { @@ -212,7 +214,7 @@ class CommandMenu extends React.Component, State> { const href = event.currentTarget.value; const matches = this.state.insertItem.matcher(href); - if (!matches && this.props.onShowToast) { + if (!matches) { this.props.onShowToast( this.props.dictionary.embedInvalidLink, ToastType.Error @@ -258,8 +260,11 @@ class CommandMenu extends React.Component, State> { } }; - triggerImagePick = () => { + triggerFilePick = (accept: string) => { if (this.inputRef.current) { + if (accept) { + this.inputRef.current.accept = accept; + } this.inputRef.current.click(); } }; @@ -268,14 +273,14 @@ class CommandMenu extends React.Component, State> { this.setState({ insertItem: item }); }; - handleImagePicked = (event: React.ChangeEvent) => { + handleFilePicked = (event: React.ChangeEvent) => { const files = getDataTransferFiles(event); const { view, - uploadImage, - onImageUploadStart, - onImageUploadStop, + uploadFile, + onFileUploadStart, + onFileUploadStop, onShowToast, } = this.props; const { state } = view; @@ -283,17 +288,18 @@ class CommandMenu extends React.Component, State> { this.clearSearch(); - if (!uploadImage) { - throw new Error("uploadImage prop is required to replace images"); + if (!uploadFile) { + throw new Error("uploadFile prop is required to replace files"); } if (parent) { insertFiles(view, event, parent.pos, files, { - uploadImage, - onImageUploadStart, - onImageUploadStop, + uploadFile, + onFileUploadStart, + onFileUploadStop, onShowToast, dictionary: this.props.dictionary, + isAttachment: this.inputRef.current?.accept === "*", }); } @@ -409,7 +415,7 @@ class CommandMenu extends React.Component, State> { const { embeds = [], search = "", - uploadImage, + uploadFile, commands, filterable = true, } = this.props; @@ -447,7 +453,7 @@ class CommandMenu extends React.Component, State> { } // If no image upload callback has been passed, filter the image block out - if (!uploadImage && item.name === "image") { + if (!uploadFile && item.name === "image") { return false; } @@ -470,7 +476,7 @@ class CommandMenu extends React.Component, State> { } render() { - const { dictionary, isActive, uploadImage } = this.props; + const { dictionary, isActive, uploadFile } = this.props; const items = this.filtered; const { insertItem, ...positioning } = this.state; @@ -537,13 +543,12 @@ class CommandMenu extends React.Component, State> { )} )} - {uploadImage && ( + {uploadFile && ( )} diff --git a/app/editor/components/LinkEditor.tsx b/app/editor/components/LinkEditor.tsx index d98813e2eb..28b0aea585 100644 --- a/app/editor/components/LinkEditor.tsx +++ b/app/editor/components/LinkEditor.tsx @@ -44,7 +44,7 @@ type Props = { href: string, event: React.MouseEvent ) => void; - onShowToast?: (message: string, code: string) => void; + onShowToast: (message: string, code: string) => void; view: EditorView; }; diff --git a/app/editor/components/LinkToolbar.tsx b/app/editor/components/LinkToolbar.tsx index 20f1fdf883..49dd3dcb82 100644 --- a/app/editor/components/LinkToolbar.tsx +++ b/app/editor/components/LinkToolbar.tsx @@ -15,7 +15,7 @@ type Props = { href: string, event: React.MouseEvent ) => void; - onShowToast?: (msg: string, code: string) => void; + onShowToast: (msg: string, code: string) => void; onClose: () => void; }; diff --git a/app/editor/components/SelectionToolbar.tsx b/app/editor/components/SelectionToolbar.tsx index 198125236b..f71f14a092 100644 --- a/app/editor/components/SelectionToolbar.tsx +++ b/app/editor/components/SelectionToolbar.tsx @@ -36,7 +36,7 @@ type Props = { event: MouseEvent | React.MouseEvent ) => void; onCreateLink?: (title: string) => Promise; - onShowToast?: (msg: string, code: string) => void; + onShowToast: (msg: string, code: string) => void; view: EditorView; }; diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 69122ea855..4af42b2859 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -28,6 +28,7 @@ import Strikethrough from "@shared/editor/marks/Strikethrough"; import Underline from "@shared/editor/marks/Underline"; // nodes +import Attachment from "@shared/editor/nodes/Attachment"; import Blockquote from "@shared/editor/nodes/Blockquote"; import BulletList from "@shared/editor/nodes/BulletList"; import CheckboxItem from "@shared/editor/nodes/CheckboxItem"; @@ -107,7 +108,7 @@ export type Props = { /** Heading id to scroll to when the editor has loaded */ scrollTo?: string; /** Callback for handling uploaded images, should return the url of uploaded file */ - uploadImage?: (file: File) => Promise; + uploadFile?: (file: File) => Promise; /** Callback when editor is blurred, as native input */ onBlur?: () => void; /** Callback when editor is focused, as native input */ @@ -119,9 +120,9 @@ export type Props = { /** Callback when user changes editor content */ onChange?: (value: () => string) => void; /** Callback when a file upload begins */ - onImageUploadStart?: () => void; + onFileUploadStart?: () => void; /** Callback when a file upload ends */ - onImageUploadStop?: () => void; + onFileUploadStop?: () => void; /** Callback when a link is created, should return url to created document */ onCreateLink?: (title: string) => Promise; /** Callback when user searches for documents from link insert interface */ @@ -142,7 +143,7 @@ export type Props = { /** Whether embeds should be rendered without an iframe */ embedsDisabled?: boolean; /** Callback when a toast message is triggered (eg "link copied") */ - onShowToast?: (message: string, code: ToastType) => void; + onShowToast: (message: string, code: ToastType) => void; className?: string; style?: React.CSSProperties; }; @@ -177,10 +178,10 @@ export class Editor extends React.PureComponent< defaultValue: "", dir: "auto", placeholder: "Write something nice…", - onImageUploadStart: () => { + onFileUploadStart: () => { // no default behavior }, - onImageUploadStop: () => { + onFileUploadStop: () => { // no default behavior }, embeds: [], @@ -318,7 +319,8 @@ export class Editor extends React.PureComponent< createExtensions() { const { dictionary } = this.props; - // adding nodes here? Update schema.ts for serialization on the server + // adding nodes here? Update server/editor/renderToHtml.ts for serialization + // on the server return new ExtensionManager( [ ...[ @@ -341,6 +343,9 @@ export class Editor extends React.PureComponent< new BulletList(), new Embed({ embeds: this.props.embeds }), new ListItem(), + new Attachment({ + dictionary, + }), new Notice({ dictionary, }), @@ -351,9 +356,9 @@ export class Editor extends React.PureComponent< new HorizontalRule(), new Image({ dictionary, - uploadImage: this.props.uploadImage, - onImageUploadStart: this.props.onImageUploadStart, - onImageUploadStop: this.props.onImageUploadStop, + uploadFile: this.props.uploadFile, + onFileUploadStart: this.props.onFileUploadStart, + onFileUploadStop: this.props.onFileUploadStop, onShowToast: this.props.onShowToast, }), new Table(), @@ -779,6 +784,7 @@ export class Editor extends React.PureComponent< onSearchLink={this.props.onSearchLink} onClickLink={this.props.onClickLink} onCreateLink={this.props.onCreateLink} + onShowToast={this.props.onShowToast} /> this.setState({ emojiMenuOpen: false })} @@ -807,10 +814,10 @@ export class Editor extends React.PureComponent< isActive={this.state.blockMenuOpen} search={this.state.blockMenuSearch} onClose={this.handleCloseBlockMenu} - uploadImage={this.props.uploadImage} + uploadFile={this.props.uploadFile} onLinkToolbarOpen={this.handleOpenLinkMenu} - onImageUploadStart={this.props.onImageUploadStart} - onImageUploadStop={this.props.onImageUploadStop} + onFileUploadStart={this.props.onFileUploadStart} + onFileUploadStop={this.props.onFileUploadStop} onShowToast={this.props.onShowToast} embeds={this.props.embeds} /> diff --git a/app/editor/menus/block.ts b/app/editor/menus/block.ts index 392d2758d9..82eb2df875 100644 --- a/app/editor/menus/block.ts +++ b/app/editor/menus/block.ts @@ -15,6 +15,7 @@ import { WarningIcon, InfoIcon, LinkIcon, + AttachmentIcon, } from "outline-icons"; import { MenuItem } from "@shared/editor/types"; import { Dictionary } from "~/hooks/useDictionary"; @@ -84,6 +85,12 @@ export default function blockMenuItems(dictionary: Dictionary): MenuItem[] { shortcut: `${metaDisplay} k`, keywords: "link url uri href", }, + { + name: "attachment", + title: dictionary.file, + icon: AttachmentIcon, + keywords: "file upload attach", + }, { name: "table", title: dictionary.table, @@ -124,21 +131,21 @@ export default function blockMenuItems(dictionary: Dictionary): MenuItem[] { name: "container_notice", title: dictionary.infoNotice, icon: InfoIcon, - keywords: "container_notice card information", + keywords: "notice card information", attrs: { style: "info" }, }, { name: "container_notice", title: dictionary.warningNotice, icon: WarningIcon, - keywords: "container_notice card error", + keywords: "notice card error", attrs: { style: "warning" }, }, { name: "container_notice", title: dictionary.tipNotice, icon: StarredIcon, - keywords: "container_notice card suggestion", + keywords: "notice card suggestion", attrs: { style: "tip" }, }, ]; diff --git a/app/hooks/useDictionary.ts b/app/hooks/useDictionary.ts index ce3db11713..e692d5379c 100644 --- a/app/hooks/useDictionary.ts +++ b/app/hooks/useDictionary.ts @@ -32,6 +32,7 @@ export default function useDictionary() { alignImageDefault: t("Center large"), em: t("Italic"), embedInvalidLink: t("Sorry, that link won’t work for this embed type"), + file: t("File attachment"), findOrCreateDoc: `${t("Find or create a doc")}…`, h1: t("Big heading"), h2: t("Medium heading"), @@ -39,7 +40,7 @@ export default function useDictionary() { heading: t("Heading"), hr: t("Divider"), image: t("Image"), - imageUploadError: t("Sorry, an error occurred uploading the image"), + fileUploadError: t("Sorry, an error occurred uploading the file"), imageCaptionPlaceholder: t("Write a caption"), info: t("Info"), infoNotice: t("Info notice"), diff --git a/app/models/FileOperation.ts b/app/models/FileOperation.ts index 725f656c72..36689a6631 100644 --- a/app/models/FileOperation.ts +++ b/app/models/FileOperation.ts @@ -1,4 +1,5 @@ import { computed } from "mobx"; +import { bytesToHumanReadable } from "@shared/utils/files"; import BaseModal from "./BaseModel"; import User from "./User"; @@ -23,13 +24,7 @@ class FileOperation extends BaseModal { @computed get sizeInMB(): string { - const inKB = this.size / 1024; - - if (inKB < 1024) { - return inKB.toFixed(2) + "KB"; - } - - return (inKB / 1024).toFixed(2) + "MB"; + return bytesToHumanReadable(this.size); } } diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index 881db17ec6..8c71a976f5 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -346,11 +346,11 @@ class DocumentScene extends React.Component { updateIsDirtyDebounced = debounce(this.updateIsDirty, 500); - onImageUploadStart = () => { + onFileUploadStart = () => { this.isUploading = true; }; - onImageUploadStop = () => { + onFileUploadStop = () => { this.isUploading = false; }; @@ -558,8 +558,8 @@ class DocumentScene extends React.Component { defaultValue={value} embedsDisabled={embedsDisabled} onSynced={this.onSynced} - onImageUploadStart={this.onImageUploadStart} - onImageUploadStop={this.onImageUploadStop} + onFileUploadStart={this.onFileUploadStart} + onFileUploadStop={this.onFileUploadStop} onSearchLink={this.props.onSearchLink} onCreateLink={this.props.onCreateLink} onChangeTitle={this.onChangeTitle} diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx index ebd50cee1d..30f2f8ea5b 100644 --- a/app/scenes/Settings/Import.tsx +++ b/app/scenes/Settings/Import.tsx @@ -16,7 +16,7 @@ import Subheading from "~/components/Subheading"; import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; -import { uploadFile } from "~/utils/uploadFile"; +import { uploadFile } from "~/utils/files"; import FileOperationListItem from "./components/FileOperationListItem"; function Import() { diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx index 7ab5e0f52c..11b116686f 100644 --- a/app/scenes/Settings/components/ImageUpload.tsx +++ b/app/scenes/Settings/components/ImageUpload.tsx @@ -12,7 +12,7 @@ import LoadingIndicator from "~/components/LoadingIndicator"; import Modal from "~/components/Modal"; import withStores from "~/components/withStores"; import { compressImage } from "~/utils/compressImage"; -import { uploadFile, dataUrlToBlob } from "~/utils/uploadFile"; +import { uploadFile, dataUrlToBlob } from "~/utils/files"; const EMPTY_OBJECT = {}; diff --git a/app/utils/uploadFile.ts b/app/utils/files.ts similarity index 56% rename from app/utils/uploadFile.ts rename to app/utils/files.ts index 2797cdef66..8cb7b1b7df 100644 --- a/app/utils/uploadFile.ts +++ b/app/utils/files.ts @@ -1,15 +1,21 @@ +import * as Sentry from "@sentry/react"; import invariant from "invariant"; import { client } from "./ApiClient"; -type Options = { +type UploadOptions = { + /** The user facing name of the file */ name?: string; + /** The document that this file was uploaded in, if any */ documentId?: string; + /** Whether the file should be public in cloud storage */ public?: boolean; + /** Callback will be passed a number between 0-1 as upload progresses */ + onProgress?: (fractionComplete: number) => void; }; export const uploadFile = async ( file: File | Blob, - options: Options = { + options: UploadOptions = { name: "", } ) => { @@ -38,11 +44,28 @@ export const uploadFile = async ( formData.append("file", file); } - const uploadResponse = await fetch(data.uploadUrl, { - method: "post", - body: formData, + // Using XMLHttpRequest instead of fetch because fetch doesn't support progress + let error; + const xhr = new XMLHttpRequest(); + const success = await new Promise((resolve) => { + xhr.upload.addEventListener("progress", (event) => { + if (event.lengthComputable && options.onProgress) { + options.onProgress(event.loaded / event.total); + } + }); + xhr.addEventListener("error", (err) => (error = err)); + xhr.addEventListener("loadend", () => { + resolve(xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 400); + }); + xhr.open("POST", data.uploadUrl, true); + xhr.send(formData); }); - invariant(uploadResponse.ok, "Upload failed, try again?"); + + if (!success) { + Sentry.captureException(error); + throw new Error("Upload failed"); + } + return attachment; }; diff --git a/package.json b/package.json index bd107010d9..aeb14dc71a 100644 --- a/package.json +++ b/package.json @@ -73,6 +73,7 @@ "compressorjs": "^1.0.7", "copy-to-clipboard": "^3.3.1", "core-js": "^3.10.2", + "crypto-js": "^4.1.1", "datadog-metrics": "^0.9.3", "date-fns": "^2.25.0", "dd-trace": "^0.32.2", @@ -207,6 +208,7 @@ "@pmmmwh/react-refresh-webpack-plugin": "^0.5.4", "@relative-ci/agent": "^3.0.0", "@types/bull": "^3.15.5", + "@types/crypto-js": "^4.1.0", "@types/datadog-metrics": "^0.6.2", "@types/emoji-regex": "^9.2.0", "@types/enzyme": "^3.10.10", diff --git a/server/editor/index.ts b/server/editor/index.ts index 30969f9c67..3cb88bbcd7 100644 --- a/server/editor/index.ts +++ b/server/editor/index.ts @@ -12,6 +12,7 @@ import Strikethrough from "@shared/editor/marks/Strikethrough"; import Underline from "@shared/editor/marks/Underline"; // nodes +import Attachment from "@shared/editor/nodes/Attachment"; import Blockquote from "@shared/editor/nodes/Blockquote"; import BulletList from "@shared/editor/nodes/BulletList"; import CheckboxItem from "@shared/editor/nodes/CheckboxItem"; @@ -51,6 +52,7 @@ const extensions = new ExtensionManager([ new Embed(), new ListItem(), new Notice(), + new Attachment(), new Heading(), new HorizontalRule(), new Image(), diff --git a/server/editor/renderToHtml.ts b/server/editor/renderToHtml.ts index 062d418e6a..e151ca7f32 100644 --- a/server/editor/renderToHtml.ts +++ b/server/editor/renderToHtml.ts @@ -1,5 +1,6 @@ import { PluginSimple } from "markdown-it"; import createMarkdown from "@shared/editor/lib/markdown/rules"; +import attachmentsRule from "@shared/editor/rules/attachments"; import breakRule from "@shared/editor/rules/breaks"; import checkboxRule from "@shared/editor/rules/checkboxes"; import embedsRule from "@shared/editor/rules/embeds"; @@ -18,6 +19,7 @@ const defaultRules = [ underlinesRule, tablesRule, noticesRule, + attachmentsRule, emojiRule, ]; diff --git a/server/models/User.ts b/server/models/User.ts index a68025ba05..58e0a80a87 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -22,9 +22,9 @@ import { } from "sequelize-typescript"; import { v4 as uuidv4 } from "uuid"; import { languages } from "@shared/i18n"; +import { stringToColor } from "@shared/utils/color"; import Logger from "@server/logging/logger"; import { DEFAULT_AVATAR_HOST } from "@server/utils/avatars"; -import { palette } from "@server/utils/color"; import { publicS3Endpoint, uploadToS3FromUrl } from "@server/utils/s3"; import { ValidationError } from "../errors"; import ApiKey from "./ApiKey"; @@ -157,9 +157,7 @@ class User extends ParanoidModel { } get color() { - const idAsHex = crypto.createHash("md5").update(this.id).digest("hex"); - const idAsNumber = parseInt(idAsHex, 16); - return palette[idAsNumber % palette.length]; + return stringToColor(this.id); } // instance methods diff --git a/server/presenters/document.ts b/server/presenters/document.ts index d81b5a232b..f84e469855 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -1,3 +1,4 @@ +import { escapeRegExp } from "lodash"; import { Document } from "@server/models"; import Attachment from "@server/models/Attachment"; import parseAttachmentIds from "@server/utils/parseAttachmentIds"; @@ -16,8 +17,11 @@ async function replaceImageAttachments(text: string) { const attachment = await Attachment.findByPk(id); if (attachment) { - const accessUrl = await getSignedUrl(attachment.key); - text = text.replace(attachment.redirectUrl, accessUrl); + const signedUrl = await getSignedUrl(attachment.key, 3600); + text = text.replace( + new RegExp(escapeRegExp(attachment.redirectUrl), "g"), + signedUrl + ); } }) ); diff --git a/server/presenters/env.ts b/server/presenters/env.ts index dc355e4cec..98e6aa9ea1 100644 --- a/server/presenters/env.ts +++ b/server/presenters/env.ts @@ -5,6 +5,7 @@ import { PublicEnv } from "@shared/types"; export default function present(env: Record): PublicEnv { return { URL: env.URL.replace(/\/$/, ""), + AWS_S3_UPLOAD_BUCKET_URL: env.AWS_S3_UPLOAD_BUCKET_URL, CDN_URL: (env.CDN_URL || "").replace(/\/$/, ""), COLLABORATION_URL: (env.COLLABORATION_URL || env.URL) .replace(/\/$/, "") diff --git a/server/routes/api/attachments.ts b/server/routes/api/attachments.ts index 4d24629b0e..63090ef853 100644 --- a/server/routes/api/attachments.ts +++ b/server/routes/api/attachments.ts @@ -1,6 +1,7 @@ import Router from "koa-router"; import { v4 as uuidv4 } from "uuid"; -import { NotFoundError } from "@server/errors"; +import { bytesToHumanReadable } from "@shared/utils/files"; +import { NotFoundError, ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; import { Attachment, Document, Event } from "@server/models"; import { authorize } from "@server/policies"; @@ -15,12 +16,28 @@ const router = new Router(); const AWS_S3_ACL = process.env.AWS_S3_ACL || "private"; router.post("attachments.create", auth(), async (ctx) => { - const { name, documentId, contentType, size } = ctx.body; + const { + name, + documentId, + contentType = "application/octet-stream", + size, + } = ctx.body; assertPresent(name, "name is required"); - assertPresent(contentType, "contentType is required"); assertPresent(size, "size is required"); const { user } = ctx.state; authorize(user, "createAttachment", user.team); + + if ( + process.env.AWS_S3_UPLOAD_MAX_SIZE && + size > process.env.AWS_S3_UPLOAD_MAX_SIZE + ) { + throw ValidationError( + `Sorry, this file is too large – the maximum size is ${bytesToHumanReadable( + parseInt(process.env.AWS_S3_UPLOAD_MAX_SIZE, 10) + )}` + ); + } + const s3Key = uuidv4(); const acl = ctx.body.public === undefined diff --git a/server/utils/color.ts b/server/utils/color.ts deleted file mode 100644 index b36b0d161e..0000000000 --- a/server/utils/color.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { darken } from "polished"; -import theme from "@shared/theme"; - -export const palette = [ - theme.brand.red, - theme.brand.blue, - theme.brand.purple, - theme.brand.pink, - theme.brand.marine, - theme.brand.green, - theme.brand.yellow, - darken(0.2, theme.brand.red), - darken(0.2, theme.brand.blue), - darken(0.2, theme.brand.purple), - darken(0.2, theme.brand.pink), - darken(0.2, theme.brand.marine), - darken(0.2, theme.brand.green), - darken(0.2, theme.brand.yellow), -]; diff --git a/server/utils/parseAttachmentIds.ts b/server/utils/parseAttachmentIds.ts index d69be094c5..c1f8b86e3a 100644 --- a/server/utils/parseAttachmentIds.ts +++ b/server/utils/parseAttachmentIds.ts @@ -1,11 +1,13 @@ -import { compact } from "lodash"; +import { uniq, compact } from "lodash"; const attachmentRegex = /\/api\/attachments\.redirect\?id=(?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi; export default function parseAttachmentIds(text: string): string[] { - return compact( - [...text.matchAll(attachmentRegex)].map( - (match) => match.groups && match.groups.id + return uniq( + compact( + [...text.matchAll(attachmentRegex)].map( + (match) => match.groups && match.groups.id + ) ) ); } diff --git a/server/utils/s3.ts b/server/utils/s3.ts index 6b3e707194..d0592be08d 100644 --- a/server/utils/s3.ts +++ b/server/utils/s3.ts @@ -106,11 +106,12 @@ export const getPresignedPost = ( const params = { Bucket: process.env.AWS_S3_UPLOAD_BUCKET_NAME, Conditions: [ - // @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'. - ["content-length-range", 0, +process.env.AWS_S3_UPLOAD_MAX_SIZE], + process.env.AWS_S3_UPLOAD_MAX_SIZE + ? ["content-length-range", 0, +process.env.AWS_S3_UPLOAD_MAX_SIZE] + : undefined, ["starts-with", "$Content-Type", contentType], ["starts-with", "$Cache-Control", ""], - ], + ].filter(Boolean), Fields: { key, acl, @@ -208,12 +209,12 @@ export const deleteFromS3 = (key: string) => { .promise(); }; -export const getSignedUrl = async (key: string) => { +export const getSignedUrl = async (key: string, expiresInMs = 60) => { const isDocker = AWS_S3_UPLOAD_BUCKET_URL.match(/http:\/\/s3:/); const params = { Bucket: AWS_S3_UPLOAD_BUCKET_NAME, Key: key, - Expires: 60, + Expires: expiresInMs, }; const url = isDocker diff --git a/shared/editor/commands/createAndInsertLink.ts b/shared/editor/commands/createAndInsertLink.ts index d2e9f10f12..196396caa6 100644 --- a/shared/editor/commands/createAndInsertLink.ts +++ b/shared/editor/commands/createAndInsertLink.ts @@ -38,7 +38,7 @@ const createAndInsertLink = async function ( options: { dictionary: any; onCreateLink: (title: string) => Promise; - onShowToast?: (message: string, code: string) => void; + onShowToast: (message: string, code: string) => void; } ) { const { dispatch, state } = view; diff --git a/shared/editor/commands/insertFiles.ts b/shared/editor/commands/insertFiles.ts index ca320836d2..9b4f7172f3 100644 --- a/shared/editor/commands/insertFiles.ts +++ b/shared/editor/commands/insertFiles.ts @@ -1,19 +1,23 @@ +import * as Sentry from "@sentry/react"; import { NodeSelection } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; +import { v4 as uuidv4 } from "uuid"; import uploadPlaceholderPlugin, { findPlaceholder, } from "../lib/uploadPlaceholder"; +import findAttachmentById from "../queries/findAttachmentById"; import { ToastType } from "../types"; -let uploadId = 0; - export type Options = { dictionary: any; + /** Set to true to force images to become attachments */ + isAttachment?: boolean; + /** Set to true to replace any existing image at the users selection */ replaceExisting?: boolean; - uploadImage: (file: File) => Promise; - onImageUploadStart?: () => void; - onImageUploadStop?: () => void; - onShowToast?: (message: string, code: string) => void; + uploadFile?: (file: File) => Promise; + onFileUploadStart?: () => void; + onFileUploadStop?: () => void; + onShowToast: (message: string, code: string) => void; }; const insertFiles = function ( @@ -23,85 +27,133 @@ const insertFiles = function ( files: File[], options: Options ): void { - // filter to only include image files - const images = files.filter((file) => /image/i.test(file.type)); - if (images.length === 0) { - return; - } - const { dictionary, - uploadImage, - onImageUploadStart, - onImageUploadStop, + uploadFile, + onFileUploadStart, + onFileUploadStop, onShowToast, } = options; - if (!uploadImage) { - console.warn( - "uploadImage callback must be defined to handle image uploads." - ); + if (!uploadFile) { + console.warn("uploadFile callback must be defined to handle uploads."); return; } - // okay, we have some dropped images and a handler – lets stop this + // okay, we have some dropped files and a handler – lets stop this // event going any further up the stack event.preventDefault(); - // let the user know we're starting to process the images - if (onImageUploadStart) { - onImageUploadStart(); + // let the user know we're starting to process the files + if (onFileUploadStart) { + onFileUploadStart(); } const { schema } = view.state; - // we'll use this to track of how many images have succeeded or failed + // we'll use this to track of how many files have succeeded or failed let complete = 0; - // the user might have dropped multiple images at once, we need to loop - for (const file of images) { - const id = `upload-${uploadId++}`; - + // the user might have dropped multiple files at once, we need to loop + for (const file of files) { + const id = `upload-${uuidv4()}`; + const isImage = file.type.startsWith("image/") && !options.isAttachment; const { tr } = view.state; - // insert a placeholder at this position, or mark an existing image as being - // replaced - tr.setMeta(uploadPlaceholderPlugin, { - add: { - id, - file, - pos, - replaceExisting: options.replaceExisting, - }, - }); - view.dispatch(tr); + if (isImage) { + // insert a placeholder at this position, or mark an existing file as being + // replaced + tr.setMeta(uploadPlaceholderPlugin, { + add: { + id, + file, + pos, + isImage, + replaceExisting: options.replaceExisting, + }, + }); + view.dispatch(tr); + } else { + const $pos = tr.doc.resolve(pos); + view.dispatch( + view.state.tr.replaceWith( + $pos.pos, + $pos.pos + ($pos.nodeAfter?.nodeSize || 0), + schema.nodes.attachment.create({ + id, + title: file.name, + size: file.size, + }) + ) + ); + } - // start uploading the image file to the server. Using "then" syntax + // start uploading the file to the server. Using "then" syntax // to allow all placeholders to be entered at once with the uploads // happening in the background in parallel. - uploadImage(file) + uploadFile(file) .then((src) => { - // otherwise, insert it at the placeholder's position, and remove - // the placeholder itself - const newImg = new Image(); + if (isImage) { + const newImg = new Image(); + newImg.onload = () => { + const result = findPlaceholder(view.state, id); - newImg.onload = () => { - const result = findPlaceholder(view.state, id); + // if the content around the placeholder has been deleted + // then forget about inserting this file + if (result === null) { + return; + } - // if the content around the placeholder has been deleted - // then forget about inserting this image + const [from, to] = result; + view.dispatch( + view.state.tr + .replaceWith( + from, + to || from, + schema.nodes.image.create({ src }) + ) + .setMeta(uploadPlaceholderPlugin, { remove: { id } }) + ); + + // If the users selection is still at the file then make sure to select + // the entire node once done. Otherwise, if the selection has moved + // elsewhere then we don't want to modify it + if (view.state.selection.from === from) { + view.dispatch( + view.state.tr.setSelection( + new NodeSelection(view.state.doc.resolve(from)) + ) + ); + } + }; + + newImg.onerror = (error) => { + throw error; + }; + + newImg.src = src; + } else { + const result = findAttachmentById(view.state, id); + + // if the attachment has been deleted then forget about updating it if (result === null) { return; } const [from, to] = result; view.dispatch( - view.state.tr - .replaceWith(from, to || from, schema.nodes.image.create({ src })) - .setMeta(uploadPlaceholderPlugin, { remove: { id } }) + view.state.tr.replaceWith( + from, + to || from, + schema.nodes.attachment.create({ + href: src, + title: file.name, + size: file.size, + }) + ) ); - // If the users selection is still at the image then make sure to select + // If the users selection is still at the file then make sure to select // the entire node once done. Otherwise, if the selection has moved // elsewhere then we don't want to modify it if (view.state.selection.from === from) { @@ -111,34 +163,41 @@ const insertFiles = function ( ) ); } - }; - - newImg.onerror = (error) => { - throw error; - }; - - newImg.src = src; + } }) .catch((error) => { - console.error(error); + Sentry.captureException(error); // cleanup the placeholder if there is a failure - const transaction = view.state.tr.setMeta(uploadPlaceholderPlugin, { - remove: { id }, - }); - view.dispatch(transaction); + if (isImage) { + view.dispatch( + view.state.tr.setMeta(uploadPlaceholderPlugin, { + remove: { id }, + }) + ); + } else { + const result = findAttachmentById(view.state, id); - // let the user know - if (onShowToast) { - onShowToast(dictionary.imageUploadError, ToastType.Error); + // if the attachment has been deleted then forget about updating it + if (result === null) { + return; + } + + const [from, to] = result; + view.dispatch(view.state.tr.deleteRange(from, to || from)); } + + onShowToast( + error.message || dictionary.fileUploadError, + ToastType.Error + ); }) .finally(() => { complete++; // once everything is done, let the user know - if (complete === images.length && onImageUploadStop) { - onImageUploadStop(); + if (complete === files.length && onFileUploadStop) { + onFileUploadStop(); } }); } diff --git a/shared/editor/components/DisabledEmbed.tsx b/shared/editor/components/DisabledEmbed.tsx new file mode 100644 index 0000000000..71576cadd7 --- /dev/null +++ b/shared/editor/components/DisabledEmbed.tsx @@ -0,0 +1,20 @@ +import { OpenIcon } from "outline-icons"; +import * as React from "react"; +import { DefaultTheme, ThemeProps } from "styled-components"; +import { EmbedProps as Props } from "../embeds"; +import Widget from "./Widget"; + +export default function DisabledEmbed(props: Props & ThemeProps) { + return ( + + + + ); +} diff --git a/shared/editor/components/FileExtension.tsx b/shared/editor/components/FileExtension.tsx new file mode 100644 index 0000000000..f4f799b713 --- /dev/null +++ b/shared/editor/components/FileExtension.tsx @@ -0,0 +1,42 @@ +import { AttachmentIcon } from "outline-icons"; +import * as React from "react"; +import styled from "styled-components"; +import { stringToColor } from "../../utils/color"; + +type Props = { + title: string; + size?: number; +}; + +export default function FileExtension(props: Props) { + const parts = props.title.split("."); + const extension = parts.length > 1 ? parts.pop() : undefined; + + return ( + + {extension ? ( + {extension?.slice(0, 4)} + ) : ( + + )} + + ); +} + +const Icon = styled.span<{ $size: number }>` + font-family: ${(props) => props.theme.fontFamilyMono}; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 10px; + text-transform: uppercase; + color: white; + text-align: center; + border-radius: 4px; + + min-width: ${(props) => props.$size}px; + height: ${(props) => props.$size}px; +`; diff --git a/shared/editor/embeds/components/Frame.tsx b/shared/editor/components/Frame.tsx similarity index 100% rename from shared/editor/embeds/components/Frame.tsx rename to shared/editor/components/Frame.tsx diff --git a/shared/editor/embeds/components/Image.tsx b/shared/editor/components/Image.tsx similarity index 84% rename from shared/editor/embeds/components/Image.tsx rename to shared/editor/components/Image.tsx index 14245c3ba8..29b0b60a57 100644 --- a/shared/editor/embeds/components/Image.tsx +++ b/shared/editor/components/Image.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import { cdnPath } from "../../../utils/urls"; +import { cdnPath } from "../../utils/urls"; type Props = { alt: string; diff --git a/shared/editor/components/Widget.tsx b/shared/editor/components/Widget.tsx new file mode 100644 index 0000000000..bf0bc057f4 --- /dev/null +++ b/shared/editor/components/Widget.tsx @@ -0,0 +1,98 @@ +import * as React from "react"; +import styled, { css, DefaultTheme, ThemeProps } from "styled-components"; + +type Props = { + icon: React.ReactNode; + title: React.ReactNode; + context?: React.ReactNode; + href: string; + isSelected: boolean; + children?: React.ReactNode; +}; + +export default function Widget(props: Props & ThemeProps) { + return ( + + {props.icon} + + {props.title} + {props.context} + {props.children} + + + ); +} + +const Children = styled.div` + margin-left: auto; + height: 20px; + opacity: 0; + + &:hover { + color: ${(props) => props.theme.text}; + } +`; + +const Title = styled.strong` + font-weight: 500; + font-size: 14px; + color: ${(props) => props.theme.text}; +`; + +const Preview = styled.div` + gap: 8px; + display: flex; + flex-direction: row; + flex-grow: 1; + align-items: center; + color: ${(props) => props.theme.textTertiary}; +`; + +const Subtitle = styled.span` + font-size: 13px; + color: ${(props) => props.theme.textTertiary} !important; + line-height: 0; +`; + +const Wrapper = styled.a` + display: flex; + align-items: center; + gap: 6px; + background: ${(props) => props.theme.background}; + color: ${(props) => props.theme.text} !important; + outline: 1px solid ${(props) => props.theme.divider}; + white-space: nowrap; + border-radius: 8px; + padding: 6px 8px; + max-width: 840px; + cursor: default; + + user-select: none; + text-overflow: ellipsis; + overflow: hidden; + + ${(props) => + props.href && + css` + &:hover, + &:active, + &:focus, + &:focus:not(.focus-visible) { + cursor: pointer !important; + text-decoration: none !important; + background: ${(props) => props.theme.secondaryBackground}; + outline: 1px solid ${(props) => props.theme.divider}; + + ${Children} { + opacity: 1; + } + } + `} +`; diff --git a/shared/editor/embeds/Abstract.tsx b/shared/editor/embeds/Abstract.tsx index 4133b1c950..28f01a8509 100644 --- a/shared/editor/embeds/Abstract.tsx +++ b/shared/editor/embeds/Abstract.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; export default class Abstract extends React.Component { diff --git a/shared/editor/embeds/Airtable.tsx b/shared/editor/embeds/Airtable.tsx index 37fff32bb6..532c3836d4 100644 --- a/shared/editor/embeds/Airtable.tsx +++ b/shared/editor/embeds/Airtable.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("https://airtable.com/(?:embed/)?(shr.*)$"); diff --git a/shared/editor/embeds/Bilibili.tsx b/shared/editor/embeds/Bilibili.tsx index 8d7f5916c7..06d8ecd9ff 100644 --- a/shared/editor/embeds/Bilibili.tsx +++ b/shared/editor/embeds/Bilibili.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /(?:https?:\/\/)?(www\.bilibili\.com)\/video\/([\w\d]+)?(\?\S+)?/i; diff --git a/shared/editor/embeds/Cawemo.tsx b/shared/editor/embeds/Cawemo.tsx index 37d45593f6..b59e42b53d 100644 --- a/shared/editor/embeds/Cawemo.tsx +++ b/shared/editor/embeds/Cawemo.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("https?://cawemo.com/(?:share|embed)/(.*)$"); diff --git a/shared/editor/embeds/ClickUp.tsx b/shared/editor/embeds/ClickUp.tsx index c0585905fe..a5b71daabc 100644 --- a/shared/editor/embeds/ClickUp.tsx +++ b/shared/editor/embeds/ClickUp.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Codepen.tsx b/shared/editor/embeds/Codepen.tsx index efe65d6cb0..0271f52aba 100644 --- a/shared/editor/embeds/Codepen.tsx +++ b/shared/editor/embeds/Codepen.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https://codepen.io/(.*?)/(pen|embed)/(.*)$"); diff --git a/shared/editor/embeds/DBDiagram.tsx b/shared/editor/embeds/DBDiagram.tsx index ed18329616..31fa524aca 100644 --- a/shared/editor/embeds/DBDiagram.tsx +++ b/shared/editor/embeds/DBDiagram.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; export default class DBDiagram extends React.Component { diff --git a/shared/editor/embeds/Descript.tsx b/shared/editor/embeds/Descript.tsx index 31964d4cc5..32a0de8c83 100644 --- a/shared/editor/embeds/Descript.tsx +++ b/shared/editor/embeds/Descript.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; export default class Descript extends React.Component { diff --git a/shared/editor/embeds/Diagrams.tsx b/shared/editor/embeds/Diagrams.tsx index db4c0f53c8..f115c71dc2 100644 --- a/shared/editor/embeds/Diagrams.tsx +++ b/shared/editor/embeds/Diagrams.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = /^https:\/\/viewer\.diagrams\.net\/.*(title=\\w+)?/; diff --git a/shared/editor/embeds/Figma.tsx b/shared/editor/embeds/Figma.tsx index 9fbf7c74e8..355bfc1c82 100644 --- a/shared/editor/embeds/Figma.tsx +++ b/shared/editor/embeds/Figma.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Framer.tsx b/shared/editor/embeds/Framer.tsx index 06ab7d6790..4589dde3de 100644 --- a/shared/editor/embeds/Framer.tsx +++ b/shared/editor/embeds/Framer.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https://framer.cloud/(.*)$"); diff --git a/shared/editor/embeds/GoogleCalendar.tsx b/shared/editor/embeds/GoogleCalendar.tsx index 422ebf0b37..8dc6e185ad 100644 --- a/shared/editor/embeds/GoogleCalendar.tsx +++ b/shared/editor/embeds/GoogleCalendar.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/GoogleDataStudio.tsx b/shared/editor/embeds/GoogleDataStudio.tsx index 180792b6a3..1a65c69337 100644 --- a/shared/editor/embeds/GoogleDataStudio.tsx +++ b/shared/editor/embeds/GoogleDataStudio.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/GoogleDocs.tsx b/shared/editor/embeds/GoogleDocs.tsx index 845b640f9c..7d86db401e 100644 --- a/shared/editor/embeds/GoogleDocs.tsx +++ b/shared/editor/embeds/GoogleDocs.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https?://docs.google.com/document/(.*)$"); diff --git a/shared/editor/embeds/GoogleDrawings.tsx b/shared/editor/embeds/GoogleDrawings.tsx index 96ff53e298..a86c21adad 100644 --- a/shared/editor/embeds/GoogleDrawings.tsx +++ b/shared/editor/embeds/GoogleDrawings.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/GoogleDrive.tsx b/shared/editor/embeds/GoogleDrive.tsx index 89fc8603a8..916dab23c4 100644 --- a/shared/editor/embeds/GoogleDrive.tsx +++ b/shared/editor/embeds/GoogleDrive.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https?://drive.google.com/file/d/(.*)$"); diff --git a/shared/editor/embeds/GoogleSheets.tsx b/shared/editor/embeds/GoogleSheets.tsx index 64adf91526..7416bb6a94 100644 --- a/shared/editor/embeds/GoogleSheets.tsx +++ b/shared/editor/embeds/GoogleSheets.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https?://docs.google.com/spreadsheets/d/(.*)$"); diff --git a/shared/editor/embeds/GoogleSlides.tsx b/shared/editor/embeds/GoogleSlides.tsx index 7b8f4ea3ca..9bc99e95b3 100644 --- a/shared/editor/embeds/GoogleSlides.tsx +++ b/shared/editor/embeds/GoogleSlides.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import Frame from "./components/Frame"; -import Image from "./components/Image"; +import Frame from "../components/Frame"; +import Image from "../components/Image"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https?://docs.google.com/presentation/d/(.*)$"); diff --git a/shared/editor/embeds/InVision.tsx b/shared/editor/embeds/InVision.tsx index f223d42cae..f12a7e08a0 100644 --- a/shared/editor/embeds/InVision.tsx +++ b/shared/editor/embeds/InVision.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import ImageZoom from "react-medium-image-zoom"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const IFRAME_REGEX = /^https:\/\/(invis\.io\/.*)|(projects\.invisionapp\.com\/share\/.*)$/; diff --git a/shared/editor/embeds/Loom.tsx b/shared/editor/embeds/Loom.tsx index 1dbc8f8b65..ee9fbfe9ca 100644 --- a/shared/editor/embeds/Loom.tsx +++ b/shared/editor/embeds/Loom.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /^https:\/\/(www\.)?(use)?loom.com\/(embed|share)\/(.*)$/; diff --git a/shared/editor/embeds/Lucidchart.tsx b/shared/editor/embeds/Lucidchart.tsx index 83523b8f76..f2981eeae3 100644 --- a/shared/editor/embeds/Lucidchart.tsx +++ b/shared/editor/embeds/Lucidchart.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; export default class Lucidchart extends React.Component { diff --git a/shared/editor/embeds/Marvel.tsx b/shared/editor/embeds/Marvel.tsx index 4f36e234ca..0fb8b54cae 100644 --- a/shared/editor/embeds/Marvel.tsx +++ b/shared/editor/embeds/Marvel.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https://marvelapp.com/([A-Za-z0-9-]{6})/?$"); diff --git a/shared/editor/embeds/Mindmeister.tsx b/shared/editor/embeds/Mindmeister.tsx index 2762bca71c..823caaeaf3 100644 --- a/shared/editor/embeds/Mindmeister.tsx +++ b/shared/editor/embeds/Mindmeister.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Miro.tsx b/shared/editor/embeds/Miro.tsx index 56b1ed46d9..d0df3a2229 100644 --- a/shared/editor/embeds/Miro.tsx +++ b/shared/editor/embeds/Miro.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /^https:\/\/(realtimeboard|miro).com\/app\/board\/(.*)$/; diff --git a/shared/editor/embeds/ModeAnalytics.tsx b/shared/editor/embeds/ModeAnalytics.tsx index 2ae6b0c7b4..1b61ee6fca 100644 --- a/shared/editor/embeds/ModeAnalytics.tsx +++ b/shared/editor/embeds/ModeAnalytics.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Pitch.tsx b/shared/editor/embeds/Pitch.tsx index dc4a940021..23231584a3 100644 --- a/shared/editor/embeds/Pitch.tsx +++ b/shared/editor/embeds/Pitch.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Prezi.tsx b/shared/editor/embeds/Prezi.tsx index 3a970b49a9..06193c0084 100644 --- a/shared/editor/embeds/Prezi.tsx +++ b/shared/editor/embeds/Prezi.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp("^https://prezi.com/view/(.*)$"); diff --git a/shared/editor/embeds/Spotify.tsx b/shared/editor/embeds/Spotify.tsx index 616c3d4ace..c366d63e10 100644 --- a/shared/editor/embeds/Spotify.tsx +++ b/shared/editor/embeds/Spotify.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; const URL_REGEX = new RegExp("https?://open.spotify.com/(.*)$"); import { EmbedProps as Props } from "."; diff --git a/shared/editor/embeds/Trello.tsx b/shared/editor/embeds/Trello.tsx index 78f3d006ae..87829a4ff4 100644 --- a/shared/editor/embeds/Trello.tsx +++ b/shared/editor/embeds/Trello.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /^https:\/\/trello.com\/(c|b)\/([^/]*)(.*)?$/; diff --git a/shared/editor/embeds/Typeform.tsx b/shared/editor/embeds/Typeform.tsx index a0ab088017..4b7b969910 100644 --- a/shared/editor/embeds/Typeform.tsx +++ b/shared/editor/embeds/Typeform.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = new RegExp( diff --git a/shared/editor/embeds/Vimeo.tsx b/shared/editor/embeds/Vimeo.tsx index e7b3fd73d2..f7f18607e5 100644 --- a/shared/editor/embeds/Vimeo.tsx +++ b/shared/editor/embeds/Vimeo.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /(http|https)?:\/\/(www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|)(\d+)(?:\/|\?)?([\d\w]+)?/; diff --git a/shared/editor/embeds/Whimsical.tsx b/shared/editor/embeds/Whimsical.tsx index 3e71dc9aae..7e68127ce5 100644 --- a/shared/editor/embeds/Whimsical.tsx +++ b/shared/editor/embeds/Whimsical.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /^https?:\/\/whimsical.com\/[0-9a-zA-Z-_~]*-([a-zA-Z0-9]+)\/?$/; diff --git a/shared/editor/embeds/YouTube.tsx b/shared/editor/embeds/YouTube.tsx index 44127a8654..c3a873ef84 100644 --- a/shared/editor/embeds/YouTube.tsx +++ b/shared/editor/embeds/YouTube.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Frame from "./components/Frame"; +import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; const URL_REGEX = /(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([a-zA-Z0-9_-]{11})$/i; diff --git a/shared/editor/embeds/components/Simple.tsx b/shared/editor/embeds/components/Simple.tsx deleted file mode 100644 index 5243f9cb91..0000000000 --- a/shared/editor/embeds/components/Simple.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { OpenIcon } from "outline-icons"; -import * as React from "react"; -import styled, { DefaultTheme, ThemeProps } from "styled-components"; -import { EmbedProps as Props } from "../"; - -export default function Simple(props: Props & ThemeProps) { - return ( - - {props.embed.icon(undefined)} - - {props.embed.title} - {props.attrs.href.replace(/^https?:\/\//, "")} - - - - ); -} - -const StyledOpenIcon = styled(OpenIcon)` - margin-left: auto; -`; - -const Title = styled.strong` - font-weight: 500; - font-size: 14px; - color: ${(props) => props.theme.text}; -`; - -const Preview = styled.div` - gap: 8px; - display: flex; - flex-direction: row; - flex-grow: 1; - align-items: center; - color: ${(props) => props.theme.textTertiary}; -`; - -const Subtitle = styled.span` - font-size: 13px; - color: ${(props) => props.theme.textTertiary} !important; -`; - -const Wrapper = styled.a` - display: inline-flex; - align-items: flex-start; - gap: 4px; - box-sizing: border-box !important; - color: ${(props) => props.theme.text} !important; - background: ${(props) => props.theme.secondaryBackground}; - white-space: nowrap; - border-radius: 8px; - padding: 6px 8px; - max-width: 840px; - width: 100%; - text-overflow: ellipsis; - overflow: hidden; - - &:hover { - text-decoration: none !important; - outline: 2px solid ${(props) => props.theme.divider}; - } -`; diff --git a/shared/editor/embeds/index.tsx b/shared/editor/embeds/index.tsx index 59cf7423f0..4ac1d5a990 100644 --- a/shared/editor/embeds/index.tsx +++ b/shared/editor/embeds/index.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import styled from "styled-components"; import { EmbedDescriptor } from "@shared/editor/types"; +import Image from "../components/Image"; import Abstract from "./Abstract"; import Airtable from "./Airtable"; import Bilibili from "./Bilibili"; @@ -35,7 +36,6 @@ import Typeform from "./Typeform"; import Vimeo from "./Vimeo"; import Whimsical from "./Whimsical"; import YouTube from "./YouTube"; -import Image from "./components/Image"; export type EmbedProps = { isSelected: boolean; diff --git a/shared/editor/lib/uploadPlaceholder.ts b/shared/editor/lib/uploadPlaceholder.tsx similarity index 67% rename from shared/editor/lib/uploadPlaceholder.ts rename to shared/editor/lib/uploadPlaceholder.tsx index 21b88f7a53..07c910e97c 100644 --- a/shared/editor/lib/uploadPlaceholder.ts +++ b/shared/editor/lib/uploadPlaceholder.tsx @@ -1,5 +1,8 @@ import { EditorState, Plugin } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; +import * as React from "react"; +import ReactDOM from "react-dom"; +import FileExtension from "../components/FileExtension"; // based on the example at: https://prosemirror.net/examples/upload/ const uploadPlaceholder = new Plugin({ @@ -31,7 +34,7 @@ const uploadPlaceholder = new Plugin({ ); set = set.add(tr.doc, [deco]); } - } else { + } else if (action.add.isImage) { const element = document.createElement("div"); element.className = "image placeholder"; @@ -40,6 +43,30 @@ const uploadPlaceholder = new Plugin({ element.appendChild(img); + const deco = Decoration.widget(action.add.pos, element, { + id: action.add.id, + }); + set = set.add(tr.doc, [deco]); + } else { + const element = document.createElement("div"); + element.className = "attachment placeholder"; + + const icon = document.createElement("div"); + icon.className = "icon"; + + const component = ; + ReactDOM.render(component, icon); + element.appendChild(icon); + + const text = document.createElement("span"); + text.innerText = action.add.file.name; + element.appendChild(text); + + const status = document.createElement("span"); + status.innerText = "Uploading…"; + status.className = "status"; + element.appendChild(status); + const deco = Decoration.widget(action.add.pos, element, { id: action.add.id, }); diff --git a/shared/editor/nodes/Attachment.tsx b/shared/editor/nodes/Attachment.tsx new file mode 100644 index 0000000000..66c5a17cf6 --- /dev/null +++ b/shared/editor/nodes/Attachment.tsx @@ -0,0 +1,114 @@ +import Token from "markdown-it/lib/token"; +import { DownloadIcon } from "outline-icons"; +import { NodeSpec, NodeType, Node as ProsemirrorNode } from "prosemirror-model"; +import * as React from "react"; +import { Trans } from "react-i18next"; +import { bytesToHumanReadable } from "../../utils/files"; +import toggleWrap from "../commands/toggleWrap"; +import FileExtension from "../components/FileExtension"; +import Widget from "../components/Widget"; +import { MarkdownSerializerState } from "../lib/markdown/serializer"; +import attachmentsRule from "../rules/attachments"; +import { ComponentProps } from "../types"; +import Node from "./Node"; + +export default class Attachment extends Node { + get name() { + return "attachment"; + } + + get rulePlugins() { + return [attachmentsRule]; + } + + get schema(): NodeSpec { + return { + attrs: { + id: { + default: null, + }, + href: { + default: null, + }, + title: {}, + size: {}, + }, + group: "block", + defining: true, + atom: true, + parseDOM: [ + { + priority: 100, + tag: "a.attachment", + getAttrs: (dom: HTMLAnchorElement) => { + return { + id: dom.id, + title: dom.innerText, + href: dom.getAttribute("href"), + size: parseInt(dom.dataset.size || "0", 10), + }; + }, + }, + ], + toDOM: (node) => { + return [ + "a", + { + class: `attachment`, + id: node.attrs.id, + href: node.attrs.href, + download: node.attrs.title, + "data-size": node.attrs.size, + }, + node.attrs.title, + ]; + }, + }; + } + + component({ isSelected, theme, node }: ComponentProps) { + return ( + } + href={node.attrs.href} + title={node.attrs.title} + context={ + node.attrs.href ? ( + bytesToHumanReadable(node.attrs.size) + ) : ( + <> + Uploading… + + ) + } + isSelected={isSelected} + theme={theme} + > + {node.attrs.href && } + + ); + } + + commands({ type }: { type: NodeType }) { + return (attrs: Record) => toggleWrap(type, attrs); + } + + toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) { + state.ensureNewLine(); + state.write( + `[${node.attrs.title} ${node.attrs.size}](${node.attrs.href})\n\n` + ); + state.ensureNewLine(); + } + + parseMarkdown() { + return { + node: "attachment", + getAttrs: (tok: Token) => ({ + href: tok.attrGet("href"), + title: tok.attrGet("title"), + size: tok.attrGet("size"), + }), + }; + } +} diff --git a/shared/editor/nodes/CodeFence.ts b/shared/editor/nodes/CodeFence.ts index 754bb15651..392e4103fe 100644 --- a/shared/editor/nodes/CodeFence.ts +++ b/shared/editor/nodes/CodeFence.ts @@ -197,12 +197,10 @@ export default class CodeFence extends Node { const node = view.state.doc.nodeAt(result.pos); if (node) { copy(node.textContent); - if (this.options.onShowToast) { - this.options.onShowToast( - this.options.dictionary.codeCopied, - ToastType.Info - ); - } + this.options.onShowToast( + this.options.dictionary.codeCopied, + ToastType.Info + ); } } }; diff --git a/shared/editor/nodes/Embed.tsx b/shared/editor/nodes/Embed.tsx index d50de11098..bdda25f138 100644 --- a/shared/editor/nodes/Embed.tsx +++ b/shared/editor/nodes/Embed.tsx @@ -2,7 +2,7 @@ import Token from "markdown-it/lib/token"; import { NodeSpec, NodeType, Node as ProsemirrorNode } from "prosemirror-model"; import { EditorState, Transaction } from "prosemirror-state"; import * as React from "react"; -import Simple from "../embeds/components/Simple"; +import DisabledEmbed from "../components/DisabledEmbed"; import { MarkdownSerializerState } from "../lib/markdown/serializer"; import embedsRule from "../rules/embeds"; import { ComponentProps } from "../types"; @@ -94,7 +94,7 @@ export default class Embed extends Node { if (embedsDisabled) { return ( - paste(view, event: ClipboardEvent): boolean { if ( (view.props.editable && !view.props.editable(view.state)) || - !options.uploadImage + !options.uploadFile ) { return false; } @@ -48,8 +48,9 @@ const uploadPlugin = (options: Options) => // check if we actually pasted any files const files = Array.prototype.slice .call(event.clipboardData.items) - .map((dt: any) => dt.getAsFile()) - .filter((file: File) => file); + .filter((dt: DataTransferItem) => dt.kind !== "string") + .map((dt: DataTransferItem) => dt.getAsFile()) + .filter(Boolean); if (files.length === 0) { return false; @@ -67,15 +68,13 @@ const uploadPlugin = (options: Options) => drop(view, event: DragEvent): boolean { if ( (view.props.editable && !view.props.editable(view.state)) || - !options.uploadImage + !options.uploadFile ) { return false; } // filter to only include image files - const files = getDataTransferFiles(event).filter((file) => - /image/i.test(file.type) - ); + const files = getDataTransferFiles(event); if (files.length === 0) { return false; } @@ -430,14 +429,14 @@ export default class Image extends Node { replaceImage: () => (state: EditorState) => { const { view } = this.editor; const { - uploadImage, - onImageUploadStart, - onImageUploadStop, + uploadFile, + onFileUploadStart, + onFileUploadStop, onShowToast, } = this.editor.props; - if (!uploadImage) { - throw new Error("uploadImage prop is required to replace images"); + if (!uploadFile) { + throw new Error("uploadFile prop is required to replace images"); } // create an input element and click to trigger picker @@ -447,9 +446,9 @@ export default class Image extends Node { inputElement.onchange = (event: Event) => { const files = getDataTransferFiles(event); insertFiles(view, event, state.selection.from, files, { - uploadImage, - onImageUploadStart, - onImageUploadStop, + uploadFile, + onFileUploadStart, + onFileUploadStop, onShowToast, dictionary: this.options.dictionary, replaceExisting: true, diff --git a/shared/editor/queries/findAttachmentById.ts b/shared/editor/queries/findAttachmentById.ts new file mode 100644 index 0000000000..91968b9777 --- /dev/null +++ b/shared/editor/queries/findAttachmentById.ts @@ -0,0 +1,23 @@ +import { EditorState } from "prosemirror-state"; + +const findAttachmentById = function ( + state: EditorState, + id: string +): [number, number] | null { + let result: [number, number] | null = null; + + state.doc.descendants((node, pos) => { + if (result) { + return false; + } + if (node.type.name === "attachment" && node.attrs.id === id) { + result = [pos, pos + node.nodeSize]; + return false; + } + return true; + }); + + return result; +}; + +export default findAttachmentById; diff --git a/shared/editor/rules/attachments.ts b/shared/editor/rules/attachments.ts new file mode 100644 index 0000000000..328c96d01a --- /dev/null +++ b/shared/editor/rules/attachments.ts @@ -0,0 +1,82 @@ +import MarkdownIt from "markdown-it"; +import Token from "markdown-it/lib/token"; +import env from "../../env"; + +function isParagraph(token: Token) { + return token.type === "paragraph_open"; +} + +function isInline(token: Token) { + return token.type === "inline"; +} + +function isLinkOpen(token: Token) { + return token.type === "link_open"; +} + +function isLinkClose(token: Token) { + return token.type === "link_close"; +} + +function isAttachment(token: Token) { + const href = token.attrGet("href"); + return ( + href?.includes("attachments.redirect") || + href?.startsWith(env.AWS_S3_UPLOAD_BUCKET_URL) + ); +} + +export default function linksToAttachments(md: MarkdownIt) { + md.core.ruler.after("breaks", "attachments", (state) => { + const tokens = state.tokens; + let insideLink; + + for (let i = 0; i < tokens.length - 1; i++) { + // once we find an inline token look through it's children for links + if (isInline(tokens[i]) && isParagraph(tokens[i - 1])) { + const tokenChildren = tokens[i].children || []; + + for (let j = 0; j < tokenChildren.length - 1; j++) { + const current = tokenChildren[j]; + if (!current) { + continue; + } + + if (isLinkOpen(current)) { + insideLink = current; + continue; + } + + if (isLinkClose(current)) { + insideLink = null; + continue; + } + + // of hey, we found a link – lets check to see if it should be + // converted to a file attachment + if (insideLink && isAttachment(insideLink)) { + const { content } = current; + + // convert to attachment token + const token = new Token("attachment", "a", 0); + token.attrSet("href", insideLink.attrGet("href") || ""); + + const parts = content.split(" "); + const size = parts.pop(); + const title = parts.join(" "); + token.attrSet("size", size || "0"); + token.attrSet("title", title); + + // delete the inline link – this makes the assumption that the + // attachment is the only thing in the para. + tokens.splice(i - 1, 3, token); + insideLink = null; + break; + } + } + } + } + + return false; + }); +} diff --git a/shared/editor/rules/embeds.ts b/shared/editor/rules/embeds.ts index 1089ce8f5b..11c43837e0 100644 --- a/shared/editor/rules/embeds.ts +++ b/shared/editor/rules/embeds.ts @@ -18,7 +18,7 @@ function isLinkClose(token: Token) { return token.type === "link_close"; } -export default function (embeds: EmbedDescriptor[]) { +export default function linksToEmbeds(embeds: EmbedDescriptor[]) { function isEmbed(token: Token, link: Token) { const href = link.attrs ? link.attrs[0][1] : ""; const simpleLink = href === token.content; @@ -70,7 +70,7 @@ export default function (embeds: EmbedDescriptor[]) { } // of hey, we found a link – lets check to see if it should be - // considered to be an embed + // converted to an embed if (insideLink) { const result = isEmbed(current, insideLink); if (result) { @@ -82,7 +82,6 @@ export default function (embeds: EmbedDescriptor[]) { // delete the inline link – this makes the assumption that the // embed is the only thing in the para. - // TODO: double check this tokens.splice(i - 1, 3, token); break; } diff --git a/shared/editor/version.ts b/shared/editor/version.ts index 215a3e5a7f..b087359ec3 100644 --- a/shared/editor/version.ts +++ b/shared/editor/version.ts @@ -1,3 +1,3 @@ -const EDITOR_VERSION = "11.21.3"; +const EDITOR_VERSION = "12.0.0"; export default EDITOR_VERSION; diff --git a/shared/env.ts b/shared/env.ts new file mode 100644 index 0000000000..695e28be9d --- /dev/null +++ b/shared/env.ts @@ -0,0 +1,5 @@ +import { PublicEnv } from "./types"; + +const env = typeof window === "undefined" ? process.env : window.env; + +export default env as PublicEnv; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 65411e7bd2..eea46e6465 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -194,6 +194,7 @@ "Center large": "Center large", "Italic": "Italic", "Sorry, that link won’t work for this embed type": "Sorry, that link won’t work for this embed type", + "File attachment": "File attachment", "Find or create a doc": "Find or create a doc", "Big heading": "Big heading", "Medium heading": "Medium heading", @@ -201,7 +202,7 @@ "Heading": "Heading", "Divider": "Divider", "Image": "Image", - "Sorry, an error occurred uploading the image": "Sorry, an error occurred uploading the image", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Write a caption", "Info": "Info", "Info notice": "Info notice", diff --git a/shared/types.ts b/shared/types.ts index 03a8b5b16c..76d45f8a90 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -6,6 +6,7 @@ export type PublicEnv = { URL: string; CDN_URL: string; COLLABORATION_URL: string; + AWS_S3_UPLOAD_BUCKET_URL: string; DEPLOYMENT: "hosted" | ""; ENVIRONMENT: "production" | "development"; SENTRY_DSN: string | undefined; diff --git a/shared/utils/color.ts b/shared/utils/color.ts index d743728252..db17349fce 100644 --- a/shared/utils/color.ts +++ b/shared/utils/color.ts @@ -1,2 +1,29 @@ -export const validateColorHex = (color: string) => - /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color); +import md5 from "crypto-js/md5"; +import { darken } from "polished"; +import theme from "../theme"; + +export const palette = [ + theme.brand.red, + theme.brand.blue, + theme.brand.purple, + theme.brand.pink, + theme.brand.marine, + theme.brand.green, + theme.brand.yellow, + darken(0.2, theme.brand.red), + darken(0.2, theme.brand.blue), + darken(0.2, theme.brand.purple), + darken(0.2, theme.brand.pink), + darken(0.2, theme.brand.marine), + darken(0.2, theme.brand.green), + darken(0.2, theme.brand.yellow), +]; + +export const validateColorHex = (color: string) => { + return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color); +}; + +export const stringToColor = (input: string) => { + const inputAsNumber = parseInt(md5(input).toString(), 16); + return palette[inputAsNumber % palette.length]; +}; diff --git a/shared/utils/files.test.ts b/shared/utils/files.test.ts new file mode 100644 index 0000000000..4555f0689e --- /dev/null +++ b/shared/utils/files.test.ts @@ -0,0 +1,13 @@ +import { bytesToHumanReadable } from "./files"; + +describe("bytesToHumanReadable", () => { + test("Outputs readable string", () => { + expect(bytesToHumanReadable(0)).toBe("0 Bytes"); + expect(bytesToHumanReadable(500)).toBe("500 Bytes"); + expect(bytesToHumanReadable(1000)).toBe("1 kB"); + expect(bytesToHumanReadable(15000)).toBe("15 kB"); + expect(bytesToHumanReadable(12345)).toBe("12.34 kB"); + expect(bytesToHumanReadable(123456)).toBe("123.45 kB"); + expect(bytesToHumanReadable(1234567)).toBe("1.23 MB"); + }); +}); diff --git a/shared/utils/files.ts b/shared/utils/files.ts new file mode 100644 index 0000000000..9ab5f160f4 --- /dev/null +++ b/shared/utils/files.ts @@ -0,0 +1,21 @@ +/** + * Converts bytes to human readable string for display + * + * @param bytes filesize in bytes + * @returns Human readable filesize as a string + */ +export const bytesToHumanReadable = (bytes: number) => { + const out = ("0".repeat((bytes.toString().length * 2) % 3) + bytes).match( + /.{3}/g + ); + + if (!out || bytes < 1000) { + return bytes + " Bytes"; + } + + const f = out[1].substring(0, 2); + + return `${Number(out[0])}${f === "00" ? "" : `.${f}`} ${ + " kMGTPEZY"[out.length] + }B`; +}; diff --git a/yarn.lock b/yarn.lock index 2f661ff1a8..7bb7b8c28c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2642,6 +2642,11 @@ "@types/keygrip" "*" "@types/node" "*" +"@types/crypto-js@^4.1.0": + version "4.1.0" + resolved "https://registry.yarnpkg.com/@types/crypto-js/-/crypto-js-4.1.0.tgz#09ba1b49bcce62c9a8e6d5e50a3364aa98975578" + integrity sha512-DCFfy/vh2lG6qHSGezQ+Sn2Ulf/1Mx51dqOdmOKyW5nMK3maLlxeS3onC7r212OnBM2pBR95HkAmAjjF08YkxQ== + "@types/datadog-metrics@^0.6.2": version "0.6.2" resolved "https://registry.yarnpkg.com/@types/datadog-metrics/-/datadog-metrics-0.6.2.tgz#b3b2b9b4e7838cff07830472e8a8c8caa04514fa" @@ -5695,6 +5700,16 @@ crypto-browserify@^3.11.0: randombytes "^2.0.0" randomfill "^1.0.3" +crypto-js@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/crypto-js/-/crypto-js-4.1.1.tgz#9e485bcf03521041bd85844786b83fb7619736cf" + integrity sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw== + +crypto-random-string@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-1.0.0.tgz#a230f64f568310e1498009940790ec99545bca7e" + integrity sha1-ojD2T1aDEOFJgAmUB5DsmVRbyn4= + crypto-random-string@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-2.0.0.tgz#ef2a7a966ec11083388369baa02ebead229b30d5" From cf446be2df707b5c4b25df272bc4eb094ba9ad9c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Mar 2022 21:47:30 -0800 Subject: [PATCH 003/187] fix: Dragging strings into document can attempt (and file) to insert as attachment --- shared/editor/nodes/Image.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index 034b3a3b71..1c5618fe9b 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -74,7 +74,9 @@ const uploadPlugin = (options: Options) => } // filter to only include image files - const files = getDataTransferFiles(event); + const files = getDataTransferFiles(event).filter( + (dt: any) => dt.kind !== "string" + ); if (files.length === 0) { return false; } From 9a7090d5285988c188878543538e1beb6c1081f9 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Mar 2022 21:49:44 -0800 Subject: [PATCH 004/187] fix: Finicky clicking on file attachments --- shared/editor/marks/Link.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/shared/editor/marks/Link.tsx b/shared/editor/marks/Link.tsx index 5011e3ef6e..b9a25d5ea7 100644 --- a/shared/editor/marks/Link.tsx +++ b/shared/editor/marks/Link.tsx @@ -176,6 +176,10 @@ export default class Link extends Mark { return false; } + if (event.target.classList.contains("attachment")) { + return false; + } + // clicking a link while editing should show the link toolbar, // clicking in read-only will navigate if (!view.editable || (view.editable && !view.hasFocus())) { From 80be26b2dec4b009d209165becade7f30ffa38ba Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Mar 2022 21:56:52 -0800 Subject: [PATCH 005/187] fix: Border of file attachment not rounded in Safari (outline -> box shadow) --- shared/editor/components/Widget.tsx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/shared/editor/components/Widget.tsx b/shared/editor/components/Widget.tsx index bf0bc057f4..313dbad5ab 100644 --- a/shared/editor/components/Widget.tsx +++ b/shared/editor/components/Widget.tsx @@ -67,7 +67,7 @@ const Wrapper = styled.a` gap: 6px; background: ${(props) => props.theme.background}; color: ${(props) => props.theme.text} !important; - outline: 1px solid ${(props) => props.theme.divider}; + box-shadow: 0 0 0 1px ${(props) => props.theme.divider}; white-space: nowrap; border-radius: 8px; padding: 6px 8px; @@ -82,13 +82,10 @@ const Wrapper = styled.a` props.href && css` &:hover, - &:active, - &:focus, - &:focus:not(.focus-visible) { + &:active { cursor: pointer !important; text-decoration: none !important; background: ${(props) => props.theme.secondaryBackground}; - outline: 1px solid ${(props) => props.theme.divider}; ${Children} { opacity: 1; From 85f333b2fd3f9a17a297c6b0f9c594cdecb188f9 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Mar 2022 22:52:41 -0800 Subject: [PATCH 006/187] fix: Finicky clicking on file attachments #2 --- shared/editor/marks/Link.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/shared/editor/marks/Link.tsx b/shared/editor/marks/Link.tsx index b9a25d5ea7..efea8bcdbc 100644 --- a/shared/editor/marks/Link.tsx +++ b/shared/editor/marks/Link.tsx @@ -176,7 +176,7 @@ export default class Link extends Mark { return false; } - if (event.target.classList.contains("attachment")) { + if (event.target.matches(".component-attachment *")) { return false; } @@ -211,6 +211,10 @@ export default class Link extends Mark { return false; } + if (event.target.matches(".component-attachment *")) { + return false; + } + // Prevent all default click behavior of links, see mousedown above // for custom link handling. if (this.options.onClickLink) { From 79ba8dad30bfa202fa842bdc645ae7f3eff407e1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 8 Mar 2022 16:41:02 -0800 Subject: [PATCH 007/187] chore: Improve tracing --- server/logging/sentry.ts | 10 ++++++---- server/middlewares/authentication.ts | 11 +++++++++++ server/tracing.ts | 7 ++++--- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/server/logging/sentry.ts b/server/logging/sentry.ts index efcbd8fc5f..c1948c6aab 100644 --- a/server/logging/sentry.ts +++ b/server/logging/sentry.ts @@ -35,15 +35,17 @@ export function requestErrorHandler(error: any, ctx: ContextWithState) { scope.setTag("request_id", requestId as string); } - const authType = ctx.state ? ctx.state.authType : undefined; - + const authType = ctx.state?.authType ?? undefined; if (authType) { scope.setTag("auth_type", authType); } - const userId = - ctx.state && ctx.state.user ? ctx.state.user.id : undefined; + const teamId = ctx.state?.user?.teamId ?? undefined; + if (teamId) { + scope.setTag("team_id", teamId); + } + const userId = ctx.state?.user?.id ?? undefined; if (userId) { scope.setUser({ id: userId, diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 4b13828fc5..b90d2d2d58 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -1,5 +1,6 @@ import { Next } from "koa"; import { User, Team, ApiKey } from "@server/models"; +import tracer from "@server/tracing"; import { getUserForJWT } from "@server/utils/jwt"; import { AuthenticationError, UserSuspendedError } from "../errors"; import { ContextWithState } from "../types"; @@ -97,6 +98,16 @@ export default function auth( user.updateActiveAt(ctx.request.ip); ctx.state.token = String(token); ctx.state.user = user; + + if (tracer) { + const span = tracer.scope().active(); + console.log(span); + if (span !== null) { + span.setTag("request.userId", user.id); + span.setTag("request.teamId", user.teamId); + span.setTag("request.authType", ctx.state.authType); + } + } } return next(); diff --git a/server/tracing.ts b/server/tracing.ts index a2d0d94e78..74c4f8dc73 100644 --- a/server/tracing.ts +++ b/server/tracing.ts @@ -1,12 +1,13 @@ +import tracer from "dd-trace"; + // If the DataDog agent is installed and the DD_API_KEY environment variable is // in the environment then we can safely attempt to start the DD tracer if (process.env.DD_API_KEY) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - require("dd-trace").init({ + tracer.init({ // SOURCE_COMMIT is used by Docker Hub // SOURCE_VERSION is used by Heroku version: process.env.SOURCE_COMMIT || process.env.SOURCE_VERSION, }); } -export {}; +export default tracer; From c1e8b6c823fe6626dbb03292cc213fb8f83f5813 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 8 Mar 2022 16:51:47 -0800 Subject: [PATCH 008/187] perf: Remove unneccessary join from documents.viewed --- server/middlewares/authentication.ts | 1 - server/routes/api/documents.ts | 9 --------- 2 files changed, 10 deletions(-) diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index b90d2d2d58..c9c02270c0 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -101,7 +101,6 @@ export default function auth( if (tracer) { const span = tracer.scope().active(); - console.log(span); if (span !== null) { span.setTag("request.userId", user.id); span.setTag("request.teamId", user.teamId); diff --git a/server/routes/api/documents.ts b/server/routes/api/documents.ts index 872e41ff4e..76214a85de 100644 --- a/server/routes/api/documents.ts +++ b/server/routes/api/documents.ts @@ -283,15 +283,6 @@ router.post("documents.viewed", auth(), pagination(), async (ctx) => { collectionId: collectionIds, }, include: [ - { - model: Star, - as: "starred", - where: { - userId, - }, - separate: true, - required: false, - }, { model: Collection.scope({ method: ["withMembership", userId], From 31e15f798c896d39d5f345a817989215a9faae25 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Mar 2022 17:33:55 -0800 Subject: [PATCH 009/187] chore: Remove unused DocumentList component --- app/components/DocumentList.tsx | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 app/components/DocumentList.tsx diff --git a/app/components/DocumentList.tsx b/app/components/DocumentList.tsx deleted file mode 100644 index bca9e7d18d..0000000000 --- a/app/components/DocumentList.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import ArrowKeyNavigation from "boundless-arrow-key-navigation"; -import * as React from "react"; -import Document from "~/models/Document"; -import DocumentListItem from "~/components/DocumentListItem"; - -type Props = { - documents: Document[]; - limit?: number; - showCollection?: boolean; - showPublished?: boolean; - showPin?: boolean; - showDraft?: boolean; - showTemplate?: boolean; -}; - -export default function DocumentList({ limit, documents, ...rest }: Props) { - const items = limit ? documents.splice(0, limit) : documents; - return ( - - {items.map((document) => ( - - ))} - - ); -} From 5efeb90fdda3aa972a84bc99ac043084853fffe8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Mar 2022 20:07:01 -0800 Subject: [PATCH 010/187] fix: SVGs without a natural px width are invisible (#3220) --- shared/editor/nodes/Image.tsx | 90 ++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 32 deletions(-) diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index 1c5618fe9b..73ca580a0f 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -295,35 +295,12 @@ export default class Image extends Node { }; component = (props: ComponentProps) => { - const { theme, isSelected } = props; - const { alt, src, layoutClass } = props.node.attrs; - const className = layoutClass ? `image image-${layoutClass}` : "image"; - return ( -
- - - - + - {alt} + {props.node.attrs.alt} -
+ ); }; @@ -520,6 +497,53 @@ export default class Image extends Node { } } +const ImageComponent = ( + props: ComponentProps & { + onClick: (event: React.MouseEvent) => void; + onDownload: (event: React.MouseEvent) => void; + children: React.ReactNode; + } +) => { + const { theme, isSelected, node } = props; + const { alt, src, layoutClass } = node.attrs; + const className = layoutClass ? `image image-${layoutClass}` : "image"; + const [width, setWidth] = React.useState(0); + + return ( +
+ + + { + // For some SVG's Firefox does not provide the naturalWidth, in this + // rare case we need to provide a default so that the image can be + // seen and is not sized to 0px + setWidth(ev.target.naturalWidth || "50%"); + }, + }} + defaultStyles={{ + overlay: { + backgroundColor: theme.background, + }, + }} + shouldRespectMaxDimension + /> + + {props.children} +
+ ); +}; + const Button = styled.button` position: absolute; top: 8px; @@ -576,10 +600,12 @@ const Caption = styled.p` } `; -const ImageWrapper = styled.span` +const ImageWrapper = styled.div` line-height: 0; - display: inline-block; position: relative; + margin-left: auto; + margin-right: auto; + max-width: 100%; &:hover { ${Button} { From d399e1048a92dea75c2bfc6f873a81220a1b8167 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Mar 2022 20:07:10 -0800 Subject: [PATCH 011/187] perf: Don't load CRDT state from database by default (#3215) --- server/collaboration/persistence.ts | 6 +++++- server/commands/documentPermanentDeleter.ts | 2 +- server/commands/documentUpdater.ts | 4 ++-- server/models/Document.ts | 19 +++++++++++++++++-- server/models/Share.ts | 2 +- server/routes/api/utils.ts | 2 +- 6 files changed, 27 insertions(+), 8 deletions(-) diff --git a/server/collaboration/persistence.ts b/server/collaboration/persistence.ts index 83b1f49ccd..5eae3fb870 100644 --- a/server/collaboration/persistence.ts +++ b/server/collaboration/persistence.ts @@ -20,7 +20,11 @@ export default class Persistence { return; } - const document = await Document.findByPk(documentId); + const document = await Document.scope("withState").findOne({ + where: { + id: documentId, + }, + }); invariant(document, "Document not found"); if (document.state) { diff --git a/server/commands/documentPermanentDeleter.ts b/server/commands/documentPermanentDeleter.ts index cc1a144a57..8e2b92c381 100644 --- a/server/commands/documentPermanentDeleter.ts +++ b/server/commands/documentPermanentDeleter.ts @@ -52,7 +52,7 @@ export default async function documentPermanentDeleter(documents: Document[]) { } } - return Document.scope("withUnpublished").destroy({ + return Document.scope("withDrafts").destroy({ where: { id: documents.map((document) => document.id), }, diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index 0df3e6b932..3bcc552bd8 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -15,7 +15,7 @@ export default async function documentUpdater({ ydoc: Y.Doc; userId?: string; }) { - const document = await Document.findByPk(documentId); + const document = await Document.scope("withState").findByPk(documentId); invariant(document, "document not found"); const state = Y.encodeStateAsUpdate(ydoc); @@ -34,7 +34,7 @@ export default async function documentUpdater({ const existingIds = document.collaboratorIds; const collaboratorIds = uniq([...pudIds, ...existingIds]); - await Document.scope("withUnpublished").update( + await Document.scope(["withDrafts", "withState"]).update( { text, state: Buffer.from(state), diff --git a/server/models/Document.ts b/server/models/Document.ts index a105ca0bfb..9b8159be73 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -69,6 +69,9 @@ const serializer = new MarkdownSerializer(); export const DOCUMENT_VERSION = 2; @DefaultScope(() => ({ + attributes: { + exclude: ["state"], + }, include: [ { model: User, @@ -112,7 +115,18 @@ export const DOCUMENT_VERSION = 2; ], }; }, - withUnpublished: { + withoutState: { + attributes: { + exclude: ["state"], + }, + }, + withState: { + attributes: { + // resets to include the state column + exclude: [], + }, + }, + withDrafts: { include: [ { model: User, @@ -370,7 +384,8 @@ class Document extends ParanoidModel { // allow default preloading of collection membership if `userId` is passed in find options // almost every endpoint needs the collection membership to determine policy permissions. const scope = this.scope([ - "withUnpublished", + "withoutState", + "withDrafts", { method: ["withCollection", options.userId, options.paranoid], }, diff --git a/server/models/Share.ts b/server/models/Share.ts index 148c806379..20ad32bc54 100644 --- a/server/models/Share.ts +++ b/server/models/Share.ts @@ -34,7 +34,7 @@ import Fix from "./decorators/Fix"; return { include: [ { - model: Document.scope("withUnpublished"), + model: Document.scope("withDrafts"), paranoid: true, as: "document", include: [ diff --git a/server/routes/api/utils.ts b/server/routes/api/utils.ts index 6867e72105..ccb9a9c080 100644 --- a/server/routes/api/utils.ts +++ b/server/routes/api/utils.ts @@ -20,7 +20,7 @@ router.post("utils.gc", async (ctx) => { "utils", `Permanently destroying upto ${limit} documents older than 30 days…` ); - const documents = await Document.scope("withUnpublished").findAll({ + const documents = await Document.scope("withDrafts").findAll({ attributes: ["id", "teamId", "text", "deletedAt"], where: { deletedAt: { From fd9ef3ab22477ac81adaf1ed5a04b534ef90db3b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Mar 2022 09:02:23 -0800 Subject: [PATCH 012/187] perf: Document.state still queried in documents.search endpoint --- server/models/Document.ts | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/server/models/Document.ts b/server/models/Document.ts index 9b8159be73..cca01e9f51 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -610,6 +610,7 @@ class Document extends ParanoidModel { // Final query to get associated document data const documents = await this.scope([ + "defaultScope", { method: ["withViews", user.id], }, @@ -620,18 +621,6 @@ class Document extends ParanoidModel { where: { id: map(results, "id"), }, - include: [ - { - model: User, - as: "createdBy", - paranoid: false, - }, - { - model: User, - as: "updatedBy", - paranoid: false, - }, - ], }); return { results: map(results, (result: any) => ({ From f36e18e3a6f81afd437be950fd3063550b2a3c11 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Mar 2022 09:17:29 -0800 Subject: [PATCH 013/187] perf: Document.state still queried in documents.search endpoint --- server/models/Document.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/models/Document.ts b/server/models/Document.ts index cca01e9f51..28b877fcd8 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -610,7 +610,8 @@ class Document extends ParanoidModel { // Final query to get associated document data const documents = await this.scope([ - "defaultScope", + "withoutState", + "withDrafts", { method: ["withViews", user.id], }, From 503598e16d244c6ecb49cf06c7519a41d2a8ad18 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Mar 2022 18:10:33 -0800 Subject: [PATCH 014/187] perf: Add missing indexes to views table --- .../migrations/20220311020825-views-indexes.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 server/migrations/20220311020825-views-indexes.js diff --git a/server/migrations/20220311020825-views-indexes.js b/server/migrations/20220311020825-views-indexes.js new file mode 100644 index 0000000000..47c1d7253c --- /dev/null +++ b/server/migrations/20220311020825-views-indexes.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.addIndex("views", ["userId"], { + name: "views_user_id", + }); + await queryInterface.addIndex("views", ["updatedAt"], { + name: "views_updated_at", + }); + }, + + down: async (queryInterface, Sequelize) => { + await queryInterface.removeIndex("views", "views_updated_at"); + await queryInterface.removeIndex("views", "views_user_id"); + } +}; From 2ef827ee6f2270d4b01e76038352b6c9bf93fe48 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Mar 2022 18:13:18 -0800 Subject: [PATCH 015/187] perf: Add teamId to search query to help with query planning --- server/models/Document.ts | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/server/models/Document.ts b/server/models/Document.ts index 28b877fcd8..64548bda1b 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -477,26 +477,18 @@ class Document extends ParanoidModel { resultsQuery, countQuery, ]); + // Final query to get associated document data const documents = await this.findAll({ where: { id: map(results, "id"), + teamId: team.id, }, include: [ { model: Collection, as: "collection", }, - { - model: User, - as: "createdBy", - paranoid: false, - }, - { - model: User, - as: "updatedBy", - paranoid: false, - }, ], }); @@ -620,9 +612,11 @@ class Document extends ParanoidModel { }, ]).findAll({ where: { + teamId: user.teamId, id: map(results, "id"), }, }); + return { results: map(results, (result: any) => ({ ranking: result.searchRanking, From 36f90b3a468b5740705193dca3ba45cae900b232 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Mar 2022 18:50:28 -0800 Subject: [PATCH 016/187] perf: Additional missing index --- server/migrations/20220311020825-views-indexes.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/server/migrations/20220311020825-views-indexes.js b/server/migrations/20220311020825-views-indexes.js index 47c1d7253c..74331a1b5f 100644 --- a/server/migrations/20220311020825-views-indexes.js +++ b/server/migrations/20220311020825-views-indexes.js @@ -8,10 +8,14 @@ module.exports = { await queryInterface.addIndex("views", ["updatedAt"], { name: "views_updated_at", }); + await queryInterface.addIndex("collection_users", ["userId"], { + name: "collection_users_user_id", + }); }, down: async (queryInterface, Sequelize) => { await queryInterface.removeIndex("views", "views_updated_at"); await queryInterface.removeIndex("views", "views_user_id"); + await queryInterface.removeIndex("collection_users", "collection_users_user_id"); } }; From d8104c6cb6474f8a54b6fe19eee2b7c5444120f1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Mar 2022 15:45:57 -0800 Subject: [PATCH 017/187] fix: Detect Pomerium proxy (#3219) * chore: Remove unused DocumentList component * fix: Add support for detecting Pomerium * Refactor to avoid reading cookies on every request * refactor: Just enable cookies for all self-hosted builds * Remove unused userAgent * test: Add window.env to mock --- __mocks__/window.js | 3 ++- app/utils/ApiClient.ts | 21 ++++++++------------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/__mocks__/window.js b/__mocks__/window.js index 3b827de32b..3c3a486fb0 100644 --- a/__mocks__/window.js +++ b/__mocks__/window.js @@ -1 +1,2 @@ -window.matchMedia = data => data; +window.matchMedia = (data) => data; +window.env = {}; diff --git a/app/utils/ApiClient.ts b/app/utils/ApiClient.ts index 42a70309b1..55441a5be8 100644 --- a/app/utils/ApiClient.ts +++ b/app/utils/ApiClient.ts @@ -1,9 +1,9 @@ import retry from "fetch-retry"; import invariant from "invariant"; import { map, trim } from "lodash"; -import { getCookie } from "tiny-cookie"; import EDITOR_VERSION from "@shared/editor/version"; import stores from "~/stores"; +import env from "~/env"; import download from "./download"; import { AuthorizationError, @@ -19,21 +19,15 @@ import { type Options = { baseUrl?: string; }; -// authorization cookie set by a Cloudflare Access proxy -const CF_AUTHORIZATION = getCookie("CF_Authorization"); -// if the cookie is set, we must pass it with all ApiClient requests -const CREDENTIALS = CF_AUTHORIZATION ? "same-origin" : "omit"; const fetchWithRetry = retry(fetch); +const isHosted = env.DEPLOYMENT === "hosted"; class ApiClient { baseUrl: string; - userAgent: string; - constructor(options: Options = {}) { this.baseUrl = options.baseUrl || "/api"; - this.userAgent = "OutlineFrontend"; } fetch = async ( @@ -105,7 +99,11 @@ class ApiClient { body, headers, redirect: "follow", - credentials: CREDENTIALS, + // For the hosted deployment we omit cookies on API requests as they are + // not needed for authentication this offers a performance increase. + // For self-hosted we include them to support a wide variety of + // authenticated proxies, e.g. Pomerium, Cloudflare Access etc. + credentials: isHosted ? "omit" : "same-origin", cache: "no-cache", }); } catch (err) { @@ -203,8 +201,7 @@ class ApiClient { return this.fetch(path, "POST", data, options); }; - // Helpers - constructQueryString = (data: Record) => { + private constructQueryString = (data: Record) => { return map( data, (v, k) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}` @@ -212,6 +209,4 @@ class ApiClient { }; } -export default ApiClient; // In case you don't want to always initiate, just import with `import { client } ...` - export const client = new ApiClient(); From b7097654b59658103b5664dcce5a67bae725591a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Mar 2022 15:46:13 -0800 Subject: [PATCH 018/187] chore: Allow `Button` s to take action prop (#3204) * Add ability for NudeButton to take action+context * Add example usage * Refactor to ActionButton, convert another example * Remove dupe label --- app/components/ActionButton.tsx | 73 +++++++++++++++++++ app/components/NudeButton.tsx | 16 ++-- .../Sidebar/components/CollectionLink.tsx | 30 ++++---- app/components/Star.tsx | 25 ++----- app/components/Tooltip.tsx | 2 +- app/hooks/useActionContext.ts | 1 + app/types.ts | 1 + 7 files changed, 109 insertions(+), 39 deletions(-) create mode 100644 app/components/ActionButton.tsx diff --git a/app/components/ActionButton.tsx b/app/components/ActionButton.tsx new file mode 100644 index 0000000000..4472a0e6d7 --- /dev/null +++ b/app/components/ActionButton.tsx @@ -0,0 +1,73 @@ +import * as React from "react"; +import Tooltip, { Props as TooltipProps } from "~/components/Tooltip"; +import { Action, ActionContext } from "~/types"; + +export type Props = { + /** Show the button in a disabled state */ + disabled?: boolean; + /** Hide the button entirely if action is not applicable */ + hideOnActionDisabled?: boolean; + /** Action to use on button */ + action?: Action; + /** Context of action, must be provided with action */ + context?: ActionContext; + /** If tooltip props are provided the button will be wrapped in a tooltip */ + tooltip?: Omit; +}; + +/** + * Button that can be used to trigger an action definition. + */ +const ActionButton = React.forwardRef( + ( + { + action, + context, + tooltip, + hideOnActionDisabled, + ...rest + }: Props & React.HTMLAttributes, + ref: React.Ref + ) => { + const disabled = rest.disabled; + + if (!context || !action) { + return + ); + + if (tooltip) { + return {button}; + } + + return button; + } +); + +export default ActionButton; diff --git a/app/components/NudeButton.tsx b/app/components/NudeButton.tsx index 558428669a..8412c2bf52 100644 --- a/app/components/NudeButton.tsx +++ b/app/components/NudeButton.tsx @@ -1,12 +1,18 @@ import styled from "styled-components"; +import ActionButton, { + Props as ActionButtonProps, +} from "~/components/ActionButton"; -const Button = styled.button.attrs((props) => ({ - type: "type" in props ? props.type : "button", -}))<{ +type Props = ActionButtonProps & { width?: number; height?: number; size?: number; -}>` + type?: "button" | "submit" | "reset"; +}; + +const StyledNudeButton = styled(ActionButton).attrs((props: Props) => ({ + type: "type" in props ? props.type : "button", +}))` width: ${(props) => props.width || props.size || 24}px; height: ${(props) => props.height || props.size || 24}px; background: none; @@ -20,4 +26,4 @@ const Button = styled.button.attrs((props) => ({ color: inherit; `; -export default Button; +export default StyledNudeButton; diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index da094d60da..6484b94105 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -4,7 +4,7 @@ import { PlusIcon } from "outline-icons"; import * as React from "react"; import { useDrop, useDrag, DropTargetMonitor } from "react-dnd"; import { useTranslation } from "react-i18next"; -import { useLocation, useHistory, Link } from "react-router-dom"; +import { useLocation, useHistory } from "react-router-dom"; import styled from "styled-components"; import { sortNavigationNodes } from "@shared/utils/collections"; import Collection from "~/models/Collection"; @@ -14,13 +14,13 @@ import CollectionIcon from "~/components/CollectionIcon"; import Fade from "~/components/Fade"; import Modal from "~/components/Modal"; import NudeButton from "~/components/NudeButton"; -import Tooltip from "~/components/Tooltip"; +import { createDocument } from "~/actions/definitions/documents"; +import useActionContext from "~/hooks/useActionContext"; import useBoolean from "~/hooks/useBoolean"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import CollectionMenu from "~/menus/CollectionMenu"; import { NavigationNode } from "~/types"; -import { newDocumentPath } from "~/utils/routeHelpers"; import DocumentLink from "./DocumentLink"; import DropCursor from "./DropCursor"; import DropToImport from "./DropToImport"; @@ -220,6 +220,10 @@ function CollectionLink({ } }, [collection.id, ui.activeCollectionId, search]); + const context = useActionContext({ + activeCollectionId: collection.id, + }); + return ( <> @@ -259,18 +263,14 @@ function CollectionLink({ !isEditing && !isDraggingAnyCollection && ( - {can.update && ( - - - - - - )} + + + ) => { - ev.preventDefault(); - ev.stopPropagation(); - - if (document.isStarred) { - document.unstar(); - } else { - document.star(); - } - }, - [document] - ); + const context = useActionContext({ + activeDocumentId: document.id, + }); if (!document) { return null; @@ -35,9 +24,9 @@ function Star({ size, document, ...rest }: Props) { return ( {document.isStarred ? ( diff --git a/app/components/Tooltip.tsx b/app/components/Tooltip.tsx index 00f4704e1f..98ae515f3e 100644 --- a/app/components/Tooltip.tsx +++ b/app/components/Tooltip.tsx @@ -3,7 +3,7 @@ import { TFunctionResult } from "i18next"; import * as React from "react"; import styled from "styled-components"; -type Props = Omit & { +export type Props = Omit & { tooltip: React.ReactChild | React.ReactChild[] | TFunctionResult; shortcut?: React.ReactNode; }; diff --git a/app/hooks/useActionContext.ts b/app/hooks/useActionContext.ts index c5be365482..e006bf1715 100644 --- a/app/hooks/useActionContext.ts +++ b/app/hooks/useActionContext.ts @@ -20,6 +20,7 @@ export default function useActionContext( return { isContextMenu: false, isCommandBar: false, + isButton: false, activeCollectionId: stores.ui.activeCollectionId, activeDocumentId: stores.ui.activeDocumentId, currentUserId: stores.auth.user?.id, diff --git a/app/types.ts b/app/types.ts index 6563d7edc4..2a7dccc2a7 100644 --- a/app/types.ts +++ b/app/types.ts @@ -69,6 +69,7 @@ export type MenuItem = export type ActionContext = { isContextMenu: boolean; isCommandBar: boolean; + isButton: boolean; activeCollectionId: string | undefined; activeDocumentId: string | undefined; currentUserId: string | undefined; From f867704106be853eebd731da36faf9469cf15248 Mon Sep 17 00:00:00 2001 From: Translate-O-Tron <75237327+outline-translations@users.noreply.github.com> Date: Sat, 12 Mar 2022 15:46:25 -0800 Subject: [PATCH 019/187] New Crowdin updates (#3176) * fix: New French translations from Crowdin [ci skip] * fix: New Portuguese translations from Crowdin [ci skip] * fix: New Persian translations from Crowdin [ci skip] * fix: New Portuguese, Brazilian translations from Crowdin [ci skip] * fix: New Chinese Traditional translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New Swedish translations from Crowdin [ci skip] * fix: New Russian translations from Crowdin [ci skip] * fix: New Polish translations from Crowdin [ci skip] * fix: New Spanish translations from Crowdin [ci skip] * fix: New Italian translations from Crowdin [ci skip] * fix: New German translations from Crowdin [ci skip] * fix: New Danish translations from Crowdin [ci skip] * fix: New Japanese translations from Crowdin [ci skip] * fix: New Dutch translations from Crowdin [ci skip] * fix: New Vietnamese translations from Crowdin [ci skip] * fix: New Korean translations from Crowdin [ci skip] * fix: New Thai translations from Crowdin [ci skip] * fix: New Korean translations from Crowdin [ci skip] * fix: New Korean translations from Crowdin [ci skip] * fix: New French translations from Crowdin [ci skip] * fix: New Portuguese translations from Crowdin [ci skip] * fix: New Persian translations from Crowdin [ci skip] * fix: New Portuguese, Brazilian translations from Crowdin [ci skip] * fix: New Chinese Traditional translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New Swedish translations from Crowdin [ci skip] * fix: New Russian translations from Crowdin [ci skip] * fix: New Polish translations from Crowdin [ci skip] * fix: New Spanish translations from Crowdin [ci skip] * fix: New Italian translations from Crowdin [ci skip] * fix: New German translations from Crowdin [ci skip] * fix: New Danish translations from Crowdin [ci skip] * fix: New Japanese translations from Crowdin [ci skip] * fix: New Dutch translations from Crowdin [ci skip] * fix: New Vietnamese translations from Crowdin [ci skip] * fix: New Korean translations from Crowdin [ci skip] * fix: New Thai translations from Crowdin [ci skip] * fix: New French translations from Crowdin [ci skip] * fix: New French translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New French translations from Crowdin [ci skip] * fix: New Portuguese translations from Crowdin [ci skip] * fix: New Persian translations from Crowdin [ci skip] * fix: New Portuguese, Brazilian translations from Crowdin [ci skip] * fix: New Chinese Traditional translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New Swedish translations from Crowdin [ci skip] * fix: New Russian translations from Crowdin [ci skip] * fix: New Polish translations from Crowdin [ci skip] * fix: New Spanish translations from Crowdin [ci skip] * fix: New Italian translations from Crowdin [ci skip] * fix: New German translations from Crowdin [ci skip] * fix: New Danish translations from Crowdin [ci skip] * fix: New Japanese translations from Crowdin [ci skip] * fix: New Dutch translations from Crowdin [ci skip] * fix: New Vietnamese translations from Crowdin [ci skip] * fix: New Korean translations from Crowdin [ci skip] * fix: New Thai translations from Crowdin [ci skip] * fix: New Portuguese, Brazilian translations from Crowdin [ci skip] * fix: New Portuguese, Brazilian translations from Crowdin [ci skip] * fix: New Chinese Simplified translations from Crowdin [ci skip] * fix: New French translations from Crowdin [ci skip] * fix: New Polish translations from Crowdin [ci skip] * fix: New Polish translations from Crowdin [ci skip] * fix: New Russian translations from Crowdin [ci skip] --- shared/i18n/locales/da_DK/translation.json | 12 +-- shared/i18n/locales/de_DE/translation.json | 12 +-- shared/i18n/locales/es_ES/translation.json | 12 +-- shared/i18n/locales/fa_IR/translation.json | 12 +-- shared/i18n/locales/fr_FR/translation.json | 52 ++++++------ shared/i18n/locales/it_IT/translation.json | 12 +-- shared/i18n/locales/ja_JP/translation.json | 12 +-- shared/i18n/locales/ko_KR/translation.json | 32 ++++---- shared/i18n/locales/nl_NL/translation.json | 12 +-- shared/i18n/locales/pl_PL/translation.json | 84 ++++++++++---------- shared/i18n/locales/pt_BR/translation.json | 50 ++++++------ shared/i18n/locales/pt_PT/translation.json | 12 +-- shared/i18n/locales/ru_RU/translation.json | 92 +++++++++++----------- shared/i18n/locales/sv_SE/translation.json | 12 +-- shared/i18n/locales/th_TH/translation.json | 12 +-- shared/i18n/locales/vi_VN/translation.json | 12 +-- shared/i18n/locales/zh_CN/translation.json | 36 +++++---- shared/i18n/locales/zh_TW/translation.json | 12 +-- 18 files changed, 263 insertions(+), 227 deletions(-) diff --git a/shared/i18n/locales/da_DK/translation.json b/shared/i18n/locales/da_DK/translation.json index ff820c50b3..eea46e6465 100644 --- a/shared/i18n/locales/da_DK/translation.json +++ b/shared/i18n/locales/da_DK/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Print", "Print document": "Print document", "Import document": "Import document", @@ -139,6 +140,7 @@ "Document archived": "Document archived", "Move document": "Move document", "Collections": "Collections", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Untitled", "New nested document": "New nested document", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document not supported – try Markdown, Plain text, HTML, or Word", @@ -192,6 +194,7 @@ "Center large": "Center large", "Italic": "Italic", "Sorry, that link won’t work for this embed type": "Sorry, that link won’t work for this embed type", + "File attachment": "File attachment", "Find or create a doc": "Find or create a doc", "Big heading": "Big heading", "Medium heading": "Medium heading", @@ -199,7 +202,7 @@ "Heading": "Heading", "Divider": "Divider", "Image": "Image", - "Sorry, an error occurred uploading the image": "Sorry, an error occurred uploading the image", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Write a caption", "Info": "Info", "Info notice": "Info notice", @@ -231,16 +234,15 @@ "Path to document": "Path to document", "Group member options": "Group member options", "Remove": "Remove", + "Sort in sidebar": "Sort in sidebar", + "Alphabetical sort": "Alphabetical sort", + "Manual sort": "Manual sort", "Edit": "Edit", "Permissions": "Permissions", "Delete": "Delete", "Collection permissions": "Collection permissions", "Delete collection": "Delete collection", "Export collection": "Export collection", - "Show sort menu": "Show sort menu", - "Sort in sidebar": "Sort in sidebar", - "Alphabetical sort": "Alphabetical sort", - "Manual sort": "Manual sort", "Document restored": "Document restored", "Document unpublished": "Document unpublished", "Document options": "Document options", diff --git a/shared/i18n/locales/de_DE/translation.json b/shared/i18n/locales/de_DE/translation.json index 532f1ef528..5a28a3664d 100644 --- a/shared/i18n/locales/de_DE/translation.json +++ b/shared/i18n/locales/de_DE/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Drucken", "Print document": "Dokument drucken", "Import document": "Dokument importieren", @@ -139,6 +140,7 @@ "Document archived": "Dokument archiviert", "Move document": "Dokument verschieben", "Collections": "Sammlungen", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Ohne Titel", "New nested document": "Neues verschachteltes Dokument", "Document not supported – try Markdown, Plain text, HTML, or Word": "Dokument nicht unterstützt - versuche Markdown, Klartext, HTML oder Word", @@ -192,6 +194,7 @@ "Center large": "Mittig groß", "Italic": "Kursiv", "Sorry, that link won’t work for this embed type": "Dieser Link funktioniert für diesen Einbettungstyp leider nicht", + "File attachment": "File attachment", "Find or create a doc": "Suchen oder erstellen Sie ein Dokument", "Big heading": "Große Überschrift", "Medium heading": "Mittlere Überschrift", @@ -199,7 +202,7 @@ "Heading": "Überschrift", "Divider": "Trennlinie", "Image": "Bild", - "Sorry, an error occurred uploading the image": "Beim Hochladen des Bildes ist ein Fehler aufgetreten", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Untertitel schreiben", "Info": "Info", "Info notice": "Info-Hinweis", @@ -231,16 +234,15 @@ "Path to document": "Pfad zum Dokument", "Group member options": "Optionen für Gruppenmitglieder", "Remove": "Entfernen", + "Sort in sidebar": "Seitenleiste sortieren", + "Alphabetical sort": "Alphabetisch sortieren", + "Manual sort": "Manuelle Sortierung", "Edit": "Bearbeiten", "Permissions": "Berechtigungen", "Delete": "Löschen", "Collection permissions": "Berechtigungen für Sammlungen", "Delete collection": "Sammlung löschen", "Export collection": "Sammlung exportieren", - "Show sort menu": "Sortiermenü anzeigen", - "Sort in sidebar": "Seitenleiste sortieren", - "Alphabetical sort": "Alphabetisch sortieren", - "Manual sort": "Manuelle Sortierung", "Document restored": "Dokument wiederhergestellt", "Document unpublished": "Dokument unveröffentlicht", "Document options": "Dokument-Einstellungen", diff --git a/shared/i18n/locales/es_ES/translation.json b/shared/i18n/locales/es_ES/translation.json index 6f0ee3d492..061cad128c 100644 --- a/shared/i18n/locales/es_ES/translation.json +++ b/shared/i18n/locales/es_ES/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Fijado a la colección", "Pin to home": "Fijar a inicio", "Pinned to team home": "Fijado a inicio de equipo", + "Pin": "Pin", "Print": "Imprimir", "Print document": "Imprimir documento", "Import document": "Importar documento", @@ -139,6 +140,7 @@ "Document archived": "Documento archivado", "Move document": "Mover documento", "Collections": "Colecciones", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Sin título", "New nested document": "Nuevo documento anidado", "Document not supported – try Markdown, Plain text, HTML, or Word": "Documento no compatible: prueba Markdown, Texto sin formato, HTML o Word", @@ -192,6 +194,7 @@ "Center large": "Centrar grande", "Italic": "Cursiva", "Sorry, that link won’t work for this embed type": "Lo sentimos, ese enlace no funcionará para este tipo embebido", + "File attachment": "File attachment", "Find or create a doc": "Buscar o crear un documento", "Big heading": "Título grande", "Medium heading": "Título medio", @@ -199,7 +202,7 @@ "Heading": "Título", "Divider": "Divisor", "Image": "Imagen", - "Sorry, an error occurred uploading the image": "Lo sentimos, se produjo un error al cargar la imagen", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Escribe un título", "Info": "Información", "Info notice": "Aviso de información", @@ -231,16 +234,15 @@ "Path to document": "Ruta al documento", "Group member options": "Opciones de miembros del grupo", "Remove": "Eliminar", + "Sort in sidebar": "Ordenar en barra lateral", + "Alphabetical sort": "Orden alfabético", + "Manual sort": "Orden manual", "Edit": "Editar", "Permissions": "Permisos", "Delete": "Borrar", "Collection permissions": "Permisos de la colección", "Delete collection": "Eliminar colección", "Export collection": "Exportar colección", - "Show sort menu": "Mostrar menú de ordenación", - "Sort in sidebar": "Ordenar en barra lateral", - "Alphabetical sort": "Orden alfabético", - "Manual sort": "Orden manual", "Document restored": "Documento restaurado", "Document unpublished": "Documento no publicado", "Document options": "Opciones de documento", diff --git a/shared/i18n/locales/fa_IR/translation.json b/shared/i18n/locales/fa_IR/translation.json index d7cb30f98b..e51f6d55ef 100644 --- a/shared/i18n/locales/fa_IR/translation.json +++ b/shared/i18n/locales/fa_IR/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "سنجاق کردن به مجموعه", "Pin to home": "سنجاق کردن به صفحه اول", "Pinned to team home": "به صفحه تیم سنجاق شد", + "Pin": "Pin", "Print": "چاپ", "Print document": "چاپ سند", "Import document": "وارد کردن سند", @@ -139,6 +140,7 @@ "Document archived": "سند آرشیو شد", "Move document": "انتقال سند", "Collections": "مجموعه‌ها", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "بدون عنوان", "New nested document": "ایجاد زیرسند جدید", "Document not supported – try Markdown, Plain text, HTML, or Word": "نوع سند پشتیبانی نمی‌شود - از Markdown، متن ساده، HTML، یا Word استفاده کنید", @@ -192,6 +194,7 @@ "Center large": "مرکز و بزرگ", "Italic": "مورب", "Sorry, that link won’t work for this embed type": "متاسفانه این پیوند برای این نوع جاسازی کار نمی‌کند", + "File attachment": "File attachment", "Find or create a doc": "یافتن یا ایجاد سند", "Big heading": "عنوان بزرگ", "Medium heading": "عنوان متوسط", @@ -199,7 +202,7 @@ "Heading": "عنوان", "Divider": "جدا کننده", "Image": "تصویر", - "Sorry, an error occurred uploading the image": "متاسفانه خطایی در بارگذاری تصویر رخ داد", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "عنوانی بنویسید", "Info": "اطلاع‌رسانی", "Info notice": "اخطار اطلاع‌رسانی", @@ -231,16 +234,15 @@ "Path to document": "مسیر سند", "Group member options": "گزینه‌های عضو گروه", "Remove": "حذف", + "Sort in sidebar": "مرتب‌سازی در نوار کناری", + "Alphabetical sort": "مرتب‌سازی الفبایی", + "Manual sort": "مرتب‌سازی دستی", "Edit": "ویرایش", "Permissions": "دسترسی‌ها", "Delete": "حذف", "Collection permissions": "دسترسی‌های مجموعه", "Delete collection": "حذف مجموعه", "Export collection": "صدور مجموعه", - "Show sort menu": "نمایش منوی مرتب‌سازی", - "Sort in sidebar": "مرتب‌سازی در نوار کناری", - "Alphabetical sort": "مرتب‌سازی الفبایی", - "Manual sort": "مرتب‌سازی دستی", "Document restored": "سند بازیابی شد", "Document unpublished": "انتشار سند لغو شد", "Document options": "گزینه‌های سند", diff --git a/shared/i18n/locales/fr_FR/translation.json b/shared/i18n/locales/fr_FR/translation.json index 7670c509f1..1f7d2ebd18 100644 --- a/shared/i18n/locales/fr_FR/translation.json +++ b/shared/i18n/locales/fr_FR/translation.json @@ -19,13 +19,14 @@ "Pinned to collection": "Épinglé à la collection", "Pin to home": "Épingler sur la page d'accueil", "Pinned to team home": "Ajouté à l'écran d'accueil de l’équipe", + "Pin": "Épingler", "Print": "Imprimer", "Print document": "Imprimer le document", "Import document": "Importer un document", "Templatize": "En faire un modèle", "Create template": "Créer un modèle", "Home": "Accueil", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "Chercher \"{{searchQuery}}\" dans les documents", "Drafts": "Brouillons", "Templates": "Modèles", "Archive": "Archiver", @@ -34,7 +35,7 @@ "Profile": "Profil", "API documentation": "Documentation de l'API", "Send us feedback": "Donnez-nous votre avis", - "Report a bug": "Signaler un bug", + "Report a bug": "Signalez un bug", "Changelog": "Historique des modifications", "Keyboard shortcuts": "Raccourcis clavier", "Log out": "Déconnexion", @@ -61,14 +62,14 @@ "Collapse": "Replier", "Expand": "Développer", "Type a command or search": "Entrez une commande ou faites une recherche", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "Ouvrir la recherche depuis n'importe où avec le raccourci {{ shortcut }}", "Server connection lost": "Connexion au serveur perdue", "Edits you make will sync once you’re online": "Les modifications que vous effectuez seront synchronisées lorsque vous serez en ligne", "Submenu": "Sous-menu", "Collections could not be loaded, please reload the app": "Les collections n'ont pas pu être chargées, veuillez recharger l'application", - "Start view": "Vue de démarrage", + "Start view": "Page d'accueil", "Default collection": "Collection par défaut", - "This is the screen that team members will first see when they sign in.": "Cette vue s'affichera pour les membres de l'équipe lorsqu'ils se connecteront pour la première fois.", + "This is the screen that team members will first see when they sign in.": "Cette page s'affichera pour les membres de l'équipe lors de leur première connexion.", "Deleted Collection": "Collection supprimée", "Unpin": "Désépingler", "History": "Historique", @@ -108,16 +109,16 @@ "Something Unexpected Happened": "Quelque chose d'inattendu s'est produit", "Sorry, an unrecoverable error occurred{{notified}}. Please try reloading the page, it may have been a temporary glitch.": "Désolé, une erreur irrécupérable s'est produite{{notified}}. Essayez d'actualiser la page, il s'agit peut-être d'un problème temporaire.", "our engineers have been notified": "nos ingénieurs ont été notifiés", - "Report a Bug": "Signaler un Bug", + "Report a Bug": "Signalez un Bug", "Show Detail": "Afficher les détails", "Latest version": "Dernière version", - "{{userName}} edited": "{{userName}} modifié", - "{{userName}} archived": "{{userName}} archivé", - "{{userName}} restored": "{{userName}} restauré", - "{{userName}} deleted": "{{userName}} supprimé", - "{{userName}} moved from trash": "{{userName}} déplacé de la corbeille", - "{{userName}} published": "{{userName}} publié", - "{{userName}} moved": "{{userName}} déplacé", + "{{userName}} edited": "{{userName}} a modifié", + "{{userName}} archived": "{{userName}} a archivé", + "{{userName}} restored": "{{userName}} a restauré", + "{{userName}} deleted": "{{userName}} a supprimé", + "{{userName}} moved from trash": "{{userName}} a déplacé de la corbeille", + "{{userName}} published": "{{userName}} a publié", + "{{userName}} moved": "{{userName}} a déplacé", "Icon": "Icône", "Show menu": "Afficher le menu", "Choose icon": "Choisir une icône", @@ -139,6 +140,7 @@ "Document archived": "Document archivé", "Move document": "Déplacer le document", "Collections": "Collections", + "You can't reorder documents in an alphabetically sorted collection": "Vous ne pouvez pas réorganiser les documents dans une collection triée par ordre alphabétique", "Untitled": "Sans titre", "New nested document": "Nouveau document imbriqué", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document non pris en charge - essayez un format Markdown, Text, HTML ou Word", @@ -192,6 +194,7 @@ "Center large": "Centrer en grand", "Italic": "Italique", "Sorry, that link won’t work for this embed type": "Désolé, ce lien ne fonctionne pas pour ce type d'intégration", + "File attachment": "Pièce jointe", "Find or create a doc": "Rechercher ou créer un doc", "Big heading": "En-tête", "Medium heading": "Titre moyen", @@ -199,13 +202,13 @@ "Heading": "Titre", "Divider": "Séparateur", "Image": "Image", - "Sorry, an error occurred uploading the image": "Une erreur est survenue pendant l'envoi de l'image", + "Sorry, an error occurred uploading the file": "Désolé, une erreur s'est produite lors du chargement du fichier", "Write a caption": "Ajoutez une légende", "Info": "Informations", "Info notice": "Avis d'information", "Link": "Lien", "Link copied to clipboard": "Lien copié dans le presse-papiers", - "Highlight": "Surligner", + "Highlight": "Surligné", "Type '/' to insert": "Tapez '/' pour insérer", "Keep typing to filter": "Continuez à taper pour filtrer", "Open link": "Ouvrir le lien", @@ -231,16 +234,15 @@ "Path to document": "Chemin d'accès au document", "Group member options": "Options du membres du groupe", "Remove": "Supprimer", + "Sort in sidebar": "Trier dans la barre latérale", + "Alphabetical sort": "Tri alphabétique", + "Manual sort": "Tri manuel", "Edit": "Modifier", "Permissions": "Permissions", "Delete": "Supprimer", "Collection permissions": "Permissions sur les collections", "Delete collection": "Supprimer la collection", "Export collection": "Exporter la collection", - "Show sort menu": "Afficher le menu de tri", - "Sort in sidebar": "Trier dans la barre latérale", - "Alphabetical sort": "Tri alphabétique", - "Manual sort": "Tri manuel", "Document restored": "Document restauré", "Document unpublished": "Document dépublié", "Document options": "Options de document", @@ -341,7 +343,7 @@ "Search people": "Rechercher des personnes", "No people matching your search": "Aucune personne ne correspond à votre recherche", "No people left to add": "Plus aucune personne à ajouter", - "Active <1> ago": "Active il y a <1>", + "Active <1> ago": "Actif il y a <1>", "Never signed in": "Jamais connecté", "Invited": "Invité", "{{ userName }} was removed from the collection": "{{ userName }} a été retiré de la collection", @@ -384,8 +386,8 @@ "Sorry, it looks like you don’t have permission to access the document": "Désolé, il semble que vous n’ayez pas la permission d’accéder à ce document", "This template will be permanently deleted in <2> unless restored.": "Ce modèle sera définitivement supprimé dans <2> sauf s'il est restauré.", "This document will be permanently deleted in <2> unless restored.": "Ce document sera définitivement supprimé dans <2> sauf s'il est restauré.", - "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", - "You’re editing a template": "You’re editing a template", + "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Sélectionnez du texte et utilisez le contrôle <2> pour ajouter des espaces réservés qui peuvent être remplis lors de la création de nouveaux documents", + "You’re editing a template": "Vous modifiez un modèle", "Archived by {{userName}}": "Archivé par {{userName}}", "Deleted by {{userName}}": "Supprimé par {{userName}}", "Observing {{ userName }}": "Observation de {{ userName }}", @@ -543,7 +545,7 @@ "Admins": "Administrateurs", "Logo updated": "Logo mis à jour", "Unable to upload new logo": "Impossible de charger le logo", - "These details affect the way that your Outline appears to everyone on the team.": "Ces détails changent l'apparence de votre Outline pour tous les membres de l'équipe.", + "These details affect the way that your Outline appears to everyone on the team.": "Ces paramètres changent l'apparence d'Outline pour tous les membres de l'équipe.", "Logo": "Logo", "Subdomain": "Sous-domaine", "Your knowledge base will be accessible at": "Votre base de connaissances sera accessible à l'adresse", @@ -593,8 +595,8 @@ "Delete Account": "Supprimer le compte", "You may delete your account at any time, note that this is unrecoverable": "Vous pouvez supprimer votre compte à tout moment, notez que cela est irrécupérable", "Delete account": "Supprimer compte", - "New user accounts will be given member permissions by default": "Les nouveaux utilisateurs recevront par défaut les autorisations comme membres", - "New user accounts will be given viewer permissions by default": "Les nouveaux utilisateurs recevront par défaut les autorisations comme lecteurs", + "New user accounts will be given member permissions by default": "Les nouveaux utilisateurs recevront le statut de membre par défaut", + "New user accounts will be given viewer permissions by default": "Les nouveaux utilisateurs recevront le statut de lecteur par défaut", "Settings that impact the access, security, and content of your knowledge base.": "Paramètres agissant sur l'accès, la sécurité et le contenu de votre base de connaissances.", "Allow email authentication": "Autoriser l'authentification par email", "When enabled, users can sign-in using their email address": "Lorsque cette option est activée, les utilisateurs peuvent se connecter en utilisant leur adresse e-mail", diff --git a/shared/i18n/locales/it_IT/translation.json b/shared/i18n/locales/it_IT/translation.json index bf57ae966c..5d3f8b1882 100644 --- a/shared/i18n/locales/it_IT/translation.json +++ b/shared/i18n/locales/it_IT/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Stampa", "Print document": "Print document", "Import document": "Importa documento", @@ -139,6 +140,7 @@ "Document archived": "Documento archiviato", "Move document": "Move document", "Collections": "Raccolta", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Senza titolo", "New nested document": "Nuovo documento annidato", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document not supported – try Markdown, Plain text, HTML, or Word", @@ -192,6 +194,7 @@ "Center large": "Center large", "Italic": "Corsivo", "Sorry, that link won’t work for this embed type": "Siamo spiacenti, questo link non funzionerà per questo tipo di embed", + "File attachment": "File attachment", "Find or create a doc": "Trova o crea un documento", "Big heading": "Titolo grande", "Medium heading": "Titolo medio", @@ -199,7 +202,7 @@ "Heading": "Titolo", "Divider": "Divisore", "Image": "Immagine", - "Sorry, an error occurred uploading the image": "Spiacenti, si è verificato un errore durante il caricamento dell'immagine", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Scrivi una descrizione", "Info": "Informazioni", "Info notice": "Nota informativa", @@ -231,16 +234,15 @@ "Path to document": "Percorso del documento", "Group member options": "Opzioni membri del gruppo", "Remove": "Elimina", + "Sort in sidebar": "Ordina nella barra laterale", + "Alphabetical sort": "Ordine Alfabetico", + "Manual sort": "Ordinamento manuale", "Edit": "Modifica", "Permissions": "Permessi", "Delete": "Cancella", "Collection permissions": "Collection permissions", "Delete collection": "Elimina raccolta", "Export collection": "Esporta raccolta", - "Show sort menu": "Mostra menu di ordinamento", - "Sort in sidebar": "Ordina nella barra laterale", - "Alphabetical sort": "Ordine Alfabetico", - "Manual sort": "Ordinamento manuale", "Document restored": "Documento ripristinato", "Document unpublished": "Documento depubblicato", "Document options": "Opzioni documento", diff --git a/shared/i18n/locales/ja_JP/translation.json b/shared/i18n/locales/ja_JP/translation.json index dd563bb6da..ceda27caa3 100644 --- a/shared/i18n/locales/ja_JP/translation.json +++ b/shared/i18n/locales/ja_JP/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "コレクションに追加", "Pin to home": "ホームに固定", "Pinned to team home": "チームホームに固定", + "Pin": "Pin", "Print": "プリント", "Print document": "ドキュメントを印刷する", "Import document": "ドキュメントのインポート", @@ -139,6 +140,7 @@ "Document archived": "ドキュメントをアーカイブしました", "Move document": "ドキュメントの移動", "Collections": "コレクション", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "文書", "New nested document": "新しい入れ子になった文書", "Document not supported – try Markdown, Plain text, HTML, or Word": "ドキュメントはサポートされていません。Markdown、プレーンテキスト、HTML、またはWordをお試しください", @@ -192,6 +194,7 @@ "Center large": "大きく中央", "Italic": "斜体", "Sorry, that link won’t work for this embed type": "申し訳ありませんが、この埋め込みタイプではリンクが機能しません", + "File attachment": "File attachment", "Find or create a doc": "ドキュメントを検索または作成する", "Big heading": "大見出し", "Medium heading": "中見出し", @@ -199,7 +202,7 @@ "Heading": "見出し", "Divider": "区切り線", "Image": "画像", - "Sorry, an error occurred uploading the image": "エラーにより画像のアップロードに失敗しました。", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "キャプションを書く", "Info": "情報", "Info notice": "情報の通知", @@ -231,16 +234,15 @@ "Path to document": "ドキュメントのパス", "Group member options": "グループメンバーのオプション", "Remove": "削除", + "Sort in sidebar": "サイドバーで並べ替え", + "Alphabetical sort": "アルファベット順", + "Manual sort": "手動で並べ替え", "Edit": "編集", "Permissions": "権限", "Delete": "削除", "Collection permissions": "コレクションの権限", "Delete collection": "コレクションの削除", "Export collection": "エクスポート(コレクション)", - "Show sort menu": "並べ替えメニューを表示", - "Sort in sidebar": "サイドバーで並べ替え", - "Alphabetical sort": "アルファベット順", - "Manual sort": "手動で並べ替え", "Document restored": "ドキュメントが復元されました", "Document unpublished": "ドキュメントが非公開になりました", "Document options": "ドキュメントのオプション", diff --git a/shared/i18n/locales/ko_KR/translation.json b/shared/i18n/locales/ko_KR/translation.json index 4e4edfb221..6c5d631921 100644 --- a/shared/i18n/locales/ko_KR/translation.json +++ b/shared/i18n/locales/ko_KR/translation.json @@ -1,11 +1,11 @@ { - "Open collection": "Open collection", + "Open collection": "컬렉션 열기", "New collection": "새 컬렉션", "Create a collection": "컬렉션 만들기", "Edit collection": "컬렉션 수정", "Delete IndexedDB cache": "IndexedDB 캐시 삭제", "IndexedDB cache deleted": "IndexedDB 캐시 삭제됨", - "Development": "Development", + "Development": "개발", "Open document": "문서 열기", "New document": "새 문서", "Star": "중요 문서 표시", @@ -19,13 +19,14 @@ "Pinned to collection": "컬렉션에 고정됨", "Pin to home": "홈에 고정", "Pinned to team home": "팀 홈에 고정됨", + "Pin": "Pin", "Print": "인쇄", "Print document": "문서 인쇄", "Import document": "문서 가져 오기", "Templatize": "템플릿화", "Create template": "템플릿 만들기", "Home": "홈", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "\"{{searchQuery}}\" 에 대한 문서 검색", "Drafts": "임시 보관함", "Templates": "템플릿", "Archive": "보관", @@ -41,7 +42,7 @@ "Dark": "어둡게 보기", "Light": "밝게 보기", "System": "시스템", - "Appearance": "Appearance", + "Appearance": "외관", "Change theme": "테마 변경", "Change theme to": "다음으로 테마 변경", "Invite people": "초대하기", @@ -61,14 +62,14 @@ "Collapse": "감추기", "Expand": "펼치기", "Type a command or search": "명령어를 입력하거나 검색", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "{{ shortcut }} 단축키로 어디서나 검색 열기", "Server connection lost": "서버 연결 끊김", "Edits you make will sync once you’re online": "온라인 상태가 되면 수정 사항이 동기화됩니다", "Submenu": "하위 메뉴", "Collections could not be loaded, please reload the app": "컬렉션을 불러올 수 없습니다. 앱을 새로고침하세요", - "Start view": "Start view", - "Default collection": "Default collection", - "This is the screen that team members will first see when they sign in.": "This is the screen that team members will first see when they sign in.", + "Start view": "보기 시작", + "Default collection": "기본 컬렉션", + "This is the screen that team members will first see when they sign in.": "팀원들이 로그인할 때 가장 먼저 보게 되는 화면입니다.", "Deleted Collection": "삭제 된 콜렉션", "Unpin": "고정 해제", "History": "히스토리", @@ -139,6 +140,7 @@ "Document archived": "문서가 보관되었습니다", "Move document": "문서 이동", "Collections": "컬렉션", + "You can't reorder documents in an alphabetically sorted collection": "알파벳순으로 정렬된 컬렉션에서는 문서를 재정렬할 수 없습니다.", "Untitled": "제목없음", "New nested document": "새 하위 문서", "Document not supported – try Markdown, Plain text, HTML, or Word": "이 문서는 지원되지 않습니다 – Markdown, Plain Text, HTML이나 Word를 이용해주세요", @@ -192,6 +194,7 @@ "Center large": "가운데 정렬", "Italic": "이탤릭체", "Sorry, that link won’t work for this embed type": "죄송합니다, 해당 링크를 이 임베드 유형에서 사용할 수 없습니다", + "File attachment": "File attachment", "Find or create a doc": "찾기 또는 새 문서 만들기", "Big heading": "큰 제목", "Medium heading": "중간 제목", @@ -199,17 +202,17 @@ "Heading": "제목", "Divider": "구분선", "Image": "이미지", - "Sorry, an error occurred uploading the image": "이미지 업로드 중에 오류가 발생했습니다", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "캡션 입력", "Info": "정보", "Info notice": "정보 공지", "Link": "링크", "Link copied to clipboard": "링크가 클립보드로 복사 되었습니다", "Highlight": "강조", - "Type '/' to insert": "Type '/' to insert", + "Type '/' to insert": "삽입하려면 '/'를 입력하세요.", "Keep typing to filter": "찾으실 항목을 입력해 주세요", "Open link": "링크 열기", - "Go to link": "Go to link", + "Go to link": "링크로 이동", "Ordered list": "번호가 있는 목록", "Page break": "페이지 나누기", "Paste a link": "링크 붙여 넣기", @@ -231,16 +234,15 @@ "Path to document": "문서 경로", "Group member options": "그룹 멤버 옵션", "Remove": "제거", + "Sort in sidebar": "사이드바 정렬", + "Alphabetical sort": "알파벳 순 정렬", + "Manual sort": "수동 정렬", "Edit": "수정", "Permissions": "권한", "Delete": "삭제", "Collection permissions": "컬렉션 권한", "Delete collection": "컬렉션 삭제", "Export collection": "컬렉션 내보내기", - "Show sort menu": "정렬 메뉴 표시", - "Sort in sidebar": "사이드바 정렬", - "Alphabetical sort": "알파벳 순 정렬", - "Manual sort": "수동 정렬", "Document restored": "문서가 복원되었습니다", "Document unpublished": "문서가 게시되지 않았습니다", "Document options": "문서 옵션", diff --git a/shared/i18n/locales/nl_NL/translation.json b/shared/i18n/locales/nl_NL/translation.json index ce157ca8b7..c3a81aa6f8 100644 --- a/shared/i18n/locales/nl_NL/translation.json +++ b/shared/i18n/locales/nl_NL/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Vastgemaakt aan collectie", "Pin to home": "Maak vast aan startscherm", "Pinned to team home": "Vastgemaakt aan team startscherm", + "Pin": "Pin", "Print": "Print", "Print document": "Document printen", "Import document": "Importeer document", @@ -139,6 +140,7 @@ "Document archived": "Document gearchiveerd", "Move document": "Document verplaatsen", "Collections": "Collecties", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Naamloos", "New nested document": "Nieuw genest document", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document niet ondersteund - probeer Markdown, platte tekst, HTML of Word", @@ -192,6 +194,7 @@ "Center large": "Midden groot", "Italic": "Cursief", "Sorry, that link won’t work for this embed type": "Sorry, die link werkt niet voor dit insluitingstype", + "File attachment": "File attachment", "Find or create a doc": "Zoek of maak een document", "Big heading": "Grote titel", "Medium heading": "Middelgrote titel", @@ -199,7 +202,7 @@ "Heading": "Kop", "Divider": "Scheidingslijn", "Image": "Afbeelding", - "Sorry, an error occurred uploading the image": "Sorry, er is een fout opgetreden bij het uploaden van de afbeelding", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Schrijf een onderschrift", "Info": "Info", "Info notice": "Informatie opmerking", @@ -231,16 +234,15 @@ "Path to document": "Pad naar document", "Group member options": "Opties voor groepsleden", "Remove": "Verwijder", + "Sort in sidebar": "Sorteer in zijbalk", + "Alphabetical sort": "Sorteer alfabetisch", + "Manual sort": "Sorteer handmatig", "Edit": "Wijzig", "Permissions": "Rechten", "Delete": "Verwijder", "Collection permissions": "Collection permissions", "Delete collection": "Verwijder collectie", "Export collection": "Exporteer collectie", - "Show sort menu": "Toon sorteermenu", - "Sort in sidebar": "Sorteer in zijbalk", - "Alphabetical sort": "Sorteer alfabetisch", - "Manual sort": "Sorteer handmatig", "Document restored": "Document hersteld", "Document unpublished": "Document ongepubliceerd", "Document options": "Documentopties", diff --git a/shared/i18n/locales/pl_PL/translation.json b/shared/i18n/locales/pl_PL/translation.json index 01fb017125..1dd53d4d88 100644 --- a/shared/i18n/locales/pl_PL/translation.json +++ b/shared/i18n/locales/pl_PL/translation.json @@ -16,16 +16,17 @@ "Duplicate document": "Duplikuj dokument", "Document duplicated": "Dokument powielony", "Pin to collection": "Przypnij do kolekcji", - "Pinned to collection": "Pinned to collection", - "Pin to home": "Pin to home", - "Pinned to team home": "Pinned to team home", + "Pinned to collection": "Przypięte do kolekcji", + "Pin to home": "Przypnij do góry", + "Pinned to team home": "Przypięte do ekranu głównego zespołu", + "Pin": "Przypnij", "Print": "Drukuj", "Print document": "Drukuj dokument", "Import document": "Importuj dokument", "Templatize": "Konwertuj na szablon", "Create template": "Utwórz szablon", "Home": "Strona Główna", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "Wyszukaj dokumenty dla „{{searchQuery}}”", "Drafts": "Kopie robocze", "Templates": "Szablony", "Archive": "Archiwum", @@ -41,7 +42,7 @@ "Dark": "Ciemny", "Light": "Jasny", "System": "System", - "Appearance": "Appearance", + "Appearance": "Wygląd", "Change theme": "Zmień motyw", "Change theme to": "Zmień motyw na", "Invite people": "Zaproś ludzi", @@ -50,7 +51,7 @@ "Document": "Dokument", "Navigation": "Nawigacja", "People": "Osoby", - "Recent searches": "Recent searches", + "Recent searches": "Ostatnio wyszukane", "currently editing": "aktualnie edytujesz", "currently viewing": "obecnie wyświetlasz", "previously edited": "poprzednio edytowane", @@ -61,14 +62,14 @@ "Collapse": "Zwiń", "Expand": "Rozwiń", "Type a command or search": "Wpisz komendę lub wyszukiwanie", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "Otwórz wyszukiwanie z dowolnego miejsca za pomocą skrótu {{ shortcut }}", "Server connection lost": "Utracono połączenie z serwerem", "Edits you make will sync once you’re online": "Wprowadzone przez Ciebie zmiany zostaną zsynchronizowane, gdy będziesz online", "Submenu": "Podmenu", "Collections could not be loaded, please reload the app": "Nie można załadować kolekcji, proszę odświeżyć aplikację", - "Start view": "Start view", - "Default collection": "Default collection", - "This is the screen that team members will first see when they sign in.": "This is the screen that team members will first see when they sign in.", + "Start view": "Widok początkowy", + "Default collection": "Domyślna kolekcja", + "This is the screen that team members will first see when they sign in.": "Jest to ekran, który członkowie zespołu zobaczą po raz pierwszy po zalogowaniu.", "Deleted Collection": "Usunięta kolekcja", "Unpin": "Odepnij", "History": "Historia", @@ -139,6 +140,7 @@ "Document archived": "Dokument zarchiwizowany", "Move document": "Przenieś dokument", "Collections": "Kolekcje", + "You can't reorder documents in an alphabetically sorted collection": "Nie możesz zmienić kolejności dokumentów w kolekcji posortowanej alfabetycznie", "Untitled": "Bez tytułu", "New nested document": "Nowy zagnieżdżony dokument", "Document not supported – try Markdown, Plain text, HTML, or Word": "Dokument nie jest obsługiwany – wypróbuj Markdown, zwykły tekst, HTML lub Word", @@ -186,12 +188,13 @@ "Delete table": "Usuń tabelę", "Delete image": "Usuń obraz", "Download image": "Pobierz obraz", - "Replace image": "Replace image", + "Replace image": "Zastąp obraz", "Float left": "Ustaw do lewej", "Float right": "Ustaw do prawej", "Center large": "Wyśrodkuj duże", "Italic": "Kursywa", "Sorry, that link won’t work for this embed type": "Ten link nie zadziała dla tego typu osadzenia", + "File attachment": "Załącznik", "Find or create a doc": "Znajdź lub utwórz dokument", "Big heading": "Duży nagłówek", "Medium heading": "Średni nagłówek", @@ -199,17 +202,17 @@ "Heading": "Nagłówek", "Divider": "Separator", "Image": "Zdjęcie", - "Sorry, an error occurred uploading the image": "Przepraszamy, wystąpił błąd podczas przesyłania obrazka", + "Sorry, an error occurred uploading the file": "Przepraszamy, wystąpił błąd podczas przesyłania obrazka", "Write a caption": "Napisz podpis", "Info": "Info", "Info notice": "Informacja", "Link": "Link", "Link copied to clipboard": "Link został skopiowany do schowka", "Highlight": "Podkreślenie", - "Type '/' to insert": "Type '/' to insert", + "Type '/' to insert": "Wpisz '/', aby wstawić", "Keep typing to filter": "Pisz dalej, aby filtrować", "Open link": "Otwórz link", - "Go to link": "Go to link", + "Go to link": "Przejdź do linku", "Ordered list": "Lista uporządkowana", "Page break": "Podział strony", "Paste a link": "Wklej link", @@ -231,16 +234,15 @@ "Path to document": "Ścieżka do dokumentu", "Group member options": "Opcje członka grupy", "Remove": "Usuń", + "Sort in sidebar": "Sortuj na pasku bocznym", + "Alphabetical sort": "Sortowanie alfabetyczne", + "Manual sort": "Sortowanie ręczne", "Edit": "Edytuj", "Permissions": "Uprawnienia", "Delete": "Usuń", "Collection permissions": "Uprawnienia kolekcji", "Delete collection": "Usunąć kolekcję", "Export collection": "Eksportuj kolekcję", - "Show sort menu": "Pokaż menu sortowania", - "Sort in sidebar": "Sortuj na pasku bocznym", - "Alphabetical sort": "Sortowanie alfabetyczne", - "Manual sort": "Sortowanie ręczne", "Document restored": "Dokument przywrócony", "Document unpublished": "Dokument nieopublikowany", "Document options": "Opcje dokumentu", @@ -251,7 +253,7 @@ "Permanently delete": "Trwałe usunięcie", "Enable embeds": "Włącz osadzanie", "Disable embeds": "Wyłącz osadzanie", - "Full width": "Full width", + "Full width": "Pełna szerokość", "Move {{ documentName }}": "Przenieś {{ documentName }}", "Permanently delete {{ documentName }}": "Usuń na stałe {{ documentName }}", "Export options": "Opcje eksportu", @@ -305,7 +307,7 @@ "Create a document": "Utwórz dokument", "Manage permissions": "Zarządzanie uprawnieniami", "Are you sure about that? Deleting the {{collectionName}} collection is permanent and cannot be restored, however documents within will be moved to the trash.": "Czy jesteś pewien co do tego? Usunięcie kolekcji {{collectionName}} jest trwałe i nie może zostać przywrócone, jednak dokumenty w obrębie zostaną przeniesione do kosza.", - "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.": "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.", + "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.": "Ponadto widok {{collectionName}} jest używany jako widok początkowy – usunięcie go spowoduje zresetowanie widoku początkowego do strony głównej.", "Deleting": "Usuwanie", "I’m sure – Delete": "Jestem pewien – Usuń", "The collection was updated": "Kolekcja została zaktualizowana", @@ -320,9 +322,9 @@ "Exporting": "Eksportowanie", "Export Collection": "Eksportuj kolekcję", "Collections are for grouping your documents. They work best when organized around a topic or internal team — Product or Engineering for example.": "Kolekcje służą do grupowania dokumentów. Działają najlepiej, gdy są zorganizowane tematycznie lub zespołowo - np. Produkt lub Inżynieria.", - "This is the default level of access, you can give individual users or groups more access once the collection is created.": "This is the default level of access, you can give individual users or groups more access once the collection is created.", + "This is the default level of access, you can give individual users or groups more access once the collection is created.": "To jest domyślny poziom uprawnień przyznawany członkom Twojego zespołu. Po utworzeniu kolekcji możesz przyznać poszczególnym osobom lub grupom więcej uprawnień.", "Public document sharing": "Publiczne udostępnianie dokumentów", - "When enabled any documents within this collection can be shared publicly on the internet.": "When enabled any documents within this collection can be shared publicly on the internet.", + "When enabled any documents within this collection can be shared publicly on the internet.": "Po włączeniu wszystkie dokumenty w tej kolekcji mogą być udostępniane publicznie w Internecie.", "Creating": "Tworzenie", "Create": "Utwórz", "{{ groupName }} was added to the collection": "Użytkownik {{ groupName }} został dodany do kolekcji", @@ -369,7 +371,7 @@ "Document updated by {{userName}}": "Dokument zaktualizowany przez {{userName}}", "You have unsaved changes.\nAre you sure you want to discard them?": "Masz niezapisane zmiany.\nCzy na pewno chcesz je odrzucić?", "Images are still uploading.\nAre you sure you want to discard them?": "Obrazy są nadal przesyłane.\nCzy na pewno chcesz je odrzucić?", - "Type '/' to insert, or start writing…": "Type '/' to insert, or start writing…", + "Type '/' to insert, or start writing…": "Wpisz „/”, aby wstawić, lub zacznij pisać…", "Hide contents": "Ukryj zawartość", "Show contents": "Pokaż zawartość", "Edit {{noun}}": "Edytuj {{noun}}", @@ -384,11 +386,11 @@ "Sorry, it looks like you don’t have permission to access the document": "Przepraszamy, wygląda na to, że nie masz uprawnień dostępu do dokumentu", "This template will be permanently deleted in <2> unless restored.": "Ten szablon zostanie trwale usunięty w <2> chyba że zostanie przywrócony.", "This document will be permanently deleted in <2> unless restored.": "Ten dokument zostanie trwale usunięty w <2> chyba że zostanie przywrócony.", - "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", - "You’re editing a template": "You’re editing a template", + "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Zaznacz jakiś tekst i użyj kontroli <2> aby dodać symbole zastępcze, które mogą być wypełnione podczas tworzenia nowych dokumentów", + "You’re editing a template": "Edytujesz szablon", "Archived by {{userName}}": "Zarchiwizowane przez {{userName}}", "Deleted by {{userName}}": "Usunięte przez {{userName}}", - "Observing {{ userName }}": "Observing {{ userName }}", + "Observing {{ userName }}": "Obserwowanie {{ userName }}", "Nested documents": "Dokumenty zagnieżdżone", "Referenced by": "Odwołuje się do", "Anyone with the link <1>can view this document": "Każdy, kto ma link <1> może wyświetlić ten dokument", @@ -509,7 +511,7 @@ "Past week": "Poprzedni tydzień", "Past month": "Poprzedni miesiąc", "Past year": "Poprzedni rok", - "Remove search": "Remove search", + "Remove search": "Usuń wyszukiwania", "Active documents": "Aktywne dokumenty", "Documents in collections you are able to access": "Dokumenty w zbiorach, do których masz dostęp", "All documents": "Wszystkie dokumenty", @@ -517,10 +519,10 @@ "Any author": "Dowolny autor", "Author": "Autor", "We were unable to find the page you’re looking for.": "Nie mogliśmy znaleźć strony, której szukasz.", - "No documents found for your search filters.": "No documents found for your search filters.", + "No documents found for your search filters.": "Nie znaleziono dokumentów dla Twoich filtrów wyszukiwania.", "Processing": "Przetwarzanie", "Expired": "Ważność wygasła", - "Failed": "Failed", + "Failed": "Niepowodzenie", "All collections": "Wszystkie kolekcje", "{{userName}} requested": "{{userName}} zażądano", "Upload": "Prześlij", @@ -531,17 +533,17 @@ "Last accessed": "Ostatnio otwarto", "Add to Slack": "Dodaj do Slacka", "Settings saved": "Ustawienia zapisane", - "document published": "document published", - "document updated": "document updated", - "Posting to the {{ channelName }} channel on": "Posting to the {{ channelName }} channel on", - "These events should be posted to Slack": "These events should be posted to Slack", + "document published": "dokument opublikowany", + "document updated": "dokument zaktualizowany", + "Posting to the {{ channelName }} channel on": "Wysyłanie do kanału {{ channelName }} włączone", + "These events should be posted to Slack": "Te wydarzenia należy opublikować na Slack", "Document published": "Dokument opublikowany", "Document updated": "Dokument zaktualizowany", "Disconnect": "Rozłącz", "Active": "Aktywne", "Everyone": "Wszyscy", "Admins": "Administratorzy", - "Logo updated": "Logo updated", + "Logo updated": "Logo zaktualizowane", "Unable to upload new logo": "Nie można przesłać nowego logo", "These details affect the way that your Outline appears to everyone on the team.": "Te szczegóły wpływają na sposób, w jaki Twój Outline będzie widoczny dla wszystkich członków zespołu.", "Logo": "Logo", @@ -561,14 +563,14 @@ "Groups can be used to organize and manage the people on your team.": "Grupy mogą być używane do organizowania i zarządzania ludźmi w twoim zespole.", "All groups": "Wszystkie grupy", "No groups have been created yet": "Nie utworzono jeszcze żadnych grup", - "Your import is being processed, you can safely leave this page": "Your import is being processed, you can safely leave this page", - "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.", - "Import a backup file that was previously exported from Outline": "Import a backup file that was previously exported from Outline", + "Your import is being processed, you can safely leave this page": "Twój import jest przetwarzany, możesz bezpiecznie opuścić tę stronę", + "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Szybko przenoś istniejące dokumenty, strony i pliki z innych narzędzi i usług do Outline. Możesz także przeciągać i upuszczać dowolne dokumenty HTML, Markdown i tekstowe bezpośrednio do kolekcji w aplikacji.", + "Import a backup file that was previously exported from Outline": "Zaimportuj plik kopii zapasowej, który został wcześniej wyeksportowany z Outline", "Uploading": "Wysyłanie", - "Import pages from a Confluence instance": "Import pages from a Confluence instance", - "Coming soon": "Coming soon", - "Import documents from Notion": "Import documents from Notion", - "Recent imports": "Recent imports", + "Import pages from a Confluence instance": "Importuj strony z instancji Confluence", + "Coming soon": "Wkrótce", + "Import documents from Notion": "Importuj dokumenty z Notion", + "Recent imports": "Ostatnio zaimportowane", "Everyone that has signed into Outline appears here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.": "Tutaj są wyświetlane wszystkie osoby, które zalogowały się w Outline. Możliwe, że istnieją inni użytkownicy, którzy mają dostęp przez {team.signinMethods} ale jeszcze się nie zalogowali.", "Filter": "Filtr", "Receive a notification whenever a new document is published": "Otrzymuj powiadomienie o każdym nowym opublikowanym dokumencie", diff --git a/shared/i18n/locales/pt_BR/translation.json b/shared/i18n/locales/pt_BR/translation.json index f3a1b07078..ef20de0fbb 100644 --- a/shared/i18n/locales/pt_BR/translation.json +++ b/shared/i18n/locales/pt_BR/translation.json @@ -19,13 +19,14 @@ "Pinned to collection": "Fixar à coleção", "Pin to home": "Fixar na tela principal", "Pinned to team home": "Fixado à tela inicial do time", + "Pin": "Fixar", "Print": "Imprimir", "Print document": "Imprimir documento", "Import document": "Importar documento", "Templatize": "Modelar", "Create template": "Criar template", "Home": "Início", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "Buscar documentos por \"{{searchQuery}}\"", "Drafts": "Rascunhos", "Templates": "Modelos", "Archive": "Arquivo", @@ -61,14 +62,14 @@ "Collapse": "Recolher", "Expand": "Expandir", "Type a command or search": "Digite um comando ou pesquise", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "Abra a pesquisa de qualquer lugar com o atalho {{ shortcut }}", "Server connection lost": "Conexão com o servidor perdida", "Edits you make will sync once you’re online": "As edições que você fizer serão sincronizadas quando você estiver online", "Submenu": "Submenu", "Collections could not be loaded, please reload the app": "Não foi possível carregar as coleções, recarregue o aplicativo", - "Start view": "Start view", - "Default collection": "Default collection", - "This is the screen that team members will first see when they sign in.": "This is the screen that team members will first see when they sign in.", + "Start view": "Início da visualização", + "Default collection": "Coleção padrão", + "This is the screen that team members will first see when they sign in.": "Esta é a tela que os membros da equipe verão pela primeira vez quando fizerem login.", "Deleted Collection": "Excluir Coleção", "Unpin": "Desafixar", "History": "Histórico", @@ -139,6 +140,7 @@ "Document archived": "Documento arquivado", "Move document": "Mover documento", "Collections": "Coleções", + "You can't reorder documents in an alphabetically sorted collection": "Não é possível reordenar documentos em uma coleção organizada alfabeticamente", "Untitled": "Sem título", "New nested document": "Novo documento aninhado", "Document not supported – try Markdown, Plain text, HTML, or Word": "Documento não compatível - experimente Markdown, Texto simples, HTML ou Word", @@ -192,6 +194,7 @@ "Center large": "Centralizado grande", "Italic": "Itálico", "Sorry, that link won’t work for this embed type": "Desculpe, esse link não funcionará para este tipo de incorporação", + "File attachment": "Arquivo anexo", "Find or create a doc": "Encontre ou crie um documento", "Big heading": "Cabeçalho grande", "Medium heading": "Cabeçalho médio", @@ -199,17 +202,17 @@ "Heading": "Cabeçalho", "Divider": "Divisor", "Image": "Imagem", - "Sorry, an error occurred uploading the image": "Desculpe, ocorreu um erro ao enviar a imagem", + "Sorry, an error occurred uploading the file": "Desculpe, ocorreu um erro ao fazer upload do arquivo", "Write a caption": "Escreva uma legenda", "Info": "Informação", "Info notice": "Aviso de informação", "Link": "Link", "Link copied to clipboard": "Link copiado para área de transferência", "Highlight": "Destaque", - "Type '/' to insert": "Type '/' to insert", + "Type '/' to insert": "Digite '/' para inserir", "Keep typing to filter": "Continue digitando para filtrar", "Open link": "Abrir link", - "Go to link": "Go to link", + "Go to link": "Ir para o link", "Ordered list": "Lista ordenada", "Page break": "Quebra de página", "Paste a link": "Cole um link", @@ -231,16 +234,15 @@ "Path to document": "Caminho para o documento", "Group member options": "Opções de membros do grupo", "Remove": "Remover", + "Sort in sidebar": "Ordenar na barra lateral", + "Alphabetical sort": "Ordem alfabética", + "Manual sort": "Ordenação manual", "Edit": "Editar", "Permissions": "Permissões", "Delete": "Excluir", "Collection permissions": "Permissões da coleção", "Delete collection": "Excluir coleção", "Export collection": "Exportar coleção", - "Show sort menu": "Mostrar menu de ordenação", - "Sort in sidebar": "Ordenar na barra lateral", - "Alphabetical sort": "Ordem alfabética", - "Manual sort": "Ordenação manual", "Document restored": "Documento restaurado", "Document unpublished": "Documento não publicado", "Document options": "Opções do documento", @@ -305,7 +307,7 @@ "Create a document": "Criar documento", "Manage permissions": "Gerenciar permissões", "Are you sure about that? Deleting the {{collectionName}} collection is permanent and cannot be restored, however documents within will be moved to the trash.": "Você tem certeza disso? Excluir a coleção {{collectionName}} é permanente e não pode ser restaurada, porém os documentos dentro serão movidos para a lixeira.", - "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.": "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.", + "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.": "Além disso, {{collectionName}} está sendo usado como visualização inicial – excluí-lo irá redefinir a visualização inicial para a página inicial.", "Deleting": "Excluindo", "I’m sure – Delete": "Tenho certeza - Excluir  ", "The collection was updated": "A coleção foi atualizada", @@ -369,7 +371,7 @@ "Document updated by {{userName}}": "Documento atualizado por {{userName}}", "You have unsaved changes.\nAre you sure you want to discard them?": "Existem alterações não salvas. Tem certeza que deseja descartá-las?", "Images are still uploading.\nAre you sure you want to discard them?": "As imagens ainda estão sendo carregadas.\nTem certeza que deseja descartá-las?", - "Type '/' to insert, or start writing…": "Type '/' to insert, or start writing…", + "Type '/' to insert, or start writing…": "Digite '/' para inserir, ou comece a escrever…", "Hide contents": "Esconder o conteúdo", "Show contents": "Exibir conteúdo", "Edit {{noun}}": "Editar {{noun}}", @@ -384,8 +386,8 @@ "Sorry, it looks like you don’t have permission to access the document": "Desculpe, parece que você não tem permissão para acessar o documento", "This template will be permanently deleted in <2> unless restored.": "Este template será permanentemente excluído em <2>, a menos que seja restaurado.", "This document will be permanently deleted in <2> unless restored.": "Este documento será excluído permanentemente em <2>, a menos que seja restaurado.", - "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", - "You’re editing a template": "You’re editing a template", + "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Destaque algum texto e use o controle <2> para adicionar espaços reservados que podem ser preenchidos ao criar novos documentos", + "You’re editing a template": "Você esta editando um modelo", "Archived by {{userName}}": "Arquivado por {{userName}}", "Deleted by {{userName}}": "Excluído por {{userName}}", "Observing {{ userName }}": "Observando {{ userName }}", @@ -520,7 +522,7 @@ "No documents found for your search filters.": "Nenhum documento encontrado para seus filtros de pesquisa.", "Processing": "Processando", "Expired": "Expirado", - "Failed": "Failed", + "Failed": "Falha", "All collections": "Todas coleções", "{{userName}} requested": "{{userName}} solicitado", "Upload": "Enviar", @@ -561,14 +563,14 @@ "Groups can be used to organize and manage the people on your team.": "Grupos podem ser usados para organizar e gerenciar as pessoas da sua equipe.", "All groups": "Todos os grupos", "No groups have been created yet": "Nenhum grupo foi criado ainda", - "Your import is being processed, you can safely leave this page": "Your import is being processed, you can safely leave this page", - "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.", - "Import a backup file that was previously exported from Outline": "Import a backup file that was previously exported from Outline", + "Your import is being processed, you can safely leave this page": "Sua importação está sendo processada, você pode sair dessa página com segurança", + "Quickly transfer your existing documents, pages, and files from other tools and services into Outline. You can also drag and drop any HTML, Markdown, and text documents directly into Collections in the app.": "Transfira rapidamente seus documentos, páginas e arquivos de outras ferramentas e serviços para o Outline. Você também pode arrastar e soltar qualquer documento HTML, Markdown e texto diretamente para as Coleções no aplicativo.", + "Import a backup file that was previously exported from Outline": "Importar um arquivo de backup exportado anteriormente do Outline", "Uploading": "Enviando", - "Import pages from a Confluence instance": "Import pages from a Confluence instance", - "Coming soon": "Coming soon", - "Import documents from Notion": "Import documents from Notion", - "Recent imports": "Recent imports", + "Import pages from a Confluence instance": "Importar páginas de uma instância do Confluence", + "Coming soon": "Em breve", + "Import documents from Notion": "Importar documentos do Notion", + "Recent imports": "Importações recentes", "Everyone that has signed into Outline appears here. It’s possible that there are other users who have access through {team.signinMethods} but haven’t signed in yet.": "Todos que se inscreveram no Outline aparecem aqui. É possível que existam outros usuários que tenham acesso por meio de {team.signinMethods} mas ainda não tenham feito login.", "Filter": "Filtro", "Receive a notification whenever a new document is published": "Receba uma notificação sempre que um novo documento for publicado", diff --git a/shared/i18n/locales/pt_PT/translation.json b/shared/i18n/locales/pt_PT/translation.json index 164556463e..e305b1745f 100644 --- a/shared/i18n/locales/pt_PT/translation.json +++ b/shared/i18n/locales/pt_PT/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Imprimir", "Print document": "Print document", "Import document": "Importar documento", @@ -139,6 +140,7 @@ "Document archived": "Documento arquivado", "Move document": "Move document", "Collections": "Coleções", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Sem título", "New nested document": "Novo documento aninhado", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document not supported – try Markdown, Plain text, HTML, or Word", @@ -192,6 +194,7 @@ "Center large": "Center large", "Italic": "Itálico", "Sorry, that link won’t work for this embed type": "Desculpe, esse link não funcionará para este tipo de incorporação", + "File attachment": "File attachment", "Find or create a doc": "Pesquise ou crie um documento", "Big heading": "Cabeçalho grande", "Medium heading": "Cabeçalho médio", @@ -199,7 +202,7 @@ "Heading": "Cabeçalho", "Divider": "Separador", "Image": "Imagem", - "Sorry, an error occurred uploading the image": "Desculpe, ocorreu um erro ao criar o link", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Write a caption", "Info": "Informação", "Info notice": "Aviso de informação", @@ -231,16 +234,15 @@ "Path to document": "Path to document", "Group member options": "Group member options", "Remove": "Remover", + "Sort in sidebar": "Sort in sidebar", + "Alphabetical sort": "Alphabetical sort", + "Manual sort": "Manual sort", "Edit": "Editar", "Permissions": "Permissões", "Delete": "Apagar", "Collection permissions": "Collection permissions", "Delete collection": "Apagar coleção", "Export collection": "Exportar coleção", - "Show sort menu": "Show sort menu", - "Sort in sidebar": "Sort in sidebar", - "Alphabetical sort": "Alphabetical sort", - "Manual sort": "Manual sort", "Document restored": "Documento restaurado", "Document unpublished": "Documento não publicado", "Document options": "Document options", diff --git a/shared/i18n/locales/ru_RU/translation.json b/shared/i18n/locales/ru_RU/translation.json index 60c2c1acc0..e603f6bfff 100644 --- a/shared/i18n/locales/ru_RU/translation.json +++ b/shared/i18n/locales/ru_RU/translation.json @@ -16,16 +16,17 @@ "Duplicate document": "Дублировать документ", "Document duplicated": "Документ дублирован", "Pin to collection": "Прикрепить к коллекции", - "Pinned to collection": "Pinned to collection", - "Pin to home": "Pin to home", - "Pinned to team home": "Pinned to team home", + "Pinned to collection": "Прикреплено к коллекции", + "Pin to home": "Закрепить на домашней странице", + "Pinned to team home": "Закрепить на домашней странице команды", + "Pin": "Закрепить", "Print": "Печать", "Print document": "Печать документа", "Import document": "Импорт документа", "Templatize": "Шаблон", "Create template": "Создать шаблон", "Home": "Домашняя страница", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "Поиск документов для \"{{searchQuery}}\"", "Drafts": "Черновики", "Templates": "Шаблоны", "Archive": "Архив", @@ -41,7 +42,7 @@ "Dark": "Темная", "Light": "Светлая", "System": "Система", - "Appearance": "Appearance", + "Appearance": "Внешний вид", "Change theme": "Сменить тему", "Change theme to": "Сменить тему на", "Invite people": "Пригласить людей", @@ -50,7 +51,7 @@ "Document": "Документ", "Navigation": "Навигация", "People": "Люди", - "Recent searches": "Recent searches", + "Recent searches": "Недавние запросы", "currently editing": "сейчас редактируется", "currently viewing": "сейчас просматривается", "previously edited": "ранее отредактировано", @@ -61,14 +62,14 @@ "Collapse": "Свернуть", "Expand": "Развернуть", "Type a command or search": "Введите слово для поиска", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "Откройте поиск из любого места с помощью сочетания клавиш {{ shortcut }}", "Server connection lost": "Потеряна связь с сервером", "Edits you make will sync once you’re online": "Правки, которые вы делаете, будут синхронизированы после того, как вы будете онлайн", "Submenu": "Подменю", "Collections could not be loaded, please reload the app": "Не удалось загрузить коллекции, пожалуйста, перезагрузите приложение", - "Start view": "Start view", - "Default collection": "Default collection", - "This is the screen that team members will first see when they sign in.": "This is the screen that team members will first see when they sign in.", + "Start view": "Начать просмотр", + "Default collection": "Коллекция по умолчанию", + "This is the screen that team members will first see when they sign in.": "Это экран, который участники команды увидят при входе в систему.", "Deleted Collection": "Удаленная коллекция", "Unpin": "Открепить", "History": "История", @@ -139,6 +140,7 @@ "Document archived": "Документ архивирован", "Move document": "Переместить документ", "Collections": "Коллекции", + "You can't reorder documents in an alphabetically sorted collection": "Вы не можете изменить порядок документов в коллекции, отсортированной по алфавиту", "Untitled": "Без названия", "New nested document": "Новый вложенный документ", "Document not supported – try Markdown, Plain text, HTML, or Word": "Документ не поддерживается – попробуйте Markdown, простой текст или Word", @@ -186,12 +188,13 @@ "Delete table": "Удалить таблицу", "Delete image": "Удалить изображение", "Download image": "Скачать изображение", - "Replace image": "Replace image", + "Replace image": "Заменить изображение", "Float left": "Плавающий блок слева", "Float right": "Плавающий блок справа", "Center large": "Большой блок по центру", "Italic": "Курсив", "Sorry, that link won’t work for this embed type": "К сожалению, эта ссылка не работает для такого типа встраивания", + "File attachment": "Прикрепленные файлы", "Find or create a doc": "Найти или создать документ", "Big heading": "Большой заголовок", "Medium heading": "Средний заголовок", @@ -199,17 +202,17 @@ "Heading": "Заголовок", "Divider": "Разделитель", "Image": "Картинка", - "Sorry, an error occurred uploading the image": "К сожалению, при загрузке изображения произошла ошибка", + "Sorry, an error occurred uploading the file": "К сожалению, при загрузке файла произошла ошибка", "Write a caption": "Напишите подпись", "Info": "Детали", "Info notice": "Уведомление с деталями", "Link": "Ссылка", "Link copied to clipboard": "Ссылка скопирована в буфер обмена", "Highlight": "Выделение", - "Type '/' to insert": "Type '/' to insert", + "Type '/' to insert": "Наберите '/' для вставки", "Keep typing to filter": "Продолжайте печатать для фильтрации", "Open link": "Открыть ссылку", - "Go to link": "Go to link", + "Go to link": "Перейти по ссылке", "Ordered list": "Нумерованный список", "Page break": "Разрыв страницы", "Paste a link": "Вставить ссылку", @@ -231,16 +234,15 @@ "Path to document": "Путь к документу", "Group member options": "Параметры участников группы", "Remove": "Удалить", + "Sort in sidebar": "Сортировка в боковой панели", + "Alphabetical sort": "Сортировка по алфавиту", + "Manual sort": "Ручная сортировка", "Edit": "Редактировать", "Permissions": "Права доступа", "Delete": "Удалить", "Collection permissions": "Права доступа к коллекции", "Delete collection": "Удалить коллекцию", "Export collection": "Экспорт коллекции", - "Show sort menu": "Сортировка", - "Sort in sidebar": "Сортировка в боковой панели", - "Alphabetical sort": "Сортировка по алфавиту", - "Manual sort": "Ручная сортировка", "Document restored": "Документ восстановлен", "Document unpublished": "Документ снят с публикации", "Document options": "Параметры документа", @@ -251,7 +253,7 @@ "Permanently delete": "Окончательно удалить", "Enable embeds": "Включить встраивание", "Disable embeds": "Отключить встраивание", - "Full width": "Full width", + "Full width": "На всю ширину", "Move {{ documentName }}": "Переместить {{ documentName }}", "Permanently delete {{ documentName }}": "Окончательно удалить {{ documentName }}", "Export options": "Параметры экспорта", @@ -373,24 +375,24 @@ "Hide contents": "Скрыть содержимое", "Show contents": "Показать содержимое", "Edit {{noun}}": "Редактировать {{noun}}", - "Switch to dark": "Switch to dark", - "Switch to light": "Switch to light", + "Switch to dark": "Вкл. темную тему", + "Switch to light": "Вкл. светлую тему", "Archived": "Архивировано", "Save Draft": "Сохранить черновик", "Done Editing": "Правки внесены", "New from template": "Создать из шаблона", "Publish": "Опубликовать", "Publishing": "Публикация", - "Sorry, it looks like you don’t have permission to access the document": "Sorry, it looks like you don’t have permission to access the document", + "Sorry, it looks like you don’t have permission to access the document": "Извините, похоже, что у вас нет прав на доступ к этой странице", "This template will be permanently deleted in <2> unless restored.": "Этот шаблон будет окончательно удален <2>, если не восстановить его вручную.", "This document will be permanently deleted in <2> unless restored.": "Этот документ будет окончательно удален <2>, если не восстановить его вручную.", - "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", - "You’re editing a template": "You’re editing a template", + "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Вы редактируете шаблон. Выделите текст и используйте <2> элемент управления для добавления заполнителей, которые могут быть использованы при создании новых документов из этого шаблона", + "You’re editing a template": "Вы редактируете шаблон", "Archived by {{userName}}": "Архивировано {{userName}}", "Deleted by {{userName}}": "Удалено {{userName}}", - "Observing {{ userName }}": "Observing {{ userName }}", + "Observing {{ userName }}": "Наблюдение за {{ userName }}", "Nested documents": "Вложенные документы", - "Referenced by": "Referenced by", + "Referenced by": "Ссылка на", "Anyone with the link <1>can view this document": "Все, у кого есть ссылка <1> смогут просмотреть этот документ", "Share": "Поделиться", "Share this document": "Поделиться документом", @@ -416,9 +418,9 @@ "view and edit access": "доступ для просмотра и редактирования", "view only access": "доступ только для просмотра", "no access": "нет доступа", - "Heads up – moving the document {{ title }} to the {{ newCollectionName }} collection will grant all team members {{ newPermission }}, they currently have {{ prevPermission }}.": "Heads up – moving the document {{ title }} to the {{ newCollectionName }} collection will grant all team members {{ newPermission }}, they currently have {{ prevPermission }}.", - "Moving": "Moving", - "Cancel": "Cancel", + "Heads up – moving the document {{ title }} to the {{ newCollectionName }} collection will grant all team members {{ newPermission }}, they currently have {{ prevPermission }}.": "Обратите внимание: перемещение документа {{ title }} в коллекцию {{ newCollectionName }} предоставит всем членам команды {{ newPermission }}, у них сейчас есть {{ prevPermission }}.", + "Moving": "Идет перемещение", + "Cancel": "Отменить", "Template created, go ahead and customize it": "Шаблон создан, теперь вы можете перейти к нему и продолжить настройку", "Creating a template from {{titleWithDefault}} is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.": "Создание шаблона из {{titleWithDefault}} не уничтожит ваш документ - мы сделаем копию и превратим ее в шаблон, который можно будет использовать в качестве отправной точки для новых документов.", "Search documents": "Искать документы", @@ -463,7 +465,7 @@ "Send Invites": "Отправить приглашения", "Edit current document": "Редактировать текущий документ", "Move current document": "Переместить текущий документ", - "Open document history": "Open document history", + "Open document history": "Открыть историю документа", "Jump to search": "Перейти к поиску", "Jump to home": "Перейти на главную", "Toggle navigation": "Переключить навигацию", @@ -509,7 +511,7 @@ "Past week": "За неделю", "Past month": "За месяц", "Past year": "За год", - "Remove search": "Remove search", + "Remove search": "Убрать поиск", "Active documents": "Активные документы", "Documents in collections you are able to access": "Документы в коллекциях, к которым вы имеете доступ", "All documents": "Все документы", @@ -518,11 +520,11 @@ "Author": "Автор", "We were unable to find the page you’re looking for.": "Нам не удалось найти нужную вам страницу.", "No documents found for your search filters.": "No documents found for your search filters.", - "Processing": "Processing", - "Expired": "Expired", - "Failed": "Failed", - "All collections": "All collections", - "{{userName}} requested": "{{userName}} requested", + "Processing": "Обработка", + "Expired": "Срок действия истёк", + "Failed": "Неудачно", + "All collections": "Все коллекции", + "{{userName}} requested": "Запрошено {{userName}}", "Upload": "Загрузить", "Last active": "Последняя активность", "Suspended": "Отключен", @@ -531,31 +533,31 @@ "Last accessed": "Последний доступ", "Add to Slack": "Добавить в Slack", "Settings saved": "Настройки сохранены", - "document published": "document published", - "document updated": "document updated", - "Posting to the {{ channelName }} channel on": "Posting to the {{ channelName }} channel on", - "These events should be posted to Slack": "These events should be posted to Slack", + "document published": "документ опубликован", + "document updated": "документ обновлен", + "Posting to the {{ channelName }} channel on": "Отправка в канал {{ channelName }} на", + "These events should be posted to Slack": "Эти события должны быть опубликованы в Slack", "Document published": "Документ опубликован", "Document updated": "Документ обновлен", "Disconnect": "Отключить", "Active": "Активный", "Everyone": "Все", "Admins": "Администраторы", - "Logo updated": "Logo updated", + "Logo updated": "Логотип обновлен", "Unable to upload new logo": "Не удалось загрузить новый логотип", "These details affect the way that your Outline appears to everyone on the team.": "Эти детали влияют на то, как ваш Outline будет выглядеть для всех в команде.", "Logo": "Логотип", "Subdomain": "Поддомен", "Your knowledge base will be accessible at": "Ваша база знаний будет доступна по адресу", "Export in progress…": "Выполняется экспорт…", - "Export deleted": "Export deleted", - "A full export might take some time, consider exporting a single document or collection. The exported data is a zip of your documents in Markdown format. You may leave this page once the export has started – we will email a link to {{ userEmail }} when it’s complete.": "A full export might take some time, consider exporting a single document or collection. The exported data is a zip of your documents in Markdown format. You may leave this page once the export has started – we will email a link to {{ userEmail }} when it’s complete.", + "Export deleted": "Экспорт удален", + "A full export might take some time, consider exporting a single document or collection. The exported data is a zip of your documents in Markdown format. You may leave this page once the export has started – we will email a link to {{ userEmail }} when it’s complete.": "Полный экспорт может занять некоторое время, рассмотрите возможность экспорта одного документа или коллекции. Экспортированные данные представляют собой zip-архив ваших документов в формате Markdown. Вы можете покинуть эту страницу после того, как экспорт начнется — мы отправим ссылку по адресу {{ userEmail }} , когда он будет завершен.", "Export Requested": "Экспорт запрошен", "Requesting Export": "Запрос на экспорт", "Export Data": "Экспорт данных", - "Recent exports": "Recent exports", + "Recent exports": "Недавний экспорт", "Manage optional and beta features. Changing these settings will affect the experience for all team members.": "Manage optional and beta features. Changing these settings will affect the experience for all team members.", - "Collaborative editing": "Collaborative editing", + "Collaborative editing": "Совместное редактирование", "When enabled multiple people can edit documents at the same time with shared presence and live cursors.": "When enabled multiple people can edit documents at the same time with shared presence and live cursors.", "New group": "Новая группа", "Groups can be used to organize and manage the people on your team.": "Группы могут быть использованы для организации и управления людьми в вашей команде.", diff --git a/shared/i18n/locales/sv_SE/translation.json b/shared/i18n/locales/sv_SE/translation.json index fac3dc70ea..a4fa37b670 100644 --- a/shared/i18n/locales/sv_SE/translation.json +++ b/shared/i18n/locales/sv_SE/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Skriv ut", "Print document": "Print document", "Import document": "Import document", @@ -139,6 +140,7 @@ "Document archived": "Document archived", "Move document": "Move document", "Collections": "Collections", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Untitled", "New nested document": "New nested document", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document not supported – try Markdown, Plain text, HTML, or Word", @@ -192,6 +194,7 @@ "Center large": "Center large", "Italic": "Kursiv", "Sorry, that link won’t work for this embed type": "Sorry, that link won’t work for this embed type", + "File attachment": "File attachment", "Find or create a doc": "Find or create a doc", "Big heading": "Big heading", "Medium heading": "Medium heading", @@ -199,7 +202,7 @@ "Heading": "Rubrik", "Divider": "Divider", "Image": "Bild", - "Sorry, an error occurred uploading the image": "Sorry, an error occurred uploading the image", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Write a caption", "Info": "Info", "Info notice": "Info notice", @@ -231,16 +234,15 @@ "Path to document": "Path to document", "Group member options": "Group member options", "Remove": "Ta bort", + "Sort in sidebar": "Sort in sidebar", + "Alphabetical sort": "Alphabetical sort", + "Manual sort": "Manual sort", "Edit": "Redigera", "Permissions": "Permissions", "Delete": "Radera", "Collection permissions": "Collection permissions", "Delete collection": "Delete collection", "Export collection": "Export collection", - "Show sort menu": "Show sort menu", - "Sort in sidebar": "Sort in sidebar", - "Alphabetical sort": "Alphabetical sort", - "Manual sort": "Manual sort", "Document restored": "Document restored", "Document unpublished": "Document unpublished", "Document options": "Document options", diff --git a/shared/i18n/locales/th_TH/translation.json b/shared/i18n/locales/th_TH/translation.json index e883319406..6b552d4cae 100644 --- a/shared/i18n/locales/th_TH/translation.json +++ b/shared/i18n/locales/th_TH/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "Print", "Print document": "Print document", "Import document": "Import document", @@ -139,6 +140,7 @@ "Document archived": "Document archived", "Move document": "Move document", "Collections": "Collections", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "ไม่มีชื่อ", "New nested document": "New nested document", "Document not supported – try Markdown, Plain text, HTML, or Word": "Document not supported – try Markdown, Plain text, HTML, or Word", @@ -192,6 +194,7 @@ "Center large": "Center large", "Italic": "ตัวเอียง", "Sorry, that link won’t work for this embed type": "Sorry, that link won’t work for this embed type", + "File attachment": "File attachment", "Find or create a doc": "ค้นหาหรือสร้างเอกสาร", "Big heading": "Big heading", "Medium heading": "Medium heading", @@ -199,7 +202,7 @@ "Heading": "หัวเรื่อง", "Divider": "Divider", "Image": "Image", - "Sorry, an error occurred uploading the image": "Sorry, an error occurred uploading the image", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Write a caption", "Info": "Info", "Info notice": "Info notice", @@ -231,16 +234,15 @@ "Path to document": "Path to document", "Group member options": "Group member options", "Remove": "Remove", + "Sort in sidebar": "Sort in sidebar", + "Alphabetical sort": "Alphabetical sort", + "Manual sort": "Manual sort", "Edit": "Edit", "Permissions": "Permissions", "Delete": "Delete", "Collection permissions": "Collection permissions", "Delete collection": "Delete collection", "Export collection": "Export collection", - "Show sort menu": "Show sort menu", - "Sort in sidebar": "Sort in sidebar", - "Alphabetical sort": "Alphabetical sort", - "Manual sort": "Manual sort", "Document restored": "Document restored", "Document unpublished": "Document unpublished", "Document options": "Document options", diff --git a/shared/i18n/locales/vi_VN/translation.json b/shared/i18n/locales/vi_VN/translation.json index 8cf2583642..8289eedc2c 100644 --- a/shared/i18n/locales/vi_VN/translation.json +++ b/shared/i18n/locales/vi_VN/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Đã ghim vào bộ sưu tập", "Pin to home": "Ghim vào nhà", "Pinned to team home": "Đã ghim vào đội nhà", + "Pin": "Pin", "Print": "In", "Print document": "In tài liệu", "Import document": "Nhập tài liệu", @@ -139,6 +140,7 @@ "Document archived": "Đã lưu trữ tài liệu", "Move document": "Chuyển tài liệu", "Collections": "Bộ sưu tập", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "Chưa đặt tên", "New nested document": "Tài liệu mới lồng nhau", "Document not supported – try Markdown, Plain text, HTML, or Word": "Tài liệu không được hỗ trợ - hãy thử Markdown, Plain text, HTML hoặc Word", @@ -192,6 +194,7 @@ "Center large": "Trung tâm lớn", "Italic": "Nghiêng", "Sorry, that link won’t work for this embed type": "Xin lỗi, liên kết đó sẽ không hoạt động cho loại nhúng này", + "File attachment": "File attachment", "Find or create a doc": "Tìm hoặc tạo tài liệu", "Big heading": "Tiêu đề lớn", "Medium heading": "Tiêu đề vừa", @@ -199,7 +202,7 @@ "Heading": "Tiêu đề", "Divider": "Phân cách", "Image": "Ảnh", - "Sorry, an error occurred uploading the image": "Đã xảy ra lỗi khi đang tải lên ảnh", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "Viết chú thích", "Info": "Thông tin", "Info notice": "Thông báo thông tin", @@ -231,16 +234,15 @@ "Path to document": "Đường dẫn đến tài liệu", "Group member options": "Tùy chọn thành viên nhóm", "Remove": "Bỏ", + "Sort in sidebar": "Sắp xếp trong sidebar", + "Alphabetical sort": "Sắp xếp theo bảng chữ cái", + "Manual sort": "Sắp xếp thủ công", "Edit": "Chỉnh sửa", "Permissions": "Phân quyền", "Delete": "Xóa", "Collection permissions": "Quyền thu thập", "Delete collection": "Xoá bộ sưu tập", "Export collection": "Kết xuất bộ sưu tập", - "Show sort menu": "Hiện Menu sắp xếp", - "Sort in sidebar": "Sắp xếp trong sidebar", - "Alphabetical sort": "Sắp xếp theo bảng chữ cái", - "Manual sort": "Sắp xếp thủ công", "Document restored": "Tài liệu được phục hồi", "Document unpublished": "Tài liệu chưa được xuất bản", "Document options": "Tùy chọn tài liệu", diff --git a/shared/i18n/locales/zh_CN/translation.json b/shared/i18n/locales/zh_CN/translation.json index 08a7527da6..aa0a796b07 100644 --- a/shared/i18n/locales/zh_CN/translation.json +++ b/shared/i18n/locales/zh_CN/translation.json @@ -1,7 +1,7 @@ { "Open collection": "打开文档集", "New collection": "新建文档集", - "Create a collection": "创建文档集", + "Create a collection": "创建收藏夹", "Edit collection": "编辑文档集", "Delete IndexedDB cache": "删除索引数据库缓存", "IndexedDB cache deleted": "索引数据库缓存已删除", @@ -19,13 +19,14 @@ "Pinned to collection": "固定到收藏", "Pin to home": "固定到首页", "Pinned to team home": "固定到团队首页", + "Pin": "置顶", "Print": "打印", "Print document": "打印文档", "Import document": "导入文档", "Templatize": "模板", "Create template": "创建模板", "Home": "主页", - "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Search documents for \"{{searchQuery}}\"": "搜索名为 \"{{searchQuery}}\" 的文件", "Drafts": "草稿箱", "Templates": "文档模板", "Archive": "归档", @@ -38,8 +39,8 @@ "Changelog": "更新日志", "Keyboard shortcuts": "快捷键", "Log out": "退出登录", - "Dark": "深色主题", - "Light": "浅色主题", + "Dark": "暗黑模式", + "Light": "明亮模式", "System": "系统信息", "Appearance": "外观", "Change theme": "更改主题", @@ -61,7 +62,7 @@ "Collapse": "折叠", "Expand": "展开", "Type a command or search": "输入命令或搜索", - "Open search from anywhere with the {{ shortcut }} shortcut": "Open search from anywhere with the {{ shortcut }} shortcut", + "Open search from anywhere with the {{ shortcut }} shortcut": "使用 {{ shortcut }} 快捷键从任何地方打开搜索", "Server connection lost": "服务器连接断开", "Edits you make will sync once you’re online": "您上线后,进行的编辑将会同步", "Submenu": "子菜单", @@ -139,6 +140,7 @@ "Document archived": "文件已归档", "Move document": "移动文档", "Collections": "文档集", + "You can't reorder documents in an alphabetically sorted collection": "你不能在按字母排序的收藏夹中重新排序文件", "Untitled": "无标题", "New nested document": "新建子文档", "Document not supported – try Markdown, Plain text, HTML, or Word": "不支持的文档类型-请用Markdown,纯文本,HTML或Word", @@ -192,6 +194,7 @@ "Center large": "放大居中", "Italic": "斜体", "Sorry, that link won’t work for this embed type": "抱歉,该链接不适用于此嵌入类型", + "File attachment": "附件", "Find or create a doc": "查找或创建文档", "Big heading": "主标题", "Medium heading": "次标题", @@ -199,7 +202,7 @@ "Heading": "标题", "Divider": "分割线", "Image": "图片", - "Sorry, an error occurred uploading the image": "抱歉,上传图片时发生错误", + "Sorry, an error occurred uploading the file": "抱歉,上传文件时发生错误", "Write a caption": "撰写一个标题", "Info": "信息", "Info notice": "提示信息", @@ -231,16 +234,15 @@ "Path to document": "文件路径", "Group member options": "小组成员选项", "Remove": "移除", + "Sort in sidebar": "调整侧边栏的显示顺序", + "Alphabetical sort": "按字母顺序排序", + "Manual sort": "手动排序", "Edit": "编辑", "Permissions": "权限", "Delete": "删除", "Collection permissions": "文档集权限", "Delete collection": "删除文档集", "Export collection": "导出文档集", - "Show sort menu": "显示排序菜单", - "Sort in sidebar": "调整侧边栏的显示顺序", - "Alphabetical sort": "按字母顺序排序", - "Manual sort": "手动排序", "Document restored": "文档已恢复", "Document unpublished": "未发布的文档", "Document options": "文档选项", @@ -268,7 +270,7 @@ "Revision options": "修订选项", "Restore version": "恢复此版本", "Copy link": "复制链接", - "Share link revoked": "已撤销共享链接", + "Share link revoked": "此分享链接已被撤销", "Share link copied": "分享链接已复制", "Share options": "分享选项", "Go to document": "转到文档", @@ -277,7 +279,7 @@ "Headings you add to the document will appear here": "您添加到文档的标题将显示在此处", "Table of contents": "目录", "By {{ author }}": "创建人 {{ author }}", - "Are you sure you want to make {{ userName }} an admin? Admins can modify team and billing information.": "您确定要设置 {{ userName }} 为管理员吗?管理员可以修改团队和帐单信息。", + "Are you sure you want to make {{ userName }} an admin? Admins can modify team and billing information.": "您确定要提升 {{ userName }} 为管理员吗?管理员可以修改团队和账单信息。", "Are you sure you want to make {{ userName }} a member?": "您确定要设置 {{ userName }} 为成员吗?", "Are you sure you want to make {{ userName }} a read-only viewer? They will not be able to edit any content": "您确定要将 {{ userName }} 设为只读模式吗?他们将无法编辑任何内容", "Are you sure you want to suspend this account? Suspended users will be prevented from logging in.": "您确定要冻结此帐户吗?被冻结的用户将无法登录。", @@ -297,7 +299,7 @@ "Recently updated": "最近更新", "Recently published": "最近发布", "Least recently updated": "最近最少更新", - "A–Z": "A-Z", + "A–Z": "A–Z", "Search in collection": "在文档集中搜索", "Drop documents to import": "拖放文档以导入", "{{ collectionName }} doesn’t contain any\n documents yet.": "{{ collectionName }} 尚未包含任何文档", @@ -384,8 +386,8 @@ "Sorry, it looks like you don’t have permission to access the document": "抱歉,看起来您没有权限访问此文档", "This template will be permanently deleted in <2> unless restored.": "此模板将在 <2> 中永久删除,除非手动恢复。", "This document will be permanently deleted in <2> unless restored.": "此文档将在 <2> 中永久删除,除非手动恢复。", - "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", - "You’re editing a template": "You’re editing a template", + "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "突出显示一些文本,并使用 <2> 来添加占位符,以便在创建新文件时填写。", + "You’re editing a template": "您正在编辑模板", "Archived by {{userName}}": "已被 {{userName}} 存档", "Deleted by {{userName}}": "已被 {{userName}} 删除", "Observing {{ userName }}": "观察 {{ userName }}", @@ -428,7 +430,7 @@ "We were unable to find the page you’re looking for. Go to the <2>homepage?": "我们找不到您要查找的页面。转到<2>主页?", "Offline": "离线", "We were unable to load the document while offline.": "离线状态无法加载文档。", - "Your account has been suspended": "您的游戏账号已被冻结", + "Your account has been suspended": "您的账户已被停用", "A team admin ({{ suspendedContactEmail }}) has suspended your account. To re-activate your account, please reach out to them directly.": "团队管理员({{ suspendedContactEmail }})已暂停您的帐户。要重新激活您的帐户,请直接与他们联系。", "Are you sure about that? Deleting the {{groupName}} group will cause its members to lose access to collections and documents that it is associated with.": "您确定要这样做吗? 删除 {{groupName}} 组将使其成员无法访问它所关联的文档集和文档。", "You can edit the name of this group at any time, however doing so too often might confuse your team mates.": "您可以随时编辑该群组的名称,但过于频繁可能会使您的队友感到困惑。", @@ -525,7 +527,7 @@ "{{userName}} requested": "{{userName}} 已请求", "Upload": "上传", "Last active": "最近活跃", - "Suspended": "已冻结", + "Suspended": "已停用", "Shared": "已共享", "by {{ name }}": "由 {{ name }}", "Last accessed": "上次访问", diff --git a/shared/i18n/locales/zh_TW/translation.json b/shared/i18n/locales/zh_TW/translation.json index 5803601485..479a083f90 100644 --- a/shared/i18n/locales/zh_TW/translation.json +++ b/shared/i18n/locales/zh_TW/translation.json @@ -19,6 +19,7 @@ "Pinned to collection": "Pinned to collection", "Pin to home": "Pin to home", "Pinned to team home": "Pinned to team home", + "Pin": "Pin", "Print": "列印", "Print document": "列印文件", "Import document": "匯入文件", @@ -139,6 +140,7 @@ "Document archived": "文件已被封存", "Move document": "移動文件", "Collections": "文件集", + "You can't reorder documents in an alphabetically sorted collection": "You can't reorder documents in an alphabetically sorted collection", "Untitled": "無標題", "New nested document": "建立新的子文件", "Document not supported – try Markdown, Plain text, HTML, or Word": "不支援的文件格式-請嘗試使用 Markdown、純文字、HTML 或 Word 格式", @@ -192,6 +194,7 @@ "Center large": "放大置中", "Italic": "斜體", "Sorry, that link won’t work for this embed type": "抱歉,不支援將這個連結嵌入到文件", + "File attachment": "File attachment", "Find or create a doc": "尋找或建立文件", "Big heading": "大標題", "Medium heading": "中標題", @@ -199,7 +202,7 @@ "Heading": "標題", "Divider": "分隔線", "Image": "圖片", - "Sorry, an error occurred uploading the image": "抱歉,上傳圖片時發生錯誤", + "Sorry, an error occurred uploading the file": "Sorry, an error occurred uploading the file", "Write a caption": "撰寫說明文字", "Info": "資訊", "Info notice": "訊息通知", @@ -231,16 +234,15 @@ "Path to document": "文件路徑", "Group member options": "群組成員選項", "Remove": "移除", + "Sort in sidebar": "在側邊欄中排序", + "Alphabetical sort": "依照字母排序", + "Manual sort": "手動排序", "Edit": "編輯", "Permissions": "權限", "Delete": "刪除", "Collection permissions": "文件集權限", "Delete collection": "刪除文件集", "Export collection": "匯出文件集", - "Show sort menu": "顯示排序選單", - "Sort in sidebar": "在側邊欄中排序", - "Alphabetical sort": "依照字母排序", - "Manual sort": "手動排序", "Document restored": "文件已經被還原", "Document unpublished": "文件已經回復為未公開狀態", "Document options": "文件選項", From f44b5708c3f82e9fc5726793e37d94c3847ce1cf Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Mar 2022 16:17:29 -0800 Subject: [PATCH 020/187] fix: Show error when auth.config fails rather than blank screen, useful as part of self-hosted setup in particular --- app/scenes/Login/index.tsx | 37 ++++++++++++++++++---- shared/i18n/locales/en_US/translation.json | 2 ++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/app/scenes/Login/index.tsx b/app/scenes/Login/index.tsx index bb7c54e663..751b4f16d4 100644 --- a/app/scenes/Login/index.tsx +++ b/app/scenes/Login/index.tsx @@ -11,6 +11,7 @@ import ButtonLarge from "~/components/ButtonLarge"; import Fade from "~/components/Fade"; import Flex from "~/components/Flex"; import Heading from "~/components/Heading"; +import NoticeAlert from "~/components/NoticeAlert"; import OutlineLogo from "~/components/OutlineLogo"; import PageTitle from "~/components/PageTitle"; import TeamLogo from "~/components/TeamLogo"; @@ -23,10 +24,11 @@ import { changeLanguage, detectLanguage } from "~/utils/language"; import Notices from "./Notices"; import Provider from "./Provider"; -function Header({ config }: { config: Config }) { +const isHosted = env.DEPLOYMENT === "hosted"; + +function Header({ config }: { config?: Config | undefined }) { const { t } = useTranslation(); - const isHosted = env.DEPLOYMENT === "hosted"; - const isSubdomain = !!config.hostname; + const isSubdomain = !!config?.hostname; if (!isHosted || isCustomDomain()) { return null; @@ -53,6 +55,7 @@ function Login() { const { t, i18n } = useTranslation(); const { auth } = useStores(); const { config } = auth; + const [error, setError] = React.useState(null); const [emailLinkSentTo, setEmailLinkSentTo] = React.useState(""); const isCreate = location.pathname === "/create"; const handleReset = React.useCallback(() => { @@ -63,7 +66,7 @@ function Login() { }, []); React.useEffect(() => { - auth.fetchConfig(); + auth.fetchConfig().catch(setError); }, [auth]); // TODO: Persist detected language to new user @@ -92,7 +95,27 @@ function Login() { return ; } - // we're counting on the config request being fast + if (error) { + return ( + +
+ + + + {t("Failed to load configuration.")} + {!isHosted && ( +

+ Check the network requests and server logs for full details of + the error. +

+ )} +
+
+ + ); + } + + // we're counting on the config request being fast, so display nothing while waiting if (!config) { return null; } @@ -108,7 +131,7 @@ function Login() {
- + {t("Check your email")} @@ -135,7 +158,7 @@ function Login() {
- + {env.TEAM_LOGO && env.DEPLOYMENT !== "hosted" ? ( diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index eea46e6465..a036cc1ba3 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -494,6 +494,8 @@ "Inline code": "Inline code", "Back to home": "Back to home", "Back to website": "Back to website", + "Login": "Login", + "Failed to load configuration.": "Failed to load configuration.", "Check your email": "Check your email", "A magic sign-in link has been sent to the email {{ emailLinkSentTo }}, no password needed.": "A magic sign-in link has been sent to the email {{ emailLinkSentTo }}, no password needed.", "Back to login": "Back to login", From e30f6e937cacea25a1cdc0a72ecb4f1e731c5654 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Mar 2022 17:01:46 -0800 Subject: [PATCH 021/187] fix: Automatically disable email sign-in when SMTP is not configured fix: Do not show email signin as enabled when SMTP configured closes #3227 --- server/models/Team.ts | 13 +++++++++++++ server/presenters/team.ts | 2 +- server/routes/api/auth.ts | 2 +- server/routes/auth/providers/email.ts | 4 ++-- server/test/setup.ts | 2 ++ 5 files changed, 19 insertions(+), 4 deletions(-) diff --git a/server/models/Team.ts b/server/models/Team.ts index d3e0d800d8..8ffead4e68 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -20,6 +20,7 @@ import { } from "sequelize-typescript"; import { v4 as uuidv4 } from "uuid"; import { stripSubdomain, RESERVED_SUBDOMAINS } from "@shared/utils/domains"; +import env from "@server/env"; import Logger from "@server/logging/logger"; import { generateAvatarUrl } from "@server/utils/avatars"; import { publicS3Endpoint, uploadToS3FromUrl } from "@server/utils/s3"; @@ -99,6 +100,18 @@ class Team extends ParanoidModel { // getters + /** + * Returns whether the team has email login enabled. For self-hosted installs + * this also considers whether SMTP connection details have been configured. + * + * @return {boolean} Whether to show email login options + */ + get emailSigninEnabled(): boolean { + return ( + this.guestSignin && (!!env.SMTP_HOST || env.NODE_ENV === "development") + ); + } + get url() { if (this.domain) { return `https://${this.domain}`; diff --git a/server/presenters/team.ts b/server/presenters/team.ts index 8ce13dc661..7025a7dfe2 100644 --- a/server/presenters/team.ts +++ b/server/presenters/team.ts @@ -9,7 +9,7 @@ export default function present(team: Team) { collaborativeEditing: team.collaborativeEditing, defaultCollectionId: team.defaultCollectionId, documentEmbeds: team.documentEmbeds, - guestSignin: team.guestSignin, + guestSignin: team.emailSigninEnabled, subdomain: team.subdomain, domain: team.domain, url: team.url, diff --git a/server/routes/api/auth.ts b/server/routes/api/auth.ts index d5d59a39c5..3072a2f838 100644 --- a/server/routes/api/auth.ts +++ b/server/routes/api/auth.ts @@ -17,7 +17,7 @@ function filterProviders(team: Team) { // guest sign-in is an exception as it does not have an authentication // provider using passport, instead it exists as a boolean option on the team if (provider.id === "email") { - return team && team.guestSignin; + return team?.emailSigninEnabled; } return ( diff --git a/server/routes/auth/providers/email.ts b/server/routes/auth/providers/email.ts index 150b131879..5a5383cc9e 100644 --- a/server/routes/auth/providers/email.ts +++ b/server/routes/auth/providers/email.ts @@ -92,7 +92,7 @@ router.post("email", errorHandling(), async (ctx) => { return; } - if (!team.guestSignin) { + if (!team.emailSigninEnabled) { throw AuthorizationError(); } @@ -138,7 +138,7 @@ router.get("email.callback", async (ctx) => { return; } - if (!user.team.guestSignin) { + if (!user.team.emailSigninEnabled) { return ctx.redirect("/?notice=auth-error"); } diff --git a/server/test/setup.ts b/server/test/setup.ts index 0c44f5d12b..ddcbe6d998 100644 --- a/server/test/setup.ts +++ b/server/test/setup.ts @@ -1,6 +1,7 @@ import "../env"; // test environment variables +process.env.SMTP_HOST = "smtp.example.com"; process.env.DATABASE_URL = process.env.DATABASE_URL_TEST; process.env.NODE_ENV = "test"; process.env.GOOGLE_CLIENT_ID = "123"; @@ -19,6 +20,7 @@ jest.mock("../queues"); jest.mock("aws-sdk", () => { const mS3 = { createPresignedPost: jest.fn(), + putObject: jest.fn().mockReturnThis(), deleteObject: jest.fn().mockReturnThis(), promise: jest.fn(), }; From c979d003e4c930d4bc9c25a82a336b90e429356c Mon Sep 17 00:00:00 2001 From: Saumya Pandey Date: Sun, 13 Mar 2022 09:38:36 +0530 Subject: [PATCH 022/187] fix: navigate to all the pages of settings through command bar (#3226) * fix: create useAuthorizedSettingsConfig * use config to render routes * translations and icon * mount in CommandBar * memo * Update app/hooks/useSettingsAction.tsx Co-authored-by: Tom Moor * fix: add actions into settings action * remove comment * fix: update shares * fix: Remove Slack/Zapier from translations Co-authored-by: Tom Moor --- app/actions/definitions/navigation.tsx | 1 - app/components/CommandBar.tsx | 8 +- app/hooks/useAuthorizedSettingsConfig.ts | 196 +++++++++++++++++++++ app/hooks/useSettingsAction.tsx | 38 ++++ app/routes/settings.tsx | 43 ++--- app/scenes/Settings/Zapier.tsx | 4 +- shared/i18n/locales/en_US/translation.json | 1 - 7 files changed, 254 insertions(+), 37 deletions(-) create mode 100644 app/hooks/useAuthorizedSettingsConfig.ts create mode 100644 app/hooks/useSettingsAction.tsx diff --git a/app/actions/definitions/navigation.tsx b/app/actions/definitions/navigation.tsx index 0334862dbb..41f71c0f29 100644 --- a/app/actions/definitions/navigation.tsx +++ b/app/actions/definitions/navigation.tsx @@ -174,7 +174,6 @@ export const rootNavigationActions = [ navigateToTemplates, navigateToArchive, navigateToTrash, - navigateToSettings, openAPIDocumentation, openFeedbackUrl, openBugReportUrl, diff --git a/app/components/CommandBar.tsx b/app/components/CommandBar.tsx index cfb8fb8409..809f1ecbd8 100644 --- a/app/components/CommandBar.tsx +++ b/app/components/CommandBar.tsx @@ -10,6 +10,7 @@ import CommandBarResults from "~/components/CommandBarResults"; import SearchActions from "~/components/SearchActions"; import rootActions from "~/actions/root"; import useCommandBarActions from "~/hooks/useCommandBarActions"; +import useSettingsActions from "~/hooks/useSettingsAction"; import useStores from "~/hooks/useStores"; import { CommandBarAction } from "~/types"; import { metaDisplay } from "~/utils/keyboard"; @@ -18,8 +19,13 @@ import Text from "./Text"; function CommandBar() { const { t } = useTranslation(); const { ui } = useStores(); + const settingsActions = useSettingsActions(); + const commandBarActions = React.useMemo( + () => [...rootActions, settingsActions], + [settingsActions] + ); - useCommandBarActions(rootActions); + useCommandBarActions(commandBarActions); const { rootAction } = useKBar((state) => ({ rootAction: state.currentRootActionId diff --git a/app/hooks/useAuthorizedSettingsConfig.ts b/app/hooks/useAuthorizedSettingsConfig.ts new file mode 100644 index 0000000000..fe96f56481 --- /dev/null +++ b/app/hooks/useAuthorizedSettingsConfig.ts @@ -0,0 +1,196 @@ +import { + NewDocumentIcon, + EmailIcon, + ProfileIcon, + PadlockIcon, + CodeIcon, + UserIcon, + GroupIcon, + LinkIcon, + TeamIcon, + BeakerIcon, + DownloadIcon, +} from "outline-icons"; +import React from "react"; +import { useTranslation } from "react-i18next"; +import Details from "~/scenes/Settings/Details"; +import Export from "~/scenes/Settings/Export"; +import Features from "~/scenes/Settings/Features"; +import Groups from "~/scenes/Settings/Groups"; +import Import from "~/scenes/Settings/Import"; +import Members from "~/scenes/Settings/Members"; +import Notifications from "~/scenes/Settings/Notifications"; +import Profile from "~/scenes/Settings/Profile"; +import Security from "~/scenes/Settings/Security"; +import Shares from "~/scenes/Settings/Shares"; +import Slack from "~/scenes/Settings/Slack"; +import Tokens from "~/scenes/Settings/Tokens"; +import Zapier from "~/scenes/Settings/Zapier"; +import SlackIcon from "~/components/SlackIcon"; +import ZapierIcon from "~/components/ZapierIcon"; +import env from "~/env"; +import useCurrentTeam from "./useCurrentTeam"; +import usePolicy from "./usePolicy"; + +type SettingsGroups = "Account" | "Team" | "Integrations"; +type SettingsPage = + | "Profile" + | "Notifications" + | "Api" + | "Details" + | "Security" + | "Features" + | "Members" + | "Groups" + | "Shares" + | "Import" + | "Export" + | "Slack" + | "Zapier"; + +export type ConfigItem = { + name: string; + path: string; + icon: React.FC; + component: () => JSX.Element; + enabled: boolean; + group: SettingsGroups; +}; + +type ConfigType = { + [key in SettingsPage]: ConfigItem; +}; + +const isHosted = env.DEPLOYMENT === "hosted"; + +const useAuthorizedSettingsConfig = () => { + const team = useCurrentTeam(); + const can = usePolicy(team.id); + const { t } = useTranslation(); + + const config: ConfigType = React.useMemo( + () => ({ + Profile: { + name: t("Profile"), + path: "/settings", + component: Profile, + enabled: true, + group: t("Account"), + icon: ProfileIcon, + }, + Notifications: { + name: t("Notifications"), + path: "/settings/notifications", + component: Notifications, + enabled: true, + group: t("Account"), + icon: EmailIcon, + }, + Api: { + name: t("API Tokens"), + path: "/settings/tokens", + component: Tokens, + enabled: can.createApiKey, + group: t("Account"), + icon: CodeIcon, + }, + // Team group + Details: { + name: t("Details"), + path: "/settings/details", + component: Details, + enabled: can.update, + group: t("Team"), + icon: TeamIcon, + }, + Security: { + name: t("Security"), + path: "/settings/security", + component: Security, + enabled: can.update, + group: t("Team"), + icon: PadlockIcon, + }, + Features: { + name: t("Features"), + path: "/settings/features", + component: Features, + enabled: can.update, + group: t("Team"), + icon: BeakerIcon, + }, + Members: { + name: t("Members"), + path: "/settings/members", + component: Members, + enabled: true, + group: t("Team"), + icon: UserIcon, + }, + Groups: { + name: t("Groups"), + path: "/settings/groups", + component: Groups, + enabled: true, + group: t("Team"), + icon: GroupIcon, + }, + Shares: { + name: t("Share Links"), + path: "/settings/shares", + component: Shares, + enabled: true, + group: t("Team"), + icon: LinkIcon, + }, + Import: { + name: t("Import"), + path: "/settings/import", + component: Import, + enabled: can.manage, + group: t("Team"), + icon: NewDocumentIcon, + }, + Export: { + name: t("Export"), + path: "/settings/export", + component: Export, + enabled: can.export, + group: t("Team"), + icon: DownloadIcon, + }, + // Intergrations + Slack: { + name: "Slack", + path: "/settings/integrations/slack", + component: Slack, + enabled: can.update && (!!env.SLACK_KEY || isHosted), + group: t("Integrations"), + icon: SlackIcon, + }, + Zapier: { + name: "Zapier", + path: "/settings/integrations/zapier", + component: Zapier, + enabled: can.update && isHosted, + group: t("Integrations"), + icon: ZapierIcon, + }, + }), + [can.createApiKey, can.export, can.manage, can.update, t] + ); + + const enabledConfigs = React.useMemo( + () => + Object.keys(config).reduce( + (acc, key: SettingsPage) => + config[key].enabled ? [...acc, config[key]] : acc, + [] + ), + [config] + ); + + return enabledConfigs; +}; + +export default useAuthorizedSettingsConfig; diff --git a/app/hooks/useSettingsAction.tsx b/app/hooks/useSettingsAction.tsx new file mode 100644 index 0000000000..28e64b54f6 --- /dev/null +++ b/app/hooks/useSettingsAction.tsx @@ -0,0 +1,38 @@ +import { SettingsIcon } from "outline-icons"; +import * as React from "react"; +import { createAction } from "~/actions"; +import { NavigationSection } from "~/actions/sections"; +import history from "~/utils/history"; +import useAuthorizedSettingsConfig from "./useAuthorizedSettingsConfig"; + +const useSettingsActions = () => { + const config = useAuthorizedSettingsConfig(); + const actions = React.useMemo(() => { + return config.map((item) => { + const Icon = item.icon; + return { + id: item.path, + name: item.name, + icon: , + section: NavigationSection, + perform: () => history.push(item.path), + }; + }); + }, [config]); + + const navigateToSettings = React.useMemo( + () => + createAction({ + name: ({ t }) => t("Settings"), + section: NavigationSection, + shortcut: ["g", "s"], + icon: , + children: () => actions, + }), + [actions] + ); + + return navigateToSettings; +}; + +export default useSettingsActions; diff --git a/app/routes/settings.tsx b/app/routes/settings.tsx index 7319c7b722..4efa52b22a 100644 --- a/app/routes/settings.tsx +++ b/app/routes/settings.tsx @@ -1,42 +1,21 @@ import * as React from "react"; import { Switch, Redirect } from "react-router-dom"; -import Details from "~/scenes/Settings/Details"; -import Export from "~/scenes/Settings/Export"; -import Features from "~/scenes/Settings/Features"; -import Groups from "~/scenes/Settings/Groups"; -import Import from "~/scenes/Settings/Import"; -import Members from "~/scenes/Settings/Members"; -import Notifications from "~/scenes/Settings/Notifications"; -import Profile from "~/scenes/Settings/Profile"; -import Security from "~/scenes/Settings/Security"; -import Shares from "~/scenes/Settings/Shares"; -import Slack from "~/scenes/Settings/Slack"; -import Tokens from "~/scenes/Settings/Tokens"; -import Zapier from "~/scenes/Settings/Zapier"; import Route from "~/components/ProfiledRoute"; -import env from "~/env"; - -const isHosted = env.DEPLOYMENT === "hosted"; +import useAuthorizedSettingsConfig from "~/hooks/useAuthorizedSettingsConfig"; export default function SettingsRoutes() { + const configs = useAuthorizedSettingsConfig(); + return ( - - - - - - - - - - - {isHosted && ( - - )} - - - + {configs.map((config) => ( + + ))} {/* old routes */} diff --git a/app/scenes/Settings/Zapier.tsx b/app/scenes/Settings/Zapier.tsx index 4b37ceb5ec..afc51aa000 100644 --- a/app/scenes/Settings/Zapier.tsx +++ b/app/scenes/Settings/Zapier.tsx @@ -9,8 +9,8 @@ import ZapierIcon from "~/components/ZapierIcon"; function Zapier() { const { t } = useTranslation(); return ( - }> - {t("Zapier")} + }> + Zapier Zapier is a platform that allows Outline to easily integrate with diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index a036cc1ba3..2f0abd40cd 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -622,7 +622,6 @@ "You can create an unlimited amount of personal tokens to authenticate\n with the API. Tokens have the same permissions as your user account.\n For more details see the developer documentation.": "You can create an unlimited amount of personal tokens to authenticate\n with the API. Tokens have the same permissions as your user account.\n For more details see the developer documentation.", "Tokens": "Tokens", "Create a token": "Create a token", - "Zapier": "Zapier", "Zapier is a platform that allows Outline to easily integrate with thousands of other business tools. Head over to Zapier to setup a \"Zap\" and start programmatically interacting with Outline.'": "Zapier is a platform that allows Outline to easily integrate with thousands of other business tools. Head over to Zapier to setup a \"Zap\" and start programmatically interacting with Outline.'", "Open Zapier": "Open Zapier", "There are no templates just yet.": "There are no templates just yet.", From da8714a4f6f9ee6f2eb59e46466fea1a6d2c0bae Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 13 Mar 2022 09:34:50 -0700 Subject: [PATCH 023/187] chore: Drive settings sidebar from new config (#3236) --- app/components/Sidebar/Settings.tsx | 122 ++++------------------------ 1 file changed, 15 insertions(+), 107 deletions(-) diff --git a/app/components/Sidebar/Settings.tsx b/app/components/Sidebar/Settings.tsx index f4ffeb79d4..fb8fe6c5ee 100644 --- a/app/components/Sidebar/Settings.tsx +++ b/app/components/Sidebar/Settings.tsx @@ -1,27 +1,14 @@ +import { groupBy } from "lodash"; import { observer } from "mobx-react"; -import { - NewDocumentIcon, - EmailIcon, - ProfileIcon, - PadlockIcon, - CodeIcon, - UserIcon, - GroupIcon, - LinkIcon, - TeamIcon, - BackIcon, - BeakerIcon, - DownloadIcon, -} from "outline-icons"; +import { BackIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import styled from "styled-components"; import Flex from "~/components/Flex"; import Scrollable from "~/components/Scrollable"; -import SlackIcon from "~/components/SlackIcon"; -import ZapierIcon from "~/components/ZapierIcon"; import env from "~/env"; +import useAuthorizedSettingsConfig from "~/hooks/useAuthorizedSettingsConfig"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import usePolicy from "~/hooks/usePolicy"; import Sidebar from "./Sidebar"; @@ -38,6 +25,8 @@ function SettingsSidebar() { const history = useHistory(); const team = useCurrentTeam(); const can = usePolicy(team.id); + const configs = useAuthorizedSettingsConfig(); + const groupedConfig = groupBy(configs, "group"); const returnToApp = React.useCallback(() => { history.push("/home"); @@ -54,100 +43,19 @@ function SettingsSidebar() { -
-
{t("Account")}
- } - label={t("Profile")} - /> - } - label={t("Notifications")} - /> - {can.createApiKey && ( - } - label={t("API Tokens")} - /> - )} -
-
-
{t("Team")}
- {can.update && ( - } - label={t("Details")} - /> - )} - {can.update && ( - } - label={t("Security")} - /> - )} - {can.update && ( - } - label={t("Features")} - /> - )} - } - exact={false} - label={t("Members")} - /> - } - exact={false} - label={t("Groups")} - /> - } - label={t("Share Links")} - /> - {can.manage && ( - } - label={t("Import")} - /> - )} - {can.export && ( - } - label={t("Export")} - /> - )} -
- {can.update && (env.SLACK_KEY || isHosted) && ( -
-
{t("Integrations")}
- {env.SLACK_KEY && ( + {Object.keys(groupedConfig).map((header) => ( +
+
{header}
+ {groupedConfig[header].map((item) => ( } - label="Slack" + key={item.path} + to={item.path} + icon={} + label={item.name} /> - )} - {isHosted && ( - } - label="Zapier" - /> - )} + ))}
- )} + ))} {can.update && !isHosted && (
{t("Installation")}
From 10cc6ed154e742ad49e400d10b9ad22259a92b2a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 13 Mar 2022 09:35:04 -0700 Subject: [PATCH 024/187] fix: Sidebar cannot collapse after visiting settings (#3235) --- app/components/ContextMenu/index.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/components/ContextMenu/index.tsx b/app/components/ContextMenu/index.tsx index 3c1f713581..735b4069fc 100644 --- a/app/components/ContextMenu/index.tsx +++ b/app/components/ContextMenu/index.tsx @@ -8,6 +8,7 @@ import useMenuContext from "~/hooks/useMenuContext"; import useMenuHeight from "~/hooks/useMenuHeight"; import usePrevious from "~/hooks/usePrevious"; import useStores from "~/hooks/useStores"; +import useUnmount from "~/hooks/useUnmount"; import { fadeIn, fadeAndSlideUp, @@ -57,6 +58,10 @@ export default function ContextMenu({ const { t } = useTranslation(); const { setIsMenuOpen } = useMenuContext(); + useUnmount(() => { + setIsMenuOpen(false); + }); + React.useEffect(() => { if (rest.visible && !previousVisible) { if (onOpen) { From 5977fe4caabff7e0d874796e79be3b0e440d1ea4 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 13 Mar 2022 22:08:26 -0700 Subject: [PATCH 025/187] fix: Editor title does not autoFocus on first load (#3238) * fix: Editor title does not autoFocus on first load * Detect IntersectionObserver for IE support --- app/components/ContentEditable.tsx | 13 +++++++++--- app/hooks/useOnScreen.ts | 34 ++++++++++++++++++++++++++++++ app/hooks/usePageVisibility.ts | 2 +- 3 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 app/hooks/useOnScreen.ts diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 984446ea0e..4b127a2cf0 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -1,6 +1,7 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import styled from "styled-components"; +import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { disabled?: boolean; @@ -69,11 +70,17 @@ const ContentEditable = React.forwardRef( callback?.(event); }; - React.useLayoutEffect(() => { - if (autoFocus) { + // This is to account for being within a React.Suspense boundary, in this + // case the component may be rendered with display: none. React 18 may solve + // this in the future by delaying useEffect hooks: + // https://github.com/facebook/react/issues/14536#issuecomment-861980492 + const isVisible = useOnScreen(ref); + + React.useEffect(() => { + if (autoFocus && isVisible && !disabled && !readOnly) { ref.current?.focus(); } - }, [autoFocus, ref]); + }, [autoFocus, disabled, isVisible, readOnly, ref]); React.useEffect(() => { if (value !== ref.current?.innerText) { diff --git a/app/hooks/useOnScreen.ts b/app/hooks/useOnScreen.ts new file mode 100644 index 0000000000..e73fcc357f --- /dev/null +++ b/app/hooks/useOnScreen.ts @@ -0,0 +1,34 @@ +import * as React from "react"; + +/** + * Hook to return if a given ref is visible on screen. + * + * @returns boolean if the node is visible + */ +export default function useOnScreen(ref: React.RefObject) { + const isSupported = "IntersectionObserver" in window; + const [isIntersecting, setIntersecting] = React.useState(!isSupported); + + React.useEffect(() => { + const element = ref.current; + let observer: IntersectionObserver | undefined; + + if (isSupported) { + observer = new IntersectionObserver(([entry]) => { + // Update our state when observer callback fires + setIntersecting(entry.isIntersecting); + }); + } + + if (element) { + observer?.observe(element); + } + return () => { + if (element) { + observer?.unobserve(element); + } + }; + }, []); + + return isIntersecting; +} diff --git a/app/hooks/usePageVisibility.ts b/app/hooks/usePageVisibility.ts index b5a0c35c9b..1c5db9fef4 100644 --- a/app/hooks/usePageVisibility.ts +++ b/app/hooks/usePageVisibility.ts @@ -1,10 +1,10 @@ import * as React from "react"; + /** * Hook to return page visibility state. * * @returns boolean if the page is visible */ - export default function usePageVisibility(): boolean { const [visible, setVisible] = React.useState(true); From de15f901b887a7730618d549f2217e13317a031a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Mar 2022 16:08:35 -0700 Subject: [PATCH 026/187] =?UTF-8?q?fix:=20Rare=20serialization=20error=20f?= =?UTF-8?q?or=20image=20nodes=20without=20a=20src.=20Honestly=20not=20sure?= =?UTF-8?q?=20how=20these=20get=20inserted=20=E2=80=93=20perhaps=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/editor/nodes/Image.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index 73ca580a0f..17c1ec9ae1 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -323,7 +323,7 @@ export default class Image extends Node { " ![" + state.esc((node.attrs.alt || "").replace("\n", "") || "", false) + "](" + - state.esc(node.attrs.src, false); + state.esc(node.attrs.src || "", false); if (node.attrs.layoutClass) { markdown += ' "' + state.esc(node.attrs.layoutClass, false) + '"'; } else if (node.attrs.title) { From 4fd48d9e4c276de7c18efd03d0f6a24a971ad8a8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Mar 2022 16:15:10 -0700 Subject: [PATCH 027/187] fix: utils.gc constraint issue, closes #3228 --- server/commands/teamPermanentDeleter.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/server/commands/teamPermanentDeleter.ts b/server/commands/teamPermanentDeleter.ts index 2b342c51e7..d67f2ba3e3 100644 --- a/server/commands/teamPermanentDeleter.ts +++ b/server/commands/teamPermanentDeleter.ts @@ -86,6 +86,13 @@ export default async function teamPermanentDeleter(team: Team) { force: true, transaction, }); + await Event.destroy({ + where: { + actorId: userIds, + }, + force: true, + transaction, + }); } ); // Destory team-relation models From 40e84ed481be81bdc2f31760e9335f77f8a9e010 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Mar 2022 16:15:20 -0700 Subject: [PATCH 028/187] i18n --- shared/i18n/locales/en_US/translation.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 2f0abd40cd..80eeb7c04c 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -151,11 +151,15 @@ "Toggle sidebar": "Toggle sidebar", "Delete {{ documentName }}": "Delete {{ documentName }}", "Return to App": "Back to App", + "Installation": "Installation", + "No results": "No results", + "Previous page": "Previous page", + "Next page": "Next page", "Account": "Account", "Notifications": "Notifications", "API Tokens": "API Tokens", - "Team": "Team", "Details": "Details", + "Team": "Team", "Security": "Security", "Features": "Features", "Members": "Members", @@ -164,10 +168,6 @@ "Import": "Import", "Export": "Export", "Integrations": "Integrations", - "Installation": "Installation", - "No results": "No results", - "Previous page": "Previous page", - "Next page": "Next page", "Insert column after": "Insert column after", "Insert column before": "Insert column before", "Insert row after": "Insert row after", From 1633bbf5aae37b8db09fb4a7d713f8a6eb22b3ca Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Mar 2022 17:41:55 -0700 Subject: [PATCH 029/187] cleanup search documents action --- app/actions/definitions/documents.tsx | 14 +++++++++++++- app/actions/definitions/navigation.tsx | 17 +---------------- app/actions/sections.ts | 2 -- app/components/CommandBar.tsx | 4 +--- app/components/CommandBarResults.tsx | 17 ++--------------- app/components/SearchActions.ts | 11 ++++++----- 6 files changed, 23 insertions(+), 42 deletions(-) diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 9bd3565bc2..7896f7dcf7 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -10,6 +10,7 @@ import { ShapesIcon, ImportIcon, PinIcon, + SearchIcon, } from "outline-icons"; import * as React from "react"; import getDataTransferFiles from "@shared/utils/getDataTransferFiles"; @@ -17,7 +18,7 @@ import DocumentTemplatize from "~/scenes/DocumentTemplatize"; import { createAction } from "~/actions"; import { DocumentSection } from "~/actions/sections"; import history from "~/utils/history"; -import { homePath, newDocumentPath } from "~/utils/routeHelpers"; +import { homePath, newDocumentPath, searchPath } from "~/utils/routeHelpers"; export const openDocument = createAction({ name: ({ t }) => t("Open document"), @@ -318,6 +319,17 @@ export const createTemplate = createAction({ }, }); +export const searchDocumentsForQuery = (searchQuery: string) => + createAction({ + id: "search", + section: DocumentSection, + name: ({ t }) => + t(`Search documents for "{{searchQuery}}"`, { searchQuery }), + icon: , + perform: () => history.push(searchPath(searchQuery)), + visible: ({ location }) => location.pathname !== searchPath(), + }); + export const rootDocumentActions = [ openDocument, createDocument, diff --git a/app/actions/definitions/navigation.tsx b/app/actions/definitions/navigation.tsx index 41f71c0f29..b64ff63d97 100644 --- a/app/actions/definitions/navigation.tsx +++ b/app/actions/definitions/navigation.tsx @@ -23,11 +23,7 @@ import stores from "~/stores"; import SearchQuery from "~/models/SearchQuery"; import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; import { createAction } from "~/actions"; -import { - NavigationSection, - SearchSection, - RecentSearchesSection, -} from "~/actions/sections"; +import { NavigationSection, RecentSearchesSection } from "~/actions/sections"; import history from "~/utils/history"; import { organizationSettingsPath, @@ -57,17 +53,6 @@ export const navigateToRecentSearchQuery = (searchQuery: SearchQuery) => perform: () => history.push(searchPath(searchQuery.query)), }); -export const navigateToSearchQuery = (searchQuery: string) => - createAction({ - id: "search", - section: SearchSection, - name: ({ t }) => - t(`Search documents for "{{searchQuery}}"`, { searchQuery }), - icon: , - perform: () => history.push(searchPath(searchQuery)), - visible: ({ location }) => location.pathname !== searchPath(), - }); - export const navigateToDrafts = createAction({ name: ({ t }) => t("Drafts"), section: NavigationSection, diff --git a/app/actions/sections.ts b/app/actions/sections.ts index 39549c6f19..2963e980fa 100644 --- a/app/actions/sections.ts +++ b/app/actions/sections.ts @@ -14,5 +14,3 @@ export const UserSection = ({ t }: ActionContext) => t("People"); export const RecentSearchesSection = ({ t }: ActionContext) => t("Recent searches"); - -export const SearchSection = ""; diff --git a/app/components/CommandBar.tsx b/app/components/CommandBar.tsx index 809f1ecbd8..3f63e4caa6 100644 --- a/app/components/CommandBar.tsx +++ b/app/components/CommandBar.tsx @@ -48,9 +48,7 @@ function CommandBar() { t("Type a command or search") }…`} /> - + {ui.commandBarOpenedFromSidebar && ( diff --git a/app/components/CommandBarResults.tsx b/app/components/CommandBarResults.tsx index 250269b678..7c2b59ee1a 100644 --- a/app/components/CommandBarResults.tsx +++ b/app/components/CommandBarResults.tsx @@ -1,27 +1,14 @@ import { useMatches, KBarResults } from "kbar"; -import { orderBy } from "lodash"; import * as React from "react"; import styled from "styled-components"; import CommandBarItem from "~/components/CommandBarItem"; -import { SearchSection } from "~/actions/sections"; -type Props = { - prioritizeSearchResults: boolean; -}; - -export default function CommandBarResults(props: Props) { +export default function CommandBarResults() { const { results, rootActionId } = useMatches(); return ( - // this is an unfortunate hack until kbar supports priority internally - typeof item !== "string" && - item.section === SearchSection && - props.prioritizeSearchResults - ? -1 - : 1 - )} + items={results} maxHeight={400} onRender={({ item, active }) => typeof item === "string" ? ( diff --git a/app/components/SearchActions.ts b/app/components/SearchActions.ts index b18620bce2..3dd6bf842c 100644 --- a/app/components/SearchActions.ts +++ b/app/components/SearchActions.ts @@ -1,9 +1,8 @@ import { useKBar } from "kbar"; import * as React from "react"; -import { - navigateToRecentSearchQuery, - navigateToSearchQuery, -} from "~/actions/definitions/navigation"; +import { searchDocumentsForQuery } from "~/actions/definitions/documents"; +import { navigateToRecentSearchQuery } from "~/actions/definitions/navigation"; + import useCommandBarActions from "~/hooks/useCommandBarActions"; import useStores from "~/hooks/useStores"; @@ -18,7 +17,9 @@ export default function SearchActions() { searchQuery: state.searchQuery, })); - useCommandBarActions(searchQuery ? [navigateToSearchQuery(searchQuery)] : []); + useCommandBarActions( + searchQuery ? [searchDocumentsForQuery(searchQuery)] : [] + ); useCommandBarActions(searches.recent.map(navigateToRecentSearchQuery)); From d63326066f9e8625693b3077d460e374613b6129 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Mar 2022 17:44:56 -0700 Subject: [PATCH 030/187] feat: Improve settings layout (#3234) * Setup, and security settings * Settings -> Details * Settings -> Notifications * Profile * lint * fix: Flash of loading on members screen * align language input * feat: Move share links management to sortable table * Add account menu to sidebar on settings page * Aesthetic tweaks, light borders between settings and slight column offset --- .../DefaultCollectionInputSelect.tsx | 11 +- app/components/Input.tsx | 2 +- app/components/InputSelect.tsx | 6 +- app/components/Scrollable.tsx | 1 + app/components/Sidebar/App.tsx | 24 ---- app/components/Sidebar/Settings.tsx | 8 +- app/components/Sidebar/Sidebar.tsx | 27 +++++ app/components/Table.tsx | 47 +++++--- app/components/TableFromParams.tsx | 75 +++++++++++++ app/components/Text.ts | 6 +- app/scenes/Settings/Details.tsx | 104 +++++++++++------- app/scenes/Settings/Export.tsx | 5 +- app/scenes/Settings/Features.tsx | 29 ++--- app/scenes/Settings/Import.tsx | 5 +- app/scenes/Settings/Members.tsx | 58 +--------- app/scenes/Settings/Notifications.tsx | 64 ++++++----- app/scenes/Settings/Profile.tsx | 93 ++++++++++------ app/scenes/Settings/Security.tsx | 95 +++++++++------- app/scenes/Settings/Shares.tsx | 96 ++++++++++++---- app/scenes/Settings/components/ImageInput.tsx | 31 ++---- .../components/NotificationListItem.tsx | 34 ------ .../Settings/components/PeopleTable.tsx | 20 +--- app/scenes/Settings/components/SettingRow.tsx | 72 ++++++++++++ .../Settings/components/SharesTable.tsx | 82 ++++++++++++++ server/routes/api/shares.ts | 74 +++++++------ shared/i18n/locales/en_US/translation.json | 24 ++-- 26 files changed, 682 insertions(+), 411 deletions(-) create mode 100644 app/components/TableFromParams.tsx delete mode 100644 app/scenes/Settings/components/NotificationListItem.tsx create mode 100644 app/scenes/Settings/components/SettingRow.tsx create mode 100644 app/scenes/Settings/components/SharesTable.tsx diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index 99f8222f22..c6e3633346 100644 --- a/app/components/DefaultCollectionInputSelect.tsx +++ b/app/components/DefaultCollectionInputSelect.tsx @@ -1,6 +1,7 @@ import { HomeIcon } from "outline-icons"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; +import { Optional } from "utility-types"; import CollectionIcon from "~/components/CollectionIcon"; import Flex from "~/components/Flex"; import InputSelect from "~/components/InputSelect"; @@ -8,7 +9,9 @@ import { IconWrapper } from "~/components/Sidebar/components/SidebarLink"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; -type DefaultCollectionInputSelectProps = { +type DefaultCollectionInputSelectProps = Optional< + React.ComponentProps +> & { onSelectCollection: (collection: string) => void; defaultCollectionId: string | null; }; @@ -16,6 +19,7 @@ type DefaultCollectionInputSelectProps = { const DefaultCollectionInputSelect = ({ onSelectCollection, defaultCollectionId, + ...rest }: DefaultCollectionInputSelectProps) => { const { t } = useTranslation(); const { collections } = useStores(); @@ -88,14 +92,11 @@ const DefaultCollectionInputSelect = ({ return ( ); }; diff --git a/app/components/Input.tsx b/app/components/Input.tsx index e8135f6cd3..8d8257d080 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -97,7 +97,7 @@ export const LabelText = styled.div` display: inline-block; `; -export type Props = { +export type Props = React.HTMLAttributes & { type?: "text" | "email" | "checkbox" | "search" | "textarea"; value?: string; label?: string; diff --git a/app/components/InputSelect.tsx b/app/components/InputSelect.tsx index 946860b113..6770bbca8a 100644 --- a/app/components/InputSelect.tsx +++ b/app/components/InputSelect.tsx @@ -23,6 +23,8 @@ export type Option = { }; export type Props = { + id?: string; + name?: string; value?: string | null; label?: string; nude?: boolean; @@ -54,6 +56,7 @@ const InputSelect = (props: Props) => { disabled, note, icon, + ...rest } = props; const select = useSelectState({ @@ -128,7 +131,7 @@ const InputSelect = (props: Props) => { wrappedLabel ))} - {(props) => ( ` margin-bottom: 16px; display: block; width: 100%; + cursor: default; &:hover:not(:disabled) { background: ${(props) => props.theme.buttonNeutralBackground}; diff --git a/app/components/Scrollable.tsx b/app/components/Scrollable.tsx index 58ced4d09b..5ef28f984d 100644 --- a/app/components/Scrollable.tsx +++ b/app/components/Scrollable.tsx @@ -49,6 +49,7 @@ function Scrollable( React.useEffect(() => { updateShadows(); }, [height, updateShadows]); + return ( { @@ -128,22 +124,6 @@ function AppSidebar() {
- - {(props) => ( - - } - /> - )} - )} @@ -154,10 +134,6 @@ const StyledTeamLogo = styled(TeamLogo)` margin-right: 4px; `; -const StyledAvatar = styled(Avatar)` - margin-left: 4px; -`; - const Drafts = styled(Text)` margin: 0 4px; `; diff --git a/app/components/Sidebar/Settings.tsx b/app/components/Sidebar/Settings.tsx index fb8fe6c5ee..286c709cef 100644 --- a/app/components/Sidebar/Settings.tsx +++ b/app/components/Sidebar/Settings.tsx @@ -9,8 +9,6 @@ import Flex from "~/components/Flex"; import Scrollable from "~/components/Scrollable"; import env from "~/env"; import useAuthorizedSettingsConfig from "~/hooks/useAuthorizedSettingsConfig"; -import useCurrentTeam from "~/hooks/useCurrentTeam"; -import usePolicy from "~/hooks/usePolicy"; import Sidebar from "./Sidebar"; import Header from "./components/Header"; import Section from "./components/Section"; @@ -23,8 +21,6 @@ const isHosted = env.DEPLOYMENT === "hosted"; function SettingsSidebar() { const { t } = useTranslation(); const history = useHistory(); - const team = useCurrentTeam(); - const can = usePolicy(team.id); const configs = useAuthorizedSettingsConfig(); const groupedConfig = groupBy(configs, "group"); @@ -42,7 +38,7 @@ function SettingsSidebar() { /> - + {Object.keys(groupedConfig).map((header) => (
{header}
@@ -56,7 +52,7 @@ function SettingsSidebar() { ))}
))} - {can.update && !isHosted && ( + {!isHosted && (
{t("Installation")}
diff --git a/app/components/Sidebar/Sidebar.tsx b/app/components/Sidebar/Sidebar.tsx index 3060f84ad9..192d588767 100644 --- a/app/components/Sidebar/Sidebar.tsx +++ b/app/components/Sidebar/Sidebar.tsx @@ -6,11 +6,15 @@ import { useLocation } from "react-router-dom"; import styled, { useTheme } from "styled-components"; import breakpoint from "styled-components-breakpoint"; import Flex from "~/components/Flex"; +import useCurrentUser from "~/hooks/useCurrentUser"; import useMenuContext from "~/hooks/useMenuContext"; import usePrevious from "~/hooks/usePrevious"; import useStores from "~/hooks/useStores"; +import AccountMenu from "~/menus/AccountMenu"; import { fadeIn } from "~/styles/animations"; +import Avatar from "../Avatar"; import ResizeBorder from "./components/ResizeBorder"; +import SidebarButton from "./components/SidebarButton"; import Toggle, { ToggleButton, Positioner } from "./components/Toggle"; const ANIMATION_MS = 250; @@ -28,6 +32,8 @@ const Sidebar = React.forwardRef( const location = useLocation(); const previousLocation = usePrevious(location); const { isMenuOpen } = useMenuContext(); + const user = useCurrentUser(); + const width = ui.sidebarWidth; const collapsed = (ui.isEditing || ui.sidebarCollapsed) && !isMenuOpen; const maxWidth = theme.sidebarMaxWidth; @@ -162,6 +168,23 @@ const Sidebar = React.forwardRef( )} {children} + + + {(props) => ( + + } + /> + )} + ( } ); +const StyledAvatar = styled(Avatar)` + margin-left: 4px; +`; + const Backdrop = styled.a` animation: ${fadeIn} 250ms ease-in-out; position: fixed; diff --git a/app/components/Table.tsx b/app/components/Table.tsx index db6dd33644..5af1eb2a65 100644 --- a/app/components/Table.tsx +++ b/app/components/Table.tsx @@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next"; import { useTable, useSortBy, usePagination } from "react-table"; import styled from "styled-components"; import Button from "~/components/Button"; +import DelayedMount from "~/components/DelayedMount"; import Empty from "~/components/Empty"; import Flex from "~/components/Flex"; import PlaceholderText from "~/components/PlaceholderText"; @@ -121,7 +122,11 @@ function Table({ {headerGroup.headers.map((column) => ( - + {column.render("Header")} {column.isSorted && (column.isSortedDesc ? ( @@ -190,17 +195,19 @@ export const Placeholder = ({ rows?: number; }) => { return ( - - {new Array(rows).fill(1).map((_, row) => ( - - {new Array(columns).fill(1).map((_, col) => ( - - - - ))} - - ))} - + + + {new Array(rows).fill(1).map((_, row) => ( + + {new Array(columns).fill(1).map((_, col) => ( + + + + ))} + + ))} + + ); }; @@ -214,6 +221,8 @@ const Pagination = styled(Flex)` `; const DescSortIcon = styled(CollapsedIcon)` + margin-left: -2px; + &:hover { fill: ${(props) => props.theme.text}; } @@ -229,12 +238,22 @@ const InnerTable = styled.table` width: 100%; `; -const SortWrapper = styled(Flex)` +const SortWrapper = styled(Flex)<{ $sortable: boolean }>` + display: inline-flex; height: 24px; + user-select: none; + border-radius: 4px; + margin: 0 -4px; + padding: 0 4px; + + &:hover { + background: ${(props) => + props.$sortable ? props.theme.secondaryBackground : "none"}; + } `; const Cell = styled.td` - padding: 6px; + padding: 8px 6px; border-bottom: 1px solid ${(props) => props.theme.divider}; font-size: 14px; diff --git a/app/components/TableFromParams.tsx b/app/components/TableFromParams.tsx new file mode 100644 index 0000000000..b5b692d13d --- /dev/null +++ b/app/components/TableFromParams.tsx @@ -0,0 +1,75 @@ +import * as React from "react"; +import { useHistory, useLocation } from "react-router-dom"; +import scrollIntoView from "smooth-scroll-into-view-if-needed"; +import useQuery from "~/hooks/useQuery"; +import type { Props } from "./Table"; + +const Table = React.lazy( + () => + import( + /* webpackChunkName: "table" */ + "~/components/Table" + ) +); + +const TableFromParams = ( + props: Omit +) => { + const topRef = React.useRef(); + const location = useLocation(); + const history = useHistory(); + const params = useQuery(); + + const handleChangeSort = React.useCallback( + (sort, direction) => { + if (sort) { + params.set("sort", sort); + } else { + params.delete("sort"); + } + + params.set("direction", direction.toLowerCase()); + + history.replace({ + pathname: location.pathname, + search: params.toString(), + }); + }, + [params, history, location.pathname] + ); + + const handleChangePage = React.useCallback( + (page) => { + if (page) { + params.set("page", page.toString()); + } else { + params.delete("page"); + } + + history.replace({ + pathname: location.pathname, + search: params.toString(), + }); + + if (topRef.current) { + scrollIntoView(topRef.current, { + scrollMode: "if-needed", + behavior: "auto", + block: "start", + }); + } + }, + [params, history, location.pathname] + ); + + return ( + + ); +}; + +export default TableFromParams; diff --git a/app/components/Text.ts b/app/components/Text.ts index 91a2d2b07c..2e8d73eba2 100644 --- a/app/components/Text.ts +++ b/app/components/Text.ts @@ -2,7 +2,7 @@ import styled from "styled-components"; type Props = { type?: "secondary" | "tertiary"; - size?: "small" | "xsmall"; + size?: "large" | "small" | "xsmall"; }; /** @@ -18,7 +18,9 @@ const Text = styled.p` ? props.theme.textTertiary : props.theme.text}; font-size: ${(props) => - props.size === "small" + props.size === "large" + ? "18px" + : props.size === "small" ? "14px" : props.size === "xsmall" ? "13px" diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx index bbaacb7966..fdb6688492 100644 --- a/app/scenes/Settings/Details.tsx +++ b/app/scenes/Settings/Details.tsx @@ -14,6 +14,7 @@ import useCurrentTeam from "~/hooks/useCurrentTeam"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; import ImageInput from "./components/ImageInput"; +import SettingRow from "./components/SettingRow"; function Details() { const { auth } = useStores(); @@ -89,60 +90,87 @@ function Details() { setDefaultCollectionId(defaultCollectionId); }, []); - const isValid = form.current && form.current.checkValidity(); + const isValid = form.current?.checkValidity(); return ( }> {t("Details")} - These details affect the way that your Outline appears to everyone on - the team. + These settings affect the way that your knowledge base appears to + everyone on the team. - -
- + + + - {env.SUBDOMAINS_ENABLED && ( - <> - - {subdomain && ( + description={t( + "The team name, usually the same as your company name." + )} + > + + + Your knowledge base will be accessible at{" "} {subdomain}.getoutline.com - )} - - )} - + ) : ( + t("Choose a subdomain to enable a login page just for your team.") + ) + } + > + + + + + + diff --git a/app/scenes/Settings/Export.tsx b/app/scenes/Settings/Export.tsx index 11e918e085..63052374ab 100644 --- a/app/scenes/Settings/Export.tsx +++ b/app/scenes/Settings/Export.tsx @@ -7,7 +7,6 @@ import Button from "~/components/Button"; import Heading from "~/components/Heading"; import PaginatedList from "~/components/PaginatedList"; import Scene from "~/components/Scene"; -import Subheading from "~/components/Subheading"; import Text from "~/components/Text"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; @@ -86,9 +85,9 @@ function Export() { type: "export", }} heading={ - +

Recent exports - +

} renderItem={(item) => ( }> - - Features - + {t("Features")} Manage optional and beta features. Changing these settings will affect the experience for all team members. - - When enabled multiple people can edit documents at the same time - with shared presence and live cursors. - - } - /> + label={t("Collaborative editing")} + description={t( + "When enabled multiple people can edit documents at the same time with shared presence and live cursors." + )} + > + +
); } diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx index 30f2f8ea5b..df8b3915a0 100644 --- a/app/scenes/Settings/Import.tsx +++ b/app/scenes/Settings/Import.tsx @@ -12,7 +12,6 @@ import Item from "~/components/List/Item"; import OutlineLogo from "~/components/OutlineLogo"; import PaginatedList from "~/components/PaginatedList"; import Scene from "~/components/Scene"; -import Subheading from "~/components/Subheading"; import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; @@ -139,9 +138,9 @@ function Import() { type: "import", }} heading={ - +

Recent imports - +

} renderItem={(item) => ( diff --git a/app/scenes/Settings/Members.tsx b/app/scenes/Settings/Members.tsx index 9325cc9765..e34fc0d648 100644 --- a/app/scenes/Settings/Members.tsx +++ b/app/scenes/Settings/Members.tsx @@ -4,7 +4,6 @@ import { PlusIcon, UserIcon } from "outline-icons"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { useHistory, useLocation } from "react-router-dom"; -import scrollIntoView from "smooth-scroll-into-view-if-needed"; import styled from "styled-components"; import { PAGINATION_SYMBOL } from "~/stores/BaseStore"; import User from "~/models/User"; @@ -26,7 +25,6 @@ import PeopleTable from "./components/PeopleTable"; import UserStatusFilter from "./components/UserStatusFilter"; function Members() { - const topRef = React.useRef(); const location = useLocation(); const history = useHistory(); const [ @@ -46,9 +44,9 @@ function Members() { const query = params.get("query") || ""; const filter = params.get("filter") || ""; const sort = params.get("sort") || "name"; - const direction = - params.get("direction")?.toUpperCase() === "ASC" ? "ASC" : "DESC"; - + const direction = (params.get("direction") || "asc").toUpperCase() as + | "ASC" + | "DESC"; const page = parseInt(params.get("page") || "0", 10); const limit = 25; @@ -141,52 +139,6 @@ function Members() { [params, history, location.pathname] ); - const handleChangeSort = React.useCallback( - (sort, direction) => { - if (sort) { - params.set("sort", sort); - } else { - params.delete("sort"); - } - - if (direction === "DESC") { - params.set("direction", direction.toLowerCase()); - } else { - params.delete("direction"); - } - - history.replace({ - pathname: location.pathname, - search: params.toString(), - }); - }, - [params, history, location.pathname] - ); - - const handleChangePage = React.useCallback( - (page) => { - if (page) { - params.set("page", page.toString()); - } else { - params.delete("page"); - } - - history.replace({ - pathname: location.pathname, - search: params.toString(), - }); - - if (topRef.current) { - scrollIntoView(topRef.current, { - scrollMode: "if-needed", - behavior: "auto", - block: "start", - }); - } - }, - [params, history, location.pathname] - ); - return ( diff --git a/app/scenes/Settings/Notifications.tsx b/app/scenes/Settings/Notifications.tsx index b436c7fda0..42792ae09e 100644 --- a/app/scenes/Settings/Notifications.tsx +++ b/app/scenes/Settings/Notifications.tsx @@ -3,18 +3,17 @@ import { observer } from "mobx-react"; import { EmailIcon } from "outline-icons"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; -import styled from "styled-components"; import Heading from "~/components/Heading"; import Input from "~/components/Input"; import Notice from "~/components/Notice"; import Scene from "~/components/Scene"; -import Subheading from "~/components/Subheading"; +import Switch from "~/components/Switch"; import Text from "~/components/Text"; import env from "~/env"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; -import NotificationListItem from "./components/NotificationListItem"; +import SettingRow from "./components/SettingRow"; function Notifications() { const { notificationSettings } = useStores(); @@ -48,6 +47,7 @@ function Notifications() { separator: true, }, { + visible: env.DEPLOYMENT === "hosted", event: "emails.onboarding", title: t("Getting started"), description: t( @@ -55,6 +55,7 @@ function Notifications() { ), }, { + visible: env.DEPLOYMENT === "hosted", event: "emails.features", title: t("New features"), description: t("Receive an email when new features of note are added"), @@ -101,42 +102,49 @@ function Notifications() { )} - - Manage when and where you receive email notifications from Outline. - Your email address can be updated in your SSO provider. - + Manage when and where you receive email notifications. {env.EMAIL_ENABLED ? ( <> - + name="email" + description={t( + "Your email address should be updated in your SSO provider." + )} + > + + - {t("Notifications")} +

{t("Notifications")}

- {options.map((option, index) => { + {options.map((option) => { if (option.separator || !option.event) { - return ; + return
; } const setting = notificationSettings.getByEvent(option.event); return ( - + + + ); })} @@ -153,8 +161,4 @@ function Notifications() { ); } -const Separator = styled.hr` - padding-bottom: 12px; -`; - export default observer(Notifications); diff --git a/app/scenes/Settings/Profile.tsx b/app/scenes/Settings/Profile.tsx index 952da03cc6..5fc88b0eb1 100644 --- a/app/scenes/Settings/Profile.tsx +++ b/app/scenes/Settings/Profile.tsx @@ -15,6 +15,7 @@ import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; import ImageInput from "./components/ImageInput"; +import SettingRow from "./components/SettingRow"; const Profile = () => { const { auth } = useStores(); @@ -74,51 +75,71 @@ const Profile = () => { setShowDeleteModal((prev) => !prev); }; - const isValid = form.current && form.current.checkValidity(); + const isValid = form.current?.checkValidity(); const { isSaving } = auth; return ( }> {t("Profile")} - - - + + + - + + + + - Please note that translations are currently in early access. -
- Community contributions are accepted though our{" "} - - translation portal - - + name="language" + description={ + <> + + Please note that translations are currently in early access. + Community contributions are accepted though our{" "} + + translation portal + + . + + } - short - /> + > + +
+ @@ -126,7 +147,7 @@ const Profile = () => {

{t("Delete Account")}

- + You may delete your account at any time, note that this is unrecoverable diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index 4a86a5d0ef..6176ff7e99 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -13,6 +13,7 @@ import env from "~/env"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import useStores from "~/hooks/useStores"; import useToasts from "~/hooks/useToasts"; +import SettingRow from "./components/SettingRow"; function Security() { const { auth } = useStores(); @@ -25,10 +26,6 @@ function Security() { guestSignin: team.guestSignin, defaultUserRole: team.defaultUserRole, }); - const notes = { - member: t("New user accounts will be given member permissions by default"), - viewer: t("New user accounts will be given viewer permissions by default"), - }; const showSuccessMessage = React.useMemo( () => @@ -42,7 +39,7 @@ function Security() { const handleChange = React.useCallback( async (ev: React.ChangeEvent) => { - const newData = { ...data, [ev.target.name]: ev.target.checked }; + const newData = { ...data, [ev.target.id]: ev.target.checked }; setData(newData); await auth.updateTeam(newData); showSuccessMessage(); @@ -59,9 +56,7 @@ function Security() { return ( }> - - Security - + {t("Security")} Settings that impact the access, security, and content of your @@ -69,54 +64,70 @@ function Security() { - - + + + - + + + - + > + + + + + + ); } diff --git a/app/scenes/Settings/Shares.tsx b/app/scenes/Settings/Shares.tsx index e76e86a4e0..99c03a38f7 100644 --- a/app/scenes/Settings/Shares.tsx +++ b/app/scenes/Settings/Shares.tsx @@ -1,18 +1,20 @@ +import { sortBy } from "lodash"; import { observer } from "mobx-react"; -import { LinkIcon } from "outline-icons"; +import { LinkIcon, WarningIcon } from "outline-icons"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { Link } from "react-router-dom"; -import Empty from "~/components/Empty"; +import { PAGINATION_SYMBOL } from "~/stores/BaseStore"; +import Share from "~/models/Share"; import Heading from "~/components/Heading"; -import PaginatedList from "~/components/PaginatedList"; +import Notice from "~/components/Notice"; import Scene from "~/components/Scene"; -import Subheading from "~/components/Subheading"; import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import usePolicy from "~/hooks/usePolicy"; +import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; -import ShareListItem from "./components/ShareListItem"; +import SharesTable from "./components/SharesTable"; function Shares() { const team = useCurrentTeam(); @@ -20,10 +22,64 @@ function Shares() { const { shares, auth } = useStores(); const canShareDocuments = auth.team && auth.team.sharing; const can = usePolicy(team.id); + const [isLoading, setIsLoading] = React.useState(false); + const [data, setData] = React.useState([]); + const [totalPages, setTotalPages] = React.useState(0); + const [shareIds, setShareIds] = React.useState([]); + const params = useQuery(); + const query = params.get("query") || ""; + const sort = params.get("sort") || "createdAt"; + const direction = (params.get("direction") || "desc").toUpperCase() as + | "ASC" + | "DESC"; + const page = parseInt(params.get("page") || "0", 10); + const limit = 25; + + React.useEffect(() => { + const fetchData = async () => { + setIsLoading(true); + + try { + const response = await shares.fetchPage({ + offset: page * limit, + limit, + sort, + direction, + }); + setTotalPages(Math.ceil(response[PAGINATION_SYMBOL].total / limit)); + setShareIds(response.map((u: Share) => u.id)); + } finally { + setIsLoading(false); + } + }; + + fetchData(); + }, [query, sort, page, direction, shares]); + + React.useEffect(() => { + // sort the resulting data by the original order from the server + setData(sortBy(shares.orderedData, (item) => shareIds.indexOf(item.id))); + }, [shares.orderedData, shareIds]); return ( }> {t("Share Links")} + + {can.manage && !canShareDocuments && ( + <> + }> + {t("Sharing is currently disabled.")}{" "} + , + }} + /> + +
+ + )} + Documents that have been shared are listed below. Anyone that has the @@ -31,25 +87,17 @@ function Shares() { link has been revoked. - {can.manage && ( - - {!canShareDocuments && ( - {t("Sharing is currently disabled.")} - )}{" "} - , - }} - /> - - )} - {t("Shared documents")} - {t("No share links, yet.")}} - fetch={shares.fetchPage} - renderItem={(item) => } + +

{t("Shared documents")}

+ +
); diff --git a/app/scenes/Settings/components/ImageInput.tsx b/app/scenes/Settings/components/ImageInput.tsx index 4ce1c07fad..d875eb3a3b 100644 --- a/app/scenes/Settings/components/ImageInput.tsx +++ b/app/scenes/Settings/components/ImageInput.tsx @@ -2,39 +2,30 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Flex from "~/components/Flex"; -import { LabelText } from "~/components/Input"; import ImageUpload, { Props as ImageUploadProps } from "./ImageUpload"; type Props = ImageUploadProps & { - label: string; src?: string; }; -export default function ImageInput({ label, src, ...rest }: Props) { +export default function ImageInput({ src, ...rest }: Props) { const { t } = useTranslation(); return ( - - {label} - - - - - {t("Upload")} - - - - + + + + + {t("Upload")} + + + ); } -const InputWrapper = styled(Flex)` - margin-bottom: 24px; -`; - const avatarStyles = ` - width: 80px; - height: 80px; + width: 64px; + height: 64px; `; const Avatar = styled.img` diff --git a/app/scenes/Settings/components/NotificationListItem.tsx b/app/scenes/Settings/components/NotificationListItem.tsx deleted file mode 100644 index c690522020..0000000000 --- a/app/scenes/Settings/components/NotificationListItem.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import * as React from "react"; -import NotificationSetting from "~/models/NotificationSetting"; -import Switch from "~/components/Switch"; - -type Props = { - setting?: NotificationSetting; - title: string; - event: string; - description: string; - disabled: boolean; - onChange: (ev: React.SyntheticEvent) => void | Promise; -}; - -const NotificationListItem = ({ - setting, - title, - event, - onChange, - disabled, - description, -}: Props) => { - return ( - - ); -}; - -export default NotificationListItem; diff --git a/app/scenes/Settings/components/PeopleTable.tsx b/app/scenes/Settings/components/PeopleTable.tsx index df467400c6..205b3fc1e6 100644 --- a/app/scenes/Settings/components/PeopleTable.tsx +++ b/app/scenes/Settings/components/PeopleTable.tsx @@ -2,29 +2,16 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import { $Diff } from "utility-types"; import User from "~/models/User"; import Avatar from "~/components/Avatar"; import Badge from "~/components/Badge"; import Flex from "~/components/Flex"; -import { Props as TableProps } from "~/components/Table"; +import TableFromParams from "~/components/TableFromParams"; import Time from "~/components/Time"; import useCurrentUser from "~/hooks/useCurrentUser"; import UserMenu from "~/menus/UserMenu"; -const Table = React.lazy( - () => - import( - /* webpackChunkName: "table" */ - "~/components/Table" - ) -); -type Props = $Diff< - TableProps, - { - columns: any; - } -> & { +type Props = Omit, "columns"> & { data: User[]; canManage: boolean; }; @@ -82,6 +69,7 @@ function PeopleTable({ canManage, ...rest }: Props) { Header: " ", accessor: "id", className: "actions", + disableSortBy: true, Cell: observer( ({ row, value }: { value: string; row: { original: User } }) => currentUser.id !== value ? ( @@ -94,7 +82,7 @@ function PeopleTable({ canManage, ...rest }: Props) { [t, canManage, currentUser] ); - return
; + return ; } const Badges = styled.div` diff --git a/app/scenes/Settings/components/SettingRow.tsx b/app/scenes/Settings/components/SettingRow.tsx new file mode 100644 index 0000000000..79d29584ea --- /dev/null +++ b/app/scenes/Settings/components/SettingRow.tsx @@ -0,0 +1,72 @@ +import { transparentize } from "polished"; +import * as React from "react"; +import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; +import Flex from "~/components/Flex"; +import Text from "~/components/Text"; + +type Props = { + label: React.ReactNode; + description: React.ReactNode; + name: string; + children: React.ReactNode; + visible?: boolean; + border?: boolean; +}; + +const Row = styled(Flex)<{ $border?: boolean }>` + display: block; + padding: 24px 0; + border-bottom: 1px solid + ${(props) => + props.$border === false + ? "transparent" + : transparentize(0.5, props.theme.divider)}; + + ${breakpoint("tablet")` + display: flex; + `}; + + &:last-child { + border-bottom: 0; + } +`; + +const Column = styled.div` + display: flex; + flex-direction: column; + flex-basis: 100%; + flex: 1; + + &:first-child { + min-width: 60%; + } + + ${breakpoint("tablet")` + p { + margin-bottom: 0; + } + `}; +`; + +const Label = styled(Text)` + margin-bottom: 4px; +`; + +export default function SettingRow(props: Props) { + if (props.visible === false) { + return null; + } + + return ( + + + + {props.description} + + {props.children} + + ); +} diff --git a/app/scenes/Settings/components/SharesTable.tsx b/app/scenes/Settings/components/SharesTable.tsx new file mode 100644 index 0000000000..54c8644387 --- /dev/null +++ b/app/scenes/Settings/components/SharesTable.tsx @@ -0,0 +1,82 @@ +import { observer } from "mobx-react"; +import { CheckmarkIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { useTheme } from "styled-components"; +import Share from "~/models/Share"; +import TableFromParams from "~/components/TableFromParams"; +import Time from "~/components/Time"; +import ShareMenu from "~/menus/ShareMenu"; + +type Props = Omit, "columns"> & { + data: Share[]; + canManage: boolean; +}; + +function SharesTable({ canManage, ...rest }: Props) { + const { t } = useTranslation(); + const theme = useTheme(); + + const columns = React.useMemo( + () => + [ + { + id: "documentTitle", + Header: t("Document"), + accessor: "documentTitle", + disableSortBy: true, + Cell: observer(({ value }: { value: string }) => <>{value}), + }, + { + id: "createdAt", + Header: t("Date shared"), + accessor: "createdAt", + Cell: observer( + ({ value, row }: { value: string; row: { original: Share } }) => + value ? ( + <> + + } + > + + + ); } diff --git a/app/scenes/ErrorSuspended.tsx b/app/scenes/ErrorSuspended.tsx index c0f9949538..e397861c0b 100644 --- a/app/scenes/ErrorSuspended.tsx +++ b/app/scenes/ErrorSuspended.tsx @@ -13,7 +13,7 @@ const ErrorSuspended = () => {

- + ⚠️ {" "} {t("Your account has been suspended")} diff --git a/app/scenes/Search/Search.tsx b/app/scenes/Search/Search.tsx index 5e7cfcf0e7..e2fc5fa711 100644 --- a/app/scenes/Search/Search.tsx +++ b/app/scenes/Search/Search.tsx @@ -1,4 +1,3 @@ -import ArrowKeyNavigation from "boundless-arrow-key-navigation"; import { isEqual } from "lodash"; import { observable, action } from "mobx"; import { observer } from "mobx-react"; @@ -14,6 +13,7 @@ import { DateFilter as TDateFilter } from "@shared/types"; import { DEFAULT_PAGINATION_LIMIT } from "~/stores/BaseStore"; import { SearchParams } from "~/stores/DocumentsStore"; import RootStore from "~/stores/RootStore"; +import ArrowKeyNavigation from "~/components/ArrowKeyNavigation"; import DocumentListItem from "~/components/DocumentListItem"; import Empty from "~/components/Empty"; import Fade from "~/components/Fade"; @@ -44,7 +44,8 @@ type Props = RouteComponentProps< @observer class Search extends React.Component { - firstDocument: HTMLAnchorElement | null | undefined; + compositeRef: HTMLDivElement | null | undefined; + searchInputRef: HTMLInputElement | null | undefined; lastQuery = ""; @@ -102,10 +103,11 @@ class Search extends React.Component { if (ev.key === "ArrowDown") { ev.preventDefault(); - if (this.firstDocument) { - if (this.firstDocument instanceof HTMLElement) { - this.firstDocument.focus(); - } + if (this.compositeRef) { + const linkItems = this.compositeRef.querySelectorAll( + "[href]" + ) as NodeListOf; + linkItems[0]?.focus(); } } }; @@ -252,8 +254,16 @@ class Search extends React.Component { }); }; - setFirstDocumentRef = (ref: HTMLAnchorElement | null) => { - this.firstDocument = ref; + setCompositeRef = (ref: HTMLDivElement | null) => { + this.compositeRef = ref; + }; + + setSearchInputRef = (ref: HTMLInputElement | null) => { + this.searchInputRef = ref; + }; + + handleEscape = () => { + this.searchInputRef?.focus(); }; render() { @@ -275,6 +285,7 @@ class Search extends React.Component { )} { )} - {results.map((result, index) => { - const document = documents.data.get(result.document.id); - if (!document) { - return null; - } - return ( - index === 0 && this.setFirstDocumentRef(ref)} - key={document.id} - document={document} - highlight={this.query} - context={result.context} - showCollection - showTemplate - /> - ); - })} + {(compositeProps) => + results.map((result) => { + const document = documents.data.get(result.document.id); + if (!document) { + return null; + } + return ( + + ); + }) + } {this.allowLoadMore && ( diff --git a/app/scenes/Search/components/SearchInput.tsx b/app/scenes/Search/components/SearchInput.tsx index 36143a3433..3efea4e290 100644 --- a/app/scenes/Search/components/SearchInput.tsx +++ b/app/scenes/Search/components/SearchInput.tsx @@ -8,18 +8,19 @@ type Props = React.HTMLAttributes & { placeholder?: string; }; -function SearchInput({ defaultValue, ...rest }: Props) { +function SearchInput( + { defaultValue, ...rest }: Props, + ref: React.RefObject +) { const theme = useTheme(); - const inputRef = React.useRef(null); - const focusInput = React.useCallback(() => { - inputRef.current?.focus(); - }, []); + ref.current?.focus(); + }, [ref]); React.useEffect(() => { // ensure that focus is placed at end of input const len = (defaultValue || "").length; - inputRef.current?.setSelectionRange(len, len); + ref.current?.setSelectionRange(len, len); const timeoutId = setTimeout(() => { focusInput(); }, 100); // arbitrary number @@ -27,7 +28,7 @@ function SearchInput({ defaultValue, ...rest }: Props) { return () => { clearTimeout(timeoutId); }; - }, [defaultValue, focusInput]); + }, [ref, defaultValue, focusInput]); return ( @@ -35,7 +36,7 @@ function SearchInput({ defaultValue, ...rest }: Props) { props.theme.primary}; + outline-offset: -1px; } `; diff --git a/app/typings/index.d.ts b/app/typings/index.d.ts index e7e8d44372..d279e404f8 100644 --- a/app/typings/index.d.ts +++ b/app/typings/index.d.ts @@ -1,7 +1,5 @@ declare module "autotrack/autotrack.js"; -declare module "boundless-arrow-key-navigation"; - declare module "string-replace-to-array"; declare module "sequelize-encrypted"; diff --git a/package.json b/package.json index fba934940b..b8b223d6e3 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,6 @@ "babel-plugin-lodash": "^3.3.4", "babel-plugin-styled-components": "^1.11.1", "babel-plugin-transform-class-properties": "^6.24.1", - "boundless-arrow-key-navigation": "^1.0.4", "bull": "^3.29.0", "cancan": "3.1.0", "chalk": "^4.1.0", diff --git a/webpack.config.js b/webpack.config.js index 17acdbe957..10f01b1ecb 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -49,7 +49,6 @@ module.exports = { "~": path.resolve(__dirname, 'app'), "@shared": path.resolve(__dirname, 'shared'), "@server": path.resolve(__dirname, 'server'), - 'boundless-arrow-key-navigation': 'boundless-arrow-key-navigation/build', 'boundless-popover': 'boundless-popover/build', 'boundless-utils-omit-keys': 'boundless-utils-omit-keys/build', 'boundless-utils-uuid': 'boundless-utils-uuid/build' From ac2a12471436dd2abd4eebdd82ad4c796425ca0f Mon Sep 17 00:00:00 2001 From: Nan Yu Date: Wed, 16 Mar 2022 15:01:25 -0700 Subject: [PATCH 038/187] fix: prevent history from crashing due to missing EditorView (#3257) * put the editor into read only mode when examining history --- app/editor/index.tsx | 4 ++-- app/scenes/Document/components/DataLoader.tsx | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 4af42b2859..69d4bfe8af 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -118,7 +118,7 @@ export type Props = { /** Callback when user uses cancel key combo */ onCancel?: () => void; /** Callback when user changes editor content */ - onChange?: (value: () => string) => void; + onChange?: (value: () => string | undefined) => void; /** Callback when a file upload begins */ onFileUploadStart?: () => void; /** Callback when a file upload ends */ @@ -629,7 +629,7 @@ export class Editor extends React.PureComponent< } this.props.onChange(() => { - return this.value(); + return this.view ? this.value() : undefined; }); }; diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index c8a3792c55..9f9d6c6da0 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -272,7 +272,11 @@ class DataLoader extends React.Component { revision, abilities, isEditing: this.isEditing, - readOnly: !this.isEditing || !abilities.update || document.isArchived, + readOnly: + !this.isEditing || + !abilities.update || + document.isArchived || + !!revisionId, onSearchLink: this.onSearchLink, onCreateLink: this.onCreateLink, sharedTree: this.sharedTree, From a27af88d4a711bc6b7f97b0f01b128c34cb76309 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Mar 2022 15:18:04 -0700 Subject: [PATCH 039/187] perf: Stop copying attachments when moving documents (#3251) * perf: Stop copying attachments when moving documents * lint --- server/commands/documentMover.test.ts | 44 ----------------------- server/commands/documentMover.ts | 51 +-------------------------- server/routes/api/attachments.ts | 14 ++++---- 3 files changed, 8 insertions(+), 101 deletions(-) diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts index 9d1a102a2e..64af61f6c2 100644 --- a/server/commands/documentMover.test.ts +++ b/server/commands/documentMover.test.ts @@ -1,12 +1,9 @@ -import Attachment from "@server/models/Attachment"; import { buildDocument, - buildAttachment, buildCollection, buildUser, } from "@server/test/factories"; import { flushdb, seed } from "@server/test/support"; -import parseAttachmentIds from "@server/utils/parseAttachmentIds"; import documentMover from "./documentMover"; beforeEach(() => flushdb()); @@ -110,45 +107,4 @@ describe("documentMover", () => { expect(response.documents[0].collection.id).toEqual(newCollection.id); expect(response.documents[1].collection.id).toEqual(newCollection.id); }); - - it("should move attachments in children to another collection", async () => { - const { document, user, collection } = await seed(); - const newCollection = await buildCollection({ - teamId: collection.teamId, - }); - const attachment = await buildAttachment({ - teamId: user.teamId, - userId: user.id, - }); - const newDocument = await buildDocument({ - parentDocumentId: document.id, - collectionId: collection.id, - teamId: collection.teamId, - userId: collection.createdById, - title: "Child document", - text: `content ![attachment](${attachment.redirectUrl})`, - }); - - await collection.addDocumentToStructure(newDocument); - await documentMover({ - user, - document, - collectionId: newCollection.id, - parentDocumentId: undefined, - index: 0, - ip, - }); - - // check document ids where updated - await newDocument.reload(); - expect(newDocument.collectionId).toBe(newCollection.id); - - // check new attachment was created pointint to same key - const attachmentIds = parseAttachmentIds(newDocument.text); - const newAttachment = await Attachment.findByPk(attachmentIds[0]); - expect(newAttachment?.documentId).toBe(newDocument.id); - expect(newAttachment?.key).toBe(attachment.key); - await document.reload(); - expect(document.collectionId).toBe(newCollection.id); - }); }); diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 1c4ba0f9ab..bd2ca461b5 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -2,52 +2,9 @@ import invariant from "invariant"; import { Transaction } from "sequelize"; import { sequelize } from "@server/database/sequelize"; import { APM } from "@server/logging/tracing"; -import { - User, - Document, - Attachment, - Collection, - Pin, - Event, -} from "@server/models"; -import parseAttachmentIds from "@server/utils/parseAttachmentIds"; +import { User, Document, Collection, Pin, Event } from "@server/models"; import pinDestroyer from "./pinDestroyer"; -async function copyAttachments( - document: Document, - options?: { transaction?: Transaction } -) { - let text = document.text; - const documentId = document.id; - // find any image attachments that are in this documents text - const attachmentIds = parseAttachmentIds(text); - - for (const id of attachmentIds) { - const existing = await Attachment.findOne({ - where: { - teamId: document.teamId, - id, - }, - }); - - // if the image attachment was originally uploaded to another document - // (this can happen in various ways, copy/paste, or duplicate for example) - // then create a new attachment pointed to this doc and update the reference - // in the text so that it gets the moved documents permissions - if (existing && existing.documentId !== documentId) { - // @ts-expect-error dataValues exists - const { id, ...rest } = existing.dataValues; - const attachment = await Attachment.create( - { ...rest, documentId }, - options - ); - text = text.replace(existing.redirectUrl, attachment.redirectUrl); - } - } - - return text; -} - type Props = { user: User; document: Document; @@ -127,9 +84,6 @@ async function documentMover({ await collection?.save({ transaction, }); - document.text = await copyAttachments(document, { - transaction, - }); } // add to new collection (may be the same) @@ -171,9 +125,6 @@ async function documentMover({ await Promise.all( childDocuments.map(async (child) => { await loopChildren(child.id); - child.text = await copyAttachments(child, { - transaction, - }); child.collectionId = collectionId; await child.save(); diff --git a/server/routes/api/attachments.ts b/server/routes/api/attachments.ts index 63090ef853..f33cef994e 100644 --- a/server/routes/api/attachments.ts +++ b/server/routes/api/attachments.ts @@ -1,7 +1,11 @@ import Router from "koa-router"; import { v4 as uuidv4 } from "uuid"; import { bytesToHumanReadable } from "@shared/utils/files"; -import { NotFoundError, ValidationError } from "@server/errors"; +import { + AuthorizationError, + NotFoundError, + ValidationError, +} from "@server/errors"; import auth from "@server/middlewares/authentication"; import { Attachment, Document, Event } from "@server/models"; import { authorize } from "@server/policies"; @@ -141,12 +145,8 @@ router.post("attachments.redirect", auth(), async (ctx) => { } if (attachment.isPrivate) { - if (attachment.documentId) { - const document = await Document.findByPk(attachment.documentId, { - userId: user.id, - paranoid: false, - }); - authorize(user, "read", document); + if (attachment.teamId !== user.teamId) { + throw AuthorizationError(); } const accessUrl = await getSignedUrl(attachment.key); From 76e1869ebfacd5c491d212ca0c2482c2e10863e6 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Mar 2022 15:18:16 -0700 Subject: [PATCH 040/187] fix: Catch error when emoji combinations cause document to be unable to persist (#3250) * fix: Catch and warn of rare error when emoji combinations cause document to be unable to persist changes closes #3230 * addEventListener -> removeEventListener --- app/components/Toast.tsx | 9 ++++++-- .../Document/components/MultiplayerEditor.tsx | 22 +++++++++++++++++++ shared/i18n/locales/en_US/translation.json | 7 +++--- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/app/components/Toast.tsx b/app/components/Toast.tsx index 50e6dbc342..a859bdf70a 100644 --- a/app/components/Toast.tsx +++ b/app/components/Toast.tsx @@ -17,7 +17,12 @@ function Toast({ closeAfterMs = 3000, onRequestClose, toast }: Props) { const { action, type = "info", reoccurring } = toast; React.useEffect(() => { - timeout.current = setTimeout(onRequestClose, toast.timeout || closeAfterMs); + if (toast.timeout) { + timeout.current = setTimeout( + onRequestClose, + toast.timeout || closeAfterMs + ); + } return () => timeout.current && clearTimeout(timeout.current); }, [onRequestClose, toast, closeAfterMs]); @@ -36,7 +41,7 @@ function Toast({ closeAfterMs = 3000, onRequestClose, toast }: Props) { }, []); const handleResume = React.useCallback(() => { - if (timeout.current) { + if (timeout.current && toast.timeout) { timeout.current = setTimeout( onRequestClose, toast.timeout || closeAfterMs diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index 0c0da6d951..20848f0c91 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -229,6 +229,28 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) { } }, [remoteProvider, isIdle, isVisible]); + // Certain emoji combinations trigger this error in YJS, while waiting for a fix + // we must prevent the user from continuing to edit as their changes will not + // be persisted. See: https://github.com/yjs/yjs/issues/303 + React.useEffect(() => { + function onUnhandledError(err: any) { + if (err.message.includes("URIError: URI malformed")) { + showToast( + t( + "Sorry, the last change could not be persisted – please reload the page" + ), + { + type: "error", + timeout: 0, + } + ); + } + } + + window.addEventListener("error", onUnhandledError); + return () => window.removeEventListener("error", onUnhandledError); + }, [showToast, t]); + if (!extensions.length) { return null; } diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 316733356e..f94c706239 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -25,8 +25,8 @@ "Import document": "Import document", "Templatize": "Templatize", "Create template": "Create template", - "Home": "Home", "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", + "Home": "Home", "Drafts": "Drafts", "Templates": "Templates", "Archive": "Archive", @@ -135,6 +135,7 @@ "Change Language": "Change Language", "Dismiss": "Dismiss", "Back": "Back", + "Documents": "Documents", "Document archived": "Document archived", "Move document": "Move document", "Collections": "Collections", @@ -290,7 +291,6 @@ "Suspend account": "Suspend account", "API token created": "API token created", "Name your token something that will help you to remember it's use in the future, for example \"local development\", \"production\", or \"continuous integration\".": "Name your token something that will help you to remember it's use in the future, for example \"local development\", \"production\", or \"continuous integration\".", - "Documents": "Documents", "The document archive is empty at the moment.": "The document archive is empty at the moment.", "This collection is only visible to those given access": "This collection is only visible to those given access", "Private": "Private", @@ -429,6 +429,7 @@ "Offline": "Offline", "We were unable to load the document while offline.": "We were unable to load the document while offline.", "Your account has been suspended": "Your account has been suspended", + "Warning Sign": "Warning Sign", "A team admin ({{ suspendedContactEmail }}) has suspended your account. To re-activate your account, please reach out to them directly.": "A team admin ({{ suspendedContactEmail }}) has suspended your account. To re-activate your account, please reach out to them directly.", "Are you sure about that? Deleting the {{groupName}} group will cause its members to lose access to collections and documents that it is associated with.": "Are you sure about that? Deleting the {{groupName}} group will cause its members to lose access to collections and documents that it is associated with.", "You can edit the name of this group at any time, however doing so too often might confuse your team mates.": "You can edit the name of this group at any time, however doing so too often might confuse your team mates.", @@ -520,6 +521,7 @@ "Author": "Author", "We were unable to find the page you’re looking for.": "We were unable to find the page you’re looking for.", "No documents found for your search filters.": "No documents found for your search filters.", + "Search Results": "Search Results", "Processing": "Processing", "Expired": "Expired", "Failed": "Failed", @@ -617,7 +619,6 @@ "Sharing is currently disabled.": "Sharing is currently disabled.", "You can globally enable and disable public document sharing in the security settings.": "You can globally enable and disable public document sharing in the security settings.", "Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.": "Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.", - "Shared documents": "Shared documents", "Whoops, you need to accept the permissions in Slack to connect Outline to your team. Try again?": "Whoops, you need to accept the permissions in Slack to connect Outline to your team. Try again?", "Something went wrong while authenticating your request. Please try logging in again?": "Something went wrong while authenticating your request. Please try logging in again?", "Get rich previews of Outline links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.": "Get rich previews of Outline links shared in Slack and use the {{ command }} slash command to search for documents without leaving your chat.", From 52358073e0b06c84f61df1cb27b8667c41f64cc3 Mon Sep 17 00:00:00 2001 From: Saumya Pandey Date: Thu, 17 Mar 2022 01:59:27 +0530 Subject: [PATCH 041/187] fix: settings collab switch --- app/scenes/Settings/Features.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/app/scenes/Settings/Features.tsx b/app/scenes/Settings/Features.tsx index d1659cfbb0..ff49defe68 100644 --- a/app/scenes/Settings/Features.tsx +++ b/app/scenes/Settings/Features.tsx @@ -52,6 +52,7 @@ function Features() { > Date: Wed, 16 Mar 2022 23:04:25 -0700 Subject: [PATCH 042/187] i18n --- shared/i18n/locales/en_US/translation.json | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index f94c706239..36e516ee8a 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -382,6 +382,7 @@ "Publish": "Publish", "Publishing": "Publishing", "Sorry, it looks like you don’t have permission to access the document": "Sorry, it looks like you don’t have permission to access the document", + "Sorry, the last change could not be persisted – please reload the page": "Sorry, the last change could not be persisted – please reload the page", "This template will be permanently deleted in <2> unless restored.": "This template will be permanently deleted in <2> unless restored.", "This document will be permanently deleted in <2> unless restored.": "This document will be permanently deleted in <2> unless restored.", "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <2> control to add placeholders that can be filled out when creating new documents", From 203980c84580a2ae71d83383fc7bc9086b1dc741 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Mar 2022 23:41:06 -0700 Subject: [PATCH 043/187] fix: ARIA fixes, missing button labels --- app/components/DocumentCard.tsx | 2 +- app/components/DocumentListItem.tsx | 1 + app/components/Sidebar/App.tsx | 7 ++++++- app/components/Sidebar/Sidebar.tsx | 1 + .../Sidebar/components/Disclosure.tsx | 11 ++++++++++- app/editor/components/CommandMenu.tsx | 14 +++++++++----- app/menus/CollectionMenu.tsx | 19 +++++++++++-------- app/menus/DocumentMenu.tsx | 19 +++++++++++-------- app/scenes/Collection/Actions.tsx | 1 + .../Search/components/RecentSearches.tsx | 1 + shared/i18n/locales/en_US/translation.json | 3 ++- 11 files changed, 54 insertions(+), 25 deletions(-) diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index 2c89b96ec9..7fce7b7bb1 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -108,7 +108,7 @@ function DocumentCard(props: Props) { {!isDragging && pin && ( - + diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index 4deb1e4552..c5a9e3960e 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -78,6 +78,7 @@ function DocumentListItem( as={DocumentLink} ref={ref} dir={document.dir} + role="menuitem" $isStarred={document.isStarred} $menuOpen={menuOpen} to={{ diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index 3233b54793..fc5ea7b4d4 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -60,7 +60,12 @@ function AppSidebar() { {...props} title={team.name} image={ - + } showDisclosure /> diff --git a/app/components/Sidebar/Sidebar.tsx b/app/components/Sidebar/Sidebar.tsx index 718380a4e8..4a08ceb5f2 100644 --- a/app/components/Sidebar/Sidebar.tsx +++ b/app/components/Sidebar/Sidebar.tsx @@ -177,6 +177,7 @@ const Sidebar = React.forwardRef( title={user.name} image={ + ); diff --git a/app/editor/components/CommandMenu.tsx b/app/editor/components/CommandMenu.tsx index fa3ec3c5e7..0d87a0b898 100644 --- a/app/editor/components/CommandMenu.tsx +++ b/app/editor/components/CommandMenu.tsx @@ -2,6 +2,7 @@ import { capitalize } from "lodash"; import { findDomRefAtPos, findParentNode } from "prosemirror-utils"; import { EditorView } from "prosemirror-view"; import * as React from "react"; +import { Trans } from "react-i18next"; import { Portal } from "react-portal"; import { VisuallyHidden } from "reakit/VisuallyHidden"; import styled from "styled-components"; @@ -545,11 +546,14 @@ class CommandMenu extends React.Component, State> { )} {uploadFile && ( - + )} diff --git a/app/menus/CollectionMenu.tsx b/app/menus/CollectionMenu.tsx index 9ad476231c..4699eac1c0 100644 --- a/app/menus/CollectionMenu.tsx +++ b/app/menus/CollectionMenu.tsx @@ -238,14 +238,17 @@ function CollectionMenu({ return ( <> - + {label ? ( {label} diff --git a/app/menus/DocumentMenu.tsx b/app/menus/DocumentMenu.tsx index 5c7d860d3b..3e15da9b6b 100644 --- a/app/menus/DocumentMenu.tsx +++ b/app/menus/DocumentMenu.tsx @@ -258,14 +258,17 @@ function DocumentMenu({ return ( <> - + {label ? ( {label} diff --git a/app/scenes/Collection/Actions.tsx b/app/scenes/Collection/Actions.tsx index b85c5d646b..fe22705b7b 100644 --- a/app/scenes/Collection/Actions.tsx +++ b/app/scenes/Collection/Actions.tsx @@ -62,6 +62,7 @@ function Actions({ collection }: Props) { placement="bottom-end" label={(props) => (