A field that allows editing of javascript
325006
function JavascriptField(type, options) {
  Field.call(this, type, options);

  this.onInputChange = this.onInputChange.bind(this);
  this.arg = new ScriptArgument('', '{ ', ' }');

  this.element = util.createElement(this.document, 'div');

  this.input = util.createElement(this.document, 'input');
  this.input.type = 'text';
  this.input.addEventListener('keyup', this.onInputChange, false);
  this.input.classList.add('gcli-field');
  this.input.classList.add('gcli-field-javascript');
  this.element.appendChild(this.input);

  this.menu = new Menu({
    document: this.document,
    field: true,
    type: type
  });
  this.element.appendChild(this.menu.element);

  var initial = new Conversion(undefined, new ScriptArgument(''),
                               Status.INCOMPLETE, '');
  this.setConversion(initial);

  this.onFieldChange = util.createEvent('JavascriptField.onFieldChange');

  // i.e. Register this.onItemClick as the default action for a menu click
  this.menu.onItemClick.add(this.itemClicked, this);
}
74385
function initAceEditor(themeId, folderName, fileName, text, mode) {
        hideImageHolder();
        $("#" + editorId).show();
        var doc = new Document(text);
        var session = new EditSession(doc, "ace/mode/" + mode);
        session.setUndoManager(new UndoManager());
        editor.setSession(session);

        //bind change event for text changes in opened file and save them.
        doc.on('change', function (e) {
            // e.type, etc
            console.log(e);
            saveFileChanges(themeId, folderName, fileName, doc.getValue());
        });
    }
