feat: Show drafts in sidebar when viewing (#2820)

This commit is contained in:
Tom Moor
2021-12-11 09:34:36 -08:00
committed by GitHub
parent e5b4186faa
commit 7aa4709e69
39 changed files with 445 additions and 246 deletions

View File

@@ -1,4 +1,6 @@
import { set, observable } from "mobx";
import { pick } from "lodash";
import { set, computed, observable } from "mobx";
import { getFieldsForModel } from "./decorators/Field";
export default class BaseModel {
@observable
@@ -10,7 +12,7 @@ export default class BaseModel {
store: any;
constructor(fields: Record<string, any>, store: any) {
set(this, fields);
this.updateFromJson(fields);
this.store = store;
}
@@ -19,16 +21,28 @@ export default class BaseModel {
try {
// ensure that the id is passed if the document has one
if (params) params = { ...params, id: this.id };
if (params) {
params = { ...params, id: this.id };
}
const model = await this.store.save(params || this.toJS());
// if saving is successful set the new values on the model itself
set(this, { ...params, ...model });
this.persistedAttributes = this.toJS();
return model;
} finally {
this.isSaving = false;
}
};
updateFromJson = (data: any) => {
set(this, data);
this.persistedAttributes = this.toJS();
};
fetch = (options?: any) => {
return this.store.fetch(this.id, options);
};
@@ -49,7 +63,43 @@ export default class BaseModel {
}
};
/**
* Returns a plain object representation of the model
*
* @returns {Record<string, any>}
*/
toJS = (): Record<string, any> => {
return { ...this };
const fields = getFieldsForModel(this);
return pick(this, fields) || [];
};
/**
* Returns a boolean indicating if the model has changed since it was last
* persisted to the server
*
* @returns boolean true if unsaved
*/
isDirty(): boolean {
const attributes = this.toJS();
if (Object.keys(attributes).length === 0) {
console.warn("Checking dirty on model with no @Field decorators");
}
return (
JSON.stringify(this.persistedAttributes) !== JSON.stringify(attributes)
);
}
/**
* Returns a boolean indicating whether the model has been persisted to db
*
* @returns boolean true if the model has never been persisted
*/
@computed
get isNew(): boolean {
return !this.id;
}
protected persistedAttributes: Partial<BaseModel> = {};
}