Compare commits

...

50 Commits

Author SHA1 Message Date
Tom Moor 831c256c59 renaming, tweaks 2021-03-15 18:59:00 -07:00
Tom Moor 4bdeb609e2 flow: various flow fixes 2021-03-15 18:49:43 -07:00
Saumya Pandey 4b540968dd Add test for index collision 2021-03-15 17:57:33 +05:30
Saumya Pandey 41c84a92cd Remove unnecessary logic from removeIndexCollisions 2021-03-15 17:25:32 +05:30
Saumya Pandey d6a494910f Modify collections.create 2021-03-15 17:25:04 +05:30
Saumya Pandey 0b88a02949 Better drag and drop 2021-03-15 16:53:58 +05:30
Saumya Pandey 11feb8e078 Merge branch 'reorder-collection-dev' of https://github.com/iamsaumya/outline into reorder-collection-dev 2021-03-15 11:46:45 +05:30
Saumya Pandey 79ac582b77 Use optimized removeIndexCollision 2021-03-15 11:45:02 +05:30
Saumya Pandey e118fc6a91 Update server/api/collections.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:04:06 +05:30
Saumya Pandey 0b95fb4593 Update app/stores/CollectionsStore.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:03:42 +05:30
Saumya Pandey c27d455fcd Update app/components/Sidebar/components/Collections.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:03:20 +05:30
Saumya Pandey 8043753163 Update app/components/Sidebar/components/CollectionLink.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:03:03 +05:30
Saumya Pandey fdd2068e5b Update app/components/Sidebar/components/CollectionLink.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:02:32 +05:30
Saumya Pandey 58e2598752 Update app/components/Sidebar/components/CollectionLink.js
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2021-03-15 11:01:49 +05:30
Saumya Pandey 3c440b085a Update Event type 2021-03-14 21:13:18 +05:30
Saumya Pandey 66262ced55 Working websockets 2021-03-14 20:41:41 +05:30
Saumya Pandey 06c285bad2 Add collections.move event 2021-03-12 02:27:34 +05:30
Saumya Pandey 6ac39dbe55 Don't fetch name column 2021-03-12 00:52:52 +05:30
Saumya Pandey ae26060f1b Use collate and create collection on the top 2021-03-12 00:44:19 +05:30
Saumya Pandey 6226783b5f Bug fix 2021-03-11 10:58:57 +05:30
Saumya Pandey 2e433aae2f Merge branch 'main' of https://github.com/outline/outline into reorder-collection-dev 2021-03-11 04:32:56 +05:30
Saumya Pandey d06a61a3e6 Lint error 2021-03-09 14:59:46 +05:30
Saumya Pandey 191f1f1ecb Remove indexForNew 2021-03-09 14:55:30 +05:30
Saumya Pandey 3c2b2c8a91 Work on review and make reordering predictable 2021-03-09 14:41:44 +05:30
Saumya Pandey b5921be007 Assign index in the natural order 2021-03-09 00:30:08 +05:30
Saumya Pandey 8139281650 Remove unnecessary logic from controller 2021-03-09 00:29:22 +05:30
Saumya Pandey f55bbc668b Apply suggestions from the review 2021-03-08 14:15:33 +05:30
Saumya Pandey c69619abf6 Filter for repeated index as well 2021-03-06 04:20:07 +05:30
Saumya Pandey 87b8023597 Add tests for collections.move 2021-03-06 03:57:13 +05:30
Saumya Pandey 47117890aa Update collection.create to use index 2021-03-06 02:56:37 +05:30
Saumya Pandey f7132e263b Replace naturalSort with Machine sort 2021-03-06 01:34:21 +05:30
Saumya Pandey 5380f44f79 Stop unnecessary collection moving 2021-03-05 14:25:04 +05:30
Saumya Pandey e06e432373 Update collection index in the store if successfully moved 2021-03-05 14:23:44 +05:30
Saumya Pandey 59affbcc7e Resolve bug in ordering the collections 2021-03-05 12:09:56 +05:30
Saumya Pandey 3c40aa4be0 Use move action 2021-03-04 03:57:43 +05:30
Saumya Pandey 243da7cc05 Add move action and update orderedData 2021-03-04 03:57:25 +05:30
Saumya Pandey 3027ae767d Add policy 2021-03-04 03:55:32 +05:30
Saumya Pandey 3f751f48a3 Fix bug in collections.list 2021-03-04 03:54:36 +05:30
Saumya Pandey af2086f99f Merge branch 'main' of https://github.com/outline/outline into reorder-collection-dev 2021-03-03 18:36:16 +05:30
Saumya Pandey 6f6c1b1e0b Make collectionIndexing aa util 2021-03-03 18:36:08 +05:30
Saumya Pandey a1356d30fd Create middleware to attach index to collections with compromised index 2021-02-19 01:48:45 +05:30
Saumya Pandey 2288082946 Add index column in collections 2021-02-18 17:35:56 +05:30
Saumya Pandey b0008cb3ea Merge branch 'main' of https://github.com/outline/outline into reorder-collection-dev 2021-02-18 16:39:42 +05:30
Saumya Pandey 58d98dc1eb Show top cursor if collection is hovered 2021-02-12 18:01:18 +05:30
Saumya Pandey b99ace6b2b Merge branch 'main' of https://github.com/outline/outline into reorder-collection-dev 2021-02-10 02:23:09 +05:30
Saumya Pandey 2eb1aa1475 Covert Collections.js to a functional component 2021-02-10 02:08:54 +05:30
Saumya Pandey 36dd04eec7 Move keydown('n') decorator 2021-02-10 01:40:47 +05:30
Saumya Pandey 0c341d44fc Really fix the typo in variable name 2021-02-09 22:51:16 +05:30
Saumya Pandey dfb4668a87 Fix the top cursor not showing bug and typo in variable name 2021-02-09 22:48:04 +05:30
Saumya Pandey f19ee5a01a Pseudo drag and drop of collection 2021-02-07 15:39:33 +05:30
21 changed files with 588 additions and 121 deletions
+23 -2
View File
@@ -6,11 +6,18 @@ import * as React from "react";
import { Helmet } from "react-helmet";
import { withTranslation, type TFunction } from "react-i18next";
import keydown from "react-keydown";
import { Switch, Route, Redirect } from "react-router-dom";
import {
Switch,
Route,
Redirect,
withRouter,
type RouterHistory,
} from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import AuthStore from "stores/AuthStore";
import DocumentsStore from "stores/DocumentsStore";
import PoliciesStore from "stores/PoliciesStore";
import UiStore from "stores/UiStore";
import ErrorSuspended from "scenes/ErrorSuspended";
import KeyboardShortcuts from "scenes/KeyboardShortcuts";
@@ -29,6 +36,7 @@ import {
homeUrl,
searchUrl,
matchDocumentSlug as slug,
newDocumentUrl,
} from "utils/routeHelpers";
type Props = {
@@ -38,6 +46,8 @@ type Props = {
title?: ?React.Node,
auth: AuthStore,
ui: UiStore,
history: RouterHistory,
policies: PoliciesStore,
notifications?: React.Node,
i18n: Object,
t: TFunction,
@@ -81,6 +91,17 @@ class Layout extends React.Component<Props> {
this.redirectTo = homeUrl();
}
@keydown("n")
goToNewDocument() {
const { activeCollectionId } = this.props.ui;
if (!activeCollectionId) return;
const can = this.props.policies.abilities(activeCollectionId);
if (!can.update) return;
this.props.history.push(newDocumentUrl(activeCollectionId));
}
render() {
const { auth, t, ui } = this.props;
const { user, team } = auth;
@@ -198,5 +219,5 @@ const Content = styled(Flex)`
`;
export default withTranslation()<Layout>(
inject("auth", "ui", "documents")(Layout)
inject("auth", "ui", "documents", "policies")(withRouter(Layout))
);
@@ -1,9 +1,9 @@
// @flow
import fractionalIndex from "fractional-index";
import { observer } from "mobx-react";
import * as React from "react";
import { useDrop } from "react-dnd";
import { useDrop, useDrag } from "react-dnd";
import styled from "styled-components";
import UiStore from "stores/UiStore";
import Collection from "models/Collection";
import Document from "models/Document";
import CollectionIcon from "components/CollectionIcon";
@@ -18,10 +18,12 @@ import CollectionSortMenu from "menus/CollectionSortMenu";
type Props = {|
collection: Collection,
ui: UiStore,
canUpdate: boolean,
activeDocument: ?Document,
prefetchDocument: (id: string) => Promise<void>,
belowCollection: Collection | void,
isDraggingAnyCollection: boolean,
onChangeDragging: (dragging: boolean) => void,
|};
function CollectionLink({
@@ -29,8 +31,11 @@ function CollectionLink({
activeDocument,
prefetchDocument,
canUpdate,
ui,
belowCollection,
isDraggingAnyCollection,
onChangeDragging,
}: Props) {
const { ui } = useStores();
const [menuOpen, setMenuOpen] = React.useState(false);
const handleTitleChange = React.useCallback(
@@ -40,10 +45,23 @@ function CollectionLink({
[collection]
);
const { documents, policies } = useStores();
const expanded = collection.id === ui.activeCollectionId;
const { documents, policies, collections } = useStores();
const [expanded, setExpanded] = React.useState(
collection.id === ui.activeCollectionId
);
React.useEffect(() => {
if (isDraggingAnyCollection) {
setExpanded(false);
} else {
setExpanded(collection.id === ui.activeCollectionId);
}
}, [isDraggingAnyCollection, collection.id, ui.activeCollectionId]);
const manualSort = collection.sort.field === "index";
const can = policies.abilities(collection.id);
const belowCollectionIndex = belowCollection ? belowCollection.index : null;
// Drop to re-parent
const [{ isOver, canDrop }, drop] = useDrop({
@@ -74,49 +92,101 @@ function CollectionLink({
}),
});
// Drop to reorder Collection
const [{ isCollectionDropping }, dropToReorderCollection] = useDrop({
accept: "collection",
drop: async (item, monitor) => {
collections.move(
item.id,
fractionalIndex(collection.index, belowCollectionIndex)
);
},
canDrop: (item, monitor) => {
return (
collection.id !== item.id &&
(!belowCollection || item.id !== belowCollection.id)
);
},
collect: (monitor) => ({
isCollectionDropping: monitor.isOver(),
}),
});
// Drag to reorder Collection
const [{ isCollectionDragging }, dragToReorderCollection] = useDrag({
type: "collection",
item: () => {
onChangeDragging(true);
return {
id: collection.id,
};
},
collect: (monitor) => ({
isCollectionDragging: monitor.isDragging(),
}),
canDrag: (monitor) => {
return can.move;
},
end: (monitor) => {
onChangeDragging(false);
},
});
return (
<>
<div ref={drop} style={{ position: "relative" }}>
<DropToImport key={collection.id} collectionId={collection.id}>
<SidebarLinkWithPadding
key={collection.id}
to={collection.url}
icon={
<CollectionIcon collection={collection} expanded={expanded} />
}
iconColor={collection.color}
expanded={expanded}
showActions={menuOpen || expanded}
isActiveDrop={isOver && canDrop}
label={
<EditableTitle
title={collection.name}
onSubmit={handleTitleChange}
canUpdate={canUpdate}
/>
}
exact={false}
menu={
<>
{can.update && (
<CollectionSortMenuWithMargin
<Draggable
key={collection.id}
ref={dragToReorderCollection}
$isDragging={isCollectionDragging}
$isMoving={isCollectionDragging}
>
<DropToImport collectionId={collection.id}>
<SidebarLinkWithPadding
to={collection.url}
icon={
<CollectionIcon collection={collection} expanded={expanded} />
}
iconColor={collection.color}
expanded={expanded}
showActions={menuOpen || expanded}
isActiveDrop={isOver && canDrop}
label={
<EditableTitle
title={collection.name}
onSubmit={handleTitleChange}
canUpdate={canUpdate}
/>
}
exact={false}
menu={
<>
{can.update && (
<CollectionSortMenuWithMargin
collection={collection}
onOpen={() => setMenuOpen(true)}
onClose={() => setMenuOpen(false)}
/>
)}
<CollectionMenu
collection={collection}
onOpen={() => setMenuOpen(true)}
onClose={() => setMenuOpen(false)}
/>
)}
<CollectionMenu
collection={collection}
onOpen={() => setMenuOpen(true)}
onClose={() => setMenuOpen(false)}
/>
</>
}
/>
</DropToImport>
</>
}
/>
</DropToImport>
</Draggable>
{expanded && manualSort && (
<DropCursor isActiveDrop={isOverReorder} innerRef={dropToReorder} />
)}
{isDraggingAnyCollection && (
<DropCursor
isActiveDrop={isCollectionDropping}
innerRef={dropToReorderCollection}
/>
)}
</div>
{expanded &&
@@ -136,6 +206,11 @@ function CollectionLink({
);
}
const Draggable = styled("div")`
opacity: ${(props) => (props.$isDragging || props.$isMoving ? 0.5 : 1)};
pointer-events: ${(props) => (props.$isMoving ? "none" : "auto")};
`;
const SidebarLinkWithPadding = styled(SidebarLink)`
padding-right: 60px;
`;
@@ -1,98 +1,97 @@
// @flow
import { observer, inject } from "mobx-react";
import fractionalIndex from "fractional-index";
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
import * as React from "react";
import { withTranslation, type TFunction } from "react-i18next";
import keydown from "react-keydown";
import { withRouter, type RouterHistory } from "react-router-dom";
import CollectionsStore from "stores/CollectionsStore";
import DocumentsStore from "stores/DocumentsStore";
import PoliciesStore from "stores/PoliciesStore";
import UiStore from "stores/UiStore";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import Fade from "components/Fade";
import Flex from "components/Flex";
import useStores from "../../../hooks/useStores";
import CollectionLink from "./CollectionLink";
import CollectionsLoading from "./CollectionsLoading";
import DropCursor from "./DropCursor";
import Header from "./Header";
import SidebarLink from "./SidebarLink";
import { newDocumentUrl } from "utils/routeHelpers";
type Props = {
history: RouterHistory,
policies: PoliciesStore,
collections: CollectionsStore,
documents: DocumentsStore,
onCreateCollection: () => void,
ui: UiStore,
t: TFunction,
};
@observer
class Collections extends React.Component<Props> {
isPreloaded: boolean = !!this.props.collections.orderedData.length;
componentDidMount() {
const { collections } = this.props;
function Collections({ onCreateCollection }: Props) {
const { policies, documents, collections } = useStores();
const isPreloaded: boolean = !!collections.orderedData.length;
const { t } = useTranslation();
const orderedCollections = collections.orderedData;
const [isDraggingAnyCollection, setIsDraggingAnyCollection] = React.useState(
false
);
React.useEffect(() => {
if (!collections.isLoaded) {
collections.fetchPage({ limit: 100 });
}
}
});
@keydown("n")
goToNewDocument() {
const { activeCollectionId } = this.props.ui;
if (!activeCollectionId) return;
const [{ isCollectionDropping }, dropToReorderCollection] = useDrop({
accept: "collection",
drop: async (item, monitor) => {
collections.move(
item.id,
fractionalIndex(null, orderedCollections[0].index)
);
},
canDrop: (item, monitor) => {
return item.id !== orderedCollections[0].id;
},
collect: (monitor) => ({
isCollectionDropping: monitor.isOver(),
}),
});
const can = this.props.policies.abilities(activeCollectionId);
if (!can.update) return;
this.props.history.push(newDocumentUrl(activeCollectionId));
}
render() {
const { collections, ui, policies, documents, t } = this.props;
const content = (
<>
{collections.orderedData.map((collection) => (
<CollectionLink
key={collection.id}
collection={collection}
activeDocument={documents.active}
prefetchDocument={documents.prefetchDocument}
canUpdate={policies.abilities(collection.id).update}
ui={ui}
/>
))}
<SidebarLink
to="/collections"
onClick={this.props.onCreateCollection}
icon={<PlusIcon color="currentColor" />}
label={`${t("New collection")}`}
exact
const content = (
<>
<DropCursor
isActiveDrop={isCollectionDropping}
innerRef={dropToReorderCollection}
from="collections"
/>
{orderedCollections.map((collection, index) => (
<CollectionLink
key={collection.id}
collection={collection}
activeDocument={documents.active}
prefetchDocument={documents.prefetchDocument}
canUpdate={policies.abilities(collection.id).update}
isDraggingAnyCollection={isDraggingAnyCollection}
onChangeDragging={setIsDraggingAnyCollection}
belowCollection={orderedCollections[index + 1]}
/>
</>
);
))}
<SidebarLink
to="/collections"
onClick={onCreateCollection}
icon={<PlusIcon color="currentColor" />}
label={`${t("New collection")}`}
exact
/>
</>
);
if (!collections.isLoaded) {
return (
<Flex column>
<Header>{t("Collections")}</Header>
{collections.isLoaded ? (
this.isPreloaded ? (
content
) : (
<Fade>{content}</Fade>
)
) : (
<CollectionsLoading />
)}
<CollectionsLoading />
</Flex>
);
}
return (
<Flex column>
<Header>{t("Collections")}</Header>
{isPreloaded ? content : <Fade>{content}</Fade>}
</Flex>
);
}
export default withTranslation()<Collections>(
inject("collections", "ui", "documents", "policies")(withRouter(Collections))
);
export default observer(Collections);
@@ -7,12 +7,14 @@ function DropCursor({
isActiveDrop,
innerRef,
theme,
from,
}: {
isActiveDrop: boolean,
innerRef: React.Ref<any>,
theme: Theme,
from: string,
}) {
return <Cursor isOver={isActiveDrop} ref={innerRef} />;
return <Cursor isOver={isActiveDrop} ref={innerRef} from={from} />;
}
// transparent hover zone with a thin visible band vertically centered
@@ -25,7 +27,7 @@ const Cursor = styled("div")`
width: 100%;
height: 14px;
bottom: -7px;
${(props) => (props.from === "collections" ? "top: 15px;" : "bottom: -7px;")}
background: transparent;
::after {
+7
View File
@@ -272,6 +272,13 @@ class SocketProvider extends React.Component<Props> {
}
});
this.socket.on("collections.update_index", (event) => {
const collection = collections.get(event.collectionId);
if (collection) {
collection.updateIndex(event.index);
}
});
// received a message from the API server that we should request
// to join a specific room. Forward that to the ws server.
this.socket.on("join", (event) => {
+9 -2
View File
@@ -17,9 +17,10 @@ export default class Collection extends BaseModel {
color: string;
private: boolean;
sharing: boolean;
index: string;
documents: NavigationNode[];
createdAt: ?string;
updatedAt: ?string;
createdAt: string;
updatedAt: string;
deletedAt: ?string;
sort: { field: string, direction: "asc" | "desc" };
url: string;
@@ -67,6 +68,11 @@ export default class Collection extends BaseModel {
travelDocuments(this.documents);
}
@action
updateIndex(index: string) {
this.index = index;
}
getDocumentChildren(documentId: string): NavigationNode[] {
let result = [];
const traveler = (nodes) => {
@@ -117,6 +123,7 @@ export default class Collection extends BaseModel {
"icon",
"private",
"sort",
"index",
]);
};
+27 -5
View File
@@ -1,7 +1,7 @@
// @flow
import { concat, filter, last } from "lodash";
import invariant from "invariant";
import { concat, last } from "lodash";
import { computed, action } from "mobx";
import naturalSort from "shared/utils/naturalSort";
import Collection from "models/Collection";
import BaseStore from "./BaseStore";
import RootStore from "./RootStore";
@@ -33,10 +33,18 @@ export default class CollectionsStore extends BaseStore<Collection> {
@computed
get orderedData(): Collection[] {
return filter(
naturalSort(Array.from(this.data.values()), "name"),
(d) => !d.deletedAt
let collections = Array.from(this.data.values());
collections = collections.filter((collection) =>
collection.deletedAt ? false : true
);
return collections.sort((a, b) => {
if (a.index === b.index) {
return a.updatedAt > b.updatedAt ? -1 : 1;
}
return a.index < b.index ? -1 : 1;
});
}
@computed
@@ -95,6 +103,20 @@ export default class CollectionsStore extends BaseStore<Collection> {
});
};
@action
move = async (collectionId: string, index: string) => {
const res = await client.post("/collections.move", {
id: collectionId,
index,
});
invariant(res && res.success, "Collection could not be moved");
const collection = this.get(collectionId);
if (collection) {
collection.updateIndex(index);
}
};
async update(params: Object): Promise<Collection> {
const result = await super.update(params);
+1
View File
@@ -93,6 +93,7 @@
"file-loader": "^1.1.6",
"flow-typed": "^2.6.2",
"focus-visible": "^5.1.0",
"fractional-index": "^1.0.0",
"fs-extra": "^4.0.2",
"google-auth-library": "^5.5.1",
"http-errors": "1.4.0",
@@ -97,6 +97,15 @@ Object {
}
`;
exports[`#collections.move should require authentication 1`] = `
Object {
"error": "authentication_required",
"message": "Authentication required",
"ok": false,
"status": 401,
}
`;
exports[`#collections.remove_group should require group in team 1`] = `
Object {
"error": "authorization_error",
+85 -2
View File
@@ -1,5 +1,6 @@
// @flow
import fs from "fs";
import fractionalIndex from "fractional-index";
import Router from "koa-router";
import { ValidationError } from "../errors";
import { exportCollections } from "../exporter";
@@ -23,7 +24,10 @@ import {
presentGroup,
presentCollectionGroupMembership,
} from "../presenters";
import { Op } from "../sequelize";
import { Op, sequelize } from "../sequelize";
import collectionIndexing from "../utils/collectionIndexing";
import removeIndexCollisions from "../utils/removeIndexCollisions";
import { archiveCollection, archiveCollections } from "../utils/zip";
import pagination from "./middlewares/pagination";
@@ -39,6 +43,8 @@ router.post("collections.create", auth(), async (ctx) => {
icon,
sort = Collection.DEFAULT_SORT,
} = ctx.body;
let { index } = ctx.body;
const isPrivate = ctx.body.private;
ctx.assertPresent(name, "name is required");
@@ -49,6 +55,33 @@ router.post("collections.create", auth(), async (ctx) => {
const user = ctx.state.user;
authorize(user, "create", Collection);
const collections = await Collection.findAll({
where: { teamId: user.teamId, deletedAt: null },
attributes: ["id", "index", "updatedAt"],
limit: 1,
order: [
// using LC_COLLATE:"C" because we need byte order to drive the sorting
sequelize.literal('"collection"."index" collate "C"'),
["updatedAt", "DESC"],
],
});
if (index) {
const allowedASCII = new RegExp(/^[\x21-\x7E]+$/);
if (!allowedASCII.test(index)) {
throw new ValidationError(
"Index characters must be between x21 to x7E ASCII"
);
}
} else {
index = fractionalIndex(null, collections[0].index);
}
// before creating a collection we check if a collection with same index exists
const collectionWithSameIndex = await Collection.findOne({
where: { index, teamId: user.teamId, deletedAt: null },
});
let collection = await Collection.create({
name,
description,
@@ -59,14 +92,21 @@ router.post("collections.create", auth(), async (ctx) => {
private: isPrivate,
sharing,
sort,
index,
});
let collectionIdsWithIndex;
if (collectionWithSameIndex) {
collectionIdsWithIndex = await removeIndexCollisions(user.teamId);
}
await Event.create({
name: "collections.create",
collectionId: collection.id,
teamId: collection.teamId,
actorId: user.id,
data: { name },
data: { name, collectionIdsWithIndex },
ip: ctx.request.ip,
});
@@ -571,6 +611,17 @@ router.post("collections.list", auth(), pagination(), async (ctx) => {
limit: ctx.state.pagination.limit,
});
const nullIndexCollection = collections.findIndex(
(collection) => collection.index === null
);
if (nullIndexCollection !== -1) {
const indexedCollections = await collectionIndexing(ctx.state.user.teamId);
collections.forEach((collection) => {
collection.index = indexedCollections[collection.id];
});
}
ctx.body = {
pagination: ctx.state.pagination,
data: collections.map(presentCollection),
@@ -608,4 +659,36 @@ router.post("collections.delete", auth(), async (ctx) => {
};
});
router.post("collections.move", auth(), async (ctx) => {
const { index, id } = ctx.body;
ctx.assertPresent(index, "index is required");
ctx.assertUuid(id, "id must be a uuid");
const user = ctx.state.user;
const collection = await Collection.findByPk(id);
authorize(user, "move", collection);
await collection.update({ index });
let collectionIdsWithIndex = await removeIndexCollisions(user.teamId);
if (!collectionIdsWithIndex) {
collectionIdsWithIndex = [[id, index]];
} else {
collectionIdsWithIndex.push([id, index]);
}
await Event.create({
name: "collections.move",
collectionId: collection.id,
teamId: collection.teamId,
actorId: user.id,
data: { collectionIdsWithIndex: collectionIdsWithIndex },
ip: ctx.request.ip,
});
ctx.body = {
success: true,
};
});
export default router;
+70
View File
@@ -130,6 +130,76 @@ describe("#collections.import", () => {
});
});
describe("#collections.move", () => {
it("should require authentication", async () => {
const res = await server.post("/api/collections.move");
const body = await res.json();
expect(res.status).toEqual(401);
expect(body).toMatchSnapshot();
});
it("should require authorization", async () => {
const user = await buildUser();
const { collection } = await seed();
const res = await server.post("/api/collections.move", {
body: { token: user.getJwtToken(), id: collection.id, index: "P" },
});
expect(res.status).toEqual(403);
});
it("should return success", async () => {
const { admin, collection } = await seed();
const res = await server.post("/api/collections.move", {
body: { token: admin.getJwtToken(), id: collection.id, index: "P" },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.success).toBe(true);
});
it("if index collision occurs, should updated index of other collections", async () => {
const { user, admin, collection } = await seed();
const createdCollectionResponse = await server.post(
"/api/collections.create",
{
body: {
token: user.getJwtToken(),
name: "Test",
sharing: false,
index: "Q",
},
}
);
const createdCollection = await createdCollectionResponse.json();
const movedCollectionRes = await server.post("/api/collections.move", {
body: { token: admin.getJwtToken(), id: collection.id, index: "Q" },
});
const movedCollection = await movedCollectionRes.json();
expect(movedCollectionRes.status).toEqual(200);
expect(movedCollection.success).toBe(true);
const updatedCreatedCollectionResponse = await server.post(
"/api/collections.info",
{
body: { token: admin.getJwtToken(), id: createdCollection.data.id },
}
);
const updateCreatedCollection = await updatedCreatedCollectionResponse.json();
expect(updateCreatedCollection.data.index).not.toEqual("Q");
expect(updateCreatedCollection.data.index).toEqual("h");
expect(updateCreatedCollection.data.index > "Q").toBeTruthy();
});
});
describe("#collections.export", () => {
it("should now allow export of private collection not a member", async () => {
const { user } = await seed();
+9
View File
@@ -118,6 +118,7 @@ export type CollectionEvent =
collectionId: string,
teamId: string,
actorId: string,
data: { name: string, collectionIdsWithIndex?: [[string, string]] },
ip: string,
}
| {
@@ -135,6 +136,14 @@ export type CollectionEvent =
actorId: string,
data: { name: string, groupId: string },
ip: string,
}
| {
name: "collections.move",
collectionId: string,
teamId: string,
actorId: string,
data: { collectionIdsWithIndex: [[string, string]] },
ip: string,
};
export type GroupEvent =
@@ -0,0 +1,14 @@
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("collections", "index", {
type: Sequelize.TEXT,
defaultValue: null,
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("collections", "index");
},
};
+4
View File
@@ -21,6 +21,10 @@ const Collection = sequelize.define(
description: DataTypes.STRING,
icon: DataTypes.STRING,
color: DataTypes.STRING,
index: {
type: DataTypes.STRING,
defaultValue: null,
},
private: DataTypes.BOOLEAN,
maintainerApprovalRequired: DataTypes.BOOLEAN,
documentStructure: DataTypes.JSONB,
+2
View File
@@ -57,6 +57,7 @@ Event.add = (event) => {
Event.ACTIVITY_EVENTS = [
"collections.create",
"collections.delete",
"collections.move",
"documents.publish",
"documents.archive",
"documents.unarchive",
@@ -73,6 +74,7 @@ Event.AUDIT_EVENTS = [
"api_keys.delete",
"collections.create",
"collections.update",
"collections.move",
"collections.add_user",
"collections.remove_user",
"collections.add_group",
+7
View File
@@ -14,6 +14,13 @@ allow(User, "import", Collection, (actor) => {
throw new AdminRequiredError();
});
allow(User, "move", Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
if (collection.deletedAt) return false;
if (user.isAdmin) return true;
throw new AdminRequiredError();
});
allow(User, ["read", "export"], Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) return false;
+1
View File
@@ -28,6 +28,7 @@ export default function present(collection: Collection) {
description: collection.description,
sort: collection.sort,
icon: collection.icon,
index: collection.index,
color: collection.color || "#4E5C6E",
private: collection.private,
sharing: collection.sharing,
+26
View File
@@ -170,6 +170,18 @@ export default class Websockets {
},
],
});
if (event.data.collectionIdsWithIndex) {
event.data.collectionIdsWithIndex.forEach((collectionIdWithIndex) => {
socketio
.to(`collection-${collectionIdWithIndex[0]}`)
.emit("collections.update_index", {
collectionId: collectionIdWithIndex[0],
index: collectionIdWithIndex[1],
});
});
}
return socketio
.to(
collection.private
@@ -197,6 +209,20 @@ export default class Websockets {
],
});
}
case "collections.move": {
if (event.data.collectionIdsWithIndex) {
event.data.collectionIdsWithIndex.forEach((collectionIdWithIndex) => {
socketio
.to(`collection-${collectionIdWithIndex[0]}`)
.emit("collections.update_index", {
collectionId: collectionIdWithIndex[0],
index: collectionIdWithIndex[1],
});
});
}
return;
}
case "collections.add_user": {
// the user being added isn't yet in the websocket channel for the collection
// so they need to be notified separately
+39
View File
@@ -0,0 +1,39 @@
// @flow
import fractionalIndex from "fractional-index";
import naturalSort from "../../shared/utils/naturalSort";
import { Collection } from "../models";
export default async function collectionIndexing(teamId: string) {
const collections = await Collection.findAll({
where: { teamId, deletedAt: null }, //no point in maintaining index of deleted collections.
attributes: ["id", "index", "name"],
});
let sortableCollections = collections.map((collection) => {
return [collection, collection.index];
});
sortableCollections = naturalSort(
sortableCollections,
(collection) => collection[0].name
);
//for each collection with null index, use previous collection index to create new index
let previousCollectionIndex = null;
for (const collection of sortableCollections) {
if (collection[1] === null) {
const index = fractionalIndex(previousCollectionIndex, collection[1]);
collection[0].index = index;
await collection[0].save();
}
previousCollectionIndex = collection[0].index;
}
const indexedCollections = {};
sortableCollections.forEach((collection) => {
indexedCollections[collection[0].id] = collection[0].index;
});
return indexedCollections;
}
+64
View File
@@ -0,0 +1,64 @@
// @flow
import fractionalIndex from "fractional-index";
import { Collection } from "../models";
import { sequelize } from "../sequelize";
/**
*
* @param teamId The team id whose collections has to be fetched
* @returns An array or undefined. If array, each array element is an array of collided collection id and its new index [id,newIndex]
*/
export default async function removeIndexCollisions(teamId: string) {
let collections = await Collection.findAll({
where: { teamId, deletedAt: null },
attributes: ["id", "index", "updatedAt"],
order: [
sequelize.literal('"collection"."index" collate "C"'),
["updatedAt", "DESC"],
],
});
collections = collections.map((collection) => {
return [collection, collection.index];
});
// a set to store the index value of collections.
const indexSet = new Set();
let collision = false;
// make the index null, if there is index collision
collections = collections.map((collection) => {
if (indexSet.has(collection[1])) {
collision = true;
collection[1] = null;
return collection;
}
indexSet.add(collection[1]);
return collection;
});
if (!collision) {
return;
}
let indexArray = Array.from(indexSet);
indexArray.sort();
const collectionIdsWithIndex = [];
for (const [i, collection] of collections.entries()) {
if (collection[1] === null) {
const previousCollectionIndex = i - 1 < 0 ? null : indexArray[i - 1];
const nextCollectionIndex =
i === indexArray.length ? null : indexArray[i];
const newIndex = fractionalIndex(
previousCollectionIndex,
nextCollectionIndex
);
indexArray.splice(i, 0, newIndex);
await collection[0].update({ index: newIndex });
collectionIdsWithIndex.push([collection[0].id, newIndex]);
}
}
return collectionIdsWithIndex;
}
+5
View File
@@ -5756,6 +5756,11 @@ formidable@^1.1.1:
resolved "https://registry.yarnpkg.com/formidable/-/formidable-1.2.2.tgz#bf69aea2972982675f00865342b982986f6b8dd9"
integrity sha512-V8gLm+41I/8kguQ4/o1D3RIHRmhYFG4pnNyonvua+40rqcEmT4+V71yaZ3B457xbbgCsCfjSPi65u/W6vK1U5Q==
fractional-index@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fractional-index/-/fractional-index-1.0.0.tgz#98d528e26176a70930ef397e3f912de259b6cda9"
integrity sha512-AsCqhK0KuX37mZC8BtP9jSTfor6GxIivLYhbYJS1e6gW//kph+d9oF+BM/Y6NMcCHfGCxhuj+ueyXLLIc+ri1A==
fragment-cache@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19"