Refactored PostSettingsMenuController

Closes #2845.
Ref #1351.
- Refactored `PostSettingsMenuController` to appropriately set and display
  slug and publish date and their placeholders.
- Removed api spam on title change by putting `slugPlaceholder` generation
  inside of an `Ember.run.debounce` call.
- Renamed `gh-blur-text-field` to `gh-blur-input`
- Created `SlugGenerator` class to abstract slug generation.
- Added `timestampVerification` function to `utils/date-formatting`
- `utils/date-formatting` now uses `strict` parsing of dates
- Added more acceptable date formats to accommodate strict parsing
- Moved `isDraft` and `isPublished` computed properties from
  `EditorController` to `PostModel`
This commit is contained in:
Matt Enlow 2014-06-08 14:48:14 -06:00
parent 668dbde7fa
commit 175194fcff
8 changed files with 151 additions and 107 deletions

View File

@ -1,4 +1,4 @@
var BlurTextField = Ember.TextField.extend({
var BlurInput = Ember.TextField.extend({
selectOnClick: false,
click: function (event) {
if (this.get('selectOnClick')) {
@ -10,4 +10,4 @@ var BlurTextField = Ember.TextField.extend({
}
});
export default BlurTextField;
export default BlurInput;

View File

@ -1,4 +1,6 @@
/* global moment */
import {parseDateString, formatDate} from 'ghost/utils/date-formatting';
import SlugGenerator from 'ghost/models/slug-generator';
var PostSettingsMenuController = Ember.ObjectController.extend({
isStaticPage: function (key, val) {
@ -16,123 +18,143 @@ var PostSettingsMenuController = Ember.ObjectController.extend({
return !!this.get('page');
}.property('page'),
/**
* The placeholder is the published date of the post,
* or the current date if the pubdate has not been set.
*/
publishedAtPlaceholder: function () {
var pubDate = this.get('published_at');
if (pubDate) {
return formatDate(pubDate);
}
return formatDate(moment());
}.property('publishedAtValue'),
newSlugBinding: Ember.computed.oneWay('slug'),
publishedAtValue: function (key, value) {
if (arguments.length > 1) {
return value;
}
return formatDate(this.get('published_at'));
}.property('published_at'),
slugPlaceholder: function () {
return this.get('model').generateSlug();
}.property('title'),
slugValue: function (key, value) {
if (arguments.length > 1) {
return value;
}
return this.get('slug');
}.property('slug'),
//Lazy load the slug generator for slugPlaceholder
slugGenerator: Ember.computed(function () {
return SlugGenerator.create({ghostPaths: this.get('ghostPaths')});
}),
//Requests slug from title
generateSlugPlaceholder: function () {
var self = this,
slugGenerator = this.get('slugGenerator'),
title = this.get('title');
slugGenerator.generateSlug(title).then(function (slug) {
return self.set('slugPlaceholder', slug);
});
},
titleObserver: function () {
Ember.run.debounce(this, 'generateSlugPlaceholder', 700);
}.observes('title'),
slugPlaceholder: function (key, value) {
var slug = this.get('slug');
//If the post has a slug, that's its placeholder.
if (slug) {
return slug;
}
//Otherwise, it's whatever value was set by the
// slugGenerator (below)
if (arguments.length > 1) {
return value;
}
//The title will stand in until the actual slug has been generated
return this.get('title');
}.property(),
actions: {
updateSlug: function () {
var newSlug = this.get('newSlug'),
slug = this.get('slug'),
placeholder = this.get('slugPlaceholder'),
/**
* triggered by user manually changing slug
*/
updateSlug: function (newSlug) {
var slug = this.get('slug'),
self = this;
newSlug = (!newSlug && placeholder) ? placeholder : newSlug;
// Ignore unchanged slugs
if (slug === newSlug) {
return;
}
//reset to model's slug on empty string
if (!newSlug) {
this.set('newSlug', slug);
return;
}
//Validation complete
this.set('slug', newSlug);
// If the model doesn't currently
// exist on the server
// then just update the model's value
if (!this.get('isNew')) {
//Don't save just yet if it's an empty slug on a draft
if (!newSlug && this.get('isDraft')) {
return;
}
this.get('model').save().then(function () {
this.get('model').save('slug').then(function () {
self.notifications.showSuccess('Permalink successfully changed to <strong>' +
self.get('slug') + '</strong>.');
}, this.notifications.showErrors);
},
updatePublishedAt: function (userInput) {
var self = this,
errMessage = '',
newPubDate = formatDate(parseDateString(userInput)),
pubDate = this.get('publishedAt'),
newPubDateMoment,
pubDateMoment;
/**
* Parse user's set published date.
* Action sent by post settings menu view.
* (#1351)
*/
setPublishedAt: function (userInput) {
var errMessage = '',
newPublishedAt = parseDateString(userInput),
publishedAt = this.get('published_at'),
self = this;
// if there is no new pub date, mark that until the post is published,
// when we'll fill in with the current time.
if (!newPubDate) {
this.set('publishedAt', '');
if (!userInput) {
//Clear out the published_at field for a draft
if (this.get('isDraft')) {
this.set('published_at', null);
}
return;
}
// Check for missing time stamp on new data
// If no time specified, add a 12:00
if (newPubDate && !newPubDate.slice(-5).match(/\d+:\d\d/)) {
newPubDate += ' 12:00';
}
newPubDateMoment = parseDateString(newPubDate);
// If there was a published date already set
if (pubDate) {
// Check for missing time stamp on current model
// If no time specified, add a 12:00
if (!pubDate.slice(-5).match(/\d+:\d\d/)) {
pubDate += ' 12:00';
}
pubDateMoment = parseDateString(pubDate);
// Quit if the new date is the same
if (pubDateMoment.isSame(newPubDateMoment)) {
return;
}
// Do nothing if the user didn't actually change the date
if (publishedAt && publishedAt.isSame(newPublishedAt)) {
return;
}
// Validate new Published date
if (!newPubDateMoment.isValid() || newPubDate.substr(0, 12) === 'Invalid date') {
if (!newPublishedAt.isValid()) {
errMessage = 'Published Date must be a valid date with format: ' +
'DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
}
if (newPubDateMoment.diff(new Date(), 'h') > 0) {
//Can't publish in the future yet
if (newPublishedAt.diff(new Date(), 'h') > 0) {
errMessage = 'Published Date cannot currently be in the future.';
}
//If errors, notify and exit.
if (errMessage) {
// Show error message
this.notifications.showError(errMessage);
//Hack to push a "change" when it's actually staying
// the same.
//This alerts the listener on post-settings-menu
this.notifyPropertyChange('publishedAt');
return;
}
//Validation complete
this.set('published_at', newPubDateMoment.toDate());
this.set('published_at', newPublishedAt);
// If the model doesn't currently
// exist on the server
// then just update the model's value
if (!this.get('isNew')) {
return;
}
this.get('model').save().then(function () {
this.notifications.showSuccess('Publish date successfully changed to <strong>' +
self.get('publishedAt') + '</strong>.');
//@ TODO: Make sure we're saving ONLY the publish date here,
// Don't want to accidentally save text the user's been working on.
this.get('model').save('published_at').then(function () {
self.notifications.showSuccess('Publish date successfully changed to <strong>' +
formatDate(self.get('published_at')) + '</strong>.');
}, this.notifications.showErrors);
}
}
});
export default PostSettingsMenuController;
export default PostSettingsMenuController;

View File

@ -1,9 +1,6 @@
/* global console */
var EditorControllerMixin = Ember.Mixin.create({
//## Computed post properties
isPublished: Ember.computed.equal('status', 'published'),
isDraft: Ember.computed.equal('status', 'draft'),
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)

View File

@ -19,21 +19,10 @@ var Post = DS.Model.extend({
published_at: DS.attr('moment-date'),
published_by: DS.belongsTo('user', { async: true }),
tags: DS.hasMany('tag', { async: true }),
generateSlug: function () {
var title = this.get('title'),
url;
if (!title) {
return;
}
url = this.get('ghostPaths').apiUrl('slugs', 'post', encodeURIComponent(title));
return ic.ajax.request(url, {
type: 'GET'
});
},
//## Computed post properties
isPublished: Ember.computed.equal('status', 'published'),
isDraft: Ember.computed.equal('status', 'draft'),
validate: function () {
var validationErrors = [];
@ -48,4 +37,4 @@ var Post = DS.Model.extend({
}.property('title')
});
export default Post;
export default Post;

27
models/slug-generator.js Normal file
View File

@ -0,0 +1,27 @@
var SlugGenerator = Ember.Object.extend({
ghostPaths: null,
value: null,
toString: function () {
return this.get('value');
},
generateSlug: function (textToSlugify) {
var self = this,
url;
if (!textToSlugify) {
return Ember.RSVP.resolve('');
}
url = this.get('ghostPaths').apiUrl('slugs', 'post', encodeURIComponent(textToSlugify));
return ic.ajax.request(url, {
type: 'GET'
}).then(function (response) {
var slug = response.slugs[0].slug;
self.set('value', slug);
return slug;
});
}
});
export default SlugGenerator;

View File

@ -17,7 +17,6 @@
{{/if}}
<span class="name">{{user.name}}</span>
{{/gh-popover-button}}
{{!-- @TODO: add functionality to allow for dropdown to work --}}
{{#gh-popover tagName="ul" classNames="overlay" name="user-menu" closeOnClick="true"}}
<li class="usermenu-profile">{{#link-to "settings.user"}}Your Profile{{/link-to}}</li>
<li class="divider"></li>

View File

@ -6,7 +6,7 @@
<label for="url">URL</label>
</td>
<td class="post-setting-field">
{{gh-blur-text-field class="post-setting-slug" id="url" value=newSlug action="updateSlug" placeholder=slugPlaceholder selectOnClick="true"}}
{{gh-blur-input class="post-setting-slug" id="url" value=slugValue action="updateSlug" placeholder=slugPlaceholder selectOnClick="true"}}
</td>
</tr>
<tr class="post-setting">
@ -14,7 +14,7 @@
<label for="pub-date">Pub Date</label>
</td>
<td class="post-setting-field">
{{gh-blur-text-field class="post-setting-date" value=view.publishedAt action="updatePublishedAt" placeholder=view.datePlaceholder}}
{{gh-blur-input class="post-setting-date" value=publishedAtValue action="setPublishedAt" placeholder=publishedAtPlaceholder}}
</td>
</tr>
<tr class="post-setting">

View File

@ -1,21 +1,31 @@
/* global moment */
var parseDateFormats = ['DD MMM YY HH:mm',
'DD MMM YYYY HH:mm',
'DD/MM/YY HH:mm',
'DD/MM/YYYY HH:mm',
'DD-MM-YY HH:mm',
'DD-MM-YYYY HH:mm',
'YYYY-MM-DD HH:mm'],
var parseDateFormats = ['DD MMM YY @ HH:mm', 'DD MMM YY HH:mm',
'DD MMM YYYY @ HH:mm', 'DD MMM YYYY HH:mm',
'DD/MM/YY @ HH:mm', 'DD/MM/YY HH:mm',
'DD/MM/YYYY @ HH:mm', 'DD/MM/YYYY HH:mm',
'DD-MM-YY @ HH:mm', 'DD-MM-YY HH:mm',
'DD-MM-YYYY @ HH:mm', 'DD-MM-YYYY HH:mm',
'YYYY-MM-DD @ HH:mm', 'YYYY-MM-DD HH:mm'],
displayDateFormat = 'DD MMM YY @ HH:mm';
/**
* Add missing timestamps
*/
var verifyTimeStamp = function (dateString) {
if (dateString && !dateString.slice(-5).match(/\d+:\d\d/)) {
dateString += ' 12:00';
}
return dateString;
};
//Parses a string to a Moment
var parseDateString = function (value) {
return value ? moment(value, parseDateFormats) : '';
return value ? moment(verifyTimeStamp(value), parseDateFormats, true) : undefined;
};
//Formats a Date or Moment
var formatDate = function (value) {
return value ? moment(value).format(displayDateFormat) : '';
return verifyTimeStamp(value ? moment(value).format(displayDateFormat) : '');
};
export {parseDateString, formatDate};
export {parseDateString, formatDate};