import React from 'react'; import ReactDOM from 'react-dom'; import { PropTypes, localized, Actions, Message, DraftEditingSession, FeatureUsageStore, } from 'mailspring-exports'; import { Menu, RetinaImg } from 'mailspring-component-kit'; import { TranslatePopupOptions, translateMessageBody, TranslationsUsedLexicon } from './service'; export class TranslateComposerButton extends React.Component<{ draft: Message; session: DraftEditingSession; }> { // Adding a `displayName` makes debugging React easier static displayName = 'TranslateComposerButton'; // Since our button is being injected into the Composer Footer, // we receive the local id of the current draft as a `prop` (a read-only // property). Since our code depends on this prop, we mark it as a requirement. static propTypes = { draft: PropTypes.object.isRequired, session: PropTypes.object.isRequired, }; shouldComponentUpdate(nextProps) { // Our render method doesn't use the provided `draft`, and the draft changes // constantly (on every keystroke!) `shouldComponentUpdate` helps keep Mailspring fast. return nextProps.session !== this.props.session; } _onTranslate = async langName => { Actions.closePopover(); try { await FeatureUsageStore.markUsedOrUpgrade('translation', TranslationsUsedLexicon); } catch (err) { // user does not have access to this feature return; } // Obtain the session for the current draft. The draft session provides us // the draft object and also manages saving changes to the local cache and // Nilas API as multiple parts of the application touch the draft. const langCode = TranslatePopupOptions[langName]; const translated = await translateMessageBody(this.props.draft.body, langCode); // To update the draft, we add the new body to it's session. The session object // automatically marshalls changes to the database and ensures that others accessing // the same draft are notified of changes. this.props.session.changes.add({ body: translated }); this.props.session.changes.commit(); }; _onClickTranslateButton = () => { const buttonRect = (ReactDOM.findDOMNode(this) as HTMLElement).getBoundingClientRect(); Actions.openPopover(this._renderPopover(), { originRect: buttonRect, direction: 'up' }); }; // Helper method that will render the contents of our popover. _renderPopover() { const headerComponents = [{localized('Translate')}:]; return (