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();
227 txtNode.setText(txt.substr(0, txt.length-1));
235 applies: function() {
236 return toMerge.is({tagName: 'header'});
239 if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
240 return merge(toMerge, prev);
245 applies: function() {
246 return toMerge.is('item');
250 if(prev && prev.is('item')) {
251 return merge(toMerge, prev);
252 } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
253 list.before(toMerge);
254 toMerge.setClass('p');
255 if(!list.contents().length) {
258 return {node: toMerge.contents()[0], offset:0};
265 strategies.some(function(strategy) {
266 if(strategy.applies()) {
267 toret = strategy.run();
275 var undoRedoAction = function(dir) {
279 document: {type: 'context', name: 'document'},
282 label: dir === 'undo' ? '<-' : '->',
284 iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
285 execute: function(callback, params) {
286 var metadata = _.last(params.document[dir+'Stack']).metadata,
287 fragment = metadata && metadata.fragment;
288 params.document[dir]();
290 if(!fragment.isValid()) {
291 fragment.restoreFromPaths();
293 if(fragment.isValid()) {
300 getState: function(params) {
301 var allowed = params.document && !!(params.document[dir+'Stack'].length),
302 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
303 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
305 var metadata = _.last(params.document[dir+'Stack']).metadata;
307 desc += ': ' + (metadata.description || gettext('unknown operation'));
312 description: allowed ? desc : descEmpty
318 var pad = function(number) {
320 number = '0' + number;
325 var commentAction = {
328 fragment: {type: 'context', name: 'fragment'}
332 execute: function(callback, params, editor) {
334 var node = params.fragment.node,
336 if(node.nodeType === Node.TEXT_NODE) {
337 node = node.parent();
339 node.document.transaction(function() {
340 var comment = node.after({tagName: 'aside', attrs: {'class': 'comment'}});
341 comment.append({text:''});
342 var user = editor.getUser(), creator;
346 creator += ' (' + user.email + ')';
349 creator = 'anonymous';
352 var currentDate = new Date(),
353 dt = pad(currentDate.getDate()) + '-' +
354 pad((currentDate.getMonth() + 1)) + '-' +
355 pad(currentDate.getFullYear()) + ' ' +
356 pad(currentDate.getHours()) + ':' +
357 pad(currentDate.getMinutes()) + ':' +
358 pad(currentDate.getSeconds());
360 var metadata = comment.getMetadata();
361 metadata.add({key: 'creator', value: creator});
362 metadata.add({key: 'date', value: dt});
365 description: action.getState().description
371 getState: function(params) {
373 allowed: params.fragment && params.fragment.isValid() &&
374 params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
377 state.description = gettext('Insert comment');
384 var createWrapTextAction = function(createParams) {
386 name: createParams.name,
388 fragment: {type: 'context', name: 'fragment'},
390 getState: function(params) {
392 label: this.config.label
396 if(!params.fragment || !params.fragment.isValid()) {
397 return _.extend(state, {allowed: false});
400 if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
401 return _.extend(state, {
404 description: createParams.unwrapDescription,
405 execute: function(callback, params) {
406 var node = params.fragment.node,
408 toRemove = node.getParent(createParams.klass),
411 if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
412 prefLen = toRemove.prev().getText().length;
415 doc.transaction(function() {
416 var ret = toRemove.unwrapContent(),
417 newFragment = params.fragment;
418 if(!newFragment.isValid()) {
419 newFragment = doc.createFragment(doc.CaretFragment, {
421 offset: prefLen + params.fragment.offset
427 description: createParams.unwrapDescription,
428 fragment: params.fragment
436 if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
437 parent = params.fragment.startNode.parent();
438 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
439 return _.extend(state, {allowed: false});
442 return _.extend(state, {
444 description: createParams.wrapDescription,
445 execute: function(callback, params) {
446 params.fragment.document.transaction(function() {
447 var parent = params.fragment.startNode.parent(),
448 doc = params.fragment.document,
449 wrapper, lastTextNode;
451 wrapper = parent.wrapText({
452 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
453 offsetStart: params.fragment.startOffset,
454 offsetEnd: params.fragment.endOffset,
455 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
458 lastTextNode = wrapper.getLastTextNode();
460 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
464 description: createParams.wrapDescription,
465 fragment: params.fragment
472 return _.extend(state, {allowed: false});
478 var createLinkFromSelection = function(callback, params) {
479 var doc = params.fragment.document,
480 dialog = Dialog.create({
481 title: gettext('Create link'),
482 executeButtonText: gettext('Apply'),
483 cancelButtonText: gettext('Cancel'),
485 {label: gettext('Link'), name: 'href', type: 'input',
486 prePasteHandler: function(text) {
487 return params.fragment.document.getLinkForUrl(text);
494 dialog.on('execute', function(event) {
495 doc.transaction(function() {
496 var span = action.params.fragment.startNode.parent().wrapText({
497 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
498 offsetStart: params.fragment.startOffset,
499 offsetEnd: params.fragment.endOffset,
500 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
502 doc = params.fragment.document;
504 return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
507 description: action.getState().description,
508 fragment: params.fragment
516 var editLink = function(callback, params) {
517 var doc = params.fragment.document,
518 link = params.fragment.node.getParent('link'),
519 dialog = Dialog.create({
520 title: gettext('Edit link'),
521 executeButtonText: gettext('Apply'),
522 cancelButtonText: gettext('Cancel'),
524 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
529 dialog.on('execute', function(event) {
530 doc.transaction(function() {
531 link.setAttr('href', event.formData.href);
533 return params.fragment;
536 description: action.getState().description,
537 fragment: params.fragment
548 fragment: {type: 'context', name: 'fragment'}
551 label: gettext('link')
553 getState: function(params) {
554 if(!params.fragment || !params.fragment.isValid()) {
555 return {allowed: false};
558 if(params.fragment instanceof params.fragment.TextRangeFragment) {
559 if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
560 return {allowed: false};
564 description: gettext('Create link from selection'),
565 execute: createLinkFromSelection
569 if(params.fragment instanceof params.fragment.CaretFragment) {
570 if(params.fragment.node.isInside('link')) {
574 description: gettext('Edit link'),
579 return {allowed: false};
583 var metadataParams = {};
586 undoRedoAction('undo'),
587 undoRedoAction('redo'),
589 createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
590 createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
592 metadataEditor.action(metadataParams)
593 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
596 plugin.config = function(config) {
597 // templates.actions[0].config(config.templates);
598 templates.actions[0].params.template.options = config.templates;
599 metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
600 if(configRow1.key < configRow2.key) {
603 if(configRow1.key > configRow2.key) {
610 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);