Returns the JavaScript code for initializing each configuration defined within tinymce.yml.
779974
def tinymce_configurations_javascript(options={})
      javascript = []

      TinyMCE::Rails.each_configuration do |name, config|
        config = config.merge(options) if options.present?
        javascript << "TinyMCERails.configuration.#{name} = #{config.to_javascript};".html_safe
      end

      safe_join(javascript, "\n")
    end
1144179
function(highlighter)
            {
                var html = '<div class="toolbar">',
                    items = sh.toolbar.items,
                    list = items.list
                    ;

                function defaultGetHtml(highlighter, name)
                {
                    return sh.toolbar.getButtonHtml(highlighter, name, sh.config.strings[name]);
                };

                for (var i = 0; i < list.length; i++)
                    html += (items[list[i]].getHtml || defaultGetHtml)(highlighter, list[i]);

                html += '</div>';

                return html;
            }
1038745
function(code)
        {
            if (code === null)
                code = '';

            this.code = code;

            var div = this.create('div');

            // create main HTML
            div.innerHTML = this.getHtml(code);

            // set up click handlers
            if (this.getParam('toolbar'))
                attachEvent(findElement(div, '.toolbar'), 'click', sh.toolbar.handler);

            if (this.getParam('quick-code'))
                attachEvent(findElement(div, '.code'), 'dblclick', quickCodeHandler);

            return div;
        }
609412
function generateCodeEntryJs (config) {

	// Read the entry point script
	var entry_js = null;
	try {
		// Read from current script
		entry_js = fs.readFileSync(ENTRY_POINT_FILENAME).toString();
	} catch (e) {
		// Read from template script
		entry_js = fs.readFileSync(__dirname + '/../templates/' + ENTRY_POINT_FILENAME + '.tmpl').toString() + '\n';
	}

	return entry_js;

}
1130184
function() {
      var UITinymceService = function() {
   	    var ID_ATTR = 'ui-tinymce';
    	// uniqueId keeps track of the latest assigned ID
    	var uniqueId = 0;
        // getUniqueId returns a unique ID
    	var getUniqueId = function() {
          uniqueId ++;
          return ID_ATTR + '-' + uniqueId;
        };
        // return the function as a public method of the service
        return {
        	getUniqueId: getUniqueId
        };
      };
      // return a new instance of the service
      return new UITinymceService();
    }
985885
private String getJavaScriptAsString() {
		InputStream fis = getClass().getResourceAsStream("RobotiumWeb.js");
		StringBuffer javaScript = new StringBuffer();

		try {
			BufferedReader input =  new BufferedReader(new InputStreamReader(fis));
			String line = null;
			while (( line = input.readLine()) != null){
				javaScript.append(line);
				javaScript.append("\n");
			}
			input.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return javaScript.toString();
	}
1042663
public function generateAndIncludeJavaScript()
    {
        $filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath() . '.js';

        $this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
            $filePath,
            function () {
                return
                    // Form initialization code.
                    $this->getFormInitializationJavaScriptAssetHandler()
                        ->getFormInitializationJavaScriptCode() .
                    LF .
                    // Fields validation code.
                    $this->getFieldsValidationJavaScriptAssetHandler()
                        ->getJavaScriptCode() .
                    LF .
                    // Fields activation conditions code.
                    $this->getFieldsActivationJavaScriptAssetHandler()
                        ->getFieldsActivationJavaScriptCode() .
                    LF .
                    // Fields validation activation conditions code.
                    $this->getFieldsValidationActivationJavaScriptAssetHandler()
                        ->getFieldsValidationActivationJavaScriptCode();
            }
        );

        $this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));

        return $this;
    }
