Ghost/ghost/admin/app/components/modal-post-preview/email.js

148 lines
4.7 KiB
JavaScript
Raw Normal View History

import Component from '@glimmer/component';
import validator from 'validator';
import {action} from '@ember/object';
import {htmlSafe} from '@ember/template';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency-decorators';
import {timeout} from 'ember-concurrency';
import {tracked} from '@glimmer/tracking';
const INJECTED_CSS = `
html::-webkit-scrollbar {
display: none;
width: 0;
background: transparent
}
html {
scrollbar-width: none;
}
`;
// TODO: remove duplication with <ModalPostEmailPreview>
export default class ModalPostPreviewEmailComponent extends Component {
@service ajax;
@service config;
@service feature;
@service ghostPaths;
@service session;
@service settings;
@tracked html = '';
@tracked subject = '';
@tracked memberSegment = 'status:free';
Made `session.user` a synchronous property rather than a promise no issue Having `session.user` return a promise made dealing with it in components difficult because you always had to remember it returned a promise rather than a model and had to handle the async behaviour. It also meant that you couldn't use any current user properties directly inside getters which made refactors to Glimmer/Octane idioms harder to reason about. `session.user` was a cached computed property so it really made no sense for it to be a promise - it was loaded on first access and then always returned instantly but with a fulfilled promise rather than the underlying model. Refactoring to a synchronous property that is loaded as part of the authentication flows (we load the current user to check that we're logged in - we may as well make use of that!) means one less thing to be aware of/remember and provides a nicer migration process to Glimmer components. As part of the refactor, the auth flows and pre-load of required data across other services was also simplified to make it easier to find and follow. - refactored app setup and `session.user` - added `session.populateUser()` that fetches a user model from the current user endpoint and sets it on `session.user` - removed knowledge of app setup from the `cookie` authenticator and moved it into = `session.postAuthPreparation()`, this means we have the same post-authentication setup no matter which authenticator is used so we have more consistent behaviour in tests which don't use the `cookie` authenticator - switched `session` service to native class syntax to get the expected `super()` behaviour - updated `handleAuthentication()` so it populate's `session.user` and performs post-auth setup before transitioning (handles sign-in after app load) - updated `application` route to remove duplicated knowledge of app preload behaviour that now lives in `session.postAuthPreparation()` (handles already-authed app load) - removed out-of-date attempt at pre-loading data from setup controller as that's now handled automatically via `session.handleAuthentication` - updated app code to not treat `session.user` as a promise - predominant usage was router `beforeModel` hooks that transitioned users without valid permissions, this sets us up for an easier removal of the `current-user-settings` mixin in the future
2021-07-08 16:37:31 +03:00
@tracked previewEmailAddress = this.session.user.email;
@tracked sendPreviewEmailError = '';
get mailgunIsEnabled() {
return this.config.get('mailgunIsConfigured') ||
!!(this.settings.get('mailgunApiKey') && this.settings.get('mailgunDomain') && this.settings.get('mailgunBaseUrl'));
}
@action
async renderEmailPreview(iframe) {
this._previewIframe = iframe;
await this._fetchEmailData();
// avoid timing issues when _fetchEmailData didn't perform any async ops
await timeout(100);
if (iframe) {
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(this.html);
iframe.contentWindow.document.close();
}
}
@action
changeMemberSegment(segment) {
this.memberSegment = segment;
if (this._previewIframe) {
this.renderEmailPreview(this._previewIframe);
}
}
@task({drop: true})
*sendPreviewEmailTask() {
try {
const resourceId = this.args.post.id;
const testEmail = this.previewEmailAddress.trim();
if (!validator.isEmail(testEmail)) {
this.sendPreviewEmailError = 'Please enter a valid email';
return false;
}
if (!this.mailgunIsEnabled) {
this.sendPreviewEmailError = 'Please verify your email settings';
return false;
}
this.sendPreviewEmailError = '';
const url = this.ghostPaths.url.api('/email_preview/posts', resourceId);
const data = {emails: [testEmail], memberSegment: this.memberSegment};
const options = {
data,
dataType: 'json'
};
return yield this.ajax.post(url, options);
} catch (error) {
if (error) {
let message = 'Email could not be sent, verify mail settings';
// grab custom error message if present
if (
error.payload && error.payload.errors
&& error.payload.errors[0] && error.payload.errors[0].message) {
message = htmlSafe(error.payload.errors[0].message);
}
this.sendPreviewEmailError = message;
throw error;
}
}
}
async _fetchEmailData() {
let {html, subject, memberSegment} = this;
let {post} = this.args;
if (html && subject && memberSegment === this._lastMemberSegment) {
return {html, subject};
}
this._lastMemberSegment = memberSegment;
// model is an email
if (post.html && post.subject) {
html = post.html;
subject = post.subject;
// model is a post with an existing email
} else if (post.email) {
html = post.email.html;
subject = post.email.subject;
// model is a post, fetch email preview
} else {
let url = this.ghostPaths.url.api('/email_preview/posts', post.id);
if (this.feature.emailCardSegments) {
url = `${url}?memberSegment=${encodeURIComponent(this.memberSegment)}`;
}
let response = await this.ajax.request(url);
let [emailPreview] = response.email_previews;
html = emailPreview.html;
subject = emailPreview.subject;
}
// inject extra CSS into the html for disabling links and scrollbars etc
let domParser = new DOMParser();
let htmlDoc = domParser.parseFromString(html, 'text/html');
let stylesheet = htmlDoc.querySelector('style');
let originalCss = stylesheet.innerHTML;
stylesheet.innerHTML = `${originalCss}\n\n${INJECTED_CSS}`;
html = htmlDoc.documentElement.innerHTML;
this.html = html;
this.subject = subject;
}
}