wp_enqueue_code_editor() WP 4.9.0

Підключає все необхідне (скрипти, стилі, налаштування, мови) для використання вбудованого у WordPress редактора коду.

Для редагування коду в полі textarea використовується бібліотека CodeMirror з версії WP 4.9.

Що виконує функція?

Функція ставить на чергу підключення такі базові скрипти і стилі WP:

wp_enqueue_script( 'code-editor');
wp_enqueue_style( 'code-editor');

Далі, на основі зазначеного або визначився тип коду, який буде використовуватися в textarea , може підключити додаткові скрипти lint/hint, потрібні CodeMirror. Наприклад, при типі HTML ці доповнення будуть автозакривати теги, виводити підказки і т.д.

wp_enqueue_script( 'htmlhint' );
wp_enqueue_script( 'csslint' );
wp_enqueue_script( 'jshint' );

Далі, на основі переданих функцій параметрів, збирає параметри для CodeMirror та замінює/доповнює дефолтні параметри: wp.codeEditor.defaultSettings .

Фільтр wp_code_editor_settings

Плагіни можуть відфільтрувати параметри CodeMirror, перш ніж вони будуть об’єднані з дефолтними, через фільтр wp_code_editor_settings .

Якщо фільтр поверне false , то функція не підключить жодних скриптів.

Вимкнення підсвічування

Якщо в опціях поточного користувача підсвічування синтаксису відключено, то функція нічого не робитиме і перерве свою роботу на самому початку:

Глобальна змінна wp.codeEditor

При підключенні скрипту CodeMirror, в JS не реєструється глобальна змінна, щоб не було конфлікту, якщо якийсь плагін використовує свою версію цієї бібліотеки. Примірник об’єкта CodeMirror знаходиться у змінній wp.codeEditor . Тобто. можна написати так: window.CodeMirror = wp.CodeMirror .

Метод initialize()wp.codeEditor.initialize( id, options ) – це аналог CodeMirror.fromTextArea() . Першим аргументом він приймає id або об’єкт елемента текстовоїобласті, а другим опції для CodeMirror. Такі опції повертає ця функція лише у вигляді PHP масиву.

Також, в опціях для методу initialize() можна вказати додаткові callback функції: onChangeLintingErrors, onUpdateErrorNotice, onTabPrevious, onTabNext. Ці коллбеки дозволяють керувати відображенням блоків з lint помилками та навігацією з клавіатури (для підказок).

Працює на основі:
wp_enqueue_script() ,
wp_enqueue_style()

Хуки з функції

Повертає

Массив|false. Масив налаштувань для CodeMirror у PHP форматі.

Використання

$settings = wp_enqueue_code_editor( $args );
$args
(масив) (обов’язковий)

Параметри.

  • type (рядок)
    MIME – тип файлу, який збираємося редагувати. Наприклад:text/html, говорить про те, що в полі редагування буде написано HTML код. Можливі типи:

    typeмова
    text/htmlhtml
    xmlxml
    application/javascriptjavascript
    jsonjson
    application/x-httpd-phpphp
    text/x-sqlsql
    text/csscss
    text/x-scssscss
    text/x-lessless
    text/x-sasssass
    text/nginxnginx
    text/x-markdownmarkdown
    text/x-gfmgfm
    jsxjsx
    text/x-diffdiff
  • file (рядок)
    Альтернатива параметру $type . Назва файлу, наприклад file.php . Використовується, щоб визначити тип ($type) для розширення файлу.

  • codemirror (масив)
    Дозволяє безпосередньо вказати параметри для CodeMirror. Перепише поточні. Масив має таку ж структуру, як ми передавали параметри CodeMirror в JS. Див. документацію .

  • csslint (масив)
    Дозволяє безпосередньо вказати параметри для CSSLint. Перепише поточні.

  • jshint (масив)
    Дозволяє безпосередньо вказати параметри для JSHint. Перепише поточні.

  • htmlhint (масив)
    Дозволяє безпосередньо вказати параметри для HTMLHint. Перепише поточні.

  • theme (WP_Theme)
    Тема, яка редагується. Для сторінки редагування файлів теми.

  • plugin (рядок)
    Плагін який редагується. Для сторінки редагування файлів плагіна.

Приклади

0

#1 Приклад створення редактора коду для тексту

Для цього, давайте перетворимо поле Біографія на сторінці редагування профілю на редактор HTML коду.

Щоб краще розуміти що робить код, подивимося на HTML код textarea, який у результаті перетвориться на редактор коду:

<textarea id="description" name="description" rows="5" cols="30"></textarea>
add_action( 'admin_enqueue_scripts', function() {
	if ( 'profile' !== get_current_screen()->id ) {
		return;
	}

	// Підключаємо редактор коду для HTML.
	$settings = wp_enqueue_code_editor( array( 'type' => 'text/html' ) );

	// нічого не робимо, якщо CodeMirror вимкнений.
	if ( false === $settings ) {
		return;
	}

	// ініціалізація
	wp_add_inline_script(
		'code-editor',
		sprintf( 'jQuery( function() { wp.codeEditor.initialize( "description", %s ); } );', wp_json_encode( $settings ) )  
	);

} );

В результаті отримаємо:

Змінна $settings містить такий масив:

Array
(
	[codemirror] => Array
		(
			[indentUnit] => 4
			[indentWithTabs] => 1
			[inputStyle] => contenteditable
			[lineNumbers] => 1
			[lineWrapping] => 1
			[styleActiveLine] => 1
			[continueComments] => 1
			[extraKeys] => Array
				(
					[Ctrl-Space] => autocomplete
					[Ctrl-/] => toggleComment
					[Cmd-/] => toggleComment
					[Alt-F] => findPersistent
					[Ctrl-F] => findPersistent
					[Cmd-F] => findPersistent
				)

			[direction] => ltr
			[gutters] => Array
				(
					[0] => CodeMirror-lint-markers
				)

			[mode] => css
			[lint] => 1
			[autoCloseBrackets] => 1
			[matchBrackets] => 1
		)

	[csslint] => Array
		(
			[errors] => 1
			[box-model] => 1
			[display-property-grouping] => 1
			[duplicate-properties] => 1
			[known-properties] => 1
			[outline-none] => 1
		)

	[jshint] => Array
		(
			[boss] => 1
			[Curly] => 1
			[eqeqeq] => 1
			[eqnull] => 1
			[es3] => 1
			[expr] => 1
			[immed] => 1
			[noarg] => 1
			[nonbsp] => 1
			[onevar] => 1
			[quotmark] => single
			[trailing] => 1
			[undef] => 1
			[unused] => 1
			[browser] => 1
			[globals] => Array
				(
					[_] =>
					[Backbone] =>
					[jQuery] =>
					[JSON] =>
					[wp] =>
				)

		)

	[htmlhint] => Array
		(
			[tagname-lowercase] => 1
			[attr-lowercase] => 1
			[attr-value-double-quotes] =>
			[doctype-first] =>
			[tag-pair] => 1
			[spec-char-escape] => 1
			[id-unique] => 1
			[src-not-empty] => 1
			[attr-no-duplication] => 1
			[alt-require] => 1
			[space-tab-mixed-disabled] => tab
			[attr-unsafe-chars] => 1
		)

)
0

#2 Виведення редактора css коду з оновленням textarea

У цьому прикладі показано як зібрати стилі редактора JS без передачі їх з PHP. А також показано як при будь-якій зміні коду оновлювати значення тексту регіону і запускати подію change.

add_action( 'admin_enqueue_scripts', function() {

	if ( 'toplevel_page_custom_css' !== get_current_screen()->id ) {
		return;
	}

	// Підключаємо редактор коду для HTML.
	$settings = wp_enqueue_code_editor( [ 'type' => 'text/css' ] );

	// CodeMirror вимкнено.
	if ( false === $settings ) {
		return;
	}

	// ініціалізація
	wp_add_inline_script(
		'code-editor',
		<<<JS
		document.addEventListener( 'DOMContentLoaded', function(){

			const textarea = document.querySelector( '#textarea_css_editor' )

			const settings = wp.codeEditor.defaultSettings? _.clone( wp.codeEditor.defaultSettings ) : {}

			settings.codemirror = _.extend( {}, settings.codemirror, {
				indentUnit: 2,
				tabSize: 2,
				mode: 'css',
			} )

			console.log( settings.codemirror )

			const editor = wp.codeEditor.initialize(textarea, settings)

			document.querySelector( '.CodeMirror-code' ).addEventListener( 'keyup', ev => {
				editor.codemirror.save()
				jQuery(textarea).trigger('change')
			} )

		} )
		JS,
	);

} );

JS функція wp.codeEditor.initialize(textarea, settings)

Знаходиться у файлі wp-admin/js/code-editor.js

Параметри:

textarea
(string|jQuery|Element) (обов’язковий)
Атрибут id елемента у вигляді рядка, jquery елемент або DOM елемент поля textarea, для якого буде використано редактор.
settings
(об’єкт) (обов’язковий)

JS об’єкт налаштувань для codeMirror. Його як PHP масиву повертає ця функція: wp_enqueue_code_editor() .