439995
protected String defaultActionHtmlStart() throws JspException {

        StringBuffer result = new StringBuffer(2048);
        result.append(htmlStart("administration/index.html"));
        result.append("<script type=\"text/javascript\" src=\"").append(getResourceUri()).append(
            "editors/xmlcontent/edit.js\"></script>\n");
        result.append("<script type=\"text/javascript\" src=\"").append(getResourceUri()).append(
            "editors/xmlcontent/help.js\"></script>\n");
        result.append(getWidgetIncludes());
        result.append("<script type=\"text/javascript\">\n<!--\n");
        result.append("// flag indicating if form initialization is finished\n");
        result.append("var initialized = false;\n");
        result.append("// the OpenCms context path\n");
        result.append("var contextPath = \"").append(OpenCms.getSystemInfo().getOpenCmsContext()).append("\";\n\n");
        result.append("// action parameters of the form\n");
        result.append("var actionAddElement = \"").append(EDITOR_ACTION_ELEMENT_ADD).append("\";\n");
        result.append("var actionRemoveElement = \"").append(EDITOR_ACTION_ELEMENT_REMOVE).append("\";\n");
        result.append("function init() {\n");
        result.append(getWidgetInitCalls());
        result.append("\tsetTimeout(\"scrollForm();\", 200);\n");
        result.append("\tinitialized = true;\n");
        result.append("\twindow.onbeforeunload=exitEditor;\n");
        result.append("}\n\n");
        result.append("window.exitEditorCalled = false;\n");
        result.append("function exitEditor() {\n");
        result.append("\tif (window.exitEditorCalled) return;\n");
        result.append("\twindow.exitEditorCalled = true; \n");
        result.append("\ttry {\n");
        result.append("\t\t// close file selector popup if present\n");
        result.append("\t\tcloseTreeWin();\n");
        result.append("\t} catch (e) {}\n");
        result.append("}\n");
        result.append(getWidgetInitMethods());
        result.append("\n// -->\n</script>\n");
        result.append(bodyStart(null, "onload='init();'  onunload='exitEditor();'"));
        result.append(dialogStart());
        return result.toString();
    }
512675
private String createScript(String skinCookieName) {
		StringWriter sw = new StringWriter();
		try (InputStream is = ClassLoaderResourceUtils.getResourceAsStream(SCRIPT_TEMPLATE, this)) {
			IOUtils.copy(is, sw);
		} catch (IOException e) {
			Marker fatal = MarkerFactory.getMarker("FATAL");
			LOGGER.error(fatal, "a serious error occurred when initializing ThemeSwitcherJsGenerator");
			throw new BundlingProcessException(
					"Classloading issues prevent loading the themeSwitcher template to be loaded. ", e);
		}

		return sw.getBuffer().toString().replaceAll("\\{JAWR_SKIN_COOKIE_NAME\\}", skinCookieName);
	}
1302926
public function init(){
		parent::init();

		$id = $this->getRandomId();
		$view = $this->getView();
		TinymceAsset::register($view);
		TinymceLanguageAsset::register($view);
		$view->registerJs("tinymce.init({selector:'#$id',plugins:'$this->plugins',font_formats:'$this->font_formats',fontsize_formats:'$this->fontsize_formats',autosave_ask_before_unload:false,preview_styles:false,toolbar:'$this->toolbar'});");
	}