905831
function (title, fields, cmd) {
            var t = this,
                prefix = t.o.prefix,
                lg = t.lang,
                html = '';

            $.each(fields, function (fieldName, field) {
                var l = field.label || fieldName,
                    n = field.name || fieldName,
                    a = field.attributes || {};

                var attr = Object.keys(a).map(function (prop) {
                    return prop + '="' + a[prop] + '"';
                }).join(' ');

                html += '<label><input type="' + (field.type || 'text') + '" name="' + n + '"' +
                    (field.type === 'checkbox' && field.value ? ' checked="checked"' : ' value="' + (field.value || '').replace(/"/g, '&quot;')) +
                    '"' + attr + '><span class="' + prefix + 'input-infos"><span>' +
                    (lg[l] ? lg[l] : l) +
                    '</span></span></label>';
            });

            return t.openModal(title, html)
                .on(CONFIRM_EVENT, function () {
                    var $form = $('form', $(this)),
                        valid = true,
                        values = {};

                    $.each(fields, function (fieldName, field) {
                        var n = field.name || fieldName;

                        var $field = $('input[name="' + n + '"]', $form),
                            inputType = $field.attr('type');

                        switch (inputType.toLowerCase()) {
                            case 'checkbox':
                                values[n] = $field.is(':checked');
                                break;
                            case 'radio':
                                values[n] = $field.filter(':checked').val();
                                break;
                            default:
                                values[n] = $.trim($field.val());
                                break;
                        }
                        // Validate value
                        if (field.required && values[n] === '') {
                            valid = false;
                            t.addErrorOnModalField($field, t.lang.required);
                        } else if (field.pattern && !field.pattern.test(values[n])) {
                            valid = false;
                            t.addErrorOnModalField($field, field.patternError);
                        }
                    });

                    if (valid) {
                        t.restoreRange();

                        if (cmd(values, fields)) {
                            t.syncCode();
                            t.$c.trigger('tbwchange');
                            t.closeModal();
                            $(this).off(CONFIRM_EVENT);
                        }
                    }
                })
                .one(CANCEL_EVENT, function () {
                    $(this).off(CONFIRM_EVENT);
                    t.closeModal();
                });
        }
575610
def field(self, name, fieldType="C", size="50", decimal=0):
        """"""
        self.fields.append((name, fieldType, size, decimal))
1293382
def edit_form(self, obj):
        """"""
        form = super(OAISetModelView, self).edit_form(obj)
        del form.spec
        return form
947298
function() {

      var x, arr, el, configs, model, value, attr, parts, style;

      // setup config events
      arr = document.querySelectorAll('.hashedit-config, .hashedit-modal');

      for (x = 0; x < arr.length; x += 1) {

        // delegate on .hashedit-config
        ['propertychange', 'change', 'click', 'keyup', 'input', 'paste'].forEach
          (function(e) {

            arr[x].addEventListener(e, function(e) {

              el = e.target;

              if (el.hasAttribute('hashedit-cancel-modal')) {

                // hide .hashedit-config, .hashedit-modal
                configs = document.querySelectorAll(
                  '.hashedit-modal');

                for (x = 0; x < configs.length; x += 1) {
                  configs[x].removeAttribute('visible');
                }

              }

              // look for [data-model]
              if (el.hasAttribute('data-model')) {

                model = el.getAttribute('data-model');
                value = '';
                attr = '';

                value = el.value;

                if (model.indexOf('node.') != -1) {
                  parts = model.split('.');

                  // converts camelcase to hyphens, sets attribute
                  if (parts.length > 1) {

                    // get property
                    attr = parts[1].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

                    if(attr === 'html') {
                      hashedit.current.node.innerHTML = value;

                      hashedit.setupElementMenu(hashedit.current.node);
                    }
                    else { // other elements

                      // get currentValue
                      var old = hashedit.current.node.getAttribute(attr);

                      // set attribute
                      hashedit.current.node.setAttribute(attr, value);

                      if(hashedit.debug === true) {
                        console.log('setattribute on [data-model]');
                        console.log('attr=' + attr + 'value=' + value);
                      }

                      // create text style
                      style = hashedit.createTextStyle(hashedit.current.node);

                      hashedit.current.node.setAttribute('style', style);

                      // call change event
                      for (x = 0; x < hashedit.menu.length; x += 1) {

                        if(hashedit.current.node.matches(hashedit.menu[x].selector)) {
                          if(hashedit.menu[x].change) {
                            hashedit.menu[x].change(attr, value, old);
                          }

                        }

                      }

                    }


                  }
                }

                if (model.indexOf('link.') != -1) {
                  parts = model.split('.');

                  // converts camelcase to hyphens, sets attribute
                  if (parts.length > 1) {

                    // get property
                    attr = parts[1].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

                    // set attribute
                    hashedit.currLink.setAttribute(attr, value);

                    // get current node
                    if(hashedit.current.node == null){
                      hashedit.current.node = hashedit.findParentBySelector(hashedit.currLink, '[hashedit-element]');
                    }

                    // fire event
                    hashedit.current.node.dispatchEvent(new Event(
                      'input', {
                        'bubbles': true
                      }));

                  }
                }

                if (model.indexOf('image.') != -1) {
                  parts = model.split('.');

                  // converts camelcase to hyphens, sets attribute
                  if (parts.length > 1) {

                    // get property
                    attr = parts[1].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

                    // set attribute
                    hashedit.current.image.setAttribute(attr, value);

                    hashedit.current.node = hashedit.findParentBySelector(hashedit.current.image, '[hashedit-element]');

                    // fire event
                    if (hashedit.current.node !== null) {

                      hashedit.current.node.dispatchEvent(new Event(
                        'input', {
                          'bubbles': true
                        }));
                    }

                  }
                }

              }

            }, false);

          });

      }

    }
728386
function( editor, output ) {
				var env = CKEDITOR.env;

				var id = 'cke_' + this.id;
				var clickFn = CKEDITOR.tools.addFunction( function( el ) {
					// Restore locked selection in Opera.
					if ( selLocked ) {
						editor.unlockSelection( 1 );
						selLocked = 0;
					}
					instance.execute( el );
				}, this );

				var combo = this;
				var instance = {
					id: id,
					combo: this,
					focus: function() {
						var element = CKEDITOR.document.getById( id ).getChild( 1 );
						element.focus();
					},
					execute: function( el ) {
						var _ = combo._;

						if ( _.state == CKEDITOR.TRISTATE_DISABLED )
							return;

						combo.createPanel( editor );

						if ( _.on ) {
							_.panel.hide();
							return;
						}

						combo.commit();
						var value = combo.getValue();
						if ( value )
							_.list.mark( value );
						else
							_.list.unmarkAll();

						_.panel.showBlock( combo.id, new CKEDITOR.dom.element( el ), 4 );
					},
					clickFn: clickFn
				};

				function updateState() {
					// Don't change state while richcombo is active (#11793).
					if ( this.getState() == CKEDITOR.TRISTATE_ON )
						return;

					var state = this.modes[ editor.mode ] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;

					if ( editor.readOnly && !this.readOnly )
						state = CKEDITOR.TRISTATE_DISABLED;

					this.setState( state );
					this.setValue( '' );

					// Let plugin to disable button.
					if ( state != CKEDITOR.TRISTATE_DISABLED && this.refresh )
						this.refresh();
				}

				// Update status when activeFilter, mode, selection or readOnly changes.
				editor.on( 'activeFilterChange', updateState, this );
				editor.on( 'mode', updateState, this );
				editor.on( 'selectionChange', updateState, this );
				// If this combo is sensitive to readOnly state, update it accordingly.
				!this.readOnly && editor.on( 'readOnly', updateState, this );

				var keyDownFn = CKEDITOR.tools.addFunction( function( ev, element ) {
					ev = new CKEDITOR.dom.event( ev );

					var keystroke = ev.getKeystroke();

					// ARROW-DOWN
					// This call is duplicated in plugins/toolbar/plugin.js in itemKeystroke().
					// Move focus to the first element after drop down was opened by the arrow down key.
					if ( keystroke == 40 ) {
						editor.once( 'panelShow', function( evt ) {
							evt.data._.panel._.currentBlock.onKeyDown( 40 );
						} );
					}

					switch ( keystroke ) {
						case 13: // ENTER
						case 32: // SPACE
						case 40: // ARROW-DOWN
							// Show panel
							CKEDITOR.tools.callFunction( clickFn, element );
							break;
						default:
							// Delegate the default behavior to toolbar button key handling.
							instance.onkey( instance, keystroke );
					}

					// Avoid subsequent focus grab on editor document.
					ev.preventDefault();
				} );

				var focusFn = CKEDITOR.tools.addFunction( function() {
					instance.onfocus && instance.onfocus();
				} );

				var selLocked = 0;

				// For clean up
				instance.keyDownFn = keyDownFn;

				var params = {
					id: id,
					name: this.name || this.command,
					label: this.label,
					title: this.title,
					cls: this.className || '',
					titleJs: env.gecko && !env.hc ? '' : ( this.title || '' ).replace( "'", '' ),
					keydownFn: keyDownFn,
					focusFn: focusFn,
					clickFn: clickFn
				};

				rcomboTpl.output( params, output );

				if ( this.onRender )
					this.onRender();

				return instance;
			}
305846
function(editor, pos) {
			var allowedSyntaxes = {'html': 1, 'xml': 1, 'xsl': 1, 'jsx': 1};
			var syntax = editor.getSyntax();
			if (syntax in allowedSyntaxes) {
				var content = editor.getContent();
				if (typeof pos === 'undefined') {
					pos = editor.getCaretPos();
				}

				var tag = htmlMatcher.find(content, pos);
				if (tag && tag.type == 'tag') {
					var startTag = tag.open;
					var contextNode = {
						name: startTag.name,
						attributes: [],
						match: tag
					};
					
					// parse attributes
					var tagTree = xmlEditTree.parse(startTag.range.substring(content));
					if (tagTree) {
						contextNode.attributes = tagTree.getAll().map(function(item) {
							return {
								name: item.name(),
								value: item.value()
							};
						});
					}
					
					return contextNode;
				}
			}
			
			return null;
		}
547411
function() {
	   if(!inputEx.TinyMCEfieldsNumber) { inputEx.TinyMCEfieldsNumber = 0; }
	   
	   var id = "inputEx-TinyMCEField-"+inputEx.TinyMCEfieldsNumber;
		this.id = id;
	   var attributes = {id:id, className: "mceAdvanced"};
      if(this.options.name) { attributes.name = this.options.name; }

	   this.el = inputEx.cn('textarea', attributes);
	   
	   inputEx.TinyMCEfieldsNumber += 1;
	   this.fieldContainer.appendChild(this.el);
			
		this.editor = new tinymce.Editor(this.id, this.options.opts);

		// Adds an observer to the onInit event using the render method
		this.editorReady = false;		
		var that = this;
		this.editor.onInit.add(function(ed) {
			that.editorReady = true;
		});

		this.editor.render();
	}
564264
function( field ){
    var tagName = field.tagName.toLowerCase();

    if( tagName == 'input' && field.type == 'checkbox' ){
        return field.checked;
    }

    if( tagName == 'select' ){
        return field.options[field.selectedIndex].value;
    }

    return field.value;
}
1055691
function( field, prefix ) {
					var self = this;
					if ( 'onpropertychange' in field ) {
						field.get(0).onpropertychange = function() {
							self.saveToBrowserStorage( prefix, field.val() );
						};
					} else {
						field.get(0).oninput = function() {
							self.saveToBrowserStorage( prefix, field.val() );
						};
					}
					if ( this.isCKEditorExists() ) {
						var editor = CKEDITOR.instances[ field.attr("name") ] || CKEDITOR.instances[ field.attr("id") ];
						if ( editor ) {
							editor.document.on( 'keyup', function() {
								editor.updateElement();
								self.saveToBrowserStorage( prefix, field.val() );
							} );
						}
					}
				}
15447
function toggleEdit() {
    document.body.classList.toggle('form-rendered', editing)
    if (!editing) {
      $('.build-wrap').formBuilder('setData', $('.render-wrap').formRender('userData'))
    } else {
      const formRenderData = $('.build-wrap').formBuilder('getData', dataType)
      $('.render-wrap').formRender({
        formData: formRenderData,
        templates: templates,
        dataType,
      })
      window.sessionStorage.setItem('formData', formRenderData)
    }
    return (editing = !editing)
  }
856369
function(field) {
            var
              $field      = module.get.field(field.identifier),
              fieldValid  = true,
              fieldErrors = []
            ;
            if(field.rules !== undefined) {
              $.each(field.rules, function(index, rule) {
                if( module.has.field(field.identifier) && !( module.validate.rule(field, rule) ) ) {
                  module.debug('Field is invalid', field.identifier, rule.type);
                  fieldErrors.push(rule.prompt);
                  fieldValid = false;
                }
              });
            }
            if(fieldValid) {
              module.remove.prompt(field, fieldErrors);
              $.proxy(settings.onValid, $field)();
            }
            else {
              formErrors = formErrors.concat(fieldErrors);
              module.add.prompt(field, fieldErrors);
              $.proxy(settings.onInvalid, $field)(fieldErrors);
              return false;
            }
            return true;
          }
814295
function (type) {
    return function (opts) {
        var opt = opts || {};
        var userAttrs = getUserAttrs(opt);
        var w = {
            classes: opt.classes,
            type: type,
            formatValue: function (value) {
                return (value || value === 0) ? value : null;
            }
        };
        w.toHTML = function (name, field) {
            var f = field || {};
            var attrs = {
                type: type,
                name: name,
                id: f.id === false ? false : (f.id || true),
                classes: w.classes,
                value: w.formatValue(f.value)
            };
            return tag('input', [attrs, userAttrs, w.attrs || {}]);
        };
        return w;
    };
}
905998
def _make_field_info(self, field_name, field):
        
        supported_field_types = (
            (Integer, 'integer'),
            (Float, 'float'),
            (Boolean, 'boolean'),
            (String, 'string'),
            (List, 'list'),
            (DateTime, 'datepicker'),
            (JSONField, 'generic'),  # This is last so as a last resort we display a text field w/ the JSON string
        )
        if self.service_declaration("i18n"):
            ugettext = self.ugettext
        else:

            def ugettext(text):
                """ Dummy ugettext method that doesn't do anything """
                return text

        info = {
            'name': field_name,
            'display_name': ugettext(field.display_name) if field.display_name else "",
            'is_set': field.is_set_on(self),
            'default': field.default,
            'value': field.read_from(self),
            'has_values': False,
            'help': ugettext(field.help) if field.help else "",
            'allow_reset': field.runtime_options.get('resettable_editor', True),
            'list_values': None,  # Only available for List fields
            'has_list_values': False,  # True if list_values_provider exists, even if it returned no available options
        }
        for type_class, type_name in supported_field_types:
            if isinstance(field, type_class):
                info['type'] = type_name
                # If String fields are declared like String(..., multiline_editor=True), then call them "text" type:
                editor_type = field.runtime_options.get('multiline_editor')
                if type_class is String and editor_type:
                    if editor_type == "html":
                        info['type'] = 'html'
                    else:
                        info['type'] = 'text'
                if type_class is List and field.runtime_options.get('list_style') == "set":
                    # List represents unordered, unique items, optionally drawn from list_values_provider()
                    info['type'] = 'set'
                elif type_class is List:
                    info['type'] = "generic"  # disable other types of list for now until properly implemented
                break
        if "type" not in info:
            raise NotImplementedError("StudioEditableXBlockMixin currently only supports fields derived from JSONField")
        if info["type"] in ("list", "set"):
            info["value"] = [json.dumps(val) for val in info["value"]]
            info["default"] = json.dumps(info["default"])
        elif info["type"] == "generic":
            # Convert value to JSON string if we're treating this field generically:
            info["value"] = json.dumps(info["value"])
            info["default"] = json.dumps(info["default"])
        elif info["type"] == "datepicker":
            if info["value"]:
                info["value"] = info["value"].strftime("%m/%d/%Y")
            if info["default"]:
                info["default"] = info["default"].strftime("%m/%d/%Y")

        if 'values_provider' in field.runtime_options:
            values = field.runtime_options["values_provider"](self)
        else:
            values = field.values
        if values and not isinstance(field, Boolean):
            # This field has only a limited number of pre-defined options.
            # Protip: when defining the field, values= can be a callable.
            if isinstance(field.values, dict) and isinstance(field, (Float, Integer)):
                # e.g. {"min": 0 , "max": 10, "step": .1}
                for option in field.values:
                    if option in ("min", "max", "step"):
                        info[option] = field.values.get(option)
                    else:
                        raise KeyError("Invalid 'values' key. Should be like values={'min': 1, 'max': 10, 'step': 1}")
            elif isinstance(values[0], dict) and "display_name" in values[0] and "value" in values[0]:
                # e.g. [ {"display_name": "Always", "value": "always"}, ... ]
                for value in values:
                    assert "display_name" in value and "value" in value
                info['values'] = values
            else:
                # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format
                info['values'] = [{"display_name": text_type(val), "value": val} for val in values]
            info['has_values'] = 'values' in info
        if info["type"] in ("list", "set") and field.runtime_options.get('list_values_provider'):
            list_values = field.runtime_options['list_values_provider'](self)
            # list_values must be a list of values or {"display_name": x, "value": y} objects
            # Furthermore, we need to convert all values to JSON since they could be of any type
            if list_values and isinstance(list_values[0], dict) and "display_name" in list_values[0]:
                # e.g. [ {"display_name": "Always", "value": "always"}, ... ]
                for entry in list_values:
                    assert "display_name" in entry and "value" in entry
                    entry["value"] = json.dumps(entry["value"])
            else:
                # e.g. [1, 2, 3] - we need to convert it to the [{"display_name": x, "value": x}] format
                list_values = [json.dumps(val) for val in list_values]
                list_values = [{"display_name": text_type(val), "value": val} for val in list_values]
            info['list_values'] = list_values
            info['has_list_values'] = True
        return info
1151466
function() {
			var editor = this.undoManager.editor,
				editable = editor.editable(),
				that = this;

			// We'll create a snapshot here (before DOM modification), because we'll
			// need unmodified content when we got keygroup toggled in keyup.
			editable.attachListener( editable, 'keydown', function( evt ) {
				that.onKeydown( evt );

				// On IE keypress isn't fired for functional (backspace/delete) keys.
				// Let's pretend that something's changed.
				if ( UndoManager.ieFunctionalKeysBug( evt.data.getKey() ) ) {
					that.onInput();
				}
			}, null, null, 999 );

			// Only IE can't use input event, because it's not fired in contenteditable.
			editable.attachListener( editable, ( CKEDITOR.env.ie ? 'keypress' : 'input' ), that.onInput, that, null, 999 );

			// Keyup executes main snapshot logic.
			editable.attachListener( editable, 'keyup', that.onKeyup, that, null, 999 );

			// On paste and drop we need to ignore input event.
			// It would result with calling undoManager.type() on any following key.
			editable.attachListener( editable, 'paste', that.ignoreInputEventListener, that, null, 999 );
			editable.attachListener( editable, 'drop', that.ignoreInputEventListener, that, null, 999 );

			// Click should create a snapshot if needed, but shouldn't cause change event.
			// Don't pass onNavigationKey directly as a listener because it accepts one argument which
			// will conflict with evt passed to listener.
			// #12324 comment:4
			editable.attachListener( editable.isInline() ? editable : editor.document.getDocumentElement(), 'click', function() {
				that.onNavigationKey();
			}, null, null, 999 );

			// When pressing `Tab` key while editable is focused, `keyup` event is not fired.
			// Which means that record for `tab` key stays in key events stack.
			// We assume that when editor is blurred `tab` key is already up.
			editable.attachListener( this.undoManager.editor, 'blur', function() {
				that.keyEventsStack.remove( 9 /*Tab*/ );
			}, null, null, 999 );
		}
582160
function() {
	   Event.addListener(this.el, "change", this.onChange, this, true);

       if (YAHOO.env.ua.ie){ // refer to inputEx-95
            var field = this.el;
            new YAHOO.util.KeyListener(this.el, {keys:[13]}, {fn:function(){
                field.blur();
                field.focus();
            }}).enable();
       }

	   Event.addFocusListener(this.el, this.onFocus, this, true);
		Event.addBlurListener(this.el, this.onBlur, this, true);
	   Event.addListener(this.el, "keypress", this.onKeyPress, this, true);
	   Event.addListener(this.el, "keyup", this.onKeyUp, this, true);
   }