-
-
Notifications
You must be signed in to change notification settings - Fork 11.8k
Expand file tree
/
Copy pathcontext-menu.js
More file actions
596 lines (514 loc) · 19.4 KB
/
Copy pathcontext-menu.js
File metadata and controls
596 lines (514 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import AddPostTagsModal from './modals/add-tag';
import Component from '@glimmer/component';
import DeletePostsModal from './modals/delete-posts';
import EditPostsAccessModal from './modals/edit-posts-access';
import UnpublishPostsModal from './modals/unpublish-posts';
import UnschedulePostsModal from './modals/unschedule-posts';
import copyTextToClipboard from 'ghost-admin/utils/copy-text-to-clipboard';
import nql from '@tryghost/nql';
import {action} from '@ember/object';
import {capitalizeFirstLetter} from 'ghost-admin/helpers/capitalize-first-letter';
import {getPagePlacement, pagePathForSlug, setPagesNavigationPlacement} from 'ghost-admin/utils/site-navigation';
import {inject} from 'ghost-admin/decorators/inject';
import {inject as service} from '@ember/service';
import {task, timeout} from 'ember-concurrency';
/**
* @tryghost/tpl doesn't work in admin yet (Safari)
*/
function tpl(str, data) {
for (const key in data) {
str = str.replace(new RegExp(`{${key}}`, 'g'), data[key]);
}
return str;
}
const messages = {
deleted: {
single: '{Type} deleted',
multiple: '{count} {type}s deleted'
},
unpublished: {
single: '{Type} reverted to a draft',
multiple: '{count} {type}s reverted to drafts'
},
unscheduled: {
single: '{Type} unscheduled',
multiple: '{count} {type}s unscheduled'
},
accessUpdated: {
single: '{Type} access updated',
multiple: '{Type} access updated for {count} {type}s'
},
tagsAdded: {
single: 'Tags added',
multiple: 'Tags added to {count} {type}s'
},
tagAdded: {
single: 'Tag added',
multiple: 'Tag added to {count} {type}s'
},
duplicated: {
single: '{Type} duplicated',
multiple: '{count} {type}s duplicated'
},
copiedPostUrl: {
single: 'Post link copied'
},
copiedPreviewUrl: {
single: 'Preview link copied'
}
};
export default class PostsContextMenu extends Component {
@service ajax;
@service ghostPaths;
@service session;
@service infinity;
@service store;
@service notifications;
@service membersUtils;
@service settings;
@inject config;
get menu() {
return this.args.menu;
}
get selectionList() {
return this.menu.selectionList;
}
get type() {
return this.selectionList.first?.displayName === 'page' ? 'page' : 'post';
}
#getToastMessage(type) {
if (this.selectionList.isSingle) {
return tpl(messages[type].single, {count: this.selectionList.count, type: this.type, Type: capitalizeFirstLetter(this.type)});
}
return tpl(messages[type].multiple, {count: this.selectionList.count, type: this.type, Type: capitalizeFirstLetter(this.type)});
}
@action
async copyPostLink() {
this.menu.performTask(this.copyPostLinkTask);
}
@action
async copyPreviewLink() {
this.menu.performTask(this.copyPreviewLinkTask);
}
@action
async featurePosts() {
this.menu.performTask(this.featurePostsTask);
}
@action
async unfeaturePosts() {
this.menu.performTask(this.unfeaturePostsTask);
}
@action
async addTagToPosts() {
await this.menu.openModal(AddPostTagsModal, {
type: this.type,
selectionList: this.selectionList,
confirm: this.addTagToPostsTask
});
}
@action
async deletePosts() {
this.menu.openModal(DeletePostsModal, {
type: this.type,
selectionList: this.selectionList,
confirm: this.deletePostsTask
});
}
@action
async unpublishPosts() {
await this.menu.openModal(UnpublishPostsModal, {
type: this.type,
selectionList: this.selectionList,
confirm: this.unpublishPostsTask
});
}
@action
async unschedulePosts() {
await this.menu.openModal(UnschedulePostsModal, {
type: this.type,
selectionList: this.selectionList,
confirm: this.unschedulePostsTask
});
}
@action
async editPostsAccess() {
this.menu.openModal(EditPostsAccessModal, {
type: this.type,
selectionList: this.selectionList,
confirm: this.editPostsAccessTask
});
}
@action
async copyPosts() {
this.menu.performTask(this.copyPostsTask);
}
@task
*addTagToPostsTask(tags) {
yield this.performBulkEdit('addTag', {
tags: tags.map((t) => {
return {
id: t.id,
name: t.name,
slug: t.slug
};
})
});
if (tags.length > 1) {
this.notifications.showNotification(this.#getToastMessage('tagsAdded'), {type: 'success'});
} else {
this.notifications.showNotification(this.#getToastMessage('tagAdded'), {type: 'success'});
}
// Destroy unsaved new tags (otherwise we could select them again)
this.store.peekAll('tag').forEach((tag) => {
if (tag.isNew) {
tag.destroyRecord();
}
});
// Re-fetch all updated posts so the client store is up-to-date
// Fetch in batches of 50 to avoid too-long URLs from all of the ObjectIDs
const updatedPosts = this.selectionList.availableModels;
const BATCH_SIZE = 50;
for (let i = 0; i < updatedPosts.length; i += BATCH_SIZE) {
const batch = updatedPosts.slice(i, i + BATCH_SIZE);
yield this.store.query('post', {filter: `id:[${batch.map(p => p.id).join(',')}]`});
}
// Remove posts that no longer match the filter
this.updateFilteredPosts();
return true;
}
@task
*deletePostsTask() {
const deletedModels = this.selectionList.availableModels;
yield this.performBulkDestroy();
this.notifications.showNotification(this.#getToastMessage('deleted'), {type: 'success'});
for (const key in this.selectionList.infinityModel) {
const remainingModels = this.selectionList.infinityModel[key].content.filter((model) => {
return !deletedModels.includes(model);
});
// Deleteobjects method from infintiymodel is broken for all models except the first page, so we cannot use this
this.infinity.replace(this.selectionList.infinityModel[key], remainingModels);
}
this.selectionList.clearSelection({force: true});
return true;
}
@task
*unpublishPostsTask() {
const updatedModels = this.selectionList.availableModels;
yield this.performBulkEdit('unpublish');
this.notifications.showNotification(this.#getToastMessage('unpublished'), {type: 'success'});
// Update the models on the client side
for (const post of updatedModels) {
if (post.status === 'published') {
// We need to do it this way to prevent marking the model as dirty
this.store.push({
data: {
id: post.id,
type: this.type,
attributes: {
status: 'draft'
}
}
});
}
}
this.updateFilteredPosts();
return true;
}
@task
*unschedulePostsTask() {
const updatedModels = this.selectionList.availableModels;
yield this.performBulkEdit('unschedule');
this.notifications.showNotification(this.#getToastMessage('unscheduled'), {type: 'success'});
// Update the models on the client side
for (const post of updatedModels) {
if (post.status === 'scheduled') {
// We need to do it this way to prevent marking the model as dirty
this.store.push({
data: {
id: post.id,
type: this.type,
attributes: {
status: 'draft',
published_at: null
}
}
});
}
}
this.updateFilteredPosts();
return true;
}
updateFilteredPosts() {
const updatedModels = this.selectionList.availableModels;
const filter = this.selectionList.allFilter;
const filterNql = nql(filter, {
expansions: [
{
key: 'primary_tag',
replacement: 'tags.slug',
expansion: 'posts_tags.sort_order:0+tags.visibility:public'
}, {
key: 'primary_author',
replacement: 'authors.slug',
expansion: 'posts_authors.sort_order:0+authors.visibility:public'
}, {
key: 'authors',
replacement: 'authors.slug'
}, {
key: 'author',
replacement: 'authors.slug'
}, {
key: 'tag',
replacement: 'tags.slug'
}, {
key: 'tags',
replacement: 'tags.slug'
}
]
});
for (const key in this.selectionList.infinityModel) {
const remainingModels = this.selectionList.infinityModel[key].content.filter((model) => {
if (!updatedModels.find(u => u.id === model.id)) {
return true;
}
return filterNql.queryJSON(model.serialize({includeId: true}));
});
// Deleteobjects method from infinitymodel is broken for all models except the first page, so we cannot use this
this.infinity.replace(this.selectionList.infinityModel[key], remainingModels);
}
this.selectionList.clearUnavailableItems();
}
@task
*editPostsAccessTask(close, {visibility, tiers}) {
const updatedModels = this.selectionList.availableModels;
yield this.performBulkEdit('access', {visibility, tiers});
this.notifications.showNotification(this.#getToastMessage('accessUpdated'), {type: 'success'});
// Update the models on the client side
for (const post of updatedModels) {
// We need to do it this way to prevent marking the model as dirty
this.store.push({
data: {
id: post.id,
type: this.type,
attributes: {
visibility,
tiers // tiers is a weird one, it's set up as an attribute but represents a relationship
}
}
});
}
// Remove posts that no longer match the filter
this.updateFilteredPosts();
close();
return true;
}
@task
*featurePostsTask() {
const updatedModels = this.selectionList.availableModels;
yield this.performBulkEdit('feature');
// Update the models on the client side
for (const post of updatedModels) {
// We need to do it this way to prevent marking the model as dirty
this.store.push({
data: {
id: post.id,
type: this.type,
attributes: {
featured: true
}
}
});
}
// Remove posts that no longer match the filter
this.updateFilteredPosts();
return true;
}
@task
*unfeaturePostsTask() {
const updatedModels = this.selectionList.availableModels;
yield this.performBulkEdit('unfeature');
// Update the models on the client side
for (const post of updatedModels) {
// We need to do it this way to prevent marking the model as dirty
this.store.push({
data: {
id: post.id,
type: this.type,
attributes: {
featured: false
}
}
});
}
// Remove posts that no longer match the filter
this.updateFilteredPosts();
return true;
}
@task
*copyPostsTask() {
try {
const result = yield this.performCopy();
// Add to the store and retrieve model
this.store.pushPayload(result);
const data = result[this.type === 'post' ? 'posts' : 'pages'][0];
const model = this.store.peekRecord(this.type, data.id);
// Update infinity draft posts content - copied posts are always drafts
if (this.selectionList.infinityModel.draftInfinityModel) {
this.selectionList.infinityModel.draftInfinityModel.content.unshiftObject(model);
}
// Show notification
this.notifications.showNotification(this.#getToastMessage('duplicated'), {type: 'success'});
} catch (error) {
this.notifications.showAPIError(error, {key: `${this.type}.copy.failed`});
}
return true;
}
@task
*copyPostLinkTask() {
copyTextToClipboard(this.selectionList.availableModels[0].url);
this.notifications.showNotification(this.#getToastMessage('copiedPostUrl'), {type: 'success'});
yield timeout(1000);
return true;
}
@task
*copyPreviewLinkTask() {
copyTextToClipboard(this.selectionList.availableModels[0].url);
this.notifications.showNotification(this.#getToastMessage('copiedPreviewUrl'), {type: 'success'});
yield timeout(1000);
return true;
}
async performBulkDestroy() {
const filter = this.selectionList.filter;
let bulkUpdateUrl = this.ghostPaths.url.api(this.type === 'post' ? 'posts' : 'pages') + `?filter=${encodeURIComponent(filter)}`;
return await this.ajax.delete(bulkUpdateUrl);
}
async performBulkEdit(_action, meta = {}) {
const filter = this.selectionList.filter;
let bulkUpdateUrl = this.ghostPaths.url.api(this.type === 'post' ? 'posts/bulk' : 'pages/bulk') + `?filter=${encodeURIComponent(filter)}`;
return await this.ajax.put(bulkUpdateUrl, {
data: {
bulk: {
action: _action,
meta
}
}
});
}
async performCopy() {
const id = this.selectionList.availableModels[0].id;
const copyUrl = this.ghostPaths.url.api(`${this.type === 'post' ? 'posts' : 'pages'}/${id}/copy`) + '?formats=mobiledoc,lexical';
return await this.ajax.post(copyUrl);
}
get shouldFeatureSelection() {
let featuredCount = 0;
for (const m of this.selectionList.availableModels) {
if (m.featured) {
featuredCount += 1;
}
}
return featuredCount <= this.selectionList.availableModels.length / 2;
}
get canFeatureSelection() {
for (const m of this.selectionList.availableModels) {
if (m.get('status') !== 'sent') {
return true;
}
}
return false;
}
get canUnpublishSelection() {
for (const m of this.selectionList.availableModels) {
if (m.status === 'published') {
return true;
}
}
return false;
}
get canUnscheduleSelection() {
for (const m of this.selectionList.availableModels) {
if (m.status === 'scheduled') {
return true;
}
}
return false;
}
get canCopySelection() {
return this.selectionList.availableModels.length === 1;
}
// site navigation --------------------------------------------------------
// a nav link points at the page's published URL, so only published pages can
// be placed in navigation - linking a draft/scheduled page would 404. Draft
// pages set their placement at publish time via the publish flow instead.
get canManageNavigation() {
return this.type === 'page'
&& this.session.user.isAdmin
&& this.selectionList.availableModels.every(model => model.status === 'published');
}
get selectedPagePlacements() {
return this.selectionList.availableModels
.map(model => getPagePlacement(this.settings, pagePathForSlug(model.slug, this.config.blogUrl), this.config.blogUrl));
}
get isSingleSelection() {
return this.selectionList.availableModels.length === 1;
}
// current placement when exactly one page is selected, otherwise null
get singleNavigationPlacement() {
return this.isSingleSelection ? this.selectedPagePlacements[0] : null;
}
// only offer a destination the selection isn't already entirely in
get canAddToPrimaryNavigation() {
return this.selectedPagePlacements.some(placement => placement !== 'primary');
}
get canAddToSecondaryNavigation() {
return this.selectedPagePlacements.some(placement => placement !== 'secondary');
}
get canRemoveFromNavigation() {
return this.selectedPagePlacements.some(placement => placement !== null);
}
// a single already-linked page is moved between menus rather than added
get primaryNavigationActionLabel() {
return this.singleNavigationPlacement === 'secondary' ? 'Move to primary navigation' : 'Add to primary navigation';
}
get secondaryNavigationActionLabel() {
return this.singleNavigationPlacement === 'primary' ? 'Move to secondary navigation' : 'Add to secondary navigation';
}
@action
addToPrimaryNavigation() {
this.menu.performTask({perform: () => this.updateNavigationPlacementTask.perform('primary')});
}
@action
addToSecondaryNavigation() {
this.menu.performTask({perform: () => this.updateNavigationPlacementTask.perform('secondary')});
}
@action
removeFromNavigation() {
this.menu.performTask({perform: () => this.updateNavigationPlacementTask.perform('none')});
}
@task
*updateNavigationPlacementTask(placement) {
const pages = this.selectionList.availableModels
.map(model => ({label: model.title, path: pagePathForSlug(model.slug, this.config.blogUrl)}));
const count = pages.length;
// a single already-linked page is moved rather than added
const isMove = count === 1 && this.singleNavigationPlacement && this.singleNavigationPlacement !== placement;
try {
yield setPagesNavigationPlacement(this.settings, {
pages,
placement: placement === 'none' ? null : placement,
blogUrl: this.config.blogUrl
});
let message;
if (placement === 'none') {
message = count > 1 ? `${count} pages removed from navigation` : 'Page removed from navigation';
} else if (isMove) {
message = `Page moved to ${placement} navigation`;
} else {
message = count > 1 ? `${count} pages added to ${placement} navigation` : `Page added to ${placement} navigation`;
}
this.notifications.showNotification(message, {type: 'success'});
} catch (error) {
this.notifications.showAPIError(error, {key: 'navigation.save'});
}
return true;
}
}