503380
function createElementScript() {
  return gulp
    .src(`./${config.src.path}/${config.src.entrypoint}`)
    .pipe(
      modifyFile(content => {
        /**
         * Strip the imports and exports out of the parse code and return them.
         *
         * @param {Program} parsedCode
         *   The parsed code.
         * @returns {{imports:Map<number,Object>, exports:Map<number,Object>}}
         */
        const stripImportsAndExports = parsedCode => {
          // Get info about the code.
          const codeIndexesToRemove = [];
          const imports = new Map();
          const exports = new Map();
          for (const [nodeIndex, node] of parsedCode.body.entries()) {
            switch (node.type) {
              case 'ImportDeclaration':
                for (const specifiers of node.specifiers) {
                  let importedName;
                  if (specifiers.type === 'ImportDefaultSpecifier') {
                    importedName = specifiers.local.name;
                  } else if (specifiers.type === 'ImportSpecifier') {
                    importedName = specifiers.imported.name;
                  }

                  if (
                    importedName != null &&
                    importedName.toLowerCase().startsWith('catalyst')
                  ) {
                    imports.set(nodeIndex, node);
                    codeIndexesToRemove.push(nodeIndex);
                  } else {
                    throw new Error(
                      `Cannot automatically process import "${importedName}."`
                    );
                  }
                }
                break;

              case 'ExportDefaultDeclaration':
              case 'ExportNamedDeclaration':
                exports.set(nodeIndex, parsedCode.body[nodeIndex]);
                codeIndexesToRemove.push(nodeIndex);
                break;

              // Different type? Do nothing.
              default:
            }
          }

          // Remove imports and exports.
          parsedCode.body = parsedCode.body.filter(
            (e, i) => !codeIndexesToRemove.includes(i)
          );

          return {
            imports: imports,
            exports: exports
          };
        };

        /**
         * Replace catalyst element's imports with globally accessible object import.
         *
         * @param {Program} parsedCode
         *   The parsed code with the imports already stripped out.
         * @param {Map<number,Object>} imports
         *   The imports that have been stripped out of the parsed code.
         */
        const processImports = (parsedCode, imports) => {
          for (const [importDefIndex, importDef] of imports) {
            for (const specifier of Object.values(importDef.specifiers)) {
              const localName = specifier.local.name;
              const importedName = specifier.imported
                ? specifier.imported.name
                : localName;

              if (importedName.toLowerCase().startsWith('catalyst')) {
                parsedCode.body.splice(
                  importDefIndex,
                  0,
                  esprima.parseScript(
                    `let ${localName} = window.CatalystElements.${importedName};`
                  )
                );
              } else {
                throw new Error(
                  `Cannot automatically process import "${importedName}."`
                );
              }
            }
          }
        };

        /**
         * Replace exports with globally accessible object exports.
         *
         * @param {Program} parsedCode
         *   The parsed code with the exports already stripped out.
         * @param {Map<number,Object>} exports
         *   The exports that have been stripped out of the parsed code.
         */
        const processExports = (parsedCode, exports) => {
          const exportNamesUsed = [];

          // Replace exports with globally accessible object exports.
          for (const [exportDefIndex, exportDef] of exports) {
            if (exportDef.declaration === null) {
              for (const specifier of Object.values(exportDef.specifiers)) {
                const localName = specifier.local.name;
                const exportedName = specifier.imported
                  ? specifier.imported.name
                  : localName;

                if (!exportNamesUsed.includes(exportedName)) {
                  parsedCode.body.splice(
                    exportDefIndex,
                    0,
                    esprima.parseScript(
                      `window.CatalystElements.${exportedName} = ${localName};`
                    )
                  );
                  exportNamesUsed.push(exportedName);
                }
              }
            } else if (exportDef.declaration.type === 'Identifier') {
              if (!exportNamesUsed.includes(exportDef.declaration.name)) {
                parsedCode.body.splice(
                  exportDefIndex,
                  0,
                  esprima.parseScript(
                    `window.CatalystElements.${exportDef.declaration.name} = ${
                      exportDef.declaration.name
                    };`
                  )
                );
                exportNamesUsed.push(exportDef.declaration.name);
              }
            } else {
              console.error(
                `Cannot automatically process declaration in ${exportDef.type}.`
              );
            }
          }
        };

        // Parse the code.
        const parsedCode = esprima.parseModule(content);

        // Run functions defined above.
        const { imports, exports } = stripImportsAndExports(parsedCode);
        processImports(parsedCode, imports);
        processExports(parsedCode, exports);

        // Generate the updated code.
        return (
          'window.CatalystElements = window.CatalystElements || {};\n' +
          `${escodegen.generate(parsedCode)}`
        );
      })
    )
    .pipe(
      rename(path => {
        path.basename = config.element.tag;
        path.extname = `.script${path.extname}`;
      })
    )
    .pipe(gulp.dest(`./${config.temp.path}`));
}
876409
protected function getPluginsConfig()
	{
		$plugins = new Dictionary;

		foreach ($this->config['plugins'] as $pluginName => $pluginConfig)
		{
			if (!isset($pluginConfig['js']))
			{
				// Skip this plugin
				continue;
			}
			$js = $pluginConfig['js'];
			unset($pluginConfig['js']);

			// Not needed in JavaScript
			unset($pluginConfig['className']);

			// Ensure that quickMatch is UTF-8 if present
			if (isset($pluginConfig['quickMatch']))
			{
				// Well-formed UTF-8 sequences
				$valid = [
					'[[:ascii:]]',
					// [1100 0000-1101 1111] [1000 0000-1011 1111]
					'[\\xC0-\\xDF][\\x80-\\xBF]',
					// [1110 0000-1110 1111] [1000 0000-1011 1111]{2}
					'[\\xE0-\\xEF][\\x80-\\xBF]{2}',
					// [1111 0000-1111 0111] [1000 0000-1011 1111]{3}
					'[\\xF0-\\xF7][\\x80-\\xBF]{3}'
				];

				$regexp = '#(?>' . implode('|', $valid) . ')+#';

				// Keep only the first valid sequence of UTF-8, or unset quickMatch if none is found
				if (preg_match($regexp, $pluginConfig['quickMatch'], $m))
				{
					$pluginConfig['quickMatch'] = $m[0];
				}
				else
				{
					unset($pluginConfig['quickMatch']);
				}
			}

			/**
			* @var array Keys of elements that are kept in the global scope. Everything else will be
			*            moved into the plugin's parser
			*/
			$globalKeys = [
				'quickMatch'  => 1,
				'regexp'      => 1,
				'regexpLimit' => 1
			];

			$globalConfig = array_intersect_key($pluginConfig, $globalKeys);
			$localConfig  = array_diff_key($pluginConfig, $globalKeys);

			if (isset($globalConfig['regexp']) && !($globalConfig['regexp'] instanceof Code))
			{
				$globalConfig['regexp'] = new Code(RegexpConvertor::toJS($globalConfig['regexp'], true));
			}

			$globalConfig['parser'] = new Code(
				'/**
				* @param {!string} text
				* @param {!Array.<Array>} matches
				*/
				function(text, matches)
				{
					/** @const */
					var config=' . $this->encode($localConfig) . ';
					' . $js . '
				}'
			);

			$plugins[$pluginName] = $globalConfig;
		}

		return $plugins;
	}
