ardas / stripo-plugin

stripo-plugin
19 stars 32 forks source link

TypeScript type definitions? #19

Open ghost opened 1 year ago

ghost commented 1 year ago

Hello, you have quite a few options to initialize Stripo.

Do you have any typescript definitions for this?

ghost commented 1 year ago

I created some types for anyone else who might be looking for them.

The definitions include Stripo, StripoApi, StripoInitOptions and other related object interfaces.

These are fairly complete and they include even the undocumented StripoApi members.

Expand this section to see the TypeScript definitions. ```ts declare global { interface Window { Stripo: Stripo; StripoApi: StripoApi; } } interface Stripo { init(options: StripoInitOptions, beforeInitCallback?: () => void): void; } interface StripoApi { /** * This parameter helps to identify whether all changes are saved or not. If * something was not saved it returns `false`, if everything saved - `true`. * Can be applied only if you don’t use Autosave option. */ allDataSaved(): void; /** Undocumented StripoApi function. */ applyDefaultStyles(): void; /** * This method returns compiled and compressed HTML code that is ready to be * sent out to clients. * * @example * compileEmail(function(error, html, ampHtml, ampErrors) {...}, false) * * @param callback If an error occurs, the first parameter will contain the * error description. In case of success, the first parameter will be null * and the second parameter will contain HTML code. * * In case your email template contains AMP elements or components, the third * parameter will contain the HTML code of the AMP HTML Mime type. In case * AMP HTML is invalid, the fourth parameter will contain the error * descriptions (array of strings). * @param minimize If true — the HTML code will be in a format of a single * line without line breaks. */ compileEmail( callback: ( error: string, html: string, ampHtml: string, ampErrors: string, ) => void, minimize?: boolean, ): void; /** Undocumented StripoApi function. */ compileHistoryEmail(e: unknown, t: unknown, n: unknown, r: unknown): void; /** Undocumented StripoApi function. */ createVersionHistoryPoint(): void; /** Undocumented StripoApi function. */ createVersionHistoryPointAsync(e: unknown): Promise; /** Undocumented StripoApi function. */ flushChanges(): void; /** Undocumented StripoApi function. */ getEmail(): void; /** * This method returns the Gmail Promo Annotations’ microdata inserted into * the HTML code of the email template in the editor. * * In case the microdata code is not available there, the `null` value is * returned. * * If any of the parameters are disabled or empty, then the empty data is * returned (for example, `discountCode: ''`). * * For more information on these parameters, please refer to this page * https://stripo.email/gmail-promo/ (go to the “Generate my code” button and * check the “Microdata Format” tab) or on our blog * https://stripo.email/blog/gmail-new-promotions-tab-guide/ */ getGoogleAnnotations(): Record< | "logo" | "description" | "discountCode" | "availabilityStarts" | "availabilityEnds" | "timeZonesId" | "image", string > | null; /** This method returns an email’s hidden preheader. */ getHiddenPreHeader(): string; /** Undocumented StripoApi function. */ getHistoryTemplate(): void; /** Undocumented StripoApi function. */ getLastChangeInfo(): unknown; /** * This method returns the HTML and CSS codes with the Plugin internal extra * styles and editor markup. You should **call the getTemplate function to * take out modified HTML and CSS from the editor in order to save it in your * DB.** */ getTemplate( callback: ( html: string, css: string, width: number, height: number, ) => void, ): void; /** This method returns an email title/subject line. */ getTitle(): string; /** Undocumented StripoApi function. */ getUndoState(): void; /** Get a unique Stripo version identifier string. */ getVersion(): string; /** Internal use only. Call `window.Stripo.init()` instead. */ init(e: any): void; /** Undocumented StripoApi function. */ setName(...args: unknown[]): void; /** This method sets an email title/subject line. */ setTitle(value: string): void; /** * This method inserts/updates the Gmail Promo Annotations’ microdata in HTML * code of the opened email template in the editor. In case you want to * disable the whole feature please pass the `null` value. Otherwise, you will * pass all or any parameters with the data according to these requirements. * If you want to disable any of the parameters, simply pass the empty data * (for example, `discountCode: ''`). Please find more information on every * parameter https://stripo.email/gmail-promo/ (go to the “Generate my code” * button and check the “Microdata Format” tab) or on our blog * https://stripo.email/blog/gmail-new-promotions-tab-guide/ * * @param value */ setGoogleAnnotations( value: Record< | "logo" | "description" | "discountCode" | "availabilityStarts" | "availabilityEnds" | "timeZonesId" | "image", string > | null, ): void; /** This method sets an email’s hidden preheader. */ setHiddenPreHeader(value: string): void; /** * Use this function to display the AMP validation errors in the Stripo * preview mode if there are any in the email template. * * Please find the detailed description here * https://stripo.email/plugin-api/#how-to-call-the-showamperorsmodal-function * * @example * showAmpErrorsModal(ampErrors, userSuccessButtons, onCancel, onSubmit); * * @param ampErrors Represents the array of AMP errors received after calling * the compileEmail function. * @param userSuccessButtons Includes the array of external buttons that may * be displayed in the preview window in case if there are no validation * errors. * @param onCancel A callback function the editor may call if the user closes * the preview window. * @param onSubmit A callback function the editor may call when the user * clicks on the “Fix in Code Editor” button if there are any errors. Please * be advised that this button won’t be displayed if you did not pass the * `codeEditorButtonId` with the Plugin initialization. */ showAmpErrorsModal( ampErrors: unknown[], userSuccessButtons: unknown[], onCancel: () => void, onSubmit: () => void, ): void; /** Undocumented but obvious function. */ showChangeHistoryPanel(): void; /** Undocumented but obvious function. */ toggleChangeHistoryPanel(): void; /** Undocumented StripoApi function. */ updateAutosaveToken(e: unknown): void; /** Undocumented StripoApi function. */ updateImagesLibraryConfig(e): void; /** Undocumented StripoApi function. */ updateLinks(): void; /** Undocumented StripoApi function. */ updateHtmlAndCss(html: string, css: string): void; /** Undocumented StripoApi function. */ updateTimers(e: unknown): void; /** Undocumented StripoApi function. */ setHtmlReadyForSave(): void; /** * If the editor is closed by the user in your web application, we recommend * calling the `stop` function to stop all processes and improve the * performance of your application. */ stop(): void; } /** * Parameters for `window.Stripo.init()`. * * @see https://stripo.email/plugin-api/#initialization-configuration */ interface StripoInitOptions { /** * Request data used by Stripo to uniquely identify this email. The `emailId` * field is mandatory. Other "tenant/user/account" ids may also be included * which Stripo may use to build paths for image and document storage. * * These parameters will be passed to the backend with every request. Refer to * “the Plugin request parameters” section for details. */ apiRequestData: { emailId: string | number } & Record; /** CSS to edit. */ css: string; /** * Function that should contact your API server, which should then send a POST * to `https://plugins.stripo.email/api/v1/auth` and return the result. * * Please implement this function to get the auth token from the backend. See * the “Plugin authentication” section for details. */ getAuthToken(callback: (token: string) => void): void; /** HTML to edit. **MUST include HTML `` and `` tags.** */ html: string; /** HTML element id for Stripo to inject the preview panel. */ previewId: string; /** HTML element id for Stripo to inject the settings panel. */ settingsId: string; /** * This parameter helps to identify whether all changes are saved or not. If * something was not saved it returns False, if everything saved - True. */ allDataSaved?: () => boolean; /** * Specifies a list of domains allowed as sources for script tags in the * edited document. Example: https://domain1.com http://doman2.net Default: * `‘’` */ allowedScriptSourceDomains?: string; /** * This parameter is used to fetch a list of services (endpoints) used for * collecting data gathered by the Form block. See the “AMP-Form Services" * section for details. Default: `false` */ ampFormServices?: unknown; /** The Stripo Plugin main backend entrypoint. Default: `"/pluginapi/api/v1"` */ apiBaseUrl?: unknown; /** * Default search string for images from the “Image Bank” if it is enabled. * Default: Depends on current season: “spring” / “summer” / “autumn” / * “winter” */ bankImagesDefaultSearchString?: unknown; /** * User can move blocks inside the structure just by using a mouse. Catch * needed block content and move it in right place. Default: `{ * moveBlockAvailability: true }` */ blocks?: { moveBlockAvailability: boolean }; /** * Initial list of colors to be in the brand palette. These colors will be * unchanged during editor session. Example: `['#35882C', '#FFD351', * '#1924FF', '#B621EC', '#95C4EC','#812724', '#95C4EC']` */ brandColorPaletteColors?: unknown; /** Title of custom colors palette. Example: `'Brand Colors:'` */ brandColorPaletteLabel?: unknown; /** * This function depending on the result enable or disable 'save as module' * functionality for individual containers/structures/stripes. Default: * `canBeSavedToLibrary: function(moduleHtml) {return true}` */ canBeSavedToLibrary?: unknown; /** ID of the open/close code editor button. */ codeEditorButtonId?: string; /** * Set to True if you want to enable the Conditions tab. See the “Display * Conditions” section for details Default: `false` */ conditionsEnabled?: unknown; /** * List of colors to display in the color palette for the Text Editor panel * and the Settings panel for every basic block. See the “Custom Color * Palette” section for details. Default: See the “Custom Color Palette” * section for default values */ customColorPalette?: unknown; /** * Initial list of colors to be in the custom palette. These colors will be * updated after custom color selection by user. Example: `['#882724', * '#35882C', '#FFD351', '#1924FF', '#B621EC', '#95C4EC','#812724']` */ customColorPaletteColors?: unknown; /** * Callback that is called on custom color selection with new custom colors * palette. Example: function(colors) { console.log('Colors palette changed: * ' * * - Colors); } */ customColorPaletteColorsChanged?: unknown; /** Title of custom colors palette. Example: 'Last Used Colors:' */ customColorPaletteLabel?: unknown; /** * Set up your desired colors for the text available only in the side menu and * the CKEditor menu. See the “Custom Color Palette” section for details. */ customColorPaletteTextOnly?: unknown; /** * Predefined values for the menu items (number and titles) Default: * `"defaultMenuItems":[ { "name":"Item 1", "href":"https://google.com" }, { * "name":"Item 2", "href":"https://test.com" } ]` */ defaultMenuItems?: unknown; /** * The Stripo Plugin supports auto-save that makes calls to the server. In * order to be notified in JavaScript when the content is changed and saved, * you can rely on this parameter as described in the examples. Default: * `draft: { showAutoSaveLoader: function() {console.log('Auto save in * process')}, hideAutoSaveLoader: function(error) {console.log('Auto save * completed')} }` */ draft?: unknown; /** * List of fonts to be included in the Text Editor panel and the Settings * panel for basic blocks. See the “Сustom Font Sizes list” section for * details. Default: See the “Fonts Management” documentation for default * values */ editorFonts?: unknown; /** * List of font sizes to be included in the Text Editor panel and the Settings * panel for basic blocks. See the “Сustom Font Sizes list” section for * details. Default: See the “Сustom Font Sizes list” section for default * values */ editorFontSizes?: unknown; /** * BOOL Specifies if meta tag with Security Policy will be applied to the * edited document. Default: `false` */ enableXSSSecurity?: unknown; /** * This parameter is used to display your own component with an external data * list in a pop-up window. See the “Advanced parameters” section for details */ externalSmartElementsLibrary?: unknown; /** * List of selectors of elements, click on which does not start the * clickOutsidePreview event and as a result does not reset the block * selection in the preview area. */ ignoreClickOutsideSelectors?: string[]; /** * 2-letter language identifier. Available Languages: English: “en” Spanish: * “es” French: “fr” German: “de” Italian: “it” Portuguese: “pt” Slovenian: * “sl” Russian: “ru” Ukrainian: “uk” Dutch: “nl” Czech: “cs” Turkish: “tr” * Polish: “pl” Chinese Traditional: “zh” Default: `“en”` */ locale?: string; /** * It is possible to override any translation in the editor.A list of all * editor phrases can be found here: * https://plugins.stripo.email/static/latest/assets/i18n/en.json. In order to * override translations, you need to list the keys and new values for each * language in the value in the format: { "localePatch": { "key1": { "en": * "en_value", "ru": "ru_value" }, "key2": { "en": "en_value" } } } Example: { * "localePatch": { "settingsPanel.accordion.structures": { "en": "Available * Structures", "ru": "Доступные структуры" }, "settingsPanel.block.timer": { * "en": "Clock" } } } Default: `{}` */ localePatch?: unknown; /** * List of the merge tags to be included in the Text Editor panel. See the * “Merge Tags” section for details. Default: See the “Merge Tags” section for * default values */ mergeTags?: StripoMergeTags[]; /** * Set of methods that will be called when any message needs to be visible for * the user. See the “Plugin notifications” section for details. Default: `{ * info: message => console.log(message), error: message => * console.error(message), success: message => console.log(message), warn: * message => console.log(message), loader: message => console.log(message), * hide: message => console.log(message) }` */ notifications?: Record< "info" | "error" | "success" | "warn" | "loader" | "hide", (message: string) => void >; /** * If defined this function is called when there are unsaved changes in the * email. Default: `onDataChanged : function() {console.log('data changed')}` */ onDataChanged?: unknown; /** * This parameter helps to notify the external application when the plugin * initialization is completed. Default: `onTemplateLoaded: function() * {console.log('Loaded')}` */ onTemplateLoaded?: () => void; /** * This parameter helps to notify the external application when the plugin * code editor changes its state (opened/closed). Default: * `onToggleCodeEditor: function(codeEditorVisible) {}` */ onToggleCodeEditor?: unknown; /** ID of the redo button. */ redoButtonId?: string; /** * If true then block will be selected after d&d from the settings panel. * Default: `false` */ selectBlockAfterDropFromSettingsPanel?: unknown; /** * List of social networks to be included in the “Social Networks” block. See * the “Social Networks" section for details */ socialNetworks?: any[]; /** * List of the special links to be included in the Link selector component in * the editor. Default: See the “Special Links” section for default values */ specialLinks?: StripoSpecialLinks[]; /** * Passing this parameter with a "true" value will enable the "Outlook * Support" control for the "Button" block. Default: `false` */ supportOutlookButtonsByDefault?: unknown; /** ID of the undo button. */ undoButtonId?: string; /** * This value will be applied to the link if the “Unsubscribe” link type is * chosen. */ unSubscribeLink?: string; /** * A full name of the user that uses the editor. Will be displayed in the * Version History section of the editor. */ userFullName?: string; /** See the “Version History” section for details. */ versionHistory?: unknown; /** * This value will be applied to the link if the “View In Browser” link type * is chosen. */ viewInBrowserLink?: string; /** * Set to TRUE if you want to disable email modifications by a user. Default: * `false` */ viewOnly?: unknown; /** * This parameter connects with Youtube for the video link and generates a * screenshot in the “Video” block. Default: Refer to “How to Get a YouTube * API Key” article for details. If you don’t pass this parameter, our default * key will be used instead; however, we do not recommend using it for * security reasons. */ youtubeApiKey?: unknown; } interface StripoMergeTag { /** This label will be displayed as a merge tag name in the Text Editor. */ label: string; /** This value will be inserted into HTML code after clicking on merge tag. */ value: string; /** Additional description for the tag. */ hint?: string; } interface StripoMergeTags { /** Used to group similar merge tags under one label. */ category: string; /** Array of merge tags for category. */ entries?: StripoMergeTag[]; } interface StripoSpecialLink { /** This label will be displayed as a link name in the Text Editor. */ label: string; /** This value will be inserted into HTML code after clicking an entry. */ value: string; /** This parameter allows hiding the label with value. */ hidden?: true; } interface StripoSpecialLinks { /** Used to group similar links under one label. */ category: string; /** Array of links in category. */ entries?: StripoSpecialLink[]; } ```
ghost commented 1 year ago

