|
| 1 | +import EventEmitter from "wolfy87-eventemitter"; |
| 2 | +import postRobot from "post-robot"; |
| 3 | +import { IContentTypeSidebarInitData } from "./types"; |
| 4 | +import { ContentType } from "./types/stack.types"; |
| 5 | +import { GenericObjectType } from "./types/common.types"; |
| 6 | + |
| 7 | +/** Class representing a Content type Sidebar UI Location from Contentstack UI. */ |
| 8 | + |
| 9 | +class ContentTypeSidebarWidget { |
| 10 | + /** |
| 11 | + * @hideconstructor |
| 12 | + */ |
| 13 | + |
| 14 | + currentContentType: ContentType; |
| 15 | + _emitter: EventEmitter; |
| 16 | + _connection: typeof postRobot; |
| 17 | + _changedData?: GenericObjectType; |
| 18 | + |
| 19 | + constructor( |
| 20 | + initializationData: IContentTypeSidebarInitData, |
| 21 | + connection: typeof postRobot, |
| 22 | + emitter: EventEmitter |
| 23 | + ) { |
| 24 | + this.currentContentType = initializationData.currentContentType; |
| 25 | + |
| 26 | + this._emitter = emitter; |
| 27 | + |
| 28 | + this._connection = connection; |
| 29 | + |
| 30 | + const thisContentType = this; |
| 31 | + |
| 32 | + this._emitter.on("contentTypeSave", (event: { data: ContentType }) => { |
| 33 | + thisContentType.currentContentType = event.data; |
| 34 | + }); |
| 35 | + |
| 36 | + this.getData = this.getData.bind(this); |
| 37 | + this.onSave = this.onSave.bind(this); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Get the current content type data. |
| 42 | + * @returns {ContentTypeData} The current content type data. |
| 43 | + */ |
| 44 | + getData(): ContentType { |
| 45 | + return this.currentContentType; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Executes the provided callback function every time a content type is saved. |
| 50 | + * @param {function} callback - The function to be called when a content type is saved. |
| 51 | + * @param {ContentType} arg0 - The content type data passed as an argument to the callback function when a content type is saved. |
| 52 | + */ |
| 53 | + onSave(callback: (arg0: ContentType) => void) { |
| 54 | + const contentTypeObj = this; |
| 55 | + if (callback && typeof callback === "function") { |
| 56 | + contentTypeObj._emitter.on( |
| 57 | + "contentTypeSave", |
| 58 | + (event: { data: ContentType }) => { |
| 59 | + callback(event.data); |
| 60 | + } |
| 61 | + ); |
| 62 | + this._emitter.emitEvent("_eventRegistration", [ |
| 63 | + { name: "contentTypeSave" }, |
| 64 | + ]); |
| 65 | + } else { |
| 66 | + throw Error("Callback must be a function"); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +export default ContentTypeSidebarWidget; |
0 commit comments