/
file.js
1401 lines (1170 loc) · 39.5 KB
/
file.js
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var CodeMirror = require('codemirror');
var $ = require('jquery-browserify');
var _ = require('underscore');
var queue = require('queue-async');
var jsyaml = require('js-yaml');
var patch = require('../../vendor/liquid.patch');
var Handsontable = require('handsontable');
var Papa = require('papaparse');
var ModalView = require('./modal');
var marked = require('marked');
var diff = require('diff');
var Backbone = require('backbone');
var File = require('../models/file');
var HeaderView = require('./header');
var ToolbarView = require('./toolbar');
var MetadataView = require('./metadata');
var auth = require('../config');
var util = require('../util');
var upload = require('../upload');
var cookie = require('../cookie');
var templates = require('../../dist/templates');
module.exports = Backbone.View.extend({
id: 'post',
template: templates.file,
subviews: {},
initialize: function(options) {
_.bindAll(this);
var app = options.app;
app.loader.start();
// Patch Liquid
patch.apply(this);
this.app = app;
this.branch = options.branch || options.repo.get('default_branch');
this.branches = options.branches;
this.mode = options.mode;
this.nav = options.nav;
this.path = options.path || '';
this.repo = options.repo;
this.router = options.router;
this.sidebar = options.sidebar;
// Set the active nav element established by this.mode
this.nav.setFileState(this.mode);
// Events from vertical nav
this.listenTo(this.nav, 'edit', this.edit);
this.listenTo(this.nav, 'blob', this.blob);
this.listenTo(this.nav, 'meta', this.meta);
this.listenTo(this.nav, 'settings', this.settings);
this.listenTo(this.nav, 'save', this.showDiff);
// Events from sidebar
this.listenTo(this.sidebar, 'destroy', this.destroy);
this.listenTo(this.sidebar, 'toggle-editor', this.toggleEditor);
this.listenTo(this.sidebar, 'draft', this.draft);
this.listenTo(this.sidebar, 'cancel', this.cancel);
this.listenTo(this.sidebar, 'confirm', this.updateFile);
this.listenTo(this.sidebar, 'translate', this.translate);
// Stash editor and metadataEditor content to sessionStorage on pagehide event
this.listenTo($(window), 'pagehide', this.stashFile);
// Prevent exit when there are unsaved changes
// jQuery won't bind to 'beforeunload' event
// e.returnValue for Firefox compatibility
// https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload
window.onbeforeunload = (function(e) {
if (this.dirty) {
var message = t('actions.unsaved');
(e || window.event).returnValue = message;
return message;
}
}).bind(this);
this.branches.fetch({
success: this.setCollection,
error: (function(model, xhr, options) {
this.router.error(xhr);
}).bind(this),
complete: app.loader.done
});
},
setCollection: function() {
this.app.loader.start();
this.collection = this.branches.findWhere({ name: this.branch }).files;
this.collection.fetch({
success: this.setModel,
error: (function(model, xhr, options) {
this.router.error(xhr);
}).bind(this),
complete: this.app.loader.done,
args: arguments
});
},
setModel: function() {
this.app.loader.start();
// Set model either by calling directly for new File models
// or by filtering collection for existing File models
switch(this.mode) {
case 'edit':
case 'blob':
this.model = this.collection.findWhere({ path: this.path });
break;
case 'preview':
this.model = this.collection.findWhere({ path: this.path });
if (!this.model) {
// We may be trying to preview a new file that only has
// stashed information lets check and create a dummy model
var previewPath = this.absolutePathFromComponents (
this.repo.get('owner').login,
this.repo.get('name'),
this.branch,
this.path
);
if (this.getStashForPath(previewPath)) {
this.model = this.newEmptyFile();
}
}
break;
case 'new':
this.model = this.newEmptyFile();
break;
}
// Set default metadata from collection
var defaults = this.collection.defaults;
var path;
if (this.model) {
if (defaults) {
path = this.nearestPath(this.model.get('path'), defaults);
this.model.set('defaults', defaults[path]);
}
// Render on complete to render even if model does not exist on remote yet
this.model.fetch({
complete: (function() {
this.app.loader.done();
this.render();
}).bind(this)
});
} else {
this.router.notify(
t('notification.error.exists'),
undefined,
[
{
'title': t('notification.create'),
'className': 'create',
'link': '#'
},
{
'title': t('notification.back'),
'link': '#' + _.compact([
this.repo.get('owner').login,
this.repo.get('name'),
'tree',
this.branch,
util.extractFilename(this.path)[0]
]).join('/')
}
]
);
this.app.loader.done();
}
},
newEmptyFile: function() {
return new File({
branch: this.branches.findWhere({ name: this.branch }),
collection: this.collection,
path: this.path,
repo: this.repo
});
},
nearestPath: function(path, defaults) {
// Match nearest parent directory default metadata
// Match paths in _drafts to corresponding defaults set at _posts
path = path.replace(/^(_drafts)/, '_posts');
var nearestDir = /\/?(?!.*\/).*$/;
while (!_.has(defaults, path) && nearestDir.test(path) && path) {
path = path.replace( nearestDir, '' );
}
return path;
},
cursor: function() {
var view = this;
var selection = util.trim(this.editor.getSelection());
var match = {
lineBreak: /\n/,
h1: /^#{1}/,
h2: /^#{2}/,
h3: /^#{3}/,
h4: /^#{4}/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
italic: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
isNumber: parseInt(selection.charAt(0), 10)
};
if (!match.isNumber) {
switch (selection.charAt(0)) {
case '#':
if (!match.lineBreak.test(selection)) {
if (match.h3.test(selection) && !match.h4.test(selection)) {
this.toolbar.highlight('sub-heading');
} else if (match.h2.test(selection) && !match.h3.test(selection)) {
this.toolbar.highlight('heading');
}
}
break;
case '>':
this.toolbar.highlight('quote');
break;
case '*':
case '_':
if (!match.lineBreak.test(selection)) {
if (match.strong.test(selection)) {
// trigger a change
this.toolbar.highlight('bold');
} else if (match.italic.test(selection)) {
this.toolbar.highlight('italic');
}
}
break;
case '!':
if (!match.lineBreak.test(selection) &&
selection.charAt(1) === '[' &&
selection.charAt(selection.length - 1) === ')') {
this.toolbar.highlight('media');
}
break;
case '[':
if (!match.lineBreak.test(selection) &&
selection.charAt(selection.length - 1) === ')') {
this.toolbar.highlight('link');
}
break;
case '-':
if (selection.charAt(1) === ' ') {
this.toolbar.highlight('list');
}
break;
default:
if (this.toolbar) this.toolbar.highlight();
break;
}
} else {
if (selection.charAt(1) === '.' && selection.charAt(2) === ' ') {
this.toolbar.highlight('numbered-list');
}
}
},
compilePreview: function(content) {
// Scan the content search for ![]()
// grab the path and file and form a RAW github aboslute request for it
var scan = /\!\[([^\[]*)\]\(([^\)]+)\)/g;
var image = /\!\[([^\[]*)\]\(([^\)]+)\)/;
var titleAttribute = /".*?"/;
// Build an array of found images
var results = content.match(scan);
// Iterate over the results and replace
_.each(results, (function(r) {
var parts = (image).exec(r);
var path;
if (parts !== null) {
path = parts[2];
if (!util.absolutePath(path)) {
// Remove any title attribute in the image tag is there is one.
if (titleAttribute.test(path)) {
path = path.split(titleAttribute)[0];
}
// Remove {{site.baseurl}}
path = path.replace('{{site.baseurl}}/', '/');
// Prepend directory path if not site root relative
path = /^\//.test(path) ? path.slice(1) :
util.extractFilename(this.model.get('path'))[0] + '/' + path;
var url = auth.site + '/' + this.repo.get('owner').login + '/' + this.repo.get('name') + '/blob/' + this.branch + '/' + window.escape(path) + '?raw=true';
content = content.replace(r, '![' + parts[1] + '](' + url + ')');
}
}
}).bind(this));
return _.escape(content);
},
toggleEditor: function() {
cookie.set('disableCSVEditor', !cookie.get('disableCSVEditor'))
this.render();
},
parseCSV: function(csvString) {
return Papa.parse(util.trim(csvString), { // remove trailing whitespace, mholt/PapaParse#279
skipEmptyLines: true
});
},
initCSVEditor: function() {
var self = this;
var $container = this.$el.find('#csv');
var container = $container[0];
var data = this.parseCSV(this.model.get('content'))
var distanceFromTop = $container.offset().top;
var documentHeight = $(document).height();
var editorHeight = documentHeight - distanceFromTop;
this.editor = new Handsontable(container, {
data: data.data,
colHeaders: true,
rowHeaders: true,
stretchH: 'all',
height: editorHeight,
fixedRowsTop: 1,
manualColumnResize: true,
manualRowResize: true,
contextMenu: ['row_above', 'row_below', 'col_left', 'col_right', 'remove_row', 'remove_col', 'undo', 'redo'],
undo: true,
afterChange: function(changes, source) {
if (source !== 'loadData') self.makeDirty();
}
})
this.editor.getValue = function() {
return Papa.unparse(this.getSourceData());
};
this.editor.setValue = function(newValue) {
var parsedValue = self.parseCSV(newValue);
this.loadData(parsedValue.data);
self.makeDirty();
};
// Check sessionStorage for existing stash
// Apply if stash exists and is current, remove if expired
this.stashApply();
},
initEditor: function() {
var lang = this.model.get('lang');
var code = this.$el.find('#code')[0];
code.value = this.model.get('content') || '';
// TODO: set default content for CodeMirror
this.editor = CodeMirror.fromTextArea(code, {
mode: lang,
lineWrapping: true,
lineNumbers: (lang === 'gfm' || lang === null) ? false : true,
extraKeys: this.keyMap(),
matchBrackets: true,
dragDrop: false,
theme: 'prose-bright'
});
// Bind Drag and Drop work on the editor
if (this.model.get('markdown') && this.model.get('writable')) {
upload.dragDrop(this.$el, (function(e, file, content) {
if (this.$el.find('#dialog').hasClass('dialog')) {
this.updateImageInsert(e, file, content);
} else {
// Clear selection
this.editor.focus();
this.editor.replaceSelection('');
// Append images links in this.upload()
this.upload(e, file, content);
}
}).bind(this));
}
// Monitor the current selection and apply
// an active class to any snippet links
if (lang === 'gfm') {
this.listenTo(this.editor, 'cursorActivity', this.cursor);
}
this.listenTo(this.editor, 'change', this.makeDirty, this);
this.listenTo(this.editor, 'focus', this.focus, this);
this.refreshCodeMirror();
// Check sessionStorage for existing stash
// Apply if stash exists and is current, remove if expired
this.stashApply();
},
keyMap: function() {
var self = this;
if (this.model.get('markdown')) {
return {
'Ctrl-Enter': function (codemirror) {
self.blob();
},
'Ctrl-S': function(codemirror) {
self.updateFile();
},
'Cmd-B': function(codemirror) {
if (self.editor.getSelection() !== '') self.toolbar.bold(self.editor.getSelection());
},
'Ctrl-B': function(codemirror) {
if (self.editor.getSelection() !== '') self.toolbar.bold(self.editor.getSelection());
},
'Cmd-I': function(codemirror) {
if (self.editor.getSelection() !== '') self.toolbar.italic(self.editor.getSelection());
},
'Ctrl-I': function(codemirror) {
if (self.editor.getSelection() !== '') self.toolbar.italic(self.editor.getSelection());
}
};
} else {
return {
'Ctrl-S': function(codemirror) {
self.updateFile();
}
};
}
},
focus: function() {
// If an upload queue is set, we want to clear it.
this.queue = undefined;
// If a dialog window is open and the editor is in focus, close it.
this.$el.find('.toolbar .group a').removeClass('on');
this.$el.find('#dialog').empty().removeClass();
},
initToolbar: function() {
this.toolbar = new ToolbarView({
view: this,
file: this.model,
collection: this.collection,
config: this.config
});
this.subviews['toolbar'] = this.toolbar;
this.toolbar.setElement(this.$el.find('#toolbar')).render();
this.listenTo(this.toolbar, 'updateImageInsert', this.updateImageInsert);
this.listenTo(this.toolbar, 'post', this.post);
},
titleAsHeading: function() {
// If the file is Markdown, has metadata for a title,
// the editable field in the header should be
// the title of the Markdown document.
var metadata = this.model.get('metadata');
if (this.model.get('markdown')) {
// 1. A title exists in a files current metadata
if (metadata && metadata.title) {
return metadata.title;
// 2. A title does not exist and should be checked in the defaults
} else if (this.model.get('defaults')) {
var defaultTitle = _(this.model.get('defaults')).find(function(t) {
return t.name == 'title';
});
if (defaultTitle) {
if (defaultTitle.field && defaultTitle.field.value) {
return defaultTitle.field.value;
} else {
// 3. If a title entry is in the defaults but with no
// default value, use an untitled placeholder message.
// return t('main.file.noTitle');
return t('main.file.noTitle');
}
} else {
return false;
}
} else {
// This is not a Markdown post, bounce
// TODO: Should this handle _posts/name.html?
return false;
}
}
},
initSidebar: function() {
// Settings sidebar panel
this.settings = this.sidebar.initSubview('settings', {
sidebar: this.sidebar,
config: this.collection.config,
file: this.model,
fileInput: this.titleAsHeading()
}).render();
this.subviews['settings'] = this.settings;
this.listenTo(this.sidebar, 'makeDirty', this.makeDirty);
// Commit message sidebar panel
this.save = this.sidebar.initSubview('save', {
sidebar: this.sidebar,
file: this.model
}).render();
this.subviews['save'] = this.save;
},
initHeader: function() {
var title = this.titleAsHeading();
var input = title ?
title :
this.model.get('path');
this.header = new HeaderView({
input: input,
title: title ? true : false,
file: this.model,
repo: this.repo,
alterable: true,
placeholder: this.model.isNew() && !this.model.translate && !this.model.isClone()
});
this.subviews['header'] = this.header;
this.header.setElement(this.$el.find('#heading')).render();
this.listenTo(this.header, 'makeDirty', this.makeDirty);
},
renderMetadata: function() {
this.metadataEditor = new MetadataView({
model: this.model,
titleAsHeading: this.titleAsHeading(),
view: this
});
this.metadataEditor.setElement(this.$el.find('#meta')).render();
this.subviews['metadata'] = this.metadataEditor;
},
render: function() {
this.app.loader.start();
if (this.mode === 'preview') {
this.preview();
} else {
var content = this.model.get('content');
var file = {
markdown: this.model.get('markdown'),
lang: this.model.get('lang'),
useCSVEditor: (['csv', 'tsv'].indexOf(this.model.get('lang')) !== -1 && !cookie.get('disableCSVEditor'))
};
this.$el.empty().append(_.template(this.template, file, {
variable: 'file'
}));
// Store the configuration object from the collection
this.config = this.model.get('collection').config;
// initialize the subviews
if (file.useCSVEditor) {
this.initCSVEditor();
} else {
this.initEditor();
}
this.initHeader();
this.initToolbar();
this.initSidebar();
var mode = ['file'];
var markdown = this.model.get('markdown');
var jekyll = /^(_posts|_drafts)/.test(this.model.get('path'));
// Update the navigation view with menu options
// if a file contains metadata, has default metadata or is Markdown (except CSVs)
if (!file.useCSVEditor && (this.model.get('metadata') || this.model.get('defaults') || (markdown && jekyll))) {
this.renderMetadata();
mode.push('meta');
}
if (markdown || this.model.get('extension') === 'html') mode.push('preview');
if (!this.model.isNew()) mode.push('settings');
this.nav.mode(mode.join(' '));
this.updateDocumentTitle();
// Preview needs access to marked, so it's registered here
Liquid.Template.registerFilter({
'markdownify': function(input) {
return marked(input || '');
}
});
if (this.model.get('markdown') && this.mode === 'blob') {
this.blob();
} else {
// Editor is first up so trigger an active class for it
this.$el.find('#edit').toggleClass('active', true);
this.$el.find('.file .edit').addClass('active');
if (this.model.get('markdown')) {
util.fixedScroll(this.$el.find('.topbar'), 90);
}
}
if (this.mode === 'blob') {
this.blob();
}
}
this.app.loader.done();
return this;
},
updateDocumentTitle: function() {
var context = (this.mode === 'blob' ? t('docheader.preview') : t('docheader.editing'));
var path = this.model.get('path');
var pathTitle = path ? path : '';
util.documentTitle(context + ' ' + pathTitle + '/' + this.model.get('name') + ' at ' + this.branch);
},
edit: function() {
var view = this;
this.sidebar.close();
// If preview was hit on load this.editor
// was not initialized.
if (!this.editor) {
this.initEditor();
if (this.model.get('markdown')) {
_.delay(function() {
util.fixedScroll($('.topbar', view.el), 90);
}, 1);
}
}
$('#prose').toggleClass('open', false);
this.contentMode('edit');
this.mode = this.model.isNew() ? 'new' : 'edit';
this.nav.setFileState(this.mode);
this.updateURL();
},
blob: function(e) {
this.sidebar.close();
var metadata = this.model.get('metadata');
var jekyll = this.config && this.config.siteurl && metadata && metadata.layout;
if (jekyll && e) {
// TODO: this could all be removed if preview button listened to
// change:path event on model
this.nav.setFileState('edit'); // Return to edit because we are creating a new window
this.stashFile();
var hash = this.absoluteFilepath().split('/');
hash.splice(2, 0, 'preview');
$(e.currentTarget).attr({
target: '_blank',
href: '#' + hash.join('/')
});
} else {
if (e) e.preventDefault();
this.$el.find('#preview').html(marked(this.compilePreview(this.model.get('content'))));
this.mode = 'blob';
this.contentMode('preview');
this.nav.setFileState('blob');
this.updateURL();
}
},
preview: function() {
var q = queue(1);
// Retrieve the stash from the model path because thats what would
// have been stored when the preview button is clicked
var stash = this.getStashForPath(this.absolutePathFromFile(this.model));
var metadata = {};
var content = '';
if (stash && stash.content) {
metadata = stash.metadata;
content = stash.content;
} else {
metadata = this.model.get('metadata') || {};
content = this.model.get('content') || '';
}
// Run the liquid parsing.
var parsedTemplate = Liquid.parse(this.compilePreview(content)).render({
site: this.collection.config,
post: metadata,
page: metadata
});
// If it's markdown, run it through marked; otherwise, leave it alone.
if(this.model.get('markdown')) parsedTemplate = marked(parsedTemplate);
var p = {
site: this.collection.config,
post: metadata,
page: metadata,
content: parsedTemplate || ''
};
// Grab a date from the filename
// and add this post to be evaluated as {{post.date}}
var parts = util.extractFilename(this.path)[1].split('-');
var year = parts[0];
var month = parts[1];
var day = parts[2];
// TODO: remove EST specific time adjustment
var date = [year, month, day].join('-') + ' 05:00:00';
try {
p.post.date = jsyaml.safeLoad(date).toDateString();
} catch(err) {
console.log("Error parsing date");
console.log(err);
}
// Parse JSONP links
if (p.site && p.site.site) {
_(p.site.site).each(function(file, key) {
q.defer(function(cb){
var next = false;
$.ajax({
cache: true,
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'callback',
url: file,
timeout: 5000,
success: function(d) {
p.site[key] = d;
next = true;
cb();
},
error: function(msg, b, c) {
if (!next) cb();
}
});
});
});
}
function getLayout(cb) {
var file = p.page.layout;
var layout = this.collection.findWhere({ path: '_layouts/' + file + '.html' });
layout.fetch({
success: (function(model, res, options) {
model.getContent({
success: (function(model, res, options) {
var meta = model.get('metadata');
var content = model.get('content');
var template = Liquid.parse(content);
p.page = _.extend(metadata, meta);
p.content = template.render({
site: p.site,
post: p.post,
page: p.page,
content: p.content
});
// Handle nested layouts
if (meta && meta.layout) q.defer(getLayout.bind(this));
cb();
}).bind(this),
error: (function(model, xhr, options) {
this.router.error(xhr);
}).bind(this)
});
}).bind(this),
error: (function(model, xhr, options) {
this.router.error(xhr);
}).bind(this)
});
}
if (p.page.layout) {
q.defer(getLayout.bind(this));
}
q.await((function() {
var config = this.collection.config;
var content = p.content;
// Set base URL to public site
if (config && config.siteurl) {
content = content.replace(/(<head(?:.*)>)/, (function() {
return arguments[1] + '<base href="' + config.siteurl + '">';
}).bind(this));
}
document.write(content);
document.close();
}).bind(this));
},
contentMode: function(mode) {
this.$el.find('.views .view').removeClass('active');
if (mode) {
this.$el.find('#' + mode).addClass('active');
} else {
if (this.mode === 'blob') {
this.$el.find('#preview').addClass('active');
} else {
this.$el.find('#edit').addClass('active');
}
}
},
meta: function() {
this.sidebar.close();
this.contentMode('meta');
// Refresh any textarea's in the frontmatter form that use codemirror
this.metadataEditor.refresh();
},
destroy: function() {
if (confirm(t('actions.delete.warn'))) {
this.model.destroy({
success: (function() {
this.router.navigate([
this.repo.get('owner').login,
this.repo.get('name'),
'tree',
this.branch
].join('/'), true);
}).bind(this),
error: (function(model, xhr, options) {
this.router.error(xhr);
}).bind(this)
});
}
},
updateURL: function() {
var url = _.compact([
this.repo.get('owner').login,
this.repo.get('name'),
this.mode,
this.branch,
this.path
]);
this.router.navigate(url.join('/'), {
trigger: false,
replace: true
});
this.updateDocumentTitle();
// TODO: what is this updating?
this.$el.find('.chzn-select').trigger('liszt:updated');
},
makeDirty: function(e) {
this.dirty = true;
// Update Content.
if (this.editor && this.editor.getValue) {
this.model.set('content', this.editor.getValue());
}
var label = this.model.get('writable') ?
t('actions.change.save') :
t('actions.change.submit');
this.updateSaveState(label, 'save');
},
settings: function() {
this.contentMode();
this.sidebar.mode('settings');
this.sidebar.open();
},
showDiff: function() {
this.contentMode('diff');
this.sidebar.mode('save');
this.sidebar.open();
var $diff = this.$el.find('#diff');
// Use _.escape() to prevent rendering HTML tags
var text1 = this.model.isNew() ? '' : _.escape(this.model.get('previous'));
var text2 = _.escape(this.model.serialize());
var d = diff.diffWords(text1, text2);
var length = d.length;
var compare = '';
for (var i = 0; i < length; i++) {
if (d[i].removed) {
compare += '<del>' + d[i].value + '</del>';
} else if (d[i].added) {
compare += '<ins>' + d[i].value + '</ins>';
} else {
compare += d[i].value;
}
}
$diff.find('.diff-content').html('<pre>' + compare + '</pre>');
},
cancel: function() {
// Close the sidebar and return the
// active nav item to the current file mode.
this.sidebar.close();
this.nav.active(this.mode);
// Return back to old mode.
this.contentMode();
},
refreshCodeMirror: function() {
if (typeof this.editor.refresh === 'function') this.editor.refresh();
},
updateMetaData: function() {
if (!this.model.jekyll) return true; // metadata -> skip
this.model.metadata = this.metadataEditor.getValue();
return true;
},
patch: function() {
// Submit a patch (fork + pull request workflow)
this.updateSaveState(t('actions.save.patch'), 'saving');
// view.updateMetaData();
this.model.patch({
success: (function(res) {
/*
// TODO: revert to previous state?
var previous = view.model.get('previous');
this.model.content = previous;
this.editor.setValue(previous);
this.dirty = false;
this.model.persisted = true;
this.model.file = filename;
this.model.set('previous', filecontent);
*/
// TODO: why is this breaking?
// this.toolbar.updatePublishState();
this.updateURL();
this.sidebar.close();
this.updateSaveState(t('actions.save.submission'), 'saved');
}).bind(this),
error: (function(model, xhr, options) {
var message = util.xhrErrorMessage(xhr);
this.updateSaveState(message, 'error');
}).bind(this)
});
},
filepath: function() {
if (this.titleAsHeading()) {
return this.sidebar.filepathGet();
} else {