Here's how I generated the docs from your plugin support page...

Expand this section to see the code used to generate the initial StripoInitOptions. ```js function isReq(req) { return ["yes", "true"].includes((req || "").toLowerCase().trim()); } /** * Generated from devtools at https://stripo.email/plugin-api Select the * appropriate `container table__row-list` in devtools Elements and run the * following example in the Console. * * Then update the items array in this file and run this file with Node. You can * use Prettier with prettier-plugin-jsdoc to format the jsdoc. * * @example * [...$0.children].map(ch => ({ * name: ch.children[0].innerText, * req: ch.children[1].innerText, * desc: ch.children[2].innerText, * def: ch.children[3].innerText, * })); */ const items = [ // { // name: "Parameter", // req: "Required", // desc: "Description", // def: "Default", // }, { name: "locale", req: "No", desc: "2-letter language identifier.\nAvailable Languages:\nEnglish: “en”\nSpanish: “es”\nFrench: “fr”\nGerman: “de”\nItalian: “it”\nPortuguese: “pt”\nSlovenian: “sl”\nRussian: “ru”\nUkrainian: “uk”\nDutch: “nl”\nCzech: “cs”\nTurkish: “tr”\nPolish: “pl”\nChinese Traditional: “zh”", def: "“en”", }, { name: "previewId", req: "Yes", desc: "ID of preview container.", def: "", }, { name: "settingsId", req: "Yes", desc: "ID of settings container.", def: "", }, { name: "apiRequestData", req: "Yes", desc: "These parameters will be passed to the backend with every request. Refer to “the Plugin request parameters” section for details.", def: "", }, { name: "getAuthToken", req: "Yes", desc: "Please implement this function to get the auth token from the backend. See the “Plugin authentication” section for details.", def: "", }, { name: "html", req: "Yes", desc: "The HTML code of the email template has to be open.", def: "", }, { name: "css", req: "Yes", desc: "The CSS code has to be applied to email.", def: "", }, { name: "userFullName", req: "No", desc: "A full name of the user that uses the editor. Will be displayed in the Version History section of the editor.", def: "", }, { name: "codeEditorButtonId", req: "No", desc: "ID of the open/close code editor button.", def: "", }, { name: "undoButtonId", req: "No", desc: "ID of the undo button.", def: "", }, { name: "redoButtonId", req: "No", desc: "ID of the redo button.", def: "", }, { name: "unSubscribeLink", req: "No", desc: "This value will be applied to the link if the “Unsubscribe” link type is chosen.", def: "", }, { name: "viewInBrowserLink", req: "No", desc: "This value will be applied to the link if the “View In Browser” link type is chosen.", def: "", }, { name: "ignoreClickOutsideSelectors", req: "No", desc: "List of selectors of elements, click on which does not start the clickOutsidePreview event and as a result does not reset the block selection in the preview area.", def: "", }, { name: "notifications", req: "No", desc: "Set of methods that will be called when any message needs to be visible for the user. See the “Plugin notifications” section for details.", def: "{ info: message => console.log(message), error: message => console.error(message), success: message => console.log(message), warn: message => console.log(message), loader: message => console.log(message), hide: message => console.log(message) }", }, { name: "onTemplateLoaded", req: "No", desc: "This parameter helps to notify the external application when the plugin initialization is completed.", def: "onTemplateLoaded: function() {console.log('Loaded')}", }, { name: "socialNetworks", req: "No", desc: 'List of social networks to be included in the “Social Networks” block. See the “Social Networks" section for details', def: "", }, { name: "mergeTags", req: "No", desc: "List of the merge tags to be included in the Text Editor panel. See the “Merge Tags” section for details.", def: "See the “Merge Tags” section for default values", }, { name: "specialLinks", req: "No", desc: "List of the special links to be included in the Link selector component in the editor.", def: "See the “Special Links” section for default values", }, { name: "editorFonts", req: "No", desc: "List of fonts to be included in the Text Editor panel and the Settings panel for basic blocks. See the “Сustom Font Sizes list” section for details.", def: "See the “Fonts Management” documentation for default values", }, { name: "editorFontSizes", req: "No", desc: "List of font sizes to be included in the Text Editor panel and the Settings panel for basic blocks. See the “Сustom Font Sizes list” section for details.", def: "See the “Сustom Font Sizes list” section for default values", }, { name: "customColorPalette", req: "No", desc: "List of colors to display in the color palette for the Text Editor panel and the Settings panel for every basic block. See the “Custom Color Palette” section for details.", def: "See the “Custom Color Palette” section for default values", }, { name: "customColorPaletteTextOnly", req: "No", desc: "Set up your desired colors for the text available only in the side menu and the CKEditor menu. See the “Custom Color Palette” section for details.", def: "", }, { name: "viewOnly", req: "No", desc: "Set to TRUE if you want to disable email modifications by a user.", def: "false", }, { name: "apiBaseUrl", req: "No", desc: "The Stripo Plugin main backend entrypoint.", def: "/pluginapi/api/v1", }, { name: "bankImagesDefaultSearchString", req: "No", desc: "Default search string for images from the “Image Bank” if it is enabled.", def: "Depends on current season: “spring” / “summer” / “autumn” / “winter”", }, { name: "versionHistory", req: "No", desc: "See the “Version History” section for details.", def: "", }, { name: "draft", req: "No", desc: "The Stripo Plugin supports auto-save that makes calls to the server. In order to be notified in JavaScript when the content is changed and saved, you can rely on this parameter as described in the examples.", def: "draft: { showAutoSaveLoader: function() {console.log('Auto save in process')}, hideAutoSaveLoader: function(error) {console.log('Auto save completed')} }", }, { name: "allDataSaved", req: "No", desc: "This parameter helps to identify whether all changes are saved or not.\nIf something was not saved it returns False, if everything saved - True.", def: "", }, { name: "externalSmartElementsLibrary", req: "No", desc: "This parameter is used to display your own component with an external data list in a pop-up window. See the “Advanced parameters” section for details", def: "", }, { name: "enableXSSSecurity", req: "No", desc: "BOOL Specifies if meta tag with Security Policy will be applied to the edited document.", def: "false", }, { name: "allowedScriptSourceDomains", req: "No", desc: "Specifies a list of domains allowed as sources for script tags in the edited document. Example:\nhttps://domain1.com\nhttp://doman2.net", def: "‘’", }, { name: "conditionsEnabled", req: "No", desc: "Set to True if you want to enable the Conditions tab. See the “Display Conditions” section for details", def: "False", }, { name: "ampFormServices", req: "No", desc: 'This parameter is used to fetch a list of services (endpoints) used for collecting data gathered by the Form block. See the “AMP-Form Services" section for details.', def: "False", }, { name: "onToggleCodeEditor", req: "false", desc: "This parameter helps to notify the external application when the plugin code editor changes its state (opened/closed).", def: "onToggleCodeEditor: function(codeEditorVisible) {}", }, { name: "canBeSavedToLibrary", req: "false", desc: "This function depending on the result enable or disable 'save as module' functionality for individual containers/structures/stripes.", def: "canBeSavedToLibrary: function(moduleHtml) {return true}", }, { name: "onDataChanged", req: "false", desc: "If defined this function is called when there are unsaved changes in the email.", def: "onDataChanged : function() {console.log('data changed')}", }, { name: "selectBlockAfterDropFromSettingsPanel", req: "false", desc: "If true then block will be selected after d&d from the settings panel.", def: "false", }, { name: "localePatch", req: "false", desc: 'It is possible to override any translation in the editor.A list of all editor phrases can be found here: https://plugins.stripo.email/static/latest/assets/i18n/en.json. In order to override translations, you need to list the keys and new values for each language in the value in the format:\n{ "localePatch": {\n"key1": {\n"en": "en_value",\n"ru": "ru_value"\n},\n"key2": {\n"en": "en_value"\n} } }\nExample:\n{ "localePatch": {\n"settingsPanel.accordion.structures": {\n"en": "Available Structures",\n"ru": "Доступные структуры"\n},\n"settingsPanel.block.timer": {\n"en": "Clock"\n} } }', def: "{}", }, { name: "defaultMenuItems", req: "no", desc: "Predefined values for the menu items (number and titles)", def: '"defaultMenuItems":[\n{ "name":"Item 1",\n"href":"https://google.com"\n},\n{ "name":"Item 2",\n"href":"https://test.com"\n} ]', }, { name: "customColorPaletteColors", req: "false", desc: "Initial list of colors to be in the custom palette. These colors will be updated after custom color selection by user.\nExample: ['#882724', '#35882C', '#FFD351', '#1924FF', '#B621EC', '#95C4EC','#812724']", def: "", }, { name: "customColorPaletteColorsChanged", req: "false", desc: "Callback that is called on custom color selection with new custom colors palette.\nExample: function(colors) {\nconsole.log('Colors palette changed: ' + colors);\n}", def: "", }, { name: "customColorPaletteLabel", req: "false", desc: "Title of custom colors palette.\nExample: 'Last Used Colors:'", def: "", }, { name: "brandColorPaletteColors", req: "false", desc: "Initial list of colors to be in the brand palette. These colors will be unchanged during editor session.\nExample: ['#35882C', '#FFD351', '#1924FF', '#B621EC', '#95C4EC','#812724', '#95C4EC']", def: "", }, { name: "brandColorPaletteLabel", req: "false", desc: "Title of custom colors palette.\nExample: 'Brand Colors:'", def: "", }, { name: "youtubeApiKey", req: "No", desc: "This parameter connects with Youtube for the video link and generates a screenshot in the “Video” block.", def: "Refer to “How to Get a YouTube API Key” article for details. If you don’t pass this parameter, our default key will be used instead; however, we do not recommend using it for security reasons.", }, { name: "supportOutlookButtonsByDefault", req: "No", desc: 'Passing this parameter with a "true" value will enable the "Outlook Support" control for the "Button" block.', def: "false", }, { name: "blocks", req: "No", desc: "User can move blocks inside the structure just by using a mouse. Catch needed block content and move it in right place.", def: "{ moveBlockAvailability: true }", }, ].sort((a, b) => { const ar = isReq(a.req); const br = isReq(b.req); return ar && !br ? -1 : br && !ar ? 1 : // a.name.localeCompare(b.name); }); let code = ` interface StripoInitOptions { ${items .map(it => { return ( // Description ` /** ${it.desc.replaceAll("\n", " ")}${ it.def ? "Default: " + it.def : "" } */\n` + // Name : type; ` ${it.name}${isReq(it.req) ? ":" : "?:"} unknown;` ); }) .join("\n")} } `; // console.log(code); const filePath = "./StripoInitOptions.d.ts"; require("fs").writeFileSync(filePath, code); console.log(`Wrote ${filePath}`); ```
ghost commented 1 year ago

Here are the types updated from latest docs (~ release 1.77.0).

In whatever code initializes the Stripo API you can put the following to use the types.

declare global {
  interface Window {
    Stripo: Stripo;
    StripoApi: StripoApi;
  }
}
Expand to see Stripo and StripoApi TypeScript types. ```ts // See https://github.com/ardas/stripo-plugin/issues/19 // // These types were generated from version 1.72.0 and updated from 1.77.0 docs. // To check for any possible changes see: // - https://stripo.email/releases/ // - https://stripo.email/plugin-api/ declare interface Stripo { init(options: StripoInitOptions, beforeInitCallback?: () => void): void; } declare interface StripoApi { /** * This parameter helps to identify whether all changes are saved or not. If * something was not saved it returns `false`, if everything saved - `true`. * Can be applied only if you don’t use Autosave option. */ allDataSaved(): void; /** Undocumented StripoApi function. */ applyDefaultStyles(): void; /** * This method returns compiled and compressed HTML code that is ready to be * sent out to clients. * * @example * compileEmail(function(error, html, ampHtml, ampErrors) {...}, false) * * @param callback If an error occurs, the first parameter will contain the * error description. In case of success, the first parameter will be null * and the second parameter will contain HTML code. * * In case your email template contains AMP elements or components, the third * parameter will contain the HTML code of the AMP HTML Mime type. In case * AMP HTML is invalid, the fourth parameter will contain the error * descriptions (array of strings). * @param minimize If true — the HTML code will be in a format of a single * line without line breaks. */ compileEmail( callback: ( error: string, html: string, ampHtml: string, ampErrors: string, ) => void, minimize?: boolean, ): void; /** Undocumented StripoApi function. */ compileHistoryEmail(e: unknown, t: unknown, n: unknown, r: unknown): void; /** Undocumented StripoApi function. */ createVersionHistoryPoint(): void; /** Undocumented StripoApi function. */ createVersionHistoryPointAsync(e: unknown): Promise; /** Undocumented StripoApi function. */ flushChanges(): void; /** Undocumented StripoApi function. */ getEmail(): void; /** * This method returns the Gmail Promo Annotations’ microdata inserted into * the HTML code of the email template in the editor. * * In case the microdata code is not available there, the `null` value is * returned. * * If any of the parameters are disabled or empty, then the empty data is * returned (for example, `discountCode: ''`). * * For more information on these parameters, please refer to this page * https://stripo.email/gmail-promo/ (go to the “Generate my code” button and * check the “Microdata Format” tab) or on our blog * https://stripo.email/blog/gmail-new-promotions-tab-guide/ */ getGoogleAnnotations(): Record< | "logo" | "description" | "discountCode" | "availabilityStarts" | "availabilityEnds" | "timeZonesId" | "image", string > | null; /** This method returns an email’s hidden preheader. */ getHiddenPreHeader(): string; /** Undocumented StripoApi function. */ getHistoryTemplate(): void; /** Undocumented StripoApi function. */ getLastChangeInfo(): unknown; /** * This method returns the HTML and CSS codes with the Plugin internal extra * styles and editor markup. You should **call the getTemplate function to * take out modified HTML and CSS from the editor in order to save it in your * DB.** */ getTemplate( callback: ( html: string, css: string, width: number, height: number, ) => void, ): void; /** This method returns an email title/subject line. */ getTitle(): string; /** Undocumented StripoApi function. */ getUndoState(): void; /** Get a unique Stripo version identifier string. */ getVersion(): string; /** Internal use only. Call `window.Stripo.init()` instead. */ init(e: any): void; /** Undocumented StripoApi function. */ setName(...args: unknown[]): void; /** This method sets an email title/subject line. */ setTitle(value: string): void; /** * This method inserts/updates the Gmail Promo Annotations’ microdata in HTML * code of the opened email template in the editor. In case you want to * disable the whole feature please pass the `null` value. Otherwise, you will * pass all or any parameters with the data according to these requirements. * If you want to disable any of the parameters, simply pass the empty data * (for example, `discountCode: ''`). Please find more information on every * parameter https://stripo.email/gmail-promo/ (go to the “Generate my code” * button and check the “Microdata Format” tab) or on our blog * https://stripo.email/blog/gmail-new-promotions-tab-guide/ * * @param value */ setGoogleAnnotations( value: Record< | "logo" | "description" | "discountCode" | "availabilityStarts" | "availabilityEnds" | "timeZonesId" | "image", string > | null, ): void; /** This method sets an email’s hidden preheader. */ setHiddenPreHeader(value: string): void; /** * Use this function to display the AMP validation errors in the Stripo * preview mode if there are any in the email template. * * Please find the detailed description here * https://stripo.email/plugin-api/#how-to-call-the-showamperorsmodal-function * * @example * showAmpErrorsModal(ampErrors, userSuccessButtons, onCancel, onSubmit); * * @param ampErrors Represents the array of AMP errors received after calling * the compileEmail function. * @param userSuccessButtons Includes the array of external buttons that may * be displayed in the preview window in case if there are no validation * errors. * @param onCancel A callback function the editor may call if the user closes * the preview window. * @param onSubmit A callback function the editor may call when the user * clicks on the “Fix in Code Editor” button if there are any errors. Please * be advised that this button won’t be displayed if you did not pass the * `codeEditorButtonId` with the Plugin initialization. */ showAmpErrorsModal( ampErrors: unknown[], userSuccessButtons: unknown[], onCancel: () => void, onSubmit: () => void, ): void; /** Undocumented but obvious function. */ showChangeHistoryPanel(): void; /** Undocumented but obvious function. */ toggleChangeHistoryPanel(): void; /** Undocumented StripoApi function. */ updateAutosaveToken(e: unknown): void; /** Undocumented StripoApi function. */ updateImagesLibraryConfig(e): void; /** Undocumented StripoApi function. */ updateLinks(): void; /** Undocumented StripoApi function. */ updateHtmlAndCss(html: string, css: string): void; /** Undocumented StripoApi function. */ updateTimers(e: unknown): void; /** Undocumented StripoApi function. */ setHtmlReadyForSave(): void; /** * If the editor is closed by the user in your web application, we recommend * calling the `stop` function to stop all processes and improve the * performance of your application. */ stop(): void; } /** * Parameters for `window.Stripo.init()`. * * @see https://stripo.email/plugin-api/#initialization-configuration */ declare interface StripoInitOptions { /** * **NOTE: You must pass ALL variables used in the Stripo plugin editor, under * UI Settings -> Image Gallery -> Folders configuration: Folder paths.** * * Request data used by Stripo to uniquely identify this email. The `emailId` * field is mandatory. Other "tenant/user/account" ids may also be included * which Stripo may use to build paths for image and document storage. * * These parameters will be passed to the backend with every request. Refer to * “the Plugin request parameters” section for details. */ apiRequestData: { emailId: string | number } & Record< string, string | number >; /** CSS to edit. */ css: string; /** * Function that should contact your API server, which should then send a POST * to `https://plugins.stripo.email/api/v1/auth` and return the result. * * Please implement this function to get the auth token from the backend. See * the “Plugin authentication” section for details. */ getAuthToken(callback: (token: string) => void): void; /** HTML to edit. **MUST include HTML `` and `` tags.** */ html: string; /** HTML element id for Stripo to inject the preview panel. */ previewId: string; /** HTML element id for Stripo to inject the settings panel. */ settingsId: string; /** * This parameter helps to identify whether all changes are saved or not. If * something was not saved it returns False, if everything saved - True. */ allDataSaved?: () => boolean; /** * Specifies a list of domains allowed as sources for script tags in the * edited document. Example: https://domain1.com http://doman2.net Default: * `‘’` */ allowedScriptSourceDomains?: string; /** * This parameter is used to fetch a list of services (endpoints) used for * collecting data gathered by the Form block. See the “AMP-Form Services" * section for details. Default: `false` */ ampFormServices?: unknown; /** The Stripo Plugin main backend entrypoint. Default: `"/pluginapi/api/v1"` */ apiBaseUrl?: unknown; /** * Default search string for images from the “Image Bank” if it is enabled. * Default: Depends on current season: “spring” / “summer” / “autumn” / * “winter” */ bankImagesDefaultSearchString?: unknown; /** * User can move blocks inside the structure just by using a mouse. Catch * needed block content and move it in right place. Default: `{ * moveBlockAvailability: true }` */ blocks?: { moveBlockAvailability: boolean }; /** * Initial list of colors to be in the brand palette. These colors will be * unchanged during editor session. Example: `['#35882C', '#FFD351', * '#1924FF', '#B621EC', '#95C4EC','#812724', '#95C4EC']` */ brandColorPaletteColors?: unknown; /** Title of custom colors palette. Example: `'Brand Colors:'` */ brandColorPaletteLabel?: unknown; /** * This function depending on the result enable or disable 'save as module' * functionality for individual containers/structures/stripes. Default: * `canBeSavedToLibrary: function(moduleHtml) {return true}` */ canBeSavedToLibrary?: unknown; /** ID of the open/close code editor button. */ codeEditorButtonId?: string; /** * Set to True if you want to enable the Conditions tab. See the “Display * Conditions” section for details Default: `false` */ conditionsEnabled?: unknown; /** * List of colors to display in the color palette for the Text Editor panel * and the Settings panel for every basic block. See the “Custom Color * Palette” section for details. Default: See the “Custom Color Palette” * section for default values */ customColorPalette?: unknown; /** * Initial list of colors to be in the custom palette. These colors will be * updated after custom color selection by user. Example: `['#882724', * '#35882C', '#FFD351', '#1924FF', '#B621EC', '#95C4EC','#812724']` */ customColorPaletteColors?: unknown; /** * Callback that is called on custom color selection with new custom colors * palette. Example: function(colors) { console.log('Colors palette changed: * ' * * - Colors); } */ customColorPaletteColorsChanged?: unknown; /** Title of custom colors palette. Example: 'Last Used Colors:' */ customColorPaletteLabel?: unknown; /** * Set up your desired colors for the text available only in the side menu and * the CKEditor menu. See the “Custom Color Palette” section for details. */ customColorPaletteTextOnly?: unknown; /** * Predefined values for the menu items (number and titles) Default: * `"defaultMenuItems":[ { "name":"Item 1", "href":"https://google.com" }, { * "name":"Item 2", "href":"https://test.com" } ]` */ defaultMenuItems?: unknown; /** * Set to TRUE to disable the responsive view for your email template. In this * case the “Responsive design” control within Appearance tab of the editor * will be deactivated by default. */ disableAdaptDesign?: boolean; /** * The Stripo Plugin supports auto-save that makes calls to the server. In * order to be notified in JavaScript when the content is changed and saved, * you can rely on this parameter as described in the examples. Default: * `draft: { showAutoSaveLoader: function() {console.log('Auto save in * process')}, hideAutoSaveLoader: function(error) {console.log('Auto save * completed')} }` */ draft?: unknown; /** * List of fonts to be included in the Text Editor panel and the Settings * panel for basic blocks. See the “Сustom Font Sizes list” section for * details. Default: See the “Fonts Management” documentation for default * values */ editorFonts?: unknown; /** * List of font sizes to be included in the Text Editor panel and the Settings * panel for basic blocks. See the “Сustom Font Sizes list” section for * details. Default: See the “Сustom Font Sizes list” section for default * values */ editorFontSizes?: unknown; /** * Set to TRUE to enable narrative spellchecker for the users in the editor. * In this case, the text with typos will be underlined and, by * right-clicking, will appear in the context menu of suggestions for * correction. Works in beta-mode. */ enableNativeSpellChecker?: boolean; /** * BOOL Specifies if meta tag with Security Policy will be applied to the * edited document. Default: `false` */ enableXSSSecurity?: unknown; /** * This parameter helps to notify when the customer takes any actions with * modules and or basic block name. */ eventHandler?: ( type: | "MODULE_SAVED_BY_CUSTOMER" | "MODULE_UPDATED_BY_CUSTOMER" | "MODULE_DROPPED" | "BLOCK_REMOVED" | "BLOCK_MOVED" | "BLOCK_DROPPED", data: unknown, ) => void; /** * This parameter is used to display your own component with an external data * list in a pop-up window. See the “Advanced parameters” section for details */ externalSmartElementsLibrary?: unknown; /** * Set to TRUE to hide the value of the selected image in the Image Path input * field located in the Image gallery in case the image is hosted with Stripo * CDN. */ hideStripoImgUrl?: boolean; /** * List of selectors of elements, click on which does not start the * clickOutsidePreview event and as a result does not reset the block * selection in the preview area. */ ignoreClickOutsideSelectors?: string[]; /** * 2-letter language identifier. Available Languages: English: “en” Spanish: * “es” French: “fr” German: “de” Italian: “it” Portuguese: “pt” Slovenian: * “sl” Russian: “ru” Ukrainian: “uk” Dutch: “nl” Czech: “cs” Turkish: “tr” * Polish: “pl” Chinese Traditional: “zh” Default: `“en”` */ locale?: string; /** * It is possible to override any translation in the editor.A list of all * editor phrases can be found here: * https://plugins.stripo.email/static/latest/assets/i18n/en.json. In order to * override translations, you need to list the keys and new values for each * language in the value in the format: { "localePatch": { "key1": { "en": * "en_value", "ru": "ru_value" }, "key2": { "en": "en_value" } } } Example: { * "localePatch": { "settingsPanel.accordion.structures": { "en": "Available * Structures", "ru": "Доступные структуры" }, "settingsPanel.block.timer": { * "en": "Clock" } } } Default: `{}` */ localePatch?: unknown; /** * List of the merge tags to be included in the Text Editor panel. See the * “Merge Tags” section for details. Default: See the “Merge Tags” section for * default values */ mergeTags?: StripoMergeTags[]; /** * Set to TRUE if you want your users to manage the modules (the ability to * see and manage them on the Settings Panel along with the ability to save * new ones). This parameter will be ignored if you deactivate Modules within * the plugin configuration page. */ modulesDisabled?: boolean; /** * Set of methods that will be called when any message needs to be visible for * the user. See the “Plugin notifications” section for details. Default: `{ * info: message => console.log(message), error: message => * console.error(message), success: message => console.log(message), warn: * message => console.log(message), loader: message => console.log(message), * hide: message => console.log(message) }` */ notifications?: Record< "info" | "error" | "success" | "warn" | "loader" | "hide", (message: string) => void >; /** * If defined this function is called when there are unsaved changes in the * email. Default: `onDataChanged : function() {console.log('data changed')}` */ onDataChanged?: unknown; /** * This parameter helps to notify the external application when the plugin * initialization is completed. Default: `onTemplateLoaded: function() * {console.log('Loaded')}` */ onTemplateLoaded?: () => void; /** * This parameter helps to notify the external application when the plugin * code editor changes its state (opened/closed). Default: * `onToggleCodeEditor: function(codeEditorVisible) {}` */ onToggleCodeEditor?: unknown; /** * This parameter allows you to add any custom attributes for the * `​​stripoPreviewContainer` container if needed for your use cases. * @example * previewIframeAttributes: { foo: "bar", withoutValue: "" } */ previewIframeAttributes?: unknown; /** ID of the redo button. */ redoButtonId?: string; /** * If true then block will be selected after d&d from the settings panel. * Default: `false` */ selectBlockAfterDropFromSettingsPanel?: unknown; /** * List of social networks to be included in the “Social Networks” block. See * the “Social Networks" section for details */ socialNetworks?: any[]; /** * List of the special links to be included in the Link selector component in * the editor. Default: See the “Special Links” section for default values */ specialLinks?: StripoSpecialLinks[]; /** * Passing this parameter with a "true" value will enable the "Outlook * Support" control for the "Button" block. Default: `false` */ supportOutlookButtonsByDefault?: unknown; /** ID of the undo button. */ undoButtonId?: string; /** * This value will be applied to the link if the “Unsubscribe” link type is * chosen. */ unSubscribeLink?: string; /** * A full name of the user that uses the editor. Will be displayed in the * Version History section of the editor. */ userFullName?: string; /** See the “Version History” section for details. */ versionHistory?: unknown; /** * This value will be applied to the link if the “View In Browser” link type * is chosen. */ viewInBrowserLink?: string; /** * Set to TRUE if you want to disable email modifications by a user. Default: * `false` */ viewOnly?: unknown; /** * This parameter connects with Youtube for the video link and generates a * screenshot in the “Video” block. Default: Refer to “How to Get a YouTube * API Key” article for details. If you don’t pass this parameter, our default * key will be used instead; however, we do not recommend using it for * security reasons. */ youtubeApiKey?: unknown; } declare interface StripoMergeTag { /** This label will be displayed as a merge tag name in the Text Editor. */ label: string; /** This value will be inserted into HTML code after clicking on merge tag. */ value: string; /** Additional description for the tag. */ hint?: string; } declare interface StripoMergeTags { /** Used to group similar merge tags under one label. */ category: string; /** Array of merge tags for category. */ entries?: StripoMergeTag[]; } declare interface StripoSpecialLink { /** This label will be displayed as a link name in the Text Editor. */ label: string; /** This value will be inserted into HTML code after clicking an entry. */ value: string; /** This parameter allows hiding the label with value. */ hidden?: true; } declare interface StripoSpecialLinks { /** Used to group similar links under one label. */ category: string; /** Array of links in category. */ entries?: StripoSpecialLink[]; } ```