feat(widgets): rebuild admin widgets page to match reference theme

- Replace transfer modal/admin-post flow with reference-style AJAX
  export/import/template dialogs (admin-transfer.js, TransferController)
- Customizer "移出模块" action, reference lazy form loading with t-notice
- Common fields use reference labels, dependencies, compact/inline rows,
  top/bottom-only extra spacing; form header with description/reminder
- Remove placement hint, template preview and legacy transfer code
- Fix widget audit (current_datetime stub, honor catalog common flags)
  and regenerate stale golden fixtures for posts_toc, quote, posts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
kate522andClaude Fable 5 committed 2026-10-30 14:00:57 +08:00
1 parent ea80cd96cc
commit a579a5b00a
14 files changed
+698 -446

No files matched your search

+325
View File
@@ -0,0 +1,325 @@
/* Sidebar toolbar: per-area export / import / template import (zibll WIE flow). */
(function ($) {
'use strict';
const config = window.aksrtWidgetAdmin || {};
const t = (key) => (config.i18n && config.i18n[key]) || key;
function post(action, data) {
return $.ajax({
url: config.ajaxUrl,
type: 'POST',
dataType: 'json',
data: $.extend({ action, nonce: config.transferNonce }, data || {}),
});
}
function failMessage(res, xhr, fallbackKey) {
return res?.data?.message || xhr?.responseJSON?.data?.message || t(fallbackKey);
}
function clearResult($result) {
return $result.removeClass('is-ok is-warn is-err').empty();
}
function showError($result, message) {
clearResult($result).addClass('is-err').text(message);
}
function reloadButton() {
return $('<p class="aksrt-wie-modal__reload-wrap"></p>').append(
$('<button type="button" class="button button-primary aksrt-wie-modal__reload"></button>').text(t('reloadPage'))
);
}
function renderImportResult($result, res, autoReload) {
clearResult($result);
if (!res?.success || !res.data) {
showError($result, failMessage(res, null, 'importFailed'));
return;
}
const warnings = Array.isArray(res.data.warnings) ? res.data.warnings : [];
$result.addClass(warnings.length ? 'is-warn' : 'is-ok');
[res.data.message || t('importSuccess')].concat(warnings).forEach((line, index) => {
if (index) $result.append('<br>');
$result.append(document.createTextNode(String(line)));
});
$result.append(reloadButton());
if (autoReload) window.setTimeout(() => window.location.reload(), 200);
}
function withButtonLoading($button, loadingText, idleText, request) {
$button.prop('disabled', true).text(loadingText);
return request().always(() => $button.prop('disabled', false).text(idleText));
}
function importModeHtml(name) {
return `<div class="aksrt-wie-modal__import-mode">
<div class="aksrt-wie-modal__import-mode-title description"></div>
<label class="aksrt-wie-modal__import-mode-row"><input type="radio" name="${name}" value="replace"> <span data-mode-label="replace"></span></label>
<label class="aksrt-wie-modal__import-mode-row"><input type="radio" name="${name}" value="append" checked> <span data-mode-label="append"></span></label>
</div>`;
}
function createModal(opts) {
let $modal = null;
function ensure() {
if ($modal) return $modal;
$modal = $(`<div id="${opts.id}" class="aksrt-wie-modal${opts.extraClass ? ' ' + opts.extraClass : ''}" aria-hidden="true">
<div class="aksrt-wie-modal__backdrop" data-aksrt-wie-close></div>
<div class="aksrt-wie-modal__dialog" role="dialog" aria-modal="true">
<button type="button" class="aksrt-wie-modal__close" data-aksrt-wie-close aria-label="${t('close')}">&times;</button>
${opts.bodyHtml}
${opts.actionsHtml}
<p class="aksrt-wie-modal__result" aria-live="polite"></p>
</div>
</div>`).appendTo('body');
$modal.find('.aksrt-wie-modal__import-mode-title').text(t('importModeLabel'));
$modal.find('[data-mode-label="replace"]').text(t('importModeReplace'));
$modal.find('[data-mode-label="append"]').text(t('importModeAppend'));
$modal.find('.aksrt-wie-modal__cancel').text(t('close'));
$modal.on('click', '[data-aksrt-wie-close], .aksrt-wie-modal__cancel', close);
if (opts.onInit) opts.onInit($modal);
return $modal;
}
function open() {
ensure().find('input[name$="-import-mode"][value="append"]').prop('checked', true);
clearResult($modal.find('.aksrt-wie-modal__result'));
$modal.addClass('is-open').attr('aria-hidden', 'false');
}
function close() {
if ($modal) $modal.removeClass('is-open').attr('aria-hidden', 'true');
}
return { ensure, open, close, $result: () => ensure().find('.aksrt-wie-modal__result') };
}
const state = { mode: 'export', sidebarId: '', templateSidebarId: '' };
const ioModal = createModal({
id: 'aksrt-wie-modal',
bodyHtml: `<h3 class="aksrt-wie-modal__title"></h3>
<p class="aksrt-wie-modal__hint description"></p>
<textarea class="aksrt-wie-modal__textarea" spellcheck="false"></textarea>
${importModeHtml('aksrt-wie-import-mode')}`,
actionsHtml: `<p class="aksrt-wie-modal__actions">
<button type="button" class="button aksrt-wie-modal__copy"></button>
<button type="button" class="button button-primary aksrt-wie-modal__submit"></button>
<button type="button" class="button aksrt-wie-modal__cancel"></button>
</p>`,
onInit($modal) {
$modal.find('.aksrt-wie-modal__copy').on('click', function () {
const textarea = $modal.find('.aksrt-wie-modal__textarea')[0];
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
try {
document.execCommand('copy');
$(this).text(t('copyDone'));
} catch (_error) {
window.alert(t('copyFail'));
}
});
$modal.find('.aksrt-wie-modal__submit').on('click', submitImport);
},
});
const templateModal = createModal({
id: 'aksrt-wie-template-modal',
extraClass: 'aksrt-wie-template-layer',
bodyHtml: `<h3 class="aksrt-wie-modal__title"></h3>
<div class="aksrt-wie-modal__hint description"></div>
<div class="aksrt-wie-template-list-wrap"><p class="aksrt-wie-template-list-status description"></p><div class="aksrt-wie-template-list"></div></div>
${importModeHtml('aksrt-wie-template-import-mode')}`,
actionsHtml: `<p class="aksrt-wie-modal__actions">
<button type="button" class="button button-primary aksrt-wie-template-submit"></button>
<button type="button" class="button aksrt-wie-modal__cancel"></button>
</p>`,
onInit($modal) {
$modal.find('.aksrt-wie-modal__title').text(t('templateModalTitle'));
// templateHint is server-built, escaped translation markup.
$modal.find('.aksrt-wie-modal__hint').html(t('templateHint'));
$modal.find('.aksrt-wie-template-submit').text(t('templateSubmit')).on('click', submitTemplate);
},
});
function openIoModal(mode, sidebarId) {
state.mode = mode;
state.sidebarId = sidebarId;
const $modal = ioModal.ensure();
const isExport = mode === 'export';
$modal.find('.aksrt-wie-modal__title').text(t(isExport ? 'exportTitle' : 'importTitle'));
$modal.find('.aksrt-wie-modal__hint').text(t(isExport ? 'exportHint' : 'importHint'));
$modal.find('.aksrt-wie-modal__textarea').prop('readonly', isExport).val('');
$modal.find('.aksrt-wie-modal__copy').toggle(isExport).text(t('copy'));
$modal.find('.aksrt-wie-modal__submit').toggle(!isExport).text(t('submitImport')).prop('disabled', false);
$modal.find('.aksrt-wie-modal__import-mode').toggle(!isExport);
ioModal.open();
if (isExport) fetchExport();
}
function fetchExport() {
const $textarea = ioModal.ensure().find('.aksrt-wie-modal__textarea').val(t('loadingExport'));
post('aksrt_widgets_export_sidebar', { sidebar_id: state.sidebarId })
.done((res) => {
if (res?.success && res.data?.json_text) {
$textarea.val(res.data.json_text);
return;
}
$textarea.val('');
showError(ioModal.$result(), failMessage(res, null, 'exportFailed'));
})
.fail((xhr) => {
$textarea.val('');
showError(ioModal.$result(), failMessage(null, xhr, 'networkError'));
});
}
function submitImport() {
const $modal = ioModal.ensure();
const mode = $modal.find('input[name="aksrt-wie-import-mode"]:checked').val() || 'append';
if (!window.confirm(t(mode === 'append' ? 'confirmImportAppend' : 'confirmImportReplace'))) return;
const raw = String($modal.find('.aksrt-wie-modal__textarea').val() || '').trim();
if (!raw) {
showError(ioModal.$result(), t('pasteJsonFirst'));
return;
}
withButtonLoading($modal.find('.aksrt-wie-modal__submit'), t('loadingImport'), t('submitImport'), () =>
post('aksrt_widgets_import_sidebar', { sidebar_id: state.sidebarId, json: raw, import_mode: mode })
.done((res) => {
if (res?.success) $modal.find('.aksrt-wie-modal__textarea').val('');
renderImportResult(ioModal.$result(), res, false);
})
.fail((xhr) => showError(ioModal.$result(), failMessage(null, xhr, 'networkError')))
);
}
function templateItem(template) {
const $meta = $('<span class="aksrt-wie-template-item-meta"></span>')
.append($('<span class="aksrt-wie-template-item-title"></span>').text(template.title || template.id));
if (template.desc) $meta.append($('<span class="aksrt-wie-template-item-desc"></span>').text(template.desc));
if (template.remind) {
$meta.append($('<span class="aksrt-wie-template-item-remind"></span>')
.append('<span class="dashicons dashicons-info-outline" aria-hidden="true"></span>')
.append(document.createTextNode(template.remind)));
}
if (Array.isArray(template.modules) && template.modules.length) {
$meta.append($('<span class="aksrt-wie-template-item-modules"></span>').text(template.modules.map((module) => module.title).join(' / ')));
}
const $label = $('<label class="aksrt-wie-template-item-label"></label>')
.append($('<input type="radio" name="aksrt-wie-template-id">').val(template.id))
.append($meta);
return $('<div class="aksrt-wie-template-item"></div>').append($('<div class="aksrt-wie-template-item-row"></div>').append($label));
}
function openTemplateModal(sidebarId) {
state.templateSidebarId = sidebarId;
const $modal = templateModal.ensure();
const $list = $modal.find('.aksrt-wie-template-list').empty();
const $status = $modal.find('.aksrt-wie-template-list-status').text(t('templateLoadingList'));
templateModal.open();
post('aksrt_widgets_list_templates')
.done((res) => {
const templates = res?.success ? res.data?.templates : null;
$status.text(Array.isArray(templates) && templates.length ? '' : t('templateEmpty'));
(templates || []).forEach((template) => $list.append(templateItem(template)));
})
.fail((xhr) => $status.text(failMessage(null, xhr, 'networkError')));
}
function submitTemplate() {
const $modal = templateModal.ensure();
const $picked = $modal.find('input[name="aksrt-wie-template-id"]:checked');
if (!$picked.length) {
window.alert(t('templatePick'));
return;
}
const templateId = String($picked.val());
const mode = $modal.find('input[name="aksrt-wie-template-import-mode"]:checked').val() || 'append';
const title = $picked.closest('.aksrt-wie-template-item').find('.aksrt-wie-template-item-title').text().trim() || templateId;
const message = t('confirmTemplate').replace('{title}', title).replace('{mode}', t(mode === 'append' ? 'importModeAppend' : 'importModeReplace'));
if (!window.confirm(message)) return;
withButtonLoading($modal.find('.aksrt-wie-template-submit'), t('loadingImport'), t('templateSubmit'), () =>
post('aksrt_widgets_import_template', { sidebar_id: state.templateSidebarId, template_id: templateId, import_mode: mode })
.done((res) => renderImportResult(templateModal.$result(), res, true))
.fail((xhr) => showError(templateModal.$result(), failMessage(null, xhr, 'networkError')))
);
}
function injectToolbar($anchor, sidebarId) {
if (!$anchor?.length || !sidebarId || $anchor.next('.aksrt-wie-toolbar').length) return;
const $toolbar = $('<div class="aksrt-wie-toolbar"></div>');
[['export', 'exportModules'], ['import', 'importModules'], ['template', 'importTemplate']].forEach(([action, label]) => {
$('<button type="button" class="button button-small"></button>')
.text(t(label))
.attr('data-aksrt-wie-action', action)
.attr('data-sidebar-id', sidebarId)
.appendTo($toolbar);
});
$anchor.after($toolbar);
}
function scanWidgetsScreen() {
$('.widgets-holder-wrap:not(#available-widgets):not(.inactive-sidebar):not(.is-aksrt-wie)').each(function () {
const $wrap = $(this);
const $sortables = $wrap.find('.widgets-sortables').first();
const sidebarId = String($sortables.attr('id') || '');
if (!sidebarId) return;
const $description = $sortables.find('.sidebar-description .description').first();
$wrap.addClass('is-aksrt-wie');
injectToolbar($description.length ? $description : $sortables.find('.description').first(), sidebarId);
});
}
function scanCustomizer() {
const prefix = 'sub-accordion-section-sidebar-widgets-';
$('.control-section-sidebar:not(.is-aksrt-wie)').each(function () {
const $section = $(this);
const sectionId = String($section.attr('id') || '');
if (!sectionId.startsWith(prefix) || sectionId.length === prefix.length) return;
$section.addClass('is-aksrt-wie');
const $description = $section.find('.section-meta .description').first();
injectToolbar($description.length ? $description : $section.find('.accordion-section-title, .customize-section-title').first(), sectionId.slice(prefix.length));
});
$('.customize-control-widget_form:not(.is-aksrt-wie)').each(function () {
const $nav = $(this).find('.widget-reorder-nav').first();
if (!$nav.length) return;
$('<span class="aksrt-wie-btn-delete dashicons-trash" tabindex="0" role="button"></span>').text(t('removeModule')).appendTo($nav);
$(this).addClass('is-aksrt-wie');
});
}
$(document)
.on('click', '[data-aksrt-wie-action]', function () {
const action = String($(this).data('aksrt-wie-action'));
const sidebarId = String($(this).data('sidebar-id') || '');
if (!sidebarId) return;
if (action === 'template') openTemplateModal(sidebarId);
else openIoModal(action, sidebarId);
})
.on('click keydown', '.aksrt-wie-btn-delete', function (event) {
if (event.type === 'keydown' && event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
$(this).closest('.customize-control-widget_form').find('.widget-control-remove').first().trigger('click');
})
.on('click', '.aksrt-wie-modal__reload', () => window.location.reload())
.on('keydown', (event) => {
if (event.key !== 'Escape') return;
ioModal.close();
templateModal.close();
})
.on('widget-added', () => {
if (document.body.classList.contains('wp-customizer')) scanCustomizer();
});
$(function () {
if (!config.ajaxUrl) return;
if (document.body.classList.contains('widgets-php')) scanWidgetsScreen();
if (document.body.classList.contains('wp-customizer')) {
window.wp?.customize?.bind?.('ready', () => window.setTimeout(scanCustomizer, 300));
$(document).on('click', '.control-panel-widgets .control-section-sidebar', () => window.setTimeout(scanCustomizer, 100));
}
});
})(jQuery);
+68 -43
View File
@@ -41,6 +41,21 @@
.aksrt-widget-field--switcher .description { grid-column: 1 / -1; grid-row: 2; }
.aksrt-widget-field--switcher > .aksrt-widget-switch { grid-column: 2; grid-row: 1; }
/* Reference CSF row modifiers. */
.aksrt-widget-field.is-compact { margin-top: -12px; padding-top: 0; border-top: 0; }
.aksrt-widget-field__subtitle { margin: 0 0 5px; color: #646970; font-size: 12px; }
.aksrt-widget-field.is-inline .aksrt-widget-choices--radio label > span { padding: 0; border: 0; background: none; box-shadow: none; }
.aksrt-widget-field.is-inline .aksrt-widget-choices--radio { gap: 4px 14px; }
.aksrt-widget-field--content { padding: 10px 0; color: #50575e; }
.aksrt-widget-field--subheading { padding: 10px 12px; margin: 6px 0 0; border: 0; background: #f6f7f9; color: #0991f5; font-weight: 600; }
.aksrt-widget-field--submessage { padding: 8px 12px; margin: 8px 0; border: 0; border-radius: 4px; font-size: 13px; }
.aksrt-widget-field--submessage-normal { background: #f5f5f5; color: #555; }
.aksrt-widget-field--submessage-success { background: rgba(18, 185, 40, .1); color: #12b928; }
.aksrt-widget-field--submessage-info { background: rgba(41, 151, 247, .1); color: #2997f7; }
.aksrt-widget-field--submessage-warning { background: rgba(255, 156, 57, .1); color: #e18c47; }
.aksrt-widget-field--submessage-danger { background: rgba(255, 69, 69, .1); color: #ff4646; }
.aksrt-widget-field .c-yellow { color: #fc844c; }
.aksrt-widget-switch {
display: inline-flex;
cursor: pointer;
@@ -144,6 +159,8 @@
gap: 6px;
}
.aksrt-widget-spacing--2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.aksrt-widget-spacing label span {
display: block;
margin-bottom: 3px;
@@ -201,55 +218,63 @@
.aksrt-widget-form .button { min-height: 32px; line-height: 30px; border-radius: 3px; }
.aksrt-widget-form .button-primary { background: #0991f5; border-color: #087bcf; }
.aksrt-widget-form-lazy {
padding: 14px;
border: 1px dashed #c3c4c7;
border-radius: 6px;
text-align: center;
}
.aksrt-widget-form-lazy { padding: 10px 0; }
.aksrt-widget-form-lazy__status:empty { display: none; }
.aksrt-widget-form-lazy__status { margin-top: 0; color: #646970; }
/* Reference t-notice boxes (lazy form status). */
.t-notice { padding: 8px 12px; border-radius: 4px; font-size: 13px; line-height: 1.5; }
.t-notice.t-loading { background: rgba(255, 156, 57, .1); color: #e18c47; }
.t-notice.t-error { background: rgba(255, 69, 69, .1); color: #ff4646; }
.aksrt-widget-placement-hint {
display: flex;
gap: 6px;
align-items: flex-start;
margin: 10px 0 0;
padding: 8px;
border-left: 3px solid #72aee6;
background: #f0f6fc;
color: #50575e;
}
/* Sidebar toolbar: export / import / template import. */
.aksrt-wie-toolbar { margin: 8px 0 12px; }
.aksrt-wie-toolbar .button { margin-right: 6px; margin-bottom: 4px; }
.aksrt-wie-btn-delete { display: inline-flex; align-items: center; gap: 2px; margin-left: 8px; color: #b32d2e; font-size: 12px; cursor: pointer; }
.aksrt-wie-btn-delete::before { font: normal 16px/1 dashicons; content: ' 182'; }
.aksrt-wie-btn-delete:hover,
.aksrt-wie-btn-delete:focus { color: #d63638; }
.aksrt-widget-placement-hint.is-warning {
border-color: #dba617;
background: #fcf9e8;
color: #614200;
}
/* WIE modal shell. */
.aksrt-wie-modal { display: none; position: fixed; inset: 0; z-index: 1000100; align-items: center; justify-content: center; padding: 20px; box-sizing: border-box; }
.aksrt-wie-modal.is-open { display: flex; }
.aksrt-wie-modal__backdrop { position: absolute; inset: 0; background: rgba(0, 0, 0, .45); }
.aksrt-wie-modal__dialog { position: relative; z-index: 1; width: 100%; max-width: min(920px, 96vw); max-height: 90vh; overflow: auto; padding: 18px 20px 16px; box-sizing: border-box; border: 1px solid #c3c4c7; border-radius: 6px; background: #fff; box-shadow: 0 8px 32px rgba(0, 0, 0, .14); }
.aksrt-wie-modal__close { position: absolute; top: 10px; right: 10px; width: 2em; height: 2em; padding: 0; border: none; background: transparent; color: #646970; font-size: 20px; line-height: 1; cursor: pointer; }
.aksrt-wie-modal__close:hover { color: #1d2327; }
.aksrt-wie-modal__title { margin: 0 32px 10px 0; font-size: 16px; line-height: 1.3; }
.aksrt-wie-modal__hint { margin: 0 0 10px; font-size: 13px; }
.aksrt-wie-modal__import-mode { display: flex; flex-wrap: wrap; gap: 16px; align-items: baseline; margin: 0 0 12px; padding: 10px 12px; border: 1px solid #dcdcde; border-radius: 4px; background: #f6f7f7; }
.aksrt-wie-modal__import-mode-title { margin: 0 0 8px; font-weight: 600; }
.aksrt-wie-modal__import-mode-row { display: block; margin: 6px 0 0; cursor: pointer; }
.aksrt-wie-modal__import-mode-row input { margin-right: 6px; vertical-align: middle; }
.aksrt-wie-modal__textarea { width: 100%; min-height: 240px; box-sizing: border-box; font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 1.45; }
.aksrt-wie-modal__actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 12px 0 0; }
.aksrt-wie-modal__result { margin: 10px 0 0; font-size: 13px; }
.aksrt-wie-modal__result.is-ok { color: #008a20; }
.aksrt-wie-modal__result.is-warn { color: #996800; }
.aksrt-wie-modal__result.is-err { color: #d63638; }
.aksrt-wie-modal__reload-wrap { margin: 12px 0 0; }
.aksrt-wie-remind { margin-bottom: 10px; color: #fc844c; font-size: .9em; }
.aksrt-wie-remind b { color: inherit; }
.aksrt-widget-transfer-toolbar { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 12px; }
.aksrt-widget-transfer-toolbar .button { margin: 0; }
.aksrt-widget-customizer-remove { margin-left: 8px; color: #b32d2e; }
.aksrt-widget-transfer-modal[hidden] { display: none !important; }
.aksrt-widget-transfer-modal.is-open { position: fixed; inset: 0; z-index: 1000100; display: flex; align-items: center; justify-content: center; padding: 20px; }
.aksrt-widget-transfer-modal__backdrop { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: rgba(0, 0, 0, .45); }
.aksrt-widget-transfer-modal__dialog { position: relative; z-index: 1; box-sizing: border-box; width: min(720px, 96vw); max-height: 90vh; overflow: auto; padding: 18px 20px 16px; border: 1px solid #c3c4c7; border-radius: 6px; background: #fff; box-shadow: 0 8px 32px rgba(0, 0, 0, .14); }
.aksrt-widget-transfer-modal__dialog h2 { margin: 0 36px 10px 0; font-size: 16px; }
.aksrt-widget-transfer-modal__area { margin: 0 0 12px; }
.aksrt-widget-transfer-modal__close { position: absolute; top: 10px; right: 10px; width: 32px; height: 32px; border: 0; background: transparent; color: #646970; font-size: 22px; cursor: pointer; }
.aksrt-widget-transfer-modal__tabs { display: flex; gap: 6px; margin-bottom: 14px; padding-bottom: 10px; border-bottom: 1px solid #dcdcde; }
.aksrt-widget-transfer-modal__tabs .is-active { border-color: #0991f5; color: #087bcf; box-shadow: inset 0 -2px #0991f5; }
.aksrt-widget-transfer-modal__panel form { display: grid; align-content: start; gap: 10px; }
.aksrt-widget-transfer-modal__panel select,
.aksrt-widget-transfer-modal__panel input[type="file"] { width: 100%; }
.aksrt-widget-transfer__actions { display: flex; flex-wrap: wrap; gap: 8px; }
.aksrt-widget-template-preview-output { max-height: 420px; overflow: auto; margin-top: 14px; padding: 14px; border: 1px solid #dcdcde; background: #fff; }
.aksrt-widget-template-preview__area { margin-bottom: 18px; }
.aksrt-widget-template-preview__module { margin: 10px 0; padding: 12px; border: 1px dashed #c3c4c7; border-radius: 6px; }
/* Template picker layer. */
.aksrt-wie-template-layer { z-index: 1000120; }
.aksrt-wie-template-list-wrap { margin-bottom: 12px; }
.aksrt-wie-template-list { display: flex; flex-wrap: wrap; gap: 10px; max-height: 42vh; overflow: auto; }
.aksrt-wie-template-item { flex: 1 1 30%; min-width: 360px; }
.aksrt-wie-template-item-row { display: flex; gap: 8px; align-items: flex-start; height: 100%; }
.aksrt-wie-template-item-label { display: flex; flex: 1 1 auto; gap: 10px; align-items: flex-start; min-width: 0; height: stretch; margin: 0; padding: 10px 12px; border: 1px solid #efeeee; border-radius: 8px; background: #fbfbfb; cursor: pointer; }
.aksrt-wie-template-item-label:hover { background: #f7fbfe; }
.aksrt-wie-template-item-label input[type="radio"] { flex-shrink: 0; margin-top: 3px; }
.aksrt-wie-template-item-meta { display: flex; flex-direction: column; gap: 4px; }
.aksrt-wie-template-item-title { font-weight: 600; }
.aksrt-wie-template-item-desc { color: #646970; font-size: 12px; line-height: 1.4; }
.aksrt-wie-template-item-remind { color: #fc844c; font-size: 12px; line-height: 1.4; }
.aksrt-wie-template-item-modules { margin: 0; padding-left: 1.2em; font-size: 12px; line-height: 1.5; color: #50575e; }
@media (max-width: 600px) {
.aksrt-widget-transfer-modal.is-open { padding: 10px; }
.aksrt-widget-transfer-modal__dialog { width: 100%; padding: 16px; }
.aksrt-wie-modal { padding: 10px; }
.aksrt-wie-template-item { min-width: 100%; }
}
@media (prefers-reduced-motion: reduce) {
+18 -126
View File
@@ -22,7 +22,6 @@
});
evaluateDependencies($root);
updateWidgetTitle($root);
updatePlacementWarning($root);
updateRepeaterControls($root);
}
@@ -54,82 +53,6 @@
}).first().replaceWith(`${title} `);
}
function updatePlacementWarning(root) {
const $widget = $(root).closest('.widget');
const $hint = $widget.find('.aksrt-widget-placement-hint').first();
if (!$hint.length) return;
const size = String($hint.data('widget-size') || 'any');
const area = String($widget.closest('.widgets-sortables').attr('id') || '');
const isSidebar = /sidebar/.test(area);
$hint.toggleClass('is-warning', (size === 'wide' && isSidebar) || (size === 'sidebar' && !isSidebar && area !== ''));
}
function injectTransferToolbar($anchor, sidebarId) {
if (!$anchor?.length || !sidebarId || $anchor.next('.aksrt-widget-transfer-toolbar').length) return;
const $toolbar = $('<div class="aksrt-widget-transfer-toolbar" role="group"></div>');
[
['export', config.i18n?.export || '导出'],
['import', config.i18n?.import || '导入'],
['template', config.i18n?.template || '应用模板'],
].forEach(([action, label]) => {
$('<button type="button" class="button button-small"></button>')
.text(label)
.attr('data-aksrt-transfer-action', action)
.attr('data-sidebar-id', sidebarId)
.appendTo($toolbar);
});
$anchor.after($toolbar);
}
function scanWidgetAreas() {
$('.widgets-holder-wrap:not(#available-widgets):not(.inactive-sidebar)').each(function () {
const $wrap = $(this);
const $sortables = $wrap.find('.widgets-sortables').first();
const sidebarId = String($sortables.attr('id') || '');
if (!sidebarId) return;
const $description = $sortables.find('.sidebar-description .description').first();
const $anchor = $description.length ? $description : $sortables.find('.description').first();
if ($anchor.length) injectTransferToolbar($anchor, sidebarId);
});
$('.control-section-sidebar').each(function () {
const $section = $(this);
const sectionId = String($section.attr('id') || '');
const prefix = 'sub-accordion-section-sidebar-widgets-';
if (!sectionId.startsWith(prefix)) return;
const sidebarId = sectionId.slice(prefix.length);
const $description = $section.find('.section-meta .description').first();
const $anchor = $description.length ? $description : $section.find('.accordion-section-title, .customize-section-title').first();
if ($anchor.length) injectTransferToolbar($anchor, sidebarId);
});
$('.customize-control-widget_form').each(function () {
const $control = $(this);
const $nav = $control.find('.widget-reorder-nav').first();
if (!$nav.length || $nav.find('.aksrt-widget-customizer-remove').length) return;
$('<button type="button" class="button-link-delete aksrt-widget-customizer-remove" aria-label="移除此小工具">移除</button>').appendTo($nav);
});
}
function openTransferModal(action, sidebarId) {
const $modal = $('#aksrt-widget-transfer-modal');
if (!$modal.length) return;
const sidebars = config.sidebars || {};
const areaName = sidebars[sidebarId] || sidebarId;
$modal.find('.aksrt-widget-transfer-modal__area').text(areaName);
$modal.find('input[name="sidebar"], input[name="target_sidebar"]').val(sidebarId);
$modal.find('[data-transfer-tab]').removeClass('is-active');
$modal.find(`[data-transfer-tab="${action}"]`).addClass('is-active');
$modal.find('[data-transfer-panel]').prop('hidden', true);
$modal.find(`[data-transfer-panel="${action}"]`).prop('hidden', false);
$modal.prop('hidden', false).addClass('is-open').attr('aria-hidden', 'false');
$modal.find('[data-transfer-panel="' + action + '"] button, [data-transfer-panel="' + action + '"] input, [data-transfer-panel="' + action + '"] select').filter(':visible').first().trigger('focus');
}
function closeTransferModal() {
$('#aksrt-widget-transfer-modal').removeClass('is-open').attr('aria-hidden', 'true').prop('hidden', true);
}
function loadForm(container) {
const $container = $(container);
if ($container.data('loading') || $container.data('loaded')) return;
@@ -138,7 +61,8 @@
const number = core.resolveWidgetNumber(inputName, $widget.attr('id'), $container.data('widget-number'));
// New-widget templates use __i__ until WordPress assigns a real instance number.
if (!number) return;
$container.data('loading', true).find('.aksrt-widget-form-lazy__status').text(config.i18n?.loading || 'Loading…');
$container.data('loading', true);
setLazyStatus($container, 'loading', config.i18n?.loading || '正在加载模块配置…');
$.post(config.ajaxUrl, {
action: config.action,
nonce: config.nonce,
@@ -146,17 +70,25 @@
widget_number: number,
}).done((response) => {
if (!response?.success || !response.data?.html) {
$container.data('loading', false).find('.aksrt-widget-form-lazy__status').text(response?.data?.message || config.i18n?.error || 'Failed to load.');
$container.data('loading', false);
setLazyStatus($container, 'error', response?.data?.message || config.i18n?.error || '加载失败,请刷新页面后重试');
return;
}
const $form = $(response.data.html);
$container.replaceWith($form);
$container.data('loaded', true).replaceWith($form);
initForm($form);
}).fail(() => {
$container.data('loading', false).find('.aksrt-widget-form-lazy__status').text(config.i18n?.error || 'Failed to load.');
}).fail((xhr) => {
$container.data('loading', false);
setLazyStatus($container, 'error', xhr?.responseJSON?.data?.message || config.i18n?.error || '加载失败,请刷新页面后重试');
});
}
/* Lazy placeholder status uses the reference t-notice box (t-loading / t-error). */
function setLazyStatus($container, type, message) {
const $notice = $('<div class="t-notice"></div>').addClass(`t-${type}`).text(message);
$container.find('.aksrt-widget-form-lazy__status').empty().append($notice);
}
function renumberRepeaters(_event, ui) {
const $form = $(ui?.item || this).closest('.aksrt-widget-form');
$form.find('.aksrt-widget-repeater__rows').each(function () {
@@ -216,24 +148,10 @@
}
$(document)
.on('click', '[data-aksrt-transfer-action]', function () {
openTransferModal(String($(this).data('aksrt-transfer-action')), String($(this).data('sidebar-id')));
.on('click', '.widget-top', function () {
const $widget = $(this).closest('.widget, .customize-control-widget_form');
window.setTimeout(() => $widget.find('.aksrt-widget-form-lazy').each(function () { loadForm(this); }), 20);
})
.on('click', '[data-aksrt-transfer-close]', closeTransferModal)
.on('click', '[data-transfer-tab]', function () {
const $modal = $(this).closest('.aksrt-widget-transfer-modal');
const panel = String($(this).data('transfer-tab'));
$modal.find('[data-transfer-tab]').removeClass('is-active');
$(this).addClass('is-active');
$modal.find('[data-transfer-panel]').prop('hidden', true);
$modal.find(`[data-transfer-panel="${panel}"]`).prop('hidden', false);
})
.on('click', '.aksrt-widget-customizer-remove', function (event) {
event.preventDefault();
$(this).closest('.customize-control-widget_form').find('.widget-control-remove').first().trigger('click');
})
.on('click', '.aksrt-widget-form-lazy__load', function () { loadForm($(this).closest('.aksrt-widget-form-lazy')); })
.on('click', '.widget.open .aksrt-widget-form-lazy, .customize-control-widget_form .aksrt-widget-form-lazy', function () { loadForm(this); })
.on('change input', '.aksrt-widget-form input, .aksrt-widget-form select, .aksrt-widget-form textarea', function () {
const $form = $(this).closest('.aksrt-widget-form');
evaluateDependencies($form);
@@ -300,31 +218,10 @@
const $wrap = $(this).closest('.aksrt-widget-upload');
$wrap.find('input[type="url"]').val('').trigger('change');
$wrap.find('img').remove();
})
.on('click', '.aksrt-widget-template-preview', function () {
const $form = $(this).closest('form');
const $output = $('.aksrt-widget-template-preview-output').first();
$output.prop('hidden', false).html('<p>正在生成预览…</p>');
$.post(config.ajaxUrl, {
action: 'aksrt_widgets_template_preview',
nonce: config.transferNonce,
template: $form.find('[name="template"]').val(),
}).done((response) => {
if (!response?.success || !response.data) {
$output.empty().append($('<p class="notice notice-error"></p>').text(response?.data?.message || config.i18n?.error || '预览加载失败,请重试。'));
return;
}
$output.html(response.data.html || '<p>模板为空。</p>');
}).fail((xhr) => {
const message = xhr?.responseJSON?.data?.message || config.i18n?.error || '预览加载失败,请重试。';
$output.empty().append($('<p class="notice notice-error"></p>').text(message));
});
});
});
$(document).on('widget-added widget-updated', function (_event, widget) {
$(widget).find('.aksrt-widget-form-lazy').each(function () { loadForm(this); });
updatePlacementWarning(widget);
scanWidgetAreas();
});
if (window.wp?.customize?.bind) {
@@ -332,7 +229,6 @@
$('#customize-theme-controls').on('expanded', function (_event, section) {
if (!section || !String(section.id || section).includes('sidebar-widgets')) return;
window.setTimeout(function () {
scanWidgetAreas();
$('.customize-control-widget_form .aksrt-widget-form-lazy').each(function () { loadForm(this); });
}, 100);
});
@@ -340,10 +236,6 @@
}
$(function () {
scanWidgetAreas();
$(document).on('keydown', function (event) {
if (event.key === 'Escape') closeTransferModal();
});
$('.aksrt-widget-form').each(function () { initForm(this); });
$('.widget.open .aksrt-widget-form-lazy').each(function () { loadForm(this); });
});
+44 -13
View File
@@ -31,26 +31,57 @@ final class AdminFormController {
aksrt_icon_picker_assets(['wp-color-picker']);
wp_enqueue_script('aksrt-widget-admin-core', AKSRT_URI . '/assets/widgets/admin-core.js', [], AKSRT_VERSION, true);
wp_enqueue_script('aksrt-widget-admin', AKSRT_URI . '/assets/widgets/admin.js', ['jquery', 'jquery-ui-sortable', 'wp-color-picker', 'aksrt-widget-admin-core'], AKSRT_VERSION, true);
$sidebars = [];
foreach ((array) ($GLOBALS['wp_registered_sidebars'] ?? []) as $id => $sidebar) {
$sidebars[(string) $id] = (string) ($sidebar['name'] ?? $id);
}
wp_enqueue_script('aksrt-widget-admin-transfer', AKSRT_URI . '/assets/widgets/admin-transfer.js', ['jquery', 'aksrt-widget-admin'], 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),
'transferNonce' => wp_create_nonce('aksrt_widgets_transfer'),
'sidebars' => $sidebars,
'i18n' => [
'loading' => __('正在加载模块配置…', 'aksrt'),
'error' => __('加载失败,请重试。', 'aksrt'),
'export' => __('导出', 'aksrt'),
'import' => __('导入', 'aksrt'),
'template' => __('应用模板', 'aksrt'),
],
'transferNonce' => wp_create_nonce(TransferController::NONCE),
'i18n' => self::i18n(),
]);
}
/** @return array<string,string> */
private static function i18n(): array {
return [
'loading' => __('正在加载模块配置…', 'aksrt'),
'error' => __('加载失败,请刷新页面后重试', 'aksrt'),
'confirmImportReplace' => __('将覆盖当前容器中已有的全部模块,导入内容将替换该侧栏;确定继续?', 'aksrt'),
'confirmImportAppend' => __('将在当前容器已有模块列表末尾追加导入内容,不会删除原有模块;确定继续?', 'aksrt'),
'importModeLabel' => __('导入方式', 'aksrt'),
'importModeReplace' => __('覆盖(替换现有)', 'aksrt'),
'importModeAppend' => __('追加(保留现有)', 'aksrt'),
'loadingExport' => __('正在生成 JSON…', 'aksrt'),
'loadingImport' => __('正在导入…', 'aksrt'),
'copyDone' => __('已复制', 'aksrt'),
'copyFail' => __('复制失败,请手动全选复制', 'aksrt'),
'exportTitle' => __('导出 JSON(可复制)', 'aksrt'),
'importTitle' => __('导入 JSON(粘贴后确认)', 'aksrt'),
'importHint' => __('将导出得到的 JSON 粘贴到下方文本框以导入。注意:不同主题版本或非同站的的模块导入后可能会出现错误,此时可以重新配置一下有错误的模块,即可恢复正常', 'aksrt'),
'exportHint' => __('以下为当前容器模块数据,可直接全选复制保存。', 'aksrt'),
'close' => __('关闭', 'aksrt'),
'copy' => __('复制全部', 'aksrt'),
'submitImport' => __('确认导入', 'aksrt'),
'reloadPage' => __('刷新页面', 'aksrt'),
'templateModalTitle' => __('从模板导入', 'aksrt'),
'templateHint' => __('使用模板可快速配置网站布局,选择对应的模板点击导入即可。', 'aksrt') . '<div class="aksrt-wie-remind"><b>' . __('注意事项:', 'aksrt') . '</b>' . __('1.导入模板必须对容器位置对应,例如不能将侧边栏模板导入到全宽度中!', 'aksrt') . '<br>' . __('2.导入模板需已经有对应的内容,例如:导入文章相关的模板,那么至少已经有多篇文章和文章分类', 'aksrt') . '</div>',
'templateLoadingList' => __('正在加载模板列表…', 'aksrt'),
'templateEmpty' => __('暂无可用模板。', 'aksrt'),
'templateSubmit' => __('导入所选模板', 'aksrt'),
'confirmTemplate' => __('确定导入模板「{title}」吗?导入方式:{mode}', 'aksrt'),
'templatePick' => __('请选择一个模板。', 'aksrt'),
'exportFailed' => __('导出失败', 'aksrt'),
'importSuccess' => __('导入成功', 'aksrt'),
'importFailed' => __('导入失败', 'aksrt'),
'pasteJsonFirst' => __('请先粘贴 JSON', 'aksrt'),
'exportModules' => __('导出模块', 'aksrt'),
'importModules' => __('导入模块', 'aksrt'),
'importTemplate' => __('模板导入', 'aksrt'),
'removeModule' => __('移出模块', 'aksrt'),
'networkError' => __('网络错误,请刷新页面后重试', 'aksrt'),
];
}
public static function ajax_form(): void {
check_ajax_referer(self::NONCE_ACTION, 'nonce');
if (!current_user_can('edit_theme_options')) {
+42 -24
View File
@@ -29,22 +29,28 @@ final class CommonFields {
}
private static function title_fields(): array {
$link = static fn(string $id, string $label) => ['id' => $id, 'type' => 'link', 'label' => $label, 'default' => ['url' => '', 'text' => '', 'target' => '']];
$has_title = ['title', '!=', ''];
$big_title = ['title|title_style', '!=|==', '|big'];
$link = static fn(string $id, string $label, array $extra = []) => array_merge(
['id' => $id, 'type' => 'link', 'label' => $label, 'default' => ['url' => '', 'text' => '', 'target' => '']],
$extra
);
return [
['id' => 'title', 'type' => 'textarea', 'label' => '模块标题', 'default' => ''],
['id' => 'subtitle', 'type' => 'textarea', 'label' => '副标题', 'default' => '', 'dependency' => ['title', '!=', '']],
['id' => 'title_style', 'type' => 'radio', 'label' => '标题样式', 'default' => '', 'options' => ['' => '简约', 'big' => '居中大标题'], 'dependency' => ['title', '!=', '']],
['id' => 'title_highlight', 'type' => 'text', 'label' => '标题选字高亮', 'default' => '', 'dependency' => ['title', '!=', '']],
['id' => 'title_highlight_color', 'type' => 'palette', 'label' => '高亮颜色', 'default' => 'focus-color', 'options' => self::palette()],
$link('title_link', '标题链接'),
$link('title_link2', '标题链接 2'),
$link('title_link3', '标题链接 3'),
['id' => 'title', 'type' => 'textarea', 'label' => '模块标题', 'default' => '', 'attributes' => ['rows' => 1]],
['id' => 'subtitle', 'type' => 'textarea', 'label' => '', 'subtitle' => '副标题', 'class' => 'compact', 'default' => '', 'attributes' => ['rows' => 1], 'dependency' => $has_title],
['id' => 'title_style', 'type' => 'radio', 'label' => '标题样式', 'inline' => true, 'default' => '', 'options' => ['' => '简约', 'big' => '居中大标题'], 'dependency' => $has_title],
['id' => 'title_highlight', 'type' => 'text', 'label' => '标题选字高亮', 'description' => '标题中要被高亮的部分', 'default' => '', 'dependency' => $has_title],
['id' => 'title_highlight_color', 'type' => 'palette', 'label' => '', 'class' => 'skin-color compact', 'default' => 'focus-color', 'options' => self::palette(), 'dependency' => ['title|title_highlight', '!=|!=', '|']],
$link('title_link', '标题链接', ['dependency' => $has_title]),
$link('title_link2', '', ['subtitle' => '标题链接2', 'class' => 'compact', 'dependency' => $big_title]),
$link('title_link3', '', ['subtitle' => '标题链接3', 'class' => 'compact', 'dependency' => $big_title]),
[
'id' => 'title_link_style', 'type' => 'accordion', 'label' => '标题链接样式',
'id' => 'title_link_style', 'type' => 'accordion', 'label' => '链接样式',
'dependency' => ['title|title_style|title_link', '!=|==|!=', '|big|'],
'fields' => [
['id' => 'color_1', 'type' => 'palette', 'label' => '链接 1 颜色', 'default' => 'jb-blue', 'options' => self::palette()],
['id' => 'color_2', 'type' => 'palette', 'label' => '链接 2 颜色', 'default' => 'jb-yellow', 'options' => self::palette()],
['id' => 'color_3', 'type' => 'palette', 'label' => '链接 3 颜色', 'default' => 'jb-green', 'options' => self::palette()],
['id' => 'color_1', 'type' => 'palette', 'label' => '链接1:颜色', 'class' => 'skin-color', 'default' => 'jb-blue', 'options' => self::palette()],
['id' => 'color_2', 'type' => 'palette', 'label' => '链接2:颜色', 'class' => 'skin-color', 'default' => 'jb-yellow', 'options' => self::palette()],
['id' => 'color_3', 'type' => 'palette', 'label' => '链接3:颜色', 'class' => 'skin-color', 'default' => 'jb-green', 'options' => self::palette()],
],
],
];
@@ -52,28 +58,41 @@ final class CommonFields {
private static function visibility_fields(): array {
return [
['id' => 'show_type', 'type' => 'radio', 'label' => '显示规则', 'default' => 'all', 'options' => ['all' => '全部显示', 'only_pc' => '仅 PC 端', 'only_sm' => '仅移动端']],
['id' => 'show_id_type', 'type' => 'radio', 'label' => '按 ID 显示或隐藏', 'default' => '', 'options' => ['' => '不限制', 'show' => '仅指定 ID 显示', 'hide' => '指定 ID 隐藏']],
['id' => 'show_ids', 'type' => 'text', 'label' => '文章 ID', 'description' => '多个 ID 使用逗号分隔', 'default' => '', 'sanitize' => 'ids', 'dependency' => ['show_id_type', '!=', '']],
['id' => 'show_type', 'type' => 'radio', 'label' => '显示规则', 'inline' => true, 'default' => 'all', 'options' => ['all' => '全部显示', 'only_pc' => '仅PC端显示', 'only_sm' => '仅移动端显示']],
['id' => 'show_id_type', 'type' => 'radio', 'label' => '按ID显示或隐藏', 'inline' => true, 'default' => '', 'options' => ['' => '不限制', 'show' => '在指定ID中显示', 'hide' => '在指定ID中隐藏']],
[
'id' => 'show_ids', 'type' => 'text', 'label' => '', 'class' => 'compact', 'default' => '', 'sanitize' => 'ids',
'description' => '当此模块添加在文章、帖子、板块、商品页面时候,可以通过此处设置ID,来控制显示或隐藏此模块,多个ID用英文逗号隔开。 例如:<code>1,2,3</code>',
'dependency' => ['show_id_type', '!=', ''],
],
];
}
private static function animation_fields(): array {
return [
['id' => 'animation_in', 'type' => 'select', 'label' => '模块入场动画', 'default' => '', 'options' => ['' => '无动画', 'fade' => '淡入', 'slideup' => '从下往上', 'slidedown' => '从上往下', 'slideright' => '从左往右', 'slideleft' => '从右往左', 'zoomin' => '由小变大', 'zoomout' => '由大变小']],
['id' => 'animation_repeat', 'type' => 'switcher', 'label' => '重复动画', 'default' => false],
[
'id' => 'animation_in', 'type' => 'select', 'label' => '模块入场动画', 'default' => '',
'description' => '当页面滚动到此模块时,会自动触发此动画,注意:合理适当启用才能达到最佳效果',
'options' => ['' => '无动画', 'fade' => '淡入', 'slideup' => '从下往上滑出', 'slidedown' => '从上往下滑出', 'slideright' => '从左往右滑出', 'slideleft' => '从右往左滑出', 'zoomin' => '由小变大', 'zoomout' => '由大变小'],
],
[
'id' => 'animation_repeat', 'type' => 'switcher', 'label' => '', 'class' => 'compact', 'default' => false,
'description' => '每次滚动到此模块都触发动画[注意:有性能消耗,部分老旧浏览器会有闪烁问题]',
'dependency' => ['animation_in', '!=', ''],
],
];
}
private static function layout_fields(): array {
$spacing = ['top' => '', 'right' => '', 'bottom' => '', 'left' => ''];
return [
['id' => 'layout_pin_pc', 'type' => 'spacing', 'label' => '模块额外间距(PC)', 'default' => ['top' => '', 'right' => '', 'bottom' => '', 'left' => '']],
['id' => 'layout_pin_m', 'type' => 'spacing', 'label' => '模块额外间距(移动端)', 'default' => ['top' => '', 'right' => '', 'bottom' => '', 'left' => '']],
['id' => 'layout_pin_pc', 'type' => 'spacing', 'label' => '模块额外间距(PC端)', 'edges' => ['top', 'bottom'], 'default' => $spacing],
['id' => 'layout_pin_m', 'type' => 'spacing', 'label' => '', 'subtitle' => '移动端额外间距', 'class' => 'compact', 'description' => '添加额外间距(默认已有20px下边距)', 'edges' => ['top', 'bottom'], 'default' => $spacing],
[
'id' => 'layout_bg', 'type' => 'accordion', 'label' => '区块背景',
'id' => 'layout_bg', 'type' => 'accordion', 'label' => '区块背景', 'description' => '背景及间距需根据所在容器位置合理配置!',
'fields' => [
['id' => 'light', 'type' => 'background', 'label' => '日间模式背景', 'default' => []],
['id' => 'dark', 'type' => 'background', 'label' => '夜间模式背景', 'default' => []],
['id' => 'light', 'type' => 'background', 'label' => '日间模式背景', 'description' => '可同时设置图片和颜色,图片优先级高于颜色', 'default' => []],
['id' => 'dark', 'type' => 'background', 'label' => '夜间模式背景', 'description' => '如果留空则使用日间模式背景', 'default' => []],
],
],
];
@@ -91,4 +110,3 @@ final class CommonFields {
];
}
}
+31 -7
View File
@@ -32,7 +32,7 @@ final class FormRenderer {
$field_name = $widget->get_field_name($key);
$dependency = !empty($field['dependency']) ? wp_json_encode($field['dependency']) : '';
echo '<div class="aksrt-widget-field aksrt-widget-field--' . esc_attr($type) . '" data-field-id="' . esc_attr($id) . '"';
echo '<div class="' . esc_attr(self::field_class($field, $type)) . '" data-field-id="' . esc_attr($id) . '"';
if ($dependency !== '') {
echo ' data-dependency="' . esc_attr($dependency) . '"';
}
@@ -40,6 +40,9 @@ final class FormRenderer {
if (!empty($field['label'])) {
echo '<label class="aksrt-widget-field__label" for="' . esc_attr($field_id) . '">' . esc_html((string) $field['label']) . '</label>';
}
if (!empty($field['subtitle'])) {
echo '<p class="aksrt-widget-field__subtitle">' . esc_html((string) $field['subtitle']) . '</p>';
}
if (!empty($field['description'])) {
echo '<p class="description">' . wp_kses_post((string) $field['description']) . '</p>';
}
@@ -85,7 +88,7 @@ final class FormRenderer {
self::link($widget, $key, is_array($value) ? $value : []);
break;
case 'spacing':
self::spacing($widget, $key, is_array($value) ? $value : []);
self::spacing($widget, $key, is_array($value) ? $value : [], (array) ($field['edges'] ?? []));
break;
case 'background':
self::background($widget, $key, is_array($value) ? $value : []);
@@ -106,7 +109,26 @@ final class FormRenderer {
private static function display_field(array $field, string $type): void {
$content = (string) ($field['content'] ?? $field['label'] ?? '');
echo '<div class="aksrt-widget-field aksrt-widget-field--' . esc_attr($type) . '">' . wp_kses_post($content) . '</div>';
$class = self::field_class($field, $type);
if ($type === 'submessage') {
$style = in_array($field['style'] ?? '', ['success', 'info', 'warning', 'danger'], true) ? $field['style'] : 'normal';
$class .= ' aksrt-widget-field--submessage-' . $style;
}
echo '<div class="' . esc_attr($class) . '">' . wp_kses_post($content) . '</div>';
}
/** Reference CSF row classes: type modifier plus schema `class` (e.g. compact) and `inline`. */
private static function field_class(array $field, string $type): string {
$classes = ['aksrt-widget-field', 'aksrt-widget-field--' . $type];
foreach (preg_split('/\s+/', trim((string) ($field['class'] ?? ''))) ?: [] as $extra) {
if ($extra !== '') {
$classes[] = 'is-' . sanitize_html_class($extra);
}
}
if (!empty($field['inline'])) {
$classes[] = 'is-inline';
}
return implode(' ', $classes);
}
private static function switcher(string $id, string $name, bool $value): void {
@@ -232,10 +254,12 @@ final class FormRenderer {
echo '<label><input type="checkbox" name="' . esc_attr($name) . '" value="_blank" ' . checked(($value['target'] ?? '') === '_blank', true, false) . '> ' . esc_html__('新窗口打开', 'aksrt') . '</label></div>';
}
private static function spacing(SchemaWidget $widget, string $key, array $value): void {
echo '<div class="aksrt-widget-spacing">';
foreach (['top' => '上', 'right' => '右', 'bottom' => '下', 'left' => '左'] as $edge => $label) {
echo '<label><span>' . esc_html($label) . '</span>';
private static function spacing(SchemaWidget $widget, string $key, array $value, array $edges = []): void {
$all = ['top' => 'dashicons-arrow-up-alt', 'right' => 'dashicons-arrow-right-alt', 'bottom' => 'dashicons-arrow-down-alt', 'left' => 'dashicons-arrow-left-alt'];
$visible = $edges ? array_intersect_key($all, array_flip($edges)) : $all;
echo '<div class="aksrt-widget-spacing aksrt-widget-spacing--' . count($visible) . '">';
foreach ($visible as $edge => $icon) {
echo '<label><span class="dashicons ' . esc_attr($icon) . '" aria-hidden="true"></span>';
self::plain_input($widget, $key . '[' . $edge . ']', (string) ($value[$edge] ?? ''), 'number', 'px');
echo '</label>';
}
-18
View File
@@ -24,7 +24,6 @@ final class Runtime {
(new RestController())->register_routes();
});
add_action('wp_enqueue_scripts', [AssetManager::class, 'enqueue_active'], 20);
add_action('in_widget_form', [self::class, 'render_placement_hint'], 20, 1);
AdminFormController::register_hooks();
TransferController::register_hooks();
@@ -48,21 +47,4 @@ final class Runtime {
register_widget(new SchemaWidget($definition));
}
}
public static function render_placement_hint(\WP_Widget $widget): void {
if (!$widget instanceof SchemaWidget) {
return;
}
$definition = $widget->definition();
$messages = [
'wide' => __('宽版模块:建议放入全宽或主内容区域;放入侧栏时会显示尺寸警告。', 'aksrt'),
'sidebar' => __('侧栏模块:建议放入侧栏区域;放入全宽区域时会显示尺寸警告。', 'aksrt'),
'any' => __('自适应模块:可放入主内容、全宽或侧栏区域。', 'aksrt'),
];
printf(
'<p class="aksrt-widget-placement-hint" data-widget-size="%1$s"><span class="dashicons dashicons-info-outline" aria-hidden="true"></span>%2$s</p>',
esc_attr($definition->size()),
esc_html($messages[$definition->size()] ?? $messages['any'])
);
}
}
+4 -5
View File
@@ -41,11 +41,11 @@ final class SchemaWidget extends \WP_Widget {
$this->render_lazy_placeholder();
return;
}
FormRenderer::render($this, $this->definition->fields(), $instance);
FormRenderer::render($this, $this->definition->form_fields(), $instance);
}
public function render_full_form(array $instance): void {
FormRenderer::render($this, $this->definition->fields(), array_merge($this->definition->defaults(), $instance));
FormRenderer::render($this, $this->definition->form_fields(), array_merge($this->definition->defaults(), $instance));
}
public function update($new_instance, $old_instance): array {
@@ -65,11 +65,10 @@ final class SchemaWidget extends \WP_Widget {
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>',
'<div class="aksrt-widget-form-lazy" data-id-base="%1$s" data-widget-number="%2$s"><div class="aksrt-widget-form-lazy__status"><div class="t-notice t-loading">%3$s</div></div></div>',
esc_attr($this->id_base),
esc_attr((string) $this->number),
esc_html__('配置将在展开或添加模块后加载。', 'aksrt'),
esc_html__('加载配置', 'aksrt')
esc_html__('正在加载模块配置…', 'aksrt')
);
}
}
+84 -120
View File
@@ -4,156 +4,120 @@ namespace AKSRT\WidgetSystem;
defined('ABSPATH') || exit;
/** Admin-only import, export, template application and preview. */
/** Admin AJAX endpoints for per-sidebar export, JSON import and template import. */
final class TransferController {
private const NONCE = 'aksrt_widgets_transfer';
private static bool $controls_rendered = false;
public const NONCE = 'aksrt_widgets_transfer';
public static function register_hooks(): void {
add_action('admin_notices', [self::class, 'render_panel']);
add_action('customize_controls_print_footer_scripts', [self::class, 'render_panel']);
add_action('admin_post_aksrt_widgets_export', [self::class, 'handle_export']);
add_action('admin_post_aksrt_widgets_import', [self::class, 'handle_import']);
add_action('admin_post_aksrt_widgets_template', [self::class, 'handle_template']);
add_action('wp_ajax_aksrt_widgets_template_preview', [self::class, 'ajax_preview']);
add_action('wp_ajax_aksrt_widgets_export_sidebar', [self::class, 'ajax_export']);
add_action('wp_ajax_aksrt_widgets_import_sidebar', [self::class, 'ajax_import']);
add_action('wp_ajax_aksrt_widgets_list_templates', [self::class, 'ajax_list_templates']);
add_action('wp_ajax_aksrt_widgets_import_template', [self::class, 'ajax_import_template']);
}
public static function render_panel(): void {
if (self::$controls_rendered) {
return;
}
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
if (!$screen || !in_array($screen->id, ['widgets', 'customize'], true) || !current_user_can('edit_theme_options')) {
return;
}
self::$controls_rendered = true;
$templates = WidgetTransfer::templates();
$notice = isset($_GET['aksrt_widgets_notice']) ? sanitize_key(wp_unslash($_GET['aksrt_widgets_notice'])) : '';
if ($notice !== '') {
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('小工具配置已更新。', 'aksrt') . '</p></div>';
}
?>
<div class="aksrt-widget-transfer-modal" id="aksrt-widget-transfer-modal" aria-hidden="true" hidden>
<button type="button" class="aksrt-widget-transfer-modal__backdrop" data-aksrt-transfer-close aria-label="<?php esc_attr_e('关闭', 'aksrt'); ?>"></button>
<section class="aksrt-widget-transfer-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="aksrt-widget-transfer-title">
<button type="button" class="aksrt-widget-transfer-modal__close" data-aksrt-transfer-close aria-label="<?php esc_attr_e('关闭', 'aksrt'); ?>">&times;</button>
<h2 id="aksrt-widget-transfer-title"><?php esc_html_e('小工具区域管理', 'aksrt'); ?></h2>
<p class="description aksrt-widget-transfer-modal__area"></p>
<nav class="aksrt-widget-transfer-modal__tabs" aria-label="<?php esc_attr_e('小工具操作', 'aksrt'); ?>">
<button type="button" class="button is-active" data-transfer-tab="export"><?php esc_html_e('导出', 'aksrt'); ?></button>
<button type="button" class="button" data-transfer-tab="import"><?php esc_html_e('导入', 'aksrt'); ?></button>
<button type="button" class="button" data-transfer-tab="template"><?php esc_html_e('内置模板', 'aksrt'); ?></button>
</nav>
<div class="aksrt-widget-transfer-modal__panel" data-transfer-panel="export">
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="aksrt_widgets_export">
<?php wp_nonce_field(self::NONCE); ?>
<input type="hidden" name="sidebar" value="">
<p><?php esc_html_e('导出当前小工具区域的配置文件。', 'aksrt'); ?></p>
<?php submit_button(__('下载配置', 'aksrt'), 'primary', 'submit', false); ?>
</form>
</div>
<div class="aksrt-widget-transfer-modal__panel" data-transfer-panel="import" hidden>
<form method="post" enctype="multipart/form-data" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="aksrt_widgets_import">
<?php wp_nonce_field(self::NONCE); ?>
<input type="file" name="widgets_file" accept="application/json,.json" required>
<?php self::mode_select(); ?>
<input type="hidden" name="target_sidebar" value="">
<?php submit_button(__('导入配置', 'aksrt'), 'primary', 'submit', false); ?>
</form>
</div>
<div class="aksrt-widget-transfer-modal__panel" data-transfer-panel="template" hidden>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="aksrt_widgets_template">
<?php wp_nonce_field(self::NONCE); ?>
<select name="template" class="aksrt-widget-template-select" aria-label="<?php esc_attr_e('选择内置模板', 'aksrt'); ?>">
<?php foreach ($templates as $key => $template) : ?>
<option value="<?php echo esc_attr($key); ?>"><?php echo esc_html((string) $template['label']); ?></option>
<?php endforeach; ?>
</select>
<?php self::mode_select(); ?>
<input type="hidden" name="target_sidebar" value="">
<div class="aksrt-widget-transfer__actions">
<button type="button" class="button aksrt-widget-template-preview"><?php esc_html_e('预览模块', 'aksrt'); ?></button>
<?php submit_button(__('应用模板', 'aksrt'), 'primary', 'submit', false); ?>
</div>
</form>
<div class="aksrt-widget-template-preview-output" hidden></div>
</div>
</section>
</div>
<?php
}
public static function handle_export(): void {
public static function ajax_export(): void {
self::authorize();
$sidebar = isset($_POST['sidebar']) ? sanitize_key(wp_unslash($_POST['sidebar'])) : '';
$payload = WidgetTransfer::export($sidebar);
nocache_headers();
header('Content-Type: application/json; charset=utf-8');
header('Content-Disposition: attachment; filename="aksrt-widgets-' . gmdate('Ymd-His') . '.json"');
echo wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
$sidebar = self::target_sidebar();
$json = wp_json_encode(WidgetTransfer::export($sidebar), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
wp_send_json_success(['json_text' => (string) $json, 'sidebar_id' => $sidebar]);
}
public static function handle_import(): void {
public static function ajax_import(): void {
self::authorize();
$file = $_FILES['widgets_file'] ?? null;
if (!is_array($file) || !empty($file['error']) || empty($file['tmp_name']) || (int) ($file['size'] ?? 0) > 2 * MB_IN_BYTES) {
wp_die(esc_html__('导入文件无效或超过 2MB。', 'aksrt'));
$sidebar = self::target_sidebar();
$raw = isset($_POST['json']) ? trim((string) wp_unslash($_POST['json'])) : '';
if ($raw === '') {
wp_send_json_error(['message' => __('请粘贴 JSON 内容。', 'aksrt')]);
}
$payload = json_decode((string) file_get_contents((string) $file['tmp_name']), true);
if (strlen($raw) > 2 * MB_IN_BYTES) {
wp_send_json_error(['message' => __('JSON 内容超过 2MB。', 'aksrt')]);
}
$payload = json_decode($raw, true);
if (!is_array($payload)) {
wp_die(esc_html__('导入文件不是有效 JSON。', 'aksrt'));
wp_send_json_error(['message' => __('JSON 解析失败,请检查格式。', 'aksrt')]);
}
self::run_import($payload);
$mode = self::import_mode();
$result = self::run_import($payload, $sidebar, $mode);
$message = $mode === 'append'
/* translators: 1: sidebar name, 2: imported widget count */
? __('已向侧栏「%1$s」末尾追加 %2$d 个小工具。请刷新页面后查看效果。', 'aksrt')
/* translators: 1: sidebar name, 2: imported widget count */
: __('已覆盖侧栏「%1$s」并导入 %2$d 个小工具。请刷新页面后查看效果。', 'aksrt');
self::send_result($sidebar, $mode, $result, $message);
}
public static function handle_template(): void {
public static function ajax_list_templates(): void {
self::authorize();
$template = isset($_POST['template']) ? sanitize_key(wp_unslash($_POST['template'])) : '';
$list = [];
foreach (WidgetTransfer::templates() as $id => $template) {
$list[] = [
'id' => (string) $id,
'title' => (string) $template['title'],
'desc' => (string) ($template['desc'] ?? ''),
'remind' => (string) ($template['remind'] ?? ''),
'modules' => WidgetTransfer::template_modules((string) $id),
];
}
wp_send_json_success(['templates' => $list]);
}
public static function ajax_import_template(): void {
self::authorize();
$sidebar = self::target_sidebar();
$template = isset($_POST['template_id']) ? sanitize_key(wp_unslash($_POST['template_id'])) : '';
try {
$payload = WidgetTransfer::template_payload($template);
} catch (\InvalidArgumentException $error) {
wp_die(esc_html($error->getMessage()), '', ['response' => 400]);
}
self::run_import($payload);
}
public static function ajax_preview(): void {
check_ajax_referer(self::NONCE, 'nonce');
if (!current_user_can('edit_theme_options')) {
wp_send_json_error(['message' => __('权限不足。', 'aksrt')], 403);
}
$template = isset($_POST['template']) ? sanitize_key(wp_unslash($_POST['template'])) : '';
try {
wp_send_json_success(['html' => WidgetTransfer::preview($template)]);
} catch (\InvalidArgumentException $error) {
wp_send_json_error(['message' => $error->getMessage()], 400);
wp_send_json_error(['message' => $error->getMessage()]);
}
$mode = self::import_mode();
$result = self::run_import($payload, $sidebar, $mode);
$message = $mode === 'append'
/* translators: 1: sidebar name, 2: imported widget count */
? __('已从模板向侧栏「%1$s」末尾追加 %2$d 个小工具。请刷新页面后查看效果。', 'aksrt')
/* translators: 1: sidebar name, 2: imported widget count */
: __('已用模板覆盖侧栏「%1$s」并导入 %2$d 个小工具。请刷新页面后查看效果。', 'aksrt');
self::send_result($sidebar, $mode, $result, $message, ['template_id' => $template]);
}
private static function authorize(): void {
check_ajax_referer(self::NONCE, 'nonce');
if (!current_user_can('edit_theme_options')) {
wp_die(esc_html__('权限不足。', 'aksrt'), '', ['response' => 403]);
wp_send_json_error(['message' => __('权限不足', 'aksrt')], 403);
}
check_admin_referer(self::NONCE);
}
private static function run_import(array $payload): void {
$mode = isset($_POST['mode']) ? sanitize_key(wp_unslash($_POST['mode'])) : 'append';
$target = isset($_POST['target_sidebar']) ? sanitize_key(wp_unslash($_POST['target_sidebar'])) : '';
private static function target_sidebar(): string {
$sidebar = isset($_POST['sidebar_id']) ? sanitize_key(wp_unslash($_POST['sidebar_id'])) : '';
if ($sidebar === '' || !isset($GLOBALS['wp_registered_sidebars'][$sidebar])) {
wp_send_json_error(['message' => __('无效的侧栏。', 'aksrt')]);
}
return $sidebar;
}
private static function import_mode(): string {
$mode = isset($_POST['import_mode']) ? sanitize_key(wp_unslash($_POST['import_mode'])) : 'append';
return $mode === 'replace' ? 'replace' : 'append';
}
/** @return array{sidebars:int,widgets:int} */
private static function run_import(array $payload, string $sidebar, string $mode): array {
try {
WidgetTransfer::import($payload, $mode, $target);
return WidgetTransfer::import($payload, $mode, $sidebar);
} catch (\InvalidArgumentException $error) {
wp_die(esc_html($error->getMessage()), '', ['response' => 400]);
wp_send_json_error(['message' => $error->getMessage()]);
}
wp_safe_redirect(add_query_arg('aksrt_widgets_notice', 'updated', admin_url('widgets.php')));
exit;
}
private static function mode_select(): void {
echo '<select name="mode"><option value="append">' . esc_html__('追加', 'aksrt') . '</option><option value="replace">' . esc_html__('替换区域', 'aksrt') . '</option></select>';
/** @param array{sidebars:int,widgets:int} $result */
private static function send_result(string $sidebar, string $mode, array $result, string $message, array $extra = []): void {
$name = (string) ($GLOBALS['wp_registered_sidebars'][$sidebar]['name'] ?? $sidebar);
wp_send_json_success(array_merge([
'imported' => (int) $result['widgets'],
'sidebar_id' => $sidebar,
'import_mode' => $mode,
'warnings' => [],
'message' => sprintf($message, $name, (int) $result['widgets']),
], $extra));
}
}
+20
View File
@@ -92,6 +92,26 @@ final class WidgetDefinition {
return array_merge(CommonFields::for_definition($this->common), $this->fields);
}
/** Admin form layout: reference header (description, reminder), common params, then the "模块内容配置" subheading. */
public function form_fields(): array {
$header = [];
if ($this->description !== '') {
$header[] = ['type' => 'content', 'content' => esc_html($this->description)];
}
$reminders = [
'wide' => __('此模块适合放在页面的全宽度或主内容容器中,不能放置在较小的容器中', 'aksrt'),
'sidebar' => __('此模块只适合添加到侧边栏', 'aksrt'),
];
if (isset($reminders[$this->size])) {
$header[] = ['type' => 'submessage', 'style' => 'warning', 'content' => '<i class="fa fa-fw fa-info-circle"></i>' . esc_html($reminders[$this->size])];
}
$common = CommonFields::for_definition($this->common);
if ($common && $this->fields) {
$common[] = ['type' => 'subheading', 'content' => esc_html__('模块内容配置', 'aksrt')];
}
return array_merge($header, $common, $this->fields);
}
public function defaults(): array {
return FieldSchema::defaults($this->fields());
}
+23 -24
View File
@@ -12,8 +12,9 @@ final class WidgetTransfer {
public static function templates(): array {
return [
'article_home' => [
'label' => __('文章首页', 'aksrt'),
'description' => __('公告、幻灯片、多栏目文章与热榜侧栏。', 'aksrt'),
'title' => __('文章首页', 'aksrt'),
'desc' => __('公告、幻灯片、多栏目文章与热榜侧栏。', 'aksrt'),
'remind' => __('导入到首页主内容区域,侧栏模块会一并导入。', 'aksrt'),
'sidebars' => [
'home_top_content' => [
['widget' => 'notice', 'settings' => ['title' => '站点公告']],
@@ -24,8 +25,9 @@ final class WidgetTransfer {
],
],
'article_list' => [
'label' => __('文章列表', 'aksrt'),
'description' => __('标题、分类卡片与可分页文章列表。', 'aksrt'),
'title' => __('文章列表', 'aksrt'),
'desc' => __('标题、分类卡片与可分页文章列表。', 'aksrt'),
'remind' => __('需已有文章与分类内容。', 'aksrt'),
'sidebars' => [
'home_top_content' => [
['widget' => 'text_title', 'settings' => ['heading' => '最新知识内容', 'description' => '持续更新的课程、文章与资料']],
@@ -35,8 +37,9 @@ final class WidgetTransfer {
],
],
'links_navigation' => [
'label' => __('链接导航', 'aksrt'),
'description' => __('搜索、分类入口与链接列表。', 'aksrt'),
'title' => __('链接导航', 'aksrt'),
'desc' => __('搜索、分类入口与链接列表。', 'aksrt'),
'remind' => __('需已在链接管理中添加链接。', 'aksrt'),
'sidebars' => [
'home_top_content' => [
['widget' => 'icon_cover_cards', 'settings' => ['title' => '常用入口']],
@@ -46,8 +49,9 @@ final class WidgetTransfer {
],
],
'article_sidebar' => [
'label' => __('文章侧栏', 'aksrt'),
'description' => __('目录、作者、付费授权与热榜文章。', 'aksrt'),
'title' => __('文章侧栏', 'aksrt'),
'desc' => __('目录、作者、付费授权与热榜文章。', 'aksrt'),
'remind' => __('只能导入到文章页侧边栏。', 'aksrt'),
'sidebars' => [
'single_sidebar' => [
['widget' => 'posts_toc', 'settings' => ['title' => '文章目录']],
@@ -58,8 +62,9 @@ final class WidgetTransfer {
],
],
'knowledge_landing' => [
'label' => __('知识付费落地页', 'aksrt'),
'description' => __('亮点、方案、评价与常见问题。', 'aksrt'),
'title' => __('知识付费落地页', 'aksrt'),
'desc' => __('亮点、方案、评价与常见问题。', 'aksrt'),
'remind' => __('适合放置在全宽度或主内容容器中。', 'aksrt'),
'sidebars' => [
'home_top_content' => [
['widget' => 'feature_intro', 'settings' => ['title' => '系统化学习路径']],
@@ -160,24 +165,18 @@ final class WidgetTransfer {
return ['sidebars' => $changed, 'widgets' => $created];
}
public static function preview(string $template): string {
$payload = self::template_payload($template);
$html = '';
foreach ($payload['sidebars'] as $sidebar_id => $items) {
$html .= '<section class="aksrt-widget-template-preview__area"><h4>' . esc_html((string) $sidebar_id) . '</h4>';
foreach ($items as $item) {
/** @return list<array{id_base:string,title:string}> */
public static function template_modules(string $template): array {
$modules = [];
foreach (self::template_payload($template)['sidebars'] as $items) {
foreach ((array) $items as $item) {
$definition = WidgetRegistry::get((string) ($item['widget'] ?? ''));
if ($definition === null) {
continue;
if ($definition !== null) {
$modules[] = ['id_base' => $definition->id_base(), 'title' => $definition->name()];
}
$settings = $definition->normalize((array) ($item['settings'] ?? []));
$html .= '<article class="aksrt-widget-template-preview__module aksrt-widget aksrt-widget--' . esc_attr($definition->slug()) . '"><strong>' . esc_html($definition->name()) . '</strong><div class="aksrt-widget__content">';
$html .= RendererRegistry::render($definition->renderer(), $settings, ['widget_id' => 'preview-0']);
$html .= '</div></article>';
}
$html .= '</section>';
}
return $html;
return $modules;
}
private static function export_widget(string $widget_id): ?array {
+4 -51
View File
@@ -267,54 +267,11 @@
"sha256": "07ea0c3260a9ee9701b1ce03795941fbbfb61c377ad71fe8f7820107763c5528"
},
"field_ids": [
"show_type",
"show_id_type",
"show_ids",
"animation_in",
"animation_repeat",
"layout_pin_pc",
"layout_pin_m",
"layout_bg",
"title",
"mini_title",
"in_affix"
],
"settings": {
"show_type": "all",
"show_id_type": "",
"show_ids": "",
"animation_in": "",
"animation_repeat": false,
"layout_pin_pc": {
"top": 0,
"right": 0,
"bottom": 20,
"left": 0
},
"layout_pin_m": {
"top": 0,
"right": 0,
"bottom": 20,
"left": 0
},
"layout_bg": {
"light": {
"color": "#ffffff",
"image": "",
"position": "center center",
"repeat": "no-repeat",
"attachment": "scroll",
"size": "cover"
},
"dark": {
"color": "#1d1e24",
"image": "",
"position": "center center",
"repeat": "no-repeat",
"attachment": "scroll",
"size": "cover"
}
},
"title": "AKSRT · Posts toc",
"mini_title": "AKSRT mini title 1",
"in_affix": false
@@ -354,10 +311,7 @@
"animation_repeat",
"layout_pin_pc",
"layout_pin_m",
"layout_bg",
"source",
"quotes",
"interval"
"layout_bg"
],
"settings": {
"title": "AKSRT · Quote",
@@ -420,10 +374,7 @@
"attachment": "scroll",
"size": "cover"
}
},
"source": "local",
"quotes": "保持好奇,持续创造。\n知识因为分享而更有价值。",
"interval": 30
}
},
"root_selector": "[data-aksrt-widget=\"quote\"]",
"states": [
@@ -2657,6 +2608,7 @@
"title_link2",
"title_link3",
"title_link_style",
"sidebar_affix",
"show_type",
"show_id_type",
"show_ids",
@@ -2702,6 +2654,7 @@
"color_2": "jb-yellow",
"color_3": "jb-green"
},
"sidebar_affix": false,
"show_type": "all",
"show_id_type": "",
"show_ids": "",
@@ -6,7 +6,8 @@ const path = require('node:path')
const root = path.resolve(__dirname, '../..')
const core = require(path.join(root, 'assets/widgets/admin-core.js'))
const admin = fs.readFileSync(path.join(root, 'assets/widgets/admin.js'), 'utf8')
const controller = fs.readFileSync(path.join(root, 'src/WidgetSystem/AdminFormController.php'), 'utf8')
const wie = fs.readFileSync(path.join(root, 'assets/widgets/admin-transfer.js'), 'utf8')
const controller =fs.readFileSync(path.join(root, 'src/WidgetSystem/AdminFormController.php'), 'utf8')
const transfer = fs.readFileSync(path.join(root, 'src/WidgetSystem/TransferController.php'), 'utf8')
const renderer = fs.readFileSync(path.join(root, 'src/WidgetSystem/FormRenderer.php'), 'utf8')
const styles = fs.readFileSync(path.join(root, 'assets/widgets/admin.css'), 'utf8')
@@ -25,17 +26,22 @@ test('lazy form AJAX failures remain retryable and instance filters match WordPr
assert.match(controller, /apply_filters\('widget_form_callback', \$instance, \$widget\)/)
})
test('sidebar toolbars open one contextual import, export, or template dialog', () => {
assert.match(admin, /widgets-holder-wrap:not\(#available-widgets\)/)
assert.match(admin, /control-section-sidebar/)
assert.match(admin, /data-aksrt-transfer-action/)
assert.match(admin, /data-sidebar-id/)
assert.match(admin, /data-transfer-tab/)
assert.match(transfer, /aksrt-widget-transfer-modal__dialog/)
assert.match(transfer, /aksrt_widgets_template_preview/)
assert.doesNotMatch(transfer, /aksrt-widget-transfer__grid/)
assert.doesNotMatch(transfer, /function sidebar_select/)
assert.match(admin, /aksrt-widget-customizer-remove/)
test('sidebar toolbars drive reference-style AJAX export, import and template modals', () => {
assert.match(wie, /widgets-holder-wrap:not\(#available-widgets\)/)
assert.match(wie, /control-section-sidebar/)
assert.match(wie, /data-aksrt-wie-action/)
assert.match(wie, /data-sidebar-id/)
assert.match(wie, /aksrt-wie-btn-delete/)
assert.match(wie, /nonce: config\.transferNonce/)
for (const action of ['export_sidebar', 'import_sidebar', 'list_templates', 'import_template']) {
assert.match(wie, new RegExp(`aksrt_widgets_${action}`))
assert.match(transfer, new RegExp(`wp_ajax_aksrt_widgets_${action}`))
}
assert.match(transfer, /check_ajax_referer\(self::NONCE, 'nonce'\)/)
assert.match(transfer, /edit_theme_options/)
assert.doesNotMatch(transfer, /aksrt_widgets_template_preview|admin_post_|admin_notices/)
assert.doesNotMatch(admin, /data-aksrt-transfer-action|aksrt-widget-customizer-remove|aksrt-widget-form-lazy__load/)
assert.match(styles, /\.aksrt-wie-modal__dialog/)
})
test('widget fields follow the current CSF compact palette and cloneable group patterns', () => {
@@ -46,7 +52,9 @@ test('widget fields follow the current CSF compact palette and cloneable group p
assert.match(styles, /\.aksrt-widget-choices--palette/)
assert.match(styles, /\.aksrt-widget-repeater__bar/)
assert.match(styles, /\.customize-control-widget_form \.aksrt-widget-field__label/)
assert.match(admin, /if \(!response\?\.success \|\| !response\.data\) \{/)
assert.match(admin, /if \(!response\?\.success \|\| !response\.data\?\.html\) \{/)
assert.match(admin, /t-notice/)
assert.match(styles, /\.aksrt-widget-field\.is-compact/)
assert.match(admin, /responseJSON\?\.data\?\.message/)
assert.doesNotMatch(admin, /if \(!response\?\.success\) throw new Error/)
})
+14 -2
View File
@@ -133,8 +133,15 @@ foreach ($registry as $slug => $definition) {
$fields = $definition->fields();
$walk($fields, $slug);
$field_ids = array_column($fields, 'id');
$required_common = ['show_type', 'show_id_type', 'show_ids', 'layout_pin_pc', 'layout_bg'];
if (($definition->common()['animation'] ?? true)) {
$flags = $definition->common();
$required_common = [];
if (!empty($flags['visibility'])) {
array_push($required_common, 'show_type', 'show_id_type', 'show_ids');
}
if (!empty($flags['layout'])) {
array_push($required_common, 'layout_pin_pc', 'layout_bg');
}
if (!empty($flags['animation'])) {
$required_common[] = 'animation_in';
}
foreach ($required_common as $required) {
@@ -164,6 +171,11 @@ foreach ($expected as $slug) {
if (!defined('DAY_IN_SECONDS')) {
define('DAY_IN_SECONDS', 86400);
}
if (!function_exists('current_datetime')) {
function current_datetime(): DateTimeImmutable {
return new DateTimeImmutable('now', new DateTimeZone('UTC'));
}
}
$query_args = PostQuery::arguments([
'count' => 7,
'category_ids' => '2,5',