1 define(function(require) {
6 var _ = require('libs/underscore'),
7 templates = require('plugins/core/templates'),
8 footnote = require('plugins/core/footnote'),
9 switchTo = require('plugins/core/switch'),
10 lists = require('plugins/core/lists'),
11 plugin = {name: 'core', actions: [], canvas: {}, documentExtension: {textNode: {}, elementNode: {}}},
12 Dialog = require('views/dialog/dialog'),
13 canvasElements = require('plugins/core/canvasElements'),
14 metadataEditor = require('plugins/core/metadataEditor/metadataEditor');
18 plugin.documentExtension.textNode.transformations = {
20 impl: function(args) {
22 isSpan = node.parent().getTagName() === 'span',
23 parentDescribingNodes = [],
25 newNodes = node.split({offset: args.offset});
26 newNodes.second.contents()
27 .filter(function(child) {
28 return child.object.describesParent;
30 .forEach(function(child) {
32 parentDescribingNodes.push(child);
35 [newNodes.first, newNodes.second].some(function(newNode) {
36 if(!(newNode.contents().length)) {
37 emptyText = newNode.append({text: ''});
41 parentDescribingNodes.forEach(function(node) {
42 newNodes.first.append(node);
47 var copyNode = function(n) {
49 n.getAttrs().forEach(function(attr) {
50 attrs[attr.name] = attr.value;
53 return node.document.createDocumentNode({
54 tagName: n.getTagName(),
59 var move = function(node, to) {
61 if(!node.containsNode(newNodes.second)) {
65 if(!node.sameNode(newNodes.second)) {
66 copy = to.append(copyNode(node));
67 node.contents().some(function(n) {
76 newNodes.first.parents().some(function(p) {
77 if(p.getTagName() !== 'span') {
82 newNode = parent.before({tagName: parent.getTagName(), attrs: {'class': parent.getClass()}});
83 parent.contents().some(function(n) {
84 return move(n, newNode);
88 return _.extend(newNodes, {emptyText: emptyText});
91 mergeContentUp: function() {
97 if(myPrev.nodeType === Node.TEXT_NODE) {
98 if(myPrev.getIndex() > 0) {
101 myPrev = base = myPrev.parent();
104 myPrev = myPrev && myPrev.prev();
106 if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE) {
112 ret = myPrev.append(ptr);
122 return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
127 plugin.documentExtension.elementNode.transformations = {
130 prev = toMerge.prev();
132 var merge = function(from, to) {
134 from.contents().forEach(function(node, idx) {
136 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
137 len = node.getText().length;
139 ret = to.append(node);
144 offset: ret.getText().length - len
154 applies: function() {
155 return toMerge.is('p');
158 if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
159 return merge(toMerge, prev);
161 if(prev && prev.is('list')) {
162 var items = prev.contents().filter(function(n) { return n.is('item');});
163 return merge(toMerge, items[items.length-1]);
168 applies: function() {
169 return toMerge.is({tagName: 'header'});
172 if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
173 return merge(toMerge, prev);
178 applies: function() {
179 return toMerge.is('item');
183 if(prev && prev.is('item')) {
184 return merge(toMerge, prev);
185 } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
186 list.before(toMerge);
187 toMerge.setClass('p');
188 if(!list.contents().length) {
191 return {node: toMerge.contents()[0], offset:0};
198 strategies.some(function(strategy) {
199 if(strategy.applies()) {
200 toret = strategy.run();
208 var undoRedoAction = function(dir) {
212 document: {type: 'context', name: 'document'},
215 label: dir === 'undo' ? '<-' : '->',
217 iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
218 execute: function(callback, params) {
219 var metadata = _.last(params.document[dir+'Stack']).metadata,
220 fragment = metadata && metadata.fragment;
221 params.document[dir]();
223 if(!fragment.isValid()) {
224 fragment.restoreFromPaths();
226 if(fragment.isValid()) {
233 getState: function(params) {
234 var allowed = params.document && !!(params.document[dir+'Stack'].length),
235 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
236 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
238 var metadata = _.last(params.document[dir+'Stack']).metadata;
240 desc += ': ' + (metadata.description || gettext('unknown operation'));
245 description: allowed ? desc : descEmpty
251 var pad = function(number) {
253 number = '0' + number;
258 var commentAction = {
261 fragment: {type: 'context', name: 'fragment'}
265 execute: function(callback, params, editor) {
267 var node = params.fragment.node,
269 if(node.nodeType === Node.TEXT_NODE) {
270 node = node.parent();
272 node.document.transaction(function() {
273 var comment = node.after({tagName: 'aside', attrs: {'class': 'comment'}});
274 comment.append({text:''});
275 var user = editor.getUser(), creator;
279 creator += ' (' + user.email + ')';
282 creator = 'anonymous';
285 var currentDate = new Date(),
286 dt = pad(currentDate.getDate()) + '-' +
287 pad((currentDate.getMonth() + 1)) + '-' +
288 pad(currentDate.getFullYear()) + ' ' +
289 pad(currentDate.getHours()) + ':' +
290 pad(currentDate.getMinutes()) + ':' +
291 pad(currentDate.getSeconds());
293 var metadata = comment.getMetadata();
294 metadata.add({key: 'creator', value: creator});
295 metadata.add({key: 'date', value: dt});
298 description: action.getState().description
304 getState: function(params) {
306 allowed: params.fragment && params.fragment.isValid() &&
307 params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
310 state.description = gettext('Insert comment');
317 var createWrapTextAction = function(createParams) {
319 name: createParams.name,
321 fragment: {type: 'context', name: 'fragment'},
323 getState: function(params) {
325 label: this.config.label
329 if(!params.fragment || !params.fragment.isValid()) {
330 return _.extend(state, {allowed: false});
333 if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
334 return _.extend(state, {
337 description: createParams.unwrapDescription,
338 execute: function(callback, params) {
339 var node = params.fragment.node,
341 toRemove = node.getParent(createParams.klass),
344 if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
345 prefLen = toRemove.prev().getText().length;
348 doc.transaction(function() {
349 var ret = toRemove.unwrapContent(),
350 newFragment = params.fragment;
351 if(!newFragment.isValid()) {
352 newFragment = doc.createFragment(doc.CaretFragment, {
354 offset: prefLen + params.fragment.offset
360 description: createParams.unwrapDescription,
361 fragment: params.fragment
369 if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
370 parent = params.fragment.startNode.parent();
371 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
372 return _.extend(state, {allowed: false});
375 return _.extend(state, {
377 description: createParams.wrapDescription,
378 execute: function(callback, params) {
379 params.fragment.document.transaction(function() {
380 var parent = params.fragment.startNode.parent(),
381 doc = params.fragment.document,
382 wrapper, lastTextNode;
384 wrapper = parent.wrapText({
385 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
386 offsetStart: params.fragment.startOffset,
387 offsetEnd: params.fragment.endOffset,
388 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
391 lastTextNode = wrapper.getLastTextNode();
393 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
397 description: createParams.wrapDescription,
398 fragment: params.fragment
405 return _.extend(state, {allowed: false});
411 var createLinkFromSelection = function(callback, params) {
412 var doc = params.fragment.document,
413 dialog = Dialog.create({
414 title: gettext('Create link'),
415 executeButtonText: gettext('Apply'),
416 cancelButtonText: gettext('Cancel'),
418 {label: gettext('Link'), name: 'href', type: 'input',
419 prePasteHandler: function(text) {
420 return params.fragment.document.getLinkForUrl(text);
427 dialog.on('execute', function(event) {
428 doc.transaction(function() {
429 var span = action.params.fragment.startNode.parent().wrapText({
430 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
431 offsetStart: params.fragment.startOffset,
432 offsetEnd: params.fragment.endOffset,
433 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
435 doc = params.fragment.document;
437 return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
440 description: action.getState().description,
441 fragment: params.fragment
449 var editLink = function(callback, params) {
450 var doc = params.fragment.document,
451 link = params.fragment.node.getParent('link'),
452 dialog = Dialog.create({
453 title: gettext('Edit link'),
454 executeButtonText: gettext('Apply'),
455 cancelButtonText: gettext('Cancel'),
457 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
462 dialog.on('execute', function(event) {
463 doc.transaction(function() {
464 link.setAttr('href', event.formData.href);
466 return params.fragment;
469 description: action.getState().description,
470 fragment: params.fragment
481 fragment: {type: 'context', name: 'fragment'}
484 label: gettext('link')
486 getState: function(params) {
487 if(!params.fragment || !params.fragment.isValid()) {
488 return {allowed: false};
491 if(params.fragment instanceof params.fragment.TextRangeFragment) {
492 if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
493 return {allowed: false};
497 description: gettext('Create link from selection'),
498 execute: createLinkFromSelection
502 if(params.fragment instanceof params.fragment.CaretFragment) {
503 if(params.fragment.node.isInside('link')) {
507 description: gettext('Edit link'),
512 return {allowed: false};
516 var metadataParams = {};
519 undoRedoAction('undo'),
520 undoRedoAction('redo'),
522 createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
523 createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
525 metadataEditor.action(metadataParams)
526 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
530 plugin.config = function(config) {
531 // templates.actions[0].config(config.templates);
532 templates.actions[0].params.template.options = config.templates;
533 metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
534 if(configRow1.key < configRow2.key) {
537 if(configRow1.key > configRow2.key) {
544 plugin.canvasElements = canvasElements;