250077
public function getJavascripts()
    {
        $self = $this;
        $parse_javascripts = function ($params, $javascripts) use ($self) {
            foreach ($params as $js) {
                if (is_string($js)) {
                    $js = array(
                        'path' => $js,
                    );
                } elseif (isset($js['route'])) {
                    $js = array(
                        'path' => $self->getGenerator()
                                        ->getRouter()
                                        ->generate($js['route'], $js['routeparams']),
                    );
                }

                $javascripts[] = $js;
            }

            return $javascripts;
        };

        // From config.yml
        $javascripts = $parse_javascripts(
            $this->getGenerator()->getFromBundleConfig('javascripts', array()), array()
        );

        // From generator.yml
        $javascripts = $parse_javascripts(
            $this->getVariable('javascripts', array()), $javascripts
        );

        return $javascripts;
    }
1129336
public function getJavaScriptCode()
    {
        $fieldsJavaScriptCode = [];
        $formConfiguration = $this->getFormObject()->getConfiguration();

        foreach ($formConfiguration->getFields() as $field) {
            $fieldsJavaScriptCode[] = $this->processField($field);
        }

        $formName = GeneralUtility::quoteJSvalue($this->getFormObject()->getName());
        $fieldsJavaScriptCode = implode(CRLF, $fieldsJavaScriptCode);

        return <<<JS
(function() {
    Fz.Form.get(
        $formName,
        function(form) {
            var field = null;

$fieldsJavaScriptCode
        }
    );
})();
JS;
    }
1191283
function () {
  var source = editors.javascript.editor.getCode();
  
  // default jshint options
  var options = {
    'eqnull': true
  };
  
  $.extend(options, jsbin.settings.jshintOptions || {});
  var ok = JSHINT(source, options);

  return ok ? true : JSHINT.data();
}
742612
protected Map<String, Object> initializeVariables(final Set<StringTextValue<?>> allSettings)
	{
		final Map<String, Object> variables = new HashMap<>();

		// 2. put the component id that is the initiator for the js code...
		if (withComponentId)
		{
			variables.put(JavascriptGenerator.COMPONENT_ID, componentId);
		}
		for (final StringTextValue<?> textValue : allSettings)
		{
			if (!textValue.isInitialValue())
			{
				switch (textValue.getType())
				{
					case STRING :
						if (textValue.getQuotationMarkType().equals(QuotationMarkType.NONE))
						{
							variables.put(textValue.getName(), textValue.getValue());
							break;
						}
						TextTemplateExtensions.setVariableWithSingleQuotationMarks(
							textValue.getName(), textValue.getValue(), variables);
						break;
					case ENUM :
						TextTemplateExtensions.setVariableWithSingleQuotationMarks(
							textValue.getName(), ((ValueEnum)textValue.getValue()).getValue(),
							variables);
						break;
					case STRING_INTEGER :
						TextTemplateExtensions.setVariableWithSingleQuotationMarks(
							textValue.getName(), textValue.getValue(), variables);
						break;
					default :
						variables.put(textValue.getName(), textValue.getValue());
						break;
				}
			}
		}
		return variables;
	}
357000
public function htmlTextarea($name, $value = null, $htmlOptions = array(), $tinyMCETemplate = 'basic')
    {
        $r = Html::get()->mpfScriptFile('jquery.js') . Html::get()->mpfScriptFile('tinymce/tinymce.min.js') . Html::get()->mpfScriptFile('tinymce/jquery.tinymce.min.js');
        if (!isset($htmlOptions['id'])) {
            $htmlOptions['id'] = 'tinymce_' . uniqid();
        }
        $htmlOptions['class'] = (isset($htmlOptions['class']) ? $htmlOptions['class'] . ' ' : '') . 'input tinymce-textarea';
        $r .= $this->textarea($name, $value, $htmlOptions);
        $options = json_encode($this->tinyMCEOptionTemplates[$tinyMCETemplate]);
        $r .= Html::get()->script("$('#{$htmlOptions['id']}').tinymce($options)");
        return $r;
    }