Merge branch 'wip_MDL-45941_m28_message' of git://github.com/skodak/moodle
[moodle.git] / lib / editor / atto / plugins / equation / yui / src / button / js / button.js
CommitLineData
8bf5ad67
DW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
62467795 17 * @package atto_equation
8bf5ad67
DW
18 * @copyright 2013 Damyon Wiese <damyon@moodle.com>
19 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
20 */
62467795
AN
21
22/**
23 * Atto text editor equation plugin.
24 */
25
26/**
27 * Atto equation editor.
28 *
29 * @namespace M.atto_equation
30 * @class Button
31 * @extends M.editor_atto.EditorPlugin
32 */
33
34var COMPONENTNAME = 'atto_equation',
050159dc 35 LOGNAME = 'atto_equation',
62467795
AN
36 CSS = {
37 EQUATION_TEXT: 'atto_equation_equation',
38 EQUATION_PREVIEW: 'atto_equation_preview',
39 SUBMIT: 'atto_equation_submit',
40 LIBRARY: 'atto_equation_library',
050159dc
FM
41 LIBRARY_GROUPS: 'atto_equation_groups',
42 LIBRARY_GROUP_PREFIX: 'atto_equation_group'
62467795
AN
43 },
44 SELECTORS = {
050159dc
FM
45 LIBRARY: '.' + CSS.LIBRARY,
46 LIBRARY_GROUP: '.' + CSS.LIBRARY_GROUPS + ' > div > div',
62467795
AN
47 EQUATION_TEXT: '.' + CSS.EQUATION_TEXT,
48 EQUATION_PREVIEW: '.' + CSS.EQUATION_PREVIEW,
49 SUBMIT: '.' + CSS.SUBMIT,
50 LIBRARY_BUTTON: '.' + CSS.LIBRARY + ' button'
51 },
cc90cedc
DW
52 DELIMITERS = {
53 START: '\\(',
54 END: '\\)'
55 },
62467795
AN
56 TEMPLATES = {
57 FORM: '' +
58 '<form class="atto_form">' +
59 '{{{library}}}' +
36beb828 60 '<label for="{{elementid}}_{{CSS.EQUATION_TEXT}}">{{{get_string "editequation" component texdocsurl}}}</label>' +
62467795 61 '<textarea class="fullwidth {{CSS.EQUATION_TEXT}}" id="{{elementid}}_{{CSS.EQUATION_TEXT}}" rows="8"></textarea><br/>' +
62467795 62 '<label for="{{elementid}}_{{CSS.EQUATION_PREVIEW}}">{{get_string "preview" component}}</label>' +
24183668
AN
63 '<div describedby="{{elementid}}_cursorinfo" class="well well-small fullwidth {{CSS.EQUATION_PREVIEW}}" id="{{elementid}}_{{CSS.EQUATION_PREVIEW}}"></div>' +
64 '<div id="{{elementid}}_cursorinfo">{{get_string "cursorinfo" component}}</div>' +
62467795
AN
65 '<div class="mdl-align">' +
66 '<br/>' +
67 '<button class="{{CSS.SUBMIT}}">{{get_string "saveequation" component}}</button>' +
68 '</div>' +
69 '</form>',
70 LIBRARY: '' +
71 '<div class="{{CSS.LIBRARY}}">' +
72 '<ul>' +
73 '{{#each library}}' +
050159dc
FM
74 '<li><a href="#{{../elementid}}_{{../CSS.LIBRARY_GROUP_PREFIX}}_{{@key}}">' +
75 '{{get_string groupname ../component}}' +
76 '</a></li>' +
62467795
AN
77 '{{/each}}' +
78 '</ul>' +
050159dc 79 '<div class="{{CSS.LIBRARY_GROUPS}}">' +
62467795 80 '{{#each library}}' +
050159dc
FM
81 '<div id="{{../elementid}}_{{../CSS.LIBRARY_GROUP_PREFIX}}_{{@key}}">' +
82 '<div role="toolbar">' +
83 '{{#split "\n" elements}}' +
0610d2ca
DW
84 '<button tabindex="-1" data-tex="{{this}}" aria-label="{{this}}" title="{{this}}">' +
85 '{{../../DELIMITERS.START}}{{this}}{{../../DELIMITERS.END}}' +
86 '</button>' +
050159dc
FM
87 '{{/split}}' +
88 '</div>' +
62467795
AN
89 '</div>' +
90 '{{/each}}' +
91 '</div>' +
92 '</div>'
93 };
94
95Y.namespace('M.atto_equation').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], {
8bf5ad67
DW
96
97 /**
98 * The selection object returned by the browser.
99 *
62467795 100 * @property _currentSelection
8bf5ad67
DW
101 * @type Range
102 * @default null
62467795 103 * @private
8bf5ad67 104 */
62467795 105 _currentSelection: null,
8bf5ad67
DW
106
107 /**
62467795 108 * The cursor position in the equation textarea.
8bf5ad67 109 *
62467795
AN
110 * @property _lastCursorPos
111 * @type Number
8bf5ad67 112 * @default 0
62467795 113 * @private
8bf5ad67 114 */
62467795 115 _lastCursorPos: 0,
8bf5ad67
DW
116
117 /**
62467795 118 * A reference to the dialogue content.
8bf5ad67 119 *
62467795
AN
120 * @property _content
121 * @type Node
122 * @private
8bf5ad67 123 */
62467795 124 _content: null,
8bf5ad67 125
cc90cedc
DW
126 /**
127 * The source equation we are editing in the text.
128 *
129 * @property _sourceEquation
ea382dea 130 * @type Object
cc90cedc
DW
131 * @private
132 */
ea382dea 133 _sourceEquation: null,
cc90cedc 134
050159dc
FM
135 /**
136 * A reference to the tab focus set on each group.
137 *
138 * The keys are the IDs of the group, the value is the Node on which the focus is set.
139 *
140 * @property _groupFocus
141 * @type Object
142 * @private
143 */
144 _groupFocus: null,
145
ea382dea
AN
146 /**
147 * Regular Expression patterns used to pick out the equations in a String.
148 *
149 * @property _equationPatterns
150 * @type Array
151 * @private
152 */
153 _equationPatterns: [
154 // We use space or not space because . does not match new lines.
155 // $$ blah $$.
156 /\$\$([\S\s]+?)\$\$/,
157 // E.g. "\( blah \)".
158 /\\\(([\S\s]+?)\\\)/,
159 // E.g. "\[ blah \]".
160 /\\\[([\S\s]+?)\\\]/,
161 // E.g. "[tex] blah [/tex]".
162 /\[tex\]([\S\s]+?)\[\/tex\]/
163 ],
164
62467795 165 initializer: function() {
050159dc 166 this._groupFocus = {};
0610d2ca 167
cc90cedc
DW
168 // If there is a tex filter active - enable this button.
169 if (this.get('texfilteractive')) {
62467795
AN
170 // Add the button to the toolbar.
171 this.addButton({
172 icon: 'e/math',
173 callback: this._displayDialogue
8bf5ad67
DW
174 });
175
62467795
AN
176 // We need custom highlight logic for this button.
177 this.get('host').on('atto:selectionchanged', function() {
178 if (this._resolveEquation()) {
179 this.highlightButtons();
180 } else {
181 this.unHighlightButtons();
182 }
183 }, this);
cc90cedc
DW
184
185 // We need to convert these to a non dom node based format.
186 this.editor.all('tex').each(function (texNode) {
187 var replacement = Y.Node.create('<span>' + DELIMITERS.START + ' ' + texNode.get('text') + ' ' + DELIMITERS.END + '</span>');
188 texNode.replace(replacement);
189 });
8bf5ad67 190 }
cc90cedc 191
8bf5ad67
DW
192 },
193
194 /**
62467795 195 * Display the equation editor.
8bf5ad67 196 *
62467795
AN
197 * @method _displayDialogue
198 * @private
8bf5ad67 199 */
62467795
AN
200 _displayDialogue: function() {
201 this._currentSelection = this.get('host').getSelection();
8bf5ad67 202
62467795
AN
203 if (this._currentSelection === false) {
204 return;
205 }
8bf5ad67 206
62467795
AN
207 var dialogue = this.getDialogue({
208 headerContent: M.util.get_string('pluginname', COMPONENTNAME),
1eb5839c 209 focusAfterHide: true,
e5ddec38 210 width: 600,
c1660772 211 focusOnShowSelector: SELECTORS.EQUATION_TEXT
62467795
AN
212 });
213
214 var content = this._getDialogueContent();
215 dialogue.set('bodyContent', content);
216
050159dc 217 var library = content.one(SELECTORS.LIBRARY);
62467795
AN
218
219 var tabview = new Y.TabView({
220 srcNode: library
221 });
222
223 tabview.render();
224 dialogue.show();
cc90cedc
DW
225 // Trigger any JS filters to reprocess the new nodes.
226 Y.fire(M.core.event.FILTER_CONTENT_UPDATED, {nodes: (new Y.NodeList(dialogue.get('boundingBox')))});
62467795
AN
227
228 var equation = this._resolveEquation();
229 if (equation) {
230 content.one(SELECTORS.EQUATION_TEXT).set('text', equation);
8bf5ad67 231 }
62467795 232 this._updatePreview(false);
8bf5ad67
DW
233 },
234
235 /**
236 * If there is selected text and it is part of an equation,
237 * extract the equation (and set it in the form).
238 *
62467795
AN
239 * @method _resolveEquation
240 * @private
3ee53a42 241 * @return {String|Boolean} The equation or false.
8bf5ad67 242 */
62467795
AN
243 _resolveEquation: function() {
244
8bf5ad67 245 // Find the equation in the surrounding text.
62467795 246 var selectedNode = this.get('host').getSelectionParentNode(),
ea382dea 247 selection = this.get('host').getSelection(),
8bf5ad67 248 text,
ea382dea
AN
249 returnValue = false;
250
251 this.sourceEquation = null;
8bf5ad67
DW
252
253 // Note this is a document fragment and YUI doesn't like them.
62467795 254 if (!selectedNode) {
3ee53a42 255 return false;
8bf5ad67
DW
256 }
257
ea382dea
AN
258 // We don't yet have a cursor selection somehow so we can't possible be resolving an equation that has selection.
259 if (!selection || selection.length === 0) {
260 return false;
261 }
262 selection = selection[0];
cc90cedc 263
ea382dea 264 text = Y.one(selectedNode).get('text');
cc90cedc 265
ea382dea
AN
266 // For each of these patterns we have a RegExp which captures the inner component of the equation but also includes the delimiters.
267 // We first run the RegExp adding the global flag ("g"). This ignores the capture, instead matching the entire
268 // equation including delimiters and returning one entry per match of the whole equation.
269 // We have to deal with multiple occurences of the same equation in a String so must be able to loop on the
270 // match results.
271 Y.Array.find(this._equationPatterns, function(pattern) {
272 // For each pattern in turn, find all whole matches (including the delimiters).
273 var patternMatches = text.match(new RegExp(pattern.source, "g"));
274
275 if (patternMatches && patternMatches.length) {
276 // This pattern matches at least once. See if this pattern matches our current position.
277 // Note: We return here to break the Y.Array.find loop - any truthy return will stop any subsequent
278 // searches which is the required behaviour of this function.
279 return Y.Array.find(patternMatches, function(match) {
280 // Check each occurrence of this match.
281 var startIndex = 0;
282 while(text.indexOf(match, startIndex) !== -1) {
283 // Determine whether the cursor is in the current occurrence of this string.
284 // Note: We do not support a selection exceeding the bounds of an equation.
285 var startOuter = text.indexOf(match, startIndex),
286 endOuter = startOuter + match.length,
287 startMatch = (selection.startOffset >= startOuter && selection.startOffset < endOuter),
288 endMatch = (selection.endOffset <= endOuter && selection.endOffset > startOuter);
289
290 if (startMatch && endMatch) {
291 // This match is in our current position - fetch the innerMatch data.
292 var innerMatch = match.match(pattern);
293 if (innerMatch && innerMatch.length) {
294 // We need the start and end of the inner match for later.
295 var startInner = text.indexOf(innerMatch[1], startOuter),
296 endInner = startInner + innerMatch[1].length;
297
298 // We'll be returning the inner match for use in the editor itself.
299 returnValue = innerMatch[1];
300
301 // Save all data for later.
302 this.sourceEquation = {
303 // Outer match data.
304 startOuterPosition: startOuter,
305 endOuterPosition: endOuter,
306 outerMatch: match,
307
308 // Inner match data.
309 startInnerPosition: startInner,
310 endInnerPosition: endInner,
311 innerMatch: innerMatch
312 };
313
314 // This breaks out of both Y.Array.find functions.
315 return true;
316 }
317 }
318
319 // Update the startIndex to match the end of the current match so that we can continue hunting
320 // for further matches.
321 startIndex = endOuter;
322 }
323 }, this);
cc90cedc 324 }
ea382dea 325 }, this);
cc90cedc 326
ea382dea 327 return returnValue;
8bf5ad67
DW
328 },
329
330 /**
62467795 331 * Handle insertion of a new equation, or update of an existing one.
8bf5ad67 332 *
62467795
AN
333 * @method _setEquation
334 * @param {EventFacade} e
335 * @private
8bf5ad67 336 */
62467795 337 _setEquation: function(e) {
8bf5ad67 338 var input,
62467795 339 selectedNode,
8bf5ad67 340 text,
cc90cedc
DW
341 value,
342 host;
8bf5ad67 343
cc90cedc 344 host = this.get('host');
62467795 345
8bf5ad67 346 e.preventDefault();
62467795
AN
347 this.getDialogue({
348 focusAfterHide: null
349 }).hide();
8bf5ad67
DW
350
351 input = e.currentTarget.ancestor('.atto_form').one('textarea');
352
353 value = input.get('value');
354 if (value !== '') {
62467795
AN
355 host.setSelection(this._currentSelection);
356
ea382dea 357 if (this.sourceEquation) {
8bf5ad67 358 // Replace the equation.
cc90cedc
DW
359 selectedNode = Y.one(host.getSelectionParentNode());
360 text = selectedNode.get('text');
ea382dea
AN
361 newText = text.slice(0, this.sourceEquation.startInnerPosition) +
362 value +
363 text.slice(this.sourceEquation.endInnerPosition);
cc90cedc 364
ea382dea 365 selectedNode.set('text', newText);
8bf5ad67
DW
366 } else {
367 // Insert the new equation.
cc90cedc 368 value = DELIMITERS.START + ' ' + value + ' ' + DELIMITERS.END;
62467795 369 host.insertContentAtFocusPoint(value);
8bf5ad67
DW
370 }
371
372 // Clean the YUI ids from the HTML.
62467795 373 this.markUpdated();
8bf5ad67
DW
374 }
375 },
376
cc90cedc
DW
377 /**
378 * Smart throttle, only call a function every delay milli seconds,
441f94b2
DW
379 * and always run the last call. Y.throttle does not work here,
380 * because it calls the function immediately, the first time, and then
381 * ignores repeated calls within X seconds. This does not guarantee
382 * that the last call will be executed (which is required here).
cc90cedc
DW
383 *
384 * @param {function} fn
441f94b2 385 * @param {Number} delay Delay in milliseconds
cc90cedc
DW
386 * @method _throttle
387 * @private
388 */
389 _throttle: function(fn, delay) {
390 var timer = null;
391 return function () {
392 var context = this, args = arguments;
393 clearTimeout(timer);
394 timer = setTimeout(function () {
395 fn.apply(context, args);
396 }, delay);
397 };
398 },
399
8bf5ad67
DW
400 /**
401 * Update the preview div to match the current equation.
402 *
62467795
AN
403 * @param {EventFacade} e
404 * @method _updatePreview
405 * @private
8bf5ad67 406 */
62467795
AN
407 _updatePreview: function(e) {
408 var textarea = this._content.one(SELECTORS.EQUATION_TEXT),
409 equation = textarea.get('value'),
410 url,
411 preview,
412 currentPos = textarea.get('selectionStart'),
413 prefix = '',
d8e2dc99 414 cursorLatex = '\\Downarrow ',
441f94b2
DW
415 isChar,
416 params;
62467795 417
62467795
AN
418 if (e) {
419 e.preventDefault();
420 }
421
d926ce71
AN
422 // Move the cursor so it does not break expressions.
423 // Start at the very beginning.
62467795
AN
424 if (!currentPos) {
425 currentPos = 0;
8bf5ad67 426 }
d926ce71
AN
427
428 // First move back to the beginning of the line.
429 while (equation.charAt(currentPos) === '\\' && currentPos >= 0) {
62467795 430 currentPos -= 1;
8bf5ad67 431 }
cc90cedc 432 isChar = /[a-zA-Z\{\}]/;
d926ce71
AN
433 if (currentPos !== 0) {
434 // Now match to the end of the line.
435 while (isChar.test(equation.charAt(currentPos)) && currentPos < equation.length && isChar.test(equation.charAt(currentPos-1))) {
436 currentPos += 1;
437 }
8bf5ad67
DW
438 }
439 // Save the cursor position - for insertion from the library.
62467795
AN
440 this._lastCursorPos = currentPos;
441 equation = prefix + equation.substring(0, currentPos) + cursorLatex + equation.substring(currentPos);
8939ebac
DW
442
443 var previewNode = this._content.one(SELECTORS.EQUATION_PREVIEW);
cc90cedc
DW
444 equation = DELIMITERS.START + ' ' + equation + ' ' + DELIMITERS.END;
445 // Make an ajax request to the filter.
446 url = M.cfg.wwwroot + '/lib/editor/atto/plugins/equation/ajax.php';
447 params = {
448 sesskey: M.cfg.sesskey,
449 contextid: this.get('contextid'),
450 action: 'filtertext',
451 text: equation
452 };
453
441f94b2
DW
454 preview = Y.io(url, {
455 sync: true,
456 data: params
457 });
458
cc90cedc
DW
459 if (preview.status === 200) {
460 previewNode.setHTML(preview.responseText);
461 Y.fire(M.core.event.FILTER_CONTENT_UPDATED, {nodes: (new Y.NodeList(previewNode))});
8bf5ad67
DW
462 }
463 },
464
465 /**
62467795
AN
466 * Return the dialogue content for the tool, attaching any required
467 * events.
8bf5ad67 468 *
62467795
AN
469 * @method _getDialogueContent
470 * @return {Node}
471 * @private
8bf5ad67 472 */
62467795
AN
473 _getDialogueContent: function() {
474 var library = this._getLibraryContent(),
475 template = Y.Handlebars.compile(TEMPLATES.FORM);
476
477 this._content = Y.Node.create(template({
478 elementid: this.get('host').get('elementid'),
479 component: COMPONENTNAME,
480 library: library,
36beb828 481 texdocsurl: this.get('texdocsurl'),
62467795
AN
482 CSS: CSS
483 }));
484
050159dc
FM
485 // Sets the default focus.
486 this._content.all(SELECTORS.LIBRARY_GROUP).each(function(group) {
487 // The first button gets the focus.
488 this._setGroupTabFocus(group, group.one('button'));
489 // Sometimes the filter adds an anchor in the button, no tabindex on that.
490 group.all('button a').setAttribute('tabindex', '-1');
491 }, this);
492
493 // Keyboard navigation in groups.
494 this._content.delegate('key', this._groupNavigation, 'down:37,39', SELECTORS.LIBRARY_BUTTON, this);
495
62467795 496 this._content.one(SELECTORS.SUBMIT).on('click', this._setEquation, this);
cc90cedc
DW
497 this._content.one(SELECTORS.EQUATION_TEXT).on('valuechange', this._throttle(this._updatePreview, 500), this);
498 this._content.one(SELECTORS.EQUATION_TEXT).on('mouseup', this._throttle(this._updatePreview, 500), this);
499 this._content.one(SELECTORS.EQUATION_TEXT).on('keyup', this._throttle(this._updatePreview, 500), this);
62467795
AN
500 this._content.delegate('click', this._selectLibraryItem, SELECTORS.LIBRARY_BUTTON, this);
501
502 return this._content;
8bf5ad67
DW
503 },
504
050159dc
FM
505 /**
506 * Callback handling the keyboard navigation in the groups of the library.
507 *
508 * @param {EventFacade} e The event.
509 * @method _groupNavigation
510 * @private
511 */
512 _groupNavigation: function(e) {
513 e.preventDefault();
514
515 var current = e.currentTarget,
516 parent = current.get('parentNode'), // This must be the <div> containing all the buttons of the group.
517 buttons = parent.all('button'),
518 direction = e.keyCode !== 37 ? 1 : -1,
519 index = buttons.indexOf(current),
520 nextButton;
521
522 if (index < 0) {
523 Y.log('Unable to find the current button in the list of buttons', 'debug', LOGNAME);
524 index = 0;
525 }
526
527 index += direction;
528 if (index < 0) {
529 index = buttons.size() - 1;
530 } else if (index >= buttons.size()) {
531 index = 0;
532 }
533 nextButton = buttons.item(index);
534
535 this._setGroupTabFocus(parent, nextButton);
536 nextButton.focus();
537 },
538
539 /**
540 * Sets tab focus for the group.
541 *
542 * @method _setGroupTabFocus
543 * @param {Node} button The node that focus should now be set to.
544 * @private
545 */
546 _setGroupTabFocus: function(parent, button) {
547 var parentId = parent.generateID();
548
549 // Unset the previous entry.
550 if (typeof this._groupFocus[parentId] !== 'undefined') {
551 this._groupFocus[parentId].setAttribute('tabindex', '-1');
552 }
553
554 // Set on the new entry.
555 this._groupFocus[parentId] = button;
556 button.setAttribute('tabindex', 0);
557 parent.setAttribute('aria-activedescendant', button.generateID());
558 },
559
8bf5ad67 560 /**
62467795 561 * Reponse to button presses in the TeX library panels.
8bf5ad67 562 *
62467795
AN
563 * @method _selectLibraryItem
564 * @param {EventFacade} e
565 * @return {string}
566 * @private
8bf5ad67 567 */
62467795 568 _selectLibraryItem: function(e) {
d926ce71
AN
569 var tex = e.currentTarget.getAttribute('data-tex'),
570 oldValue,
571 newValue,
572 input,
573 focusPoint = 0;
8bf5ad67 574
62467795 575 e.preventDefault();
8bf5ad67 576
050159dc
FM
577 // Set the group focus on the button.
578 this._setGroupTabFocus(e.currentTarget.get('parentNode'), e.currentTarget);
579
62467795 580 input = e.currentTarget.ancestor('.atto_form').one('textarea');
8bf5ad67 581
d926ce71
AN
582 oldValue = input.get('value');
583
584 newValue = oldValue.substring(0, this._lastCursorPos);
585 if (newValue.charAt(newValue.length - 1) !== ' ') {
586 newValue += ' ';
587 }
588 newValue += tex;
589 focusPoint = newValue.length;
8bf5ad67 590
d926ce71
AN
591 if (oldValue.charAt(this._lastCursorPos) !== ' ') {
592 newValue += ' ';
593 }
594 newValue += oldValue.substring(this._lastCursorPos, oldValue.length);
8bf5ad67 595
d926ce71 596 input.set('value', newValue);
8bf5ad67 597 input.focus();
9ee8a359 598
d926ce71 599 var realInput = input.getDOMNode();
9ee8a359
AN
600 if (typeof realInput.selectionStart === "number") {
601 // Modern browsers have selectionStart and selectionEnd to control the cursor position.
602 realInput.selectionStart = realInput.selectionEnd = focusPoint;
603 } else if (typeof realInput.createTextRange !== "undefined") {
604 // Legacy browsers (IE<=9) use createTextRange().
605 var range = realInput.createTextRange();
606 range.moveToPoint(focusPoint);
607 range.select();
608 }
609 // Focus must be set before updating the preview for the cursor box to be in the correct location.
62467795 610 this._updatePreview(false);
8bf5ad67
DW
611 },
612
613 /**
614 * Return the HTML for rendering the library of predefined buttons.
615 *
62467795
AN
616 * @method _getLibraryContent
617 * @return {string}
618 * @private
8bf5ad67 619 */
62467795
AN
620 _getLibraryContent: function() {
621 var template = Y.Handlebars.compile(TEMPLATES.LIBRARY),
622 library = this.get('library'),
623 content = '';
624
625 // Helper to iterate over a newline separated string.
626 Y.Handlebars.registerHelper('split', function(delimiter, str, options) {
627 var parts,
628 current,
629 out;
630 if (typeof delimiter === "undefined" || typeof str === "undefined") {
631 Y.log('Handlebars split helper: String and delimiter are required.', 'debug', 'moodle-atto_equation-button');
632 return '';
8bf5ad67 633 }
62467795
AN
634
635 out = '';
636 parts = str.trim().split(delimiter);
637 while (parts.length > 0) {
cc90cedc 638 current = parts.shift().trim();
62467795
AN
639 out += options.fn(current);
640 }
641
642 return out;
643 });
644 content = template({
645 elementid: this.get('host').get('elementid'),
646 component: COMPONENTNAME,
647 library: library,
cc90cedc
DW
648 CSS: CSS,
649 DELIMITERS: DELIMITERS
62467795 650 });
8bf5ad67 651
cc90cedc
DW
652 var url = M.cfg.wwwroot + '/lib/editor/atto/plugins/equation/ajax.php';
653 var params = {
654 sesskey: M.cfg.sesskey,
655 contextid: this.get('contextid'),
656 action: 'filtertext',
657 text: content
658 };
659
660 preview = Y.io(url, {
661 sync: true,
662 data: params,
663 method: 'POST'
664 });
8bf5ad67 665
cc90cedc
DW
666 if (preview.status === 200) {
667 content = preview.responseText;
8bf5ad67
DW
668 }
669 return content;
670 }
62467795
AN
671}, {
672 ATTRS: {
673 /**
674 * Whether the TeX filter is currently active.
675 *
676 * @attribute texfilteractive
677 * @type Boolean
678 */
679 texfilteractive: {
680 value: false
681 },
cc90cedc 682
62467795
AN
683 /**
684 * The contextid to use when generating this preview.
685 *
686 * @attribute contextid
687 * @type String
688 */
689 contextid: {
690 value: null
691 },
692
693 /**
694 * The content of the example library.
695 *
696 * @attribute library
697 * @type object
698 */
699 library: {
700 value: {}
36beb828
FM
701 },
702
703 /**
704 * The link to the Moodle Docs page about TeX.
705 *
706 * @attribute texdocsurl
707 * @type string
708 */
709 texdocsurl: {
710 value: null
62467795 711 }
cc90cedc 712
62467795
AN
713 }
714});