Що можна вказати в об’єкті:

  • settings.onChangeLintingErrors (Function) – Зворотний виклик при зміні помилок компонування.
  • settings.onUpdateErrorNotice (Function) – Зворотний дзвінок для відображення повідомлення про помилку.
  • settings.onTabPrevious (Function) – Зворотний дзвінок для обробки натискання на TAB до попереднього елемента.
  • settings.onTabNext (Function) – Зворотний дзвінок для обробки натискання на TAB до наступного елемента.
  • settings.codemirror (object) – Опції CodeMirror.
  • settings.csslint (object) – Правила CSSLint.
  • settings.htmlhint (object) – Правила HTMLHint.
  • settings.jshint (object) – Правила JSHint.

Виглядає так:

{
	"codemirror": {
		"indentUnit" : 4,
		"indentWithTabs" : true,
		"inputStyle" : "contenteditable",
		"lineNumbers" : true,
		"lineWrapping" : true,
		"styleActiveLine" : true,
		"continueComments": true,
		"extraKeys": {
			"Ctrl-Space" : "autocomplete",
			"Ctrl-/" : "toggleComment",
			"Cmd-/" : "toggleComment",
			"Alt-F" : "findPersistent",
			"Ctrl-F" : "findPersistent",
			"Cmd-F" : "findPersistent"
		},
		"direction": "ltr",
		"Gutters": [
			"CodeMirror-lint-markers"
		],
		"mode" : "css",
		"lint" : true,
		"autoCloseBrackets" : true,
		"matchBrackets" : true
	},
	"csslint": {
		"errors" : true,
		"box-model" : true,
		"display-property-grouping" : true,
		"duplicate-properties" : true,
		"known-properties" : true,
		"outline-none" : true
	},
	"jshint": {
		"boss" : true,
		"curly" : true,
		"eqeqeq" : true,
		"eqnull" : true,
		"es3" : true,
		"expr" : true,
		"immed" : true,
		"noarg" : true,
		"nonbsp" : true,
		"onevar" : true,
		"quotmark": "single",
		"trailing": true,
		"undef" : true,
		"unused" : true,
		"browser" : true,
		"globals": {
			"_" : false,
			"Backbone": false,
			"jQuery" : false,
			"JSON": false,
			"wp": false
		}
	},
	"htmlhint": {
		"tagname-lowercase" : true,
		"attr-lowercase" : true,
		"attr-value-double-quotes": false,
		"doctype-first": false,
		"tag-pair" : true,
		"spec-char-escape" : true,
		"id-unique" : true,
		"src-not-empty" : true,
		"attr-no-duplication" : true,
		"alt-require" : true,
		"space-tab-mixed-disabled": "tab",
		"attr-unsafe-chars" : true
	}
}

нотатки

список змін

З версії 4.9.0Введено.

Код wp_enqueue_code_editor() WP 6.0.2

function wp_enqueue_code_editor( $args ) {
	if ( is_user_logged_in() && 'false' === wp_get_current_user()->syntax_highlighting ) {
		return false;
	}

	$settings = wp_get_code_editor_settings( $args );

	if ( empty( $settings ) || empty( $settings['codemirror'] ) ) {
		return false;
	}

	wp_enqueue_script( 'code-editor');
	wp_enqueue_style( 'code-editor');

	if ( isset( $settings['codemirror']['mode'] ) ) {
		$mode = $settings['codemirror']['mode'];
		if ( is_string( $mode ) ) {
			$mode = array(
				'name' => $mode,
			);
		}

		if ( ! empty( $settings['codemirror']['lint'] ) ) {
			switch ( $mode['name'] ) {
				case 'css':
				case 'text/css':
				case 'text/x-scss':
				case 'text/x-less':
					wp_enqueue_script( 'csslint' );
					break;
				case 'htmlmixed':
				case 'text/html':
				case 'php':
				case 'application/x-httpd-php':
				case 'text/x-php':
					wp_enqueue_script( 'htmlhint' );
					wp_enqueue_script( 'csslint' );
					wp_enqueue_script( 'jshint' );
					if ( ! current_user_can( 'unfiltered_html' ) ) {
						wp_enqueue_script( 'htmlhint-kses');
					}
					break;
				case 'javascript':
				case 'application/ecmascript':
				case 'application/json':
				case 'application/javascript':
				case 'application/ld+json':
				case 'text/typescript':
				case 'application/typescript':
					wp_enqueue_script( 'jshint' );
					wp_enqueue_script( 'jsonlint' );
					break;
			}
		}
	}

	wp_add_inline_script( 'code-editor', sprintf( 'jQuery.extend( wp.codeEditor.defaultSettings, %s );', wp_json_encode( $settings ) ) );

	/**
	 * Fires when scripts and styles are enqueued for the code editor.
	 *
	 * @ Since 4.9.0
	 *
	 * @param array $settings Settings for the enqueued code editor.
	 */
	do_action( 'wp_enqueue_code_editor', $settings );

	return $settings;
}

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *