This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
outline/app/models/Document.js

347 lines
7.6 KiB
JavaScript
Raw Normal View History

// @flow
import { addDays, differenceInDays } from "date-fns";
import invariant from "invariant";
import { floor } from "lodash";
import { action, computed, observable, set } from "mobx";
import parseTitle from "shared/utils/parseTitle";
import unescape from "shared/utils/unescape";
import DocumentsStore from "stores/DocumentsStore";
import BaseModel from "models/BaseModel";
import User from "models/User";
import View from "./View";
2021-09-11 05:46:57 +00:00
type SaveOptions = {|
publish?: boolean,
done?: boolean,
autosave?: boolean,
lastRevision?: number,
2021-09-11 05:46:57 +00:00
|};
2018-05-07 05:13:52 +00:00
export default class Document extends BaseModel {
@observable isSaving: boolean = false;
@observable embedsDisabled: boolean = false;
2020-09-21 06:37:09 +00:00
@observable lastViewedAt: ?string;
store: DocumentsStore;
collaboratorIds: string[];
2017-11-20 05:32:18 +00:00
collectionId: string;
createdAt: string;
createdBy: User;
updatedAt: string;
updatedBy: User;
id: string;
team: string;
pinned: boolean;
text: string;
title: string;
emoji: string;
template: boolean;
templateId: ?string;
parentDocumentId: ?string;
publishedAt: ?string;
archivedAt: string;
deletedAt: ?string;
url: string;
urlId: string;
tasks: { completed: number, total: number };
revision: number;
constructor(fields: Object, store: DocumentsStore) {
super(fields, store);
if (this.isNewDocument && this.isFromTemplate) {
this.title = "";
}
}
get emoji() {
const { emoji } = parseTitle(this.title);
return emoji;
}
/**
* Best-guess the text direction of the document based on the language the
* title is written in. Note: wrapping as a computed getter means that it will
* only be called directly when the title changes.
*/
@computed
get dir(): "rtl" | "ltr" {
const element = document.createElement("p");
element.innerHTML = this.title;
element.style.visibility = "hidden";
element.dir = "auto";
// element must appear in body for direction to be computed
document.body?.appendChild(element);
const direction = window.getComputedStyle(element).direction;
document.body?.removeChild(element);
return direction;
}
@computed
get noun(): string {
return this.template ? "template" : "document";
}
@computed
get isOnlyTitle(): boolean {
return !this.text.trim();
}
2017-11-10 22:14:30 +00:00
@computed
get modifiedSinceViewed(): boolean {
return !!this.lastViewedAt && this.lastViewedAt < this.updatedAt;
}
@computed
get isNew(): boolean {
return (
!this.lastViewedAt &&
differenceInDays(new Date(), new Date(this.createdAt)) < 14
);
}
2017-11-10 22:14:30 +00:00
@computed
get isStarred(): boolean {
return !!this.store.starredIds.get(this.id);
}
@computed
get isArchived(): boolean {
return !!this.archivedAt;
}
@computed
get isDeleted(): boolean {
return !!this.deletedAt;
}
@computed
get isTemplate(): boolean {
return !!this.template;
}
2018-08-07 06:22:20 +00:00
@computed
get isDraft(): boolean {
return !this.publishedAt;
}
@computed
get titleWithDefault(): string {
return this.title || "Untitled";
}
@computed
get permanentlyDeletedAt(): ?string {
if (!this.deletedAt) {
2019-12-24 02:12:16 +00:00
return undefined;
}
return addDays(new Date(this.deletedAt), 30).toString();
}
@computed
get isNewDocument(): boolean {
return this.createdAt === this.updatedAt;
}
@computed
get isFromTemplate(): boolean {
return !!this.templateId;
}
@computed
get isTasks(): boolean {
return !!this.tasks.total;
}
@computed
get tasksPercentage(): number {
if (!this.isTasks) {
return 0;
}
return floor((this.tasks.completed / this.tasks.total) * 100);
}
2018-05-17 06:07:33 +00:00
@action
share = async () => {
return this.store.rootStore.shares.create({ documentId: this.id });
2018-05-17 06:07:33 +00:00
};
@action
updateFromJson = (data: Object) => {
set(this, data);
};
archive = () => {
return this.store.archive(this);
};
restore = (options: { revisionId?: string, collectionId?: string }) => {
return this.store.restore(this, options);
};
unpublish = () => {
return this.store.unpublish(this);
};
@action
enableEmbeds = () => {
this.embedsDisabled = false;
};
@action
disableEmbeds = () => {
this.embedsDisabled = true;
};
@action
pin = async () => {
this.pinned = true;
try {
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
const res = await this.store.pin(this);
invariant(res && res.data, "Data should be available");
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
this.updateFromJson(res.data);
} catch (err) {
this.pinned = false;
throw err;
}
};
@action
unpin = async () => {
this.pinned = false;
try {
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
const res = await this.store.unpin(this);
invariant(res && res.data, "Data should be available");
feat: Memberships (#1032) * WIP * feat: Add collection.memberships endpoint * feat: Add ability to filter collection.memberships with query * WIP * Merge stashed work * feat: Add ability to filter memberships by permission * continued refactoring * paginated list component * Collection member management * fix: Incorrect policy data sent down after collection.update * Reduce duplication, add empty state * cleanup * fix: Modal close should be a real button * fix: Allow opening edit from modal * fix: remove unused methods * test: fix * Passing test suite * Refactor * fix: Flow UI errors * test: Add collections.update tests * lint * test: moar tests * fix: Missing scopes, more missing tests * fix: Handle collection privacy change over socket * fix: More membership scopes * fix: view endpoint permissions * fix: respond to privacy change on socket event * policy driven menus * fix: share endpoint policies * chore: Use policies to drive documents UI * alignment * fix: Header height * fix: Correct behavior when collection becomes private * fix: Header height for read-only collection * send id's over socket instead of serialized objects * fix: Remote policy change * fix: reduce collection fetching * More websocket efficiencies * fix: Document collection pinning * fix: Restored ability to edit drafts fix: Removed ability to star drafts * fix: Require write permissions to pin doc to collection * fix: Header title overlaying document actions at small screen sizes * fix: Jank on load caused by previous commit * fix: Double collection fetch post-publish * fix: Hide publish button if draft is in no longer accessible collection * fix: Always allow deleting drafts fix: Improved handling of deleted documents * feat: Show collections in drafts view feat: Show more obvious 'draft' badge on documents * fix: incorrect policies after publish to private collection * fix: Duplicating a draft publishes it
2019-10-06 01:42:03 +00:00
this.updateFromJson(res.data);
} catch (err) {
this.pinned = true;
throw err;
}
};
2017-11-10 22:14:30 +00:00
@action
star = () => {
return this.store.star(this);
};
2017-11-10 22:14:30 +00:00
@action
unstar = async () => {
return this.store.unstar(this);
};
2017-11-10 22:14:30 +00:00
@action
view = () => {
// we don't record views for documents in the trash
if (this.isDeleted || !this.publishedAt) {
return;
}
return this.store.rootStore.views.create({ documentId: this.id });
};
@action
updateLastViewed = (view: View) => {
this.lastViewedAt = view.lastViewedAt;
};
2017-11-10 22:14:30 +00:00
@action
templatize = async () => {
return this.store.templatize(this.id);
};
@action
2021-09-11 05:46:57 +00:00
update = async (options: {| ...SaveOptions, title: string |}) => {
if (this.isSaving) return this;
this.isSaving = true;
try {
if (options.lastRevision) {
return await this.store.update({
id: this.id,
title: this.title,
lastRevision: options.lastRevision,
...options,
});
}
throw new Error("Attempting to update without a lastRevision");
} finally {
this.isSaving = false;
}
};
2017-11-10 22:14:30 +00:00
@action
2021-09-11 05:46:57 +00:00
save = async (options: ?SaveOptions) => {
if (this.isSaving) return this;
2018-07-04 20:00:53 +00:00
const isCreating = !this.id;
this.isSaving = true;
try {
2018-07-04 20:00:53 +00:00
if (isCreating) {
return await this.store.create({
parentDocumentId: this.parentDocumentId,
collectionId: this.collectionId,
title: this.title,
text: this.text,
2021-09-11 05:46:57 +00:00
publish: options?.publish,
done: options?.done,
autosave: options?.autosave,
2018-07-04 20:00:53 +00:00
});
}
2021-09-11 05:46:57 +00:00
if (options?.lastRevision) {
2020-06-03 06:17:54 +00:00
return await this.store.update({
id: this.id,
title: this.title,
text: this.text,
templateId: this.templateId,
2021-09-11 05:46:57 +00:00
lastRevision: options?.lastRevision,
publish: options?.publish,
done: options?.done,
autosave: options?.autosave,
2020-06-03 06:17:54 +00:00
});
}
throw new Error("Attempting to update without a lastRevision");
} finally {
this.isSaving = false;
}
2017-09-04 21:48:56 +00:00
};
move = (collectionId: string, parentDocumentId: ?string) => {
return this.store.move(this.id, collectionId, parentDocumentId);
};
duplicate = () => {
return this.store.duplicate(this);
};
getSummary = (paragraphs: number = 4) => {
const result = this.text.trim().split("\n").slice(0, paragraphs).join("\n");
return result;
};
download = async () => {
// Ensure the document is upto date with latest server contents
await this.fetch();
const body = unescape(this.text);
const blob = new Blob([`# ${this.title}\n\n${body}`], {
type: "text/markdown",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
// Firefox support requires the anchor tag be in the DOM to trigger the dl
if (document.body) document.body.appendChild(a);
a.href = url;
a.download = `${this.titleWithDefault}.md`;
a.click();
};
}