77 lines
2.5 KiB
PHP
77 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace AKSRT\WidgetSystem;
|
|
|
|
defined('ABSPATH') || exit;
|
|
|
|
/**
|
|
* One reusable WP_Widget implementation backed by a WidgetDefinition.
|
|
*/
|
|
final class SchemaWidget extends \WP_Widget {
|
|
private WidgetDefinition $definition;
|
|
|
|
public function __construct(WidgetDefinition $definition) {
|
|
$this->definition = $definition;
|
|
parent::__construct(
|
|
$definition->id_base(),
|
|
$definition->name(),
|
|
[
|
|
'classname' => 'aksrt-schema-widget aksrt-schema-widget--' . $definition->slug(),
|
|
'description' => $definition->description(),
|
|
'customize_selective_refresh' => true,
|
|
],
|
|
['width' => 520]
|
|
);
|
|
}
|
|
|
|
public function definition(): WidgetDefinition {
|
|
return $this->definition;
|
|
}
|
|
|
|
public function widget($args, $instance): void {
|
|
$renderer = 'AKSRT\\WidgetSystem\\FrontendRenderer';
|
|
if (class_exists($renderer) && is_callable([$renderer, 'render'])) {
|
|
$renderer::render($this->definition, (array) $args, $this->definition->normalize((array) $instance), $this);
|
|
}
|
|
}
|
|
|
|
public function form($instance): void {
|
|
$instance = array_merge($this->definition->defaults(), is_array($instance) ? $instance : []);
|
|
if ($this->should_lazy_load()) {
|
|
$this->render_lazy_placeholder();
|
|
return;
|
|
}
|
|
FormRenderer::render($this, $this->definition->fields(), $instance);
|
|
}
|
|
|
|
public function render_full_form(array $instance): void {
|
|
FormRenderer::render($this, $this->definition->fields(), array_merge($this->definition->defaults(), $instance));
|
|
}
|
|
|
|
public function update($new_instance, $old_instance): array {
|
|
return $this->definition->normalize(is_array($new_instance) ? $new_instance : []);
|
|
}
|
|
|
|
private function should_lazy_load(): bool {
|
|
if (wp_doing_ajax() && isset($_REQUEST['action']) && $_REQUEST['action'] === AdminFormController::AJAX_ACTION) {
|
|
return false;
|
|
}
|
|
if (function_exists('is_customize_preview') && is_customize_preview()) {
|
|
return true;
|
|
}
|
|
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
|
|
return $screen && in_array($screen->id, ['widgets', 'customize'], true);
|
|
}
|
|
|
|
private function render_lazy_placeholder(): void {
|
|
printf(
|
|
'<div class="aksrt-widget-form-lazy" data-id-base="%1$s" data-widget-number="%2$s"><p class="aksrt-widget-form-lazy__status">%3$s</p><button type="button" class="button aksrt-widget-form-lazy__load">%4$s</button></div>',
|
|
esc_attr($this->id_base),
|
|
esc_attr((string) $this->number),
|
|
esc_html__('配置将在展开或添加模块后加载。', 'aksrt'),
|
|
esc_html__('加载配置', 'aksrt')
|
|
);
|
|
}
|
|
}
|
|
|