Debian Codegraph @

dijit/_editor/plugins/FontChoice.js

raw symbols SCIP
1 define([
2 "require",
3 "dojo/_base/array", // array.indexOf array.map
4 "dojo/_base/declare", // declare
5 "dojo/dom-construct", // domConstruct.place
6 "dojo/i18n", // i18n.getLocalization
7 "dojo/_base/lang", // lang.delegate lang.hitch lang.isString
8 "dojo/string",
9 "dojo/store/Memory", // MemoryStore
10 "../../registry", // registry.getUniqueId
11 "../../_Widget",
12 "../../_TemplatedMixin",
13 "../../_WidgetsInTemplateMixin",
14 "../../form/FilteringSelect",
15 "../_Plugin",
16 "../range",
17 "dojo/i18n!../nls/FontChoice"
18 ], function(require, array, declare, domConstruct, i18n, lang, stringUtil, MemoryStore,
19 registry, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, FilteringSelect, _Plugin, rangeapi){
20
21 // module:
22 // dijit/_editor/plugins/FontChoice
23
24 var _FontDropDown = declare("dijit._editor.plugins._FontDropDown",
25 [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
26 // summary:
27 // Base class for widgets that contains a label (like "Font:")
28 // and a FilteringSelect drop down to pick a value.
29 // Used as Toolbar entry.
30
31 // label: [public] String
32 // The label to apply to this particular FontDropDown.
33 label: "",
34
35 // plainText: [public] boolean
36 // Flag to indicate that the returned label should be plain text
37 // instead of an example.
38 plainText: false,
39
40 // templateString: [public] String
41 // The template used to construct the labeled dropdown.
42 templateString: "<span style='white-space: nowrap' class='dijit dijitReset dijitInline'>" +
43 "<label class='dijitLeft dijitInline' for='${selectId}'>${label}</label>" +
44 "<input data-dojo-type='../../form/FilteringSelect' required='false' " +
45 "data-dojo-props='labelType:\"html\", labelAttr:\"label\", searchAttr:\"name\"' " +
46 "class='${comboClass}' " +
47 "tabIndex='-1' id='${selectId}' data-dojo-attach-point='select' value=''/>" +
48 "</span>",
49
50 // contextRequire: [public] Function
51 // The context require that is used to resolve modules in template.
52 contextRequire: require,
53
54 postMixInProperties: function(){
55 // summary:
56 // Over-ride to set specific properties.
57 this.inherited(arguments);
58
59 this.strings = i18n.getLocalization("dijit._editor", "FontChoice");
60
61 // Set some substitution variables used in the template
62 this.label = this.strings[this.command];
63
64 // _WidgetBase sets the id after postMixInProperties(), but we need it now.
65 // Alternative is to have a buildRendering() method and move this.selectId setting there,
66 // or alternately get rid of selectId variable and just access ${id} in template?
67 this.id = registry.getUniqueId(this.declaredClass.replace(/\./g, "_"));
68
69 this.selectId = this.id + "_select"; // used in template
70
71 this.inherited(arguments);
72 },
73
74 postCreate: function(){
75 // summary:
76 // Over-ride for the default postCreate action
77 // This establishes the filtering selects and the like.
78
79 // Initialize the list of items in the drop down by creating data store with items like:
80 // {value: 1, name: "xx-small", label: "<font size=1>xx-small</font-size>" }
81 this.select.set("store", new MemoryStore({
82 idProperty: "value",
83 data: array.map(this.values, function(value){
84 var name = this.strings[value] || value;
85 return {
86 label: this.getLabel(value, name),
87 name: name,
88 value: value
89 };
90 }, this)
91 }));
92
93 this.select.set("value", "", false);
94 this.disabled = this.select.get("disabled");
95 },
96
97 _setValueAttr: function(value, priorityChange){
98 // summary:
99 // Over-ride for the default action of setting the
100 // widget value, maps the input to known values
101 // value: Object|String
102 // The value to set in the select.
103 // priorityChange:
104 // Optional parameter used to tell the select whether or not to fire
105 // onChange event.
106
107 // if the value is not a permitted value, just set empty string to prevent showing the warning icon
108 priorityChange = priorityChange !== false;
109 this.select.set('value', array.indexOf(this.values, value) < 0 ? "" : value, priorityChange);
110 if(!priorityChange){
111 // Clear the last state in case of updateState calls. Ref: #10466
112 this.select._lastValueReported = null;
113 }
114 },
115
116 _getValueAttr: function(){
117 // summary:
118 // Allow retrieving the value from the composite select on
119 // call to button.get("value");
120 return this.select.get('value');
121 },
122
123 focus: function(){
124 // summary:
125 // Over-ride for focus control of this widget. Delegates focus down to the
126 // filtering select.
127 this.select.focus();
128 },
129
130 _setDisabledAttr: function(value){
131 // summary:
132 // Over-ride for the button's 'disabled' attribute so that it can be
133 // disabled programmatically.
134
135 // Save off ths disabled state so the get retrieves it correctly
136 //without needing to have a function proxy it.
137 this._set("disabled", value);
138 this.select.set("disabled", value);
139 }
140 });
141
142
143 var _FontNameDropDown = declare("dijit._editor.plugins._FontNameDropDown", _FontDropDown, {
144 // summary:
145 // Dropdown to select a font; goes in editor toolbar.
146
147 // generic: [const] Boolean
148 // Use generic (web standard) font names
149 generic: false,
150
151 // command: [public] String
152 // The editor 'command' implemented by this plugin.
153 command: "fontName",
154
155 comboClass: "dijitFontNameCombo",
156
157 postMixInProperties: function(){
158 // summary:
159 // Over-ride for the default posr mixin control
160 if(!this.values){
161 this.values = this.generic ?
162 ["serif", "sans-serif", "monospace", "cursive", "fantasy"] : // CSS font-family generics
163 ["Arial", "Times New Roman", "Comic Sans MS", "Courier New"];
164 }
165 this.inherited(arguments);
166 },
167
168 getLabel: function(value, name){
169 // summary:
170 // Function used to generate the labels of the format dropdown
171 // will return a formatted, or plain label based on the value
172 // of the plainText option.
173 // value: String
174 // The 'insert value' associated with a name
175 // name: String
176 // The text name of the value
177 if(this.plainText){
178 return name;
179 }else{
180 return "<div style='font-family: " + value + "'>" + name + "</div>";
181 }
182 },
183
184 _normalizeFontName: function (value) {
185 // summary:
186 // Function used to choose one font name when the value is a list of font names
187 // like "Verdana, Arial, Helvetica, sans-serif"
188 var allowedValues = this.values;
189 if (!value || !allowedValues) {
190 return value;
191 }
192 var fontNames = value.split(',');
193 if (fontNames.length > 1) {
194 for (var i = 0, l = fontNames.length; i < l; i++) {
195 var fontName = stringUtil.trim(fontNames[i]);
196 var pos = array.indexOf(allowedValues, fontName);
197 if (pos > -1) {
198 return fontName;
199 }
200 }
201 }
202 return value;
203 },
204
205 _setValueAttr: function(value, priorityChange){
206 // summary:
207 // Over-ride for the default action of setting the
208 // widget value, maps the input to known values
209
210 priorityChange = priorityChange !== false;
211 value = this._normalizeFontName(value);
212 if(this.generic){
213 var map = {
214 "Arial": "sans-serif",
215 "Helvetica": "sans-serif",
216 "Myriad": "sans-serif",
217 "Times": "serif",
218 "Times New Roman": "serif",
219 "Comic Sans MS": "cursive",
220 "Apple Chancery": "cursive",
221 "Courier": "monospace",
222 "Courier New": "monospace",
223 "Papyrus": "fantasy",
224 "Estrangelo Edessa": "cursive", // Windows 7
225 "Gabriola": "fantasy" // Windows 7
226 };
227 value = map[value] || value;
228 }
229 this.inherited(arguments, [value, priorityChange]);
230 }
231 });
232
233 var _FontSizeDropDown = declare("dijit._editor.plugins._FontSizeDropDown", _FontDropDown, {
234 // summary:
235 // Dropdown to select a font size; goes in editor toolbar.
236
237 // command: [public] String
238 // The editor 'command' implemented by this plugin.
239 command: "fontSize",
240
241 comboClass: "dijitFontSizeCombo",
242
243 // values: [public] Number[]
244 // The HTML font size values supported by this plugin
245 values: [1, 2, 3, 4, 5, 6, 7], // sizes according to the old HTML FONT SIZE
246
247 getLabel: function(value, name){
248 // summary:
249 // Function used to generate the labels of the format dropdown
250 // will return a formatted, or plain label based on the value
251 // of the plainText option.
252 // We're stuck using the deprecated FONT tag to correspond
253 // with the size measurements used by the editor
254 // value: String
255 // The 'insert value' associated with a name
256 // name: String
257 // The text name of the value
258 if(this.plainText){
259 return name;
260 }else{
261 return "<font size=" + value + "'>" + name + "</font>";
262 }
263 },
264
265 _setValueAttr: function(value, priorityChange){
266 // summary:
267 // Over-ride for the default action of setting the
268 // widget value, maps the input to known values
269 priorityChange = priorityChange !== false;
270 if(value.indexOf && value.indexOf("px") != -1){
271 var pixels = parseInt(value, 10);
272 value = {10: 1, 13: 2, 16: 3, 18: 4, 24: 5, 32: 6, 48: 7}[pixels] || value;
273 }
274
275 this.inherited(arguments, [value, priorityChange]);
276 }
277 });
278
279
280 var _FormatBlockDropDown = declare("dijit._editor.plugins._FormatBlockDropDown", _FontDropDown, {
281 // summary:
282 // Dropdown to select a format (like paragraph or heading); goes in editor toolbar.
283
284 // command: [public] String
285 // The editor 'command' implemented by this plugin.
286 command: "formatBlock",
287
288 comboClass: "dijitFormatBlockCombo",
289
290 // values: [public] Array
291 // The HTML format tags supported by this plugin
292 values: ["noFormat", "p", "h1", "h2", "h3", "pre"],
293
294 postCreate: function(){
295 // Init and set the default value to no formatting. Update state will adjust it
296 // as needed.
297 this.inherited(arguments);
298 this.set("value", "noFormat", false);
299 },
300
301 getLabel: function(value, name){
302 // summary:
303 // Function used to generate the labels of the format dropdown
304 // will return a formatted, or plain label based on the value
305 // of the plainText option.
306 // value: String
307 // The 'insert value' associated with a name
308 // name: String
309 // The text name of the value
310 if(this.plainText || value == "noFormat"){
311 return name;
312 }else{
313 return "<" + value + ">" + name + "</" + value + ">";
314 }
315 },
316
317 _execCommand: function(editor, command, choice){
318 // summary:
319 // Over-ride for default exec-command label.
320 // Allows us to treat 'none' as special.
321 if(choice === "noFormat"){
322 var start;
323 var end;
324 var sel = rangeapi.getSelection(editor.window);
325 if(sel && sel.rangeCount > 0){
326 var range = sel.getRangeAt(0);
327 var node, tag;
328 if(range){
329 start = range.startContainer;
330 end = range.endContainer;
331
332 // find containing nodes of start/end.
333 while(start && start !== editor.editNode &&
334 start !== editor.document.body &&
335 start.nodeType !== 1){
336 start = start.parentNode;
337 }
338
339 while(end && end !== editor.editNode &&
340 end !== editor.document.body &&
341 end.nodeType !== 1){
342 end = end.parentNode;
343 }
344
345 var processChildren = lang.hitch(this, function(node, ary){
346 if(node.childNodes && node.childNodes.length){
347 var i;
348 for(i = 0; i < node.childNodes.length; i++){
349 var c = node.childNodes[i];
350 if(c.nodeType == 1){
351 if(editor.selection.inSelection(c)){
352 var tag = c.tagName ? c.tagName.toLowerCase() : "";
353 if(array.indexOf(this.values, tag) !== -1){
354 ary.push(c);
355 }
356 processChildren(c, ary);
357 }
358 }
359 }
360 }
361 });
362
363 var unformatNodes = lang.hitch(this, function(nodes){
364 // summary:
365 // Internal function to clear format nodes.
366 // nodes:
367 // The array of nodes to strip formatting from.
368 if(nodes && nodes.length){
369 editor.beginEditing();
370 while(nodes.length){
371 this._removeFormat(editor, nodes.pop());
372 }
373 editor.endEditing();
374 }
375 });
376
377 var clearNodes = [];
378 if(start == end){
379 //Contained within the same block, may be collapsed, but who cares, see if we
380 // have a block element to remove.
381 var block;
382 node = start;
383 while(node && node !== editor.editNode && node !== editor.document.body){
384 if(node.nodeType == 1){
385 tag = node.tagName ? node.tagName.toLowerCase() : "";
386 if(array.indexOf(this.values, tag) !== -1){
387 block = node;
388 break;
389 }
390 }
391 node = node.parentNode;
392 }
393
394 //Also look for all child nodes in the selection that may need to be
395 //cleared of formatting
396 processChildren(start, clearNodes);
397 if(block){
398 clearNodes = [block].concat(clearNodes);
399 }
400 unformatNodes(clearNodes);
401 }else{
402 // Probably a multi select, so we have to process it. Whee.
403 node = start;
404 while(editor.selection.inSelection(node)){
405 if(node.nodeType == 1){
406 tag = node.tagName ? node.tagName.toLowerCase() : "";
407 if(array.indexOf(this.values, tag) !== -1){
408 clearNodes.push(node);
409 }
410 processChildren(node, clearNodes);
411 }
412 node = node.nextSibling;
413 }
414 unformatNodes(clearNodes);
415 }
416 editor.onDisplayChanged();
417 }
418 }
419 }else{
420 editor.execCommand(command, choice);
421 }
422 },
423
424 _removeFormat: function(editor, node){
425 // summary:
426 // function to remove the block format node.
427 // node:
428 // The block format node to remove (and leave the contents behind)
429 if(editor.customUndo){
430 // So of course IE doesn't work right with paste-overs.
431 // We have to do this manually, which is okay since IE already uses
432 // customUndo and we turned it on for WebKit. WebKit pasted funny,
433 // so couldn't use the execCommand approach
434 while(node.firstChild){
435 domConstruct.place(node.firstChild, node, "before");
436 }
437 node.parentNode.removeChild(node);
438 }else{
439 // Everyone else works fine this way, a paste-over and is native
440 // undo friendly.
441 editor.selection.selectElementChildren(node);
442 var html = editor.selection.getSelectedHtml();
443 editor.selection.selectElement(node);
444 editor.execCommand("inserthtml", html || "");
445 }
446 }
447 });
448
449 // TODO: for 2.0, split into FontChoice plugin into three separate classes,
450 // one for each command (and change registry below)
451 var FontChoice = declare("dijit._editor.plugins.FontChoice", _Plugin, {
452 // summary:
453 // This plugin provides three drop downs for setting style in the editor
454 // (font, font size, and format block), as controlled by command.
455 //
456 // description:
457 // The commands provided by this plugin are:
458 //
459 // - fontName: Provides a drop down to select from a list of font names
460 // - fontSize: Provides a drop down to select from a list of font sizes
461 // - formatBlock: Provides a drop down to select from a list of block styles
462 // which can easily be added to an editor by including one or more of the above commands
463 // in the `plugins` attribute as follows:
464 //
465 // | plugins="['fontName','fontSize',...]"
466 //
467 // It is possible to override the default dropdown list by providing an Array for the `custom` property when
468 // instantiating this plugin, e.g.
469 //
470 // | plugins="[{name:'dijit._editor.plugins.FontChoice', command:'fontName', values:['Verdana','Myriad','Garamond']},...]"
471 //
472 // Alternatively, for `fontName` only, `generic:true` may be specified to provide a dropdown with
473 // [CSS generic font families](http://www.w3.org/TR/REC-CSS2/fonts.html#generic-font-families).
474 //
475 // Note that the editor is often unable to properly handle font styling information defined outside
476 // the context of the current editor instance, such as pre-populated HTML.
477
478 // useDefaultCommand: [protected] Boolean
479 // Override _Plugin.useDefaultCommand...
480 // processing is handled by this plugin, not by dijit/Editor.
481 useDefaultCommand: false,
482
483 _initButton: function(){
484 // summary:
485 // Overrides _Plugin._initButton(), to initialize the FilteringSelect+label in toolbar,
486 // rather than a simple button.
487 // tags:
488 // protected
489
490 // Create the widget to go into the toolbar (the so-called "button")
491 var clazz = {
492 fontName: _FontNameDropDown,
493 fontSize: _FontSizeDropDown,
494 formatBlock: _FormatBlockDropDown
495 }[this.command],
496 params = this.params;
497
498 // For back-compat reasons support setting custom values via "custom" parameter
499 // rather than "values" parameter. Remove in 2.0.
500 if(this.params.custom){
501 params.values = this.params.custom;
502 }
503
504 var editor = this.editor;
505 this.button = new clazz(lang.delegate({dir: editor.dir, lang: editor.lang}, params));
506
507 // Reflect changes to the drop down in the editor
508 this.own(this.button.select.on("change", lang.hitch(this, function(choice){
509 // User invoked change, since all internal updates set priorityChange to false and will
510 // not trigger an onChange event.
511
512 if(this.editor.focused){
513 // put focus back in the iframe, unless focus has somehow been shifted out of the editor completely
514 this.editor.focus();
515 }
516
517 if(this.command == "fontName" && choice.indexOf(" ") != -1){
518 choice = "'" + choice + "'";
519 }
520
521 // Invoke, the editor already normalizes commands called through its
522 // execCommand.
523 if(this.button._execCommand){
524 this.button._execCommand(this.editor, this.command, choice);
525 }else{
526 this.editor.execCommand(this.command, choice);
527 }
528 })));
529 },
530
531 updateState: function(){
532 // summary:
533 // Overrides _Plugin.updateState(). This controls updating the menu
534 // options to the right values on state changes in the document (that trigger a
535 // test of the actions.)
536 // It set value of drop down in toolbar to reflect font/font size/format block
537 // of text at current caret position.
538 // tags:
539 // protected
540 var _e = this.editor;
541 var _c = this.command;
542 if(!_e || !_e.isLoaded || !_c.length){
543 return;
544 }
545
546 if(this.button){
547 var disabled = this.get("disabled");
548 this.button.set("disabled", disabled);
549 if(disabled){
550 return;
551 }
552 var value;
553 try{
554 value = _e.queryCommandValue(_c) || "";
555 }catch(e){
556 //Firefox may throw error above if the editor is just loaded, ignore it
557 value = "";
558 }
559
560 // strip off single quotes, if any
561 var quoted = lang.isString(value) && (value.match(/'([^']*)'/) || value.match(/"([^"]*)"/));
562 if(quoted){
563 value = quoted[1];
564 }
565 if (_c === "fontSize" && !value) {
566 value = 3; // default to "small" since Editor starts out with 16px font which is considered "small".
567 }
568 if(_c === "formatBlock"){
569 if(!value || value == "p"){
570 // Some browsers (WebKit) doesn't actually get the tag info right.
571 // and IE returns paragraph when in a DIV!, so incorrect a lot,
572 // so we have double-check it.
573 value = null;
574 var elem;
575 // Try to find the current element where the caret is.
576 var sel = rangeapi.getSelection(this.editor.window);
577 if(sel && sel.rangeCount > 0){
578 var range = sel.getRangeAt(0);
579 if(range){
580 elem = range.endContainer;
581 }
582 }
583
584 // Okay, now see if we can find one of the formatting types we're in.
585 while(elem && elem !== _e.editNode && elem !== _e.document){
586 var tg = elem.tagName ? elem.tagName.toLowerCase() : "";
587 if(tg && array.indexOf(this.button.values, tg) > -1){
588 value = tg;
589 break;
590 }
591 elem = elem.parentNode;
592 }
593 if(!value){
594 // Still no value, so lets select 'none'.
595 value = "noFormat";
596 }
597 }else{
598 // Check that the block format is one allowed, if not,
599 // null it so that it gets set to empty.
600 if(array.indexOf(this.button.values, value) < 0){
601 value = "noFormat";
602 }
603 }
604 }
605 if(value !== this.button.get("value")){
606 // Set the value, but denote it is not a priority change, so no
607 // onchange fires.
608 this.button.set('value', value, false);
609 }
610 }
611 }
612 });
613
614 // Register these plugins
615 array.forEach(["fontName", "fontSize", "formatBlock"], function(name){
616 _Plugin.registry[name] = function(args){
617 return new FontChoice({
618 command: name,
619 plainText: args.plainText
620 });
621 };
622 });
623
624 // Make all classes available through AMD, and return main class
625 FontChoice._FontDropDown = _FontDropDown;
626 FontChoice._FontNameDropDown = _FontNameDropDown;
627 FontChoice._FontSizeDropDown = _FontSizeDropDown;
628 FontChoice._FormatBlockDropDown = _FormatBlockDropDown;
629 return FontChoice;
630
631 });