feat: rewrite schema-driven widget system
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace AKSRT\WidgetSystem;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* Lazy widget form endpoint and admin-only assets.
|
||||
*/
|
||||
final class AdminFormController {
|
||||
public const AJAX_ACTION = 'aksrt_widget_form';
|
||||
private const NONCE_ACTION = 'aksrt_widget_form';
|
||||
|
||||
public static function register_hooks(): void {
|
||||
add_action('wp_ajax_' . self::AJAX_ACTION, [self::class, 'ajax_form']);
|
||||
add_action('admin_enqueue_scripts', [self::class, 'enqueue']);
|
||||
add_action('customize_controls_enqueue_scripts', [self::class, 'enqueue']);
|
||||
}
|
||||
|
||||
public static function enqueue(): void {
|
||||
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
|
||||
if (!$screen || !in_array($screen->id, ['widgets', 'customize'], true)) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_media();
|
||||
wp_enqueue_style('wp-color-picker');
|
||||
wp_enqueue_script('jquery-ui-sortable');
|
||||
wp_enqueue_style('aksrt-widget-admin', AKSRT_URI . '/assets/widgets/admin.css', ['wp-color-picker'], AKSRT_VERSION);
|
||||
wp_enqueue_script('aksrt-widget-admin', AKSRT_URI . '/assets/widgets/admin.js', ['jquery', 'jquery-ui-sortable', 'wp-color-picker'], AKSRT_VERSION, true);
|
||||
wp_localize_script('aksrt-widget-admin', 'aksrtWidgetAdmin', [
|
||||
'ajaxUrl' => admin_url('admin-ajax.php'),
|
||||
'action' => self::AJAX_ACTION,
|
||||
'nonce' => wp_create_nonce(self::NONCE_ACTION),
|
||||
'i18n' => [
|
||||
'loading' => __('正在加载模块配置…', 'aksrt'),
|
||||
'error' => __('加载失败,请重试。', 'aksrt'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public static function ajax_form(): void {
|
||||
check_ajax_referer(self::NONCE_ACTION, 'nonce');
|
||||
if (!current_user_can('edit_theme_options')) {
|
||||
wp_send_json_error(['message' => __('权限不足。', 'aksrt')], 403);
|
||||
}
|
||||
|
||||
$id_base = isset($_POST['id_base']) ? sanitize_key(wp_unslash($_POST['id_base'])) : '';
|
||||
$number = isset($_POST['widget_number']) ? absint($_POST['widget_number']) : 0;
|
||||
$definition = WidgetRegistry::get_by_id_base($id_base);
|
||||
if (!$definition || $number < 1) {
|
||||
wp_send_json_error(['message' => __('无效的小工具实例。', 'aksrt')], 400);
|
||||
}
|
||||
|
||||
$widget = new SchemaWidget($definition);
|
||||
$widget->_set($number);
|
||||
$settings = $widget->get_settings();
|
||||
$instance = isset($settings[$number]) && is_array($settings[$number]) ? $settings[$number] : [];
|
||||
ob_start();
|
||||
$widget->render_full_form($instance);
|
||||
$html = (string) ob_get_clean();
|
||||
wp_send_json_success(['html' => $html]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user