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: {}, documentNode: {}}},
12 Dialog = require('views/dialog/dialog'),
13 canvasElements = require('plugins/core/canvasElements'),
14 metadataEditor = require('plugins/core/metadataEditor/metadataEditor'),
15 edumed = require('plugins/core/edumed/edumed');
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.documentNode.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);
141 if(idx === 0 && ret.nodeType === Node.TEXT_NODE) {
144 offset: ret.getText().length - len
148 node: ret.getFirstTextNode(),
159 applies: function() {
160 return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
163 var textNode = prev.getLastTextNode(),
164 txt, prevText, prevTextLen;
166 txt = textNode.getText();
168 textNode.setText(txt.substr(0, txt.length-1));
169 return {node: toMerge, offset: 0};
171 if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
172 prevTextLen = prevText.getText().length;
176 node: prevText ? prevText : toMerge,
177 offset : prevText ? prevTextLen : 0
184 applies: function() {
185 return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
188 if(prev && (prev.is('p') || prev.is({tagName: 'header'}))) {
189 return merge(toMerge, prev);
191 if(prev && prev.is('list')) {
192 var items = prev.contents().filter(function(n) { return n.is('item');});
193 return merge(toMerge, items[items.length-1]);
198 applies: function() {
199 return toMerge.is({tagName: 'span'});
203 var toret = {node: toMerge.contents()[0] , offset: 0},
204 txt, txtNode, parent;
206 toMerge.parents().some(function(p) {
207 if(p.is({tagName: 'span'})) {
213 prev = prev && prev.prev();
219 return parent.moveUp();
221 else if(prev.nodeType === Node.TEXT_NODE && (txt = prev.getText())) {
222 prev.setText(txt.substr(0, txt.length-1));
224 } else if(prev.is({tagName: 'span'})) {
225 if((txtNode = prev.getLastTextNode())) {
226 txt = txtNode.getText();
228 txtNode.setText(txt.substr(0, txt.length-1));
230 if(txtNode.parent().contents().length === 1) {
231 txtNode.parent().detach();
244 applies: function() {
245 return toMerge.is({tagName: 'header'});
248 if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
249 return merge(toMerge, prev);
254 applies: function() {
255 return toMerge.is('item');
259 if(prev && prev.is('item')) {
260 return merge(toMerge, prev);
261 } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
262 list.before(toMerge);
263 toMerge.setClass('p');
264 if(!list.contents().length) {
267 return {node: toMerge.contents()[0], offset:0};
274 strategies.some(function(strategy) {
275 if(strategy.applies()) {
276 toret = strategy.run();
284 var undoRedoAction = function(dir) {
288 document: {type: 'context', name: 'document'},
291 label: dir === 'undo' ? '<-' : '->',
293 iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
294 execute: function(callback, params) {
295 var metadata = _.last(params.document[dir+'Stack']).metadata,
296 fragment = metadata && metadata.fragment;
297 params.document[dir]();
299 if(!fragment.isValid()) {
300 fragment.restoreFromPaths();
302 if(fragment.isValid()) {
309 getState: function(params) {
310 var allowed = params.document && !!(params.document[dir+'Stack'].length),
311 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
312 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
314 var metadata = _.last(params.document[dir+'Stack']).metadata;
316 desc += ': ' + (metadata.description || gettext('unknown operation'));
321 description: allowed ? desc : descEmpty
327 var pad = function(number) {
329 number = '0' + number;
334 var commentAction = {
337 fragment: {type: 'context', name: 'fragment'}
341 execute: function(callback, params, editor) {
343 var node = params.fragment.node,
345 if(node.nodeType === Node.TEXT_NODE) {
346 node = node.parent();
348 node.document.transaction(function() {
349 var comment = node.after({tagName: 'aside', attrs: {'class': 'comment'}});
350 comment.append({text:''});
351 var user = editor.getUser(), creator;
355 creator += ' (' + user.email + ')';
358 creator = 'anonymous';
361 var currentDate = new Date(),
362 dt = pad(currentDate.getDate()) + '-' +
363 pad((currentDate.getMonth() + 1)) + '-' +
364 pad(currentDate.getFullYear()) + ' ' +
365 pad(currentDate.getHours()) + ':' +
366 pad(currentDate.getMinutes()) + ':' +
367 pad(currentDate.getSeconds());
369 var metadata = comment.getMetadata();
370 metadata.add({key: 'creator', value: creator});
371 metadata.add({key: 'date', value: dt});
374 description: action.getState().description
380 getState: function(params) {
382 allowed: params.fragment && params.fragment.isValid() &&
383 params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
386 state.description = gettext('Insert comment');
393 var createWrapTextAction = function(createParams) {
395 name: createParams.name,
397 fragment: {type: 'context', name: 'fragment'},
399 getState: function(params) {
401 label: this.config.label
405 if(!params.fragment || !params.fragment.isValid()) {
406 return _.extend(state, {allowed: false});
409 if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
410 return _.extend(state, {
413 description: createParams.unwrapDescription,
414 execute: function(callback, params) {
415 var node = params.fragment.node,
417 toRemove = node.getParent(createParams.klass),
420 if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
421 prefLen = toRemove.prev().getText().length;
424 doc.transaction(function() {
425 var ret = toRemove.unwrapContent(),
426 newFragment = params.fragment;
427 if(!newFragment.isValid()) {
428 newFragment = doc.createFragment(doc.CaretFragment, {
430 offset: prefLen + params.fragment.offset
436 description: createParams.unwrapDescription,
437 fragment: params.fragment
445 if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
446 parent = params.fragment.startNode.parent();
447 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
448 return _.extend(state, {allowed: false});
451 return _.extend(state, {
453 description: createParams.wrapDescription,
454 execute: function(callback, params) {
455 params.fragment.document.transaction(function() {
456 var parent = params.fragment.startNode.parent(),
457 doc = params.fragment.document,
458 wrapper, lastTextNode;
460 wrapper = parent.wrapText({
461 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
462 offsetStart: params.fragment.startOffset,
463 offsetEnd: params.fragment.endOffset,
464 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
467 lastTextNode = wrapper.getLastTextNode();
469 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
473 description: createParams.wrapDescription,
474 fragment: params.fragment
481 return _.extend(state, {allowed: false});
487 var createLinkFromSelection = function(callback, params) {
488 var doc = params.fragment.document,
489 dialog = Dialog.create({
490 title: gettext('Create link'),
491 executeButtonText: gettext('Apply'),
492 cancelButtonText: gettext('Cancel'),
494 {label: gettext('Link'), name: 'href', type: 'input',
495 prePasteHandler: function(text) {
496 return params.fragment.document.getLinkForUrl(text);
503 dialog.on('execute', function(event) {
504 doc.transaction(function() {
505 var span = action.params.fragment.startNode.parent().wrapText({
506 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
507 offsetStart: params.fragment.startOffset,
508 offsetEnd: params.fragment.endOffset,
509 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
511 doc = params.fragment.document;
513 return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
516 description: action.getState().description,
517 fragment: params.fragment
525 var editLink = function(callback, params) {
526 var doc = params.fragment.document,
527 link = params.fragment.node.getParent('link'),
528 dialog = Dialog.create({
529 title: gettext('Edit link'),
530 executeButtonText: gettext('Apply'),
531 cancelButtonText: gettext('Cancel'),
533 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
538 dialog.on('execute', function(event) {
539 doc.transaction(function() {
540 link.setAttr('href', event.formData.href);
542 return params.fragment;
545 description: action.getState().description,
546 fragment: params.fragment
557 fragment: {type: 'context', name: 'fragment'}
560 label: gettext('link')
562 getState: function(params) {
563 if(!params.fragment || !params.fragment.isValid()) {
564 return {allowed: false};
567 if(params.fragment instanceof params.fragment.TextRangeFragment) {
568 if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
569 return {allowed: false};
573 description: gettext('Create link from selection'),
574 execute: createLinkFromSelection
578 if(params.fragment instanceof params.fragment.CaretFragment) {
579 if(params.fragment.node.isInside('link')) {
583 description: gettext('Edit link'),
588 return {allowed: false};
592 var metadataParams = {};
595 undoRedoAction('undo'),
596 undoRedoAction('redo'),
598 createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
599 createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
601 metadataEditor.action(metadataParams)
602 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
605 plugin.config = function(config) {
606 // templates.actions[0].config(config.templates);
607 templates.actions[0].params.template.options = config.templates;
608 metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
609 if(configRow1.key < configRow2.key) {
612 if(configRow1.key > configRow2.key) {
619 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);